blob: d6291395a33a16925d1f9efede744e1857cce82e [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
kwibergc13ded52016-06-17 06:00:45 -070095 private:
96 struct InputData {
Per Åhgren4f2e9402019-10-04 11:06:15 +020097 InputData() : buffer(kInitialInputDataBufferSize) {}
kwibergc13ded52016-06-17 06:00:45 -070098 uint32_t input_timestamp;
99 const int16_t* audio;
100 size_t length_per_channel;
101 size_t audio_channel;
102 // If a re-mix is required (up or down), this buffer will store a re-mixed
103 // version of the input.
Per Åhgren4f2e9402019-10-04 11:06:15 +0200104 std::vector<int16_t> buffer;
kwibergc13ded52016-06-17 06:00:45 -0700105 };
106
Markus Handell0df0fae2020-07-07 15:53:34 +0200107 InputData input_data_ RTC_GUARDED_BY(acm_mutex_);
Per Åhgren4f2e9402019-10-04 11:06:15 +0200108
kwibergc13ded52016-06-17 06:00:45 -0700109 // This member class writes values to the named UMA histogram, but only if
110 // the value has changed since the last time (and always for the first call).
111 class ChangeLogger {
112 public:
113 explicit ChangeLogger(const std::string& histogram_name)
114 : histogram_name_(histogram_name) {}
115 // Logs the new value if it is different from the last logged value, or if
116 // this is the first call.
117 void MaybeLog(int value);
118
119 private:
120 int last_value_ = 0;
121 int first_time_ = true;
122 const std::string histogram_name_;
123 };
124
kwibergc13ded52016-06-17 06:00:45 -0700125 int Add10MsDataInternal(const AudioFrame& audio_frame, InputData* input_data)
Markus Handell0df0fae2020-07-07 15:53:34 +0200126 RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_mutex_);
Minyue Lidea73ee2020-02-18 15:45:41 +0100127
Artem Titovd00ce742021-07-28 20:00:17 +0200128 // TODO(bugs.webrtc.org/10739): change `absolute_capture_timestamp_ms` to
Minyue Lidea73ee2020-02-18 15:45:41 +0100129 // int64_t when it always receives a valid value.
130 int Encode(const InputData& input_data,
131 absl::optional<int64_t> absolute_capture_timestamp_ms)
Markus Handell0df0fae2020-07-07 15:53:34 +0200132 RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_mutex_);
kwibergc13ded52016-06-17 06:00:45 -0700133
Markus Handell0df0fae2020-07-07 15:53:34 +0200134 int InitializeReceiverSafe() RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_mutex_);
kwibergc13ded52016-06-17 06:00:45 -0700135
136 bool HaveValidEncoder(const char* caller_name) const
Markus Handell0df0fae2020-07-07 15:53:34 +0200137 RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_mutex_);
kwibergc13ded52016-06-17 06:00:45 -0700138
139 // Preprocessing of input audio, including resampling and down-mixing if
140 // required, before pushing audio into encoder's buffer.
141 //
142 // in_frame: input audio-frame
143 // ptr_out: pointer to output audio_frame. If no preprocessing is required
Artem Titovd00ce742021-07-28 20:00:17 +0200144 // `ptr_out` will be pointing to `in_frame`, otherwise pointing to
145 // `preprocess_frame_`.
kwibergc13ded52016-06-17 06:00:45 -0700146 //
147 // Return value:
148 // -1: if encountering an error.
149 // 0: otherwise.
150 int PreprocessToAddData(const AudioFrame& in_frame,
151 const AudioFrame** ptr_out)
Markus Handell0df0fae2020-07-07 15:53:34 +0200152 RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_mutex_);
kwibergc13ded52016-06-17 06:00:45 -0700153
154 // Change required states after starting to receive the codec corresponding
Artem Titovd00ce742021-07-28 20:00:17 +0200155 // to `index`.
kwibergc13ded52016-06-17 06:00:45 -0700156 int UpdateUponReceivingCodec(int index);
157
Markus Handell0df0fae2020-07-07 15:53:34 +0200158 mutable Mutex acm_mutex_;
159 rtc::Buffer encode_buffer_ RTC_GUARDED_BY(acm_mutex_);
160 uint32_t expected_codec_ts_ RTC_GUARDED_BY(acm_mutex_);
161 uint32_t expected_in_ts_ RTC_GUARDED_BY(acm_mutex_);
162 acm2::ACMResampler resampler_ RTC_GUARDED_BY(acm_mutex_);
kwibergc13ded52016-06-17 06:00:45 -0700163 acm2::AcmReceiver receiver_; // AcmReceiver has it's own internal lock.
Markus Handell0df0fae2020-07-07 15:53:34 +0200164 ChangeLogger bitrate_logger_ RTC_GUARDED_BY(acm_mutex_);
kwibergc13ded52016-06-17 06:00:45 -0700165
Karl Wiberg49c33ce2018-11-12 14:21:58 +0100166 // Current encoder stack, provided by a call to RegisterEncoder.
Markus Handell0df0fae2020-07-07 15:53:34 +0200167 std::unique_ptr<AudioEncoder> encoder_stack_ RTC_GUARDED_BY(acm_mutex_);
kwibergc13ded52016-06-17 06:00:45 -0700168
kwibergc13ded52016-06-17 06:00:45 -0700169 // This is to keep track of CN instances where we can send DTMFs.
Markus Handell0df0fae2020-07-07 15:53:34 +0200170 uint8_t previous_pltype_ RTC_GUARDED_BY(acm_mutex_);
kwibergc13ded52016-06-17 06:00:45 -0700171
Markus Handell0df0fae2020-07-07 15:53:34 +0200172 bool receiver_initialized_ RTC_GUARDED_BY(acm_mutex_);
kwibergc13ded52016-06-17 06:00:45 -0700173
Markus Handell0df0fae2020-07-07 15:53:34 +0200174 AudioFrame preprocess_frame_ RTC_GUARDED_BY(acm_mutex_);
175 bool first_10ms_data_ RTC_GUARDED_BY(acm_mutex_);
kwibergc13ded52016-06-17 06:00:45 -0700176
Markus Handell0df0fae2020-07-07 15:53:34 +0200177 bool first_frame_ RTC_GUARDED_BY(acm_mutex_);
178 uint32_t last_timestamp_ RTC_GUARDED_BY(acm_mutex_);
179 uint32_t last_rtp_timestamp_ RTC_GUARDED_BY(acm_mutex_);
kwibergc13ded52016-06-17 06:00:45 -0700180
Markus Handell0df0fae2020-07-07 15:53:34 +0200181 Mutex callback_mutex_;
kwibergc13ded52016-06-17 06:00:45 -0700182 AudioPacketizationCallback* packetization_callback_
Markus Handell0df0fae2020-07-07 15:53:34 +0200183 RTC_GUARDED_BY(callback_mutex_);
kwibergc13ded52016-06-17 06:00:45 -0700184
185 int codec_histogram_bins_log_[static_cast<size_t>(
186 AudioEncoder::CodecType::kMaxLoggedAudioCodecTypes)];
187 int number_of_consecutive_empty_packets_;
188};
189
190// Adds a codec usage sample to the histogram.
191void UpdateCodecTypeHistogram(size_t codec_type) {
192 RTC_HISTOGRAM_ENUMERATION(
193 "WebRTC.Audio.Encoder.CodecType", static_cast<int>(codec_type),
194 static_cast<int>(
195 webrtc::AudioEncoder::CodecType::kMaxLoggedAudioCodecTypes));
196}
197
kwibergc13ded52016-06-17 06:00:45 -0700198void AudioCodingModuleImpl::ChangeLogger::MaybeLog(int value) {
199 if (value != last_value_ || first_time_) {
200 first_time_ = false;
201 last_value_ = value;
202 RTC_HISTOGRAM_COUNTS_SPARSE_100(histogram_name_, value);
203 }
204}
205
206AudioCodingModuleImpl::AudioCodingModuleImpl(
207 const AudioCodingModule::Config& config)
solenbergc7b4a452017-09-28 07:37:11 -0700208 : expected_codec_ts_(0xD87F3F9F),
kwibergc13ded52016-06-17 06:00:45 -0700209 expected_in_ts_(0xD87F3F9F),
210 receiver_(config),
211 bitrate_logger_("WebRTC.Audio.TargetBitrateInKbps"),
kwibergc13ded52016-06-17 06:00:45 -0700212 encoder_stack_(nullptr),
213 previous_pltype_(255),
214 receiver_initialized_(false),
215 first_10ms_data_(false),
216 first_frame_(true),
217 packetization_callback_(NULL),
kwibergc13ded52016-06-17 06:00:45 -0700218 codec_histogram_bins_log_(),
219 number_of_consecutive_empty_packets_(0) {
220 if (InitializeReceiverSafe() < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100221 RTC_LOG(LS_ERROR) << "Cannot initialize receiver";
kwibergc13ded52016-06-17 06:00:45 -0700222 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100223 RTC_LOG(LS_INFO) << "Created";
kwibergc13ded52016-06-17 06:00:45 -0700224}
225
226AudioCodingModuleImpl::~AudioCodingModuleImpl() = default;
227
Minyue Lidea73ee2020-02-18 15:45:41 +0100228int32_t AudioCodingModuleImpl::Encode(
229 const InputData& input_data,
230 absl::optional<int64_t> absolute_capture_timestamp_ms) {
231 // TODO(bugs.webrtc.org/10739): add dcheck that
232 // |audio_frame.absolute_capture_timestamp_ms()| always has a value.
kwibergc13ded52016-06-17 06:00:45 -0700233 AudioEncoder::EncodedInfo encoded_info;
234 uint8_t previous_pltype;
235
236 // Check if there is an encoder before.
237 if (!HaveValidEncoder("Process"))
238 return -1;
239
Yves Gerey665174f2018-06-19 15:03:05 +0200240 if (!first_frame_) {
deadbeeffcada902016-08-24 12:45:13 -0700241 RTC_DCHECK(IsNewerTimestamp(input_data.input_timestamp, last_timestamp_))
ossu63fb95a2016-07-06 09:34:22 -0700242 << "Time should not move backwards";
243 }
244
kwibergc13ded52016-06-17 06:00:45 -0700245 // Scale the timestamp to the codec's RTP timestamp rate.
246 uint32_t rtp_timestamp =
Karl Wiberg053c3712019-05-16 15:24:17 +0200247 first_frame_
248 ? input_data.input_timestamp
249 : last_rtp_timestamp_ +
250 rtc::dchecked_cast<uint32_t>(rtc::CheckedDivExact(
251 int64_t{input_data.input_timestamp - last_timestamp_} *
252 encoder_stack_->RtpTimestampRateHz(),
253 int64_t{encoder_stack_->SampleRateHz()}));
Minyue Liff0e4db2020-01-23 13:45:50 +0100254
kwibergc13ded52016-06-17 06:00:45 -0700255 last_timestamp_ = input_data.input_timestamp;
256 last_rtp_timestamp_ = rtp_timestamp;
257 first_frame_ = false;
258
259 // Clear the buffer before reuse - encoded data will get appended.
260 encode_buffer_.Clear();
261 encoded_info = encoder_stack_->Encode(
Yves Gerey665174f2018-06-19 15:03:05 +0200262 rtp_timestamp,
263 rtc::ArrayView<const int16_t>(
264 input_data.audio,
265 input_data.audio_channel * input_data.length_per_channel),
kwibergc13ded52016-06-17 06:00:45 -0700266 &encode_buffer_);
267
268 bitrate_logger_.MaybeLog(encoder_stack_->GetTargetBitrate() / 1000);
269 if (encode_buffer_.size() == 0 && !encoded_info.send_even_if_empty) {
270 // Not enough data.
271 return 0;
272 }
273 previous_pltype = previous_pltype_; // Read it while we have the critsect.
274
275 // Log codec type to histogram once every 500 packets.
276 if (encoded_info.encoded_bytes == 0) {
277 ++number_of_consecutive_empty_packets_;
278 } else {
279 size_t codec_type = static_cast<size_t>(encoded_info.encoder_type);
280 codec_histogram_bins_log_[codec_type] +=
281 number_of_consecutive_empty_packets_ + 1;
282 number_of_consecutive_empty_packets_ = 0;
283 if (codec_histogram_bins_log_[codec_type] >= 500) {
284 codec_histogram_bins_log_[codec_type] -= 500;
285 UpdateCodecTypeHistogram(codec_type);
286 }
287 }
288
Niels Möller87e2d782019-03-07 10:18:23 +0100289 AudioFrameType frame_type;
kwibergc13ded52016-06-17 06:00:45 -0700290 if (encode_buffer_.size() == 0 && encoded_info.send_even_if_empty) {
Niels Möllerc936cb62019-03-19 14:10:16 +0100291 frame_type = AudioFrameType::kEmptyFrame;
kwibergc13ded52016-06-17 06:00:45 -0700292 encoded_info.payload_type = previous_pltype;
293 } else {
kwibergaf476c72016-11-28 15:21:39 -0800294 RTC_DCHECK_GT(encode_buffer_.size(), 0);
Niels Möllerc936cb62019-03-19 14:10:16 +0100295 frame_type = encoded_info.speech ? AudioFrameType::kAudioFrameSpeech
296 : AudioFrameType::kAudioFrameCN;
kwibergc13ded52016-06-17 06:00:45 -0700297 }
298
299 {
Markus Handell0df0fae2020-07-07 15:53:34 +0200300 MutexLock lock(&callback_mutex_);
kwibergc13ded52016-06-17 06:00:45 -0700301 if (packetization_callback_) {
302 packetization_callback_->SendData(
303 frame_type, encoded_info.payload_type, encoded_info.encoded_timestamp,
Minyue Liff0e4db2020-01-23 13:45:50 +0100304 encode_buffer_.data(), encode_buffer_.size(),
Minyue Lidea73ee2020-02-18 15:45:41 +0100305 absolute_capture_timestamp_ms.value_or(-1));
kwibergc13ded52016-06-17 06:00:45 -0700306 }
kwibergc13ded52016-06-17 06:00:45 -0700307 }
308 previous_pltype_ = encoded_info.payload_type;
309 return static_cast<int32_t>(encode_buffer_.size());
310}
311
312/////////////////////////////////////////
313// Sender
314//
315
kwibergc13ded52016-06-17 06:00:45 -0700316void AudioCodingModuleImpl::ModifyEncoder(
kwiberg24c7c122016-09-28 11:57:10 -0700317 rtc::FunctionView<void(std::unique_ptr<AudioEncoder>*)> modifier) {
Markus Handell0df0fae2020-07-07 15:53:34 +0200318 MutexLock lock(&acm_mutex_);
kwibergc13ded52016-06-17 06:00:45 -0700319 modifier(&encoder_stack_);
320}
321
kwibergc13ded52016-06-17 06:00:45 -0700322// Register a transport callback which will be called to deliver
323// the encoded buffers.
324int AudioCodingModuleImpl::RegisterTransportCallback(
325 AudioPacketizationCallback* transport) {
Markus Handell0df0fae2020-07-07 15:53:34 +0200326 MutexLock lock(&callback_mutex_);
kwibergc13ded52016-06-17 06:00:45 -0700327 packetization_callback_ = transport;
328 return 0;
329}
330
331// Add 10MS of raw (PCM) audio data to the encoder.
332int AudioCodingModuleImpl::Add10MsData(const AudioFrame& audio_frame) {
Markus Handell0df0fae2020-07-07 15:53:34 +0200333 MutexLock lock(&acm_mutex_);
Per Åhgren4f2e9402019-10-04 11:06:15 +0200334 int r = Add10MsDataInternal(audio_frame, &input_data_);
Minyue Lidea73ee2020-02-18 15:45:41 +0100335 // TODO(bugs.webrtc.org/10739): add dcheck that
336 // |audio_frame.absolute_capture_timestamp_ms()| always has a value.
337 return r < 0
338 ? r
339 : Encode(input_data_, audio_frame.absolute_capture_timestamp_ms());
kwibergc13ded52016-06-17 06:00:45 -0700340}
341
342int AudioCodingModuleImpl::Add10MsDataInternal(const AudioFrame& audio_frame,
343 InputData* input_data) {
344 if (audio_frame.samples_per_channel_ == 0) {
Mirko Bonadei25ab3222021-07-08 20:08:20 +0200345 RTC_NOTREACHED();
Mirko Bonadei675513b2017-11-09 11:09:25 +0100346 RTC_LOG(LS_ERROR) << "Cannot Add 10 ms audio, payload length is zero";
kwibergc13ded52016-06-17 06:00:45 -0700347 return -1;
348 }
349
Per Åhgrend82a02c2020-03-12 11:53:30 +0100350 if (audio_frame.sample_rate_hz_ > kMaxInputSampleRateHz) {
Mirko Bonadei25ab3222021-07-08 20:08:20 +0200351 RTC_NOTREACHED();
Mirko Bonadei675513b2017-11-09 11:09:25 +0100352 RTC_LOG(LS_ERROR) << "Cannot Add 10 ms audio, input frequency not valid";
kwibergc13ded52016-06-17 06:00:45 -0700353 return -1;
354 }
355
356 // If the length and frequency matches. We currently just support raw PCM.
357 if (static_cast<size_t>(audio_frame.sample_rate_hz_ / 100) !=
358 audio_frame.samples_per_channel_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100359 RTC_LOG(LS_ERROR)
Alex Loiko300ec8c2017-05-30 17:23:28 +0200360 << "Cannot Add 10 ms audio, input frequency and length doesn't match";
kwibergc13ded52016-06-17 06:00:45 -0700361 return -1;
362 }
363
Alex Loiko65438812019-02-22 10:13:44 +0100364 if (audio_frame.num_channels_ != 1 && audio_frame.num_channels_ != 2 &&
365 audio_frame.num_channels_ != 4 && audio_frame.num_channels_ != 6 &&
366 audio_frame.num_channels_ != 8) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100367 RTC_LOG(LS_ERROR) << "Cannot Add 10 ms audio, invalid number of channels.";
kwibergc13ded52016-06-17 06:00:45 -0700368 return -1;
369 }
370
371 // Do we have a codec registered?
372 if (!HaveValidEncoder("Add10MsData")) {
373 return -1;
374 }
375
376 const AudioFrame* ptr_frame;
377 // Perform a resampling, also down-mix if it is required and can be
378 // performed before resampling (a down mix prior to resampling will take
379 // place if both primary and secondary encoders are mono and input is in
380 // stereo).
381 if (PreprocessToAddData(audio_frame, &ptr_frame) < 0) {
382 return -1;
383 }
384
385 // Check whether we need an up-mix or down-mix?
386 const size_t current_num_channels = encoder_stack_->NumChannels();
387 const bool same_num_channels =
388 ptr_frame->num_channels_ == current_num_channels;
389
yujo36b1a5f2017-06-12 12:45:32 -0700390 // TODO(yujo): Skip encode of muted frames.
kwibergc13ded52016-06-17 06:00:45 -0700391 input_data->input_timestamp = ptr_frame->timestamp_;
kwibergc13ded52016-06-17 06:00:45 -0700392 input_data->length_per_channel = ptr_frame->samples_per_channel_;
393 input_data->audio_channel = current_num_channels;
394
Per Åhgren4f2e9402019-10-04 11:06:15 +0200395 if (!same_num_channels) {
396 // Remixes the input frame to the output data and in the process resize the
397 // output data if needed.
Per Åhgren4dd56a32019-11-19 21:00:59 +0100398 ReMixFrame(*ptr_frame, current_num_channels, &input_data->buffer);
Per Åhgren4f2e9402019-10-04 11:06:15 +0200399
Artem Titovd00ce742021-07-28 20:00:17 +0200400 // For pushing data to primary, point the `ptr_audio` to correct buffer.
Per Åhgren4f2e9402019-10-04 11:06:15 +0200401 input_data->audio = input_data->buffer.data();
402 RTC_DCHECK_GE(input_data->buffer.size(),
403 input_data->length_per_channel * input_data->audio_channel);
404 } else {
405 // When adding data to encoders this pointer is pointing to an audio buffer
406 // with correct number of channels.
407 input_data->audio = ptr_frame->data();
408 }
409
kwibergc13ded52016-06-17 06:00:45 -0700410 return 0;
411}
412
413// Perform a resampling and down-mix if required. We down-mix only if
414// encoder is mono and input is stereo. In case of dual-streaming, both
415// encoders has to be mono for down-mix to take place.
416// |*ptr_out| will point to the pre-processed audio-frame. If no pre-processing
Artem Titovd00ce742021-07-28 20:00:17 +0200417// is required, |*ptr_out| points to `in_frame`.
yujo36b1a5f2017-06-12 12:45:32 -0700418// TODO(yujo): Make this more efficient for muted frames.
kwibergc13ded52016-06-17 06:00:45 -0700419int AudioCodingModuleImpl::PreprocessToAddData(const AudioFrame& in_frame,
420 const AudioFrame** ptr_out) {
421 const bool resample =
422 in_frame.sample_rate_hz_ != encoder_stack_->SampleRateHz();
423
424 // This variable is true if primary codec and secondary codec (if exists)
425 // are both mono and input is stereo.
426 // TODO(henrik.lundin): This condition should probably be
427 // in_frame.num_channels_ > encoder_stack_->NumChannels()
428 const bool down_mix =
429 in_frame.num_channels_ == 2 && encoder_stack_->NumChannels() == 1;
430
431 if (!first_10ms_data_) {
432 expected_in_ts_ = in_frame.timestamp_;
433 expected_codec_ts_ = in_frame.timestamp_;
434 first_10ms_data_ = true;
435 } else if (in_frame.timestamp_ != expected_in_ts_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100436 RTC_LOG(LS_WARNING) << "Unexpected input timestamp: " << in_frame.timestamp_
437 << ", expected: " << expected_in_ts_;
kwibergc13ded52016-06-17 06:00:45 -0700438 expected_codec_ts_ +=
439 (in_frame.timestamp_ - expected_in_ts_) *
440 static_cast<uint32_t>(
441 static_cast<double>(encoder_stack_->SampleRateHz()) /
442 static_cast<double>(in_frame.sample_rate_hz_));
443 expected_in_ts_ = in_frame.timestamp_;
444 }
445
kwibergc13ded52016-06-17 06:00:45 -0700446 if (!down_mix && !resample) {
447 // No pre-processing is required.
ossu63fb95a2016-07-06 09:34:22 -0700448 if (expected_in_ts_ == expected_codec_ts_) {
449 // If we've never resampled, we can use the input frame as-is
450 *ptr_out = &in_frame;
451 } else {
452 // Otherwise we'll need to alter the timestamp. Since in_frame is const,
453 // we'll have to make a copy of it.
454 preprocess_frame_.CopyFrom(in_frame);
455 preprocess_frame_.timestamp_ = expected_codec_ts_;
456 *ptr_out = &preprocess_frame_;
457 }
458
kwibergc13ded52016-06-17 06:00:45 -0700459 expected_in_ts_ += static_cast<uint32_t>(in_frame.samples_per_channel_);
460 expected_codec_ts_ += static_cast<uint32_t>(in_frame.samples_per_channel_);
kwibergc13ded52016-06-17 06:00:45 -0700461 return 0;
462 }
463
464 *ptr_out = &preprocess_frame_;
465 preprocess_frame_.num_channels_ = in_frame.num_channels_;
Per Åhgren4dd56a32019-11-19 21:00:59 +0100466 preprocess_frame_.samples_per_channel_ = in_frame.samples_per_channel_;
Per Åhgrend82a02c2020-03-12 11:53:30 +0100467 std::array<int16_t, AudioFrame::kMaxDataSizeSamples> audio;
468 const int16_t* src_ptr_audio;
kwibergc13ded52016-06-17 06:00:45 -0700469 if (down_mix) {
Per Åhgrend82a02c2020-03-12 11:53:30 +0100470 // If a resampling is required, the output of a down-mix is written into a
kwibergc13ded52016-06-17 06:00:45 -0700471 // local buffer, otherwise, it will be written to the output frame.
Yves Gerey665174f2018-06-19 15:03:05 +0200472 int16_t* dest_ptr_audio =
Per Åhgren4dd56a32019-11-19 21:00:59 +0100473 resample ? audio.data() : preprocess_frame_.mutable_data();
Per Åhgrend82a02c2020-03-12 11:53:30 +0100474 RTC_DCHECK_GE(audio.size(), preprocess_frame_.samples_per_channel_);
Per Åhgren4dd56a32019-11-19 21:00:59 +0100475 RTC_DCHECK_GE(audio.size(), in_frame.samples_per_channel_);
476 DownMixFrame(in_frame,
477 rtc::ArrayView<int16_t>(
478 dest_ptr_audio, preprocess_frame_.samples_per_channel_));
kwibergc13ded52016-06-17 06:00:45 -0700479 preprocess_frame_.num_channels_ = 1;
Per Åhgrend82a02c2020-03-12 11:53:30 +0100480
481 // Set the input of the resampler to the down-mixed signal.
Per Åhgren4dd56a32019-11-19 21:00:59 +0100482 src_ptr_audio = audio.data();
Per Åhgrend82a02c2020-03-12 11:53:30 +0100483 } else {
484 // Set the input of the resampler to the original data.
485 src_ptr_audio = in_frame.data();
kwibergc13ded52016-06-17 06:00:45 -0700486 }
487
488 preprocess_frame_.timestamp_ = expected_codec_ts_;
kwibergc13ded52016-06-17 06:00:45 -0700489 preprocess_frame_.sample_rate_hz_ = in_frame.sample_rate_hz_;
490 // If it is required, we have to do a resampling.
491 if (resample) {
492 // The result of the resampler is written to output frame.
yujo36b1a5f2017-06-12 12:45:32 -0700493 int16_t* dest_ptr_audio = preprocess_frame_.mutable_data();
kwibergc13ded52016-06-17 06:00:45 -0700494
495 int samples_per_channel = resampler_.Resample10Msec(
496 src_ptr_audio, in_frame.sample_rate_hz_, encoder_stack_->SampleRateHz(),
497 preprocess_frame_.num_channels_, AudioFrame::kMaxDataSizeSamples,
498 dest_ptr_audio);
499
500 if (samples_per_channel < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100501 RTC_LOG(LS_ERROR) << "Cannot add 10 ms audio, resampling failed";
kwibergc13ded52016-06-17 06:00:45 -0700502 return -1;
503 }
504 preprocess_frame_.samples_per_channel_ =
505 static_cast<size_t>(samples_per_channel);
506 preprocess_frame_.sample_rate_hz_ = encoder_stack_->SampleRateHz();
507 }
508
509 expected_codec_ts_ +=
510 static_cast<uint32_t>(preprocess_frame_.samples_per_channel_);
511 expected_in_ts_ += static_cast<uint32_t>(in_frame.samples_per_channel_);
512
513 return 0;
514}
515
516/////////////////////////////////////////
kwibergc13ded52016-06-17 06:00:45 -0700517// (FEC) Forward Error Correction (codec internal)
518//
519
kwibergc13ded52016-06-17 06:00:45 -0700520int AudioCodingModuleImpl::SetPacketLossRate(int loss_rate) {
Markus Handell0df0fae2020-07-07 15:53:34 +0200521 MutexLock lock(&acm_mutex_);
kwibergc13ded52016-06-17 06:00:45 -0700522 if (HaveValidEncoder("SetPacketLossRate")) {
minyue4b9a2cb2016-11-30 06:49:59 -0800523 encoder_stack_->OnReceivedUplinkPacketLossFraction(loss_rate / 100.0);
kwibergc13ded52016-06-17 06:00:45 -0700524 }
525 return 0;
526}
527
528/////////////////////////////////////////
kwibergc13ded52016-06-17 06:00:45 -0700529// Receiver
530//
531
532int AudioCodingModuleImpl::InitializeReceiver() {
Markus Handell0df0fae2020-07-07 15:53:34 +0200533 MutexLock lock(&acm_mutex_);
kwibergc13ded52016-06-17 06:00:45 -0700534 return InitializeReceiverSafe();
535}
536
537// Initialize receiver, resets codec database etc.
538int AudioCodingModuleImpl::InitializeReceiverSafe() {
539 // If the receiver is already initialized then we want to destroy any
540 // existing decoders. After a call to this function, we should have a clean
541 // start-up.
kwiberg6b19b562016-09-20 04:02:25 -0700542 if (receiver_initialized_)
543 receiver_.RemoveAllCodecs();
kwibergc13ded52016-06-17 06:00:45 -0700544 receiver_.FlushBuffers();
545
kwibergc13ded52016-06-17 06:00:45 -0700546 receiver_initialized_ = true;
547 return 0;
548}
549
kwiberg1c07c702017-03-27 07:15:49 -0700550void AudioCodingModuleImpl::SetReceiveCodecs(
551 const std::map<int, SdpAudioFormat>& codecs) {
Markus Handell0df0fae2020-07-07 15:53:34 +0200552 MutexLock lock(&acm_mutex_);
kwiberg1c07c702017-03-27 07:15:49 -0700553 receiver_.SetCodecs(codecs);
554}
555
kwibergc13ded52016-06-17 06:00:45 -0700556// Incoming packet from network parsed and ready for decode.
557int AudioCodingModuleImpl::IncomingPacket(const uint8_t* incoming_payload,
558 const size_t payload_length,
Niels Möllerafb5dbb2019-02-15 15:21:47 +0100559 const RTPHeader& rtp_header) {
henrik.lundinb8c55b12017-05-10 07:38:01 -0700560 RTC_DCHECK_EQ(payload_length == 0, incoming_payload == nullptr);
kwibergc13ded52016-06-17 06:00:45 -0700561 return receiver_.InsertPacket(
562 rtp_header,
563 rtc::ArrayView<const uint8_t>(incoming_payload, payload_length));
564}
565
kwibergc13ded52016-06-17 06:00:45 -0700566// Get 10 milliseconds of raw audio data to play out.
567// Automatic resample to the requested frequency.
568int AudioCodingModuleImpl::PlayoutData10Ms(int desired_freq_hz,
569 AudioFrame* audio_frame,
570 bool* muted) {
571 // GetAudio always returns 10 ms, at the requested sample rate.
572 if (receiver_.GetAudio(desired_freq_hz, audio_frame, muted) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100573 RTC_LOG(LS_ERROR) << "PlayoutData failed, RecOut Failed";
kwibergc13ded52016-06-17 06:00:45 -0700574 return -1;
575 }
kwibergc13ded52016-06-17 06:00:45 -0700576 return 0;
577}
578
kwibergc13ded52016-06-17 06:00:45 -0700579/////////////////////////////////////////
580// Statistics
581//
582
583// TODO(turajs) change the return value to void. Also change the corresponding
584// NetEq function.
585int AudioCodingModuleImpl::GetNetworkStatistics(NetworkStatistics* statistics) {
586 receiver_.GetNetworkStatistics(statistics);
587 return 0;
588}
589
kwibergc13ded52016-06-17 06:00:45 -0700590bool AudioCodingModuleImpl::HaveValidEncoder(const char* caller_name) const {
591 if (!encoder_stack_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100592 RTC_LOG(LS_ERROR) << caller_name << " failed: No send codec is registered.";
kwibergc13ded52016-06-17 06:00:45 -0700593 return false;
594 }
595 return true;
596}
597
ivoce1198e02017-09-08 08:13:19 -0700598ANAStats AudioCodingModuleImpl::GetANAStats() const {
Markus Handell0df0fae2020-07-07 15:53:34 +0200599 MutexLock lock(&acm_mutex_);
ivoce1198e02017-09-08 08:13:19 -0700600 if (encoder_stack_)
601 return encoder_stack_->GetANAStats();
602 // If no encoder is set, return default stats.
603 return ANAStats();
604}
605
kwibergc13ded52016-06-17 06:00:45 -0700606} // namespace
607
Karl Wiberg5817d3d2018-04-06 10:06:42 +0200608AudioCodingModule::Config::Config(
609 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory)
610 : neteq_config(),
611 clock(Clock::GetRealTimeClock()),
612 decoder_factory(decoder_factory) {
kwiberg36a43882016-08-29 05:33:32 -0700613 // Post-decode VAD is disabled by default in NetEq, however, Audio
614 // Conference Mixer relies on VAD decisions and fails without them.
615 neteq_config.enable_post_decode_vad = true;
616}
617
618AudioCodingModule::Config::Config(const Config&) = default;
619AudioCodingModule::Config::~Config() = default;
620
Henrik Lundin64dad832015-05-11 12:44:23 +0200621AudioCodingModule* AudioCodingModule::Create(const Config& config) {
kwibergc13ded52016-06-17 06:00:45 -0700622 return new AudioCodingModuleImpl(config);
turaj@webrtc.org7959e162013-09-12 18:30:26 +0000623}
624
turaj@webrtc.org7959e162013-09-12 18:30:26 +0000625} // namespace webrtc