blob: 80313dcec90a36d328d18cc3bd5e479cf5384560 [file] [log] [blame]
turaj@webrtc.org7959e162013-09-12 18:30:26 +00001/*
2 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "modules/audio_coding/include/audio_coding_module.h"
turaj@webrtc.org7959e162013-09-12 18:30:26 +000012
Yves Gerey988cc082018-10-23 12:03:01 +020013#include <assert.h>
Jonas Olssona4d87372019-07-05 19:08:33 +020014
Jonathan Yu36344a02017-07-30 01:55:34 -070015#include <algorithm>
Yves Gerey988cc082018-10-23 12:03:01 +020016#include <cstdint>
Jonathan Yu36344a02017-07-30 01:55:34 -070017
Niels Möller2edab4c2018-10-22 09:48:08 +020018#include "absl/strings/match.h"
Yves Gerey988cc082018-10-23 12:03:01 +020019#include "api/array_view.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020020#include "modules/audio_coding/acm2/acm_receiver.h"
21#include "modules/audio_coding/acm2/acm_resampler.h"
Fredrik Solenbergbbf21a32018-04-12 22:44:09 +020022#include "modules/include/module_common_types.h"
Yves Gerey988cc082018-10-23 12:03:01 +020023#include "modules/include/module_common_types_public.h"
24#include "rtc_base/buffer.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020025#include "rtc_base/checks.h"
Steve Anton10542f22019-01-11 09:11:00 -080026#include "rtc_base/critical_section.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020027#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010028#include "rtc_base/numerics/safe_conversions.h"
Yves Gerey988cc082018-10-23 12:03:01 +020029#include "rtc_base/thread_annotations.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020030#include "system_wrappers/include/metrics.h"
turaj@webrtc.org7959e162013-09-12 18:30:26 +000031
32namespace webrtc {
33
kwibergc13ded52016-06-17 06:00:45 -070034namespace {
35
kwibergc13ded52016-06-17 06:00:45 -070036class AudioCodingModuleImpl final : public AudioCodingModule {
37 public:
38 explicit AudioCodingModuleImpl(const AudioCodingModule::Config& config);
39 ~AudioCodingModuleImpl() override;
40
41 /////////////////////////////////////////
42 // Sender
43 //
44
kwiberg24c7c122016-09-28 11:57:10 -070045 void ModifyEncoder(rtc::FunctionView<void(std::unique_ptr<AudioEncoder>*)>
46 modifier) override;
kwibergc13ded52016-06-17 06:00:45 -070047
kwibergc13ded52016-06-17 06:00:45 -070048 // Register a transport callback which will be
49 // called to deliver the encoded buffers.
50 int RegisterTransportCallback(AudioPacketizationCallback* transport) override;
51
52 // Add 10 ms of raw (PCM) audio data to the encoder.
53 int Add10MsData(const AudioFrame& audio_frame) override;
54
55 /////////////////////////////////////////
kwibergc13ded52016-06-17 06:00:45 -070056 // (FEC) Forward Error Correction (codec internal)
57 //
58
kwibergc13ded52016-06-17 06:00:45 -070059 // Set target packet loss rate
60 int SetPacketLossRate(int loss_rate) override;
61
62 /////////////////////////////////////////
63 // (VAD) Voice Activity Detection
64 // and
65 // (CNG) Comfort Noise Generation
66 //
67
kwibergc13ded52016-06-17 06:00:45 -070068 int RegisterVADCallback(ACMVADCallback* vad_callback) override;
69
70 /////////////////////////////////////////
71 // Receiver
72 //
73
74 // Initialize receiver, resets codec database etc.
75 int InitializeReceiver() override;
76
77 // Get current receive frequency.
78 int ReceiveFrequency() const override;
79
80 // Get current playout frequency.
81 int PlayoutFrequency() const override;
82
kwiberg1c07c702017-03-27 07:15:49 -070083 void SetReceiveCodecs(const std::map<int, SdpAudioFormat>& codecs) override;
84
kwibergc13ded52016-06-17 06:00:45 -070085 // Get current received codec.
Fredrik Solenbergf693bfa2018-12-11 12:22:10 +010086 absl::optional<std::pair<int, SdpAudioFormat>> ReceiveCodec() const override;
ossue280cde2016-10-12 11:04:10 -070087
kwibergc13ded52016-06-17 06:00:45 -070088 // Incoming packet from network parsed and ready for decode.
89 int IncomingPacket(const uint8_t* incoming_payload,
90 const size_t payload_length,
Niels Möllerafb5dbb2019-02-15 15:21:47 +010091 const RTPHeader& rtp_info) override;
kwibergc13ded52016-06-17 06:00:45 -070092
kwibergc13ded52016-06-17 06:00:45 -070093 // Minimum playout delay.
94 int SetMinimumPlayoutDelay(int time_ms) override;
95
96 // Maximum playout delay.
97 int SetMaximumPlayoutDelay(int time_ms) override;
98
Ruslan Burakov3b50f9f2019-02-06 09:45:56 +010099 bool SetBaseMinimumPlayoutDelayMs(int delay_ms) override;
100
101 int GetBaseMinimumPlayoutDelayMs() const override;
102
Danil Chapovalovb6021232018-06-19 13:26:36 +0200103 absl::optional<uint32_t> PlayoutTimestamp() override;
kwibergc13ded52016-06-17 06:00:45 -0700104
henrik.lundinb3f1c5d2016-08-22 15:39:53 -0700105 int FilteredCurrentDelayMs() const override;
106
Henrik Lundinabbff892017-11-29 09:14:04 +0100107 int TargetDelayMs() const override;
108
kwibergc13ded52016-06-17 06:00:45 -0700109 // Get 10 milliseconds of raw audio data to play out, and
110 // automatic resample to the requested frequency if > 0.
111 int PlayoutData10Ms(int desired_freq_hz,
112 AudioFrame* audio_frame,
113 bool* muted) override;
kwibergc13ded52016-06-17 06:00:45 -0700114
115 /////////////////////////////////////////
116 // Statistics
117 //
118
119 int GetNetworkStatistics(NetworkStatistics* statistics) override;
120
kwibergc13ded52016-06-17 06:00:45 -0700121 // If current send codec is Opus, informs it about the maximum playback rate
122 // the receiver will render.
123 int SetOpusMaxPlaybackRate(int frequency_hz) override;
124
125 int EnableOpusDtx() override;
126
127 int DisableOpusDtx() override;
128
kwibergc13ded52016-06-17 06:00:45 -0700129 int EnableNack(size_t max_nack_list_size) override;
130
131 void DisableNack() override;
132
133 std::vector<uint16_t> GetNackList(int64_t round_trip_time_ms) const override;
134
135 void GetDecodingCallStatistics(AudioDecodingCallStats* stats) const override;
136
ivoce1198e02017-09-08 08:13:19 -0700137 ANAStats GetANAStats() const override;
138
kwibergc13ded52016-06-17 06:00:45 -0700139 private:
140 struct InputData {
141 uint32_t input_timestamp;
142 const int16_t* audio;
143 size_t length_per_channel;
144 size_t audio_channel;
145 // If a re-mix is required (up or down), this buffer will store a re-mixed
146 // version of the input.
147 int16_t buffer[WEBRTC_10MS_PCM_AUDIO];
148 };
149
150 // This member class writes values to the named UMA histogram, but only if
151 // the value has changed since the last time (and always for the first call).
152 class ChangeLogger {
153 public:
154 explicit ChangeLogger(const std::string& histogram_name)
155 : histogram_name_(histogram_name) {}
156 // Logs the new value if it is different from the last logged value, or if
157 // this is the first call.
158 void MaybeLog(int value);
159
160 private:
161 int last_value_ = 0;
162 int first_time_ = true;
163 const std::string histogram_name_;
164 };
165
kwibergc13ded52016-06-17 06:00:45 -0700166 int Add10MsDataInternal(const AudioFrame& audio_frame, InputData* input_data)
danilchap56359be2017-09-07 07:53:45 -0700167 RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700168 int Encode(const InputData& input_data)
danilchap56359be2017-09-07 07:53:45 -0700169 RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700170
danilchap56359be2017-09-07 07:53:45 -0700171 int InitializeReceiverSafe() RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700172
173 bool HaveValidEncoder(const char* caller_name) const
danilchap56359be2017-09-07 07:53:45 -0700174 RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700175
176 // Preprocessing of input audio, including resampling and down-mixing if
177 // required, before pushing audio into encoder's buffer.
178 //
179 // in_frame: input audio-frame
180 // ptr_out: pointer to output audio_frame. If no preprocessing is required
181 // |ptr_out| will be pointing to |in_frame|, otherwise pointing to
182 // |preprocess_frame_|.
183 //
184 // Return value:
185 // -1: if encountering an error.
186 // 0: otherwise.
187 int PreprocessToAddData(const AudioFrame& in_frame,
188 const AudioFrame** ptr_out)
danilchap56359be2017-09-07 07:53:45 -0700189 RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700190
191 // Change required states after starting to receive the codec corresponding
192 // to |index|.
193 int UpdateUponReceivingCodec(int index);
194
195 rtc::CriticalSection acm_crit_sect_;
danilchap56359be2017-09-07 07:53:45 -0700196 rtc::Buffer encode_buffer_ RTC_GUARDED_BY(acm_crit_sect_);
danilchap56359be2017-09-07 07:53:45 -0700197 uint32_t expected_codec_ts_ RTC_GUARDED_BY(acm_crit_sect_);
198 uint32_t expected_in_ts_ RTC_GUARDED_BY(acm_crit_sect_);
199 acm2::ACMResampler resampler_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700200 acm2::AcmReceiver receiver_; // AcmReceiver has it's own internal lock.
danilchap56359be2017-09-07 07:53:45 -0700201 ChangeLogger bitrate_logger_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700202
Karl Wiberg49c33ce2018-11-12 14:21:58 +0100203 // Current encoder stack, provided by a call to RegisterEncoder.
danilchap56359be2017-09-07 07:53:45 -0700204 std::unique_ptr<AudioEncoder> encoder_stack_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700205
danilchap56359be2017-09-07 07:53:45 -0700206 std::unique_ptr<AudioDecoder> isac_decoder_16k_
207 RTC_GUARDED_BY(acm_crit_sect_);
208 std::unique_ptr<AudioDecoder> isac_decoder_32k_
209 RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700210
211 // This is to keep track of CN instances where we can send DTMFs.
danilchap56359be2017-09-07 07:53:45 -0700212 uint8_t previous_pltype_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700213
danilchap56359be2017-09-07 07:53:45 -0700214 bool receiver_initialized_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700215
danilchap56359be2017-09-07 07:53:45 -0700216 AudioFrame preprocess_frame_ RTC_GUARDED_BY(acm_crit_sect_);
217 bool first_10ms_data_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700218
danilchap56359be2017-09-07 07:53:45 -0700219 bool first_frame_ RTC_GUARDED_BY(acm_crit_sect_);
220 uint32_t last_timestamp_ RTC_GUARDED_BY(acm_crit_sect_);
221 uint32_t last_rtp_timestamp_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700222
223 rtc::CriticalSection callback_crit_sect_;
224 AudioPacketizationCallback* packetization_callback_
danilchap56359be2017-09-07 07:53:45 -0700225 RTC_GUARDED_BY(callback_crit_sect_);
226 ACMVADCallback* vad_callback_ RTC_GUARDED_BY(callback_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700227
228 int codec_histogram_bins_log_[static_cast<size_t>(
229 AudioEncoder::CodecType::kMaxLoggedAudioCodecTypes)];
230 int number_of_consecutive_empty_packets_;
231};
232
233// Adds a codec usage sample to the histogram.
234void UpdateCodecTypeHistogram(size_t codec_type) {
235 RTC_HISTOGRAM_ENUMERATION(
236 "WebRTC.Audio.Encoder.CodecType", static_cast<int>(codec_type),
237 static_cast<int>(
238 webrtc::AudioEncoder::CodecType::kMaxLoggedAudioCodecTypes));
239}
240
kwibergc13ded52016-06-17 06:00:45 -0700241// Stereo-to-mono can be used as in-place.
242int DownMix(const AudioFrame& frame,
243 size_t length_out_buff,
244 int16_t* out_buff) {
yujo36b1a5f2017-06-12 12:45:32 -0700245 RTC_DCHECK_EQ(frame.num_channels_, 2);
246 RTC_DCHECK_GE(length_out_buff, frame.samples_per_channel_);
247
248 if (!frame.muted()) {
249 const int16_t* frame_data = frame.data();
250 for (size_t n = 0; n < frame.samples_per_channel_; ++n) {
Yves Gerey665174f2018-06-19 15:03:05 +0200251 out_buff[n] =
252 static_cast<int16_t>((static_cast<int32_t>(frame_data[2 * n]) +
253 static_cast<int32_t>(frame_data[2 * n + 1])) >>
254 1);
yujo36b1a5f2017-06-12 12:45:32 -0700255 }
256 } else {
Jonathan Yu36344a02017-07-30 01:55:34 -0700257 std::fill(out_buff, out_buff + frame.samples_per_channel_, 0);
kwibergc13ded52016-06-17 06:00:45 -0700258 }
kwibergc13ded52016-06-17 06:00:45 -0700259 return 0;
260}
261
262// Mono-to-stereo can be used as in-place.
263int UpMix(const AudioFrame& frame, size_t length_out_buff, int16_t* out_buff) {
yujo36b1a5f2017-06-12 12:45:32 -0700264 RTC_DCHECK_EQ(frame.num_channels_, 1);
265 RTC_DCHECK_GE(length_out_buff, 2 * frame.samples_per_channel_);
266
267 if (!frame.muted()) {
268 const int16_t* frame_data = frame.data();
269 for (size_t n = frame.samples_per_channel_; n != 0; --n) {
270 size_t i = n - 1;
271 int16_t sample = frame_data[i];
272 out_buff[2 * i + 1] = sample;
273 out_buff[2 * i] = sample;
274 }
275 } else {
Jonathan Yu36344a02017-07-30 01:55:34 -0700276 std::fill(out_buff, out_buff + frame.samples_per_channel_ * 2, 0);
kwibergc13ded52016-06-17 06:00:45 -0700277 }
278 return 0;
279}
280
kwibergc13ded52016-06-17 06:00:45 -0700281void AudioCodingModuleImpl::ChangeLogger::MaybeLog(int value) {
282 if (value != last_value_ || first_time_) {
283 first_time_ = false;
284 last_value_ = value;
285 RTC_HISTOGRAM_COUNTS_SPARSE_100(histogram_name_, value);
286 }
287}
288
289AudioCodingModuleImpl::AudioCodingModuleImpl(
290 const AudioCodingModule::Config& config)
solenbergc7b4a452017-09-28 07:37:11 -0700291 : expected_codec_ts_(0xD87F3F9F),
kwibergc13ded52016-06-17 06:00:45 -0700292 expected_in_ts_(0xD87F3F9F),
293 receiver_(config),
294 bitrate_logger_("WebRTC.Audio.TargetBitrateInKbps"),
kwibergc13ded52016-06-17 06:00:45 -0700295 encoder_stack_(nullptr),
296 previous_pltype_(255),
297 receiver_initialized_(false),
298 first_10ms_data_(false),
299 first_frame_(true),
300 packetization_callback_(NULL),
301 vad_callback_(NULL),
302 codec_histogram_bins_log_(),
303 number_of_consecutive_empty_packets_(0) {
304 if (InitializeReceiverSafe() < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100305 RTC_LOG(LS_ERROR) << "Cannot initialize receiver";
kwibergc13ded52016-06-17 06:00:45 -0700306 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100307 RTC_LOG(LS_INFO) << "Created";
kwibergc13ded52016-06-17 06:00:45 -0700308}
309
310AudioCodingModuleImpl::~AudioCodingModuleImpl() = default;
311
312int32_t AudioCodingModuleImpl::Encode(const InputData& input_data) {
313 AudioEncoder::EncodedInfo encoded_info;
314 uint8_t previous_pltype;
315
316 // Check if there is an encoder before.
317 if (!HaveValidEncoder("Process"))
318 return -1;
319
Yves Gerey665174f2018-06-19 15:03:05 +0200320 if (!first_frame_) {
deadbeeffcada902016-08-24 12:45:13 -0700321 RTC_DCHECK(IsNewerTimestamp(input_data.input_timestamp, last_timestamp_))
ossu63fb95a2016-07-06 09:34:22 -0700322 << "Time should not move backwards";
323 }
324
kwibergc13ded52016-06-17 06:00:45 -0700325 // Scale the timestamp to the codec's RTP timestamp rate.
326 uint32_t rtp_timestamp =
Karl Wiberg053c3712019-05-16 15:24:17 +0200327 first_frame_
328 ? input_data.input_timestamp
329 : last_rtp_timestamp_ +
330 rtc::dchecked_cast<uint32_t>(rtc::CheckedDivExact(
331 int64_t{input_data.input_timestamp - last_timestamp_} *
332 encoder_stack_->RtpTimestampRateHz(),
333 int64_t{encoder_stack_->SampleRateHz()}));
kwibergc13ded52016-06-17 06:00:45 -0700334 last_timestamp_ = input_data.input_timestamp;
335 last_rtp_timestamp_ = rtp_timestamp;
336 first_frame_ = false;
337
338 // Clear the buffer before reuse - encoded data will get appended.
339 encode_buffer_.Clear();
340 encoded_info = encoder_stack_->Encode(
Yves Gerey665174f2018-06-19 15:03:05 +0200341 rtp_timestamp,
342 rtc::ArrayView<const int16_t>(
343 input_data.audio,
344 input_data.audio_channel * input_data.length_per_channel),
kwibergc13ded52016-06-17 06:00:45 -0700345 &encode_buffer_);
346
347 bitrate_logger_.MaybeLog(encoder_stack_->GetTargetBitrate() / 1000);
348 if (encode_buffer_.size() == 0 && !encoded_info.send_even_if_empty) {
349 // Not enough data.
350 return 0;
351 }
352 previous_pltype = previous_pltype_; // Read it while we have the critsect.
353
354 // Log codec type to histogram once every 500 packets.
355 if (encoded_info.encoded_bytes == 0) {
356 ++number_of_consecutive_empty_packets_;
357 } else {
358 size_t codec_type = static_cast<size_t>(encoded_info.encoder_type);
359 codec_histogram_bins_log_[codec_type] +=
360 number_of_consecutive_empty_packets_ + 1;
361 number_of_consecutive_empty_packets_ = 0;
362 if (codec_histogram_bins_log_[codec_type] >= 500) {
363 codec_histogram_bins_log_[codec_type] -= 500;
364 UpdateCodecTypeHistogram(codec_type);
365 }
366 }
367
Niels Möller87e2d782019-03-07 10:18:23 +0100368 AudioFrameType frame_type;
kwibergc13ded52016-06-17 06:00:45 -0700369 if (encode_buffer_.size() == 0 && encoded_info.send_even_if_empty) {
Niels Möllerc936cb62019-03-19 14:10:16 +0100370 frame_type = AudioFrameType::kEmptyFrame;
kwibergc13ded52016-06-17 06:00:45 -0700371 encoded_info.payload_type = previous_pltype;
372 } else {
kwibergaf476c72016-11-28 15:21:39 -0800373 RTC_DCHECK_GT(encode_buffer_.size(), 0);
Niels Möllerc936cb62019-03-19 14:10:16 +0100374 frame_type = encoded_info.speech ? AudioFrameType::kAudioFrameSpeech
375 : AudioFrameType::kAudioFrameCN;
kwibergc13ded52016-06-17 06:00:45 -0700376 }
377
378 {
379 rtc::CritScope lock(&callback_crit_sect_);
380 if (packetization_callback_) {
381 packetization_callback_->SendData(
382 frame_type, encoded_info.payload_type, encoded_info.encoded_timestamp,
Niels Möllerc35b6e62019-04-25 16:31:18 +0200383 encode_buffer_.data(), encode_buffer_.size());
kwibergc13ded52016-06-17 06:00:45 -0700384 }
385
386 if (vad_callback_) {
387 // Callback with VAD decision.
388 vad_callback_->InFrameType(frame_type);
389 }
390 }
391 previous_pltype_ = encoded_info.payload_type;
392 return static_cast<int32_t>(encode_buffer_.size());
393}
394
395/////////////////////////////////////////
396// Sender
397//
398
kwibergc13ded52016-06-17 06:00:45 -0700399void AudioCodingModuleImpl::ModifyEncoder(
kwiberg24c7c122016-09-28 11:57:10 -0700400 rtc::FunctionView<void(std::unique_ptr<AudioEncoder>*)> modifier) {
kwibergc13ded52016-06-17 06:00:45 -0700401 rtc::CritScope lock(&acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700402 modifier(&encoder_stack_);
403}
404
kwibergc13ded52016-06-17 06:00:45 -0700405// Register a transport callback which will be called to deliver
406// the encoded buffers.
407int AudioCodingModuleImpl::RegisterTransportCallback(
408 AudioPacketizationCallback* transport) {
409 rtc::CritScope lock(&callback_crit_sect_);
410 packetization_callback_ = transport;
411 return 0;
412}
413
414// Add 10MS of raw (PCM) audio data to the encoder.
415int AudioCodingModuleImpl::Add10MsData(const AudioFrame& audio_frame) {
416 InputData input_data;
417 rtc::CritScope lock(&acm_crit_sect_);
418 int r = Add10MsDataInternal(audio_frame, &input_data);
419 return r < 0 ? r : Encode(input_data);
420}
421
422int AudioCodingModuleImpl::Add10MsDataInternal(const AudioFrame& audio_frame,
423 InputData* input_data) {
424 if (audio_frame.samples_per_channel_ == 0) {
425 assert(false);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100426 RTC_LOG(LS_ERROR) << "Cannot Add 10 ms audio, payload length is zero";
kwibergc13ded52016-06-17 06:00:45 -0700427 return -1;
428 }
429
430 if (audio_frame.sample_rate_hz_ > 48000) {
431 assert(false);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100432 RTC_LOG(LS_ERROR) << "Cannot Add 10 ms audio, input frequency not valid";
kwibergc13ded52016-06-17 06:00:45 -0700433 return -1;
434 }
435
436 // If the length and frequency matches. We currently just support raw PCM.
437 if (static_cast<size_t>(audio_frame.sample_rate_hz_ / 100) !=
438 audio_frame.samples_per_channel_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100439 RTC_LOG(LS_ERROR)
Alex Loiko300ec8c2017-05-30 17:23:28 +0200440 << "Cannot Add 10 ms audio, input frequency and length doesn't match";
kwibergc13ded52016-06-17 06:00:45 -0700441 return -1;
442 }
443
Alex Loiko65438812019-02-22 10:13:44 +0100444 if (audio_frame.num_channels_ != 1 && audio_frame.num_channels_ != 2 &&
445 audio_frame.num_channels_ != 4 && audio_frame.num_channels_ != 6 &&
446 audio_frame.num_channels_ != 8) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100447 RTC_LOG(LS_ERROR) << "Cannot Add 10 ms audio, invalid number of channels.";
kwibergc13ded52016-06-17 06:00:45 -0700448 return -1;
449 }
450
451 // Do we have a codec registered?
452 if (!HaveValidEncoder("Add10MsData")) {
453 return -1;
454 }
455
456 const AudioFrame* ptr_frame;
457 // Perform a resampling, also down-mix if it is required and can be
458 // performed before resampling (a down mix prior to resampling will take
459 // place if both primary and secondary encoders are mono and input is in
460 // stereo).
461 if (PreprocessToAddData(audio_frame, &ptr_frame) < 0) {
462 return -1;
463 }
464
465 // Check whether we need an up-mix or down-mix?
466 const size_t current_num_channels = encoder_stack_->NumChannels();
467 const bool same_num_channels =
468 ptr_frame->num_channels_ == current_num_channels;
469
470 if (!same_num_channels) {
471 if (ptr_frame->num_channels_ == 1) {
472 if (UpMix(*ptr_frame, WEBRTC_10MS_PCM_AUDIO, input_data->buffer) < 0)
473 return -1;
474 } else {
475 if (DownMix(*ptr_frame, WEBRTC_10MS_PCM_AUDIO, input_data->buffer) < 0)
476 return -1;
477 }
478 }
479
480 // When adding data to encoders this pointer is pointing to an audio buffer
481 // with correct number of channels.
yujo36b1a5f2017-06-12 12:45:32 -0700482 const int16_t* ptr_audio = ptr_frame->data();
kwibergc13ded52016-06-17 06:00:45 -0700483
484 // For pushing data to primary, point the |ptr_audio| to correct buffer.
485 if (!same_num_channels)
486 ptr_audio = input_data->buffer;
487
yujo36b1a5f2017-06-12 12:45:32 -0700488 // TODO(yujo): Skip encode of muted frames.
kwibergc13ded52016-06-17 06:00:45 -0700489 input_data->input_timestamp = ptr_frame->timestamp_;
490 input_data->audio = ptr_audio;
491 input_data->length_per_channel = ptr_frame->samples_per_channel_;
492 input_data->audio_channel = current_num_channels;
493
494 return 0;
495}
496
497// Perform a resampling and down-mix if required. We down-mix only if
498// encoder is mono and input is stereo. In case of dual-streaming, both
499// encoders has to be mono for down-mix to take place.
500// |*ptr_out| will point to the pre-processed audio-frame. If no pre-processing
501// is required, |*ptr_out| points to |in_frame|.
yujo36b1a5f2017-06-12 12:45:32 -0700502// TODO(yujo): Make this more efficient for muted frames.
kwibergc13ded52016-06-17 06:00:45 -0700503int AudioCodingModuleImpl::PreprocessToAddData(const AudioFrame& in_frame,
504 const AudioFrame** ptr_out) {
505 const bool resample =
506 in_frame.sample_rate_hz_ != encoder_stack_->SampleRateHz();
507
508 // This variable is true if primary codec and secondary codec (if exists)
509 // are both mono and input is stereo.
510 // TODO(henrik.lundin): This condition should probably be
511 // in_frame.num_channels_ > encoder_stack_->NumChannels()
512 const bool down_mix =
513 in_frame.num_channels_ == 2 && encoder_stack_->NumChannels() == 1;
514
515 if (!first_10ms_data_) {
516 expected_in_ts_ = in_frame.timestamp_;
517 expected_codec_ts_ = in_frame.timestamp_;
518 first_10ms_data_ = true;
519 } else if (in_frame.timestamp_ != expected_in_ts_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100520 RTC_LOG(LS_WARNING) << "Unexpected input timestamp: " << in_frame.timestamp_
521 << ", expected: " << expected_in_ts_;
kwibergc13ded52016-06-17 06:00:45 -0700522 expected_codec_ts_ +=
523 (in_frame.timestamp_ - expected_in_ts_) *
524 static_cast<uint32_t>(
525 static_cast<double>(encoder_stack_->SampleRateHz()) /
526 static_cast<double>(in_frame.sample_rate_hz_));
527 expected_in_ts_ = in_frame.timestamp_;
528 }
529
kwibergc13ded52016-06-17 06:00:45 -0700530 if (!down_mix && !resample) {
531 // No pre-processing is required.
ossu63fb95a2016-07-06 09:34:22 -0700532 if (expected_in_ts_ == expected_codec_ts_) {
533 // If we've never resampled, we can use the input frame as-is
534 *ptr_out = &in_frame;
535 } else {
536 // Otherwise we'll need to alter the timestamp. Since in_frame is const,
537 // we'll have to make a copy of it.
538 preprocess_frame_.CopyFrom(in_frame);
539 preprocess_frame_.timestamp_ = expected_codec_ts_;
540 *ptr_out = &preprocess_frame_;
541 }
542
kwibergc13ded52016-06-17 06:00:45 -0700543 expected_in_ts_ += static_cast<uint32_t>(in_frame.samples_per_channel_);
544 expected_codec_ts_ += static_cast<uint32_t>(in_frame.samples_per_channel_);
kwibergc13ded52016-06-17 06:00:45 -0700545 return 0;
546 }
547
548 *ptr_out = &preprocess_frame_;
549 preprocess_frame_.num_channels_ = in_frame.num_channels_;
550 int16_t audio[WEBRTC_10MS_PCM_AUDIO];
yujo36b1a5f2017-06-12 12:45:32 -0700551 const int16_t* src_ptr_audio = in_frame.data();
kwibergc13ded52016-06-17 06:00:45 -0700552 if (down_mix) {
553 // If a resampling is required the output of a down-mix is written into a
554 // local buffer, otherwise, it will be written to the output frame.
Yves Gerey665174f2018-06-19 15:03:05 +0200555 int16_t* dest_ptr_audio =
556 resample ? audio : preprocess_frame_.mutable_data();
kwibergc13ded52016-06-17 06:00:45 -0700557 if (DownMix(in_frame, WEBRTC_10MS_PCM_AUDIO, dest_ptr_audio) < 0)
558 return -1;
559 preprocess_frame_.num_channels_ = 1;
560 // Set the input of the resampler is the down-mixed signal.
561 src_ptr_audio = audio;
562 }
563
564 preprocess_frame_.timestamp_ = expected_codec_ts_;
565 preprocess_frame_.samples_per_channel_ = in_frame.samples_per_channel_;
566 preprocess_frame_.sample_rate_hz_ = in_frame.sample_rate_hz_;
567 // If it is required, we have to do a resampling.
568 if (resample) {
569 // The result of the resampler is written to output frame.
yujo36b1a5f2017-06-12 12:45:32 -0700570 int16_t* dest_ptr_audio = preprocess_frame_.mutable_data();
kwibergc13ded52016-06-17 06:00:45 -0700571
572 int samples_per_channel = resampler_.Resample10Msec(
573 src_ptr_audio, in_frame.sample_rate_hz_, encoder_stack_->SampleRateHz(),
574 preprocess_frame_.num_channels_, AudioFrame::kMaxDataSizeSamples,
575 dest_ptr_audio);
576
577 if (samples_per_channel < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100578 RTC_LOG(LS_ERROR) << "Cannot add 10 ms audio, resampling failed";
kwibergc13ded52016-06-17 06:00:45 -0700579 return -1;
580 }
581 preprocess_frame_.samples_per_channel_ =
582 static_cast<size_t>(samples_per_channel);
583 preprocess_frame_.sample_rate_hz_ = encoder_stack_->SampleRateHz();
584 }
585
586 expected_codec_ts_ +=
587 static_cast<uint32_t>(preprocess_frame_.samples_per_channel_);
588 expected_in_ts_ += static_cast<uint32_t>(in_frame.samples_per_channel_);
589
590 return 0;
591}
592
593/////////////////////////////////////////
kwibergc13ded52016-06-17 06:00:45 -0700594// (FEC) Forward Error Correction (codec internal)
595//
596
kwibergc13ded52016-06-17 06:00:45 -0700597int AudioCodingModuleImpl::SetPacketLossRate(int loss_rate) {
598 rtc::CritScope lock(&acm_crit_sect_);
599 if (HaveValidEncoder("SetPacketLossRate")) {
minyue4b9a2cb2016-11-30 06:49:59 -0800600 encoder_stack_->OnReceivedUplinkPacketLossFraction(loss_rate / 100.0);
kwibergc13ded52016-06-17 06:00:45 -0700601 }
602 return 0;
603}
604
605/////////////////////////////////////////
kwibergc13ded52016-06-17 06:00:45 -0700606// Receiver
607//
608
609int AudioCodingModuleImpl::InitializeReceiver() {
610 rtc::CritScope lock(&acm_crit_sect_);
611 return InitializeReceiverSafe();
612}
613
614// Initialize receiver, resets codec database etc.
615int AudioCodingModuleImpl::InitializeReceiverSafe() {
616 // If the receiver is already initialized then we want to destroy any
617 // existing decoders. After a call to this function, we should have a clean
618 // start-up.
kwiberg6b19b562016-09-20 04:02:25 -0700619 if (receiver_initialized_)
620 receiver_.RemoveAllCodecs();
kwibergc13ded52016-06-17 06:00:45 -0700621 receiver_.FlushBuffers();
622
kwibergc13ded52016-06-17 06:00:45 -0700623 receiver_initialized_ = true;
624 return 0;
625}
626
627// Get current receive frequency.
628int AudioCodingModuleImpl::ReceiveFrequency() const {
629 const auto last_packet_sample_rate = receiver_.last_packet_sample_rate_hz();
630 return last_packet_sample_rate ? *last_packet_sample_rate
631 : receiver_.last_output_sample_rate_hz();
632}
633
634// Get current playout frequency.
635int AudioCodingModuleImpl::PlayoutFrequency() const {
kwibergc13ded52016-06-17 06:00:45 -0700636 return receiver_.last_output_sample_rate_hz();
637}
638
kwiberg1c07c702017-03-27 07:15:49 -0700639void AudioCodingModuleImpl::SetReceiveCodecs(
640 const std::map<int, SdpAudioFormat>& codecs) {
641 rtc::CritScope lock(&acm_crit_sect_);
642 receiver_.SetCodecs(codecs);
643}
644
Fredrik Solenbergf693bfa2018-12-11 12:22:10 +0100645absl::optional<std::pair<int, SdpAudioFormat>>
Jonas Olssona4d87372019-07-05 19:08:33 +0200646AudioCodingModuleImpl::ReceiveCodec() const {
kwiberg5adaf732016-10-04 09:33:27 -0700647 rtc::CritScope lock(&acm_crit_sect_);
Fredrik Solenbergf693bfa2018-12-11 12:22:10 +0100648 return receiver_.LastDecoder();
ossue280cde2016-10-12 11:04:10 -0700649}
650
kwibergc13ded52016-06-17 06:00:45 -0700651// Incoming packet from network parsed and ready for decode.
652int AudioCodingModuleImpl::IncomingPacket(const uint8_t* incoming_payload,
653 const size_t payload_length,
Niels Möllerafb5dbb2019-02-15 15:21:47 +0100654 const RTPHeader& rtp_header) {
henrik.lundinb8c55b12017-05-10 07:38:01 -0700655 RTC_DCHECK_EQ(payload_length == 0, incoming_payload == nullptr);
kwibergc13ded52016-06-17 06:00:45 -0700656 return receiver_.InsertPacket(
657 rtp_header,
658 rtc::ArrayView<const uint8_t>(incoming_payload, payload_length));
659}
660
661// Minimum playout delay (Used for lip-sync).
662int AudioCodingModuleImpl::SetMinimumPlayoutDelay(int time_ms) {
663 if ((time_ms < 0) || (time_ms > 10000)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100664 RTC_LOG(LS_ERROR) << "Delay must be in the range of 0-10000 milliseconds.";
kwibergc13ded52016-06-17 06:00:45 -0700665 return -1;
666 }
667 return receiver_.SetMinimumDelay(time_ms);
668}
669
670int AudioCodingModuleImpl::SetMaximumPlayoutDelay(int time_ms) {
671 if ((time_ms < 0) || (time_ms > 10000)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100672 RTC_LOG(LS_ERROR) << "Delay must be in the range of 0-10000 milliseconds.";
kwibergc13ded52016-06-17 06:00:45 -0700673 return -1;
674 }
675 return receiver_.SetMaximumDelay(time_ms);
676}
677
Ruslan Burakov3b50f9f2019-02-06 09:45:56 +0100678bool AudioCodingModuleImpl::SetBaseMinimumPlayoutDelayMs(int delay_ms) {
679 // All necessary validation happens on NetEq level.
680 return receiver_.SetBaseMinimumDelayMs(delay_ms);
681}
682
683int AudioCodingModuleImpl::GetBaseMinimumPlayoutDelayMs() const {
684 return receiver_.GetBaseMinimumDelayMs();
685}
686
kwibergc13ded52016-06-17 06:00:45 -0700687// Get 10 milliseconds of raw audio data to play out.
688// Automatic resample to the requested frequency.
689int AudioCodingModuleImpl::PlayoutData10Ms(int desired_freq_hz,
690 AudioFrame* audio_frame,
691 bool* muted) {
692 // GetAudio always returns 10 ms, at the requested sample rate.
693 if (receiver_.GetAudio(desired_freq_hz, audio_frame, muted) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100694 RTC_LOG(LS_ERROR) << "PlayoutData failed, RecOut Failed";
kwibergc13ded52016-06-17 06:00:45 -0700695 return -1;
696 }
kwibergc13ded52016-06-17 06:00:45 -0700697 return 0;
698}
699
kwibergc13ded52016-06-17 06:00:45 -0700700/////////////////////////////////////////
701// Statistics
702//
703
704// TODO(turajs) change the return value to void. Also change the corresponding
705// NetEq function.
706int AudioCodingModuleImpl::GetNetworkStatistics(NetworkStatistics* statistics) {
707 receiver_.GetNetworkStatistics(statistics);
708 return 0;
709}
710
711int AudioCodingModuleImpl::RegisterVADCallback(ACMVADCallback* vad_callback) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100712 RTC_LOG(LS_VERBOSE) << "RegisterVADCallback()";
kwibergc13ded52016-06-17 06:00:45 -0700713 rtc::CritScope lock(&callback_crit_sect_);
714 vad_callback_ = vad_callback;
715 return 0;
716}
717
kwibergc13ded52016-06-17 06:00:45 -0700718// Informs Opus encoder of the maximum playback rate the receiver will render.
719int AudioCodingModuleImpl::SetOpusMaxPlaybackRate(int frequency_hz) {
720 rtc::CritScope lock(&acm_crit_sect_);
721 if (!HaveValidEncoder("SetOpusMaxPlaybackRate")) {
722 return -1;
723 }
724 encoder_stack_->SetMaxPlaybackRate(frequency_hz);
725 return 0;
726}
727
728int AudioCodingModuleImpl::EnableOpusDtx() {
729 rtc::CritScope lock(&acm_crit_sect_);
730 if (!HaveValidEncoder("EnableOpusDtx")) {
731 return -1;
732 }
733 return encoder_stack_->SetDtx(true) ? 0 : -1;
734}
735
736int AudioCodingModuleImpl::DisableOpusDtx() {
737 rtc::CritScope lock(&acm_crit_sect_);
738 if (!HaveValidEncoder("DisableOpusDtx")) {
739 return -1;
740 }
741 return encoder_stack_->SetDtx(false) ? 0 : -1;
742}
743
Danil Chapovalovb6021232018-06-19 13:26:36 +0200744absl::optional<uint32_t> AudioCodingModuleImpl::PlayoutTimestamp() {
kwibergc13ded52016-06-17 06:00:45 -0700745 return receiver_.GetPlayoutTimestamp();
746}
747
henrik.lundinb3f1c5d2016-08-22 15:39:53 -0700748int AudioCodingModuleImpl::FilteredCurrentDelayMs() const {
749 return receiver_.FilteredCurrentDelayMs();
750}
751
Henrik Lundinabbff892017-11-29 09:14:04 +0100752int AudioCodingModuleImpl::TargetDelayMs() const {
753 return receiver_.TargetDelayMs();
754}
755
kwibergc13ded52016-06-17 06:00:45 -0700756bool AudioCodingModuleImpl::HaveValidEncoder(const char* caller_name) const {
757 if (!encoder_stack_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100758 RTC_LOG(LS_ERROR) << caller_name << " failed: No send codec is registered.";
kwibergc13ded52016-06-17 06:00:45 -0700759 return false;
760 }
761 return true;
762}
763
kwibergc13ded52016-06-17 06:00:45 -0700764int AudioCodingModuleImpl::EnableNack(size_t max_nack_list_size) {
765 return receiver_.EnableNack(max_nack_list_size);
766}
767
768void AudioCodingModuleImpl::DisableNack() {
769 receiver_.DisableNack();
770}
771
772std::vector<uint16_t> AudioCodingModuleImpl::GetNackList(
773 int64_t round_trip_time_ms) const {
774 return receiver_.GetNackList(round_trip_time_ms);
775}
776
kwibergc13ded52016-06-17 06:00:45 -0700777void AudioCodingModuleImpl::GetDecodingCallStatistics(
Yves Gerey665174f2018-06-19 15:03:05 +0200778 AudioDecodingCallStats* call_stats) const {
kwibergc13ded52016-06-17 06:00:45 -0700779 receiver_.GetDecodingCallStatistics(call_stats);
780}
781
ivoce1198e02017-09-08 08:13:19 -0700782ANAStats AudioCodingModuleImpl::GetANAStats() const {
783 rtc::CritScope lock(&acm_crit_sect_);
784 if (encoder_stack_)
785 return encoder_stack_->GetANAStats();
786 // If no encoder is set, return default stats.
787 return ANAStats();
788}
789
kwibergc13ded52016-06-17 06:00:45 -0700790} // namespace
791
Karl Wiberg5817d3d2018-04-06 10:06:42 +0200792AudioCodingModule::Config::Config(
793 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory)
794 : neteq_config(),
795 clock(Clock::GetRealTimeClock()),
796 decoder_factory(decoder_factory) {
kwiberg36a43882016-08-29 05:33:32 -0700797 // Post-decode VAD is disabled by default in NetEq, however, Audio
798 // Conference Mixer relies on VAD decisions and fails without them.
799 neteq_config.enable_post_decode_vad = true;
800}
801
802AudioCodingModule::Config::Config(const Config&) = default;
803AudioCodingModule::Config::~Config() = default;
804
Henrik Lundin64dad832015-05-11 12:44:23 +0200805AudioCodingModule* AudioCodingModule::Create(const Config& config) {
kwibergc13ded52016-06-17 06:00:45 -0700806 return new AudioCodingModuleImpl(config);
turaj@webrtc.org7959e162013-09-12 18:30:26 +0000807}
808
turaj@webrtc.org7959e162013-09-12 18:30:26 +0000809} // namespace webrtc