blob: 741cef9969754eabbaf5e283b7913705dd30fbe8 [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"
20#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"
Steve Anton10542f22019-01-11 09:11:00 -080025#include "rtc_base/critical_section.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020026#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010027#include "rtc_base/numerics/safe_conversions.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
kwibergc13ded52016-06-17 06:00:45 -070035class AudioCodingModuleImpl final : public AudioCodingModule {
36 public:
37 explicit AudioCodingModuleImpl(const AudioCodingModule::Config& config);
38 ~AudioCodingModuleImpl() override;
39
40 /////////////////////////////////////////
41 // Sender
42 //
43
kwiberg24c7c122016-09-28 11:57:10 -070044 void ModifyEncoder(rtc::FunctionView<void(std::unique_ptr<AudioEncoder>*)>
45 modifier) override;
kwibergc13ded52016-06-17 06:00:45 -070046
kwibergc13ded52016-06-17 06:00:45 -070047 // Sets the bitrate to the specified value in bits/sec. In case the codec does
48 // not support the requested value it will choose an appropriate value
49 // instead.
50 void SetBitRate(int bitrate_bps) override;
51
52 // Register a transport callback which will be
53 // called to deliver the encoded buffers.
54 int RegisterTransportCallback(AudioPacketizationCallback* transport) override;
55
56 // Add 10 ms of raw (PCM) audio data to the encoder.
57 int Add10MsData(const AudioFrame& audio_frame) override;
58
59 /////////////////////////////////////////
kwibergc13ded52016-06-17 06:00:45 -070060 // (FEC) Forward Error Correction (codec internal)
61 //
62
kwibergc13ded52016-06-17 06:00:45 -070063 // Set target packet loss rate
64 int SetPacketLossRate(int loss_rate) override;
65
66 /////////////////////////////////////////
67 // (VAD) Voice Activity Detection
68 // and
69 // (CNG) Comfort Noise Generation
70 //
71
kwibergc13ded52016-06-17 06:00:45 -070072 int RegisterVADCallback(ACMVADCallback* vad_callback) override;
73
74 /////////////////////////////////////////
75 // Receiver
76 //
77
78 // Initialize receiver, resets codec database etc.
79 int InitializeReceiver() override;
80
81 // Get current receive frequency.
82 int ReceiveFrequency() const override;
83
84 // Get current playout frequency.
85 int PlayoutFrequency() const override;
86
kwiberg1c07c702017-03-27 07:15:49 -070087 void SetReceiveCodecs(const std::map<int, SdpAudioFormat>& codecs) override;
88
kwibergc13ded52016-06-17 06:00:45 -070089 // Get current received codec.
Fredrik Solenbergf693bfa2018-12-11 12:22:10 +010090 absl::optional<std::pair<int, SdpAudioFormat>> ReceiveCodec() const override;
ossue280cde2016-10-12 11:04:10 -070091
kwibergc13ded52016-06-17 06:00:45 -070092 // Incoming packet from network parsed and ready for decode.
93 int IncomingPacket(const uint8_t* incoming_payload,
94 const size_t payload_length,
Niels Möllerafb5dbb2019-02-15 15:21:47 +010095 const RTPHeader& rtp_info) override;
kwibergc13ded52016-06-17 06:00:45 -070096
kwibergc13ded52016-06-17 06:00:45 -070097 // Minimum playout delay.
98 int SetMinimumPlayoutDelay(int time_ms) override;
99
100 // Maximum playout delay.
101 int SetMaximumPlayoutDelay(int time_ms) override;
102
Ruslan Burakov3b50f9f2019-02-06 09:45:56 +0100103 bool SetBaseMinimumPlayoutDelayMs(int delay_ms) override;
104
105 int GetBaseMinimumPlayoutDelayMs() const override;
106
Danil Chapovalovb6021232018-06-19 13:26:36 +0200107 absl::optional<uint32_t> PlayoutTimestamp() override;
kwibergc13ded52016-06-17 06:00:45 -0700108
henrik.lundinb3f1c5d2016-08-22 15:39:53 -0700109 int FilteredCurrentDelayMs() const override;
110
Henrik Lundinabbff892017-11-29 09:14:04 +0100111 int TargetDelayMs() const override;
112
kwibergc13ded52016-06-17 06:00:45 -0700113 // Get 10 milliseconds of raw audio data to play out, and
114 // automatic resample to the requested frequency if > 0.
115 int PlayoutData10Ms(int desired_freq_hz,
116 AudioFrame* audio_frame,
117 bool* muted) override;
kwibergc13ded52016-06-17 06:00:45 -0700118
119 /////////////////////////////////////////
120 // Statistics
121 //
122
123 int GetNetworkStatistics(NetworkStatistics* statistics) override;
124
kwibergc13ded52016-06-17 06:00:45 -0700125 // If current send codec is Opus, informs it about the maximum playback rate
126 // the receiver will render.
127 int SetOpusMaxPlaybackRate(int frequency_hz) override;
128
129 int EnableOpusDtx() override;
130
131 int DisableOpusDtx() override;
132
kwibergc13ded52016-06-17 06:00:45 -0700133 int EnableNack(size_t max_nack_list_size) override;
134
135 void DisableNack() override;
136
137 std::vector<uint16_t> GetNackList(int64_t round_trip_time_ms) const override;
138
139 void GetDecodingCallStatistics(AudioDecodingCallStats* stats) const override;
140
ivoce1198e02017-09-08 08:13:19 -0700141 ANAStats GetANAStats() const override;
142
kwibergc13ded52016-06-17 06:00:45 -0700143 private:
144 struct InputData {
145 uint32_t input_timestamp;
146 const int16_t* audio;
147 size_t length_per_channel;
148 size_t audio_channel;
149 // If a re-mix is required (up or down), this buffer will store a re-mixed
150 // version of the input.
151 int16_t buffer[WEBRTC_10MS_PCM_AUDIO];
152 };
153
154 // This member class writes values to the named UMA histogram, but only if
155 // the value has changed since the last time (and always for the first call).
156 class ChangeLogger {
157 public:
158 explicit ChangeLogger(const std::string& histogram_name)
159 : histogram_name_(histogram_name) {}
160 // Logs the new value if it is different from the last logged value, or if
161 // this is the first call.
162 void MaybeLog(int value);
163
164 private:
165 int last_value_ = 0;
166 int first_time_ = true;
167 const std::string histogram_name_;
168 };
169
kwibergc13ded52016-06-17 06:00:45 -0700170 int Add10MsDataInternal(const AudioFrame& audio_frame, InputData* input_data)
danilchap56359be2017-09-07 07:53:45 -0700171 RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700172 int Encode(const InputData& input_data)
danilchap56359be2017-09-07 07:53:45 -0700173 RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700174
danilchap56359be2017-09-07 07:53:45 -0700175 int InitializeReceiverSafe() RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700176
177 bool HaveValidEncoder(const char* caller_name) const
danilchap56359be2017-09-07 07:53:45 -0700178 RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700179
180 // Preprocessing of input audio, including resampling and down-mixing if
181 // required, before pushing audio into encoder's buffer.
182 //
183 // in_frame: input audio-frame
184 // ptr_out: pointer to output audio_frame. If no preprocessing is required
185 // |ptr_out| will be pointing to |in_frame|, otherwise pointing to
186 // |preprocess_frame_|.
187 //
188 // Return value:
189 // -1: if encountering an error.
190 // 0: otherwise.
191 int PreprocessToAddData(const AudioFrame& in_frame,
192 const AudioFrame** ptr_out)
danilchap56359be2017-09-07 07:53:45 -0700193 RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700194
195 // Change required states after starting to receive the codec corresponding
196 // to |index|.
197 int UpdateUponReceivingCodec(int index);
198
199 rtc::CriticalSection acm_crit_sect_;
danilchap56359be2017-09-07 07:53:45 -0700200 rtc::Buffer encode_buffer_ RTC_GUARDED_BY(acm_crit_sect_);
danilchap56359be2017-09-07 07:53:45 -0700201 uint32_t expected_codec_ts_ RTC_GUARDED_BY(acm_crit_sect_);
202 uint32_t expected_in_ts_ RTC_GUARDED_BY(acm_crit_sect_);
203 acm2::ACMResampler resampler_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700204 acm2::AcmReceiver receiver_; // AcmReceiver has it's own internal lock.
danilchap56359be2017-09-07 07:53:45 -0700205 ChangeLogger bitrate_logger_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700206
Karl Wiberg49c33ce2018-11-12 14:21:58 +0100207 // Current encoder stack, provided by a call to RegisterEncoder.
danilchap56359be2017-09-07 07:53:45 -0700208 std::unique_ptr<AudioEncoder> encoder_stack_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700209
danilchap56359be2017-09-07 07:53:45 -0700210 std::unique_ptr<AudioDecoder> isac_decoder_16k_
211 RTC_GUARDED_BY(acm_crit_sect_);
212 std::unique_ptr<AudioDecoder> isac_decoder_32k_
213 RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700214
215 // This is to keep track of CN instances where we can send DTMFs.
danilchap56359be2017-09-07 07:53:45 -0700216 uint8_t previous_pltype_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700217
danilchap56359be2017-09-07 07:53:45 -0700218 bool receiver_initialized_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700219
danilchap56359be2017-09-07 07:53:45 -0700220 AudioFrame preprocess_frame_ RTC_GUARDED_BY(acm_crit_sect_);
221 bool first_10ms_data_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700222
danilchap56359be2017-09-07 07:53:45 -0700223 bool first_frame_ RTC_GUARDED_BY(acm_crit_sect_);
224 uint32_t last_timestamp_ RTC_GUARDED_BY(acm_crit_sect_);
225 uint32_t last_rtp_timestamp_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700226
227 rtc::CriticalSection callback_crit_sect_;
228 AudioPacketizationCallback* packetization_callback_
danilchap56359be2017-09-07 07:53:45 -0700229 RTC_GUARDED_BY(callback_crit_sect_);
230 ACMVADCallback* vad_callback_ RTC_GUARDED_BY(callback_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700231
232 int codec_histogram_bins_log_[static_cast<size_t>(
233 AudioEncoder::CodecType::kMaxLoggedAudioCodecTypes)];
234 int number_of_consecutive_empty_packets_;
235};
236
237// Adds a codec usage sample to the histogram.
238void UpdateCodecTypeHistogram(size_t codec_type) {
239 RTC_HISTOGRAM_ENUMERATION(
240 "WebRTC.Audio.Encoder.CodecType", static_cast<int>(codec_type),
241 static_cast<int>(
242 webrtc::AudioEncoder::CodecType::kMaxLoggedAudioCodecTypes));
243}
244
kwibergc13ded52016-06-17 06:00:45 -0700245// Stereo-to-mono can be used as in-place.
246int DownMix(const AudioFrame& frame,
247 size_t length_out_buff,
248 int16_t* out_buff) {
yujo36b1a5f2017-06-12 12:45:32 -0700249 RTC_DCHECK_EQ(frame.num_channels_, 2);
250 RTC_DCHECK_GE(length_out_buff, frame.samples_per_channel_);
251
252 if (!frame.muted()) {
253 const int16_t* frame_data = frame.data();
254 for (size_t n = 0; n < frame.samples_per_channel_; ++n) {
Yves Gerey665174f2018-06-19 15:03:05 +0200255 out_buff[n] =
256 static_cast<int16_t>((static_cast<int32_t>(frame_data[2 * n]) +
257 static_cast<int32_t>(frame_data[2 * n + 1])) >>
258 1);
yujo36b1a5f2017-06-12 12:45:32 -0700259 }
260 } else {
Jonathan Yu36344a02017-07-30 01:55:34 -0700261 std::fill(out_buff, out_buff + frame.samples_per_channel_, 0);
kwibergc13ded52016-06-17 06:00:45 -0700262 }
kwibergc13ded52016-06-17 06:00:45 -0700263 return 0;
264}
265
266// Mono-to-stereo can be used as in-place.
267int UpMix(const AudioFrame& frame, size_t length_out_buff, int16_t* out_buff) {
yujo36b1a5f2017-06-12 12:45:32 -0700268 RTC_DCHECK_EQ(frame.num_channels_, 1);
269 RTC_DCHECK_GE(length_out_buff, 2 * frame.samples_per_channel_);
270
271 if (!frame.muted()) {
272 const int16_t* frame_data = frame.data();
273 for (size_t n = frame.samples_per_channel_; n != 0; --n) {
274 size_t i = n - 1;
275 int16_t sample = frame_data[i];
276 out_buff[2 * i + 1] = sample;
277 out_buff[2 * i] = sample;
278 }
279 } else {
Jonathan Yu36344a02017-07-30 01:55:34 -0700280 std::fill(out_buff, out_buff + frame.samples_per_channel_ * 2, 0);
kwibergc13ded52016-06-17 06:00:45 -0700281 }
282 return 0;
283}
284
kwibergc13ded52016-06-17 06:00:45 -0700285void AudioCodingModuleImpl::ChangeLogger::MaybeLog(int value) {
286 if (value != last_value_ || first_time_) {
287 first_time_ = false;
288 last_value_ = value;
289 RTC_HISTOGRAM_COUNTS_SPARSE_100(histogram_name_, value);
290 }
291}
292
293AudioCodingModuleImpl::AudioCodingModuleImpl(
294 const AudioCodingModule::Config& config)
solenbergc7b4a452017-09-28 07:37:11 -0700295 : expected_codec_ts_(0xD87F3F9F),
kwibergc13ded52016-06-17 06:00:45 -0700296 expected_in_ts_(0xD87F3F9F),
297 receiver_(config),
298 bitrate_logger_("WebRTC.Audio.TargetBitrateInKbps"),
kwibergc13ded52016-06-17 06:00:45 -0700299 encoder_stack_(nullptr),
300 previous_pltype_(255),
301 receiver_initialized_(false),
302 first_10ms_data_(false),
303 first_frame_(true),
304 packetization_callback_(NULL),
305 vad_callback_(NULL),
306 codec_histogram_bins_log_(),
307 number_of_consecutive_empty_packets_(0) {
308 if (InitializeReceiverSafe() < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100309 RTC_LOG(LS_ERROR) << "Cannot initialize receiver";
kwibergc13ded52016-06-17 06:00:45 -0700310 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100311 RTC_LOG(LS_INFO) << "Created";
kwibergc13ded52016-06-17 06:00:45 -0700312}
313
314AudioCodingModuleImpl::~AudioCodingModuleImpl() = default;
315
316int32_t AudioCodingModuleImpl::Encode(const InputData& input_data) {
317 AudioEncoder::EncodedInfo encoded_info;
318 uint8_t previous_pltype;
319
320 // Check if there is an encoder before.
321 if (!HaveValidEncoder("Process"))
322 return -1;
323
Yves Gerey665174f2018-06-19 15:03:05 +0200324 if (!first_frame_) {
deadbeeffcada902016-08-24 12:45:13 -0700325 RTC_DCHECK(IsNewerTimestamp(input_data.input_timestamp, last_timestamp_))
ossu63fb95a2016-07-06 09:34:22 -0700326 << "Time should not move backwards";
327 }
328
kwibergc13ded52016-06-17 06:00:45 -0700329 // Scale the timestamp to the codec's RTP timestamp rate.
330 uint32_t rtp_timestamp =
Karl Wiberg053c3712019-05-16 15:24:17 +0200331 first_frame_
332 ? input_data.input_timestamp
333 : last_rtp_timestamp_ +
334 rtc::dchecked_cast<uint32_t>(rtc::CheckedDivExact(
335 int64_t{input_data.input_timestamp - last_timestamp_} *
336 encoder_stack_->RtpTimestampRateHz(),
337 int64_t{encoder_stack_->SampleRateHz()}));
kwibergc13ded52016-06-17 06:00:45 -0700338 last_timestamp_ = input_data.input_timestamp;
339 last_rtp_timestamp_ = rtp_timestamp;
340 first_frame_ = false;
341
342 // Clear the buffer before reuse - encoded data will get appended.
343 encode_buffer_.Clear();
344 encoded_info = encoder_stack_->Encode(
Yves Gerey665174f2018-06-19 15:03:05 +0200345 rtp_timestamp,
346 rtc::ArrayView<const int16_t>(
347 input_data.audio,
348 input_data.audio_channel * input_data.length_per_channel),
kwibergc13ded52016-06-17 06:00:45 -0700349 &encode_buffer_);
350
351 bitrate_logger_.MaybeLog(encoder_stack_->GetTargetBitrate() / 1000);
352 if (encode_buffer_.size() == 0 && !encoded_info.send_even_if_empty) {
353 // Not enough data.
354 return 0;
355 }
356 previous_pltype = previous_pltype_; // Read it while we have the critsect.
357
358 // Log codec type to histogram once every 500 packets.
359 if (encoded_info.encoded_bytes == 0) {
360 ++number_of_consecutive_empty_packets_;
361 } else {
362 size_t codec_type = static_cast<size_t>(encoded_info.encoder_type);
363 codec_histogram_bins_log_[codec_type] +=
364 number_of_consecutive_empty_packets_ + 1;
365 number_of_consecutive_empty_packets_ = 0;
366 if (codec_histogram_bins_log_[codec_type] >= 500) {
367 codec_histogram_bins_log_[codec_type] -= 500;
368 UpdateCodecTypeHistogram(codec_type);
369 }
370 }
371
Niels Möller87e2d782019-03-07 10:18:23 +0100372 AudioFrameType frame_type;
kwibergc13ded52016-06-17 06:00:45 -0700373 if (encode_buffer_.size() == 0 && encoded_info.send_even_if_empty) {
Niels Möllerc936cb62019-03-19 14:10:16 +0100374 frame_type = AudioFrameType::kEmptyFrame;
kwibergc13ded52016-06-17 06:00:45 -0700375 encoded_info.payload_type = previous_pltype;
376 } else {
kwibergaf476c72016-11-28 15:21:39 -0800377 RTC_DCHECK_GT(encode_buffer_.size(), 0);
Niels Möllerc936cb62019-03-19 14:10:16 +0100378 frame_type = encoded_info.speech ? AudioFrameType::kAudioFrameSpeech
379 : AudioFrameType::kAudioFrameCN;
kwibergc13ded52016-06-17 06:00:45 -0700380 }
381
382 {
383 rtc::CritScope lock(&callback_crit_sect_);
384 if (packetization_callback_) {
385 packetization_callback_->SendData(
386 frame_type, encoded_info.payload_type, encoded_info.encoded_timestamp,
Niels Möllerc35b6e62019-04-25 16:31:18 +0200387 encode_buffer_.data(), encode_buffer_.size());
kwibergc13ded52016-06-17 06:00:45 -0700388 }
389
390 if (vad_callback_) {
391 // Callback with VAD decision.
392 vad_callback_->InFrameType(frame_type);
393 }
394 }
395 previous_pltype_ = encoded_info.payload_type;
396 return static_cast<int32_t>(encode_buffer_.size());
397}
398
399/////////////////////////////////////////
400// Sender
401//
402
kwibergc13ded52016-06-17 06:00:45 -0700403void AudioCodingModuleImpl::ModifyEncoder(
kwiberg24c7c122016-09-28 11:57:10 -0700404 rtc::FunctionView<void(std::unique_ptr<AudioEncoder>*)> modifier) {
kwibergc13ded52016-06-17 06:00:45 -0700405 rtc::CritScope lock(&acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700406 modifier(&encoder_stack_);
407}
408
kwibergc13ded52016-06-17 06:00:45 -0700409void AudioCodingModuleImpl::SetBitRate(int bitrate_bps) {
410 rtc::CritScope lock(&acm_crit_sect_);
411 if (encoder_stack_) {
Danil Chapovalovb6021232018-06-19 13:26:36 +0200412 encoder_stack_->OnReceivedUplinkBandwidth(bitrate_bps, absl::nullopt);
kwibergc13ded52016-06-17 06:00:45 -0700413 }
414}
415
416// Register a transport callback which will be called to deliver
417// the encoded buffers.
418int AudioCodingModuleImpl::RegisterTransportCallback(
419 AudioPacketizationCallback* transport) {
420 rtc::CritScope lock(&callback_crit_sect_);
421 packetization_callback_ = transport;
422 return 0;
423}
424
425// Add 10MS of raw (PCM) audio data to the encoder.
426int AudioCodingModuleImpl::Add10MsData(const AudioFrame& audio_frame) {
427 InputData input_data;
428 rtc::CritScope lock(&acm_crit_sect_);
429 int r = Add10MsDataInternal(audio_frame, &input_data);
430 return r < 0 ? r : Encode(input_data);
431}
432
433int AudioCodingModuleImpl::Add10MsDataInternal(const AudioFrame& audio_frame,
434 InputData* input_data) {
435 if (audio_frame.samples_per_channel_ == 0) {
436 assert(false);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100437 RTC_LOG(LS_ERROR) << "Cannot Add 10 ms audio, payload length is zero";
kwibergc13ded52016-06-17 06:00:45 -0700438 return -1;
439 }
440
441 if (audio_frame.sample_rate_hz_ > 48000) {
442 assert(false);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100443 RTC_LOG(LS_ERROR) << "Cannot Add 10 ms audio, input frequency not valid";
kwibergc13ded52016-06-17 06:00:45 -0700444 return -1;
445 }
446
447 // If the length and frequency matches. We currently just support raw PCM.
448 if (static_cast<size_t>(audio_frame.sample_rate_hz_ / 100) !=
449 audio_frame.samples_per_channel_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100450 RTC_LOG(LS_ERROR)
Alex Loiko300ec8c2017-05-30 17:23:28 +0200451 << "Cannot Add 10 ms audio, input frequency and length doesn't match";
kwibergc13ded52016-06-17 06:00:45 -0700452 return -1;
453 }
454
Alex Loiko65438812019-02-22 10:13:44 +0100455 if (audio_frame.num_channels_ != 1 && audio_frame.num_channels_ != 2 &&
456 audio_frame.num_channels_ != 4 && audio_frame.num_channels_ != 6 &&
457 audio_frame.num_channels_ != 8) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100458 RTC_LOG(LS_ERROR) << "Cannot Add 10 ms audio, invalid number of channels.";
kwibergc13ded52016-06-17 06:00:45 -0700459 return -1;
460 }
461
462 // Do we have a codec registered?
463 if (!HaveValidEncoder("Add10MsData")) {
464 return -1;
465 }
466
467 const AudioFrame* ptr_frame;
468 // Perform a resampling, also down-mix if it is required and can be
469 // performed before resampling (a down mix prior to resampling will take
470 // place if both primary and secondary encoders are mono and input is in
471 // stereo).
472 if (PreprocessToAddData(audio_frame, &ptr_frame) < 0) {
473 return -1;
474 }
475
476 // Check whether we need an up-mix or down-mix?
477 const size_t current_num_channels = encoder_stack_->NumChannels();
478 const bool same_num_channels =
479 ptr_frame->num_channels_ == current_num_channels;
480
481 if (!same_num_channels) {
482 if (ptr_frame->num_channels_ == 1) {
483 if (UpMix(*ptr_frame, WEBRTC_10MS_PCM_AUDIO, input_data->buffer) < 0)
484 return -1;
485 } else {
486 if (DownMix(*ptr_frame, WEBRTC_10MS_PCM_AUDIO, input_data->buffer) < 0)
487 return -1;
488 }
489 }
490
491 // When adding data to encoders this pointer is pointing to an audio buffer
492 // with correct number of channels.
yujo36b1a5f2017-06-12 12:45:32 -0700493 const int16_t* ptr_audio = ptr_frame->data();
kwibergc13ded52016-06-17 06:00:45 -0700494
495 // For pushing data to primary, point the |ptr_audio| to correct buffer.
496 if (!same_num_channels)
497 ptr_audio = input_data->buffer;
498
yujo36b1a5f2017-06-12 12:45:32 -0700499 // TODO(yujo): Skip encode of muted frames.
kwibergc13ded52016-06-17 06:00:45 -0700500 input_data->input_timestamp = ptr_frame->timestamp_;
501 input_data->audio = ptr_audio;
502 input_data->length_per_channel = ptr_frame->samples_per_channel_;
503 input_data->audio_channel = current_num_channels;
504
505 return 0;
506}
507
508// Perform a resampling and down-mix if required. We down-mix only if
509// encoder is mono and input is stereo. In case of dual-streaming, both
510// encoders has to be mono for down-mix to take place.
511// |*ptr_out| will point to the pre-processed audio-frame. If no pre-processing
512// is required, |*ptr_out| points to |in_frame|.
yujo36b1a5f2017-06-12 12:45:32 -0700513// TODO(yujo): Make this more efficient for muted frames.
kwibergc13ded52016-06-17 06:00:45 -0700514int AudioCodingModuleImpl::PreprocessToAddData(const AudioFrame& in_frame,
515 const AudioFrame** ptr_out) {
516 const bool resample =
517 in_frame.sample_rate_hz_ != encoder_stack_->SampleRateHz();
518
519 // This variable is true if primary codec and secondary codec (if exists)
520 // are both mono and input is stereo.
521 // TODO(henrik.lundin): This condition should probably be
522 // in_frame.num_channels_ > encoder_stack_->NumChannels()
523 const bool down_mix =
524 in_frame.num_channels_ == 2 && encoder_stack_->NumChannels() == 1;
525
526 if (!first_10ms_data_) {
527 expected_in_ts_ = in_frame.timestamp_;
528 expected_codec_ts_ = in_frame.timestamp_;
529 first_10ms_data_ = true;
530 } else if (in_frame.timestamp_ != expected_in_ts_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100531 RTC_LOG(LS_WARNING) << "Unexpected input timestamp: " << in_frame.timestamp_
532 << ", expected: " << expected_in_ts_;
kwibergc13ded52016-06-17 06:00:45 -0700533 expected_codec_ts_ +=
534 (in_frame.timestamp_ - expected_in_ts_) *
535 static_cast<uint32_t>(
536 static_cast<double>(encoder_stack_->SampleRateHz()) /
537 static_cast<double>(in_frame.sample_rate_hz_));
538 expected_in_ts_ = in_frame.timestamp_;
539 }
540
kwibergc13ded52016-06-17 06:00:45 -0700541 if (!down_mix && !resample) {
542 // No pre-processing is required.
ossu63fb95a2016-07-06 09:34:22 -0700543 if (expected_in_ts_ == expected_codec_ts_) {
544 // If we've never resampled, we can use the input frame as-is
545 *ptr_out = &in_frame;
546 } else {
547 // Otherwise we'll need to alter the timestamp. Since in_frame is const,
548 // we'll have to make a copy of it.
549 preprocess_frame_.CopyFrom(in_frame);
550 preprocess_frame_.timestamp_ = expected_codec_ts_;
551 *ptr_out = &preprocess_frame_;
552 }
553
kwibergc13ded52016-06-17 06:00:45 -0700554 expected_in_ts_ += static_cast<uint32_t>(in_frame.samples_per_channel_);
555 expected_codec_ts_ += static_cast<uint32_t>(in_frame.samples_per_channel_);
kwibergc13ded52016-06-17 06:00:45 -0700556 return 0;
557 }
558
559 *ptr_out = &preprocess_frame_;
560 preprocess_frame_.num_channels_ = in_frame.num_channels_;
561 int16_t audio[WEBRTC_10MS_PCM_AUDIO];
yujo36b1a5f2017-06-12 12:45:32 -0700562 const int16_t* src_ptr_audio = in_frame.data();
kwibergc13ded52016-06-17 06:00:45 -0700563 if (down_mix) {
564 // If a resampling is required the output of a down-mix is written into a
565 // local buffer, otherwise, it will be written to the output frame.
Yves Gerey665174f2018-06-19 15:03:05 +0200566 int16_t* dest_ptr_audio =
567 resample ? audio : preprocess_frame_.mutable_data();
kwibergc13ded52016-06-17 06:00:45 -0700568 if (DownMix(in_frame, WEBRTC_10MS_PCM_AUDIO, dest_ptr_audio) < 0)
569 return -1;
570 preprocess_frame_.num_channels_ = 1;
571 // Set the input of the resampler is the down-mixed signal.
572 src_ptr_audio = audio;
573 }
574
575 preprocess_frame_.timestamp_ = expected_codec_ts_;
576 preprocess_frame_.samples_per_channel_ = in_frame.samples_per_channel_;
577 preprocess_frame_.sample_rate_hz_ = in_frame.sample_rate_hz_;
578 // If it is required, we have to do a resampling.
579 if (resample) {
580 // The result of the resampler is written to output frame.
yujo36b1a5f2017-06-12 12:45:32 -0700581 int16_t* dest_ptr_audio = preprocess_frame_.mutable_data();
kwibergc13ded52016-06-17 06:00:45 -0700582
583 int samples_per_channel = resampler_.Resample10Msec(
584 src_ptr_audio, in_frame.sample_rate_hz_, encoder_stack_->SampleRateHz(),
585 preprocess_frame_.num_channels_, AudioFrame::kMaxDataSizeSamples,
586 dest_ptr_audio);
587
588 if (samples_per_channel < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100589 RTC_LOG(LS_ERROR) << "Cannot add 10 ms audio, resampling failed";
kwibergc13ded52016-06-17 06:00:45 -0700590 return -1;
591 }
592 preprocess_frame_.samples_per_channel_ =
593 static_cast<size_t>(samples_per_channel);
594 preprocess_frame_.sample_rate_hz_ = encoder_stack_->SampleRateHz();
595 }
596
597 expected_codec_ts_ +=
598 static_cast<uint32_t>(preprocess_frame_.samples_per_channel_);
599 expected_in_ts_ += static_cast<uint32_t>(in_frame.samples_per_channel_);
600
601 return 0;
602}
603
604/////////////////////////////////////////
kwibergc13ded52016-06-17 06:00:45 -0700605// (FEC) Forward Error Correction (codec internal)
606//
607
kwibergc13ded52016-06-17 06:00:45 -0700608int AudioCodingModuleImpl::SetPacketLossRate(int loss_rate) {
609 rtc::CritScope lock(&acm_crit_sect_);
610 if (HaveValidEncoder("SetPacketLossRate")) {
minyue4b9a2cb2016-11-30 06:49:59 -0800611 encoder_stack_->OnReceivedUplinkPacketLossFraction(loss_rate / 100.0);
kwibergc13ded52016-06-17 06:00:45 -0700612 }
613 return 0;
614}
615
616/////////////////////////////////////////
kwibergc13ded52016-06-17 06:00:45 -0700617// Receiver
618//
619
620int AudioCodingModuleImpl::InitializeReceiver() {
621 rtc::CritScope lock(&acm_crit_sect_);
622 return InitializeReceiverSafe();
623}
624
625// Initialize receiver, resets codec database etc.
626int AudioCodingModuleImpl::InitializeReceiverSafe() {
627 // If the receiver is already initialized then we want to destroy any
628 // existing decoders. After a call to this function, we should have a clean
629 // start-up.
kwiberg6b19b562016-09-20 04:02:25 -0700630 if (receiver_initialized_)
631 receiver_.RemoveAllCodecs();
kwibergc13ded52016-06-17 06:00:45 -0700632 receiver_.FlushBuffers();
633
kwibergc13ded52016-06-17 06:00:45 -0700634 receiver_initialized_ = true;
635 return 0;
636}
637
638// Get current receive frequency.
639int AudioCodingModuleImpl::ReceiveFrequency() const {
640 const auto last_packet_sample_rate = receiver_.last_packet_sample_rate_hz();
641 return last_packet_sample_rate ? *last_packet_sample_rate
642 : receiver_.last_output_sample_rate_hz();
643}
644
645// Get current playout frequency.
646int AudioCodingModuleImpl::PlayoutFrequency() const {
kwibergc13ded52016-06-17 06:00:45 -0700647 return receiver_.last_output_sample_rate_hz();
648}
649
kwiberg1c07c702017-03-27 07:15:49 -0700650void AudioCodingModuleImpl::SetReceiveCodecs(
651 const std::map<int, SdpAudioFormat>& codecs) {
652 rtc::CritScope lock(&acm_crit_sect_);
653 receiver_.SetCodecs(codecs);
654}
655
Fredrik Solenbergf693bfa2018-12-11 12:22:10 +0100656absl::optional<std::pair<int, SdpAudioFormat>>
657 AudioCodingModuleImpl::ReceiveCodec() const {
kwiberg5adaf732016-10-04 09:33:27 -0700658 rtc::CritScope lock(&acm_crit_sect_);
Fredrik Solenbergf693bfa2018-12-11 12:22:10 +0100659 return receiver_.LastDecoder();
ossue280cde2016-10-12 11:04:10 -0700660}
661
kwibergc13ded52016-06-17 06:00:45 -0700662// Incoming packet from network parsed and ready for decode.
663int AudioCodingModuleImpl::IncomingPacket(const uint8_t* incoming_payload,
664 const size_t payload_length,
Niels Möllerafb5dbb2019-02-15 15:21:47 +0100665 const RTPHeader& rtp_header) {
henrik.lundinb8c55b12017-05-10 07:38:01 -0700666 RTC_DCHECK_EQ(payload_length == 0, incoming_payload == nullptr);
kwibergc13ded52016-06-17 06:00:45 -0700667 return receiver_.InsertPacket(
668 rtp_header,
669 rtc::ArrayView<const uint8_t>(incoming_payload, payload_length));
670}
671
672// Minimum playout delay (Used for lip-sync).
673int AudioCodingModuleImpl::SetMinimumPlayoutDelay(int time_ms) {
674 if ((time_ms < 0) || (time_ms > 10000)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100675 RTC_LOG(LS_ERROR) << "Delay must be in the range of 0-10000 milliseconds.";
kwibergc13ded52016-06-17 06:00:45 -0700676 return -1;
677 }
678 return receiver_.SetMinimumDelay(time_ms);
679}
680
681int AudioCodingModuleImpl::SetMaximumPlayoutDelay(int time_ms) {
682 if ((time_ms < 0) || (time_ms > 10000)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100683 RTC_LOG(LS_ERROR) << "Delay must be in the range of 0-10000 milliseconds.";
kwibergc13ded52016-06-17 06:00:45 -0700684 return -1;
685 }
686 return receiver_.SetMaximumDelay(time_ms);
687}
688
Ruslan Burakov3b50f9f2019-02-06 09:45:56 +0100689bool AudioCodingModuleImpl::SetBaseMinimumPlayoutDelayMs(int delay_ms) {
690 // All necessary validation happens on NetEq level.
691 return receiver_.SetBaseMinimumDelayMs(delay_ms);
692}
693
694int AudioCodingModuleImpl::GetBaseMinimumPlayoutDelayMs() const {
695 return receiver_.GetBaseMinimumDelayMs();
696}
697
kwibergc13ded52016-06-17 06:00:45 -0700698// Get 10 milliseconds of raw audio data to play out.
699// Automatic resample to the requested frequency.
700int AudioCodingModuleImpl::PlayoutData10Ms(int desired_freq_hz,
701 AudioFrame* audio_frame,
702 bool* muted) {
703 // GetAudio always returns 10 ms, at the requested sample rate.
704 if (receiver_.GetAudio(desired_freq_hz, audio_frame, muted) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100705 RTC_LOG(LS_ERROR) << "PlayoutData failed, RecOut Failed";
kwibergc13ded52016-06-17 06:00:45 -0700706 return -1;
707 }
kwibergc13ded52016-06-17 06:00:45 -0700708 return 0;
709}
710
kwibergc13ded52016-06-17 06:00:45 -0700711/////////////////////////////////////////
712// Statistics
713//
714
715// TODO(turajs) change the return value to void. Also change the corresponding
716// NetEq function.
717int AudioCodingModuleImpl::GetNetworkStatistics(NetworkStatistics* statistics) {
718 receiver_.GetNetworkStatistics(statistics);
719 return 0;
720}
721
722int AudioCodingModuleImpl::RegisterVADCallback(ACMVADCallback* vad_callback) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100723 RTC_LOG(LS_VERBOSE) << "RegisterVADCallback()";
kwibergc13ded52016-06-17 06:00:45 -0700724 rtc::CritScope lock(&callback_crit_sect_);
725 vad_callback_ = vad_callback;
726 return 0;
727}
728
kwibergc13ded52016-06-17 06:00:45 -0700729// Informs Opus encoder of the maximum playback rate the receiver will render.
730int AudioCodingModuleImpl::SetOpusMaxPlaybackRate(int frequency_hz) {
731 rtc::CritScope lock(&acm_crit_sect_);
732 if (!HaveValidEncoder("SetOpusMaxPlaybackRate")) {
733 return -1;
734 }
735 encoder_stack_->SetMaxPlaybackRate(frequency_hz);
736 return 0;
737}
738
739int AudioCodingModuleImpl::EnableOpusDtx() {
740 rtc::CritScope lock(&acm_crit_sect_);
741 if (!HaveValidEncoder("EnableOpusDtx")) {
742 return -1;
743 }
744 return encoder_stack_->SetDtx(true) ? 0 : -1;
745}
746
747int AudioCodingModuleImpl::DisableOpusDtx() {
748 rtc::CritScope lock(&acm_crit_sect_);
749 if (!HaveValidEncoder("DisableOpusDtx")) {
750 return -1;
751 }
752 return encoder_stack_->SetDtx(false) ? 0 : -1;
753}
754
Danil Chapovalovb6021232018-06-19 13:26:36 +0200755absl::optional<uint32_t> AudioCodingModuleImpl::PlayoutTimestamp() {
kwibergc13ded52016-06-17 06:00:45 -0700756 return receiver_.GetPlayoutTimestamp();
757}
758
henrik.lundinb3f1c5d2016-08-22 15:39:53 -0700759int AudioCodingModuleImpl::FilteredCurrentDelayMs() const {
760 return receiver_.FilteredCurrentDelayMs();
761}
762
Henrik Lundinabbff892017-11-29 09:14:04 +0100763int AudioCodingModuleImpl::TargetDelayMs() const {
764 return receiver_.TargetDelayMs();
765}
766
kwibergc13ded52016-06-17 06:00:45 -0700767bool AudioCodingModuleImpl::HaveValidEncoder(const char* caller_name) const {
768 if (!encoder_stack_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100769 RTC_LOG(LS_ERROR) << caller_name << " failed: No send codec is registered.";
kwibergc13ded52016-06-17 06:00:45 -0700770 return false;
771 }
772 return true;
773}
774
kwibergc13ded52016-06-17 06:00:45 -0700775int AudioCodingModuleImpl::EnableNack(size_t max_nack_list_size) {
776 return receiver_.EnableNack(max_nack_list_size);
777}
778
779void AudioCodingModuleImpl::DisableNack() {
780 receiver_.DisableNack();
781}
782
783std::vector<uint16_t> AudioCodingModuleImpl::GetNackList(
784 int64_t round_trip_time_ms) const {
785 return receiver_.GetNackList(round_trip_time_ms);
786}
787
kwibergc13ded52016-06-17 06:00:45 -0700788void AudioCodingModuleImpl::GetDecodingCallStatistics(
Yves Gerey665174f2018-06-19 15:03:05 +0200789 AudioDecodingCallStats* call_stats) const {
kwibergc13ded52016-06-17 06:00:45 -0700790 receiver_.GetDecodingCallStatistics(call_stats);
791}
792
ivoce1198e02017-09-08 08:13:19 -0700793ANAStats AudioCodingModuleImpl::GetANAStats() const {
794 rtc::CritScope lock(&acm_crit_sect_);
795 if (encoder_stack_)
796 return encoder_stack_->GetANAStats();
797 // If no encoder is set, return default stats.
798 return ANAStats();
799}
800
kwibergc13ded52016-06-17 06:00:45 -0700801} // namespace
802
Karl Wiberg5817d3d2018-04-06 10:06:42 +0200803AudioCodingModule::Config::Config(
804 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory)
805 : neteq_config(),
806 clock(Clock::GetRealTimeClock()),
807 decoder_factory(decoder_factory) {
kwiberg36a43882016-08-29 05:33:32 -0700808 // Post-decode VAD is disabled by default in NetEq, however, Audio
809 // Conference Mixer relies on VAD decisions and fails without them.
810 neteq_config.enable_post_decode_vad = true;
811}
812
813AudioCodingModule::Config::Config(const Config&) = default;
814AudioCodingModule::Config::~Config() = default;
815
Henrik Lundin64dad832015-05-11 12:44:23 +0200816AudioCodingModule* AudioCodingModule::Create(const Config& config) {
kwibergc13ded52016-06-17 06:00:45 -0700817 return new AudioCodingModuleImpl(config);
turaj@webrtc.org7959e162013-09-12 18:30:26 +0000818}
819
turaj@webrtc.org7959e162013-09-12 18:30:26 +0000820} // namespace webrtc