blob: efef3c090d24f12bf7fe45f6256c079c3989aff9 [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
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;
kwibergc13ded52016-06-17 06:00:45 -0700112 };
113
Per Åhgren4f2e9402019-10-04 11:06:15 +0200114 InputData input_data_ RTC_GUARDED_BY(acm_crit_sect_);
115
kwibergc13ded52016-06-17 06:00:45 -0700116 // This member class writes values to the named UMA histogram, but only if
117 // the value has changed since the last time (and always for the first call).
118 class ChangeLogger {
119 public:
120 explicit ChangeLogger(const std::string& histogram_name)
121 : histogram_name_(histogram_name) {}
122 // Logs the new value if it is different from the last logged value, or if
123 // this is the first call.
124 void MaybeLog(int value);
125
126 private:
127 int last_value_ = 0;
128 int first_time_ = true;
129 const std::string histogram_name_;
130 };
131
kwibergc13ded52016-06-17 06:00:45 -0700132 int Add10MsDataInternal(const AudioFrame& audio_frame, InputData* input_data)
danilchap56359be2017-09-07 07:53:45 -0700133 RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700134 int Encode(const InputData& input_data)
danilchap56359be2017-09-07 07:53:45 -0700135 RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700136
danilchap56359be2017-09-07 07:53:45 -0700137 int InitializeReceiverSafe() RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700138
139 bool HaveValidEncoder(const char* caller_name) const
danilchap56359be2017-09-07 07:53:45 -0700140 RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700141
142 // Preprocessing of input audio, including resampling and down-mixing if
143 // required, before pushing audio into encoder's buffer.
144 //
145 // in_frame: input audio-frame
146 // ptr_out: pointer to output audio_frame. If no preprocessing is required
147 // |ptr_out| will be pointing to |in_frame|, otherwise pointing to
148 // |preprocess_frame_|.
149 //
150 // Return value:
151 // -1: if encountering an error.
152 // 0: otherwise.
153 int PreprocessToAddData(const AudioFrame& in_frame,
154 const AudioFrame** ptr_out)
danilchap56359be2017-09-07 07:53:45 -0700155 RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700156
157 // Change required states after starting to receive the codec corresponding
158 // to |index|.
159 int UpdateUponReceivingCodec(int index);
160
161 rtc::CriticalSection acm_crit_sect_;
danilchap56359be2017-09-07 07:53:45 -0700162 rtc::Buffer encode_buffer_ RTC_GUARDED_BY(acm_crit_sect_);
danilchap56359be2017-09-07 07:53:45 -0700163 uint32_t expected_codec_ts_ RTC_GUARDED_BY(acm_crit_sect_);
164 uint32_t expected_in_ts_ RTC_GUARDED_BY(acm_crit_sect_);
165 acm2::ACMResampler resampler_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700166 acm2::AcmReceiver receiver_; // AcmReceiver has it's own internal lock.
danilchap56359be2017-09-07 07:53:45 -0700167 ChangeLogger bitrate_logger_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700168
Karl Wiberg49c33ce2018-11-12 14:21:58 +0100169 // Current encoder stack, provided by a call to RegisterEncoder.
danilchap56359be2017-09-07 07:53:45 -0700170 std::unique_ptr<AudioEncoder> encoder_stack_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700171
kwibergc13ded52016-06-17 06:00:45 -0700172 // This is to keep track of CN instances where we can send DTMFs.
danilchap56359be2017-09-07 07:53:45 -0700173 uint8_t previous_pltype_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700174
danilchap56359be2017-09-07 07:53:45 -0700175 bool receiver_initialized_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700176
danilchap56359be2017-09-07 07:53:45 -0700177 AudioFrame preprocess_frame_ RTC_GUARDED_BY(acm_crit_sect_);
178 bool first_10ms_data_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700179
danilchap56359be2017-09-07 07:53:45 -0700180 bool first_frame_ RTC_GUARDED_BY(acm_crit_sect_);
181 uint32_t last_timestamp_ RTC_GUARDED_BY(acm_crit_sect_);
182 uint32_t last_rtp_timestamp_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700183
184 rtc::CriticalSection callback_crit_sect_;
185 AudioPacketizationCallback* packetization_callback_
danilchap56359be2017-09-07 07:53:45 -0700186 RTC_GUARDED_BY(callback_crit_sect_);
187 ACMVADCallback* vad_callback_ RTC_GUARDED_BY(callback_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700188
189 int codec_histogram_bins_log_[static_cast<size_t>(
190 AudioEncoder::CodecType::kMaxLoggedAudioCodecTypes)];
191 int number_of_consecutive_empty_packets_;
192};
193
194// Adds a codec usage sample to the histogram.
195void UpdateCodecTypeHistogram(size_t codec_type) {
196 RTC_HISTOGRAM_ENUMERATION(
197 "WebRTC.Audio.Encoder.CodecType", static_cast<int>(codec_type),
198 static_cast<int>(
199 webrtc::AudioEncoder::CodecType::kMaxLoggedAudioCodecTypes));
200}
201
kwibergc13ded52016-06-17 06:00:45 -0700202// Stereo-to-mono can be used as in-place.
Per Åhgren4f2e9402019-10-04 11:06:15 +0200203void DownMix(const AudioFrame& frame,
204 size_t length_out_buff,
205 int16_t* out_buff) {
yujo36b1a5f2017-06-12 12:45:32 -0700206 RTC_DCHECK_EQ(frame.num_channels_, 2);
207 RTC_DCHECK_GE(length_out_buff, frame.samples_per_channel_);
208
209 if (!frame.muted()) {
210 const int16_t* frame_data = frame.data();
211 for (size_t n = 0; n < frame.samples_per_channel_; ++n) {
Yves Gerey665174f2018-06-19 15:03:05 +0200212 out_buff[n] =
213 static_cast<int16_t>((static_cast<int32_t>(frame_data[2 * n]) +
214 static_cast<int32_t>(frame_data[2 * n + 1])) >>
215 1);
yujo36b1a5f2017-06-12 12:45:32 -0700216 }
217 } else {
Jonathan Yu36344a02017-07-30 01:55:34 -0700218 std::fill(out_buff, out_buff + frame.samples_per_channel_, 0);
kwibergc13ded52016-06-17 06:00:45 -0700219 }
kwibergc13ded52016-06-17 06:00:45 -0700220}
221
Per Åhgren4f2e9402019-10-04 11:06:15 +0200222// Remixes the input frame to an output data vector. The output vector is
223// resized if needed.
224void ReMix(const AudioFrame& input,
225 size_t num_output_channels,
226 std::vector<int16_t>* output) {
227 const size_t output_size = num_output_channels * input.samples_per_channel_;
yujo36b1a5f2017-06-12 12:45:32 -0700228
Per Åhgren4f2e9402019-10-04 11:06:15 +0200229 if (output->size() != output_size) {
230 output->resize(output_size);
kwibergc13ded52016-06-17 06:00:45 -0700231 }
Per Åhgren4f2e9402019-10-04 11:06:15 +0200232
233 // For muted frames, fill the frame with zeros.
234 if (input.muted()) {
235 std::fill(output->begin(), output->end(), 0);
236 return;
237 }
238
239 // Ensure that the special case of zero input channels is handled correctly
240 // (zero samples per channel is already handled correctly in the code below).
241 if (input.num_channels_ == 0) {
242 return;
243 }
244
245 const int16_t* input_data = input.data();
Per Åhgren4f2e9402019-10-04 11:06:15 +0200246 size_t out_index = 0;
247
Per Åhgrenbb55c5e2019-11-15 14:22:30 +0100248 // When upmixing is needed and the input is mono copy the left channel
249 // into the left and right channels, and set any remaining channels to zero.
250 if (input.num_channels_ == 1 && input.num_channels_ < num_output_channels) {
251 for (size_t k = 0; k < input.samples_per_channel_; ++k) {
252 (*output)[out_index++] = input_data[k];
253 (*output)[out_index++] = input_data[k];
254 for (size_t j = 2; j < num_output_channels; ++j) {
255 (*output)[out_index++] = 0;
256 }
257 RTC_DCHECK_EQ(out_index, (k + 1) * num_output_channels);
258 }
259 RTC_DCHECK_EQ(out_index, input.samples_per_channel_ * num_output_channels);
260 return;
261 }
262
263 size_t in_index = 0;
264
265 // When upmixing is needed and the output is surround, copy the available
266 // channels directly, and set the remaining channels to zero.
Per Åhgren4f2e9402019-10-04 11:06:15 +0200267 if (input.num_channels_ < num_output_channels) {
268 for (size_t k = 0; k < input.samples_per_channel_; ++k) {
269 for (size_t j = 0; j < input.num_channels_; ++j) {
270 (*output)[out_index++] = input_data[in_index++];
271 }
Per Åhgren4f2e9402019-10-04 11:06:15 +0200272 for (size_t j = input.num_channels_; j < num_output_channels; ++j) {
Per Åhgren048b10a2019-11-13 15:44:57 +0100273 (*output)[out_index++] = 0;
Per Åhgren4f2e9402019-10-04 11:06:15 +0200274 }
Per Åhgren048b10a2019-11-13 15:44:57 +0100275 RTC_DCHECK_EQ(in_index, (k + 1) * input.num_channels_);
276 RTC_DCHECK_EQ(out_index, (k + 1) * num_output_channels);
Per Åhgren4f2e9402019-10-04 11:06:15 +0200277 }
Per Åhgren048b10a2019-11-13 15:44:57 +0100278 RTC_DCHECK_EQ(in_index, input.samples_per_channel_ * input.num_channels_);
279 RTC_DCHECK_EQ(out_index, input.samples_per_channel_ * num_output_channels);
280
Per Åhgren4f2e9402019-10-04 11:06:15 +0200281 return;
282 }
283
284 // When downmixing is needed, and the input is stereo, average the channels.
285 if (input.num_channels_ == 2) {
286 for (size_t n = 0; n < input.samples_per_channel_; ++n) {
287 (*output)[n] =
288 static_cast<int16_t>((static_cast<int32_t>(input_data[2 * n]) +
289 static_cast<int32_t>(input_data[2 * n + 1])) >>
290 1);
291 }
292 return;
293 }
294
295 // When downmixing is needed, and the input is multichannel, drop the surplus
296 // channels.
297 const size_t num_channels_to_drop = input.num_channels_ - num_output_channels;
298 for (size_t k = 0; k < input.samples_per_channel_; ++k) {
299 for (size_t j = 0; j < num_output_channels; ++j) {
300 (*output)[out_index++] = input_data[in_index++];
301 }
302 in_index += num_channels_to_drop;
303 }
kwibergc13ded52016-06-17 06:00:45 -0700304}
305
kwibergc13ded52016-06-17 06:00:45 -0700306void AudioCodingModuleImpl::ChangeLogger::MaybeLog(int value) {
307 if (value != last_value_ || first_time_) {
308 first_time_ = false;
309 last_value_ = value;
310 RTC_HISTOGRAM_COUNTS_SPARSE_100(histogram_name_, value);
311 }
312}
313
314AudioCodingModuleImpl::AudioCodingModuleImpl(
315 const AudioCodingModule::Config& config)
solenbergc7b4a452017-09-28 07:37:11 -0700316 : expected_codec_ts_(0xD87F3F9F),
kwibergc13ded52016-06-17 06:00:45 -0700317 expected_in_ts_(0xD87F3F9F),
318 receiver_(config),
319 bitrate_logger_("WebRTC.Audio.TargetBitrateInKbps"),
kwibergc13ded52016-06-17 06:00:45 -0700320 encoder_stack_(nullptr),
321 previous_pltype_(255),
322 receiver_initialized_(false),
323 first_10ms_data_(false),
324 first_frame_(true),
325 packetization_callback_(NULL),
326 vad_callback_(NULL),
327 codec_histogram_bins_log_(),
328 number_of_consecutive_empty_packets_(0) {
329 if (InitializeReceiverSafe() < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100330 RTC_LOG(LS_ERROR) << "Cannot initialize receiver";
kwibergc13ded52016-06-17 06:00:45 -0700331 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100332 RTC_LOG(LS_INFO) << "Created";
kwibergc13ded52016-06-17 06:00:45 -0700333}
334
335AudioCodingModuleImpl::~AudioCodingModuleImpl() = default;
336
337int32_t AudioCodingModuleImpl::Encode(const InputData& input_data) {
338 AudioEncoder::EncodedInfo encoded_info;
339 uint8_t previous_pltype;
340
341 // Check if there is an encoder before.
342 if (!HaveValidEncoder("Process"))
343 return -1;
344
Yves Gerey665174f2018-06-19 15:03:05 +0200345 if (!first_frame_) {
deadbeeffcada902016-08-24 12:45:13 -0700346 RTC_DCHECK(IsNewerTimestamp(input_data.input_timestamp, last_timestamp_))
ossu63fb95a2016-07-06 09:34:22 -0700347 << "Time should not move backwards";
348 }
349
kwibergc13ded52016-06-17 06:00:45 -0700350 // Scale the timestamp to the codec's RTP timestamp rate.
351 uint32_t rtp_timestamp =
Karl Wiberg053c3712019-05-16 15:24:17 +0200352 first_frame_
353 ? input_data.input_timestamp
354 : last_rtp_timestamp_ +
355 rtc::dchecked_cast<uint32_t>(rtc::CheckedDivExact(
356 int64_t{input_data.input_timestamp - last_timestamp_} *
357 encoder_stack_->RtpTimestampRateHz(),
358 int64_t{encoder_stack_->SampleRateHz()}));
kwibergc13ded52016-06-17 06:00:45 -0700359 last_timestamp_ = input_data.input_timestamp;
360 last_rtp_timestamp_ = rtp_timestamp;
361 first_frame_ = false;
362
363 // Clear the buffer before reuse - encoded data will get appended.
364 encode_buffer_.Clear();
365 encoded_info = encoder_stack_->Encode(
Yves Gerey665174f2018-06-19 15:03:05 +0200366 rtp_timestamp,
367 rtc::ArrayView<const int16_t>(
368 input_data.audio,
369 input_data.audio_channel * input_data.length_per_channel),
kwibergc13ded52016-06-17 06:00:45 -0700370 &encode_buffer_);
371
372 bitrate_logger_.MaybeLog(encoder_stack_->GetTargetBitrate() / 1000);
373 if (encode_buffer_.size() == 0 && !encoded_info.send_even_if_empty) {
374 // Not enough data.
375 return 0;
376 }
377 previous_pltype = previous_pltype_; // Read it while we have the critsect.
378
379 // Log codec type to histogram once every 500 packets.
380 if (encoded_info.encoded_bytes == 0) {
381 ++number_of_consecutive_empty_packets_;
382 } else {
383 size_t codec_type = static_cast<size_t>(encoded_info.encoder_type);
384 codec_histogram_bins_log_[codec_type] +=
385 number_of_consecutive_empty_packets_ + 1;
386 number_of_consecutive_empty_packets_ = 0;
387 if (codec_histogram_bins_log_[codec_type] >= 500) {
388 codec_histogram_bins_log_[codec_type] -= 500;
389 UpdateCodecTypeHistogram(codec_type);
390 }
391 }
392
Niels Möller87e2d782019-03-07 10:18:23 +0100393 AudioFrameType frame_type;
kwibergc13ded52016-06-17 06:00:45 -0700394 if (encode_buffer_.size() == 0 && encoded_info.send_even_if_empty) {
Niels Möllerc936cb62019-03-19 14:10:16 +0100395 frame_type = AudioFrameType::kEmptyFrame;
kwibergc13ded52016-06-17 06:00:45 -0700396 encoded_info.payload_type = previous_pltype;
397 } else {
kwibergaf476c72016-11-28 15:21:39 -0800398 RTC_DCHECK_GT(encode_buffer_.size(), 0);
Niels Möllerc936cb62019-03-19 14:10:16 +0100399 frame_type = encoded_info.speech ? AudioFrameType::kAudioFrameSpeech
400 : AudioFrameType::kAudioFrameCN;
kwibergc13ded52016-06-17 06:00:45 -0700401 }
402
403 {
404 rtc::CritScope lock(&callback_crit_sect_);
405 if (packetization_callback_) {
406 packetization_callback_->SendData(
407 frame_type, encoded_info.payload_type, encoded_info.encoded_timestamp,
Niels Möllerc35b6e62019-04-25 16:31:18 +0200408 encode_buffer_.data(), encode_buffer_.size());
kwibergc13ded52016-06-17 06:00:45 -0700409 }
410
411 if (vad_callback_) {
412 // Callback with VAD decision.
413 vad_callback_->InFrameType(frame_type);
414 }
415 }
416 previous_pltype_ = encoded_info.payload_type;
417 return static_cast<int32_t>(encode_buffer_.size());
418}
419
420/////////////////////////////////////////
421// Sender
422//
423
kwibergc13ded52016-06-17 06:00:45 -0700424void AudioCodingModuleImpl::ModifyEncoder(
kwiberg24c7c122016-09-28 11:57:10 -0700425 rtc::FunctionView<void(std::unique_ptr<AudioEncoder>*)> modifier) {
kwibergc13ded52016-06-17 06:00:45 -0700426 rtc::CritScope lock(&acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700427 modifier(&encoder_stack_);
428}
429
kwibergc13ded52016-06-17 06:00:45 -0700430// Register a transport callback which will be called to deliver
431// the encoded buffers.
432int AudioCodingModuleImpl::RegisterTransportCallback(
433 AudioPacketizationCallback* transport) {
434 rtc::CritScope lock(&callback_crit_sect_);
435 packetization_callback_ = transport;
436 return 0;
437}
438
439// Add 10MS of raw (PCM) audio data to the encoder.
440int AudioCodingModuleImpl::Add10MsData(const AudioFrame& audio_frame) {
kwibergc13ded52016-06-17 06:00:45 -0700441 rtc::CritScope lock(&acm_crit_sect_);
Per Åhgren4f2e9402019-10-04 11:06:15 +0200442 int r = Add10MsDataInternal(audio_frame, &input_data_);
443 return r < 0 ? r : Encode(input_data_);
kwibergc13ded52016-06-17 06:00:45 -0700444}
445
446int AudioCodingModuleImpl::Add10MsDataInternal(const AudioFrame& audio_frame,
447 InputData* input_data) {
448 if (audio_frame.samples_per_channel_ == 0) {
449 assert(false);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100450 RTC_LOG(LS_ERROR) << "Cannot Add 10 ms audio, payload length is zero";
kwibergc13ded52016-06-17 06:00:45 -0700451 return -1;
452 }
453
henrika33541572019-09-10 14:27:40 +0200454 if (audio_frame.sample_rate_hz_ > 192000) {
kwibergc13ded52016-06-17 06:00:45 -0700455 assert(false);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100456 RTC_LOG(LS_ERROR) << "Cannot Add 10 ms audio, input frequency not valid";
kwibergc13ded52016-06-17 06:00:45 -0700457 return -1;
458 }
459
460 // If the length and frequency matches. We currently just support raw PCM.
461 if (static_cast<size_t>(audio_frame.sample_rate_hz_ / 100) !=
462 audio_frame.samples_per_channel_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100463 RTC_LOG(LS_ERROR)
Alex Loiko300ec8c2017-05-30 17:23:28 +0200464 << "Cannot Add 10 ms audio, input frequency and length doesn't match";
kwibergc13ded52016-06-17 06:00:45 -0700465 return -1;
466 }
467
Alex Loiko65438812019-02-22 10:13:44 +0100468 if (audio_frame.num_channels_ != 1 && audio_frame.num_channels_ != 2 &&
469 audio_frame.num_channels_ != 4 && audio_frame.num_channels_ != 6 &&
470 audio_frame.num_channels_ != 8) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100471 RTC_LOG(LS_ERROR) << "Cannot Add 10 ms audio, invalid number of channels.";
kwibergc13ded52016-06-17 06:00:45 -0700472 return -1;
473 }
474
475 // Do we have a codec registered?
476 if (!HaveValidEncoder("Add10MsData")) {
477 return -1;
478 }
479
480 const AudioFrame* ptr_frame;
481 // Perform a resampling, also down-mix if it is required and can be
482 // performed before resampling (a down mix prior to resampling will take
483 // place if both primary and secondary encoders are mono and input is in
484 // stereo).
485 if (PreprocessToAddData(audio_frame, &ptr_frame) < 0) {
486 return -1;
487 }
488
489 // Check whether we need an up-mix or down-mix?
490 const size_t current_num_channels = encoder_stack_->NumChannels();
491 const bool same_num_channels =
492 ptr_frame->num_channels_ == current_num_channels;
493
yujo36b1a5f2017-06-12 12:45:32 -0700494 // TODO(yujo): Skip encode of muted frames.
kwibergc13ded52016-06-17 06:00:45 -0700495 input_data->input_timestamp = ptr_frame->timestamp_;
kwibergc13ded52016-06-17 06:00:45 -0700496 input_data->length_per_channel = ptr_frame->samples_per_channel_;
497 input_data->audio_channel = current_num_channels;
498
Per Åhgren4f2e9402019-10-04 11:06:15 +0200499 if (!same_num_channels) {
500 // Remixes the input frame to the output data and in the process resize the
501 // output data if needed.
502 ReMix(*ptr_frame, current_num_channels, &input_data->buffer);
503
504 // For pushing data to primary, point the |ptr_audio| to correct buffer.
505 input_data->audio = input_data->buffer.data();
506 RTC_DCHECK_GE(input_data->buffer.size(),
507 input_data->length_per_channel * input_data->audio_channel);
508 } else {
509 // When adding data to encoders this pointer is pointing to an audio buffer
510 // with correct number of channels.
511 input_data->audio = ptr_frame->data();
512 }
513
kwibergc13ded52016-06-17 06:00:45 -0700514 return 0;
515}
516
517// Perform a resampling and down-mix if required. We down-mix only if
518// encoder is mono and input is stereo. In case of dual-streaming, both
519// encoders has to be mono for down-mix to take place.
520// |*ptr_out| will point to the pre-processed audio-frame. If no pre-processing
521// is required, |*ptr_out| points to |in_frame|.
yujo36b1a5f2017-06-12 12:45:32 -0700522// TODO(yujo): Make this more efficient for muted frames.
kwibergc13ded52016-06-17 06:00:45 -0700523int AudioCodingModuleImpl::PreprocessToAddData(const AudioFrame& in_frame,
524 const AudioFrame** ptr_out) {
525 const bool resample =
526 in_frame.sample_rate_hz_ != encoder_stack_->SampleRateHz();
527
528 // This variable is true if primary codec and secondary codec (if exists)
529 // are both mono and input is stereo.
530 // TODO(henrik.lundin): This condition should probably be
531 // in_frame.num_channels_ > encoder_stack_->NumChannels()
532 const bool down_mix =
533 in_frame.num_channels_ == 2 && encoder_stack_->NumChannels() == 1;
534
535 if (!first_10ms_data_) {
536 expected_in_ts_ = in_frame.timestamp_;
537 expected_codec_ts_ = in_frame.timestamp_;
538 first_10ms_data_ = true;
539 } else if (in_frame.timestamp_ != expected_in_ts_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100540 RTC_LOG(LS_WARNING) << "Unexpected input timestamp: " << in_frame.timestamp_
541 << ", expected: " << expected_in_ts_;
kwibergc13ded52016-06-17 06:00:45 -0700542 expected_codec_ts_ +=
543 (in_frame.timestamp_ - expected_in_ts_) *
544 static_cast<uint32_t>(
545 static_cast<double>(encoder_stack_->SampleRateHz()) /
546 static_cast<double>(in_frame.sample_rate_hz_));
547 expected_in_ts_ = in_frame.timestamp_;
548 }
549
kwibergc13ded52016-06-17 06:00:45 -0700550 if (!down_mix && !resample) {
551 // No pre-processing is required.
ossu63fb95a2016-07-06 09:34:22 -0700552 if (expected_in_ts_ == expected_codec_ts_) {
553 // If we've never resampled, we can use the input frame as-is
554 *ptr_out = &in_frame;
555 } else {
556 // Otherwise we'll need to alter the timestamp. Since in_frame is const,
557 // we'll have to make a copy of it.
558 preprocess_frame_.CopyFrom(in_frame);
559 preprocess_frame_.timestamp_ = expected_codec_ts_;
560 *ptr_out = &preprocess_frame_;
561 }
562
kwibergc13ded52016-06-17 06:00:45 -0700563 expected_in_ts_ += static_cast<uint32_t>(in_frame.samples_per_channel_);
564 expected_codec_ts_ += static_cast<uint32_t>(in_frame.samples_per_channel_);
kwibergc13ded52016-06-17 06:00:45 -0700565 return 0;
566 }
567
568 *ptr_out = &preprocess_frame_;
569 preprocess_frame_.num_channels_ = in_frame.num_channels_;
570 int16_t audio[WEBRTC_10MS_PCM_AUDIO];
yujo36b1a5f2017-06-12 12:45:32 -0700571 const int16_t* src_ptr_audio = in_frame.data();
kwibergc13ded52016-06-17 06:00:45 -0700572 if (down_mix) {
573 // If a resampling is required the output of a down-mix is written into a
574 // local buffer, otherwise, it will be written to the output frame.
Yves Gerey665174f2018-06-19 15:03:05 +0200575 int16_t* dest_ptr_audio =
576 resample ? audio : preprocess_frame_.mutable_data();
Per Åhgren4f2e9402019-10-04 11:06:15 +0200577 DownMix(in_frame, WEBRTC_10MS_PCM_AUDIO, dest_ptr_audio);
kwibergc13ded52016-06-17 06:00:45 -0700578 preprocess_frame_.num_channels_ = 1;
579 // Set the input of the resampler is the down-mixed signal.
580 src_ptr_audio = audio;
581 }
582
583 preprocess_frame_.timestamp_ = expected_codec_ts_;
584 preprocess_frame_.samples_per_channel_ = in_frame.samples_per_channel_;
585 preprocess_frame_.sample_rate_hz_ = in_frame.sample_rate_hz_;
586 // If it is required, we have to do a resampling.
587 if (resample) {
588 // The result of the resampler is written to output frame.
yujo36b1a5f2017-06-12 12:45:32 -0700589 int16_t* dest_ptr_audio = preprocess_frame_.mutable_data();
kwibergc13ded52016-06-17 06:00:45 -0700590
591 int samples_per_channel = resampler_.Resample10Msec(
592 src_ptr_audio, in_frame.sample_rate_hz_, encoder_stack_->SampleRateHz(),
593 preprocess_frame_.num_channels_, AudioFrame::kMaxDataSizeSamples,
594 dest_ptr_audio);
595
596 if (samples_per_channel < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100597 RTC_LOG(LS_ERROR) << "Cannot add 10 ms audio, resampling failed";
kwibergc13ded52016-06-17 06:00:45 -0700598 return -1;
599 }
600 preprocess_frame_.samples_per_channel_ =
601 static_cast<size_t>(samples_per_channel);
602 preprocess_frame_.sample_rate_hz_ = encoder_stack_->SampleRateHz();
603 }
604
605 expected_codec_ts_ +=
606 static_cast<uint32_t>(preprocess_frame_.samples_per_channel_);
607 expected_in_ts_ += static_cast<uint32_t>(in_frame.samples_per_channel_);
608
609 return 0;
610}
611
612/////////////////////////////////////////
kwibergc13ded52016-06-17 06:00:45 -0700613// (FEC) Forward Error Correction (codec internal)
614//
615
kwibergc13ded52016-06-17 06:00:45 -0700616int AudioCodingModuleImpl::SetPacketLossRate(int loss_rate) {
617 rtc::CritScope lock(&acm_crit_sect_);
618 if (HaveValidEncoder("SetPacketLossRate")) {
minyue4b9a2cb2016-11-30 06:49:59 -0800619 encoder_stack_->OnReceivedUplinkPacketLossFraction(loss_rate / 100.0);
kwibergc13ded52016-06-17 06:00:45 -0700620 }
621 return 0;
622}
623
624/////////////////////////////////////////
kwibergc13ded52016-06-17 06:00:45 -0700625// Receiver
626//
627
628int AudioCodingModuleImpl::InitializeReceiver() {
629 rtc::CritScope lock(&acm_crit_sect_);
630 return InitializeReceiverSafe();
631}
632
633// Initialize receiver, resets codec database etc.
634int AudioCodingModuleImpl::InitializeReceiverSafe() {
635 // If the receiver is already initialized then we want to destroy any
636 // existing decoders. After a call to this function, we should have a clean
637 // start-up.
kwiberg6b19b562016-09-20 04:02:25 -0700638 if (receiver_initialized_)
639 receiver_.RemoveAllCodecs();
kwibergc13ded52016-06-17 06:00:45 -0700640 receiver_.FlushBuffers();
641
kwibergc13ded52016-06-17 06:00:45 -0700642 receiver_initialized_ = true;
643 return 0;
644}
645
kwiberg1c07c702017-03-27 07:15:49 -0700646void AudioCodingModuleImpl::SetReceiveCodecs(
647 const std::map<int, SdpAudioFormat>& codecs) {
648 rtc::CritScope lock(&acm_crit_sect_);
649 receiver_.SetCodecs(codecs);
650}
651
kwibergc13ded52016-06-17 06:00:45 -0700652// Incoming packet from network parsed and ready for decode.
653int AudioCodingModuleImpl::IncomingPacket(const uint8_t* incoming_payload,
654 const size_t payload_length,
Niels Möllerafb5dbb2019-02-15 15:21:47 +0100655 const RTPHeader& rtp_header) {
henrik.lundinb8c55b12017-05-10 07:38:01 -0700656 RTC_DCHECK_EQ(payload_length == 0, incoming_payload == nullptr);
kwibergc13ded52016-06-17 06:00:45 -0700657 return receiver_.InsertPacket(
658 rtp_header,
659 rtc::ArrayView<const uint8_t>(incoming_payload, payload_length));
660}
661
kwibergc13ded52016-06-17 06:00:45 -0700662// Get 10 milliseconds of raw audio data to play out.
663// Automatic resample to the requested frequency.
664int AudioCodingModuleImpl::PlayoutData10Ms(int desired_freq_hz,
665 AudioFrame* audio_frame,
666 bool* muted) {
667 // GetAudio always returns 10 ms, at the requested sample rate.
668 if (receiver_.GetAudio(desired_freq_hz, audio_frame, muted) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100669 RTC_LOG(LS_ERROR) << "PlayoutData failed, RecOut Failed";
kwibergc13ded52016-06-17 06:00:45 -0700670 return -1;
671 }
kwibergc13ded52016-06-17 06:00:45 -0700672 return 0;
673}
674
kwibergc13ded52016-06-17 06:00:45 -0700675/////////////////////////////////////////
676// Statistics
677//
678
679// TODO(turajs) change the return value to void. Also change the corresponding
680// NetEq function.
681int AudioCodingModuleImpl::GetNetworkStatistics(NetworkStatistics* statistics) {
682 receiver_.GetNetworkStatistics(statistics);
683 return 0;
684}
685
686int AudioCodingModuleImpl::RegisterVADCallback(ACMVADCallback* vad_callback) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100687 RTC_LOG(LS_VERBOSE) << "RegisterVADCallback()";
kwibergc13ded52016-06-17 06:00:45 -0700688 rtc::CritScope lock(&callback_crit_sect_);
689 vad_callback_ = vad_callback;
690 return 0;
691}
692
kwibergc13ded52016-06-17 06:00:45 -0700693bool AudioCodingModuleImpl::HaveValidEncoder(const char* caller_name) const {
694 if (!encoder_stack_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100695 RTC_LOG(LS_ERROR) << caller_name << " failed: No send codec is registered.";
kwibergc13ded52016-06-17 06:00:45 -0700696 return false;
697 }
698 return true;
699}
700
ivoce1198e02017-09-08 08:13:19 -0700701ANAStats AudioCodingModuleImpl::GetANAStats() const {
702 rtc::CritScope lock(&acm_crit_sect_);
703 if (encoder_stack_)
704 return encoder_stack_->GetANAStats();
705 // If no encoder is set, return default stats.
706 return ANAStats();
707}
708
kwibergc13ded52016-06-17 06:00:45 -0700709} // namespace
710
Karl Wiberg5817d3d2018-04-06 10:06:42 +0200711AudioCodingModule::Config::Config(
712 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory)
713 : neteq_config(),
714 clock(Clock::GetRealTimeClock()),
715 decoder_factory(decoder_factory) {
kwiberg36a43882016-08-29 05:33:32 -0700716 // Post-decode VAD is disabled by default in NetEq, however, Audio
717 // Conference Mixer relies on VAD decisions and fails without them.
718 neteq_config.enable_post_decode_vad = true;
719}
720
721AudioCodingModule::Config::Config(const Config&) = default;
722AudioCodingModule::Config::~Config() = default;
723
Henrik Lundin64dad832015-05-11 12:44:23 +0200724AudioCodingModule* AudioCodingModule::Create(const Config& config) {
kwibergc13ded52016-06-17 06:00:45 -0700725 return new AudioCodingModuleImpl(config);
turaj@webrtc.org7959e162013-09-12 18:30:26 +0000726}
727
turaj@webrtc.org7959e162013-09-12 18:30:26 +0000728} // namespace webrtc