blob: 2ce768b85bb409b42fe3fef379bfb23678a83c79 [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,
95 const WebRtcRTPHeader& rtp_info) override;
96
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
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
281void ConvertEncodedInfoToFragmentationHeader(
282 const AudioEncoder::EncodedInfo& info,
283 RTPFragmentationHeader* frag) {
284 if (info.redundant.empty()) {
285 frag->fragmentationVectorSize = 0;
286 return;
287 }
288
289 frag->VerifyAndAllocateFragmentationHeader(
290 static_cast<uint16_t>(info.redundant.size()));
291 frag->fragmentationVectorSize = static_cast<uint16_t>(info.redundant.size());
292 size_t offset = 0;
293 for (size_t i = 0; i < info.redundant.size(); ++i) {
294 frag->fragmentationOffset[i] = offset;
295 offset += info.redundant[i].encoded_bytes;
296 frag->fragmentationLength[i] = info.redundant[i].encoded_bytes;
kwibergd3edd772017-03-01 18:52:48 -0800297 frag->fragmentationTimeDiff[i] = rtc::dchecked_cast<uint16_t>(
kwibergc13ded52016-06-17 06:00:45 -0700298 info.encoded_timestamp - info.redundant[i].encoded_timestamp);
299 frag->fragmentationPlType[i] = info.redundant[i].payload_type;
300 }
301}
302
kwibergc13ded52016-06-17 06:00:45 -0700303void AudioCodingModuleImpl::ChangeLogger::MaybeLog(int value) {
304 if (value != last_value_ || first_time_) {
305 first_time_ = false;
306 last_value_ = value;
307 RTC_HISTOGRAM_COUNTS_SPARSE_100(histogram_name_, value);
308 }
309}
310
311AudioCodingModuleImpl::AudioCodingModuleImpl(
312 const AudioCodingModule::Config& config)
solenbergc7b4a452017-09-28 07:37:11 -0700313 : expected_codec_ts_(0xD87F3F9F),
kwibergc13ded52016-06-17 06:00:45 -0700314 expected_in_ts_(0xD87F3F9F),
315 receiver_(config),
316 bitrate_logger_("WebRTC.Audio.TargetBitrateInKbps"),
kwibergc13ded52016-06-17 06:00:45 -0700317 encoder_stack_(nullptr),
318 previous_pltype_(255),
319 receiver_initialized_(false),
320 first_10ms_data_(false),
321 first_frame_(true),
322 packetization_callback_(NULL),
323 vad_callback_(NULL),
324 codec_histogram_bins_log_(),
325 number_of_consecutive_empty_packets_(0) {
326 if (InitializeReceiverSafe() < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100327 RTC_LOG(LS_ERROR) << "Cannot initialize receiver";
kwibergc13ded52016-06-17 06:00:45 -0700328 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100329 RTC_LOG(LS_INFO) << "Created";
kwibergc13ded52016-06-17 06:00:45 -0700330}
331
332AudioCodingModuleImpl::~AudioCodingModuleImpl() = default;
333
334int32_t AudioCodingModuleImpl::Encode(const InputData& input_data) {
335 AudioEncoder::EncodedInfo encoded_info;
336 uint8_t previous_pltype;
337
338 // Check if there is an encoder before.
339 if (!HaveValidEncoder("Process"))
340 return -1;
341
Yves Gerey665174f2018-06-19 15:03:05 +0200342 if (!first_frame_) {
deadbeeffcada902016-08-24 12:45:13 -0700343 RTC_DCHECK(IsNewerTimestamp(input_data.input_timestamp, last_timestamp_))
ossu63fb95a2016-07-06 09:34:22 -0700344 << "Time should not move backwards";
345 }
346
kwibergc13ded52016-06-17 06:00:45 -0700347 // Scale the timestamp to the codec's RTP timestamp rate.
348 uint32_t rtp_timestamp =
349 first_frame_ ? input_data.input_timestamp
350 : last_rtp_timestamp_ +
351 rtc::CheckedDivExact(
352 input_data.input_timestamp - last_timestamp_,
353 static_cast<uint32_t>(rtc::CheckedDivExact(
354 encoder_stack_->SampleRateHz(),
355 encoder_stack_->RtpTimestampRateHz())));
356 last_timestamp_ = input_data.input_timestamp;
357 last_rtp_timestamp_ = rtp_timestamp;
358 first_frame_ = false;
359
360 // Clear the buffer before reuse - encoded data will get appended.
361 encode_buffer_.Clear();
362 encoded_info = encoder_stack_->Encode(
Yves Gerey665174f2018-06-19 15:03:05 +0200363 rtp_timestamp,
364 rtc::ArrayView<const int16_t>(
365 input_data.audio,
366 input_data.audio_channel * input_data.length_per_channel),
kwibergc13ded52016-06-17 06:00:45 -0700367 &encode_buffer_);
368
369 bitrate_logger_.MaybeLog(encoder_stack_->GetTargetBitrate() / 1000);
370 if (encode_buffer_.size() == 0 && !encoded_info.send_even_if_empty) {
371 // Not enough data.
372 return 0;
373 }
374 previous_pltype = previous_pltype_; // Read it while we have the critsect.
375
376 // Log codec type to histogram once every 500 packets.
377 if (encoded_info.encoded_bytes == 0) {
378 ++number_of_consecutive_empty_packets_;
379 } else {
380 size_t codec_type = static_cast<size_t>(encoded_info.encoder_type);
381 codec_histogram_bins_log_[codec_type] +=
382 number_of_consecutive_empty_packets_ + 1;
383 number_of_consecutive_empty_packets_ = 0;
384 if (codec_histogram_bins_log_[codec_type] >= 500) {
385 codec_histogram_bins_log_[codec_type] -= 500;
386 UpdateCodecTypeHistogram(codec_type);
387 }
388 }
389
390 RTPFragmentationHeader my_fragmentation;
391 ConvertEncodedInfoToFragmentationHeader(encoded_info, &my_fragmentation);
392 FrameType frame_type;
393 if (encode_buffer_.size() == 0 && encoded_info.send_even_if_empty) {
394 frame_type = kEmptyFrame;
395 encoded_info.payload_type = previous_pltype;
396 } else {
kwibergaf476c72016-11-28 15:21:39 -0800397 RTC_DCHECK_GT(encode_buffer_.size(), 0);
kwibergc13ded52016-06-17 06:00:45 -0700398 frame_type = encoded_info.speech ? kAudioFrameSpeech : kAudioFrameCN;
399 }
400
401 {
402 rtc::CritScope lock(&callback_crit_sect_);
403 if (packetization_callback_) {
404 packetization_callback_->SendData(
405 frame_type, encoded_info.payload_type, encoded_info.encoded_timestamp,
406 encode_buffer_.data(), encode_buffer_.size(),
407 my_fragmentation.fragmentationVectorSize > 0 ? &my_fragmentation
408 : nullptr);
409 }
410
411 if (vad_callback_) {
412 // Callback with VAD decision.
413 vad_callback_->InFrameType(frame_type);
414 }
415 }
416 previous_pltype_ = encoded_info.payload_type;
417 return static_cast<int32_t>(encode_buffer_.size());
418}
419
420/////////////////////////////////////////
421// Sender
422//
423
kwibergc13ded52016-06-17 06:00:45 -0700424void AudioCodingModuleImpl::ModifyEncoder(
kwiberg24c7c122016-09-28 11:57:10 -0700425 rtc::FunctionView<void(std::unique_ptr<AudioEncoder>*)> modifier) {
kwibergc13ded52016-06-17 06:00:45 -0700426 rtc::CritScope lock(&acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700427 modifier(&encoder_stack_);
428}
429
kwibergc13ded52016-06-17 06:00:45 -0700430void AudioCodingModuleImpl::SetBitRate(int bitrate_bps) {
431 rtc::CritScope lock(&acm_crit_sect_);
432 if (encoder_stack_) {
Danil Chapovalovb6021232018-06-19 13:26:36 +0200433 encoder_stack_->OnReceivedUplinkBandwidth(bitrate_bps, absl::nullopt);
kwibergc13ded52016-06-17 06:00:45 -0700434 }
435}
436
437// Register a transport callback which will be called to deliver
438// the encoded buffers.
439int AudioCodingModuleImpl::RegisterTransportCallback(
440 AudioPacketizationCallback* transport) {
441 rtc::CritScope lock(&callback_crit_sect_);
442 packetization_callback_ = transport;
443 return 0;
444}
445
446// Add 10MS of raw (PCM) audio data to the encoder.
447int AudioCodingModuleImpl::Add10MsData(const AudioFrame& audio_frame) {
448 InputData input_data;
449 rtc::CritScope lock(&acm_crit_sect_);
450 int r = Add10MsDataInternal(audio_frame, &input_data);
451 return r < 0 ? r : Encode(input_data);
452}
453
454int AudioCodingModuleImpl::Add10MsDataInternal(const AudioFrame& audio_frame,
455 InputData* input_data) {
456 if (audio_frame.samples_per_channel_ == 0) {
457 assert(false);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100458 RTC_LOG(LS_ERROR) << "Cannot Add 10 ms audio, payload length is zero";
kwibergc13ded52016-06-17 06:00:45 -0700459 return -1;
460 }
461
462 if (audio_frame.sample_rate_hz_ > 48000) {
463 assert(false);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100464 RTC_LOG(LS_ERROR) << "Cannot Add 10 ms audio, input frequency not valid";
kwibergc13ded52016-06-17 06:00:45 -0700465 return -1;
466 }
467
468 // If the length and frequency matches. We currently just support raw PCM.
469 if (static_cast<size_t>(audio_frame.sample_rate_hz_ / 100) !=
470 audio_frame.samples_per_channel_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100471 RTC_LOG(LS_ERROR)
Alex Loiko300ec8c2017-05-30 17:23:28 +0200472 << "Cannot Add 10 ms audio, input frequency and length doesn't match";
kwibergc13ded52016-06-17 06:00:45 -0700473 return -1;
474 }
475
476 if (audio_frame.num_channels_ != 1 && audio_frame.num_channels_ != 2) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100477 RTC_LOG(LS_ERROR) << "Cannot Add 10 ms audio, invalid number of channels.";
kwibergc13ded52016-06-17 06:00:45 -0700478 return -1;
479 }
480
481 // Do we have a codec registered?
482 if (!HaveValidEncoder("Add10MsData")) {
483 return -1;
484 }
485
486 const AudioFrame* ptr_frame;
487 // Perform a resampling, also down-mix if it is required and can be
488 // performed before resampling (a down mix prior to resampling will take
489 // place if both primary and secondary encoders are mono and input is in
490 // stereo).
491 if (PreprocessToAddData(audio_frame, &ptr_frame) < 0) {
492 return -1;
493 }
494
495 // Check whether we need an up-mix or down-mix?
496 const size_t current_num_channels = encoder_stack_->NumChannels();
497 const bool same_num_channels =
498 ptr_frame->num_channels_ == current_num_channels;
499
500 if (!same_num_channels) {
501 if (ptr_frame->num_channels_ == 1) {
502 if (UpMix(*ptr_frame, WEBRTC_10MS_PCM_AUDIO, input_data->buffer) < 0)
503 return -1;
504 } else {
505 if (DownMix(*ptr_frame, WEBRTC_10MS_PCM_AUDIO, input_data->buffer) < 0)
506 return -1;
507 }
508 }
509
510 // When adding data to encoders this pointer is pointing to an audio buffer
511 // with correct number of channels.
yujo36b1a5f2017-06-12 12:45:32 -0700512 const int16_t* ptr_audio = ptr_frame->data();
kwibergc13ded52016-06-17 06:00:45 -0700513
514 // For pushing data to primary, point the |ptr_audio| to correct buffer.
515 if (!same_num_channels)
516 ptr_audio = input_data->buffer;
517
yujo36b1a5f2017-06-12 12:45:32 -0700518 // TODO(yujo): Skip encode of muted frames.
kwibergc13ded52016-06-17 06:00:45 -0700519 input_data->input_timestamp = ptr_frame->timestamp_;
520 input_data->audio = ptr_audio;
521 input_data->length_per_channel = ptr_frame->samples_per_channel_;
522 input_data->audio_channel = current_num_channels;
523
524 return 0;
525}
526
527// Perform a resampling and down-mix if required. We down-mix only if
528// encoder is mono and input is stereo. In case of dual-streaming, both
529// encoders has to be mono for down-mix to take place.
530// |*ptr_out| will point to the pre-processed audio-frame. If no pre-processing
531// is required, |*ptr_out| points to |in_frame|.
yujo36b1a5f2017-06-12 12:45:32 -0700532// TODO(yujo): Make this more efficient for muted frames.
kwibergc13ded52016-06-17 06:00:45 -0700533int AudioCodingModuleImpl::PreprocessToAddData(const AudioFrame& in_frame,
534 const AudioFrame** ptr_out) {
535 const bool resample =
536 in_frame.sample_rate_hz_ != encoder_stack_->SampleRateHz();
537
538 // This variable is true if primary codec and secondary codec (if exists)
539 // are both mono and input is stereo.
540 // TODO(henrik.lundin): This condition should probably be
541 // in_frame.num_channels_ > encoder_stack_->NumChannels()
542 const bool down_mix =
543 in_frame.num_channels_ == 2 && encoder_stack_->NumChannels() == 1;
544
545 if (!first_10ms_data_) {
546 expected_in_ts_ = in_frame.timestamp_;
547 expected_codec_ts_ = in_frame.timestamp_;
548 first_10ms_data_ = true;
549 } else if (in_frame.timestamp_ != expected_in_ts_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100550 RTC_LOG(LS_WARNING) << "Unexpected input timestamp: " << in_frame.timestamp_
551 << ", expected: " << expected_in_ts_;
kwibergc13ded52016-06-17 06:00:45 -0700552 expected_codec_ts_ +=
553 (in_frame.timestamp_ - expected_in_ts_) *
554 static_cast<uint32_t>(
555 static_cast<double>(encoder_stack_->SampleRateHz()) /
556 static_cast<double>(in_frame.sample_rate_hz_));
557 expected_in_ts_ = in_frame.timestamp_;
558 }
559
kwibergc13ded52016-06-17 06:00:45 -0700560 if (!down_mix && !resample) {
561 // No pre-processing is required.
ossu63fb95a2016-07-06 09:34:22 -0700562 if (expected_in_ts_ == expected_codec_ts_) {
563 // If we've never resampled, we can use the input frame as-is
564 *ptr_out = &in_frame;
565 } else {
566 // Otherwise we'll need to alter the timestamp. Since in_frame is const,
567 // we'll have to make a copy of it.
568 preprocess_frame_.CopyFrom(in_frame);
569 preprocess_frame_.timestamp_ = expected_codec_ts_;
570 *ptr_out = &preprocess_frame_;
571 }
572
kwibergc13ded52016-06-17 06:00:45 -0700573 expected_in_ts_ += static_cast<uint32_t>(in_frame.samples_per_channel_);
574 expected_codec_ts_ += static_cast<uint32_t>(in_frame.samples_per_channel_);
kwibergc13ded52016-06-17 06:00:45 -0700575 return 0;
576 }
577
578 *ptr_out = &preprocess_frame_;
579 preprocess_frame_.num_channels_ = in_frame.num_channels_;
580 int16_t audio[WEBRTC_10MS_PCM_AUDIO];
yujo36b1a5f2017-06-12 12:45:32 -0700581 const int16_t* src_ptr_audio = in_frame.data();
kwibergc13ded52016-06-17 06:00:45 -0700582 if (down_mix) {
583 // If a resampling is required the output of a down-mix is written into a
584 // local buffer, otherwise, it will be written to the output frame.
Yves Gerey665174f2018-06-19 15:03:05 +0200585 int16_t* dest_ptr_audio =
586 resample ? audio : preprocess_frame_.mutable_data();
kwibergc13ded52016-06-17 06:00:45 -0700587 if (DownMix(in_frame, WEBRTC_10MS_PCM_AUDIO, dest_ptr_audio) < 0)
588 return -1;
589 preprocess_frame_.num_channels_ = 1;
590 // Set the input of the resampler is the down-mixed signal.
591 src_ptr_audio = audio;
592 }
593
594 preprocess_frame_.timestamp_ = expected_codec_ts_;
595 preprocess_frame_.samples_per_channel_ = in_frame.samples_per_channel_;
596 preprocess_frame_.sample_rate_hz_ = in_frame.sample_rate_hz_;
597 // If it is required, we have to do a resampling.
598 if (resample) {
599 // The result of the resampler is written to output frame.
yujo36b1a5f2017-06-12 12:45:32 -0700600 int16_t* dest_ptr_audio = preprocess_frame_.mutable_data();
kwibergc13ded52016-06-17 06:00:45 -0700601
602 int samples_per_channel = resampler_.Resample10Msec(
603 src_ptr_audio, in_frame.sample_rate_hz_, encoder_stack_->SampleRateHz(),
604 preprocess_frame_.num_channels_, AudioFrame::kMaxDataSizeSamples,
605 dest_ptr_audio);
606
607 if (samples_per_channel < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100608 RTC_LOG(LS_ERROR) << "Cannot add 10 ms audio, resampling failed";
kwibergc13ded52016-06-17 06:00:45 -0700609 return -1;
610 }
611 preprocess_frame_.samples_per_channel_ =
612 static_cast<size_t>(samples_per_channel);
613 preprocess_frame_.sample_rate_hz_ = encoder_stack_->SampleRateHz();
614 }
615
616 expected_codec_ts_ +=
617 static_cast<uint32_t>(preprocess_frame_.samples_per_channel_);
618 expected_in_ts_ += static_cast<uint32_t>(in_frame.samples_per_channel_);
619
620 return 0;
621}
622
623/////////////////////////////////////////
kwibergc13ded52016-06-17 06:00:45 -0700624// (FEC) Forward Error Correction (codec internal)
625//
626
kwibergc13ded52016-06-17 06:00:45 -0700627int AudioCodingModuleImpl::SetPacketLossRate(int loss_rate) {
628 rtc::CritScope lock(&acm_crit_sect_);
629 if (HaveValidEncoder("SetPacketLossRate")) {
minyue4b9a2cb2016-11-30 06:49:59 -0800630 encoder_stack_->OnReceivedUplinkPacketLossFraction(loss_rate / 100.0);
kwibergc13ded52016-06-17 06:00:45 -0700631 }
632 return 0;
633}
634
635/////////////////////////////////////////
kwibergc13ded52016-06-17 06:00:45 -0700636// Receiver
637//
638
639int AudioCodingModuleImpl::InitializeReceiver() {
640 rtc::CritScope lock(&acm_crit_sect_);
641 return InitializeReceiverSafe();
642}
643
644// Initialize receiver, resets codec database etc.
645int AudioCodingModuleImpl::InitializeReceiverSafe() {
646 // If the receiver is already initialized then we want to destroy any
647 // existing decoders. After a call to this function, we should have a clean
648 // start-up.
kwiberg6b19b562016-09-20 04:02:25 -0700649 if (receiver_initialized_)
650 receiver_.RemoveAllCodecs();
kwibergc13ded52016-06-17 06:00:45 -0700651 receiver_.ResetInitialDelay();
652 receiver_.SetMinimumDelay(0);
653 receiver_.SetMaximumDelay(0);
654 receiver_.FlushBuffers();
655
kwibergc13ded52016-06-17 06:00:45 -0700656 receiver_initialized_ = true;
657 return 0;
658}
659
660// Get current receive frequency.
661int AudioCodingModuleImpl::ReceiveFrequency() const {
662 const auto last_packet_sample_rate = receiver_.last_packet_sample_rate_hz();
663 return last_packet_sample_rate ? *last_packet_sample_rate
664 : receiver_.last_output_sample_rate_hz();
665}
666
667// Get current playout frequency.
668int AudioCodingModuleImpl::PlayoutFrequency() const {
kwibergc13ded52016-06-17 06:00:45 -0700669 return receiver_.last_output_sample_rate_hz();
670}
671
kwiberg1c07c702017-03-27 07:15:49 -0700672void AudioCodingModuleImpl::SetReceiveCodecs(
673 const std::map<int, SdpAudioFormat>& codecs) {
674 rtc::CritScope lock(&acm_crit_sect_);
675 receiver_.SetCodecs(codecs);
676}
677
Fredrik Solenbergf693bfa2018-12-11 12:22:10 +0100678absl::optional<std::pair<int, SdpAudioFormat>>
679 AudioCodingModuleImpl::ReceiveCodec() const {
kwiberg5adaf732016-10-04 09:33:27 -0700680 rtc::CritScope lock(&acm_crit_sect_);
Fredrik Solenbergf693bfa2018-12-11 12:22:10 +0100681 return receiver_.LastDecoder();
ossue280cde2016-10-12 11:04:10 -0700682}
683
kwibergc13ded52016-06-17 06:00:45 -0700684// Incoming packet from network parsed and ready for decode.
685int AudioCodingModuleImpl::IncomingPacket(const uint8_t* incoming_payload,
686 const size_t payload_length,
687 const WebRtcRTPHeader& rtp_header) {
henrik.lundinb8c55b12017-05-10 07:38:01 -0700688 RTC_DCHECK_EQ(payload_length == 0, incoming_payload == nullptr);
kwibergc13ded52016-06-17 06:00:45 -0700689 return receiver_.InsertPacket(
690 rtp_header,
691 rtc::ArrayView<const uint8_t>(incoming_payload, payload_length));
692}
693
694// Minimum playout delay (Used for lip-sync).
695int AudioCodingModuleImpl::SetMinimumPlayoutDelay(int time_ms) {
696 if ((time_ms < 0) || (time_ms > 10000)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100697 RTC_LOG(LS_ERROR) << "Delay must be in the range of 0-10000 milliseconds.";
kwibergc13ded52016-06-17 06:00:45 -0700698 return -1;
699 }
700 return receiver_.SetMinimumDelay(time_ms);
701}
702
703int AudioCodingModuleImpl::SetMaximumPlayoutDelay(int time_ms) {
704 if ((time_ms < 0) || (time_ms > 10000)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100705 RTC_LOG(LS_ERROR) << "Delay must be in the range of 0-10000 milliseconds.";
kwibergc13ded52016-06-17 06:00:45 -0700706 return -1;
707 }
708 return receiver_.SetMaximumDelay(time_ms);
709}
710
711// Get 10 milliseconds of raw audio data to play out.
712// Automatic resample to the requested frequency.
713int AudioCodingModuleImpl::PlayoutData10Ms(int desired_freq_hz,
714 AudioFrame* audio_frame,
715 bool* muted) {
716 // GetAudio always returns 10 ms, at the requested sample rate.
717 if (receiver_.GetAudio(desired_freq_hz, audio_frame, muted) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100718 RTC_LOG(LS_ERROR) << "PlayoutData failed, RecOut Failed";
kwibergc13ded52016-06-17 06:00:45 -0700719 return -1;
720 }
kwibergc13ded52016-06-17 06:00:45 -0700721 return 0;
722}
723
kwibergc13ded52016-06-17 06:00:45 -0700724/////////////////////////////////////////
725// Statistics
726//
727
728// TODO(turajs) change the return value to void. Also change the corresponding
729// NetEq function.
730int AudioCodingModuleImpl::GetNetworkStatistics(NetworkStatistics* statistics) {
731 receiver_.GetNetworkStatistics(statistics);
732 return 0;
733}
734
735int AudioCodingModuleImpl::RegisterVADCallback(ACMVADCallback* vad_callback) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100736 RTC_LOG(LS_VERBOSE) << "RegisterVADCallback()";
kwibergc13ded52016-06-17 06:00:45 -0700737 rtc::CritScope lock(&callback_crit_sect_);
738 vad_callback_ = vad_callback;
739 return 0;
740}
741
kwibergc13ded52016-06-17 06:00:45 -0700742// Informs Opus encoder of the maximum playback rate the receiver will render.
743int AudioCodingModuleImpl::SetOpusMaxPlaybackRate(int frequency_hz) {
744 rtc::CritScope lock(&acm_crit_sect_);
745 if (!HaveValidEncoder("SetOpusMaxPlaybackRate")) {
746 return -1;
747 }
748 encoder_stack_->SetMaxPlaybackRate(frequency_hz);
749 return 0;
750}
751
752int AudioCodingModuleImpl::EnableOpusDtx() {
753 rtc::CritScope lock(&acm_crit_sect_);
754 if (!HaveValidEncoder("EnableOpusDtx")) {
755 return -1;
756 }
757 return encoder_stack_->SetDtx(true) ? 0 : -1;
758}
759
760int AudioCodingModuleImpl::DisableOpusDtx() {
761 rtc::CritScope lock(&acm_crit_sect_);
762 if (!HaveValidEncoder("DisableOpusDtx")) {
763 return -1;
764 }
765 return encoder_stack_->SetDtx(false) ? 0 : -1;
766}
767
Danil Chapovalovb6021232018-06-19 13:26:36 +0200768absl::optional<uint32_t> AudioCodingModuleImpl::PlayoutTimestamp() {
kwibergc13ded52016-06-17 06:00:45 -0700769 return receiver_.GetPlayoutTimestamp();
770}
771
henrik.lundinb3f1c5d2016-08-22 15:39:53 -0700772int AudioCodingModuleImpl::FilteredCurrentDelayMs() const {
773 return receiver_.FilteredCurrentDelayMs();
774}
775
Henrik Lundinabbff892017-11-29 09:14:04 +0100776int AudioCodingModuleImpl::TargetDelayMs() const {
777 return receiver_.TargetDelayMs();
778}
779
kwibergc13ded52016-06-17 06:00:45 -0700780bool AudioCodingModuleImpl::HaveValidEncoder(const char* caller_name) const {
781 if (!encoder_stack_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100782 RTC_LOG(LS_ERROR) << caller_name << " failed: No send codec is registered.";
kwibergc13ded52016-06-17 06:00:45 -0700783 return false;
784 }
785 return true;
786}
787
kwibergc13ded52016-06-17 06:00:45 -0700788int AudioCodingModuleImpl::EnableNack(size_t max_nack_list_size) {
789 return receiver_.EnableNack(max_nack_list_size);
790}
791
792void AudioCodingModuleImpl::DisableNack() {
793 receiver_.DisableNack();
794}
795
796std::vector<uint16_t> AudioCodingModuleImpl::GetNackList(
797 int64_t round_trip_time_ms) const {
798 return receiver_.GetNackList(round_trip_time_ms);
799}
800
kwibergc13ded52016-06-17 06:00:45 -0700801void AudioCodingModuleImpl::GetDecodingCallStatistics(
Yves Gerey665174f2018-06-19 15:03:05 +0200802 AudioDecodingCallStats* call_stats) const {
kwibergc13ded52016-06-17 06:00:45 -0700803 receiver_.GetDecodingCallStatistics(call_stats);
804}
805
ivoce1198e02017-09-08 08:13:19 -0700806ANAStats AudioCodingModuleImpl::GetANAStats() const {
807 rtc::CritScope lock(&acm_crit_sect_);
808 if (encoder_stack_)
809 return encoder_stack_->GetANAStats();
810 // If no encoder is set, return default stats.
811 return ANAStats();
812}
813
kwibergc13ded52016-06-17 06:00:45 -0700814} // namespace
815
Karl Wiberg5817d3d2018-04-06 10:06:42 +0200816AudioCodingModule::Config::Config(
817 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory)
818 : neteq_config(),
819 clock(Clock::GetRealTimeClock()),
820 decoder_factory(decoder_factory) {
kwiberg36a43882016-08-29 05:33:32 -0700821 // Post-decode VAD is disabled by default in NetEq, however, Audio
822 // Conference Mixer relies on VAD decisions and fails without them.
823 neteq_config.enable_post_decode_vad = true;
824}
825
826AudioCodingModule::Config::Config(const Config&) = default;
827AudioCodingModule::Config::~Config() = default;
828
Henrik Lundin64dad832015-05-11 12:44:23 +0200829AudioCodingModule* AudioCodingModule::Create(const Config& config) {
kwibergc13ded52016-06-17 06:00:45 -0700830 return new AudioCodingModuleImpl(config);
turaj@webrtc.org7959e162013-09-12 18:30:26 +0000831}
832
turaj@webrtc.org7959e162013-09-12 18:30:26 +0000833} // namespace webrtc