blob: b742a824a9cd82ea2b93b6122b9003063b1a3d7b [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
Jonathan Yu36344a02017-07-30 01:55:34 -070013#include <algorithm>
Yves Gerey988cc082018-10-23 12:03:01 +020014#include <cstdint>
Jonathan Yu36344a02017-07-30 01:55:34 -070015
Niels Möller2edab4c2018-10-22 09:48:08 +020016#include "absl/strings/match.h"
Yves Gerey988cc082018-10-23 12:03:01 +020017#include "api/array_view.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020018#include "modules/audio_coding/acm2/acm_receiver.h"
Per Åhgren4dd56a32019-11-19 21:00:59 +010019#include "modules/audio_coding/acm2/acm_remixing.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020020#include "modules/audio_coding/acm2/acm_resampler.h"
Fredrik Solenbergbbf21a32018-04-12 22:44:09 +020021#include "modules/include/module_common_types.h"
Yves Gerey988cc082018-10-23 12:03:01 +020022#include "modules/include/module_common_types_public.h"
23#include "rtc_base/buffer.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020024#include "rtc_base/checks.h"
25#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010026#include "rtc_base/numerics/safe_conversions.h"
Markus Handell0df0fae2020-07-07 15:53:34 +020027#include "rtc_base/synchronization/mutex.h"
Yves Gerey988cc082018-10-23 12:03:01 +020028#include "rtc_base/thread_annotations.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020029#include "system_wrappers/include/metrics.h"
turaj@webrtc.org7959e162013-09-12 18:30:26 +000030
31namespace webrtc {
32
kwibergc13ded52016-06-17 06:00:45 -070033namespace {
34
Per Åhgren4f2e9402019-10-04 11:06:15 +020035// Initial size for the buffer in InputBuffer. This matches 6 channels of 10 ms
36// 48 kHz data.
37constexpr size_t kInitialInputDataBufferSize = 6 * 480;
38
Per Åhgrend82a02c2020-03-12 11:53:30 +010039constexpr int32_t kMaxInputSampleRateHz = 192000;
40
kwibergc13ded52016-06-17 06:00:45 -070041class AudioCodingModuleImpl final : public AudioCodingModule {
42 public:
43 explicit AudioCodingModuleImpl(const AudioCodingModule::Config& config);
44 ~AudioCodingModuleImpl() override;
45
46 /////////////////////////////////////////
47 // Sender
48 //
49
kwiberg24c7c122016-09-28 11:57:10 -070050 void ModifyEncoder(rtc::FunctionView<void(std::unique_ptr<AudioEncoder>*)>
51 modifier) override;
kwibergc13ded52016-06-17 06:00:45 -070052
kwibergc13ded52016-06-17 06:00:45 -070053 // Register a transport callback which will be
54 // called to deliver the encoded buffers.
55 int RegisterTransportCallback(AudioPacketizationCallback* transport) override;
56
57 // Add 10 ms of raw (PCM) audio data to the encoder.
58 int Add10MsData(const AudioFrame& audio_frame) override;
59
60 /////////////////////////////////////////
kwibergc13ded52016-06-17 06:00:45 -070061 // (FEC) Forward Error Correction (codec internal)
62 //
63
kwibergc13ded52016-06-17 06:00:45 -070064 // Set target packet loss rate
65 int SetPacketLossRate(int loss_rate) override;
66
67 /////////////////////////////////////////
kwibergc13ded52016-06-17 06:00:45 -070068 // Receiver
69 //
70
71 // Initialize receiver, resets codec database etc.
72 int InitializeReceiver() override;
73
kwiberg1c07c702017-03-27 07:15:49 -070074 void SetReceiveCodecs(const std::map<int, SdpAudioFormat>& codecs) override;
75
kwibergc13ded52016-06-17 06:00:45 -070076 // Incoming packet from network parsed and ready for decode.
77 int IncomingPacket(const uint8_t* incoming_payload,
78 const size_t payload_length,
Niels Möllerafb5dbb2019-02-15 15:21:47 +010079 const RTPHeader& rtp_info) override;
kwibergc13ded52016-06-17 06:00:45 -070080
kwibergc13ded52016-06-17 06:00:45 -070081 // Get 10 milliseconds of raw audio data to play out, and
82 // automatic resample to the requested frequency if > 0.
83 int PlayoutData10Ms(int desired_freq_hz,
84 AudioFrame* audio_frame,
85 bool* muted) override;
kwibergc13ded52016-06-17 06:00:45 -070086
87 /////////////////////////////////////////
88 // Statistics
89 //
90
91 int GetNetworkStatistics(NetworkStatistics* statistics) override;
92
ivoce1198e02017-09-08 08:13:19 -070093 ANAStats GetANAStats() const override;
94
Jakob Ivarssonbf087452021-11-11 13:43:49 +010095 int GetTargetBitrate() const override;
96
kwibergc13ded52016-06-17 06:00:45 -070097 private:
98 struct InputData {
Per Åhgren4f2e9402019-10-04 11:06:15 +020099 InputData() : buffer(kInitialInputDataBufferSize) {}
kwibergc13ded52016-06-17 06:00:45 -0700100 uint32_t input_timestamp;
101 const int16_t* audio;
102 size_t length_per_channel;
103 size_t audio_channel;
104 // If a re-mix is required (up or down), this buffer will store a re-mixed
105 // version of the input.
Per Åhgren4f2e9402019-10-04 11:06:15 +0200106 std::vector<int16_t> buffer;
kwibergc13ded52016-06-17 06:00:45 -0700107 };
108
Markus Handell0df0fae2020-07-07 15:53:34 +0200109 InputData input_data_ RTC_GUARDED_BY(acm_mutex_);
Per Åhgren4f2e9402019-10-04 11:06:15 +0200110
kwibergc13ded52016-06-17 06:00:45 -0700111 // This member class writes values to the named UMA histogram, but only if
112 // the value has changed since the last time (and always for the first call).
113 class ChangeLogger {
114 public:
115 explicit ChangeLogger(const std::string& histogram_name)
116 : histogram_name_(histogram_name) {}
117 // Logs the new value if it is different from the last logged value, or if
118 // this is the first call.
119 void MaybeLog(int value);
120
121 private:
122 int last_value_ = 0;
123 int first_time_ = true;
124 const std::string histogram_name_;
125 };
126
kwibergc13ded52016-06-17 06:00:45 -0700127 int Add10MsDataInternal(const AudioFrame& audio_frame, InputData* input_data)
Markus Handell0df0fae2020-07-07 15:53:34 +0200128 RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_mutex_);
Minyue Lidea73ee2020-02-18 15:45:41 +0100129
Artem Titovd00ce742021-07-28 20:00:17 +0200130 // TODO(bugs.webrtc.org/10739): change `absolute_capture_timestamp_ms` to
Minyue Lidea73ee2020-02-18 15:45:41 +0100131 // int64_t when it always receives a valid value.
132 int Encode(const InputData& input_data,
133 absl::optional<int64_t> absolute_capture_timestamp_ms)
Markus Handell0df0fae2020-07-07 15:53:34 +0200134 RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_mutex_);
kwibergc13ded52016-06-17 06:00:45 -0700135
Markus Handell0df0fae2020-07-07 15:53:34 +0200136 int InitializeReceiverSafe() RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_mutex_);
kwibergc13ded52016-06-17 06:00:45 -0700137
138 bool HaveValidEncoder(const char* caller_name) const
Markus Handell0df0fae2020-07-07 15:53:34 +0200139 RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_mutex_);
kwibergc13ded52016-06-17 06:00:45 -0700140
141 // Preprocessing of input audio, including resampling and down-mixing if
142 // required, before pushing audio into encoder's buffer.
143 //
144 // in_frame: input audio-frame
145 // ptr_out: pointer to output audio_frame. If no preprocessing is required
Artem Titovd00ce742021-07-28 20:00:17 +0200146 // `ptr_out` will be pointing to `in_frame`, otherwise pointing to
147 // `preprocess_frame_`.
kwibergc13ded52016-06-17 06:00:45 -0700148 //
149 // Return value:
150 // -1: if encountering an error.
151 // 0: otherwise.
152 int PreprocessToAddData(const AudioFrame& in_frame,
153 const AudioFrame** ptr_out)
Markus Handell0df0fae2020-07-07 15:53:34 +0200154 RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_mutex_);
kwibergc13ded52016-06-17 06:00:45 -0700155
156 // Change required states after starting to receive the codec corresponding
Artem Titovd00ce742021-07-28 20:00:17 +0200157 // to `index`.
kwibergc13ded52016-06-17 06:00:45 -0700158 int UpdateUponReceivingCodec(int index);
159
Markus Handell0df0fae2020-07-07 15:53:34 +0200160 mutable Mutex acm_mutex_;
161 rtc::Buffer encode_buffer_ RTC_GUARDED_BY(acm_mutex_);
162 uint32_t expected_codec_ts_ RTC_GUARDED_BY(acm_mutex_);
163 uint32_t expected_in_ts_ RTC_GUARDED_BY(acm_mutex_);
164 acm2::ACMResampler resampler_ RTC_GUARDED_BY(acm_mutex_);
kwibergc13ded52016-06-17 06:00:45 -0700165 acm2::AcmReceiver receiver_; // AcmReceiver has it's own internal lock.
Markus Handell0df0fae2020-07-07 15:53:34 +0200166 ChangeLogger bitrate_logger_ RTC_GUARDED_BY(acm_mutex_);
kwibergc13ded52016-06-17 06:00:45 -0700167
Karl Wiberg49c33ce2018-11-12 14:21:58 +0100168 // Current encoder stack, provided by a call to RegisterEncoder.
Markus Handell0df0fae2020-07-07 15:53:34 +0200169 std::unique_ptr<AudioEncoder> encoder_stack_ RTC_GUARDED_BY(acm_mutex_);
kwibergc13ded52016-06-17 06:00:45 -0700170
kwibergc13ded52016-06-17 06:00:45 -0700171 // This is to keep track of CN instances where we can send DTMFs.
Markus Handell0df0fae2020-07-07 15:53:34 +0200172 uint8_t previous_pltype_ RTC_GUARDED_BY(acm_mutex_);
kwibergc13ded52016-06-17 06:00:45 -0700173
Markus Handell0df0fae2020-07-07 15:53:34 +0200174 bool receiver_initialized_ RTC_GUARDED_BY(acm_mutex_);
kwibergc13ded52016-06-17 06:00:45 -0700175
Markus Handell0df0fae2020-07-07 15:53:34 +0200176 AudioFrame preprocess_frame_ RTC_GUARDED_BY(acm_mutex_);
177 bool first_10ms_data_ RTC_GUARDED_BY(acm_mutex_);
kwibergc13ded52016-06-17 06:00:45 -0700178
Markus Handell0df0fae2020-07-07 15:53:34 +0200179 bool first_frame_ RTC_GUARDED_BY(acm_mutex_);
180 uint32_t last_timestamp_ RTC_GUARDED_BY(acm_mutex_);
181 uint32_t last_rtp_timestamp_ RTC_GUARDED_BY(acm_mutex_);
kwibergc13ded52016-06-17 06:00:45 -0700182
Markus Handell0df0fae2020-07-07 15:53:34 +0200183 Mutex callback_mutex_;
kwibergc13ded52016-06-17 06:00:45 -0700184 AudioPacketizationCallback* packetization_callback_
Markus Handell0df0fae2020-07-07 15:53:34 +0200185 RTC_GUARDED_BY(callback_mutex_);
kwibergc13ded52016-06-17 06:00:45 -0700186
187 int codec_histogram_bins_log_[static_cast<size_t>(
188 AudioEncoder::CodecType::kMaxLoggedAudioCodecTypes)];
189 int number_of_consecutive_empty_packets_;
190};
191
192// Adds a codec usage sample to the histogram.
193void UpdateCodecTypeHistogram(size_t codec_type) {
194 RTC_HISTOGRAM_ENUMERATION(
195 "WebRTC.Audio.Encoder.CodecType", static_cast<int>(codec_type),
196 static_cast<int>(
197 webrtc::AudioEncoder::CodecType::kMaxLoggedAudioCodecTypes));
198}
199
kwibergc13ded52016-06-17 06:00:45 -0700200void AudioCodingModuleImpl::ChangeLogger::MaybeLog(int value) {
201 if (value != last_value_ || first_time_) {
202 first_time_ = false;
203 last_value_ = value;
204 RTC_HISTOGRAM_COUNTS_SPARSE_100(histogram_name_, value);
205 }
206}
207
208AudioCodingModuleImpl::AudioCodingModuleImpl(
209 const AudioCodingModule::Config& config)
solenbergc7b4a452017-09-28 07:37:11 -0700210 : expected_codec_ts_(0xD87F3F9F),
kwibergc13ded52016-06-17 06:00:45 -0700211 expected_in_ts_(0xD87F3F9F),
212 receiver_(config),
213 bitrate_logger_("WebRTC.Audio.TargetBitrateInKbps"),
kwibergc13ded52016-06-17 06:00:45 -0700214 encoder_stack_(nullptr),
215 previous_pltype_(255),
216 receiver_initialized_(false),
217 first_10ms_data_(false),
218 first_frame_(true),
219 packetization_callback_(NULL),
kwibergc13ded52016-06-17 06:00:45 -0700220 codec_histogram_bins_log_(),
221 number_of_consecutive_empty_packets_(0) {
222 if (InitializeReceiverSafe() < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100223 RTC_LOG(LS_ERROR) << "Cannot initialize receiver";
kwibergc13ded52016-06-17 06:00:45 -0700224 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100225 RTC_LOG(LS_INFO) << "Created";
kwibergc13ded52016-06-17 06:00:45 -0700226}
227
228AudioCodingModuleImpl::~AudioCodingModuleImpl() = default;
229
Minyue Lidea73ee2020-02-18 15:45:41 +0100230int32_t AudioCodingModuleImpl::Encode(
231 const InputData& input_data,
232 absl::optional<int64_t> absolute_capture_timestamp_ms) {
233 // TODO(bugs.webrtc.org/10739): add dcheck that
Artem Titovcfea2182021-08-10 01:22:31 +0200234 // `audio_frame.absolute_capture_timestamp_ms()` always has a value.
kwibergc13ded52016-06-17 06:00:45 -0700235 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 Liff0e4db2020-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 {
Markus Handell0df0fae2020-07-07 15:53:34 +0200302 MutexLock lock(&callback_mutex_);
kwibergc13ded52016-06-17 06:00:45 -0700303 if (packetization_callback_) {
304 packetization_callback_->SendData(
305 frame_type, encoded_info.payload_type, encoded_info.encoded_timestamp,
Minyue Liff0e4db2020-01-23 13:45:50 +0100306 encode_buffer_.data(), encode_buffer_.size(),
Minyue Lidea73ee2020-02-18 15:45:41 +0100307 absolute_capture_timestamp_ms.value_or(-1));
kwibergc13ded52016-06-17 06:00:45 -0700308 }
kwibergc13ded52016-06-17 06:00:45 -0700309 }
310 previous_pltype_ = encoded_info.payload_type;
311 return static_cast<int32_t>(encode_buffer_.size());
312}
313
314/////////////////////////////////////////
315// Sender
316//
317
kwibergc13ded52016-06-17 06:00:45 -0700318void AudioCodingModuleImpl::ModifyEncoder(
kwiberg24c7c122016-09-28 11:57:10 -0700319 rtc::FunctionView<void(std::unique_ptr<AudioEncoder>*)> modifier) {
Markus Handell0df0fae2020-07-07 15:53:34 +0200320 MutexLock lock(&acm_mutex_);
kwibergc13ded52016-06-17 06:00:45 -0700321 modifier(&encoder_stack_);
322}
323
kwibergc13ded52016-06-17 06:00:45 -0700324// Register a transport callback which will be called to deliver
325// the encoded buffers.
326int AudioCodingModuleImpl::RegisterTransportCallback(
327 AudioPacketizationCallback* transport) {
Markus Handell0df0fae2020-07-07 15:53:34 +0200328 MutexLock lock(&callback_mutex_);
kwibergc13ded52016-06-17 06:00:45 -0700329 packetization_callback_ = transport;
330 return 0;
331}
332
333// Add 10MS of raw (PCM) audio data to the encoder.
334int AudioCodingModuleImpl::Add10MsData(const AudioFrame& audio_frame) {
Markus Handell0df0fae2020-07-07 15:53:34 +0200335 MutexLock lock(&acm_mutex_);
Per Åhgren4f2e9402019-10-04 11:06:15 +0200336 int r = Add10MsDataInternal(audio_frame, &input_data_);
Minyue Lidea73ee2020-02-18 15:45:41 +0100337 // TODO(bugs.webrtc.org/10739): add dcheck that
Artem Titovcfea2182021-08-10 01:22:31 +0200338 // `audio_frame.absolute_capture_timestamp_ms()` always has a value.
Minyue Lidea73ee2020-02-18 15:45:41 +0100339 return r < 0
340 ? r
341 : Encode(input_data_, audio_frame.absolute_capture_timestamp_ms());
kwibergc13ded52016-06-17 06:00:45 -0700342}
343
344int AudioCodingModuleImpl::Add10MsDataInternal(const AudioFrame& audio_frame,
345 InputData* input_data) {
346 if (audio_frame.samples_per_channel_ == 0) {
Mirko Bonadei25ab3222021-07-08 20:08:20 +0200347 RTC_NOTREACHED();
Mirko Bonadei675513b2017-11-09 11:09:25 +0100348 RTC_LOG(LS_ERROR) << "Cannot Add 10 ms audio, payload length is zero";
kwibergc13ded52016-06-17 06:00:45 -0700349 return -1;
350 }
351
Per Åhgrend82a02c2020-03-12 11:53:30 +0100352 if (audio_frame.sample_rate_hz_ > kMaxInputSampleRateHz) {
Mirko Bonadei25ab3222021-07-08 20:08:20 +0200353 RTC_NOTREACHED();
Mirko Bonadei675513b2017-11-09 11:09:25 +0100354 RTC_LOG(LS_ERROR) << "Cannot Add 10 ms audio, input frequency not valid";
kwibergc13ded52016-06-17 06:00:45 -0700355 return -1;
356 }
357
358 // If the length and frequency matches. We currently just support raw PCM.
359 if (static_cast<size_t>(audio_frame.sample_rate_hz_ / 100) !=
360 audio_frame.samples_per_channel_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100361 RTC_LOG(LS_ERROR)
Alex Loiko300ec8c2017-05-30 17:23:28 +0200362 << "Cannot Add 10 ms audio, input frequency and length doesn't match";
kwibergc13ded52016-06-17 06:00:45 -0700363 return -1;
364 }
365
Alex Loiko65438812019-02-22 10:13:44 +0100366 if (audio_frame.num_channels_ != 1 && audio_frame.num_channels_ != 2 &&
367 audio_frame.num_channels_ != 4 && audio_frame.num_channels_ != 6 &&
368 audio_frame.num_channels_ != 8) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100369 RTC_LOG(LS_ERROR) << "Cannot Add 10 ms audio, invalid number of channels.";
kwibergc13ded52016-06-17 06:00:45 -0700370 return -1;
371 }
372
373 // Do we have a codec registered?
374 if (!HaveValidEncoder("Add10MsData")) {
375 return -1;
376 }
377
378 const AudioFrame* ptr_frame;
379 // Perform a resampling, also down-mix if it is required and can be
380 // performed before resampling (a down mix prior to resampling will take
381 // place if both primary and secondary encoders are mono and input is in
382 // stereo).
383 if (PreprocessToAddData(audio_frame, &ptr_frame) < 0) {
384 return -1;
385 }
386
387 // Check whether we need an up-mix or down-mix?
388 const size_t current_num_channels = encoder_stack_->NumChannels();
389 const bool same_num_channels =
390 ptr_frame->num_channels_ == current_num_channels;
391
yujo36b1a5f2017-06-12 12:45:32 -0700392 // TODO(yujo): Skip encode of muted frames.
kwibergc13ded52016-06-17 06:00:45 -0700393 input_data->input_timestamp = ptr_frame->timestamp_;
kwibergc13ded52016-06-17 06:00:45 -0700394 input_data->length_per_channel = ptr_frame->samples_per_channel_;
395 input_data->audio_channel = current_num_channels;
396
Per Åhgren4f2e9402019-10-04 11:06:15 +0200397 if (!same_num_channels) {
398 // Remixes the input frame to the output data and in the process resize the
399 // output data if needed.
Per Åhgren4dd56a32019-11-19 21:00:59 +0100400 ReMixFrame(*ptr_frame, current_num_channels, &input_data->buffer);
Per Åhgren4f2e9402019-10-04 11:06:15 +0200401
Artem Titovd00ce742021-07-28 20:00:17 +0200402 // For pushing data to primary, point the `ptr_audio` to correct buffer.
Per Åhgren4f2e9402019-10-04 11:06:15 +0200403 input_data->audio = input_data->buffer.data();
404 RTC_DCHECK_GE(input_data->buffer.size(),
405 input_data->length_per_channel * input_data->audio_channel);
406 } else {
407 // When adding data to encoders this pointer is pointing to an audio buffer
408 // with correct number of channels.
409 input_data->audio = ptr_frame->data();
410 }
411
kwibergc13ded52016-06-17 06:00:45 -0700412 return 0;
413}
414
415// Perform a resampling and down-mix if required. We down-mix only if
416// encoder is mono and input is stereo. In case of dual-streaming, both
417// encoders has to be mono for down-mix to take place.
418// |*ptr_out| will point to the pre-processed audio-frame. If no pre-processing
Artem Titovd00ce742021-07-28 20:00:17 +0200419// is required, |*ptr_out| points to `in_frame`.
yujo36b1a5f2017-06-12 12:45:32 -0700420// TODO(yujo): Make this more efficient for muted frames.
kwibergc13ded52016-06-17 06:00:45 -0700421int AudioCodingModuleImpl::PreprocessToAddData(const AudioFrame& in_frame,
422 const AudioFrame** ptr_out) {
423 const bool resample =
424 in_frame.sample_rate_hz_ != encoder_stack_->SampleRateHz();
425
426 // This variable is true if primary codec and secondary codec (if exists)
427 // are both mono and input is stereo.
428 // TODO(henrik.lundin): This condition should probably be
429 // in_frame.num_channels_ > encoder_stack_->NumChannels()
430 const bool down_mix =
431 in_frame.num_channels_ == 2 && encoder_stack_->NumChannels() == 1;
432
433 if (!first_10ms_data_) {
434 expected_in_ts_ = in_frame.timestamp_;
435 expected_codec_ts_ = in_frame.timestamp_;
436 first_10ms_data_ = true;
437 } else if (in_frame.timestamp_ != expected_in_ts_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100438 RTC_LOG(LS_WARNING) << "Unexpected input timestamp: " << in_frame.timestamp_
439 << ", expected: " << expected_in_ts_;
kwibergc13ded52016-06-17 06:00:45 -0700440 expected_codec_ts_ +=
441 (in_frame.timestamp_ - expected_in_ts_) *
442 static_cast<uint32_t>(
443 static_cast<double>(encoder_stack_->SampleRateHz()) /
444 static_cast<double>(in_frame.sample_rate_hz_));
445 expected_in_ts_ = in_frame.timestamp_;
446 }
447
kwibergc13ded52016-06-17 06:00:45 -0700448 if (!down_mix && !resample) {
449 // No pre-processing is required.
ossu63fb95a2016-07-06 09:34:22 -0700450 if (expected_in_ts_ == expected_codec_ts_) {
451 // If we've never resampled, we can use the input frame as-is
452 *ptr_out = &in_frame;
453 } else {
454 // Otherwise we'll need to alter the timestamp. Since in_frame is const,
455 // we'll have to make a copy of it.
456 preprocess_frame_.CopyFrom(in_frame);
457 preprocess_frame_.timestamp_ = expected_codec_ts_;
458 *ptr_out = &preprocess_frame_;
459 }
460
kwibergc13ded52016-06-17 06:00:45 -0700461 expected_in_ts_ += static_cast<uint32_t>(in_frame.samples_per_channel_);
462 expected_codec_ts_ += static_cast<uint32_t>(in_frame.samples_per_channel_);
kwibergc13ded52016-06-17 06:00:45 -0700463 return 0;
464 }
465
466 *ptr_out = &preprocess_frame_;
467 preprocess_frame_.num_channels_ = in_frame.num_channels_;
Per Åhgren4dd56a32019-11-19 21:00:59 +0100468 preprocess_frame_.samples_per_channel_ = in_frame.samples_per_channel_;
Per Åhgrend82a02c2020-03-12 11:53:30 +0100469 std::array<int16_t, AudioFrame::kMaxDataSizeSamples> audio;
470 const int16_t* src_ptr_audio;
kwibergc13ded52016-06-17 06:00:45 -0700471 if (down_mix) {
Per Åhgrend82a02c2020-03-12 11:53:30 +0100472 // If a resampling is required, the output of a down-mix is written into a
kwibergc13ded52016-06-17 06:00:45 -0700473 // local buffer, otherwise, it will be written to the output frame.
Yves Gerey665174f2018-06-19 15:03:05 +0200474 int16_t* dest_ptr_audio =
Per Åhgren4dd56a32019-11-19 21:00:59 +0100475 resample ? audio.data() : preprocess_frame_.mutable_data();
Per Åhgrend82a02c2020-03-12 11:53:30 +0100476 RTC_DCHECK_GE(audio.size(), preprocess_frame_.samples_per_channel_);
Per Åhgren4dd56a32019-11-19 21:00:59 +0100477 RTC_DCHECK_GE(audio.size(), in_frame.samples_per_channel_);
478 DownMixFrame(in_frame,
479 rtc::ArrayView<int16_t>(
480 dest_ptr_audio, preprocess_frame_.samples_per_channel_));
kwibergc13ded52016-06-17 06:00:45 -0700481 preprocess_frame_.num_channels_ = 1;
Per Åhgrend82a02c2020-03-12 11:53:30 +0100482
483 // Set the input of the resampler to the down-mixed signal.
Per Åhgren4dd56a32019-11-19 21:00:59 +0100484 src_ptr_audio = audio.data();
Per Åhgrend82a02c2020-03-12 11:53:30 +0100485 } else {
486 // Set the input of the resampler to the original data.
487 src_ptr_audio = in_frame.data();
kwibergc13ded52016-06-17 06:00:45 -0700488 }
489
490 preprocess_frame_.timestamp_ = expected_codec_ts_;
kwibergc13ded52016-06-17 06:00:45 -0700491 preprocess_frame_.sample_rate_hz_ = in_frame.sample_rate_hz_;
492 // If it is required, we have to do a resampling.
493 if (resample) {
494 // The result of the resampler is written to output frame.
yujo36b1a5f2017-06-12 12:45:32 -0700495 int16_t* dest_ptr_audio = preprocess_frame_.mutable_data();
kwibergc13ded52016-06-17 06:00:45 -0700496
497 int samples_per_channel = resampler_.Resample10Msec(
498 src_ptr_audio, in_frame.sample_rate_hz_, encoder_stack_->SampleRateHz(),
499 preprocess_frame_.num_channels_, AudioFrame::kMaxDataSizeSamples,
500 dest_ptr_audio);
501
502 if (samples_per_channel < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100503 RTC_LOG(LS_ERROR) << "Cannot add 10 ms audio, resampling failed";
kwibergc13ded52016-06-17 06:00:45 -0700504 return -1;
505 }
506 preprocess_frame_.samples_per_channel_ =
507 static_cast<size_t>(samples_per_channel);
508 preprocess_frame_.sample_rate_hz_ = encoder_stack_->SampleRateHz();
509 }
510
511 expected_codec_ts_ +=
512 static_cast<uint32_t>(preprocess_frame_.samples_per_channel_);
513 expected_in_ts_ += static_cast<uint32_t>(in_frame.samples_per_channel_);
514
515 return 0;
516}
517
518/////////////////////////////////////////
kwibergc13ded52016-06-17 06:00:45 -0700519// (FEC) Forward Error Correction (codec internal)
520//
521
kwibergc13ded52016-06-17 06:00:45 -0700522int AudioCodingModuleImpl::SetPacketLossRate(int loss_rate) {
Markus Handell0df0fae2020-07-07 15:53:34 +0200523 MutexLock lock(&acm_mutex_);
kwibergc13ded52016-06-17 06:00:45 -0700524 if (HaveValidEncoder("SetPacketLossRate")) {
minyue4b9a2cb2016-11-30 06:49:59 -0800525 encoder_stack_->OnReceivedUplinkPacketLossFraction(loss_rate / 100.0);
kwibergc13ded52016-06-17 06:00:45 -0700526 }
527 return 0;
528}
529
530/////////////////////////////////////////
kwibergc13ded52016-06-17 06:00:45 -0700531// Receiver
532//
533
534int AudioCodingModuleImpl::InitializeReceiver() {
Markus Handell0df0fae2020-07-07 15:53:34 +0200535 MutexLock lock(&acm_mutex_);
kwibergc13ded52016-06-17 06:00:45 -0700536 return InitializeReceiverSafe();
537}
538
539// Initialize receiver, resets codec database etc.
540int AudioCodingModuleImpl::InitializeReceiverSafe() {
541 // If the receiver is already initialized then we want to destroy any
542 // existing decoders. After a call to this function, we should have a clean
543 // start-up.
kwiberg6b19b562016-09-20 04:02:25 -0700544 if (receiver_initialized_)
545 receiver_.RemoveAllCodecs();
kwibergc13ded52016-06-17 06:00:45 -0700546 receiver_.FlushBuffers();
547
kwibergc13ded52016-06-17 06:00:45 -0700548 receiver_initialized_ = true;
549 return 0;
550}
551
kwiberg1c07c702017-03-27 07:15:49 -0700552void AudioCodingModuleImpl::SetReceiveCodecs(
553 const std::map<int, SdpAudioFormat>& codecs) {
Markus Handell0df0fae2020-07-07 15:53:34 +0200554 MutexLock lock(&acm_mutex_);
kwiberg1c07c702017-03-27 07:15:49 -0700555 receiver_.SetCodecs(codecs);
556}
557
kwibergc13ded52016-06-17 06:00:45 -0700558// Incoming packet from network parsed and ready for decode.
559int AudioCodingModuleImpl::IncomingPacket(const uint8_t* incoming_payload,
560 const size_t payload_length,
Niels Möllerafb5dbb2019-02-15 15:21:47 +0100561 const RTPHeader& rtp_header) {
henrik.lundinb8c55b12017-05-10 07:38:01 -0700562 RTC_DCHECK_EQ(payload_length == 0, incoming_payload == nullptr);
kwibergc13ded52016-06-17 06:00:45 -0700563 return receiver_.InsertPacket(
564 rtp_header,
565 rtc::ArrayView<const uint8_t>(incoming_payload, payload_length));
566}
567
kwibergc13ded52016-06-17 06:00:45 -0700568// Get 10 milliseconds of raw audio data to play out.
569// Automatic resample to the requested frequency.
570int AudioCodingModuleImpl::PlayoutData10Ms(int desired_freq_hz,
571 AudioFrame* audio_frame,
572 bool* muted) {
573 // GetAudio always returns 10 ms, at the requested sample rate.
574 if (receiver_.GetAudio(desired_freq_hz, audio_frame, muted) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100575 RTC_LOG(LS_ERROR) << "PlayoutData failed, RecOut Failed";
kwibergc13ded52016-06-17 06:00:45 -0700576 return -1;
577 }
kwibergc13ded52016-06-17 06:00:45 -0700578 return 0;
579}
580
kwibergc13ded52016-06-17 06:00:45 -0700581/////////////////////////////////////////
582// Statistics
583//
584
585// TODO(turajs) change the return value to void. Also change the corresponding
586// NetEq function.
587int AudioCodingModuleImpl::GetNetworkStatistics(NetworkStatistics* statistics) {
588 receiver_.GetNetworkStatistics(statistics);
589 return 0;
590}
591
kwibergc13ded52016-06-17 06:00:45 -0700592bool AudioCodingModuleImpl::HaveValidEncoder(const char* caller_name) const {
593 if (!encoder_stack_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100594 RTC_LOG(LS_ERROR) << caller_name << " failed: No send codec is registered.";
kwibergc13ded52016-06-17 06:00:45 -0700595 return false;
596 }
597 return true;
598}
599
ivoce1198e02017-09-08 08:13:19 -0700600ANAStats AudioCodingModuleImpl::GetANAStats() const {
Markus Handell0df0fae2020-07-07 15:53:34 +0200601 MutexLock lock(&acm_mutex_);
ivoce1198e02017-09-08 08:13:19 -0700602 if (encoder_stack_)
603 return encoder_stack_->GetANAStats();
604 // If no encoder is set, return default stats.
605 return ANAStats();
606}
607
Jakob Ivarssonbf087452021-11-11 13:43:49 +0100608int AudioCodingModuleImpl::GetTargetBitrate() const {
609 MutexLock lock(&acm_mutex_);
610 if (!encoder_stack_) {
611 return -1;
612 }
613 return encoder_stack_->GetTargetBitrate();
614}
615
kwibergc13ded52016-06-17 06:00:45 -0700616} // namespace
617
Karl Wiberg5817d3d2018-04-06 10:06:42 +0200618AudioCodingModule::Config::Config(
619 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory)
620 : neteq_config(),
621 clock(Clock::GetRealTimeClock()),
622 decoder_factory(decoder_factory) {
kwiberg36a43882016-08-29 05:33:32 -0700623 // Post-decode VAD is disabled by default in NetEq, however, Audio
624 // Conference Mixer relies on VAD decisions and fails without them.
625 neteq_config.enable_post_decode_vad = true;
626}
627
628AudioCodingModule::Config::Config(const Config&) = default;
629AudioCodingModule::Config::~Config() = default;
630
Henrik Lundin64dad832015-05-11 12:44:23 +0200631AudioCodingModule* AudioCodingModule::Create(const Config& config) {
kwibergc13ded52016-06-17 06:00:45 -0700632 return new AudioCodingModuleImpl(config);
turaj@webrtc.org7959e162013-09-12 18:30:26 +0000633}
634
turaj@webrtc.org7959e162013-09-12 18:30:26 +0000635} // namespace webrtc