blob: f3dd5b1a1f2ef09ae0f3bc26037edad116006bad [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"
Per Åhgren4dd56a32019-11-19 21:00:59 +010020#include "modules/audio_coding/acm2/acm_remixing.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020021#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
Per Åhgren4f2e9402019-10-04 11:06:15 +020036// Initial size for the buffer in InputBuffer. This matches 6 channels of 10 ms
37// 48 kHz data.
38constexpr size_t kInitialInputDataBufferSize = 6 * 480;
39
kwibergc13ded52016-06-17 06:00:45 -070040class AudioCodingModuleImpl final : public AudioCodingModule {
41 public:
42 explicit AudioCodingModuleImpl(const AudioCodingModule::Config& config);
43 ~AudioCodingModuleImpl() override;
44
45 /////////////////////////////////////////
46 // Sender
47 //
48
kwiberg24c7c122016-09-28 11:57:10 -070049 void ModifyEncoder(rtc::FunctionView<void(std::unique_ptr<AudioEncoder>*)>
50 modifier) override;
kwibergc13ded52016-06-17 06:00:45 -070051
kwibergc13ded52016-06-17 06:00:45 -070052 // Register a transport callback which will be
53 // called to deliver the encoded buffers.
54 int RegisterTransportCallback(AudioPacketizationCallback* transport) override;
55
56 // Add 10 ms of raw (PCM) audio data to the encoder.
57 int Add10MsData(const AudioFrame& audio_frame) override;
58
59 /////////////////////////////////////////
kwibergc13ded52016-06-17 06:00:45 -070060 // (FEC) Forward Error Correction (codec internal)
61 //
62
kwibergc13ded52016-06-17 06:00:45 -070063 // Set target packet loss rate
64 int SetPacketLossRate(int loss_rate) override;
65
66 /////////////////////////////////////////
67 // (VAD) Voice Activity Detection
68 // and
69 // (CNG) Comfort Noise Generation
70 //
71
kwibergc13ded52016-06-17 06:00:45 -070072 int RegisterVADCallback(ACMVADCallback* vad_callback) override;
73
74 /////////////////////////////////////////
75 // Receiver
76 //
77
78 // Initialize receiver, resets codec database etc.
79 int InitializeReceiver() override;
80
kwiberg1c07c702017-03-27 07:15:49 -070081 void SetReceiveCodecs(const std::map<int, SdpAudioFormat>& codecs) override;
82
kwibergc13ded52016-06-17 06:00:45 -070083 // Incoming packet from network parsed and ready for decode.
84 int IncomingPacket(const uint8_t* incoming_payload,
85 const size_t payload_length,
Niels Möllerafb5dbb2019-02-15 15:21:47 +010086 const RTPHeader& rtp_info) override;
kwibergc13ded52016-06-17 06:00:45 -070087
kwibergc13ded52016-06-17 06:00:45 -070088 // Get 10 milliseconds of raw audio data to play out, and
89 // automatic resample to the requested frequency if > 0.
90 int PlayoutData10Ms(int desired_freq_hz,
91 AudioFrame* audio_frame,
92 bool* muted) override;
kwibergc13ded52016-06-17 06:00:45 -070093
94 /////////////////////////////////////////
95 // Statistics
96 //
97
98 int GetNetworkStatistics(NetworkStatistics* statistics) override;
99
ivoce1198e02017-09-08 08:13:19 -0700100 ANAStats GetANAStats() const override;
101
kwibergc13ded52016-06-17 06:00:45 -0700102 private:
103 struct InputData {
Per Åhgren4f2e9402019-10-04 11:06:15 +0200104 InputData() : buffer(kInitialInputDataBufferSize) {}
kwibergc13ded52016-06-17 06:00:45 -0700105 uint32_t input_timestamp;
106 const int16_t* audio;
107 size_t length_per_channel;
108 size_t audio_channel;
109 // If a re-mix is required (up or down), this buffer will store a re-mixed
110 // version of the input.
Per Åhgren4f2e9402019-10-04 11:06:15 +0200111 std::vector<int16_t> buffer;
Minyue Li48655cf2020-01-23 13:45:50 +0100112 int64_t absolute_capture_timestamp_ms;
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()}));
Minyue Li48655cf2020-01-23 13:45:50 +0100256
kwibergc13ded52016-06-17 06:00:45 -0700257 last_timestamp_ = input_data.input_timestamp;
258 last_rtp_timestamp_ = rtp_timestamp;
259 first_frame_ = false;
260
261 // Clear the buffer before reuse - encoded data will get appended.
262 encode_buffer_.Clear();
263 encoded_info = encoder_stack_->Encode(
Yves Gerey665174f2018-06-19 15:03:05 +0200264 rtp_timestamp,
265 rtc::ArrayView<const int16_t>(
266 input_data.audio,
267 input_data.audio_channel * input_data.length_per_channel),
kwibergc13ded52016-06-17 06:00:45 -0700268 &encode_buffer_);
269
270 bitrate_logger_.MaybeLog(encoder_stack_->GetTargetBitrate() / 1000);
271 if (encode_buffer_.size() == 0 && !encoded_info.send_even_if_empty) {
272 // Not enough data.
273 return 0;
274 }
275 previous_pltype = previous_pltype_; // Read it while we have the critsect.
276
277 // Log codec type to histogram once every 500 packets.
278 if (encoded_info.encoded_bytes == 0) {
279 ++number_of_consecutive_empty_packets_;
280 } else {
281 size_t codec_type = static_cast<size_t>(encoded_info.encoder_type);
282 codec_histogram_bins_log_[codec_type] +=
283 number_of_consecutive_empty_packets_ + 1;
284 number_of_consecutive_empty_packets_ = 0;
285 if (codec_histogram_bins_log_[codec_type] >= 500) {
286 codec_histogram_bins_log_[codec_type] -= 500;
287 UpdateCodecTypeHistogram(codec_type);
288 }
289 }
290
Niels Möller87e2d782019-03-07 10:18:23 +0100291 AudioFrameType frame_type;
kwibergc13ded52016-06-17 06:00:45 -0700292 if (encode_buffer_.size() == 0 && encoded_info.send_even_if_empty) {
Niels Möllerc936cb62019-03-19 14:10:16 +0100293 frame_type = AudioFrameType::kEmptyFrame;
kwibergc13ded52016-06-17 06:00:45 -0700294 encoded_info.payload_type = previous_pltype;
295 } else {
kwibergaf476c72016-11-28 15:21:39 -0800296 RTC_DCHECK_GT(encode_buffer_.size(), 0);
Niels Möllerc936cb62019-03-19 14:10:16 +0100297 frame_type = encoded_info.speech ? AudioFrameType::kAudioFrameSpeech
298 : AudioFrameType::kAudioFrameCN;
kwibergc13ded52016-06-17 06:00:45 -0700299 }
300
301 {
302 rtc::CritScope lock(&callback_crit_sect_);
303 if (packetization_callback_) {
304 packetization_callback_->SendData(
305 frame_type, encoded_info.payload_type, encoded_info.encoded_timestamp,
Minyue Li48655cf2020-01-23 13:45:50 +0100306 encode_buffer_.data(), encode_buffer_.size(),
307 input_data.absolute_capture_timestamp_ms);
kwibergc13ded52016-06-17 06:00:45 -0700308 }
309
310 if (vad_callback_) {
311 // Callback with VAD decision.
312 vad_callback_->InFrameType(frame_type);
313 }
314 }
315 previous_pltype_ = encoded_info.payload_type;
316 return static_cast<int32_t>(encode_buffer_.size());
317}
318
319/////////////////////////////////////////
320// Sender
321//
322
kwibergc13ded52016-06-17 06:00:45 -0700323void AudioCodingModuleImpl::ModifyEncoder(
kwiberg24c7c122016-09-28 11:57:10 -0700324 rtc::FunctionView<void(std::unique_ptr<AudioEncoder>*)> modifier) {
kwibergc13ded52016-06-17 06:00:45 -0700325 rtc::CritScope lock(&acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700326 modifier(&encoder_stack_);
327}
328
kwibergc13ded52016-06-17 06:00:45 -0700329// Register a transport callback which will be called to deliver
330// the encoded buffers.
331int AudioCodingModuleImpl::RegisterTransportCallback(
332 AudioPacketizationCallback* transport) {
333 rtc::CritScope lock(&callback_crit_sect_);
334 packetization_callback_ = transport;
335 return 0;
336}
337
338// Add 10MS of raw (PCM) audio data to the encoder.
339int AudioCodingModuleImpl::Add10MsData(const AudioFrame& audio_frame) {
kwibergc13ded52016-06-17 06:00:45 -0700340 rtc::CritScope lock(&acm_crit_sect_);
Per Åhgren4f2e9402019-10-04 11:06:15 +0200341 int r = Add10MsDataInternal(audio_frame, &input_data_);
342 return r < 0 ? r : Encode(input_data_);
kwibergc13ded52016-06-17 06:00:45 -0700343}
344
345int AudioCodingModuleImpl::Add10MsDataInternal(const AudioFrame& audio_frame,
346 InputData* input_data) {
347 if (audio_frame.samples_per_channel_ == 0) {
348 assert(false);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100349 RTC_LOG(LS_ERROR) << "Cannot Add 10 ms audio, payload length is zero";
kwibergc13ded52016-06-17 06:00:45 -0700350 return -1;
351 }
352
henrika33541572019-09-10 14:27:40 +0200353 if (audio_frame.sample_rate_hz_ > 192000) {
kwibergc13ded52016-06-17 06:00:45 -0700354 assert(false);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100355 RTC_LOG(LS_ERROR) << "Cannot Add 10 ms audio, input frequency not valid";
kwibergc13ded52016-06-17 06:00:45 -0700356 return -1;
357 }
358
359 // If the length and frequency matches. We currently just support raw PCM.
360 if (static_cast<size_t>(audio_frame.sample_rate_hz_ / 100) !=
361 audio_frame.samples_per_channel_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100362 RTC_LOG(LS_ERROR)
Alex Loiko300ec8c2017-05-30 17:23:28 +0200363 << "Cannot Add 10 ms audio, input frequency and length doesn't match";
kwibergc13ded52016-06-17 06:00:45 -0700364 return -1;
365 }
366
Alex Loiko65438812019-02-22 10:13:44 +0100367 if (audio_frame.num_channels_ != 1 && audio_frame.num_channels_ != 2 &&
368 audio_frame.num_channels_ != 4 && audio_frame.num_channels_ != 6 &&
369 audio_frame.num_channels_ != 8) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100370 RTC_LOG(LS_ERROR) << "Cannot Add 10 ms audio, invalid number of channels.";
kwibergc13ded52016-06-17 06:00:45 -0700371 return -1;
372 }
373
374 // Do we have a codec registered?
375 if (!HaveValidEncoder("Add10MsData")) {
376 return -1;
377 }
378
379 const AudioFrame* ptr_frame;
380 // Perform a resampling, also down-mix if it is required and can be
381 // performed before resampling (a down mix prior to resampling will take
382 // place if both primary and secondary encoders are mono and input is in
383 // stereo).
384 if (PreprocessToAddData(audio_frame, &ptr_frame) < 0) {
385 return -1;
386 }
387
388 // Check whether we need an up-mix or down-mix?
389 const size_t current_num_channels = encoder_stack_->NumChannels();
390 const bool same_num_channels =
391 ptr_frame->num_channels_ == current_num_channels;
392
yujo36b1a5f2017-06-12 12:45:32 -0700393 // TODO(yujo): Skip encode of muted frames.
kwibergc13ded52016-06-17 06:00:45 -0700394 input_data->input_timestamp = ptr_frame->timestamp_;
kwibergc13ded52016-06-17 06:00:45 -0700395 input_data->length_per_channel = ptr_frame->samples_per_channel_;
396 input_data->audio_channel = current_num_channels;
Minyue Li48655cf2020-01-23 13:45:50 +0100397 // TODO(bugs.webrtc.org/10739): Assign from a corresponding field in
398 // audio_frame when it is added in AudioFrame.
399 input_data->absolute_capture_timestamp_ms = 0;
kwibergc13ded52016-06-17 06:00:45 -0700400
Per Åhgren4f2e9402019-10-04 11:06:15 +0200401 if (!same_num_channels) {
402 // Remixes the input frame to the output data and in the process resize the
403 // output data if needed.
Per Åhgren4dd56a32019-11-19 21:00:59 +0100404 ReMixFrame(*ptr_frame, current_num_channels, &input_data->buffer);
Per Åhgren4f2e9402019-10-04 11:06:15 +0200405
406 // For pushing data to primary, point the |ptr_audio| to correct buffer.
407 input_data->audio = input_data->buffer.data();
408 RTC_DCHECK_GE(input_data->buffer.size(),
409 input_data->length_per_channel * input_data->audio_channel);
410 } else {
411 // When adding data to encoders this pointer is pointing to an audio buffer
412 // with correct number of channels.
413 input_data->audio = ptr_frame->data();
414 }
415
kwibergc13ded52016-06-17 06:00:45 -0700416 return 0;
417}
418
419// Perform a resampling and down-mix if required. We down-mix only if
420// encoder is mono and input is stereo. In case of dual-streaming, both
421// encoders has to be mono for down-mix to take place.
422// |*ptr_out| will point to the pre-processed audio-frame. If no pre-processing
423// is required, |*ptr_out| points to |in_frame|.
yujo36b1a5f2017-06-12 12:45:32 -0700424// TODO(yujo): Make this more efficient for muted frames.
kwibergc13ded52016-06-17 06:00:45 -0700425int AudioCodingModuleImpl::PreprocessToAddData(const AudioFrame& in_frame,
426 const AudioFrame** ptr_out) {
427 const bool resample =
428 in_frame.sample_rate_hz_ != encoder_stack_->SampleRateHz();
429
430 // This variable is true if primary codec and secondary codec (if exists)
431 // are both mono and input is stereo.
432 // TODO(henrik.lundin): This condition should probably be
433 // in_frame.num_channels_ > encoder_stack_->NumChannels()
434 const bool down_mix =
435 in_frame.num_channels_ == 2 && encoder_stack_->NumChannels() == 1;
436
437 if (!first_10ms_data_) {
438 expected_in_ts_ = in_frame.timestamp_;
439 expected_codec_ts_ = in_frame.timestamp_;
440 first_10ms_data_ = true;
441 } else if (in_frame.timestamp_ != expected_in_ts_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100442 RTC_LOG(LS_WARNING) << "Unexpected input timestamp: " << in_frame.timestamp_
443 << ", expected: " << expected_in_ts_;
kwibergc13ded52016-06-17 06:00:45 -0700444 expected_codec_ts_ +=
445 (in_frame.timestamp_ - expected_in_ts_) *
446 static_cast<uint32_t>(
447 static_cast<double>(encoder_stack_->SampleRateHz()) /
448 static_cast<double>(in_frame.sample_rate_hz_));
449 expected_in_ts_ = in_frame.timestamp_;
450 }
451
kwibergc13ded52016-06-17 06:00:45 -0700452 if (!down_mix && !resample) {
453 // No pre-processing is required.
ossu63fb95a2016-07-06 09:34:22 -0700454 if (expected_in_ts_ == expected_codec_ts_) {
455 // If we've never resampled, we can use the input frame as-is
456 *ptr_out = &in_frame;
457 } else {
458 // Otherwise we'll need to alter the timestamp. Since in_frame is const,
459 // we'll have to make a copy of it.
460 preprocess_frame_.CopyFrom(in_frame);
461 preprocess_frame_.timestamp_ = expected_codec_ts_;
462 *ptr_out = &preprocess_frame_;
463 }
464
kwibergc13ded52016-06-17 06:00:45 -0700465 expected_in_ts_ += static_cast<uint32_t>(in_frame.samples_per_channel_);
466 expected_codec_ts_ += static_cast<uint32_t>(in_frame.samples_per_channel_);
kwibergc13ded52016-06-17 06:00:45 -0700467 return 0;
468 }
469
470 *ptr_out = &preprocess_frame_;
471 preprocess_frame_.num_channels_ = in_frame.num_channels_;
Per Åhgren4dd56a32019-11-19 21:00:59 +0100472 preprocess_frame_.samples_per_channel_ = in_frame.samples_per_channel_;
473 std::array<int16_t, WEBRTC_10MS_PCM_AUDIO> audio;
yujo36b1a5f2017-06-12 12:45:32 -0700474 const int16_t* src_ptr_audio = in_frame.data();
kwibergc13ded52016-06-17 06:00:45 -0700475 if (down_mix) {
476 // If a resampling is required the output of a down-mix is written into a
477 // local buffer, otherwise, it will be written to the output frame.
Yves Gerey665174f2018-06-19 15:03:05 +0200478 int16_t* dest_ptr_audio =
Per Åhgren4dd56a32019-11-19 21:00:59 +0100479 resample ? audio.data() : preprocess_frame_.mutable_data();
480 RTC_DCHECK_GE(audio.size(), in_frame.samples_per_channel_);
481 DownMixFrame(in_frame,
482 rtc::ArrayView<int16_t>(
483 dest_ptr_audio, preprocess_frame_.samples_per_channel_));
kwibergc13ded52016-06-17 06:00:45 -0700484 preprocess_frame_.num_channels_ = 1;
485 // Set the input of the resampler is the down-mixed signal.
Per Åhgren4dd56a32019-11-19 21:00:59 +0100486 src_ptr_audio = audio.data();
kwibergc13ded52016-06-17 06:00:45 -0700487 }
488
489 preprocess_frame_.timestamp_ = expected_codec_ts_;
kwibergc13ded52016-06-17 06:00:45 -0700490 preprocess_frame_.sample_rate_hz_ = in_frame.sample_rate_hz_;
491 // If it is required, we have to do a resampling.
492 if (resample) {
493 // The result of the resampler is written to output frame.
yujo36b1a5f2017-06-12 12:45:32 -0700494 int16_t* dest_ptr_audio = preprocess_frame_.mutable_data();
kwibergc13ded52016-06-17 06:00:45 -0700495
496 int samples_per_channel = resampler_.Resample10Msec(
497 src_ptr_audio, in_frame.sample_rate_hz_, encoder_stack_->SampleRateHz(),
498 preprocess_frame_.num_channels_, AudioFrame::kMaxDataSizeSamples,
499 dest_ptr_audio);
500
501 if (samples_per_channel < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100502 RTC_LOG(LS_ERROR) << "Cannot add 10 ms audio, resampling failed";
kwibergc13ded52016-06-17 06:00:45 -0700503 return -1;
504 }
505 preprocess_frame_.samples_per_channel_ =
506 static_cast<size_t>(samples_per_channel);
507 preprocess_frame_.sample_rate_hz_ = encoder_stack_->SampleRateHz();
508 }
509
510 expected_codec_ts_ +=
511 static_cast<uint32_t>(preprocess_frame_.samples_per_channel_);
512 expected_in_ts_ += static_cast<uint32_t>(in_frame.samples_per_channel_);
513
514 return 0;
515}
516
517/////////////////////////////////////////
kwibergc13ded52016-06-17 06:00:45 -0700518// (FEC) Forward Error Correction (codec internal)
519//
520
kwibergc13ded52016-06-17 06:00:45 -0700521int AudioCodingModuleImpl::SetPacketLossRate(int loss_rate) {
522 rtc::CritScope lock(&acm_crit_sect_);
523 if (HaveValidEncoder("SetPacketLossRate")) {
minyue4b9a2cb2016-11-30 06:49:59 -0800524 encoder_stack_->OnReceivedUplinkPacketLossFraction(loss_rate / 100.0);
kwibergc13ded52016-06-17 06:00:45 -0700525 }
526 return 0;
527}
528
529/////////////////////////////////////////
kwibergc13ded52016-06-17 06:00:45 -0700530// Receiver
531//
532
533int AudioCodingModuleImpl::InitializeReceiver() {
534 rtc::CritScope lock(&acm_crit_sect_);
535 return InitializeReceiverSafe();
536}
537
538// Initialize receiver, resets codec database etc.
539int AudioCodingModuleImpl::InitializeReceiverSafe() {
540 // If the receiver is already initialized then we want to destroy any
541 // existing decoders. After a call to this function, we should have a clean
542 // start-up.
kwiberg6b19b562016-09-20 04:02:25 -0700543 if (receiver_initialized_)
544 receiver_.RemoveAllCodecs();
kwibergc13ded52016-06-17 06:00:45 -0700545 receiver_.FlushBuffers();
546
kwibergc13ded52016-06-17 06:00:45 -0700547 receiver_initialized_ = true;
548 return 0;
549}
550
kwiberg1c07c702017-03-27 07:15:49 -0700551void AudioCodingModuleImpl::SetReceiveCodecs(
552 const std::map<int, SdpAudioFormat>& codecs) {
553 rtc::CritScope lock(&acm_crit_sect_);
554 receiver_.SetCodecs(codecs);
555}
556
kwibergc13ded52016-06-17 06:00:45 -0700557// Incoming packet from network parsed and ready for decode.
558int AudioCodingModuleImpl::IncomingPacket(const uint8_t* incoming_payload,
559 const size_t payload_length,
Niels Möllerafb5dbb2019-02-15 15:21:47 +0100560 const RTPHeader& rtp_header) {
henrik.lundinb8c55b12017-05-10 07:38:01 -0700561 RTC_DCHECK_EQ(payload_length == 0, incoming_payload == nullptr);
kwibergc13ded52016-06-17 06:00:45 -0700562 return receiver_.InsertPacket(
563 rtp_header,
564 rtc::ArrayView<const uint8_t>(incoming_payload, payload_length));
565}
566
kwibergc13ded52016-06-17 06:00:45 -0700567// Get 10 milliseconds of raw audio data to play out.
568// Automatic resample to the requested frequency.
569int AudioCodingModuleImpl::PlayoutData10Ms(int desired_freq_hz,
570 AudioFrame* audio_frame,
571 bool* muted) {
572 // GetAudio always returns 10 ms, at the requested sample rate.
573 if (receiver_.GetAudio(desired_freq_hz, audio_frame, muted) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100574 RTC_LOG(LS_ERROR) << "PlayoutData failed, RecOut Failed";
kwibergc13ded52016-06-17 06:00:45 -0700575 return -1;
576 }
kwibergc13ded52016-06-17 06:00:45 -0700577 return 0;
578}
579
kwibergc13ded52016-06-17 06:00:45 -0700580/////////////////////////////////////////
581// Statistics
582//
583
584// TODO(turajs) change the return value to void. Also change the corresponding
585// NetEq function.
586int AudioCodingModuleImpl::GetNetworkStatistics(NetworkStatistics* statistics) {
587 receiver_.GetNetworkStatistics(statistics);
588 return 0;
589}
590
591int AudioCodingModuleImpl::RegisterVADCallback(ACMVADCallback* vad_callback) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100592 RTC_LOG(LS_VERBOSE) << "RegisterVADCallback()";
kwibergc13ded52016-06-17 06:00:45 -0700593 rtc::CritScope lock(&callback_crit_sect_);
594 vad_callback_ = vad_callback;
595 return 0;
596}
597
kwibergc13ded52016-06-17 06:00:45 -0700598bool AudioCodingModuleImpl::HaveValidEncoder(const char* caller_name) const {
599 if (!encoder_stack_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100600 RTC_LOG(LS_ERROR) << caller_name << " failed: No send codec is registered.";
kwibergc13ded52016-06-17 06:00:45 -0700601 return false;
602 }
603 return true;
604}
605
ivoce1198e02017-09-08 08:13:19 -0700606ANAStats AudioCodingModuleImpl::GetANAStats() const {
607 rtc::CritScope lock(&acm_crit_sect_);
608 if (encoder_stack_)
609 return encoder_stack_->GetANAStats();
610 // If no encoder is set, return default stats.
611 return ANAStats();
612}
613
kwibergc13ded52016-06-17 06:00:45 -0700614} // namespace
615
Karl Wiberg5817d3d2018-04-06 10:06:42 +0200616AudioCodingModule::Config::Config(
617 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory)
618 : neteq_config(),
619 clock(Clock::GetRealTimeClock()),
620 decoder_factory(decoder_factory) {
kwiberg36a43882016-08-29 05:33:32 -0700621 // Post-decode VAD is disabled by default in NetEq, however, Audio
622 // Conference Mixer relies on VAD decisions and fails without them.
623 neteq_config.enable_post_decode_vad = true;
624}
625
626AudioCodingModule::Config::Config(const Config&) = default;
627AudioCodingModule::Config::~Config() = default;
628
Henrik Lundin64dad832015-05-11 12:44:23 +0200629AudioCodingModule* AudioCodingModule::Create(const Config& config) {
kwibergc13ded52016-06-17 06:00:45 -0700630 return new AudioCodingModuleImpl(config);
turaj@webrtc.org7959e162013-09-12 18:30:26 +0000631}
632
turaj@webrtc.org7959e162013-09-12 18:30:26 +0000633} // namespace webrtc