blob: e500c78b50657ee029702157034d4eec15491e38 [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>
Jonas Olssona4d87372019-07-05 19:08:33 +020014
Jonathan Yu36344a02017-07-30 01:55:34 -070015#include <algorithm>
Yves Gerey988cc082018-10-23 12:03:01 +020016#include <cstdint>
Jonathan Yu36344a02017-07-30 01:55:34 -070017
Niels Möller2edab4c2018-10-22 09:48:08 +020018#include "absl/strings/match.h"
Yves Gerey988cc082018-10-23 12:03:01 +020019#include "api/array_view.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020020#include "modules/audio_coding/acm2/acm_receiver.h"
21#include "modules/audio_coding/acm2/acm_resampler.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"
Steve Anton10542f22019-01-11 09:11:00 -080026#include "rtc_base/critical_section.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
kwibergc13ded52016-06-17 06:00:45 -070048 // Sets the bitrate to the specified value in bits/sec. In case the codec does
49 // not support the requested value it will choose an appropriate value
50 // instead.
51 void SetBitRate(int bitrate_bps) override;
52
53 // Register a transport callback which will be
54 // called to deliver the encoded buffers.
55 int RegisterTransportCallback(AudioPacketizationCallback* transport) override;
56
57 // Add 10 ms of raw (PCM) audio data to the encoder.
58 int Add10MsData(const AudioFrame& audio_frame) override;
59
60 /////////////////////////////////////////
kwibergc13ded52016-06-17 06:00:45 -070061 // (FEC) Forward Error Correction (codec internal)
62 //
63
kwibergc13ded52016-06-17 06:00:45 -070064 // Set target packet loss rate
65 int SetPacketLossRate(int loss_rate) override;
66
67 /////////////////////////////////////////
68 // (VAD) Voice Activity Detection
69 // and
70 // (CNG) Comfort Noise Generation
71 //
72
kwibergc13ded52016-06-17 06:00:45 -070073 int RegisterVADCallback(ACMVADCallback* vad_callback) override;
74
75 /////////////////////////////////////////
76 // Receiver
77 //
78
79 // Initialize receiver, resets codec database etc.
80 int InitializeReceiver() override;
81
82 // Get current receive frequency.
83 int ReceiveFrequency() const override;
84
85 // Get current playout frequency.
86 int PlayoutFrequency() const override;
87
kwiberg1c07c702017-03-27 07:15:49 -070088 void SetReceiveCodecs(const std::map<int, SdpAudioFormat>& codecs) override;
89
kwibergc13ded52016-06-17 06:00:45 -070090 // Get current received codec.
Fredrik Solenbergf693bfa2018-12-11 12:22:10 +010091 absl::optional<std::pair<int, SdpAudioFormat>> ReceiveCodec() const override;
ossue280cde2016-10-12 11:04:10 -070092
kwibergc13ded52016-06-17 06:00:45 -070093 // Incoming packet from network parsed and ready for decode.
94 int IncomingPacket(const uint8_t* incoming_payload,
95 const size_t payload_length,
Niels Möllerafb5dbb2019-02-15 15:21:47 +010096 const RTPHeader& rtp_info) override;
kwibergc13ded52016-06-17 06:00:45 -070097
kwibergc13ded52016-06-17 06:00:45 -070098 // Minimum playout delay.
99 int SetMinimumPlayoutDelay(int time_ms) override;
100
101 // Maximum playout delay.
102 int SetMaximumPlayoutDelay(int time_ms) override;
103
Ruslan Burakov3b50f9f2019-02-06 09:45:56 +0100104 bool SetBaseMinimumPlayoutDelayMs(int delay_ms) override;
105
106 int GetBaseMinimumPlayoutDelayMs() const override;
107
Danil Chapovalovb6021232018-06-19 13:26:36 +0200108 absl::optional<uint32_t> PlayoutTimestamp() override;
kwibergc13ded52016-06-17 06:00:45 -0700109
henrik.lundinb3f1c5d2016-08-22 15:39:53 -0700110 int FilteredCurrentDelayMs() const override;
111
Henrik Lundinabbff892017-11-29 09:14:04 +0100112 int TargetDelayMs() const override;
113
kwibergc13ded52016-06-17 06:00:45 -0700114 // Get 10 milliseconds of raw audio data to play out, and
115 // automatic resample to the requested frequency if > 0.
116 int PlayoutData10Ms(int desired_freq_hz,
117 AudioFrame* audio_frame,
118 bool* muted) override;
kwibergc13ded52016-06-17 06:00:45 -0700119
120 /////////////////////////////////////////
121 // Statistics
122 //
123
124 int GetNetworkStatistics(NetworkStatistics* statistics) override;
125
kwibergc13ded52016-06-17 06:00:45 -0700126 // If current send codec is Opus, informs it about the maximum playback rate
127 // the receiver will render.
128 int SetOpusMaxPlaybackRate(int frequency_hz) override;
129
130 int EnableOpusDtx() override;
131
132 int DisableOpusDtx() override;
133
kwibergc13ded52016-06-17 06:00:45 -0700134 int EnableNack(size_t max_nack_list_size) override;
135
136 void DisableNack() override;
137
138 std::vector<uint16_t> GetNackList(int64_t round_trip_time_ms) const override;
139
140 void GetDecodingCallStatistics(AudioDecodingCallStats* stats) const override;
141
ivoce1198e02017-09-08 08:13:19 -0700142 ANAStats GetANAStats() const override;
143
kwibergc13ded52016-06-17 06:00:45 -0700144 private:
145 struct InputData {
146 uint32_t input_timestamp;
147 const int16_t* audio;
148 size_t length_per_channel;
149 size_t audio_channel;
150 // If a re-mix is required (up or down), this buffer will store a re-mixed
151 // version of the input.
152 int16_t buffer[WEBRTC_10MS_PCM_AUDIO];
153 };
154
155 // This member class writes values to the named UMA histogram, but only if
156 // the value has changed since the last time (and always for the first call).
157 class ChangeLogger {
158 public:
159 explicit ChangeLogger(const std::string& histogram_name)
160 : histogram_name_(histogram_name) {}
161 // Logs the new value if it is different from the last logged value, or if
162 // this is the first call.
163 void MaybeLog(int value);
164
165 private:
166 int last_value_ = 0;
167 int first_time_ = true;
168 const std::string histogram_name_;
169 };
170
kwibergc13ded52016-06-17 06:00:45 -0700171 int Add10MsDataInternal(const AudioFrame& audio_frame, InputData* input_data)
danilchap56359be2017-09-07 07:53:45 -0700172 RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700173 int Encode(const InputData& input_data)
danilchap56359be2017-09-07 07:53:45 -0700174 RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700175
danilchap56359be2017-09-07 07:53:45 -0700176 int InitializeReceiverSafe() RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700177
178 bool HaveValidEncoder(const char* caller_name) const
danilchap56359be2017-09-07 07:53:45 -0700179 RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700180
181 // Preprocessing of input audio, including resampling and down-mixing if
182 // required, before pushing audio into encoder's buffer.
183 //
184 // in_frame: input audio-frame
185 // ptr_out: pointer to output audio_frame. If no preprocessing is required
186 // |ptr_out| will be pointing to |in_frame|, otherwise pointing to
187 // |preprocess_frame_|.
188 //
189 // Return value:
190 // -1: if encountering an error.
191 // 0: otherwise.
192 int PreprocessToAddData(const AudioFrame& in_frame,
193 const AudioFrame** ptr_out)
danilchap56359be2017-09-07 07:53:45 -0700194 RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700195
196 // Change required states after starting to receive the codec corresponding
197 // to |index|.
198 int UpdateUponReceivingCodec(int index);
199
200 rtc::CriticalSection acm_crit_sect_;
danilchap56359be2017-09-07 07:53:45 -0700201 rtc::Buffer encode_buffer_ RTC_GUARDED_BY(acm_crit_sect_);
danilchap56359be2017-09-07 07:53:45 -0700202 uint32_t expected_codec_ts_ RTC_GUARDED_BY(acm_crit_sect_);
203 uint32_t expected_in_ts_ RTC_GUARDED_BY(acm_crit_sect_);
204 acm2::ACMResampler resampler_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700205 acm2::AcmReceiver receiver_; // AcmReceiver has it's own internal lock.
danilchap56359be2017-09-07 07:53:45 -0700206 ChangeLogger bitrate_logger_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700207
Karl Wiberg49c33ce2018-11-12 14:21:58 +0100208 // Current encoder stack, provided by a call to RegisterEncoder.
danilchap56359be2017-09-07 07:53:45 -0700209 std::unique_ptr<AudioEncoder> encoder_stack_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700210
danilchap56359be2017-09-07 07:53:45 -0700211 std::unique_ptr<AudioDecoder> isac_decoder_16k_
212 RTC_GUARDED_BY(acm_crit_sect_);
213 std::unique_ptr<AudioDecoder> isac_decoder_32k_
214 RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700215
216 // This is to keep track of CN instances where we can send DTMFs.
danilchap56359be2017-09-07 07:53:45 -0700217 uint8_t previous_pltype_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700218
danilchap56359be2017-09-07 07:53:45 -0700219 bool receiver_initialized_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700220
danilchap56359be2017-09-07 07:53:45 -0700221 AudioFrame preprocess_frame_ RTC_GUARDED_BY(acm_crit_sect_);
222 bool first_10ms_data_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700223
danilchap56359be2017-09-07 07:53:45 -0700224 bool first_frame_ RTC_GUARDED_BY(acm_crit_sect_);
225 uint32_t last_timestamp_ RTC_GUARDED_BY(acm_crit_sect_);
226 uint32_t last_rtp_timestamp_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700227
228 rtc::CriticalSection callback_crit_sect_;
229 AudioPacketizationCallback* packetization_callback_
danilchap56359be2017-09-07 07:53:45 -0700230 RTC_GUARDED_BY(callback_crit_sect_);
231 ACMVADCallback* vad_callback_ RTC_GUARDED_BY(callback_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700232
233 int codec_histogram_bins_log_[static_cast<size_t>(
234 AudioEncoder::CodecType::kMaxLoggedAudioCodecTypes)];
235 int number_of_consecutive_empty_packets_;
236};
237
238// Adds a codec usage sample to the histogram.
239void UpdateCodecTypeHistogram(size_t codec_type) {
240 RTC_HISTOGRAM_ENUMERATION(
241 "WebRTC.Audio.Encoder.CodecType", static_cast<int>(codec_type),
242 static_cast<int>(
243 webrtc::AudioEncoder::CodecType::kMaxLoggedAudioCodecTypes));
244}
245
kwibergc13ded52016-06-17 06:00:45 -0700246// Stereo-to-mono can be used as in-place.
247int DownMix(const AudioFrame& frame,
248 size_t length_out_buff,
249 int16_t* out_buff) {
yujo36b1a5f2017-06-12 12:45:32 -0700250 RTC_DCHECK_EQ(frame.num_channels_, 2);
251 RTC_DCHECK_GE(length_out_buff, frame.samples_per_channel_);
252
253 if (!frame.muted()) {
254 const int16_t* frame_data = frame.data();
255 for (size_t n = 0; n < frame.samples_per_channel_; ++n) {
Yves Gerey665174f2018-06-19 15:03:05 +0200256 out_buff[n] =
257 static_cast<int16_t>((static_cast<int32_t>(frame_data[2 * n]) +
258 static_cast<int32_t>(frame_data[2 * n + 1])) >>
259 1);
yujo36b1a5f2017-06-12 12:45:32 -0700260 }
261 } else {
Jonathan Yu36344a02017-07-30 01:55:34 -0700262 std::fill(out_buff, out_buff + frame.samples_per_channel_, 0);
kwibergc13ded52016-06-17 06:00:45 -0700263 }
kwibergc13ded52016-06-17 06:00:45 -0700264 return 0;
265}
266
267// Mono-to-stereo can be used as in-place.
268int UpMix(const AudioFrame& frame, size_t length_out_buff, int16_t* out_buff) {
yujo36b1a5f2017-06-12 12:45:32 -0700269 RTC_DCHECK_EQ(frame.num_channels_, 1);
270 RTC_DCHECK_GE(length_out_buff, 2 * frame.samples_per_channel_);
271
272 if (!frame.muted()) {
273 const int16_t* frame_data = frame.data();
274 for (size_t n = frame.samples_per_channel_; n != 0; --n) {
275 size_t i = n - 1;
276 int16_t sample = frame_data[i];
277 out_buff[2 * i + 1] = sample;
278 out_buff[2 * i] = sample;
279 }
280 } else {
Jonathan Yu36344a02017-07-30 01:55:34 -0700281 std::fill(out_buff, out_buff + frame.samples_per_channel_ * 2, 0);
kwibergc13ded52016-06-17 06:00:45 -0700282 }
283 return 0;
284}
285
kwibergc13ded52016-06-17 06:00:45 -0700286void AudioCodingModuleImpl::ChangeLogger::MaybeLog(int value) {
287 if (value != last_value_ || first_time_) {
288 first_time_ = false;
289 last_value_ = value;
290 RTC_HISTOGRAM_COUNTS_SPARSE_100(histogram_name_, value);
291 }
292}
293
294AudioCodingModuleImpl::AudioCodingModuleImpl(
295 const AudioCodingModule::Config& config)
solenbergc7b4a452017-09-28 07:37:11 -0700296 : expected_codec_ts_(0xD87F3F9F),
kwibergc13ded52016-06-17 06:00:45 -0700297 expected_in_ts_(0xD87F3F9F),
298 receiver_(config),
299 bitrate_logger_("WebRTC.Audio.TargetBitrateInKbps"),
kwibergc13ded52016-06-17 06:00:45 -0700300 encoder_stack_(nullptr),
301 previous_pltype_(255),
302 receiver_initialized_(false),
303 first_10ms_data_(false),
304 first_frame_(true),
305 packetization_callback_(NULL),
306 vad_callback_(NULL),
307 codec_histogram_bins_log_(),
308 number_of_consecutive_empty_packets_(0) {
309 if (InitializeReceiverSafe() < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100310 RTC_LOG(LS_ERROR) << "Cannot initialize receiver";
kwibergc13ded52016-06-17 06:00:45 -0700311 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100312 RTC_LOG(LS_INFO) << "Created";
kwibergc13ded52016-06-17 06:00:45 -0700313}
314
315AudioCodingModuleImpl::~AudioCodingModuleImpl() = default;
316
317int32_t AudioCodingModuleImpl::Encode(const InputData& input_data) {
318 AudioEncoder::EncodedInfo encoded_info;
319 uint8_t previous_pltype;
320
321 // Check if there is an encoder before.
322 if (!HaveValidEncoder("Process"))
323 return -1;
324
Yves Gerey665174f2018-06-19 15:03:05 +0200325 if (!first_frame_) {
deadbeeffcada902016-08-24 12:45:13 -0700326 RTC_DCHECK(IsNewerTimestamp(input_data.input_timestamp, last_timestamp_))
ossu63fb95a2016-07-06 09:34:22 -0700327 << "Time should not move backwards";
328 }
329
kwibergc13ded52016-06-17 06:00:45 -0700330 // Scale the timestamp to the codec's RTP timestamp rate.
331 uint32_t rtp_timestamp =
Karl Wiberg053c3712019-05-16 15:24:17 +0200332 first_frame_
333 ? input_data.input_timestamp
334 : last_rtp_timestamp_ +
335 rtc::dchecked_cast<uint32_t>(rtc::CheckedDivExact(
336 int64_t{input_data.input_timestamp - last_timestamp_} *
337 encoder_stack_->RtpTimestampRateHz(),
338 int64_t{encoder_stack_->SampleRateHz()}));
kwibergc13ded52016-06-17 06:00:45 -0700339 last_timestamp_ = input_data.input_timestamp;
340 last_rtp_timestamp_ = rtp_timestamp;
341 first_frame_ = false;
342
343 // Clear the buffer before reuse - encoded data will get appended.
344 encode_buffer_.Clear();
345 encoded_info = encoder_stack_->Encode(
Yves Gerey665174f2018-06-19 15:03:05 +0200346 rtp_timestamp,
347 rtc::ArrayView<const int16_t>(
348 input_data.audio,
349 input_data.audio_channel * input_data.length_per_channel),
kwibergc13ded52016-06-17 06:00:45 -0700350 &encode_buffer_);
351
352 bitrate_logger_.MaybeLog(encoder_stack_->GetTargetBitrate() / 1000);
353 if (encode_buffer_.size() == 0 && !encoded_info.send_even_if_empty) {
354 // Not enough data.
355 return 0;
356 }
357 previous_pltype = previous_pltype_; // Read it while we have the critsect.
358
359 // Log codec type to histogram once every 500 packets.
360 if (encoded_info.encoded_bytes == 0) {
361 ++number_of_consecutive_empty_packets_;
362 } else {
363 size_t codec_type = static_cast<size_t>(encoded_info.encoder_type);
364 codec_histogram_bins_log_[codec_type] +=
365 number_of_consecutive_empty_packets_ + 1;
366 number_of_consecutive_empty_packets_ = 0;
367 if (codec_histogram_bins_log_[codec_type] >= 500) {
368 codec_histogram_bins_log_[codec_type] -= 500;
369 UpdateCodecTypeHistogram(codec_type);
370 }
371 }
372
Niels Möller87e2d782019-03-07 10:18:23 +0100373 AudioFrameType frame_type;
kwibergc13ded52016-06-17 06:00:45 -0700374 if (encode_buffer_.size() == 0 && encoded_info.send_even_if_empty) {
Niels Möllerc936cb62019-03-19 14:10:16 +0100375 frame_type = AudioFrameType::kEmptyFrame;
kwibergc13ded52016-06-17 06:00:45 -0700376 encoded_info.payload_type = previous_pltype;
377 } else {
kwibergaf476c72016-11-28 15:21:39 -0800378 RTC_DCHECK_GT(encode_buffer_.size(), 0);
Niels Möllerc936cb62019-03-19 14:10:16 +0100379 frame_type = encoded_info.speech ? AudioFrameType::kAudioFrameSpeech
380 : AudioFrameType::kAudioFrameCN;
kwibergc13ded52016-06-17 06:00:45 -0700381 }
382
383 {
384 rtc::CritScope lock(&callback_crit_sect_);
385 if (packetization_callback_) {
386 packetization_callback_->SendData(
387 frame_type, encoded_info.payload_type, encoded_info.encoded_timestamp,
Niels Möllerc35b6e62019-04-25 16:31:18 +0200388 encode_buffer_.data(), encode_buffer_.size());
kwibergc13ded52016-06-17 06:00:45 -0700389 }
390
391 if (vad_callback_) {
392 // Callback with VAD decision.
393 vad_callback_->InFrameType(frame_type);
394 }
395 }
396 previous_pltype_ = encoded_info.payload_type;
397 return static_cast<int32_t>(encode_buffer_.size());
398}
399
400/////////////////////////////////////////
401// Sender
402//
403
kwibergc13ded52016-06-17 06:00:45 -0700404void AudioCodingModuleImpl::ModifyEncoder(
kwiberg24c7c122016-09-28 11:57:10 -0700405 rtc::FunctionView<void(std::unique_ptr<AudioEncoder>*)> modifier) {
kwibergc13ded52016-06-17 06:00:45 -0700406 rtc::CritScope lock(&acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700407 modifier(&encoder_stack_);
408}
409
kwibergc13ded52016-06-17 06:00:45 -0700410void AudioCodingModuleImpl::SetBitRate(int bitrate_bps) {
411 rtc::CritScope lock(&acm_crit_sect_);
412 if (encoder_stack_) {
Danil Chapovalovb6021232018-06-19 13:26:36 +0200413 encoder_stack_->OnReceivedUplinkBandwidth(bitrate_bps, absl::nullopt);
kwibergc13ded52016-06-17 06:00:45 -0700414 }
415}
416
417// Register a transport callback which will be called to deliver
418// the encoded buffers.
419int AudioCodingModuleImpl::RegisterTransportCallback(
420 AudioPacketizationCallback* transport) {
421 rtc::CritScope lock(&callback_crit_sect_);
422 packetization_callback_ = transport;
423 return 0;
424}
425
426// Add 10MS of raw (PCM) audio data to the encoder.
427int AudioCodingModuleImpl::Add10MsData(const AudioFrame& audio_frame) {
428 InputData input_data;
429 rtc::CritScope lock(&acm_crit_sect_);
430 int r = Add10MsDataInternal(audio_frame, &input_data);
431 return r < 0 ? r : Encode(input_data);
432}
433
434int AudioCodingModuleImpl::Add10MsDataInternal(const AudioFrame& audio_frame,
435 InputData* input_data) {
436 if (audio_frame.samples_per_channel_ == 0) {
437 assert(false);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100438 RTC_LOG(LS_ERROR) << "Cannot Add 10 ms audio, payload length is zero";
kwibergc13ded52016-06-17 06:00:45 -0700439 return -1;
440 }
441
442 if (audio_frame.sample_rate_hz_ > 48000) {
443 assert(false);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100444 RTC_LOG(LS_ERROR) << "Cannot Add 10 ms audio, input frequency not valid";
kwibergc13ded52016-06-17 06:00:45 -0700445 return -1;
446 }
447
448 // If the length and frequency matches. We currently just support raw PCM.
449 if (static_cast<size_t>(audio_frame.sample_rate_hz_ / 100) !=
450 audio_frame.samples_per_channel_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100451 RTC_LOG(LS_ERROR)
Alex Loiko300ec8c2017-05-30 17:23:28 +0200452 << "Cannot Add 10 ms audio, input frequency and length doesn't match";
kwibergc13ded52016-06-17 06:00:45 -0700453 return -1;
454 }
455
Alex Loiko65438812019-02-22 10:13:44 +0100456 if (audio_frame.num_channels_ != 1 && audio_frame.num_channels_ != 2 &&
457 audio_frame.num_channels_ != 4 && audio_frame.num_channels_ != 6 &&
458 audio_frame.num_channels_ != 8) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100459 RTC_LOG(LS_ERROR) << "Cannot Add 10 ms audio, invalid number of channels.";
kwibergc13ded52016-06-17 06:00:45 -0700460 return -1;
461 }
462
463 // Do we have a codec registered?
464 if (!HaveValidEncoder("Add10MsData")) {
465 return -1;
466 }
467
468 const AudioFrame* ptr_frame;
469 // Perform a resampling, also down-mix if it is required and can be
470 // performed before resampling (a down mix prior to resampling will take
471 // place if both primary and secondary encoders are mono and input is in
472 // stereo).
473 if (PreprocessToAddData(audio_frame, &ptr_frame) < 0) {
474 return -1;
475 }
476
477 // Check whether we need an up-mix or down-mix?
478 const size_t current_num_channels = encoder_stack_->NumChannels();
479 const bool same_num_channels =
480 ptr_frame->num_channels_ == current_num_channels;
481
482 if (!same_num_channels) {
483 if (ptr_frame->num_channels_ == 1) {
484 if (UpMix(*ptr_frame, WEBRTC_10MS_PCM_AUDIO, input_data->buffer) < 0)
485 return -1;
486 } else {
487 if (DownMix(*ptr_frame, WEBRTC_10MS_PCM_AUDIO, input_data->buffer) < 0)
488 return -1;
489 }
490 }
491
492 // When adding data to encoders this pointer is pointing to an audio buffer
493 // with correct number of channels.
yujo36b1a5f2017-06-12 12:45:32 -0700494 const int16_t* ptr_audio = ptr_frame->data();
kwibergc13ded52016-06-17 06:00:45 -0700495
496 // For pushing data to primary, point the |ptr_audio| to correct buffer.
497 if (!same_num_channels)
498 ptr_audio = input_data->buffer;
499
yujo36b1a5f2017-06-12 12:45:32 -0700500 // TODO(yujo): Skip encode of muted frames.
kwibergc13ded52016-06-17 06:00:45 -0700501 input_data->input_timestamp = ptr_frame->timestamp_;
502 input_data->audio = ptr_audio;
503 input_data->length_per_channel = ptr_frame->samples_per_channel_;
504 input_data->audio_channel = current_num_channels;
505
506 return 0;
507}
508
509// Perform a resampling and down-mix if required. We down-mix only if
510// encoder is mono and input is stereo. In case of dual-streaming, both
511// encoders has to be mono for down-mix to take place.
512// |*ptr_out| will point to the pre-processed audio-frame. If no pre-processing
513// is required, |*ptr_out| points to |in_frame|.
yujo36b1a5f2017-06-12 12:45:32 -0700514// TODO(yujo): Make this more efficient for muted frames.
kwibergc13ded52016-06-17 06:00:45 -0700515int AudioCodingModuleImpl::PreprocessToAddData(const AudioFrame& in_frame,
516 const AudioFrame** ptr_out) {
517 const bool resample =
518 in_frame.sample_rate_hz_ != encoder_stack_->SampleRateHz();
519
520 // This variable is true if primary codec and secondary codec (if exists)
521 // are both mono and input is stereo.
522 // TODO(henrik.lundin): This condition should probably be
523 // in_frame.num_channels_ > encoder_stack_->NumChannels()
524 const bool down_mix =
525 in_frame.num_channels_ == 2 && encoder_stack_->NumChannels() == 1;
526
527 if (!first_10ms_data_) {
528 expected_in_ts_ = in_frame.timestamp_;
529 expected_codec_ts_ = in_frame.timestamp_;
530 first_10ms_data_ = true;
531 } else if (in_frame.timestamp_ != expected_in_ts_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100532 RTC_LOG(LS_WARNING) << "Unexpected input timestamp: " << in_frame.timestamp_
533 << ", expected: " << expected_in_ts_;
kwibergc13ded52016-06-17 06:00:45 -0700534 expected_codec_ts_ +=
535 (in_frame.timestamp_ - expected_in_ts_) *
536 static_cast<uint32_t>(
537 static_cast<double>(encoder_stack_->SampleRateHz()) /
538 static_cast<double>(in_frame.sample_rate_hz_));
539 expected_in_ts_ = in_frame.timestamp_;
540 }
541
kwibergc13ded52016-06-17 06:00:45 -0700542 if (!down_mix && !resample) {
543 // No pre-processing is required.
ossu63fb95a2016-07-06 09:34:22 -0700544 if (expected_in_ts_ == expected_codec_ts_) {
545 // If we've never resampled, we can use the input frame as-is
546 *ptr_out = &in_frame;
547 } else {
548 // Otherwise we'll need to alter the timestamp. Since in_frame is const,
549 // we'll have to make a copy of it.
550 preprocess_frame_.CopyFrom(in_frame);
551 preprocess_frame_.timestamp_ = expected_codec_ts_;
552 *ptr_out = &preprocess_frame_;
553 }
554
kwibergc13ded52016-06-17 06:00:45 -0700555 expected_in_ts_ += static_cast<uint32_t>(in_frame.samples_per_channel_);
556 expected_codec_ts_ += static_cast<uint32_t>(in_frame.samples_per_channel_);
kwibergc13ded52016-06-17 06:00:45 -0700557 return 0;
558 }
559
560 *ptr_out = &preprocess_frame_;
561 preprocess_frame_.num_channels_ = in_frame.num_channels_;
562 int16_t audio[WEBRTC_10MS_PCM_AUDIO];
yujo36b1a5f2017-06-12 12:45:32 -0700563 const int16_t* src_ptr_audio = in_frame.data();
kwibergc13ded52016-06-17 06:00:45 -0700564 if (down_mix) {
565 // If a resampling is required the output of a down-mix is written into a
566 // local buffer, otherwise, it will be written to the output frame.
Yves Gerey665174f2018-06-19 15:03:05 +0200567 int16_t* dest_ptr_audio =
568 resample ? audio : preprocess_frame_.mutable_data();
kwibergc13ded52016-06-17 06:00:45 -0700569 if (DownMix(in_frame, WEBRTC_10MS_PCM_AUDIO, dest_ptr_audio) < 0)
570 return -1;
571 preprocess_frame_.num_channels_ = 1;
572 // Set the input of the resampler is the down-mixed signal.
573 src_ptr_audio = audio;
574 }
575
576 preprocess_frame_.timestamp_ = expected_codec_ts_;
577 preprocess_frame_.samples_per_channel_ = in_frame.samples_per_channel_;
578 preprocess_frame_.sample_rate_hz_ = in_frame.sample_rate_hz_;
579 // If it is required, we have to do a resampling.
580 if (resample) {
581 // The result of the resampler is written to output frame.
yujo36b1a5f2017-06-12 12:45:32 -0700582 int16_t* dest_ptr_audio = preprocess_frame_.mutable_data();
kwibergc13ded52016-06-17 06:00:45 -0700583
584 int samples_per_channel = resampler_.Resample10Msec(
585 src_ptr_audio, in_frame.sample_rate_hz_, encoder_stack_->SampleRateHz(),
586 preprocess_frame_.num_channels_, AudioFrame::kMaxDataSizeSamples,
587 dest_ptr_audio);
588
589 if (samples_per_channel < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100590 RTC_LOG(LS_ERROR) << "Cannot add 10 ms audio, resampling failed";
kwibergc13ded52016-06-17 06:00:45 -0700591 return -1;
592 }
593 preprocess_frame_.samples_per_channel_ =
594 static_cast<size_t>(samples_per_channel);
595 preprocess_frame_.sample_rate_hz_ = encoder_stack_->SampleRateHz();
596 }
597
598 expected_codec_ts_ +=
599 static_cast<uint32_t>(preprocess_frame_.samples_per_channel_);
600 expected_in_ts_ += static_cast<uint32_t>(in_frame.samples_per_channel_);
601
602 return 0;
603}
604
605/////////////////////////////////////////
kwibergc13ded52016-06-17 06:00:45 -0700606// (FEC) Forward Error Correction (codec internal)
607//
608
kwibergc13ded52016-06-17 06:00:45 -0700609int AudioCodingModuleImpl::SetPacketLossRate(int loss_rate) {
610 rtc::CritScope lock(&acm_crit_sect_);
611 if (HaveValidEncoder("SetPacketLossRate")) {
minyue4b9a2cb2016-11-30 06:49:59 -0800612 encoder_stack_->OnReceivedUplinkPacketLossFraction(loss_rate / 100.0);
kwibergc13ded52016-06-17 06:00:45 -0700613 }
614 return 0;
615}
616
617/////////////////////////////////////////
kwibergc13ded52016-06-17 06:00:45 -0700618// Receiver
619//
620
621int AudioCodingModuleImpl::InitializeReceiver() {
622 rtc::CritScope lock(&acm_crit_sect_);
623 return InitializeReceiverSafe();
624}
625
626// Initialize receiver, resets codec database etc.
627int AudioCodingModuleImpl::InitializeReceiverSafe() {
628 // If the receiver is already initialized then we want to destroy any
629 // existing decoders. After a call to this function, we should have a clean
630 // start-up.
kwiberg6b19b562016-09-20 04:02:25 -0700631 if (receiver_initialized_)
632 receiver_.RemoveAllCodecs();
kwibergc13ded52016-06-17 06:00:45 -0700633 receiver_.FlushBuffers();
634
kwibergc13ded52016-06-17 06:00:45 -0700635 receiver_initialized_ = true;
636 return 0;
637}
638
639// Get current receive frequency.
640int AudioCodingModuleImpl::ReceiveFrequency() const {
641 const auto last_packet_sample_rate = receiver_.last_packet_sample_rate_hz();
642 return last_packet_sample_rate ? *last_packet_sample_rate
643 : receiver_.last_output_sample_rate_hz();
644}
645
646// Get current playout frequency.
647int AudioCodingModuleImpl::PlayoutFrequency() const {
kwibergc13ded52016-06-17 06:00:45 -0700648 return receiver_.last_output_sample_rate_hz();
649}
650
kwiberg1c07c702017-03-27 07:15:49 -0700651void AudioCodingModuleImpl::SetReceiveCodecs(
652 const std::map<int, SdpAudioFormat>& codecs) {
653 rtc::CritScope lock(&acm_crit_sect_);
654 receiver_.SetCodecs(codecs);
655}
656
Fredrik Solenbergf693bfa2018-12-11 12:22:10 +0100657absl::optional<std::pair<int, SdpAudioFormat>>
Jonas Olssona4d87372019-07-05 19:08:33 +0200658AudioCodingModuleImpl::ReceiveCodec() const {
kwiberg5adaf732016-10-04 09:33:27 -0700659 rtc::CritScope lock(&acm_crit_sect_);
Fredrik Solenbergf693bfa2018-12-11 12:22:10 +0100660 return receiver_.LastDecoder();
ossue280cde2016-10-12 11:04:10 -0700661}
662
kwibergc13ded52016-06-17 06:00:45 -0700663// Incoming packet from network parsed and ready for decode.
664int AudioCodingModuleImpl::IncomingPacket(const uint8_t* incoming_payload,
665 const size_t payload_length,
Niels Möllerafb5dbb2019-02-15 15:21:47 +0100666 const RTPHeader& rtp_header) {
henrik.lundinb8c55b12017-05-10 07:38:01 -0700667 RTC_DCHECK_EQ(payload_length == 0, incoming_payload == nullptr);
kwibergc13ded52016-06-17 06:00:45 -0700668 return receiver_.InsertPacket(
669 rtp_header,
670 rtc::ArrayView<const uint8_t>(incoming_payload, payload_length));
671}
672
673// Minimum playout delay (Used for lip-sync).
674int AudioCodingModuleImpl::SetMinimumPlayoutDelay(int time_ms) {
675 if ((time_ms < 0) || (time_ms > 10000)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100676 RTC_LOG(LS_ERROR) << "Delay must be in the range of 0-10000 milliseconds.";
kwibergc13ded52016-06-17 06:00:45 -0700677 return -1;
678 }
679 return receiver_.SetMinimumDelay(time_ms);
680}
681
682int AudioCodingModuleImpl::SetMaximumPlayoutDelay(int time_ms) {
683 if ((time_ms < 0) || (time_ms > 10000)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100684 RTC_LOG(LS_ERROR) << "Delay must be in the range of 0-10000 milliseconds.";
kwibergc13ded52016-06-17 06:00:45 -0700685 return -1;
686 }
687 return receiver_.SetMaximumDelay(time_ms);
688}
689
Ruslan Burakov3b50f9f2019-02-06 09:45:56 +0100690bool AudioCodingModuleImpl::SetBaseMinimumPlayoutDelayMs(int delay_ms) {
691 // All necessary validation happens on NetEq level.
692 return receiver_.SetBaseMinimumDelayMs(delay_ms);
693}
694
695int AudioCodingModuleImpl::GetBaseMinimumPlayoutDelayMs() const {
696 return receiver_.GetBaseMinimumDelayMs();
697}
698
kwibergc13ded52016-06-17 06:00:45 -0700699// Get 10 milliseconds of raw audio data to play out.
700// Automatic resample to the requested frequency.
701int AudioCodingModuleImpl::PlayoutData10Ms(int desired_freq_hz,
702 AudioFrame* audio_frame,
703 bool* muted) {
704 // GetAudio always returns 10 ms, at the requested sample rate.
705 if (receiver_.GetAudio(desired_freq_hz, audio_frame, muted) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100706 RTC_LOG(LS_ERROR) << "PlayoutData failed, RecOut Failed";
kwibergc13ded52016-06-17 06:00:45 -0700707 return -1;
708 }
kwibergc13ded52016-06-17 06:00:45 -0700709 return 0;
710}
711
kwibergc13ded52016-06-17 06:00:45 -0700712/////////////////////////////////////////
713// Statistics
714//
715
716// TODO(turajs) change the return value to void. Also change the corresponding
717// NetEq function.
718int AudioCodingModuleImpl::GetNetworkStatistics(NetworkStatistics* statistics) {
719 receiver_.GetNetworkStatistics(statistics);
720 return 0;
721}
722
723int AudioCodingModuleImpl::RegisterVADCallback(ACMVADCallback* vad_callback) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100724 RTC_LOG(LS_VERBOSE) << "RegisterVADCallback()";
kwibergc13ded52016-06-17 06:00:45 -0700725 rtc::CritScope lock(&callback_crit_sect_);
726 vad_callback_ = vad_callback;
727 return 0;
728}
729
kwibergc13ded52016-06-17 06:00:45 -0700730// Informs Opus encoder of the maximum playback rate the receiver will render.
731int AudioCodingModuleImpl::SetOpusMaxPlaybackRate(int frequency_hz) {
732 rtc::CritScope lock(&acm_crit_sect_);
733 if (!HaveValidEncoder("SetOpusMaxPlaybackRate")) {
734 return -1;
735 }
736 encoder_stack_->SetMaxPlaybackRate(frequency_hz);
737 return 0;
738}
739
740int AudioCodingModuleImpl::EnableOpusDtx() {
741 rtc::CritScope lock(&acm_crit_sect_);
742 if (!HaveValidEncoder("EnableOpusDtx")) {
743 return -1;
744 }
745 return encoder_stack_->SetDtx(true) ? 0 : -1;
746}
747
748int AudioCodingModuleImpl::DisableOpusDtx() {
749 rtc::CritScope lock(&acm_crit_sect_);
750 if (!HaveValidEncoder("DisableOpusDtx")) {
751 return -1;
752 }
753 return encoder_stack_->SetDtx(false) ? 0 : -1;
754}
755
Danil Chapovalovb6021232018-06-19 13:26:36 +0200756absl::optional<uint32_t> AudioCodingModuleImpl::PlayoutTimestamp() {
kwibergc13ded52016-06-17 06:00:45 -0700757 return receiver_.GetPlayoutTimestamp();
758}
759
henrik.lundinb3f1c5d2016-08-22 15:39:53 -0700760int AudioCodingModuleImpl::FilteredCurrentDelayMs() const {
761 return receiver_.FilteredCurrentDelayMs();
762}
763
Henrik Lundinabbff892017-11-29 09:14:04 +0100764int AudioCodingModuleImpl::TargetDelayMs() const {
765 return receiver_.TargetDelayMs();
766}
767
kwibergc13ded52016-06-17 06:00:45 -0700768bool AudioCodingModuleImpl::HaveValidEncoder(const char* caller_name) const {
769 if (!encoder_stack_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100770 RTC_LOG(LS_ERROR) << caller_name << " failed: No send codec is registered.";
kwibergc13ded52016-06-17 06:00:45 -0700771 return false;
772 }
773 return true;
774}
775
kwibergc13ded52016-06-17 06:00:45 -0700776int AudioCodingModuleImpl::EnableNack(size_t max_nack_list_size) {
777 return receiver_.EnableNack(max_nack_list_size);
778}
779
780void AudioCodingModuleImpl::DisableNack() {
781 receiver_.DisableNack();
782}
783
784std::vector<uint16_t> AudioCodingModuleImpl::GetNackList(
785 int64_t round_trip_time_ms) const {
786 return receiver_.GetNackList(round_trip_time_ms);
787}
788
kwibergc13ded52016-06-17 06:00:45 -0700789void AudioCodingModuleImpl::GetDecodingCallStatistics(
Yves Gerey665174f2018-06-19 15:03:05 +0200790 AudioDecodingCallStats* call_stats) const {
kwibergc13ded52016-06-17 06:00:45 -0700791 receiver_.GetDecodingCallStatistics(call_stats);
792}
793
ivoce1198e02017-09-08 08:13:19 -0700794ANAStats AudioCodingModuleImpl::GetANAStats() const {
795 rtc::CritScope lock(&acm_crit_sect_);
796 if (encoder_stack_)
797 return encoder_stack_->GetANAStats();
798 // If no encoder is set, return default stats.
799 return ANAStats();
800}
801
kwibergc13ded52016-06-17 06:00:45 -0700802} // namespace
803
Karl Wiberg5817d3d2018-04-06 10:06:42 +0200804AudioCodingModule::Config::Config(
805 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory)
806 : neteq_config(),
807 clock(Clock::GetRealTimeClock()),
808 decoder_factory(decoder_factory) {
kwiberg36a43882016-08-29 05:33:32 -0700809 // Post-decode VAD is disabled by default in NetEq, however, Audio
810 // Conference Mixer relies on VAD decisions and fails without them.
811 neteq_config.enable_post_decode_vad = true;
812}
813
814AudioCodingModule::Config::Config(const Config&) = default;
815AudioCodingModule::Config::~Config() = default;
816
Henrik Lundin64dad832015-05-11 12:44:23 +0200817AudioCodingModule* AudioCodingModule::Create(const Config& config) {
kwibergc13ded52016-06-17 06:00:45 -0700818 return new AudioCodingModuleImpl(config);
turaj@webrtc.org7959e162013-09-12 18:30:26 +0000819}
820
turaj@webrtc.org7959e162013-09-12 18:30:26 +0000821} // namespace webrtc