blob: db6f125629c72e8a9903bdf61e65babf71e9b3d3 [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 /////////////////////////////////////////
kwibergc13ded52016-06-17 06:00:45 -070067 // Receiver
68 //
69
70 // Initialize receiver, resets codec database etc.
71 int InitializeReceiver() override;
72
kwiberg1c07c702017-03-27 07:15:49 -070073 void SetReceiveCodecs(const std::map<int, SdpAudioFormat>& codecs) override;
74
kwibergc13ded52016-06-17 06:00:45 -070075 // Incoming packet from network parsed and ready for decode.
76 int IncomingPacket(const uint8_t* incoming_payload,
77 const size_t payload_length,
Niels Möllerafb5dbb2019-02-15 15:21:47 +010078 const RTPHeader& rtp_info) override;
kwibergc13ded52016-06-17 06:00:45 -070079
kwibergc13ded52016-06-17 06:00:45 -070080 // Get 10 milliseconds of raw audio data to play out, and
81 // automatic resample to the requested frequency if > 0.
82 int PlayoutData10Ms(int desired_freq_hz,
83 AudioFrame* audio_frame,
84 bool* muted) override;
kwibergc13ded52016-06-17 06:00:45 -070085
86 /////////////////////////////////////////
87 // Statistics
88 //
89
90 int GetNetworkStatistics(NetworkStatistics* statistics) override;
91
ivoce1198e02017-09-08 08:13:19 -070092 ANAStats GetANAStats() const override;
93
kwibergc13ded52016-06-17 06:00:45 -070094 private:
95 struct InputData {
Per Åhgren4f2e9402019-10-04 11:06:15 +020096 InputData() : buffer(kInitialInputDataBufferSize) {}
kwibergc13ded52016-06-17 06:00:45 -070097 uint32_t input_timestamp;
98 const int16_t* audio;
99 size_t length_per_channel;
100 size_t audio_channel;
101 // If a re-mix is required (up or down), this buffer will store a re-mixed
102 // version of the input.
Per Åhgren4f2e9402019-10-04 11:06:15 +0200103 std::vector<int16_t> buffer;
kwibergc13ded52016-06-17 06:00:45 -0700104 };
105
Per Åhgren4f2e9402019-10-04 11:06:15 +0200106 InputData input_data_ RTC_GUARDED_BY(acm_crit_sect_);
107
kwibergc13ded52016-06-17 06:00:45 -0700108 // This member class writes values to the named UMA histogram, but only if
109 // the value has changed since the last time (and always for the first call).
110 class ChangeLogger {
111 public:
112 explicit ChangeLogger(const std::string& histogram_name)
113 : histogram_name_(histogram_name) {}
114 // Logs the new value if it is different from the last logged value, or if
115 // this is the first call.
116 void MaybeLog(int value);
117
118 private:
119 int last_value_ = 0;
120 int first_time_ = true;
121 const std::string histogram_name_;
122 };
123
kwibergc13ded52016-06-17 06:00:45 -0700124 int Add10MsDataInternal(const AudioFrame& audio_frame, InputData* input_data)
danilchap56359be2017-09-07 07:53:45 -0700125 RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
Minyue Lidea73ee2020-02-18 15:45:41 +0100126
127 // TODO(bugs.webrtc.org/10739): change |absolute_capture_timestamp_ms| to
128 // int64_t when it always receives a valid value.
129 int Encode(const InputData& input_data,
130 absl::optional<int64_t> absolute_capture_timestamp_ms)
danilchap56359be2017-09-07 07:53:45 -0700131 RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700132
danilchap56359be2017-09-07 07:53:45 -0700133 int InitializeReceiverSafe() RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700134
135 bool HaveValidEncoder(const char* caller_name) const
danilchap56359be2017-09-07 07:53:45 -0700136 RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700137
138 // Preprocessing of input audio, including resampling and down-mixing if
139 // required, before pushing audio into encoder's buffer.
140 //
141 // in_frame: input audio-frame
142 // ptr_out: pointer to output audio_frame. If no preprocessing is required
143 // |ptr_out| will be pointing to |in_frame|, otherwise pointing to
144 // |preprocess_frame_|.
145 //
146 // Return value:
147 // -1: if encountering an error.
148 // 0: otherwise.
149 int PreprocessToAddData(const AudioFrame& in_frame,
150 const AudioFrame** ptr_out)
danilchap56359be2017-09-07 07:53:45 -0700151 RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700152
153 // Change required states after starting to receive the codec corresponding
154 // to |index|.
155 int UpdateUponReceivingCodec(int index);
156
157 rtc::CriticalSection acm_crit_sect_;
danilchap56359be2017-09-07 07:53:45 -0700158 rtc::Buffer encode_buffer_ RTC_GUARDED_BY(acm_crit_sect_);
danilchap56359be2017-09-07 07:53:45 -0700159 uint32_t expected_codec_ts_ RTC_GUARDED_BY(acm_crit_sect_);
160 uint32_t expected_in_ts_ RTC_GUARDED_BY(acm_crit_sect_);
161 acm2::ACMResampler resampler_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700162 acm2::AcmReceiver receiver_; // AcmReceiver has it's own internal lock.
danilchap56359be2017-09-07 07:53:45 -0700163 ChangeLogger bitrate_logger_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700164
Karl Wiberg49c33ce2018-11-12 14:21:58 +0100165 // Current encoder stack, provided by a call to RegisterEncoder.
danilchap56359be2017-09-07 07:53:45 -0700166 std::unique_ptr<AudioEncoder> encoder_stack_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700167
kwibergc13ded52016-06-17 06:00:45 -0700168 // This is to keep track of CN instances where we can send DTMFs.
danilchap56359be2017-09-07 07:53:45 -0700169 uint8_t previous_pltype_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700170
danilchap56359be2017-09-07 07:53:45 -0700171 bool receiver_initialized_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700172
danilchap56359be2017-09-07 07:53:45 -0700173 AudioFrame preprocess_frame_ RTC_GUARDED_BY(acm_crit_sect_);
174 bool first_10ms_data_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700175
danilchap56359be2017-09-07 07:53:45 -0700176 bool first_frame_ RTC_GUARDED_BY(acm_crit_sect_);
177 uint32_t last_timestamp_ RTC_GUARDED_BY(acm_crit_sect_);
178 uint32_t last_rtp_timestamp_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700179
180 rtc::CriticalSection callback_crit_sect_;
181 AudioPacketizationCallback* packetization_callback_
danilchap56359be2017-09-07 07:53:45 -0700182 RTC_GUARDED_BY(callback_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700183
184 int codec_histogram_bins_log_[static_cast<size_t>(
185 AudioEncoder::CodecType::kMaxLoggedAudioCodecTypes)];
186 int number_of_consecutive_empty_packets_;
187};
188
189// Adds a codec usage sample to the histogram.
190void UpdateCodecTypeHistogram(size_t codec_type) {
191 RTC_HISTOGRAM_ENUMERATION(
192 "WebRTC.Audio.Encoder.CodecType", static_cast<int>(codec_type),
193 static_cast<int>(
194 webrtc::AudioEncoder::CodecType::kMaxLoggedAudioCodecTypes));
195}
196
kwibergc13ded52016-06-17 06:00:45 -0700197void AudioCodingModuleImpl::ChangeLogger::MaybeLog(int value) {
198 if (value != last_value_ || first_time_) {
199 first_time_ = false;
200 last_value_ = value;
201 RTC_HISTOGRAM_COUNTS_SPARSE_100(histogram_name_, value);
202 }
203}
204
205AudioCodingModuleImpl::AudioCodingModuleImpl(
206 const AudioCodingModule::Config& config)
solenbergc7b4a452017-09-28 07:37:11 -0700207 : expected_codec_ts_(0xD87F3F9F),
kwibergc13ded52016-06-17 06:00:45 -0700208 expected_in_ts_(0xD87F3F9F),
209 receiver_(config),
210 bitrate_logger_("WebRTC.Audio.TargetBitrateInKbps"),
kwibergc13ded52016-06-17 06:00:45 -0700211 encoder_stack_(nullptr),
212 previous_pltype_(255),
213 receiver_initialized_(false),
214 first_10ms_data_(false),
215 first_frame_(true),
216 packetization_callback_(NULL),
kwibergc13ded52016-06-17 06:00:45 -0700217 codec_histogram_bins_log_(),
218 number_of_consecutive_empty_packets_(0) {
219 if (InitializeReceiverSafe() < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100220 RTC_LOG(LS_ERROR) << "Cannot initialize receiver";
kwibergc13ded52016-06-17 06:00:45 -0700221 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100222 RTC_LOG(LS_INFO) << "Created";
kwibergc13ded52016-06-17 06:00:45 -0700223}
224
225AudioCodingModuleImpl::~AudioCodingModuleImpl() = default;
226
Minyue Lidea73ee2020-02-18 15:45:41 +0100227int32_t AudioCodingModuleImpl::Encode(
228 const InputData& input_data,
229 absl::optional<int64_t> absolute_capture_timestamp_ms) {
230 // TODO(bugs.webrtc.org/10739): add dcheck that
231 // |audio_frame.absolute_capture_timestamp_ms()| always has a value.
kwibergc13ded52016-06-17 06:00:45 -0700232 AudioEncoder::EncodedInfo encoded_info;
233 uint8_t previous_pltype;
234
235 // Check if there is an encoder before.
236 if (!HaveValidEncoder("Process"))
237 return -1;
238
Yves Gerey665174f2018-06-19 15:03:05 +0200239 if (!first_frame_) {
deadbeeffcada902016-08-24 12:45:13 -0700240 RTC_DCHECK(IsNewerTimestamp(input_data.input_timestamp, last_timestamp_))
ossu63fb95a2016-07-06 09:34:22 -0700241 << "Time should not move backwards";
242 }
243
kwibergc13ded52016-06-17 06:00:45 -0700244 // Scale the timestamp to the codec's RTP timestamp rate.
245 uint32_t rtp_timestamp =
Karl Wiberg053c3712019-05-16 15:24:17 +0200246 first_frame_
247 ? input_data.input_timestamp
248 : last_rtp_timestamp_ +
249 rtc::dchecked_cast<uint32_t>(rtc::CheckedDivExact(
250 int64_t{input_data.input_timestamp - last_timestamp_} *
251 encoder_stack_->RtpTimestampRateHz(),
252 int64_t{encoder_stack_->SampleRateHz()}));
Minyue Liff0e4db2020-01-23 13:45:50 +0100253
kwibergc13ded52016-06-17 06:00:45 -0700254 last_timestamp_ = input_data.input_timestamp;
255 last_rtp_timestamp_ = rtp_timestamp;
256 first_frame_ = false;
257
258 // Clear the buffer before reuse - encoded data will get appended.
259 encode_buffer_.Clear();
260 encoded_info = encoder_stack_->Encode(
Yves Gerey665174f2018-06-19 15:03:05 +0200261 rtp_timestamp,
262 rtc::ArrayView<const int16_t>(
263 input_data.audio,
264 input_data.audio_channel * input_data.length_per_channel),
kwibergc13ded52016-06-17 06:00:45 -0700265 &encode_buffer_);
266
267 bitrate_logger_.MaybeLog(encoder_stack_->GetTargetBitrate() / 1000);
268 if (encode_buffer_.size() == 0 && !encoded_info.send_even_if_empty) {
269 // Not enough data.
270 return 0;
271 }
272 previous_pltype = previous_pltype_; // Read it while we have the critsect.
273
274 // Log codec type to histogram once every 500 packets.
275 if (encoded_info.encoded_bytes == 0) {
276 ++number_of_consecutive_empty_packets_;
277 } else {
278 size_t codec_type = static_cast<size_t>(encoded_info.encoder_type);
279 codec_histogram_bins_log_[codec_type] +=
280 number_of_consecutive_empty_packets_ + 1;
281 number_of_consecutive_empty_packets_ = 0;
282 if (codec_histogram_bins_log_[codec_type] >= 500) {
283 codec_histogram_bins_log_[codec_type] -= 500;
284 UpdateCodecTypeHistogram(codec_type);
285 }
286 }
287
Niels Möller87e2d782019-03-07 10:18:23 +0100288 AudioFrameType frame_type;
kwibergc13ded52016-06-17 06:00:45 -0700289 if (encode_buffer_.size() == 0 && encoded_info.send_even_if_empty) {
Niels Möllerc936cb62019-03-19 14:10:16 +0100290 frame_type = AudioFrameType::kEmptyFrame;
kwibergc13ded52016-06-17 06:00:45 -0700291 encoded_info.payload_type = previous_pltype;
292 } else {
kwibergaf476c72016-11-28 15:21:39 -0800293 RTC_DCHECK_GT(encode_buffer_.size(), 0);
Niels Möllerc936cb62019-03-19 14:10:16 +0100294 frame_type = encoded_info.speech ? AudioFrameType::kAudioFrameSpeech
295 : AudioFrameType::kAudioFrameCN;
kwibergc13ded52016-06-17 06:00:45 -0700296 }
297
298 {
299 rtc::CritScope lock(&callback_crit_sect_);
300 if (packetization_callback_) {
301 packetization_callback_->SendData(
302 frame_type, encoded_info.payload_type, encoded_info.encoded_timestamp,
Minyue Liff0e4db2020-01-23 13:45:50 +0100303 encode_buffer_.data(), encode_buffer_.size(),
Minyue Lidea73ee2020-02-18 15:45:41 +0100304 absolute_capture_timestamp_ms.value_or(-1));
kwibergc13ded52016-06-17 06:00:45 -0700305 }
kwibergc13ded52016-06-17 06:00:45 -0700306 }
307 previous_pltype_ = encoded_info.payload_type;
308 return static_cast<int32_t>(encode_buffer_.size());
309}
310
311/////////////////////////////////////////
312// Sender
313//
314
kwibergc13ded52016-06-17 06:00:45 -0700315void AudioCodingModuleImpl::ModifyEncoder(
kwiberg24c7c122016-09-28 11:57:10 -0700316 rtc::FunctionView<void(std::unique_ptr<AudioEncoder>*)> modifier) {
kwibergc13ded52016-06-17 06:00:45 -0700317 rtc::CritScope lock(&acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700318 modifier(&encoder_stack_);
319}
320
kwibergc13ded52016-06-17 06:00:45 -0700321// Register a transport callback which will be called to deliver
322// the encoded buffers.
323int AudioCodingModuleImpl::RegisterTransportCallback(
324 AudioPacketizationCallback* transport) {
325 rtc::CritScope lock(&callback_crit_sect_);
326 packetization_callback_ = transport;
327 return 0;
328}
329
330// Add 10MS of raw (PCM) audio data to the encoder.
331int AudioCodingModuleImpl::Add10MsData(const AudioFrame& audio_frame) {
kwibergc13ded52016-06-17 06:00:45 -0700332 rtc::CritScope lock(&acm_crit_sect_);
Per Åhgren4f2e9402019-10-04 11:06:15 +0200333 int r = Add10MsDataInternal(audio_frame, &input_data_);
Minyue Lidea73ee2020-02-18 15:45:41 +0100334 // TODO(bugs.webrtc.org/10739): add dcheck that
335 // |audio_frame.absolute_capture_timestamp_ms()| always has a value.
336 return r < 0
337 ? r
338 : Encode(input_data_, audio_frame.absolute_capture_timestamp_ms());
kwibergc13ded52016-06-17 06:00:45 -0700339}
340
341int AudioCodingModuleImpl::Add10MsDataInternal(const AudioFrame& audio_frame,
342 InputData* input_data) {
343 if (audio_frame.samples_per_channel_ == 0) {
344 assert(false);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100345 RTC_LOG(LS_ERROR) << "Cannot Add 10 ms audio, payload length is zero";
kwibergc13ded52016-06-17 06:00:45 -0700346 return -1;
347 }
348
henrika33541572019-09-10 14:27:40 +0200349 if (audio_frame.sample_rate_hz_ > 192000) {
kwibergc13ded52016-06-17 06:00:45 -0700350 assert(false);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100351 RTC_LOG(LS_ERROR) << "Cannot Add 10 ms audio, input frequency not valid";
kwibergc13ded52016-06-17 06:00:45 -0700352 return -1;
353 }
354
355 // If the length and frequency matches. We currently just support raw PCM.
356 if (static_cast<size_t>(audio_frame.sample_rate_hz_ / 100) !=
357 audio_frame.samples_per_channel_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100358 RTC_LOG(LS_ERROR)
Alex Loiko300ec8c2017-05-30 17:23:28 +0200359 << "Cannot Add 10 ms audio, input frequency and length doesn't match";
kwibergc13ded52016-06-17 06:00:45 -0700360 return -1;
361 }
362
Alex Loiko65438812019-02-22 10:13:44 +0100363 if (audio_frame.num_channels_ != 1 && audio_frame.num_channels_ != 2 &&
364 audio_frame.num_channels_ != 4 && audio_frame.num_channels_ != 6 &&
365 audio_frame.num_channels_ != 8) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100366 RTC_LOG(LS_ERROR) << "Cannot Add 10 ms audio, invalid number of channels.";
kwibergc13ded52016-06-17 06:00:45 -0700367 return -1;
368 }
369
370 // Do we have a codec registered?
371 if (!HaveValidEncoder("Add10MsData")) {
372 return -1;
373 }
374
375 const AudioFrame* ptr_frame;
376 // Perform a resampling, also down-mix if it is required and can be
377 // performed before resampling (a down mix prior to resampling will take
378 // place if both primary and secondary encoders are mono and input is in
379 // stereo).
380 if (PreprocessToAddData(audio_frame, &ptr_frame) < 0) {
381 return -1;
382 }
383
384 // Check whether we need an up-mix or down-mix?
385 const size_t current_num_channels = encoder_stack_->NumChannels();
386 const bool same_num_channels =
387 ptr_frame->num_channels_ == current_num_channels;
388
yujo36b1a5f2017-06-12 12:45:32 -0700389 // TODO(yujo): Skip encode of muted frames.
kwibergc13ded52016-06-17 06:00:45 -0700390 input_data->input_timestamp = ptr_frame->timestamp_;
kwibergc13ded52016-06-17 06:00:45 -0700391 input_data->length_per_channel = ptr_frame->samples_per_channel_;
392 input_data->audio_channel = current_num_channels;
393
Per Åhgren4f2e9402019-10-04 11:06:15 +0200394 if (!same_num_channels) {
395 // Remixes the input frame to the output data and in the process resize the
396 // output data if needed.
Per Åhgren4dd56a32019-11-19 21:00:59 +0100397 ReMixFrame(*ptr_frame, current_num_channels, &input_data->buffer);
Per Åhgren4f2e9402019-10-04 11:06:15 +0200398
399 // For pushing data to primary, point the |ptr_audio| to correct buffer.
400 input_data->audio = input_data->buffer.data();
401 RTC_DCHECK_GE(input_data->buffer.size(),
402 input_data->length_per_channel * input_data->audio_channel);
403 } else {
404 // When adding data to encoders this pointer is pointing to an audio buffer
405 // with correct number of channels.
406 input_data->audio = ptr_frame->data();
407 }
408
kwibergc13ded52016-06-17 06:00:45 -0700409 return 0;
410}
411
412// Perform a resampling and down-mix if required. We down-mix only if
413// encoder is mono and input is stereo. In case of dual-streaming, both
414// encoders has to be mono for down-mix to take place.
415// |*ptr_out| will point to the pre-processed audio-frame. If no pre-processing
416// is required, |*ptr_out| points to |in_frame|.
yujo36b1a5f2017-06-12 12:45:32 -0700417// TODO(yujo): Make this more efficient for muted frames.
kwibergc13ded52016-06-17 06:00:45 -0700418int AudioCodingModuleImpl::PreprocessToAddData(const AudioFrame& in_frame,
419 const AudioFrame** ptr_out) {
420 const bool resample =
421 in_frame.sample_rate_hz_ != encoder_stack_->SampleRateHz();
422
423 // This variable is true if primary codec and secondary codec (if exists)
424 // are both mono and input is stereo.
425 // TODO(henrik.lundin): This condition should probably be
426 // in_frame.num_channels_ > encoder_stack_->NumChannels()
427 const bool down_mix =
428 in_frame.num_channels_ == 2 && encoder_stack_->NumChannels() == 1;
429
430 if (!first_10ms_data_) {
431 expected_in_ts_ = in_frame.timestamp_;
432 expected_codec_ts_ = in_frame.timestamp_;
433 first_10ms_data_ = true;
434 } else if (in_frame.timestamp_ != expected_in_ts_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100435 RTC_LOG(LS_WARNING) << "Unexpected input timestamp: " << in_frame.timestamp_
436 << ", expected: " << expected_in_ts_;
kwibergc13ded52016-06-17 06:00:45 -0700437 expected_codec_ts_ +=
438 (in_frame.timestamp_ - expected_in_ts_) *
439 static_cast<uint32_t>(
440 static_cast<double>(encoder_stack_->SampleRateHz()) /
441 static_cast<double>(in_frame.sample_rate_hz_));
442 expected_in_ts_ = in_frame.timestamp_;
443 }
444
kwibergc13ded52016-06-17 06:00:45 -0700445 if (!down_mix && !resample) {
446 // No pre-processing is required.
ossu63fb95a2016-07-06 09:34:22 -0700447 if (expected_in_ts_ == expected_codec_ts_) {
448 // If we've never resampled, we can use the input frame as-is
449 *ptr_out = &in_frame;
450 } else {
451 // Otherwise we'll need to alter the timestamp. Since in_frame is const,
452 // we'll have to make a copy of it.
453 preprocess_frame_.CopyFrom(in_frame);
454 preprocess_frame_.timestamp_ = expected_codec_ts_;
455 *ptr_out = &preprocess_frame_;
456 }
457
kwibergc13ded52016-06-17 06:00:45 -0700458 expected_in_ts_ += static_cast<uint32_t>(in_frame.samples_per_channel_);
459 expected_codec_ts_ += static_cast<uint32_t>(in_frame.samples_per_channel_);
kwibergc13ded52016-06-17 06:00:45 -0700460 return 0;
461 }
462
463 *ptr_out = &preprocess_frame_;
464 preprocess_frame_.num_channels_ = in_frame.num_channels_;
Per Åhgren4dd56a32019-11-19 21:00:59 +0100465 preprocess_frame_.samples_per_channel_ = in_frame.samples_per_channel_;
466 std::array<int16_t, WEBRTC_10MS_PCM_AUDIO> audio;
yujo36b1a5f2017-06-12 12:45:32 -0700467 const int16_t* src_ptr_audio = in_frame.data();
kwibergc13ded52016-06-17 06:00:45 -0700468 if (down_mix) {
469 // If a resampling is required the output of a down-mix is written into a
470 // local buffer, otherwise, it will be written to the output frame.
Yves Gerey665174f2018-06-19 15:03:05 +0200471 int16_t* dest_ptr_audio =
Per Åhgren4dd56a32019-11-19 21:00:59 +0100472 resample ? audio.data() : preprocess_frame_.mutable_data();
473 RTC_DCHECK_GE(audio.size(), in_frame.samples_per_channel_);
474 DownMixFrame(in_frame,
475 rtc::ArrayView<int16_t>(
476 dest_ptr_audio, preprocess_frame_.samples_per_channel_));
kwibergc13ded52016-06-17 06:00:45 -0700477 preprocess_frame_.num_channels_ = 1;
478 // Set the input of the resampler is the down-mixed signal.
Per Åhgren4dd56a32019-11-19 21:00:59 +0100479 src_ptr_audio = audio.data();
kwibergc13ded52016-06-17 06:00:45 -0700480 }
481
482 preprocess_frame_.timestamp_ = expected_codec_ts_;
kwibergc13ded52016-06-17 06:00:45 -0700483 preprocess_frame_.sample_rate_hz_ = in_frame.sample_rate_hz_;
484 // If it is required, we have to do a resampling.
485 if (resample) {
486 // The result of the resampler is written to output frame.
yujo36b1a5f2017-06-12 12:45:32 -0700487 int16_t* dest_ptr_audio = preprocess_frame_.mutable_data();
kwibergc13ded52016-06-17 06:00:45 -0700488
489 int samples_per_channel = resampler_.Resample10Msec(
490 src_ptr_audio, in_frame.sample_rate_hz_, encoder_stack_->SampleRateHz(),
491 preprocess_frame_.num_channels_, AudioFrame::kMaxDataSizeSamples,
492 dest_ptr_audio);
493
494 if (samples_per_channel < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100495 RTC_LOG(LS_ERROR) << "Cannot add 10 ms audio, resampling failed";
kwibergc13ded52016-06-17 06:00:45 -0700496 return -1;
497 }
498 preprocess_frame_.samples_per_channel_ =
499 static_cast<size_t>(samples_per_channel);
500 preprocess_frame_.sample_rate_hz_ = encoder_stack_->SampleRateHz();
501 }
502
503 expected_codec_ts_ +=
504 static_cast<uint32_t>(preprocess_frame_.samples_per_channel_);
505 expected_in_ts_ += static_cast<uint32_t>(in_frame.samples_per_channel_);
506
507 return 0;
508}
509
510/////////////////////////////////////////
kwibergc13ded52016-06-17 06:00:45 -0700511// (FEC) Forward Error Correction (codec internal)
512//
513
kwibergc13ded52016-06-17 06:00:45 -0700514int AudioCodingModuleImpl::SetPacketLossRate(int loss_rate) {
515 rtc::CritScope lock(&acm_crit_sect_);
516 if (HaveValidEncoder("SetPacketLossRate")) {
minyue4b9a2cb2016-11-30 06:49:59 -0800517 encoder_stack_->OnReceivedUplinkPacketLossFraction(loss_rate / 100.0);
kwibergc13ded52016-06-17 06:00:45 -0700518 }
519 return 0;
520}
521
522/////////////////////////////////////////
kwibergc13ded52016-06-17 06:00:45 -0700523// Receiver
524//
525
526int AudioCodingModuleImpl::InitializeReceiver() {
527 rtc::CritScope lock(&acm_crit_sect_);
528 return InitializeReceiverSafe();
529}
530
531// Initialize receiver, resets codec database etc.
532int AudioCodingModuleImpl::InitializeReceiverSafe() {
533 // If the receiver is already initialized then we want to destroy any
534 // existing decoders. After a call to this function, we should have a clean
535 // start-up.
kwiberg6b19b562016-09-20 04:02:25 -0700536 if (receiver_initialized_)
537 receiver_.RemoveAllCodecs();
kwibergc13ded52016-06-17 06:00:45 -0700538 receiver_.FlushBuffers();
539
kwibergc13ded52016-06-17 06:00:45 -0700540 receiver_initialized_ = true;
541 return 0;
542}
543
kwiberg1c07c702017-03-27 07:15:49 -0700544void AudioCodingModuleImpl::SetReceiveCodecs(
545 const std::map<int, SdpAudioFormat>& codecs) {
546 rtc::CritScope lock(&acm_crit_sect_);
547 receiver_.SetCodecs(codecs);
548}
549
kwibergc13ded52016-06-17 06:00:45 -0700550// Incoming packet from network parsed and ready for decode.
551int AudioCodingModuleImpl::IncomingPacket(const uint8_t* incoming_payload,
552 const size_t payload_length,
Niels Möllerafb5dbb2019-02-15 15:21:47 +0100553 const RTPHeader& rtp_header) {
henrik.lundinb8c55b12017-05-10 07:38:01 -0700554 RTC_DCHECK_EQ(payload_length == 0, incoming_payload == nullptr);
kwibergc13ded52016-06-17 06:00:45 -0700555 return receiver_.InsertPacket(
556 rtp_header,
557 rtc::ArrayView<const uint8_t>(incoming_payload, payload_length));
558}
559
kwibergc13ded52016-06-17 06:00:45 -0700560// Get 10 milliseconds of raw audio data to play out.
561// Automatic resample to the requested frequency.
562int AudioCodingModuleImpl::PlayoutData10Ms(int desired_freq_hz,
563 AudioFrame* audio_frame,
564 bool* muted) {
565 // GetAudio always returns 10 ms, at the requested sample rate.
566 if (receiver_.GetAudio(desired_freq_hz, audio_frame, muted) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100567 RTC_LOG(LS_ERROR) << "PlayoutData failed, RecOut Failed";
kwibergc13ded52016-06-17 06:00:45 -0700568 return -1;
569 }
kwibergc13ded52016-06-17 06:00:45 -0700570 return 0;
571}
572
kwibergc13ded52016-06-17 06:00:45 -0700573/////////////////////////////////////////
574// Statistics
575//
576
577// TODO(turajs) change the return value to void. Also change the corresponding
578// NetEq function.
579int AudioCodingModuleImpl::GetNetworkStatistics(NetworkStatistics* statistics) {
580 receiver_.GetNetworkStatistics(statistics);
581 return 0;
582}
583
kwibergc13ded52016-06-17 06:00:45 -0700584bool AudioCodingModuleImpl::HaveValidEncoder(const char* caller_name) const {
585 if (!encoder_stack_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100586 RTC_LOG(LS_ERROR) << caller_name << " failed: No send codec is registered.";
kwibergc13ded52016-06-17 06:00:45 -0700587 return false;
588 }
589 return true;
590}
591
ivoce1198e02017-09-08 08:13:19 -0700592ANAStats AudioCodingModuleImpl::GetANAStats() const {
593 rtc::CritScope lock(&acm_crit_sect_);
594 if (encoder_stack_)
595 return encoder_stack_->GetANAStats();
596 // If no encoder is set, return default stats.
597 return ANAStats();
598}
599
kwibergc13ded52016-06-17 06:00:45 -0700600} // namespace
601
Karl Wiberg5817d3d2018-04-06 10:06:42 +0200602AudioCodingModule::Config::Config(
603 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory)
604 : neteq_config(),
605 clock(Clock::GetRealTimeClock()),
606 decoder_factory(decoder_factory) {
kwiberg36a43882016-08-29 05:33:32 -0700607 // Post-decode VAD is disabled by default in NetEq, however, Audio
608 // Conference Mixer relies on VAD decisions and fails without them.
609 neteq_config.enable_post_decode_vad = true;
610}
611
612AudioCodingModule::Config::Config(const Config&) = default;
613AudioCodingModule::Config::~Config() = default;
614
Henrik Lundin64dad832015-05-11 12:44:23 +0200615AudioCodingModule* AudioCodingModule::Create(const Config& config) {
kwibergc13ded52016-06-17 06:00:45 -0700616 return new AudioCodingModuleImpl(config);
turaj@webrtc.org7959e162013-09-12 18:30:26 +0000617}
618
turaj@webrtc.org7959e162013-09-12 18:30:26 +0000619} // namespace webrtc