blob: 3a4a9704981c77287fa385dcd999d25f8780564b [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"
henrikaec6fbd22017-03-31 05:43:36 -070024#include "webrtc/base/task_queue.h"
25#include "webrtc/base/thread_checker.h"
wu@webrtc.org94454b72014-06-05 20:34:08 +000026#include "webrtc/base/timeutils.h"
nisseb8f9a322017-03-27 05:36:15 -070027#include "webrtc/call/rtp_transport_controller_send.h"
Henrik Lundin64dad832015-05-11 12:44:23 +020028#include "webrtc/config.h"
skvladcc91d282016-10-03 18:31:22 -070029#include "webrtc/logging/rtc_event_log/rtc_event_log.h"
kwibergda2bf4e2016-10-24 13:47:09 -070030#include "webrtc/modules/audio_coding/codecs/audio_format_conversion.h"
turaj@webrtc.org6388c3e2013-02-12 21:42:18 +000031#include "webrtc/modules/audio_device/include/audio_device.h"
32#include "webrtc/modules/audio_processing/include/audio_processing.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010033#include "webrtc/modules/include/module_common_types.h"
Stefan Holmerb86d4e42015-12-07 10:26:18 +010034#include "webrtc/modules/pacing/packet_router.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010035#include "webrtc/modules/rtp_rtcp/include/receive_statistics.h"
36#include "webrtc/modules/rtp_rtcp/include/rtp_payload_registry.h"
37#include "webrtc/modules/rtp_rtcp/include/rtp_receiver.h"
nisse657bab22017-02-21 06:28:10 -080038#include "webrtc/modules/rtp_rtcp/source/rtp_packet_received.h"
wu@webrtc.org822fbd82013-08-15 23:38:54 +000039#include "webrtc/modules/rtp_rtcp/source/rtp_receiver_strategy.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010040#include "webrtc/modules/utility/include/process_thread.h"
elad.alon28770482017-03-28 05:03:55 -070041#include "webrtc/system_wrappers/include/field_trial.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010042#include "webrtc/system_wrappers/include/trace.h"
turaj@webrtc.org6388c3e2013-02-12 21:42:18 +000043#include "webrtc/voice_engine/include/voe_rtp_rtcp.h"
44#include "webrtc/voice_engine/output_mixer.h"
45#include "webrtc/voice_engine/statistics.h"
turaj@webrtc.org6388c3e2013-02-12 21:42:18 +000046#include "webrtc/voice_engine/utility.h"
niklase@google.com470e71d2011-07-07 08:21:25 +000047
andrew@webrtc.org50419b02012-11-14 19:07:54 +000048namespace webrtc {
49namespace voe {
niklase@google.com470e71d2011-07-07 08:21:25 +000050
kwibergc8d071e2016-04-06 12:22:38 -070051namespace {
52
Erik Språng737336d2016-07-29 12:59:36 +020053constexpr int64_t kMaxRetransmissionWindowMs = 1000;
54constexpr int64_t kMinRetransmissionWindowMs = 30;
55
kwibergc8d071e2016-04-06 12:22:38 -070056} // namespace
57
solenberg8842c3e2016-03-11 03:06:41 -080058const int kTelephoneEventAttenuationdB = 10;
59
ivoc14d5dbe2016-07-04 07:06:55 -070060class RtcEventLogProxy final : public webrtc::RtcEventLog {
61 public:
62 RtcEventLogProxy() : event_log_(nullptr) {}
63
64 bool StartLogging(const std::string& file_name,
65 int64_t max_size_bytes) override {
66 RTC_NOTREACHED();
67 return false;
68 }
69
70 bool StartLogging(rtc::PlatformFile log_file,
71 int64_t max_size_bytes) override {
72 RTC_NOTREACHED();
73 return false;
74 }
75
76 void StopLogging() override { RTC_NOTREACHED(); }
77
78 void LogVideoReceiveStreamConfig(
79 const webrtc::VideoReceiveStream::Config& config) override {
80 rtc::CritScope lock(&crit_);
81 if (event_log_) {
82 event_log_->LogVideoReceiveStreamConfig(config);
83 }
84 }
85
86 void LogVideoSendStreamConfig(
87 const webrtc::VideoSendStream::Config& config) override {
88 rtc::CritScope lock(&crit_);
89 if (event_log_) {
90 event_log_->LogVideoSendStreamConfig(config);
91 }
92 }
93
ivoce0928d82016-10-10 05:12:51 -070094 void LogAudioReceiveStreamConfig(
95 const webrtc::AudioReceiveStream::Config& config) override {
96 rtc::CritScope lock(&crit_);
97 if (event_log_) {
98 event_log_->LogAudioReceiveStreamConfig(config);
99 }
100 }
101
102 void LogAudioSendStreamConfig(
103 const webrtc::AudioSendStream::Config& config) override {
104 rtc::CritScope lock(&crit_);
105 if (event_log_) {
106 event_log_->LogAudioSendStreamConfig(config);
107 }
108 }
109
ivoc14d5dbe2016-07-04 07:06:55 -0700110 void LogRtpHeader(webrtc::PacketDirection direction,
111 webrtc::MediaType media_type,
112 const uint8_t* header,
113 size_t packet_length) override {
philipel32d00102017-02-27 02:18:46 -0800114 LogRtpHeader(direction, media_type, header, packet_length,
115 PacedPacketInfo::kNotAProbe);
116 }
117
118 void LogRtpHeader(webrtc::PacketDirection direction,
119 webrtc::MediaType media_type,
120 const uint8_t* header,
121 size_t packet_length,
122 int probe_cluster_id) override {
ivoc14d5dbe2016-07-04 07:06:55 -0700123 rtc::CritScope lock(&crit_);
124 if (event_log_) {
philipel32d00102017-02-27 02:18:46 -0800125 event_log_->LogRtpHeader(direction, media_type, header, packet_length,
126 probe_cluster_id);
ivoc14d5dbe2016-07-04 07:06:55 -0700127 }
128 }
129
130 void LogRtcpPacket(webrtc::PacketDirection direction,
131 webrtc::MediaType media_type,
132 const uint8_t* packet,
133 size_t length) override {
134 rtc::CritScope lock(&crit_);
135 if (event_log_) {
136 event_log_->LogRtcpPacket(direction, media_type, packet, length);
137 }
138 }
139
140 void LogAudioPlayout(uint32_t ssrc) override {
141 rtc::CritScope lock(&crit_);
142 if (event_log_) {
143 event_log_->LogAudioPlayout(ssrc);
144 }
145 }
146
terelius424e6cf2017-02-20 05:14:41 -0800147 void LogLossBasedBweUpdate(int32_t bitrate_bps,
ivoc14d5dbe2016-07-04 07:06:55 -0700148 uint8_t fraction_loss,
149 int32_t total_packets) override {
150 rtc::CritScope lock(&crit_);
151 if (event_log_) {
terelius424e6cf2017-02-20 05:14:41 -0800152 event_log_->LogLossBasedBweUpdate(bitrate_bps, fraction_loss,
153 total_packets);
ivoc14d5dbe2016-07-04 07:06:55 -0700154 }
155 }
156
terelius424e6cf2017-02-20 05:14:41 -0800157 void LogDelayBasedBweUpdate(int32_t bitrate_bps,
terelius0baf55d2017-02-17 03:38:28 -0800158 BandwidthUsage detector_state) override {
159 rtc::CritScope lock(&crit_);
160 if (event_log_) {
terelius424e6cf2017-02-20 05:14:41 -0800161 event_log_->LogDelayBasedBweUpdate(bitrate_bps, detector_state);
terelius0baf55d2017-02-17 03:38:28 -0800162 }
163 }
164
minyue4b7c9522017-01-24 04:54:59 -0800165 void LogAudioNetworkAdaptation(
michaeltcde46b72017-04-06 05:59:10 -0700166 const AudioEncoderRuntimeConfig& config) override {
minyue4b7c9522017-01-24 04:54:59 -0800167 rtc::CritScope lock(&crit_);
168 if (event_log_) {
169 event_log_->LogAudioNetworkAdaptation(config);
170 }
171 }
172
philipel32d00102017-02-27 02:18:46 -0800173 void LogProbeClusterCreated(int id,
174 int bitrate_bps,
175 int min_probes,
176 int min_bytes) override {
177 rtc::CritScope lock(&crit_);
178 if (event_log_) {
179 event_log_->LogProbeClusterCreated(id, bitrate_bps, min_probes,
180 min_bytes);
181 }
182 };
183
184 void LogProbeResultSuccess(int id, int bitrate_bps) override {
185 rtc::CritScope lock(&crit_);
186 if (event_log_) {
187 event_log_->LogProbeResultSuccess(id, bitrate_bps);
188 }
189 };
190
191 void LogProbeResultFailure(int id,
192 ProbeFailureReason failure_reason) override {
193 rtc::CritScope lock(&crit_);
194 if (event_log_) {
195 event_log_->LogProbeResultFailure(id, failure_reason);
196 }
197 };
198
ivoc14d5dbe2016-07-04 07:06:55 -0700199 void SetEventLog(RtcEventLog* event_log) {
200 rtc::CritScope lock(&crit_);
201 event_log_ = event_log;
202 }
203
204 private:
205 rtc::CriticalSection crit_;
206 RtcEventLog* event_log_ GUARDED_BY(crit_);
207 RTC_DISALLOW_COPY_AND_ASSIGN(RtcEventLogProxy);
208};
209
michaelt9332b7d2016-11-30 07:51:13 -0800210class RtcpRttStatsProxy final : public RtcpRttStats {
211 public:
212 RtcpRttStatsProxy() : rtcp_rtt_stats_(nullptr) {}
213
214 void OnRttUpdate(int64_t rtt) override {
215 rtc::CritScope lock(&crit_);
216 if (rtcp_rtt_stats_)
217 rtcp_rtt_stats_->OnRttUpdate(rtt);
218 }
219
220 int64_t LastProcessedRtt() const override {
221 rtc::CritScope lock(&crit_);
222 if (!rtcp_rtt_stats_)
223 return 0;
224 return rtcp_rtt_stats_->LastProcessedRtt();
225 }
226
227 void SetRtcpRttStats(RtcpRttStats* rtcp_rtt_stats) {
228 rtc::CritScope lock(&crit_);
229 rtcp_rtt_stats_ = rtcp_rtt_stats;
230 }
231
232 private:
233 rtc::CriticalSection crit_;
234 RtcpRttStats* rtcp_rtt_stats_ GUARDED_BY(crit_);
235 RTC_DISALLOW_COPY_AND_ASSIGN(RtcpRttStatsProxy);
236};
237
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100238class TransportFeedbackProxy : public TransportFeedbackObserver {
239 public:
240 TransportFeedbackProxy() : feedback_observer_(nullptr) {
241 pacer_thread_.DetachFromThread();
242 network_thread_.DetachFromThread();
243 }
244
245 void SetTransportFeedbackObserver(
246 TransportFeedbackObserver* feedback_observer) {
247 RTC_DCHECK(thread_checker_.CalledOnValidThread());
248 rtc::CritScope lock(&crit_);
249 feedback_observer_ = feedback_observer;
250 }
251
252 // Implements TransportFeedbackObserver.
elad.alond12a8e12017-03-23 11:04:48 -0700253 void AddPacket(uint32_t ssrc,
254 uint16_t sequence_number,
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100255 size_t length,
philipel8aadd502017-02-23 02:56:13 -0800256 const PacedPacketInfo& pacing_info) override {
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100257 RTC_DCHECK(pacer_thread_.CalledOnValidThread());
258 rtc::CritScope lock(&crit_);
259 if (feedback_observer_)
elad.alond12a8e12017-03-23 11:04:48 -0700260 feedback_observer_->AddPacket(ssrc, sequence_number, length, pacing_info);
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100261 }
philipel8aadd502017-02-23 02:56:13 -0800262
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100263 void OnTransportFeedback(const rtcp::TransportFeedback& feedback) override {
264 RTC_DCHECK(network_thread_.CalledOnValidThread());
265 rtc::CritScope lock(&crit_);
michaelt9960bb12016-10-18 09:40:34 -0700266 if (feedback_observer_)
267 feedback_observer_->OnTransportFeedback(feedback);
Stefan Holmer60e43462016-09-07 09:58:20 +0200268 }
elad.alonf9490002017-03-06 05:32:21 -0800269 std::vector<PacketFeedback> GetTransportFeedbackVector() const override {
Stefan Holmer60e43462016-09-07 09:58:20 +0200270 RTC_NOTREACHED();
elad.alonf9490002017-03-06 05:32:21 -0800271 return std::vector<PacketFeedback>();
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100272 }
273
274 private:
275 rtc::CriticalSection crit_;
276 rtc::ThreadChecker thread_checker_;
277 rtc::ThreadChecker pacer_thread_;
278 rtc::ThreadChecker network_thread_;
279 TransportFeedbackObserver* feedback_observer_ GUARDED_BY(&crit_);
280};
281
282class TransportSequenceNumberProxy : public TransportSequenceNumberAllocator {
283 public:
284 TransportSequenceNumberProxy() : seq_num_allocator_(nullptr) {
285 pacer_thread_.DetachFromThread();
286 }
287
288 void SetSequenceNumberAllocator(
289 TransportSequenceNumberAllocator* seq_num_allocator) {
290 RTC_DCHECK(thread_checker_.CalledOnValidThread());
291 rtc::CritScope lock(&crit_);
292 seq_num_allocator_ = seq_num_allocator;
293 }
294
295 // Implements TransportSequenceNumberAllocator.
296 uint16_t AllocateSequenceNumber() override {
297 RTC_DCHECK(pacer_thread_.CalledOnValidThread());
298 rtc::CritScope lock(&crit_);
299 if (!seq_num_allocator_)
300 return 0;
301 return seq_num_allocator_->AllocateSequenceNumber();
302 }
303
304 private:
305 rtc::CriticalSection crit_;
306 rtc::ThreadChecker thread_checker_;
307 rtc::ThreadChecker pacer_thread_;
308 TransportSequenceNumberAllocator* seq_num_allocator_ GUARDED_BY(&crit_);
309};
310
311class RtpPacketSenderProxy : public RtpPacketSender {
312 public:
kwiberg55b97fe2016-01-28 05:22:45 -0800313 RtpPacketSenderProxy() : rtp_packet_sender_(nullptr) {}
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100314
315 void SetPacketSender(RtpPacketSender* rtp_packet_sender) {
316 RTC_DCHECK(thread_checker_.CalledOnValidThread());
317 rtc::CritScope lock(&crit_);
318 rtp_packet_sender_ = rtp_packet_sender;
319 }
320
321 // Implements RtpPacketSender.
322 void InsertPacket(Priority priority,
323 uint32_t ssrc,
324 uint16_t sequence_number,
325 int64_t capture_time_ms,
326 size_t bytes,
327 bool retransmission) override {
328 rtc::CritScope lock(&crit_);
329 if (rtp_packet_sender_) {
330 rtp_packet_sender_->InsertPacket(priority, ssrc, sequence_number,
331 capture_time_ms, bytes, retransmission);
332 }
333 }
334
335 private:
336 rtc::ThreadChecker thread_checker_;
337 rtc::CriticalSection crit_;
338 RtpPacketSender* rtp_packet_sender_ GUARDED_BY(&crit_);
339};
340
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000341class VoERtcpObserver : public RtcpBandwidthObserver {
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000342 public:
stefan7de8d642017-02-07 07:14:08 -0800343 explicit VoERtcpObserver(Channel* owner)
344 : owner_(owner), bandwidth_observer_(nullptr) {}
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000345 virtual ~VoERtcpObserver() {}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000346
stefan7de8d642017-02-07 07:14:08 -0800347 void SetBandwidthObserver(RtcpBandwidthObserver* bandwidth_observer) {
348 rtc::CritScope lock(&crit_);
349 bandwidth_observer_ = bandwidth_observer;
350 }
351
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000352 void OnReceivedEstimatedBitrate(uint32_t bitrate) override {
stefan7de8d642017-02-07 07:14:08 -0800353 rtc::CritScope lock(&crit_);
354 if (bandwidth_observer_) {
355 bandwidth_observer_->OnReceivedEstimatedBitrate(bitrate);
356 }
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000357 }
358
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +0000359 void OnReceivedRtcpReceiverReport(const ReportBlockList& report_blocks,
360 int64_t rtt,
361 int64_t now_ms) override {
stefan7de8d642017-02-07 07:14:08 -0800362 {
363 rtc::CritScope lock(&crit_);
364 if (bandwidth_observer_) {
365 bandwidth_observer_->OnReceivedRtcpReceiverReport(report_blocks, rtt,
366 now_ms);
367 }
368 }
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000369 // TODO(mflodman): Do we need to aggregate reports here or can we jut send
370 // what we get? I.e. do we ever get multiple reports bundled into one RTCP
371 // report for VoiceEngine?
372 if (report_blocks.empty())
373 return;
374
375 int fraction_lost_aggregate = 0;
376 int total_number_of_packets = 0;
377
378 // If receiving multiple report blocks, calculate the weighted average based
379 // on the number of packets a report refers to.
380 for (ReportBlockList::const_iterator block_it = report_blocks.begin();
381 block_it != report_blocks.end(); ++block_it) {
382 // Find the previous extended high sequence number for this remote SSRC,
383 // to calculate the number of RTP packets this report refers to. Ignore if
384 // we haven't seen this SSRC before.
385 std::map<uint32_t, uint32_t>::iterator seq_num_it =
386 extended_max_sequence_number_.find(block_it->sourceSSRC);
387 int number_of_packets = 0;
388 if (seq_num_it != extended_max_sequence_number_.end()) {
389 number_of_packets = block_it->extendedHighSeqNum - seq_num_it->second;
390 }
391 fraction_lost_aggregate += number_of_packets * block_it->fractionLost;
392 total_number_of_packets += number_of_packets;
393
394 extended_max_sequence_number_[block_it->sourceSSRC] =
395 block_it->extendedHighSeqNum;
396 }
397 int weighted_fraction_lost = 0;
398 if (total_number_of_packets > 0) {
kwiberg55b97fe2016-01-28 05:22:45 -0800399 weighted_fraction_lost =
400 (fraction_lost_aggregate + total_number_of_packets / 2) /
401 total_number_of_packets;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000402 }
elad.alond12a8e12017-03-23 11:04:48 -0700403 owner_->OnUplinkPacketLossRate(weighted_fraction_lost / 255.0f);
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000404 }
405
406 private:
407 Channel* owner_;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000408 // Maps remote side ssrc to extended highest sequence number received.
409 std::map<uint32_t, uint32_t> extended_max_sequence_number_;
stefan7de8d642017-02-07 07:14:08 -0800410 rtc::CriticalSection crit_;
411 RtcpBandwidthObserver* bandwidth_observer_ GUARDED_BY(crit_);
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000412};
413
henrikaec6fbd22017-03-31 05:43:36 -0700414class Channel::ProcessAndEncodeAudioTask : public rtc::QueuedTask {
415 public:
416 ProcessAndEncodeAudioTask(std::unique_ptr<AudioFrame> audio_frame,
417 Channel* channel)
418 : audio_frame_(std::move(audio_frame)), channel_(channel) {
419 RTC_DCHECK(channel_);
420 }
421
422 private:
423 bool Run() override {
424 RTC_DCHECK_RUN_ON(channel_->encoder_queue_);
425 channel_->ProcessAndEncodeAudioOnTaskQueue(audio_frame_.get());
426 return true;
427 }
428
429 std::unique_ptr<AudioFrame> audio_frame_;
430 Channel* const channel_;
431};
432
kwiberg55b97fe2016-01-28 05:22:45 -0800433int32_t Channel::SendData(FrameType frameType,
434 uint8_t payloadType,
435 uint32_t timeStamp,
436 const uint8_t* payloadData,
437 size_t payloadSize,
438 const RTPFragmentationHeader* fragmentation) {
henrikaec6fbd22017-03-31 05:43:36 -0700439 RTC_DCHECK_RUN_ON(encoder_queue_);
kwiberg55b97fe2016-01-28 05:22:45 -0800440 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
441 "Channel::SendData(frameType=%u, payloadType=%u, timeStamp=%u,"
442 " payloadSize=%" PRIuS ", fragmentation=0x%x)",
443 frameType, payloadType, timeStamp, payloadSize, fragmentation);
niklase@google.com470e71d2011-07-07 08:21:25 +0000444
kwiberg55b97fe2016-01-28 05:22:45 -0800445 if (_includeAudioLevelIndication) {
446 // Store current audio level in the RTP/RTCP module.
447 // The level will be used in combination with voice-activity state
448 // (frameType) to add an RTP header extension
henrik.lundin50499422016-11-29 04:26:24 -0800449 _rtpRtcpModule->SetAudioLevel(rms_level_.Average());
kwiberg55b97fe2016-01-28 05:22:45 -0800450 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000451
kwiberg55b97fe2016-01-28 05:22:45 -0800452 // Push data from ACM to RTP/RTCP-module to deliver audio frame for
453 // packetization.
454 // This call will trigger Transport::SendPacket() from the RTP/RTCP module.
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700455 if (!_rtpRtcpModule->SendOutgoingData(
kwiberg55b97fe2016-01-28 05:22:45 -0800456 (FrameType&)frameType, payloadType, timeStamp,
457 // Leaving the time when this frame was
458 // received from the capture device as
459 // undefined for voice for now.
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700460 -1, payloadData, payloadSize, fragmentation, nullptr, nullptr)) {
kwiberg55b97fe2016-01-28 05:22:45 -0800461 _engineStatisticsPtr->SetLastError(
462 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
463 "Channel::SendData() failed to send data to RTP/RTCP module");
464 return -1;
465 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000466
kwiberg55b97fe2016-01-28 05:22:45 -0800467 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000468}
469
stefan1d8a5062015-10-02 03:39:33 -0700470bool Channel::SendRtp(const uint8_t* data,
471 size_t len,
472 const PacketOptions& options) {
kwiberg55b97fe2016-01-28 05:22:45 -0800473 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
474 "Channel::SendPacket(channel=%d, len=%" PRIuS ")", len);
niklase@google.com470e71d2011-07-07 08:21:25 +0000475
kwiberg55b97fe2016-01-28 05:22:45 -0800476 rtc::CritScope cs(&_callbackCritSect);
wu@webrtc.orgfb648da2013-10-18 21:10:51 +0000477
kwiberg55b97fe2016-01-28 05:22:45 -0800478 if (_transportPtr == NULL) {
479 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
480 "Channel::SendPacket() failed to send RTP packet due to"
481 " invalid transport object");
482 return false;
483 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000484
kwiberg55b97fe2016-01-28 05:22:45 -0800485 uint8_t* bufferToSendPtr = (uint8_t*)data;
486 size_t bufferLength = len;
niklase@google.com470e71d2011-07-07 08:21:25 +0000487
kwiberg55b97fe2016-01-28 05:22:45 -0800488 if (!_transportPtr->SendRtp(bufferToSendPtr, bufferLength, options)) {
489 std::string transport_name =
490 _externalTransport ? "external transport" : "WebRtc sockets";
491 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
492 "Channel::SendPacket() RTP transmission using %s failed",
493 transport_name.c_str());
494 return false;
495 }
496 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000497}
498
kwiberg55b97fe2016-01-28 05:22:45 -0800499bool Channel::SendRtcp(const uint8_t* data, size_t len) {
500 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
501 "Channel::SendRtcp(len=%" PRIuS ")", len);
niklase@google.com470e71d2011-07-07 08:21:25 +0000502
kwiberg55b97fe2016-01-28 05:22:45 -0800503 rtc::CritScope cs(&_callbackCritSect);
504 if (_transportPtr == NULL) {
505 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
506 "Channel::SendRtcp() failed to send RTCP packet"
507 " due to invalid transport object");
508 return false;
509 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000510
kwiberg55b97fe2016-01-28 05:22:45 -0800511 uint8_t* bufferToSendPtr = (uint8_t*)data;
512 size_t bufferLength = len;
niklase@google.com470e71d2011-07-07 08:21:25 +0000513
kwiberg55b97fe2016-01-28 05:22:45 -0800514 int n = _transportPtr->SendRtcp(bufferToSendPtr, bufferLength);
515 if (n < 0) {
516 std::string transport_name =
517 _externalTransport ? "external transport" : "WebRtc sockets";
518 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
519 "Channel::SendRtcp() transmission using %s failed",
520 transport_name.c_str());
521 return false;
522 }
523 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000524}
525
kwiberg55b97fe2016-01-28 05:22:45 -0800526void Channel::OnIncomingSSRCChanged(uint32_t ssrc) {
527 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
528 "Channel::OnIncomingSSRCChanged(SSRC=%d)", ssrc);
niklase@google.com470e71d2011-07-07 08:21:25 +0000529
kwiberg55b97fe2016-01-28 05:22:45 -0800530 // Update ssrc so that NTP for AV sync can be updated.
531 _rtpRtcpModule->SetRemoteSSRC(ssrc);
niklase@google.com470e71d2011-07-07 08:21:25 +0000532}
533
Peter Boströmac547a62015-09-17 23:03:57 +0200534void Channel::OnIncomingCSRCChanged(uint32_t CSRC, bool added) {
535 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
536 "Channel::OnIncomingCSRCChanged(CSRC=%d, added=%d)", CSRC,
537 added);
niklase@google.com470e71d2011-07-07 08:21:25 +0000538}
539
Peter Boströmac547a62015-09-17 23:03:57 +0200540int32_t Channel::OnInitializeDecoder(
pbos@webrtc.org92135212013-05-14 08:31:39 +0000541 int8_t payloadType,
leozwang@webrtc.org813e4b02012-03-01 18:34:25 +0000542 const char payloadName[RTP_PAYLOAD_NAME_SIZE],
pbos@webrtc.org92135212013-05-14 08:31:39 +0000543 int frequency,
Peter Kasting69558702016-01-12 16:26:35 -0800544 size_t channels,
Peter Boströmac547a62015-09-17 23:03:57 +0200545 uint32_t rate) {
kwiberg55b97fe2016-01-28 05:22:45 -0800546 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
547 "Channel::OnInitializeDecoder(payloadType=%d, "
548 "payloadName=%s, frequency=%u, channels=%" PRIuS ", rate=%u)",
549 payloadType, payloadName, frequency, channels, rate);
niklase@google.com470e71d2011-07-07 08:21:25 +0000550
kwiberg55b97fe2016-01-28 05:22:45 -0800551 CodecInst receiveCodec = {0};
552 CodecInst dummyCodec = {0};
niklase@google.com470e71d2011-07-07 08:21:25 +0000553
kwiberg55b97fe2016-01-28 05:22:45 -0800554 receiveCodec.pltype = payloadType;
555 receiveCodec.plfreq = frequency;
556 receiveCodec.channels = channels;
557 receiveCodec.rate = rate;
558 strncpy(receiveCodec.plname, payloadName, RTP_PAYLOAD_NAME_SIZE - 1);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +0000559
kwiberg55b97fe2016-01-28 05:22:45 -0800560 audio_coding_->Codec(payloadName, &dummyCodec, frequency, channels);
561 receiveCodec.pacsize = dummyCodec.pacsize;
niklase@google.com470e71d2011-07-07 08:21:25 +0000562
kwiberg55b97fe2016-01-28 05:22:45 -0800563 // Register the new codec to the ACM
kwibergda2bf4e2016-10-24 13:47:09 -0700564 if (!audio_coding_->RegisterReceiveCodec(receiveCodec.pltype,
565 CodecInstToSdp(receiveCodec))) {
kwiberg55b97fe2016-01-28 05:22:45 -0800566 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
567 "Channel::OnInitializeDecoder() invalid codec ("
568 "pt=%d, name=%s) received - 1",
569 payloadType, payloadName);
570 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR);
571 return -1;
572 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000573
kwiberg55b97fe2016-01-28 05:22:45 -0800574 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000575}
576
kwiberg55b97fe2016-01-28 05:22:45 -0800577int32_t Channel::OnReceivedPayloadData(const uint8_t* payloadData,
578 size_t payloadSize,
579 const WebRtcRTPHeader* rtpHeader) {
580 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
581 "Channel::OnReceivedPayloadData(payloadSize=%" PRIuS
582 ","
583 " payloadType=%u, audioChannel=%" PRIuS ")",
584 payloadSize, rtpHeader->header.payloadType,
585 rtpHeader->type.Audio.channel);
niklase@google.com470e71d2011-07-07 08:21:25 +0000586
kwiberg55b97fe2016-01-28 05:22:45 -0800587 if (!channel_state_.Get().playing) {
588 // Avoid inserting into NetEQ when we are not playing. Count the
589 // packet as discarded.
590 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
591 "received packet is discarded since playing is not"
592 " activated");
niklase@google.com470e71d2011-07-07 08:21:25 +0000593 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800594 }
595
596 // Push the incoming payload (parsed and ready for decoding) into the ACM
597 if (audio_coding_->IncomingPacket(payloadData, payloadSize, *rtpHeader) !=
598 0) {
599 _engineStatisticsPtr->SetLastError(
600 VE_AUDIO_CODING_MODULE_ERROR, kTraceWarning,
601 "Channel::OnReceivedPayloadData() unable to push data to the ACM");
602 return -1;
603 }
604
kwiberg55b97fe2016-01-28 05:22:45 -0800605 int64_t round_trip_time = 0;
606 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), &round_trip_time, NULL, NULL,
607 NULL);
608
609 std::vector<uint16_t> nack_list = audio_coding_->GetNackList(round_trip_time);
610 if (!nack_list.empty()) {
611 // Can't use nack_list.data() since it's not supported by all
612 // compilers.
613 ResendPackets(&(nack_list[0]), static_cast<int>(nack_list.size()));
614 }
615 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000616}
617
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000618bool Channel::OnRecoveredPacket(const uint8_t* rtp_packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000619 size_t rtp_packet_length) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000620 RTPHeader header;
621 if (!rtp_header_parser_->Parse(rtp_packet, rtp_packet_length, &header)) {
622 WEBRTC_TRACE(kTraceDebug, webrtc::kTraceVoice, _channelId,
623 "IncomingPacket invalid RTP header");
624 return false;
625 }
626 header.payload_type_frequency =
627 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
628 if (header.payload_type_frequency < 0)
629 return false;
630 return ReceivePacket(rtp_packet, rtp_packet_length, header, false);
631}
632
henrik.lundin42dda502016-05-18 05:36:01 -0700633MixerParticipant::AudioFrameInfo Channel::GetAudioFrameWithMuted(
634 int32_t id,
635 AudioFrame* audioFrame) {
ivoc14d5dbe2016-07-04 07:06:55 -0700636 unsigned int ssrc;
nisse7d59f6b2017-02-21 03:40:24 -0800637 RTC_CHECK_EQ(GetRemoteSSRC(ssrc), 0);
ivoc14d5dbe2016-07-04 07:06:55 -0700638 event_log_proxy_->LogAudioPlayout(ssrc);
kwiberg55b97fe2016-01-28 05:22:45 -0800639 // Get 10ms raw PCM data from the ACM (mixer limits output frequency)
henrik.lundind4ccb002016-05-17 12:21:55 -0700640 bool muted;
641 if (audio_coding_->PlayoutData10Ms(audioFrame->sample_rate_hz_, audioFrame,
642 &muted) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -0800643 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
644 "Channel::GetAudioFrame() PlayoutData10Ms() failed!");
645 // In all likelihood, the audio in this frame is garbage. We return an
646 // error so that the audio mixer module doesn't add it to the mix. As
647 // a result, it won't be played out and the actions skipped here are
648 // irrelevant.
henrik.lundin42dda502016-05-18 05:36:01 -0700649 return MixerParticipant::AudioFrameInfo::kError;
kwiberg55b97fe2016-01-28 05:22:45 -0800650 }
henrik.lundina89ab962016-05-18 08:52:45 -0700651
652 if (muted) {
653 // TODO(henrik.lundin): We should be able to do better than this. But we
654 // will have to go through all the cases below where the audio samples may
655 // be used, and handle the muted case in some way.
aleloi6321b492016-12-05 01:46:09 -0800656 AudioFrameOperations::Mute(audioFrame);
henrik.lundina89ab962016-05-18 08:52:45 -0700657 }
kwiberg55b97fe2016-01-28 05:22:45 -0800658
kwiberg55b97fe2016-01-28 05:22:45 -0800659 // Convert module ID to internal VoE channel ID
660 audioFrame->id_ = VoEChannelId(audioFrame->id_);
661 // Store speech type for dead-or-alive detection
662 _outputSpeechType = audioFrame->speech_type_;
663
664 ChannelState::State state = channel_state_.Get();
665
kwiberg55b97fe2016-01-28 05:22:45 -0800666 {
667 // Pass the audio buffers to an optional sink callback, before applying
668 // scaling/panning, as that applies to the mix operation.
669 // External recipients of the audio (e.g. via AudioTrack), will do their
670 // own mixing/dynamic processing.
671 rtc::CritScope cs(&_callbackCritSect);
672 if (audio_sink_) {
673 AudioSinkInterface::Data data(
674 &audioFrame->data_[0], audioFrame->samples_per_channel_,
675 audioFrame->sample_rate_hz_, audioFrame->num_channels_,
676 audioFrame->timestamp_);
677 audio_sink_->OnData(data);
678 }
679 }
680
681 float output_gain = 1.0f;
kwiberg55b97fe2016-01-28 05:22:45 -0800682 {
683 rtc::CritScope cs(&volume_settings_critsect_);
684 output_gain = _outputGain;
kwiberg55b97fe2016-01-28 05:22:45 -0800685 }
686
687 // Output volume scaling
688 if (output_gain < 0.99f || output_gain > 1.01f) {
solenberg8d73f8c2017-03-08 01:52:20 -0800689 // TODO(solenberg): Combine with mute state - this can cause clicks!
oprypin67fdb802017-03-09 06:25:06 -0800690 AudioFrameOperations::ScaleWithSat(output_gain, audioFrame);
kwiberg55b97fe2016-01-28 05:22:45 -0800691 }
692
kwiberg55b97fe2016-01-28 05:22:45 -0800693 // Mix decoded PCM output with file if file mixing is enabled
694 if (state.output_file_playing) {
695 MixAudioWithFile(*audioFrame, audioFrame->sample_rate_hz_);
henrik.lundina89ab962016-05-18 08:52:45 -0700696 muted = false; // We may have added non-zero samples.
kwiberg55b97fe2016-01-28 05:22:45 -0800697 }
698
kwiberg55b97fe2016-01-28 05:22:45 -0800699 // Record playout if enabled
700 {
701 rtc::CritScope cs(&_fileCritSect);
702
kwiberg5a25d952016-08-17 07:31:12 -0700703 if (_outputFileRecording && output_file_recorder_) {
704 output_file_recorder_->RecordAudioToFile(*audioFrame);
kwiberg55b97fe2016-01-28 05:22:45 -0800705 }
706 }
707
708 // Measure audio level (0-9)
henrik.lundina89ab962016-05-18 08:52:45 -0700709 // TODO(henrik.lundin) Use the |muted| information here too.
kwiberg55b97fe2016-01-28 05:22:45 -0800710 _outputAudioLevel.ComputeLevel(*audioFrame);
711
712 if (capture_start_rtp_time_stamp_ < 0 && audioFrame->timestamp_ != 0) {
713 // The first frame with a valid rtp timestamp.
714 capture_start_rtp_time_stamp_ = audioFrame->timestamp_;
715 }
716
717 if (capture_start_rtp_time_stamp_ >= 0) {
718 // audioFrame.timestamp_ should be valid from now on.
719
720 // Compute elapsed time.
721 int64_t unwrap_timestamp =
722 rtp_ts_wraparound_handler_->Unwrap(audioFrame->timestamp_);
723 audioFrame->elapsed_time_ms_ =
724 (unwrap_timestamp - capture_start_rtp_time_stamp_) /
ossue280cde2016-10-12 11:04:10 -0700725 (GetRtpTimestampRateHz() / 1000);
kwiberg55b97fe2016-01-28 05:22:45 -0800726
niklase@google.com470e71d2011-07-07 08:21:25 +0000727 {
kwiberg55b97fe2016-01-28 05:22:45 -0800728 rtc::CritScope lock(&ts_stats_lock_);
729 // Compute ntp time.
730 audioFrame->ntp_time_ms_ =
731 ntp_estimator_.Estimate(audioFrame->timestamp_);
732 // |ntp_time_ms_| won't be valid until at least 2 RTCP SRs are received.
733 if (audioFrame->ntp_time_ms_ > 0) {
734 // Compute |capture_start_ntp_time_ms_| so that
735 // |capture_start_ntp_time_ms_| + |elapsed_time_ms_| == |ntp_time_ms_|
736 capture_start_ntp_time_ms_ =
737 audioFrame->ntp_time_ms_ - audioFrame->elapsed_time_ms_;
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000738 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000739 }
kwiberg55b97fe2016-01-28 05:22:45 -0800740 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000741
henrik.lundin42dda502016-05-18 05:36:01 -0700742 return muted ? MixerParticipant::AudioFrameInfo::kMuted
743 : MixerParticipant::AudioFrameInfo::kNormal;
niklase@google.com470e71d2011-07-07 08:21:25 +0000744}
745
aleloi6c278492016-10-20 14:24:39 -0700746AudioMixer::Source::AudioFrameInfo Channel::GetAudioFrameWithInfo(
747 int sample_rate_hz,
748 AudioFrame* audio_frame) {
749 audio_frame->sample_rate_hz_ = sample_rate_hz;
aleloiaed581a2016-10-20 06:32:39 -0700750
aleloi6c278492016-10-20 14:24:39 -0700751 const auto frame_info = GetAudioFrameWithMuted(-1, audio_frame);
aleloiaed581a2016-10-20 06:32:39 -0700752
753 using FrameInfo = AudioMixer::Source::AudioFrameInfo;
754 FrameInfo new_audio_frame_info = FrameInfo::kError;
755 switch (frame_info) {
756 case MixerParticipant::AudioFrameInfo::kNormal:
757 new_audio_frame_info = FrameInfo::kNormal;
758 break;
759 case MixerParticipant::AudioFrameInfo::kMuted:
760 new_audio_frame_info = FrameInfo::kMuted;
761 break;
762 case MixerParticipant::AudioFrameInfo::kError:
763 new_audio_frame_info = FrameInfo::kError;
764 break;
765 }
aleloi6c278492016-10-20 14:24:39 -0700766 return new_audio_frame_info;
aleloiaed581a2016-10-20 06:32:39 -0700767}
768
kwiberg55b97fe2016-01-28 05:22:45 -0800769int32_t Channel::NeededFrequency(int32_t id) const {
770 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
771 "Channel::NeededFrequency(id=%d)", id);
niklase@google.com470e71d2011-07-07 08:21:25 +0000772
kwiberg55b97fe2016-01-28 05:22:45 -0800773 int highestNeeded = 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000774
kwiberg55b97fe2016-01-28 05:22:45 -0800775 // Determine highest needed receive frequency
776 int32_t receiveFrequency = audio_coding_->ReceiveFrequency();
niklase@google.com470e71d2011-07-07 08:21:25 +0000777
kwiberg55b97fe2016-01-28 05:22:45 -0800778 // Return the bigger of playout and receive frequency in the ACM.
779 if (audio_coding_->PlayoutFrequency() > receiveFrequency) {
780 highestNeeded = audio_coding_->PlayoutFrequency();
781 } else {
782 highestNeeded = receiveFrequency;
783 }
784
785 // Special case, if we're playing a file on the playout side
786 // we take that frequency into consideration as well
787 // This is not needed on sending side, since the codec will
788 // limit the spectrum anyway.
789 if (channel_state_.Get().output_file_playing) {
790 rtc::CritScope cs(&_fileCritSect);
kwiberg5a25d952016-08-17 07:31:12 -0700791 if (output_file_player_) {
792 if (output_file_player_->Frequency() > highestNeeded) {
793 highestNeeded = output_file_player_->Frequency();
kwiberg55b97fe2016-01-28 05:22:45 -0800794 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000795 }
kwiberg55b97fe2016-01-28 05:22:45 -0800796 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000797
kwiberg55b97fe2016-01-28 05:22:45 -0800798 return (highestNeeded);
niklase@google.com470e71d2011-07-07 08:21:25 +0000799}
800
henrikaec6fbd22017-03-31 05:43:36 -0700801int32_t Channel::CreateChannel(Channel*& channel,
802 int32_t channelId,
803 uint32_t instanceId,
804 const VoEBase::ChannelConfig& config) {
kwiberg55b97fe2016-01-28 05:22:45 -0800805 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(instanceId, channelId),
806 "Channel::CreateChannel(channelId=%d, instanceId=%d)", channelId,
807 instanceId);
niklase@google.com470e71d2011-07-07 08:21:25 +0000808
solenberg88499ec2016-09-07 07:34:41 -0700809 channel = new Channel(channelId, instanceId, config);
kwiberg55b97fe2016-01-28 05:22:45 -0800810 if (channel == NULL) {
811 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(instanceId, channelId),
812 "Channel::CreateChannel() unable to allocate memory for"
813 " channel");
814 return -1;
815 }
816 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000817}
818
kwiberg55b97fe2016-01-28 05:22:45 -0800819void Channel::PlayNotification(int32_t id, uint32_t durationMs) {
820 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
821 "Channel::PlayNotification(id=%d, durationMs=%d)", id,
822 durationMs);
niklase@google.com470e71d2011-07-07 08:21:25 +0000823
kwiberg55b97fe2016-01-28 05:22:45 -0800824 // Not implement yet
niklase@google.com470e71d2011-07-07 08:21:25 +0000825}
826
kwiberg55b97fe2016-01-28 05:22:45 -0800827void Channel::RecordNotification(int32_t id, uint32_t durationMs) {
828 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
829 "Channel::RecordNotification(id=%d, durationMs=%d)", id,
830 durationMs);
niklase@google.com470e71d2011-07-07 08:21:25 +0000831
kwiberg55b97fe2016-01-28 05:22:45 -0800832 // Not implement yet
niklase@google.com470e71d2011-07-07 08:21:25 +0000833}
834
kwiberg55b97fe2016-01-28 05:22:45 -0800835void Channel::PlayFileEnded(int32_t id) {
836 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
837 "Channel::PlayFileEnded(id=%d)", id);
niklase@google.com470e71d2011-07-07 08:21:25 +0000838
kwiberg55b97fe2016-01-28 05:22:45 -0800839 if (id == _inputFilePlayerId) {
840 channel_state_.SetInputFilePlaying(false);
841 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
842 "Channel::PlayFileEnded() => input file player module is"
niklase@google.com470e71d2011-07-07 08:21:25 +0000843 " shutdown");
kwiberg55b97fe2016-01-28 05:22:45 -0800844 } else if (id == _outputFilePlayerId) {
845 channel_state_.SetOutputFilePlaying(false);
846 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
847 "Channel::PlayFileEnded() => output file player module is"
848 " shutdown");
849 }
850}
851
852void Channel::RecordFileEnded(int32_t id) {
853 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
854 "Channel::RecordFileEnded(id=%d)", id);
855
856 assert(id == _outputFileRecorderId);
857
858 rtc::CritScope cs(&_fileCritSect);
859
860 _outputFileRecording = false;
861 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
862 "Channel::RecordFileEnded() => output file recorder module is"
863 " shutdown");
niklase@google.com470e71d2011-07-07 08:21:25 +0000864}
865
pbos@webrtc.org92135212013-05-14 08:31:39 +0000866Channel::Channel(int32_t channelId,
minyue@webrtc.orge509f942013-09-12 17:03:00 +0000867 uint32_t instanceId,
solenberg88499ec2016-09-07 07:34:41 -0700868 const VoEBase::ChannelConfig& config)
tommi31fc21f2016-01-21 10:37:37 -0800869 : _instanceId(instanceId),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100870 _channelId(channelId),
ivoc14d5dbe2016-07-04 07:06:55 -0700871 event_log_proxy_(new RtcEventLogProxy()),
michaelt9332b7d2016-11-30 07:51:13 -0800872 rtcp_rtt_stats_proxy_(new RtcpRttStatsProxy()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100873 rtp_header_parser_(RtpHeaderParser::Create()),
magjedf3feeff2016-11-25 06:40:25 -0800874 rtp_payload_registry_(new RTPPayloadRegistry()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100875 rtp_receive_statistics_(
876 ReceiveStatistics::Create(Clock::GetRealTimeClock())),
877 rtp_receiver_(
878 RtpReceiver::CreateAudioReceiver(Clock::GetRealTimeClock(),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100879 this,
880 this,
881 rtp_payload_registry_.get())),
danilchap799a9d02016-09-22 03:36:27 -0700882 telephone_event_handler_(rtp_receiver_->GetTelephoneEventHandler()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100883 _outputAudioLevel(),
884 _externalTransport(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100885 // Avoid conflict with other channels by adding 1024 - 1026,
886 // won't use as much as 1024 channels.
887 _inputFilePlayerId(VoEModuleId(instanceId, channelId) + 1024),
888 _outputFilePlayerId(VoEModuleId(instanceId, channelId) + 1025),
889 _outputFileRecorderId(VoEModuleId(instanceId, channelId) + 1026),
890 _outputFileRecording(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100891 _timeStamp(0), // This is just an offset, RTP module will add it's own
892 // random offset
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100893 ntp_estimator_(Clock::GetRealTimeClock()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100894 playout_timestamp_rtp_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100895 playout_delay_ms_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100896 send_sequence_number_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100897 rtp_ts_wraparound_handler_(new rtc::TimestampWrapAroundHandler()),
898 capture_start_rtp_time_stamp_(-1),
899 capture_start_ntp_time_ms_(-1),
900 _engineStatisticsPtr(NULL),
901 _outputMixerPtr(NULL),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100902 _moduleProcessThreadPtr(NULL),
903 _audioDeviceModulePtr(NULL),
904 _voiceEngineObserverPtr(NULL),
905 _callbackCritSectPtr(NULL),
906 _transportPtr(NULL),
solenberg1c2af8e2016-03-24 10:36:00 -0700907 input_mute_(false),
908 previous_frame_muted_(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100909 _outputGain(1.0f),
solenberg8d73f8c2017-03-08 01:52:20 -0800910 _mixFileWithMicrophone(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100911 _includeAudioLevelIndication(false),
nisse284542b2017-01-10 08:58:32 -0800912 transport_overhead_per_packet_(0),
913 rtp_overhead_per_packet_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100914 _outputSpeechType(AudioFrame::kNormalSpeech),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100915 restored_packet_in_use_(false),
916 rtcp_observer_(new VoERtcpObserver(this)),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100917 associate_send_channel_(ChannelOwner(nullptr)),
solenberg88499ec2016-09-07 07:34:41 -0700918 pacing_enabled_(config.enable_voice_pacing),
stefanbba9dec2016-02-01 04:39:55 -0800919 feedback_observer_proxy_(new TransportFeedbackProxy()),
920 seq_num_allocator_proxy_(new TransportSequenceNumberProxy()),
ossu29b1a8d2016-06-13 07:34:51 -0700921 rtp_packet_sender_proxy_(new RtpPacketSenderProxy()),
Erik Språng737336d2016-07-29 12:59:36 +0200922 retransmission_rate_limiter_(new RateLimiter(Clock::GetRealTimeClock(),
923 kMaxRetransmissionWindowMs)),
elad.alond12a8e12017-03-23 11:04:48 -0700924 decoder_factory_(config.acm_config.decoder_factory),
elad.alon28770482017-03-28 05:03:55 -0700925 use_twcc_plr_for_ana_(
926 webrtc::field_trial::FindFullName("UseTwccPlrForAna") == "Enabled") {
kwiberg55b97fe2016-01-28 05:22:45 -0800927 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
928 "Channel::Channel() - ctor");
solenberg88499ec2016-09-07 07:34:41 -0700929 AudioCodingModule::Config acm_config(config.acm_config);
kwiberg55b97fe2016-01-28 05:22:45 -0800930 acm_config.id = VoEModuleId(instanceId, channelId);
henrik.lundina89ab962016-05-18 08:52:45 -0700931 acm_config.neteq_config.enable_muted_state = true;
kwiberg55b97fe2016-01-28 05:22:45 -0800932 audio_coding_.reset(AudioCodingModule::Create(acm_config));
Henrik Lundin64dad832015-05-11 12:44:23 +0200933
kwiberg55b97fe2016-01-28 05:22:45 -0800934 _outputAudioLevel.Clear();
niklase@google.com470e71d2011-07-07 08:21:25 +0000935
kwiberg55b97fe2016-01-28 05:22:45 -0800936 RtpRtcp::Configuration configuration;
937 configuration.audio = true;
938 configuration.outgoing_transport = this;
michaeltbf65be52016-12-15 06:24:49 -0800939 configuration.overhead_observer = this;
kwiberg55b97fe2016-01-28 05:22:45 -0800940 configuration.receive_statistics = rtp_receive_statistics_.get();
941 configuration.bandwidth_callback = rtcp_observer_.get();
stefanbba9dec2016-02-01 04:39:55 -0800942 if (pacing_enabled_) {
943 configuration.paced_sender = rtp_packet_sender_proxy_.get();
944 configuration.transport_sequence_number_allocator =
945 seq_num_allocator_proxy_.get();
946 configuration.transport_feedback_callback = feedback_observer_proxy_.get();
947 }
ivoc14d5dbe2016-07-04 07:06:55 -0700948 configuration.event_log = &(*event_log_proxy_);
michaelt9332b7d2016-11-30 07:51:13 -0800949 configuration.rtt_stats = &(*rtcp_rtt_stats_proxy_);
Erik Språng737336d2016-07-29 12:59:36 +0200950 configuration.retransmission_rate_limiter =
951 retransmission_rate_limiter_.get();
pwestin@webrtc.org2853dde2012-05-11 11:08:54 +0000952
kwiberg55b97fe2016-01-28 05:22:45 -0800953 _rtpRtcpModule.reset(RtpRtcp::CreateRtpRtcp(configuration));
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100954 _rtpRtcpModule->SetSendingMediaStatus(false);
niklase@google.com470e71d2011-07-07 08:21:25 +0000955}
956
kwiberg55b97fe2016-01-28 05:22:45 -0800957Channel::~Channel() {
tommi0a2391f2017-03-21 02:31:51 -0700958 RTC_DCHECK(!channel_state_.Get().sending);
959 RTC_DCHECK(!channel_state_.Get().playing);
niklase@google.com470e71d2011-07-07 08:21:25 +0000960}
961
kwiberg55b97fe2016-01-28 05:22:45 -0800962int32_t Channel::Init() {
tommi0a2391f2017-03-21 02:31:51 -0700963 RTC_DCHECK(construction_thread_.CalledOnValidThread());
kwiberg55b97fe2016-01-28 05:22:45 -0800964 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
965 "Channel::Init()");
niklase@google.com470e71d2011-07-07 08:21:25 +0000966
kwiberg55b97fe2016-01-28 05:22:45 -0800967 channel_state_.Reset();
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +0000968
kwiberg55b97fe2016-01-28 05:22:45 -0800969 // --- Initial sanity
niklase@google.com470e71d2011-07-07 08:21:25 +0000970
kwiberg55b97fe2016-01-28 05:22:45 -0800971 if ((_engineStatisticsPtr == NULL) || (_moduleProcessThreadPtr == NULL)) {
972 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
973 "Channel::Init() must call SetEngineInformation() first");
974 return -1;
975 }
976
977 // --- Add modules to process thread (for periodic schedulation)
978
tommidea489f2017-03-03 03:20:24 -0800979 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get(), RTC_FROM_HERE);
kwiberg55b97fe2016-01-28 05:22:45 -0800980
981 // --- ACM initialization
982
983 if (audio_coding_->InitializeReceiver() == -1) {
984 _engineStatisticsPtr->SetLastError(
985 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
986 "Channel::Init() unable to initialize the ACM - 1");
987 return -1;
988 }
989
990 // --- RTP/RTCP module initialization
991
992 // Ensure that RTCP is enabled by default for the created channel.
993 // Note that, the module will keep generating RTCP until it is explicitly
994 // disabled by the user.
995 // After StopListen (when no sockets exists), RTCP packets will no longer
996 // be transmitted since the Transport object will then be invalid.
danilchap799a9d02016-09-22 03:36:27 -0700997 telephone_event_handler_->SetTelephoneEventForwardToDecoder(true);
kwiberg55b97fe2016-01-28 05:22:45 -0800998 // RTCP is enabled by default.
999 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
1000 // --- Register all permanent callbacks
solenbergfe7dd6d2017-03-11 08:10:43 -08001001 if (audio_coding_->RegisterTransportCallback(this) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08001002 _engineStatisticsPtr->SetLastError(
1003 VE_CANNOT_INIT_CHANNEL, kTraceError,
1004 "Channel::Init() callbacks not registered");
1005 return -1;
1006 }
1007
kwiberg1c07c702017-03-27 07:15:49 -07001008 // Register a default set of send codecs.
1009 const int nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
kwiberg55b97fe2016-01-28 05:22:45 -08001010 for (int idx = 0; idx < nSupportedCodecs; idx++) {
kwiberg1c07c702017-03-27 07:15:49 -07001011 CodecInst codec;
1012 RTC_CHECK_EQ(0, audio_coding_->Codec(idx, &codec));
1013
1014 // Ensure that PCMU is used as default send codec.
1015 if (STR_CASE_CMP(codec.plname, "PCMU") == 0 && codec.channels == 1) {
1016 SetSendCodec(codec);
1017 }
1018
1019 // Register default PT for 'telephone-event'
1020 if (STR_CASE_CMP(codec.plname, "telephone-event") == 0) {
1021 if (_rtpRtcpModule->RegisterSendPayload(codec) == -1) {
1022 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1023 "Channel::Init() failed to register outband "
1024 "'telephone-event' (%d/%d) correctly",
1025 codec.pltype, codec.plfreq);
1026 }
1027 }
1028
1029 if (STR_CASE_CMP(codec.plname, "CN") == 0) {
1030 if (!codec_manager_.RegisterEncoder(codec) ||
1031 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get()) ||
1032 _rtpRtcpModule->RegisterSendPayload(codec) == -1) {
1033 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1034 "Channel::Init() failed to register CN (%d/%d) "
1035 "correctly - 1",
1036 codec.pltype, codec.plfreq);
1037 }
1038 }
1039 }
1040
1041 return 0;
1042}
1043
1044void Channel::RegisterLegacyReceiveCodecs() {
1045 const int nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
1046 for (int idx = 0; idx < nSupportedCodecs; idx++) {
1047 CodecInst codec;
1048 RTC_CHECK_EQ(0, audio_coding_->Codec(idx, &codec));
1049
kwiberg55b97fe2016-01-28 05:22:45 -08001050 // Open up the RTP/RTCP receiver for all supported codecs
kwiberg1c07c702017-03-27 07:15:49 -07001051 if (rtp_receiver_->RegisterReceivePayload(codec) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08001052 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1053 "Channel::Init() unable to register %s "
1054 "(%d/%d/%" PRIuS "/%d) to RTP/RTCP receiver",
1055 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1056 codec.rate);
1057 } else {
1058 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1059 "Channel::Init() %s (%d/%d/%" PRIuS
1060 "/%d) has been "
1061 "added to the RTP/RTCP receiver",
1062 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1063 codec.rate);
niklase@google.com470e71d2011-07-07 08:21:25 +00001064 }
1065
kwiberg1c07c702017-03-27 07:15:49 -07001066 // Register default PT for 'telephone-event'
1067 if (STR_CASE_CMP(codec.plname, "telephone-event") == 0) {
1068 if (!audio_coding_->RegisterReceiveCodec(codec.pltype,
kwibergda2bf4e2016-10-24 13:47:09 -07001069 CodecInstToSdp(codec))) {
kwiberg55b97fe2016-01-28 05:22:45 -08001070 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
kwiberg1c07c702017-03-27 07:15:49 -07001071 "Channel::Init() failed to register inband "
kwiberg55b97fe2016-01-28 05:22:45 -08001072 "'telephone-event' (%d/%d) correctly",
1073 codec.pltype, codec.plfreq);
1074 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001075 }
1076
kwiberg1c07c702017-03-27 07:15:49 -07001077 if (STR_CASE_CMP(codec.plname, "CN") == 0) {
1078 if (!audio_coding_->RegisterReceiveCodec(codec.pltype,
1079 CodecInstToSdp(codec))) {
kwiberg55b97fe2016-01-28 05:22:45 -08001080 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1081 "Channel::Init() failed to register CN (%d/%d) "
1082 "correctly - 1",
1083 codec.pltype, codec.plfreq);
1084 }
1085 }
kwiberg55b97fe2016-01-28 05:22:45 -08001086 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001087}
1088
tommi0a2391f2017-03-21 02:31:51 -07001089void Channel::Terminate() {
1090 RTC_DCHECK(construction_thread_.CalledOnValidThread());
1091 // Must be called on the same thread as Init().
1092 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
1093 "Channel::Terminate");
1094
1095 rtp_receive_statistics_->RegisterRtcpStatisticsCallback(NULL);
1096
1097 StopSend();
1098 StopPlayout();
1099
1100 {
1101 rtc::CritScope cs(&_fileCritSect);
1102 if (input_file_player_) {
1103 input_file_player_->RegisterModuleFileCallback(NULL);
1104 input_file_player_->StopPlayingFile();
1105 }
1106 if (output_file_player_) {
1107 output_file_player_->RegisterModuleFileCallback(NULL);
1108 output_file_player_->StopPlayingFile();
1109 }
1110 if (output_file_recorder_) {
1111 output_file_recorder_->RegisterModuleFileCallback(NULL);
1112 output_file_recorder_->StopRecording();
1113 }
1114 }
1115
1116 // The order to safely shutdown modules in a channel is:
1117 // 1. De-register callbacks in modules
1118 // 2. De-register modules in process thread
1119 // 3. Destroy modules
1120 if (audio_coding_->RegisterTransportCallback(NULL) == -1) {
1121 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1122 "Terminate() failed to de-register transport callback"
1123 " (Audio coding module)");
1124 }
1125
1126 if (audio_coding_->RegisterVADCallback(NULL) == -1) {
1127 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1128 "Terminate() failed to de-register VAD callback"
1129 " (Audio coding module)");
1130 }
1131
1132 // De-register modules in process thread
1133 if (_moduleProcessThreadPtr)
1134 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
1135
1136 // End of modules shutdown
1137}
1138
kwiberg55b97fe2016-01-28 05:22:45 -08001139int32_t Channel::SetEngineInformation(Statistics& engineStatistics,
1140 OutputMixer& outputMixer,
kwiberg55b97fe2016-01-28 05:22:45 -08001141 ProcessThread& moduleProcessThread,
1142 AudioDeviceModule& audioDeviceModule,
1143 VoiceEngineObserver* voiceEngineObserver,
henrikaec6fbd22017-03-31 05:43:36 -07001144 rtc::CriticalSection* callbackCritSect,
1145 rtc::TaskQueue* encoder_queue) {
1146 RTC_DCHECK(encoder_queue);
1147 RTC_DCHECK(!encoder_queue_);
kwiberg55b97fe2016-01-28 05:22:45 -08001148 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1149 "Channel::SetEngineInformation()");
1150 _engineStatisticsPtr = &engineStatistics;
1151 _outputMixerPtr = &outputMixer;
kwiberg55b97fe2016-01-28 05:22:45 -08001152 _moduleProcessThreadPtr = &moduleProcessThread;
1153 _audioDeviceModulePtr = &audioDeviceModule;
1154 _voiceEngineObserverPtr = voiceEngineObserver;
1155 _callbackCritSectPtr = callbackCritSect;
henrikaec6fbd22017-03-31 05:43:36 -07001156 encoder_queue_ = encoder_queue;
kwiberg55b97fe2016-01-28 05:22:45 -08001157 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001158}
1159
kwibergb7f89d62016-02-17 10:04:18 -08001160void Channel::SetSink(std::unique_ptr<AudioSinkInterface> sink) {
tommi31fc21f2016-01-21 10:37:37 -08001161 rtc::CritScope cs(&_callbackCritSect);
deadbeef2d110be2016-01-13 12:00:26 -08001162 audio_sink_ = std::move(sink);
Tommif888bb52015-12-12 01:37:01 +01001163}
1164
ossu29b1a8d2016-06-13 07:34:51 -07001165const rtc::scoped_refptr<AudioDecoderFactory>&
1166Channel::GetAudioDecoderFactory() const {
1167 return decoder_factory_;
1168}
1169
kwiberg55b97fe2016-01-28 05:22:45 -08001170int32_t Channel::StartPlayout() {
1171 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1172 "Channel::StartPlayout()");
1173 if (channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001174 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001175 }
1176
solenberge374e012017-02-14 04:55:00 -08001177 // Add participant as candidates for mixing.
1178 if (_outputMixerPtr->SetMixabilityStatus(*this, true) != 0) {
1179 _engineStatisticsPtr->SetLastError(
1180 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1181 "StartPlayout() failed to add participant to mixer");
1182 return -1;
kwiberg55b97fe2016-01-28 05:22:45 -08001183 }
1184
1185 channel_state_.SetPlaying(true);
1186 if (RegisterFilePlayingToMixer() != 0)
1187 return -1;
1188
1189 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001190}
1191
kwiberg55b97fe2016-01-28 05:22:45 -08001192int32_t Channel::StopPlayout() {
1193 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1194 "Channel::StopPlayout()");
1195 if (!channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001196 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001197 }
1198
solenberge374e012017-02-14 04:55:00 -08001199 // Remove participant as candidates for mixing
1200 if (_outputMixerPtr->SetMixabilityStatus(*this, false) != 0) {
1201 _engineStatisticsPtr->SetLastError(
1202 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1203 "StopPlayout() failed to remove participant from mixer");
1204 return -1;
kwiberg55b97fe2016-01-28 05:22:45 -08001205 }
1206
1207 channel_state_.SetPlaying(false);
1208 _outputAudioLevel.Clear();
1209
1210 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001211}
1212
kwiberg55b97fe2016-01-28 05:22:45 -08001213int32_t Channel::StartSend() {
1214 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1215 "Channel::StartSend()");
kwiberg55b97fe2016-01-28 05:22:45 -08001216 if (channel_state_.Get().sending) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001217 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001218 }
1219 channel_state_.SetSending(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00001220
solenberg08b19df2017-02-15 00:42:31 -08001221 // Resume the previous sequence number which was reset by StopSend(). This
1222 // needs to be done before |sending| is set to true on the RTP/RTCP module.
1223 if (send_sequence_number_) {
1224 _rtpRtcpModule->SetSequenceNumber(send_sequence_number_);
1225 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001226 _rtpRtcpModule->SetSendingMediaStatus(true);
kwiberg55b97fe2016-01-28 05:22:45 -08001227 if (_rtpRtcpModule->SetSendingStatus(true) != 0) {
1228 _engineStatisticsPtr->SetLastError(
1229 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1230 "StartSend() RTP/RTCP failed to start sending");
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001231 _rtpRtcpModule->SetSendingMediaStatus(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001232 rtc::CritScope cs(&_callbackCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001233 channel_state_.SetSending(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001234 return -1;
1235 }
xians@webrtc.orge07247a2011-11-28 16:31:28 +00001236
kwiberg55b97fe2016-01-28 05:22:45 -08001237 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001238}
1239
henrikaec6fbd22017-03-31 05:43:36 -07001240void Channel::StopSend() {
kwiberg55b97fe2016-01-28 05:22:45 -08001241 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1242 "Channel::StopSend()");
1243 if (!channel_state_.Get().sending) {
henrikaec6fbd22017-03-31 05:43:36 -07001244 return;
kwiberg55b97fe2016-01-28 05:22:45 -08001245 }
1246 channel_state_.SetSending(false);
1247
henrikaec6fbd22017-03-31 05:43:36 -07001248 // Post a task to the encoder thread which sets an event when the task is
1249 // executed. We know that no more encoding tasks will be added to the task
1250 // queue for this channel since sending is now deactivated. It means that,
1251 // if we wait for the event to bet set, we know that no more pending tasks
1252 // exists and it is therfore guaranteed that the task queue will never try
1253 // to acccess and invalid channel object.
1254 RTC_DCHECK(encoder_queue_);
1255 rtc::Event flush(false, false);
1256 encoder_queue_->PostTask([&flush]() { flush.Set(); });
1257 flush.Wait(rtc::Event::kForever);
1258
kwiberg55b97fe2016-01-28 05:22:45 -08001259 // Store the sequence number to be able to pick up the same sequence for
1260 // the next StartSend(). This is needed for restarting device, otherwise
1261 // it might cause libSRTP to complain about packets being replayed.
1262 // TODO(xians): Remove this workaround after RtpRtcpModule's refactoring
1263 // CL is landed. See issue
1264 // https://code.google.com/p/webrtc/issues/detail?id=2111 .
1265 send_sequence_number_ = _rtpRtcpModule->SequenceNumber();
1266
1267 // Reset sending SSRC and sequence number and triggers direct transmission
1268 // of RTCP BYE
1269 if (_rtpRtcpModule->SetSendingStatus(false) == -1) {
1270 _engineStatisticsPtr->SetLastError(
1271 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
1272 "StartSend() RTP/RTCP failed to stop sending");
1273 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001274 _rtpRtcpModule->SetSendingMediaStatus(false);
niklase@google.com470e71d2011-07-07 08:21:25 +00001275}
1276
kwiberg55b97fe2016-01-28 05:22:45 -08001277int32_t Channel::RegisterVoiceEngineObserver(VoiceEngineObserver& observer) {
1278 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1279 "Channel::RegisterVoiceEngineObserver()");
1280 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00001281
kwiberg55b97fe2016-01-28 05:22:45 -08001282 if (_voiceEngineObserverPtr) {
1283 _engineStatisticsPtr->SetLastError(
1284 VE_INVALID_OPERATION, kTraceError,
1285 "RegisterVoiceEngineObserver() observer already enabled");
1286 return -1;
1287 }
1288 _voiceEngineObserverPtr = &observer;
1289 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001290}
1291
kwiberg55b97fe2016-01-28 05:22:45 -08001292int32_t Channel::DeRegisterVoiceEngineObserver() {
1293 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1294 "Channel::DeRegisterVoiceEngineObserver()");
1295 rtc::CritScope cs(&_callbackCritSect);
1296
1297 if (!_voiceEngineObserverPtr) {
1298 _engineStatisticsPtr->SetLastError(
1299 VE_INVALID_OPERATION, kTraceWarning,
1300 "DeRegisterVoiceEngineObserver() observer already disabled");
1301 return 0;
1302 }
1303 _voiceEngineObserverPtr = NULL;
1304 return 0;
1305}
1306
1307int32_t Channel::GetSendCodec(CodecInst& codec) {
kwibergc8d071e2016-04-06 12:22:38 -07001308 auto send_codec = codec_manager_.GetCodecInst();
kwiberg1fd4a4a2015-11-03 11:20:50 -08001309 if (send_codec) {
1310 codec = *send_codec;
1311 return 0;
1312 }
1313 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001314}
1315
kwiberg55b97fe2016-01-28 05:22:45 -08001316int32_t Channel::GetRecCodec(CodecInst& codec) {
1317 return (audio_coding_->ReceiveCodec(&codec));
niklase@google.com470e71d2011-07-07 08:21:25 +00001318}
1319
kwiberg55b97fe2016-01-28 05:22:45 -08001320int32_t Channel::SetSendCodec(const CodecInst& codec) {
1321 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1322 "Channel::SetSendCodec()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001323
kwibergc8d071e2016-04-06 12:22:38 -07001324 if (!codec_manager_.RegisterEncoder(codec) ||
1325 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001326 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1327 "SetSendCodec() failed to register codec to ACM");
1328 return -1;
1329 }
1330
1331 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1332 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1333 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1334 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1335 "SetSendCodec() failed to register codec to"
1336 " RTP/RTCP module");
1337 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001338 }
kwiberg55b97fe2016-01-28 05:22:45 -08001339 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001340
kwiberg55b97fe2016-01-28 05:22:45 -08001341 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001342}
1343
minyue78b4d562016-11-30 04:47:39 -08001344void Channel::SetBitRate(int bitrate_bps, int64_t probing_interval_ms) {
Ivo Creusenadf89b72015-04-29 16:03:33 +02001345 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1346 "Channel::SetBitRate(bitrate_bps=%d)", bitrate_bps);
minyue7e304322016-10-12 05:00:55 -07001347 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
michaelt2fedf9c2016-11-28 02:34:18 -08001348 if (*encoder) {
1349 (*encoder)->OnReceivedUplinkBandwidth(
michaelt566d8202017-01-12 10:17:38 -08001350 bitrate_bps, rtc::Optional<int64_t>(probing_interval_ms));
michaelt2fedf9c2016-11-28 02:34:18 -08001351 }
1352 });
michaelt566d8202017-01-12 10:17:38 -08001353 retransmission_rate_limiter_->SetMaxRate(bitrate_bps);
Ivo Creusenadf89b72015-04-29 16:03:33 +02001354}
1355
elad.alond12a8e12017-03-23 11:04:48 -07001356void Channel::OnTwccBasedUplinkPacketLossRate(float packet_loss_rate) {
1357 if (!use_twcc_plr_for_ana_)
1358 return;
minyue7e304322016-10-12 05:00:55 -07001359 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
elad.alond12a8e12017-03-23 11:04:48 -07001360 if (*encoder) {
1361 (*encoder)->OnReceivedUplinkPacketLossFraction(packet_loss_rate);
1362 }
1363 });
1364}
1365
elad.alondadb4dc2017-03-23 15:29:50 -07001366void Channel::OnRecoverableUplinkPacketLossRate(
1367 float recoverable_packet_loss_rate) {
1368 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1369 if (*encoder) {
1370 (*encoder)->OnReceivedUplinkRecoverablePacketLossFraction(
1371 recoverable_packet_loss_rate);
1372 }
1373 });
1374}
1375
elad.alond12a8e12017-03-23 11:04:48 -07001376void Channel::OnUplinkPacketLossRate(float packet_loss_rate) {
1377 if (use_twcc_plr_for_ana_)
1378 return;
1379 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1380 if (*encoder) {
1381 (*encoder)->OnReceivedUplinkPacketLossFraction(packet_loss_rate);
1382 }
minyue7e304322016-10-12 05:00:55 -07001383 });
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00001384}
1385
kwiberg55b97fe2016-01-28 05:22:45 -08001386int32_t Channel::SetVADStatus(bool enableVAD,
1387 ACMVADMode mode,
1388 bool disableDTX) {
1389 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1390 "Channel::SetVADStatus(mode=%d)", mode);
kwibergc8d071e2016-04-06 12:22:38 -07001391 RTC_DCHECK(!(disableDTX && enableVAD)); // disableDTX mode is deprecated.
1392 if (!codec_manager_.SetVAD(enableVAD, mode) ||
1393 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001394 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR,
1395 kTraceError,
1396 "SetVADStatus() failed to set VAD");
1397 return -1;
1398 }
1399 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001400}
1401
kwiberg55b97fe2016-01-28 05:22:45 -08001402int32_t Channel::GetVADStatus(bool& enabledVAD,
1403 ACMVADMode& mode,
1404 bool& disabledDTX) {
kwibergc8d071e2016-04-06 12:22:38 -07001405 const auto* params = codec_manager_.GetStackParams();
1406 enabledVAD = params->use_cng;
1407 mode = params->vad_mode;
1408 disabledDTX = !params->use_cng;
kwiberg55b97fe2016-01-28 05:22:45 -08001409 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001410}
1411
kwiberg1c07c702017-03-27 07:15:49 -07001412void Channel::SetReceiveCodecs(const std::map<int, SdpAudioFormat>& codecs) {
1413 rtp_payload_registry_->SetAudioReceivePayloads(codecs);
1414 audio_coding_->SetReceiveCodecs(codecs);
1415}
1416
kwiberg55b97fe2016-01-28 05:22:45 -08001417int32_t Channel::SetRecPayloadType(const CodecInst& codec) {
kwibergd32bf752017-01-19 07:03:59 -08001418 return SetRecPayloadType(codec.pltype, CodecInstToSdp(codec));
1419}
1420
1421int32_t Channel::SetRecPayloadType(int payload_type,
1422 const SdpAudioFormat& format) {
kwiberg55b97fe2016-01-28 05:22:45 -08001423 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1424 "Channel::SetRecPayloadType()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001425
kwiberg55b97fe2016-01-28 05:22:45 -08001426 if (channel_state_.Get().playing) {
1427 _engineStatisticsPtr->SetLastError(
1428 VE_ALREADY_PLAYING, kTraceError,
1429 "SetRecPayloadType() unable to set PT while playing");
1430 return -1;
1431 }
kwiberg55b97fe2016-01-28 05:22:45 -08001432
kwiberg09f090c2017-03-01 01:57:11 -08001433 const CodecInst codec = SdpToCodecInst(payload_type, format);
kwibergd32bf752017-01-19 07:03:59 -08001434
1435 if (payload_type == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08001436 // De-register the selected codec (RTP/RTCP module and ACM)
1437
1438 int8_t pltype(-1);
1439 CodecInst rxCodec = codec;
1440
1441 // Get payload type for the given codec
magjed56124bd2016-11-24 09:34:46 -08001442 rtp_payload_registry_->ReceivePayloadType(rxCodec, &pltype);
kwiberg55b97fe2016-01-28 05:22:45 -08001443 rxCodec.pltype = pltype;
1444
1445 if (rtp_receiver_->DeRegisterReceivePayload(pltype) != 0) {
1446 _engineStatisticsPtr->SetLastError(
1447 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1448 "SetRecPayloadType() RTP/RTCP-module deregistration "
1449 "failed");
1450 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001451 }
kwiberg55b97fe2016-01-28 05:22:45 -08001452 if (audio_coding_->UnregisterReceiveCodec(rxCodec.pltype) != 0) {
1453 _engineStatisticsPtr->SetLastError(
1454 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1455 "SetRecPayloadType() ACM deregistration failed - 1");
1456 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001457 }
kwiberg55b97fe2016-01-28 05:22:45 -08001458 return 0;
1459 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001460
magjed56124bd2016-11-24 09:34:46 -08001461 if (rtp_receiver_->RegisterReceivePayload(codec) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001462 // First attempt to register failed => de-register and try again
kwibergc8d071e2016-04-06 12:22:38 -07001463 // TODO(kwiberg): Retrying is probably not necessary, since
1464 // AcmReceiver::AddCodec also retries.
kwiberg55b97fe2016-01-28 05:22:45 -08001465 rtp_receiver_->DeRegisterReceivePayload(codec.pltype);
magjed56124bd2016-11-24 09:34:46 -08001466 if (rtp_receiver_->RegisterReceivePayload(codec) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001467 _engineStatisticsPtr->SetLastError(
1468 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1469 "SetRecPayloadType() RTP/RTCP-module registration failed");
1470 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001471 }
kwiberg55b97fe2016-01-28 05:22:45 -08001472 }
kwibergd32bf752017-01-19 07:03:59 -08001473 if (!audio_coding_->RegisterReceiveCodec(payload_type, format)) {
1474 audio_coding_->UnregisterReceiveCodec(payload_type);
1475 if (!audio_coding_->RegisterReceiveCodec(payload_type, format)) {
kwiberg55b97fe2016-01-28 05:22:45 -08001476 _engineStatisticsPtr->SetLastError(
1477 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1478 "SetRecPayloadType() ACM registration failed - 1");
1479 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001480 }
kwiberg55b97fe2016-01-28 05:22:45 -08001481 }
1482 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001483}
1484
kwiberg55b97fe2016-01-28 05:22:45 -08001485int32_t Channel::GetRecPayloadType(CodecInst& codec) {
1486 int8_t payloadType(-1);
magjed56124bd2016-11-24 09:34:46 -08001487 if (rtp_payload_registry_->ReceivePayloadType(codec, &payloadType) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001488 _engineStatisticsPtr->SetLastError(
1489 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
1490 "GetRecPayloadType() failed to retrieve RX payload type");
1491 return -1;
1492 }
1493 codec.pltype = payloadType;
1494 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001495}
1496
kwiberg55b97fe2016-01-28 05:22:45 -08001497int32_t Channel::SetSendCNPayloadType(int type, PayloadFrequencies frequency) {
1498 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1499 "Channel::SetSendCNPayloadType()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001500
kwiberg55b97fe2016-01-28 05:22:45 -08001501 CodecInst codec;
1502 int32_t samplingFreqHz(-1);
1503 const size_t kMono = 1;
1504 if (frequency == kFreq32000Hz)
1505 samplingFreqHz = 32000;
1506 else if (frequency == kFreq16000Hz)
1507 samplingFreqHz = 16000;
niklase@google.com470e71d2011-07-07 08:21:25 +00001508
kwiberg55b97fe2016-01-28 05:22:45 -08001509 if (audio_coding_->Codec("CN", &codec, samplingFreqHz, kMono) == -1) {
1510 _engineStatisticsPtr->SetLastError(
1511 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1512 "SetSendCNPayloadType() failed to retrieve default CN codec "
1513 "settings");
1514 return -1;
1515 }
1516
1517 // Modify the payload type (must be set to dynamic range)
1518 codec.pltype = type;
1519
kwibergc8d071e2016-04-06 12:22:38 -07001520 if (!codec_manager_.RegisterEncoder(codec) ||
1521 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001522 _engineStatisticsPtr->SetLastError(
1523 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1524 "SetSendCNPayloadType() failed to register CN to ACM");
1525 return -1;
1526 }
1527
1528 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1529 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1530 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1531 _engineStatisticsPtr->SetLastError(
1532 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1533 "SetSendCNPayloadType() failed to register CN to RTP/RTCP "
1534 "module");
1535 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001536 }
kwiberg55b97fe2016-01-28 05:22:45 -08001537 }
1538 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001539}
1540
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001541int Channel::SetOpusMaxPlaybackRate(int frequency_hz) {
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001542 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001543 "Channel::SetOpusMaxPlaybackRate()");
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001544
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001545 if (audio_coding_->SetOpusMaxPlaybackRate(frequency_hz) != 0) {
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001546 _engineStatisticsPtr->SetLastError(
1547 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001548 "SetOpusMaxPlaybackRate() failed to set maximum playback rate");
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001549 return -1;
1550 }
1551 return 0;
1552}
1553
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001554int Channel::SetOpusDtx(bool enable_dtx) {
1555 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1556 "Channel::SetOpusDtx(%d)", enable_dtx);
Minyue Li092041c2015-05-11 12:19:35 +02001557 int ret = enable_dtx ? audio_coding_->EnableOpusDtx()
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001558 : audio_coding_->DisableOpusDtx();
1559 if (ret != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001560 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR,
1561 kTraceError, "SetOpusDtx() failed");
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001562 return -1;
1563 }
1564 return 0;
1565}
1566
ivoc85228d62016-07-27 04:53:47 -07001567int Channel::GetOpusDtx(bool* enabled) {
1568 int success = -1;
1569 audio_coding_->QueryEncoder([&](AudioEncoder const* encoder) {
1570 if (encoder) {
1571 *enabled = encoder->GetDtx();
1572 success = 0;
1573 }
1574 });
1575 return success;
1576}
1577
minyue7e304322016-10-12 05:00:55 -07001578bool Channel::EnableAudioNetworkAdaptor(const std::string& config_string) {
1579 bool success = false;
1580 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1581 if (*encoder) {
1582 success = (*encoder)->EnableAudioNetworkAdaptor(
michaeltbf279fc2017-01-13 06:02:29 -08001583 config_string, event_log_proxy_.get(), Clock::GetRealTimeClock());
minyue7e304322016-10-12 05:00:55 -07001584 }
1585 });
1586 return success;
1587}
1588
1589void Channel::DisableAudioNetworkAdaptor() {
1590 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1591 if (*encoder)
1592 (*encoder)->DisableAudioNetworkAdaptor();
1593 });
1594}
1595
1596void Channel::SetReceiverFrameLengthRange(int min_frame_length_ms,
1597 int max_frame_length_ms) {
1598 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1599 if (*encoder) {
1600 (*encoder)->SetReceiverFrameLengthRange(min_frame_length_ms,
1601 max_frame_length_ms);
1602 }
1603 });
1604}
1605
mflodman3d7db262016-04-29 00:57:13 -07001606int32_t Channel::RegisterExternalTransport(Transport* transport) {
kwiberg55b97fe2016-01-28 05:22:45 -08001607 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00001608 "Channel::RegisterExternalTransport()");
1609
kwiberg55b97fe2016-01-28 05:22:45 -08001610 rtc::CritScope cs(&_callbackCritSect);
kwiberg55b97fe2016-01-28 05:22:45 -08001611 if (_externalTransport) {
1612 _engineStatisticsPtr->SetLastError(
1613 VE_INVALID_OPERATION, kTraceError,
1614 "RegisterExternalTransport() external transport already enabled");
1615 return -1;
1616 }
1617 _externalTransport = true;
mflodman3d7db262016-04-29 00:57:13 -07001618 _transportPtr = transport;
kwiberg55b97fe2016-01-28 05:22:45 -08001619 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001620}
1621
kwiberg55b97fe2016-01-28 05:22:45 -08001622int32_t Channel::DeRegisterExternalTransport() {
1623 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1624 "Channel::DeRegisterExternalTransport()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001625
kwiberg55b97fe2016-01-28 05:22:45 -08001626 rtc::CritScope cs(&_callbackCritSect);
mflodman3d7db262016-04-29 00:57:13 -07001627 if (_transportPtr) {
1628 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1629 "DeRegisterExternalTransport() all transport is disabled");
1630 } else {
kwiberg55b97fe2016-01-28 05:22:45 -08001631 _engineStatisticsPtr->SetLastError(
1632 VE_INVALID_OPERATION, kTraceWarning,
1633 "DeRegisterExternalTransport() external transport already "
1634 "disabled");
kwiberg55b97fe2016-01-28 05:22:45 -08001635 }
1636 _externalTransport = false;
1637 _transportPtr = NULL;
kwiberg55b97fe2016-01-28 05:22:45 -08001638 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001639}
1640
nisse657bab22017-02-21 06:28:10 -08001641// TODO(nisse): Delete this method together with ReceivedRTPPacket.
1642// It's a temporary hack to support both ReceivedRTPPacket and
1643// OnRtpPacket interfaces without too much code duplication.
1644bool Channel::OnRtpPacketWithHeader(const uint8_t* received_packet,
1645 size_t length,
1646 RTPHeader *header) {
1647 // Store playout timestamp for the received RTP packet
1648 UpdatePlayoutTimestamp(false);
1649
1650 header->payload_type_frequency =
1651 rtp_payload_registry_->GetPayloadTypeFrequency(header->payloadType);
1652 if (header->payload_type_frequency < 0)
1653 return false;
1654 bool in_order = IsPacketInOrder(*header);
1655 rtp_receive_statistics_->IncomingPacket(
1656 *header, length, IsPacketRetransmitted(*header, in_order));
1657 rtp_payload_registry_->SetIncomingPayloadType(*header);
1658
1659 return ReceivePacket(received_packet, length, *header, in_order);
1660}
1661
mflodman3d7db262016-04-29 00:57:13 -07001662int32_t Channel::ReceivedRTPPacket(const uint8_t* received_packet,
kwiberg55b97fe2016-01-28 05:22:45 -08001663 size_t length,
solenberg@webrtc.orgb1f50102014-03-24 10:38:25 +00001664 const PacketTime& packet_time) {
kwiberg55b97fe2016-01-28 05:22:45 -08001665 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001666 "Channel::ReceivedRTPPacket()");
1667
stefan@webrtc.orga5cb98c2013-05-29 12:12:51 +00001668 RTPHeader header;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001669 if (!rtp_header_parser_->Parse(received_packet, length, &header)) {
1670 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1671 "Incoming packet: invalid RTP header");
stefan@webrtc.orga5cb98c2013-05-29 12:12:51 +00001672 return -1;
1673 }
nisse657bab22017-02-21 06:28:10 -08001674 return OnRtpPacketWithHeader(received_packet, length, &header) ? 0 : -1;
1675}
solenberg@webrtc.orgb1f50102014-03-24 10:38:25 +00001676
nisse657bab22017-02-21 06:28:10 -08001677void Channel::OnRtpPacket(const RtpPacketReceived& packet) {
1678 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
1679 "Channel::ReceivedRTPPacket()");
1680
1681 RTPHeader header;
1682 packet.GetHeader(&header);
1683 OnRtpPacketWithHeader(packet.data(), packet.size(), &header);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001684}
1685
1686bool Channel::ReceivePacket(const uint8_t* packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001687 size_t packet_length,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001688 const RTPHeader& header,
1689 bool in_order) {
minyue@webrtc.org456f0142015-01-23 11:58:42 +00001690 if (rtp_payload_registry_->IsRtx(header)) {
1691 return HandleRtxPacket(packet, packet_length, header);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001692 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001693 const uint8_t* payload = packet + header.headerLength;
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001694 assert(packet_length >= header.headerLength);
1695 size_t payload_length = packet_length - header.headerLength;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001696 PayloadUnion payload_specific;
1697 if (!rtp_payload_registry_->GetPayloadSpecifics(header.payloadType,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001698 &payload_specific)) {
1699 return false;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001700 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001701 return rtp_receiver_->IncomingRtpPacket(header, payload, payload_length,
1702 payload_specific, in_order);
1703}
1704
minyue@webrtc.org456f0142015-01-23 11:58:42 +00001705bool Channel::HandleRtxPacket(const uint8_t* packet,
1706 size_t packet_length,
1707 const RTPHeader& header) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001708 if (!rtp_payload_registry_->IsRtx(header))
1709 return false;
1710
1711 // Remove the RTX header and parse the original RTP header.
1712 if (packet_length < header.headerLength)
1713 return false;
1714 if (packet_length > kVoiceEngineMaxIpPacketSizeBytes)
1715 return false;
1716 if (restored_packet_in_use_) {
1717 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1718 "Multiple RTX headers detected, dropping packet");
1719 return false;
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001720 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001721 if (!rtp_payload_registry_->RestoreOriginalPacket(
noahric65220a72015-10-14 11:29:49 -07001722 restored_packet_, packet, &packet_length, rtp_receiver_->SSRC(),
1723 header)) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001724 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1725 "Incoming RTX packet: invalid RTP header");
1726 return false;
1727 }
1728 restored_packet_in_use_ = true;
noahric65220a72015-10-14 11:29:49 -07001729 bool ret = OnRecoveredPacket(restored_packet_, packet_length);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001730 restored_packet_in_use_ = false;
1731 return ret;
1732}
1733
1734bool Channel::IsPacketInOrder(const RTPHeader& header) const {
1735 StreamStatistician* statistician =
1736 rtp_receive_statistics_->GetStatistician(header.ssrc);
1737 if (!statistician)
1738 return false;
1739 return statistician->IsPacketInOrder(header.sequenceNumber);
niklase@google.com470e71d2011-07-07 08:21:25 +00001740}
1741
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001742bool Channel::IsPacketRetransmitted(const RTPHeader& header,
1743 bool in_order) const {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001744 // Retransmissions are handled separately if RTX is enabled.
1745 if (rtp_payload_registry_->RtxEnabled())
1746 return false;
1747 StreamStatistician* statistician =
1748 rtp_receive_statistics_->GetStatistician(header.ssrc);
1749 if (!statistician)
1750 return false;
1751 // Check if this is a retransmission.
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001752 int64_t min_rtt = 0;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001753 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), NULL, NULL, &min_rtt, NULL);
kwiberg55b97fe2016-01-28 05:22:45 -08001754 return !in_order && statistician->IsRetransmitOfOldPacket(header, min_rtt);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001755}
1756
mflodman3d7db262016-04-29 00:57:13 -07001757int32_t Channel::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
kwiberg55b97fe2016-01-28 05:22:45 -08001758 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001759 "Channel::ReceivedRTCPPacket()");
1760 // Store playout timestamp for the received RTCP packet
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001761 UpdatePlayoutTimestamp(true);
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001762
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001763 // Deliver RTCP packet to RTP/RTCP module for parsing
mflodman3d7db262016-04-29 00:57:13 -07001764 if (_rtpRtcpModule->IncomingRtcpPacket(data, length) == -1) {
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001765 _engineStatisticsPtr->SetLastError(
1766 VE_SOCKET_TRANSPORT_MODULE_ERROR, kTraceWarning,
1767 "Channel::IncomingRTPPacket() RTCP packet is invalid");
1768 }
wu@webrtc.org82c4b852014-05-20 22:55:01 +00001769
Minyue2013aec2015-05-13 14:14:42 +02001770 int64_t rtt = GetRTT(true);
1771 if (rtt == 0) {
1772 // Waiting for valid RTT.
1773 return 0;
1774 }
Erik Språng737336d2016-07-29 12:59:36 +02001775
1776 int64_t nack_window_ms = rtt;
1777 if (nack_window_ms < kMinRetransmissionWindowMs) {
1778 nack_window_ms = kMinRetransmissionWindowMs;
1779 } else if (nack_window_ms > kMaxRetransmissionWindowMs) {
1780 nack_window_ms = kMaxRetransmissionWindowMs;
1781 }
1782 retransmission_rate_limiter_->SetWindowSize(nack_window_ms);
1783
minyue7e304322016-10-12 05:00:55 -07001784 // Invoke audio encoders OnReceivedRtt().
1785 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1786 if (*encoder)
1787 (*encoder)->OnReceivedRtt(rtt);
1788 });
1789
Minyue2013aec2015-05-13 14:14:42 +02001790 uint32_t ntp_secs = 0;
1791 uint32_t ntp_frac = 0;
1792 uint32_t rtp_timestamp = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001793 if (0 !=
1794 _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
1795 &rtp_timestamp)) {
Minyue2013aec2015-05-13 14:14:42 +02001796 // Waiting for RTCP.
1797 return 0;
1798 }
1799
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001800 {
tommi31fc21f2016-01-21 10:37:37 -08001801 rtc::CritScope lock(&ts_stats_lock_);
minyue@webrtc.org2c0cdbc2014-10-09 10:52:43 +00001802 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001803 }
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001804 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001805}
1806
niklase@google.com470e71d2011-07-07 08:21:25 +00001807int Channel::StartPlayingFileLocally(const char* fileName,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001808 bool loop,
1809 FileFormats format,
1810 int startPosition,
1811 float volumeScaling,
1812 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001813 const CodecInst* codecInst) {
1814 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1815 "Channel::StartPlayingFileLocally(fileNameUTF8[]=%s, loop=%d,"
1816 " format=%d, volumeScaling=%5.3f, startPosition=%d, "
1817 "stopPosition=%d)",
1818 fileName, loop, format, volumeScaling, startPosition,
1819 stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001820
kwiberg55b97fe2016-01-28 05:22:45 -08001821 if (channel_state_.Get().output_file_playing) {
1822 _engineStatisticsPtr->SetLastError(
1823 VE_ALREADY_PLAYING, kTraceError,
1824 "StartPlayingFileLocally() is already playing");
1825 return -1;
1826 }
1827
1828 {
1829 rtc::CritScope cs(&_fileCritSect);
1830
kwiberg5a25d952016-08-17 07:31:12 -07001831 if (output_file_player_) {
1832 output_file_player_->RegisterModuleFileCallback(NULL);
1833 output_file_player_.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +00001834 }
1835
kwiberg5b356f42016-09-08 04:32:33 -07001836 output_file_player_ = FilePlayer::CreateFilePlayer(
kwiberg55b97fe2016-01-28 05:22:45 -08001837 _outputFilePlayerId, (const FileFormats)format);
henrike@webrtc.orgb37c6282011-10-31 23:53:04 +00001838
kwiberg5a25d952016-08-17 07:31:12 -07001839 if (!output_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08001840 _engineStatisticsPtr->SetLastError(
1841 VE_INVALID_ARGUMENT, kTraceError,
1842 "StartPlayingFileLocally() filePlayer format is not correct");
1843 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001844 }
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001845
kwiberg55b97fe2016-01-28 05:22:45 -08001846 const uint32_t notificationTime(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00001847
kwiberg5a25d952016-08-17 07:31:12 -07001848 if (output_file_player_->StartPlayingFile(
kwiberg55b97fe2016-01-28 05:22:45 -08001849 fileName, loop, startPosition, volumeScaling, notificationTime,
1850 stopPosition, (const CodecInst*)codecInst) != 0) {
1851 _engineStatisticsPtr->SetLastError(
1852 VE_BAD_FILE, kTraceError,
1853 "StartPlayingFile() failed to start file playout");
kwiberg5a25d952016-08-17 07:31:12 -07001854 output_file_player_->StopPlayingFile();
1855 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001856 return -1;
1857 }
kwiberg5a25d952016-08-17 07:31:12 -07001858 output_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08001859 channel_state_.SetOutputFilePlaying(true);
1860 }
1861
1862 if (RegisterFilePlayingToMixer() != 0)
1863 return -1;
1864
1865 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001866}
1867
1868int Channel::StartPlayingFileLocally(InStream* stream,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001869 FileFormats format,
1870 int startPosition,
1871 float volumeScaling,
1872 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001873 const CodecInst* codecInst) {
1874 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1875 "Channel::StartPlayingFileLocally(format=%d,"
1876 " volumeScaling=%5.3f, startPosition=%d, stopPosition=%d)",
1877 format, volumeScaling, startPosition, stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001878
kwiberg55b97fe2016-01-28 05:22:45 -08001879 if (stream == NULL) {
1880 _engineStatisticsPtr->SetLastError(
1881 VE_BAD_FILE, kTraceError,
1882 "StartPlayingFileLocally() NULL as input stream");
1883 return -1;
1884 }
1885
1886 if (channel_state_.Get().output_file_playing) {
1887 _engineStatisticsPtr->SetLastError(
1888 VE_ALREADY_PLAYING, kTraceError,
1889 "StartPlayingFileLocally() is already playing");
1890 return -1;
1891 }
1892
1893 {
1894 rtc::CritScope cs(&_fileCritSect);
1895
1896 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07001897 if (output_file_player_) {
1898 output_file_player_->RegisterModuleFileCallback(NULL);
1899 output_file_player_.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +00001900 }
1901
kwiberg55b97fe2016-01-28 05:22:45 -08001902 // Create the instance
kwiberg5b356f42016-09-08 04:32:33 -07001903 output_file_player_ = FilePlayer::CreateFilePlayer(
kwiberg55b97fe2016-01-28 05:22:45 -08001904 _outputFilePlayerId, (const FileFormats)format);
niklase@google.com470e71d2011-07-07 08:21:25 +00001905
kwiberg5a25d952016-08-17 07:31:12 -07001906 if (!output_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08001907 _engineStatisticsPtr->SetLastError(
1908 VE_INVALID_ARGUMENT, kTraceError,
1909 "StartPlayingFileLocally() filePlayer format isnot correct");
1910 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001911 }
1912
kwiberg55b97fe2016-01-28 05:22:45 -08001913 const uint32_t notificationTime(0);
henrike@webrtc.orgb37c6282011-10-31 23:53:04 +00001914
kwiberg4ec01d92016-08-22 08:43:54 -07001915 if (output_file_player_->StartPlayingFile(stream, startPosition,
kwiberg5a25d952016-08-17 07:31:12 -07001916 volumeScaling, notificationTime,
1917 stopPosition, codecInst) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001918 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
1919 "StartPlayingFile() failed to "
1920 "start file playout");
kwiberg5a25d952016-08-17 07:31:12 -07001921 output_file_player_->StopPlayingFile();
1922 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001923 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001924 }
kwiberg5a25d952016-08-17 07:31:12 -07001925 output_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08001926 channel_state_.SetOutputFilePlaying(true);
1927 }
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001928
kwiberg55b97fe2016-01-28 05:22:45 -08001929 if (RegisterFilePlayingToMixer() != 0)
1930 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001931
kwiberg55b97fe2016-01-28 05:22:45 -08001932 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001933}
1934
kwiberg55b97fe2016-01-28 05:22:45 -08001935int Channel::StopPlayingFileLocally() {
1936 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1937 "Channel::StopPlayingFileLocally()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001938
kwiberg55b97fe2016-01-28 05:22:45 -08001939 if (!channel_state_.Get().output_file_playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001940 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001941 }
1942
1943 {
1944 rtc::CritScope cs(&_fileCritSect);
1945
kwiberg5a25d952016-08-17 07:31:12 -07001946 if (output_file_player_->StopPlayingFile() != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001947 _engineStatisticsPtr->SetLastError(
1948 VE_STOP_RECORDING_FAILED, kTraceError,
1949 "StopPlayingFile() could not stop playing");
1950 return -1;
1951 }
kwiberg5a25d952016-08-17 07:31:12 -07001952 output_file_player_->RegisterModuleFileCallback(NULL);
1953 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001954 channel_state_.SetOutputFilePlaying(false);
1955 }
1956 // _fileCritSect cannot be taken while calling
1957 // SetAnonymousMixibilityStatus. Refer to comments in
1958 // StartPlayingFileLocally(const char* ...) for more details.
1959 if (_outputMixerPtr->SetAnonymousMixabilityStatus(*this, false) != 0) {
1960 _engineStatisticsPtr->SetLastError(
1961 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1962 "StopPlayingFile() failed to stop participant from playing as"
1963 "file in the mixer");
1964 return -1;
1965 }
1966
1967 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001968}
1969
kwiberg55b97fe2016-01-28 05:22:45 -08001970int Channel::IsPlayingFileLocally() const {
1971 return channel_state_.Get().output_file_playing;
niklase@google.com470e71d2011-07-07 08:21:25 +00001972}
1973
kwiberg55b97fe2016-01-28 05:22:45 -08001974int Channel::RegisterFilePlayingToMixer() {
1975 // Return success for not registering for file playing to mixer if:
1976 // 1. playing file before playout is started on that channel.
1977 // 2. starting playout without file playing on that channel.
1978 if (!channel_state_.Get().playing ||
1979 !channel_state_.Get().output_file_playing) {
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001980 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001981 }
1982
1983 // |_fileCritSect| cannot be taken while calling
1984 // SetAnonymousMixabilityStatus() since as soon as the participant is added
1985 // frames can be pulled by the mixer. Since the frames are generated from
1986 // the file, _fileCritSect will be taken. This would result in a deadlock.
1987 if (_outputMixerPtr->SetAnonymousMixabilityStatus(*this, true) != 0) {
1988 channel_state_.SetOutputFilePlaying(false);
1989 rtc::CritScope cs(&_fileCritSect);
1990 _engineStatisticsPtr->SetLastError(
1991 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1992 "StartPlayingFile() failed to add participant as file to mixer");
kwiberg5a25d952016-08-17 07:31:12 -07001993 output_file_player_->StopPlayingFile();
1994 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001995 return -1;
1996 }
1997
1998 return 0;
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001999}
2000
niklase@google.com470e71d2011-07-07 08:21:25 +00002001int Channel::StartPlayingFileAsMicrophone(const char* fileName,
pbos@webrtc.org92135212013-05-14 08:31:39 +00002002 bool loop,
2003 FileFormats format,
2004 int startPosition,
2005 float volumeScaling,
2006 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08002007 const CodecInst* codecInst) {
2008 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2009 "Channel::StartPlayingFileAsMicrophone(fileNameUTF8[]=%s, "
2010 "loop=%d, format=%d, volumeScaling=%5.3f, startPosition=%d, "
2011 "stopPosition=%d)",
2012 fileName, loop, format, volumeScaling, startPosition,
2013 stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00002014
kwiberg55b97fe2016-01-28 05:22:45 -08002015 rtc::CritScope cs(&_fileCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00002016
kwiberg55b97fe2016-01-28 05:22:45 -08002017 if (channel_state_.Get().input_file_playing) {
2018 _engineStatisticsPtr->SetLastError(
2019 VE_ALREADY_PLAYING, kTraceWarning,
2020 "StartPlayingFileAsMicrophone() filePlayer is playing");
niklase@google.com470e71d2011-07-07 08:21:25 +00002021 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002022 }
2023
2024 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07002025 if (input_file_player_) {
2026 input_file_player_->RegisterModuleFileCallback(NULL);
2027 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002028 }
2029
2030 // Create the instance
kwiberg5b356f42016-09-08 04:32:33 -07002031 input_file_player_ = FilePlayer::CreateFilePlayer(_inputFilePlayerId,
kwiberg5a25d952016-08-17 07:31:12 -07002032 (const FileFormats)format);
kwiberg55b97fe2016-01-28 05:22:45 -08002033
kwiberg5a25d952016-08-17 07:31:12 -07002034 if (!input_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002035 _engineStatisticsPtr->SetLastError(
2036 VE_INVALID_ARGUMENT, kTraceError,
2037 "StartPlayingFileAsMicrophone() filePlayer format isnot correct");
2038 return -1;
2039 }
2040
2041 const uint32_t notificationTime(0);
2042
kwiberg5a25d952016-08-17 07:31:12 -07002043 if (input_file_player_->StartPlayingFile(
kwiberg55b97fe2016-01-28 05:22:45 -08002044 fileName, loop, startPosition, volumeScaling, notificationTime,
2045 stopPosition, (const CodecInst*)codecInst) != 0) {
2046 _engineStatisticsPtr->SetLastError(
2047 VE_BAD_FILE, kTraceError,
2048 "StartPlayingFile() failed to start file playout");
kwiberg5a25d952016-08-17 07:31:12 -07002049 input_file_player_->StopPlayingFile();
2050 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002051 return -1;
2052 }
kwiberg5a25d952016-08-17 07:31:12 -07002053 input_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002054 channel_state_.SetInputFilePlaying(true);
2055
2056 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002057}
2058
2059int Channel::StartPlayingFileAsMicrophone(InStream* stream,
pbos@webrtc.org92135212013-05-14 08:31:39 +00002060 FileFormats format,
2061 int startPosition,
2062 float volumeScaling,
2063 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08002064 const CodecInst* codecInst) {
2065 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2066 "Channel::StartPlayingFileAsMicrophone(format=%d, "
2067 "volumeScaling=%5.3f, startPosition=%d, stopPosition=%d)",
2068 format, volumeScaling, startPosition, stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00002069
kwiberg55b97fe2016-01-28 05:22:45 -08002070 if (stream == NULL) {
2071 _engineStatisticsPtr->SetLastError(
2072 VE_BAD_FILE, kTraceError,
2073 "StartPlayingFileAsMicrophone NULL as input stream");
2074 return -1;
2075 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002076
kwiberg55b97fe2016-01-28 05:22:45 -08002077 rtc::CritScope cs(&_fileCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00002078
kwiberg55b97fe2016-01-28 05:22:45 -08002079 if (channel_state_.Get().input_file_playing) {
2080 _engineStatisticsPtr->SetLastError(
2081 VE_ALREADY_PLAYING, kTraceWarning,
2082 "StartPlayingFileAsMicrophone() is playing");
niklase@google.com470e71d2011-07-07 08:21:25 +00002083 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002084 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002085
kwiberg55b97fe2016-01-28 05:22:45 -08002086 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07002087 if (input_file_player_) {
2088 input_file_player_->RegisterModuleFileCallback(NULL);
2089 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002090 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002091
kwiberg55b97fe2016-01-28 05:22:45 -08002092 // Create the instance
kwiberg5b356f42016-09-08 04:32:33 -07002093 input_file_player_ = FilePlayer::CreateFilePlayer(_inputFilePlayerId,
kwiberg5a25d952016-08-17 07:31:12 -07002094 (const FileFormats)format);
kwiberg55b97fe2016-01-28 05:22:45 -08002095
kwiberg5a25d952016-08-17 07:31:12 -07002096 if (!input_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002097 _engineStatisticsPtr->SetLastError(
2098 VE_INVALID_ARGUMENT, kTraceError,
2099 "StartPlayingInputFile() filePlayer format isnot correct");
2100 return -1;
2101 }
2102
2103 const uint32_t notificationTime(0);
2104
kwiberg4ec01d92016-08-22 08:43:54 -07002105 if (input_file_player_->StartPlayingFile(stream, startPosition, volumeScaling,
2106 notificationTime, stopPosition,
2107 codecInst) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002108 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
2109 "StartPlayingFile() failed to start "
2110 "file playout");
kwiberg5a25d952016-08-17 07:31:12 -07002111 input_file_player_->StopPlayingFile();
2112 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002113 return -1;
2114 }
2115
kwiberg5a25d952016-08-17 07:31:12 -07002116 input_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002117 channel_state_.SetInputFilePlaying(true);
2118
2119 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002120}
2121
kwiberg55b97fe2016-01-28 05:22:45 -08002122int Channel::StopPlayingFileAsMicrophone() {
2123 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2124 "Channel::StopPlayingFileAsMicrophone()");
2125
2126 rtc::CritScope cs(&_fileCritSect);
2127
2128 if (!channel_state_.Get().input_file_playing) {
2129 return 0;
2130 }
2131
kwiberg5a25d952016-08-17 07:31:12 -07002132 if (input_file_player_->StopPlayingFile() != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002133 _engineStatisticsPtr->SetLastError(
2134 VE_STOP_RECORDING_FAILED, kTraceError,
2135 "StopPlayingFile() could not stop playing");
2136 return -1;
2137 }
kwiberg5a25d952016-08-17 07:31:12 -07002138 input_file_player_->RegisterModuleFileCallback(NULL);
2139 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002140 channel_state_.SetInputFilePlaying(false);
2141
2142 return 0;
2143}
2144
2145int Channel::IsPlayingFileAsMicrophone() const {
2146 return channel_state_.Get().input_file_playing;
niklase@google.com470e71d2011-07-07 08:21:25 +00002147}
2148
leozwang@webrtc.org813e4b02012-03-01 18:34:25 +00002149int Channel::StartRecordingPlayout(const char* fileName,
kwiberg55b97fe2016-01-28 05:22:45 -08002150 const CodecInst* codecInst) {
2151 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2152 "Channel::StartRecordingPlayout(fileName=%s)", fileName);
niklase@google.com470e71d2011-07-07 08:21:25 +00002153
kwiberg55b97fe2016-01-28 05:22:45 -08002154 if (_outputFileRecording) {
2155 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, -1),
2156 "StartRecordingPlayout() is already recording");
niklase@google.com470e71d2011-07-07 08:21:25 +00002157 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002158 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002159
kwiberg55b97fe2016-01-28 05:22:45 -08002160 FileFormats format;
2161 const uint32_t notificationTime(0); // Not supported in VoE
2162 CodecInst dummyCodec = {100, "L16", 16000, 320, 1, 320000};
niklase@google.com470e71d2011-07-07 08:21:25 +00002163
kwiberg55b97fe2016-01-28 05:22:45 -08002164 if ((codecInst != NULL) &&
2165 ((codecInst->channels < 1) || (codecInst->channels > 2))) {
2166 _engineStatisticsPtr->SetLastError(
2167 VE_BAD_ARGUMENT, kTraceError,
2168 "StartRecordingPlayout() invalid compression");
2169 return (-1);
2170 }
2171 if (codecInst == NULL) {
2172 format = kFileFormatPcm16kHzFile;
2173 codecInst = &dummyCodec;
2174 } else if ((STR_CASE_CMP(codecInst->plname, "L16") == 0) ||
2175 (STR_CASE_CMP(codecInst->plname, "PCMU") == 0) ||
2176 (STR_CASE_CMP(codecInst->plname, "PCMA") == 0)) {
2177 format = kFileFormatWavFile;
2178 } else {
2179 format = kFileFormatCompressedFile;
2180 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002181
kwiberg55b97fe2016-01-28 05:22:45 -08002182 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002183
kwiberg55b97fe2016-01-28 05:22:45 -08002184 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07002185 if (output_file_recorder_) {
2186 output_file_recorder_->RegisterModuleFileCallback(NULL);
2187 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002188 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002189
kwiberg5a25d952016-08-17 07:31:12 -07002190 output_file_recorder_ = FileRecorder::CreateFileRecorder(
kwiberg55b97fe2016-01-28 05:22:45 -08002191 _outputFileRecorderId, (const FileFormats)format);
kwiberg5a25d952016-08-17 07:31:12 -07002192 if (!output_file_recorder_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002193 _engineStatisticsPtr->SetLastError(
2194 VE_INVALID_ARGUMENT, kTraceError,
2195 "StartRecordingPlayout() fileRecorder format isnot correct");
2196 return -1;
2197 }
2198
kwiberg5a25d952016-08-17 07:31:12 -07002199 if (output_file_recorder_->StartRecordingAudioFile(
kwiberg55b97fe2016-01-28 05:22:45 -08002200 fileName, (const CodecInst&)*codecInst, notificationTime) != 0) {
2201 _engineStatisticsPtr->SetLastError(
2202 VE_BAD_FILE, kTraceError,
2203 "StartRecordingAudioFile() failed to start file recording");
kwiberg5a25d952016-08-17 07:31:12 -07002204 output_file_recorder_->StopRecording();
2205 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002206 return -1;
2207 }
kwiberg5a25d952016-08-17 07:31:12 -07002208 output_file_recorder_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002209 _outputFileRecording = true;
2210
2211 return 0;
2212}
2213
2214int Channel::StartRecordingPlayout(OutStream* stream,
2215 const CodecInst* codecInst) {
2216 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2217 "Channel::StartRecordingPlayout()");
2218
2219 if (_outputFileRecording) {
2220 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, -1),
2221 "StartRecordingPlayout() is already recording");
niklase@google.com470e71d2011-07-07 08:21:25 +00002222 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002223 }
2224
2225 FileFormats format;
2226 const uint32_t notificationTime(0); // Not supported in VoE
2227 CodecInst dummyCodec = {100, "L16", 16000, 320, 1, 320000};
2228
2229 if (codecInst != NULL && codecInst->channels != 1) {
2230 _engineStatisticsPtr->SetLastError(
2231 VE_BAD_ARGUMENT, kTraceError,
2232 "StartRecordingPlayout() invalid compression");
2233 return (-1);
2234 }
2235 if (codecInst == NULL) {
2236 format = kFileFormatPcm16kHzFile;
2237 codecInst = &dummyCodec;
2238 } else if ((STR_CASE_CMP(codecInst->plname, "L16") == 0) ||
2239 (STR_CASE_CMP(codecInst->plname, "PCMU") == 0) ||
2240 (STR_CASE_CMP(codecInst->plname, "PCMA") == 0)) {
2241 format = kFileFormatWavFile;
2242 } else {
2243 format = kFileFormatCompressedFile;
2244 }
2245
2246 rtc::CritScope cs(&_fileCritSect);
2247
2248 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07002249 if (output_file_recorder_) {
2250 output_file_recorder_->RegisterModuleFileCallback(NULL);
2251 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002252 }
2253
kwiberg5a25d952016-08-17 07:31:12 -07002254 output_file_recorder_ = FileRecorder::CreateFileRecorder(
kwiberg55b97fe2016-01-28 05:22:45 -08002255 _outputFileRecorderId, (const FileFormats)format);
kwiberg5a25d952016-08-17 07:31:12 -07002256 if (!output_file_recorder_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002257 _engineStatisticsPtr->SetLastError(
2258 VE_INVALID_ARGUMENT, kTraceError,
2259 "StartRecordingPlayout() fileRecorder format isnot correct");
2260 return -1;
2261 }
2262
kwiberg4ec01d92016-08-22 08:43:54 -07002263 if (output_file_recorder_->StartRecordingAudioFile(stream, *codecInst,
kwiberg5a25d952016-08-17 07:31:12 -07002264 notificationTime) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002265 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
2266 "StartRecordingPlayout() failed to "
2267 "start file recording");
kwiberg5a25d952016-08-17 07:31:12 -07002268 output_file_recorder_->StopRecording();
2269 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002270 return -1;
2271 }
2272
kwiberg5a25d952016-08-17 07:31:12 -07002273 output_file_recorder_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002274 _outputFileRecording = true;
2275
2276 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002277}
2278
kwiberg55b97fe2016-01-28 05:22:45 -08002279int Channel::StopRecordingPlayout() {
2280 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, -1),
2281 "Channel::StopRecordingPlayout()");
2282
2283 if (!_outputFileRecording) {
2284 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, -1),
2285 "StopRecordingPlayout() isnot recording");
2286 return -1;
2287 }
2288
2289 rtc::CritScope cs(&_fileCritSect);
2290
kwiberg5a25d952016-08-17 07:31:12 -07002291 if (output_file_recorder_->StopRecording() != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002292 _engineStatisticsPtr->SetLastError(
2293 VE_STOP_RECORDING_FAILED, kTraceError,
2294 "StopRecording() could not stop recording");
2295 return (-1);
2296 }
kwiberg5a25d952016-08-17 07:31:12 -07002297 output_file_recorder_->RegisterModuleFileCallback(NULL);
2298 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002299 _outputFileRecording = false;
2300
2301 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002302}
2303
kwiberg55b97fe2016-01-28 05:22:45 -08002304void Channel::SetMixWithMicStatus(bool mix) {
2305 rtc::CritScope cs(&_fileCritSect);
2306 _mixFileWithMicrophone = mix;
niklase@google.com470e71d2011-07-07 08:21:25 +00002307}
2308
solenberg8d73f8c2017-03-08 01:52:20 -08002309int Channel::GetSpeechOutputLevel() const {
2310 return _outputAudioLevel.Level();
niklase@google.com470e71d2011-07-07 08:21:25 +00002311}
2312
solenberg8d73f8c2017-03-08 01:52:20 -08002313int Channel::GetSpeechOutputLevelFullRange() const {
2314 return _outputAudioLevel.LevelFullRange();
kwiberg55b97fe2016-01-28 05:22:45 -08002315}
2316
solenberg8d73f8c2017-03-08 01:52:20 -08002317void Channel::SetInputMute(bool enable) {
kwiberg55b97fe2016-01-28 05:22:45 -08002318 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07002319 input_mute_ = enable;
niklase@google.com470e71d2011-07-07 08:21:25 +00002320}
2321
solenberg1c2af8e2016-03-24 10:36:00 -07002322bool Channel::InputMute() const {
kwiberg55b97fe2016-01-28 05:22:45 -08002323 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07002324 return input_mute_;
niklase@google.com470e71d2011-07-07 08:21:25 +00002325}
2326
solenberg8d73f8c2017-03-08 01:52:20 -08002327void Channel::SetChannelOutputVolumeScaling(float scaling) {
kwiberg55b97fe2016-01-28 05:22:45 -08002328 rtc::CritScope cs(&volume_settings_critsect_);
kwiberg55b97fe2016-01-28 05:22:45 -08002329 _outputGain = scaling;
niklase@google.com470e71d2011-07-07 08:21:25 +00002330}
2331
solenberg8842c3e2016-03-11 03:06:41 -08002332int Channel::SendTelephoneEventOutband(int event, int duration_ms) {
kwiberg55b97fe2016-01-28 05:22:45 -08002333 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
solenberg8842c3e2016-03-11 03:06:41 -08002334 "Channel::SendTelephoneEventOutband(...)");
2335 RTC_DCHECK_LE(0, event);
2336 RTC_DCHECK_GE(255, event);
2337 RTC_DCHECK_LE(0, duration_ms);
2338 RTC_DCHECK_GE(65535, duration_ms);
kwiberg55b97fe2016-01-28 05:22:45 -08002339 if (!Sending()) {
2340 return -1;
2341 }
solenberg8842c3e2016-03-11 03:06:41 -08002342 if (_rtpRtcpModule->SendTelephoneEventOutband(
2343 event, duration_ms, kTelephoneEventAttenuationdB) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002344 _engineStatisticsPtr->SetLastError(
2345 VE_SEND_DTMF_FAILED, kTraceWarning,
2346 "SendTelephoneEventOutband() failed to send event");
2347 return -1;
2348 }
2349 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002350}
2351
solenbergffbbcac2016-11-17 05:25:37 -08002352int Channel::SetSendTelephoneEventPayloadType(int payload_type,
2353 int payload_frequency) {
kwiberg55b97fe2016-01-28 05:22:45 -08002354 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002355 "Channel::SetSendTelephoneEventPayloadType()");
solenberg31642aa2016-03-14 08:00:37 -07002356 RTC_DCHECK_LE(0, payload_type);
2357 RTC_DCHECK_GE(127, payload_type);
2358 CodecInst codec = {0};
solenberg31642aa2016-03-14 08:00:37 -07002359 codec.pltype = payload_type;
solenbergffbbcac2016-11-17 05:25:37 -08002360 codec.plfreq = payload_frequency;
kwiberg55b97fe2016-01-28 05:22:45 -08002361 memcpy(codec.plname, "telephone-event", 16);
2362 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
2363 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
2364 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
2365 _engineStatisticsPtr->SetLastError(
2366 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2367 "SetSendTelephoneEventPayloadType() failed to register send"
2368 "payload type");
2369 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002370 }
kwiberg55b97fe2016-01-28 05:22:45 -08002371 }
kwiberg55b97fe2016-01-28 05:22:45 -08002372 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002373}
2374
kwiberg55b97fe2016-01-28 05:22:45 -08002375int Channel::SetLocalSSRC(unsigned int ssrc) {
2376 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2377 "Channel::SetLocalSSRC()");
2378 if (channel_state_.Get().sending) {
2379 _engineStatisticsPtr->SetLastError(VE_ALREADY_SENDING, kTraceError,
2380 "SetLocalSSRC() already sending");
2381 return -1;
2382 }
2383 _rtpRtcpModule->SetSSRC(ssrc);
2384 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002385}
2386
kwiberg55b97fe2016-01-28 05:22:45 -08002387int Channel::GetLocalSSRC(unsigned int& ssrc) {
2388 ssrc = _rtpRtcpModule->SSRC();
2389 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002390}
2391
kwiberg55b97fe2016-01-28 05:22:45 -08002392int Channel::GetRemoteSSRC(unsigned int& ssrc) {
2393 ssrc = rtp_receiver_->SSRC();
2394 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002395}
2396
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002397int Channel::SetSendAudioLevelIndicationStatus(bool enable, unsigned char id) {
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00002398 _includeAudioLevelIndication = enable;
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002399 return SetSendRtpHeaderExtension(enable, kRtpExtensionAudioLevel, id);
niklase@google.com470e71d2011-07-07 08:21:25 +00002400}
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00002401
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00002402int Channel::SetReceiveAudioLevelIndicationStatus(bool enable,
2403 unsigned char id) {
kwiberg55b97fe2016-01-28 05:22:45 -08002404 rtp_header_parser_->DeregisterRtpHeaderExtension(kRtpExtensionAudioLevel);
2405 if (enable &&
2406 !rtp_header_parser_->RegisterRtpHeaderExtension(kRtpExtensionAudioLevel,
2407 id)) {
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00002408 return -1;
2409 }
2410 return 0;
2411}
2412
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002413void Channel::EnableSendTransportSequenceNumber(int id) {
2414 int ret =
2415 SetSendRtpHeaderExtension(true, kRtpExtensionTransportSequenceNumber, id);
2416 RTC_DCHECK_EQ(0, ret);
2417}
2418
stefan3313ec92016-01-21 06:32:43 -08002419void Channel::EnableReceiveTransportSequenceNumber(int id) {
2420 rtp_header_parser_->DeregisterRtpHeaderExtension(
2421 kRtpExtensionTransportSequenceNumber);
2422 bool ret = rtp_header_parser_->RegisterRtpHeaderExtension(
2423 kRtpExtensionTransportSequenceNumber, id);
2424 RTC_DCHECK(ret);
2425}
2426
stefanbba9dec2016-02-01 04:39:55 -08002427void Channel::RegisterSenderCongestionControlObjects(
nisseb8f9a322017-03-27 05:36:15 -07002428 RtpTransportControllerSendInterface* transport,
stefan7de8d642017-02-07 07:14:08 -08002429 RtcpBandwidthObserver* bandwidth_observer) {
nisseb8f9a322017-03-27 05:36:15 -07002430 RtpPacketSender* rtp_packet_sender = transport->packet_sender();
2431 TransportFeedbackObserver* transport_feedback_observer =
2432 transport->transport_feedback_observer();
2433 PacketRouter* packet_router = transport->packet_router();
2434
stefanbba9dec2016-02-01 04:39:55 -08002435 RTC_DCHECK(rtp_packet_sender);
2436 RTC_DCHECK(transport_feedback_observer);
2437 RTC_DCHECK(packet_router && !packet_router_);
stefan7de8d642017-02-07 07:14:08 -08002438 rtcp_observer_->SetBandwidthObserver(bandwidth_observer);
stefanbba9dec2016-02-01 04:39:55 -08002439 feedback_observer_proxy_->SetTransportFeedbackObserver(
2440 transport_feedback_observer);
2441 seq_num_allocator_proxy_->SetSequenceNumberAllocator(packet_router);
2442 rtp_packet_sender_proxy_->SetPacketSender(rtp_packet_sender);
2443 _rtpRtcpModule->SetStorePacketsStatus(true, 600);
nissefdbfdc92017-03-31 05:44:52 -07002444 packet_router->AddSendRtpModule(_rtpRtcpModule.get());
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002445 packet_router_ = packet_router;
2446}
2447
stefanbba9dec2016-02-01 04:39:55 -08002448void Channel::RegisterReceiverCongestionControlObjects(
2449 PacketRouter* packet_router) {
2450 RTC_DCHECK(packet_router && !packet_router_);
nissefdbfdc92017-03-31 05:44:52 -07002451 packet_router->AddReceiveRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08002452 packet_router_ = packet_router;
2453}
2454
nissefdbfdc92017-03-31 05:44:52 -07002455void Channel::ResetSenderCongestionControlObjects() {
stefanbba9dec2016-02-01 04:39:55 -08002456 RTC_DCHECK(packet_router_);
2457 _rtpRtcpModule->SetStorePacketsStatus(false, 600);
stefan7de8d642017-02-07 07:14:08 -08002458 rtcp_observer_->SetBandwidthObserver(nullptr);
stefanbba9dec2016-02-01 04:39:55 -08002459 feedback_observer_proxy_->SetTransportFeedbackObserver(nullptr);
2460 seq_num_allocator_proxy_->SetSequenceNumberAllocator(nullptr);
nissefdbfdc92017-03-31 05:44:52 -07002461 packet_router_->RemoveSendRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08002462 packet_router_ = nullptr;
2463 rtp_packet_sender_proxy_->SetPacketSender(nullptr);
2464}
2465
nissefdbfdc92017-03-31 05:44:52 -07002466void Channel::ResetReceiverCongestionControlObjects() {
2467 RTC_DCHECK(packet_router_);
2468 packet_router_->RemoveReceiveRtpModule(_rtpRtcpModule.get());
2469 packet_router_ = nullptr;
2470}
2471
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00002472void Channel::SetRTCPStatus(bool enable) {
2473 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2474 "Channel::SetRTCPStatus()");
pbosda903ea2015-10-02 02:36:56 -07002475 _rtpRtcpModule->SetRTCPStatus(enable ? RtcpMode::kCompound : RtcpMode::kOff);
niklase@google.com470e71d2011-07-07 08:21:25 +00002476}
2477
kwiberg55b97fe2016-01-28 05:22:45 -08002478int Channel::GetRTCPStatus(bool& enabled) {
pbosda903ea2015-10-02 02:36:56 -07002479 RtcpMode method = _rtpRtcpModule->RTCP();
2480 enabled = (method != RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08002481 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002482}
2483
kwiberg55b97fe2016-01-28 05:22:45 -08002484int Channel::SetRTCP_CNAME(const char cName[256]) {
2485 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2486 "Channel::SetRTCP_CNAME()");
2487 if (_rtpRtcpModule->SetCNAME(cName) != 0) {
2488 _engineStatisticsPtr->SetLastError(
2489 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2490 "SetRTCP_CNAME() failed to set RTCP CNAME");
2491 return -1;
2492 }
2493 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002494}
2495
kwiberg55b97fe2016-01-28 05:22:45 -08002496int Channel::GetRemoteRTCP_CNAME(char cName[256]) {
2497 if (cName == NULL) {
2498 _engineStatisticsPtr->SetLastError(
2499 VE_INVALID_ARGUMENT, kTraceError,
2500 "GetRemoteRTCP_CNAME() invalid CNAME input buffer");
2501 return -1;
2502 }
2503 char cname[RTCP_CNAME_SIZE];
2504 const uint32_t remoteSSRC = rtp_receiver_->SSRC();
2505 if (_rtpRtcpModule->RemoteCNAME(remoteSSRC, cname) != 0) {
2506 _engineStatisticsPtr->SetLastError(
2507 VE_CANNOT_RETRIEVE_CNAME, kTraceError,
2508 "GetRemoteRTCP_CNAME() failed to retrieve remote RTCP CNAME");
2509 return -1;
2510 }
2511 strcpy(cName, cname);
2512 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002513}
2514
kwiberg55b97fe2016-01-28 05:22:45 -08002515int Channel::SendApplicationDefinedRTCPPacket(
2516 unsigned char subType,
2517 unsigned int name,
2518 const char* data,
2519 unsigned short dataLengthInBytes) {
2520 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2521 "Channel::SendApplicationDefinedRTCPPacket()");
2522 if (!channel_state_.Get().sending) {
2523 _engineStatisticsPtr->SetLastError(
2524 VE_NOT_SENDING, kTraceError,
2525 "SendApplicationDefinedRTCPPacket() not sending");
2526 return -1;
2527 }
2528 if (NULL == data) {
2529 _engineStatisticsPtr->SetLastError(
2530 VE_INVALID_ARGUMENT, kTraceError,
2531 "SendApplicationDefinedRTCPPacket() invalid data value");
2532 return -1;
2533 }
2534 if (dataLengthInBytes % 4 != 0) {
2535 _engineStatisticsPtr->SetLastError(
2536 VE_INVALID_ARGUMENT, kTraceError,
2537 "SendApplicationDefinedRTCPPacket() invalid length value");
2538 return -1;
2539 }
2540 RtcpMode status = _rtpRtcpModule->RTCP();
2541 if (status == RtcpMode::kOff) {
2542 _engineStatisticsPtr->SetLastError(
2543 VE_RTCP_ERROR, kTraceError,
2544 "SendApplicationDefinedRTCPPacket() RTCP is disabled");
2545 return -1;
2546 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002547
kwiberg55b97fe2016-01-28 05:22:45 -08002548 // Create and schedule the RTCP APP packet for transmission
2549 if (_rtpRtcpModule->SetRTCPApplicationSpecificData(
2550 subType, name, (const unsigned char*)data, dataLengthInBytes) != 0) {
2551 _engineStatisticsPtr->SetLastError(
2552 VE_SEND_ERROR, kTraceError,
2553 "SendApplicationDefinedRTCPPacket() failed to send RTCP packet");
2554 return -1;
2555 }
2556 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002557}
2558
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002559int Channel::GetRemoteRTCPReportBlocks(
2560 std::vector<ReportBlock>* report_blocks) {
2561 if (report_blocks == NULL) {
kwiberg55b97fe2016-01-28 05:22:45 -08002562 _engineStatisticsPtr->SetLastError(
2563 VE_INVALID_ARGUMENT, kTraceError,
2564 "GetRemoteRTCPReportBlock()s invalid report_blocks.");
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002565 return -1;
2566 }
2567
2568 // Get the report blocks from the latest received RTCP Sender or Receiver
2569 // Report. Each element in the vector contains the sender's SSRC and a
2570 // report block according to RFC 3550.
2571 std::vector<RTCPReportBlock> rtcp_report_blocks;
2572 if (_rtpRtcpModule->RemoteRTCPStat(&rtcp_report_blocks) != 0) {
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002573 return -1;
2574 }
2575
2576 if (rtcp_report_blocks.empty())
2577 return 0;
2578
2579 std::vector<RTCPReportBlock>::const_iterator it = rtcp_report_blocks.begin();
2580 for (; it != rtcp_report_blocks.end(); ++it) {
2581 ReportBlock report_block;
2582 report_block.sender_SSRC = it->remoteSSRC;
2583 report_block.source_SSRC = it->sourceSSRC;
2584 report_block.fraction_lost = it->fractionLost;
2585 report_block.cumulative_num_packets_lost = it->cumulativeLost;
2586 report_block.extended_highest_sequence_number = it->extendedHighSeqNum;
2587 report_block.interarrival_jitter = it->jitter;
2588 report_block.last_SR_timestamp = it->lastSR;
2589 report_block.delay_since_last_SR = it->delaySinceLastSR;
2590 report_blocks->push_back(report_block);
2591 }
2592 return 0;
2593}
2594
kwiberg55b97fe2016-01-28 05:22:45 -08002595int Channel::GetRTPStatistics(CallStatistics& stats) {
2596 // --- RtcpStatistics
niklase@google.com470e71d2011-07-07 08:21:25 +00002597
kwiberg55b97fe2016-01-28 05:22:45 -08002598 // The jitter statistics is updated for each received RTP packet and is
2599 // based on received packets.
2600 RtcpStatistics statistics;
2601 StreamStatistician* statistician =
2602 rtp_receive_statistics_->GetStatistician(rtp_receiver_->SSRC());
Peter Boström59013bc2016-02-12 11:35:08 +01002603 if (statistician) {
2604 statistician->GetStatistics(&statistics,
2605 _rtpRtcpModule->RTCP() == RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08002606 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002607
kwiberg55b97fe2016-01-28 05:22:45 -08002608 stats.fractionLost = statistics.fraction_lost;
2609 stats.cumulativeLost = statistics.cumulative_lost;
2610 stats.extendedMax = statistics.extended_max_sequence_number;
2611 stats.jitterSamples = statistics.jitter;
niklase@google.com470e71d2011-07-07 08:21:25 +00002612
kwiberg55b97fe2016-01-28 05:22:45 -08002613 // --- RTT
2614 stats.rttMs = GetRTT(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00002615
kwiberg55b97fe2016-01-28 05:22:45 -08002616 // --- Data counters
niklase@google.com470e71d2011-07-07 08:21:25 +00002617
kwiberg55b97fe2016-01-28 05:22:45 -08002618 size_t bytesSent(0);
2619 uint32_t packetsSent(0);
2620 size_t bytesReceived(0);
2621 uint32_t packetsReceived(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00002622
kwiberg55b97fe2016-01-28 05:22:45 -08002623 if (statistician) {
2624 statistician->GetDataCounters(&bytesReceived, &packetsReceived);
2625 }
wu@webrtc.org822fbd82013-08-15 23:38:54 +00002626
kwiberg55b97fe2016-01-28 05:22:45 -08002627 if (_rtpRtcpModule->DataCountersRTP(&bytesSent, &packetsSent) != 0) {
2628 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2629 "GetRTPStatistics() failed to retrieve RTP datacounters =>"
2630 " output will not be complete");
2631 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002632
kwiberg55b97fe2016-01-28 05:22:45 -08002633 stats.bytesSent = bytesSent;
2634 stats.packetsSent = packetsSent;
2635 stats.bytesReceived = bytesReceived;
2636 stats.packetsReceived = packetsReceived;
niklase@google.com470e71d2011-07-07 08:21:25 +00002637
kwiberg55b97fe2016-01-28 05:22:45 -08002638 // --- Timestamps
2639 {
2640 rtc::CritScope lock(&ts_stats_lock_);
2641 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
2642 }
2643 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002644}
2645
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002646int Channel::SetCodecFECStatus(bool enable) {
2647 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2648 "Channel::SetCodecFECStatus()");
2649
kwibergc8d071e2016-04-06 12:22:38 -07002650 if (!codec_manager_.SetCodecFEC(enable) ||
2651 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002652 _engineStatisticsPtr->SetLastError(
2653 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
2654 "SetCodecFECStatus() failed to set FEC state");
2655 return -1;
2656 }
2657 return 0;
2658}
2659
2660bool Channel::GetCodecFECStatus() {
kwibergc8d071e2016-04-06 12:22:38 -07002661 return codec_manager_.GetStackParams()->use_codec_fec;
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002662}
2663
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002664void Channel::SetNACKStatus(bool enable, int maxNumberOfPackets) {
2665 // None of these functions can fail.
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002666 // If pacing is enabled we always store packets.
2667 if (!pacing_enabled_)
2668 _rtpRtcpModule->SetStorePacketsStatus(enable, maxNumberOfPackets);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00002669 rtp_receive_statistics_->SetMaxReorderingThreshold(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002670 if (enable)
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00002671 audio_coding_->EnableNack(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002672 else
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00002673 audio_coding_->DisableNack();
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002674}
2675
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002676// Called when we are missing one or more packets.
2677int Channel::ResendPackets(const uint16_t* sequence_numbers, int length) {
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002678 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
2679}
2680
henrikaec6fbd22017-03-31 05:43:36 -07002681void Channel::ProcessAndEncodeAudio(const AudioFrame& audio_input) {
2682 RTC_DCHECK(channel_state_.Get().sending);
2683 std::unique_ptr<AudioFrame> audio_frame(new AudioFrame());
2684 // TODO(henrika): try to avoid copying by moving ownership of audio frame
2685 // either into pool of frames or into the task itself.
2686 audio_frame->CopyFrom(audio_input);
2687 audio_frame->id_ = ChannelId();
2688 encoder_queue_->PostTask(std::unique_ptr<rtc::QueuedTask>(
2689 new ProcessAndEncodeAudioTask(std::move(audio_frame), this)));
niklase@google.com470e71d2011-07-07 08:21:25 +00002690}
2691
henrikaec6fbd22017-03-31 05:43:36 -07002692void Channel::ProcessAndEncodeAudio(const int16_t* audio_data,
2693 int sample_rate,
2694 size_t number_of_frames,
2695 size_t number_of_channels) {
2696 RTC_DCHECK(channel_state_.Get().sending);
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002697 CodecInst codec;
2698 GetSendCodec(codec);
henrikaec6fbd22017-03-31 05:43:36 -07002699 std::unique_ptr<AudioFrame> audio_frame(new AudioFrame());
2700 audio_frame->id_ = ChannelId();
2701 audio_frame->sample_rate_hz_ = std::min(codec.plfreq, sample_rate);
2702 audio_frame->num_channels_ = std::min(number_of_channels, codec.channels);
Alejandro Luebscdfe20b2015-09-23 12:49:12 -07002703 RemixAndResample(audio_data, number_of_frames, number_of_channels,
henrikaec6fbd22017-03-31 05:43:36 -07002704 sample_rate, &input_resampler_, audio_frame.get());
2705 encoder_queue_->PostTask(std::unique_ptr<rtc::QueuedTask>(
2706 new ProcessAndEncodeAudioTask(std::move(audio_frame), this)));
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002707}
2708
henrikaec6fbd22017-03-31 05:43:36 -07002709void Channel::ProcessAndEncodeAudioOnTaskQueue(AudioFrame* audio_input) {
2710 RTC_DCHECK_RUN_ON(encoder_queue_);
2711 RTC_DCHECK_GT(audio_input->samples_per_channel_, 0);
2712 RTC_DCHECK_LE(audio_input->num_channels_, 2);
2713 RTC_DCHECK_EQ(audio_input->id_, ChannelId());
kwiberg55b97fe2016-01-28 05:22:45 -08002714
2715 if (channel_state_.Get().input_file_playing) {
henrikaec6fbd22017-03-31 05:43:36 -07002716 MixOrReplaceAudioWithFile(audio_input);
kwiberg55b97fe2016-01-28 05:22:45 -08002717 }
2718
henrikaec6fbd22017-03-31 05:43:36 -07002719 bool is_muted = InputMute();
2720 AudioFrameOperations::Mute(audio_input, previous_frame_muted_, is_muted);
kwiberg55b97fe2016-01-28 05:22:45 -08002721
kwiberg55b97fe2016-01-28 05:22:45 -08002722 if (_includeAudioLevelIndication) {
2723 size_t length =
henrikaec6fbd22017-03-31 05:43:36 -07002724 audio_input->samples_per_channel_ * audio_input->num_channels_;
2725 RTC_CHECK_LE(length, sizeof(audio_input->data_));
solenberg1c2af8e2016-03-24 10:36:00 -07002726 if (is_muted && previous_frame_muted_) {
henrik.lundin50499422016-11-29 04:26:24 -08002727 rms_level_.AnalyzeMuted(length);
kwiberg55b97fe2016-01-28 05:22:45 -08002728 } else {
henrik.lundin50499422016-11-29 04:26:24 -08002729 rms_level_.Analyze(
henrikaec6fbd22017-03-31 05:43:36 -07002730 rtc::ArrayView<const int16_t>(audio_input->data_, length));
niklase@google.com470e71d2011-07-07 08:21:25 +00002731 }
kwiberg55b97fe2016-01-28 05:22:45 -08002732 }
solenberg1c2af8e2016-03-24 10:36:00 -07002733 previous_frame_muted_ = is_muted;
niklase@google.com470e71d2011-07-07 08:21:25 +00002734
henrikaec6fbd22017-03-31 05:43:36 -07002735 // Add 10ms of raw (PCM) audio data to the encoder @ 32kHz.
niklase@google.com470e71d2011-07-07 08:21:25 +00002736
kwiberg55b97fe2016-01-28 05:22:45 -08002737 // The ACM resamples internally.
henrikaec6fbd22017-03-31 05:43:36 -07002738 audio_input->timestamp_ = _timeStamp;
kwiberg55b97fe2016-01-28 05:22:45 -08002739 // This call will trigger AudioPacketizationCallback::SendData if encoding
2740 // is done and payload is ready for packetization and transmission.
2741 // Otherwise, it will return without invoking the callback.
henrikaec6fbd22017-03-31 05:43:36 -07002742 if (audio_coding_->Add10MsData(*audio_input) < 0) {
2743 LOG(LS_ERROR) << "ACM::Add10MsData() failed for channel " << _channelId;
2744 return;
kwiberg55b97fe2016-01-28 05:22:45 -08002745 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002746
henrikaec6fbd22017-03-31 05:43:36 -07002747 _timeStamp += static_cast<uint32_t>(audio_input->samples_per_channel_);
niklase@google.com470e71d2011-07-07 08:21:25 +00002748}
2749
solenberg7602aab2016-11-14 11:30:07 -08002750void Channel::set_associate_send_channel(const ChannelOwner& channel) {
2751 RTC_DCHECK(!channel.channel() ||
2752 channel.channel()->ChannelId() != _channelId);
2753 rtc::CritScope lock(&assoc_send_channel_lock_);
2754 associate_send_channel_ = channel;
2755}
2756
Minyue2013aec2015-05-13 14:14:42 +02002757void Channel::DisassociateSendChannel(int channel_id) {
tommi31fc21f2016-01-21 10:37:37 -08002758 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02002759 Channel* channel = associate_send_channel_.channel();
2760 if (channel && channel->ChannelId() == channel_id) {
2761 // If this channel is associated with a send channel of the specified
2762 // Channel ID, disassociate with it.
2763 ChannelOwner ref(NULL);
2764 associate_send_channel_ = ref;
2765 }
2766}
2767
ivoc14d5dbe2016-07-04 07:06:55 -07002768void Channel::SetRtcEventLog(RtcEventLog* event_log) {
2769 event_log_proxy_->SetEventLog(event_log);
2770}
2771
michaelt9332b7d2016-11-30 07:51:13 -08002772void Channel::SetRtcpRttStats(RtcpRttStats* rtcp_rtt_stats) {
2773 rtcp_rtt_stats_proxy_->SetRtcpRttStats(rtcp_rtt_stats);
2774}
2775
nisse284542b2017-01-10 08:58:32 -08002776void Channel::UpdateOverheadForEncoder() {
hbos3fd31fe2017-02-28 05:43:16 -08002777 size_t overhead_per_packet =
2778 transport_overhead_per_packet_ + rtp_overhead_per_packet_;
nisse284542b2017-01-10 08:58:32 -08002779 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
2780 if (*encoder) {
hbos3fd31fe2017-02-28 05:43:16 -08002781 (*encoder)->OnReceivedOverhead(overhead_per_packet);
nisse284542b2017-01-10 08:58:32 -08002782 }
2783 });
2784}
2785
2786void Channel::SetTransportOverhead(size_t transport_overhead_per_packet) {
hbos3fd31fe2017-02-28 05:43:16 -08002787 rtc::CritScope cs(&overhead_per_packet_lock_);
nisse284542b2017-01-10 08:58:32 -08002788 transport_overhead_per_packet_ = transport_overhead_per_packet;
2789 UpdateOverheadForEncoder();
michaelt79e05882016-11-08 02:50:09 -08002790}
2791
hbos3fd31fe2017-02-28 05:43:16 -08002792// TODO(solenberg): Make AudioSendStream an OverheadObserver instead.
michaeltbf65be52016-12-15 06:24:49 -08002793void Channel::OnOverheadChanged(size_t overhead_bytes_per_packet) {
hbos3fd31fe2017-02-28 05:43:16 -08002794 rtc::CritScope cs(&overhead_per_packet_lock_);
nisse284542b2017-01-10 08:58:32 -08002795 rtp_overhead_per_packet_ = overhead_bytes_per_packet;
2796 UpdateOverheadForEncoder();
michaeltbf65be52016-12-15 06:24:49 -08002797}
2798
kwiberg55b97fe2016-01-28 05:22:45 -08002799int Channel::GetNetworkStatistics(NetworkStatistics& stats) {
2800 return audio_coding_->GetNetworkStatistics(&stats);
niklase@google.com470e71d2011-07-07 08:21:25 +00002801}
2802
wu@webrtc.org24301a62013-12-13 19:17:43 +00002803void Channel::GetDecodingCallStatistics(AudioDecodingCallStats* stats) const {
2804 audio_coding_->GetDecodingCallStatistics(stats);
2805}
2806
solenberg358057b2015-11-27 10:46:42 -08002807uint32_t Channel::GetDelayEstimate() const {
solenberg08b19df2017-02-15 00:42:31 -08002808 rtc::CritScope lock(&video_sync_lock_);
2809 return audio_coding_->FilteredCurrentDelayMs() + playout_delay_ms_;
deadbeef74375882015-08-13 12:09:10 -07002810}
2811
kwiberg55b97fe2016-01-28 05:22:45 -08002812int Channel::SetMinimumPlayoutDelay(int delayMs) {
2813 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2814 "Channel::SetMinimumPlayoutDelay()");
2815 if ((delayMs < kVoiceEngineMinMinPlayoutDelayMs) ||
2816 (delayMs > kVoiceEngineMaxMinPlayoutDelayMs)) {
2817 _engineStatisticsPtr->SetLastError(
2818 VE_INVALID_ARGUMENT, kTraceError,
2819 "SetMinimumPlayoutDelay() invalid min delay");
2820 return -1;
2821 }
2822 if (audio_coding_->SetMinimumPlayoutDelay(delayMs) != 0) {
2823 _engineStatisticsPtr->SetLastError(
2824 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
2825 "SetMinimumPlayoutDelay() failed to set min playout delay");
2826 return -1;
2827 }
2828 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002829}
2830
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00002831int Channel::GetPlayoutTimestamp(unsigned int& timestamp) {
deadbeef74375882015-08-13 12:09:10 -07002832 uint32_t playout_timestamp_rtp = 0;
2833 {
tommi31fc21f2016-01-21 10:37:37 -08002834 rtc::CritScope lock(&video_sync_lock_);
deadbeef74375882015-08-13 12:09:10 -07002835 playout_timestamp_rtp = playout_timestamp_rtp_;
2836 }
kwiberg55b97fe2016-01-28 05:22:45 -08002837 if (playout_timestamp_rtp == 0) {
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00002838 _engineStatisticsPtr->SetLastError(
skvlad4c0536b2016-07-07 13:06:26 -07002839 VE_CANNOT_RETRIEVE_VALUE, kTraceStateInfo,
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00002840 "GetPlayoutTimestamp() failed to retrieve timestamp");
2841 return -1;
2842 }
deadbeef74375882015-08-13 12:09:10 -07002843 timestamp = playout_timestamp_rtp;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00002844 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002845}
2846
kwiberg55b97fe2016-01-28 05:22:45 -08002847int Channel::GetRtpRtcp(RtpRtcp** rtpRtcpModule,
2848 RtpReceiver** rtp_receiver) const {
2849 *rtpRtcpModule = _rtpRtcpModule.get();
2850 *rtp_receiver = rtp_receiver_.get();
2851 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002852}
2853
andrew@webrtc.orge59a0ac2012-05-08 17:12:40 +00002854// TODO(andrew): refactor Mix functions here and in transmit_mixer.cc to use
2855// a shared helper.
henrikaec6fbd22017-03-31 05:43:36 -07002856int32_t Channel::MixOrReplaceAudioWithFile(AudioFrame* audio_input) {
2857 RTC_DCHECK_RUN_ON(encoder_queue_);
kwibergb7f89d62016-02-17 10:04:18 -08002858 std::unique_ptr<int16_t[]> fileBuffer(new int16_t[640]);
kwiberg55b97fe2016-01-28 05:22:45 -08002859 size_t fileSamples(0);
henrikaec6fbd22017-03-31 05:43:36 -07002860 const int mixingFrequency = audio_input->sample_rate_hz_;
kwiberg55b97fe2016-01-28 05:22:45 -08002861 {
2862 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002863
kwiberg5a25d952016-08-17 07:31:12 -07002864 if (!input_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002865 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2866 "Channel::MixOrReplaceAudioWithFile() fileplayer"
2867 " doesnt exist");
2868 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002869 }
2870
kwiberg4ec01d92016-08-22 08:43:54 -07002871 if (input_file_player_->Get10msAudioFromFile(fileBuffer.get(), &fileSamples,
kwiberg5a25d952016-08-17 07:31:12 -07002872 mixingFrequency) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08002873 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2874 "Channel::MixOrReplaceAudioWithFile() file mixing "
2875 "failed");
2876 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002877 }
kwiberg55b97fe2016-01-28 05:22:45 -08002878 if (fileSamples == 0) {
2879 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2880 "Channel::MixOrReplaceAudioWithFile() file is ended");
2881 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002882 }
kwiberg55b97fe2016-01-28 05:22:45 -08002883 }
2884
henrikaec6fbd22017-03-31 05:43:36 -07002885 RTC_DCHECK_EQ(audio_input->samples_per_channel_, fileSamples);
kwiberg55b97fe2016-01-28 05:22:45 -08002886
2887 if (_mixFileWithMicrophone) {
2888 // Currently file stream is always mono.
2889 // TODO(xians): Change the code when FilePlayer supports real stereo.
henrikaec6fbd22017-03-31 05:43:36 -07002890 MixWithSat(audio_input->data_, audio_input->num_channels_, fileBuffer.get(),
kwiberg55b97fe2016-01-28 05:22:45 -08002891 1, fileSamples);
2892 } else {
2893 // Replace ACM audio with file.
2894 // Currently file stream is always mono.
2895 // TODO(xians): Change the code when FilePlayer supports real stereo.
henrikaec6fbd22017-03-31 05:43:36 -07002896 audio_input->UpdateFrame(
kwiberg55b97fe2016-01-28 05:22:45 -08002897 _channelId, 0xFFFFFFFF, fileBuffer.get(), fileSamples, mixingFrequency,
2898 AudioFrame::kNormalSpeech, AudioFrame::kVadUnknown, 1);
2899 }
2900 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002901}
2902
kwiberg55b97fe2016-01-28 05:22:45 -08002903int32_t Channel::MixAudioWithFile(AudioFrame& audioFrame, int mixingFrequency) {
2904 assert(mixingFrequency <= 48000);
niklase@google.com470e71d2011-07-07 08:21:25 +00002905
kwibergb7f89d62016-02-17 10:04:18 -08002906 std::unique_ptr<int16_t[]> fileBuffer(new int16_t[960]);
kwiberg55b97fe2016-01-28 05:22:45 -08002907 size_t fileSamples(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00002908
kwiberg55b97fe2016-01-28 05:22:45 -08002909 {
2910 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002911
kwiberg5a25d952016-08-17 07:31:12 -07002912 if (!output_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002913 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2914 "Channel::MixAudioWithFile() file mixing failed");
2915 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002916 }
2917
kwiberg55b97fe2016-01-28 05:22:45 -08002918 // We should get the frequency we ask for.
kwiberg4ec01d92016-08-22 08:43:54 -07002919 if (output_file_player_->Get10msAudioFromFile(
2920 fileBuffer.get(), &fileSamples, mixingFrequency) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08002921 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2922 "Channel::MixAudioWithFile() file mixing failed");
2923 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002924 }
kwiberg55b97fe2016-01-28 05:22:45 -08002925 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002926
kwiberg55b97fe2016-01-28 05:22:45 -08002927 if (audioFrame.samples_per_channel_ == fileSamples) {
2928 // Currently file stream is always mono.
2929 // TODO(xians): Change the code when FilePlayer supports real stereo.
2930 MixWithSat(audioFrame.data_, audioFrame.num_channels_, fileBuffer.get(), 1,
2931 fileSamples);
2932 } else {
2933 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2934 "Channel::MixAudioWithFile() samples_per_channel_(%" PRIuS
2935 ") != "
2936 "fileSamples(%" PRIuS ")",
2937 audioFrame.samples_per_channel_, fileSamples);
2938 return -1;
2939 }
2940
2941 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002942}
2943
deadbeef74375882015-08-13 12:09:10 -07002944void Channel::UpdatePlayoutTimestamp(bool rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07002945 jitter_buffer_playout_timestamp_ = audio_coding_->PlayoutTimestamp();
deadbeef74375882015-08-13 12:09:10 -07002946
henrik.lundin96bd5022016-04-06 04:13:56 -07002947 if (!jitter_buffer_playout_timestamp_) {
2948 // This can happen if this channel has not received any RTP packets. In
2949 // this case, NetEq is not capable of computing a playout timestamp.
deadbeef74375882015-08-13 12:09:10 -07002950 return;
2951 }
2952
2953 uint16_t delay_ms = 0;
2954 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08002955 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07002956 "Channel::UpdatePlayoutTimestamp() failed to read playout"
2957 " delay from the ADM");
2958 _engineStatisticsPtr->SetLastError(
2959 VE_CANNOT_RETRIEVE_VALUE, kTraceError,
2960 "UpdatePlayoutTimestamp() failed to retrieve playout delay");
2961 return;
2962 }
2963
henrik.lundin96bd5022016-04-06 04:13:56 -07002964 RTC_DCHECK(jitter_buffer_playout_timestamp_);
2965 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
deadbeef74375882015-08-13 12:09:10 -07002966
2967 // Remove the playout delay.
ossue280cde2016-10-12 11:04:10 -07002968 playout_timestamp -= (delay_ms * (GetRtpTimestampRateHz() / 1000));
deadbeef74375882015-08-13 12:09:10 -07002969
kwiberg55b97fe2016-01-28 05:22:45 -08002970 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07002971 "Channel::UpdatePlayoutTimestamp() => playoutTimestamp = %lu",
henrik.lundin96bd5022016-04-06 04:13:56 -07002972 playout_timestamp);
deadbeef74375882015-08-13 12:09:10 -07002973
2974 {
tommi31fc21f2016-01-21 10:37:37 -08002975 rtc::CritScope lock(&video_sync_lock_);
solenberg81d93f32017-02-14 03:44:57 -08002976 if (!rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07002977 playout_timestamp_rtp_ = playout_timestamp;
deadbeef74375882015-08-13 12:09:10 -07002978 }
2979 playout_delay_ms_ = delay_ms;
2980 }
2981}
2982
kwiberg55b97fe2016-01-28 05:22:45 -08002983void Channel::RegisterReceiveCodecsToRTPModule() {
2984 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2985 "Channel::RegisterReceiveCodecsToRTPModule()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002986
kwiberg55b97fe2016-01-28 05:22:45 -08002987 CodecInst codec;
2988 const uint8_t nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
niklase@google.com470e71d2011-07-07 08:21:25 +00002989
kwiberg55b97fe2016-01-28 05:22:45 -08002990 for (int idx = 0; idx < nSupportedCodecs; idx++) {
2991 // Open up the RTP/RTCP receiver for all supported codecs
2992 if ((audio_coding_->Codec(idx, &codec) == -1) ||
magjed56124bd2016-11-24 09:34:46 -08002993 (rtp_receiver_->RegisterReceivePayload(codec) == -1)) {
kwiberg55b97fe2016-01-28 05:22:45 -08002994 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2995 "Channel::RegisterReceiveCodecsToRTPModule() unable"
2996 " to register %s (%d/%d/%" PRIuS
2997 "/%d) to RTP/RTCP "
2998 "receiver",
2999 codec.plname, codec.pltype, codec.plfreq, codec.channels,
3000 codec.rate);
3001 } else {
3002 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3003 "Channel::RegisterReceiveCodecsToRTPModule() %s "
3004 "(%d/%d/%" PRIuS
3005 "/%d) has been added to the RTP/RTCP "
3006 "receiver",
3007 codec.plname, codec.pltype, codec.plfreq, codec.channels,
3008 codec.rate);
niklase@google.com470e71d2011-07-07 08:21:25 +00003009 }
kwiberg55b97fe2016-01-28 05:22:45 -08003010 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003011}
3012
kwiberg55b97fe2016-01-28 05:22:45 -08003013int Channel::SetSendRtpHeaderExtension(bool enable,
3014 RTPExtensionType type,
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00003015 unsigned char id) {
3016 int error = 0;
3017 _rtpRtcpModule->DeregisterSendRtpHeaderExtension(type);
3018 if (enable) {
3019 error = _rtpRtcpModule->RegisterSendRtpHeaderExtension(type, id);
3020 }
3021 return error;
3022}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00003023
ossue280cde2016-10-12 11:04:10 -07003024int Channel::GetRtpTimestampRateHz() const {
3025 const auto format = audio_coding_->ReceiveFormat();
3026 // Default to the playout frequency if we've not gotten any packets yet.
3027 // TODO(ossu): Zero clockrate can only happen if we've added an external
3028 // decoder for a format we don't support internally. Remove once that way of
3029 // adding decoders is gone!
3030 return (format && format->clockrate_hz != 0)
3031 ? format->clockrate_hz
3032 : audio_coding_->PlayoutFrequency();
wu@webrtc.org94454b72014-06-05 20:34:08 +00003033}
3034
Minyue2013aec2015-05-13 14:14:42 +02003035int64_t Channel::GetRTT(bool allow_associate_channel) const {
pbosda903ea2015-10-02 02:36:56 -07003036 RtcpMode method = _rtpRtcpModule->RTCP();
3037 if (method == RtcpMode::kOff) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003038 return 0;
3039 }
3040 std::vector<RTCPReportBlock> report_blocks;
3041 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
Minyue2013aec2015-05-13 14:14:42 +02003042
3043 int64_t rtt = 0;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003044 if (report_blocks.empty()) {
Minyue2013aec2015-05-13 14:14:42 +02003045 if (allow_associate_channel) {
tommi31fc21f2016-01-21 10:37:37 -08003046 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02003047 Channel* channel = associate_send_channel_.channel();
3048 // Tries to get RTT from an associated channel. This is important for
3049 // receive-only channels.
3050 if (channel) {
3051 // To prevent infinite recursion and deadlock, calling GetRTT of
3052 // associate channel should always use "false" for argument:
3053 // |allow_associate_channel|.
3054 rtt = channel->GetRTT(false);
3055 }
3056 }
3057 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003058 }
3059
3060 uint32_t remoteSSRC = rtp_receiver_->SSRC();
3061 std::vector<RTCPReportBlock>::const_iterator it = report_blocks.begin();
3062 for (; it != report_blocks.end(); ++it) {
3063 if (it->remoteSSRC == remoteSSRC)
3064 break;
3065 }
3066 if (it == report_blocks.end()) {
3067 // We have not received packets with SSRC matching the report blocks.
3068 // To calculate RTT we try with the SSRC of the first report block.
3069 // This is very important for send-only channels where we don't know
3070 // the SSRC of the other end.
3071 remoteSSRC = report_blocks[0].remoteSSRC;
3072 }
Minyue2013aec2015-05-13 14:14:42 +02003073
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003074 int64_t avg_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08003075 int64_t max_rtt = 0;
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003076 int64_t min_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08003077 if (_rtpRtcpModule->RTT(remoteSSRC, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
3078 0) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003079 return 0;
3080 }
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003081 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003082}
3083
pbos@webrtc.orgd900e8b2013-07-03 15:12:26 +00003084} // namespace voe
3085} // namespace webrtc