blob: c0aab3a30fa539a3bb90ea8b130fdb027f57cc50 [file] [log] [blame]
turaj@webrtc.org7959e162013-09-12 18:30:26 +00001/*
2 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
3 *
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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "modules/audio_coding/include/audio_coding_module.h"
turaj@webrtc.org7959e162013-09-12 18:30:26 +000012
Yves Gerey988cc082018-10-23 12:03:01 +020013#include <assert.h>
Jonathan Yu36344a02017-07-30 01:55:34 -070014#include <algorithm>
Yves Gerey988cc082018-10-23 12:03:01 +020015#include <cstdint>
Jonathan Yu36344a02017-07-30 01:55:34 -070016
Niels Möller2edab4c2018-10-22 09:48:08 +020017#include "absl/strings/match.h"
Yves Gerey988cc082018-10-23 12:03:01 +020018#include "api/array_view.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020019#include "modules/audio_coding/acm2/acm_receiver.h"
20#include "modules/audio_coding/acm2/acm_resampler.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020021#include "modules/audio_coding/acm2/rent_a_codec.h"
Fredrik Solenbergbbf21a32018-04-12 22:44:09 +020022#include "modules/include/module_common_types.h"
Yves Gerey988cc082018-10-23 12:03:01 +020023#include "modules/include/module_common_types_public.h"
24#include "rtc_base/buffer.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020025#include "rtc_base/checks.h"
Yves Gerey988cc082018-10-23 12:03:01 +020026#include "rtc_base/criticalsection.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020027#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010028#include "rtc_base/numerics/safe_conversions.h"
Yves Gerey988cc082018-10-23 12:03:01 +020029#include "rtc_base/thread_annotations.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020030#include "system_wrappers/include/metrics.h"
turaj@webrtc.org7959e162013-09-12 18:30:26 +000031
32namespace webrtc {
33
kwibergc13ded52016-06-17 06:00:45 -070034namespace {
35
kwibergc13ded52016-06-17 06:00:45 -070036class AudioCodingModuleImpl final : public AudioCodingModule {
37 public:
38 explicit AudioCodingModuleImpl(const AudioCodingModule::Config& config);
39 ~AudioCodingModuleImpl() override;
40
41 /////////////////////////////////////////
42 // Sender
43 //
44
kwiberg24c7c122016-09-28 11:57:10 -070045 void ModifyEncoder(rtc::FunctionView<void(std::unique_ptr<AudioEncoder>*)>
46 modifier) override;
kwibergc13ded52016-06-17 06:00:45 -070047
48 // Get current send codec.
Danil Chapovalovb6021232018-06-19 13:26:36 +020049 absl::optional<CodecInst> SendCodec() const override;
kwibergc13ded52016-06-17 06:00:45 -070050
kwibergc13ded52016-06-17 06:00:45 -070051 // Sets the bitrate to the specified value in bits/sec. In case the codec does
52 // not support the requested value it will choose an appropriate value
53 // instead.
54 void SetBitRate(int bitrate_bps) override;
55
56 // Register a transport callback which will be
57 // called to deliver the encoded buffers.
58 int RegisterTransportCallback(AudioPacketizationCallback* transport) override;
59
60 // Add 10 ms of raw (PCM) audio data to the encoder.
61 int Add10MsData(const AudioFrame& audio_frame) override;
62
63 /////////////////////////////////////////
kwibergc13ded52016-06-17 06:00:45 -070064 // (FEC) Forward Error Correction (codec internal)
65 //
66
kwibergc13ded52016-06-17 06:00:45 -070067 // Set target packet loss rate
68 int SetPacketLossRate(int loss_rate) override;
69
70 /////////////////////////////////////////
71 // (VAD) Voice Activity Detection
72 // and
73 // (CNG) Comfort Noise Generation
74 //
75
kwibergc13ded52016-06-17 06:00:45 -070076 int RegisterVADCallback(ACMVADCallback* vad_callback) override;
77
78 /////////////////////////////////////////
79 // Receiver
80 //
81
82 // Initialize receiver, resets codec database etc.
83 int InitializeReceiver() override;
84
85 // Get current receive frequency.
86 int ReceiveFrequency() const override;
87
88 // Get current playout frequency.
89 int PlayoutFrequency() const override;
90
kwiberg1c07c702017-03-27 07:15:49 -070091 void SetReceiveCodecs(const std::map<int, SdpAudioFormat>& codecs) override;
92
kwiberg5adaf732016-10-04 09:33:27 -070093 bool RegisterReceiveCodec(int rtp_payload_type,
94 const SdpAudioFormat& audio_format) override;
95
kwibergc13ded52016-06-17 06:00:45 -070096 int RegisterExternalReceiveCodec(int rtp_payload_type,
97 AudioDecoder* external_decoder,
98 int sample_rate_hz,
99 int num_channels,
100 const std::string& name) override;
101
102 // Get current received codec.
103 int ReceiveCodec(CodecInst* current_codec) const override;
104
Danil Chapovalovb6021232018-06-19 13:26:36 +0200105 absl::optional<SdpAudioFormat> ReceiveFormat() const override;
ossue280cde2016-10-12 11:04:10 -0700106
kwibergc13ded52016-06-17 06:00:45 -0700107 // Incoming packet from network parsed and ready for decode.
108 int IncomingPacket(const uint8_t* incoming_payload,
109 const size_t payload_length,
110 const WebRtcRTPHeader& rtp_info) override;
111
kwibergc13ded52016-06-17 06:00:45 -0700112 // Minimum playout delay.
113 int SetMinimumPlayoutDelay(int time_ms) override;
114
115 // Maximum playout delay.
116 int SetMaximumPlayoutDelay(int time_ms) override;
117
Danil Chapovalovb6021232018-06-19 13:26:36 +0200118 absl::optional<uint32_t> PlayoutTimestamp() override;
kwibergc13ded52016-06-17 06:00:45 -0700119
henrik.lundinb3f1c5d2016-08-22 15:39:53 -0700120 int FilteredCurrentDelayMs() const override;
121
Henrik Lundinabbff892017-11-29 09:14:04 +0100122 int TargetDelayMs() const override;
123
kwibergc13ded52016-06-17 06:00:45 -0700124 // Get 10 milliseconds of raw audio data to play out, and
125 // automatic resample to the requested frequency if > 0.
126 int PlayoutData10Ms(int desired_freq_hz,
127 AudioFrame* audio_frame,
128 bool* muted) override;
kwibergc13ded52016-06-17 06:00:45 -0700129
130 /////////////////////////////////////////
131 // Statistics
132 //
133
134 int GetNetworkStatistics(NetworkStatistics* statistics) override;
135
kwibergc13ded52016-06-17 06:00:45 -0700136 // If current send codec is Opus, informs it about the maximum playback rate
137 // the receiver will render.
138 int SetOpusMaxPlaybackRate(int frequency_hz) override;
139
140 int EnableOpusDtx() override;
141
142 int DisableOpusDtx() override;
143
144 int UnregisterReceiveCodec(uint8_t payload_type) override;
145
146 int EnableNack(size_t max_nack_list_size) override;
147
148 void DisableNack() override;
149
150 std::vector<uint16_t> GetNackList(int64_t round_trip_time_ms) const override;
151
152 void GetDecodingCallStatistics(AudioDecodingCallStats* stats) const override;
153
ivoce1198e02017-09-08 08:13:19 -0700154 ANAStats GetANAStats() const override;
155
kwibergc13ded52016-06-17 06:00:45 -0700156 private:
157 struct InputData {
158 uint32_t input_timestamp;
159 const int16_t* audio;
160 size_t length_per_channel;
161 size_t audio_channel;
162 // If a re-mix is required (up or down), this buffer will store a re-mixed
163 // version of the input.
164 int16_t buffer[WEBRTC_10MS_PCM_AUDIO];
165 };
166
167 // This member class writes values to the named UMA histogram, but only if
168 // the value has changed since the last time (and always for the first call).
169 class ChangeLogger {
170 public:
171 explicit ChangeLogger(const std::string& histogram_name)
172 : histogram_name_(histogram_name) {}
173 // Logs the new value if it is different from the last logged value, or if
174 // this is the first call.
175 void MaybeLog(int value);
176
177 private:
178 int last_value_ = 0;
179 int first_time_ = true;
180 const std::string histogram_name_;
181 };
182
kwibergc13ded52016-06-17 06:00:45 -0700183 int Add10MsDataInternal(const AudioFrame& audio_frame, InputData* input_data)
danilchap56359be2017-09-07 07:53:45 -0700184 RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700185 int Encode(const InputData& input_data)
danilchap56359be2017-09-07 07:53:45 -0700186 RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700187
danilchap56359be2017-09-07 07:53:45 -0700188 int InitializeReceiverSafe() RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700189
190 bool HaveValidEncoder(const char* caller_name) const
danilchap56359be2017-09-07 07:53:45 -0700191 RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700192
193 // Preprocessing of input audio, including resampling and down-mixing if
194 // required, before pushing audio into encoder's buffer.
195 //
196 // in_frame: input audio-frame
197 // ptr_out: pointer to output audio_frame. If no preprocessing is required
198 // |ptr_out| will be pointing to |in_frame|, otherwise pointing to
199 // |preprocess_frame_|.
200 //
201 // Return value:
202 // -1: if encountering an error.
203 // 0: otherwise.
204 int PreprocessToAddData(const AudioFrame& in_frame,
205 const AudioFrame** ptr_out)
danilchap56359be2017-09-07 07:53:45 -0700206 RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700207
208 // Change required states after starting to receive the codec corresponding
209 // to |index|.
210 int UpdateUponReceivingCodec(int index);
211
212 rtc::CriticalSection acm_crit_sect_;
danilchap56359be2017-09-07 07:53:45 -0700213 rtc::Buffer encode_buffer_ RTC_GUARDED_BY(acm_crit_sect_);
danilchap56359be2017-09-07 07:53:45 -0700214 uint32_t expected_codec_ts_ RTC_GUARDED_BY(acm_crit_sect_);
215 uint32_t expected_in_ts_ RTC_GUARDED_BY(acm_crit_sect_);
216 acm2::ACMResampler resampler_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700217 acm2::AcmReceiver receiver_; // AcmReceiver has it's own internal lock.
danilchap56359be2017-09-07 07:53:45 -0700218 ChangeLogger bitrate_logger_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700219
Karl Wiberg49c33ce2018-11-12 14:21:58 +0100220 // Current encoder stack, provided by a call to RegisterEncoder.
danilchap56359be2017-09-07 07:53:45 -0700221 std::unique_ptr<AudioEncoder> encoder_stack_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700222
danilchap56359be2017-09-07 07:53:45 -0700223 std::unique_ptr<AudioDecoder> isac_decoder_16k_
224 RTC_GUARDED_BY(acm_crit_sect_);
225 std::unique_ptr<AudioDecoder> isac_decoder_32k_
226 RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700227
228 // This is to keep track of CN instances where we can send DTMFs.
danilchap56359be2017-09-07 07:53:45 -0700229 uint8_t previous_pltype_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700230
danilchap56359be2017-09-07 07:53:45 -0700231 bool receiver_initialized_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700232
danilchap56359be2017-09-07 07:53:45 -0700233 AudioFrame preprocess_frame_ RTC_GUARDED_BY(acm_crit_sect_);
234 bool first_10ms_data_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700235
danilchap56359be2017-09-07 07:53:45 -0700236 bool first_frame_ RTC_GUARDED_BY(acm_crit_sect_);
237 uint32_t last_timestamp_ RTC_GUARDED_BY(acm_crit_sect_);
238 uint32_t last_rtp_timestamp_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700239
240 rtc::CriticalSection callback_crit_sect_;
241 AudioPacketizationCallback* packetization_callback_
danilchap56359be2017-09-07 07:53:45 -0700242 RTC_GUARDED_BY(callback_crit_sect_);
243 ACMVADCallback* vad_callback_ RTC_GUARDED_BY(callback_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700244
245 int codec_histogram_bins_log_[static_cast<size_t>(
246 AudioEncoder::CodecType::kMaxLoggedAudioCodecTypes)];
247 int number_of_consecutive_empty_packets_;
248};
249
250// Adds a codec usage sample to the histogram.
251void UpdateCodecTypeHistogram(size_t codec_type) {
252 RTC_HISTOGRAM_ENUMERATION(
253 "WebRTC.Audio.Encoder.CodecType", static_cast<int>(codec_type),
254 static_cast<int>(
255 webrtc::AudioEncoder::CodecType::kMaxLoggedAudioCodecTypes));
256}
257
kwibergc13ded52016-06-17 06:00:45 -0700258// Stereo-to-mono can be used as in-place.
259int DownMix(const AudioFrame& frame,
260 size_t length_out_buff,
261 int16_t* out_buff) {
yujo36b1a5f2017-06-12 12:45:32 -0700262 RTC_DCHECK_EQ(frame.num_channels_, 2);
263 RTC_DCHECK_GE(length_out_buff, frame.samples_per_channel_);
264
265 if (!frame.muted()) {
266 const int16_t* frame_data = frame.data();
267 for (size_t n = 0; n < frame.samples_per_channel_; ++n) {
Yves Gerey665174f2018-06-19 15:03:05 +0200268 out_buff[n] =
269 static_cast<int16_t>((static_cast<int32_t>(frame_data[2 * n]) +
270 static_cast<int32_t>(frame_data[2 * n + 1])) >>
271 1);
yujo36b1a5f2017-06-12 12:45:32 -0700272 }
273 } else {
Jonathan Yu36344a02017-07-30 01:55:34 -0700274 std::fill(out_buff, out_buff + frame.samples_per_channel_, 0);
kwibergc13ded52016-06-17 06:00:45 -0700275 }
kwibergc13ded52016-06-17 06:00:45 -0700276 return 0;
277}
278
279// Mono-to-stereo can be used as in-place.
280int UpMix(const AudioFrame& frame, size_t length_out_buff, int16_t* out_buff) {
yujo36b1a5f2017-06-12 12:45:32 -0700281 RTC_DCHECK_EQ(frame.num_channels_, 1);
282 RTC_DCHECK_GE(length_out_buff, 2 * frame.samples_per_channel_);
283
284 if (!frame.muted()) {
285 const int16_t* frame_data = frame.data();
286 for (size_t n = frame.samples_per_channel_; n != 0; --n) {
287 size_t i = n - 1;
288 int16_t sample = frame_data[i];
289 out_buff[2 * i + 1] = sample;
290 out_buff[2 * i] = sample;
291 }
292 } else {
Jonathan Yu36344a02017-07-30 01:55:34 -0700293 std::fill(out_buff, out_buff + frame.samples_per_channel_ * 2, 0);
kwibergc13ded52016-06-17 06:00:45 -0700294 }
295 return 0;
296}
297
298void ConvertEncodedInfoToFragmentationHeader(
299 const AudioEncoder::EncodedInfo& info,
300 RTPFragmentationHeader* frag) {
301 if (info.redundant.empty()) {
302 frag->fragmentationVectorSize = 0;
303 return;
304 }
305
306 frag->VerifyAndAllocateFragmentationHeader(
307 static_cast<uint16_t>(info.redundant.size()));
308 frag->fragmentationVectorSize = static_cast<uint16_t>(info.redundant.size());
309 size_t offset = 0;
310 for (size_t i = 0; i < info.redundant.size(); ++i) {
311 frag->fragmentationOffset[i] = offset;
312 offset += info.redundant[i].encoded_bytes;
313 frag->fragmentationLength[i] = info.redundant[i].encoded_bytes;
kwibergd3edd772017-03-01 18:52:48 -0800314 frag->fragmentationTimeDiff[i] = rtc::dchecked_cast<uint16_t>(
kwibergc13ded52016-06-17 06:00:45 -0700315 info.encoded_timestamp - info.redundant[i].encoded_timestamp);
316 frag->fragmentationPlType[i] = info.redundant[i].payload_type;
317 }
318}
319
320// Wraps a raw AudioEncoder pointer. The idea is that you can put one of these
321// in a unique_ptr, to protect the contained raw pointer from being deleted
322// when the unique_ptr expires. (This is of course a bad idea in general, but
323// backwards compatibility.)
324class RawAudioEncoderWrapper final : public AudioEncoder {
325 public:
326 RawAudioEncoderWrapper(AudioEncoder* enc) : enc_(enc) {}
327 int SampleRateHz() const override { return enc_->SampleRateHz(); }
328 size_t NumChannels() const override { return enc_->NumChannels(); }
329 int RtpTimestampRateHz() const override { return enc_->RtpTimestampRateHz(); }
330 size_t Num10MsFramesInNextPacket() const override {
331 return enc_->Num10MsFramesInNextPacket();
332 }
333 size_t Max10MsFramesInAPacket() const override {
334 return enc_->Max10MsFramesInAPacket();
335 }
336 int GetTargetBitrate() const override { return enc_->GetTargetBitrate(); }
337 EncodedInfo EncodeImpl(uint32_t rtp_timestamp,
338 rtc::ArrayView<const int16_t> audio,
339 rtc::Buffer* encoded) override {
340 return enc_->Encode(rtp_timestamp, audio, encoded);
341 }
342 void Reset() override { return enc_->Reset(); }
343 bool SetFec(bool enable) override { return enc_->SetFec(enable); }
344 bool SetDtx(bool enable) override { return enc_->SetDtx(enable); }
345 bool SetApplication(Application application) override {
346 return enc_->SetApplication(application);
347 }
348 void SetMaxPlaybackRate(int frequency_hz) override {
349 return enc_->SetMaxPlaybackRate(frequency_hz);
350 }
kwibergc13ded52016-06-17 06:00:45 -0700351
352 private:
353 AudioEncoder* enc_;
354};
355
kwibergc13ded52016-06-17 06:00:45 -0700356void AudioCodingModuleImpl::ChangeLogger::MaybeLog(int value) {
357 if (value != last_value_ || first_time_) {
358 first_time_ = false;
359 last_value_ = value;
360 RTC_HISTOGRAM_COUNTS_SPARSE_100(histogram_name_, value);
361 }
362}
363
364AudioCodingModuleImpl::AudioCodingModuleImpl(
365 const AudioCodingModule::Config& config)
solenbergc7b4a452017-09-28 07:37:11 -0700366 : expected_codec_ts_(0xD87F3F9F),
kwibergc13ded52016-06-17 06:00:45 -0700367 expected_in_ts_(0xD87F3F9F),
368 receiver_(config),
369 bitrate_logger_("WebRTC.Audio.TargetBitrateInKbps"),
kwibergc13ded52016-06-17 06:00:45 -0700370 encoder_stack_(nullptr),
371 previous_pltype_(255),
372 receiver_initialized_(false),
373 first_10ms_data_(false),
374 first_frame_(true),
375 packetization_callback_(NULL),
376 vad_callback_(NULL),
377 codec_histogram_bins_log_(),
378 number_of_consecutive_empty_packets_(0) {
379 if (InitializeReceiverSafe() < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100380 RTC_LOG(LS_ERROR) << "Cannot initialize receiver";
kwibergc13ded52016-06-17 06:00:45 -0700381 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100382 RTC_LOG(LS_INFO) << "Created";
kwibergc13ded52016-06-17 06:00:45 -0700383}
384
385AudioCodingModuleImpl::~AudioCodingModuleImpl() = default;
386
387int32_t AudioCodingModuleImpl::Encode(const InputData& input_data) {
388 AudioEncoder::EncodedInfo encoded_info;
389 uint8_t previous_pltype;
390
391 // Check if there is an encoder before.
392 if (!HaveValidEncoder("Process"))
393 return -1;
394
Yves Gerey665174f2018-06-19 15:03:05 +0200395 if (!first_frame_) {
deadbeeffcada902016-08-24 12:45:13 -0700396 RTC_DCHECK(IsNewerTimestamp(input_data.input_timestamp, last_timestamp_))
ossu63fb95a2016-07-06 09:34:22 -0700397 << "Time should not move backwards";
398 }
399
kwibergc13ded52016-06-17 06:00:45 -0700400 // Scale the timestamp to the codec's RTP timestamp rate.
401 uint32_t rtp_timestamp =
402 first_frame_ ? input_data.input_timestamp
403 : last_rtp_timestamp_ +
404 rtc::CheckedDivExact(
405 input_data.input_timestamp - last_timestamp_,
406 static_cast<uint32_t>(rtc::CheckedDivExact(
407 encoder_stack_->SampleRateHz(),
408 encoder_stack_->RtpTimestampRateHz())));
409 last_timestamp_ = input_data.input_timestamp;
410 last_rtp_timestamp_ = rtp_timestamp;
411 first_frame_ = false;
412
413 // Clear the buffer before reuse - encoded data will get appended.
414 encode_buffer_.Clear();
415 encoded_info = encoder_stack_->Encode(
Yves Gerey665174f2018-06-19 15:03:05 +0200416 rtp_timestamp,
417 rtc::ArrayView<const int16_t>(
418 input_data.audio,
419 input_data.audio_channel * input_data.length_per_channel),
kwibergc13ded52016-06-17 06:00:45 -0700420 &encode_buffer_);
421
422 bitrate_logger_.MaybeLog(encoder_stack_->GetTargetBitrate() / 1000);
423 if (encode_buffer_.size() == 0 && !encoded_info.send_even_if_empty) {
424 // Not enough data.
425 return 0;
426 }
427 previous_pltype = previous_pltype_; // Read it while we have the critsect.
428
429 // Log codec type to histogram once every 500 packets.
430 if (encoded_info.encoded_bytes == 0) {
431 ++number_of_consecutive_empty_packets_;
432 } else {
433 size_t codec_type = static_cast<size_t>(encoded_info.encoder_type);
434 codec_histogram_bins_log_[codec_type] +=
435 number_of_consecutive_empty_packets_ + 1;
436 number_of_consecutive_empty_packets_ = 0;
437 if (codec_histogram_bins_log_[codec_type] >= 500) {
438 codec_histogram_bins_log_[codec_type] -= 500;
439 UpdateCodecTypeHistogram(codec_type);
440 }
441 }
442
443 RTPFragmentationHeader my_fragmentation;
444 ConvertEncodedInfoToFragmentationHeader(encoded_info, &my_fragmentation);
445 FrameType frame_type;
446 if (encode_buffer_.size() == 0 && encoded_info.send_even_if_empty) {
447 frame_type = kEmptyFrame;
448 encoded_info.payload_type = previous_pltype;
449 } else {
kwibergaf476c72016-11-28 15:21:39 -0800450 RTC_DCHECK_GT(encode_buffer_.size(), 0);
kwibergc13ded52016-06-17 06:00:45 -0700451 frame_type = encoded_info.speech ? kAudioFrameSpeech : kAudioFrameCN;
452 }
453
454 {
455 rtc::CritScope lock(&callback_crit_sect_);
456 if (packetization_callback_) {
457 packetization_callback_->SendData(
458 frame_type, encoded_info.payload_type, encoded_info.encoded_timestamp,
459 encode_buffer_.data(), encode_buffer_.size(),
460 my_fragmentation.fragmentationVectorSize > 0 ? &my_fragmentation
461 : nullptr);
462 }
463
464 if (vad_callback_) {
465 // Callback with VAD decision.
466 vad_callback_->InFrameType(frame_type);
467 }
468 }
469 previous_pltype_ = encoded_info.payload_type;
470 return static_cast<int32_t>(encode_buffer_.size());
471}
472
473/////////////////////////////////////////
474// Sender
475//
476
kwibergc13ded52016-06-17 06:00:45 -0700477void AudioCodingModuleImpl::ModifyEncoder(
kwiberg24c7c122016-09-28 11:57:10 -0700478 rtc::FunctionView<void(std::unique_ptr<AudioEncoder>*)> modifier) {
kwibergc13ded52016-06-17 06:00:45 -0700479 rtc::CritScope lock(&acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700480 modifier(&encoder_stack_);
481}
482
483// Get current send codec.
Danil Chapovalovb6021232018-06-19 13:26:36 +0200484absl::optional<CodecInst> AudioCodingModuleImpl::SendCodec() const {
kwibergc13ded52016-06-17 06:00:45 -0700485 rtc::CritScope lock(&acm_crit_sect_);
Karl Wiberg49c33ce2018-11-12 14:21:58 +0100486 if (encoder_stack_) {
487 CodecInst ci;
488 ci.channels = encoder_stack_->NumChannels();
489 ci.plfreq = encoder_stack_->SampleRateHz();
490 ci.pacsize = rtc::CheckedDivExact(
491 static_cast<int>(encoder_stack_->Max10MsFramesInAPacket() * ci.plfreq),
492 100);
493 ci.pltype = -1; // Not valid.
494 ci.rate = -1; // Not valid.
495 static const char kName[] = "external";
496 memcpy(ci.plname, kName, sizeof(kName));
497 return ci;
kwibergc13ded52016-06-17 06:00:45 -0700498 } else {
Karl Wiberg49c33ce2018-11-12 14:21:58 +0100499 return absl::nullopt;
kwibergc13ded52016-06-17 06:00:45 -0700500 }
501}
502
kwibergc13ded52016-06-17 06:00:45 -0700503void AudioCodingModuleImpl::SetBitRate(int bitrate_bps) {
504 rtc::CritScope lock(&acm_crit_sect_);
505 if (encoder_stack_) {
Danil Chapovalovb6021232018-06-19 13:26:36 +0200506 encoder_stack_->OnReceivedUplinkBandwidth(bitrate_bps, absl::nullopt);
kwibergc13ded52016-06-17 06:00:45 -0700507 }
508}
509
510// Register a transport callback which will be called to deliver
511// the encoded buffers.
512int AudioCodingModuleImpl::RegisterTransportCallback(
513 AudioPacketizationCallback* transport) {
514 rtc::CritScope lock(&callback_crit_sect_);
515 packetization_callback_ = transport;
516 return 0;
517}
518
519// Add 10MS of raw (PCM) audio data to the encoder.
520int AudioCodingModuleImpl::Add10MsData(const AudioFrame& audio_frame) {
521 InputData input_data;
522 rtc::CritScope lock(&acm_crit_sect_);
523 int r = Add10MsDataInternal(audio_frame, &input_data);
524 return r < 0 ? r : Encode(input_data);
525}
526
527int AudioCodingModuleImpl::Add10MsDataInternal(const AudioFrame& audio_frame,
528 InputData* input_data) {
529 if (audio_frame.samples_per_channel_ == 0) {
530 assert(false);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100531 RTC_LOG(LS_ERROR) << "Cannot Add 10 ms audio, payload length is zero";
kwibergc13ded52016-06-17 06:00:45 -0700532 return -1;
533 }
534
535 if (audio_frame.sample_rate_hz_ > 48000) {
536 assert(false);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100537 RTC_LOG(LS_ERROR) << "Cannot Add 10 ms audio, input frequency not valid";
kwibergc13ded52016-06-17 06:00:45 -0700538 return -1;
539 }
540
541 // If the length and frequency matches. We currently just support raw PCM.
542 if (static_cast<size_t>(audio_frame.sample_rate_hz_ / 100) !=
543 audio_frame.samples_per_channel_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100544 RTC_LOG(LS_ERROR)
Alex Loiko300ec8c2017-05-30 17:23:28 +0200545 << "Cannot Add 10 ms audio, input frequency and length doesn't match";
kwibergc13ded52016-06-17 06:00:45 -0700546 return -1;
547 }
548
549 if (audio_frame.num_channels_ != 1 && audio_frame.num_channels_ != 2) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100550 RTC_LOG(LS_ERROR) << "Cannot Add 10 ms audio, invalid number of channels.";
kwibergc13ded52016-06-17 06:00:45 -0700551 return -1;
552 }
553
554 // Do we have a codec registered?
555 if (!HaveValidEncoder("Add10MsData")) {
556 return -1;
557 }
558
559 const AudioFrame* ptr_frame;
560 // Perform a resampling, also down-mix if it is required and can be
561 // performed before resampling (a down mix prior to resampling will take
562 // place if both primary and secondary encoders are mono and input is in
563 // stereo).
564 if (PreprocessToAddData(audio_frame, &ptr_frame) < 0) {
565 return -1;
566 }
567
568 // Check whether we need an up-mix or down-mix?
569 const size_t current_num_channels = encoder_stack_->NumChannels();
570 const bool same_num_channels =
571 ptr_frame->num_channels_ == current_num_channels;
572
573 if (!same_num_channels) {
574 if (ptr_frame->num_channels_ == 1) {
575 if (UpMix(*ptr_frame, WEBRTC_10MS_PCM_AUDIO, input_data->buffer) < 0)
576 return -1;
577 } else {
578 if (DownMix(*ptr_frame, WEBRTC_10MS_PCM_AUDIO, input_data->buffer) < 0)
579 return -1;
580 }
581 }
582
583 // When adding data to encoders this pointer is pointing to an audio buffer
584 // with correct number of channels.
yujo36b1a5f2017-06-12 12:45:32 -0700585 const int16_t* ptr_audio = ptr_frame->data();
kwibergc13ded52016-06-17 06:00:45 -0700586
587 // For pushing data to primary, point the |ptr_audio| to correct buffer.
588 if (!same_num_channels)
589 ptr_audio = input_data->buffer;
590
yujo36b1a5f2017-06-12 12:45:32 -0700591 // TODO(yujo): Skip encode of muted frames.
kwibergc13ded52016-06-17 06:00:45 -0700592 input_data->input_timestamp = ptr_frame->timestamp_;
593 input_data->audio = ptr_audio;
594 input_data->length_per_channel = ptr_frame->samples_per_channel_;
595 input_data->audio_channel = current_num_channels;
596
597 return 0;
598}
599
600// Perform a resampling and down-mix if required. We down-mix only if
601// encoder is mono and input is stereo. In case of dual-streaming, both
602// encoders has to be mono for down-mix to take place.
603// |*ptr_out| will point to the pre-processed audio-frame. If no pre-processing
604// is required, |*ptr_out| points to |in_frame|.
yujo36b1a5f2017-06-12 12:45:32 -0700605// TODO(yujo): Make this more efficient for muted frames.
kwibergc13ded52016-06-17 06:00:45 -0700606int AudioCodingModuleImpl::PreprocessToAddData(const AudioFrame& in_frame,
607 const AudioFrame** ptr_out) {
608 const bool resample =
609 in_frame.sample_rate_hz_ != encoder_stack_->SampleRateHz();
610
611 // This variable is true if primary codec and secondary codec (if exists)
612 // are both mono and input is stereo.
613 // TODO(henrik.lundin): This condition should probably be
614 // in_frame.num_channels_ > encoder_stack_->NumChannels()
615 const bool down_mix =
616 in_frame.num_channels_ == 2 && encoder_stack_->NumChannels() == 1;
617
618 if (!first_10ms_data_) {
619 expected_in_ts_ = in_frame.timestamp_;
620 expected_codec_ts_ = in_frame.timestamp_;
621 first_10ms_data_ = true;
622 } else if (in_frame.timestamp_ != expected_in_ts_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100623 RTC_LOG(LS_WARNING) << "Unexpected input timestamp: " << in_frame.timestamp_
624 << ", expected: " << expected_in_ts_;
kwibergc13ded52016-06-17 06:00:45 -0700625 expected_codec_ts_ +=
626 (in_frame.timestamp_ - expected_in_ts_) *
627 static_cast<uint32_t>(
628 static_cast<double>(encoder_stack_->SampleRateHz()) /
629 static_cast<double>(in_frame.sample_rate_hz_));
630 expected_in_ts_ = in_frame.timestamp_;
631 }
632
kwibergc13ded52016-06-17 06:00:45 -0700633 if (!down_mix && !resample) {
634 // No pre-processing is required.
ossu63fb95a2016-07-06 09:34:22 -0700635 if (expected_in_ts_ == expected_codec_ts_) {
636 // If we've never resampled, we can use the input frame as-is
637 *ptr_out = &in_frame;
638 } else {
639 // Otherwise we'll need to alter the timestamp. Since in_frame is const,
640 // we'll have to make a copy of it.
641 preprocess_frame_.CopyFrom(in_frame);
642 preprocess_frame_.timestamp_ = expected_codec_ts_;
643 *ptr_out = &preprocess_frame_;
644 }
645
kwibergc13ded52016-06-17 06:00:45 -0700646 expected_in_ts_ += static_cast<uint32_t>(in_frame.samples_per_channel_);
647 expected_codec_ts_ += static_cast<uint32_t>(in_frame.samples_per_channel_);
kwibergc13ded52016-06-17 06:00:45 -0700648 return 0;
649 }
650
651 *ptr_out = &preprocess_frame_;
652 preprocess_frame_.num_channels_ = in_frame.num_channels_;
653 int16_t audio[WEBRTC_10MS_PCM_AUDIO];
yujo36b1a5f2017-06-12 12:45:32 -0700654 const int16_t* src_ptr_audio = in_frame.data();
kwibergc13ded52016-06-17 06:00:45 -0700655 if (down_mix) {
656 // If a resampling is required the output of a down-mix is written into a
657 // local buffer, otherwise, it will be written to the output frame.
Yves Gerey665174f2018-06-19 15:03:05 +0200658 int16_t* dest_ptr_audio =
659 resample ? audio : preprocess_frame_.mutable_data();
kwibergc13ded52016-06-17 06:00:45 -0700660 if (DownMix(in_frame, WEBRTC_10MS_PCM_AUDIO, dest_ptr_audio) < 0)
661 return -1;
662 preprocess_frame_.num_channels_ = 1;
663 // Set the input of the resampler is the down-mixed signal.
664 src_ptr_audio = audio;
665 }
666
667 preprocess_frame_.timestamp_ = expected_codec_ts_;
668 preprocess_frame_.samples_per_channel_ = in_frame.samples_per_channel_;
669 preprocess_frame_.sample_rate_hz_ = in_frame.sample_rate_hz_;
670 // If it is required, we have to do a resampling.
671 if (resample) {
672 // The result of the resampler is written to output frame.
yujo36b1a5f2017-06-12 12:45:32 -0700673 int16_t* dest_ptr_audio = preprocess_frame_.mutable_data();
kwibergc13ded52016-06-17 06:00:45 -0700674
675 int samples_per_channel = resampler_.Resample10Msec(
676 src_ptr_audio, in_frame.sample_rate_hz_, encoder_stack_->SampleRateHz(),
677 preprocess_frame_.num_channels_, AudioFrame::kMaxDataSizeSamples,
678 dest_ptr_audio);
679
680 if (samples_per_channel < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100681 RTC_LOG(LS_ERROR) << "Cannot add 10 ms audio, resampling failed";
kwibergc13ded52016-06-17 06:00:45 -0700682 return -1;
683 }
684 preprocess_frame_.samples_per_channel_ =
685 static_cast<size_t>(samples_per_channel);
686 preprocess_frame_.sample_rate_hz_ = encoder_stack_->SampleRateHz();
687 }
688
689 expected_codec_ts_ +=
690 static_cast<uint32_t>(preprocess_frame_.samples_per_channel_);
691 expected_in_ts_ += static_cast<uint32_t>(in_frame.samples_per_channel_);
692
693 return 0;
694}
695
696/////////////////////////////////////////
kwibergc13ded52016-06-17 06:00:45 -0700697// (FEC) Forward Error Correction (codec internal)
698//
699
kwibergc13ded52016-06-17 06:00:45 -0700700int AudioCodingModuleImpl::SetPacketLossRate(int loss_rate) {
701 rtc::CritScope lock(&acm_crit_sect_);
702 if (HaveValidEncoder("SetPacketLossRate")) {
minyue4b9a2cb2016-11-30 06:49:59 -0800703 encoder_stack_->OnReceivedUplinkPacketLossFraction(loss_rate / 100.0);
kwibergc13ded52016-06-17 06:00:45 -0700704 }
705 return 0;
706}
707
708/////////////////////////////////////////
kwibergc13ded52016-06-17 06:00:45 -0700709// Receiver
710//
711
712int AudioCodingModuleImpl::InitializeReceiver() {
713 rtc::CritScope lock(&acm_crit_sect_);
714 return InitializeReceiverSafe();
715}
716
717// Initialize receiver, resets codec database etc.
718int AudioCodingModuleImpl::InitializeReceiverSafe() {
719 // If the receiver is already initialized then we want to destroy any
720 // existing decoders. After a call to this function, we should have a clean
721 // start-up.
kwiberg6b19b562016-09-20 04:02:25 -0700722 if (receiver_initialized_)
723 receiver_.RemoveAllCodecs();
kwibergc13ded52016-06-17 06:00:45 -0700724 receiver_.ResetInitialDelay();
725 receiver_.SetMinimumDelay(0);
726 receiver_.SetMaximumDelay(0);
727 receiver_.FlushBuffers();
728
kwibergc13ded52016-06-17 06:00:45 -0700729 receiver_initialized_ = true;
730 return 0;
731}
732
733// Get current receive frequency.
734int AudioCodingModuleImpl::ReceiveFrequency() const {
735 const auto last_packet_sample_rate = receiver_.last_packet_sample_rate_hz();
736 return last_packet_sample_rate ? *last_packet_sample_rate
737 : receiver_.last_output_sample_rate_hz();
738}
739
740// Get current playout frequency.
741int AudioCodingModuleImpl::PlayoutFrequency() const {
kwibergc13ded52016-06-17 06:00:45 -0700742 return receiver_.last_output_sample_rate_hz();
743}
744
kwiberg1c07c702017-03-27 07:15:49 -0700745void AudioCodingModuleImpl::SetReceiveCodecs(
746 const std::map<int, SdpAudioFormat>& codecs) {
747 rtc::CritScope lock(&acm_crit_sect_);
748 receiver_.SetCodecs(codecs);
749}
750
kwiberg5adaf732016-10-04 09:33:27 -0700751bool AudioCodingModuleImpl::RegisterReceiveCodec(
752 int rtp_payload_type,
753 const SdpAudioFormat& audio_format) {
754 rtc::CritScope lock(&acm_crit_sect_);
755 RTC_DCHECK(receiver_initialized_);
756
757 if (!acm2::RentACodec::IsPayloadTypeValid(rtp_payload_type)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100758 RTC_LOG_F(LS_ERROR) << "Invalid payload-type " << rtp_payload_type
759 << " for decoder.";
kwiberg5adaf732016-10-04 09:33:27 -0700760 return false;
761 }
762
763 return receiver_.AddCodec(rtp_payload_type, audio_format);
764}
765
kwibergc13ded52016-06-17 06:00:45 -0700766int AudioCodingModuleImpl::RegisterExternalReceiveCodec(
767 int rtp_payload_type,
768 AudioDecoder* external_decoder,
769 int sample_rate_hz,
770 int num_channels,
771 const std::string& name) {
772 rtc::CritScope lock(&acm_crit_sect_);
773 RTC_DCHECK(receiver_initialized_);
774 if (num_channels > 2 || num_channels < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100775 RTC_LOG_F(LS_ERROR) << "Unsupported number of channels: " << num_channels;
kwibergc13ded52016-06-17 06:00:45 -0700776 return -1;
777 }
778
779 // Check if the payload-type is valid.
780 if (!acm2::RentACodec::IsPayloadTypeValid(rtp_payload_type)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100781 RTC_LOG_F(LS_ERROR) << "Invalid payload-type " << rtp_payload_type
782 << " for external decoder.";
kwibergc13ded52016-06-17 06:00:45 -0700783 return -1;
784 }
785
786 return receiver_.AddCodec(-1 /* external */, rtp_payload_type, num_channels,
787 sample_rate_hz, external_decoder, name);
788}
789
790// Get current received codec.
791int AudioCodingModuleImpl::ReceiveCodec(CodecInst* current_codec) const {
792 rtc::CritScope lock(&acm_crit_sect_);
793 return receiver_.LastAudioCodec(current_codec);
794}
795
Danil Chapovalovb6021232018-06-19 13:26:36 +0200796absl::optional<SdpAudioFormat> AudioCodingModuleImpl::ReceiveFormat() const {
ossue280cde2016-10-12 11:04:10 -0700797 rtc::CritScope lock(&acm_crit_sect_);
798 return receiver_.LastAudioFormat();
799}
800
kwibergc13ded52016-06-17 06:00:45 -0700801// Incoming packet from network parsed and ready for decode.
802int AudioCodingModuleImpl::IncomingPacket(const uint8_t* incoming_payload,
803 const size_t payload_length,
804 const WebRtcRTPHeader& rtp_header) {
henrik.lundinb8c55b12017-05-10 07:38:01 -0700805 RTC_DCHECK_EQ(payload_length == 0, incoming_payload == nullptr);
kwibergc13ded52016-06-17 06:00:45 -0700806 return receiver_.InsertPacket(
807 rtp_header,
808 rtc::ArrayView<const uint8_t>(incoming_payload, payload_length));
809}
810
811// Minimum playout delay (Used for lip-sync).
812int AudioCodingModuleImpl::SetMinimumPlayoutDelay(int time_ms) {
813 if ((time_ms < 0) || (time_ms > 10000)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100814 RTC_LOG(LS_ERROR) << "Delay must be in the range of 0-10000 milliseconds.";
kwibergc13ded52016-06-17 06:00:45 -0700815 return -1;
816 }
817 return receiver_.SetMinimumDelay(time_ms);
818}
819
820int AudioCodingModuleImpl::SetMaximumPlayoutDelay(int time_ms) {
821 if ((time_ms < 0) || (time_ms > 10000)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100822 RTC_LOG(LS_ERROR) << "Delay must be in the range of 0-10000 milliseconds.";
kwibergc13ded52016-06-17 06:00:45 -0700823 return -1;
824 }
825 return receiver_.SetMaximumDelay(time_ms);
826}
827
828// Get 10 milliseconds of raw audio data to play out.
829// Automatic resample to the requested frequency.
830int AudioCodingModuleImpl::PlayoutData10Ms(int desired_freq_hz,
831 AudioFrame* audio_frame,
832 bool* muted) {
833 // GetAudio always returns 10 ms, at the requested sample rate.
834 if (receiver_.GetAudio(desired_freq_hz, audio_frame, muted) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100835 RTC_LOG(LS_ERROR) << "PlayoutData failed, RecOut Failed";
kwibergc13ded52016-06-17 06:00:45 -0700836 return -1;
837 }
kwibergc13ded52016-06-17 06:00:45 -0700838 return 0;
839}
840
kwibergc13ded52016-06-17 06:00:45 -0700841/////////////////////////////////////////
842// Statistics
843//
844
845// TODO(turajs) change the return value to void. Also change the corresponding
846// NetEq function.
847int AudioCodingModuleImpl::GetNetworkStatistics(NetworkStatistics* statistics) {
848 receiver_.GetNetworkStatistics(statistics);
849 return 0;
850}
851
852int AudioCodingModuleImpl::RegisterVADCallback(ACMVADCallback* vad_callback) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100853 RTC_LOG(LS_VERBOSE) << "RegisterVADCallback()";
kwibergc13ded52016-06-17 06:00:45 -0700854 rtc::CritScope lock(&callback_crit_sect_);
855 vad_callback_ = vad_callback;
856 return 0;
857}
858
kwibergc13ded52016-06-17 06:00:45 -0700859// Informs Opus encoder of the maximum playback rate the receiver will render.
860int AudioCodingModuleImpl::SetOpusMaxPlaybackRate(int frequency_hz) {
861 rtc::CritScope lock(&acm_crit_sect_);
862 if (!HaveValidEncoder("SetOpusMaxPlaybackRate")) {
863 return -1;
864 }
865 encoder_stack_->SetMaxPlaybackRate(frequency_hz);
866 return 0;
867}
868
869int AudioCodingModuleImpl::EnableOpusDtx() {
870 rtc::CritScope lock(&acm_crit_sect_);
871 if (!HaveValidEncoder("EnableOpusDtx")) {
872 return -1;
873 }
874 return encoder_stack_->SetDtx(true) ? 0 : -1;
875}
876
877int AudioCodingModuleImpl::DisableOpusDtx() {
878 rtc::CritScope lock(&acm_crit_sect_);
879 if (!HaveValidEncoder("DisableOpusDtx")) {
880 return -1;
881 }
882 return encoder_stack_->SetDtx(false) ? 0 : -1;
883}
884
Danil Chapovalovb6021232018-06-19 13:26:36 +0200885absl::optional<uint32_t> AudioCodingModuleImpl::PlayoutTimestamp() {
kwibergc13ded52016-06-17 06:00:45 -0700886 return receiver_.GetPlayoutTimestamp();
887}
888
henrik.lundinb3f1c5d2016-08-22 15:39:53 -0700889int AudioCodingModuleImpl::FilteredCurrentDelayMs() const {
890 return receiver_.FilteredCurrentDelayMs();
891}
892
Henrik Lundinabbff892017-11-29 09:14:04 +0100893int AudioCodingModuleImpl::TargetDelayMs() const {
894 return receiver_.TargetDelayMs();
895}
896
kwibergc13ded52016-06-17 06:00:45 -0700897bool AudioCodingModuleImpl::HaveValidEncoder(const char* caller_name) const {
898 if (!encoder_stack_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100899 RTC_LOG(LS_ERROR) << caller_name << " failed: No send codec is registered.";
kwibergc13ded52016-06-17 06:00:45 -0700900 return false;
901 }
902 return true;
903}
904
905int AudioCodingModuleImpl::UnregisterReceiveCodec(uint8_t payload_type) {
906 return receiver_.RemoveCodec(payload_type);
907}
908
909int AudioCodingModuleImpl::EnableNack(size_t max_nack_list_size) {
910 return receiver_.EnableNack(max_nack_list_size);
911}
912
913void AudioCodingModuleImpl::DisableNack() {
914 receiver_.DisableNack();
915}
916
917std::vector<uint16_t> AudioCodingModuleImpl::GetNackList(
918 int64_t round_trip_time_ms) const {
919 return receiver_.GetNackList(round_trip_time_ms);
920}
921
kwibergc13ded52016-06-17 06:00:45 -0700922void AudioCodingModuleImpl::GetDecodingCallStatistics(
Yves Gerey665174f2018-06-19 15:03:05 +0200923 AudioDecodingCallStats* call_stats) const {
kwibergc13ded52016-06-17 06:00:45 -0700924 receiver_.GetDecodingCallStatistics(call_stats);
925}
926
ivoce1198e02017-09-08 08:13:19 -0700927ANAStats AudioCodingModuleImpl::GetANAStats() const {
928 rtc::CritScope lock(&acm_crit_sect_);
929 if (encoder_stack_)
930 return encoder_stack_->GetANAStats();
931 // If no encoder is set, return default stats.
932 return ANAStats();
933}
934
kwibergc13ded52016-06-17 06:00:45 -0700935} // namespace
936
Karl Wiberg5817d3d2018-04-06 10:06:42 +0200937AudioCodingModule::Config::Config(
938 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory)
939 : neteq_config(),
940 clock(Clock::GetRealTimeClock()),
941 decoder_factory(decoder_factory) {
kwiberg36a43882016-08-29 05:33:32 -0700942 // Post-decode VAD is disabled by default in NetEq, however, Audio
943 // Conference Mixer relies on VAD decisions and fails without them.
944 neteq_config.enable_post_decode_vad = true;
945}
946
947AudioCodingModule::Config::Config(const Config&) = default;
948AudioCodingModule::Config::~Config() = default;
949
Henrik Lundin64dad832015-05-11 12:44:23 +0200950AudioCodingModule* AudioCodingModule::Create(const Config& config) {
kwibergc13ded52016-06-17 06:00:45 -0700951 return new AudioCodingModuleImpl(config);
turaj@webrtc.org7959e162013-09-12 18:30:26 +0000952}
953
turaj@webrtc.org7959e162013-09-12 18:30:26 +0000954int AudioCodingModule::NumberOfCodecs() {
kwibergfce4a942015-10-27 11:40:24 -0700955 return static_cast<int>(acm2::RentACodec::NumberOfCodecs());
turaj@webrtc.org7959e162013-09-12 18:30:26 +0000956}
957
turaj@webrtc.org7959e162013-09-12 18:30:26 +0000958int AudioCodingModule::Codec(int list_id, CodecInst* codec) {
kwibergfce4a942015-10-27 11:40:24 -0700959 auto codec_id = acm2::RentACodec::CodecIdFromIndex(list_id);
960 if (!codec_id)
961 return -1;
962 auto ci = acm2::RentACodec::CodecInstById(*codec_id);
963 if (!ci)
964 return -1;
965 *codec = *ci;
966 return 0;
turaj@webrtc.org7959e162013-09-12 18:30:26 +0000967}
968
turaj@webrtc.org7959e162013-09-12 18:30:26 +0000969int AudioCodingModule::Codec(const char* payload_name,
970 CodecInst* codec,
971 int sampling_freq_hz,
Peter Kasting69558702016-01-12 16:26:35 -0800972 size_t channels) {
Danil Chapovalovb6021232018-06-19 13:26:36 +0200973 absl::optional<CodecInst> ci = acm2::RentACodec::CodecInstByParams(
turaj@webrtc.org6d5d2482013-10-06 04:47:28 +0000974 payload_name, sampling_freq_hz, channels);
kwibergfce4a942015-10-27 11:40:24 -0700975 if (ci) {
976 *codec = *ci;
977 return 0;
978 } else {
979 // We couldn't find a matching codec, so set the parameters to unacceptable
turaj@webrtc.org7959e162013-09-12 18:30:26 +0000980 // values and return.
981 codec->plname[0] = '\0';
982 codec->pltype = -1;
983 codec->pacsize = 0;
984 codec->rate = 0;
985 codec->plfreq = 0;
986 return -1;
987 }
turaj@webrtc.org7959e162013-09-12 18:30:26 +0000988}
989
turaj@webrtc.org7959e162013-09-12 18:30:26 +0000990int AudioCodingModule::Codec(const char* payload_name,
991 int sampling_freq_hz,
Peter Kasting69558702016-01-12 16:26:35 -0800992 size_t channels) {
Danil Chapovalovb6021232018-06-19 13:26:36 +0200993 absl::optional<acm2::RentACodec::CodecId> ci =
Karl Wibergbe579832015-11-10 22:34:18 +0100994 acm2::RentACodec::CodecIdByParams(payload_name, sampling_freq_hz,
995 channels);
kwibergfce4a942015-10-27 11:40:24 -0700996 if (!ci)
997 return -1;
Danil Chapovalovb6021232018-06-19 13:26:36 +0200998 absl::optional<int> i = acm2::RentACodec::CodecIndexFromId(*ci);
kwibergfce4a942015-10-27 11:40:24 -0700999 return i ? *i : -1;
turaj@webrtc.org7959e162013-09-12 18:30:26 +00001000}
1001
turaj@webrtc.org7959e162013-09-12 18:30:26 +00001002} // namespace webrtc