blob: b68579b1cbacf2e31f60e72ba996c26b0d5d4df1 [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"
Per Åhgren4dd56a32019-11-19 21:00:59 +010021#include "modules/audio_coding/acm2/acm_remixing.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020022#include "modules/audio_coding/acm2/acm_resampler.h"
Fredrik Solenbergbbf21a32018-04-12 22:44:09 +020023#include "modules/include/module_common_types.h"
Yves Gerey988cc082018-10-23 12:03:01 +020024#include "modules/include/module_common_types_public.h"
25#include "rtc_base/buffer.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020026#include "rtc_base/checks.h"
Steve Anton10542f22019-01-11 09:11:00 -080027#include "rtc_base/critical_section.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020028#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010029#include "rtc_base/numerics/safe_conversions.h"
Yves Gerey988cc082018-10-23 12:03:01 +020030#include "rtc_base/thread_annotations.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020031#include "system_wrappers/include/metrics.h"
turaj@webrtc.org7959e162013-09-12 18:30:26 +000032
33namespace webrtc {
34
kwibergc13ded52016-06-17 06:00:45 -070035namespace {
36
Per Åhgren4f2e9402019-10-04 11:06:15 +020037// Initial size for the buffer in InputBuffer. This matches 6 channels of 10 ms
38// 48 kHz data.
39constexpr size_t kInitialInputDataBufferSize = 6 * 480;
40
kwibergc13ded52016-06-17 06:00:45 -070041class AudioCodingModuleImpl final : public AudioCodingModule {
42 public:
43 explicit AudioCodingModuleImpl(const AudioCodingModule::Config& config);
44 ~AudioCodingModuleImpl() override;
45
46 /////////////////////////////////////////
47 // Sender
48 //
49
kwiberg24c7c122016-09-28 11:57:10 -070050 void ModifyEncoder(rtc::FunctionView<void(std::unique_ptr<AudioEncoder>*)>
51 modifier) override;
kwibergc13ded52016-06-17 06:00:45 -070052
kwibergc13ded52016-06-17 06:00:45 -070053 // 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
kwiberg1c07c702017-03-27 07:15:49 -070082 void SetReceiveCodecs(const std::map<int, SdpAudioFormat>& codecs) override;
83
kwibergc13ded52016-06-17 06:00:45 -070084 // Incoming packet from network parsed and ready for decode.
85 int IncomingPacket(const uint8_t* incoming_payload,
86 const size_t payload_length,
Niels Möllerafb5dbb2019-02-15 15:21:47 +010087 const RTPHeader& rtp_info) override;
kwibergc13ded52016-06-17 06:00:45 -070088
kwibergc13ded52016-06-17 06:00:45 -070089 // Get 10 milliseconds of raw audio data to play out, and
90 // automatic resample to the requested frequency if > 0.
91 int PlayoutData10Ms(int desired_freq_hz,
92 AudioFrame* audio_frame,
93 bool* muted) override;
kwibergc13ded52016-06-17 06:00:45 -070094
95 /////////////////////////////////////////
96 // Statistics
97 //
98
99 int GetNetworkStatistics(NetworkStatistics* statistics) override;
100
ivoce1198e02017-09-08 08:13:19 -0700101 ANAStats GetANAStats() const override;
102
kwibergc13ded52016-06-17 06:00:45 -0700103 private:
104 struct InputData {
Per Åhgren4f2e9402019-10-04 11:06:15 +0200105 InputData() : buffer(kInitialInputDataBufferSize) {}
kwibergc13ded52016-06-17 06:00:45 -0700106 uint32_t input_timestamp;
107 const int16_t* audio;
108 size_t length_per_channel;
109 size_t audio_channel;
110 // If a re-mix is required (up or down), this buffer will store a re-mixed
111 // version of the input.
Per Åhgren4f2e9402019-10-04 11:06:15 +0200112 std::vector<int16_t> buffer;
kwibergc13ded52016-06-17 06:00:45 -0700113 };
114
Per Åhgren4f2e9402019-10-04 11:06:15 +0200115 InputData input_data_ RTC_GUARDED_BY(acm_crit_sect_);
116
kwibergc13ded52016-06-17 06:00:45 -0700117 // This member class writes values to the named UMA histogram, but only if
118 // the value has changed since the last time (and always for the first call).
119 class ChangeLogger {
120 public:
121 explicit ChangeLogger(const std::string& histogram_name)
122 : histogram_name_(histogram_name) {}
123 // Logs the new value if it is different from the last logged value, or if
124 // this is the first call.
125 void MaybeLog(int value);
126
127 private:
128 int last_value_ = 0;
129 int first_time_ = true;
130 const std::string histogram_name_;
131 };
132
kwibergc13ded52016-06-17 06:00:45 -0700133 int Add10MsDataInternal(const AudioFrame& audio_frame, InputData* input_data)
danilchap56359be2017-09-07 07:53:45 -0700134 RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700135 int Encode(const InputData& input_data)
danilchap56359be2017-09-07 07:53:45 -0700136 RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700137
danilchap56359be2017-09-07 07:53:45 -0700138 int InitializeReceiverSafe() RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700139
140 bool HaveValidEncoder(const char* caller_name) const
danilchap56359be2017-09-07 07:53:45 -0700141 RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700142
143 // Preprocessing of input audio, including resampling and down-mixing if
144 // required, before pushing audio into encoder's buffer.
145 //
146 // in_frame: input audio-frame
147 // ptr_out: pointer to output audio_frame. If no preprocessing is required
148 // |ptr_out| will be pointing to |in_frame|, otherwise pointing to
149 // |preprocess_frame_|.
150 //
151 // Return value:
152 // -1: if encountering an error.
153 // 0: otherwise.
154 int PreprocessToAddData(const AudioFrame& in_frame,
155 const AudioFrame** ptr_out)
danilchap56359be2017-09-07 07:53:45 -0700156 RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700157
158 // Change required states after starting to receive the codec corresponding
159 // to |index|.
160 int UpdateUponReceivingCodec(int index);
161
162 rtc::CriticalSection acm_crit_sect_;
danilchap56359be2017-09-07 07:53:45 -0700163 rtc::Buffer encode_buffer_ RTC_GUARDED_BY(acm_crit_sect_);
danilchap56359be2017-09-07 07:53:45 -0700164 uint32_t expected_codec_ts_ RTC_GUARDED_BY(acm_crit_sect_);
165 uint32_t expected_in_ts_ RTC_GUARDED_BY(acm_crit_sect_);
166 acm2::ACMResampler resampler_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700167 acm2::AcmReceiver receiver_; // AcmReceiver has it's own internal lock.
danilchap56359be2017-09-07 07:53:45 -0700168 ChangeLogger bitrate_logger_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700169
Karl Wiberg49c33ce2018-11-12 14:21:58 +0100170 // Current encoder stack, provided by a call to RegisterEncoder.
danilchap56359be2017-09-07 07:53:45 -0700171 std::unique_ptr<AudioEncoder> encoder_stack_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700172
kwibergc13ded52016-06-17 06:00:45 -0700173 // This is to keep track of CN instances where we can send DTMFs.
danilchap56359be2017-09-07 07:53:45 -0700174 uint8_t previous_pltype_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700175
danilchap56359be2017-09-07 07:53:45 -0700176 bool receiver_initialized_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700177
danilchap56359be2017-09-07 07:53:45 -0700178 AudioFrame preprocess_frame_ RTC_GUARDED_BY(acm_crit_sect_);
179 bool first_10ms_data_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700180
danilchap56359be2017-09-07 07:53:45 -0700181 bool first_frame_ RTC_GUARDED_BY(acm_crit_sect_);
182 uint32_t last_timestamp_ RTC_GUARDED_BY(acm_crit_sect_);
183 uint32_t last_rtp_timestamp_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700184
185 rtc::CriticalSection callback_crit_sect_;
186 AudioPacketizationCallback* packetization_callback_
danilchap56359be2017-09-07 07:53:45 -0700187 RTC_GUARDED_BY(callback_crit_sect_);
188 ACMVADCallback* vad_callback_ RTC_GUARDED_BY(callback_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700189
190 int codec_histogram_bins_log_[static_cast<size_t>(
191 AudioEncoder::CodecType::kMaxLoggedAudioCodecTypes)];
192 int number_of_consecutive_empty_packets_;
193};
194
195// Adds a codec usage sample to the histogram.
196void UpdateCodecTypeHistogram(size_t codec_type) {
197 RTC_HISTOGRAM_ENUMERATION(
198 "WebRTC.Audio.Encoder.CodecType", static_cast<int>(codec_type),
199 static_cast<int>(
200 webrtc::AudioEncoder::CodecType::kMaxLoggedAudioCodecTypes));
201}
202
kwibergc13ded52016-06-17 06:00:45 -0700203void AudioCodingModuleImpl::ChangeLogger::MaybeLog(int value) {
204 if (value != last_value_ || first_time_) {
205 first_time_ = false;
206 last_value_ = value;
207 RTC_HISTOGRAM_COUNTS_SPARSE_100(histogram_name_, value);
208 }
209}
210
211AudioCodingModuleImpl::AudioCodingModuleImpl(
212 const AudioCodingModule::Config& config)
solenbergc7b4a452017-09-28 07:37:11 -0700213 : expected_codec_ts_(0xD87F3F9F),
kwibergc13ded52016-06-17 06:00:45 -0700214 expected_in_ts_(0xD87F3F9F),
215 receiver_(config),
216 bitrate_logger_("WebRTC.Audio.TargetBitrateInKbps"),
kwibergc13ded52016-06-17 06:00:45 -0700217 encoder_stack_(nullptr),
218 previous_pltype_(255),
219 receiver_initialized_(false),
220 first_10ms_data_(false),
221 first_frame_(true),
222 packetization_callback_(NULL),
223 vad_callback_(NULL),
224 codec_histogram_bins_log_(),
225 number_of_consecutive_empty_packets_(0) {
226 if (InitializeReceiverSafe() < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100227 RTC_LOG(LS_ERROR) << "Cannot initialize receiver";
kwibergc13ded52016-06-17 06:00:45 -0700228 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100229 RTC_LOG(LS_INFO) << "Created";
kwibergc13ded52016-06-17 06:00:45 -0700230}
231
232AudioCodingModuleImpl::~AudioCodingModuleImpl() = default;
233
234int32_t AudioCodingModuleImpl::Encode(const InputData& input_data) {
235 AudioEncoder::EncodedInfo encoded_info;
236 uint8_t previous_pltype;
237
238 // Check if there is an encoder before.
239 if (!HaveValidEncoder("Process"))
240 return -1;
241
Yves Gerey665174f2018-06-19 15:03:05 +0200242 if (!first_frame_) {
deadbeeffcada902016-08-24 12:45:13 -0700243 RTC_DCHECK(IsNewerTimestamp(input_data.input_timestamp, last_timestamp_))
ossu63fb95a2016-07-06 09:34:22 -0700244 << "Time should not move backwards";
245 }
246
kwibergc13ded52016-06-17 06:00:45 -0700247 // Scale the timestamp to the codec's RTP timestamp rate.
248 uint32_t rtp_timestamp =
Karl Wiberg053c3712019-05-16 15:24:17 +0200249 first_frame_
250 ? input_data.input_timestamp
251 : last_rtp_timestamp_ +
252 rtc::dchecked_cast<uint32_t>(rtc::CheckedDivExact(
253 int64_t{input_data.input_timestamp - last_timestamp_} *
254 encoder_stack_->RtpTimestampRateHz(),
255 int64_t{encoder_stack_->SampleRateHz()}));
kwibergc13ded52016-06-17 06:00:45 -0700256 last_timestamp_ = input_data.input_timestamp;
257 last_rtp_timestamp_ = rtp_timestamp;
258 first_frame_ = false;
259
260 // Clear the buffer before reuse - encoded data will get appended.
261 encode_buffer_.Clear();
262 encoded_info = encoder_stack_->Encode(
Yves Gerey665174f2018-06-19 15:03:05 +0200263 rtp_timestamp,
264 rtc::ArrayView<const int16_t>(
265 input_data.audio,
266 input_data.audio_channel * input_data.length_per_channel),
kwibergc13ded52016-06-17 06:00:45 -0700267 &encode_buffer_);
268
269 bitrate_logger_.MaybeLog(encoder_stack_->GetTargetBitrate() / 1000);
270 if (encode_buffer_.size() == 0 && !encoded_info.send_even_if_empty) {
271 // Not enough data.
272 return 0;
273 }
274 previous_pltype = previous_pltype_; // Read it while we have the critsect.
275
276 // Log codec type to histogram once every 500 packets.
277 if (encoded_info.encoded_bytes == 0) {
278 ++number_of_consecutive_empty_packets_;
279 } else {
280 size_t codec_type = static_cast<size_t>(encoded_info.encoder_type);
281 codec_histogram_bins_log_[codec_type] +=
282 number_of_consecutive_empty_packets_ + 1;
283 number_of_consecutive_empty_packets_ = 0;
284 if (codec_histogram_bins_log_[codec_type] >= 500) {
285 codec_histogram_bins_log_[codec_type] -= 500;
286 UpdateCodecTypeHistogram(codec_type);
287 }
288 }
289
Niels Möller87e2d782019-03-07 10:18:23 +0100290 AudioFrameType frame_type;
kwibergc13ded52016-06-17 06:00:45 -0700291 if (encode_buffer_.size() == 0 && encoded_info.send_even_if_empty) {
Niels Möllerc936cb62019-03-19 14:10:16 +0100292 frame_type = AudioFrameType::kEmptyFrame;
kwibergc13ded52016-06-17 06:00:45 -0700293 encoded_info.payload_type = previous_pltype;
294 } else {
kwibergaf476c72016-11-28 15:21:39 -0800295 RTC_DCHECK_GT(encode_buffer_.size(), 0);
Niels Möllerc936cb62019-03-19 14:10:16 +0100296 frame_type = encoded_info.speech ? AudioFrameType::kAudioFrameSpeech
297 : AudioFrameType::kAudioFrameCN;
kwibergc13ded52016-06-17 06:00:45 -0700298 }
299
300 {
301 rtc::CritScope lock(&callback_crit_sect_);
302 if (packetization_callback_) {
303 packetization_callback_->SendData(
304 frame_type, encoded_info.payload_type, encoded_info.encoded_timestamp,
Niels Möllerc35b6e62019-04-25 16:31:18 +0200305 encode_buffer_.data(), encode_buffer_.size());
kwibergc13ded52016-06-17 06:00:45 -0700306 }
307
308 if (vad_callback_) {
309 // Callback with VAD decision.
310 vad_callback_->InFrameType(frame_type);
311 }
312 }
313 previous_pltype_ = encoded_info.payload_type;
314 return static_cast<int32_t>(encode_buffer_.size());
315}
316
317/////////////////////////////////////////
318// Sender
319//
320
kwibergc13ded52016-06-17 06:00:45 -0700321void AudioCodingModuleImpl::ModifyEncoder(
kwiberg24c7c122016-09-28 11:57:10 -0700322 rtc::FunctionView<void(std::unique_ptr<AudioEncoder>*)> modifier) {
kwibergc13ded52016-06-17 06:00:45 -0700323 rtc::CritScope lock(&acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700324 modifier(&encoder_stack_);
325}
326
kwibergc13ded52016-06-17 06:00:45 -0700327// Register a transport callback which will be called to deliver
328// the encoded buffers.
329int AudioCodingModuleImpl::RegisterTransportCallback(
330 AudioPacketizationCallback* transport) {
331 rtc::CritScope lock(&callback_crit_sect_);
332 packetization_callback_ = transport;
333 return 0;
334}
335
336// Add 10MS of raw (PCM) audio data to the encoder.
337int AudioCodingModuleImpl::Add10MsData(const AudioFrame& audio_frame) {
kwibergc13ded52016-06-17 06:00:45 -0700338 rtc::CritScope lock(&acm_crit_sect_);
Per Åhgren4f2e9402019-10-04 11:06:15 +0200339 int r = Add10MsDataInternal(audio_frame, &input_data_);
340 return r < 0 ? r : Encode(input_data_);
kwibergc13ded52016-06-17 06:00:45 -0700341}
342
343int AudioCodingModuleImpl::Add10MsDataInternal(const AudioFrame& audio_frame,
344 InputData* input_data) {
345 if (audio_frame.samples_per_channel_ == 0) {
346 assert(false);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100347 RTC_LOG(LS_ERROR) << "Cannot Add 10 ms audio, payload length is zero";
kwibergc13ded52016-06-17 06:00:45 -0700348 return -1;
349 }
350
henrika33541572019-09-10 14:27:40 +0200351 if (audio_frame.sample_rate_hz_ > 192000) {
kwibergc13ded52016-06-17 06:00:45 -0700352 assert(false);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100353 RTC_LOG(LS_ERROR) << "Cannot Add 10 ms audio, input frequency not valid";
kwibergc13ded52016-06-17 06:00:45 -0700354 return -1;
355 }
356
357 // If the length and frequency matches. We currently just support raw PCM.
358 if (static_cast<size_t>(audio_frame.sample_rate_hz_ / 100) !=
359 audio_frame.samples_per_channel_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100360 RTC_LOG(LS_ERROR)
Alex Loiko300ec8c2017-05-30 17:23:28 +0200361 << "Cannot Add 10 ms audio, input frequency and length doesn't match";
kwibergc13ded52016-06-17 06:00:45 -0700362 return -1;
363 }
364
Alex Loiko65438812019-02-22 10:13:44 +0100365 if (audio_frame.num_channels_ != 1 && audio_frame.num_channels_ != 2 &&
366 audio_frame.num_channels_ != 4 && audio_frame.num_channels_ != 6 &&
367 audio_frame.num_channels_ != 8) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100368 RTC_LOG(LS_ERROR) << "Cannot Add 10 ms audio, invalid number of channels.";
kwibergc13ded52016-06-17 06:00:45 -0700369 return -1;
370 }
371
372 // Do we have a codec registered?
373 if (!HaveValidEncoder("Add10MsData")) {
374 return -1;
375 }
376
377 const AudioFrame* ptr_frame;
378 // Perform a resampling, also down-mix if it is required and can be
379 // performed before resampling (a down mix prior to resampling will take
380 // place if both primary and secondary encoders are mono and input is in
381 // stereo).
382 if (PreprocessToAddData(audio_frame, &ptr_frame) < 0) {
383 return -1;
384 }
385
386 // Check whether we need an up-mix or down-mix?
387 const size_t current_num_channels = encoder_stack_->NumChannels();
388 const bool same_num_channels =
389 ptr_frame->num_channels_ == current_num_channels;
390
yujo36b1a5f2017-06-12 12:45:32 -0700391 // TODO(yujo): Skip encode of muted frames.
kwibergc13ded52016-06-17 06:00:45 -0700392 input_data->input_timestamp = ptr_frame->timestamp_;
kwibergc13ded52016-06-17 06:00:45 -0700393 input_data->length_per_channel = ptr_frame->samples_per_channel_;
394 input_data->audio_channel = current_num_channels;
395
Per Åhgren4f2e9402019-10-04 11:06:15 +0200396 if (!same_num_channels) {
397 // Remixes the input frame to the output data and in the process resize the
398 // output data if needed.
Per Åhgren4dd56a32019-11-19 21:00:59 +0100399 ReMixFrame(*ptr_frame, current_num_channels, &input_data->buffer);
Per Åhgren4f2e9402019-10-04 11:06:15 +0200400
401 // For pushing data to primary, point the |ptr_audio| to correct buffer.
402 input_data->audio = input_data->buffer.data();
403 RTC_DCHECK_GE(input_data->buffer.size(),
404 input_data->length_per_channel * input_data->audio_channel);
405 } else {
406 // When adding data to encoders this pointer is pointing to an audio buffer
407 // with correct number of channels.
408 input_data->audio = ptr_frame->data();
409 }
410
kwibergc13ded52016-06-17 06:00:45 -0700411 return 0;
412}
413
414// Perform a resampling and down-mix if required. We down-mix only if
415// encoder is mono and input is stereo. In case of dual-streaming, both
416// encoders has to be mono for down-mix to take place.
417// |*ptr_out| will point to the pre-processed audio-frame. If no pre-processing
418// is required, |*ptr_out| points to |in_frame|.
yujo36b1a5f2017-06-12 12:45:32 -0700419// TODO(yujo): Make this more efficient for muted frames.
kwibergc13ded52016-06-17 06:00:45 -0700420int AudioCodingModuleImpl::PreprocessToAddData(const AudioFrame& in_frame,
421 const AudioFrame** ptr_out) {
422 const bool resample =
423 in_frame.sample_rate_hz_ != encoder_stack_->SampleRateHz();
424
425 // This variable is true if primary codec and secondary codec (if exists)
426 // are both mono and input is stereo.
427 // TODO(henrik.lundin): This condition should probably be
428 // in_frame.num_channels_ > encoder_stack_->NumChannels()
429 const bool down_mix =
430 in_frame.num_channels_ == 2 && encoder_stack_->NumChannels() == 1;
431
432 if (!first_10ms_data_) {
433 expected_in_ts_ = in_frame.timestamp_;
434 expected_codec_ts_ = in_frame.timestamp_;
435 first_10ms_data_ = true;
436 } else if (in_frame.timestamp_ != expected_in_ts_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100437 RTC_LOG(LS_WARNING) << "Unexpected input timestamp: " << in_frame.timestamp_
438 << ", expected: " << expected_in_ts_;
kwibergc13ded52016-06-17 06:00:45 -0700439 expected_codec_ts_ +=
440 (in_frame.timestamp_ - expected_in_ts_) *
441 static_cast<uint32_t>(
442 static_cast<double>(encoder_stack_->SampleRateHz()) /
443 static_cast<double>(in_frame.sample_rate_hz_));
444 expected_in_ts_ = in_frame.timestamp_;
445 }
446
kwibergc13ded52016-06-17 06:00:45 -0700447 if (!down_mix && !resample) {
448 // No pre-processing is required.
ossu63fb95a2016-07-06 09:34:22 -0700449 if (expected_in_ts_ == expected_codec_ts_) {
450 // If we've never resampled, we can use the input frame as-is
451 *ptr_out = &in_frame;
452 } else {
453 // Otherwise we'll need to alter the timestamp. Since in_frame is const,
454 // we'll have to make a copy of it.
455 preprocess_frame_.CopyFrom(in_frame);
456 preprocess_frame_.timestamp_ = expected_codec_ts_;
457 *ptr_out = &preprocess_frame_;
458 }
459
kwibergc13ded52016-06-17 06:00:45 -0700460 expected_in_ts_ += static_cast<uint32_t>(in_frame.samples_per_channel_);
461 expected_codec_ts_ += static_cast<uint32_t>(in_frame.samples_per_channel_);
kwibergc13ded52016-06-17 06:00:45 -0700462 return 0;
463 }
464
465 *ptr_out = &preprocess_frame_;
466 preprocess_frame_.num_channels_ = in_frame.num_channels_;
Per Åhgren4dd56a32019-11-19 21:00:59 +0100467 preprocess_frame_.samples_per_channel_ = in_frame.samples_per_channel_;
468 std::array<int16_t, WEBRTC_10MS_PCM_AUDIO> audio;
yujo36b1a5f2017-06-12 12:45:32 -0700469 const int16_t* src_ptr_audio = in_frame.data();
kwibergc13ded52016-06-17 06:00:45 -0700470 if (down_mix) {
471 // If a resampling is required the output of a down-mix is written into a
472 // local buffer, otherwise, it will be written to the output frame.
Yves Gerey665174f2018-06-19 15:03:05 +0200473 int16_t* dest_ptr_audio =
Per Åhgren4dd56a32019-11-19 21:00:59 +0100474 resample ? audio.data() : preprocess_frame_.mutable_data();
475 RTC_DCHECK_GE(audio.size(), in_frame.samples_per_channel_);
476 DownMixFrame(in_frame,
477 rtc::ArrayView<int16_t>(
478 dest_ptr_audio, preprocess_frame_.samples_per_channel_));
kwibergc13ded52016-06-17 06:00:45 -0700479 preprocess_frame_.num_channels_ = 1;
480 // Set the input of the resampler is the down-mixed signal.
Per Åhgren4dd56a32019-11-19 21:00:59 +0100481 src_ptr_audio = audio.data();
kwibergc13ded52016-06-17 06:00:45 -0700482 }
483
484 preprocess_frame_.timestamp_ = expected_codec_ts_;
kwibergc13ded52016-06-17 06:00:45 -0700485 preprocess_frame_.sample_rate_hz_ = in_frame.sample_rate_hz_;
486 // If it is required, we have to do a resampling.
487 if (resample) {
488 // The result of the resampler is written to output frame.
yujo36b1a5f2017-06-12 12:45:32 -0700489 int16_t* dest_ptr_audio = preprocess_frame_.mutable_data();
kwibergc13ded52016-06-17 06:00:45 -0700490
491 int samples_per_channel = resampler_.Resample10Msec(
492 src_ptr_audio, in_frame.sample_rate_hz_, encoder_stack_->SampleRateHz(),
493 preprocess_frame_.num_channels_, AudioFrame::kMaxDataSizeSamples,
494 dest_ptr_audio);
495
496 if (samples_per_channel < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100497 RTC_LOG(LS_ERROR) << "Cannot add 10 ms audio, resampling failed";
kwibergc13ded52016-06-17 06:00:45 -0700498 return -1;
499 }
500 preprocess_frame_.samples_per_channel_ =
501 static_cast<size_t>(samples_per_channel);
502 preprocess_frame_.sample_rate_hz_ = encoder_stack_->SampleRateHz();
503 }
504
505 expected_codec_ts_ +=
506 static_cast<uint32_t>(preprocess_frame_.samples_per_channel_);
507 expected_in_ts_ += static_cast<uint32_t>(in_frame.samples_per_channel_);
508
509 return 0;
510}
511
512/////////////////////////////////////////
kwibergc13ded52016-06-17 06:00:45 -0700513// (FEC) Forward Error Correction (codec internal)
514//
515
kwibergc13ded52016-06-17 06:00:45 -0700516int AudioCodingModuleImpl::SetPacketLossRate(int loss_rate) {
517 rtc::CritScope lock(&acm_crit_sect_);
518 if (HaveValidEncoder("SetPacketLossRate")) {
minyue4b9a2cb2016-11-30 06:49:59 -0800519 encoder_stack_->OnReceivedUplinkPacketLossFraction(loss_rate / 100.0);
kwibergc13ded52016-06-17 06:00:45 -0700520 }
521 return 0;
522}
523
524/////////////////////////////////////////
kwibergc13ded52016-06-17 06:00:45 -0700525// Receiver
526//
527
528int AudioCodingModuleImpl::InitializeReceiver() {
529 rtc::CritScope lock(&acm_crit_sect_);
530 return InitializeReceiverSafe();
531}
532
533// Initialize receiver, resets codec database etc.
534int AudioCodingModuleImpl::InitializeReceiverSafe() {
535 // If the receiver is already initialized then we want to destroy any
536 // existing decoders. After a call to this function, we should have a clean
537 // start-up.
kwiberg6b19b562016-09-20 04:02:25 -0700538 if (receiver_initialized_)
539 receiver_.RemoveAllCodecs();
kwibergc13ded52016-06-17 06:00:45 -0700540 receiver_.FlushBuffers();
541
kwibergc13ded52016-06-17 06:00:45 -0700542 receiver_initialized_ = true;
543 return 0;
544}
545
kwiberg1c07c702017-03-27 07:15:49 -0700546void AudioCodingModuleImpl::SetReceiveCodecs(
547 const std::map<int, SdpAudioFormat>& codecs) {
548 rtc::CritScope lock(&acm_crit_sect_);
549 receiver_.SetCodecs(codecs);
550}
551
kwibergc13ded52016-06-17 06:00:45 -0700552// Incoming packet from network parsed and ready for decode.
553int AudioCodingModuleImpl::IncomingPacket(const uint8_t* incoming_payload,
554 const size_t payload_length,
Niels Möllerafb5dbb2019-02-15 15:21:47 +0100555 const RTPHeader& rtp_header) {
henrik.lundinb8c55b12017-05-10 07:38:01 -0700556 RTC_DCHECK_EQ(payload_length == 0, incoming_payload == nullptr);
kwibergc13ded52016-06-17 06:00:45 -0700557 return receiver_.InsertPacket(
558 rtp_header,
559 rtc::ArrayView<const uint8_t>(incoming_payload, payload_length));
560}
561
kwibergc13ded52016-06-17 06:00:45 -0700562// Get 10 milliseconds of raw audio data to play out.
563// Automatic resample to the requested frequency.
564int AudioCodingModuleImpl::PlayoutData10Ms(int desired_freq_hz,
565 AudioFrame* audio_frame,
566 bool* muted) {
567 // GetAudio always returns 10 ms, at the requested sample rate.
568 if (receiver_.GetAudio(desired_freq_hz, audio_frame, muted) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100569 RTC_LOG(LS_ERROR) << "PlayoutData failed, RecOut Failed";
kwibergc13ded52016-06-17 06:00:45 -0700570 return -1;
571 }
kwibergc13ded52016-06-17 06:00:45 -0700572 return 0;
573}
574
kwibergc13ded52016-06-17 06:00:45 -0700575/////////////////////////////////////////
576// Statistics
577//
578
579// TODO(turajs) change the return value to void. Also change the corresponding
580// NetEq function.
581int AudioCodingModuleImpl::GetNetworkStatistics(NetworkStatistics* statistics) {
582 receiver_.GetNetworkStatistics(statistics);
583 return 0;
584}
585
586int AudioCodingModuleImpl::RegisterVADCallback(ACMVADCallback* vad_callback) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100587 RTC_LOG(LS_VERBOSE) << "RegisterVADCallback()";
kwibergc13ded52016-06-17 06:00:45 -0700588 rtc::CritScope lock(&callback_crit_sect_);
589 vad_callback_ = vad_callback;
590 return 0;
591}
592
kwibergc13ded52016-06-17 06:00:45 -0700593bool AudioCodingModuleImpl::HaveValidEncoder(const char* caller_name) const {
594 if (!encoder_stack_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100595 RTC_LOG(LS_ERROR) << caller_name << " failed: No send codec is registered.";
kwibergc13ded52016-06-17 06:00:45 -0700596 return false;
597 }
598 return true;
599}
600
ivoce1198e02017-09-08 08:13:19 -0700601ANAStats AudioCodingModuleImpl::GetANAStats() const {
602 rtc::CritScope lock(&acm_crit_sect_);
603 if (encoder_stack_)
604 return encoder_stack_->GetANAStats();
605 // If no encoder is set, return default stats.
606 return ANAStats();
607}
608
kwibergc13ded52016-06-17 06:00:45 -0700609} // namespace
610
Karl Wiberg5817d3d2018-04-06 10:06:42 +0200611AudioCodingModule::Config::Config(
612 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory)
613 : neteq_config(),
614 clock(Clock::GetRealTimeClock()),
615 decoder_factory(decoder_factory) {
kwiberg36a43882016-08-29 05:33:32 -0700616 // Post-decode VAD is disabled by default in NetEq, however, Audio
617 // Conference Mixer relies on VAD decisions and fails without them.
618 neteq_config.enable_post_decode_vad = true;
619}
620
621AudioCodingModule::Config::Config(const Config&) = default;
622AudioCodingModule::Config::~Config() = default;
623
Henrik Lundin64dad832015-05-11 12:44:23 +0200624AudioCodingModule* AudioCodingModule::Create(const Config& config) {
kwibergc13ded52016-06-17 06:00:45 -0700625 return new AudioCodingModuleImpl(config);
turaj@webrtc.org7959e162013-09-12 18:30:26 +0000626}
627
turaj@webrtc.org7959e162013-09-12 18:30:26 +0000628} // namespace webrtc