blob: 1ab69714f7962a746e99d2f13058a451efed3f71 [file] [log] [blame]
niklase@google.com470e71d2011-07-07 08:21:25 +00001/*
henrika@webrtc.org2919e952012-01-31 08:45:03 +00002 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
niklase@google.com470e71d2011-07-07 08:21:25 +00003 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
turaj@webrtc.org6388c3e2013-02-12 21:42:18 +000011#include "webrtc/voice_engine/channel.h"
niklase@google.com470e71d2011-07-07 08:21:25 +000012
Henrik Lundin64dad832015-05-11 12:44:23 +020013#include <algorithm>
Tommif888bb52015-12-12 01:37:01 +010014#include <utility>
Henrik Lundin64dad832015-05-11 12:44:23 +020015
aleloi6321b492016-12-05 01:46:09 -080016#include "webrtc/audio/utility/audio_frame_operations.h"
henrik.lundin50499422016-11-29 04:26:24 -080017#include "webrtc/base/array_view.h"
Ivo Creusenae856f22015-09-17 16:30:16 +020018#include "webrtc/base/checks.h"
tommi31fc21f2016-01-21 10:37:37 -080019#include "webrtc/base/criticalsection.h"
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +000020#include "webrtc/base/format_macros.h"
tommidea489f2017-03-03 03:20:24 -080021#include "webrtc/base/location.h"
pbosad856222015-11-27 09:48:36 -080022#include "webrtc/base/logging.h"
Erik Språng737336d2016-07-29 12:59:36 +020023#include "webrtc/base/rate_limiter.h"
wu@webrtc.org94454b72014-06-05 20:34:08 +000024#include "webrtc/base/timeutils.h"
nisseb8f9a322017-03-27 05:36:15 -070025#include "webrtc/call/rtp_transport_controller_send.h"
Henrik Lundin64dad832015-05-11 12:44:23 +020026#include "webrtc/config.h"
skvladcc91d282016-10-03 18:31:22 -070027#include "webrtc/logging/rtc_event_log/rtc_event_log.h"
kwibergda2bf4e2016-10-24 13:47:09 -070028#include "webrtc/modules/audio_coding/codecs/audio_format_conversion.h"
turaj@webrtc.org6388c3e2013-02-12 21:42:18 +000029#include "webrtc/modules/audio_device/include/audio_device.h"
30#include "webrtc/modules/audio_processing/include/audio_processing.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010031#include "webrtc/modules/include/module_common_types.h"
Stefan Holmerb86d4e42015-12-07 10:26:18 +010032#include "webrtc/modules/pacing/packet_router.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010033#include "webrtc/modules/rtp_rtcp/include/receive_statistics.h"
34#include "webrtc/modules/rtp_rtcp/include/rtp_payload_registry.h"
35#include "webrtc/modules/rtp_rtcp/include/rtp_receiver.h"
nisse657bab22017-02-21 06:28:10 -080036#include "webrtc/modules/rtp_rtcp/source/rtp_packet_received.h"
wu@webrtc.org822fbd82013-08-15 23:38:54 +000037#include "webrtc/modules/rtp_rtcp/source/rtp_receiver_strategy.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010038#include "webrtc/modules/utility/include/process_thread.h"
elad.alon28770482017-03-28 05:03:55 -070039#include "webrtc/system_wrappers/include/field_trial.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010040#include "webrtc/system_wrappers/include/trace.h"
turaj@webrtc.org6388c3e2013-02-12 21:42:18 +000041#include "webrtc/voice_engine/include/voe_rtp_rtcp.h"
42#include "webrtc/voice_engine/output_mixer.h"
43#include "webrtc/voice_engine/statistics.h"
turaj@webrtc.org6388c3e2013-02-12 21:42:18 +000044#include "webrtc/voice_engine/utility.h"
niklase@google.com470e71d2011-07-07 08:21:25 +000045
andrew@webrtc.org50419b02012-11-14 19:07:54 +000046namespace webrtc {
47namespace voe {
niklase@google.com470e71d2011-07-07 08:21:25 +000048
kwibergc8d071e2016-04-06 12:22:38 -070049namespace {
50
Erik Språng737336d2016-07-29 12:59:36 +020051constexpr int64_t kMaxRetransmissionWindowMs = 1000;
52constexpr int64_t kMinRetransmissionWindowMs = 30;
53
kwibergc8d071e2016-04-06 12:22:38 -070054} // namespace
55
solenberg8842c3e2016-03-11 03:06:41 -080056const int kTelephoneEventAttenuationdB = 10;
57
ivoc14d5dbe2016-07-04 07:06:55 -070058class RtcEventLogProxy final : public webrtc::RtcEventLog {
59 public:
60 RtcEventLogProxy() : event_log_(nullptr) {}
61
62 bool StartLogging(const std::string& file_name,
63 int64_t max_size_bytes) override {
64 RTC_NOTREACHED();
65 return false;
66 }
67
68 bool StartLogging(rtc::PlatformFile log_file,
69 int64_t max_size_bytes) override {
70 RTC_NOTREACHED();
71 return false;
72 }
73
74 void StopLogging() override { RTC_NOTREACHED(); }
75
76 void LogVideoReceiveStreamConfig(
77 const webrtc::VideoReceiveStream::Config& config) override {
78 rtc::CritScope lock(&crit_);
79 if (event_log_) {
80 event_log_->LogVideoReceiveStreamConfig(config);
81 }
82 }
83
84 void LogVideoSendStreamConfig(
85 const webrtc::VideoSendStream::Config& config) override {
86 rtc::CritScope lock(&crit_);
87 if (event_log_) {
88 event_log_->LogVideoSendStreamConfig(config);
89 }
90 }
91
ivoce0928d82016-10-10 05:12:51 -070092 void LogAudioReceiveStreamConfig(
93 const webrtc::AudioReceiveStream::Config& config) override {
94 rtc::CritScope lock(&crit_);
95 if (event_log_) {
96 event_log_->LogAudioReceiveStreamConfig(config);
97 }
98 }
99
100 void LogAudioSendStreamConfig(
101 const webrtc::AudioSendStream::Config& config) override {
102 rtc::CritScope lock(&crit_);
103 if (event_log_) {
104 event_log_->LogAudioSendStreamConfig(config);
105 }
106 }
107
ivoc14d5dbe2016-07-04 07:06:55 -0700108 void LogRtpHeader(webrtc::PacketDirection direction,
109 webrtc::MediaType media_type,
110 const uint8_t* header,
111 size_t packet_length) override {
philipel32d00102017-02-27 02:18:46 -0800112 LogRtpHeader(direction, media_type, header, packet_length,
113 PacedPacketInfo::kNotAProbe);
114 }
115
116 void LogRtpHeader(webrtc::PacketDirection direction,
117 webrtc::MediaType media_type,
118 const uint8_t* header,
119 size_t packet_length,
120 int probe_cluster_id) override {
ivoc14d5dbe2016-07-04 07:06:55 -0700121 rtc::CritScope lock(&crit_);
122 if (event_log_) {
philipel32d00102017-02-27 02:18:46 -0800123 event_log_->LogRtpHeader(direction, media_type, header, packet_length,
124 probe_cluster_id);
ivoc14d5dbe2016-07-04 07:06:55 -0700125 }
126 }
127
128 void LogRtcpPacket(webrtc::PacketDirection direction,
129 webrtc::MediaType media_type,
130 const uint8_t* packet,
131 size_t length) override {
132 rtc::CritScope lock(&crit_);
133 if (event_log_) {
134 event_log_->LogRtcpPacket(direction, media_type, packet, length);
135 }
136 }
137
138 void LogAudioPlayout(uint32_t ssrc) override {
139 rtc::CritScope lock(&crit_);
140 if (event_log_) {
141 event_log_->LogAudioPlayout(ssrc);
142 }
143 }
144
terelius424e6cf2017-02-20 05:14:41 -0800145 void LogLossBasedBweUpdate(int32_t bitrate_bps,
ivoc14d5dbe2016-07-04 07:06:55 -0700146 uint8_t fraction_loss,
147 int32_t total_packets) override {
148 rtc::CritScope lock(&crit_);
149 if (event_log_) {
terelius424e6cf2017-02-20 05:14:41 -0800150 event_log_->LogLossBasedBweUpdate(bitrate_bps, fraction_loss,
151 total_packets);
ivoc14d5dbe2016-07-04 07:06:55 -0700152 }
153 }
154
terelius424e6cf2017-02-20 05:14:41 -0800155 void LogDelayBasedBweUpdate(int32_t bitrate_bps,
terelius0baf55d2017-02-17 03:38:28 -0800156 BandwidthUsage detector_state) override {
157 rtc::CritScope lock(&crit_);
158 if (event_log_) {
terelius424e6cf2017-02-20 05:14:41 -0800159 event_log_->LogDelayBasedBweUpdate(bitrate_bps, detector_state);
terelius0baf55d2017-02-17 03:38:28 -0800160 }
161 }
162
minyue4b7c9522017-01-24 04:54:59 -0800163 void LogAudioNetworkAdaptation(
164 const AudioNetworkAdaptor::EncoderRuntimeConfig& config) override {
165 rtc::CritScope lock(&crit_);
166 if (event_log_) {
167 event_log_->LogAudioNetworkAdaptation(config);
168 }
169 }
170
philipel32d00102017-02-27 02:18:46 -0800171 void LogProbeClusterCreated(int id,
172 int bitrate_bps,
173 int min_probes,
174 int min_bytes) override {
175 rtc::CritScope lock(&crit_);
176 if (event_log_) {
177 event_log_->LogProbeClusterCreated(id, bitrate_bps, min_probes,
178 min_bytes);
179 }
180 };
181
182 void LogProbeResultSuccess(int id, int bitrate_bps) override {
183 rtc::CritScope lock(&crit_);
184 if (event_log_) {
185 event_log_->LogProbeResultSuccess(id, bitrate_bps);
186 }
187 };
188
189 void LogProbeResultFailure(int id,
190 ProbeFailureReason failure_reason) override {
191 rtc::CritScope lock(&crit_);
192 if (event_log_) {
193 event_log_->LogProbeResultFailure(id, failure_reason);
194 }
195 };
196
ivoc14d5dbe2016-07-04 07:06:55 -0700197 void SetEventLog(RtcEventLog* event_log) {
198 rtc::CritScope lock(&crit_);
199 event_log_ = event_log;
200 }
201
202 private:
203 rtc::CriticalSection crit_;
204 RtcEventLog* event_log_ GUARDED_BY(crit_);
205 RTC_DISALLOW_COPY_AND_ASSIGN(RtcEventLogProxy);
206};
207
michaelt9332b7d2016-11-30 07:51:13 -0800208class RtcpRttStatsProxy final : public RtcpRttStats {
209 public:
210 RtcpRttStatsProxy() : rtcp_rtt_stats_(nullptr) {}
211
212 void OnRttUpdate(int64_t rtt) override {
213 rtc::CritScope lock(&crit_);
214 if (rtcp_rtt_stats_)
215 rtcp_rtt_stats_->OnRttUpdate(rtt);
216 }
217
218 int64_t LastProcessedRtt() const override {
219 rtc::CritScope lock(&crit_);
220 if (!rtcp_rtt_stats_)
221 return 0;
222 return rtcp_rtt_stats_->LastProcessedRtt();
223 }
224
225 void SetRtcpRttStats(RtcpRttStats* rtcp_rtt_stats) {
226 rtc::CritScope lock(&crit_);
227 rtcp_rtt_stats_ = rtcp_rtt_stats;
228 }
229
230 private:
231 rtc::CriticalSection crit_;
232 RtcpRttStats* rtcp_rtt_stats_ GUARDED_BY(crit_);
233 RTC_DISALLOW_COPY_AND_ASSIGN(RtcpRttStatsProxy);
234};
235
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100236class TransportFeedbackProxy : public TransportFeedbackObserver {
237 public:
238 TransportFeedbackProxy() : feedback_observer_(nullptr) {
239 pacer_thread_.DetachFromThread();
240 network_thread_.DetachFromThread();
241 }
242
243 void SetTransportFeedbackObserver(
244 TransportFeedbackObserver* feedback_observer) {
245 RTC_DCHECK(thread_checker_.CalledOnValidThread());
246 rtc::CritScope lock(&crit_);
247 feedback_observer_ = feedback_observer;
248 }
249
250 // Implements TransportFeedbackObserver.
elad.alond12a8e12017-03-23 11:04:48 -0700251 void AddPacket(uint32_t ssrc,
252 uint16_t sequence_number,
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100253 size_t length,
philipel8aadd502017-02-23 02:56:13 -0800254 const PacedPacketInfo& pacing_info) override {
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100255 RTC_DCHECK(pacer_thread_.CalledOnValidThread());
256 rtc::CritScope lock(&crit_);
257 if (feedback_observer_)
elad.alond12a8e12017-03-23 11:04:48 -0700258 feedback_observer_->AddPacket(ssrc, sequence_number, length, pacing_info);
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100259 }
philipel8aadd502017-02-23 02:56:13 -0800260
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100261 void OnTransportFeedback(const rtcp::TransportFeedback& feedback) override {
262 RTC_DCHECK(network_thread_.CalledOnValidThread());
263 rtc::CritScope lock(&crit_);
michaelt9960bb12016-10-18 09:40:34 -0700264 if (feedback_observer_)
265 feedback_observer_->OnTransportFeedback(feedback);
Stefan Holmer60e43462016-09-07 09:58:20 +0200266 }
elad.alonf9490002017-03-06 05:32:21 -0800267 std::vector<PacketFeedback> GetTransportFeedbackVector() const override {
Stefan Holmer60e43462016-09-07 09:58:20 +0200268 RTC_NOTREACHED();
elad.alonf9490002017-03-06 05:32:21 -0800269 return std::vector<PacketFeedback>();
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100270 }
271
272 private:
273 rtc::CriticalSection crit_;
274 rtc::ThreadChecker thread_checker_;
275 rtc::ThreadChecker pacer_thread_;
276 rtc::ThreadChecker network_thread_;
277 TransportFeedbackObserver* feedback_observer_ GUARDED_BY(&crit_);
278};
279
280class TransportSequenceNumberProxy : public TransportSequenceNumberAllocator {
281 public:
282 TransportSequenceNumberProxy() : seq_num_allocator_(nullptr) {
283 pacer_thread_.DetachFromThread();
284 }
285
286 void SetSequenceNumberAllocator(
287 TransportSequenceNumberAllocator* seq_num_allocator) {
288 RTC_DCHECK(thread_checker_.CalledOnValidThread());
289 rtc::CritScope lock(&crit_);
290 seq_num_allocator_ = seq_num_allocator;
291 }
292
293 // Implements TransportSequenceNumberAllocator.
294 uint16_t AllocateSequenceNumber() override {
295 RTC_DCHECK(pacer_thread_.CalledOnValidThread());
296 rtc::CritScope lock(&crit_);
297 if (!seq_num_allocator_)
298 return 0;
299 return seq_num_allocator_->AllocateSequenceNumber();
300 }
301
302 private:
303 rtc::CriticalSection crit_;
304 rtc::ThreadChecker thread_checker_;
305 rtc::ThreadChecker pacer_thread_;
306 TransportSequenceNumberAllocator* seq_num_allocator_ GUARDED_BY(&crit_);
307};
308
309class RtpPacketSenderProxy : public RtpPacketSender {
310 public:
kwiberg55b97fe2016-01-28 05:22:45 -0800311 RtpPacketSenderProxy() : rtp_packet_sender_(nullptr) {}
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100312
313 void SetPacketSender(RtpPacketSender* rtp_packet_sender) {
314 RTC_DCHECK(thread_checker_.CalledOnValidThread());
315 rtc::CritScope lock(&crit_);
316 rtp_packet_sender_ = rtp_packet_sender;
317 }
318
319 // Implements RtpPacketSender.
320 void InsertPacket(Priority priority,
321 uint32_t ssrc,
322 uint16_t sequence_number,
323 int64_t capture_time_ms,
324 size_t bytes,
325 bool retransmission) override {
326 rtc::CritScope lock(&crit_);
327 if (rtp_packet_sender_) {
328 rtp_packet_sender_->InsertPacket(priority, ssrc, sequence_number,
329 capture_time_ms, bytes, retransmission);
330 }
331 }
332
333 private:
334 rtc::ThreadChecker thread_checker_;
335 rtc::CriticalSection crit_;
336 RtpPacketSender* rtp_packet_sender_ GUARDED_BY(&crit_);
337};
338
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000339class VoERtcpObserver : public RtcpBandwidthObserver {
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000340 public:
stefan7de8d642017-02-07 07:14:08 -0800341 explicit VoERtcpObserver(Channel* owner)
342 : owner_(owner), bandwidth_observer_(nullptr) {}
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000343 virtual ~VoERtcpObserver() {}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000344
stefan7de8d642017-02-07 07:14:08 -0800345 void SetBandwidthObserver(RtcpBandwidthObserver* bandwidth_observer) {
346 rtc::CritScope lock(&crit_);
347 bandwidth_observer_ = bandwidth_observer;
348 }
349
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000350 void OnReceivedEstimatedBitrate(uint32_t bitrate) override {
stefan7de8d642017-02-07 07:14:08 -0800351 rtc::CritScope lock(&crit_);
352 if (bandwidth_observer_) {
353 bandwidth_observer_->OnReceivedEstimatedBitrate(bitrate);
354 }
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000355 }
356
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +0000357 void OnReceivedRtcpReceiverReport(const ReportBlockList& report_blocks,
358 int64_t rtt,
359 int64_t now_ms) override {
stefan7de8d642017-02-07 07:14:08 -0800360 {
361 rtc::CritScope lock(&crit_);
362 if (bandwidth_observer_) {
363 bandwidth_observer_->OnReceivedRtcpReceiverReport(report_blocks, rtt,
364 now_ms);
365 }
366 }
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000367 // TODO(mflodman): Do we need to aggregate reports here or can we jut send
368 // what we get? I.e. do we ever get multiple reports bundled into one RTCP
369 // report for VoiceEngine?
370 if (report_blocks.empty())
371 return;
372
373 int fraction_lost_aggregate = 0;
374 int total_number_of_packets = 0;
375
376 // If receiving multiple report blocks, calculate the weighted average based
377 // on the number of packets a report refers to.
378 for (ReportBlockList::const_iterator block_it = report_blocks.begin();
379 block_it != report_blocks.end(); ++block_it) {
380 // Find the previous extended high sequence number for this remote SSRC,
381 // to calculate the number of RTP packets this report refers to. Ignore if
382 // we haven't seen this SSRC before.
383 std::map<uint32_t, uint32_t>::iterator seq_num_it =
384 extended_max_sequence_number_.find(block_it->sourceSSRC);
385 int number_of_packets = 0;
386 if (seq_num_it != extended_max_sequence_number_.end()) {
387 number_of_packets = block_it->extendedHighSeqNum - seq_num_it->second;
388 }
389 fraction_lost_aggregate += number_of_packets * block_it->fractionLost;
390 total_number_of_packets += number_of_packets;
391
392 extended_max_sequence_number_[block_it->sourceSSRC] =
393 block_it->extendedHighSeqNum;
394 }
395 int weighted_fraction_lost = 0;
396 if (total_number_of_packets > 0) {
kwiberg55b97fe2016-01-28 05:22:45 -0800397 weighted_fraction_lost =
398 (fraction_lost_aggregate + total_number_of_packets / 2) /
399 total_number_of_packets;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000400 }
elad.alond12a8e12017-03-23 11:04:48 -0700401 owner_->OnUplinkPacketLossRate(weighted_fraction_lost / 255.0f);
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000402 }
403
404 private:
405 Channel* owner_;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000406 // Maps remote side ssrc to extended highest sequence number received.
407 std::map<uint32_t, uint32_t> extended_max_sequence_number_;
stefan7de8d642017-02-07 07:14:08 -0800408 rtc::CriticalSection crit_;
409 RtcpBandwidthObserver* bandwidth_observer_ GUARDED_BY(crit_);
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000410};
411
kwiberg55b97fe2016-01-28 05:22:45 -0800412int32_t Channel::SendData(FrameType frameType,
413 uint8_t payloadType,
414 uint32_t timeStamp,
415 const uint8_t* payloadData,
416 size_t payloadSize,
417 const RTPFragmentationHeader* fragmentation) {
418 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
419 "Channel::SendData(frameType=%u, payloadType=%u, timeStamp=%u,"
420 " payloadSize=%" PRIuS ", fragmentation=0x%x)",
421 frameType, payloadType, timeStamp, payloadSize, fragmentation);
niklase@google.com470e71d2011-07-07 08:21:25 +0000422
kwiberg55b97fe2016-01-28 05:22:45 -0800423 if (_includeAudioLevelIndication) {
424 // Store current audio level in the RTP/RTCP module.
425 // The level will be used in combination with voice-activity state
426 // (frameType) to add an RTP header extension
henrik.lundin50499422016-11-29 04:26:24 -0800427 _rtpRtcpModule->SetAudioLevel(rms_level_.Average());
kwiberg55b97fe2016-01-28 05:22:45 -0800428 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000429
kwiberg55b97fe2016-01-28 05:22:45 -0800430 // Push data from ACM to RTP/RTCP-module to deliver audio frame for
431 // packetization.
432 // This call will trigger Transport::SendPacket() from the RTP/RTCP module.
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700433 if (!_rtpRtcpModule->SendOutgoingData(
kwiberg55b97fe2016-01-28 05:22:45 -0800434 (FrameType&)frameType, payloadType, timeStamp,
435 // Leaving the time when this frame was
436 // received from the capture device as
437 // undefined for voice for now.
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700438 -1, payloadData, payloadSize, fragmentation, nullptr, nullptr)) {
kwiberg55b97fe2016-01-28 05:22:45 -0800439 _engineStatisticsPtr->SetLastError(
440 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
441 "Channel::SendData() failed to send data to RTP/RTCP module");
442 return -1;
443 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000444
kwiberg55b97fe2016-01-28 05:22:45 -0800445 _lastLocalTimeStamp = timeStamp;
446 _lastPayloadType = payloadType;
niklase@google.com470e71d2011-07-07 08:21:25 +0000447
kwiberg55b97fe2016-01-28 05:22:45 -0800448 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000449}
450
stefan1d8a5062015-10-02 03:39:33 -0700451bool Channel::SendRtp(const uint8_t* data,
452 size_t len,
453 const PacketOptions& options) {
kwiberg55b97fe2016-01-28 05:22:45 -0800454 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
455 "Channel::SendPacket(channel=%d, len=%" PRIuS ")", len);
niklase@google.com470e71d2011-07-07 08:21:25 +0000456
kwiberg55b97fe2016-01-28 05:22:45 -0800457 rtc::CritScope cs(&_callbackCritSect);
wu@webrtc.orgfb648da2013-10-18 21:10:51 +0000458
kwiberg55b97fe2016-01-28 05:22:45 -0800459 if (_transportPtr == NULL) {
460 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
461 "Channel::SendPacket() failed to send RTP packet due to"
462 " invalid transport object");
463 return false;
464 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000465
kwiberg55b97fe2016-01-28 05:22:45 -0800466 uint8_t* bufferToSendPtr = (uint8_t*)data;
467 size_t bufferLength = len;
niklase@google.com470e71d2011-07-07 08:21:25 +0000468
kwiberg55b97fe2016-01-28 05:22:45 -0800469 if (!_transportPtr->SendRtp(bufferToSendPtr, bufferLength, options)) {
470 std::string transport_name =
471 _externalTransport ? "external transport" : "WebRtc sockets";
472 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
473 "Channel::SendPacket() RTP transmission using %s failed",
474 transport_name.c_str());
475 return false;
476 }
477 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000478}
479
kwiberg55b97fe2016-01-28 05:22:45 -0800480bool Channel::SendRtcp(const uint8_t* data, size_t len) {
481 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
482 "Channel::SendRtcp(len=%" PRIuS ")", len);
niklase@google.com470e71d2011-07-07 08:21:25 +0000483
kwiberg55b97fe2016-01-28 05:22:45 -0800484 rtc::CritScope cs(&_callbackCritSect);
485 if (_transportPtr == NULL) {
486 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
487 "Channel::SendRtcp() failed to send RTCP packet"
488 " due to invalid transport object");
489 return false;
490 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000491
kwiberg55b97fe2016-01-28 05:22:45 -0800492 uint8_t* bufferToSendPtr = (uint8_t*)data;
493 size_t bufferLength = len;
niklase@google.com470e71d2011-07-07 08:21:25 +0000494
kwiberg55b97fe2016-01-28 05:22:45 -0800495 int n = _transportPtr->SendRtcp(bufferToSendPtr, bufferLength);
496 if (n < 0) {
497 std::string transport_name =
498 _externalTransport ? "external transport" : "WebRtc sockets";
499 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
500 "Channel::SendRtcp() transmission using %s failed",
501 transport_name.c_str());
502 return false;
503 }
504 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000505}
506
kwiberg55b97fe2016-01-28 05:22:45 -0800507void Channel::OnIncomingSSRCChanged(uint32_t ssrc) {
508 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
509 "Channel::OnIncomingSSRCChanged(SSRC=%d)", ssrc);
niklase@google.com470e71d2011-07-07 08:21:25 +0000510
kwiberg55b97fe2016-01-28 05:22:45 -0800511 // Update ssrc so that NTP for AV sync can be updated.
512 _rtpRtcpModule->SetRemoteSSRC(ssrc);
niklase@google.com470e71d2011-07-07 08:21:25 +0000513}
514
Peter Boströmac547a62015-09-17 23:03:57 +0200515void Channel::OnIncomingCSRCChanged(uint32_t CSRC, bool added) {
516 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
517 "Channel::OnIncomingCSRCChanged(CSRC=%d, added=%d)", CSRC,
518 added);
niklase@google.com470e71d2011-07-07 08:21:25 +0000519}
520
Peter Boströmac547a62015-09-17 23:03:57 +0200521int32_t Channel::OnInitializeDecoder(
pbos@webrtc.org92135212013-05-14 08:31:39 +0000522 int8_t payloadType,
leozwang@webrtc.org813e4b02012-03-01 18:34:25 +0000523 const char payloadName[RTP_PAYLOAD_NAME_SIZE],
pbos@webrtc.org92135212013-05-14 08:31:39 +0000524 int frequency,
Peter Kasting69558702016-01-12 16:26:35 -0800525 size_t channels,
Peter Boströmac547a62015-09-17 23:03:57 +0200526 uint32_t rate) {
kwiberg55b97fe2016-01-28 05:22:45 -0800527 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
528 "Channel::OnInitializeDecoder(payloadType=%d, "
529 "payloadName=%s, frequency=%u, channels=%" PRIuS ", rate=%u)",
530 payloadType, payloadName, frequency, channels, rate);
niklase@google.com470e71d2011-07-07 08:21:25 +0000531
kwiberg55b97fe2016-01-28 05:22:45 -0800532 CodecInst receiveCodec = {0};
533 CodecInst dummyCodec = {0};
niklase@google.com470e71d2011-07-07 08:21:25 +0000534
kwiberg55b97fe2016-01-28 05:22:45 -0800535 receiveCodec.pltype = payloadType;
536 receiveCodec.plfreq = frequency;
537 receiveCodec.channels = channels;
538 receiveCodec.rate = rate;
539 strncpy(receiveCodec.plname, payloadName, RTP_PAYLOAD_NAME_SIZE - 1);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +0000540
kwiberg55b97fe2016-01-28 05:22:45 -0800541 audio_coding_->Codec(payloadName, &dummyCodec, frequency, channels);
542 receiveCodec.pacsize = dummyCodec.pacsize;
niklase@google.com470e71d2011-07-07 08:21:25 +0000543
kwiberg55b97fe2016-01-28 05:22:45 -0800544 // Register the new codec to the ACM
kwibergda2bf4e2016-10-24 13:47:09 -0700545 if (!audio_coding_->RegisterReceiveCodec(receiveCodec.pltype,
546 CodecInstToSdp(receiveCodec))) {
kwiberg55b97fe2016-01-28 05:22:45 -0800547 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
548 "Channel::OnInitializeDecoder() invalid codec ("
549 "pt=%d, name=%s) received - 1",
550 payloadType, payloadName);
551 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR);
552 return -1;
553 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000554
kwiberg55b97fe2016-01-28 05:22:45 -0800555 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000556}
557
kwiberg55b97fe2016-01-28 05:22:45 -0800558int32_t Channel::OnReceivedPayloadData(const uint8_t* payloadData,
559 size_t payloadSize,
560 const WebRtcRTPHeader* rtpHeader) {
561 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
562 "Channel::OnReceivedPayloadData(payloadSize=%" PRIuS
563 ","
564 " payloadType=%u, audioChannel=%" PRIuS ")",
565 payloadSize, rtpHeader->header.payloadType,
566 rtpHeader->type.Audio.channel);
niklase@google.com470e71d2011-07-07 08:21:25 +0000567
kwiberg55b97fe2016-01-28 05:22:45 -0800568 if (!channel_state_.Get().playing) {
569 // Avoid inserting into NetEQ when we are not playing. Count the
570 // packet as discarded.
571 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
572 "received packet is discarded since playing is not"
573 " activated");
niklase@google.com470e71d2011-07-07 08:21:25 +0000574 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800575 }
576
577 // Push the incoming payload (parsed and ready for decoding) into the ACM
578 if (audio_coding_->IncomingPacket(payloadData, payloadSize, *rtpHeader) !=
579 0) {
580 _engineStatisticsPtr->SetLastError(
581 VE_AUDIO_CODING_MODULE_ERROR, kTraceWarning,
582 "Channel::OnReceivedPayloadData() unable to push data to the ACM");
583 return -1;
584 }
585
kwiberg55b97fe2016-01-28 05:22:45 -0800586 int64_t round_trip_time = 0;
587 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), &round_trip_time, NULL, NULL,
588 NULL);
589
590 std::vector<uint16_t> nack_list = audio_coding_->GetNackList(round_trip_time);
591 if (!nack_list.empty()) {
592 // Can't use nack_list.data() since it's not supported by all
593 // compilers.
594 ResendPackets(&(nack_list[0]), static_cast<int>(nack_list.size()));
595 }
596 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000597}
598
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000599bool Channel::OnRecoveredPacket(const uint8_t* rtp_packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000600 size_t rtp_packet_length) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000601 RTPHeader header;
602 if (!rtp_header_parser_->Parse(rtp_packet, rtp_packet_length, &header)) {
603 WEBRTC_TRACE(kTraceDebug, webrtc::kTraceVoice, _channelId,
604 "IncomingPacket invalid RTP header");
605 return false;
606 }
607 header.payload_type_frequency =
608 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
609 if (header.payload_type_frequency < 0)
610 return false;
611 return ReceivePacket(rtp_packet, rtp_packet_length, header, false);
612}
613
henrik.lundin42dda502016-05-18 05:36:01 -0700614MixerParticipant::AudioFrameInfo Channel::GetAudioFrameWithMuted(
615 int32_t id,
616 AudioFrame* audioFrame) {
ivoc14d5dbe2016-07-04 07:06:55 -0700617 unsigned int ssrc;
nisse7d59f6b2017-02-21 03:40:24 -0800618 RTC_CHECK_EQ(GetRemoteSSRC(ssrc), 0);
ivoc14d5dbe2016-07-04 07:06:55 -0700619 event_log_proxy_->LogAudioPlayout(ssrc);
kwiberg55b97fe2016-01-28 05:22:45 -0800620 // Get 10ms raw PCM data from the ACM (mixer limits output frequency)
henrik.lundind4ccb002016-05-17 12:21:55 -0700621 bool muted;
622 if (audio_coding_->PlayoutData10Ms(audioFrame->sample_rate_hz_, audioFrame,
623 &muted) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -0800624 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
625 "Channel::GetAudioFrame() PlayoutData10Ms() failed!");
626 // In all likelihood, the audio in this frame is garbage. We return an
627 // error so that the audio mixer module doesn't add it to the mix. As
628 // a result, it won't be played out and the actions skipped here are
629 // irrelevant.
henrik.lundin42dda502016-05-18 05:36:01 -0700630 return MixerParticipant::AudioFrameInfo::kError;
kwiberg55b97fe2016-01-28 05:22:45 -0800631 }
henrik.lundina89ab962016-05-18 08:52:45 -0700632
633 if (muted) {
634 // TODO(henrik.lundin): We should be able to do better than this. But we
635 // will have to go through all the cases below where the audio samples may
636 // be used, and handle the muted case in some way.
aleloi6321b492016-12-05 01:46:09 -0800637 AudioFrameOperations::Mute(audioFrame);
henrik.lundina89ab962016-05-18 08:52:45 -0700638 }
kwiberg55b97fe2016-01-28 05:22:45 -0800639
kwiberg55b97fe2016-01-28 05:22:45 -0800640 // Convert module ID to internal VoE channel ID
641 audioFrame->id_ = VoEChannelId(audioFrame->id_);
642 // Store speech type for dead-or-alive detection
643 _outputSpeechType = audioFrame->speech_type_;
644
645 ChannelState::State state = channel_state_.Get();
646
kwiberg55b97fe2016-01-28 05:22:45 -0800647 {
648 // Pass the audio buffers to an optional sink callback, before applying
649 // scaling/panning, as that applies to the mix operation.
650 // External recipients of the audio (e.g. via AudioTrack), will do their
651 // own mixing/dynamic processing.
652 rtc::CritScope cs(&_callbackCritSect);
653 if (audio_sink_) {
654 AudioSinkInterface::Data data(
655 &audioFrame->data_[0], audioFrame->samples_per_channel_,
656 audioFrame->sample_rate_hz_, audioFrame->num_channels_,
657 audioFrame->timestamp_);
658 audio_sink_->OnData(data);
659 }
660 }
661
662 float output_gain = 1.0f;
kwiberg55b97fe2016-01-28 05:22:45 -0800663 {
664 rtc::CritScope cs(&volume_settings_critsect_);
665 output_gain = _outputGain;
kwiberg55b97fe2016-01-28 05:22:45 -0800666 }
667
668 // Output volume scaling
669 if (output_gain < 0.99f || output_gain > 1.01f) {
solenberg8d73f8c2017-03-08 01:52:20 -0800670 // TODO(solenberg): Combine with mute state - this can cause clicks!
oprypin67fdb802017-03-09 06:25:06 -0800671 AudioFrameOperations::ScaleWithSat(output_gain, audioFrame);
kwiberg55b97fe2016-01-28 05:22:45 -0800672 }
673
kwiberg55b97fe2016-01-28 05:22:45 -0800674 // Mix decoded PCM output with file if file mixing is enabled
675 if (state.output_file_playing) {
676 MixAudioWithFile(*audioFrame, audioFrame->sample_rate_hz_);
henrik.lundina89ab962016-05-18 08:52:45 -0700677 muted = false; // We may have added non-zero samples.
kwiberg55b97fe2016-01-28 05:22:45 -0800678 }
679
kwiberg55b97fe2016-01-28 05:22:45 -0800680 // Record playout if enabled
681 {
682 rtc::CritScope cs(&_fileCritSect);
683
kwiberg5a25d952016-08-17 07:31:12 -0700684 if (_outputFileRecording && output_file_recorder_) {
685 output_file_recorder_->RecordAudioToFile(*audioFrame);
kwiberg55b97fe2016-01-28 05:22:45 -0800686 }
687 }
688
689 // Measure audio level (0-9)
henrik.lundina89ab962016-05-18 08:52:45 -0700690 // TODO(henrik.lundin) Use the |muted| information here too.
kwiberg55b97fe2016-01-28 05:22:45 -0800691 _outputAudioLevel.ComputeLevel(*audioFrame);
692
693 if (capture_start_rtp_time_stamp_ < 0 && audioFrame->timestamp_ != 0) {
694 // The first frame with a valid rtp timestamp.
695 capture_start_rtp_time_stamp_ = audioFrame->timestamp_;
696 }
697
698 if (capture_start_rtp_time_stamp_ >= 0) {
699 // audioFrame.timestamp_ should be valid from now on.
700
701 // Compute elapsed time.
702 int64_t unwrap_timestamp =
703 rtp_ts_wraparound_handler_->Unwrap(audioFrame->timestamp_);
704 audioFrame->elapsed_time_ms_ =
705 (unwrap_timestamp - capture_start_rtp_time_stamp_) /
ossue280cde2016-10-12 11:04:10 -0700706 (GetRtpTimestampRateHz() / 1000);
kwiberg55b97fe2016-01-28 05:22:45 -0800707
niklase@google.com470e71d2011-07-07 08:21:25 +0000708 {
kwiberg55b97fe2016-01-28 05:22:45 -0800709 rtc::CritScope lock(&ts_stats_lock_);
710 // Compute ntp time.
711 audioFrame->ntp_time_ms_ =
712 ntp_estimator_.Estimate(audioFrame->timestamp_);
713 // |ntp_time_ms_| won't be valid until at least 2 RTCP SRs are received.
714 if (audioFrame->ntp_time_ms_ > 0) {
715 // Compute |capture_start_ntp_time_ms_| so that
716 // |capture_start_ntp_time_ms_| + |elapsed_time_ms_| == |ntp_time_ms_|
717 capture_start_ntp_time_ms_ =
718 audioFrame->ntp_time_ms_ - audioFrame->elapsed_time_ms_;
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000719 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000720 }
kwiberg55b97fe2016-01-28 05:22:45 -0800721 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000722
henrik.lundin42dda502016-05-18 05:36:01 -0700723 return muted ? MixerParticipant::AudioFrameInfo::kMuted
724 : MixerParticipant::AudioFrameInfo::kNormal;
niklase@google.com470e71d2011-07-07 08:21:25 +0000725}
726
aleloi6c278492016-10-20 14:24:39 -0700727AudioMixer::Source::AudioFrameInfo Channel::GetAudioFrameWithInfo(
728 int sample_rate_hz,
729 AudioFrame* audio_frame) {
730 audio_frame->sample_rate_hz_ = sample_rate_hz;
aleloiaed581a2016-10-20 06:32:39 -0700731
aleloi6c278492016-10-20 14:24:39 -0700732 const auto frame_info = GetAudioFrameWithMuted(-1, audio_frame);
aleloiaed581a2016-10-20 06:32:39 -0700733
734 using FrameInfo = AudioMixer::Source::AudioFrameInfo;
735 FrameInfo new_audio_frame_info = FrameInfo::kError;
736 switch (frame_info) {
737 case MixerParticipant::AudioFrameInfo::kNormal:
738 new_audio_frame_info = FrameInfo::kNormal;
739 break;
740 case MixerParticipant::AudioFrameInfo::kMuted:
741 new_audio_frame_info = FrameInfo::kMuted;
742 break;
743 case MixerParticipant::AudioFrameInfo::kError:
744 new_audio_frame_info = FrameInfo::kError;
745 break;
746 }
aleloi6c278492016-10-20 14:24:39 -0700747 return new_audio_frame_info;
aleloiaed581a2016-10-20 06:32:39 -0700748}
749
kwiberg55b97fe2016-01-28 05:22:45 -0800750int32_t Channel::NeededFrequency(int32_t id) const {
751 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
752 "Channel::NeededFrequency(id=%d)", id);
niklase@google.com470e71d2011-07-07 08:21:25 +0000753
kwiberg55b97fe2016-01-28 05:22:45 -0800754 int highestNeeded = 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000755
kwiberg55b97fe2016-01-28 05:22:45 -0800756 // Determine highest needed receive frequency
757 int32_t receiveFrequency = audio_coding_->ReceiveFrequency();
niklase@google.com470e71d2011-07-07 08:21:25 +0000758
kwiberg55b97fe2016-01-28 05:22:45 -0800759 // Return the bigger of playout and receive frequency in the ACM.
760 if (audio_coding_->PlayoutFrequency() > receiveFrequency) {
761 highestNeeded = audio_coding_->PlayoutFrequency();
762 } else {
763 highestNeeded = receiveFrequency;
764 }
765
766 // Special case, if we're playing a file on the playout side
767 // we take that frequency into consideration as well
768 // This is not needed on sending side, since the codec will
769 // limit the spectrum anyway.
770 if (channel_state_.Get().output_file_playing) {
771 rtc::CritScope cs(&_fileCritSect);
kwiberg5a25d952016-08-17 07:31:12 -0700772 if (output_file_player_) {
773 if (output_file_player_->Frequency() > highestNeeded) {
774 highestNeeded = output_file_player_->Frequency();
kwiberg55b97fe2016-01-28 05:22:45 -0800775 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000776 }
kwiberg55b97fe2016-01-28 05:22:45 -0800777 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000778
kwiberg55b97fe2016-01-28 05:22:45 -0800779 return (highestNeeded);
niklase@google.com470e71d2011-07-07 08:21:25 +0000780}
781
ossu5f7cfa52016-05-30 08:11:28 -0700782int32_t Channel::CreateChannel(
783 Channel*& channel,
784 int32_t channelId,
785 uint32_t instanceId,
solenberg88499ec2016-09-07 07:34:41 -0700786 const VoEBase::ChannelConfig& config) {
kwiberg55b97fe2016-01-28 05:22:45 -0800787 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(instanceId, channelId),
788 "Channel::CreateChannel(channelId=%d, instanceId=%d)", channelId,
789 instanceId);
niklase@google.com470e71d2011-07-07 08:21:25 +0000790
solenberg88499ec2016-09-07 07:34:41 -0700791 channel = new Channel(channelId, instanceId, config);
kwiberg55b97fe2016-01-28 05:22:45 -0800792 if (channel == NULL) {
793 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(instanceId, channelId),
794 "Channel::CreateChannel() unable to allocate memory for"
795 " channel");
796 return -1;
797 }
798 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000799}
800
kwiberg55b97fe2016-01-28 05:22:45 -0800801void Channel::PlayNotification(int32_t id, uint32_t durationMs) {
802 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
803 "Channel::PlayNotification(id=%d, durationMs=%d)", id,
804 durationMs);
niklase@google.com470e71d2011-07-07 08:21:25 +0000805
kwiberg55b97fe2016-01-28 05:22:45 -0800806 // Not implement yet
niklase@google.com470e71d2011-07-07 08:21:25 +0000807}
808
kwiberg55b97fe2016-01-28 05:22:45 -0800809void Channel::RecordNotification(int32_t id, uint32_t durationMs) {
810 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
811 "Channel::RecordNotification(id=%d, durationMs=%d)", id,
812 durationMs);
niklase@google.com470e71d2011-07-07 08:21:25 +0000813
kwiberg55b97fe2016-01-28 05:22:45 -0800814 // Not implement yet
niklase@google.com470e71d2011-07-07 08:21:25 +0000815}
816
kwiberg55b97fe2016-01-28 05:22:45 -0800817void Channel::PlayFileEnded(int32_t id) {
818 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
819 "Channel::PlayFileEnded(id=%d)", id);
niklase@google.com470e71d2011-07-07 08:21:25 +0000820
kwiberg55b97fe2016-01-28 05:22:45 -0800821 if (id == _inputFilePlayerId) {
822 channel_state_.SetInputFilePlaying(false);
823 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
824 "Channel::PlayFileEnded() => input file player module is"
niklase@google.com470e71d2011-07-07 08:21:25 +0000825 " shutdown");
kwiberg55b97fe2016-01-28 05:22:45 -0800826 } else if (id == _outputFilePlayerId) {
827 channel_state_.SetOutputFilePlaying(false);
828 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
829 "Channel::PlayFileEnded() => output file player module is"
830 " shutdown");
831 }
832}
833
834void Channel::RecordFileEnded(int32_t id) {
835 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
836 "Channel::RecordFileEnded(id=%d)", id);
837
838 assert(id == _outputFileRecorderId);
839
840 rtc::CritScope cs(&_fileCritSect);
841
842 _outputFileRecording = false;
843 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
844 "Channel::RecordFileEnded() => output file recorder module is"
845 " shutdown");
niklase@google.com470e71d2011-07-07 08:21:25 +0000846}
847
pbos@webrtc.org92135212013-05-14 08:31:39 +0000848Channel::Channel(int32_t channelId,
minyue@webrtc.orge509f942013-09-12 17:03:00 +0000849 uint32_t instanceId,
solenberg88499ec2016-09-07 07:34:41 -0700850 const VoEBase::ChannelConfig& config)
tommi31fc21f2016-01-21 10:37:37 -0800851 : _instanceId(instanceId),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100852 _channelId(channelId),
ivoc14d5dbe2016-07-04 07:06:55 -0700853 event_log_proxy_(new RtcEventLogProxy()),
michaelt9332b7d2016-11-30 07:51:13 -0800854 rtcp_rtt_stats_proxy_(new RtcpRttStatsProxy()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100855 rtp_header_parser_(RtpHeaderParser::Create()),
magjedf3feeff2016-11-25 06:40:25 -0800856 rtp_payload_registry_(new RTPPayloadRegistry()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100857 rtp_receive_statistics_(
858 ReceiveStatistics::Create(Clock::GetRealTimeClock())),
859 rtp_receiver_(
860 RtpReceiver::CreateAudioReceiver(Clock::GetRealTimeClock(),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100861 this,
862 this,
863 rtp_payload_registry_.get())),
danilchap799a9d02016-09-22 03:36:27 -0700864 telephone_event_handler_(rtp_receiver_->GetTelephoneEventHandler()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100865 _outputAudioLevel(),
866 _externalTransport(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100867 // Avoid conflict with other channels by adding 1024 - 1026,
868 // won't use as much as 1024 channels.
869 _inputFilePlayerId(VoEModuleId(instanceId, channelId) + 1024),
870 _outputFilePlayerId(VoEModuleId(instanceId, channelId) + 1025),
871 _outputFileRecorderId(VoEModuleId(instanceId, channelId) + 1026),
872 _outputFileRecording(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100873 _timeStamp(0), // This is just an offset, RTP module will add it's own
874 // random offset
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100875 ntp_estimator_(Clock::GetRealTimeClock()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100876 playout_timestamp_rtp_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100877 playout_delay_ms_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100878 send_sequence_number_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100879 rtp_ts_wraparound_handler_(new rtc::TimestampWrapAroundHandler()),
880 capture_start_rtp_time_stamp_(-1),
881 capture_start_ntp_time_ms_(-1),
882 _engineStatisticsPtr(NULL),
883 _outputMixerPtr(NULL),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100884 _moduleProcessThreadPtr(NULL),
885 _audioDeviceModulePtr(NULL),
886 _voiceEngineObserverPtr(NULL),
887 _callbackCritSectPtr(NULL),
888 _transportPtr(NULL),
solenberg1c2af8e2016-03-24 10:36:00 -0700889 input_mute_(false),
890 previous_frame_muted_(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100891 _outputGain(1.0f),
solenberg8d73f8c2017-03-08 01:52:20 -0800892 _mixFileWithMicrophone(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100893 _lastLocalTimeStamp(0),
894 _lastPayloadType(0),
895 _includeAudioLevelIndication(false),
nisse284542b2017-01-10 08:58:32 -0800896 transport_overhead_per_packet_(0),
897 rtp_overhead_per_packet_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100898 _outputSpeechType(AudioFrame::kNormalSpeech),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100899 restored_packet_in_use_(false),
900 rtcp_observer_(new VoERtcpObserver(this)),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100901 associate_send_channel_(ChannelOwner(nullptr)),
solenberg88499ec2016-09-07 07:34:41 -0700902 pacing_enabled_(config.enable_voice_pacing),
stefanbba9dec2016-02-01 04:39:55 -0800903 feedback_observer_proxy_(new TransportFeedbackProxy()),
904 seq_num_allocator_proxy_(new TransportSequenceNumberProxy()),
ossu29b1a8d2016-06-13 07:34:51 -0700905 rtp_packet_sender_proxy_(new RtpPacketSenderProxy()),
Erik Språng737336d2016-07-29 12:59:36 +0200906 retransmission_rate_limiter_(new RateLimiter(Clock::GetRealTimeClock(),
907 kMaxRetransmissionWindowMs)),
elad.alond12a8e12017-03-23 11:04:48 -0700908 decoder_factory_(config.acm_config.decoder_factory),
elad.alon28770482017-03-28 05:03:55 -0700909 use_twcc_plr_for_ana_(
910 webrtc::field_trial::FindFullName("UseTwccPlrForAna") == "Enabled") {
kwiberg55b97fe2016-01-28 05:22:45 -0800911 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
912 "Channel::Channel() - ctor");
solenberg88499ec2016-09-07 07:34:41 -0700913 AudioCodingModule::Config acm_config(config.acm_config);
kwiberg55b97fe2016-01-28 05:22:45 -0800914 acm_config.id = VoEModuleId(instanceId, channelId);
henrik.lundina89ab962016-05-18 08:52:45 -0700915 acm_config.neteq_config.enable_muted_state = true;
kwiberg55b97fe2016-01-28 05:22:45 -0800916 audio_coding_.reset(AudioCodingModule::Create(acm_config));
Henrik Lundin64dad832015-05-11 12:44:23 +0200917
kwiberg55b97fe2016-01-28 05:22:45 -0800918 _outputAudioLevel.Clear();
niklase@google.com470e71d2011-07-07 08:21:25 +0000919
kwiberg55b97fe2016-01-28 05:22:45 -0800920 RtpRtcp::Configuration configuration;
921 configuration.audio = true;
922 configuration.outgoing_transport = this;
michaeltbf65be52016-12-15 06:24:49 -0800923 configuration.overhead_observer = this;
kwiberg55b97fe2016-01-28 05:22:45 -0800924 configuration.receive_statistics = rtp_receive_statistics_.get();
925 configuration.bandwidth_callback = rtcp_observer_.get();
stefanbba9dec2016-02-01 04:39:55 -0800926 if (pacing_enabled_) {
927 configuration.paced_sender = rtp_packet_sender_proxy_.get();
928 configuration.transport_sequence_number_allocator =
929 seq_num_allocator_proxy_.get();
930 configuration.transport_feedback_callback = feedback_observer_proxy_.get();
931 }
ivoc14d5dbe2016-07-04 07:06:55 -0700932 configuration.event_log = &(*event_log_proxy_);
michaelt9332b7d2016-11-30 07:51:13 -0800933 configuration.rtt_stats = &(*rtcp_rtt_stats_proxy_);
Erik Språng737336d2016-07-29 12:59:36 +0200934 configuration.retransmission_rate_limiter =
935 retransmission_rate_limiter_.get();
pwestin@webrtc.org2853dde2012-05-11 11:08:54 +0000936
kwiberg55b97fe2016-01-28 05:22:45 -0800937 _rtpRtcpModule.reset(RtpRtcp::CreateRtpRtcp(configuration));
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100938 _rtpRtcpModule->SetSendingMediaStatus(false);
niklase@google.com470e71d2011-07-07 08:21:25 +0000939}
940
kwiberg55b97fe2016-01-28 05:22:45 -0800941Channel::~Channel() {
tommi0a2391f2017-03-21 02:31:51 -0700942 RTC_DCHECK(!channel_state_.Get().sending);
943 RTC_DCHECK(!channel_state_.Get().playing);
niklase@google.com470e71d2011-07-07 08:21:25 +0000944}
945
kwiberg55b97fe2016-01-28 05:22:45 -0800946int32_t Channel::Init() {
tommi0a2391f2017-03-21 02:31:51 -0700947 RTC_DCHECK(construction_thread_.CalledOnValidThread());
kwiberg55b97fe2016-01-28 05:22:45 -0800948 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
949 "Channel::Init()");
niklase@google.com470e71d2011-07-07 08:21:25 +0000950
kwiberg55b97fe2016-01-28 05:22:45 -0800951 channel_state_.Reset();
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +0000952
kwiberg55b97fe2016-01-28 05:22:45 -0800953 // --- Initial sanity
niklase@google.com470e71d2011-07-07 08:21:25 +0000954
kwiberg55b97fe2016-01-28 05:22:45 -0800955 if ((_engineStatisticsPtr == NULL) || (_moduleProcessThreadPtr == NULL)) {
956 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
957 "Channel::Init() must call SetEngineInformation() first");
958 return -1;
959 }
960
961 // --- Add modules to process thread (for periodic schedulation)
962
tommidea489f2017-03-03 03:20:24 -0800963 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get(), RTC_FROM_HERE);
kwiberg55b97fe2016-01-28 05:22:45 -0800964
965 // --- ACM initialization
966
967 if (audio_coding_->InitializeReceiver() == -1) {
968 _engineStatisticsPtr->SetLastError(
969 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
970 "Channel::Init() unable to initialize the ACM - 1");
971 return -1;
972 }
973
974 // --- RTP/RTCP module initialization
975
976 // Ensure that RTCP is enabled by default for the created channel.
977 // Note that, the module will keep generating RTCP until it is explicitly
978 // disabled by the user.
979 // After StopListen (when no sockets exists), RTCP packets will no longer
980 // be transmitted since the Transport object will then be invalid.
danilchap799a9d02016-09-22 03:36:27 -0700981 telephone_event_handler_->SetTelephoneEventForwardToDecoder(true);
kwiberg55b97fe2016-01-28 05:22:45 -0800982 // RTCP is enabled by default.
983 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
984 // --- Register all permanent callbacks
solenbergfe7dd6d2017-03-11 08:10:43 -0800985 if (audio_coding_->RegisterTransportCallback(this) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -0800986 _engineStatisticsPtr->SetLastError(
987 VE_CANNOT_INIT_CHANNEL, kTraceError,
988 "Channel::Init() callbacks not registered");
989 return -1;
990 }
991
kwiberg1c07c702017-03-27 07:15:49 -0700992 // Register a default set of send codecs.
993 const int nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
kwiberg55b97fe2016-01-28 05:22:45 -0800994 for (int idx = 0; idx < nSupportedCodecs; idx++) {
kwiberg1c07c702017-03-27 07:15:49 -0700995 CodecInst codec;
996 RTC_CHECK_EQ(0, audio_coding_->Codec(idx, &codec));
997
998 // Ensure that PCMU is used as default send codec.
999 if (STR_CASE_CMP(codec.plname, "PCMU") == 0 && codec.channels == 1) {
1000 SetSendCodec(codec);
1001 }
1002
1003 // Register default PT for 'telephone-event'
1004 if (STR_CASE_CMP(codec.plname, "telephone-event") == 0) {
1005 if (_rtpRtcpModule->RegisterSendPayload(codec) == -1) {
1006 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1007 "Channel::Init() failed to register outband "
1008 "'telephone-event' (%d/%d) correctly",
1009 codec.pltype, codec.plfreq);
1010 }
1011 }
1012
1013 if (STR_CASE_CMP(codec.plname, "CN") == 0) {
1014 if (!codec_manager_.RegisterEncoder(codec) ||
1015 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get()) ||
1016 _rtpRtcpModule->RegisterSendPayload(codec) == -1) {
1017 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1018 "Channel::Init() failed to register CN (%d/%d) "
1019 "correctly - 1",
1020 codec.pltype, codec.plfreq);
1021 }
1022 }
1023 }
1024
1025 return 0;
1026}
1027
1028void Channel::RegisterLegacyReceiveCodecs() {
1029 const int nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
1030 for (int idx = 0; idx < nSupportedCodecs; idx++) {
1031 CodecInst codec;
1032 RTC_CHECK_EQ(0, audio_coding_->Codec(idx, &codec));
1033
kwiberg55b97fe2016-01-28 05:22:45 -08001034 // Open up the RTP/RTCP receiver for all supported codecs
kwiberg1c07c702017-03-27 07:15:49 -07001035 if (rtp_receiver_->RegisterReceivePayload(codec) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08001036 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1037 "Channel::Init() unable to register %s "
1038 "(%d/%d/%" PRIuS "/%d) to RTP/RTCP receiver",
1039 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1040 codec.rate);
1041 } else {
1042 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1043 "Channel::Init() %s (%d/%d/%" PRIuS
1044 "/%d) has been "
1045 "added to the RTP/RTCP receiver",
1046 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1047 codec.rate);
niklase@google.com470e71d2011-07-07 08:21:25 +00001048 }
1049
kwiberg1c07c702017-03-27 07:15:49 -07001050 // Register default PT for 'telephone-event'
1051 if (STR_CASE_CMP(codec.plname, "telephone-event") == 0) {
1052 if (!audio_coding_->RegisterReceiveCodec(codec.pltype,
kwibergda2bf4e2016-10-24 13:47:09 -07001053 CodecInstToSdp(codec))) {
kwiberg55b97fe2016-01-28 05:22:45 -08001054 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
kwiberg1c07c702017-03-27 07:15:49 -07001055 "Channel::Init() failed to register inband "
kwiberg55b97fe2016-01-28 05:22:45 -08001056 "'telephone-event' (%d/%d) correctly",
1057 codec.pltype, codec.plfreq);
1058 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001059 }
1060
kwiberg1c07c702017-03-27 07:15:49 -07001061 if (STR_CASE_CMP(codec.plname, "CN") == 0) {
1062 if (!audio_coding_->RegisterReceiveCodec(codec.pltype,
1063 CodecInstToSdp(codec))) {
kwiberg55b97fe2016-01-28 05:22:45 -08001064 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1065 "Channel::Init() failed to register CN (%d/%d) "
1066 "correctly - 1",
1067 codec.pltype, codec.plfreq);
1068 }
1069 }
kwiberg55b97fe2016-01-28 05:22:45 -08001070 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001071}
1072
tommi0a2391f2017-03-21 02:31:51 -07001073void Channel::Terminate() {
1074 RTC_DCHECK(construction_thread_.CalledOnValidThread());
1075 // Must be called on the same thread as Init().
1076 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
1077 "Channel::Terminate");
1078
1079 rtp_receive_statistics_->RegisterRtcpStatisticsCallback(NULL);
1080
1081 StopSend();
1082 StopPlayout();
1083
1084 {
1085 rtc::CritScope cs(&_fileCritSect);
1086 if (input_file_player_) {
1087 input_file_player_->RegisterModuleFileCallback(NULL);
1088 input_file_player_->StopPlayingFile();
1089 }
1090 if (output_file_player_) {
1091 output_file_player_->RegisterModuleFileCallback(NULL);
1092 output_file_player_->StopPlayingFile();
1093 }
1094 if (output_file_recorder_) {
1095 output_file_recorder_->RegisterModuleFileCallback(NULL);
1096 output_file_recorder_->StopRecording();
1097 }
1098 }
1099
1100 // The order to safely shutdown modules in a channel is:
1101 // 1. De-register callbacks in modules
1102 // 2. De-register modules in process thread
1103 // 3. Destroy modules
1104 if (audio_coding_->RegisterTransportCallback(NULL) == -1) {
1105 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1106 "Terminate() failed to de-register transport callback"
1107 " (Audio coding module)");
1108 }
1109
1110 if (audio_coding_->RegisterVADCallback(NULL) == -1) {
1111 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1112 "Terminate() failed to de-register VAD callback"
1113 " (Audio coding module)");
1114 }
1115
1116 // De-register modules in process thread
1117 if (_moduleProcessThreadPtr)
1118 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
1119
1120 // End of modules shutdown
1121}
1122
kwiberg55b97fe2016-01-28 05:22:45 -08001123int32_t Channel::SetEngineInformation(Statistics& engineStatistics,
1124 OutputMixer& outputMixer,
kwiberg55b97fe2016-01-28 05:22:45 -08001125 ProcessThread& moduleProcessThread,
1126 AudioDeviceModule& audioDeviceModule,
1127 VoiceEngineObserver* voiceEngineObserver,
1128 rtc::CriticalSection* callbackCritSect) {
1129 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1130 "Channel::SetEngineInformation()");
1131 _engineStatisticsPtr = &engineStatistics;
1132 _outputMixerPtr = &outputMixer;
kwiberg55b97fe2016-01-28 05:22:45 -08001133 _moduleProcessThreadPtr = &moduleProcessThread;
1134 _audioDeviceModulePtr = &audioDeviceModule;
1135 _voiceEngineObserverPtr = voiceEngineObserver;
1136 _callbackCritSectPtr = callbackCritSect;
1137 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001138}
1139
kwiberg55b97fe2016-01-28 05:22:45 -08001140int32_t Channel::UpdateLocalTimeStamp() {
1141 _timeStamp += static_cast<uint32_t>(_audioFrame.samples_per_channel_);
1142 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001143}
1144
kwibergb7f89d62016-02-17 10:04:18 -08001145void Channel::SetSink(std::unique_ptr<AudioSinkInterface> sink) {
tommi31fc21f2016-01-21 10:37:37 -08001146 rtc::CritScope cs(&_callbackCritSect);
deadbeef2d110be2016-01-13 12:00:26 -08001147 audio_sink_ = std::move(sink);
Tommif888bb52015-12-12 01:37:01 +01001148}
1149
ossu29b1a8d2016-06-13 07:34:51 -07001150const rtc::scoped_refptr<AudioDecoderFactory>&
1151Channel::GetAudioDecoderFactory() const {
1152 return decoder_factory_;
1153}
1154
kwiberg55b97fe2016-01-28 05:22:45 -08001155int32_t Channel::StartPlayout() {
1156 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1157 "Channel::StartPlayout()");
1158 if (channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001159 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001160 }
1161
solenberge374e012017-02-14 04:55:00 -08001162 // Add participant as candidates for mixing.
1163 if (_outputMixerPtr->SetMixabilityStatus(*this, true) != 0) {
1164 _engineStatisticsPtr->SetLastError(
1165 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1166 "StartPlayout() failed to add participant to mixer");
1167 return -1;
kwiberg55b97fe2016-01-28 05:22:45 -08001168 }
1169
1170 channel_state_.SetPlaying(true);
1171 if (RegisterFilePlayingToMixer() != 0)
1172 return -1;
1173
1174 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001175}
1176
kwiberg55b97fe2016-01-28 05:22:45 -08001177int32_t Channel::StopPlayout() {
1178 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1179 "Channel::StopPlayout()");
1180 if (!channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001181 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001182 }
1183
solenberge374e012017-02-14 04:55:00 -08001184 // Remove participant as candidates for mixing
1185 if (_outputMixerPtr->SetMixabilityStatus(*this, false) != 0) {
1186 _engineStatisticsPtr->SetLastError(
1187 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1188 "StopPlayout() failed to remove participant from mixer");
1189 return -1;
kwiberg55b97fe2016-01-28 05:22:45 -08001190 }
1191
1192 channel_state_.SetPlaying(false);
1193 _outputAudioLevel.Clear();
1194
1195 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001196}
1197
kwiberg55b97fe2016-01-28 05:22:45 -08001198int32_t Channel::StartSend() {
1199 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1200 "Channel::StartSend()");
kwiberg55b97fe2016-01-28 05:22:45 -08001201 if (channel_state_.Get().sending) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001202 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001203 }
1204 channel_state_.SetSending(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00001205
solenberg08b19df2017-02-15 00:42:31 -08001206 // Resume the previous sequence number which was reset by StopSend(). This
1207 // needs to be done before |sending| is set to true on the RTP/RTCP module.
1208 if (send_sequence_number_) {
1209 _rtpRtcpModule->SetSequenceNumber(send_sequence_number_);
1210 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001211 _rtpRtcpModule->SetSendingMediaStatus(true);
kwiberg55b97fe2016-01-28 05:22:45 -08001212 if (_rtpRtcpModule->SetSendingStatus(true) != 0) {
1213 _engineStatisticsPtr->SetLastError(
1214 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1215 "StartSend() RTP/RTCP failed to start sending");
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001216 _rtpRtcpModule->SetSendingMediaStatus(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001217 rtc::CritScope cs(&_callbackCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001218 channel_state_.SetSending(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001219 return -1;
1220 }
xians@webrtc.orge07247a2011-11-28 16:31:28 +00001221
kwiberg55b97fe2016-01-28 05:22:45 -08001222 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001223}
1224
kwiberg55b97fe2016-01-28 05:22:45 -08001225int32_t Channel::StopSend() {
1226 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1227 "Channel::StopSend()");
1228 if (!channel_state_.Get().sending) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001229 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001230 }
1231 channel_state_.SetSending(false);
1232
1233 // Store the sequence number to be able to pick up the same sequence for
1234 // the next StartSend(). This is needed for restarting device, otherwise
1235 // it might cause libSRTP to complain about packets being replayed.
1236 // TODO(xians): Remove this workaround after RtpRtcpModule's refactoring
1237 // CL is landed. See issue
1238 // https://code.google.com/p/webrtc/issues/detail?id=2111 .
1239 send_sequence_number_ = _rtpRtcpModule->SequenceNumber();
1240
1241 // Reset sending SSRC and sequence number and triggers direct transmission
1242 // of RTCP BYE
1243 if (_rtpRtcpModule->SetSendingStatus(false) == -1) {
1244 _engineStatisticsPtr->SetLastError(
1245 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
1246 "StartSend() RTP/RTCP failed to stop sending");
1247 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001248 _rtpRtcpModule->SetSendingMediaStatus(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001249
1250 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001251}
1252
kwiberg55b97fe2016-01-28 05:22:45 -08001253int32_t Channel::RegisterVoiceEngineObserver(VoiceEngineObserver& observer) {
1254 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1255 "Channel::RegisterVoiceEngineObserver()");
1256 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00001257
kwiberg55b97fe2016-01-28 05:22:45 -08001258 if (_voiceEngineObserverPtr) {
1259 _engineStatisticsPtr->SetLastError(
1260 VE_INVALID_OPERATION, kTraceError,
1261 "RegisterVoiceEngineObserver() observer already enabled");
1262 return -1;
1263 }
1264 _voiceEngineObserverPtr = &observer;
1265 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001266}
1267
kwiberg55b97fe2016-01-28 05:22:45 -08001268int32_t Channel::DeRegisterVoiceEngineObserver() {
1269 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1270 "Channel::DeRegisterVoiceEngineObserver()");
1271 rtc::CritScope cs(&_callbackCritSect);
1272
1273 if (!_voiceEngineObserverPtr) {
1274 _engineStatisticsPtr->SetLastError(
1275 VE_INVALID_OPERATION, kTraceWarning,
1276 "DeRegisterVoiceEngineObserver() observer already disabled");
1277 return 0;
1278 }
1279 _voiceEngineObserverPtr = NULL;
1280 return 0;
1281}
1282
1283int32_t Channel::GetSendCodec(CodecInst& codec) {
kwibergc8d071e2016-04-06 12:22:38 -07001284 auto send_codec = codec_manager_.GetCodecInst();
kwiberg1fd4a4a2015-11-03 11:20:50 -08001285 if (send_codec) {
1286 codec = *send_codec;
1287 return 0;
1288 }
1289 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001290}
1291
kwiberg55b97fe2016-01-28 05:22:45 -08001292int32_t Channel::GetRecCodec(CodecInst& codec) {
1293 return (audio_coding_->ReceiveCodec(&codec));
niklase@google.com470e71d2011-07-07 08:21:25 +00001294}
1295
kwiberg55b97fe2016-01-28 05:22:45 -08001296int32_t Channel::SetSendCodec(const CodecInst& codec) {
1297 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1298 "Channel::SetSendCodec()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001299
kwibergc8d071e2016-04-06 12:22:38 -07001300 if (!codec_manager_.RegisterEncoder(codec) ||
1301 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001302 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1303 "SetSendCodec() failed to register codec to ACM");
1304 return -1;
1305 }
1306
1307 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1308 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1309 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1310 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1311 "SetSendCodec() failed to register codec to"
1312 " RTP/RTCP module");
1313 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001314 }
kwiberg55b97fe2016-01-28 05:22:45 -08001315 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001316
kwiberg55b97fe2016-01-28 05:22:45 -08001317 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001318}
1319
minyue78b4d562016-11-30 04:47:39 -08001320void Channel::SetBitRate(int bitrate_bps, int64_t probing_interval_ms) {
Ivo Creusenadf89b72015-04-29 16:03:33 +02001321 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1322 "Channel::SetBitRate(bitrate_bps=%d)", bitrate_bps);
minyue7e304322016-10-12 05:00:55 -07001323 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
michaelt2fedf9c2016-11-28 02:34:18 -08001324 if (*encoder) {
1325 (*encoder)->OnReceivedUplinkBandwidth(
michaelt566d8202017-01-12 10:17:38 -08001326 bitrate_bps, rtc::Optional<int64_t>(probing_interval_ms));
michaelt2fedf9c2016-11-28 02:34:18 -08001327 }
1328 });
michaelt566d8202017-01-12 10:17:38 -08001329 retransmission_rate_limiter_->SetMaxRate(bitrate_bps);
Ivo Creusenadf89b72015-04-29 16:03:33 +02001330}
1331
elad.alond12a8e12017-03-23 11:04:48 -07001332void Channel::OnTwccBasedUplinkPacketLossRate(float packet_loss_rate) {
1333 if (!use_twcc_plr_for_ana_)
1334 return;
minyue7e304322016-10-12 05:00:55 -07001335 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
elad.alond12a8e12017-03-23 11:04:48 -07001336 if (*encoder) {
1337 (*encoder)->OnReceivedUplinkPacketLossFraction(packet_loss_rate);
1338 }
1339 });
1340}
1341
elad.alondadb4dc2017-03-23 15:29:50 -07001342void Channel::OnRecoverableUplinkPacketLossRate(
1343 float recoverable_packet_loss_rate) {
1344 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1345 if (*encoder) {
1346 (*encoder)->OnReceivedUplinkRecoverablePacketLossFraction(
1347 recoverable_packet_loss_rate);
1348 }
1349 });
1350}
1351
elad.alond12a8e12017-03-23 11:04:48 -07001352void Channel::OnUplinkPacketLossRate(float packet_loss_rate) {
1353 if (use_twcc_plr_for_ana_)
1354 return;
1355 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1356 if (*encoder) {
1357 (*encoder)->OnReceivedUplinkPacketLossFraction(packet_loss_rate);
1358 }
minyue7e304322016-10-12 05:00:55 -07001359 });
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00001360}
1361
kwiberg55b97fe2016-01-28 05:22:45 -08001362int32_t Channel::SetVADStatus(bool enableVAD,
1363 ACMVADMode mode,
1364 bool disableDTX) {
1365 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1366 "Channel::SetVADStatus(mode=%d)", mode);
kwibergc8d071e2016-04-06 12:22:38 -07001367 RTC_DCHECK(!(disableDTX && enableVAD)); // disableDTX mode is deprecated.
1368 if (!codec_manager_.SetVAD(enableVAD, mode) ||
1369 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001370 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR,
1371 kTraceError,
1372 "SetVADStatus() failed to set VAD");
1373 return -1;
1374 }
1375 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001376}
1377
kwiberg55b97fe2016-01-28 05:22:45 -08001378int32_t Channel::GetVADStatus(bool& enabledVAD,
1379 ACMVADMode& mode,
1380 bool& disabledDTX) {
kwibergc8d071e2016-04-06 12:22:38 -07001381 const auto* params = codec_manager_.GetStackParams();
1382 enabledVAD = params->use_cng;
1383 mode = params->vad_mode;
1384 disabledDTX = !params->use_cng;
kwiberg55b97fe2016-01-28 05:22:45 -08001385 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001386}
1387
kwiberg1c07c702017-03-27 07:15:49 -07001388void Channel::SetReceiveCodecs(const std::map<int, SdpAudioFormat>& codecs) {
1389 rtp_payload_registry_->SetAudioReceivePayloads(codecs);
1390 audio_coding_->SetReceiveCodecs(codecs);
1391}
1392
kwiberg55b97fe2016-01-28 05:22:45 -08001393int32_t Channel::SetRecPayloadType(const CodecInst& codec) {
kwibergd32bf752017-01-19 07:03:59 -08001394 return SetRecPayloadType(codec.pltype, CodecInstToSdp(codec));
1395}
1396
1397int32_t Channel::SetRecPayloadType(int payload_type,
1398 const SdpAudioFormat& format) {
kwiberg55b97fe2016-01-28 05:22:45 -08001399 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1400 "Channel::SetRecPayloadType()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001401
kwiberg55b97fe2016-01-28 05:22:45 -08001402 if (channel_state_.Get().playing) {
1403 _engineStatisticsPtr->SetLastError(
1404 VE_ALREADY_PLAYING, kTraceError,
1405 "SetRecPayloadType() unable to set PT while playing");
1406 return -1;
1407 }
kwiberg55b97fe2016-01-28 05:22:45 -08001408
kwiberg09f090c2017-03-01 01:57:11 -08001409 const CodecInst codec = SdpToCodecInst(payload_type, format);
kwibergd32bf752017-01-19 07:03:59 -08001410
1411 if (payload_type == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08001412 // De-register the selected codec (RTP/RTCP module and ACM)
1413
1414 int8_t pltype(-1);
1415 CodecInst rxCodec = codec;
1416
1417 // Get payload type for the given codec
magjed56124bd2016-11-24 09:34:46 -08001418 rtp_payload_registry_->ReceivePayloadType(rxCodec, &pltype);
kwiberg55b97fe2016-01-28 05:22:45 -08001419 rxCodec.pltype = pltype;
1420
1421 if (rtp_receiver_->DeRegisterReceivePayload(pltype) != 0) {
1422 _engineStatisticsPtr->SetLastError(
1423 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1424 "SetRecPayloadType() RTP/RTCP-module deregistration "
1425 "failed");
1426 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001427 }
kwiberg55b97fe2016-01-28 05:22:45 -08001428 if (audio_coding_->UnregisterReceiveCodec(rxCodec.pltype) != 0) {
1429 _engineStatisticsPtr->SetLastError(
1430 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1431 "SetRecPayloadType() ACM deregistration failed - 1");
1432 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001433 }
kwiberg55b97fe2016-01-28 05:22:45 -08001434 return 0;
1435 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001436
magjed56124bd2016-11-24 09:34:46 -08001437 if (rtp_receiver_->RegisterReceivePayload(codec) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001438 // First attempt to register failed => de-register and try again
kwibergc8d071e2016-04-06 12:22:38 -07001439 // TODO(kwiberg): Retrying is probably not necessary, since
1440 // AcmReceiver::AddCodec also retries.
kwiberg55b97fe2016-01-28 05:22:45 -08001441 rtp_receiver_->DeRegisterReceivePayload(codec.pltype);
magjed56124bd2016-11-24 09:34:46 -08001442 if (rtp_receiver_->RegisterReceivePayload(codec) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001443 _engineStatisticsPtr->SetLastError(
1444 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1445 "SetRecPayloadType() RTP/RTCP-module registration failed");
1446 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001447 }
kwiberg55b97fe2016-01-28 05:22:45 -08001448 }
kwibergd32bf752017-01-19 07:03:59 -08001449 if (!audio_coding_->RegisterReceiveCodec(payload_type, format)) {
1450 audio_coding_->UnregisterReceiveCodec(payload_type);
1451 if (!audio_coding_->RegisterReceiveCodec(payload_type, format)) {
kwiberg55b97fe2016-01-28 05:22:45 -08001452 _engineStatisticsPtr->SetLastError(
1453 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1454 "SetRecPayloadType() ACM registration failed - 1");
1455 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001456 }
kwiberg55b97fe2016-01-28 05:22:45 -08001457 }
1458 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001459}
1460
kwiberg55b97fe2016-01-28 05:22:45 -08001461int32_t Channel::GetRecPayloadType(CodecInst& codec) {
1462 int8_t payloadType(-1);
magjed56124bd2016-11-24 09:34:46 -08001463 if (rtp_payload_registry_->ReceivePayloadType(codec, &payloadType) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001464 _engineStatisticsPtr->SetLastError(
1465 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
1466 "GetRecPayloadType() failed to retrieve RX payload type");
1467 return -1;
1468 }
1469 codec.pltype = payloadType;
1470 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001471}
1472
kwiberg55b97fe2016-01-28 05:22:45 -08001473int32_t Channel::SetSendCNPayloadType(int type, PayloadFrequencies frequency) {
1474 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1475 "Channel::SetSendCNPayloadType()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001476
kwiberg55b97fe2016-01-28 05:22:45 -08001477 CodecInst codec;
1478 int32_t samplingFreqHz(-1);
1479 const size_t kMono = 1;
1480 if (frequency == kFreq32000Hz)
1481 samplingFreqHz = 32000;
1482 else if (frequency == kFreq16000Hz)
1483 samplingFreqHz = 16000;
niklase@google.com470e71d2011-07-07 08:21:25 +00001484
kwiberg55b97fe2016-01-28 05:22:45 -08001485 if (audio_coding_->Codec("CN", &codec, samplingFreqHz, kMono) == -1) {
1486 _engineStatisticsPtr->SetLastError(
1487 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1488 "SetSendCNPayloadType() failed to retrieve default CN codec "
1489 "settings");
1490 return -1;
1491 }
1492
1493 // Modify the payload type (must be set to dynamic range)
1494 codec.pltype = type;
1495
kwibergc8d071e2016-04-06 12:22:38 -07001496 if (!codec_manager_.RegisterEncoder(codec) ||
1497 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001498 _engineStatisticsPtr->SetLastError(
1499 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1500 "SetSendCNPayloadType() failed to register CN to ACM");
1501 return -1;
1502 }
1503
1504 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1505 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1506 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1507 _engineStatisticsPtr->SetLastError(
1508 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1509 "SetSendCNPayloadType() failed to register CN to RTP/RTCP "
1510 "module");
1511 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001512 }
kwiberg55b97fe2016-01-28 05:22:45 -08001513 }
1514 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001515}
1516
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001517int Channel::SetOpusMaxPlaybackRate(int frequency_hz) {
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001518 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001519 "Channel::SetOpusMaxPlaybackRate()");
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001520
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001521 if (audio_coding_->SetOpusMaxPlaybackRate(frequency_hz) != 0) {
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001522 _engineStatisticsPtr->SetLastError(
1523 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001524 "SetOpusMaxPlaybackRate() failed to set maximum playback rate");
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001525 return -1;
1526 }
1527 return 0;
1528}
1529
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001530int Channel::SetOpusDtx(bool enable_dtx) {
1531 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1532 "Channel::SetOpusDtx(%d)", enable_dtx);
Minyue Li092041c2015-05-11 12:19:35 +02001533 int ret = enable_dtx ? audio_coding_->EnableOpusDtx()
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001534 : audio_coding_->DisableOpusDtx();
1535 if (ret != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001536 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR,
1537 kTraceError, "SetOpusDtx() failed");
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001538 return -1;
1539 }
1540 return 0;
1541}
1542
ivoc85228d62016-07-27 04:53:47 -07001543int Channel::GetOpusDtx(bool* enabled) {
1544 int success = -1;
1545 audio_coding_->QueryEncoder([&](AudioEncoder const* encoder) {
1546 if (encoder) {
1547 *enabled = encoder->GetDtx();
1548 success = 0;
1549 }
1550 });
1551 return success;
1552}
1553
minyue7e304322016-10-12 05:00:55 -07001554bool Channel::EnableAudioNetworkAdaptor(const std::string& config_string) {
1555 bool success = false;
1556 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1557 if (*encoder) {
1558 success = (*encoder)->EnableAudioNetworkAdaptor(
michaeltbf279fc2017-01-13 06:02:29 -08001559 config_string, event_log_proxy_.get(), Clock::GetRealTimeClock());
minyue7e304322016-10-12 05:00:55 -07001560 }
1561 });
1562 return success;
1563}
1564
1565void Channel::DisableAudioNetworkAdaptor() {
1566 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1567 if (*encoder)
1568 (*encoder)->DisableAudioNetworkAdaptor();
1569 });
1570}
1571
1572void Channel::SetReceiverFrameLengthRange(int min_frame_length_ms,
1573 int max_frame_length_ms) {
1574 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1575 if (*encoder) {
1576 (*encoder)->SetReceiverFrameLengthRange(min_frame_length_ms,
1577 max_frame_length_ms);
1578 }
1579 });
1580}
1581
mflodman3d7db262016-04-29 00:57:13 -07001582int32_t Channel::RegisterExternalTransport(Transport* transport) {
kwiberg55b97fe2016-01-28 05:22:45 -08001583 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00001584 "Channel::RegisterExternalTransport()");
1585
kwiberg55b97fe2016-01-28 05:22:45 -08001586 rtc::CritScope cs(&_callbackCritSect);
kwiberg55b97fe2016-01-28 05:22:45 -08001587 if (_externalTransport) {
1588 _engineStatisticsPtr->SetLastError(
1589 VE_INVALID_OPERATION, kTraceError,
1590 "RegisterExternalTransport() external transport already enabled");
1591 return -1;
1592 }
1593 _externalTransport = true;
mflodman3d7db262016-04-29 00:57:13 -07001594 _transportPtr = transport;
kwiberg55b97fe2016-01-28 05:22:45 -08001595 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001596}
1597
kwiberg55b97fe2016-01-28 05:22:45 -08001598int32_t Channel::DeRegisterExternalTransport() {
1599 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1600 "Channel::DeRegisterExternalTransport()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001601
kwiberg55b97fe2016-01-28 05:22:45 -08001602 rtc::CritScope cs(&_callbackCritSect);
mflodman3d7db262016-04-29 00:57:13 -07001603 if (_transportPtr) {
1604 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1605 "DeRegisterExternalTransport() all transport is disabled");
1606 } else {
kwiberg55b97fe2016-01-28 05:22:45 -08001607 _engineStatisticsPtr->SetLastError(
1608 VE_INVALID_OPERATION, kTraceWarning,
1609 "DeRegisterExternalTransport() external transport already "
1610 "disabled");
kwiberg55b97fe2016-01-28 05:22:45 -08001611 }
1612 _externalTransport = false;
1613 _transportPtr = NULL;
kwiberg55b97fe2016-01-28 05:22:45 -08001614 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001615}
1616
nisse657bab22017-02-21 06:28:10 -08001617// TODO(nisse): Delete this method together with ReceivedRTPPacket.
1618// It's a temporary hack to support both ReceivedRTPPacket and
1619// OnRtpPacket interfaces without too much code duplication.
1620bool Channel::OnRtpPacketWithHeader(const uint8_t* received_packet,
1621 size_t length,
1622 RTPHeader *header) {
1623 // Store playout timestamp for the received RTP packet
1624 UpdatePlayoutTimestamp(false);
1625
1626 header->payload_type_frequency =
1627 rtp_payload_registry_->GetPayloadTypeFrequency(header->payloadType);
1628 if (header->payload_type_frequency < 0)
1629 return false;
1630 bool in_order = IsPacketInOrder(*header);
1631 rtp_receive_statistics_->IncomingPacket(
1632 *header, length, IsPacketRetransmitted(*header, in_order));
1633 rtp_payload_registry_->SetIncomingPayloadType(*header);
1634
1635 return ReceivePacket(received_packet, length, *header, in_order);
1636}
1637
mflodman3d7db262016-04-29 00:57:13 -07001638int32_t Channel::ReceivedRTPPacket(const uint8_t* received_packet,
kwiberg55b97fe2016-01-28 05:22:45 -08001639 size_t length,
solenberg@webrtc.orgb1f50102014-03-24 10:38:25 +00001640 const PacketTime& packet_time) {
kwiberg55b97fe2016-01-28 05:22:45 -08001641 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001642 "Channel::ReceivedRTPPacket()");
1643
stefan@webrtc.orga5cb98c2013-05-29 12:12:51 +00001644 RTPHeader header;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001645 if (!rtp_header_parser_->Parse(received_packet, length, &header)) {
1646 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1647 "Incoming packet: invalid RTP header");
stefan@webrtc.orga5cb98c2013-05-29 12:12:51 +00001648 return -1;
1649 }
nisse657bab22017-02-21 06:28:10 -08001650 return OnRtpPacketWithHeader(received_packet, length, &header) ? 0 : -1;
1651}
solenberg@webrtc.orgb1f50102014-03-24 10:38:25 +00001652
nisse657bab22017-02-21 06:28:10 -08001653void Channel::OnRtpPacket(const RtpPacketReceived& packet) {
1654 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
1655 "Channel::ReceivedRTPPacket()");
1656
1657 RTPHeader header;
1658 packet.GetHeader(&header);
1659 OnRtpPacketWithHeader(packet.data(), packet.size(), &header);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001660}
1661
1662bool Channel::ReceivePacket(const uint8_t* packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001663 size_t packet_length,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001664 const RTPHeader& header,
1665 bool in_order) {
minyue@webrtc.org456f0142015-01-23 11:58:42 +00001666 if (rtp_payload_registry_->IsRtx(header)) {
1667 return HandleRtxPacket(packet, packet_length, header);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001668 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001669 const uint8_t* payload = packet + header.headerLength;
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001670 assert(packet_length >= header.headerLength);
1671 size_t payload_length = packet_length - header.headerLength;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001672 PayloadUnion payload_specific;
1673 if (!rtp_payload_registry_->GetPayloadSpecifics(header.payloadType,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001674 &payload_specific)) {
1675 return false;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001676 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001677 return rtp_receiver_->IncomingRtpPacket(header, payload, payload_length,
1678 payload_specific, in_order);
1679}
1680
minyue@webrtc.org456f0142015-01-23 11:58:42 +00001681bool Channel::HandleRtxPacket(const uint8_t* packet,
1682 size_t packet_length,
1683 const RTPHeader& header) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001684 if (!rtp_payload_registry_->IsRtx(header))
1685 return false;
1686
1687 // Remove the RTX header and parse the original RTP header.
1688 if (packet_length < header.headerLength)
1689 return false;
1690 if (packet_length > kVoiceEngineMaxIpPacketSizeBytes)
1691 return false;
1692 if (restored_packet_in_use_) {
1693 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1694 "Multiple RTX headers detected, dropping packet");
1695 return false;
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001696 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001697 if (!rtp_payload_registry_->RestoreOriginalPacket(
noahric65220a72015-10-14 11:29:49 -07001698 restored_packet_, packet, &packet_length, rtp_receiver_->SSRC(),
1699 header)) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001700 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1701 "Incoming RTX packet: invalid RTP header");
1702 return false;
1703 }
1704 restored_packet_in_use_ = true;
noahric65220a72015-10-14 11:29:49 -07001705 bool ret = OnRecoveredPacket(restored_packet_, packet_length);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001706 restored_packet_in_use_ = false;
1707 return ret;
1708}
1709
1710bool Channel::IsPacketInOrder(const RTPHeader& header) const {
1711 StreamStatistician* statistician =
1712 rtp_receive_statistics_->GetStatistician(header.ssrc);
1713 if (!statistician)
1714 return false;
1715 return statistician->IsPacketInOrder(header.sequenceNumber);
niklase@google.com470e71d2011-07-07 08:21:25 +00001716}
1717
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001718bool Channel::IsPacketRetransmitted(const RTPHeader& header,
1719 bool in_order) const {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001720 // Retransmissions are handled separately if RTX is enabled.
1721 if (rtp_payload_registry_->RtxEnabled())
1722 return false;
1723 StreamStatistician* statistician =
1724 rtp_receive_statistics_->GetStatistician(header.ssrc);
1725 if (!statistician)
1726 return false;
1727 // Check if this is a retransmission.
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001728 int64_t min_rtt = 0;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001729 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), NULL, NULL, &min_rtt, NULL);
kwiberg55b97fe2016-01-28 05:22:45 -08001730 return !in_order && statistician->IsRetransmitOfOldPacket(header, min_rtt);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001731}
1732
mflodman3d7db262016-04-29 00:57:13 -07001733int32_t Channel::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
kwiberg55b97fe2016-01-28 05:22:45 -08001734 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001735 "Channel::ReceivedRTCPPacket()");
1736 // Store playout timestamp for the received RTCP packet
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001737 UpdatePlayoutTimestamp(true);
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001738
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001739 // Deliver RTCP packet to RTP/RTCP module for parsing
mflodman3d7db262016-04-29 00:57:13 -07001740 if (_rtpRtcpModule->IncomingRtcpPacket(data, length) == -1) {
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001741 _engineStatisticsPtr->SetLastError(
1742 VE_SOCKET_TRANSPORT_MODULE_ERROR, kTraceWarning,
1743 "Channel::IncomingRTPPacket() RTCP packet is invalid");
1744 }
wu@webrtc.org82c4b852014-05-20 22:55:01 +00001745
Minyue2013aec2015-05-13 14:14:42 +02001746 int64_t rtt = GetRTT(true);
1747 if (rtt == 0) {
1748 // Waiting for valid RTT.
1749 return 0;
1750 }
Erik Språng737336d2016-07-29 12:59:36 +02001751
1752 int64_t nack_window_ms = rtt;
1753 if (nack_window_ms < kMinRetransmissionWindowMs) {
1754 nack_window_ms = kMinRetransmissionWindowMs;
1755 } else if (nack_window_ms > kMaxRetransmissionWindowMs) {
1756 nack_window_ms = kMaxRetransmissionWindowMs;
1757 }
1758 retransmission_rate_limiter_->SetWindowSize(nack_window_ms);
1759
minyue7e304322016-10-12 05:00:55 -07001760 // Invoke audio encoders OnReceivedRtt().
1761 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1762 if (*encoder)
1763 (*encoder)->OnReceivedRtt(rtt);
1764 });
1765
Minyue2013aec2015-05-13 14:14:42 +02001766 uint32_t ntp_secs = 0;
1767 uint32_t ntp_frac = 0;
1768 uint32_t rtp_timestamp = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001769 if (0 !=
1770 _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
1771 &rtp_timestamp)) {
Minyue2013aec2015-05-13 14:14:42 +02001772 // Waiting for RTCP.
1773 return 0;
1774 }
1775
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001776 {
tommi31fc21f2016-01-21 10:37:37 -08001777 rtc::CritScope lock(&ts_stats_lock_);
minyue@webrtc.org2c0cdbc2014-10-09 10:52:43 +00001778 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001779 }
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001780 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001781}
1782
niklase@google.com470e71d2011-07-07 08:21:25 +00001783int Channel::StartPlayingFileLocally(const char* fileName,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001784 bool loop,
1785 FileFormats format,
1786 int startPosition,
1787 float volumeScaling,
1788 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001789 const CodecInst* codecInst) {
1790 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1791 "Channel::StartPlayingFileLocally(fileNameUTF8[]=%s, loop=%d,"
1792 " format=%d, volumeScaling=%5.3f, startPosition=%d, "
1793 "stopPosition=%d)",
1794 fileName, loop, format, volumeScaling, startPosition,
1795 stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001796
kwiberg55b97fe2016-01-28 05:22:45 -08001797 if (channel_state_.Get().output_file_playing) {
1798 _engineStatisticsPtr->SetLastError(
1799 VE_ALREADY_PLAYING, kTraceError,
1800 "StartPlayingFileLocally() is already playing");
1801 return -1;
1802 }
1803
1804 {
1805 rtc::CritScope cs(&_fileCritSect);
1806
kwiberg5a25d952016-08-17 07:31:12 -07001807 if (output_file_player_) {
1808 output_file_player_->RegisterModuleFileCallback(NULL);
1809 output_file_player_.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +00001810 }
1811
kwiberg5b356f42016-09-08 04:32:33 -07001812 output_file_player_ = FilePlayer::CreateFilePlayer(
kwiberg55b97fe2016-01-28 05:22:45 -08001813 _outputFilePlayerId, (const FileFormats)format);
henrike@webrtc.orgb37c6282011-10-31 23:53:04 +00001814
kwiberg5a25d952016-08-17 07:31:12 -07001815 if (!output_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08001816 _engineStatisticsPtr->SetLastError(
1817 VE_INVALID_ARGUMENT, kTraceError,
1818 "StartPlayingFileLocally() filePlayer format is not correct");
1819 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001820 }
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001821
kwiberg55b97fe2016-01-28 05:22:45 -08001822 const uint32_t notificationTime(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00001823
kwiberg5a25d952016-08-17 07:31:12 -07001824 if (output_file_player_->StartPlayingFile(
kwiberg55b97fe2016-01-28 05:22:45 -08001825 fileName, loop, startPosition, volumeScaling, notificationTime,
1826 stopPosition, (const CodecInst*)codecInst) != 0) {
1827 _engineStatisticsPtr->SetLastError(
1828 VE_BAD_FILE, kTraceError,
1829 "StartPlayingFile() failed to start file playout");
kwiberg5a25d952016-08-17 07:31:12 -07001830 output_file_player_->StopPlayingFile();
1831 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001832 return -1;
1833 }
kwiberg5a25d952016-08-17 07:31:12 -07001834 output_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08001835 channel_state_.SetOutputFilePlaying(true);
1836 }
1837
1838 if (RegisterFilePlayingToMixer() != 0)
1839 return -1;
1840
1841 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001842}
1843
1844int Channel::StartPlayingFileLocally(InStream* stream,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001845 FileFormats format,
1846 int startPosition,
1847 float volumeScaling,
1848 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001849 const CodecInst* codecInst) {
1850 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1851 "Channel::StartPlayingFileLocally(format=%d,"
1852 " volumeScaling=%5.3f, startPosition=%d, stopPosition=%d)",
1853 format, volumeScaling, startPosition, stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001854
kwiberg55b97fe2016-01-28 05:22:45 -08001855 if (stream == NULL) {
1856 _engineStatisticsPtr->SetLastError(
1857 VE_BAD_FILE, kTraceError,
1858 "StartPlayingFileLocally() NULL as input stream");
1859 return -1;
1860 }
1861
1862 if (channel_state_.Get().output_file_playing) {
1863 _engineStatisticsPtr->SetLastError(
1864 VE_ALREADY_PLAYING, kTraceError,
1865 "StartPlayingFileLocally() is already playing");
1866 return -1;
1867 }
1868
1869 {
1870 rtc::CritScope cs(&_fileCritSect);
1871
1872 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07001873 if (output_file_player_) {
1874 output_file_player_->RegisterModuleFileCallback(NULL);
1875 output_file_player_.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +00001876 }
1877
kwiberg55b97fe2016-01-28 05:22:45 -08001878 // Create the instance
kwiberg5b356f42016-09-08 04:32:33 -07001879 output_file_player_ = FilePlayer::CreateFilePlayer(
kwiberg55b97fe2016-01-28 05:22:45 -08001880 _outputFilePlayerId, (const FileFormats)format);
niklase@google.com470e71d2011-07-07 08:21:25 +00001881
kwiberg5a25d952016-08-17 07:31:12 -07001882 if (!output_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08001883 _engineStatisticsPtr->SetLastError(
1884 VE_INVALID_ARGUMENT, kTraceError,
1885 "StartPlayingFileLocally() filePlayer format isnot correct");
1886 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001887 }
1888
kwiberg55b97fe2016-01-28 05:22:45 -08001889 const uint32_t notificationTime(0);
henrike@webrtc.orgb37c6282011-10-31 23:53:04 +00001890
kwiberg4ec01d92016-08-22 08:43:54 -07001891 if (output_file_player_->StartPlayingFile(stream, startPosition,
kwiberg5a25d952016-08-17 07:31:12 -07001892 volumeScaling, notificationTime,
1893 stopPosition, codecInst) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001894 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
1895 "StartPlayingFile() failed to "
1896 "start file playout");
kwiberg5a25d952016-08-17 07:31:12 -07001897 output_file_player_->StopPlayingFile();
1898 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001899 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001900 }
kwiberg5a25d952016-08-17 07:31:12 -07001901 output_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08001902 channel_state_.SetOutputFilePlaying(true);
1903 }
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001904
kwiberg55b97fe2016-01-28 05:22:45 -08001905 if (RegisterFilePlayingToMixer() != 0)
1906 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001907
kwiberg55b97fe2016-01-28 05:22:45 -08001908 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001909}
1910
kwiberg55b97fe2016-01-28 05:22:45 -08001911int Channel::StopPlayingFileLocally() {
1912 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1913 "Channel::StopPlayingFileLocally()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001914
kwiberg55b97fe2016-01-28 05:22:45 -08001915 if (!channel_state_.Get().output_file_playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001916 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001917 }
1918
1919 {
1920 rtc::CritScope cs(&_fileCritSect);
1921
kwiberg5a25d952016-08-17 07:31:12 -07001922 if (output_file_player_->StopPlayingFile() != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001923 _engineStatisticsPtr->SetLastError(
1924 VE_STOP_RECORDING_FAILED, kTraceError,
1925 "StopPlayingFile() could not stop playing");
1926 return -1;
1927 }
kwiberg5a25d952016-08-17 07:31:12 -07001928 output_file_player_->RegisterModuleFileCallback(NULL);
1929 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001930 channel_state_.SetOutputFilePlaying(false);
1931 }
1932 // _fileCritSect cannot be taken while calling
1933 // SetAnonymousMixibilityStatus. Refer to comments in
1934 // StartPlayingFileLocally(const char* ...) for more details.
1935 if (_outputMixerPtr->SetAnonymousMixabilityStatus(*this, false) != 0) {
1936 _engineStatisticsPtr->SetLastError(
1937 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1938 "StopPlayingFile() failed to stop participant from playing as"
1939 "file in the mixer");
1940 return -1;
1941 }
1942
1943 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001944}
1945
kwiberg55b97fe2016-01-28 05:22:45 -08001946int Channel::IsPlayingFileLocally() const {
1947 return channel_state_.Get().output_file_playing;
niklase@google.com470e71d2011-07-07 08:21:25 +00001948}
1949
kwiberg55b97fe2016-01-28 05:22:45 -08001950int Channel::RegisterFilePlayingToMixer() {
1951 // Return success for not registering for file playing to mixer if:
1952 // 1. playing file before playout is started on that channel.
1953 // 2. starting playout without file playing on that channel.
1954 if (!channel_state_.Get().playing ||
1955 !channel_state_.Get().output_file_playing) {
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001956 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001957 }
1958
1959 // |_fileCritSect| cannot be taken while calling
1960 // SetAnonymousMixabilityStatus() since as soon as the participant is added
1961 // frames can be pulled by the mixer. Since the frames are generated from
1962 // the file, _fileCritSect will be taken. This would result in a deadlock.
1963 if (_outputMixerPtr->SetAnonymousMixabilityStatus(*this, true) != 0) {
1964 channel_state_.SetOutputFilePlaying(false);
1965 rtc::CritScope cs(&_fileCritSect);
1966 _engineStatisticsPtr->SetLastError(
1967 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1968 "StartPlayingFile() failed to add participant as file to mixer");
kwiberg5a25d952016-08-17 07:31:12 -07001969 output_file_player_->StopPlayingFile();
1970 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001971 return -1;
1972 }
1973
1974 return 0;
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001975}
1976
niklase@google.com470e71d2011-07-07 08:21:25 +00001977int Channel::StartPlayingFileAsMicrophone(const char* fileName,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001978 bool loop,
1979 FileFormats format,
1980 int startPosition,
1981 float volumeScaling,
1982 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001983 const CodecInst* codecInst) {
1984 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1985 "Channel::StartPlayingFileAsMicrophone(fileNameUTF8[]=%s, "
1986 "loop=%d, format=%d, volumeScaling=%5.3f, startPosition=%d, "
1987 "stopPosition=%d)",
1988 fileName, loop, format, volumeScaling, startPosition,
1989 stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001990
kwiberg55b97fe2016-01-28 05:22:45 -08001991 rtc::CritScope cs(&_fileCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001992
kwiberg55b97fe2016-01-28 05:22:45 -08001993 if (channel_state_.Get().input_file_playing) {
1994 _engineStatisticsPtr->SetLastError(
1995 VE_ALREADY_PLAYING, kTraceWarning,
1996 "StartPlayingFileAsMicrophone() filePlayer is playing");
niklase@google.com470e71d2011-07-07 08:21:25 +00001997 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001998 }
1999
2000 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07002001 if (input_file_player_) {
2002 input_file_player_->RegisterModuleFileCallback(NULL);
2003 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002004 }
2005
2006 // Create the instance
kwiberg5b356f42016-09-08 04:32:33 -07002007 input_file_player_ = FilePlayer::CreateFilePlayer(_inputFilePlayerId,
kwiberg5a25d952016-08-17 07:31:12 -07002008 (const FileFormats)format);
kwiberg55b97fe2016-01-28 05:22:45 -08002009
kwiberg5a25d952016-08-17 07:31:12 -07002010 if (!input_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002011 _engineStatisticsPtr->SetLastError(
2012 VE_INVALID_ARGUMENT, kTraceError,
2013 "StartPlayingFileAsMicrophone() filePlayer format isnot correct");
2014 return -1;
2015 }
2016
2017 const uint32_t notificationTime(0);
2018
kwiberg5a25d952016-08-17 07:31:12 -07002019 if (input_file_player_->StartPlayingFile(
kwiberg55b97fe2016-01-28 05:22:45 -08002020 fileName, loop, startPosition, volumeScaling, notificationTime,
2021 stopPosition, (const CodecInst*)codecInst) != 0) {
2022 _engineStatisticsPtr->SetLastError(
2023 VE_BAD_FILE, kTraceError,
2024 "StartPlayingFile() failed to start file playout");
kwiberg5a25d952016-08-17 07:31:12 -07002025 input_file_player_->StopPlayingFile();
2026 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002027 return -1;
2028 }
kwiberg5a25d952016-08-17 07:31:12 -07002029 input_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002030 channel_state_.SetInputFilePlaying(true);
2031
2032 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002033}
2034
2035int Channel::StartPlayingFileAsMicrophone(InStream* stream,
pbos@webrtc.org92135212013-05-14 08:31:39 +00002036 FileFormats format,
2037 int startPosition,
2038 float volumeScaling,
2039 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08002040 const CodecInst* codecInst) {
2041 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2042 "Channel::StartPlayingFileAsMicrophone(format=%d, "
2043 "volumeScaling=%5.3f, startPosition=%d, stopPosition=%d)",
2044 format, volumeScaling, startPosition, stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00002045
kwiberg55b97fe2016-01-28 05:22:45 -08002046 if (stream == NULL) {
2047 _engineStatisticsPtr->SetLastError(
2048 VE_BAD_FILE, kTraceError,
2049 "StartPlayingFileAsMicrophone NULL as input stream");
2050 return -1;
2051 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002052
kwiberg55b97fe2016-01-28 05:22:45 -08002053 rtc::CritScope cs(&_fileCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00002054
kwiberg55b97fe2016-01-28 05:22:45 -08002055 if (channel_state_.Get().input_file_playing) {
2056 _engineStatisticsPtr->SetLastError(
2057 VE_ALREADY_PLAYING, kTraceWarning,
2058 "StartPlayingFileAsMicrophone() is playing");
niklase@google.com470e71d2011-07-07 08:21:25 +00002059 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002060 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002061
kwiberg55b97fe2016-01-28 05:22:45 -08002062 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07002063 if (input_file_player_) {
2064 input_file_player_->RegisterModuleFileCallback(NULL);
2065 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002066 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002067
kwiberg55b97fe2016-01-28 05:22:45 -08002068 // Create the instance
kwiberg5b356f42016-09-08 04:32:33 -07002069 input_file_player_ = FilePlayer::CreateFilePlayer(_inputFilePlayerId,
kwiberg5a25d952016-08-17 07:31:12 -07002070 (const FileFormats)format);
kwiberg55b97fe2016-01-28 05:22:45 -08002071
kwiberg5a25d952016-08-17 07:31:12 -07002072 if (!input_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002073 _engineStatisticsPtr->SetLastError(
2074 VE_INVALID_ARGUMENT, kTraceError,
2075 "StartPlayingInputFile() filePlayer format isnot correct");
2076 return -1;
2077 }
2078
2079 const uint32_t notificationTime(0);
2080
kwiberg4ec01d92016-08-22 08:43:54 -07002081 if (input_file_player_->StartPlayingFile(stream, startPosition, volumeScaling,
2082 notificationTime, stopPosition,
2083 codecInst) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002084 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
2085 "StartPlayingFile() failed to start "
2086 "file playout");
kwiberg5a25d952016-08-17 07:31:12 -07002087 input_file_player_->StopPlayingFile();
2088 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002089 return -1;
2090 }
2091
kwiberg5a25d952016-08-17 07:31:12 -07002092 input_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002093 channel_state_.SetInputFilePlaying(true);
2094
2095 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002096}
2097
kwiberg55b97fe2016-01-28 05:22:45 -08002098int Channel::StopPlayingFileAsMicrophone() {
2099 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2100 "Channel::StopPlayingFileAsMicrophone()");
2101
2102 rtc::CritScope cs(&_fileCritSect);
2103
2104 if (!channel_state_.Get().input_file_playing) {
2105 return 0;
2106 }
2107
kwiberg5a25d952016-08-17 07:31:12 -07002108 if (input_file_player_->StopPlayingFile() != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002109 _engineStatisticsPtr->SetLastError(
2110 VE_STOP_RECORDING_FAILED, kTraceError,
2111 "StopPlayingFile() could not stop playing");
2112 return -1;
2113 }
kwiberg5a25d952016-08-17 07:31:12 -07002114 input_file_player_->RegisterModuleFileCallback(NULL);
2115 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002116 channel_state_.SetInputFilePlaying(false);
2117
2118 return 0;
2119}
2120
2121int Channel::IsPlayingFileAsMicrophone() const {
2122 return channel_state_.Get().input_file_playing;
niklase@google.com470e71d2011-07-07 08:21:25 +00002123}
2124
leozwang@webrtc.org813e4b02012-03-01 18:34:25 +00002125int Channel::StartRecordingPlayout(const char* fileName,
kwiberg55b97fe2016-01-28 05:22:45 -08002126 const CodecInst* codecInst) {
2127 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2128 "Channel::StartRecordingPlayout(fileName=%s)", fileName);
niklase@google.com470e71d2011-07-07 08:21:25 +00002129
kwiberg55b97fe2016-01-28 05:22:45 -08002130 if (_outputFileRecording) {
2131 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, -1),
2132 "StartRecordingPlayout() is already recording");
niklase@google.com470e71d2011-07-07 08:21:25 +00002133 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002134 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002135
kwiberg55b97fe2016-01-28 05:22:45 -08002136 FileFormats format;
2137 const uint32_t notificationTime(0); // Not supported in VoE
2138 CodecInst dummyCodec = {100, "L16", 16000, 320, 1, 320000};
niklase@google.com470e71d2011-07-07 08:21:25 +00002139
kwiberg55b97fe2016-01-28 05:22:45 -08002140 if ((codecInst != NULL) &&
2141 ((codecInst->channels < 1) || (codecInst->channels > 2))) {
2142 _engineStatisticsPtr->SetLastError(
2143 VE_BAD_ARGUMENT, kTraceError,
2144 "StartRecordingPlayout() invalid compression");
2145 return (-1);
2146 }
2147 if (codecInst == NULL) {
2148 format = kFileFormatPcm16kHzFile;
2149 codecInst = &dummyCodec;
2150 } else if ((STR_CASE_CMP(codecInst->plname, "L16") == 0) ||
2151 (STR_CASE_CMP(codecInst->plname, "PCMU") == 0) ||
2152 (STR_CASE_CMP(codecInst->plname, "PCMA") == 0)) {
2153 format = kFileFormatWavFile;
2154 } else {
2155 format = kFileFormatCompressedFile;
2156 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002157
kwiberg55b97fe2016-01-28 05:22:45 -08002158 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002159
kwiberg55b97fe2016-01-28 05:22:45 -08002160 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07002161 if (output_file_recorder_) {
2162 output_file_recorder_->RegisterModuleFileCallback(NULL);
2163 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002164 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002165
kwiberg5a25d952016-08-17 07:31:12 -07002166 output_file_recorder_ = FileRecorder::CreateFileRecorder(
kwiberg55b97fe2016-01-28 05:22:45 -08002167 _outputFileRecorderId, (const FileFormats)format);
kwiberg5a25d952016-08-17 07:31:12 -07002168 if (!output_file_recorder_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002169 _engineStatisticsPtr->SetLastError(
2170 VE_INVALID_ARGUMENT, kTraceError,
2171 "StartRecordingPlayout() fileRecorder format isnot correct");
2172 return -1;
2173 }
2174
kwiberg5a25d952016-08-17 07:31:12 -07002175 if (output_file_recorder_->StartRecordingAudioFile(
kwiberg55b97fe2016-01-28 05:22:45 -08002176 fileName, (const CodecInst&)*codecInst, notificationTime) != 0) {
2177 _engineStatisticsPtr->SetLastError(
2178 VE_BAD_FILE, kTraceError,
2179 "StartRecordingAudioFile() failed to start file recording");
kwiberg5a25d952016-08-17 07:31:12 -07002180 output_file_recorder_->StopRecording();
2181 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002182 return -1;
2183 }
kwiberg5a25d952016-08-17 07:31:12 -07002184 output_file_recorder_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002185 _outputFileRecording = true;
2186
2187 return 0;
2188}
2189
2190int Channel::StartRecordingPlayout(OutStream* stream,
2191 const CodecInst* codecInst) {
2192 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2193 "Channel::StartRecordingPlayout()");
2194
2195 if (_outputFileRecording) {
2196 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, -1),
2197 "StartRecordingPlayout() is already recording");
niklase@google.com470e71d2011-07-07 08:21:25 +00002198 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002199 }
2200
2201 FileFormats format;
2202 const uint32_t notificationTime(0); // Not supported in VoE
2203 CodecInst dummyCodec = {100, "L16", 16000, 320, 1, 320000};
2204
2205 if (codecInst != NULL && codecInst->channels != 1) {
2206 _engineStatisticsPtr->SetLastError(
2207 VE_BAD_ARGUMENT, kTraceError,
2208 "StartRecordingPlayout() invalid compression");
2209 return (-1);
2210 }
2211 if (codecInst == NULL) {
2212 format = kFileFormatPcm16kHzFile;
2213 codecInst = &dummyCodec;
2214 } else if ((STR_CASE_CMP(codecInst->plname, "L16") == 0) ||
2215 (STR_CASE_CMP(codecInst->plname, "PCMU") == 0) ||
2216 (STR_CASE_CMP(codecInst->plname, "PCMA") == 0)) {
2217 format = kFileFormatWavFile;
2218 } else {
2219 format = kFileFormatCompressedFile;
2220 }
2221
2222 rtc::CritScope cs(&_fileCritSect);
2223
2224 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07002225 if (output_file_recorder_) {
2226 output_file_recorder_->RegisterModuleFileCallback(NULL);
2227 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002228 }
2229
kwiberg5a25d952016-08-17 07:31:12 -07002230 output_file_recorder_ = FileRecorder::CreateFileRecorder(
kwiberg55b97fe2016-01-28 05:22:45 -08002231 _outputFileRecorderId, (const FileFormats)format);
kwiberg5a25d952016-08-17 07:31:12 -07002232 if (!output_file_recorder_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002233 _engineStatisticsPtr->SetLastError(
2234 VE_INVALID_ARGUMENT, kTraceError,
2235 "StartRecordingPlayout() fileRecorder format isnot correct");
2236 return -1;
2237 }
2238
kwiberg4ec01d92016-08-22 08:43:54 -07002239 if (output_file_recorder_->StartRecordingAudioFile(stream, *codecInst,
kwiberg5a25d952016-08-17 07:31:12 -07002240 notificationTime) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002241 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
2242 "StartRecordingPlayout() failed to "
2243 "start file recording");
kwiberg5a25d952016-08-17 07:31:12 -07002244 output_file_recorder_->StopRecording();
2245 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002246 return -1;
2247 }
2248
kwiberg5a25d952016-08-17 07:31:12 -07002249 output_file_recorder_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002250 _outputFileRecording = true;
2251
2252 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002253}
2254
kwiberg55b97fe2016-01-28 05:22:45 -08002255int Channel::StopRecordingPlayout() {
2256 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, -1),
2257 "Channel::StopRecordingPlayout()");
2258
2259 if (!_outputFileRecording) {
2260 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, -1),
2261 "StopRecordingPlayout() isnot recording");
2262 return -1;
2263 }
2264
2265 rtc::CritScope cs(&_fileCritSect);
2266
kwiberg5a25d952016-08-17 07:31:12 -07002267 if (output_file_recorder_->StopRecording() != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002268 _engineStatisticsPtr->SetLastError(
2269 VE_STOP_RECORDING_FAILED, kTraceError,
2270 "StopRecording() could not stop recording");
2271 return (-1);
2272 }
kwiberg5a25d952016-08-17 07:31:12 -07002273 output_file_recorder_->RegisterModuleFileCallback(NULL);
2274 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002275 _outputFileRecording = false;
2276
2277 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002278}
2279
kwiberg55b97fe2016-01-28 05:22:45 -08002280void Channel::SetMixWithMicStatus(bool mix) {
2281 rtc::CritScope cs(&_fileCritSect);
2282 _mixFileWithMicrophone = mix;
niklase@google.com470e71d2011-07-07 08:21:25 +00002283}
2284
solenberg8d73f8c2017-03-08 01:52:20 -08002285int Channel::GetSpeechOutputLevel() const {
2286 return _outputAudioLevel.Level();
niklase@google.com470e71d2011-07-07 08:21:25 +00002287}
2288
solenberg8d73f8c2017-03-08 01:52:20 -08002289int Channel::GetSpeechOutputLevelFullRange() const {
2290 return _outputAudioLevel.LevelFullRange();
kwiberg55b97fe2016-01-28 05:22:45 -08002291}
2292
solenberg8d73f8c2017-03-08 01:52:20 -08002293void Channel::SetInputMute(bool enable) {
kwiberg55b97fe2016-01-28 05:22:45 -08002294 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07002295 input_mute_ = enable;
niklase@google.com470e71d2011-07-07 08:21:25 +00002296}
2297
solenberg1c2af8e2016-03-24 10:36:00 -07002298bool Channel::InputMute() const {
kwiberg55b97fe2016-01-28 05:22:45 -08002299 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07002300 return input_mute_;
niklase@google.com470e71d2011-07-07 08:21:25 +00002301}
2302
solenberg8d73f8c2017-03-08 01:52:20 -08002303void Channel::SetChannelOutputVolumeScaling(float scaling) {
kwiberg55b97fe2016-01-28 05:22:45 -08002304 rtc::CritScope cs(&volume_settings_critsect_);
kwiberg55b97fe2016-01-28 05:22:45 -08002305 _outputGain = scaling;
niklase@google.com470e71d2011-07-07 08:21:25 +00002306}
2307
solenberg8842c3e2016-03-11 03:06:41 -08002308int Channel::SendTelephoneEventOutband(int event, int duration_ms) {
kwiberg55b97fe2016-01-28 05:22:45 -08002309 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
solenberg8842c3e2016-03-11 03:06:41 -08002310 "Channel::SendTelephoneEventOutband(...)");
2311 RTC_DCHECK_LE(0, event);
2312 RTC_DCHECK_GE(255, event);
2313 RTC_DCHECK_LE(0, duration_ms);
2314 RTC_DCHECK_GE(65535, duration_ms);
kwiberg55b97fe2016-01-28 05:22:45 -08002315 if (!Sending()) {
2316 return -1;
2317 }
solenberg8842c3e2016-03-11 03:06:41 -08002318 if (_rtpRtcpModule->SendTelephoneEventOutband(
2319 event, duration_ms, kTelephoneEventAttenuationdB) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002320 _engineStatisticsPtr->SetLastError(
2321 VE_SEND_DTMF_FAILED, kTraceWarning,
2322 "SendTelephoneEventOutband() failed to send event");
2323 return -1;
2324 }
2325 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002326}
2327
solenbergffbbcac2016-11-17 05:25:37 -08002328int Channel::SetSendTelephoneEventPayloadType(int payload_type,
2329 int payload_frequency) {
kwiberg55b97fe2016-01-28 05:22:45 -08002330 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002331 "Channel::SetSendTelephoneEventPayloadType()");
solenberg31642aa2016-03-14 08:00:37 -07002332 RTC_DCHECK_LE(0, payload_type);
2333 RTC_DCHECK_GE(127, payload_type);
2334 CodecInst codec = {0};
solenberg31642aa2016-03-14 08:00:37 -07002335 codec.pltype = payload_type;
solenbergffbbcac2016-11-17 05:25:37 -08002336 codec.plfreq = payload_frequency;
kwiberg55b97fe2016-01-28 05:22:45 -08002337 memcpy(codec.plname, "telephone-event", 16);
2338 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
2339 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
2340 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
2341 _engineStatisticsPtr->SetLastError(
2342 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2343 "SetSendTelephoneEventPayloadType() failed to register send"
2344 "payload type");
2345 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002346 }
kwiberg55b97fe2016-01-28 05:22:45 -08002347 }
kwiberg55b97fe2016-01-28 05:22:45 -08002348 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002349}
2350
kwiberg55b97fe2016-01-28 05:22:45 -08002351int Channel::SetLocalSSRC(unsigned int ssrc) {
2352 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2353 "Channel::SetLocalSSRC()");
2354 if (channel_state_.Get().sending) {
2355 _engineStatisticsPtr->SetLastError(VE_ALREADY_SENDING, kTraceError,
2356 "SetLocalSSRC() already sending");
2357 return -1;
2358 }
2359 _rtpRtcpModule->SetSSRC(ssrc);
2360 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002361}
2362
kwiberg55b97fe2016-01-28 05:22:45 -08002363int Channel::GetLocalSSRC(unsigned int& ssrc) {
2364 ssrc = _rtpRtcpModule->SSRC();
2365 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002366}
2367
kwiberg55b97fe2016-01-28 05:22:45 -08002368int Channel::GetRemoteSSRC(unsigned int& ssrc) {
2369 ssrc = rtp_receiver_->SSRC();
2370 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002371}
2372
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002373int Channel::SetSendAudioLevelIndicationStatus(bool enable, unsigned char id) {
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00002374 _includeAudioLevelIndication = enable;
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002375 return SetSendRtpHeaderExtension(enable, kRtpExtensionAudioLevel, id);
niklase@google.com470e71d2011-07-07 08:21:25 +00002376}
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00002377
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00002378int Channel::SetReceiveAudioLevelIndicationStatus(bool enable,
2379 unsigned char id) {
kwiberg55b97fe2016-01-28 05:22:45 -08002380 rtp_header_parser_->DeregisterRtpHeaderExtension(kRtpExtensionAudioLevel);
2381 if (enable &&
2382 !rtp_header_parser_->RegisterRtpHeaderExtension(kRtpExtensionAudioLevel,
2383 id)) {
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00002384 return -1;
2385 }
2386 return 0;
2387}
2388
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002389void Channel::EnableSendTransportSequenceNumber(int id) {
2390 int ret =
2391 SetSendRtpHeaderExtension(true, kRtpExtensionTransportSequenceNumber, id);
2392 RTC_DCHECK_EQ(0, ret);
2393}
2394
stefan3313ec92016-01-21 06:32:43 -08002395void Channel::EnableReceiveTransportSequenceNumber(int id) {
2396 rtp_header_parser_->DeregisterRtpHeaderExtension(
2397 kRtpExtensionTransportSequenceNumber);
2398 bool ret = rtp_header_parser_->RegisterRtpHeaderExtension(
2399 kRtpExtensionTransportSequenceNumber, id);
2400 RTC_DCHECK(ret);
2401}
2402
stefanbba9dec2016-02-01 04:39:55 -08002403void Channel::RegisterSenderCongestionControlObjects(
nisseb8f9a322017-03-27 05:36:15 -07002404 RtpTransportControllerSendInterface* transport,
stefan7de8d642017-02-07 07:14:08 -08002405 RtcpBandwidthObserver* bandwidth_observer) {
nisseb8f9a322017-03-27 05:36:15 -07002406 RtpPacketSender* rtp_packet_sender = transport->packet_sender();
2407 TransportFeedbackObserver* transport_feedback_observer =
2408 transport->transport_feedback_observer();
2409 PacketRouter* packet_router = transport->packet_router();
2410
stefanbba9dec2016-02-01 04:39:55 -08002411 RTC_DCHECK(rtp_packet_sender);
2412 RTC_DCHECK(transport_feedback_observer);
2413 RTC_DCHECK(packet_router && !packet_router_);
stefan7de8d642017-02-07 07:14:08 -08002414 rtcp_observer_->SetBandwidthObserver(bandwidth_observer);
stefanbba9dec2016-02-01 04:39:55 -08002415 feedback_observer_proxy_->SetTransportFeedbackObserver(
2416 transport_feedback_observer);
2417 seq_num_allocator_proxy_->SetSequenceNumberAllocator(packet_router);
2418 rtp_packet_sender_proxy_->SetPacketSender(rtp_packet_sender);
2419 _rtpRtcpModule->SetStorePacketsStatus(true, 600);
Peter Boström3dd5d1d2016-02-25 16:56:48 +01002420 packet_router->AddRtpModule(_rtpRtcpModule.get());
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002421 packet_router_ = packet_router;
2422}
2423
stefanbba9dec2016-02-01 04:39:55 -08002424void Channel::RegisterReceiverCongestionControlObjects(
2425 PacketRouter* packet_router) {
2426 RTC_DCHECK(packet_router && !packet_router_);
Peter Boström3dd5d1d2016-02-25 16:56:48 +01002427 packet_router->AddRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08002428 packet_router_ = packet_router;
2429}
2430
2431void Channel::ResetCongestionControlObjects() {
2432 RTC_DCHECK(packet_router_);
2433 _rtpRtcpModule->SetStorePacketsStatus(false, 600);
stefan7de8d642017-02-07 07:14:08 -08002434 rtcp_observer_->SetBandwidthObserver(nullptr);
stefanbba9dec2016-02-01 04:39:55 -08002435 feedback_observer_proxy_->SetTransportFeedbackObserver(nullptr);
2436 seq_num_allocator_proxy_->SetSequenceNumberAllocator(nullptr);
Peter Boström3dd5d1d2016-02-25 16:56:48 +01002437 packet_router_->RemoveRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08002438 packet_router_ = nullptr;
2439 rtp_packet_sender_proxy_->SetPacketSender(nullptr);
2440}
2441
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00002442void Channel::SetRTCPStatus(bool enable) {
2443 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2444 "Channel::SetRTCPStatus()");
pbosda903ea2015-10-02 02:36:56 -07002445 _rtpRtcpModule->SetRTCPStatus(enable ? RtcpMode::kCompound : RtcpMode::kOff);
niklase@google.com470e71d2011-07-07 08:21:25 +00002446}
2447
kwiberg55b97fe2016-01-28 05:22:45 -08002448int Channel::GetRTCPStatus(bool& enabled) {
pbosda903ea2015-10-02 02:36:56 -07002449 RtcpMode method = _rtpRtcpModule->RTCP();
2450 enabled = (method != RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08002451 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002452}
2453
kwiberg55b97fe2016-01-28 05:22:45 -08002454int Channel::SetRTCP_CNAME(const char cName[256]) {
2455 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2456 "Channel::SetRTCP_CNAME()");
2457 if (_rtpRtcpModule->SetCNAME(cName) != 0) {
2458 _engineStatisticsPtr->SetLastError(
2459 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2460 "SetRTCP_CNAME() failed to set RTCP CNAME");
2461 return -1;
2462 }
2463 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002464}
2465
kwiberg55b97fe2016-01-28 05:22:45 -08002466int Channel::GetRemoteRTCP_CNAME(char cName[256]) {
2467 if (cName == NULL) {
2468 _engineStatisticsPtr->SetLastError(
2469 VE_INVALID_ARGUMENT, kTraceError,
2470 "GetRemoteRTCP_CNAME() invalid CNAME input buffer");
2471 return -1;
2472 }
2473 char cname[RTCP_CNAME_SIZE];
2474 const uint32_t remoteSSRC = rtp_receiver_->SSRC();
2475 if (_rtpRtcpModule->RemoteCNAME(remoteSSRC, cname) != 0) {
2476 _engineStatisticsPtr->SetLastError(
2477 VE_CANNOT_RETRIEVE_CNAME, kTraceError,
2478 "GetRemoteRTCP_CNAME() failed to retrieve remote RTCP CNAME");
2479 return -1;
2480 }
2481 strcpy(cName, cname);
2482 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002483}
2484
kwiberg55b97fe2016-01-28 05:22:45 -08002485int Channel::SendApplicationDefinedRTCPPacket(
2486 unsigned char subType,
2487 unsigned int name,
2488 const char* data,
2489 unsigned short dataLengthInBytes) {
2490 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2491 "Channel::SendApplicationDefinedRTCPPacket()");
2492 if (!channel_state_.Get().sending) {
2493 _engineStatisticsPtr->SetLastError(
2494 VE_NOT_SENDING, kTraceError,
2495 "SendApplicationDefinedRTCPPacket() not sending");
2496 return -1;
2497 }
2498 if (NULL == data) {
2499 _engineStatisticsPtr->SetLastError(
2500 VE_INVALID_ARGUMENT, kTraceError,
2501 "SendApplicationDefinedRTCPPacket() invalid data value");
2502 return -1;
2503 }
2504 if (dataLengthInBytes % 4 != 0) {
2505 _engineStatisticsPtr->SetLastError(
2506 VE_INVALID_ARGUMENT, kTraceError,
2507 "SendApplicationDefinedRTCPPacket() invalid length value");
2508 return -1;
2509 }
2510 RtcpMode status = _rtpRtcpModule->RTCP();
2511 if (status == RtcpMode::kOff) {
2512 _engineStatisticsPtr->SetLastError(
2513 VE_RTCP_ERROR, kTraceError,
2514 "SendApplicationDefinedRTCPPacket() RTCP is disabled");
2515 return -1;
2516 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002517
kwiberg55b97fe2016-01-28 05:22:45 -08002518 // Create and schedule the RTCP APP packet for transmission
2519 if (_rtpRtcpModule->SetRTCPApplicationSpecificData(
2520 subType, name, (const unsigned char*)data, dataLengthInBytes) != 0) {
2521 _engineStatisticsPtr->SetLastError(
2522 VE_SEND_ERROR, kTraceError,
2523 "SendApplicationDefinedRTCPPacket() failed to send RTCP packet");
2524 return -1;
2525 }
2526 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002527}
2528
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002529int Channel::GetRemoteRTCPReportBlocks(
2530 std::vector<ReportBlock>* report_blocks) {
2531 if (report_blocks == NULL) {
kwiberg55b97fe2016-01-28 05:22:45 -08002532 _engineStatisticsPtr->SetLastError(
2533 VE_INVALID_ARGUMENT, kTraceError,
2534 "GetRemoteRTCPReportBlock()s invalid report_blocks.");
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002535 return -1;
2536 }
2537
2538 // Get the report blocks from the latest received RTCP Sender or Receiver
2539 // Report. Each element in the vector contains the sender's SSRC and a
2540 // report block according to RFC 3550.
2541 std::vector<RTCPReportBlock> rtcp_report_blocks;
2542 if (_rtpRtcpModule->RemoteRTCPStat(&rtcp_report_blocks) != 0) {
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002543 return -1;
2544 }
2545
2546 if (rtcp_report_blocks.empty())
2547 return 0;
2548
2549 std::vector<RTCPReportBlock>::const_iterator it = rtcp_report_blocks.begin();
2550 for (; it != rtcp_report_blocks.end(); ++it) {
2551 ReportBlock report_block;
2552 report_block.sender_SSRC = it->remoteSSRC;
2553 report_block.source_SSRC = it->sourceSSRC;
2554 report_block.fraction_lost = it->fractionLost;
2555 report_block.cumulative_num_packets_lost = it->cumulativeLost;
2556 report_block.extended_highest_sequence_number = it->extendedHighSeqNum;
2557 report_block.interarrival_jitter = it->jitter;
2558 report_block.last_SR_timestamp = it->lastSR;
2559 report_block.delay_since_last_SR = it->delaySinceLastSR;
2560 report_blocks->push_back(report_block);
2561 }
2562 return 0;
2563}
2564
kwiberg55b97fe2016-01-28 05:22:45 -08002565int Channel::GetRTPStatistics(CallStatistics& stats) {
2566 // --- RtcpStatistics
niklase@google.com470e71d2011-07-07 08:21:25 +00002567
kwiberg55b97fe2016-01-28 05:22:45 -08002568 // The jitter statistics is updated for each received RTP packet and is
2569 // based on received packets.
2570 RtcpStatistics statistics;
2571 StreamStatistician* statistician =
2572 rtp_receive_statistics_->GetStatistician(rtp_receiver_->SSRC());
Peter Boström59013bc2016-02-12 11:35:08 +01002573 if (statistician) {
2574 statistician->GetStatistics(&statistics,
2575 _rtpRtcpModule->RTCP() == RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08002576 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002577
kwiberg55b97fe2016-01-28 05:22:45 -08002578 stats.fractionLost = statistics.fraction_lost;
2579 stats.cumulativeLost = statistics.cumulative_lost;
2580 stats.extendedMax = statistics.extended_max_sequence_number;
2581 stats.jitterSamples = statistics.jitter;
niklase@google.com470e71d2011-07-07 08:21:25 +00002582
kwiberg55b97fe2016-01-28 05:22:45 -08002583 // --- RTT
2584 stats.rttMs = GetRTT(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00002585
kwiberg55b97fe2016-01-28 05:22:45 -08002586 // --- Data counters
niklase@google.com470e71d2011-07-07 08:21:25 +00002587
kwiberg55b97fe2016-01-28 05:22:45 -08002588 size_t bytesSent(0);
2589 uint32_t packetsSent(0);
2590 size_t bytesReceived(0);
2591 uint32_t packetsReceived(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00002592
kwiberg55b97fe2016-01-28 05:22:45 -08002593 if (statistician) {
2594 statistician->GetDataCounters(&bytesReceived, &packetsReceived);
2595 }
wu@webrtc.org822fbd82013-08-15 23:38:54 +00002596
kwiberg55b97fe2016-01-28 05:22:45 -08002597 if (_rtpRtcpModule->DataCountersRTP(&bytesSent, &packetsSent) != 0) {
2598 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2599 "GetRTPStatistics() failed to retrieve RTP datacounters =>"
2600 " output will not be complete");
2601 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002602
kwiberg55b97fe2016-01-28 05:22:45 -08002603 stats.bytesSent = bytesSent;
2604 stats.packetsSent = packetsSent;
2605 stats.bytesReceived = bytesReceived;
2606 stats.packetsReceived = packetsReceived;
niklase@google.com470e71d2011-07-07 08:21:25 +00002607
kwiberg55b97fe2016-01-28 05:22:45 -08002608 // --- Timestamps
2609 {
2610 rtc::CritScope lock(&ts_stats_lock_);
2611 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
2612 }
2613 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002614}
2615
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002616int Channel::SetCodecFECStatus(bool enable) {
2617 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2618 "Channel::SetCodecFECStatus()");
2619
kwibergc8d071e2016-04-06 12:22:38 -07002620 if (!codec_manager_.SetCodecFEC(enable) ||
2621 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002622 _engineStatisticsPtr->SetLastError(
2623 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
2624 "SetCodecFECStatus() failed to set FEC state");
2625 return -1;
2626 }
2627 return 0;
2628}
2629
2630bool Channel::GetCodecFECStatus() {
kwibergc8d071e2016-04-06 12:22:38 -07002631 return codec_manager_.GetStackParams()->use_codec_fec;
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002632}
2633
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002634void Channel::SetNACKStatus(bool enable, int maxNumberOfPackets) {
2635 // None of these functions can fail.
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002636 // If pacing is enabled we always store packets.
2637 if (!pacing_enabled_)
2638 _rtpRtcpModule->SetStorePacketsStatus(enable, maxNumberOfPackets);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00002639 rtp_receive_statistics_->SetMaxReorderingThreshold(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002640 if (enable)
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00002641 audio_coding_->EnableNack(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002642 else
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00002643 audio_coding_->DisableNack();
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002644}
2645
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002646// Called when we are missing one or more packets.
2647int Channel::ResendPackets(const uint16_t* sequence_numbers, int length) {
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002648 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
2649}
2650
kwiberg55b97fe2016-01-28 05:22:45 -08002651uint32_t Channel::Demultiplex(const AudioFrame& audioFrame) {
2652 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2653 "Channel::Demultiplex()");
2654 _audioFrame.CopyFrom(audioFrame);
2655 _audioFrame.id_ = _channelId;
2656 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002657}
2658
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002659void Channel::Demultiplex(const int16_t* audio_data,
xians@webrtc.org8fff1f02013-07-31 16:27:42 +00002660 int sample_rate,
Peter Kastingdce40cf2015-08-24 14:52:23 -07002661 size_t number_of_frames,
Peter Kasting69558702016-01-12 16:26:35 -08002662 size_t number_of_channels) {
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002663 CodecInst codec;
2664 GetSendCodec(codec);
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002665
Alejandro Luebscdfe20b2015-09-23 12:49:12 -07002666 // Never upsample or upmix the capture signal here. This should be done at the
2667 // end of the send chain.
2668 _audioFrame.sample_rate_hz_ = std::min(codec.plfreq, sample_rate);
2669 _audioFrame.num_channels_ = std::min(number_of_channels, codec.channels);
2670 RemixAndResample(audio_data, number_of_frames, number_of_channels,
2671 sample_rate, &input_resampler_, &_audioFrame);
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002672}
2673
kwiberg55b97fe2016-01-28 05:22:45 -08002674uint32_t Channel::PrepareEncodeAndSend(int mixingFrequency) {
2675 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2676 "Channel::PrepareEncodeAndSend()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002677
kwiberg55b97fe2016-01-28 05:22:45 -08002678 if (_audioFrame.samples_per_channel_ == 0) {
2679 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2680 "Channel::PrepareEncodeAndSend() invalid audio frame");
2681 return 0xFFFFFFFF;
2682 }
2683
2684 if (channel_state_.Get().input_file_playing) {
2685 MixOrReplaceAudioWithFile(mixingFrequency);
2686 }
2687
solenberg1c2af8e2016-03-24 10:36:00 -07002688 bool is_muted = InputMute(); // Cache locally as InputMute() takes a lock.
2689 AudioFrameOperations::Mute(&_audioFrame, previous_frame_muted_, is_muted);
kwiberg55b97fe2016-01-28 05:22:45 -08002690
kwiberg55b97fe2016-01-28 05:22:45 -08002691 if (_includeAudioLevelIndication) {
2692 size_t length =
2693 _audioFrame.samples_per_channel_ * _audioFrame.num_channels_;
Tommi60c4e0a2016-05-26 21:35:27 +02002694 RTC_CHECK_LE(length, sizeof(_audioFrame.data_));
solenberg1c2af8e2016-03-24 10:36:00 -07002695 if (is_muted && previous_frame_muted_) {
henrik.lundin50499422016-11-29 04:26:24 -08002696 rms_level_.AnalyzeMuted(length);
kwiberg55b97fe2016-01-28 05:22:45 -08002697 } else {
henrik.lundin50499422016-11-29 04:26:24 -08002698 rms_level_.Analyze(
2699 rtc::ArrayView<const int16_t>(_audioFrame.data_, length));
niklase@google.com470e71d2011-07-07 08:21:25 +00002700 }
kwiberg55b97fe2016-01-28 05:22:45 -08002701 }
solenberg1c2af8e2016-03-24 10:36:00 -07002702 previous_frame_muted_ = is_muted;
niklase@google.com470e71d2011-07-07 08:21:25 +00002703
kwiberg55b97fe2016-01-28 05:22:45 -08002704 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002705}
2706
kwiberg55b97fe2016-01-28 05:22:45 -08002707uint32_t Channel::EncodeAndSend() {
2708 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
2709 "Channel::EncodeAndSend()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002710
kwiberg55b97fe2016-01-28 05:22:45 -08002711 assert(_audioFrame.num_channels_ <= 2);
2712 if (_audioFrame.samples_per_channel_ == 0) {
2713 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2714 "Channel::EncodeAndSend() invalid audio frame");
2715 return 0xFFFFFFFF;
2716 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002717
kwiberg55b97fe2016-01-28 05:22:45 -08002718 _audioFrame.id_ = _channelId;
niklase@google.com470e71d2011-07-07 08:21:25 +00002719
kwiberg55b97fe2016-01-28 05:22:45 -08002720 // --- Add 10ms of raw (PCM) audio data to the encoder @ 32kHz.
niklase@google.com470e71d2011-07-07 08:21:25 +00002721
kwiberg55b97fe2016-01-28 05:22:45 -08002722 // The ACM resamples internally.
2723 _audioFrame.timestamp_ = _timeStamp;
2724 // This call will trigger AudioPacketizationCallback::SendData if encoding
2725 // is done and payload is ready for packetization and transmission.
2726 // Otherwise, it will return without invoking the callback.
2727 if (audio_coding_->Add10MsData((AudioFrame&)_audioFrame) < 0) {
2728 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
2729 "Channel::EncodeAndSend() ACM encoding failed");
2730 return 0xFFFFFFFF;
2731 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002732
kwiberg55b97fe2016-01-28 05:22:45 -08002733 _timeStamp += static_cast<uint32_t>(_audioFrame.samples_per_channel_);
2734 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002735}
2736
solenberg7602aab2016-11-14 11:30:07 -08002737void Channel::set_associate_send_channel(const ChannelOwner& channel) {
2738 RTC_DCHECK(!channel.channel() ||
2739 channel.channel()->ChannelId() != _channelId);
2740 rtc::CritScope lock(&assoc_send_channel_lock_);
2741 associate_send_channel_ = channel;
2742}
2743
Minyue2013aec2015-05-13 14:14:42 +02002744void Channel::DisassociateSendChannel(int channel_id) {
tommi31fc21f2016-01-21 10:37:37 -08002745 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02002746 Channel* channel = associate_send_channel_.channel();
2747 if (channel && channel->ChannelId() == channel_id) {
2748 // If this channel is associated with a send channel of the specified
2749 // Channel ID, disassociate with it.
2750 ChannelOwner ref(NULL);
2751 associate_send_channel_ = ref;
2752 }
2753}
2754
ivoc14d5dbe2016-07-04 07:06:55 -07002755void Channel::SetRtcEventLog(RtcEventLog* event_log) {
2756 event_log_proxy_->SetEventLog(event_log);
2757}
2758
michaelt9332b7d2016-11-30 07:51:13 -08002759void Channel::SetRtcpRttStats(RtcpRttStats* rtcp_rtt_stats) {
2760 rtcp_rtt_stats_proxy_->SetRtcpRttStats(rtcp_rtt_stats);
2761}
2762
nisse284542b2017-01-10 08:58:32 -08002763void Channel::UpdateOverheadForEncoder() {
hbos3fd31fe2017-02-28 05:43:16 -08002764 size_t overhead_per_packet =
2765 transport_overhead_per_packet_ + rtp_overhead_per_packet_;
nisse284542b2017-01-10 08:58:32 -08002766 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
2767 if (*encoder) {
hbos3fd31fe2017-02-28 05:43:16 -08002768 (*encoder)->OnReceivedOverhead(overhead_per_packet);
nisse284542b2017-01-10 08:58:32 -08002769 }
2770 });
2771}
2772
2773void Channel::SetTransportOverhead(size_t transport_overhead_per_packet) {
hbos3fd31fe2017-02-28 05:43:16 -08002774 rtc::CritScope cs(&overhead_per_packet_lock_);
nisse284542b2017-01-10 08:58:32 -08002775 transport_overhead_per_packet_ = transport_overhead_per_packet;
2776 UpdateOverheadForEncoder();
michaelt79e05882016-11-08 02:50:09 -08002777}
2778
hbos3fd31fe2017-02-28 05:43:16 -08002779// TODO(solenberg): Make AudioSendStream an OverheadObserver instead.
michaeltbf65be52016-12-15 06:24:49 -08002780void Channel::OnOverheadChanged(size_t overhead_bytes_per_packet) {
hbos3fd31fe2017-02-28 05:43:16 -08002781 rtc::CritScope cs(&overhead_per_packet_lock_);
nisse284542b2017-01-10 08:58:32 -08002782 rtp_overhead_per_packet_ = overhead_bytes_per_packet;
2783 UpdateOverheadForEncoder();
michaeltbf65be52016-12-15 06:24:49 -08002784}
2785
kwiberg55b97fe2016-01-28 05:22:45 -08002786int Channel::GetNetworkStatistics(NetworkStatistics& stats) {
2787 return audio_coding_->GetNetworkStatistics(&stats);
niklase@google.com470e71d2011-07-07 08:21:25 +00002788}
2789
wu@webrtc.org24301a62013-12-13 19:17:43 +00002790void Channel::GetDecodingCallStatistics(AudioDecodingCallStats* stats) const {
2791 audio_coding_->GetDecodingCallStatistics(stats);
2792}
2793
solenberg358057b2015-11-27 10:46:42 -08002794uint32_t Channel::GetDelayEstimate() const {
solenberg08b19df2017-02-15 00:42:31 -08002795 rtc::CritScope lock(&video_sync_lock_);
2796 return audio_coding_->FilteredCurrentDelayMs() + playout_delay_ms_;
deadbeef74375882015-08-13 12:09:10 -07002797}
2798
kwiberg55b97fe2016-01-28 05:22:45 -08002799int Channel::SetMinimumPlayoutDelay(int delayMs) {
2800 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2801 "Channel::SetMinimumPlayoutDelay()");
2802 if ((delayMs < kVoiceEngineMinMinPlayoutDelayMs) ||
2803 (delayMs > kVoiceEngineMaxMinPlayoutDelayMs)) {
2804 _engineStatisticsPtr->SetLastError(
2805 VE_INVALID_ARGUMENT, kTraceError,
2806 "SetMinimumPlayoutDelay() invalid min delay");
2807 return -1;
2808 }
2809 if (audio_coding_->SetMinimumPlayoutDelay(delayMs) != 0) {
2810 _engineStatisticsPtr->SetLastError(
2811 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
2812 "SetMinimumPlayoutDelay() failed to set min playout delay");
2813 return -1;
2814 }
2815 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002816}
2817
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00002818int Channel::GetPlayoutTimestamp(unsigned int& timestamp) {
deadbeef74375882015-08-13 12:09:10 -07002819 uint32_t playout_timestamp_rtp = 0;
2820 {
tommi31fc21f2016-01-21 10:37:37 -08002821 rtc::CritScope lock(&video_sync_lock_);
deadbeef74375882015-08-13 12:09:10 -07002822 playout_timestamp_rtp = playout_timestamp_rtp_;
2823 }
kwiberg55b97fe2016-01-28 05:22:45 -08002824 if (playout_timestamp_rtp == 0) {
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00002825 _engineStatisticsPtr->SetLastError(
skvlad4c0536b2016-07-07 13:06:26 -07002826 VE_CANNOT_RETRIEVE_VALUE, kTraceStateInfo,
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00002827 "GetPlayoutTimestamp() failed to retrieve timestamp");
2828 return -1;
2829 }
deadbeef74375882015-08-13 12:09:10 -07002830 timestamp = playout_timestamp_rtp;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00002831 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002832}
2833
kwiberg55b97fe2016-01-28 05:22:45 -08002834int Channel::GetRtpRtcp(RtpRtcp** rtpRtcpModule,
2835 RtpReceiver** rtp_receiver) const {
2836 *rtpRtcpModule = _rtpRtcpModule.get();
2837 *rtp_receiver = rtp_receiver_.get();
2838 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002839}
2840
andrew@webrtc.orge59a0ac2012-05-08 17:12:40 +00002841// TODO(andrew): refactor Mix functions here and in transmit_mixer.cc to use
2842// a shared helper.
kwiberg55b97fe2016-01-28 05:22:45 -08002843int32_t Channel::MixOrReplaceAudioWithFile(int mixingFrequency) {
kwibergb7f89d62016-02-17 10:04:18 -08002844 std::unique_ptr<int16_t[]> fileBuffer(new int16_t[640]);
kwiberg55b97fe2016-01-28 05:22:45 -08002845 size_t fileSamples(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00002846
kwiberg55b97fe2016-01-28 05:22:45 -08002847 {
2848 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002849
kwiberg5a25d952016-08-17 07:31:12 -07002850 if (!input_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002851 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2852 "Channel::MixOrReplaceAudioWithFile() fileplayer"
2853 " doesnt exist");
2854 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002855 }
2856
kwiberg4ec01d92016-08-22 08:43:54 -07002857 if (input_file_player_->Get10msAudioFromFile(fileBuffer.get(), &fileSamples,
kwiberg5a25d952016-08-17 07:31:12 -07002858 mixingFrequency) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08002859 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2860 "Channel::MixOrReplaceAudioWithFile() file mixing "
2861 "failed");
2862 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002863 }
kwiberg55b97fe2016-01-28 05:22:45 -08002864 if (fileSamples == 0) {
2865 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2866 "Channel::MixOrReplaceAudioWithFile() file is ended");
2867 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002868 }
kwiberg55b97fe2016-01-28 05:22:45 -08002869 }
2870
2871 assert(_audioFrame.samples_per_channel_ == fileSamples);
2872
2873 if (_mixFileWithMicrophone) {
2874 // Currently file stream is always mono.
2875 // TODO(xians): Change the code when FilePlayer supports real stereo.
2876 MixWithSat(_audioFrame.data_, _audioFrame.num_channels_, fileBuffer.get(),
2877 1, fileSamples);
2878 } else {
2879 // Replace ACM audio with file.
2880 // Currently file stream is always mono.
2881 // TODO(xians): Change the code when FilePlayer supports real stereo.
2882 _audioFrame.UpdateFrame(
2883 _channelId, 0xFFFFFFFF, fileBuffer.get(), fileSamples, mixingFrequency,
2884 AudioFrame::kNormalSpeech, AudioFrame::kVadUnknown, 1);
2885 }
2886 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002887}
2888
kwiberg55b97fe2016-01-28 05:22:45 -08002889int32_t Channel::MixAudioWithFile(AudioFrame& audioFrame, int mixingFrequency) {
2890 assert(mixingFrequency <= 48000);
niklase@google.com470e71d2011-07-07 08:21:25 +00002891
kwibergb7f89d62016-02-17 10:04:18 -08002892 std::unique_ptr<int16_t[]> fileBuffer(new int16_t[960]);
kwiberg55b97fe2016-01-28 05:22:45 -08002893 size_t fileSamples(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00002894
kwiberg55b97fe2016-01-28 05:22:45 -08002895 {
2896 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002897
kwiberg5a25d952016-08-17 07:31:12 -07002898 if (!output_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002899 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2900 "Channel::MixAudioWithFile() file mixing failed");
2901 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002902 }
2903
kwiberg55b97fe2016-01-28 05:22:45 -08002904 // We should get the frequency we ask for.
kwiberg4ec01d92016-08-22 08:43:54 -07002905 if (output_file_player_->Get10msAudioFromFile(
2906 fileBuffer.get(), &fileSamples, mixingFrequency) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08002907 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2908 "Channel::MixAudioWithFile() file mixing failed");
2909 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002910 }
kwiberg55b97fe2016-01-28 05:22:45 -08002911 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002912
kwiberg55b97fe2016-01-28 05:22:45 -08002913 if (audioFrame.samples_per_channel_ == fileSamples) {
2914 // Currently file stream is always mono.
2915 // TODO(xians): Change the code when FilePlayer supports real stereo.
2916 MixWithSat(audioFrame.data_, audioFrame.num_channels_, fileBuffer.get(), 1,
2917 fileSamples);
2918 } else {
2919 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2920 "Channel::MixAudioWithFile() samples_per_channel_(%" PRIuS
2921 ") != "
2922 "fileSamples(%" PRIuS ")",
2923 audioFrame.samples_per_channel_, fileSamples);
2924 return -1;
2925 }
2926
2927 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002928}
2929
deadbeef74375882015-08-13 12:09:10 -07002930void Channel::UpdatePlayoutTimestamp(bool rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07002931 jitter_buffer_playout_timestamp_ = audio_coding_->PlayoutTimestamp();
deadbeef74375882015-08-13 12:09:10 -07002932
henrik.lundin96bd5022016-04-06 04:13:56 -07002933 if (!jitter_buffer_playout_timestamp_) {
2934 // This can happen if this channel has not received any RTP packets. In
2935 // this case, NetEq is not capable of computing a playout timestamp.
deadbeef74375882015-08-13 12:09:10 -07002936 return;
2937 }
2938
2939 uint16_t delay_ms = 0;
2940 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08002941 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07002942 "Channel::UpdatePlayoutTimestamp() failed to read playout"
2943 " delay from the ADM");
2944 _engineStatisticsPtr->SetLastError(
2945 VE_CANNOT_RETRIEVE_VALUE, kTraceError,
2946 "UpdatePlayoutTimestamp() failed to retrieve playout delay");
2947 return;
2948 }
2949
henrik.lundin96bd5022016-04-06 04:13:56 -07002950 RTC_DCHECK(jitter_buffer_playout_timestamp_);
2951 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
deadbeef74375882015-08-13 12:09:10 -07002952
2953 // Remove the playout delay.
ossue280cde2016-10-12 11:04:10 -07002954 playout_timestamp -= (delay_ms * (GetRtpTimestampRateHz() / 1000));
deadbeef74375882015-08-13 12:09:10 -07002955
kwiberg55b97fe2016-01-28 05:22:45 -08002956 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07002957 "Channel::UpdatePlayoutTimestamp() => playoutTimestamp = %lu",
henrik.lundin96bd5022016-04-06 04:13:56 -07002958 playout_timestamp);
deadbeef74375882015-08-13 12:09:10 -07002959
2960 {
tommi31fc21f2016-01-21 10:37:37 -08002961 rtc::CritScope lock(&video_sync_lock_);
solenberg81d93f32017-02-14 03:44:57 -08002962 if (!rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07002963 playout_timestamp_rtp_ = playout_timestamp;
deadbeef74375882015-08-13 12:09:10 -07002964 }
2965 playout_delay_ms_ = delay_ms;
2966 }
2967}
2968
kwiberg55b97fe2016-01-28 05:22:45 -08002969void Channel::RegisterReceiveCodecsToRTPModule() {
2970 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2971 "Channel::RegisterReceiveCodecsToRTPModule()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002972
kwiberg55b97fe2016-01-28 05:22:45 -08002973 CodecInst codec;
2974 const uint8_t nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
niklase@google.com470e71d2011-07-07 08:21:25 +00002975
kwiberg55b97fe2016-01-28 05:22:45 -08002976 for (int idx = 0; idx < nSupportedCodecs; idx++) {
2977 // Open up the RTP/RTCP receiver for all supported codecs
2978 if ((audio_coding_->Codec(idx, &codec) == -1) ||
magjed56124bd2016-11-24 09:34:46 -08002979 (rtp_receiver_->RegisterReceivePayload(codec) == -1)) {
kwiberg55b97fe2016-01-28 05:22:45 -08002980 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2981 "Channel::RegisterReceiveCodecsToRTPModule() unable"
2982 " to register %s (%d/%d/%" PRIuS
2983 "/%d) to RTP/RTCP "
2984 "receiver",
2985 codec.plname, codec.pltype, codec.plfreq, codec.channels,
2986 codec.rate);
2987 } else {
2988 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2989 "Channel::RegisterReceiveCodecsToRTPModule() %s "
2990 "(%d/%d/%" PRIuS
2991 "/%d) has been added to the RTP/RTCP "
2992 "receiver",
2993 codec.plname, codec.pltype, codec.plfreq, codec.channels,
2994 codec.rate);
niklase@google.com470e71d2011-07-07 08:21:25 +00002995 }
kwiberg55b97fe2016-01-28 05:22:45 -08002996 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002997}
2998
kwiberg55b97fe2016-01-28 05:22:45 -08002999int Channel::SetSendRtpHeaderExtension(bool enable,
3000 RTPExtensionType type,
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00003001 unsigned char id) {
3002 int error = 0;
3003 _rtpRtcpModule->DeregisterSendRtpHeaderExtension(type);
3004 if (enable) {
3005 error = _rtpRtcpModule->RegisterSendRtpHeaderExtension(type, id);
3006 }
3007 return error;
3008}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00003009
ossue280cde2016-10-12 11:04:10 -07003010int Channel::GetRtpTimestampRateHz() const {
3011 const auto format = audio_coding_->ReceiveFormat();
3012 // Default to the playout frequency if we've not gotten any packets yet.
3013 // TODO(ossu): Zero clockrate can only happen if we've added an external
3014 // decoder for a format we don't support internally. Remove once that way of
3015 // adding decoders is gone!
3016 return (format && format->clockrate_hz != 0)
3017 ? format->clockrate_hz
3018 : audio_coding_->PlayoutFrequency();
wu@webrtc.org94454b72014-06-05 20:34:08 +00003019}
3020
Minyue2013aec2015-05-13 14:14:42 +02003021int64_t Channel::GetRTT(bool allow_associate_channel) const {
pbosda903ea2015-10-02 02:36:56 -07003022 RtcpMode method = _rtpRtcpModule->RTCP();
3023 if (method == RtcpMode::kOff) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003024 return 0;
3025 }
3026 std::vector<RTCPReportBlock> report_blocks;
3027 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
Minyue2013aec2015-05-13 14:14:42 +02003028
3029 int64_t rtt = 0;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003030 if (report_blocks.empty()) {
Minyue2013aec2015-05-13 14:14:42 +02003031 if (allow_associate_channel) {
tommi31fc21f2016-01-21 10:37:37 -08003032 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02003033 Channel* channel = associate_send_channel_.channel();
3034 // Tries to get RTT from an associated channel. This is important for
3035 // receive-only channels.
3036 if (channel) {
3037 // To prevent infinite recursion and deadlock, calling GetRTT of
3038 // associate channel should always use "false" for argument:
3039 // |allow_associate_channel|.
3040 rtt = channel->GetRTT(false);
3041 }
3042 }
3043 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003044 }
3045
3046 uint32_t remoteSSRC = rtp_receiver_->SSRC();
3047 std::vector<RTCPReportBlock>::const_iterator it = report_blocks.begin();
3048 for (; it != report_blocks.end(); ++it) {
3049 if (it->remoteSSRC == remoteSSRC)
3050 break;
3051 }
3052 if (it == report_blocks.end()) {
3053 // We have not received packets with SSRC matching the report blocks.
3054 // To calculate RTT we try with the SSRC of the first report block.
3055 // This is very important for send-only channels where we don't know
3056 // the SSRC of the other end.
3057 remoteSSRC = report_blocks[0].remoteSSRC;
3058 }
Minyue2013aec2015-05-13 14:14:42 +02003059
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003060 int64_t avg_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08003061 int64_t max_rtt = 0;
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003062 int64_t min_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08003063 if (_rtpRtcpModule->RTT(remoteSSRC, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
3064 0) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003065 return 0;
3066 }
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003067 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003068}
3069
pbos@webrtc.orgd900e8b2013-07-03 15:12:26 +00003070} // namespace voe
3071} // namespace webrtc