blob: f0b35ca0aee4e4e83ee103420f71786b0a20e33e [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
170 int SetOpusApplication(OpusApplicationMode application) override;
171
172 // If current send codec is Opus, informs it about the maximum playback rate
173 // the receiver will render.
174 int SetOpusMaxPlaybackRate(int frequency_hz) override;
175
176 int EnableOpusDtx() override;
177
178 int DisableOpusDtx() override;
179
180 int UnregisterReceiveCodec(uint8_t payload_type) override;
181
182 int EnableNack(size_t max_nack_list_size) override;
183
184 void DisableNack() override;
185
186 std::vector<uint16_t> GetNackList(int64_t round_trip_time_ms) const override;
187
188 void GetDecodingCallStatistics(AudioDecodingCallStats* stats) const override;
189
ivoce1198e02017-09-08 08:13:19 -0700190 ANAStats GetANAStats() const override;
191
kwibergc13ded52016-06-17 06:00:45 -0700192 private:
193 struct InputData {
194 uint32_t input_timestamp;
195 const int16_t* audio;
196 size_t length_per_channel;
197 size_t audio_channel;
198 // If a re-mix is required (up or down), this buffer will store a re-mixed
199 // version of the input.
200 int16_t buffer[WEBRTC_10MS_PCM_AUDIO];
201 };
202
203 // This member class writes values to the named UMA histogram, but only if
204 // the value has changed since the last time (and always for the first call).
205 class ChangeLogger {
206 public:
207 explicit ChangeLogger(const std::string& histogram_name)
208 : histogram_name_(histogram_name) {}
209 // Logs the new value if it is different from the last logged value, or if
210 // this is the first call.
211 void MaybeLog(int value);
212
213 private:
214 int last_value_ = 0;
215 int first_time_ = true;
216 const std::string histogram_name_;
217 };
218
219 int RegisterReceiveCodecUnlocked(
220 const CodecInst& codec,
kwiberg24c7c122016-09-28 11:57:10 -0700221 rtc::FunctionView<std::unique_ptr<AudioDecoder>()> isac_factory)
danilchap56359be2017-09-07 07:53:45 -0700222 RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700223
224 int Add10MsDataInternal(const AudioFrame& audio_frame, InputData* input_data)
danilchap56359be2017-09-07 07:53:45 -0700225 RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700226 int Encode(const InputData& input_data)
danilchap56359be2017-09-07 07:53:45 -0700227 RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700228
danilchap56359be2017-09-07 07:53:45 -0700229 int InitializeReceiverSafe() RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700230
231 bool HaveValidEncoder(const char* caller_name) const
danilchap56359be2017-09-07 07:53:45 -0700232 RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700233
234 // Preprocessing of input audio, including resampling and down-mixing if
235 // required, before pushing audio into encoder's buffer.
236 //
237 // in_frame: input audio-frame
238 // ptr_out: pointer to output audio_frame. If no preprocessing is required
239 // |ptr_out| will be pointing to |in_frame|, otherwise pointing to
240 // |preprocess_frame_|.
241 //
242 // Return value:
243 // -1: if encountering an error.
244 // 0: otherwise.
245 int PreprocessToAddData(const AudioFrame& in_frame,
246 const AudioFrame** ptr_out)
danilchap56359be2017-09-07 07:53:45 -0700247 RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700248
249 // Change required states after starting to receive the codec corresponding
250 // to |index|.
251 int UpdateUponReceivingCodec(int index);
252
253 rtc::CriticalSection acm_crit_sect_;
danilchap56359be2017-09-07 07:53:45 -0700254 rtc::Buffer encode_buffer_ RTC_GUARDED_BY(acm_crit_sect_);
danilchap56359be2017-09-07 07:53:45 -0700255 uint32_t expected_codec_ts_ RTC_GUARDED_BY(acm_crit_sect_);
256 uint32_t expected_in_ts_ RTC_GUARDED_BY(acm_crit_sect_);
257 acm2::ACMResampler resampler_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700258 acm2::AcmReceiver receiver_; // AcmReceiver has it's own internal lock.
danilchap56359be2017-09-07 07:53:45 -0700259 ChangeLogger bitrate_logger_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700260
danilchap56359be2017-09-07 07:53:45 -0700261 std::unique_ptr<EncoderFactory> encoder_factory_
262 RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700263
264 // Current encoder stack, either obtained from
265 // encoder_factory_->rent_a_codec.RentEncoderStack or provided by a call to
266 // RegisterEncoder.
danilchap56359be2017-09-07 07:53:45 -0700267 std::unique_ptr<AudioEncoder> encoder_stack_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700268
danilchap56359be2017-09-07 07:53:45 -0700269 std::unique_ptr<AudioDecoder> isac_decoder_16k_
270 RTC_GUARDED_BY(acm_crit_sect_);
271 std::unique_ptr<AudioDecoder> isac_decoder_32k_
272 RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700273
274 // This is to keep track of CN instances where we can send DTMFs.
danilchap56359be2017-09-07 07:53:45 -0700275 uint8_t previous_pltype_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700276
danilchap56359be2017-09-07 07:53:45 -0700277 bool receiver_initialized_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700278
danilchap56359be2017-09-07 07:53:45 -0700279 AudioFrame preprocess_frame_ RTC_GUARDED_BY(acm_crit_sect_);
280 bool first_10ms_data_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700281
danilchap56359be2017-09-07 07:53:45 -0700282 bool first_frame_ RTC_GUARDED_BY(acm_crit_sect_);
283 uint32_t last_timestamp_ RTC_GUARDED_BY(acm_crit_sect_);
284 uint32_t last_rtp_timestamp_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700285
286 rtc::CriticalSection callback_crit_sect_;
287 AudioPacketizationCallback* packetization_callback_
danilchap56359be2017-09-07 07:53:45 -0700288 RTC_GUARDED_BY(callback_crit_sect_);
289 ACMVADCallback* vad_callback_ RTC_GUARDED_BY(callback_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700290
291 int codec_histogram_bins_log_[static_cast<size_t>(
292 AudioEncoder::CodecType::kMaxLoggedAudioCodecTypes)];
293 int number_of_consecutive_empty_packets_;
294};
295
296// Adds a codec usage sample to the histogram.
297void UpdateCodecTypeHistogram(size_t codec_type) {
298 RTC_HISTOGRAM_ENUMERATION(
299 "WebRTC.Audio.Encoder.CodecType", static_cast<int>(codec_type),
300 static_cast<int>(
301 webrtc::AudioEncoder::CodecType::kMaxLoggedAudioCodecTypes));
302}
303
kwibergc13ded52016-06-17 06:00:45 -0700304// Stereo-to-mono can be used as in-place.
305int DownMix(const AudioFrame& frame,
306 size_t length_out_buff,
307 int16_t* out_buff) {
yujo36b1a5f2017-06-12 12:45:32 -0700308 RTC_DCHECK_EQ(frame.num_channels_, 2);
309 RTC_DCHECK_GE(length_out_buff, frame.samples_per_channel_);
310
311 if (!frame.muted()) {
312 const int16_t* frame_data = frame.data();
313 for (size_t n = 0; n < frame.samples_per_channel_; ++n) {
Yves Gerey665174f2018-06-19 15:03:05 +0200314 out_buff[n] =
315 static_cast<int16_t>((static_cast<int32_t>(frame_data[2 * n]) +
316 static_cast<int32_t>(frame_data[2 * n + 1])) >>
317 1);
yujo36b1a5f2017-06-12 12:45:32 -0700318 }
319 } else {
Jonathan Yu36344a02017-07-30 01:55:34 -0700320 std::fill(out_buff, out_buff + frame.samples_per_channel_, 0);
kwibergc13ded52016-06-17 06:00:45 -0700321 }
kwibergc13ded52016-06-17 06:00:45 -0700322 return 0;
323}
324
325// Mono-to-stereo can be used as in-place.
326int UpMix(const AudioFrame& frame, size_t length_out_buff, int16_t* out_buff) {
yujo36b1a5f2017-06-12 12:45:32 -0700327 RTC_DCHECK_EQ(frame.num_channels_, 1);
328 RTC_DCHECK_GE(length_out_buff, 2 * frame.samples_per_channel_);
329
330 if (!frame.muted()) {
331 const int16_t* frame_data = frame.data();
332 for (size_t n = frame.samples_per_channel_; n != 0; --n) {
333 size_t i = n - 1;
334 int16_t sample = frame_data[i];
335 out_buff[2 * i + 1] = sample;
336 out_buff[2 * i] = sample;
337 }
338 } else {
Jonathan Yu36344a02017-07-30 01:55:34 -0700339 std::fill(out_buff, out_buff + frame.samples_per_channel_ * 2, 0);
kwibergc13ded52016-06-17 06:00:45 -0700340 }
341 return 0;
342}
343
344void ConvertEncodedInfoToFragmentationHeader(
345 const AudioEncoder::EncodedInfo& info,
346 RTPFragmentationHeader* frag) {
347 if (info.redundant.empty()) {
348 frag->fragmentationVectorSize = 0;
349 return;
350 }
351
352 frag->VerifyAndAllocateFragmentationHeader(
353 static_cast<uint16_t>(info.redundant.size()));
354 frag->fragmentationVectorSize = static_cast<uint16_t>(info.redundant.size());
355 size_t offset = 0;
356 for (size_t i = 0; i < info.redundant.size(); ++i) {
357 frag->fragmentationOffset[i] = offset;
358 offset += info.redundant[i].encoded_bytes;
359 frag->fragmentationLength[i] = info.redundant[i].encoded_bytes;
kwibergd3edd772017-03-01 18:52:48 -0800360 frag->fragmentationTimeDiff[i] = rtc::dchecked_cast<uint16_t>(
kwibergc13ded52016-06-17 06:00:45 -0700361 info.encoded_timestamp - info.redundant[i].encoded_timestamp);
362 frag->fragmentationPlType[i] = info.redundant[i].payload_type;
363 }
364}
365
366// Wraps a raw AudioEncoder pointer. The idea is that you can put one of these
367// in a unique_ptr, to protect the contained raw pointer from being deleted
368// when the unique_ptr expires. (This is of course a bad idea in general, but
369// backwards compatibility.)
370class RawAudioEncoderWrapper final : public AudioEncoder {
371 public:
372 RawAudioEncoderWrapper(AudioEncoder* enc) : enc_(enc) {}
373 int SampleRateHz() const override { return enc_->SampleRateHz(); }
374 size_t NumChannels() const override { return enc_->NumChannels(); }
375 int RtpTimestampRateHz() const override { return enc_->RtpTimestampRateHz(); }
376 size_t Num10MsFramesInNextPacket() const override {
377 return enc_->Num10MsFramesInNextPacket();
378 }
379 size_t Max10MsFramesInAPacket() const override {
380 return enc_->Max10MsFramesInAPacket();
381 }
382 int GetTargetBitrate() const override { return enc_->GetTargetBitrate(); }
383 EncodedInfo EncodeImpl(uint32_t rtp_timestamp,
384 rtc::ArrayView<const int16_t> audio,
385 rtc::Buffer* encoded) override {
386 return enc_->Encode(rtp_timestamp, audio, encoded);
387 }
388 void Reset() override { return enc_->Reset(); }
389 bool SetFec(bool enable) override { return enc_->SetFec(enable); }
390 bool SetDtx(bool enable) override { return enc_->SetDtx(enable); }
391 bool SetApplication(Application application) override {
392 return enc_->SetApplication(application);
393 }
394 void SetMaxPlaybackRate(int frequency_hz) override {
395 return enc_->SetMaxPlaybackRate(frequency_hz);
396 }
kwibergc13ded52016-06-17 06:00:45 -0700397
398 private:
399 AudioEncoder* enc_;
400};
401
402// Return false on error.
403bool CreateSpeechEncoderIfNecessary(EncoderFactory* ef) {
404 auto* sp = ef->codec_manager.GetStackParams();
405 if (sp->speech_encoder) {
406 // Do nothing; we already have a speech encoder.
407 } else if (ef->codec_manager.GetCodecInst()) {
408 RTC_DCHECK(!ef->external_speech_encoder);
409 // We have no speech encoder, but we have a specification for making one.
410 std::unique_ptr<AudioEncoder> enc =
411 ef->rent_a_codec.RentEncoder(*ef->codec_manager.GetCodecInst());
412 if (!enc)
413 return false; // Encoder spec was bad.
414 sp->speech_encoder = std::move(enc);
415 } else if (ef->external_speech_encoder) {
416 RTC_DCHECK(!ef->codec_manager.GetCodecInst());
417 // We have an external speech encoder.
418 sp->speech_encoder = std::unique_ptr<AudioEncoder>(
419 new RawAudioEncoderWrapper(ef->external_speech_encoder));
420 }
421 return true;
422}
423
424void AudioCodingModuleImpl::ChangeLogger::MaybeLog(int value) {
425 if (value != last_value_ || first_time_) {
426 first_time_ = false;
427 last_value_ = value;
428 RTC_HISTOGRAM_COUNTS_SPARSE_100(histogram_name_, value);
429 }
430}
431
432AudioCodingModuleImpl::AudioCodingModuleImpl(
433 const AudioCodingModule::Config& config)
solenbergc7b4a452017-09-28 07:37:11 -0700434 : expected_codec_ts_(0xD87F3F9F),
kwibergc13ded52016-06-17 06:00:45 -0700435 expected_in_ts_(0xD87F3F9F),
436 receiver_(config),
437 bitrate_logger_("WebRTC.Audio.TargetBitrateInKbps"),
438 encoder_factory_(new EncoderFactory),
439 encoder_stack_(nullptr),
440 previous_pltype_(255),
441 receiver_initialized_(false),
442 first_10ms_data_(false),
443 first_frame_(true),
444 packetization_callback_(NULL),
445 vad_callback_(NULL),
446 codec_histogram_bins_log_(),
447 number_of_consecutive_empty_packets_(0) {
448 if (InitializeReceiverSafe() < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100449 RTC_LOG(LS_ERROR) << "Cannot initialize receiver";
kwibergc13ded52016-06-17 06:00:45 -0700450 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100451 RTC_LOG(LS_INFO) << "Created";
kwibergc13ded52016-06-17 06:00:45 -0700452}
453
454AudioCodingModuleImpl::~AudioCodingModuleImpl() = default;
455
456int32_t AudioCodingModuleImpl::Encode(const InputData& input_data) {
457 AudioEncoder::EncodedInfo encoded_info;
458 uint8_t previous_pltype;
459
460 // Check if there is an encoder before.
461 if (!HaveValidEncoder("Process"))
462 return -1;
463
Yves Gerey665174f2018-06-19 15:03:05 +0200464 if (!first_frame_) {
deadbeeffcada902016-08-24 12:45:13 -0700465 RTC_DCHECK(IsNewerTimestamp(input_data.input_timestamp, last_timestamp_))
ossu63fb95a2016-07-06 09:34:22 -0700466 << "Time should not move backwards";
467 }
468
kwibergc13ded52016-06-17 06:00:45 -0700469 // Scale the timestamp to the codec's RTP timestamp rate.
470 uint32_t rtp_timestamp =
471 first_frame_ ? input_data.input_timestamp
472 : last_rtp_timestamp_ +
473 rtc::CheckedDivExact(
474 input_data.input_timestamp - last_timestamp_,
475 static_cast<uint32_t>(rtc::CheckedDivExact(
476 encoder_stack_->SampleRateHz(),
477 encoder_stack_->RtpTimestampRateHz())));
478 last_timestamp_ = input_data.input_timestamp;
479 last_rtp_timestamp_ = rtp_timestamp;
480 first_frame_ = false;
481
482 // Clear the buffer before reuse - encoded data will get appended.
483 encode_buffer_.Clear();
484 encoded_info = encoder_stack_->Encode(
Yves Gerey665174f2018-06-19 15:03:05 +0200485 rtp_timestamp,
486 rtc::ArrayView<const int16_t>(
487 input_data.audio,
488 input_data.audio_channel * input_data.length_per_channel),
kwibergc13ded52016-06-17 06:00:45 -0700489 &encode_buffer_);
490
491 bitrate_logger_.MaybeLog(encoder_stack_->GetTargetBitrate() / 1000);
492 if (encode_buffer_.size() == 0 && !encoded_info.send_even_if_empty) {
493 // Not enough data.
494 return 0;
495 }
496 previous_pltype = previous_pltype_; // Read it while we have the critsect.
497
498 // Log codec type to histogram once every 500 packets.
499 if (encoded_info.encoded_bytes == 0) {
500 ++number_of_consecutive_empty_packets_;
501 } else {
502 size_t codec_type = static_cast<size_t>(encoded_info.encoder_type);
503 codec_histogram_bins_log_[codec_type] +=
504 number_of_consecutive_empty_packets_ + 1;
505 number_of_consecutive_empty_packets_ = 0;
506 if (codec_histogram_bins_log_[codec_type] >= 500) {
507 codec_histogram_bins_log_[codec_type] -= 500;
508 UpdateCodecTypeHistogram(codec_type);
509 }
510 }
511
512 RTPFragmentationHeader my_fragmentation;
513 ConvertEncodedInfoToFragmentationHeader(encoded_info, &my_fragmentation);
514 FrameType frame_type;
515 if (encode_buffer_.size() == 0 && encoded_info.send_even_if_empty) {
516 frame_type = kEmptyFrame;
517 encoded_info.payload_type = previous_pltype;
518 } else {
kwibergaf476c72016-11-28 15:21:39 -0800519 RTC_DCHECK_GT(encode_buffer_.size(), 0);
kwibergc13ded52016-06-17 06:00:45 -0700520 frame_type = encoded_info.speech ? kAudioFrameSpeech : kAudioFrameCN;
521 }
522
523 {
524 rtc::CritScope lock(&callback_crit_sect_);
525 if (packetization_callback_) {
526 packetization_callback_->SendData(
527 frame_type, encoded_info.payload_type, encoded_info.encoded_timestamp,
528 encode_buffer_.data(), encode_buffer_.size(),
529 my_fragmentation.fragmentationVectorSize > 0 ? &my_fragmentation
530 : nullptr);
531 }
532
533 if (vad_callback_) {
534 // Callback with VAD decision.
535 vad_callback_->InFrameType(frame_type);
536 }
537 }
538 previous_pltype_ = encoded_info.payload_type;
539 return static_cast<int32_t>(encode_buffer_.size());
540}
541
542/////////////////////////////////////////
543// Sender
544//
545
546// Can be called multiple times for Codec, CNG, RED.
547int AudioCodingModuleImpl::RegisterSendCodec(const CodecInst& send_codec) {
548 rtc::CritScope lock(&acm_crit_sect_);
549 if (!encoder_factory_->codec_manager.RegisterEncoder(send_codec)) {
550 return -1;
551 }
552 if (encoder_factory_->codec_manager.GetCodecInst()) {
553 encoder_factory_->external_speech_encoder = nullptr;
554 }
555 if (!CreateSpeechEncoderIfNecessary(encoder_factory_.get())) {
556 return -1;
557 }
558 auto* sp = encoder_factory_->codec_manager.GetStackParams();
559 if (sp->speech_encoder)
560 encoder_stack_ = encoder_factory_->rent_a_codec.RentEncoderStack(sp);
561 return 0;
562}
563
564void AudioCodingModuleImpl::RegisterExternalSendCodec(
565 AudioEncoder* external_speech_encoder) {
566 rtc::CritScope lock(&acm_crit_sect_);
567 encoder_factory_->codec_manager.UnsetCodecInst();
568 encoder_factory_->external_speech_encoder = external_speech_encoder;
569 RTC_CHECK(CreateSpeechEncoderIfNecessary(encoder_factory_.get()));
570 auto* sp = encoder_factory_->codec_manager.GetStackParams();
571 RTC_CHECK(sp->speech_encoder);
572 encoder_stack_ = encoder_factory_->rent_a_codec.RentEncoderStack(sp);
573}
574
575void AudioCodingModuleImpl::ModifyEncoder(
kwiberg24c7c122016-09-28 11:57:10 -0700576 rtc::FunctionView<void(std::unique_ptr<AudioEncoder>*)> modifier) {
kwibergc13ded52016-06-17 06:00:45 -0700577 rtc::CritScope lock(&acm_crit_sect_);
578
579 // Wipe the encoder factory, so that everything that relies on it will fail.
580 // We don't want the complexity of supporting swapping back and forth.
581 if (encoder_factory_) {
582 encoder_factory_.reset();
583 RTC_CHECK(!encoder_stack_); // Ensure we hadn't started using the factory.
584 }
585
586 modifier(&encoder_stack_);
587}
588
589// Get current send codec.
Danil Chapovalovb6021232018-06-19 13:26:36 +0200590absl::optional<CodecInst> AudioCodingModuleImpl::SendCodec() const {
kwibergc13ded52016-06-17 06:00:45 -0700591 rtc::CritScope lock(&acm_crit_sect_);
592 if (encoder_factory_) {
593 auto* ci = encoder_factory_->codec_manager.GetCodecInst();
594 if (ci) {
Oskar Sundbom12ab00b2017-11-16 15:31:38 +0100595 return *ci;
kwibergc13ded52016-06-17 06:00:45 -0700596 }
597 CreateSpeechEncoderIfNecessary(encoder_factory_.get());
598 const std::unique_ptr<AudioEncoder>& enc =
599 encoder_factory_->codec_manager.GetStackParams()->speech_encoder;
600 if (enc) {
Oskar Sundbom12ab00b2017-11-16 15:31:38 +0100601 return acm2::CodecManager::ForgeCodecInst(enc.get());
kwibergc13ded52016-06-17 06:00:45 -0700602 }
Danil Chapovalovb6021232018-06-19 13:26:36 +0200603 return absl::nullopt;
kwibergc13ded52016-06-17 06:00:45 -0700604 } else {
605 return encoder_stack_
Danil Chapovalovb6021232018-06-19 13:26:36 +0200606 ? absl::optional<CodecInst>(
kwibergc13ded52016-06-17 06:00:45 -0700607 acm2::CodecManager::ForgeCodecInst(encoder_stack_.get()))
Danil Chapovalovb6021232018-06-19 13:26:36 +0200608 : absl::nullopt;
kwibergc13ded52016-06-17 06:00:45 -0700609 }
610}
611
kwibergc13ded52016-06-17 06:00:45 -0700612void AudioCodingModuleImpl::SetBitRate(int bitrate_bps) {
613 rtc::CritScope lock(&acm_crit_sect_);
614 if (encoder_stack_) {
Danil Chapovalovb6021232018-06-19 13:26:36 +0200615 encoder_stack_->OnReceivedUplinkBandwidth(bitrate_bps, absl::nullopt);
kwibergc13ded52016-06-17 06:00:45 -0700616 }
617}
618
619// Register a transport callback which will be called to deliver
620// the encoded buffers.
621int AudioCodingModuleImpl::RegisterTransportCallback(
622 AudioPacketizationCallback* transport) {
623 rtc::CritScope lock(&callback_crit_sect_);
624 packetization_callback_ = transport;
625 return 0;
626}
627
628// Add 10MS of raw (PCM) audio data to the encoder.
629int AudioCodingModuleImpl::Add10MsData(const AudioFrame& audio_frame) {
630 InputData input_data;
631 rtc::CritScope lock(&acm_crit_sect_);
632 int r = Add10MsDataInternal(audio_frame, &input_data);
633 return r < 0 ? r : Encode(input_data);
634}
635
636int AudioCodingModuleImpl::Add10MsDataInternal(const AudioFrame& audio_frame,
637 InputData* input_data) {
638 if (audio_frame.samples_per_channel_ == 0) {
639 assert(false);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100640 RTC_LOG(LS_ERROR) << "Cannot Add 10 ms audio, payload length is zero";
kwibergc13ded52016-06-17 06:00:45 -0700641 return -1;
642 }
643
644 if (audio_frame.sample_rate_hz_ > 48000) {
645 assert(false);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100646 RTC_LOG(LS_ERROR) << "Cannot Add 10 ms audio, input frequency not valid";
kwibergc13ded52016-06-17 06:00:45 -0700647 return -1;
648 }
649
650 // If the length and frequency matches. We currently just support raw PCM.
651 if (static_cast<size_t>(audio_frame.sample_rate_hz_ / 100) !=
652 audio_frame.samples_per_channel_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100653 RTC_LOG(LS_ERROR)
Alex Loiko300ec8c2017-05-30 17:23:28 +0200654 << "Cannot Add 10 ms audio, input frequency and length doesn't match";
kwibergc13ded52016-06-17 06:00:45 -0700655 return -1;
656 }
657
658 if (audio_frame.num_channels_ != 1 && audio_frame.num_channels_ != 2) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100659 RTC_LOG(LS_ERROR) << "Cannot Add 10 ms audio, invalid number of channels.";
kwibergc13ded52016-06-17 06:00:45 -0700660 return -1;
661 }
662
663 // Do we have a codec registered?
664 if (!HaveValidEncoder("Add10MsData")) {
665 return -1;
666 }
667
668 const AudioFrame* ptr_frame;
669 // Perform a resampling, also down-mix if it is required and can be
670 // performed before resampling (a down mix prior to resampling will take
671 // place if both primary and secondary encoders are mono and input is in
672 // stereo).
673 if (PreprocessToAddData(audio_frame, &ptr_frame) < 0) {
674 return -1;
675 }
676
677 // Check whether we need an up-mix or down-mix?
678 const size_t current_num_channels = encoder_stack_->NumChannels();
679 const bool same_num_channels =
680 ptr_frame->num_channels_ == current_num_channels;
681
682 if (!same_num_channels) {
683 if (ptr_frame->num_channels_ == 1) {
684 if (UpMix(*ptr_frame, WEBRTC_10MS_PCM_AUDIO, input_data->buffer) < 0)
685 return -1;
686 } else {
687 if (DownMix(*ptr_frame, WEBRTC_10MS_PCM_AUDIO, input_data->buffer) < 0)
688 return -1;
689 }
690 }
691
692 // When adding data to encoders this pointer is pointing to an audio buffer
693 // with correct number of channels.
yujo36b1a5f2017-06-12 12:45:32 -0700694 const int16_t* ptr_audio = ptr_frame->data();
kwibergc13ded52016-06-17 06:00:45 -0700695
696 // For pushing data to primary, point the |ptr_audio| to correct buffer.
697 if (!same_num_channels)
698 ptr_audio = input_data->buffer;
699
yujo36b1a5f2017-06-12 12:45:32 -0700700 // TODO(yujo): Skip encode of muted frames.
kwibergc13ded52016-06-17 06:00:45 -0700701 input_data->input_timestamp = ptr_frame->timestamp_;
702 input_data->audio = ptr_audio;
703 input_data->length_per_channel = ptr_frame->samples_per_channel_;
704 input_data->audio_channel = current_num_channels;
705
706 return 0;
707}
708
709// Perform a resampling and down-mix if required. We down-mix only if
710// encoder is mono and input is stereo. In case of dual-streaming, both
711// encoders has to be mono for down-mix to take place.
712// |*ptr_out| will point to the pre-processed audio-frame. If no pre-processing
713// is required, |*ptr_out| points to |in_frame|.
yujo36b1a5f2017-06-12 12:45:32 -0700714// TODO(yujo): Make this more efficient for muted frames.
kwibergc13ded52016-06-17 06:00:45 -0700715int AudioCodingModuleImpl::PreprocessToAddData(const AudioFrame& in_frame,
716 const AudioFrame** ptr_out) {
717 const bool resample =
718 in_frame.sample_rate_hz_ != encoder_stack_->SampleRateHz();
719
720 // This variable is true if primary codec and secondary codec (if exists)
721 // are both mono and input is stereo.
722 // TODO(henrik.lundin): This condition should probably be
723 // in_frame.num_channels_ > encoder_stack_->NumChannels()
724 const bool down_mix =
725 in_frame.num_channels_ == 2 && encoder_stack_->NumChannels() == 1;
726
727 if (!first_10ms_data_) {
728 expected_in_ts_ = in_frame.timestamp_;
729 expected_codec_ts_ = in_frame.timestamp_;
730 first_10ms_data_ = true;
731 } else if (in_frame.timestamp_ != expected_in_ts_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100732 RTC_LOG(LS_WARNING) << "Unexpected input timestamp: " << in_frame.timestamp_
733 << ", expected: " << expected_in_ts_;
kwibergc13ded52016-06-17 06:00:45 -0700734 expected_codec_ts_ +=
735 (in_frame.timestamp_ - expected_in_ts_) *
736 static_cast<uint32_t>(
737 static_cast<double>(encoder_stack_->SampleRateHz()) /
738 static_cast<double>(in_frame.sample_rate_hz_));
739 expected_in_ts_ = in_frame.timestamp_;
740 }
741
kwibergc13ded52016-06-17 06:00:45 -0700742 if (!down_mix && !resample) {
743 // No pre-processing is required.
ossu63fb95a2016-07-06 09:34:22 -0700744 if (expected_in_ts_ == expected_codec_ts_) {
745 // If we've never resampled, we can use the input frame as-is
746 *ptr_out = &in_frame;
747 } else {
748 // Otherwise we'll need to alter the timestamp. Since in_frame is const,
749 // we'll have to make a copy of it.
750 preprocess_frame_.CopyFrom(in_frame);
751 preprocess_frame_.timestamp_ = expected_codec_ts_;
752 *ptr_out = &preprocess_frame_;
753 }
754
kwibergc13ded52016-06-17 06:00:45 -0700755 expected_in_ts_ += static_cast<uint32_t>(in_frame.samples_per_channel_);
756 expected_codec_ts_ += static_cast<uint32_t>(in_frame.samples_per_channel_);
kwibergc13ded52016-06-17 06:00:45 -0700757 return 0;
758 }
759
760 *ptr_out = &preprocess_frame_;
761 preprocess_frame_.num_channels_ = in_frame.num_channels_;
762 int16_t audio[WEBRTC_10MS_PCM_AUDIO];
yujo36b1a5f2017-06-12 12:45:32 -0700763 const int16_t* src_ptr_audio = in_frame.data();
kwibergc13ded52016-06-17 06:00:45 -0700764 if (down_mix) {
765 // If a resampling is required the output of a down-mix is written into a
766 // local buffer, otherwise, it will be written to the output frame.
Yves Gerey665174f2018-06-19 15:03:05 +0200767 int16_t* dest_ptr_audio =
768 resample ? audio : preprocess_frame_.mutable_data();
kwibergc13ded52016-06-17 06:00:45 -0700769 if (DownMix(in_frame, WEBRTC_10MS_PCM_AUDIO, dest_ptr_audio) < 0)
770 return -1;
771 preprocess_frame_.num_channels_ = 1;
772 // Set the input of the resampler is the down-mixed signal.
773 src_ptr_audio = audio;
774 }
775
776 preprocess_frame_.timestamp_ = expected_codec_ts_;
777 preprocess_frame_.samples_per_channel_ = in_frame.samples_per_channel_;
778 preprocess_frame_.sample_rate_hz_ = in_frame.sample_rate_hz_;
779 // If it is required, we have to do a resampling.
780 if (resample) {
781 // The result of the resampler is written to output frame.
yujo36b1a5f2017-06-12 12:45:32 -0700782 int16_t* dest_ptr_audio = preprocess_frame_.mutable_data();
kwibergc13ded52016-06-17 06:00:45 -0700783
784 int samples_per_channel = resampler_.Resample10Msec(
785 src_ptr_audio, in_frame.sample_rate_hz_, encoder_stack_->SampleRateHz(),
786 preprocess_frame_.num_channels_, AudioFrame::kMaxDataSizeSamples,
787 dest_ptr_audio);
788
789 if (samples_per_channel < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100790 RTC_LOG(LS_ERROR) << "Cannot add 10 ms audio, resampling failed";
kwibergc13ded52016-06-17 06:00:45 -0700791 return -1;
792 }
793 preprocess_frame_.samples_per_channel_ =
794 static_cast<size_t>(samples_per_channel);
795 preprocess_frame_.sample_rate_hz_ = encoder_stack_->SampleRateHz();
796 }
797
798 expected_codec_ts_ +=
799 static_cast<uint32_t>(preprocess_frame_.samples_per_channel_);
800 expected_in_ts_ += static_cast<uint32_t>(in_frame.samples_per_channel_);
801
802 return 0;
803}
804
805/////////////////////////////////////////
806// (RED) Redundant Coding
807//
808
809bool AudioCodingModuleImpl::REDStatus() const {
810 rtc::CritScope lock(&acm_crit_sect_);
811 return encoder_factory_->codec_manager.GetStackParams()->use_red;
812}
813
814// Configure RED status i.e on/off.
815int AudioCodingModuleImpl::SetREDStatus(bool enable_red) {
816#ifdef WEBRTC_CODEC_RED
817 rtc::CritScope lock(&acm_crit_sect_);
818 CreateSpeechEncoderIfNecessary(encoder_factory_.get());
819 if (!encoder_factory_->codec_manager.SetCopyRed(enable_red)) {
820 return -1;
821 }
822 auto* sp = encoder_factory_->codec_manager.GetStackParams();
823 if (sp->speech_encoder)
824 encoder_stack_ = encoder_factory_->rent_a_codec.RentEncoderStack(sp);
825 return 0;
826#else
Mirko Bonadei675513b2017-11-09 11:09:25 +0100827 RTC_LOG(LS_WARNING) << " WEBRTC_CODEC_RED is undefined";
kwibergc13ded52016-06-17 06:00:45 -0700828 return -1;
829#endif
830}
831
832/////////////////////////////////////////
833// (FEC) Forward Error Correction (codec internal)
834//
835
836bool AudioCodingModuleImpl::CodecFEC() const {
837 rtc::CritScope lock(&acm_crit_sect_);
838 return encoder_factory_->codec_manager.GetStackParams()->use_codec_fec;
839}
840
841int AudioCodingModuleImpl::SetCodecFEC(bool enable_codec_fec) {
842 rtc::CritScope lock(&acm_crit_sect_);
843 CreateSpeechEncoderIfNecessary(encoder_factory_.get());
844 if (!encoder_factory_->codec_manager.SetCodecFEC(enable_codec_fec)) {
845 return -1;
846 }
847 auto* sp = encoder_factory_->codec_manager.GetStackParams();
848 if (sp->speech_encoder)
849 encoder_stack_ = encoder_factory_->rent_a_codec.RentEncoderStack(sp);
850 if (enable_codec_fec) {
851 return sp->use_codec_fec ? 0 : -1;
852 } else {
853 RTC_DCHECK(!sp->use_codec_fec);
854 return 0;
855 }
856}
857
858int AudioCodingModuleImpl::SetPacketLossRate(int loss_rate) {
859 rtc::CritScope lock(&acm_crit_sect_);
860 if (HaveValidEncoder("SetPacketLossRate")) {
minyue4b9a2cb2016-11-30 06:49:59 -0800861 encoder_stack_->OnReceivedUplinkPacketLossFraction(loss_rate / 100.0);
kwibergc13ded52016-06-17 06:00:45 -0700862 }
863 return 0;
864}
865
866/////////////////////////////////////////
867// (VAD) Voice Activity Detection
868//
869int AudioCodingModuleImpl::SetVAD(bool enable_dtx,
870 bool enable_vad,
871 ACMVADMode mode) {
872 // Note: |enable_vad| is not used; VAD is enabled based on the DTX setting.
873 RTC_DCHECK_EQ(enable_dtx, enable_vad);
874 rtc::CritScope lock(&acm_crit_sect_);
875 CreateSpeechEncoderIfNecessary(encoder_factory_.get());
876 if (!encoder_factory_->codec_manager.SetVAD(enable_dtx, mode)) {
877 return -1;
878 }
879 auto* sp = encoder_factory_->codec_manager.GetStackParams();
880 if (sp->speech_encoder)
881 encoder_stack_ = encoder_factory_->rent_a_codec.RentEncoderStack(sp);
882 return 0;
883}
884
885// Get VAD/DTX settings.
Yves Gerey665174f2018-06-19 15:03:05 +0200886int AudioCodingModuleImpl::VAD(bool* dtx_enabled,
887 bool* vad_enabled,
kwibergc13ded52016-06-17 06:00:45 -0700888 ACMVADMode* mode) const {
889 rtc::CritScope lock(&acm_crit_sect_);
890 const auto* sp = encoder_factory_->codec_manager.GetStackParams();
891 *dtx_enabled = *vad_enabled = sp->use_cng;
892 *mode = sp->vad_mode;
893 return 0;
894}
895
896/////////////////////////////////////////
897// Receiver
898//
899
900int AudioCodingModuleImpl::InitializeReceiver() {
901 rtc::CritScope lock(&acm_crit_sect_);
902 return InitializeReceiverSafe();
903}
904
905// Initialize receiver, resets codec database etc.
906int AudioCodingModuleImpl::InitializeReceiverSafe() {
907 // If the receiver is already initialized then we want to destroy any
908 // existing decoders. After a call to this function, we should have a clean
909 // start-up.
kwiberg6b19b562016-09-20 04:02:25 -0700910 if (receiver_initialized_)
911 receiver_.RemoveAllCodecs();
kwibergc13ded52016-06-17 06:00:45 -0700912 receiver_.ResetInitialDelay();
913 receiver_.SetMinimumDelay(0);
914 receiver_.SetMaximumDelay(0);
915 receiver_.FlushBuffers();
916
kwibergc13ded52016-06-17 06:00:45 -0700917 receiver_initialized_ = true;
918 return 0;
919}
920
921// Get current receive frequency.
922int AudioCodingModuleImpl::ReceiveFrequency() const {
923 const auto last_packet_sample_rate = receiver_.last_packet_sample_rate_hz();
924 return last_packet_sample_rate ? *last_packet_sample_rate
925 : receiver_.last_output_sample_rate_hz();
926}
927
928// Get current playout frequency.
929int AudioCodingModuleImpl::PlayoutFrequency() const {
kwibergc13ded52016-06-17 06:00:45 -0700930 return receiver_.last_output_sample_rate_hz();
931}
932
kwiberg1c07c702017-03-27 07:15:49 -0700933void AudioCodingModuleImpl::SetReceiveCodecs(
934 const std::map<int, SdpAudioFormat>& codecs) {
935 rtc::CritScope lock(&acm_crit_sect_);
936 receiver_.SetCodecs(codecs);
937}
938
kwiberg5adaf732016-10-04 09:33:27 -0700939bool AudioCodingModuleImpl::RegisterReceiveCodec(
940 int rtp_payload_type,
941 const SdpAudioFormat& audio_format) {
942 rtc::CritScope lock(&acm_crit_sect_);
943 RTC_DCHECK(receiver_initialized_);
944
945 if (!acm2::RentACodec::IsPayloadTypeValid(rtp_payload_type)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100946 RTC_LOG_F(LS_ERROR) << "Invalid payload-type " << rtp_payload_type
947 << " for decoder.";
kwiberg5adaf732016-10-04 09:33:27 -0700948 return false;
949 }
950
951 return receiver_.AddCodec(rtp_payload_type, audio_format);
952}
953
kwibergc13ded52016-06-17 06:00:45 -0700954int AudioCodingModuleImpl::RegisterReceiveCodec(const CodecInst& codec) {
955 rtc::CritScope lock(&acm_crit_sect_);
956 auto* ef = encoder_factory_.get();
957 return RegisterReceiveCodecUnlocked(
958 codec, [&] { return ef->rent_a_codec.RentIsacDecoder(codec.plfreq); });
959}
960
961int AudioCodingModuleImpl::RegisterReceiveCodec(
962 const CodecInst& codec,
kwiberg24c7c122016-09-28 11:57:10 -0700963 rtc::FunctionView<std::unique_ptr<AudioDecoder>()> isac_factory) {
kwibergc13ded52016-06-17 06:00:45 -0700964 rtc::CritScope lock(&acm_crit_sect_);
965 return RegisterReceiveCodecUnlocked(codec, isac_factory);
966}
967
968int AudioCodingModuleImpl::RegisterReceiveCodecUnlocked(
969 const CodecInst& codec,
kwiberg24c7c122016-09-28 11:57:10 -0700970 rtc::FunctionView<std::unique_ptr<AudioDecoder>()> isac_factory) {
kwibergc13ded52016-06-17 06:00:45 -0700971 RTC_DCHECK(receiver_initialized_);
972 if (codec.channels > 2) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100973 RTC_LOG_F(LS_ERROR) << "Unsupported number of channels: " << codec.channels;
kwibergc13ded52016-06-17 06:00:45 -0700974 return -1;
975 }
976
977 auto codec_id = acm2::RentACodec::CodecIdByParams(codec.plname, codec.plfreq,
978 codec.channels);
979 if (!codec_id) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100980 RTC_LOG_F(LS_ERROR)
981 << "Wrong codec params to be registered as receive codec";
kwibergc13ded52016-06-17 06:00:45 -0700982 return -1;
983 }
984 auto codec_index = acm2::RentACodec::CodecIndexFromId(*codec_id);
985 RTC_CHECK(codec_index) << "Invalid codec ID: " << static_cast<int>(*codec_id);
986
987 // Check if the payload-type is valid.
988 if (!acm2::RentACodec::IsPayloadTypeValid(codec.pltype)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100989 RTC_LOG_F(LS_ERROR) << "Invalid payload type " << codec.pltype << " for "
990 << codec.plname;
kwibergc13ded52016-06-17 06:00:45 -0700991 return -1;
992 }
993
994 AudioDecoder* isac_decoder = nullptr;
995 if (STR_CASE_CMP(codec.plname, "isac") == 0) {
996 std::unique_ptr<AudioDecoder>& saved_isac_decoder =
997 codec.plfreq == 16000 ? isac_decoder_16k_ : isac_decoder_32k_;
998 if (!saved_isac_decoder) {
999 saved_isac_decoder = isac_factory();
1000 }
1001 isac_decoder = saved_isac_decoder.get();
1002 }
1003 return receiver_.AddCodec(*codec_index, codec.pltype, codec.channels,
1004 codec.plfreq, isac_decoder, codec.plname);
1005}
1006
1007int AudioCodingModuleImpl::RegisterExternalReceiveCodec(
1008 int rtp_payload_type,
1009 AudioDecoder* external_decoder,
1010 int sample_rate_hz,
1011 int num_channels,
1012 const std::string& name) {
1013 rtc::CritScope lock(&acm_crit_sect_);
1014 RTC_DCHECK(receiver_initialized_);
1015 if (num_channels > 2 || num_channels < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001016 RTC_LOG_F(LS_ERROR) << "Unsupported number of channels: " << num_channels;
kwibergc13ded52016-06-17 06:00:45 -07001017 return -1;
1018 }
1019
1020 // Check if the payload-type is valid.
1021 if (!acm2::RentACodec::IsPayloadTypeValid(rtp_payload_type)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001022 RTC_LOG_F(LS_ERROR) << "Invalid payload-type " << rtp_payload_type
1023 << " for external decoder.";
kwibergc13ded52016-06-17 06:00:45 -07001024 return -1;
1025 }
1026
1027 return receiver_.AddCodec(-1 /* external */, rtp_payload_type, num_channels,
1028 sample_rate_hz, external_decoder, name);
1029}
1030
1031// Get current received codec.
1032int AudioCodingModuleImpl::ReceiveCodec(CodecInst* current_codec) const {
1033 rtc::CritScope lock(&acm_crit_sect_);
1034 return receiver_.LastAudioCodec(current_codec);
1035}
1036
Danil Chapovalovb6021232018-06-19 13:26:36 +02001037absl::optional<SdpAudioFormat> AudioCodingModuleImpl::ReceiveFormat() const {
ossue280cde2016-10-12 11:04:10 -07001038 rtc::CritScope lock(&acm_crit_sect_);
1039 return receiver_.LastAudioFormat();
1040}
1041
kwibergc13ded52016-06-17 06:00:45 -07001042// Incoming packet from network parsed and ready for decode.
1043int AudioCodingModuleImpl::IncomingPacket(const uint8_t* incoming_payload,
1044 const size_t payload_length,
1045 const WebRtcRTPHeader& rtp_header) {
henrik.lundinb8c55b12017-05-10 07:38:01 -07001046 RTC_DCHECK_EQ(payload_length == 0, incoming_payload == nullptr);
kwibergc13ded52016-06-17 06:00:45 -07001047 return receiver_.InsertPacket(
1048 rtp_header,
1049 rtc::ArrayView<const uint8_t>(incoming_payload, payload_length));
1050}
1051
1052// Minimum playout delay (Used for lip-sync).
1053int AudioCodingModuleImpl::SetMinimumPlayoutDelay(int time_ms) {
1054 if ((time_ms < 0) || (time_ms > 10000)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001055 RTC_LOG(LS_ERROR) << "Delay must be in the range of 0-10000 milliseconds.";
kwibergc13ded52016-06-17 06:00:45 -07001056 return -1;
1057 }
1058 return receiver_.SetMinimumDelay(time_ms);
1059}
1060
1061int AudioCodingModuleImpl::SetMaximumPlayoutDelay(int time_ms) {
1062 if ((time_ms < 0) || (time_ms > 10000)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001063 RTC_LOG(LS_ERROR) << "Delay must be in the range of 0-10000 milliseconds.";
kwibergc13ded52016-06-17 06:00:45 -07001064 return -1;
1065 }
1066 return receiver_.SetMaximumDelay(time_ms);
1067}
1068
1069// Get 10 milliseconds of raw audio data to play out.
1070// Automatic resample to the requested frequency.
1071int AudioCodingModuleImpl::PlayoutData10Ms(int desired_freq_hz,
1072 AudioFrame* audio_frame,
1073 bool* muted) {
1074 // GetAudio always returns 10 ms, at the requested sample rate.
1075 if (receiver_.GetAudio(desired_freq_hz, audio_frame, muted) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001076 RTC_LOG(LS_ERROR) << "PlayoutData failed, RecOut Failed";
kwibergc13ded52016-06-17 06:00:45 -07001077 return -1;
1078 }
kwibergc13ded52016-06-17 06:00:45 -07001079 return 0;
1080}
1081
kwibergc13ded52016-06-17 06:00:45 -07001082/////////////////////////////////////////
1083// Statistics
1084//
1085
1086// TODO(turajs) change the return value to void. Also change the corresponding
1087// NetEq function.
1088int AudioCodingModuleImpl::GetNetworkStatistics(NetworkStatistics* statistics) {
1089 receiver_.GetNetworkStatistics(statistics);
1090 return 0;
1091}
1092
1093int AudioCodingModuleImpl::RegisterVADCallback(ACMVADCallback* vad_callback) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001094 RTC_LOG(LS_VERBOSE) << "RegisterVADCallback()";
kwibergc13ded52016-06-17 06:00:45 -07001095 rtc::CritScope lock(&callback_crit_sect_);
1096 vad_callback_ = vad_callback;
1097 return 0;
1098}
1099
kwibergc13ded52016-06-17 06:00:45 -07001100int AudioCodingModuleImpl::SetOpusApplication(OpusApplicationMode application) {
1101 rtc::CritScope lock(&acm_crit_sect_);
1102 if (!HaveValidEncoder("SetOpusApplication")) {
1103 return -1;
1104 }
1105 AudioEncoder::Application app;
1106 switch (application) {
1107 case kVoip:
1108 app = AudioEncoder::Application::kSpeech;
1109 break;
1110 case kAudio:
1111 app = AudioEncoder::Application::kAudio;
1112 break;
1113 default:
1114 FATAL();
1115 return 0;
1116 }
1117 return encoder_stack_->SetApplication(app) ? 0 : -1;
1118}
1119
1120// Informs Opus encoder of the maximum playback rate the receiver will render.
1121int AudioCodingModuleImpl::SetOpusMaxPlaybackRate(int frequency_hz) {
1122 rtc::CritScope lock(&acm_crit_sect_);
1123 if (!HaveValidEncoder("SetOpusMaxPlaybackRate")) {
1124 return -1;
1125 }
1126 encoder_stack_->SetMaxPlaybackRate(frequency_hz);
1127 return 0;
1128}
1129
1130int AudioCodingModuleImpl::EnableOpusDtx() {
1131 rtc::CritScope lock(&acm_crit_sect_);
1132 if (!HaveValidEncoder("EnableOpusDtx")) {
1133 return -1;
1134 }
1135 return encoder_stack_->SetDtx(true) ? 0 : -1;
1136}
1137
1138int AudioCodingModuleImpl::DisableOpusDtx() {
1139 rtc::CritScope lock(&acm_crit_sect_);
1140 if (!HaveValidEncoder("DisableOpusDtx")) {
1141 return -1;
1142 }
1143 return encoder_stack_->SetDtx(false) ? 0 : -1;
1144}
1145
Danil Chapovalovb6021232018-06-19 13:26:36 +02001146absl::optional<uint32_t> AudioCodingModuleImpl::PlayoutTimestamp() {
kwibergc13ded52016-06-17 06:00:45 -07001147 return receiver_.GetPlayoutTimestamp();
1148}
1149
henrik.lundinb3f1c5d2016-08-22 15:39:53 -07001150int AudioCodingModuleImpl::FilteredCurrentDelayMs() const {
1151 return receiver_.FilteredCurrentDelayMs();
1152}
1153
Henrik Lundinabbff892017-11-29 09:14:04 +01001154int AudioCodingModuleImpl::TargetDelayMs() const {
1155 return receiver_.TargetDelayMs();
1156}
1157
kwibergc13ded52016-06-17 06:00:45 -07001158bool AudioCodingModuleImpl::HaveValidEncoder(const char* caller_name) const {
1159 if (!encoder_stack_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001160 RTC_LOG(LS_ERROR) << caller_name << " failed: No send codec is registered.";
kwibergc13ded52016-06-17 06:00:45 -07001161 return false;
1162 }
1163 return true;
1164}
1165
1166int AudioCodingModuleImpl::UnregisterReceiveCodec(uint8_t payload_type) {
1167 return receiver_.RemoveCodec(payload_type);
1168}
1169
1170int AudioCodingModuleImpl::EnableNack(size_t max_nack_list_size) {
1171 return receiver_.EnableNack(max_nack_list_size);
1172}
1173
1174void AudioCodingModuleImpl::DisableNack() {
1175 receiver_.DisableNack();
1176}
1177
1178std::vector<uint16_t> AudioCodingModuleImpl::GetNackList(
1179 int64_t round_trip_time_ms) const {
1180 return receiver_.GetNackList(round_trip_time_ms);
1181}
1182
kwibergc13ded52016-06-17 06:00:45 -07001183void AudioCodingModuleImpl::GetDecodingCallStatistics(
Yves Gerey665174f2018-06-19 15:03:05 +02001184 AudioDecodingCallStats* call_stats) const {
kwibergc13ded52016-06-17 06:00:45 -07001185 receiver_.GetDecodingCallStatistics(call_stats);
1186}
1187
ivoce1198e02017-09-08 08:13:19 -07001188ANAStats AudioCodingModuleImpl::GetANAStats() const {
1189 rtc::CritScope lock(&acm_crit_sect_);
1190 if (encoder_stack_)
1191 return encoder_stack_->GetANAStats();
1192 // If no encoder is set, return default stats.
1193 return ANAStats();
1194}
1195
kwibergc13ded52016-06-17 06:00:45 -07001196} // namespace
1197
Karl Wiberg5817d3d2018-04-06 10:06:42 +02001198AudioCodingModule::Config::Config(
1199 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory)
1200 : neteq_config(),
1201 clock(Clock::GetRealTimeClock()),
1202 decoder_factory(decoder_factory) {
kwiberg36a43882016-08-29 05:33:32 -07001203 // Post-decode VAD is disabled by default in NetEq, however, Audio
1204 // Conference Mixer relies on VAD decisions and fails without them.
1205 neteq_config.enable_post_decode_vad = true;
1206}
1207
1208AudioCodingModule::Config::Config(const Config&) = default;
1209AudioCodingModule::Config::~Config() = default;
1210
Henrik Lundin64dad832015-05-11 12:44:23 +02001211AudioCodingModule* AudioCodingModule::Create(const Config& config) {
kwibergc13ded52016-06-17 06:00:45 -07001212 return new AudioCodingModuleImpl(config);
turaj@webrtc.org7959e162013-09-12 18:30:26 +00001213}
1214
turaj@webrtc.org7959e162013-09-12 18:30:26 +00001215int AudioCodingModule::NumberOfCodecs() {
kwibergfce4a942015-10-27 11:40:24 -07001216 return static_cast<int>(acm2::RentACodec::NumberOfCodecs());
turaj@webrtc.org7959e162013-09-12 18:30:26 +00001217}
1218
turaj@webrtc.org7959e162013-09-12 18:30:26 +00001219int AudioCodingModule::Codec(int list_id, CodecInst* codec) {
kwibergfce4a942015-10-27 11:40:24 -07001220 auto codec_id = acm2::RentACodec::CodecIdFromIndex(list_id);
1221 if (!codec_id)
1222 return -1;
1223 auto ci = acm2::RentACodec::CodecInstById(*codec_id);
1224 if (!ci)
1225 return -1;
1226 *codec = *ci;
1227 return 0;
turaj@webrtc.org7959e162013-09-12 18:30:26 +00001228}
1229
turaj@webrtc.org7959e162013-09-12 18:30:26 +00001230int AudioCodingModule::Codec(const char* payload_name,
1231 CodecInst* codec,
1232 int sampling_freq_hz,
Peter Kasting69558702016-01-12 16:26:35 -08001233 size_t channels) {
Danil Chapovalovb6021232018-06-19 13:26:36 +02001234 absl::optional<CodecInst> ci = acm2::RentACodec::CodecInstByParams(
turaj@webrtc.org6d5d2482013-10-06 04:47:28 +00001235 payload_name, sampling_freq_hz, channels);
kwibergfce4a942015-10-27 11:40:24 -07001236 if (ci) {
1237 *codec = *ci;
1238 return 0;
1239 } else {
1240 // We couldn't find a matching codec, so set the parameters to unacceptable
turaj@webrtc.org7959e162013-09-12 18:30:26 +00001241 // values and return.
1242 codec->plname[0] = '\0';
1243 codec->pltype = -1;
1244 codec->pacsize = 0;
1245 codec->rate = 0;
1246 codec->plfreq = 0;
1247 return -1;
1248 }
turaj@webrtc.org7959e162013-09-12 18:30:26 +00001249}
1250
turaj@webrtc.org7959e162013-09-12 18:30:26 +00001251int AudioCodingModule::Codec(const char* payload_name,
1252 int sampling_freq_hz,
Peter Kasting69558702016-01-12 16:26:35 -08001253 size_t channels) {
Danil Chapovalovb6021232018-06-19 13:26:36 +02001254 absl::optional<acm2::RentACodec::CodecId> ci =
Karl Wibergbe579832015-11-10 22:34:18 +01001255 acm2::RentACodec::CodecIdByParams(payload_name, sampling_freq_hz,
1256 channels);
kwibergfce4a942015-10-27 11:40:24 -07001257 if (!ci)
1258 return -1;
Danil Chapovalovb6021232018-06-19 13:26:36 +02001259 absl::optional<int> i = acm2::RentACodec::CodecIndexFromId(*ci);
kwibergfce4a942015-10-27 11:40:24 -07001260 return i ? *i : -1;
turaj@webrtc.org7959e162013-09-12 18:30:26 +00001261}
1262
turaj@webrtc.org7959e162013-09-12 18:30:26 +00001263} // namespace webrtc