blob: 60afeb69bded39cfc37f24fc3f7510539c9bcc12 [file] [log] [blame]
turaj@webrtc.org7959e162013-09-12 18:30:26 +00001/*
2 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "modules/audio_coding/include/audio_coding_module.h"
turaj@webrtc.org7959e162013-09-12 18:30:26 +000012
Jonathan Yu36344a02017-07-30 01:55:34 -070013#include <algorithm>
14
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020015#include "modules/audio_coding/acm2/acm_receiver.h"
16#include "modules/audio_coding/acm2/acm_resampler.h"
17#include "modules/audio_coding/acm2/codec_manager.h"
18#include "modules/audio_coding/acm2/rent_a_codec.h"
Fredrik Solenbergbbf21a32018-04-12 22:44:09 +020019#include "modules/include/module_common_types.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020020#include "rtc_base/checks.h"
21#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010022#include "rtc_base/numerics/safe_conversions.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020023#include "system_wrappers/include/metrics.h"
turaj@webrtc.org7959e162013-09-12 18:30:26 +000024
25namespace webrtc {
26
kwibergc13ded52016-06-17 06:00:45 -070027namespace {
28
29struct EncoderFactory {
30 AudioEncoder* external_speech_encoder = nullptr;
31 acm2::CodecManager codec_manager;
32 acm2::RentACodec rent_a_codec;
33};
34
35class AudioCodingModuleImpl final : public AudioCodingModule {
36 public:
37 explicit AudioCodingModuleImpl(const AudioCodingModule::Config& config);
38 ~AudioCodingModuleImpl() override;
39
40 /////////////////////////////////////////
41 // Sender
42 //
43
44 // Can be called multiple times for Codec, CNG, RED.
45 int RegisterSendCodec(const CodecInst& send_codec) override;
46
47 void RegisterExternalSendCodec(
48 AudioEncoder* external_speech_encoder) override;
49
kwiberg24c7c122016-09-28 11:57:10 -070050 void ModifyEncoder(rtc::FunctionView<void(std::unique_ptr<AudioEncoder>*)>
51 modifier) override;
kwibergc13ded52016-06-17 06:00:45 -070052
53 // Get current send codec.
Danil Chapovalovb6021232018-06-19 13:26:36 +020054 absl::optional<CodecInst> SendCodec() const override;
kwibergc13ded52016-06-17 06:00:45 -070055
kwibergc13ded52016-06-17 06:00:45 -070056 // Sets the bitrate to the specified value in bits/sec. In case the codec does
57 // not support the requested value it will choose an appropriate value
58 // instead.
59 void SetBitRate(int bitrate_bps) override;
60
61 // Register a transport callback which will be
62 // called to deliver the encoded buffers.
63 int RegisterTransportCallback(AudioPacketizationCallback* transport) override;
64
65 // Add 10 ms of raw (PCM) audio data to the encoder.
66 int Add10MsData(const AudioFrame& audio_frame) override;
67
68 /////////////////////////////////////////
69 // (RED) Redundant Coding
70 //
71
72 // Configure RED status i.e. on/off.
73 int SetREDStatus(bool enable_red) override;
74
75 // Get RED status.
76 bool REDStatus() const override;
77
78 /////////////////////////////////////////
79 // (FEC) Forward Error Correction (codec internal)
80 //
81
82 // Configure FEC status i.e. on/off.
83 int SetCodecFEC(bool enabled_codec_fec) override;
84
85 // Get FEC status.
86 bool CodecFEC() const override;
87
88 // Set target packet loss rate
89 int SetPacketLossRate(int loss_rate) override;
90
91 /////////////////////////////////////////
92 // (VAD) Voice Activity Detection
93 // and
94 // (CNG) Comfort Noise Generation
95 //
96
97 int SetVAD(bool enable_dtx = true,
98 bool enable_vad = false,
99 ACMVADMode mode = VADNormal) override;
100
101 int VAD(bool* dtx_enabled,
102 bool* vad_enabled,
103 ACMVADMode* mode) const override;
104
105 int RegisterVADCallback(ACMVADCallback* vad_callback) override;
106
107 /////////////////////////////////////////
108 // Receiver
109 //
110
111 // Initialize receiver, resets codec database etc.
112 int InitializeReceiver() override;
113
114 // Get current receive frequency.
115 int ReceiveFrequency() const override;
116
117 // Get current playout frequency.
118 int PlayoutFrequency() const override;
119
kwiberg1c07c702017-03-27 07:15:49 -0700120 void SetReceiveCodecs(const std::map<int, SdpAudioFormat>& codecs) override;
121
kwiberg5adaf732016-10-04 09:33:27 -0700122 bool RegisterReceiveCodec(int rtp_payload_type,
123 const SdpAudioFormat& audio_format) override;
124
kwibergc13ded52016-06-17 06:00:45 -0700125 int RegisterReceiveCodec(const CodecInst& receive_codec) override;
126 int RegisterReceiveCodec(
127 const CodecInst& receive_codec,
kwiberg24c7c122016-09-28 11:57:10 -0700128 rtc::FunctionView<std::unique_ptr<AudioDecoder>()> isac_factory) override;
kwibergc13ded52016-06-17 06:00:45 -0700129
130 int RegisterExternalReceiveCodec(int rtp_payload_type,
131 AudioDecoder* external_decoder,
132 int sample_rate_hz,
133 int num_channels,
134 const std::string& name) override;
135
136 // Get current received codec.
137 int ReceiveCodec(CodecInst* current_codec) const override;
138
Danil Chapovalovb6021232018-06-19 13:26:36 +0200139 absl::optional<SdpAudioFormat> ReceiveFormat() const override;
ossue280cde2016-10-12 11:04:10 -0700140
kwibergc13ded52016-06-17 06:00:45 -0700141 // Incoming packet from network parsed and ready for decode.
142 int IncomingPacket(const uint8_t* incoming_payload,
143 const size_t payload_length,
144 const WebRtcRTPHeader& rtp_info) override;
145
kwibergc13ded52016-06-17 06:00:45 -0700146 // Minimum playout delay.
147 int SetMinimumPlayoutDelay(int time_ms) override;
148
149 // Maximum playout delay.
150 int SetMaximumPlayoutDelay(int time_ms) override;
151
Danil Chapovalovb6021232018-06-19 13:26:36 +0200152 absl::optional<uint32_t> PlayoutTimestamp() override;
kwibergc13ded52016-06-17 06:00:45 -0700153
henrik.lundinb3f1c5d2016-08-22 15:39:53 -0700154 int FilteredCurrentDelayMs() const override;
155
Henrik Lundinabbff892017-11-29 09:14:04 +0100156 int TargetDelayMs() const override;
157
kwibergc13ded52016-06-17 06:00:45 -0700158 // Get 10 milliseconds of raw audio data to play out, and
159 // automatic resample to the requested frequency if > 0.
160 int PlayoutData10Ms(int desired_freq_hz,
161 AudioFrame* audio_frame,
162 bool* muted) override;
kwibergc13ded52016-06-17 06:00:45 -0700163
164 /////////////////////////////////////////
165 // Statistics
166 //
167
168 int GetNetworkStatistics(NetworkStatistics* statistics) override;
169
kwibergc13ded52016-06-17 06:00:45 -0700170 // If current send codec is Opus, informs it about the maximum playback rate
171 // the receiver will render.
172 int SetOpusMaxPlaybackRate(int frequency_hz) override;
173
174 int EnableOpusDtx() override;
175
176 int DisableOpusDtx() override;
177
178 int UnregisterReceiveCodec(uint8_t payload_type) override;
179
180 int EnableNack(size_t max_nack_list_size) override;
181
182 void DisableNack() override;
183
184 std::vector<uint16_t> GetNackList(int64_t round_trip_time_ms) const override;
185
186 void GetDecodingCallStatistics(AudioDecodingCallStats* stats) const override;
187
ivoce1198e02017-09-08 08:13:19 -0700188 ANAStats GetANAStats() const override;
189
kwibergc13ded52016-06-17 06:00:45 -0700190 private:
191 struct InputData {
192 uint32_t input_timestamp;
193 const int16_t* audio;
194 size_t length_per_channel;
195 size_t audio_channel;
196 // If a re-mix is required (up or down), this buffer will store a re-mixed
197 // version of the input.
198 int16_t buffer[WEBRTC_10MS_PCM_AUDIO];
199 };
200
201 // This member class writes values to the named UMA histogram, but only if
202 // the value has changed since the last time (and always for the first call).
203 class ChangeLogger {
204 public:
205 explicit ChangeLogger(const std::string& histogram_name)
206 : histogram_name_(histogram_name) {}
207 // Logs the new value if it is different from the last logged value, or if
208 // this is the first call.
209 void MaybeLog(int value);
210
211 private:
212 int last_value_ = 0;
213 int first_time_ = true;
214 const std::string histogram_name_;
215 };
216
217 int RegisterReceiveCodecUnlocked(
218 const CodecInst& codec,
kwiberg24c7c122016-09-28 11:57:10 -0700219 rtc::FunctionView<std::unique_ptr<AudioDecoder>()> isac_factory)
danilchap56359be2017-09-07 07:53:45 -0700220 RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700221
222 int Add10MsDataInternal(const AudioFrame& audio_frame, InputData* input_data)
danilchap56359be2017-09-07 07:53:45 -0700223 RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700224 int Encode(const InputData& input_data)
danilchap56359be2017-09-07 07:53:45 -0700225 RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700226
danilchap56359be2017-09-07 07:53:45 -0700227 int InitializeReceiverSafe() RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700228
229 bool HaveValidEncoder(const char* caller_name) const
danilchap56359be2017-09-07 07:53:45 -0700230 RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700231
232 // Preprocessing of input audio, including resampling and down-mixing if
233 // required, before pushing audio into encoder's buffer.
234 //
235 // in_frame: input audio-frame
236 // ptr_out: pointer to output audio_frame. If no preprocessing is required
237 // |ptr_out| will be pointing to |in_frame|, otherwise pointing to
238 // |preprocess_frame_|.
239 //
240 // Return value:
241 // -1: if encountering an error.
242 // 0: otherwise.
243 int PreprocessToAddData(const AudioFrame& in_frame,
244 const AudioFrame** ptr_out)
danilchap56359be2017-09-07 07:53:45 -0700245 RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700246
247 // Change required states after starting to receive the codec corresponding
248 // to |index|.
249 int UpdateUponReceivingCodec(int index);
250
251 rtc::CriticalSection acm_crit_sect_;
danilchap56359be2017-09-07 07:53:45 -0700252 rtc::Buffer encode_buffer_ RTC_GUARDED_BY(acm_crit_sect_);
danilchap56359be2017-09-07 07:53:45 -0700253 uint32_t expected_codec_ts_ RTC_GUARDED_BY(acm_crit_sect_);
254 uint32_t expected_in_ts_ RTC_GUARDED_BY(acm_crit_sect_);
255 acm2::ACMResampler resampler_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700256 acm2::AcmReceiver receiver_; // AcmReceiver has it's own internal lock.
danilchap56359be2017-09-07 07:53:45 -0700257 ChangeLogger bitrate_logger_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700258
danilchap56359be2017-09-07 07:53:45 -0700259 std::unique_ptr<EncoderFactory> encoder_factory_
260 RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700261
262 // Current encoder stack, either obtained from
263 // encoder_factory_->rent_a_codec.RentEncoderStack or provided by a call to
264 // RegisterEncoder.
danilchap56359be2017-09-07 07:53:45 -0700265 std::unique_ptr<AudioEncoder> encoder_stack_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700266
danilchap56359be2017-09-07 07:53:45 -0700267 std::unique_ptr<AudioDecoder> isac_decoder_16k_
268 RTC_GUARDED_BY(acm_crit_sect_);
269 std::unique_ptr<AudioDecoder> isac_decoder_32k_
270 RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700271
272 // This is to keep track of CN instances where we can send DTMFs.
danilchap56359be2017-09-07 07:53:45 -0700273 uint8_t previous_pltype_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700274
danilchap56359be2017-09-07 07:53:45 -0700275 bool receiver_initialized_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700276
danilchap56359be2017-09-07 07:53:45 -0700277 AudioFrame preprocess_frame_ RTC_GUARDED_BY(acm_crit_sect_);
278 bool first_10ms_data_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700279
danilchap56359be2017-09-07 07:53:45 -0700280 bool first_frame_ RTC_GUARDED_BY(acm_crit_sect_);
281 uint32_t last_timestamp_ RTC_GUARDED_BY(acm_crit_sect_);
282 uint32_t last_rtp_timestamp_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700283
284 rtc::CriticalSection callback_crit_sect_;
285 AudioPacketizationCallback* packetization_callback_
danilchap56359be2017-09-07 07:53:45 -0700286 RTC_GUARDED_BY(callback_crit_sect_);
287 ACMVADCallback* vad_callback_ RTC_GUARDED_BY(callback_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700288
289 int codec_histogram_bins_log_[static_cast<size_t>(
290 AudioEncoder::CodecType::kMaxLoggedAudioCodecTypes)];
291 int number_of_consecutive_empty_packets_;
292};
293
294// Adds a codec usage sample to the histogram.
295void UpdateCodecTypeHistogram(size_t codec_type) {
296 RTC_HISTOGRAM_ENUMERATION(
297 "WebRTC.Audio.Encoder.CodecType", static_cast<int>(codec_type),
298 static_cast<int>(
299 webrtc::AudioEncoder::CodecType::kMaxLoggedAudioCodecTypes));
300}
301
kwibergc13ded52016-06-17 06:00:45 -0700302// Stereo-to-mono can be used as in-place.
303int DownMix(const AudioFrame& frame,
304 size_t length_out_buff,
305 int16_t* out_buff) {
yujo36b1a5f2017-06-12 12:45:32 -0700306 RTC_DCHECK_EQ(frame.num_channels_, 2);
307 RTC_DCHECK_GE(length_out_buff, frame.samples_per_channel_);
308
309 if (!frame.muted()) {
310 const int16_t* frame_data = frame.data();
311 for (size_t n = 0; n < frame.samples_per_channel_; ++n) {
Yves Gerey665174f2018-06-19 15:03:05 +0200312 out_buff[n] =
313 static_cast<int16_t>((static_cast<int32_t>(frame_data[2 * n]) +
314 static_cast<int32_t>(frame_data[2 * n + 1])) >>
315 1);
yujo36b1a5f2017-06-12 12:45:32 -0700316 }
317 } else {
Jonathan Yu36344a02017-07-30 01:55:34 -0700318 std::fill(out_buff, out_buff + frame.samples_per_channel_, 0);
kwibergc13ded52016-06-17 06:00:45 -0700319 }
kwibergc13ded52016-06-17 06:00:45 -0700320 return 0;
321}
322
323// Mono-to-stereo can be used as in-place.
324int UpMix(const AudioFrame& frame, size_t length_out_buff, int16_t* out_buff) {
yujo36b1a5f2017-06-12 12:45:32 -0700325 RTC_DCHECK_EQ(frame.num_channels_, 1);
326 RTC_DCHECK_GE(length_out_buff, 2 * frame.samples_per_channel_);
327
328 if (!frame.muted()) {
329 const int16_t* frame_data = frame.data();
330 for (size_t n = frame.samples_per_channel_; n != 0; --n) {
331 size_t i = n - 1;
332 int16_t sample = frame_data[i];
333 out_buff[2 * i + 1] = sample;
334 out_buff[2 * i] = sample;
335 }
336 } else {
Jonathan Yu36344a02017-07-30 01:55:34 -0700337 std::fill(out_buff, out_buff + frame.samples_per_channel_ * 2, 0);
kwibergc13ded52016-06-17 06:00:45 -0700338 }
339 return 0;
340}
341
342void ConvertEncodedInfoToFragmentationHeader(
343 const AudioEncoder::EncodedInfo& info,
344 RTPFragmentationHeader* frag) {
345 if (info.redundant.empty()) {
346 frag->fragmentationVectorSize = 0;
347 return;
348 }
349
350 frag->VerifyAndAllocateFragmentationHeader(
351 static_cast<uint16_t>(info.redundant.size()));
352 frag->fragmentationVectorSize = static_cast<uint16_t>(info.redundant.size());
353 size_t offset = 0;
354 for (size_t i = 0; i < info.redundant.size(); ++i) {
355 frag->fragmentationOffset[i] = offset;
356 offset += info.redundant[i].encoded_bytes;
357 frag->fragmentationLength[i] = info.redundant[i].encoded_bytes;
kwibergd3edd772017-03-01 18:52:48 -0800358 frag->fragmentationTimeDiff[i] = rtc::dchecked_cast<uint16_t>(
kwibergc13ded52016-06-17 06:00:45 -0700359 info.encoded_timestamp - info.redundant[i].encoded_timestamp);
360 frag->fragmentationPlType[i] = info.redundant[i].payload_type;
361 }
362}
363
364// Wraps a raw AudioEncoder pointer. The idea is that you can put one of these
365// in a unique_ptr, to protect the contained raw pointer from being deleted
366// when the unique_ptr expires. (This is of course a bad idea in general, but
367// backwards compatibility.)
368class RawAudioEncoderWrapper final : public AudioEncoder {
369 public:
370 RawAudioEncoderWrapper(AudioEncoder* enc) : enc_(enc) {}
371 int SampleRateHz() const override { return enc_->SampleRateHz(); }
372 size_t NumChannels() const override { return enc_->NumChannels(); }
373 int RtpTimestampRateHz() const override { return enc_->RtpTimestampRateHz(); }
374 size_t Num10MsFramesInNextPacket() const override {
375 return enc_->Num10MsFramesInNextPacket();
376 }
377 size_t Max10MsFramesInAPacket() const override {
378 return enc_->Max10MsFramesInAPacket();
379 }
380 int GetTargetBitrate() const override { return enc_->GetTargetBitrate(); }
381 EncodedInfo EncodeImpl(uint32_t rtp_timestamp,
382 rtc::ArrayView<const int16_t> audio,
383 rtc::Buffer* encoded) override {
384 return enc_->Encode(rtp_timestamp, audio, encoded);
385 }
386 void Reset() override { return enc_->Reset(); }
387 bool SetFec(bool enable) override { return enc_->SetFec(enable); }
388 bool SetDtx(bool enable) override { return enc_->SetDtx(enable); }
389 bool SetApplication(Application application) override {
390 return enc_->SetApplication(application);
391 }
392 void SetMaxPlaybackRate(int frequency_hz) override {
393 return enc_->SetMaxPlaybackRate(frequency_hz);
394 }
kwibergc13ded52016-06-17 06:00:45 -0700395
396 private:
397 AudioEncoder* enc_;
398};
399
400// Return false on error.
401bool CreateSpeechEncoderIfNecessary(EncoderFactory* ef) {
402 auto* sp = ef->codec_manager.GetStackParams();
403 if (sp->speech_encoder) {
404 // Do nothing; we already have a speech encoder.
405 } else if (ef->codec_manager.GetCodecInst()) {
406 RTC_DCHECK(!ef->external_speech_encoder);
407 // We have no speech encoder, but we have a specification for making one.
408 std::unique_ptr<AudioEncoder> enc =
409 ef->rent_a_codec.RentEncoder(*ef->codec_manager.GetCodecInst());
410 if (!enc)
411 return false; // Encoder spec was bad.
412 sp->speech_encoder = std::move(enc);
413 } else if (ef->external_speech_encoder) {
414 RTC_DCHECK(!ef->codec_manager.GetCodecInst());
415 // We have an external speech encoder.
416 sp->speech_encoder = std::unique_ptr<AudioEncoder>(
417 new RawAudioEncoderWrapper(ef->external_speech_encoder));
418 }
419 return true;
420}
421
422void AudioCodingModuleImpl::ChangeLogger::MaybeLog(int value) {
423 if (value != last_value_ || first_time_) {
424 first_time_ = false;
425 last_value_ = value;
426 RTC_HISTOGRAM_COUNTS_SPARSE_100(histogram_name_, value);
427 }
428}
429
430AudioCodingModuleImpl::AudioCodingModuleImpl(
431 const AudioCodingModule::Config& config)
solenbergc7b4a452017-09-28 07:37:11 -0700432 : expected_codec_ts_(0xD87F3F9F),
kwibergc13ded52016-06-17 06:00:45 -0700433 expected_in_ts_(0xD87F3F9F),
434 receiver_(config),
435 bitrate_logger_("WebRTC.Audio.TargetBitrateInKbps"),
436 encoder_factory_(new EncoderFactory),
437 encoder_stack_(nullptr),
438 previous_pltype_(255),
439 receiver_initialized_(false),
440 first_10ms_data_(false),
441 first_frame_(true),
442 packetization_callback_(NULL),
443 vad_callback_(NULL),
444 codec_histogram_bins_log_(),
445 number_of_consecutive_empty_packets_(0) {
446 if (InitializeReceiverSafe() < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100447 RTC_LOG(LS_ERROR) << "Cannot initialize receiver";
kwibergc13ded52016-06-17 06:00:45 -0700448 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100449 RTC_LOG(LS_INFO) << "Created";
kwibergc13ded52016-06-17 06:00:45 -0700450}
451
452AudioCodingModuleImpl::~AudioCodingModuleImpl() = default;
453
454int32_t AudioCodingModuleImpl::Encode(const InputData& input_data) {
455 AudioEncoder::EncodedInfo encoded_info;
456 uint8_t previous_pltype;
457
458 // Check if there is an encoder before.
459 if (!HaveValidEncoder("Process"))
460 return -1;
461
Yves Gerey665174f2018-06-19 15:03:05 +0200462 if (!first_frame_) {
deadbeeffcada902016-08-24 12:45:13 -0700463 RTC_DCHECK(IsNewerTimestamp(input_data.input_timestamp, last_timestamp_))
ossu63fb95a2016-07-06 09:34:22 -0700464 << "Time should not move backwards";
465 }
466
kwibergc13ded52016-06-17 06:00:45 -0700467 // Scale the timestamp to the codec's RTP timestamp rate.
468 uint32_t rtp_timestamp =
469 first_frame_ ? input_data.input_timestamp
470 : last_rtp_timestamp_ +
471 rtc::CheckedDivExact(
472 input_data.input_timestamp - last_timestamp_,
473 static_cast<uint32_t>(rtc::CheckedDivExact(
474 encoder_stack_->SampleRateHz(),
475 encoder_stack_->RtpTimestampRateHz())));
476 last_timestamp_ = input_data.input_timestamp;
477 last_rtp_timestamp_ = rtp_timestamp;
478 first_frame_ = false;
479
480 // Clear the buffer before reuse - encoded data will get appended.
481 encode_buffer_.Clear();
482 encoded_info = encoder_stack_->Encode(
Yves Gerey665174f2018-06-19 15:03:05 +0200483 rtp_timestamp,
484 rtc::ArrayView<const int16_t>(
485 input_data.audio,
486 input_data.audio_channel * input_data.length_per_channel),
kwibergc13ded52016-06-17 06:00:45 -0700487 &encode_buffer_);
488
489 bitrate_logger_.MaybeLog(encoder_stack_->GetTargetBitrate() / 1000);
490 if (encode_buffer_.size() == 0 && !encoded_info.send_even_if_empty) {
491 // Not enough data.
492 return 0;
493 }
494 previous_pltype = previous_pltype_; // Read it while we have the critsect.
495
496 // Log codec type to histogram once every 500 packets.
497 if (encoded_info.encoded_bytes == 0) {
498 ++number_of_consecutive_empty_packets_;
499 } else {
500 size_t codec_type = static_cast<size_t>(encoded_info.encoder_type);
501 codec_histogram_bins_log_[codec_type] +=
502 number_of_consecutive_empty_packets_ + 1;
503 number_of_consecutive_empty_packets_ = 0;
504 if (codec_histogram_bins_log_[codec_type] >= 500) {
505 codec_histogram_bins_log_[codec_type] -= 500;
506 UpdateCodecTypeHistogram(codec_type);
507 }
508 }
509
510 RTPFragmentationHeader my_fragmentation;
511 ConvertEncodedInfoToFragmentationHeader(encoded_info, &my_fragmentation);
512 FrameType frame_type;
513 if (encode_buffer_.size() == 0 && encoded_info.send_even_if_empty) {
514 frame_type = kEmptyFrame;
515 encoded_info.payload_type = previous_pltype;
516 } else {
kwibergaf476c72016-11-28 15:21:39 -0800517 RTC_DCHECK_GT(encode_buffer_.size(), 0);
kwibergc13ded52016-06-17 06:00:45 -0700518 frame_type = encoded_info.speech ? kAudioFrameSpeech : kAudioFrameCN;
519 }
520
521 {
522 rtc::CritScope lock(&callback_crit_sect_);
523 if (packetization_callback_) {
524 packetization_callback_->SendData(
525 frame_type, encoded_info.payload_type, encoded_info.encoded_timestamp,
526 encode_buffer_.data(), encode_buffer_.size(),
527 my_fragmentation.fragmentationVectorSize > 0 ? &my_fragmentation
528 : nullptr);
529 }
530
531 if (vad_callback_) {
532 // Callback with VAD decision.
533 vad_callback_->InFrameType(frame_type);
534 }
535 }
536 previous_pltype_ = encoded_info.payload_type;
537 return static_cast<int32_t>(encode_buffer_.size());
538}
539
540/////////////////////////////////////////
541// Sender
542//
543
544// Can be called multiple times for Codec, CNG, RED.
545int AudioCodingModuleImpl::RegisterSendCodec(const CodecInst& send_codec) {
546 rtc::CritScope lock(&acm_crit_sect_);
547 if (!encoder_factory_->codec_manager.RegisterEncoder(send_codec)) {
548 return -1;
549 }
550 if (encoder_factory_->codec_manager.GetCodecInst()) {
551 encoder_factory_->external_speech_encoder = nullptr;
552 }
553 if (!CreateSpeechEncoderIfNecessary(encoder_factory_.get())) {
554 return -1;
555 }
556 auto* sp = encoder_factory_->codec_manager.GetStackParams();
557 if (sp->speech_encoder)
558 encoder_stack_ = encoder_factory_->rent_a_codec.RentEncoderStack(sp);
559 return 0;
560}
561
562void AudioCodingModuleImpl::RegisterExternalSendCodec(
563 AudioEncoder* external_speech_encoder) {
564 rtc::CritScope lock(&acm_crit_sect_);
565 encoder_factory_->codec_manager.UnsetCodecInst();
566 encoder_factory_->external_speech_encoder = external_speech_encoder;
567 RTC_CHECK(CreateSpeechEncoderIfNecessary(encoder_factory_.get()));
568 auto* sp = encoder_factory_->codec_manager.GetStackParams();
569 RTC_CHECK(sp->speech_encoder);
570 encoder_stack_ = encoder_factory_->rent_a_codec.RentEncoderStack(sp);
571}
572
573void AudioCodingModuleImpl::ModifyEncoder(
kwiberg24c7c122016-09-28 11:57:10 -0700574 rtc::FunctionView<void(std::unique_ptr<AudioEncoder>*)> modifier) {
kwibergc13ded52016-06-17 06:00:45 -0700575 rtc::CritScope lock(&acm_crit_sect_);
576
577 // Wipe the encoder factory, so that everything that relies on it will fail.
578 // We don't want the complexity of supporting swapping back and forth.
579 if (encoder_factory_) {
580 encoder_factory_.reset();
581 RTC_CHECK(!encoder_stack_); // Ensure we hadn't started using the factory.
582 }
583
584 modifier(&encoder_stack_);
585}
586
587// Get current send codec.
Danil Chapovalovb6021232018-06-19 13:26:36 +0200588absl::optional<CodecInst> AudioCodingModuleImpl::SendCodec() const {
kwibergc13ded52016-06-17 06:00:45 -0700589 rtc::CritScope lock(&acm_crit_sect_);
590 if (encoder_factory_) {
591 auto* ci = encoder_factory_->codec_manager.GetCodecInst();
592 if (ci) {
Oskar Sundbom12ab00b2017-11-16 15:31:38 +0100593 return *ci;
kwibergc13ded52016-06-17 06:00:45 -0700594 }
595 CreateSpeechEncoderIfNecessary(encoder_factory_.get());
596 const std::unique_ptr<AudioEncoder>& enc =
597 encoder_factory_->codec_manager.GetStackParams()->speech_encoder;
598 if (enc) {
Oskar Sundbom12ab00b2017-11-16 15:31:38 +0100599 return acm2::CodecManager::ForgeCodecInst(enc.get());
kwibergc13ded52016-06-17 06:00:45 -0700600 }
Danil Chapovalovb6021232018-06-19 13:26:36 +0200601 return absl::nullopt;
kwibergc13ded52016-06-17 06:00:45 -0700602 } else {
603 return encoder_stack_
Danil Chapovalovb6021232018-06-19 13:26:36 +0200604 ? absl::optional<CodecInst>(
kwibergc13ded52016-06-17 06:00:45 -0700605 acm2::CodecManager::ForgeCodecInst(encoder_stack_.get()))
Danil Chapovalovb6021232018-06-19 13:26:36 +0200606 : absl::nullopt;
kwibergc13ded52016-06-17 06:00:45 -0700607 }
608}
609
kwibergc13ded52016-06-17 06:00:45 -0700610void AudioCodingModuleImpl::SetBitRate(int bitrate_bps) {
611 rtc::CritScope lock(&acm_crit_sect_);
612 if (encoder_stack_) {
Danil Chapovalovb6021232018-06-19 13:26:36 +0200613 encoder_stack_->OnReceivedUplinkBandwidth(bitrate_bps, absl::nullopt);
kwibergc13ded52016-06-17 06:00:45 -0700614 }
615}
616
617// Register a transport callback which will be called to deliver
618// the encoded buffers.
619int AudioCodingModuleImpl::RegisterTransportCallback(
620 AudioPacketizationCallback* transport) {
621 rtc::CritScope lock(&callback_crit_sect_);
622 packetization_callback_ = transport;
623 return 0;
624}
625
626// Add 10MS of raw (PCM) audio data to the encoder.
627int AudioCodingModuleImpl::Add10MsData(const AudioFrame& audio_frame) {
628 InputData input_data;
629 rtc::CritScope lock(&acm_crit_sect_);
630 int r = Add10MsDataInternal(audio_frame, &input_data);
631 return r < 0 ? r : Encode(input_data);
632}
633
634int AudioCodingModuleImpl::Add10MsDataInternal(const AudioFrame& audio_frame,
635 InputData* input_data) {
636 if (audio_frame.samples_per_channel_ == 0) {
637 assert(false);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100638 RTC_LOG(LS_ERROR) << "Cannot Add 10 ms audio, payload length is zero";
kwibergc13ded52016-06-17 06:00:45 -0700639 return -1;
640 }
641
642 if (audio_frame.sample_rate_hz_ > 48000) {
643 assert(false);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100644 RTC_LOG(LS_ERROR) << "Cannot Add 10 ms audio, input frequency not valid";
kwibergc13ded52016-06-17 06:00:45 -0700645 return -1;
646 }
647
648 // If the length and frequency matches. We currently just support raw PCM.
649 if (static_cast<size_t>(audio_frame.sample_rate_hz_ / 100) !=
650 audio_frame.samples_per_channel_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100651 RTC_LOG(LS_ERROR)
Alex Loiko300ec8c2017-05-30 17:23:28 +0200652 << "Cannot Add 10 ms audio, input frequency and length doesn't match";
kwibergc13ded52016-06-17 06:00:45 -0700653 return -1;
654 }
655
656 if (audio_frame.num_channels_ != 1 && audio_frame.num_channels_ != 2) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100657 RTC_LOG(LS_ERROR) << "Cannot Add 10 ms audio, invalid number of channels.";
kwibergc13ded52016-06-17 06:00:45 -0700658 return -1;
659 }
660
661 // Do we have a codec registered?
662 if (!HaveValidEncoder("Add10MsData")) {
663 return -1;
664 }
665
666 const AudioFrame* ptr_frame;
667 // Perform a resampling, also down-mix if it is required and can be
668 // performed before resampling (a down mix prior to resampling will take
669 // place if both primary and secondary encoders are mono and input is in
670 // stereo).
671 if (PreprocessToAddData(audio_frame, &ptr_frame) < 0) {
672 return -1;
673 }
674
675 // Check whether we need an up-mix or down-mix?
676 const size_t current_num_channels = encoder_stack_->NumChannels();
677 const bool same_num_channels =
678 ptr_frame->num_channels_ == current_num_channels;
679
680 if (!same_num_channels) {
681 if (ptr_frame->num_channels_ == 1) {
682 if (UpMix(*ptr_frame, WEBRTC_10MS_PCM_AUDIO, input_data->buffer) < 0)
683 return -1;
684 } else {
685 if (DownMix(*ptr_frame, WEBRTC_10MS_PCM_AUDIO, input_data->buffer) < 0)
686 return -1;
687 }
688 }
689
690 // When adding data to encoders this pointer is pointing to an audio buffer
691 // with correct number of channels.
yujo36b1a5f2017-06-12 12:45:32 -0700692 const int16_t* ptr_audio = ptr_frame->data();
kwibergc13ded52016-06-17 06:00:45 -0700693
694 // For pushing data to primary, point the |ptr_audio| to correct buffer.
695 if (!same_num_channels)
696 ptr_audio = input_data->buffer;
697
yujo36b1a5f2017-06-12 12:45:32 -0700698 // TODO(yujo): Skip encode of muted frames.
kwibergc13ded52016-06-17 06:00:45 -0700699 input_data->input_timestamp = ptr_frame->timestamp_;
700 input_data->audio = ptr_audio;
701 input_data->length_per_channel = ptr_frame->samples_per_channel_;
702 input_data->audio_channel = current_num_channels;
703
704 return 0;
705}
706
707// Perform a resampling and down-mix if required. We down-mix only if
708// encoder is mono and input is stereo. In case of dual-streaming, both
709// encoders has to be mono for down-mix to take place.
710// |*ptr_out| will point to the pre-processed audio-frame. If no pre-processing
711// is required, |*ptr_out| points to |in_frame|.
yujo36b1a5f2017-06-12 12:45:32 -0700712// TODO(yujo): Make this more efficient for muted frames.
kwibergc13ded52016-06-17 06:00:45 -0700713int AudioCodingModuleImpl::PreprocessToAddData(const AudioFrame& in_frame,
714 const AudioFrame** ptr_out) {
715 const bool resample =
716 in_frame.sample_rate_hz_ != encoder_stack_->SampleRateHz();
717
718 // This variable is true if primary codec and secondary codec (if exists)
719 // are both mono and input is stereo.
720 // TODO(henrik.lundin): This condition should probably be
721 // in_frame.num_channels_ > encoder_stack_->NumChannels()
722 const bool down_mix =
723 in_frame.num_channels_ == 2 && encoder_stack_->NumChannels() == 1;
724
725 if (!first_10ms_data_) {
726 expected_in_ts_ = in_frame.timestamp_;
727 expected_codec_ts_ = in_frame.timestamp_;
728 first_10ms_data_ = true;
729 } else if (in_frame.timestamp_ != expected_in_ts_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100730 RTC_LOG(LS_WARNING) << "Unexpected input timestamp: " << in_frame.timestamp_
731 << ", expected: " << expected_in_ts_;
kwibergc13ded52016-06-17 06:00:45 -0700732 expected_codec_ts_ +=
733 (in_frame.timestamp_ - expected_in_ts_) *
734 static_cast<uint32_t>(
735 static_cast<double>(encoder_stack_->SampleRateHz()) /
736 static_cast<double>(in_frame.sample_rate_hz_));
737 expected_in_ts_ = in_frame.timestamp_;
738 }
739
kwibergc13ded52016-06-17 06:00:45 -0700740 if (!down_mix && !resample) {
741 // No pre-processing is required.
ossu63fb95a2016-07-06 09:34:22 -0700742 if (expected_in_ts_ == expected_codec_ts_) {
743 // If we've never resampled, we can use the input frame as-is
744 *ptr_out = &in_frame;
745 } else {
746 // Otherwise we'll need to alter the timestamp. Since in_frame is const,
747 // we'll have to make a copy of it.
748 preprocess_frame_.CopyFrom(in_frame);
749 preprocess_frame_.timestamp_ = expected_codec_ts_;
750 *ptr_out = &preprocess_frame_;
751 }
752
kwibergc13ded52016-06-17 06:00:45 -0700753 expected_in_ts_ += static_cast<uint32_t>(in_frame.samples_per_channel_);
754 expected_codec_ts_ += static_cast<uint32_t>(in_frame.samples_per_channel_);
kwibergc13ded52016-06-17 06:00:45 -0700755 return 0;
756 }
757
758 *ptr_out = &preprocess_frame_;
759 preprocess_frame_.num_channels_ = in_frame.num_channels_;
760 int16_t audio[WEBRTC_10MS_PCM_AUDIO];
yujo36b1a5f2017-06-12 12:45:32 -0700761 const int16_t* src_ptr_audio = in_frame.data();
kwibergc13ded52016-06-17 06:00:45 -0700762 if (down_mix) {
763 // If a resampling is required the output of a down-mix is written into a
764 // local buffer, otherwise, it will be written to the output frame.
Yves Gerey665174f2018-06-19 15:03:05 +0200765 int16_t* dest_ptr_audio =
766 resample ? audio : preprocess_frame_.mutable_data();
kwibergc13ded52016-06-17 06:00:45 -0700767 if (DownMix(in_frame, WEBRTC_10MS_PCM_AUDIO, dest_ptr_audio) < 0)
768 return -1;
769 preprocess_frame_.num_channels_ = 1;
770 // Set the input of the resampler is the down-mixed signal.
771 src_ptr_audio = audio;
772 }
773
774 preprocess_frame_.timestamp_ = expected_codec_ts_;
775 preprocess_frame_.samples_per_channel_ = in_frame.samples_per_channel_;
776 preprocess_frame_.sample_rate_hz_ = in_frame.sample_rate_hz_;
777 // If it is required, we have to do a resampling.
778 if (resample) {
779 // The result of the resampler is written to output frame.
yujo36b1a5f2017-06-12 12:45:32 -0700780 int16_t* dest_ptr_audio = preprocess_frame_.mutable_data();
kwibergc13ded52016-06-17 06:00:45 -0700781
782 int samples_per_channel = resampler_.Resample10Msec(
783 src_ptr_audio, in_frame.sample_rate_hz_, encoder_stack_->SampleRateHz(),
784 preprocess_frame_.num_channels_, AudioFrame::kMaxDataSizeSamples,
785 dest_ptr_audio);
786
787 if (samples_per_channel < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100788 RTC_LOG(LS_ERROR) << "Cannot add 10 ms audio, resampling failed";
kwibergc13ded52016-06-17 06:00:45 -0700789 return -1;
790 }
791 preprocess_frame_.samples_per_channel_ =
792 static_cast<size_t>(samples_per_channel);
793 preprocess_frame_.sample_rate_hz_ = encoder_stack_->SampleRateHz();
794 }
795
796 expected_codec_ts_ +=
797 static_cast<uint32_t>(preprocess_frame_.samples_per_channel_);
798 expected_in_ts_ += static_cast<uint32_t>(in_frame.samples_per_channel_);
799
800 return 0;
801}
802
803/////////////////////////////////////////
804// (RED) Redundant Coding
805//
806
807bool AudioCodingModuleImpl::REDStatus() const {
808 rtc::CritScope lock(&acm_crit_sect_);
809 return encoder_factory_->codec_manager.GetStackParams()->use_red;
810}
811
812// Configure RED status i.e on/off.
813int AudioCodingModuleImpl::SetREDStatus(bool enable_red) {
814#ifdef WEBRTC_CODEC_RED
815 rtc::CritScope lock(&acm_crit_sect_);
816 CreateSpeechEncoderIfNecessary(encoder_factory_.get());
817 if (!encoder_factory_->codec_manager.SetCopyRed(enable_red)) {
818 return -1;
819 }
820 auto* sp = encoder_factory_->codec_manager.GetStackParams();
821 if (sp->speech_encoder)
822 encoder_stack_ = encoder_factory_->rent_a_codec.RentEncoderStack(sp);
823 return 0;
824#else
Mirko Bonadei675513b2017-11-09 11:09:25 +0100825 RTC_LOG(LS_WARNING) << " WEBRTC_CODEC_RED is undefined";
kwibergc13ded52016-06-17 06:00:45 -0700826 return -1;
827#endif
828}
829
830/////////////////////////////////////////
831// (FEC) Forward Error Correction (codec internal)
832//
833
834bool AudioCodingModuleImpl::CodecFEC() const {
835 rtc::CritScope lock(&acm_crit_sect_);
836 return encoder_factory_->codec_manager.GetStackParams()->use_codec_fec;
837}
838
839int AudioCodingModuleImpl::SetCodecFEC(bool enable_codec_fec) {
840 rtc::CritScope lock(&acm_crit_sect_);
841 CreateSpeechEncoderIfNecessary(encoder_factory_.get());
842 if (!encoder_factory_->codec_manager.SetCodecFEC(enable_codec_fec)) {
843 return -1;
844 }
845 auto* sp = encoder_factory_->codec_manager.GetStackParams();
846 if (sp->speech_encoder)
847 encoder_stack_ = encoder_factory_->rent_a_codec.RentEncoderStack(sp);
848 if (enable_codec_fec) {
849 return sp->use_codec_fec ? 0 : -1;
850 } else {
851 RTC_DCHECK(!sp->use_codec_fec);
852 return 0;
853 }
854}
855
856int AudioCodingModuleImpl::SetPacketLossRate(int loss_rate) {
857 rtc::CritScope lock(&acm_crit_sect_);
858 if (HaveValidEncoder("SetPacketLossRate")) {
minyue4b9a2cb2016-11-30 06:49:59 -0800859 encoder_stack_->OnReceivedUplinkPacketLossFraction(loss_rate / 100.0);
kwibergc13ded52016-06-17 06:00:45 -0700860 }
861 return 0;
862}
863
864/////////////////////////////////////////
865// (VAD) Voice Activity Detection
866//
867int AudioCodingModuleImpl::SetVAD(bool enable_dtx,
868 bool enable_vad,
869 ACMVADMode mode) {
870 // Note: |enable_vad| is not used; VAD is enabled based on the DTX setting.
871 RTC_DCHECK_EQ(enable_dtx, enable_vad);
872 rtc::CritScope lock(&acm_crit_sect_);
873 CreateSpeechEncoderIfNecessary(encoder_factory_.get());
874 if (!encoder_factory_->codec_manager.SetVAD(enable_dtx, mode)) {
875 return -1;
876 }
877 auto* sp = encoder_factory_->codec_manager.GetStackParams();
878 if (sp->speech_encoder)
879 encoder_stack_ = encoder_factory_->rent_a_codec.RentEncoderStack(sp);
880 return 0;
881}
882
883// Get VAD/DTX settings.
Yves Gerey665174f2018-06-19 15:03:05 +0200884int AudioCodingModuleImpl::VAD(bool* dtx_enabled,
885 bool* vad_enabled,
kwibergc13ded52016-06-17 06:00:45 -0700886 ACMVADMode* mode) const {
887 rtc::CritScope lock(&acm_crit_sect_);
888 const auto* sp = encoder_factory_->codec_manager.GetStackParams();
889 *dtx_enabled = *vad_enabled = sp->use_cng;
890 *mode = sp->vad_mode;
891 return 0;
892}
893
894/////////////////////////////////////////
895// Receiver
896//
897
898int AudioCodingModuleImpl::InitializeReceiver() {
899 rtc::CritScope lock(&acm_crit_sect_);
900 return InitializeReceiverSafe();
901}
902
903// Initialize receiver, resets codec database etc.
904int AudioCodingModuleImpl::InitializeReceiverSafe() {
905 // If the receiver is already initialized then we want to destroy any
906 // existing decoders. After a call to this function, we should have a clean
907 // start-up.
kwiberg6b19b562016-09-20 04:02:25 -0700908 if (receiver_initialized_)
909 receiver_.RemoveAllCodecs();
kwibergc13ded52016-06-17 06:00:45 -0700910 receiver_.ResetInitialDelay();
911 receiver_.SetMinimumDelay(0);
912 receiver_.SetMaximumDelay(0);
913 receiver_.FlushBuffers();
914
kwibergc13ded52016-06-17 06:00:45 -0700915 receiver_initialized_ = true;
916 return 0;
917}
918
919// Get current receive frequency.
920int AudioCodingModuleImpl::ReceiveFrequency() const {
921 const auto last_packet_sample_rate = receiver_.last_packet_sample_rate_hz();
922 return last_packet_sample_rate ? *last_packet_sample_rate
923 : receiver_.last_output_sample_rate_hz();
924}
925
926// Get current playout frequency.
927int AudioCodingModuleImpl::PlayoutFrequency() const {
kwibergc13ded52016-06-17 06:00:45 -0700928 return receiver_.last_output_sample_rate_hz();
929}
930
kwiberg1c07c702017-03-27 07:15:49 -0700931void AudioCodingModuleImpl::SetReceiveCodecs(
932 const std::map<int, SdpAudioFormat>& codecs) {
933 rtc::CritScope lock(&acm_crit_sect_);
934 receiver_.SetCodecs(codecs);
935}
936
kwiberg5adaf732016-10-04 09:33:27 -0700937bool AudioCodingModuleImpl::RegisterReceiveCodec(
938 int rtp_payload_type,
939 const SdpAudioFormat& audio_format) {
940 rtc::CritScope lock(&acm_crit_sect_);
941 RTC_DCHECK(receiver_initialized_);
942
943 if (!acm2::RentACodec::IsPayloadTypeValid(rtp_payload_type)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100944 RTC_LOG_F(LS_ERROR) << "Invalid payload-type " << rtp_payload_type
945 << " for decoder.";
kwiberg5adaf732016-10-04 09:33:27 -0700946 return false;
947 }
948
949 return receiver_.AddCodec(rtp_payload_type, audio_format);
950}
951
kwibergc13ded52016-06-17 06:00:45 -0700952int AudioCodingModuleImpl::RegisterReceiveCodec(const CodecInst& codec) {
953 rtc::CritScope lock(&acm_crit_sect_);
954 auto* ef = encoder_factory_.get();
955 return RegisterReceiveCodecUnlocked(
956 codec, [&] { return ef->rent_a_codec.RentIsacDecoder(codec.plfreq); });
957}
958
959int AudioCodingModuleImpl::RegisterReceiveCodec(
960 const CodecInst& codec,
kwiberg24c7c122016-09-28 11:57:10 -0700961 rtc::FunctionView<std::unique_ptr<AudioDecoder>()> isac_factory) {
kwibergc13ded52016-06-17 06:00:45 -0700962 rtc::CritScope lock(&acm_crit_sect_);
963 return RegisterReceiveCodecUnlocked(codec, isac_factory);
964}
965
966int AudioCodingModuleImpl::RegisterReceiveCodecUnlocked(
967 const CodecInst& codec,
kwiberg24c7c122016-09-28 11:57:10 -0700968 rtc::FunctionView<std::unique_ptr<AudioDecoder>()> isac_factory) {
kwibergc13ded52016-06-17 06:00:45 -0700969 RTC_DCHECK(receiver_initialized_);
970 if (codec.channels > 2) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100971 RTC_LOG_F(LS_ERROR) << "Unsupported number of channels: " << codec.channels;
kwibergc13ded52016-06-17 06:00:45 -0700972 return -1;
973 }
974
975 auto codec_id = acm2::RentACodec::CodecIdByParams(codec.plname, codec.plfreq,
976 codec.channels);
977 if (!codec_id) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100978 RTC_LOG_F(LS_ERROR)
979 << "Wrong codec params to be registered as receive codec";
kwibergc13ded52016-06-17 06:00:45 -0700980 return -1;
981 }
982 auto codec_index = acm2::RentACodec::CodecIndexFromId(*codec_id);
983 RTC_CHECK(codec_index) << "Invalid codec ID: " << static_cast<int>(*codec_id);
984
985 // Check if the payload-type is valid.
986 if (!acm2::RentACodec::IsPayloadTypeValid(codec.pltype)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100987 RTC_LOG_F(LS_ERROR) << "Invalid payload type " << codec.pltype << " for "
988 << codec.plname;
kwibergc13ded52016-06-17 06:00:45 -0700989 return -1;
990 }
991
992 AudioDecoder* isac_decoder = nullptr;
993 if (STR_CASE_CMP(codec.plname, "isac") == 0) {
994 std::unique_ptr<AudioDecoder>& saved_isac_decoder =
995 codec.plfreq == 16000 ? isac_decoder_16k_ : isac_decoder_32k_;
996 if (!saved_isac_decoder) {
997 saved_isac_decoder = isac_factory();
998 }
999 isac_decoder = saved_isac_decoder.get();
1000 }
1001 return receiver_.AddCodec(*codec_index, codec.pltype, codec.channels,
1002 codec.plfreq, isac_decoder, codec.plname);
1003}
1004
1005int AudioCodingModuleImpl::RegisterExternalReceiveCodec(
1006 int rtp_payload_type,
1007 AudioDecoder* external_decoder,
1008 int sample_rate_hz,
1009 int num_channels,
1010 const std::string& name) {
1011 rtc::CritScope lock(&acm_crit_sect_);
1012 RTC_DCHECK(receiver_initialized_);
1013 if (num_channels > 2 || num_channels < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001014 RTC_LOG_F(LS_ERROR) << "Unsupported number of channels: " << num_channels;
kwibergc13ded52016-06-17 06:00:45 -07001015 return -1;
1016 }
1017
1018 // Check if the payload-type is valid.
1019 if (!acm2::RentACodec::IsPayloadTypeValid(rtp_payload_type)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001020 RTC_LOG_F(LS_ERROR) << "Invalid payload-type " << rtp_payload_type
1021 << " for external decoder.";
kwibergc13ded52016-06-17 06:00:45 -07001022 return -1;
1023 }
1024
1025 return receiver_.AddCodec(-1 /* external */, rtp_payload_type, num_channels,
1026 sample_rate_hz, external_decoder, name);
1027}
1028
1029// Get current received codec.
1030int AudioCodingModuleImpl::ReceiveCodec(CodecInst* current_codec) const {
1031 rtc::CritScope lock(&acm_crit_sect_);
1032 return receiver_.LastAudioCodec(current_codec);
1033}
1034
Danil Chapovalovb6021232018-06-19 13:26:36 +02001035absl::optional<SdpAudioFormat> AudioCodingModuleImpl::ReceiveFormat() const {
ossue280cde2016-10-12 11:04:10 -07001036 rtc::CritScope lock(&acm_crit_sect_);
1037 return receiver_.LastAudioFormat();
1038}
1039
kwibergc13ded52016-06-17 06:00:45 -07001040// Incoming packet from network parsed and ready for decode.
1041int AudioCodingModuleImpl::IncomingPacket(const uint8_t* incoming_payload,
1042 const size_t payload_length,
1043 const WebRtcRTPHeader& rtp_header) {
henrik.lundinb8c55b12017-05-10 07:38:01 -07001044 RTC_DCHECK_EQ(payload_length == 0, incoming_payload == nullptr);
kwibergc13ded52016-06-17 06:00:45 -07001045 return receiver_.InsertPacket(
1046 rtp_header,
1047 rtc::ArrayView<const uint8_t>(incoming_payload, payload_length));
1048}
1049
1050// Minimum playout delay (Used for lip-sync).
1051int AudioCodingModuleImpl::SetMinimumPlayoutDelay(int time_ms) {
1052 if ((time_ms < 0) || (time_ms > 10000)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001053 RTC_LOG(LS_ERROR) << "Delay must be in the range of 0-10000 milliseconds.";
kwibergc13ded52016-06-17 06:00:45 -07001054 return -1;
1055 }
1056 return receiver_.SetMinimumDelay(time_ms);
1057}
1058
1059int AudioCodingModuleImpl::SetMaximumPlayoutDelay(int time_ms) {
1060 if ((time_ms < 0) || (time_ms > 10000)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001061 RTC_LOG(LS_ERROR) << "Delay must be in the range of 0-10000 milliseconds.";
kwibergc13ded52016-06-17 06:00:45 -07001062 return -1;
1063 }
1064 return receiver_.SetMaximumDelay(time_ms);
1065}
1066
1067// Get 10 milliseconds of raw audio data to play out.
1068// Automatic resample to the requested frequency.
1069int AudioCodingModuleImpl::PlayoutData10Ms(int desired_freq_hz,
1070 AudioFrame* audio_frame,
1071 bool* muted) {
1072 // GetAudio always returns 10 ms, at the requested sample rate.
1073 if (receiver_.GetAudio(desired_freq_hz, audio_frame, muted) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001074 RTC_LOG(LS_ERROR) << "PlayoutData failed, RecOut Failed";
kwibergc13ded52016-06-17 06:00:45 -07001075 return -1;
1076 }
kwibergc13ded52016-06-17 06:00:45 -07001077 return 0;
1078}
1079
kwibergc13ded52016-06-17 06:00:45 -07001080/////////////////////////////////////////
1081// Statistics
1082//
1083
1084// TODO(turajs) change the return value to void. Also change the corresponding
1085// NetEq function.
1086int AudioCodingModuleImpl::GetNetworkStatistics(NetworkStatistics* statistics) {
1087 receiver_.GetNetworkStatistics(statistics);
1088 return 0;
1089}
1090
1091int AudioCodingModuleImpl::RegisterVADCallback(ACMVADCallback* vad_callback) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001092 RTC_LOG(LS_VERBOSE) << "RegisterVADCallback()";
kwibergc13ded52016-06-17 06:00:45 -07001093 rtc::CritScope lock(&callback_crit_sect_);
1094 vad_callback_ = vad_callback;
1095 return 0;
1096}
1097
kwibergc13ded52016-06-17 06:00:45 -07001098// Informs Opus encoder of the maximum playback rate the receiver will render.
1099int AudioCodingModuleImpl::SetOpusMaxPlaybackRate(int frequency_hz) {
1100 rtc::CritScope lock(&acm_crit_sect_);
1101 if (!HaveValidEncoder("SetOpusMaxPlaybackRate")) {
1102 return -1;
1103 }
1104 encoder_stack_->SetMaxPlaybackRate(frequency_hz);
1105 return 0;
1106}
1107
1108int AudioCodingModuleImpl::EnableOpusDtx() {
1109 rtc::CritScope lock(&acm_crit_sect_);
1110 if (!HaveValidEncoder("EnableOpusDtx")) {
1111 return -1;
1112 }
1113 return encoder_stack_->SetDtx(true) ? 0 : -1;
1114}
1115
1116int AudioCodingModuleImpl::DisableOpusDtx() {
1117 rtc::CritScope lock(&acm_crit_sect_);
1118 if (!HaveValidEncoder("DisableOpusDtx")) {
1119 return -1;
1120 }
1121 return encoder_stack_->SetDtx(false) ? 0 : -1;
1122}
1123
Danil Chapovalovb6021232018-06-19 13:26:36 +02001124absl::optional<uint32_t> AudioCodingModuleImpl::PlayoutTimestamp() {
kwibergc13ded52016-06-17 06:00:45 -07001125 return receiver_.GetPlayoutTimestamp();
1126}
1127
henrik.lundinb3f1c5d2016-08-22 15:39:53 -07001128int AudioCodingModuleImpl::FilteredCurrentDelayMs() const {
1129 return receiver_.FilteredCurrentDelayMs();
1130}
1131
Henrik Lundinabbff892017-11-29 09:14:04 +01001132int AudioCodingModuleImpl::TargetDelayMs() const {
1133 return receiver_.TargetDelayMs();
1134}
1135
kwibergc13ded52016-06-17 06:00:45 -07001136bool AudioCodingModuleImpl::HaveValidEncoder(const char* caller_name) const {
1137 if (!encoder_stack_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001138 RTC_LOG(LS_ERROR) << caller_name << " failed: No send codec is registered.";
kwibergc13ded52016-06-17 06:00:45 -07001139 return false;
1140 }
1141 return true;
1142}
1143
1144int AudioCodingModuleImpl::UnregisterReceiveCodec(uint8_t payload_type) {
1145 return receiver_.RemoveCodec(payload_type);
1146}
1147
1148int AudioCodingModuleImpl::EnableNack(size_t max_nack_list_size) {
1149 return receiver_.EnableNack(max_nack_list_size);
1150}
1151
1152void AudioCodingModuleImpl::DisableNack() {
1153 receiver_.DisableNack();
1154}
1155
1156std::vector<uint16_t> AudioCodingModuleImpl::GetNackList(
1157 int64_t round_trip_time_ms) const {
1158 return receiver_.GetNackList(round_trip_time_ms);
1159}
1160
kwibergc13ded52016-06-17 06:00:45 -07001161void AudioCodingModuleImpl::GetDecodingCallStatistics(
Yves Gerey665174f2018-06-19 15:03:05 +02001162 AudioDecodingCallStats* call_stats) const {
kwibergc13ded52016-06-17 06:00:45 -07001163 receiver_.GetDecodingCallStatistics(call_stats);
1164}
1165
ivoce1198e02017-09-08 08:13:19 -07001166ANAStats AudioCodingModuleImpl::GetANAStats() const {
1167 rtc::CritScope lock(&acm_crit_sect_);
1168 if (encoder_stack_)
1169 return encoder_stack_->GetANAStats();
1170 // If no encoder is set, return default stats.
1171 return ANAStats();
1172}
1173
kwibergc13ded52016-06-17 06:00:45 -07001174} // namespace
1175
Karl Wiberg5817d3d2018-04-06 10:06:42 +02001176AudioCodingModule::Config::Config(
1177 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory)
1178 : neteq_config(),
1179 clock(Clock::GetRealTimeClock()),
1180 decoder_factory(decoder_factory) {
kwiberg36a43882016-08-29 05:33:32 -07001181 // Post-decode VAD is disabled by default in NetEq, however, Audio
1182 // Conference Mixer relies on VAD decisions and fails without them.
1183 neteq_config.enable_post_decode_vad = true;
1184}
1185
1186AudioCodingModule::Config::Config(const Config&) = default;
1187AudioCodingModule::Config::~Config() = default;
1188
Henrik Lundin64dad832015-05-11 12:44:23 +02001189AudioCodingModule* AudioCodingModule::Create(const Config& config) {
kwibergc13ded52016-06-17 06:00:45 -07001190 return new AudioCodingModuleImpl(config);
turaj@webrtc.org7959e162013-09-12 18:30:26 +00001191}
1192
turaj@webrtc.org7959e162013-09-12 18:30:26 +00001193int AudioCodingModule::NumberOfCodecs() {
kwibergfce4a942015-10-27 11:40:24 -07001194 return static_cast<int>(acm2::RentACodec::NumberOfCodecs());
turaj@webrtc.org7959e162013-09-12 18:30:26 +00001195}
1196
turaj@webrtc.org7959e162013-09-12 18:30:26 +00001197int AudioCodingModule::Codec(int list_id, CodecInst* codec) {
kwibergfce4a942015-10-27 11:40:24 -07001198 auto codec_id = acm2::RentACodec::CodecIdFromIndex(list_id);
1199 if (!codec_id)
1200 return -1;
1201 auto ci = acm2::RentACodec::CodecInstById(*codec_id);
1202 if (!ci)
1203 return -1;
1204 *codec = *ci;
1205 return 0;
turaj@webrtc.org7959e162013-09-12 18:30:26 +00001206}
1207
turaj@webrtc.org7959e162013-09-12 18:30:26 +00001208int AudioCodingModule::Codec(const char* payload_name,
1209 CodecInst* codec,
1210 int sampling_freq_hz,
Peter Kasting69558702016-01-12 16:26:35 -08001211 size_t channels) {
Danil Chapovalovb6021232018-06-19 13:26:36 +02001212 absl::optional<CodecInst> ci = acm2::RentACodec::CodecInstByParams(
turaj@webrtc.org6d5d2482013-10-06 04:47:28 +00001213 payload_name, sampling_freq_hz, channels);
kwibergfce4a942015-10-27 11:40:24 -07001214 if (ci) {
1215 *codec = *ci;
1216 return 0;
1217 } else {
1218 // We couldn't find a matching codec, so set the parameters to unacceptable
turaj@webrtc.org7959e162013-09-12 18:30:26 +00001219 // values and return.
1220 codec->plname[0] = '\0';
1221 codec->pltype = -1;
1222 codec->pacsize = 0;
1223 codec->rate = 0;
1224 codec->plfreq = 0;
1225 return -1;
1226 }
turaj@webrtc.org7959e162013-09-12 18:30:26 +00001227}
1228
turaj@webrtc.org7959e162013-09-12 18:30:26 +00001229int AudioCodingModule::Codec(const char* payload_name,
1230 int sampling_freq_hz,
Peter Kasting69558702016-01-12 16:26:35 -08001231 size_t channels) {
Danil Chapovalovb6021232018-06-19 13:26:36 +02001232 absl::optional<acm2::RentACodec::CodecId> ci =
Karl Wibergbe579832015-11-10 22:34:18 +01001233 acm2::RentACodec::CodecIdByParams(payload_name, sampling_freq_hz,
1234 channels);
kwibergfce4a942015-10-27 11:40:24 -07001235 if (!ci)
1236 return -1;
Danil Chapovalovb6021232018-06-19 13:26:36 +02001237 absl::optional<int> i = acm2::RentACodec::CodecIndexFromId(*ci);
kwibergfce4a942015-10-27 11:40:24 -07001238 return i ? *i : -1;
turaj@webrtc.org7959e162013-09-12 18:30:26 +00001239}
1240
turaj@webrtc.org7959e162013-09-12 18:30:26 +00001241} // namespace webrtc