blob: b5c597395ee577fac3aa6572db7e5b0139ced878 [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
285void ConvertEncodedInfoToFragmentationHeader(
286 const AudioEncoder::EncodedInfo& info,
287 RTPFragmentationHeader* frag) {
288 if (info.redundant.empty()) {
289 frag->fragmentationVectorSize = 0;
290 return;
291 }
292
293 frag->VerifyAndAllocateFragmentationHeader(
294 static_cast<uint16_t>(info.redundant.size()));
295 frag->fragmentationVectorSize = static_cast<uint16_t>(info.redundant.size());
296 size_t offset = 0;
297 for (size_t i = 0; i < info.redundant.size(); ++i) {
298 frag->fragmentationOffset[i] = offset;
299 offset += info.redundant[i].encoded_bytes;
300 frag->fragmentationLength[i] = info.redundant[i].encoded_bytes;
kwibergd3edd772017-03-01 18:52:48 -0800301 frag->fragmentationTimeDiff[i] = rtc::dchecked_cast<uint16_t>(
kwibergc13ded52016-06-17 06:00:45 -0700302 info.encoded_timestamp - info.redundant[i].encoded_timestamp);
303 frag->fragmentationPlType[i] = info.redundant[i].payload_type;
304 }
305}
306
kwibergc13ded52016-06-17 06:00:45 -0700307void AudioCodingModuleImpl::ChangeLogger::MaybeLog(int value) {
308 if (value != last_value_ || first_time_) {
309 first_time_ = false;
310 last_value_ = value;
311 RTC_HISTOGRAM_COUNTS_SPARSE_100(histogram_name_, value);
312 }
313}
314
315AudioCodingModuleImpl::AudioCodingModuleImpl(
316 const AudioCodingModule::Config& config)
solenbergc7b4a452017-09-28 07:37:11 -0700317 : expected_codec_ts_(0xD87F3F9F),
kwibergc13ded52016-06-17 06:00:45 -0700318 expected_in_ts_(0xD87F3F9F),
319 receiver_(config),
320 bitrate_logger_("WebRTC.Audio.TargetBitrateInKbps"),
kwibergc13ded52016-06-17 06:00:45 -0700321 encoder_stack_(nullptr),
322 previous_pltype_(255),
323 receiver_initialized_(false),
324 first_10ms_data_(false),
325 first_frame_(true),
326 packetization_callback_(NULL),
327 vad_callback_(NULL),
328 codec_histogram_bins_log_(),
329 number_of_consecutive_empty_packets_(0) {
330 if (InitializeReceiverSafe() < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100331 RTC_LOG(LS_ERROR) << "Cannot initialize receiver";
kwibergc13ded52016-06-17 06:00:45 -0700332 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100333 RTC_LOG(LS_INFO) << "Created";
kwibergc13ded52016-06-17 06:00:45 -0700334}
335
336AudioCodingModuleImpl::~AudioCodingModuleImpl() = default;
337
338int32_t AudioCodingModuleImpl::Encode(const InputData& input_data) {
339 AudioEncoder::EncodedInfo encoded_info;
340 uint8_t previous_pltype;
341
342 // Check if there is an encoder before.
343 if (!HaveValidEncoder("Process"))
344 return -1;
345
Yves Gerey665174f2018-06-19 15:03:05 +0200346 if (!first_frame_) {
deadbeeffcada902016-08-24 12:45:13 -0700347 RTC_DCHECK(IsNewerTimestamp(input_data.input_timestamp, last_timestamp_))
ossu63fb95a2016-07-06 09:34:22 -0700348 << "Time should not move backwards";
349 }
350
kwibergc13ded52016-06-17 06:00:45 -0700351 // Scale the timestamp to the codec's RTP timestamp rate.
352 uint32_t rtp_timestamp =
353 first_frame_ ? input_data.input_timestamp
354 : last_rtp_timestamp_ +
355 rtc::CheckedDivExact(
356 input_data.input_timestamp - last_timestamp_,
357 static_cast<uint32_t>(rtc::CheckedDivExact(
358 encoder_stack_->SampleRateHz(),
359 encoder_stack_->RtpTimestampRateHz())));
360 last_timestamp_ = input_data.input_timestamp;
361 last_rtp_timestamp_ = rtp_timestamp;
362 first_frame_ = false;
363
364 // Clear the buffer before reuse - encoded data will get appended.
365 encode_buffer_.Clear();
366 encoded_info = encoder_stack_->Encode(
Yves Gerey665174f2018-06-19 15:03:05 +0200367 rtp_timestamp,
368 rtc::ArrayView<const int16_t>(
369 input_data.audio,
370 input_data.audio_channel * input_data.length_per_channel),
kwibergc13ded52016-06-17 06:00:45 -0700371 &encode_buffer_);
372
373 bitrate_logger_.MaybeLog(encoder_stack_->GetTargetBitrate() / 1000);
374 if (encode_buffer_.size() == 0 && !encoded_info.send_even_if_empty) {
375 // Not enough data.
376 return 0;
377 }
378 previous_pltype = previous_pltype_; // Read it while we have the critsect.
379
380 // Log codec type to histogram once every 500 packets.
381 if (encoded_info.encoded_bytes == 0) {
382 ++number_of_consecutive_empty_packets_;
383 } else {
384 size_t codec_type = static_cast<size_t>(encoded_info.encoder_type);
385 codec_histogram_bins_log_[codec_type] +=
386 number_of_consecutive_empty_packets_ + 1;
387 number_of_consecutive_empty_packets_ = 0;
388 if (codec_histogram_bins_log_[codec_type] >= 500) {
389 codec_histogram_bins_log_[codec_type] -= 500;
390 UpdateCodecTypeHistogram(codec_type);
391 }
392 }
393
394 RTPFragmentationHeader my_fragmentation;
395 ConvertEncodedInfoToFragmentationHeader(encoded_info, &my_fragmentation);
Niels Möller87e2d782019-03-07 10:18:23 +0100396 AudioFrameType frame_type;
kwibergc13ded52016-06-17 06:00:45 -0700397 if (encode_buffer_.size() == 0 && encoded_info.send_even_if_empty) {
Niels Möllerc936cb62019-03-19 14:10:16 +0100398 frame_type = AudioFrameType::kEmptyFrame;
kwibergc13ded52016-06-17 06:00:45 -0700399 encoded_info.payload_type = previous_pltype;
400 } else {
kwibergaf476c72016-11-28 15:21:39 -0800401 RTC_DCHECK_GT(encode_buffer_.size(), 0);
Niels Möllerc936cb62019-03-19 14:10:16 +0100402 frame_type = encoded_info.speech ? AudioFrameType::kAudioFrameSpeech
403 : AudioFrameType::kAudioFrameCN;
kwibergc13ded52016-06-17 06:00:45 -0700404 }
405
406 {
407 rtc::CritScope lock(&callback_crit_sect_);
408 if (packetization_callback_) {
409 packetization_callback_->SendData(
410 frame_type, encoded_info.payload_type, encoded_info.encoded_timestamp,
411 encode_buffer_.data(), encode_buffer_.size(),
412 my_fragmentation.fragmentationVectorSize > 0 ? &my_fragmentation
413 : nullptr);
414 }
415
416 if (vad_callback_) {
417 // Callback with VAD decision.
418 vad_callback_->InFrameType(frame_type);
419 }
420 }
421 previous_pltype_ = encoded_info.payload_type;
422 return static_cast<int32_t>(encode_buffer_.size());
423}
424
425/////////////////////////////////////////
426// Sender
427//
428
kwibergc13ded52016-06-17 06:00:45 -0700429void AudioCodingModuleImpl::ModifyEncoder(
kwiberg24c7c122016-09-28 11:57:10 -0700430 rtc::FunctionView<void(std::unique_ptr<AudioEncoder>*)> modifier) {
kwibergc13ded52016-06-17 06:00:45 -0700431 rtc::CritScope lock(&acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700432 modifier(&encoder_stack_);
433}
434
kwibergc13ded52016-06-17 06:00:45 -0700435void AudioCodingModuleImpl::SetBitRate(int bitrate_bps) {
436 rtc::CritScope lock(&acm_crit_sect_);
437 if (encoder_stack_) {
Danil Chapovalovb6021232018-06-19 13:26:36 +0200438 encoder_stack_->OnReceivedUplinkBandwidth(bitrate_bps, absl::nullopt);
kwibergc13ded52016-06-17 06:00:45 -0700439 }
440}
441
442// Register a transport callback which will be called to deliver
443// the encoded buffers.
444int AudioCodingModuleImpl::RegisterTransportCallback(
445 AudioPacketizationCallback* transport) {
446 rtc::CritScope lock(&callback_crit_sect_);
447 packetization_callback_ = transport;
448 return 0;
449}
450
451// Add 10MS of raw (PCM) audio data to the encoder.
452int AudioCodingModuleImpl::Add10MsData(const AudioFrame& audio_frame) {
453 InputData input_data;
454 rtc::CritScope lock(&acm_crit_sect_);
455 int r = Add10MsDataInternal(audio_frame, &input_data);
456 return r < 0 ? r : Encode(input_data);
457}
458
459int AudioCodingModuleImpl::Add10MsDataInternal(const AudioFrame& audio_frame,
460 InputData* input_data) {
461 if (audio_frame.samples_per_channel_ == 0) {
462 assert(false);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100463 RTC_LOG(LS_ERROR) << "Cannot Add 10 ms audio, payload length is zero";
kwibergc13ded52016-06-17 06:00:45 -0700464 return -1;
465 }
466
467 if (audio_frame.sample_rate_hz_ > 48000) {
468 assert(false);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100469 RTC_LOG(LS_ERROR) << "Cannot Add 10 ms audio, input frequency not valid";
kwibergc13ded52016-06-17 06:00:45 -0700470 return -1;
471 }
472
473 // If the length and frequency matches. We currently just support raw PCM.
474 if (static_cast<size_t>(audio_frame.sample_rate_hz_ / 100) !=
475 audio_frame.samples_per_channel_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100476 RTC_LOG(LS_ERROR)
Alex Loiko300ec8c2017-05-30 17:23:28 +0200477 << "Cannot Add 10 ms audio, input frequency and length doesn't match";
kwibergc13ded52016-06-17 06:00:45 -0700478 return -1;
479 }
480
Alex Loiko65438812019-02-22 10:13:44 +0100481 if (audio_frame.num_channels_ != 1 && audio_frame.num_channels_ != 2 &&
482 audio_frame.num_channels_ != 4 && audio_frame.num_channels_ != 6 &&
483 audio_frame.num_channels_ != 8) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100484 RTC_LOG(LS_ERROR) << "Cannot Add 10 ms audio, invalid number of channels.";
kwibergc13ded52016-06-17 06:00:45 -0700485 return -1;
486 }
487
488 // Do we have a codec registered?
489 if (!HaveValidEncoder("Add10MsData")) {
490 return -1;
491 }
492
493 const AudioFrame* ptr_frame;
494 // Perform a resampling, also down-mix if it is required and can be
495 // performed before resampling (a down mix prior to resampling will take
496 // place if both primary and secondary encoders are mono and input is in
497 // stereo).
498 if (PreprocessToAddData(audio_frame, &ptr_frame) < 0) {
499 return -1;
500 }
501
502 // Check whether we need an up-mix or down-mix?
503 const size_t current_num_channels = encoder_stack_->NumChannels();
504 const bool same_num_channels =
505 ptr_frame->num_channels_ == current_num_channels;
506
507 if (!same_num_channels) {
508 if (ptr_frame->num_channels_ == 1) {
509 if (UpMix(*ptr_frame, WEBRTC_10MS_PCM_AUDIO, input_data->buffer) < 0)
510 return -1;
511 } else {
512 if (DownMix(*ptr_frame, WEBRTC_10MS_PCM_AUDIO, input_data->buffer) < 0)
513 return -1;
514 }
515 }
516
517 // When adding data to encoders this pointer is pointing to an audio buffer
518 // with correct number of channels.
yujo36b1a5f2017-06-12 12:45:32 -0700519 const int16_t* ptr_audio = ptr_frame->data();
kwibergc13ded52016-06-17 06:00:45 -0700520
521 // For pushing data to primary, point the |ptr_audio| to correct buffer.
522 if (!same_num_channels)
523 ptr_audio = input_data->buffer;
524
yujo36b1a5f2017-06-12 12:45:32 -0700525 // TODO(yujo): Skip encode of muted frames.
kwibergc13ded52016-06-17 06:00:45 -0700526 input_data->input_timestamp = ptr_frame->timestamp_;
527 input_data->audio = ptr_audio;
528 input_data->length_per_channel = ptr_frame->samples_per_channel_;
529 input_data->audio_channel = current_num_channels;
530
531 return 0;
532}
533
534// Perform a resampling and down-mix if required. We down-mix only if
535// encoder is mono and input is stereo. In case of dual-streaming, both
536// encoders has to be mono for down-mix to take place.
537// |*ptr_out| will point to the pre-processed audio-frame. If no pre-processing
538// is required, |*ptr_out| points to |in_frame|.
yujo36b1a5f2017-06-12 12:45:32 -0700539// TODO(yujo): Make this more efficient for muted frames.
kwibergc13ded52016-06-17 06:00:45 -0700540int AudioCodingModuleImpl::PreprocessToAddData(const AudioFrame& in_frame,
541 const AudioFrame** ptr_out) {
542 const bool resample =
543 in_frame.sample_rate_hz_ != encoder_stack_->SampleRateHz();
544
545 // This variable is true if primary codec and secondary codec (if exists)
546 // are both mono and input is stereo.
547 // TODO(henrik.lundin): This condition should probably be
548 // in_frame.num_channels_ > encoder_stack_->NumChannels()
549 const bool down_mix =
550 in_frame.num_channels_ == 2 && encoder_stack_->NumChannels() == 1;
551
552 if (!first_10ms_data_) {
553 expected_in_ts_ = in_frame.timestamp_;
554 expected_codec_ts_ = in_frame.timestamp_;
555 first_10ms_data_ = true;
556 } else if (in_frame.timestamp_ != expected_in_ts_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100557 RTC_LOG(LS_WARNING) << "Unexpected input timestamp: " << in_frame.timestamp_
558 << ", expected: " << expected_in_ts_;
kwibergc13ded52016-06-17 06:00:45 -0700559 expected_codec_ts_ +=
560 (in_frame.timestamp_ - expected_in_ts_) *
561 static_cast<uint32_t>(
562 static_cast<double>(encoder_stack_->SampleRateHz()) /
563 static_cast<double>(in_frame.sample_rate_hz_));
564 expected_in_ts_ = in_frame.timestamp_;
565 }
566
kwibergc13ded52016-06-17 06:00:45 -0700567 if (!down_mix && !resample) {
568 // No pre-processing is required.
ossu63fb95a2016-07-06 09:34:22 -0700569 if (expected_in_ts_ == expected_codec_ts_) {
570 // If we've never resampled, we can use the input frame as-is
571 *ptr_out = &in_frame;
572 } else {
573 // Otherwise we'll need to alter the timestamp. Since in_frame is const,
574 // we'll have to make a copy of it.
575 preprocess_frame_.CopyFrom(in_frame);
576 preprocess_frame_.timestamp_ = expected_codec_ts_;
577 *ptr_out = &preprocess_frame_;
578 }
579
kwibergc13ded52016-06-17 06:00:45 -0700580 expected_in_ts_ += static_cast<uint32_t>(in_frame.samples_per_channel_);
581 expected_codec_ts_ += static_cast<uint32_t>(in_frame.samples_per_channel_);
kwibergc13ded52016-06-17 06:00:45 -0700582 return 0;
583 }
584
585 *ptr_out = &preprocess_frame_;
586 preprocess_frame_.num_channels_ = in_frame.num_channels_;
587 int16_t audio[WEBRTC_10MS_PCM_AUDIO];
yujo36b1a5f2017-06-12 12:45:32 -0700588 const int16_t* src_ptr_audio = in_frame.data();
kwibergc13ded52016-06-17 06:00:45 -0700589 if (down_mix) {
590 // If a resampling is required the output of a down-mix is written into a
591 // local buffer, otherwise, it will be written to the output frame.
Yves Gerey665174f2018-06-19 15:03:05 +0200592 int16_t* dest_ptr_audio =
593 resample ? audio : preprocess_frame_.mutable_data();
kwibergc13ded52016-06-17 06:00:45 -0700594 if (DownMix(in_frame, WEBRTC_10MS_PCM_AUDIO, dest_ptr_audio) < 0)
595 return -1;
596 preprocess_frame_.num_channels_ = 1;
597 // Set the input of the resampler is the down-mixed signal.
598 src_ptr_audio = audio;
599 }
600
601 preprocess_frame_.timestamp_ = expected_codec_ts_;
602 preprocess_frame_.samples_per_channel_ = in_frame.samples_per_channel_;
603 preprocess_frame_.sample_rate_hz_ = in_frame.sample_rate_hz_;
604 // If it is required, we have to do a resampling.
605 if (resample) {
606 // The result of the resampler is written to output frame.
yujo36b1a5f2017-06-12 12:45:32 -0700607 int16_t* dest_ptr_audio = preprocess_frame_.mutable_data();
kwibergc13ded52016-06-17 06:00:45 -0700608
609 int samples_per_channel = resampler_.Resample10Msec(
610 src_ptr_audio, in_frame.sample_rate_hz_, encoder_stack_->SampleRateHz(),
611 preprocess_frame_.num_channels_, AudioFrame::kMaxDataSizeSamples,
612 dest_ptr_audio);
613
614 if (samples_per_channel < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100615 RTC_LOG(LS_ERROR) << "Cannot add 10 ms audio, resampling failed";
kwibergc13ded52016-06-17 06:00:45 -0700616 return -1;
617 }
618 preprocess_frame_.samples_per_channel_ =
619 static_cast<size_t>(samples_per_channel);
620 preprocess_frame_.sample_rate_hz_ = encoder_stack_->SampleRateHz();
621 }
622
623 expected_codec_ts_ +=
624 static_cast<uint32_t>(preprocess_frame_.samples_per_channel_);
625 expected_in_ts_ += static_cast<uint32_t>(in_frame.samples_per_channel_);
626
627 return 0;
628}
629
630/////////////////////////////////////////
kwibergc13ded52016-06-17 06:00:45 -0700631// (FEC) Forward Error Correction (codec internal)
632//
633
kwibergc13ded52016-06-17 06:00:45 -0700634int AudioCodingModuleImpl::SetPacketLossRate(int loss_rate) {
635 rtc::CritScope lock(&acm_crit_sect_);
636 if (HaveValidEncoder("SetPacketLossRate")) {
minyue4b9a2cb2016-11-30 06:49:59 -0800637 encoder_stack_->OnReceivedUplinkPacketLossFraction(loss_rate / 100.0);
kwibergc13ded52016-06-17 06:00:45 -0700638 }
639 return 0;
640}
641
642/////////////////////////////////////////
kwibergc13ded52016-06-17 06:00:45 -0700643// Receiver
644//
645
646int AudioCodingModuleImpl::InitializeReceiver() {
647 rtc::CritScope lock(&acm_crit_sect_);
648 return InitializeReceiverSafe();
649}
650
651// Initialize receiver, resets codec database etc.
652int AudioCodingModuleImpl::InitializeReceiverSafe() {
653 // If the receiver is already initialized then we want to destroy any
654 // existing decoders. After a call to this function, we should have a clean
655 // start-up.
kwiberg6b19b562016-09-20 04:02:25 -0700656 if (receiver_initialized_)
657 receiver_.RemoveAllCodecs();
kwibergc13ded52016-06-17 06:00:45 -0700658 receiver_.FlushBuffers();
659
kwibergc13ded52016-06-17 06:00:45 -0700660 receiver_initialized_ = true;
661 return 0;
662}
663
664// Get current receive frequency.
665int AudioCodingModuleImpl::ReceiveFrequency() const {
666 const auto last_packet_sample_rate = receiver_.last_packet_sample_rate_hz();
667 return last_packet_sample_rate ? *last_packet_sample_rate
668 : receiver_.last_output_sample_rate_hz();
669}
670
671// Get current playout frequency.
672int AudioCodingModuleImpl::PlayoutFrequency() const {
kwibergc13ded52016-06-17 06:00:45 -0700673 return receiver_.last_output_sample_rate_hz();
674}
675
kwiberg1c07c702017-03-27 07:15:49 -0700676void AudioCodingModuleImpl::SetReceiveCodecs(
677 const std::map<int, SdpAudioFormat>& codecs) {
678 rtc::CritScope lock(&acm_crit_sect_);
679 receiver_.SetCodecs(codecs);
680}
681
Fredrik Solenbergf693bfa2018-12-11 12:22:10 +0100682absl::optional<std::pair<int, SdpAudioFormat>>
683 AudioCodingModuleImpl::ReceiveCodec() const {
kwiberg5adaf732016-10-04 09:33:27 -0700684 rtc::CritScope lock(&acm_crit_sect_);
Fredrik Solenbergf693bfa2018-12-11 12:22:10 +0100685 return receiver_.LastDecoder();
ossue280cde2016-10-12 11:04:10 -0700686}
687
kwibergc13ded52016-06-17 06:00:45 -0700688// Incoming packet from network parsed and ready for decode.
689int AudioCodingModuleImpl::IncomingPacket(const uint8_t* incoming_payload,
690 const size_t payload_length,
Niels Möllerafb5dbb2019-02-15 15:21:47 +0100691 const RTPHeader& rtp_header) {
henrik.lundinb8c55b12017-05-10 07:38:01 -0700692 RTC_DCHECK_EQ(payload_length == 0, incoming_payload == nullptr);
kwibergc13ded52016-06-17 06:00:45 -0700693 return receiver_.InsertPacket(
694 rtp_header,
695 rtc::ArrayView<const uint8_t>(incoming_payload, payload_length));
696}
697
698// Minimum playout delay (Used for lip-sync).
699int AudioCodingModuleImpl::SetMinimumPlayoutDelay(int time_ms) {
700 if ((time_ms < 0) || (time_ms > 10000)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100701 RTC_LOG(LS_ERROR) << "Delay must be in the range of 0-10000 milliseconds.";
kwibergc13ded52016-06-17 06:00:45 -0700702 return -1;
703 }
704 return receiver_.SetMinimumDelay(time_ms);
705}
706
707int AudioCodingModuleImpl::SetMaximumPlayoutDelay(int time_ms) {
708 if ((time_ms < 0) || (time_ms > 10000)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100709 RTC_LOG(LS_ERROR) << "Delay must be in the range of 0-10000 milliseconds.";
kwibergc13ded52016-06-17 06:00:45 -0700710 return -1;
711 }
712 return receiver_.SetMaximumDelay(time_ms);
713}
714
Ruslan Burakov3b50f9f2019-02-06 09:45:56 +0100715bool AudioCodingModuleImpl::SetBaseMinimumPlayoutDelayMs(int delay_ms) {
716 // All necessary validation happens on NetEq level.
717 return receiver_.SetBaseMinimumDelayMs(delay_ms);
718}
719
720int AudioCodingModuleImpl::GetBaseMinimumPlayoutDelayMs() const {
721 return receiver_.GetBaseMinimumDelayMs();
722}
723
kwibergc13ded52016-06-17 06:00:45 -0700724// Get 10 milliseconds of raw audio data to play out.
725// Automatic resample to the requested frequency.
726int AudioCodingModuleImpl::PlayoutData10Ms(int desired_freq_hz,
727 AudioFrame* audio_frame,
728 bool* muted) {
729 // GetAudio always returns 10 ms, at the requested sample rate.
730 if (receiver_.GetAudio(desired_freq_hz, audio_frame, muted) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100731 RTC_LOG(LS_ERROR) << "PlayoutData failed, RecOut Failed";
kwibergc13ded52016-06-17 06:00:45 -0700732 return -1;
733 }
kwibergc13ded52016-06-17 06:00:45 -0700734 return 0;
735}
736
kwibergc13ded52016-06-17 06:00:45 -0700737/////////////////////////////////////////
738// Statistics
739//
740
741// TODO(turajs) change the return value to void. Also change the corresponding
742// NetEq function.
743int AudioCodingModuleImpl::GetNetworkStatistics(NetworkStatistics* statistics) {
744 receiver_.GetNetworkStatistics(statistics);
745 return 0;
746}
747
748int AudioCodingModuleImpl::RegisterVADCallback(ACMVADCallback* vad_callback) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100749 RTC_LOG(LS_VERBOSE) << "RegisterVADCallback()";
kwibergc13ded52016-06-17 06:00:45 -0700750 rtc::CritScope lock(&callback_crit_sect_);
751 vad_callback_ = vad_callback;
752 return 0;
753}
754
kwibergc13ded52016-06-17 06:00:45 -0700755// Informs Opus encoder of the maximum playback rate the receiver will render.
756int AudioCodingModuleImpl::SetOpusMaxPlaybackRate(int frequency_hz) {
757 rtc::CritScope lock(&acm_crit_sect_);
758 if (!HaveValidEncoder("SetOpusMaxPlaybackRate")) {
759 return -1;
760 }
761 encoder_stack_->SetMaxPlaybackRate(frequency_hz);
762 return 0;
763}
764
765int AudioCodingModuleImpl::EnableOpusDtx() {
766 rtc::CritScope lock(&acm_crit_sect_);
767 if (!HaveValidEncoder("EnableOpusDtx")) {
768 return -1;
769 }
770 return encoder_stack_->SetDtx(true) ? 0 : -1;
771}
772
773int AudioCodingModuleImpl::DisableOpusDtx() {
774 rtc::CritScope lock(&acm_crit_sect_);
775 if (!HaveValidEncoder("DisableOpusDtx")) {
776 return -1;
777 }
778 return encoder_stack_->SetDtx(false) ? 0 : -1;
779}
780
Danil Chapovalovb6021232018-06-19 13:26:36 +0200781absl::optional<uint32_t> AudioCodingModuleImpl::PlayoutTimestamp() {
kwibergc13ded52016-06-17 06:00:45 -0700782 return receiver_.GetPlayoutTimestamp();
783}
784
henrik.lundinb3f1c5d2016-08-22 15:39:53 -0700785int AudioCodingModuleImpl::FilteredCurrentDelayMs() const {
786 return receiver_.FilteredCurrentDelayMs();
787}
788
Henrik Lundinabbff892017-11-29 09:14:04 +0100789int AudioCodingModuleImpl::TargetDelayMs() const {
790 return receiver_.TargetDelayMs();
791}
792
kwibergc13ded52016-06-17 06:00:45 -0700793bool AudioCodingModuleImpl::HaveValidEncoder(const char* caller_name) const {
794 if (!encoder_stack_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100795 RTC_LOG(LS_ERROR) << caller_name << " failed: No send codec is registered.";
kwibergc13ded52016-06-17 06:00:45 -0700796 return false;
797 }
798 return true;
799}
800
kwibergc13ded52016-06-17 06:00:45 -0700801int AudioCodingModuleImpl::EnableNack(size_t max_nack_list_size) {
802 return receiver_.EnableNack(max_nack_list_size);
803}
804
805void AudioCodingModuleImpl::DisableNack() {
806 receiver_.DisableNack();
807}
808
809std::vector<uint16_t> AudioCodingModuleImpl::GetNackList(
810 int64_t round_trip_time_ms) const {
811 return receiver_.GetNackList(round_trip_time_ms);
812}
813
kwibergc13ded52016-06-17 06:00:45 -0700814void AudioCodingModuleImpl::GetDecodingCallStatistics(
Yves Gerey665174f2018-06-19 15:03:05 +0200815 AudioDecodingCallStats* call_stats) const {
kwibergc13ded52016-06-17 06:00:45 -0700816 receiver_.GetDecodingCallStatistics(call_stats);
817}
818
ivoce1198e02017-09-08 08:13:19 -0700819ANAStats AudioCodingModuleImpl::GetANAStats() const {
820 rtc::CritScope lock(&acm_crit_sect_);
821 if (encoder_stack_)
822 return encoder_stack_->GetANAStats();
823 // If no encoder is set, return default stats.
824 return ANAStats();
825}
826
kwibergc13ded52016-06-17 06:00:45 -0700827} // namespace
828
Karl Wiberg5817d3d2018-04-06 10:06:42 +0200829AudioCodingModule::Config::Config(
830 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory)
831 : neteq_config(),
832 clock(Clock::GetRealTimeClock()),
833 decoder_factory(decoder_factory) {
kwiberg36a43882016-08-29 05:33:32 -0700834 // Post-decode VAD is disabled by default in NetEq, however, Audio
835 // Conference Mixer relies on VAD decisions and fails without them.
836 neteq_config.enable_post_decode_vad = true;
837}
838
839AudioCodingModule::Config::Config(const Config&) = default;
840AudioCodingModule::Config::~Config() = default;
841
Henrik Lundin64dad832015-05-11 12:44:23 +0200842AudioCodingModule* AudioCodingModule::Create(const Config& config) {
kwibergc13ded52016-06-17 06:00:45 -0700843 return new AudioCodingModuleImpl(config);
turaj@webrtc.org7959e162013-09-12 18:30:26 +0000844}
845
turaj@webrtc.org7959e162013-09-12 18:30:26 +0000846} // namespace webrtc