blob: 02001bac6b0805d1de0a0f3d38415f0fb2cd9326 [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"
nissecae45d02017-04-24 05:53:20 -070017#include "webrtc/call/rtp_transport_controller_send_interface.h"
Henrik Lundin64dad832015-05-11 12:44:23 +020018#include "webrtc/config.h"
skvladcc91d282016-10-03 18:31:22 -070019#include "webrtc/logging/rtc_event_log/rtc_event_log.h"
kwibergda2bf4e2016-10-24 13:47:09 -070020#include "webrtc/modules/audio_coding/codecs/audio_format_conversion.h"
turaj@webrtc.org6388c3e2013-02-12 21:42:18 +000021#include "webrtc/modules/audio_device/include/audio_device.h"
22#include "webrtc/modules/audio_processing/include/audio_processing.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010023#include "webrtc/modules/include/module_common_types.h"
Stefan Holmerb86d4e42015-12-07 10:26:18 +010024#include "webrtc/modules/pacing/packet_router.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010025#include "webrtc/modules/rtp_rtcp/include/receive_statistics.h"
26#include "webrtc/modules/rtp_rtcp/include/rtp_payload_registry.h"
27#include "webrtc/modules/rtp_rtcp/include/rtp_receiver.h"
nisse657bab22017-02-21 06:28:10 -080028#include "webrtc/modules/rtp_rtcp/source/rtp_packet_received.h"
wu@webrtc.org822fbd82013-08-15 23:38:54 +000029#include "webrtc/modules/rtp_rtcp/source/rtp_receiver_strategy.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010030#include "webrtc/modules/utility/include/process_thread.h"
Edward Lemurc20978e2017-07-06 19:44:34 +020031#include "webrtc/rtc_base/array_view.h"
32#include "webrtc/rtc_base/checks.h"
33#include "webrtc/rtc_base/criticalsection.h"
34#include "webrtc/rtc_base/format_macros.h"
35#include "webrtc/rtc_base/location.h"
36#include "webrtc/rtc_base/logging.h"
37#include "webrtc/rtc_base/rate_limiter.h"
38#include "webrtc/rtc_base/task_queue.h"
39#include "webrtc/rtc_base/thread_checker.h"
40#include "webrtc/rtc_base/timeutils.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
zsteine76bd3a2017-07-14 12:17:49 -070053constexpr double kAudioSampleDurationSeconds = 0.01;
Erik Språng737336d2016-07-29 12:59:36 +020054constexpr int64_t kMaxRetransmissionWindowMs = 1000;
55constexpr int64_t kMinRetransmissionWindowMs = 30;
56
kwibergc8d071e2016-04-06 12:22:38 -070057} // namespace
58
solenberg8842c3e2016-03-11 03:06:41 -080059const int kTelephoneEventAttenuationdB = 10;
60
ivoc14d5dbe2016-07-04 07:06:55 -070061class RtcEventLogProxy final : public webrtc::RtcEventLog {
62 public:
63 RtcEventLogProxy() : event_log_(nullptr) {}
64
65 bool StartLogging(const std::string& file_name,
66 int64_t max_size_bytes) override {
67 RTC_NOTREACHED();
68 return false;
69 }
70
71 bool StartLogging(rtc::PlatformFile log_file,
72 int64_t max_size_bytes) override {
73 RTC_NOTREACHED();
74 return false;
75 }
76
77 void StopLogging() override { RTC_NOTREACHED(); }
78
79 void LogVideoReceiveStreamConfig(
perkj09e71da2017-05-22 03:26:49 -070080 const webrtc::rtclog::StreamConfig&) override {
81 RTC_NOTREACHED();
ivoc14d5dbe2016-07-04 07:06:55 -070082 }
83
perkjc0876aa2017-05-22 04:08:28 -070084 void LogVideoSendStreamConfig(const webrtc::rtclog::StreamConfig&) override {
85 RTC_NOTREACHED();
ivoc14d5dbe2016-07-04 07:06:55 -070086 }
87
ivoce0928d82016-10-10 05:12:51 -070088 void LogAudioReceiveStreamConfig(
perkjac8f52d2017-05-22 09:36:28 -070089 const webrtc::rtclog::StreamConfig& config) override {
ivoce0928d82016-10-10 05:12:51 -070090 rtc::CritScope lock(&crit_);
91 if (event_log_) {
92 event_log_->LogAudioReceiveStreamConfig(config);
93 }
94 }
95
96 void LogAudioSendStreamConfig(
perkjf4726992017-05-22 10:12:26 -070097 const webrtc::rtclog::StreamConfig& config) override {
ivoce0928d82016-10-10 05:12:51 -070098 rtc::CritScope lock(&crit_);
99 if (event_log_) {
100 event_log_->LogAudioSendStreamConfig(config);
101 }
102 }
103
ivoc14d5dbe2016-07-04 07:06:55 -0700104 void LogRtpHeader(webrtc::PacketDirection direction,
ivoc14d5dbe2016-07-04 07:06:55 -0700105 const uint8_t* header,
106 size_t packet_length) override {
perkj77cd58e2017-05-30 03:52:10 -0700107 LogRtpHeader(direction, header, packet_length, PacedPacketInfo::kNotAProbe);
philipel32d00102017-02-27 02:18:46 -0800108 }
109
110 void LogRtpHeader(webrtc::PacketDirection direction,
philipel32d00102017-02-27 02:18:46 -0800111 const uint8_t* header,
112 size_t packet_length,
113 int probe_cluster_id) override {
ivoc14d5dbe2016-07-04 07:06:55 -0700114 rtc::CritScope lock(&crit_);
115 if (event_log_) {
perkj77cd58e2017-05-30 03:52:10 -0700116 event_log_->LogRtpHeader(direction, header, packet_length,
philipel32d00102017-02-27 02:18:46 -0800117 probe_cluster_id);
ivoc14d5dbe2016-07-04 07:06:55 -0700118 }
119 }
120
121 void LogRtcpPacket(webrtc::PacketDirection direction,
ivoc14d5dbe2016-07-04 07:06:55 -0700122 const uint8_t* packet,
123 size_t length) override {
124 rtc::CritScope lock(&crit_);
125 if (event_log_) {
perkj77cd58e2017-05-30 03:52:10 -0700126 event_log_->LogRtcpPacket(direction, packet, length);
ivoc14d5dbe2016-07-04 07:06:55 -0700127 }
128 }
129
130 void LogAudioPlayout(uint32_t ssrc) override {
131 rtc::CritScope lock(&crit_);
132 if (event_log_) {
133 event_log_->LogAudioPlayout(ssrc);
134 }
135 }
136
terelius424e6cf2017-02-20 05:14:41 -0800137 void LogLossBasedBweUpdate(int32_t bitrate_bps,
ivoc14d5dbe2016-07-04 07:06:55 -0700138 uint8_t fraction_loss,
139 int32_t total_packets) override {
140 rtc::CritScope lock(&crit_);
141 if (event_log_) {
terelius424e6cf2017-02-20 05:14:41 -0800142 event_log_->LogLossBasedBweUpdate(bitrate_bps, fraction_loss,
143 total_packets);
ivoc14d5dbe2016-07-04 07:06:55 -0700144 }
145 }
146
terelius424e6cf2017-02-20 05:14:41 -0800147 void LogDelayBasedBweUpdate(int32_t bitrate_bps,
terelius0baf55d2017-02-17 03:38:28 -0800148 BandwidthUsage detector_state) override {
149 rtc::CritScope lock(&crit_);
150 if (event_log_) {
terelius424e6cf2017-02-20 05:14:41 -0800151 event_log_->LogDelayBasedBweUpdate(bitrate_bps, detector_state);
terelius0baf55d2017-02-17 03:38:28 -0800152 }
153 }
154
minyue4b7c9522017-01-24 04:54:59 -0800155 void LogAudioNetworkAdaptation(
michaeltcde46b72017-04-06 05:59:10 -0700156 const AudioEncoderRuntimeConfig& config) override {
minyue4b7c9522017-01-24 04:54:59 -0800157 rtc::CritScope lock(&crit_);
158 if (event_log_) {
159 event_log_->LogAudioNetworkAdaptation(config);
160 }
161 }
162
philipel32d00102017-02-27 02:18:46 -0800163 void LogProbeClusterCreated(int id,
164 int bitrate_bps,
165 int min_probes,
166 int min_bytes) override {
167 rtc::CritScope lock(&crit_);
168 if (event_log_) {
169 event_log_->LogProbeClusterCreated(id, bitrate_bps, min_probes,
170 min_bytes);
171 }
172 };
173
174 void LogProbeResultSuccess(int id, int bitrate_bps) override {
175 rtc::CritScope lock(&crit_);
176 if (event_log_) {
177 event_log_->LogProbeResultSuccess(id, bitrate_bps);
178 }
179 };
180
181 void LogProbeResultFailure(int id,
182 ProbeFailureReason failure_reason) override {
183 rtc::CritScope lock(&crit_);
184 if (event_log_) {
185 event_log_->LogProbeResultFailure(id, failure_reason);
186 }
187 };
188
ivoc14d5dbe2016-07-04 07:06:55 -0700189 void SetEventLog(RtcEventLog* event_log) {
190 rtc::CritScope lock(&crit_);
191 event_log_ = event_log;
192 }
193
194 private:
195 rtc::CriticalSection crit_;
196 RtcEventLog* event_log_ GUARDED_BY(crit_);
197 RTC_DISALLOW_COPY_AND_ASSIGN(RtcEventLogProxy);
198};
199
michaelt9332b7d2016-11-30 07:51:13 -0800200class RtcpRttStatsProxy final : public RtcpRttStats {
201 public:
202 RtcpRttStatsProxy() : rtcp_rtt_stats_(nullptr) {}
203
204 void OnRttUpdate(int64_t rtt) override {
205 rtc::CritScope lock(&crit_);
206 if (rtcp_rtt_stats_)
207 rtcp_rtt_stats_->OnRttUpdate(rtt);
208 }
209
210 int64_t LastProcessedRtt() const override {
211 rtc::CritScope lock(&crit_);
212 if (!rtcp_rtt_stats_)
213 return 0;
214 return rtcp_rtt_stats_->LastProcessedRtt();
215 }
216
217 void SetRtcpRttStats(RtcpRttStats* rtcp_rtt_stats) {
218 rtc::CritScope lock(&crit_);
219 rtcp_rtt_stats_ = rtcp_rtt_stats;
220 }
221
222 private:
223 rtc::CriticalSection crit_;
224 RtcpRttStats* rtcp_rtt_stats_ GUARDED_BY(crit_);
225 RTC_DISALLOW_COPY_AND_ASSIGN(RtcpRttStatsProxy);
226};
227
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100228class TransportFeedbackProxy : public TransportFeedbackObserver {
229 public:
230 TransportFeedbackProxy() : feedback_observer_(nullptr) {
231 pacer_thread_.DetachFromThread();
232 network_thread_.DetachFromThread();
233 }
234
235 void SetTransportFeedbackObserver(
236 TransportFeedbackObserver* feedback_observer) {
237 RTC_DCHECK(thread_checker_.CalledOnValidThread());
238 rtc::CritScope lock(&crit_);
239 feedback_observer_ = feedback_observer;
240 }
241
242 // Implements TransportFeedbackObserver.
elad.alond12a8e12017-03-23 11:04:48 -0700243 void AddPacket(uint32_t ssrc,
244 uint16_t sequence_number,
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100245 size_t length,
philipel8aadd502017-02-23 02:56:13 -0800246 const PacedPacketInfo& pacing_info) override {
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100247 RTC_DCHECK(pacer_thread_.CalledOnValidThread());
248 rtc::CritScope lock(&crit_);
249 if (feedback_observer_)
elad.alond12a8e12017-03-23 11:04:48 -0700250 feedback_observer_->AddPacket(ssrc, sequence_number, length, pacing_info);
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100251 }
philipel8aadd502017-02-23 02:56:13 -0800252
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100253 void OnTransportFeedback(const rtcp::TransportFeedback& feedback) override {
254 RTC_DCHECK(network_thread_.CalledOnValidThread());
255 rtc::CritScope lock(&crit_);
michaelt9960bb12016-10-18 09:40:34 -0700256 if (feedback_observer_)
257 feedback_observer_->OnTransportFeedback(feedback);
Stefan Holmer60e43462016-09-07 09:58:20 +0200258 }
elad.alonf9490002017-03-06 05:32:21 -0800259 std::vector<PacketFeedback> GetTransportFeedbackVector() const override {
Stefan Holmer60e43462016-09-07 09:58:20 +0200260 RTC_NOTREACHED();
elad.alonf9490002017-03-06 05:32:21 -0800261 return std::vector<PacketFeedback>();
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100262 }
263
264 private:
265 rtc::CriticalSection crit_;
266 rtc::ThreadChecker thread_checker_;
267 rtc::ThreadChecker pacer_thread_;
268 rtc::ThreadChecker network_thread_;
269 TransportFeedbackObserver* feedback_observer_ GUARDED_BY(&crit_);
270};
271
272class TransportSequenceNumberProxy : public TransportSequenceNumberAllocator {
273 public:
274 TransportSequenceNumberProxy() : seq_num_allocator_(nullptr) {
275 pacer_thread_.DetachFromThread();
276 }
277
278 void SetSequenceNumberAllocator(
279 TransportSequenceNumberAllocator* seq_num_allocator) {
280 RTC_DCHECK(thread_checker_.CalledOnValidThread());
281 rtc::CritScope lock(&crit_);
282 seq_num_allocator_ = seq_num_allocator;
283 }
284
285 // Implements TransportSequenceNumberAllocator.
286 uint16_t AllocateSequenceNumber() override {
287 RTC_DCHECK(pacer_thread_.CalledOnValidThread());
288 rtc::CritScope lock(&crit_);
289 if (!seq_num_allocator_)
290 return 0;
291 return seq_num_allocator_->AllocateSequenceNumber();
292 }
293
294 private:
295 rtc::CriticalSection crit_;
296 rtc::ThreadChecker thread_checker_;
297 rtc::ThreadChecker pacer_thread_;
298 TransportSequenceNumberAllocator* seq_num_allocator_ GUARDED_BY(&crit_);
299};
300
301class RtpPacketSenderProxy : public RtpPacketSender {
302 public:
kwiberg55b97fe2016-01-28 05:22:45 -0800303 RtpPacketSenderProxy() : rtp_packet_sender_(nullptr) {}
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100304
305 void SetPacketSender(RtpPacketSender* rtp_packet_sender) {
306 RTC_DCHECK(thread_checker_.CalledOnValidThread());
307 rtc::CritScope lock(&crit_);
308 rtp_packet_sender_ = rtp_packet_sender;
309 }
310
311 // Implements RtpPacketSender.
312 void InsertPacket(Priority priority,
313 uint32_t ssrc,
314 uint16_t sequence_number,
315 int64_t capture_time_ms,
316 size_t bytes,
317 bool retransmission) override {
318 rtc::CritScope lock(&crit_);
319 if (rtp_packet_sender_) {
320 rtp_packet_sender_->InsertPacket(priority, ssrc, sequence_number,
321 capture_time_ms, bytes, retransmission);
322 }
323 }
324
325 private:
326 rtc::ThreadChecker thread_checker_;
327 rtc::CriticalSection crit_;
328 RtpPacketSender* rtp_packet_sender_ GUARDED_BY(&crit_);
329};
330
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000331class VoERtcpObserver : public RtcpBandwidthObserver {
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000332 public:
stefan7de8d642017-02-07 07:14:08 -0800333 explicit VoERtcpObserver(Channel* owner)
334 : owner_(owner), bandwidth_observer_(nullptr) {}
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000335 virtual ~VoERtcpObserver() {}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000336
stefan7de8d642017-02-07 07:14:08 -0800337 void SetBandwidthObserver(RtcpBandwidthObserver* bandwidth_observer) {
338 rtc::CritScope lock(&crit_);
339 bandwidth_observer_ = bandwidth_observer;
340 }
341
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000342 void OnReceivedEstimatedBitrate(uint32_t bitrate) override {
stefan7de8d642017-02-07 07:14:08 -0800343 rtc::CritScope lock(&crit_);
344 if (bandwidth_observer_) {
345 bandwidth_observer_->OnReceivedEstimatedBitrate(bitrate);
346 }
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000347 }
348
kjellander@webrtc.org14665ff2015-03-04 12:58:35 +0000349 void OnReceivedRtcpReceiverReport(const ReportBlockList& report_blocks,
350 int64_t rtt,
351 int64_t now_ms) override {
stefan7de8d642017-02-07 07:14:08 -0800352 {
353 rtc::CritScope lock(&crit_);
354 if (bandwidth_observer_) {
355 bandwidth_observer_->OnReceivedRtcpReceiverReport(report_blocks, rtt,
356 now_ms);
357 }
358 }
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000359 // TODO(mflodman): Do we need to aggregate reports here or can we jut send
360 // what we get? I.e. do we ever get multiple reports bundled into one RTCP
361 // report for VoiceEngine?
362 if (report_blocks.empty())
363 return;
364
365 int fraction_lost_aggregate = 0;
366 int total_number_of_packets = 0;
367
368 // If receiving multiple report blocks, calculate the weighted average based
369 // on the number of packets a report refers to.
370 for (ReportBlockList::const_iterator block_it = report_blocks.begin();
371 block_it != report_blocks.end(); ++block_it) {
372 // Find the previous extended high sequence number for this remote SSRC,
373 // to calculate the number of RTP packets this report refers to. Ignore if
374 // we haven't seen this SSRC before.
375 std::map<uint32_t, uint32_t>::iterator seq_num_it =
376 extended_max_sequence_number_.find(block_it->sourceSSRC);
377 int number_of_packets = 0;
378 if (seq_num_it != extended_max_sequence_number_.end()) {
379 number_of_packets = block_it->extendedHighSeqNum - seq_num_it->second;
380 }
381 fraction_lost_aggregate += number_of_packets * block_it->fractionLost;
382 total_number_of_packets += number_of_packets;
383
384 extended_max_sequence_number_[block_it->sourceSSRC] =
385 block_it->extendedHighSeqNum;
386 }
387 int weighted_fraction_lost = 0;
388 if (total_number_of_packets > 0) {
kwiberg55b97fe2016-01-28 05:22:45 -0800389 weighted_fraction_lost =
390 (fraction_lost_aggregate + total_number_of_packets / 2) /
391 total_number_of_packets;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000392 }
elad.alond12a8e12017-03-23 11:04:48 -0700393 owner_->OnUplinkPacketLossRate(weighted_fraction_lost / 255.0f);
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000394 }
395
396 private:
397 Channel* owner_;
mflodman@webrtc.org0a7d4ee2015-02-17 12:57:14 +0000398 // Maps remote side ssrc to extended highest sequence number received.
399 std::map<uint32_t, uint32_t> extended_max_sequence_number_;
stefan7de8d642017-02-07 07:14:08 -0800400 rtc::CriticalSection crit_;
401 RtcpBandwidthObserver* bandwidth_observer_ GUARDED_BY(crit_);
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +0000402};
403
henrikaec6fbd22017-03-31 05:43:36 -0700404class Channel::ProcessAndEncodeAudioTask : public rtc::QueuedTask {
405 public:
406 ProcessAndEncodeAudioTask(std::unique_ptr<AudioFrame> audio_frame,
407 Channel* channel)
408 : audio_frame_(std::move(audio_frame)), channel_(channel) {
409 RTC_DCHECK(channel_);
410 }
411
412 private:
413 bool Run() override {
414 RTC_DCHECK_RUN_ON(channel_->encoder_queue_);
415 channel_->ProcessAndEncodeAudioOnTaskQueue(audio_frame_.get());
416 return true;
417 }
418
419 std::unique_ptr<AudioFrame> audio_frame_;
420 Channel* const channel_;
421};
422
kwiberg55b97fe2016-01-28 05:22:45 -0800423int32_t Channel::SendData(FrameType frameType,
424 uint8_t payloadType,
425 uint32_t timeStamp,
426 const uint8_t* payloadData,
427 size_t payloadSize,
428 const RTPFragmentationHeader* fragmentation) {
henrikaec6fbd22017-03-31 05:43:36 -0700429 RTC_DCHECK_RUN_ON(encoder_queue_);
kwiberg55b97fe2016-01-28 05:22:45 -0800430 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
431 "Channel::SendData(frameType=%u, payloadType=%u, timeStamp=%u,"
432 " payloadSize=%" PRIuS ", fragmentation=0x%x)",
433 frameType, payloadType, timeStamp, payloadSize, fragmentation);
niklase@google.com470e71d2011-07-07 08:21:25 +0000434
kwiberg55b97fe2016-01-28 05:22:45 -0800435 if (_includeAudioLevelIndication) {
436 // Store current audio level in the RTP/RTCP module.
437 // The level will be used in combination with voice-activity state
438 // (frameType) to add an RTP header extension
henrik.lundin50499422016-11-29 04:26:24 -0800439 _rtpRtcpModule->SetAudioLevel(rms_level_.Average());
kwiberg55b97fe2016-01-28 05:22:45 -0800440 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000441
kwiberg55b97fe2016-01-28 05:22:45 -0800442 // Push data from ACM to RTP/RTCP-module to deliver audio frame for
443 // packetization.
444 // This call will trigger Transport::SendPacket() from the RTP/RTCP module.
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700445 if (!_rtpRtcpModule->SendOutgoingData(
kwiberg55b97fe2016-01-28 05:22:45 -0800446 (FrameType&)frameType, payloadType, timeStamp,
447 // Leaving the time when this frame was
448 // received from the capture device as
449 // undefined for voice for now.
Sergey Ulanov525df3f2016-08-02 17:46:41 -0700450 -1, payloadData, payloadSize, fragmentation, nullptr, nullptr)) {
kwiberg55b97fe2016-01-28 05:22:45 -0800451 _engineStatisticsPtr->SetLastError(
452 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
453 "Channel::SendData() failed to send data to RTP/RTCP module");
454 return -1;
455 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000456
kwiberg55b97fe2016-01-28 05:22:45 -0800457 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000458}
459
stefan1d8a5062015-10-02 03:39:33 -0700460bool Channel::SendRtp(const uint8_t* data,
461 size_t len,
462 const PacketOptions& options) {
kwiberg55b97fe2016-01-28 05:22:45 -0800463 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
464 "Channel::SendPacket(channel=%d, len=%" PRIuS ")", len);
niklase@google.com470e71d2011-07-07 08:21:25 +0000465
kwiberg55b97fe2016-01-28 05:22:45 -0800466 rtc::CritScope cs(&_callbackCritSect);
wu@webrtc.orgfb648da2013-10-18 21:10:51 +0000467
kwiberg55b97fe2016-01-28 05:22:45 -0800468 if (_transportPtr == NULL) {
469 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
470 "Channel::SendPacket() failed to send RTP packet due to"
471 " invalid transport object");
472 return false;
473 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000474
kwiberg55b97fe2016-01-28 05:22:45 -0800475 uint8_t* bufferToSendPtr = (uint8_t*)data;
476 size_t bufferLength = len;
niklase@google.com470e71d2011-07-07 08:21:25 +0000477
kwiberg55b97fe2016-01-28 05:22:45 -0800478 if (!_transportPtr->SendRtp(bufferToSendPtr, bufferLength, options)) {
479 std::string transport_name =
480 _externalTransport ? "external transport" : "WebRtc sockets";
481 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
482 "Channel::SendPacket() RTP transmission using %s failed",
483 transport_name.c_str());
484 return false;
485 }
486 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000487}
488
kwiberg55b97fe2016-01-28 05:22:45 -0800489bool Channel::SendRtcp(const uint8_t* data, size_t len) {
490 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
491 "Channel::SendRtcp(len=%" PRIuS ")", len);
niklase@google.com470e71d2011-07-07 08:21:25 +0000492
kwiberg55b97fe2016-01-28 05:22:45 -0800493 rtc::CritScope cs(&_callbackCritSect);
494 if (_transportPtr == NULL) {
495 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
496 "Channel::SendRtcp() failed to send RTCP packet"
497 " due to invalid transport object");
498 return false;
499 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000500
kwiberg55b97fe2016-01-28 05:22:45 -0800501 uint8_t* bufferToSendPtr = (uint8_t*)data;
502 size_t bufferLength = len;
niklase@google.com470e71d2011-07-07 08:21:25 +0000503
kwiberg55b97fe2016-01-28 05:22:45 -0800504 int n = _transportPtr->SendRtcp(bufferToSendPtr, bufferLength);
505 if (n < 0) {
506 std::string transport_name =
507 _externalTransport ? "external transport" : "WebRtc sockets";
508 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
509 "Channel::SendRtcp() transmission using %s failed",
510 transport_name.c_str());
511 return false;
512 }
513 return true;
niklase@google.com470e71d2011-07-07 08:21:25 +0000514}
515
kwiberg55b97fe2016-01-28 05:22:45 -0800516void Channel::OnIncomingSSRCChanged(uint32_t ssrc) {
517 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
518 "Channel::OnIncomingSSRCChanged(SSRC=%d)", ssrc);
niklase@google.com470e71d2011-07-07 08:21:25 +0000519
kwiberg55b97fe2016-01-28 05:22:45 -0800520 // Update ssrc so that NTP for AV sync can be updated.
521 _rtpRtcpModule->SetRemoteSSRC(ssrc);
niklase@google.com470e71d2011-07-07 08:21:25 +0000522}
523
Peter Boströmac547a62015-09-17 23:03:57 +0200524void Channel::OnIncomingCSRCChanged(uint32_t CSRC, bool added) {
525 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
526 "Channel::OnIncomingCSRCChanged(CSRC=%d, added=%d)", CSRC,
527 added);
niklase@google.com470e71d2011-07-07 08:21:25 +0000528}
529
Peter Boströmac547a62015-09-17 23:03:57 +0200530int32_t Channel::OnInitializeDecoder(
pbos@webrtc.org92135212013-05-14 08:31:39 +0000531 int8_t payloadType,
leozwang@webrtc.org813e4b02012-03-01 18:34:25 +0000532 const char payloadName[RTP_PAYLOAD_NAME_SIZE],
pbos@webrtc.org92135212013-05-14 08:31:39 +0000533 int frequency,
Peter Kasting69558702016-01-12 16:26:35 -0800534 size_t channels,
Peter Boströmac547a62015-09-17 23:03:57 +0200535 uint32_t rate) {
kwiberg55b97fe2016-01-28 05:22:45 -0800536 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
537 "Channel::OnInitializeDecoder(payloadType=%d, "
538 "payloadName=%s, frequency=%u, channels=%" PRIuS ", rate=%u)",
539 payloadType, payloadName, frequency, channels, rate);
niklase@google.com470e71d2011-07-07 08:21:25 +0000540
kwiberg55b97fe2016-01-28 05:22:45 -0800541 CodecInst receiveCodec = {0};
542 CodecInst dummyCodec = {0};
niklase@google.com470e71d2011-07-07 08:21:25 +0000543
kwiberg55b97fe2016-01-28 05:22:45 -0800544 receiveCodec.pltype = payloadType;
545 receiveCodec.plfreq = frequency;
546 receiveCodec.channels = channels;
547 receiveCodec.rate = rate;
548 strncpy(receiveCodec.plname, payloadName, RTP_PAYLOAD_NAME_SIZE - 1);
andrew@webrtc.orgae1a58b2013-01-22 04:44:30 +0000549
kwiberg55b97fe2016-01-28 05:22:45 -0800550 audio_coding_->Codec(payloadName, &dummyCodec, frequency, channels);
551 receiveCodec.pacsize = dummyCodec.pacsize;
niklase@google.com470e71d2011-07-07 08:21:25 +0000552
kwiberg55b97fe2016-01-28 05:22:45 -0800553 // Register the new codec to the ACM
kwibergda2bf4e2016-10-24 13:47:09 -0700554 if (!audio_coding_->RegisterReceiveCodec(receiveCodec.pltype,
555 CodecInstToSdp(receiveCodec))) {
kwiberg55b97fe2016-01-28 05:22:45 -0800556 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
557 "Channel::OnInitializeDecoder() invalid codec ("
558 "pt=%d, name=%s) received - 1",
559 payloadType, payloadName);
560 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR);
561 return -1;
562 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000563
kwiberg55b97fe2016-01-28 05:22:45 -0800564 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000565}
566
kwiberg55b97fe2016-01-28 05:22:45 -0800567int32_t Channel::OnReceivedPayloadData(const uint8_t* payloadData,
568 size_t payloadSize,
569 const WebRtcRTPHeader* rtpHeader) {
570 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
571 "Channel::OnReceivedPayloadData(payloadSize=%" PRIuS
572 ","
573 " payloadType=%u, audioChannel=%" PRIuS ")",
574 payloadSize, rtpHeader->header.payloadType,
575 rtpHeader->type.Audio.channel);
niklase@google.com470e71d2011-07-07 08:21:25 +0000576
kwiberg55b97fe2016-01-28 05:22:45 -0800577 if (!channel_state_.Get().playing) {
578 // Avoid inserting into NetEQ when we are not playing. Count the
579 // packet as discarded.
580 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
581 "received packet is discarded since playing is not"
582 " activated");
niklase@google.com470e71d2011-07-07 08:21:25 +0000583 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -0800584 }
585
586 // Push the incoming payload (parsed and ready for decoding) into the ACM
587 if (audio_coding_->IncomingPacket(payloadData, payloadSize, *rtpHeader) !=
588 0) {
589 _engineStatisticsPtr->SetLastError(
590 VE_AUDIO_CODING_MODULE_ERROR, kTraceWarning,
591 "Channel::OnReceivedPayloadData() unable to push data to the ACM");
592 return -1;
593 }
594
kwiberg55b97fe2016-01-28 05:22:45 -0800595 int64_t round_trip_time = 0;
596 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), &round_trip_time, NULL, NULL,
597 NULL);
598
599 std::vector<uint16_t> nack_list = audio_coding_->GetNackList(round_trip_time);
600 if (!nack_list.empty()) {
601 // Can't use nack_list.data() since it's not supported by all
602 // compilers.
603 ResendPackets(&(nack_list[0]), static_cast<int>(nack_list.size()));
604 }
605 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000606}
607
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000608bool Channel::OnRecoveredPacket(const uint8_t* rtp_packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000609 size_t rtp_packet_length) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +0000610 RTPHeader header;
611 if (!rtp_header_parser_->Parse(rtp_packet, rtp_packet_length, &header)) {
612 WEBRTC_TRACE(kTraceDebug, webrtc::kTraceVoice, _channelId,
613 "IncomingPacket invalid RTP header");
614 return false;
615 }
616 header.payload_type_frequency =
617 rtp_payload_registry_->GetPayloadTypeFrequency(header.payloadType);
618 if (header.payload_type_frequency < 0)
619 return false;
620 return ReceivePacket(rtp_packet, rtp_packet_length, header, false);
621}
622
henrik.lundin42dda502016-05-18 05:36:01 -0700623MixerParticipant::AudioFrameInfo Channel::GetAudioFrameWithMuted(
624 int32_t id,
625 AudioFrame* audioFrame) {
ivoc14d5dbe2016-07-04 07:06:55 -0700626 unsigned int ssrc;
nisse7d59f6b2017-02-21 03:40:24 -0800627 RTC_CHECK_EQ(GetRemoteSSRC(ssrc), 0);
ivoc14d5dbe2016-07-04 07:06:55 -0700628 event_log_proxy_->LogAudioPlayout(ssrc);
kwiberg55b97fe2016-01-28 05:22:45 -0800629 // Get 10ms raw PCM data from the ACM (mixer limits output frequency)
henrik.lundind4ccb002016-05-17 12:21:55 -0700630 bool muted;
631 if (audio_coding_->PlayoutData10Ms(audioFrame->sample_rate_hz_, audioFrame,
632 &muted) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -0800633 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
634 "Channel::GetAudioFrame() PlayoutData10Ms() failed!");
635 // In all likelihood, the audio in this frame is garbage. We return an
636 // error so that the audio mixer module doesn't add it to the mix. As
637 // a result, it won't be played out and the actions skipped here are
638 // irrelevant.
henrik.lundin42dda502016-05-18 05:36:01 -0700639 return MixerParticipant::AudioFrameInfo::kError;
kwiberg55b97fe2016-01-28 05:22:45 -0800640 }
henrik.lundina89ab962016-05-18 08:52:45 -0700641
642 if (muted) {
643 // TODO(henrik.lundin): We should be able to do better than this. But we
644 // will have to go through all the cases below where the audio samples may
645 // be used, and handle the muted case in some way.
aleloi6321b492016-12-05 01:46:09 -0800646 AudioFrameOperations::Mute(audioFrame);
henrik.lundina89ab962016-05-18 08:52:45 -0700647 }
kwiberg55b97fe2016-01-28 05:22:45 -0800648
kwiberg55b97fe2016-01-28 05:22:45 -0800649 // Convert module ID to internal VoE channel ID
650 audioFrame->id_ = VoEChannelId(audioFrame->id_);
651 // Store speech type for dead-or-alive detection
652 _outputSpeechType = audioFrame->speech_type_;
653
654 ChannelState::State state = channel_state_.Get();
655
kwiberg55b97fe2016-01-28 05:22:45 -0800656 {
657 // Pass the audio buffers to an optional sink callback, before applying
658 // scaling/panning, as that applies to the mix operation.
659 // External recipients of the audio (e.g. via AudioTrack), will do their
660 // own mixing/dynamic processing.
661 rtc::CritScope cs(&_callbackCritSect);
662 if (audio_sink_) {
663 AudioSinkInterface::Data data(
yujo36b1a5f2017-06-12 12:45:32 -0700664 audioFrame->data(), audioFrame->samples_per_channel_,
kwiberg55b97fe2016-01-28 05:22:45 -0800665 audioFrame->sample_rate_hz_, audioFrame->num_channels_,
666 audioFrame->timestamp_);
667 audio_sink_->OnData(data);
668 }
669 }
670
671 float output_gain = 1.0f;
kwiberg55b97fe2016-01-28 05:22:45 -0800672 {
673 rtc::CritScope cs(&volume_settings_critsect_);
674 output_gain = _outputGain;
kwiberg55b97fe2016-01-28 05:22:45 -0800675 }
676
677 // Output volume scaling
678 if (output_gain < 0.99f || output_gain > 1.01f) {
solenberg8d73f8c2017-03-08 01:52:20 -0800679 // TODO(solenberg): Combine with mute state - this can cause clicks!
oprypin67fdb802017-03-09 06:25:06 -0800680 AudioFrameOperations::ScaleWithSat(output_gain, audioFrame);
kwiberg55b97fe2016-01-28 05:22:45 -0800681 }
682
kwiberg55b97fe2016-01-28 05:22:45 -0800683 // Mix decoded PCM output with file if file mixing is enabled
684 if (state.output_file_playing) {
685 MixAudioWithFile(*audioFrame, audioFrame->sample_rate_hz_);
henrik.lundina89ab962016-05-18 08:52:45 -0700686 muted = false; // We may have added non-zero samples.
kwiberg55b97fe2016-01-28 05:22:45 -0800687 }
688
kwiberg55b97fe2016-01-28 05:22:45 -0800689 // Record playout if enabled
690 {
691 rtc::CritScope cs(&_fileCritSect);
692
kwiberg5a25d952016-08-17 07:31:12 -0700693 if (_outputFileRecording && output_file_recorder_) {
694 output_file_recorder_->RecordAudioToFile(*audioFrame);
kwiberg55b97fe2016-01-28 05:22:45 -0800695 }
696 }
697
698 // Measure audio level (0-9)
henrik.lundina89ab962016-05-18 08:52:45 -0700699 // TODO(henrik.lundin) Use the |muted| information here too.
zsteine76bd3a2017-07-14 12:17:49 -0700700 // TODO(deadbeef): Use RmsLevel for |_outputAudioLevel| as well (see
701 // https://crbug.com/webrtc/7517).
kwiberg55b97fe2016-01-28 05:22:45 -0800702 _outputAudioLevel.ComputeLevel(*audioFrame);
zsteine76bd3a2017-07-14 12:17:49 -0700703 // See the description for "totalAudioEnergy" in the WebRTC stats spec
704 // (https://w3c.github.io/webrtc-stats/#dom-rtcmediastreamtrackstats-totalaudioenergy)
705 // for an explanation of these formulas. In short, we need a value that can
706 // be used to compute RMS audio levels over different time intervals, by
707 // taking the difference between the results from two getStats calls. To do
708 // this, the value needs to be of units "squared sample value * time".
709 double additional_energy =
710 static_cast<double>(_outputAudioLevel.LevelFullRange()) / INT16_MAX;
711 additional_energy *= additional_energy;
712 totalOutputEnergy_ += additional_energy * kAudioSampleDurationSeconds;
713 totalOutputDuration_ += kAudioSampleDurationSeconds;
kwiberg55b97fe2016-01-28 05:22:45 -0800714
715 if (capture_start_rtp_time_stamp_ < 0 && audioFrame->timestamp_ != 0) {
716 // The first frame with a valid rtp timestamp.
717 capture_start_rtp_time_stamp_ = audioFrame->timestamp_;
718 }
719
720 if (capture_start_rtp_time_stamp_ >= 0) {
721 // audioFrame.timestamp_ should be valid from now on.
722
723 // Compute elapsed time.
724 int64_t unwrap_timestamp =
725 rtp_ts_wraparound_handler_->Unwrap(audioFrame->timestamp_);
726 audioFrame->elapsed_time_ms_ =
727 (unwrap_timestamp - capture_start_rtp_time_stamp_) /
ossue280cde2016-10-12 11:04:10 -0700728 (GetRtpTimestampRateHz() / 1000);
kwiberg55b97fe2016-01-28 05:22:45 -0800729
niklase@google.com470e71d2011-07-07 08:21:25 +0000730 {
kwiberg55b97fe2016-01-28 05:22:45 -0800731 rtc::CritScope lock(&ts_stats_lock_);
732 // Compute ntp time.
733 audioFrame->ntp_time_ms_ =
734 ntp_estimator_.Estimate(audioFrame->timestamp_);
735 // |ntp_time_ms_| won't be valid until at least 2 RTCP SRs are received.
736 if (audioFrame->ntp_time_ms_ > 0) {
737 // Compute |capture_start_ntp_time_ms_| so that
738 // |capture_start_ntp_time_ms_| + |elapsed_time_ms_| == |ntp_time_ms_|
739 capture_start_ntp_time_ms_ =
740 audioFrame->ntp_time_ms_ - audioFrame->elapsed_time_ms_;
andrew@webrtc.org60730cf2014-01-07 17:45:09 +0000741 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000742 }
kwiberg55b97fe2016-01-28 05:22:45 -0800743 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000744
henrik.lundin42dda502016-05-18 05:36:01 -0700745 return muted ? MixerParticipant::AudioFrameInfo::kMuted
746 : MixerParticipant::AudioFrameInfo::kNormal;
niklase@google.com470e71d2011-07-07 08:21:25 +0000747}
748
aleloi6c278492016-10-20 14:24:39 -0700749AudioMixer::Source::AudioFrameInfo Channel::GetAudioFrameWithInfo(
750 int sample_rate_hz,
751 AudioFrame* audio_frame) {
752 audio_frame->sample_rate_hz_ = sample_rate_hz;
aleloiaed581a2016-10-20 06:32:39 -0700753
aleloi6c278492016-10-20 14:24:39 -0700754 const auto frame_info = GetAudioFrameWithMuted(-1, audio_frame);
aleloiaed581a2016-10-20 06:32:39 -0700755
756 using FrameInfo = AudioMixer::Source::AudioFrameInfo;
757 FrameInfo new_audio_frame_info = FrameInfo::kError;
758 switch (frame_info) {
759 case MixerParticipant::AudioFrameInfo::kNormal:
760 new_audio_frame_info = FrameInfo::kNormal;
761 break;
762 case MixerParticipant::AudioFrameInfo::kMuted:
763 new_audio_frame_info = FrameInfo::kMuted;
764 break;
765 case MixerParticipant::AudioFrameInfo::kError:
766 new_audio_frame_info = FrameInfo::kError;
767 break;
768 }
aleloi6c278492016-10-20 14:24:39 -0700769 return new_audio_frame_info;
aleloiaed581a2016-10-20 06:32:39 -0700770}
771
kwiberg55b97fe2016-01-28 05:22:45 -0800772int32_t Channel::NeededFrequency(int32_t id) const {
773 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
774 "Channel::NeededFrequency(id=%d)", id);
niklase@google.com470e71d2011-07-07 08:21:25 +0000775
kwiberg55b97fe2016-01-28 05:22:45 -0800776 int highestNeeded = 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000777
kwiberg55b97fe2016-01-28 05:22:45 -0800778 // Determine highest needed receive frequency
779 int32_t receiveFrequency = audio_coding_->ReceiveFrequency();
niklase@google.com470e71d2011-07-07 08:21:25 +0000780
kwiberg55b97fe2016-01-28 05:22:45 -0800781 // Return the bigger of playout and receive frequency in the ACM.
782 if (audio_coding_->PlayoutFrequency() > receiveFrequency) {
783 highestNeeded = audio_coding_->PlayoutFrequency();
784 } else {
785 highestNeeded = receiveFrequency;
786 }
787
788 // Special case, if we're playing a file on the playout side
789 // we take that frequency into consideration as well
790 // This is not needed on sending side, since the codec will
791 // limit the spectrum anyway.
792 if (channel_state_.Get().output_file_playing) {
793 rtc::CritScope cs(&_fileCritSect);
kwiberg5a25d952016-08-17 07:31:12 -0700794 if (output_file_player_) {
795 if (output_file_player_->Frequency() > highestNeeded) {
796 highestNeeded = output_file_player_->Frequency();
kwiberg55b97fe2016-01-28 05:22:45 -0800797 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000798 }
kwiberg55b97fe2016-01-28 05:22:45 -0800799 }
niklase@google.com470e71d2011-07-07 08:21:25 +0000800
kwiberg55b97fe2016-01-28 05:22:45 -0800801 return (highestNeeded);
niklase@google.com470e71d2011-07-07 08:21:25 +0000802}
803
henrikaec6fbd22017-03-31 05:43:36 -0700804int32_t Channel::CreateChannel(Channel*& channel,
805 int32_t channelId,
806 uint32_t instanceId,
807 const VoEBase::ChannelConfig& config) {
kwiberg55b97fe2016-01-28 05:22:45 -0800808 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(instanceId, channelId),
809 "Channel::CreateChannel(channelId=%d, instanceId=%d)", channelId,
810 instanceId);
niklase@google.com470e71d2011-07-07 08:21:25 +0000811
solenberg88499ec2016-09-07 07:34:41 -0700812 channel = new Channel(channelId, instanceId, config);
kwiberg55b97fe2016-01-28 05:22:45 -0800813 if (channel == NULL) {
814 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(instanceId, channelId),
815 "Channel::CreateChannel() unable to allocate memory for"
816 " channel");
817 return -1;
818 }
819 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +0000820}
821
kwiberg55b97fe2016-01-28 05:22:45 -0800822void Channel::PlayNotification(int32_t id, uint32_t durationMs) {
823 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
824 "Channel::PlayNotification(id=%d, durationMs=%d)", id,
825 durationMs);
niklase@google.com470e71d2011-07-07 08:21:25 +0000826
kwiberg55b97fe2016-01-28 05:22:45 -0800827 // Not implement yet
niklase@google.com470e71d2011-07-07 08:21:25 +0000828}
829
kwiberg55b97fe2016-01-28 05:22:45 -0800830void Channel::RecordNotification(int32_t id, uint32_t durationMs) {
831 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
832 "Channel::RecordNotification(id=%d, durationMs=%d)", id,
833 durationMs);
niklase@google.com470e71d2011-07-07 08:21:25 +0000834
kwiberg55b97fe2016-01-28 05:22:45 -0800835 // Not implement yet
niklase@google.com470e71d2011-07-07 08:21:25 +0000836}
837
kwiberg55b97fe2016-01-28 05:22:45 -0800838void Channel::PlayFileEnded(int32_t id) {
839 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
840 "Channel::PlayFileEnded(id=%d)", id);
niklase@google.com470e71d2011-07-07 08:21:25 +0000841
kwiberg55b97fe2016-01-28 05:22:45 -0800842 if (id == _inputFilePlayerId) {
843 channel_state_.SetInputFilePlaying(false);
844 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
845 "Channel::PlayFileEnded() => input file player module is"
niklase@google.com470e71d2011-07-07 08:21:25 +0000846 " shutdown");
kwiberg55b97fe2016-01-28 05:22:45 -0800847 } else if (id == _outputFilePlayerId) {
848 channel_state_.SetOutputFilePlaying(false);
849 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
850 "Channel::PlayFileEnded() => output file player module is"
851 " shutdown");
852 }
853}
854
855void Channel::RecordFileEnded(int32_t id) {
856 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
857 "Channel::RecordFileEnded(id=%d)", id);
858
859 assert(id == _outputFileRecorderId);
860
861 rtc::CritScope cs(&_fileCritSect);
862
863 _outputFileRecording = false;
864 WEBRTC_TRACE(kTraceStateInfo, kTraceVoice, VoEId(_instanceId, _channelId),
865 "Channel::RecordFileEnded() => output file recorder module is"
866 " shutdown");
niklase@google.com470e71d2011-07-07 08:21:25 +0000867}
868
pbos@webrtc.org92135212013-05-14 08:31:39 +0000869Channel::Channel(int32_t channelId,
minyue@webrtc.orge509f942013-09-12 17:03:00 +0000870 uint32_t instanceId,
solenberg88499ec2016-09-07 07:34:41 -0700871 const VoEBase::ChannelConfig& config)
tommi31fc21f2016-01-21 10:37:37 -0800872 : _instanceId(instanceId),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100873 _channelId(channelId),
ivoc14d5dbe2016-07-04 07:06:55 -0700874 event_log_proxy_(new RtcEventLogProxy()),
michaelt9332b7d2016-11-30 07:51:13 -0800875 rtcp_rtt_stats_proxy_(new RtcpRttStatsProxy()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100876 rtp_header_parser_(RtpHeaderParser::Create()),
magjedf3feeff2016-11-25 06:40:25 -0800877 rtp_payload_registry_(new RTPPayloadRegistry()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100878 rtp_receive_statistics_(
879 ReceiveStatistics::Create(Clock::GetRealTimeClock())),
880 rtp_receiver_(
881 RtpReceiver::CreateAudioReceiver(Clock::GetRealTimeClock(),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100882 this,
883 this,
884 rtp_payload_registry_.get())),
danilchap799a9d02016-09-22 03:36:27 -0700885 telephone_event_handler_(rtp_receiver_->GetTelephoneEventHandler()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100886 _outputAudioLevel(),
887 _externalTransport(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100888 // Avoid conflict with other channels by adding 1024 - 1026,
889 // won't use as much as 1024 channels.
890 _inputFilePlayerId(VoEModuleId(instanceId, channelId) + 1024),
891 _outputFilePlayerId(VoEModuleId(instanceId, channelId) + 1025),
892 _outputFileRecorderId(VoEModuleId(instanceId, channelId) + 1026),
893 _outputFileRecording(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100894 _timeStamp(0), // This is just an offset, RTP module will add it's own
895 // random offset
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100896 ntp_estimator_(Clock::GetRealTimeClock()),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100897 playout_timestamp_rtp_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100898 playout_delay_ms_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100899 send_sequence_number_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100900 rtp_ts_wraparound_handler_(new rtc::TimestampWrapAroundHandler()),
901 capture_start_rtp_time_stamp_(-1),
902 capture_start_ntp_time_ms_(-1),
903 _engineStatisticsPtr(NULL),
904 _outputMixerPtr(NULL),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100905 _moduleProcessThreadPtr(NULL),
906 _audioDeviceModulePtr(NULL),
907 _voiceEngineObserverPtr(NULL),
908 _callbackCritSectPtr(NULL),
909 _transportPtr(NULL),
solenberg1c2af8e2016-03-24 10:36:00 -0700910 input_mute_(false),
911 previous_frame_muted_(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100912 _outputGain(1.0f),
solenberg8d73f8c2017-03-08 01:52:20 -0800913 _mixFileWithMicrophone(false),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100914 _includeAudioLevelIndication(false),
nisse284542b2017-01-10 08:58:32 -0800915 transport_overhead_per_packet_(0),
916 rtp_overhead_per_packet_(0),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100917 _outputSpeechType(AudioFrame::kNormalSpeech),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100918 restored_packet_in_use_(false),
919 rtcp_observer_(new VoERtcpObserver(this)),
Stefan Holmerb86d4e42015-12-07 10:26:18 +0100920 associate_send_channel_(ChannelOwner(nullptr)),
solenberg88499ec2016-09-07 07:34:41 -0700921 pacing_enabled_(config.enable_voice_pacing),
stefanbba9dec2016-02-01 04:39:55 -0800922 feedback_observer_proxy_(new TransportFeedbackProxy()),
923 seq_num_allocator_proxy_(new TransportSequenceNumberProxy()),
ossu29b1a8d2016-06-13 07:34:51 -0700924 rtp_packet_sender_proxy_(new RtpPacketSenderProxy()),
Erik Språng737336d2016-07-29 12:59:36 +0200925 retransmission_rate_limiter_(new RateLimiter(Clock::GetRealTimeClock(),
926 kMaxRetransmissionWindowMs)),
elad.alond12a8e12017-03-23 11:04:48 -0700927 decoder_factory_(config.acm_config.decoder_factory),
elad.alon28770482017-03-28 05:03:55 -0700928 use_twcc_plr_for_ana_(
929 webrtc::field_trial::FindFullName("UseTwccPlrForAna") == "Enabled") {
kwiberg55b97fe2016-01-28 05:22:45 -0800930 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
931 "Channel::Channel() - ctor");
solenberg88499ec2016-09-07 07:34:41 -0700932 AudioCodingModule::Config acm_config(config.acm_config);
kwiberg55b97fe2016-01-28 05:22:45 -0800933 acm_config.id = VoEModuleId(instanceId, channelId);
henrik.lundina89ab962016-05-18 08:52:45 -0700934 acm_config.neteq_config.enable_muted_state = true;
kwiberg55b97fe2016-01-28 05:22:45 -0800935 audio_coding_.reset(AudioCodingModule::Create(acm_config));
Henrik Lundin64dad832015-05-11 12:44:23 +0200936
kwiberg55b97fe2016-01-28 05:22:45 -0800937 _outputAudioLevel.Clear();
niklase@google.com470e71d2011-07-07 08:21:25 +0000938
kwiberg55b97fe2016-01-28 05:22:45 -0800939 RtpRtcp::Configuration configuration;
940 configuration.audio = true;
941 configuration.outgoing_transport = this;
michaeltbf65be52016-12-15 06:24:49 -0800942 configuration.overhead_observer = this;
kwiberg55b97fe2016-01-28 05:22:45 -0800943 configuration.receive_statistics = rtp_receive_statistics_.get();
944 configuration.bandwidth_callback = rtcp_observer_.get();
stefanbba9dec2016-02-01 04:39:55 -0800945 if (pacing_enabled_) {
946 configuration.paced_sender = rtp_packet_sender_proxy_.get();
947 configuration.transport_sequence_number_allocator =
948 seq_num_allocator_proxy_.get();
949 configuration.transport_feedback_callback = feedback_observer_proxy_.get();
950 }
ivoc14d5dbe2016-07-04 07:06:55 -0700951 configuration.event_log = &(*event_log_proxy_);
michaelt9332b7d2016-11-30 07:51:13 -0800952 configuration.rtt_stats = &(*rtcp_rtt_stats_proxy_);
Erik Språng737336d2016-07-29 12:59:36 +0200953 configuration.retransmission_rate_limiter =
954 retransmission_rate_limiter_.get();
pwestin@webrtc.org2853dde2012-05-11 11:08:54 +0000955
kwiberg55b97fe2016-01-28 05:22:45 -0800956 _rtpRtcpModule.reset(RtpRtcp::CreateRtpRtcp(configuration));
Peter Boström3dd5d1d2016-02-25 16:56:48 +0100957 _rtpRtcpModule->SetSendingMediaStatus(false);
niklase@google.com470e71d2011-07-07 08:21:25 +0000958}
959
kwiberg55b97fe2016-01-28 05:22:45 -0800960Channel::~Channel() {
tommi0a2391f2017-03-21 02:31:51 -0700961 RTC_DCHECK(!channel_state_.Get().sending);
962 RTC_DCHECK(!channel_state_.Get().playing);
niklase@google.com470e71d2011-07-07 08:21:25 +0000963}
964
kwiberg55b97fe2016-01-28 05:22:45 -0800965int32_t Channel::Init() {
tommi0a2391f2017-03-21 02:31:51 -0700966 RTC_DCHECK(construction_thread_.CalledOnValidThread());
kwiberg55b97fe2016-01-28 05:22:45 -0800967 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
968 "Channel::Init()");
niklase@google.com470e71d2011-07-07 08:21:25 +0000969
kwiberg55b97fe2016-01-28 05:22:45 -0800970 channel_state_.Reset();
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +0000971
kwiberg55b97fe2016-01-28 05:22:45 -0800972 // --- Initial sanity
niklase@google.com470e71d2011-07-07 08:21:25 +0000973
kwiberg55b97fe2016-01-28 05:22:45 -0800974 if ((_engineStatisticsPtr == NULL) || (_moduleProcessThreadPtr == NULL)) {
975 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
976 "Channel::Init() must call SetEngineInformation() first");
977 return -1;
978 }
979
980 // --- Add modules to process thread (for periodic schedulation)
981
tommidea489f2017-03-03 03:20:24 -0800982 _moduleProcessThreadPtr->RegisterModule(_rtpRtcpModule.get(), RTC_FROM_HERE);
kwiberg55b97fe2016-01-28 05:22:45 -0800983
984 // --- ACM initialization
985
986 if (audio_coding_->InitializeReceiver() == -1) {
987 _engineStatisticsPtr->SetLastError(
988 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
989 "Channel::Init() unable to initialize the ACM - 1");
990 return -1;
991 }
992
993 // --- RTP/RTCP module initialization
994
995 // Ensure that RTCP is enabled by default for the created channel.
996 // Note that, the module will keep generating RTCP until it is explicitly
997 // disabled by the user.
998 // After StopListen (when no sockets exists), RTCP packets will no longer
999 // be transmitted since the Transport object will then be invalid.
danilchap799a9d02016-09-22 03:36:27 -07001000 telephone_event_handler_->SetTelephoneEventForwardToDecoder(true);
kwiberg55b97fe2016-01-28 05:22:45 -08001001 // RTCP is enabled by default.
1002 _rtpRtcpModule->SetRTCPStatus(RtcpMode::kCompound);
1003 // --- Register all permanent callbacks
solenbergfe7dd6d2017-03-11 08:10:43 -08001004 if (audio_coding_->RegisterTransportCallback(this) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08001005 _engineStatisticsPtr->SetLastError(
1006 VE_CANNOT_INIT_CHANNEL, kTraceError,
1007 "Channel::Init() callbacks not registered");
1008 return -1;
1009 }
1010
kwiberg1c07c702017-03-27 07:15:49 -07001011 // Register a default set of send codecs.
1012 const int nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
kwiberg55b97fe2016-01-28 05:22:45 -08001013 for (int idx = 0; idx < nSupportedCodecs; idx++) {
kwiberg1c07c702017-03-27 07:15:49 -07001014 CodecInst codec;
1015 RTC_CHECK_EQ(0, audio_coding_->Codec(idx, &codec));
1016
1017 // Ensure that PCMU is used as default send codec.
1018 if (STR_CASE_CMP(codec.plname, "PCMU") == 0 && codec.channels == 1) {
1019 SetSendCodec(codec);
1020 }
1021
1022 // Register default PT for 'telephone-event'
1023 if (STR_CASE_CMP(codec.plname, "telephone-event") == 0) {
1024 if (_rtpRtcpModule->RegisterSendPayload(codec) == -1) {
1025 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1026 "Channel::Init() failed to register outband "
1027 "'telephone-event' (%d/%d) correctly",
1028 codec.pltype, codec.plfreq);
1029 }
1030 }
1031
1032 if (STR_CASE_CMP(codec.plname, "CN") == 0) {
1033 if (!codec_manager_.RegisterEncoder(codec) ||
1034 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get()) ||
1035 _rtpRtcpModule->RegisterSendPayload(codec) == -1) {
1036 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1037 "Channel::Init() failed to register CN (%d/%d) "
1038 "correctly - 1",
1039 codec.pltype, codec.plfreq);
1040 }
1041 }
1042 }
1043
1044 return 0;
1045}
1046
1047void Channel::RegisterLegacyReceiveCodecs() {
1048 const int nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
1049 for (int idx = 0; idx < nSupportedCodecs; idx++) {
1050 CodecInst codec;
1051 RTC_CHECK_EQ(0, audio_coding_->Codec(idx, &codec));
1052
kwiberg55b97fe2016-01-28 05:22:45 -08001053 // Open up the RTP/RTCP receiver for all supported codecs
kwiberg1c07c702017-03-27 07:15:49 -07001054 if (rtp_receiver_->RegisterReceivePayload(codec) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08001055 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1056 "Channel::Init() unable to register %s "
1057 "(%d/%d/%" PRIuS "/%d) to RTP/RTCP receiver",
1058 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1059 codec.rate);
1060 } else {
1061 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1062 "Channel::Init() %s (%d/%d/%" PRIuS
1063 "/%d) has been "
1064 "added to the RTP/RTCP receiver",
1065 codec.plname, codec.pltype, codec.plfreq, codec.channels,
1066 codec.rate);
niklase@google.com470e71d2011-07-07 08:21:25 +00001067 }
1068
kwiberg1c07c702017-03-27 07:15:49 -07001069 // Register default PT for 'telephone-event'
1070 if (STR_CASE_CMP(codec.plname, "telephone-event") == 0) {
1071 if (!audio_coding_->RegisterReceiveCodec(codec.pltype,
kwibergda2bf4e2016-10-24 13:47:09 -07001072 CodecInstToSdp(codec))) {
kwiberg55b97fe2016-01-28 05:22:45 -08001073 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
kwiberg1c07c702017-03-27 07:15:49 -07001074 "Channel::Init() failed to register inband "
kwiberg55b97fe2016-01-28 05:22:45 -08001075 "'telephone-event' (%d/%d) correctly",
1076 codec.pltype, codec.plfreq);
1077 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001078 }
1079
kwiberg1c07c702017-03-27 07:15:49 -07001080 if (STR_CASE_CMP(codec.plname, "CN") == 0) {
1081 if (!audio_coding_->RegisterReceiveCodec(codec.pltype,
1082 CodecInstToSdp(codec))) {
kwiberg55b97fe2016-01-28 05:22:45 -08001083 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1084 "Channel::Init() failed to register CN (%d/%d) "
1085 "correctly - 1",
1086 codec.pltype, codec.plfreq);
1087 }
1088 }
kwiberg55b97fe2016-01-28 05:22:45 -08001089 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001090}
1091
tommi0a2391f2017-03-21 02:31:51 -07001092void Channel::Terminate() {
1093 RTC_DCHECK(construction_thread_.CalledOnValidThread());
1094 // Must be called on the same thread as Init().
1095 WEBRTC_TRACE(kTraceMemory, kTraceVoice, VoEId(_instanceId, _channelId),
1096 "Channel::Terminate");
1097
1098 rtp_receive_statistics_->RegisterRtcpStatisticsCallback(NULL);
1099
1100 StopSend();
1101 StopPlayout();
1102
1103 {
1104 rtc::CritScope cs(&_fileCritSect);
1105 if (input_file_player_) {
1106 input_file_player_->RegisterModuleFileCallback(NULL);
1107 input_file_player_->StopPlayingFile();
1108 }
1109 if (output_file_player_) {
1110 output_file_player_->RegisterModuleFileCallback(NULL);
1111 output_file_player_->StopPlayingFile();
1112 }
1113 if (output_file_recorder_) {
1114 output_file_recorder_->RegisterModuleFileCallback(NULL);
1115 output_file_recorder_->StopRecording();
1116 }
1117 }
1118
1119 // The order to safely shutdown modules in a channel is:
1120 // 1. De-register callbacks in modules
1121 // 2. De-register modules in process thread
1122 // 3. Destroy modules
1123 if (audio_coding_->RegisterTransportCallback(NULL) == -1) {
1124 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1125 "Terminate() failed to de-register transport callback"
1126 " (Audio coding module)");
1127 }
1128
1129 if (audio_coding_->RegisterVADCallback(NULL) == -1) {
1130 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
1131 "Terminate() failed to de-register VAD callback"
1132 " (Audio coding module)");
1133 }
1134
1135 // De-register modules in process thread
1136 if (_moduleProcessThreadPtr)
1137 _moduleProcessThreadPtr->DeRegisterModule(_rtpRtcpModule.get());
1138
1139 // End of modules shutdown
1140}
1141
kwiberg55b97fe2016-01-28 05:22:45 -08001142int32_t Channel::SetEngineInformation(Statistics& engineStatistics,
1143 OutputMixer& outputMixer,
kwiberg55b97fe2016-01-28 05:22:45 -08001144 ProcessThread& moduleProcessThread,
1145 AudioDeviceModule& audioDeviceModule,
1146 VoiceEngineObserver* voiceEngineObserver,
henrikaec6fbd22017-03-31 05:43:36 -07001147 rtc::CriticalSection* callbackCritSect,
1148 rtc::TaskQueue* encoder_queue) {
1149 RTC_DCHECK(encoder_queue);
1150 RTC_DCHECK(!encoder_queue_);
kwiberg55b97fe2016-01-28 05:22:45 -08001151 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1152 "Channel::SetEngineInformation()");
1153 _engineStatisticsPtr = &engineStatistics;
1154 _outputMixerPtr = &outputMixer;
kwiberg55b97fe2016-01-28 05:22:45 -08001155 _moduleProcessThreadPtr = &moduleProcessThread;
1156 _audioDeviceModulePtr = &audioDeviceModule;
1157 _voiceEngineObserverPtr = voiceEngineObserver;
1158 _callbackCritSectPtr = callbackCritSect;
henrikaec6fbd22017-03-31 05:43:36 -07001159 encoder_queue_ = encoder_queue;
kwiberg55b97fe2016-01-28 05:22:45 -08001160 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001161}
1162
kwibergb7f89d62016-02-17 10:04:18 -08001163void Channel::SetSink(std::unique_ptr<AudioSinkInterface> sink) {
tommi31fc21f2016-01-21 10:37:37 -08001164 rtc::CritScope cs(&_callbackCritSect);
deadbeef2d110be2016-01-13 12:00:26 -08001165 audio_sink_ = std::move(sink);
Tommif888bb52015-12-12 01:37:01 +01001166}
1167
ossu29b1a8d2016-06-13 07:34:51 -07001168const rtc::scoped_refptr<AudioDecoderFactory>&
1169Channel::GetAudioDecoderFactory() const {
1170 return decoder_factory_;
1171}
1172
kwiberg55b97fe2016-01-28 05:22:45 -08001173int32_t Channel::StartPlayout() {
1174 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1175 "Channel::StartPlayout()");
1176 if (channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001177 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001178 }
1179
solenberge374e012017-02-14 04:55:00 -08001180 // Add participant as candidates for mixing.
1181 if (_outputMixerPtr->SetMixabilityStatus(*this, true) != 0) {
1182 _engineStatisticsPtr->SetLastError(
1183 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1184 "StartPlayout() failed to add participant to mixer");
1185 return -1;
kwiberg55b97fe2016-01-28 05:22:45 -08001186 }
1187
1188 channel_state_.SetPlaying(true);
1189 if (RegisterFilePlayingToMixer() != 0)
1190 return -1;
1191
1192 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001193}
1194
kwiberg55b97fe2016-01-28 05:22:45 -08001195int32_t Channel::StopPlayout() {
1196 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1197 "Channel::StopPlayout()");
1198 if (!channel_state_.Get().playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001199 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001200 }
1201
solenberge374e012017-02-14 04:55:00 -08001202 // Remove participant as candidates for mixing
1203 if (_outputMixerPtr->SetMixabilityStatus(*this, false) != 0) {
1204 _engineStatisticsPtr->SetLastError(
1205 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
1206 "StopPlayout() failed to remove participant from mixer");
1207 return -1;
kwiberg55b97fe2016-01-28 05:22:45 -08001208 }
1209
1210 channel_state_.SetPlaying(false);
1211 _outputAudioLevel.Clear();
1212
1213 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001214}
1215
kwiberg55b97fe2016-01-28 05:22:45 -08001216int32_t Channel::StartSend() {
1217 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1218 "Channel::StartSend()");
kwiberg55b97fe2016-01-28 05:22:45 -08001219 if (channel_state_.Get().sending) {
niklase@google.com470e71d2011-07-07 08:21:25 +00001220 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001221 }
1222 channel_state_.SetSending(true);
henrika4515fa02017-05-03 08:30:15 -07001223 {
1224 // It is now OK to start posting tasks to the encoder task queue.
1225 rtc::CritScope cs(&encoder_queue_lock_);
1226 encoder_queue_is_active_ = true;
1227 }
solenberg08b19df2017-02-15 00:42:31 -08001228 // Resume the previous sequence number which was reset by StopSend(). This
1229 // needs to be done before |sending| is set to true on the RTP/RTCP module.
1230 if (send_sequence_number_) {
1231 _rtpRtcpModule->SetSequenceNumber(send_sequence_number_);
1232 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001233 _rtpRtcpModule->SetSendingMediaStatus(true);
kwiberg55b97fe2016-01-28 05:22:45 -08001234 if (_rtpRtcpModule->SetSendingStatus(true) != 0) {
1235 _engineStatisticsPtr->SetLastError(
1236 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1237 "StartSend() RTP/RTCP failed to start sending");
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001238 _rtpRtcpModule->SetSendingMediaStatus(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001239 rtc::CritScope cs(&_callbackCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00001240 channel_state_.SetSending(false);
kwiberg55b97fe2016-01-28 05:22:45 -08001241 return -1;
1242 }
xians@webrtc.orge07247a2011-11-28 16:31:28 +00001243
kwiberg55b97fe2016-01-28 05:22:45 -08001244 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001245}
1246
henrikaec6fbd22017-03-31 05:43:36 -07001247void Channel::StopSend() {
kwiberg55b97fe2016-01-28 05:22:45 -08001248 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1249 "Channel::StopSend()");
1250 if (!channel_state_.Get().sending) {
henrikaec6fbd22017-03-31 05:43:36 -07001251 return;
kwiberg55b97fe2016-01-28 05:22:45 -08001252 }
1253 channel_state_.SetSending(false);
1254
henrikaec6fbd22017-03-31 05:43:36 -07001255 // Post a task to the encoder thread which sets an event when the task is
1256 // executed. We know that no more encoding tasks will be added to the task
1257 // queue for this channel since sending is now deactivated. It means that,
1258 // if we wait for the event to bet set, we know that no more pending tasks
1259 // exists and it is therfore guaranteed that the task queue will never try
1260 // to acccess and invalid channel object.
1261 RTC_DCHECK(encoder_queue_);
henrika4515fa02017-05-03 08:30:15 -07001262
henrikaec6fbd22017-03-31 05:43:36 -07001263 rtc::Event flush(false, false);
henrika4515fa02017-05-03 08:30:15 -07001264 {
1265 // Clear |encoder_queue_is_active_| under lock to prevent any other tasks
1266 // than this final "flush task" to be posted on the queue.
1267 rtc::CritScope cs(&encoder_queue_lock_);
1268 encoder_queue_is_active_ = false;
1269 encoder_queue_->PostTask([&flush]() { flush.Set(); });
1270 }
henrikaec6fbd22017-03-31 05:43:36 -07001271 flush.Wait(rtc::Event::kForever);
1272
kwiberg55b97fe2016-01-28 05:22:45 -08001273 // Store the sequence number to be able to pick up the same sequence for
1274 // the next StartSend(). This is needed for restarting device, otherwise
1275 // it might cause libSRTP to complain about packets being replayed.
1276 // TODO(xians): Remove this workaround after RtpRtcpModule's refactoring
1277 // CL is landed. See issue
1278 // https://code.google.com/p/webrtc/issues/detail?id=2111 .
1279 send_sequence_number_ = _rtpRtcpModule->SequenceNumber();
1280
1281 // Reset sending SSRC and sequence number and triggers direct transmission
1282 // of RTCP BYE
1283 if (_rtpRtcpModule->SetSendingStatus(false) == -1) {
1284 _engineStatisticsPtr->SetLastError(
1285 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
1286 "StartSend() RTP/RTCP failed to stop sending");
1287 }
Peter Boström3dd5d1d2016-02-25 16:56:48 +01001288 _rtpRtcpModule->SetSendingMediaStatus(false);
niklase@google.com470e71d2011-07-07 08:21:25 +00001289}
1290
ossu1ffbd6c2017-04-06 12:05:04 -07001291bool Channel::SetEncoder(int payload_type,
1292 std::unique_ptr<AudioEncoder> encoder) {
1293 RTC_DCHECK_GE(payload_type, 0);
1294 RTC_DCHECK_LE(payload_type, 127);
ossu76d29f92017-06-09 07:30:13 -07001295 // TODO(ossu): Make CodecInsts up, for now: one for the RTP/RTCP module and
1296 // one for for us to keep track of sample rate and number of channels, etc.
1297
1298 // The RTP/RTCP module needs to know the RTP timestamp rate (i.e. clockrate)
1299 // as well as some other things, so we collect this info and send it along.
1300 CodecInst rtp_codec;
1301 rtp_codec.pltype = payload_type;
1302 strncpy(rtp_codec.plname, "audio", sizeof(rtp_codec.plname));
1303 rtp_codec.plname[sizeof(rtp_codec.plname) - 1] = 0;
ossu1ffbd6c2017-04-06 12:05:04 -07001304 // Seems unclear if it should be clock rate or sample rate. CodecInst
1305 // supposedly carries the sample rate, but only clock rate seems sensible to
1306 // send to the RTP/RTCP module.
ossu76d29f92017-06-09 07:30:13 -07001307 rtp_codec.plfreq = encoder->RtpTimestampRateHz();
1308 rtp_codec.pacsize = rtc::CheckedDivExact(
1309 static_cast<int>(encoder->Max10MsFramesInAPacket() * rtp_codec.plfreq),
1310 100);
1311 rtp_codec.channels = encoder->NumChannels();
1312 rtp_codec.rate = 0;
ossu1ffbd6c2017-04-06 12:05:04 -07001313
ossu76d29f92017-06-09 07:30:13 -07001314 // For audio encoding we need, instead, the actual sample rate of the codec.
1315 // The rest of the information should be the same.
1316 CodecInst send_codec = rtp_codec;
1317 send_codec.plfreq = encoder->SampleRateHz();
1318 cached_send_codec_.emplace(send_codec);
1319
1320 if (_rtpRtcpModule->RegisterSendPayload(rtp_codec) != 0) {
ossu1ffbd6c2017-04-06 12:05:04 -07001321 _rtpRtcpModule->DeRegisterSendPayload(payload_type);
ossu76d29f92017-06-09 07:30:13 -07001322 if (_rtpRtcpModule->RegisterSendPayload(rtp_codec) != 0) {
ossu1ffbd6c2017-04-06 12:05:04 -07001323 WEBRTC_TRACE(
1324 kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1325 "SetEncoder() failed to register codec to RTP/RTCP module");
1326 return false;
1327 }
1328 }
1329
1330 audio_coding_->SetEncoder(std::move(encoder));
ossu20a4b3f2017-04-27 02:08:52 -07001331 codec_manager_.UnsetCodecInst();
ossu1ffbd6c2017-04-06 12:05:04 -07001332 return true;
1333}
1334
ossu20a4b3f2017-04-27 02:08:52 -07001335void Channel::ModifyEncoder(
1336 rtc::FunctionView<void(std::unique_ptr<AudioEncoder>*)> modifier) {
1337 audio_coding_->ModifyEncoder(modifier);
1338}
1339
kwiberg55b97fe2016-01-28 05:22:45 -08001340int32_t Channel::RegisterVoiceEngineObserver(VoiceEngineObserver& observer) {
1341 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1342 "Channel::RegisterVoiceEngineObserver()");
1343 rtc::CritScope cs(&_callbackCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00001344
kwiberg55b97fe2016-01-28 05:22:45 -08001345 if (_voiceEngineObserverPtr) {
1346 _engineStatisticsPtr->SetLastError(
1347 VE_INVALID_OPERATION, kTraceError,
1348 "RegisterVoiceEngineObserver() observer already enabled");
1349 return -1;
1350 }
1351 _voiceEngineObserverPtr = &observer;
1352 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001353}
1354
kwiberg55b97fe2016-01-28 05:22:45 -08001355int32_t Channel::DeRegisterVoiceEngineObserver() {
1356 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1357 "Channel::DeRegisterVoiceEngineObserver()");
1358 rtc::CritScope cs(&_callbackCritSect);
1359
1360 if (!_voiceEngineObserverPtr) {
1361 _engineStatisticsPtr->SetLastError(
1362 VE_INVALID_OPERATION, kTraceWarning,
1363 "DeRegisterVoiceEngineObserver() observer already disabled");
1364 return 0;
1365 }
1366 _voiceEngineObserverPtr = NULL;
1367 return 0;
1368}
1369
1370int32_t Channel::GetSendCodec(CodecInst& codec) {
ossu76d29f92017-06-09 07:30:13 -07001371 if (cached_send_codec_) {
1372 codec = *cached_send_codec_;
1373 return 0;
1374 } else {
ossu20a4b3f2017-04-27 02:08:52 -07001375 const CodecInst* send_codec = codec_manager_.GetCodecInst();
1376 if (send_codec) {
1377 codec = *send_codec;
1378 return 0;
1379 }
1380 }
kwiberg1fd4a4a2015-11-03 11:20:50 -08001381 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001382}
1383
kwiberg55b97fe2016-01-28 05:22:45 -08001384int32_t Channel::GetRecCodec(CodecInst& codec) {
1385 return (audio_coding_->ReceiveCodec(&codec));
niklase@google.com470e71d2011-07-07 08:21:25 +00001386}
1387
kwiberg55b97fe2016-01-28 05:22:45 -08001388int32_t Channel::SetSendCodec(const CodecInst& codec) {
1389 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1390 "Channel::SetSendCodec()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001391
kwibergc8d071e2016-04-06 12:22:38 -07001392 if (!codec_manager_.RegisterEncoder(codec) ||
1393 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001394 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1395 "SetSendCodec() failed to register codec to ACM");
1396 return -1;
1397 }
1398
1399 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1400 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1401 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1402 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, _channelId),
1403 "SetSendCodec() failed to register codec to"
1404 " RTP/RTCP module");
1405 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001406 }
kwiberg55b97fe2016-01-28 05:22:45 -08001407 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001408
ossu76d29f92017-06-09 07:30:13 -07001409 cached_send_codec_.reset();
1410
kwiberg55b97fe2016-01-28 05:22:45 -08001411 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001412}
1413
minyue78b4d562016-11-30 04:47:39 -08001414void Channel::SetBitRate(int bitrate_bps, int64_t probing_interval_ms) {
Ivo Creusenadf89b72015-04-29 16:03:33 +02001415 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1416 "Channel::SetBitRate(bitrate_bps=%d)", bitrate_bps);
minyue7e304322016-10-12 05:00:55 -07001417 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
michaelt2fedf9c2016-11-28 02:34:18 -08001418 if (*encoder) {
1419 (*encoder)->OnReceivedUplinkBandwidth(
michaelt566d8202017-01-12 10:17:38 -08001420 bitrate_bps, rtc::Optional<int64_t>(probing_interval_ms));
michaelt2fedf9c2016-11-28 02:34:18 -08001421 }
1422 });
michaelt566d8202017-01-12 10:17:38 -08001423 retransmission_rate_limiter_->SetMaxRate(bitrate_bps);
Ivo Creusenadf89b72015-04-29 16:03:33 +02001424}
1425
elad.alond12a8e12017-03-23 11:04:48 -07001426void Channel::OnTwccBasedUplinkPacketLossRate(float packet_loss_rate) {
1427 if (!use_twcc_plr_for_ana_)
1428 return;
minyue7e304322016-10-12 05:00:55 -07001429 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
elad.alond12a8e12017-03-23 11:04:48 -07001430 if (*encoder) {
1431 (*encoder)->OnReceivedUplinkPacketLossFraction(packet_loss_rate);
1432 }
1433 });
1434}
1435
elad.alondadb4dc2017-03-23 15:29:50 -07001436void Channel::OnRecoverableUplinkPacketLossRate(
1437 float recoverable_packet_loss_rate) {
1438 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1439 if (*encoder) {
1440 (*encoder)->OnReceivedUplinkRecoverablePacketLossFraction(
1441 recoverable_packet_loss_rate);
1442 }
1443 });
1444}
1445
elad.alond12a8e12017-03-23 11:04:48 -07001446void Channel::OnUplinkPacketLossRate(float packet_loss_rate) {
1447 if (use_twcc_plr_for_ana_)
1448 return;
1449 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1450 if (*encoder) {
1451 (*encoder)->OnReceivedUplinkPacketLossFraction(packet_loss_rate);
1452 }
minyue7e304322016-10-12 05:00:55 -07001453 });
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00001454}
1455
kwiberg55b97fe2016-01-28 05:22:45 -08001456int32_t Channel::SetVADStatus(bool enableVAD,
1457 ACMVADMode mode,
1458 bool disableDTX) {
1459 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1460 "Channel::SetVADStatus(mode=%d)", mode);
kwibergc8d071e2016-04-06 12:22:38 -07001461 RTC_DCHECK(!(disableDTX && enableVAD)); // disableDTX mode is deprecated.
1462 if (!codec_manager_.SetVAD(enableVAD, mode) ||
1463 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001464 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR,
1465 kTraceError,
1466 "SetVADStatus() failed to set VAD");
1467 return -1;
1468 }
1469 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001470}
1471
kwiberg55b97fe2016-01-28 05:22:45 -08001472int32_t Channel::GetVADStatus(bool& enabledVAD,
1473 ACMVADMode& mode,
1474 bool& disabledDTX) {
kwibergc8d071e2016-04-06 12:22:38 -07001475 const auto* params = codec_manager_.GetStackParams();
1476 enabledVAD = params->use_cng;
1477 mode = params->vad_mode;
1478 disabledDTX = !params->use_cng;
kwiberg55b97fe2016-01-28 05:22:45 -08001479 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001480}
1481
kwiberg1c07c702017-03-27 07:15:49 -07001482void Channel::SetReceiveCodecs(const std::map<int, SdpAudioFormat>& codecs) {
1483 rtp_payload_registry_->SetAudioReceivePayloads(codecs);
1484 audio_coding_->SetReceiveCodecs(codecs);
1485}
1486
kwiberg55b97fe2016-01-28 05:22:45 -08001487int32_t Channel::SetRecPayloadType(const CodecInst& codec) {
kwibergd32bf752017-01-19 07:03:59 -08001488 return SetRecPayloadType(codec.pltype, CodecInstToSdp(codec));
1489}
1490
1491int32_t Channel::SetRecPayloadType(int payload_type,
1492 const SdpAudioFormat& format) {
kwiberg55b97fe2016-01-28 05:22:45 -08001493 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1494 "Channel::SetRecPayloadType()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001495
kwiberg55b97fe2016-01-28 05:22:45 -08001496 if (channel_state_.Get().playing) {
1497 _engineStatisticsPtr->SetLastError(
1498 VE_ALREADY_PLAYING, kTraceError,
1499 "SetRecPayloadType() unable to set PT while playing");
1500 return -1;
1501 }
kwiberg55b97fe2016-01-28 05:22:45 -08001502
kwiberg09f090c2017-03-01 01:57:11 -08001503 const CodecInst codec = SdpToCodecInst(payload_type, format);
kwibergd32bf752017-01-19 07:03:59 -08001504
1505 if (payload_type == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08001506 // De-register the selected codec (RTP/RTCP module and ACM)
1507
1508 int8_t pltype(-1);
1509 CodecInst rxCodec = codec;
1510
1511 // Get payload type for the given codec
magjed56124bd2016-11-24 09:34:46 -08001512 rtp_payload_registry_->ReceivePayloadType(rxCodec, &pltype);
kwiberg55b97fe2016-01-28 05:22:45 -08001513 rxCodec.pltype = pltype;
1514
1515 if (rtp_receiver_->DeRegisterReceivePayload(pltype) != 0) {
1516 _engineStatisticsPtr->SetLastError(
1517 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1518 "SetRecPayloadType() RTP/RTCP-module deregistration "
1519 "failed");
1520 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001521 }
kwiberg55b97fe2016-01-28 05:22:45 -08001522 if (audio_coding_->UnregisterReceiveCodec(rxCodec.pltype) != 0) {
1523 _engineStatisticsPtr->SetLastError(
1524 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1525 "SetRecPayloadType() ACM deregistration failed - 1");
1526 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001527 }
kwiberg55b97fe2016-01-28 05:22:45 -08001528 return 0;
1529 }
niklase@google.com470e71d2011-07-07 08:21:25 +00001530
magjed56124bd2016-11-24 09:34:46 -08001531 if (rtp_receiver_->RegisterReceivePayload(codec) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001532 // First attempt to register failed => de-register and try again
kwibergc8d071e2016-04-06 12:22:38 -07001533 // TODO(kwiberg): Retrying is probably not necessary, since
1534 // AcmReceiver::AddCodec also retries.
kwiberg55b97fe2016-01-28 05:22:45 -08001535 rtp_receiver_->DeRegisterReceivePayload(codec.pltype);
magjed56124bd2016-11-24 09:34:46 -08001536 if (rtp_receiver_->RegisterReceivePayload(codec) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001537 _engineStatisticsPtr->SetLastError(
1538 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1539 "SetRecPayloadType() RTP/RTCP-module registration failed");
1540 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001541 }
kwiberg55b97fe2016-01-28 05:22:45 -08001542 }
kwibergd32bf752017-01-19 07:03:59 -08001543 if (!audio_coding_->RegisterReceiveCodec(payload_type, format)) {
1544 audio_coding_->UnregisterReceiveCodec(payload_type);
1545 if (!audio_coding_->RegisterReceiveCodec(payload_type, format)) {
kwiberg55b97fe2016-01-28 05:22:45 -08001546 _engineStatisticsPtr->SetLastError(
1547 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1548 "SetRecPayloadType() ACM registration failed - 1");
1549 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001550 }
kwiberg55b97fe2016-01-28 05:22:45 -08001551 }
1552 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001553}
1554
kwiberg55b97fe2016-01-28 05:22:45 -08001555int32_t Channel::GetRecPayloadType(CodecInst& codec) {
1556 int8_t payloadType(-1);
magjed56124bd2016-11-24 09:34:46 -08001557 if (rtp_payload_registry_->ReceivePayloadType(codec, &payloadType) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001558 _engineStatisticsPtr->SetLastError(
1559 VE_RTP_RTCP_MODULE_ERROR, kTraceWarning,
1560 "GetRecPayloadType() failed to retrieve RX payload type");
1561 return -1;
1562 }
1563 codec.pltype = payloadType;
1564 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001565}
1566
kwiberg55b97fe2016-01-28 05:22:45 -08001567int32_t Channel::SetSendCNPayloadType(int type, PayloadFrequencies frequency) {
1568 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1569 "Channel::SetSendCNPayloadType()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001570
kwiberg55b97fe2016-01-28 05:22:45 -08001571 CodecInst codec;
1572 int32_t samplingFreqHz(-1);
1573 const size_t kMono = 1;
1574 if (frequency == kFreq32000Hz)
1575 samplingFreqHz = 32000;
1576 else if (frequency == kFreq16000Hz)
1577 samplingFreqHz = 16000;
niklase@google.com470e71d2011-07-07 08:21:25 +00001578
kwiberg55b97fe2016-01-28 05:22:45 -08001579 if (audio_coding_->Codec("CN", &codec, samplingFreqHz, kMono) == -1) {
1580 _engineStatisticsPtr->SetLastError(
1581 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1582 "SetSendCNPayloadType() failed to retrieve default CN codec "
1583 "settings");
1584 return -1;
1585 }
1586
1587 // Modify the payload type (must be set to dynamic range)
1588 codec.pltype = type;
1589
kwibergc8d071e2016-04-06 12:22:38 -07001590 if (!codec_manager_.RegisterEncoder(codec) ||
1591 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
kwiberg55b97fe2016-01-28 05:22:45 -08001592 _engineStatisticsPtr->SetLastError(
1593 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
1594 "SetSendCNPayloadType() failed to register CN to ACM");
1595 return -1;
1596 }
1597
1598 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1599 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
1600 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
1601 _engineStatisticsPtr->SetLastError(
1602 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
1603 "SetSendCNPayloadType() failed to register CN to RTP/RTCP "
1604 "module");
1605 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001606 }
kwiberg55b97fe2016-01-28 05:22:45 -08001607 }
1608 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001609}
1610
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001611int Channel::SetOpusMaxPlaybackRate(int frequency_hz) {
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001612 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001613 "Channel::SetOpusMaxPlaybackRate()");
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001614
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001615 if (audio_coding_->SetOpusMaxPlaybackRate(frequency_hz) != 0) {
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001616 _engineStatisticsPtr->SetLastError(
1617 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
minyue@webrtc.orgadee8f92014-09-03 12:28:06 +00001618 "SetOpusMaxPlaybackRate() failed to set maximum playback rate");
minyue@webrtc.org6aac93b2014-08-12 08:13:33 +00001619 return -1;
1620 }
1621 return 0;
1622}
1623
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001624int Channel::SetOpusDtx(bool enable_dtx) {
1625 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1626 "Channel::SetOpusDtx(%d)", enable_dtx);
Minyue Li092041c2015-05-11 12:19:35 +02001627 int ret = enable_dtx ? audio_coding_->EnableOpusDtx()
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001628 : audio_coding_->DisableOpusDtx();
1629 if (ret != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001630 _engineStatisticsPtr->SetLastError(VE_AUDIO_CODING_MODULE_ERROR,
1631 kTraceError, "SetOpusDtx() failed");
minyue@webrtc.org9b2e1142015-03-13 09:38:07 +00001632 return -1;
1633 }
1634 return 0;
1635}
1636
ivoc85228d62016-07-27 04:53:47 -07001637int Channel::GetOpusDtx(bool* enabled) {
1638 int success = -1;
1639 audio_coding_->QueryEncoder([&](AudioEncoder const* encoder) {
1640 if (encoder) {
1641 *enabled = encoder->GetDtx();
1642 success = 0;
1643 }
1644 });
1645 return success;
1646}
1647
minyue7e304322016-10-12 05:00:55 -07001648bool Channel::EnableAudioNetworkAdaptor(const std::string& config_string) {
1649 bool success = false;
1650 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1651 if (*encoder) {
michaelt92aef172017-04-18 00:11:48 -07001652 success = (*encoder)->EnableAudioNetworkAdaptor(config_string,
1653 event_log_proxy_.get());
minyue7e304322016-10-12 05:00:55 -07001654 }
1655 });
1656 return success;
1657}
1658
1659void Channel::DisableAudioNetworkAdaptor() {
1660 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1661 if (*encoder)
1662 (*encoder)->DisableAudioNetworkAdaptor();
1663 });
1664}
1665
1666void Channel::SetReceiverFrameLengthRange(int min_frame_length_ms,
1667 int max_frame_length_ms) {
1668 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1669 if (*encoder) {
1670 (*encoder)->SetReceiverFrameLengthRange(min_frame_length_ms,
1671 max_frame_length_ms);
1672 }
1673 });
1674}
1675
mflodman3d7db262016-04-29 00:57:13 -07001676int32_t Channel::RegisterExternalTransport(Transport* transport) {
kwiberg55b97fe2016-01-28 05:22:45 -08001677 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00001678 "Channel::RegisterExternalTransport()");
1679
kwiberg55b97fe2016-01-28 05:22:45 -08001680 rtc::CritScope cs(&_callbackCritSect);
kwiberg55b97fe2016-01-28 05:22:45 -08001681 if (_externalTransport) {
1682 _engineStatisticsPtr->SetLastError(
1683 VE_INVALID_OPERATION, kTraceError,
1684 "RegisterExternalTransport() external transport already enabled");
1685 return -1;
1686 }
1687 _externalTransport = true;
mflodman3d7db262016-04-29 00:57:13 -07001688 _transportPtr = transport;
kwiberg55b97fe2016-01-28 05:22:45 -08001689 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001690}
1691
kwiberg55b97fe2016-01-28 05:22:45 -08001692int32_t Channel::DeRegisterExternalTransport() {
1693 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1694 "Channel::DeRegisterExternalTransport()");
niklase@google.com470e71d2011-07-07 08:21:25 +00001695
kwiberg55b97fe2016-01-28 05:22:45 -08001696 rtc::CritScope cs(&_callbackCritSect);
mflodman3d7db262016-04-29 00:57:13 -07001697 if (_transportPtr) {
1698 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1699 "DeRegisterExternalTransport() all transport is disabled");
1700 } else {
kwiberg55b97fe2016-01-28 05:22:45 -08001701 _engineStatisticsPtr->SetLastError(
1702 VE_INVALID_OPERATION, kTraceWarning,
1703 "DeRegisterExternalTransport() external transport already "
1704 "disabled");
kwiberg55b97fe2016-01-28 05:22:45 -08001705 }
1706 _externalTransport = false;
1707 _transportPtr = NULL;
kwiberg55b97fe2016-01-28 05:22:45 -08001708 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001709}
1710
nisse657bab22017-02-21 06:28:10 -08001711// TODO(nisse): Delete this method together with ReceivedRTPPacket.
1712// It's a temporary hack to support both ReceivedRTPPacket and
1713// OnRtpPacket interfaces without too much code duplication.
1714bool Channel::OnRtpPacketWithHeader(const uint8_t* received_packet,
1715 size_t length,
1716 RTPHeader *header) {
1717 // Store playout timestamp for the received RTP packet
1718 UpdatePlayoutTimestamp(false);
1719
1720 header->payload_type_frequency =
1721 rtp_payload_registry_->GetPayloadTypeFrequency(header->payloadType);
1722 if (header->payload_type_frequency < 0)
1723 return false;
1724 bool in_order = IsPacketInOrder(*header);
1725 rtp_receive_statistics_->IncomingPacket(
1726 *header, length, IsPacketRetransmitted(*header, in_order));
1727 rtp_payload_registry_->SetIncomingPayloadType(*header);
1728
1729 return ReceivePacket(received_packet, length, *header, in_order);
1730}
1731
mflodman3d7db262016-04-29 00:57:13 -07001732int32_t Channel::ReceivedRTPPacket(const uint8_t* received_packet,
kwiberg55b97fe2016-01-28 05:22:45 -08001733 size_t length,
solenberg@webrtc.orgb1f50102014-03-24 10:38:25 +00001734 const PacketTime& packet_time) {
kwiberg55b97fe2016-01-28 05:22:45 -08001735 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001736 "Channel::ReceivedRTPPacket()");
1737
stefan@webrtc.orga5cb98c2013-05-29 12:12:51 +00001738 RTPHeader header;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001739 if (!rtp_header_parser_->Parse(received_packet, length, &header)) {
1740 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1741 "Incoming packet: invalid RTP header");
stefan@webrtc.orga5cb98c2013-05-29 12:12:51 +00001742 return -1;
1743 }
nisse657bab22017-02-21 06:28:10 -08001744 return OnRtpPacketWithHeader(received_packet, length, &header) ? 0 : -1;
1745}
solenberg@webrtc.orgb1f50102014-03-24 10:38:25 +00001746
nisse657bab22017-02-21 06:28:10 -08001747void Channel::OnRtpPacket(const RtpPacketReceived& packet) {
1748 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
1749 "Channel::ReceivedRTPPacket()");
1750
1751 RTPHeader header;
1752 packet.GetHeader(&header);
1753 OnRtpPacketWithHeader(packet.data(), packet.size(), &header);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001754}
1755
1756bool Channel::ReceivePacket(const uint8_t* packet,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001757 size_t packet_length,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001758 const RTPHeader& header,
1759 bool in_order) {
minyue@webrtc.org456f0142015-01-23 11:58:42 +00001760 if (rtp_payload_registry_->IsRtx(header)) {
1761 return HandleRtxPacket(packet, packet_length, header);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001762 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001763 const uint8_t* payload = packet + header.headerLength;
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001764 assert(packet_length >= header.headerLength);
1765 size_t payload_length = packet_length - header.headerLength;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001766 PayloadUnion payload_specific;
1767 if (!rtp_payload_registry_->GetPayloadSpecifics(header.payloadType,
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001768 &payload_specific)) {
1769 return false;
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001770 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001771 return rtp_receiver_->IncomingRtpPacket(header, payload, payload_length,
1772 payload_specific, in_order);
1773}
1774
minyue@webrtc.org456f0142015-01-23 11:58:42 +00001775bool Channel::HandleRtxPacket(const uint8_t* packet,
1776 size_t packet_length,
1777 const RTPHeader& header) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001778 if (!rtp_payload_registry_->IsRtx(header))
1779 return false;
1780
1781 // Remove the RTX header and parse the original RTP header.
1782 if (packet_length < header.headerLength)
1783 return false;
1784 if (packet_length > kVoiceEngineMaxIpPacketSizeBytes)
1785 return false;
1786 if (restored_packet_in_use_) {
1787 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1788 "Multiple RTX headers detected, dropping packet");
1789 return false;
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001790 }
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001791 if (!rtp_payload_registry_->RestoreOriginalPacket(
noahric65220a72015-10-14 11:29:49 -07001792 restored_packet_, packet, &packet_length, rtp_receiver_->SSRC(),
1793 header)) {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001794 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVoice, _channelId,
1795 "Incoming RTX packet: invalid RTP header");
1796 return false;
1797 }
1798 restored_packet_in_use_ = true;
noahric65220a72015-10-14 11:29:49 -07001799 bool ret = OnRecoveredPacket(restored_packet_, packet_length);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001800 restored_packet_in_use_ = false;
1801 return ret;
1802}
1803
1804bool Channel::IsPacketInOrder(const RTPHeader& header) const {
1805 StreamStatistician* statistician =
1806 rtp_receive_statistics_->GetStatistician(header.ssrc);
1807 if (!statistician)
1808 return false;
1809 return statistician->IsPacketInOrder(header.sequenceNumber);
niklase@google.com470e71d2011-07-07 08:21:25 +00001810}
1811
stefan@webrtc.org48df3812013-11-08 15:18:52 +00001812bool Channel::IsPacketRetransmitted(const RTPHeader& header,
1813 bool in_order) const {
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001814 // Retransmissions are handled separately if RTX is enabled.
1815 if (rtp_payload_registry_->RtxEnabled())
1816 return false;
1817 StreamStatistician* statistician =
1818 rtp_receive_statistics_->GetStatistician(header.ssrc);
1819 if (!statistician)
1820 return false;
1821 // Check if this is a retransmission.
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001822 int64_t min_rtt = 0;
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00001823 _rtpRtcpModule->RTT(rtp_receiver_->SSRC(), NULL, NULL, &min_rtt, NULL);
kwiberg55b97fe2016-01-28 05:22:45 -08001824 return !in_order && statistician->IsRetransmitOfOldPacket(header, min_rtt);
wu@webrtc.org822fbd82013-08-15 23:38:54 +00001825}
1826
mflodman3d7db262016-04-29 00:57:13 -07001827int32_t Channel::ReceivedRTCPPacket(const uint8_t* data, size_t length) {
kwiberg55b97fe2016-01-28 05:22:45 -08001828 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001829 "Channel::ReceivedRTCPPacket()");
1830 // Store playout timestamp for the received RTCP packet
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00001831 UpdatePlayoutTimestamp(true);
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001832
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001833 // Deliver RTCP packet to RTP/RTCP module for parsing
mflodman3d7db262016-04-29 00:57:13 -07001834 if (_rtpRtcpModule->IncomingRtcpPacket(data, length) == -1) {
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001835 _engineStatisticsPtr->SetLastError(
1836 VE_SOCKET_TRANSPORT_MODULE_ERROR, kTraceWarning,
1837 "Channel::IncomingRTPPacket() RTCP packet is invalid");
1838 }
wu@webrtc.org82c4b852014-05-20 22:55:01 +00001839
Minyue2013aec2015-05-13 14:14:42 +02001840 int64_t rtt = GetRTT(true);
1841 if (rtt == 0) {
1842 // Waiting for valid RTT.
1843 return 0;
1844 }
Erik Språng737336d2016-07-29 12:59:36 +02001845
1846 int64_t nack_window_ms = rtt;
1847 if (nack_window_ms < kMinRetransmissionWindowMs) {
1848 nack_window_ms = kMinRetransmissionWindowMs;
1849 } else if (nack_window_ms > kMaxRetransmissionWindowMs) {
1850 nack_window_ms = kMaxRetransmissionWindowMs;
1851 }
1852 retransmission_rate_limiter_->SetWindowSize(nack_window_ms);
1853
minyue7e304322016-10-12 05:00:55 -07001854 // Invoke audio encoders OnReceivedRtt().
1855 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
1856 if (*encoder)
1857 (*encoder)->OnReceivedRtt(rtt);
1858 });
1859
Minyue2013aec2015-05-13 14:14:42 +02001860 uint32_t ntp_secs = 0;
1861 uint32_t ntp_frac = 0;
1862 uint32_t rtp_timestamp = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08001863 if (0 !=
1864 _rtpRtcpModule->RemoteNTP(&ntp_secs, &ntp_frac, NULL, NULL,
1865 &rtp_timestamp)) {
Minyue2013aec2015-05-13 14:14:42 +02001866 // Waiting for RTCP.
1867 return 0;
1868 }
1869
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001870 {
tommi31fc21f2016-01-21 10:37:37 -08001871 rtc::CritScope lock(&ts_stats_lock_);
minyue@webrtc.org2c0cdbc2014-10-09 10:52:43 +00001872 ntp_estimator_.UpdateRtcpTimestamp(rtt, ntp_secs, ntp_frac, rtp_timestamp);
stefan@webrtc.org8e24d872014-09-02 18:58:24 +00001873 }
pwestin@webrtc.org0c459572013-04-03 15:43:57 +00001874 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001875}
1876
niklase@google.com470e71d2011-07-07 08:21:25 +00001877int Channel::StartPlayingFileLocally(const char* fileName,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001878 bool loop,
1879 FileFormats format,
1880 int startPosition,
1881 float volumeScaling,
1882 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001883 const CodecInst* codecInst) {
1884 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1885 "Channel::StartPlayingFileLocally(fileNameUTF8[]=%s, loop=%d,"
1886 " format=%d, volumeScaling=%5.3f, startPosition=%d, "
1887 "stopPosition=%d)",
1888 fileName, loop, format, volumeScaling, startPosition,
1889 stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001890
kwiberg55b97fe2016-01-28 05:22:45 -08001891 if (channel_state_.Get().output_file_playing) {
1892 _engineStatisticsPtr->SetLastError(
1893 VE_ALREADY_PLAYING, kTraceError,
1894 "StartPlayingFileLocally() is already playing");
1895 return -1;
1896 }
1897
1898 {
1899 rtc::CritScope cs(&_fileCritSect);
1900
kwiberg5a25d952016-08-17 07:31:12 -07001901 if (output_file_player_) {
1902 output_file_player_->RegisterModuleFileCallback(NULL);
1903 output_file_player_.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +00001904 }
1905
kwiberg5b356f42016-09-08 04:32:33 -07001906 output_file_player_ = FilePlayer::CreateFilePlayer(
kwiberg55b97fe2016-01-28 05:22:45 -08001907 _outputFilePlayerId, (const FileFormats)format);
henrike@webrtc.orgb37c6282011-10-31 23:53:04 +00001908
kwiberg5a25d952016-08-17 07:31:12 -07001909 if (!output_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08001910 _engineStatisticsPtr->SetLastError(
1911 VE_INVALID_ARGUMENT, kTraceError,
1912 "StartPlayingFileLocally() filePlayer format is not correct");
1913 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001914 }
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001915
kwiberg55b97fe2016-01-28 05:22:45 -08001916 const uint32_t notificationTime(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00001917
kwiberg5a25d952016-08-17 07:31:12 -07001918 if (output_file_player_->StartPlayingFile(
kwiberg55b97fe2016-01-28 05:22:45 -08001919 fileName, loop, startPosition, volumeScaling, notificationTime,
1920 stopPosition, (const CodecInst*)codecInst) != 0) {
1921 _engineStatisticsPtr->SetLastError(
1922 VE_BAD_FILE, kTraceError,
1923 "StartPlayingFile() failed to start file playout");
kwiberg5a25d952016-08-17 07:31:12 -07001924 output_file_player_->StopPlayingFile();
1925 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001926 return -1;
1927 }
kwiberg5a25d952016-08-17 07:31:12 -07001928 output_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08001929 channel_state_.SetOutputFilePlaying(true);
1930 }
1931
1932 if (RegisterFilePlayingToMixer() != 0)
1933 return -1;
1934
1935 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00001936}
1937
1938int Channel::StartPlayingFileLocally(InStream* stream,
pbos@webrtc.org92135212013-05-14 08:31:39 +00001939 FileFormats format,
1940 int startPosition,
1941 float volumeScaling,
1942 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08001943 const CodecInst* codecInst) {
1944 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
1945 "Channel::StartPlayingFileLocally(format=%d,"
1946 " volumeScaling=%5.3f, startPosition=%d, stopPosition=%d)",
1947 format, volumeScaling, startPosition, stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00001948
kwiberg55b97fe2016-01-28 05:22:45 -08001949 if (stream == NULL) {
1950 _engineStatisticsPtr->SetLastError(
1951 VE_BAD_FILE, kTraceError,
1952 "StartPlayingFileLocally() NULL as input stream");
1953 return -1;
1954 }
1955
1956 if (channel_state_.Get().output_file_playing) {
1957 _engineStatisticsPtr->SetLastError(
1958 VE_ALREADY_PLAYING, kTraceError,
1959 "StartPlayingFileLocally() is already playing");
1960 return -1;
1961 }
1962
1963 {
1964 rtc::CritScope cs(&_fileCritSect);
1965
1966 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07001967 if (output_file_player_) {
1968 output_file_player_->RegisterModuleFileCallback(NULL);
1969 output_file_player_.reset();
niklase@google.com470e71d2011-07-07 08:21:25 +00001970 }
1971
kwiberg55b97fe2016-01-28 05:22:45 -08001972 // Create the instance
kwiberg5b356f42016-09-08 04:32:33 -07001973 output_file_player_ = FilePlayer::CreateFilePlayer(
kwiberg55b97fe2016-01-28 05:22:45 -08001974 _outputFilePlayerId, (const FileFormats)format);
niklase@google.com470e71d2011-07-07 08:21:25 +00001975
kwiberg5a25d952016-08-17 07:31:12 -07001976 if (!output_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08001977 _engineStatisticsPtr->SetLastError(
1978 VE_INVALID_ARGUMENT, kTraceError,
1979 "StartPlayingFileLocally() filePlayer format isnot correct");
1980 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001981 }
1982
kwiberg55b97fe2016-01-28 05:22:45 -08001983 const uint32_t notificationTime(0);
henrike@webrtc.orgb37c6282011-10-31 23:53:04 +00001984
kwiberg4ec01d92016-08-22 08:43:54 -07001985 if (output_file_player_->StartPlayingFile(stream, startPosition,
kwiberg5a25d952016-08-17 07:31:12 -07001986 volumeScaling, notificationTime,
1987 stopPosition, codecInst) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08001988 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
1989 "StartPlayingFile() failed to "
1990 "start file playout");
kwiberg5a25d952016-08-17 07:31:12 -07001991 output_file_player_->StopPlayingFile();
1992 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08001993 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00001994 }
kwiberg5a25d952016-08-17 07:31:12 -07001995 output_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08001996 channel_state_.SetOutputFilePlaying(true);
1997 }
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00001998
kwiberg55b97fe2016-01-28 05:22:45 -08001999 if (RegisterFilePlayingToMixer() != 0)
2000 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002001
kwiberg55b97fe2016-01-28 05:22:45 -08002002 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002003}
2004
kwiberg55b97fe2016-01-28 05:22:45 -08002005int Channel::StopPlayingFileLocally() {
2006 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2007 "Channel::StopPlayingFileLocally()");
niklase@google.com470e71d2011-07-07 08:21:25 +00002008
kwiberg55b97fe2016-01-28 05:22:45 -08002009 if (!channel_state_.Get().output_file_playing) {
niklase@google.com470e71d2011-07-07 08:21:25 +00002010 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002011 }
2012
2013 {
2014 rtc::CritScope cs(&_fileCritSect);
2015
kwiberg5a25d952016-08-17 07:31:12 -07002016 if (output_file_player_->StopPlayingFile() != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002017 _engineStatisticsPtr->SetLastError(
2018 VE_STOP_RECORDING_FAILED, kTraceError,
2019 "StopPlayingFile() could not stop playing");
2020 return -1;
2021 }
kwiberg5a25d952016-08-17 07:31:12 -07002022 output_file_player_->RegisterModuleFileCallback(NULL);
2023 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002024 channel_state_.SetOutputFilePlaying(false);
2025 }
2026 // _fileCritSect cannot be taken while calling
2027 // SetAnonymousMixibilityStatus. Refer to comments in
2028 // StartPlayingFileLocally(const char* ...) for more details.
2029 if (_outputMixerPtr->SetAnonymousMixabilityStatus(*this, false) != 0) {
2030 _engineStatisticsPtr->SetLastError(
2031 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
2032 "StopPlayingFile() failed to stop participant from playing as"
2033 "file in the mixer");
2034 return -1;
2035 }
2036
2037 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002038}
2039
kwiberg55b97fe2016-01-28 05:22:45 -08002040int Channel::IsPlayingFileLocally() const {
2041 return channel_state_.Get().output_file_playing;
niklase@google.com470e71d2011-07-07 08:21:25 +00002042}
2043
kwiberg55b97fe2016-01-28 05:22:45 -08002044int Channel::RegisterFilePlayingToMixer() {
2045 // Return success for not registering for file playing to mixer if:
2046 // 1. playing file before playout is started on that channel.
2047 // 2. starting playout without file playing on that channel.
2048 if (!channel_state_.Get().playing ||
2049 !channel_state_.Get().output_file_playing) {
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00002050 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002051 }
2052
2053 // |_fileCritSect| cannot be taken while calling
2054 // SetAnonymousMixabilityStatus() since as soon as the participant is added
2055 // frames can be pulled by the mixer. Since the frames are generated from
2056 // the file, _fileCritSect will be taken. This would result in a deadlock.
2057 if (_outputMixerPtr->SetAnonymousMixabilityStatus(*this, true) != 0) {
2058 channel_state_.SetOutputFilePlaying(false);
2059 rtc::CritScope cs(&_fileCritSect);
2060 _engineStatisticsPtr->SetLastError(
2061 VE_AUDIO_CONF_MIX_MODULE_ERROR, kTraceError,
2062 "StartPlayingFile() failed to add participant as file to mixer");
kwiberg5a25d952016-08-17 07:31:12 -07002063 output_file_player_->StopPlayingFile();
2064 output_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002065 return -1;
2066 }
2067
2068 return 0;
braveyao@webrtc.orgab129902012-06-04 03:26:39 +00002069}
2070
niklase@google.com470e71d2011-07-07 08:21:25 +00002071int Channel::StartPlayingFileAsMicrophone(const char* fileName,
pbos@webrtc.org92135212013-05-14 08:31:39 +00002072 bool loop,
2073 FileFormats format,
2074 int startPosition,
2075 float volumeScaling,
2076 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08002077 const CodecInst* codecInst) {
2078 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2079 "Channel::StartPlayingFileAsMicrophone(fileNameUTF8[]=%s, "
2080 "loop=%d, format=%d, volumeScaling=%5.3f, startPosition=%d, "
2081 "stopPosition=%d)",
2082 fileName, loop, format, volumeScaling, startPosition,
2083 stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00002084
kwiberg55b97fe2016-01-28 05:22:45 -08002085 rtc::CritScope cs(&_fileCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00002086
kwiberg55b97fe2016-01-28 05:22:45 -08002087 if (channel_state_.Get().input_file_playing) {
2088 _engineStatisticsPtr->SetLastError(
2089 VE_ALREADY_PLAYING, kTraceWarning,
2090 "StartPlayingFileAsMicrophone() filePlayer is playing");
niklase@google.com470e71d2011-07-07 08:21:25 +00002091 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002092 }
2093
2094 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07002095 if (input_file_player_) {
2096 input_file_player_->RegisterModuleFileCallback(NULL);
2097 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002098 }
2099
2100 // Create the instance
kwiberg5b356f42016-09-08 04:32:33 -07002101 input_file_player_ = FilePlayer::CreateFilePlayer(_inputFilePlayerId,
kwiberg5a25d952016-08-17 07:31:12 -07002102 (const FileFormats)format);
kwiberg55b97fe2016-01-28 05:22:45 -08002103
kwiberg5a25d952016-08-17 07:31:12 -07002104 if (!input_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002105 _engineStatisticsPtr->SetLastError(
2106 VE_INVALID_ARGUMENT, kTraceError,
2107 "StartPlayingFileAsMicrophone() filePlayer format isnot correct");
2108 return -1;
2109 }
2110
2111 const uint32_t notificationTime(0);
2112
kwiberg5a25d952016-08-17 07:31:12 -07002113 if (input_file_player_->StartPlayingFile(
kwiberg55b97fe2016-01-28 05:22:45 -08002114 fileName, loop, startPosition, volumeScaling, notificationTime,
2115 stopPosition, (const CodecInst*)codecInst) != 0) {
2116 _engineStatisticsPtr->SetLastError(
2117 VE_BAD_FILE, kTraceError,
2118 "StartPlayingFile() failed to start file playout");
kwiberg5a25d952016-08-17 07:31:12 -07002119 input_file_player_->StopPlayingFile();
2120 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002121 return -1;
2122 }
kwiberg5a25d952016-08-17 07:31:12 -07002123 input_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002124 channel_state_.SetInputFilePlaying(true);
2125
2126 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002127}
2128
2129int Channel::StartPlayingFileAsMicrophone(InStream* stream,
pbos@webrtc.org92135212013-05-14 08:31:39 +00002130 FileFormats format,
2131 int startPosition,
2132 float volumeScaling,
2133 int stopPosition,
kwiberg55b97fe2016-01-28 05:22:45 -08002134 const CodecInst* codecInst) {
2135 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2136 "Channel::StartPlayingFileAsMicrophone(format=%d, "
2137 "volumeScaling=%5.3f, startPosition=%d, stopPosition=%d)",
2138 format, volumeScaling, startPosition, stopPosition);
niklase@google.com470e71d2011-07-07 08:21:25 +00002139
kwiberg55b97fe2016-01-28 05:22:45 -08002140 if (stream == NULL) {
2141 _engineStatisticsPtr->SetLastError(
2142 VE_BAD_FILE, kTraceError,
2143 "StartPlayingFileAsMicrophone NULL as input stream");
2144 return -1;
2145 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002146
kwiberg55b97fe2016-01-28 05:22:45 -08002147 rtc::CritScope cs(&_fileCritSect);
henrika@webrtc.org944cbeb2014-03-18 10:32:33 +00002148
kwiberg55b97fe2016-01-28 05:22:45 -08002149 if (channel_state_.Get().input_file_playing) {
2150 _engineStatisticsPtr->SetLastError(
2151 VE_ALREADY_PLAYING, kTraceWarning,
2152 "StartPlayingFileAsMicrophone() is playing");
niklase@google.com470e71d2011-07-07 08:21:25 +00002153 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002154 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002155
kwiberg55b97fe2016-01-28 05:22:45 -08002156 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07002157 if (input_file_player_) {
2158 input_file_player_->RegisterModuleFileCallback(NULL);
2159 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002160 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002161
kwiberg55b97fe2016-01-28 05:22:45 -08002162 // Create the instance
kwiberg5b356f42016-09-08 04:32:33 -07002163 input_file_player_ = FilePlayer::CreateFilePlayer(_inputFilePlayerId,
kwiberg5a25d952016-08-17 07:31:12 -07002164 (const FileFormats)format);
kwiberg55b97fe2016-01-28 05:22:45 -08002165
kwiberg5a25d952016-08-17 07:31:12 -07002166 if (!input_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002167 _engineStatisticsPtr->SetLastError(
2168 VE_INVALID_ARGUMENT, kTraceError,
2169 "StartPlayingInputFile() filePlayer format isnot correct");
2170 return -1;
2171 }
2172
2173 const uint32_t notificationTime(0);
2174
kwiberg4ec01d92016-08-22 08:43:54 -07002175 if (input_file_player_->StartPlayingFile(stream, startPosition, volumeScaling,
2176 notificationTime, stopPosition,
2177 codecInst) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002178 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
2179 "StartPlayingFile() failed to start "
2180 "file playout");
kwiberg5a25d952016-08-17 07:31:12 -07002181 input_file_player_->StopPlayingFile();
2182 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002183 return -1;
2184 }
2185
kwiberg5a25d952016-08-17 07:31:12 -07002186 input_file_player_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002187 channel_state_.SetInputFilePlaying(true);
2188
2189 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002190}
2191
kwiberg55b97fe2016-01-28 05:22:45 -08002192int Channel::StopPlayingFileAsMicrophone() {
2193 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2194 "Channel::StopPlayingFileAsMicrophone()");
2195
2196 rtc::CritScope cs(&_fileCritSect);
2197
2198 if (!channel_state_.Get().input_file_playing) {
2199 return 0;
2200 }
2201
kwiberg5a25d952016-08-17 07:31:12 -07002202 if (input_file_player_->StopPlayingFile() != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002203 _engineStatisticsPtr->SetLastError(
2204 VE_STOP_RECORDING_FAILED, kTraceError,
2205 "StopPlayingFile() could not stop playing");
2206 return -1;
2207 }
kwiberg5a25d952016-08-17 07:31:12 -07002208 input_file_player_->RegisterModuleFileCallback(NULL);
2209 input_file_player_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002210 channel_state_.SetInputFilePlaying(false);
2211
2212 return 0;
2213}
2214
2215int Channel::IsPlayingFileAsMicrophone() const {
2216 return channel_state_.Get().input_file_playing;
niklase@google.com470e71d2011-07-07 08:21:25 +00002217}
2218
leozwang@webrtc.org813e4b02012-03-01 18:34:25 +00002219int Channel::StartRecordingPlayout(const char* fileName,
kwiberg55b97fe2016-01-28 05:22:45 -08002220 const CodecInst* codecInst) {
2221 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2222 "Channel::StartRecordingPlayout(fileName=%s)", fileName);
niklase@google.com470e71d2011-07-07 08:21:25 +00002223
kwiberg55b97fe2016-01-28 05:22:45 -08002224 if (_outputFileRecording) {
2225 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, -1),
2226 "StartRecordingPlayout() is already recording");
niklase@google.com470e71d2011-07-07 08:21:25 +00002227 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002228 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002229
kwiberg55b97fe2016-01-28 05:22:45 -08002230 FileFormats format;
2231 const uint32_t notificationTime(0); // Not supported in VoE
2232 CodecInst dummyCodec = {100, "L16", 16000, 320, 1, 320000};
niklase@google.com470e71d2011-07-07 08:21:25 +00002233
kwiberg55b97fe2016-01-28 05:22:45 -08002234 if ((codecInst != NULL) &&
2235 ((codecInst->channels < 1) || (codecInst->channels > 2))) {
2236 _engineStatisticsPtr->SetLastError(
2237 VE_BAD_ARGUMENT, kTraceError,
2238 "StartRecordingPlayout() invalid compression");
2239 return (-1);
2240 }
2241 if (codecInst == NULL) {
2242 format = kFileFormatPcm16kHzFile;
2243 codecInst = &dummyCodec;
2244 } else if ((STR_CASE_CMP(codecInst->plname, "L16") == 0) ||
2245 (STR_CASE_CMP(codecInst->plname, "PCMU") == 0) ||
2246 (STR_CASE_CMP(codecInst->plname, "PCMA") == 0)) {
2247 format = kFileFormatWavFile;
2248 } else {
2249 format = kFileFormatCompressedFile;
2250 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002251
kwiberg55b97fe2016-01-28 05:22:45 -08002252 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002253
kwiberg55b97fe2016-01-28 05:22:45 -08002254 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07002255 if (output_file_recorder_) {
2256 output_file_recorder_->RegisterModuleFileCallback(NULL);
2257 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002258 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002259
kwiberg5a25d952016-08-17 07:31:12 -07002260 output_file_recorder_ = FileRecorder::CreateFileRecorder(
kwiberg55b97fe2016-01-28 05:22:45 -08002261 _outputFileRecorderId, (const FileFormats)format);
kwiberg5a25d952016-08-17 07:31:12 -07002262 if (!output_file_recorder_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002263 _engineStatisticsPtr->SetLastError(
2264 VE_INVALID_ARGUMENT, kTraceError,
2265 "StartRecordingPlayout() fileRecorder format isnot correct");
2266 return -1;
2267 }
2268
kwiberg5a25d952016-08-17 07:31:12 -07002269 if (output_file_recorder_->StartRecordingAudioFile(
kwiberg55b97fe2016-01-28 05:22:45 -08002270 fileName, (const CodecInst&)*codecInst, notificationTime) != 0) {
2271 _engineStatisticsPtr->SetLastError(
2272 VE_BAD_FILE, kTraceError,
2273 "StartRecordingAudioFile() failed to start file recording");
kwiberg5a25d952016-08-17 07:31:12 -07002274 output_file_recorder_->StopRecording();
2275 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002276 return -1;
2277 }
kwiberg5a25d952016-08-17 07:31:12 -07002278 output_file_recorder_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002279 _outputFileRecording = true;
2280
2281 return 0;
2282}
2283
2284int Channel::StartRecordingPlayout(OutStream* stream,
2285 const CodecInst* codecInst) {
2286 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2287 "Channel::StartRecordingPlayout()");
2288
2289 if (_outputFileRecording) {
2290 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, -1),
2291 "StartRecordingPlayout() is already recording");
niklase@google.com470e71d2011-07-07 08:21:25 +00002292 return 0;
kwiberg55b97fe2016-01-28 05:22:45 -08002293 }
2294
2295 FileFormats format;
2296 const uint32_t notificationTime(0); // Not supported in VoE
2297 CodecInst dummyCodec = {100, "L16", 16000, 320, 1, 320000};
2298
2299 if (codecInst != NULL && codecInst->channels != 1) {
2300 _engineStatisticsPtr->SetLastError(
2301 VE_BAD_ARGUMENT, kTraceError,
2302 "StartRecordingPlayout() invalid compression");
2303 return (-1);
2304 }
2305 if (codecInst == NULL) {
2306 format = kFileFormatPcm16kHzFile;
2307 codecInst = &dummyCodec;
2308 } else if ((STR_CASE_CMP(codecInst->plname, "L16") == 0) ||
2309 (STR_CASE_CMP(codecInst->plname, "PCMU") == 0) ||
2310 (STR_CASE_CMP(codecInst->plname, "PCMA") == 0)) {
2311 format = kFileFormatWavFile;
2312 } else {
2313 format = kFileFormatCompressedFile;
2314 }
2315
2316 rtc::CritScope cs(&_fileCritSect);
2317
2318 // Destroy the old instance
kwiberg5a25d952016-08-17 07:31:12 -07002319 if (output_file_recorder_) {
2320 output_file_recorder_->RegisterModuleFileCallback(NULL);
2321 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002322 }
2323
kwiberg5a25d952016-08-17 07:31:12 -07002324 output_file_recorder_ = FileRecorder::CreateFileRecorder(
kwiberg55b97fe2016-01-28 05:22:45 -08002325 _outputFileRecorderId, (const FileFormats)format);
kwiberg5a25d952016-08-17 07:31:12 -07002326 if (!output_file_recorder_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002327 _engineStatisticsPtr->SetLastError(
2328 VE_INVALID_ARGUMENT, kTraceError,
2329 "StartRecordingPlayout() fileRecorder format isnot correct");
2330 return -1;
2331 }
2332
kwiberg4ec01d92016-08-22 08:43:54 -07002333 if (output_file_recorder_->StartRecordingAudioFile(stream, *codecInst,
kwiberg5a25d952016-08-17 07:31:12 -07002334 notificationTime) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002335 _engineStatisticsPtr->SetLastError(VE_BAD_FILE, kTraceError,
2336 "StartRecordingPlayout() failed to "
2337 "start file recording");
kwiberg5a25d952016-08-17 07:31:12 -07002338 output_file_recorder_->StopRecording();
2339 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002340 return -1;
2341 }
2342
kwiberg5a25d952016-08-17 07:31:12 -07002343 output_file_recorder_->RegisterModuleFileCallback(this);
kwiberg55b97fe2016-01-28 05:22:45 -08002344 _outputFileRecording = true;
2345
2346 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002347}
2348
kwiberg55b97fe2016-01-28 05:22:45 -08002349int Channel::StopRecordingPlayout() {
2350 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, -1),
2351 "Channel::StopRecordingPlayout()");
2352
2353 if (!_outputFileRecording) {
2354 WEBRTC_TRACE(kTraceError, kTraceVoice, VoEId(_instanceId, -1),
2355 "StopRecordingPlayout() isnot recording");
2356 return -1;
2357 }
2358
2359 rtc::CritScope cs(&_fileCritSect);
2360
kwiberg5a25d952016-08-17 07:31:12 -07002361 if (output_file_recorder_->StopRecording() != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002362 _engineStatisticsPtr->SetLastError(
2363 VE_STOP_RECORDING_FAILED, kTraceError,
2364 "StopRecording() could not stop recording");
2365 return (-1);
2366 }
kwiberg5a25d952016-08-17 07:31:12 -07002367 output_file_recorder_->RegisterModuleFileCallback(NULL);
2368 output_file_recorder_.reset();
kwiberg55b97fe2016-01-28 05:22:45 -08002369 _outputFileRecording = false;
2370
2371 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002372}
2373
kwiberg55b97fe2016-01-28 05:22:45 -08002374void Channel::SetMixWithMicStatus(bool mix) {
2375 rtc::CritScope cs(&_fileCritSect);
2376 _mixFileWithMicrophone = mix;
niklase@google.com470e71d2011-07-07 08:21:25 +00002377}
2378
solenberg8d73f8c2017-03-08 01:52:20 -08002379int Channel::GetSpeechOutputLevel() const {
2380 return _outputAudioLevel.Level();
niklase@google.com470e71d2011-07-07 08:21:25 +00002381}
2382
solenberg8d73f8c2017-03-08 01:52:20 -08002383int Channel::GetSpeechOutputLevelFullRange() const {
2384 return _outputAudioLevel.LevelFullRange();
kwiberg55b97fe2016-01-28 05:22:45 -08002385}
2386
zsteine76bd3a2017-07-14 12:17:49 -07002387double Channel::GetTotalOutputEnergy() const {
2388 return totalOutputEnergy_;
2389}
2390
2391double Channel::GetTotalOutputDuration() const {
2392 return totalOutputDuration_;
2393}
2394
solenberg8d73f8c2017-03-08 01:52:20 -08002395void Channel::SetInputMute(bool enable) {
kwiberg55b97fe2016-01-28 05:22:45 -08002396 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07002397 input_mute_ = enable;
niklase@google.com470e71d2011-07-07 08:21:25 +00002398}
2399
solenberg1c2af8e2016-03-24 10:36:00 -07002400bool Channel::InputMute() const {
kwiberg55b97fe2016-01-28 05:22:45 -08002401 rtc::CritScope cs(&volume_settings_critsect_);
solenberg1c2af8e2016-03-24 10:36:00 -07002402 return input_mute_;
niklase@google.com470e71d2011-07-07 08:21:25 +00002403}
2404
solenberg8d73f8c2017-03-08 01:52:20 -08002405void Channel::SetChannelOutputVolumeScaling(float scaling) {
kwiberg55b97fe2016-01-28 05:22:45 -08002406 rtc::CritScope cs(&volume_settings_critsect_);
kwiberg55b97fe2016-01-28 05:22:45 -08002407 _outputGain = scaling;
niklase@google.com470e71d2011-07-07 08:21:25 +00002408}
2409
solenberg8842c3e2016-03-11 03:06:41 -08002410int Channel::SendTelephoneEventOutband(int event, int duration_ms) {
kwiberg55b97fe2016-01-28 05:22:45 -08002411 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
solenberg8842c3e2016-03-11 03:06:41 -08002412 "Channel::SendTelephoneEventOutband(...)");
2413 RTC_DCHECK_LE(0, event);
2414 RTC_DCHECK_GE(255, event);
2415 RTC_DCHECK_LE(0, duration_ms);
2416 RTC_DCHECK_GE(65535, duration_ms);
kwiberg55b97fe2016-01-28 05:22:45 -08002417 if (!Sending()) {
2418 return -1;
2419 }
solenberg8842c3e2016-03-11 03:06:41 -08002420 if (_rtpRtcpModule->SendTelephoneEventOutband(
2421 event, duration_ms, kTelephoneEventAttenuationdB) != 0) {
kwiberg55b97fe2016-01-28 05:22:45 -08002422 _engineStatisticsPtr->SetLastError(
2423 VE_SEND_DTMF_FAILED, kTraceWarning,
2424 "SendTelephoneEventOutband() failed to send event");
2425 return -1;
2426 }
2427 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002428}
2429
solenbergffbbcac2016-11-17 05:25:37 -08002430int Channel::SetSendTelephoneEventPayloadType(int payload_type,
2431 int payload_frequency) {
kwiberg55b97fe2016-01-28 05:22:45 -08002432 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
niklase@google.com470e71d2011-07-07 08:21:25 +00002433 "Channel::SetSendTelephoneEventPayloadType()");
solenberg31642aa2016-03-14 08:00:37 -07002434 RTC_DCHECK_LE(0, payload_type);
2435 RTC_DCHECK_GE(127, payload_type);
2436 CodecInst codec = {0};
solenberg31642aa2016-03-14 08:00:37 -07002437 codec.pltype = payload_type;
solenbergffbbcac2016-11-17 05:25:37 -08002438 codec.plfreq = payload_frequency;
kwiberg55b97fe2016-01-28 05:22:45 -08002439 memcpy(codec.plname, "telephone-event", 16);
2440 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
2441 _rtpRtcpModule->DeRegisterSendPayload(codec.pltype);
2442 if (_rtpRtcpModule->RegisterSendPayload(codec) != 0) {
2443 _engineStatisticsPtr->SetLastError(
2444 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2445 "SetSendTelephoneEventPayloadType() failed to register send"
2446 "payload type");
2447 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002448 }
kwiberg55b97fe2016-01-28 05:22:45 -08002449 }
kwiberg55b97fe2016-01-28 05:22:45 -08002450 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002451}
2452
kwiberg55b97fe2016-01-28 05:22:45 -08002453int Channel::SetLocalSSRC(unsigned int ssrc) {
2454 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2455 "Channel::SetLocalSSRC()");
2456 if (channel_state_.Get().sending) {
2457 _engineStatisticsPtr->SetLastError(VE_ALREADY_SENDING, kTraceError,
2458 "SetLocalSSRC() already sending");
2459 return -1;
2460 }
2461 _rtpRtcpModule->SetSSRC(ssrc);
2462 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002463}
2464
kwiberg55b97fe2016-01-28 05:22:45 -08002465int Channel::GetLocalSSRC(unsigned int& ssrc) {
2466 ssrc = _rtpRtcpModule->SSRC();
2467 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002468}
2469
kwiberg55b97fe2016-01-28 05:22:45 -08002470int Channel::GetRemoteSSRC(unsigned int& ssrc) {
2471 ssrc = rtp_receiver_->SSRC();
2472 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002473}
2474
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002475int Channel::SetSendAudioLevelIndicationStatus(bool enable, unsigned char id) {
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00002476 _includeAudioLevelIndication = enable;
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00002477 return SetSendRtpHeaderExtension(enable, kRtpExtensionAudioLevel, id);
niklase@google.com470e71d2011-07-07 08:21:25 +00002478}
andrew@webrtc.orgf3930e92013-09-18 22:37:32 +00002479
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00002480int Channel::SetReceiveAudioLevelIndicationStatus(bool enable,
2481 unsigned char id) {
kwiberg55b97fe2016-01-28 05:22:45 -08002482 rtp_header_parser_->DeregisterRtpHeaderExtension(kRtpExtensionAudioLevel);
2483 if (enable &&
2484 !rtp_header_parser_->RegisterRtpHeaderExtension(kRtpExtensionAudioLevel,
2485 id)) {
wu@webrtc.org93fd25c2014-04-24 20:33:08 +00002486 return -1;
2487 }
2488 return 0;
2489}
2490
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002491void Channel::EnableSendTransportSequenceNumber(int id) {
2492 int ret =
2493 SetSendRtpHeaderExtension(true, kRtpExtensionTransportSequenceNumber, id);
2494 RTC_DCHECK_EQ(0, ret);
2495}
2496
stefan3313ec92016-01-21 06:32:43 -08002497void Channel::EnableReceiveTransportSequenceNumber(int id) {
2498 rtp_header_parser_->DeregisterRtpHeaderExtension(
2499 kRtpExtensionTransportSequenceNumber);
2500 bool ret = rtp_header_parser_->RegisterRtpHeaderExtension(
2501 kRtpExtensionTransportSequenceNumber, id);
2502 RTC_DCHECK(ret);
2503}
2504
stefanbba9dec2016-02-01 04:39:55 -08002505void Channel::RegisterSenderCongestionControlObjects(
nisseb8f9a322017-03-27 05:36:15 -07002506 RtpTransportControllerSendInterface* transport,
stefan7de8d642017-02-07 07:14:08 -08002507 RtcpBandwidthObserver* bandwidth_observer) {
nisseb8f9a322017-03-27 05:36:15 -07002508 RtpPacketSender* rtp_packet_sender = transport->packet_sender();
2509 TransportFeedbackObserver* transport_feedback_observer =
2510 transport->transport_feedback_observer();
2511 PacketRouter* packet_router = transport->packet_router();
2512
stefanbba9dec2016-02-01 04:39:55 -08002513 RTC_DCHECK(rtp_packet_sender);
2514 RTC_DCHECK(transport_feedback_observer);
2515 RTC_DCHECK(packet_router && !packet_router_);
stefan7de8d642017-02-07 07:14:08 -08002516 rtcp_observer_->SetBandwidthObserver(bandwidth_observer);
stefanbba9dec2016-02-01 04:39:55 -08002517 feedback_observer_proxy_->SetTransportFeedbackObserver(
2518 transport_feedback_observer);
2519 seq_num_allocator_proxy_->SetSequenceNumberAllocator(packet_router);
2520 rtp_packet_sender_proxy_->SetPacketSender(rtp_packet_sender);
2521 _rtpRtcpModule->SetStorePacketsStatus(true, 600);
nissefdbfdc92017-03-31 05:44:52 -07002522 packet_router->AddSendRtpModule(_rtpRtcpModule.get());
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002523 packet_router_ = packet_router;
2524}
2525
stefanbba9dec2016-02-01 04:39:55 -08002526void Channel::RegisterReceiverCongestionControlObjects(
2527 PacketRouter* packet_router) {
2528 RTC_DCHECK(packet_router && !packet_router_);
nissefdbfdc92017-03-31 05:44:52 -07002529 packet_router->AddReceiveRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08002530 packet_router_ = packet_router;
2531}
2532
nissefdbfdc92017-03-31 05:44:52 -07002533void Channel::ResetSenderCongestionControlObjects() {
stefanbba9dec2016-02-01 04:39:55 -08002534 RTC_DCHECK(packet_router_);
2535 _rtpRtcpModule->SetStorePacketsStatus(false, 600);
stefan7de8d642017-02-07 07:14:08 -08002536 rtcp_observer_->SetBandwidthObserver(nullptr);
stefanbba9dec2016-02-01 04:39:55 -08002537 feedback_observer_proxy_->SetTransportFeedbackObserver(nullptr);
2538 seq_num_allocator_proxy_->SetSequenceNumberAllocator(nullptr);
nissefdbfdc92017-03-31 05:44:52 -07002539 packet_router_->RemoveSendRtpModule(_rtpRtcpModule.get());
stefanbba9dec2016-02-01 04:39:55 -08002540 packet_router_ = nullptr;
2541 rtp_packet_sender_proxy_->SetPacketSender(nullptr);
2542}
2543
nissefdbfdc92017-03-31 05:44:52 -07002544void Channel::ResetReceiverCongestionControlObjects() {
2545 RTC_DCHECK(packet_router_);
2546 packet_router_->RemoveReceiveRtpModule(_rtpRtcpModule.get());
2547 packet_router_ = nullptr;
2548}
2549
pbos@webrtc.orgd16e8392014-12-19 13:49:55 +00002550void Channel::SetRTCPStatus(bool enable) {
2551 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2552 "Channel::SetRTCPStatus()");
pbosda903ea2015-10-02 02:36:56 -07002553 _rtpRtcpModule->SetRTCPStatus(enable ? RtcpMode::kCompound : RtcpMode::kOff);
niklase@google.com470e71d2011-07-07 08:21:25 +00002554}
2555
kwiberg55b97fe2016-01-28 05:22:45 -08002556int Channel::GetRTCPStatus(bool& enabled) {
pbosda903ea2015-10-02 02:36:56 -07002557 RtcpMode method = _rtpRtcpModule->RTCP();
2558 enabled = (method != RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08002559 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002560}
2561
kwiberg55b97fe2016-01-28 05:22:45 -08002562int Channel::SetRTCP_CNAME(const char cName[256]) {
2563 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2564 "Channel::SetRTCP_CNAME()");
2565 if (_rtpRtcpModule->SetCNAME(cName) != 0) {
2566 _engineStatisticsPtr->SetLastError(
2567 VE_RTP_RTCP_MODULE_ERROR, kTraceError,
2568 "SetRTCP_CNAME() failed to set RTCP CNAME");
2569 return -1;
2570 }
2571 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002572}
2573
kwiberg55b97fe2016-01-28 05:22:45 -08002574int Channel::GetRemoteRTCP_CNAME(char cName[256]) {
2575 if (cName == NULL) {
2576 _engineStatisticsPtr->SetLastError(
2577 VE_INVALID_ARGUMENT, kTraceError,
2578 "GetRemoteRTCP_CNAME() invalid CNAME input buffer");
2579 return -1;
2580 }
2581 char cname[RTCP_CNAME_SIZE];
2582 const uint32_t remoteSSRC = rtp_receiver_->SSRC();
2583 if (_rtpRtcpModule->RemoteCNAME(remoteSSRC, cname) != 0) {
2584 _engineStatisticsPtr->SetLastError(
2585 VE_CANNOT_RETRIEVE_CNAME, kTraceError,
2586 "GetRemoteRTCP_CNAME() failed to retrieve remote RTCP CNAME");
2587 return -1;
2588 }
2589 strcpy(cName, cname);
2590 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002591}
2592
kwiberg55b97fe2016-01-28 05:22:45 -08002593int Channel::SendApplicationDefinedRTCPPacket(
2594 unsigned char subType,
2595 unsigned int name,
2596 const char* data,
2597 unsigned short dataLengthInBytes) {
2598 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2599 "Channel::SendApplicationDefinedRTCPPacket()");
2600 if (!channel_state_.Get().sending) {
2601 _engineStatisticsPtr->SetLastError(
2602 VE_NOT_SENDING, kTraceError,
2603 "SendApplicationDefinedRTCPPacket() not sending");
2604 return -1;
2605 }
2606 if (NULL == data) {
2607 _engineStatisticsPtr->SetLastError(
2608 VE_INVALID_ARGUMENT, kTraceError,
2609 "SendApplicationDefinedRTCPPacket() invalid data value");
2610 return -1;
2611 }
2612 if (dataLengthInBytes % 4 != 0) {
2613 _engineStatisticsPtr->SetLastError(
2614 VE_INVALID_ARGUMENT, kTraceError,
2615 "SendApplicationDefinedRTCPPacket() invalid length value");
2616 return -1;
2617 }
2618 RtcpMode status = _rtpRtcpModule->RTCP();
2619 if (status == RtcpMode::kOff) {
2620 _engineStatisticsPtr->SetLastError(
2621 VE_RTCP_ERROR, kTraceError,
2622 "SendApplicationDefinedRTCPPacket() RTCP is disabled");
2623 return -1;
2624 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002625
kwiberg55b97fe2016-01-28 05:22:45 -08002626 // Create and schedule the RTCP APP packet for transmission
2627 if (_rtpRtcpModule->SetRTCPApplicationSpecificData(
2628 subType, name, (const unsigned char*)data, dataLengthInBytes) != 0) {
2629 _engineStatisticsPtr->SetLastError(
2630 VE_SEND_ERROR, kTraceError,
2631 "SendApplicationDefinedRTCPPacket() failed to send RTCP packet");
2632 return -1;
2633 }
2634 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002635}
2636
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002637int Channel::GetRemoteRTCPReportBlocks(
2638 std::vector<ReportBlock>* report_blocks) {
2639 if (report_blocks == NULL) {
kwiberg55b97fe2016-01-28 05:22:45 -08002640 _engineStatisticsPtr->SetLastError(
2641 VE_INVALID_ARGUMENT, kTraceError,
2642 "GetRemoteRTCPReportBlock()s invalid report_blocks.");
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002643 return -1;
2644 }
2645
2646 // Get the report blocks from the latest received RTCP Sender or Receiver
2647 // Report. Each element in the vector contains the sender's SSRC and a
2648 // report block according to RFC 3550.
2649 std::vector<RTCPReportBlock> rtcp_report_blocks;
2650 if (_rtpRtcpModule->RemoteRTCPStat(&rtcp_report_blocks) != 0) {
henrika@webrtc.org8a2fc882012-08-22 08:53:55 +00002651 return -1;
2652 }
2653
2654 if (rtcp_report_blocks.empty())
2655 return 0;
2656
2657 std::vector<RTCPReportBlock>::const_iterator it = rtcp_report_blocks.begin();
2658 for (; it != rtcp_report_blocks.end(); ++it) {
2659 ReportBlock report_block;
2660 report_block.sender_SSRC = it->remoteSSRC;
2661 report_block.source_SSRC = it->sourceSSRC;
2662 report_block.fraction_lost = it->fractionLost;
2663 report_block.cumulative_num_packets_lost = it->cumulativeLost;
2664 report_block.extended_highest_sequence_number = it->extendedHighSeqNum;
2665 report_block.interarrival_jitter = it->jitter;
2666 report_block.last_SR_timestamp = it->lastSR;
2667 report_block.delay_since_last_SR = it->delaySinceLastSR;
2668 report_blocks->push_back(report_block);
2669 }
2670 return 0;
2671}
2672
kwiberg55b97fe2016-01-28 05:22:45 -08002673int Channel::GetRTPStatistics(CallStatistics& stats) {
2674 // --- RtcpStatistics
niklase@google.com470e71d2011-07-07 08:21:25 +00002675
kwiberg55b97fe2016-01-28 05:22:45 -08002676 // The jitter statistics is updated for each received RTP packet and is
2677 // based on received packets.
2678 RtcpStatistics statistics;
2679 StreamStatistician* statistician =
2680 rtp_receive_statistics_->GetStatistician(rtp_receiver_->SSRC());
Peter Boström59013bc2016-02-12 11:35:08 +01002681 if (statistician) {
2682 statistician->GetStatistics(&statistics,
2683 _rtpRtcpModule->RTCP() == RtcpMode::kOff);
kwiberg55b97fe2016-01-28 05:22:45 -08002684 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002685
kwiberg55b97fe2016-01-28 05:22:45 -08002686 stats.fractionLost = statistics.fraction_lost;
2687 stats.cumulativeLost = statistics.cumulative_lost;
2688 stats.extendedMax = statistics.extended_max_sequence_number;
2689 stats.jitterSamples = statistics.jitter;
niklase@google.com470e71d2011-07-07 08:21:25 +00002690
kwiberg55b97fe2016-01-28 05:22:45 -08002691 // --- RTT
2692 stats.rttMs = GetRTT(true);
niklase@google.com470e71d2011-07-07 08:21:25 +00002693
kwiberg55b97fe2016-01-28 05:22:45 -08002694 // --- Data counters
niklase@google.com470e71d2011-07-07 08:21:25 +00002695
kwiberg55b97fe2016-01-28 05:22:45 -08002696 size_t bytesSent(0);
2697 uint32_t packetsSent(0);
2698 size_t bytesReceived(0);
2699 uint32_t packetsReceived(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00002700
kwiberg55b97fe2016-01-28 05:22:45 -08002701 if (statistician) {
2702 statistician->GetDataCounters(&bytesReceived, &packetsReceived);
2703 }
wu@webrtc.org822fbd82013-08-15 23:38:54 +00002704
kwiberg55b97fe2016-01-28 05:22:45 -08002705 if (_rtpRtcpModule->DataCountersRTP(&bytesSent, &packetsSent) != 0) {
2706 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2707 "GetRTPStatistics() failed to retrieve RTP datacounters =>"
2708 " output will not be complete");
2709 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002710
kwiberg55b97fe2016-01-28 05:22:45 -08002711 stats.bytesSent = bytesSent;
2712 stats.packetsSent = packetsSent;
2713 stats.bytesReceived = bytesReceived;
2714 stats.packetsReceived = packetsReceived;
niklase@google.com470e71d2011-07-07 08:21:25 +00002715
kwiberg55b97fe2016-01-28 05:22:45 -08002716 // --- Timestamps
2717 {
2718 rtc::CritScope lock(&ts_stats_lock_);
2719 stats.capture_start_ntp_time_ms_ = capture_start_ntp_time_ms_;
2720 }
2721 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002722}
2723
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002724int Channel::SetCodecFECStatus(bool enable) {
2725 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2726 "Channel::SetCodecFECStatus()");
2727
kwibergc8d071e2016-04-06 12:22:38 -07002728 if (!codec_manager_.SetCodecFEC(enable) ||
2729 !codec_manager_.MakeEncoder(&rent_a_codec_, audio_coding_.get())) {
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002730 _engineStatisticsPtr->SetLastError(
2731 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
2732 "SetCodecFECStatus() failed to set FEC state");
2733 return -1;
2734 }
2735 return 0;
2736}
2737
2738bool Channel::GetCodecFECStatus() {
kwibergc8d071e2016-04-06 12:22:38 -07002739 return codec_manager_.GetStackParams()->use_codec_fec;
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00002740}
2741
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002742void Channel::SetNACKStatus(bool enable, int maxNumberOfPackets) {
2743 // None of these functions can fail.
Stefan Holmerb86d4e42015-12-07 10:26:18 +01002744 // If pacing is enabled we always store packets.
2745 if (!pacing_enabled_)
2746 _rtpRtcpModule->SetStorePacketsStatus(enable, maxNumberOfPackets);
stefan@webrtc.org7bb8f022013-09-06 13:40:11 +00002747 rtp_receive_statistics_->SetMaxReorderingThreshold(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002748 if (enable)
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00002749 audio_coding_->EnableNack(maxNumberOfPackets);
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002750 else
andrew@webrtc.orgeb524d92013-09-23 23:02:24 +00002751 audio_coding_->DisableNack();
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002752}
2753
pwestin@webrtc.orgd30859e2013-06-06 21:09:01 +00002754// Called when we are missing one or more packets.
2755int Channel::ResendPackets(const uint16_t* sequence_numbers, int length) {
pwestin@webrtc.orgdb249952013-06-05 15:33:20 +00002756 return _rtpRtcpModule->SendNACK(sequence_numbers, length);
2757}
2758
henrikaec6fbd22017-03-31 05:43:36 -07002759void Channel::ProcessAndEncodeAudio(const AudioFrame& audio_input) {
henrika4515fa02017-05-03 08:30:15 -07002760 // Avoid posting any new tasks if sending was already stopped in StopSend().
2761 rtc::CritScope cs(&encoder_queue_lock_);
2762 if (!encoder_queue_is_active_) {
2763 return;
2764 }
henrikaec6fbd22017-03-31 05:43:36 -07002765 std::unique_ptr<AudioFrame> audio_frame(new AudioFrame());
2766 // TODO(henrika): try to avoid copying by moving ownership of audio frame
2767 // either into pool of frames or into the task itself.
2768 audio_frame->CopyFrom(audio_input);
2769 audio_frame->id_ = ChannelId();
2770 encoder_queue_->PostTask(std::unique_ptr<rtc::QueuedTask>(
2771 new ProcessAndEncodeAudioTask(std::move(audio_frame), this)));
niklase@google.com470e71d2011-07-07 08:21:25 +00002772}
2773
henrikaec6fbd22017-03-31 05:43:36 -07002774void Channel::ProcessAndEncodeAudio(const int16_t* audio_data,
2775 int sample_rate,
2776 size_t number_of_frames,
2777 size_t number_of_channels) {
henrika4515fa02017-05-03 08:30:15 -07002778 // Avoid posting as new task if sending was already stopped in StopSend().
2779 rtc::CritScope cs(&encoder_queue_lock_);
2780 if (!encoder_queue_is_active_) {
2781 return;
2782 }
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002783 CodecInst codec;
ossu950c1c92017-07-11 08:19:31 -07002784 const int result = GetSendCodec(codec);
henrikaec6fbd22017-03-31 05:43:36 -07002785 std::unique_ptr<AudioFrame> audio_frame(new AudioFrame());
2786 audio_frame->id_ = ChannelId();
ossu950c1c92017-07-11 08:19:31 -07002787 // TODO(ossu): Investigate how this could happen. b/62909493
2788 if (result == 0) {
2789 audio_frame->sample_rate_hz_ = std::min(codec.plfreq, sample_rate);
2790 audio_frame->num_channels_ = std::min(number_of_channels, codec.channels);
2791 } else {
2792 audio_frame->sample_rate_hz_ = sample_rate;
2793 audio_frame->num_channels_ = number_of_channels;
2794 LOG(LS_WARNING) << "Unable to get send codec for channel " << ChannelId();
2795 RTC_NOTREACHED();
2796 }
Alejandro Luebscdfe20b2015-09-23 12:49:12 -07002797 RemixAndResample(audio_data, number_of_frames, number_of_channels,
henrikaec6fbd22017-03-31 05:43:36 -07002798 sample_rate, &input_resampler_, audio_frame.get());
2799 encoder_queue_->PostTask(std::unique_ptr<rtc::QueuedTask>(
2800 new ProcessAndEncodeAudioTask(std::move(audio_frame), this)));
xians@webrtc.org2f84afa2013-07-31 16:23:37 +00002801}
2802
henrikaec6fbd22017-03-31 05:43:36 -07002803void Channel::ProcessAndEncodeAudioOnTaskQueue(AudioFrame* audio_input) {
2804 RTC_DCHECK_RUN_ON(encoder_queue_);
2805 RTC_DCHECK_GT(audio_input->samples_per_channel_, 0);
2806 RTC_DCHECK_LE(audio_input->num_channels_, 2);
2807 RTC_DCHECK_EQ(audio_input->id_, ChannelId());
kwiberg55b97fe2016-01-28 05:22:45 -08002808
2809 if (channel_state_.Get().input_file_playing) {
henrikaec6fbd22017-03-31 05:43:36 -07002810 MixOrReplaceAudioWithFile(audio_input);
kwiberg55b97fe2016-01-28 05:22:45 -08002811 }
2812
henrikaec6fbd22017-03-31 05:43:36 -07002813 bool is_muted = InputMute();
2814 AudioFrameOperations::Mute(audio_input, previous_frame_muted_, is_muted);
kwiberg55b97fe2016-01-28 05:22:45 -08002815
kwiberg55b97fe2016-01-28 05:22:45 -08002816 if (_includeAudioLevelIndication) {
2817 size_t length =
henrikaec6fbd22017-03-31 05:43:36 -07002818 audio_input->samples_per_channel_ * audio_input->num_channels_;
yujo36b1a5f2017-06-12 12:45:32 -07002819 RTC_CHECK_LE(length, AudioFrame::kMaxDataSizeBytes);
solenberg1c2af8e2016-03-24 10:36:00 -07002820 if (is_muted && previous_frame_muted_) {
henrik.lundin50499422016-11-29 04:26:24 -08002821 rms_level_.AnalyzeMuted(length);
kwiberg55b97fe2016-01-28 05:22:45 -08002822 } else {
henrik.lundin50499422016-11-29 04:26:24 -08002823 rms_level_.Analyze(
yujo36b1a5f2017-06-12 12:45:32 -07002824 rtc::ArrayView<const int16_t>(audio_input->data(), length));
niklase@google.com470e71d2011-07-07 08:21:25 +00002825 }
kwiberg55b97fe2016-01-28 05:22:45 -08002826 }
solenberg1c2af8e2016-03-24 10:36:00 -07002827 previous_frame_muted_ = is_muted;
niklase@google.com470e71d2011-07-07 08:21:25 +00002828
henrikaec6fbd22017-03-31 05:43:36 -07002829 // Add 10ms of raw (PCM) audio data to the encoder @ 32kHz.
niklase@google.com470e71d2011-07-07 08:21:25 +00002830
kwiberg55b97fe2016-01-28 05:22:45 -08002831 // The ACM resamples internally.
henrikaec6fbd22017-03-31 05:43:36 -07002832 audio_input->timestamp_ = _timeStamp;
kwiberg55b97fe2016-01-28 05:22:45 -08002833 // This call will trigger AudioPacketizationCallback::SendData if encoding
2834 // is done and payload is ready for packetization and transmission.
2835 // Otherwise, it will return without invoking the callback.
henrikaec6fbd22017-03-31 05:43:36 -07002836 if (audio_coding_->Add10MsData(*audio_input) < 0) {
2837 LOG(LS_ERROR) << "ACM::Add10MsData() failed for channel " << _channelId;
2838 return;
kwiberg55b97fe2016-01-28 05:22:45 -08002839 }
niklase@google.com470e71d2011-07-07 08:21:25 +00002840
henrikaec6fbd22017-03-31 05:43:36 -07002841 _timeStamp += static_cast<uint32_t>(audio_input->samples_per_channel_);
niklase@google.com470e71d2011-07-07 08:21:25 +00002842}
2843
solenberg7602aab2016-11-14 11:30:07 -08002844void Channel::set_associate_send_channel(const ChannelOwner& channel) {
2845 RTC_DCHECK(!channel.channel() ||
2846 channel.channel()->ChannelId() != _channelId);
2847 rtc::CritScope lock(&assoc_send_channel_lock_);
2848 associate_send_channel_ = channel;
2849}
2850
Minyue2013aec2015-05-13 14:14:42 +02002851void Channel::DisassociateSendChannel(int channel_id) {
tommi31fc21f2016-01-21 10:37:37 -08002852 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02002853 Channel* channel = associate_send_channel_.channel();
2854 if (channel && channel->ChannelId() == channel_id) {
2855 // If this channel is associated with a send channel of the specified
2856 // Channel ID, disassociate with it.
2857 ChannelOwner ref(NULL);
2858 associate_send_channel_ = ref;
2859 }
2860}
2861
ivoc14d5dbe2016-07-04 07:06:55 -07002862void Channel::SetRtcEventLog(RtcEventLog* event_log) {
2863 event_log_proxy_->SetEventLog(event_log);
2864}
2865
michaelt9332b7d2016-11-30 07:51:13 -08002866void Channel::SetRtcpRttStats(RtcpRttStats* rtcp_rtt_stats) {
2867 rtcp_rtt_stats_proxy_->SetRtcpRttStats(rtcp_rtt_stats);
2868}
2869
nisse284542b2017-01-10 08:58:32 -08002870void Channel::UpdateOverheadForEncoder() {
hbos3fd31fe2017-02-28 05:43:16 -08002871 size_t overhead_per_packet =
2872 transport_overhead_per_packet_ + rtp_overhead_per_packet_;
nisse284542b2017-01-10 08:58:32 -08002873 audio_coding_->ModifyEncoder([&](std::unique_ptr<AudioEncoder>* encoder) {
2874 if (*encoder) {
hbos3fd31fe2017-02-28 05:43:16 -08002875 (*encoder)->OnReceivedOverhead(overhead_per_packet);
nisse284542b2017-01-10 08:58:32 -08002876 }
2877 });
2878}
2879
2880void Channel::SetTransportOverhead(size_t transport_overhead_per_packet) {
hbos3fd31fe2017-02-28 05:43:16 -08002881 rtc::CritScope cs(&overhead_per_packet_lock_);
nisse284542b2017-01-10 08:58:32 -08002882 transport_overhead_per_packet_ = transport_overhead_per_packet;
2883 UpdateOverheadForEncoder();
michaelt79e05882016-11-08 02:50:09 -08002884}
2885
hbos3fd31fe2017-02-28 05:43:16 -08002886// TODO(solenberg): Make AudioSendStream an OverheadObserver instead.
michaeltbf65be52016-12-15 06:24:49 -08002887void Channel::OnOverheadChanged(size_t overhead_bytes_per_packet) {
hbos3fd31fe2017-02-28 05:43:16 -08002888 rtc::CritScope cs(&overhead_per_packet_lock_);
nisse284542b2017-01-10 08:58:32 -08002889 rtp_overhead_per_packet_ = overhead_bytes_per_packet;
2890 UpdateOverheadForEncoder();
michaeltbf65be52016-12-15 06:24:49 -08002891}
2892
kwiberg55b97fe2016-01-28 05:22:45 -08002893int Channel::GetNetworkStatistics(NetworkStatistics& stats) {
2894 return audio_coding_->GetNetworkStatistics(&stats);
niklase@google.com470e71d2011-07-07 08:21:25 +00002895}
2896
wu@webrtc.org24301a62013-12-13 19:17:43 +00002897void Channel::GetDecodingCallStatistics(AudioDecodingCallStats* stats) const {
2898 audio_coding_->GetDecodingCallStatistics(stats);
2899}
2900
solenberg358057b2015-11-27 10:46:42 -08002901uint32_t Channel::GetDelayEstimate() const {
solenberg08b19df2017-02-15 00:42:31 -08002902 rtc::CritScope lock(&video_sync_lock_);
2903 return audio_coding_->FilteredCurrentDelayMs() + playout_delay_ms_;
deadbeef74375882015-08-13 12:09:10 -07002904}
2905
kwiberg55b97fe2016-01-28 05:22:45 -08002906int Channel::SetMinimumPlayoutDelay(int delayMs) {
2907 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
2908 "Channel::SetMinimumPlayoutDelay()");
2909 if ((delayMs < kVoiceEngineMinMinPlayoutDelayMs) ||
2910 (delayMs > kVoiceEngineMaxMinPlayoutDelayMs)) {
2911 _engineStatisticsPtr->SetLastError(
2912 VE_INVALID_ARGUMENT, kTraceError,
2913 "SetMinimumPlayoutDelay() invalid min delay");
2914 return -1;
2915 }
2916 if (audio_coding_->SetMinimumPlayoutDelay(delayMs) != 0) {
2917 _engineStatisticsPtr->SetLastError(
2918 VE_AUDIO_CODING_MODULE_ERROR, kTraceError,
2919 "SetMinimumPlayoutDelay() failed to set min playout delay");
2920 return -1;
2921 }
2922 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002923}
2924
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00002925int Channel::GetPlayoutTimestamp(unsigned int& timestamp) {
deadbeef74375882015-08-13 12:09:10 -07002926 uint32_t playout_timestamp_rtp = 0;
2927 {
tommi31fc21f2016-01-21 10:37:37 -08002928 rtc::CritScope lock(&video_sync_lock_);
deadbeef74375882015-08-13 12:09:10 -07002929 playout_timestamp_rtp = playout_timestamp_rtp_;
2930 }
kwiberg55b97fe2016-01-28 05:22:45 -08002931 if (playout_timestamp_rtp == 0) {
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00002932 _engineStatisticsPtr->SetLastError(
skvlad4c0536b2016-07-07 13:06:26 -07002933 VE_CANNOT_RETRIEVE_VALUE, kTraceStateInfo,
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00002934 "GetPlayoutTimestamp() failed to retrieve timestamp");
2935 return -1;
2936 }
deadbeef74375882015-08-13 12:09:10 -07002937 timestamp = playout_timestamp_rtp;
pwestin@webrtc.org1de01352013-04-11 20:23:35 +00002938 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002939}
2940
kwiberg55b97fe2016-01-28 05:22:45 -08002941int Channel::GetRtpRtcp(RtpRtcp** rtpRtcpModule,
2942 RtpReceiver** rtp_receiver) const {
2943 *rtpRtcpModule = _rtpRtcpModule.get();
2944 *rtp_receiver = rtp_receiver_.get();
2945 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002946}
2947
andrew@webrtc.orge59a0ac2012-05-08 17:12:40 +00002948// TODO(andrew): refactor Mix functions here and in transmit_mixer.cc to use
2949// a shared helper.
henrikaec6fbd22017-03-31 05:43:36 -07002950int32_t Channel::MixOrReplaceAudioWithFile(AudioFrame* audio_input) {
2951 RTC_DCHECK_RUN_ON(encoder_queue_);
kwibergb7f89d62016-02-17 10:04:18 -08002952 std::unique_ptr<int16_t[]> fileBuffer(new int16_t[640]);
kwiberg55b97fe2016-01-28 05:22:45 -08002953 size_t fileSamples(0);
henrikaec6fbd22017-03-31 05:43:36 -07002954 const int mixingFrequency = audio_input->sample_rate_hz_;
kwiberg55b97fe2016-01-28 05:22:45 -08002955 {
2956 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00002957
kwiberg5a25d952016-08-17 07:31:12 -07002958 if (!input_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08002959 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2960 "Channel::MixOrReplaceAudioWithFile() fileplayer"
2961 " doesnt exist");
2962 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002963 }
2964
kwiberg4ec01d92016-08-22 08:43:54 -07002965 if (input_file_player_->Get10msAudioFromFile(fileBuffer.get(), &fileSamples,
kwiberg5a25d952016-08-17 07:31:12 -07002966 mixingFrequency) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08002967 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2968 "Channel::MixOrReplaceAudioWithFile() file mixing "
2969 "failed");
2970 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00002971 }
kwiberg55b97fe2016-01-28 05:22:45 -08002972 if (fileSamples == 0) {
2973 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
2974 "Channel::MixOrReplaceAudioWithFile() file is ended");
2975 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002976 }
kwiberg55b97fe2016-01-28 05:22:45 -08002977 }
2978
henrikaec6fbd22017-03-31 05:43:36 -07002979 RTC_DCHECK_EQ(audio_input->samples_per_channel_, fileSamples);
kwiberg55b97fe2016-01-28 05:22:45 -08002980
2981 if (_mixFileWithMicrophone) {
2982 // Currently file stream is always mono.
2983 // TODO(xians): Change the code when FilePlayer supports real stereo.
yujo36b1a5f2017-06-12 12:45:32 -07002984 MixWithSat(audio_input->mutable_data(), audio_input->num_channels_,
2985 fileBuffer.get(), 1, fileSamples);
kwiberg55b97fe2016-01-28 05:22:45 -08002986 } else {
2987 // Replace ACM audio with file.
2988 // Currently file stream is always mono.
2989 // TODO(xians): Change the code when FilePlayer supports real stereo.
henrikaec6fbd22017-03-31 05:43:36 -07002990 audio_input->UpdateFrame(
kwiberg55b97fe2016-01-28 05:22:45 -08002991 _channelId, 0xFFFFFFFF, fileBuffer.get(), fileSamples, mixingFrequency,
2992 AudioFrame::kNormalSpeech, AudioFrame::kVadUnknown, 1);
2993 }
2994 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00002995}
2996
kwiberg55b97fe2016-01-28 05:22:45 -08002997int32_t Channel::MixAudioWithFile(AudioFrame& audioFrame, int mixingFrequency) {
2998 assert(mixingFrequency <= 48000);
niklase@google.com470e71d2011-07-07 08:21:25 +00002999
kwibergb7f89d62016-02-17 10:04:18 -08003000 std::unique_ptr<int16_t[]> fileBuffer(new int16_t[960]);
kwiberg55b97fe2016-01-28 05:22:45 -08003001 size_t fileSamples(0);
niklase@google.com470e71d2011-07-07 08:21:25 +00003002
kwiberg55b97fe2016-01-28 05:22:45 -08003003 {
3004 rtc::CritScope cs(&_fileCritSect);
niklase@google.com470e71d2011-07-07 08:21:25 +00003005
kwiberg5a25d952016-08-17 07:31:12 -07003006 if (!output_file_player_) {
kwiberg55b97fe2016-01-28 05:22:45 -08003007 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3008 "Channel::MixAudioWithFile() file mixing failed");
3009 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003010 }
3011
kwiberg55b97fe2016-01-28 05:22:45 -08003012 // We should get the frequency we ask for.
kwiberg4ec01d92016-08-22 08:43:54 -07003013 if (output_file_player_->Get10msAudioFromFile(
3014 fileBuffer.get(), &fileSamples, mixingFrequency) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08003015 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3016 "Channel::MixAudioWithFile() file mixing failed");
3017 return -1;
niklase@google.com470e71d2011-07-07 08:21:25 +00003018 }
kwiberg55b97fe2016-01-28 05:22:45 -08003019 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003020
kwiberg55b97fe2016-01-28 05:22:45 -08003021 if (audioFrame.samples_per_channel_ == fileSamples) {
3022 // Currently file stream is always mono.
3023 // TODO(xians): Change the code when FilePlayer supports real stereo.
yujo36b1a5f2017-06-12 12:45:32 -07003024 MixWithSat(audioFrame.mutable_data(), audioFrame.num_channels_,
3025 fileBuffer.get(), 1, fileSamples);
kwiberg55b97fe2016-01-28 05:22:45 -08003026 } else {
3027 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3028 "Channel::MixAudioWithFile() samples_per_channel_(%" PRIuS
3029 ") != "
3030 "fileSamples(%" PRIuS ")",
3031 audioFrame.samples_per_channel_, fileSamples);
3032 return -1;
3033 }
3034
3035 return 0;
niklase@google.com470e71d2011-07-07 08:21:25 +00003036}
3037
deadbeef74375882015-08-13 12:09:10 -07003038void Channel::UpdatePlayoutTimestamp(bool rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07003039 jitter_buffer_playout_timestamp_ = audio_coding_->PlayoutTimestamp();
deadbeef74375882015-08-13 12:09:10 -07003040
henrik.lundin96bd5022016-04-06 04:13:56 -07003041 if (!jitter_buffer_playout_timestamp_) {
3042 // This can happen if this channel has not received any RTP packets. In
3043 // this case, NetEq is not capable of computing a playout timestamp.
deadbeef74375882015-08-13 12:09:10 -07003044 return;
3045 }
3046
3047 uint16_t delay_ms = 0;
3048 if (_audioDeviceModulePtr->PlayoutDelay(&delay_ms) == -1) {
kwiberg55b97fe2016-01-28 05:22:45 -08003049 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07003050 "Channel::UpdatePlayoutTimestamp() failed to read playout"
3051 " delay from the ADM");
3052 _engineStatisticsPtr->SetLastError(
3053 VE_CANNOT_RETRIEVE_VALUE, kTraceError,
3054 "UpdatePlayoutTimestamp() failed to retrieve playout delay");
3055 return;
3056 }
3057
henrik.lundin96bd5022016-04-06 04:13:56 -07003058 RTC_DCHECK(jitter_buffer_playout_timestamp_);
3059 uint32_t playout_timestamp = *jitter_buffer_playout_timestamp_;
deadbeef74375882015-08-13 12:09:10 -07003060
3061 // Remove the playout delay.
ossue280cde2016-10-12 11:04:10 -07003062 playout_timestamp -= (delay_ms * (GetRtpTimestampRateHz() / 1000));
deadbeef74375882015-08-13 12:09:10 -07003063
kwiberg55b97fe2016-01-28 05:22:45 -08003064 WEBRTC_TRACE(kTraceStream, kTraceVoice, VoEId(_instanceId, _channelId),
deadbeef74375882015-08-13 12:09:10 -07003065 "Channel::UpdatePlayoutTimestamp() => playoutTimestamp = %lu",
henrik.lundin96bd5022016-04-06 04:13:56 -07003066 playout_timestamp);
deadbeef74375882015-08-13 12:09:10 -07003067
3068 {
tommi31fc21f2016-01-21 10:37:37 -08003069 rtc::CritScope lock(&video_sync_lock_);
solenberg81d93f32017-02-14 03:44:57 -08003070 if (!rtcp) {
henrik.lundin96bd5022016-04-06 04:13:56 -07003071 playout_timestamp_rtp_ = playout_timestamp;
deadbeef74375882015-08-13 12:09:10 -07003072 }
3073 playout_delay_ms_ = delay_ms;
3074 }
3075}
3076
kwiberg55b97fe2016-01-28 05:22:45 -08003077void Channel::RegisterReceiveCodecsToRTPModule() {
3078 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3079 "Channel::RegisterReceiveCodecsToRTPModule()");
niklase@google.com470e71d2011-07-07 08:21:25 +00003080
kwiberg55b97fe2016-01-28 05:22:45 -08003081 CodecInst codec;
3082 const uint8_t nSupportedCodecs = AudioCodingModule::NumberOfCodecs();
niklase@google.com470e71d2011-07-07 08:21:25 +00003083
kwiberg55b97fe2016-01-28 05:22:45 -08003084 for (int idx = 0; idx < nSupportedCodecs; idx++) {
3085 // Open up the RTP/RTCP receiver for all supported codecs
3086 if ((audio_coding_->Codec(idx, &codec) == -1) ||
magjed56124bd2016-11-24 09:34:46 -08003087 (rtp_receiver_->RegisterReceivePayload(codec) == -1)) {
kwiberg55b97fe2016-01-28 05:22:45 -08003088 WEBRTC_TRACE(kTraceWarning, kTraceVoice, VoEId(_instanceId, _channelId),
3089 "Channel::RegisterReceiveCodecsToRTPModule() unable"
3090 " to register %s (%d/%d/%" PRIuS
3091 "/%d) to RTP/RTCP "
3092 "receiver",
3093 codec.plname, codec.pltype, codec.plfreq, codec.channels,
3094 codec.rate);
3095 } else {
3096 WEBRTC_TRACE(kTraceInfo, kTraceVoice, VoEId(_instanceId, _channelId),
3097 "Channel::RegisterReceiveCodecsToRTPModule() %s "
3098 "(%d/%d/%" PRIuS
3099 "/%d) has been added to the RTP/RTCP "
3100 "receiver",
3101 codec.plname, codec.pltype, codec.plfreq, codec.channels,
3102 codec.rate);
niklase@google.com470e71d2011-07-07 08:21:25 +00003103 }
kwiberg55b97fe2016-01-28 05:22:45 -08003104 }
niklase@google.com470e71d2011-07-07 08:21:25 +00003105}
3106
kwiberg55b97fe2016-01-28 05:22:45 -08003107int Channel::SetSendRtpHeaderExtension(bool enable,
3108 RTPExtensionType type,
wu@webrtc.orgebdb0e32014-03-06 23:49:08 +00003109 unsigned char id) {
3110 int error = 0;
3111 _rtpRtcpModule->DeregisterSendRtpHeaderExtension(type);
3112 if (enable) {
3113 error = _rtpRtcpModule->RegisterSendRtpHeaderExtension(type, id);
3114 }
3115 return error;
3116}
minyue@webrtc.orgc1a40a72014-05-28 09:52:06 +00003117
ossue280cde2016-10-12 11:04:10 -07003118int Channel::GetRtpTimestampRateHz() const {
3119 const auto format = audio_coding_->ReceiveFormat();
3120 // Default to the playout frequency if we've not gotten any packets yet.
3121 // TODO(ossu): Zero clockrate can only happen if we've added an external
3122 // decoder for a format we don't support internally. Remove once that way of
3123 // adding decoders is gone!
3124 return (format && format->clockrate_hz != 0)
3125 ? format->clockrate_hz
3126 : audio_coding_->PlayoutFrequency();
wu@webrtc.org94454b72014-06-05 20:34:08 +00003127}
3128
Minyue2013aec2015-05-13 14:14:42 +02003129int64_t Channel::GetRTT(bool allow_associate_channel) const {
pbosda903ea2015-10-02 02:36:56 -07003130 RtcpMode method = _rtpRtcpModule->RTCP();
3131 if (method == RtcpMode::kOff) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003132 return 0;
3133 }
3134 std::vector<RTCPReportBlock> report_blocks;
3135 _rtpRtcpModule->RemoteRTCPStat(&report_blocks);
Minyue2013aec2015-05-13 14:14:42 +02003136
3137 int64_t rtt = 0;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003138 if (report_blocks.empty()) {
Minyue2013aec2015-05-13 14:14:42 +02003139 if (allow_associate_channel) {
tommi31fc21f2016-01-21 10:37:37 -08003140 rtc::CritScope lock(&assoc_send_channel_lock_);
Minyue2013aec2015-05-13 14:14:42 +02003141 Channel* channel = associate_send_channel_.channel();
3142 // Tries to get RTT from an associated channel. This is important for
3143 // receive-only channels.
3144 if (channel) {
3145 // To prevent infinite recursion and deadlock, calling GetRTT of
3146 // associate channel should always use "false" for argument:
3147 // |allow_associate_channel|.
3148 rtt = channel->GetRTT(false);
3149 }
3150 }
3151 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003152 }
3153
3154 uint32_t remoteSSRC = rtp_receiver_->SSRC();
3155 std::vector<RTCPReportBlock>::const_iterator it = report_blocks.begin();
3156 for (; it != report_blocks.end(); ++it) {
3157 if (it->remoteSSRC == remoteSSRC)
3158 break;
3159 }
3160 if (it == report_blocks.end()) {
3161 // We have not received packets with SSRC matching the report blocks.
3162 // To calculate RTT we try with the SSRC of the first report block.
3163 // This is very important for send-only channels where we don't know
3164 // the SSRC of the other end.
3165 remoteSSRC = report_blocks[0].remoteSSRC;
3166 }
Minyue2013aec2015-05-13 14:14:42 +02003167
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003168 int64_t avg_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08003169 int64_t max_rtt = 0;
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003170 int64_t min_rtt = 0;
kwiberg55b97fe2016-01-28 05:22:45 -08003171 if (_rtpRtcpModule->RTT(remoteSSRC, &rtt, &avg_rtt, &min_rtt, &max_rtt) !=
3172 0) {
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003173 return 0;
3174 }
pkasting@chromium.org16825b12015-01-12 21:51:21 +00003175 return rtt;
minyue@webrtc.org2b58a442014-09-11 07:51:53 +00003176}
3177
pbos@webrtc.orgd900e8b2013-07-03 15:12:26 +00003178} // namespace voe
3179} // namespace webrtc