blob: 334c0e0b38b68bcf005d4e2162af1ea5d0d6ffea [file] [log] [blame]
turaj@webrtc.org7959e162013-09-12 18:30:26 +00001/*
2 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "modules/audio_coding/include/audio_coding_module.h"
turaj@webrtc.org7959e162013-09-12 18:30:26 +000012
Yves Gerey988cc082018-10-23 12:03:01 +020013#include <assert.h>
Jonathan Yu36344a02017-07-30 01:55:34 -070014#include <algorithm>
Yves Gerey988cc082018-10-23 12:03:01 +020015#include <cstdint>
Jonathan Yu36344a02017-07-30 01:55:34 -070016
Niels Möller2edab4c2018-10-22 09:48:08 +020017#include "absl/strings/match.h"
Yves Gerey988cc082018-10-23 12:03:01 +020018#include "api/array_view.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020019#include "modules/audio_coding/acm2/acm_receiver.h"
20#include "modules/audio_coding/acm2/acm_resampler.h"
21#include "modules/audio_coding/acm2/codec_manager.h"
22#include "modules/audio_coding/acm2/rent_a_codec.h"
Fredrik Solenbergbbf21a32018-04-12 22:44:09 +020023#include "modules/include/module_common_types.h"
Yves Gerey988cc082018-10-23 12:03:01 +020024#include "modules/include/module_common_types_public.h"
25#include "rtc_base/buffer.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020026#include "rtc_base/checks.h"
Yves Gerey988cc082018-10-23 12:03:01 +020027#include "rtc_base/criticalsection.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020028#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010029#include "rtc_base/numerics/safe_conversions.h"
Yves Gerey988cc082018-10-23 12:03:01 +020030#include "rtc_base/thread_annotations.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020031#include "system_wrappers/include/metrics.h"
turaj@webrtc.org7959e162013-09-12 18:30:26 +000032
33namespace webrtc {
34
kwibergc13ded52016-06-17 06:00:45 -070035namespace {
36
37struct EncoderFactory {
38 AudioEncoder* external_speech_encoder = nullptr;
39 acm2::CodecManager codec_manager;
40 acm2::RentACodec rent_a_codec;
41};
42
43class AudioCodingModuleImpl final : public AudioCodingModule {
44 public:
45 explicit AudioCodingModuleImpl(const AudioCodingModule::Config& config);
46 ~AudioCodingModuleImpl() override;
47
48 /////////////////////////////////////////
49 // Sender
50 //
51
52 // Can be called multiple times for Codec, CNG, RED.
53 int RegisterSendCodec(const CodecInst& send_codec) override;
54
55 void RegisterExternalSendCodec(
56 AudioEncoder* external_speech_encoder) override;
57
kwiberg24c7c122016-09-28 11:57:10 -070058 void ModifyEncoder(rtc::FunctionView<void(std::unique_ptr<AudioEncoder>*)>
59 modifier) override;
kwibergc13ded52016-06-17 06:00:45 -070060
61 // Get current send codec.
Danil Chapovalovb6021232018-06-19 13:26:36 +020062 absl::optional<CodecInst> SendCodec() const override;
kwibergc13ded52016-06-17 06:00:45 -070063
kwibergc13ded52016-06-17 06:00:45 -070064 // Sets the bitrate to the specified value in bits/sec. In case the codec does
65 // not support the requested value it will choose an appropriate value
66 // instead.
67 void SetBitRate(int bitrate_bps) override;
68
69 // Register a transport callback which will be
70 // called to deliver the encoded buffers.
71 int RegisterTransportCallback(AudioPacketizationCallback* transport) override;
72
73 // Add 10 ms of raw (PCM) audio data to the encoder.
74 int Add10MsData(const AudioFrame& audio_frame) override;
75
76 /////////////////////////////////////////
77 // (RED) Redundant Coding
78 //
79
80 // Configure RED status i.e. on/off.
81 int SetREDStatus(bool enable_red) override;
82
83 // Get RED status.
84 bool REDStatus() const override;
85
86 /////////////////////////////////////////
87 // (FEC) Forward Error Correction (codec internal)
88 //
89
90 // Configure FEC status i.e. on/off.
91 int SetCodecFEC(bool enabled_codec_fec) override;
92
93 // Get FEC status.
94 bool CodecFEC() const override;
95
96 // Set target packet loss rate
97 int SetPacketLossRate(int loss_rate) override;
98
99 /////////////////////////////////////////
100 // (VAD) Voice Activity Detection
101 // and
102 // (CNG) Comfort Noise Generation
103 //
104
105 int SetVAD(bool enable_dtx = true,
106 bool enable_vad = false,
107 ACMVADMode mode = VADNormal) override;
108
109 int VAD(bool* dtx_enabled,
110 bool* vad_enabled,
111 ACMVADMode* mode) const override;
112
113 int RegisterVADCallback(ACMVADCallback* vad_callback) override;
114
115 /////////////////////////////////////////
116 // Receiver
117 //
118
119 // Initialize receiver, resets codec database etc.
120 int InitializeReceiver() override;
121
122 // Get current receive frequency.
123 int ReceiveFrequency() const override;
124
125 // Get current playout frequency.
126 int PlayoutFrequency() const override;
127
kwiberg1c07c702017-03-27 07:15:49 -0700128 void SetReceiveCodecs(const std::map<int, SdpAudioFormat>& codecs) override;
129
kwiberg5adaf732016-10-04 09:33:27 -0700130 bool RegisterReceiveCodec(int rtp_payload_type,
131 const SdpAudioFormat& audio_format) override;
132
kwibergc13ded52016-06-17 06:00:45 -0700133 int RegisterReceiveCodec(const CodecInst& receive_codec) override;
134 int RegisterReceiveCodec(
135 const CodecInst& receive_codec,
kwiberg24c7c122016-09-28 11:57:10 -0700136 rtc::FunctionView<std::unique_ptr<AudioDecoder>()> isac_factory) override;
kwibergc13ded52016-06-17 06:00:45 -0700137
138 int RegisterExternalReceiveCodec(int rtp_payload_type,
139 AudioDecoder* external_decoder,
140 int sample_rate_hz,
141 int num_channels,
142 const std::string& name) override;
143
144 // Get current received codec.
145 int ReceiveCodec(CodecInst* current_codec) const override;
146
Danil Chapovalovb6021232018-06-19 13:26:36 +0200147 absl::optional<SdpAudioFormat> ReceiveFormat() const override;
ossue280cde2016-10-12 11:04:10 -0700148
kwibergc13ded52016-06-17 06:00:45 -0700149 // Incoming packet from network parsed and ready for decode.
150 int IncomingPacket(const uint8_t* incoming_payload,
151 const size_t payload_length,
152 const WebRtcRTPHeader& rtp_info) override;
153
kwibergc13ded52016-06-17 06:00:45 -0700154 // Minimum playout delay.
155 int SetMinimumPlayoutDelay(int time_ms) override;
156
157 // Maximum playout delay.
158 int SetMaximumPlayoutDelay(int time_ms) override;
159
Danil Chapovalovb6021232018-06-19 13:26:36 +0200160 absl::optional<uint32_t> PlayoutTimestamp() override;
kwibergc13ded52016-06-17 06:00:45 -0700161
henrik.lundinb3f1c5d2016-08-22 15:39:53 -0700162 int FilteredCurrentDelayMs() const override;
163
Henrik Lundinabbff892017-11-29 09:14:04 +0100164 int TargetDelayMs() const override;
165
kwibergc13ded52016-06-17 06:00:45 -0700166 // Get 10 milliseconds of raw audio data to play out, and
167 // automatic resample to the requested frequency if > 0.
168 int PlayoutData10Ms(int desired_freq_hz,
169 AudioFrame* audio_frame,
170 bool* muted) override;
kwibergc13ded52016-06-17 06:00:45 -0700171
172 /////////////////////////////////////////
173 // Statistics
174 //
175
176 int GetNetworkStatistics(NetworkStatistics* statistics) override;
177
kwibergc13ded52016-06-17 06:00:45 -0700178 // If current send codec is Opus, informs it about the maximum playback rate
179 // the receiver will render.
180 int SetOpusMaxPlaybackRate(int frequency_hz) override;
181
182 int EnableOpusDtx() override;
183
184 int DisableOpusDtx() override;
185
186 int UnregisterReceiveCodec(uint8_t payload_type) override;
187
188 int EnableNack(size_t max_nack_list_size) override;
189
190 void DisableNack() override;
191
192 std::vector<uint16_t> GetNackList(int64_t round_trip_time_ms) const override;
193
194 void GetDecodingCallStatistics(AudioDecodingCallStats* stats) const override;
195
ivoce1198e02017-09-08 08:13:19 -0700196 ANAStats GetANAStats() const override;
197
kwibergc13ded52016-06-17 06:00:45 -0700198 private:
199 struct InputData {
200 uint32_t input_timestamp;
201 const int16_t* audio;
202 size_t length_per_channel;
203 size_t audio_channel;
204 // If a re-mix is required (up or down), this buffer will store a re-mixed
205 // version of the input.
206 int16_t buffer[WEBRTC_10MS_PCM_AUDIO];
207 };
208
209 // This member class writes values to the named UMA histogram, but only if
210 // the value has changed since the last time (and always for the first call).
211 class ChangeLogger {
212 public:
213 explicit ChangeLogger(const std::string& histogram_name)
214 : histogram_name_(histogram_name) {}
215 // Logs the new value if it is different from the last logged value, or if
216 // this is the first call.
217 void MaybeLog(int value);
218
219 private:
220 int last_value_ = 0;
221 int first_time_ = true;
222 const std::string histogram_name_;
223 };
224
225 int RegisterReceiveCodecUnlocked(
226 const CodecInst& codec,
kwiberg24c7c122016-09-28 11:57:10 -0700227 rtc::FunctionView<std::unique_ptr<AudioDecoder>()> isac_factory)
danilchap56359be2017-09-07 07:53:45 -0700228 RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700229
230 int Add10MsDataInternal(const AudioFrame& audio_frame, InputData* input_data)
danilchap56359be2017-09-07 07:53:45 -0700231 RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700232 int Encode(const InputData& input_data)
danilchap56359be2017-09-07 07:53:45 -0700233 RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700234
danilchap56359be2017-09-07 07:53:45 -0700235 int InitializeReceiverSafe() RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700236
237 bool HaveValidEncoder(const char* caller_name) const
danilchap56359be2017-09-07 07:53:45 -0700238 RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700239
240 // Preprocessing of input audio, including resampling and down-mixing if
241 // required, before pushing audio into encoder's buffer.
242 //
243 // in_frame: input audio-frame
244 // ptr_out: pointer to output audio_frame. If no preprocessing is required
245 // |ptr_out| will be pointing to |in_frame|, otherwise pointing to
246 // |preprocess_frame_|.
247 //
248 // Return value:
249 // -1: if encountering an error.
250 // 0: otherwise.
251 int PreprocessToAddData(const AudioFrame& in_frame,
252 const AudioFrame** ptr_out)
danilchap56359be2017-09-07 07:53:45 -0700253 RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700254
255 // Change required states after starting to receive the codec corresponding
256 // to |index|.
257 int UpdateUponReceivingCodec(int index);
258
259 rtc::CriticalSection acm_crit_sect_;
danilchap56359be2017-09-07 07:53:45 -0700260 rtc::Buffer encode_buffer_ RTC_GUARDED_BY(acm_crit_sect_);
danilchap56359be2017-09-07 07:53:45 -0700261 uint32_t expected_codec_ts_ RTC_GUARDED_BY(acm_crit_sect_);
262 uint32_t expected_in_ts_ RTC_GUARDED_BY(acm_crit_sect_);
263 acm2::ACMResampler resampler_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700264 acm2::AcmReceiver receiver_; // AcmReceiver has it's own internal lock.
danilchap56359be2017-09-07 07:53:45 -0700265 ChangeLogger bitrate_logger_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700266
danilchap56359be2017-09-07 07:53:45 -0700267 std::unique_ptr<EncoderFactory> encoder_factory_
268 RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700269
270 // Current encoder stack, either obtained from
271 // encoder_factory_->rent_a_codec.RentEncoderStack or provided by a call to
272 // RegisterEncoder.
danilchap56359be2017-09-07 07:53:45 -0700273 std::unique_ptr<AudioEncoder> encoder_stack_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700274
danilchap56359be2017-09-07 07:53:45 -0700275 std::unique_ptr<AudioDecoder> isac_decoder_16k_
276 RTC_GUARDED_BY(acm_crit_sect_);
277 std::unique_ptr<AudioDecoder> isac_decoder_32k_
278 RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700279
280 // This is to keep track of CN instances where we can send DTMFs.
danilchap56359be2017-09-07 07:53:45 -0700281 uint8_t previous_pltype_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700282
danilchap56359be2017-09-07 07:53:45 -0700283 bool receiver_initialized_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700284
danilchap56359be2017-09-07 07:53:45 -0700285 AudioFrame preprocess_frame_ RTC_GUARDED_BY(acm_crit_sect_);
286 bool first_10ms_data_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700287
danilchap56359be2017-09-07 07:53:45 -0700288 bool first_frame_ RTC_GUARDED_BY(acm_crit_sect_);
289 uint32_t last_timestamp_ RTC_GUARDED_BY(acm_crit_sect_);
290 uint32_t last_rtp_timestamp_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700291
292 rtc::CriticalSection callback_crit_sect_;
293 AudioPacketizationCallback* packetization_callback_
danilchap56359be2017-09-07 07:53:45 -0700294 RTC_GUARDED_BY(callback_crit_sect_);
295 ACMVADCallback* vad_callback_ RTC_GUARDED_BY(callback_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700296
297 int codec_histogram_bins_log_[static_cast<size_t>(
298 AudioEncoder::CodecType::kMaxLoggedAudioCodecTypes)];
299 int number_of_consecutive_empty_packets_;
300};
301
302// Adds a codec usage sample to the histogram.
303void UpdateCodecTypeHistogram(size_t codec_type) {
304 RTC_HISTOGRAM_ENUMERATION(
305 "WebRTC.Audio.Encoder.CodecType", static_cast<int>(codec_type),
306 static_cast<int>(
307 webrtc::AudioEncoder::CodecType::kMaxLoggedAudioCodecTypes));
308}
309
kwibergc13ded52016-06-17 06:00:45 -0700310// Stereo-to-mono can be used as in-place.
311int DownMix(const AudioFrame& frame,
312 size_t length_out_buff,
313 int16_t* out_buff) {
yujo36b1a5f2017-06-12 12:45:32 -0700314 RTC_DCHECK_EQ(frame.num_channels_, 2);
315 RTC_DCHECK_GE(length_out_buff, frame.samples_per_channel_);
316
317 if (!frame.muted()) {
318 const int16_t* frame_data = frame.data();
319 for (size_t n = 0; n < frame.samples_per_channel_; ++n) {
Yves Gerey665174f2018-06-19 15:03:05 +0200320 out_buff[n] =
321 static_cast<int16_t>((static_cast<int32_t>(frame_data[2 * n]) +
322 static_cast<int32_t>(frame_data[2 * n + 1])) >>
323 1);
yujo36b1a5f2017-06-12 12:45:32 -0700324 }
325 } else {
Jonathan Yu36344a02017-07-30 01:55:34 -0700326 std::fill(out_buff, out_buff + frame.samples_per_channel_, 0);
kwibergc13ded52016-06-17 06:00:45 -0700327 }
kwibergc13ded52016-06-17 06:00:45 -0700328 return 0;
329}
330
331// Mono-to-stereo can be used as in-place.
332int UpMix(const AudioFrame& frame, size_t length_out_buff, int16_t* out_buff) {
yujo36b1a5f2017-06-12 12:45:32 -0700333 RTC_DCHECK_EQ(frame.num_channels_, 1);
334 RTC_DCHECK_GE(length_out_buff, 2 * frame.samples_per_channel_);
335
336 if (!frame.muted()) {
337 const int16_t* frame_data = frame.data();
338 for (size_t n = frame.samples_per_channel_; n != 0; --n) {
339 size_t i = n - 1;
340 int16_t sample = frame_data[i];
341 out_buff[2 * i + 1] = sample;
342 out_buff[2 * i] = sample;
343 }
344 } else {
Jonathan Yu36344a02017-07-30 01:55:34 -0700345 std::fill(out_buff, out_buff + frame.samples_per_channel_ * 2, 0);
kwibergc13ded52016-06-17 06:00:45 -0700346 }
347 return 0;
348}
349
350void ConvertEncodedInfoToFragmentationHeader(
351 const AudioEncoder::EncodedInfo& info,
352 RTPFragmentationHeader* frag) {
353 if (info.redundant.empty()) {
354 frag->fragmentationVectorSize = 0;
355 return;
356 }
357
358 frag->VerifyAndAllocateFragmentationHeader(
359 static_cast<uint16_t>(info.redundant.size()));
360 frag->fragmentationVectorSize = static_cast<uint16_t>(info.redundant.size());
361 size_t offset = 0;
362 for (size_t i = 0; i < info.redundant.size(); ++i) {
363 frag->fragmentationOffset[i] = offset;
364 offset += info.redundant[i].encoded_bytes;
365 frag->fragmentationLength[i] = info.redundant[i].encoded_bytes;
kwibergd3edd772017-03-01 18:52:48 -0800366 frag->fragmentationTimeDiff[i] = rtc::dchecked_cast<uint16_t>(
kwibergc13ded52016-06-17 06:00:45 -0700367 info.encoded_timestamp - info.redundant[i].encoded_timestamp);
368 frag->fragmentationPlType[i] = info.redundant[i].payload_type;
369 }
370}
371
372// Wraps a raw AudioEncoder pointer. The idea is that you can put one of these
373// in a unique_ptr, to protect the contained raw pointer from being deleted
374// when the unique_ptr expires. (This is of course a bad idea in general, but
375// backwards compatibility.)
376class RawAudioEncoderWrapper final : public AudioEncoder {
377 public:
378 RawAudioEncoderWrapper(AudioEncoder* enc) : enc_(enc) {}
379 int SampleRateHz() const override { return enc_->SampleRateHz(); }
380 size_t NumChannels() const override { return enc_->NumChannels(); }
381 int RtpTimestampRateHz() const override { return enc_->RtpTimestampRateHz(); }
382 size_t Num10MsFramesInNextPacket() const override {
383 return enc_->Num10MsFramesInNextPacket();
384 }
385 size_t Max10MsFramesInAPacket() const override {
386 return enc_->Max10MsFramesInAPacket();
387 }
388 int GetTargetBitrate() const override { return enc_->GetTargetBitrate(); }
389 EncodedInfo EncodeImpl(uint32_t rtp_timestamp,
390 rtc::ArrayView<const int16_t> audio,
391 rtc::Buffer* encoded) override {
392 return enc_->Encode(rtp_timestamp, audio, encoded);
393 }
394 void Reset() override { return enc_->Reset(); }
395 bool SetFec(bool enable) override { return enc_->SetFec(enable); }
396 bool SetDtx(bool enable) override { return enc_->SetDtx(enable); }
397 bool SetApplication(Application application) override {
398 return enc_->SetApplication(application);
399 }
400 void SetMaxPlaybackRate(int frequency_hz) override {
401 return enc_->SetMaxPlaybackRate(frequency_hz);
402 }
kwibergc13ded52016-06-17 06:00:45 -0700403
404 private:
405 AudioEncoder* enc_;
406};
407
408// Return false on error.
409bool CreateSpeechEncoderIfNecessary(EncoderFactory* ef) {
410 auto* sp = ef->codec_manager.GetStackParams();
411 if (sp->speech_encoder) {
412 // Do nothing; we already have a speech encoder.
413 } else if (ef->codec_manager.GetCodecInst()) {
414 RTC_DCHECK(!ef->external_speech_encoder);
415 // We have no speech encoder, but we have a specification for making one.
416 std::unique_ptr<AudioEncoder> enc =
417 ef->rent_a_codec.RentEncoder(*ef->codec_manager.GetCodecInst());
418 if (!enc)
419 return false; // Encoder spec was bad.
420 sp->speech_encoder = std::move(enc);
421 } else if (ef->external_speech_encoder) {
422 RTC_DCHECK(!ef->codec_manager.GetCodecInst());
423 // We have an external speech encoder.
424 sp->speech_encoder = std::unique_ptr<AudioEncoder>(
425 new RawAudioEncoderWrapper(ef->external_speech_encoder));
426 }
427 return true;
428}
429
430void AudioCodingModuleImpl::ChangeLogger::MaybeLog(int value) {
431 if (value != last_value_ || first_time_) {
432 first_time_ = false;
433 last_value_ = value;
434 RTC_HISTOGRAM_COUNTS_SPARSE_100(histogram_name_, value);
435 }
436}
437
438AudioCodingModuleImpl::AudioCodingModuleImpl(
439 const AudioCodingModule::Config& config)
solenbergc7b4a452017-09-28 07:37:11 -0700440 : expected_codec_ts_(0xD87F3F9F),
kwibergc13ded52016-06-17 06:00:45 -0700441 expected_in_ts_(0xD87F3F9F),
442 receiver_(config),
443 bitrate_logger_("WebRTC.Audio.TargetBitrateInKbps"),
444 encoder_factory_(new EncoderFactory),
445 encoder_stack_(nullptr),
446 previous_pltype_(255),
447 receiver_initialized_(false),
448 first_10ms_data_(false),
449 first_frame_(true),
450 packetization_callback_(NULL),
451 vad_callback_(NULL),
452 codec_histogram_bins_log_(),
453 number_of_consecutive_empty_packets_(0) {
454 if (InitializeReceiverSafe() < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100455 RTC_LOG(LS_ERROR) << "Cannot initialize receiver";
kwibergc13ded52016-06-17 06:00:45 -0700456 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100457 RTC_LOG(LS_INFO) << "Created";
kwibergc13ded52016-06-17 06:00:45 -0700458}
459
460AudioCodingModuleImpl::~AudioCodingModuleImpl() = default;
461
462int32_t AudioCodingModuleImpl::Encode(const InputData& input_data) {
463 AudioEncoder::EncodedInfo encoded_info;
464 uint8_t previous_pltype;
465
466 // Check if there is an encoder before.
467 if (!HaveValidEncoder("Process"))
468 return -1;
469
Yves Gerey665174f2018-06-19 15:03:05 +0200470 if (!first_frame_) {
deadbeeffcada902016-08-24 12:45:13 -0700471 RTC_DCHECK(IsNewerTimestamp(input_data.input_timestamp, last_timestamp_))
ossu63fb95a2016-07-06 09:34:22 -0700472 << "Time should not move backwards";
473 }
474
kwibergc13ded52016-06-17 06:00:45 -0700475 // Scale the timestamp to the codec's RTP timestamp rate.
476 uint32_t rtp_timestamp =
477 first_frame_ ? input_data.input_timestamp
478 : last_rtp_timestamp_ +
479 rtc::CheckedDivExact(
480 input_data.input_timestamp - last_timestamp_,
481 static_cast<uint32_t>(rtc::CheckedDivExact(
482 encoder_stack_->SampleRateHz(),
483 encoder_stack_->RtpTimestampRateHz())));
484 last_timestamp_ = input_data.input_timestamp;
485 last_rtp_timestamp_ = rtp_timestamp;
486 first_frame_ = false;
487
488 // Clear the buffer before reuse - encoded data will get appended.
489 encode_buffer_.Clear();
490 encoded_info = encoder_stack_->Encode(
Yves Gerey665174f2018-06-19 15:03:05 +0200491 rtp_timestamp,
492 rtc::ArrayView<const int16_t>(
493 input_data.audio,
494 input_data.audio_channel * input_data.length_per_channel),
kwibergc13ded52016-06-17 06:00:45 -0700495 &encode_buffer_);
496
497 bitrate_logger_.MaybeLog(encoder_stack_->GetTargetBitrate() / 1000);
498 if (encode_buffer_.size() == 0 && !encoded_info.send_even_if_empty) {
499 // Not enough data.
500 return 0;
501 }
502 previous_pltype = previous_pltype_; // Read it while we have the critsect.
503
504 // Log codec type to histogram once every 500 packets.
505 if (encoded_info.encoded_bytes == 0) {
506 ++number_of_consecutive_empty_packets_;
507 } else {
508 size_t codec_type = static_cast<size_t>(encoded_info.encoder_type);
509 codec_histogram_bins_log_[codec_type] +=
510 number_of_consecutive_empty_packets_ + 1;
511 number_of_consecutive_empty_packets_ = 0;
512 if (codec_histogram_bins_log_[codec_type] >= 500) {
513 codec_histogram_bins_log_[codec_type] -= 500;
514 UpdateCodecTypeHistogram(codec_type);
515 }
516 }
517
518 RTPFragmentationHeader my_fragmentation;
519 ConvertEncodedInfoToFragmentationHeader(encoded_info, &my_fragmentation);
520 FrameType frame_type;
521 if (encode_buffer_.size() == 0 && encoded_info.send_even_if_empty) {
522 frame_type = kEmptyFrame;
523 encoded_info.payload_type = previous_pltype;
524 } else {
kwibergaf476c72016-11-28 15:21:39 -0800525 RTC_DCHECK_GT(encode_buffer_.size(), 0);
kwibergc13ded52016-06-17 06:00:45 -0700526 frame_type = encoded_info.speech ? kAudioFrameSpeech : kAudioFrameCN;
527 }
528
529 {
530 rtc::CritScope lock(&callback_crit_sect_);
531 if (packetization_callback_) {
532 packetization_callback_->SendData(
533 frame_type, encoded_info.payload_type, encoded_info.encoded_timestamp,
534 encode_buffer_.data(), encode_buffer_.size(),
535 my_fragmentation.fragmentationVectorSize > 0 ? &my_fragmentation
536 : nullptr);
537 }
538
539 if (vad_callback_) {
540 // Callback with VAD decision.
541 vad_callback_->InFrameType(frame_type);
542 }
543 }
544 previous_pltype_ = encoded_info.payload_type;
545 return static_cast<int32_t>(encode_buffer_.size());
546}
547
548/////////////////////////////////////////
549// Sender
550//
551
552// Can be called multiple times for Codec, CNG, RED.
553int AudioCodingModuleImpl::RegisterSendCodec(const CodecInst& send_codec) {
554 rtc::CritScope lock(&acm_crit_sect_);
555 if (!encoder_factory_->codec_manager.RegisterEncoder(send_codec)) {
556 return -1;
557 }
558 if (encoder_factory_->codec_manager.GetCodecInst()) {
559 encoder_factory_->external_speech_encoder = nullptr;
560 }
561 if (!CreateSpeechEncoderIfNecessary(encoder_factory_.get())) {
562 return -1;
563 }
564 auto* sp = encoder_factory_->codec_manager.GetStackParams();
565 if (sp->speech_encoder)
566 encoder_stack_ = encoder_factory_->rent_a_codec.RentEncoderStack(sp);
567 return 0;
568}
569
570void AudioCodingModuleImpl::RegisterExternalSendCodec(
571 AudioEncoder* external_speech_encoder) {
572 rtc::CritScope lock(&acm_crit_sect_);
573 encoder_factory_->codec_manager.UnsetCodecInst();
574 encoder_factory_->external_speech_encoder = external_speech_encoder;
575 RTC_CHECK(CreateSpeechEncoderIfNecessary(encoder_factory_.get()));
576 auto* sp = encoder_factory_->codec_manager.GetStackParams();
577 RTC_CHECK(sp->speech_encoder);
578 encoder_stack_ = encoder_factory_->rent_a_codec.RentEncoderStack(sp);
579}
580
581void AudioCodingModuleImpl::ModifyEncoder(
kwiberg24c7c122016-09-28 11:57:10 -0700582 rtc::FunctionView<void(std::unique_ptr<AudioEncoder>*)> modifier) {
kwibergc13ded52016-06-17 06:00:45 -0700583 rtc::CritScope lock(&acm_crit_sect_);
584
585 // Wipe the encoder factory, so that everything that relies on it will fail.
586 // We don't want the complexity of supporting swapping back and forth.
587 if (encoder_factory_) {
588 encoder_factory_.reset();
589 RTC_CHECK(!encoder_stack_); // Ensure we hadn't started using the factory.
590 }
591
592 modifier(&encoder_stack_);
593}
594
595// Get current send codec.
Danil Chapovalovb6021232018-06-19 13:26:36 +0200596absl::optional<CodecInst> AudioCodingModuleImpl::SendCodec() const {
kwibergc13ded52016-06-17 06:00:45 -0700597 rtc::CritScope lock(&acm_crit_sect_);
598 if (encoder_factory_) {
599 auto* ci = encoder_factory_->codec_manager.GetCodecInst();
600 if (ci) {
Oskar Sundbom12ab00b2017-11-16 15:31:38 +0100601 return *ci;
kwibergc13ded52016-06-17 06:00:45 -0700602 }
603 CreateSpeechEncoderIfNecessary(encoder_factory_.get());
604 const std::unique_ptr<AudioEncoder>& enc =
605 encoder_factory_->codec_manager.GetStackParams()->speech_encoder;
606 if (enc) {
Oskar Sundbom12ab00b2017-11-16 15:31:38 +0100607 return acm2::CodecManager::ForgeCodecInst(enc.get());
kwibergc13ded52016-06-17 06:00:45 -0700608 }
Danil Chapovalovb6021232018-06-19 13:26:36 +0200609 return absl::nullopt;
kwibergc13ded52016-06-17 06:00:45 -0700610 } else {
611 return encoder_stack_
Danil Chapovalovb6021232018-06-19 13:26:36 +0200612 ? absl::optional<CodecInst>(
kwibergc13ded52016-06-17 06:00:45 -0700613 acm2::CodecManager::ForgeCodecInst(encoder_stack_.get()))
Danil Chapovalovb6021232018-06-19 13:26:36 +0200614 : absl::nullopt;
kwibergc13ded52016-06-17 06:00:45 -0700615 }
616}
617
kwibergc13ded52016-06-17 06:00:45 -0700618void AudioCodingModuleImpl::SetBitRate(int bitrate_bps) {
619 rtc::CritScope lock(&acm_crit_sect_);
620 if (encoder_stack_) {
Danil Chapovalovb6021232018-06-19 13:26:36 +0200621 encoder_stack_->OnReceivedUplinkBandwidth(bitrate_bps, absl::nullopt);
kwibergc13ded52016-06-17 06:00:45 -0700622 }
623}
624
625// Register a transport callback which will be called to deliver
626// the encoded buffers.
627int AudioCodingModuleImpl::RegisterTransportCallback(
628 AudioPacketizationCallback* transport) {
629 rtc::CritScope lock(&callback_crit_sect_);
630 packetization_callback_ = transport;
631 return 0;
632}
633
634// Add 10MS of raw (PCM) audio data to the encoder.
635int AudioCodingModuleImpl::Add10MsData(const AudioFrame& audio_frame) {
636 InputData input_data;
637 rtc::CritScope lock(&acm_crit_sect_);
638 int r = Add10MsDataInternal(audio_frame, &input_data);
639 return r < 0 ? r : Encode(input_data);
640}
641
642int AudioCodingModuleImpl::Add10MsDataInternal(const AudioFrame& audio_frame,
643 InputData* input_data) {
644 if (audio_frame.samples_per_channel_ == 0) {
645 assert(false);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100646 RTC_LOG(LS_ERROR) << "Cannot Add 10 ms audio, payload length is zero";
kwibergc13ded52016-06-17 06:00:45 -0700647 return -1;
648 }
649
650 if (audio_frame.sample_rate_hz_ > 48000) {
651 assert(false);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100652 RTC_LOG(LS_ERROR) << "Cannot Add 10 ms audio, input frequency not valid";
kwibergc13ded52016-06-17 06:00:45 -0700653 return -1;
654 }
655
656 // If the length and frequency matches. We currently just support raw PCM.
657 if (static_cast<size_t>(audio_frame.sample_rate_hz_ / 100) !=
658 audio_frame.samples_per_channel_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100659 RTC_LOG(LS_ERROR)
Alex Loiko300ec8c2017-05-30 17:23:28 +0200660 << "Cannot Add 10 ms audio, input frequency and length doesn't match";
kwibergc13ded52016-06-17 06:00:45 -0700661 return -1;
662 }
663
664 if (audio_frame.num_channels_ != 1 && audio_frame.num_channels_ != 2) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100665 RTC_LOG(LS_ERROR) << "Cannot Add 10 ms audio, invalid number of channels.";
kwibergc13ded52016-06-17 06:00:45 -0700666 return -1;
667 }
668
669 // Do we have a codec registered?
670 if (!HaveValidEncoder("Add10MsData")) {
671 return -1;
672 }
673
674 const AudioFrame* ptr_frame;
675 // Perform a resampling, also down-mix if it is required and can be
676 // performed before resampling (a down mix prior to resampling will take
677 // place if both primary and secondary encoders are mono and input is in
678 // stereo).
679 if (PreprocessToAddData(audio_frame, &ptr_frame) < 0) {
680 return -1;
681 }
682
683 // Check whether we need an up-mix or down-mix?
684 const size_t current_num_channels = encoder_stack_->NumChannels();
685 const bool same_num_channels =
686 ptr_frame->num_channels_ == current_num_channels;
687
688 if (!same_num_channels) {
689 if (ptr_frame->num_channels_ == 1) {
690 if (UpMix(*ptr_frame, WEBRTC_10MS_PCM_AUDIO, input_data->buffer) < 0)
691 return -1;
692 } else {
693 if (DownMix(*ptr_frame, WEBRTC_10MS_PCM_AUDIO, input_data->buffer) < 0)
694 return -1;
695 }
696 }
697
698 // When adding data to encoders this pointer is pointing to an audio buffer
699 // with correct number of channels.
yujo36b1a5f2017-06-12 12:45:32 -0700700 const int16_t* ptr_audio = ptr_frame->data();
kwibergc13ded52016-06-17 06:00:45 -0700701
702 // For pushing data to primary, point the |ptr_audio| to correct buffer.
703 if (!same_num_channels)
704 ptr_audio = input_data->buffer;
705
yujo36b1a5f2017-06-12 12:45:32 -0700706 // TODO(yujo): Skip encode of muted frames.
kwibergc13ded52016-06-17 06:00:45 -0700707 input_data->input_timestamp = ptr_frame->timestamp_;
708 input_data->audio = ptr_audio;
709 input_data->length_per_channel = ptr_frame->samples_per_channel_;
710 input_data->audio_channel = current_num_channels;
711
712 return 0;
713}
714
715// Perform a resampling and down-mix if required. We down-mix only if
716// encoder is mono and input is stereo. In case of dual-streaming, both
717// encoders has to be mono for down-mix to take place.
718// |*ptr_out| will point to the pre-processed audio-frame. If no pre-processing
719// is required, |*ptr_out| points to |in_frame|.
yujo36b1a5f2017-06-12 12:45:32 -0700720// TODO(yujo): Make this more efficient for muted frames.
kwibergc13ded52016-06-17 06:00:45 -0700721int AudioCodingModuleImpl::PreprocessToAddData(const AudioFrame& in_frame,
722 const AudioFrame** ptr_out) {
723 const bool resample =
724 in_frame.sample_rate_hz_ != encoder_stack_->SampleRateHz();
725
726 // This variable is true if primary codec and secondary codec (if exists)
727 // are both mono and input is stereo.
728 // TODO(henrik.lundin): This condition should probably be
729 // in_frame.num_channels_ > encoder_stack_->NumChannels()
730 const bool down_mix =
731 in_frame.num_channels_ == 2 && encoder_stack_->NumChannels() == 1;
732
733 if (!first_10ms_data_) {
734 expected_in_ts_ = in_frame.timestamp_;
735 expected_codec_ts_ = in_frame.timestamp_;
736 first_10ms_data_ = true;
737 } else if (in_frame.timestamp_ != expected_in_ts_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100738 RTC_LOG(LS_WARNING) << "Unexpected input timestamp: " << in_frame.timestamp_
739 << ", expected: " << expected_in_ts_;
kwibergc13ded52016-06-17 06:00:45 -0700740 expected_codec_ts_ +=
741 (in_frame.timestamp_ - expected_in_ts_) *
742 static_cast<uint32_t>(
743 static_cast<double>(encoder_stack_->SampleRateHz()) /
744 static_cast<double>(in_frame.sample_rate_hz_));
745 expected_in_ts_ = in_frame.timestamp_;
746 }
747
kwibergc13ded52016-06-17 06:00:45 -0700748 if (!down_mix && !resample) {
749 // No pre-processing is required.
ossu63fb95a2016-07-06 09:34:22 -0700750 if (expected_in_ts_ == expected_codec_ts_) {
751 // If we've never resampled, we can use the input frame as-is
752 *ptr_out = &in_frame;
753 } else {
754 // Otherwise we'll need to alter the timestamp. Since in_frame is const,
755 // we'll have to make a copy of it.
756 preprocess_frame_.CopyFrom(in_frame);
757 preprocess_frame_.timestamp_ = expected_codec_ts_;
758 *ptr_out = &preprocess_frame_;
759 }
760
kwibergc13ded52016-06-17 06:00:45 -0700761 expected_in_ts_ += static_cast<uint32_t>(in_frame.samples_per_channel_);
762 expected_codec_ts_ += static_cast<uint32_t>(in_frame.samples_per_channel_);
kwibergc13ded52016-06-17 06:00:45 -0700763 return 0;
764 }
765
766 *ptr_out = &preprocess_frame_;
767 preprocess_frame_.num_channels_ = in_frame.num_channels_;
768 int16_t audio[WEBRTC_10MS_PCM_AUDIO];
yujo36b1a5f2017-06-12 12:45:32 -0700769 const int16_t* src_ptr_audio = in_frame.data();
kwibergc13ded52016-06-17 06:00:45 -0700770 if (down_mix) {
771 // If a resampling is required the output of a down-mix is written into a
772 // local buffer, otherwise, it will be written to the output frame.
Yves Gerey665174f2018-06-19 15:03:05 +0200773 int16_t* dest_ptr_audio =
774 resample ? audio : preprocess_frame_.mutable_data();
kwibergc13ded52016-06-17 06:00:45 -0700775 if (DownMix(in_frame, WEBRTC_10MS_PCM_AUDIO, dest_ptr_audio) < 0)
776 return -1;
777 preprocess_frame_.num_channels_ = 1;
778 // Set the input of the resampler is the down-mixed signal.
779 src_ptr_audio = audio;
780 }
781
782 preprocess_frame_.timestamp_ = expected_codec_ts_;
783 preprocess_frame_.samples_per_channel_ = in_frame.samples_per_channel_;
784 preprocess_frame_.sample_rate_hz_ = in_frame.sample_rate_hz_;
785 // If it is required, we have to do a resampling.
786 if (resample) {
787 // The result of the resampler is written to output frame.
yujo36b1a5f2017-06-12 12:45:32 -0700788 int16_t* dest_ptr_audio = preprocess_frame_.mutable_data();
kwibergc13ded52016-06-17 06:00:45 -0700789
790 int samples_per_channel = resampler_.Resample10Msec(
791 src_ptr_audio, in_frame.sample_rate_hz_, encoder_stack_->SampleRateHz(),
792 preprocess_frame_.num_channels_, AudioFrame::kMaxDataSizeSamples,
793 dest_ptr_audio);
794
795 if (samples_per_channel < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100796 RTC_LOG(LS_ERROR) << "Cannot add 10 ms audio, resampling failed";
kwibergc13ded52016-06-17 06:00:45 -0700797 return -1;
798 }
799 preprocess_frame_.samples_per_channel_ =
800 static_cast<size_t>(samples_per_channel);
801 preprocess_frame_.sample_rate_hz_ = encoder_stack_->SampleRateHz();
802 }
803
804 expected_codec_ts_ +=
805 static_cast<uint32_t>(preprocess_frame_.samples_per_channel_);
806 expected_in_ts_ += static_cast<uint32_t>(in_frame.samples_per_channel_);
807
808 return 0;
809}
810
811/////////////////////////////////////////
812// (RED) Redundant Coding
813//
814
815bool AudioCodingModuleImpl::REDStatus() const {
816 rtc::CritScope lock(&acm_crit_sect_);
817 return encoder_factory_->codec_manager.GetStackParams()->use_red;
818}
819
820// Configure RED status i.e on/off.
821int AudioCodingModuleImpl::SetREDStatus(bool enable_red) {
822#ifdef WEBRTC_CODEC_RED
823 rtc::CritScope lock(&acm_crit_sect_);
824 CreateSpeechEncoderIfNecessary(encoder_factory_.get());
825 if (!encoder_factory_->codec_manager.SetCopyRed(enable_red)) {
826 return -1;
827 }
828 auto* sp = encoder_factory_->codec_manager.GetStackParams();
829 if (sp->speech_encoder)
830 encoder_stack_ = encoder_factory_->rent_a_codec.RentEncoderStack(sp);
831 return 0;
832#else
Mirko Bonadei675513b2017-11-09 11:09:25 +0100833 RTC_LOG(LS_WARNING) << " WEBRTC_CODEC_RED is undefined";
kwibergc13ded52016-06-17 06:00:45 -0700834 return -1;
835#endif
836}
837
838/////////////////////////////////////////
839// (FEC) Forward Error Correction (codec internal)
840//
841
842bool AudioCodingModuleImpl::CodecFEC() const {
843 rtc::CritScope lock(&acm_crit_sect_);
844 return encoder_factory_->codec_manager.GetStackParams()->use_codec_fec;
845}
846
847int AudioCodingModuleImpl::SetCodecFEC(bool enable_codec_fec) {
848 rtc::CritScope lock(&acm_crit_sect_);
849 CreateSpeechEncoderIfNecessary(encoder_factory_.get());
850 if (!encoder_factory_->codec_manager.SetCodecFEC(enable_codec_fec)) {
851 return -1;
852 }
853 auto* sp = encoder_factory_->codec_manager.GetStackParams();
854 if (sp->speech_encoder)
855 encoder_stack_ = encoder_factory_->rent_a_codec.RentEncoderStack(sp);
856 if (enable_codec_fec) {
857 return sp->use_codec_fec ? 0 : -1;
858 } else {
859 RTC_DCHECK(!sp->use_codec_fec);
860 return 0;
861 }
862}
863
864int AudioCodingModuleImpl::SetPacketLossRate(int loss_rate) {
865 rtc::CritScope lock(&acm_crit_sect_);
866 if (HaveValidEncoder("SetPacketLossRate")) {
minyue4b9a2cb2016-11-30 06:49:59 -0800867 encoder_stack_->OnReceivedUplinkPacketLossFraction(loss_rate / 100.0);
kwibergc13ded52016-06-17 06:00:45 -0700868 }
869 return 0;
870}
871
872/////////////////////////////////////////
873// (VAD) Voice Activity Detection
874//
875int AudioCodingModuleImpl::SetVAD(bool enable_dtx,
876 bool enable_vad,
877 ACMVADMode mode) {
878 // Note: |enable_vad| is not used; VAD is enabled based on the DTX setting.
879 RTC_DCHECK_EQ(enable_dtx, enable_vad);
880 rtc::CritScope lock(&acm_crit_sect_);
881 CreateSpeechEncoderIfNecessary(encoder_factory_.get());
882 if (!encoder_factory_->codec_manager.SetVAD(enable_dtx, mode)) {
883 return -1;
884 }
885 auto* sp = encoder_factory_->codec_manager.GetStackParams();
886 if (sp->speech_encoder)
887 encoder_stack_ = encoder_factory_->rent_a_codec.RentEncoderStack(sp);
888 return 0;
889}
890
891// Get VAD/DTX settings.
Yves Gerey665174f2018-06-19 15:03:05 +0200892int AudioCodingModuleImpl::VAD(bool* dtx_enabled,
893 bool* vad_enabled,
kwibergc13ded52016-06-17 06:00:45 -0700894 ACMVADMode* mode) const {
895 rtc::CritScope lock(&acm_crit_sect_);
896 const auto* sp = encoder_factory_->codec_manager.GetStackParams();
897 *dtx_enabled = *vad_enabled = sp->use_cng;
898 *mode = sp->vad_mode;
899 return 0;
900}
901
902/////////////////////////////////////////
903// Receiver
904//
905
906int AudioCodingModuleImpl::InitializeReceiver() {
907 rtc::CritScope lock(&acm_crit_sect_);
908 return InitializeReceiverSafe();
909}
910
911// Initialize receiver, resets codec database etc.
912int AudioCodingModuleImpl::InitializeReceiverSafe() {
913 // If the receiver is already initialized then we want to destroy any
914 // existing decoders. After a call to this function, we should have a clean
915 // start-up.
kwiberg6b19b562016-09-20 04:02:25 -0700916 if (receiver_initialized_)
917 receiver_.RemoveAllCodecs();
kwibergc13ded52016-06-17 06:00:45 -0700918 receiver_.ResetInitialDelay();
919 receiver_.SetMinimumDelay(0);
920 receiver_.SetMaximumDelay(0);
921 receiver_.FlushBuffers();
922
kwibergc13ded52016-06-17 06:00:45 -0700923 receiver_initialized_ = true;
924 return 0;
925}
926
927// Get current receive frequency.
928int AudioCodingModuleImpl::ReceiveFrequency() const {
929 const auto last_packet_sample_rate = receiver_.last_packet_sample_rate_hz();
930 return last_packet_sample_rate ? *last_packet_sample_rate
931 : receiver_.last_output_sample_rate_hz();
932}
933
934// Get current playout frequency.
935int AudioCodingModuleImpl::PlayoutFrequency() const {
kwibergc13ded52016-06-17 06:00:45 -0700936 return receiver_.last_output_sample_rate_hz();
937}
938
kwiberg1c07c702017-03-27 07:15:49 -0700939void AudioCodingModuleImpl::SetReceiveCodecs(
940 const std::map<int, SdpAudioFormat>& codecs) {
941 rtc::CritScope lock(&acm_crit_sect_);
942 receiver_.SetCodecs(codecs);
943}
944
kwiberg5adaf732016-10-04 09:33:27 -0700945bool AudioCodingModuleImpl::RegisterReceiveCodec(
946 int rtp_payload_type,
947 const SdpAudioFormat& audio_format) {
948 rtc::CritScope lock(&acm_crit_sect_);
949 RTC_DCHECK(receiver_initialized_);
950
951 if (!acm2::RentACodec::IsPayloadTypeValid(rtp_payload_type)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100952 RTC_LOG_F(LS_ERROR) << "Invalid payload-type " << rtp_payload_type
953 << " for decoder.";
kwiberg5adaf732016-10-04 09:33:27 -0700954 return false;
955 }
956
957 return receiver_.AddCodec(rtp_payload_type, audio_format);
958}
959
kwibergc13ded52016-06-17 06:00:45 -0700960int AudioCodingModuleImpl::RegisterReceiveCodec(const CodecInst& codec) {
961 rtc::CritScope lock(&acm_crit_sect_);
962 auto* ef = encoder_factory_.get();
963 return RegisterReceiveCodecUnlocked(
964 codec, [&] { return ef->rent_a_codec.RentIsacDecoder(codec.plfreq); });
965}
966
967int AudioCodingModuleImpl::RegisterReceiveCodec(
968 const CodecInst& codec,
kwiberg24c7c122016-09-28 11:57:10 -0700969 rtc::FunctionView<std::unique_ptr<AudioDecoder>()> isac_factory) {
kwibergc13ded52016-06-17 06:00:45 -0700970 rtc::CritScope lock(&acm_crit_sect_);
971 return RegisterReceiveCodecUnlocked(codec, isac_factory);
972}
973
974int AudioCodingModuleImpl::RegisterReceiveCodecUnlocked(
975 const CodecInst& codec,
kwiberg24c7c122016-09-28 11:57:10 -0700976 rtc::FunctionView<std::unique_ptr<AudioDecoder>()> isac_factory) {
kwibergc13ded52016-06-17 06:00:45 -0700977 RTC_DCHECK(receiver_initialized_);
978 if (codec.channels > 2) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100979 RTC_LOG_F(LS_ERROR) << "Unsupported number of channels: " << codec.channels;
kwibergc13ded52016-06-17 06:00:45 -0700980 return -1;
981 }
982
983 auto codec_id = acm2::RentACodec::CodecIdByParams(codec.plname, codec.plfreq,
984 codec.channels);
985 if (!codec_id) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100986 RTC_LOG_F(LS_ERROR)
987 << "Wrong codec params to be registered as receive codec";
kwibergc13ded52016-06-17 06:00:45 -0700988 return -1;
989 }
990 auto codec_index = acm2::RentACodec::CodecIndexFromId(*codec_id);
991 RTC_CHECK(codec_index) << "Invalid codec ID: " << static_cast<int>(*codec_id);
992
993 // Check if the payload-type is valid.
994 if (!acm2::RentACodec::IsPayloadTypeValid(codec.pltype)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100995 RTC_LOG_F(LS_ERROR) << "Invalid payload type " << codec.pltype << " for "
996 << codec.plname;
kwibergc13ded52016-06-17 06:00:45 -0700997 return -1;
998 }
999
1000 AudioDecoder* isac_decoder = nullptr;
Niels Möller2edab4c2018-10-22 09:48:08 +02001001 if (absl::EqualsIgnoreCase(codec.plname, "isac")) {
kwibergc13ded52016-06-17 06:00:45 -07001002 std::unique_ptr<AudioDecoder>& saved_isac_decoder =
1003 codec.plfreq == 16000 ? isac_decoder_16k_ : isac_decoder_32k_;
1004 if (!saved_isac_decoder) {
1005 saved_isac_decoder = isac_factory();
1006 }
1007 isac_decoder = saved_isac_decoder.get();
1008 }
1009 return receiver_.AddCodec(*codec_index, codec.pltype, codec.channels,
1010 codec.plfreq, isac_decoder, codec.plname);
1011}
1012
1013int AudioCodingModuleImpl::RegisterExternalReceiveCodec(
1014 int rtp_payload_type,
1015 AudioDecoder* external_decoder,
1016 int sample_rate_hz,
1017 int num_channels,
1018 const std::string& name) {
1019 rtc::CritScope lock(&acm_crit_sect_);
1020 RTC_DCHECK(receiver_initialized_);
1021 if (num_channels > 2 || num_channels < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001022 RTC_LOG_F(LS_ERROR) << "Unsupported number of channels: " << num_channels;
kwibergc13ded52016-06-17 06:00:45 -07001023 return -1;
1024 }
1025
1026 // Check if the payload-type is valid.
1027 if (!acm2::RentACodec::IsPayloadTypeValid(rtp_payload_type)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001028 RTC_LOG_F(LS_ERROR) << "Invalid payload-type " << rtp_payload_type
1029 << " for external decoder.";
kwibergc13ded52016-06-17 06:00:45 -07001030 return -1;
1031 }
1032
1033 return receiver_.AddCodec(-1 /* external */, rtp_payload_type, num_channels,
1034 sample_rate_hz, external_decoder, name);
1035}
1036
1037// Get current received codec.
1038int AudioCodingModuleImpl::ReceiveCodec(CodecInst* current_codec) const {
1039 rtc::CritScope lock(&acm_crit_sect_);
1040 return receiver_.LastAudioCodec(current_codec);
1041}
1042
Danil Chapovalovb6021232018-06-19 13:26:36 +02001043absl::optional<SdpAudioFormat> AudioCodingModuleImpl::ReceiveFormat() const {
ossue280cde2016-10-12 11:04:10 -07001044 rtc::CritScope lock(&acm_crit_sect_);
1045 return receiver_.LastAudioFormat();
1046}
1047
kwibergc13ded52016-06-17 06:00:45 -07001048// Incoming packet from network parsed and ready for decode.
1049int AudioCodingModuleImpl::IncomingPacket(const uint8_t* incoming_payload,
1050 const size_t payload_length,
1051 const WebRtcRTPHeader& rtp_header) {
henrik.lundinb8c55b12017-05-10 07:38:01 -07001052 RTC_DCHECK_EQ(payload_length == 0, incoming_payload == nullptr);
kwibergc13ded52016-06-17 06:00:45 -07001053 return receiver_.InsertPacket(
1054 rtp_header,
1055 rtc::ArrayView<const uint8_t>(incoming_payload, payload_length));
1056}
1057
1058// Minimum playout delay (Used for lip-sync).
1059int AudioCodingModuleImpl::SetMinimumPlayoutDelay(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_.SetMinimumDelay(time_ms);
1065}
1066
1067int AudioCodingModuleImpl::SetMaximumPlayoutDelay(int time_ms) {
1068 if ((time_ms < 0) || (time_ms > 10000)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001069 RTC_LOG(LS_ERROR) << "Delay must be in the range of 0-10000 milliseconds.";
kwibergc13ded52016-06-17 06:00:45 -07001070 return -1;
1071 }
1072 return receiver_.SetMaximumDelay(time_ms);
1073}
1074
1075// Get 10 milliseconds of raw audio data to play out.
1076// Automatic resample to the requested frequency.
1077int AudioCodingModuleImpl::PlayoutData10Ms(int desired_freq_hz,
1078 AudioFrame* audio_frame,
1079 bool* muted) {
1080 // GetAudio always returns 10 ms, at the requested sample rate.
1081 if (receiver_.GetAudio(desired_freq_hz, audio_frame, muted) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001082 RTC_LOG(LS_ERROR) << "PlayoutData failed, RecOut Failed";
kwibergc13ded52016-06-17 06:00:45 -07001083 return -1;
1084 }
kwibergc13ded52016-06-17 06:00:45 -07001085 return 0;
1086}
1087
kwibergc13ded52016-06-17 06:00:45 -07001088/////////////////////////////////////////
1089// Statistics
1090//
1091
1092// TODO(turajs) change the return value to void. Also change the corresponding
1093// NetEq function.
1094int AudioCodingModuleImpl::GetNetworkStatistics(NetworkStatistics* statistics) {
1095 receiver_.GetNetworkStatistics(statistics);
1096 return 0;
1097}
1098
1099int AudioCodingModuleImpl::RegisterVADCallback(ACMVADCallback* vad_callback) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001100 RTC_LOG(LS_VERBOSE) << "RegisterVADCallback()";
kwibergc13ded52016-06-17 06:00:45 -07001101 rtc::CritScope lock(&callback_crit_sect_);
1102 vad_callback_ = vad_callback;
1103 return 0;
1104}
1105
kwibergc13ded52016-06-17 06:00:45 -07001106// Informs Opus encoder of the maximum playback rate the receiver will render.
1107int AudioCodingModuleImpl::SetOpusMaxPlaybackRate(int frequency_hz) {
1108 rtc::CritScope lock(&acm_crit_sect_);
1109 if (!HaveValidEncoder("SetOpusMaxPlaybackRate")) {
1110 return -1;
1111 }
1112 encoder_stack_->SetMaxPlaybackRate(frequency_hz);
1113 return 0;
1114}
1115
1116int AudioCodingModuleImpl::EnableOpusDtx() {
1117 rtc::CritScope lock(&acm_crit_sect_);
1118 if (!HaveValidEncoder("EnableOpusDtx")) {
1119 return -1;
1120 }
1121 return encoder_stack_->SetDtx(true) ? 0 : -1;
1122}
1123
1124int AudioCodingModuleImpl::DisableOpusDtx() {
1125 rtc::CritScope lock(&acm_crit_sect_);
1126 if (!HaveValidEncoder("DisableOpusDtx")) {
1127 return -1;
1128 }
1129 return encoder_stack_->SetDtx(false) ? 0 : -1;
1130}
1131
Danil Chapovalovb6021232018-06-19 13:26:36 +02001132absl::optional<uint32_t> AudioCodingModuleImpl::PlayoutTimestamp() {
kwibergc13ded52016-06-17 06:00:45 -07001133 return receiver_.GetPlayoutTimestamp();
1134}
1135
henrik.lundinb3f1c5d2016-08-22 15:39:53 -07001136int AudioCodingModuleImpl::FilteredCurrentDelayMs() const {
1137 return receiver_.FilteredCurrentDelayMs();
1138}
1139
Henrik Lundinabbff892017-11-29 09:14:04 +01001140int AudioCodingModuleImpl::TargetDelayMs() const {
1141 return receiver_.TargetDelayMs();
1142}
1143
kwibergc13ded52016-06-17 06:00:45 -07001144bool AudioCodingModuleImpl::HaveValidEncoder(const char* caller_name) const {
1145 if (!encoder_stack_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001146 RTC_LOG(LS_ERROR) << caller_name << " failed: No send codec is registered.";
kwibergc13ded52016-06-17 06:00:45 -07001147 return false;
1148 }
1149 return true;
1150}
1151
1152int AudioCodingModuleImpl::UnregisterReceiveCodec(uint8_t payload_type) {
1153 return receiver_.RemoveCodec(payload_type);
1154}
1155
1156int AudioCodingModuleImpl::EnableNack(size_t max_nack_list_size) {
1157 return receiver_.EnableNack(max_nack_list_size);
1158}
1159
1160void AudioCodingModuleImpl::DisableNack() {
1161 receiver_.DisableNack();
1162}
1163
1164std::vector<uint16_t> AudioCodingModuleImpl::GetNackList(
1165 int64_t round_trip_time_ms) const {
1166 return receiver_.GetNackList(round_trip_time_ms);
1167}
1168
kwibergc13ded52016-06-17 06:00:45 -07001169void AudioCodingModuleImpl::GetDecodingCallStatistics(
Yves Gerey665174f2018-06-19 15:03:05 +02001170 AudioDecodingCallStats* call_stats) const {
kwibergc13ded52016-06-17 06:00:45 -07001171 receiver_.GetDecodingCallStatistics(call_stats);
1172}
1173
ivoce1198e02017-09-08 08:13:19 -07001174ANAStats AudioCodingModuleImpl::GetANAStats() const {
1175 rtc::CritScope lock(&acm_crit_sect_);
1176 if (encoder_stack_)
1177 return encoder_stack_->GetANAStats();
1178 // If no encoder is set, return default stats.
1179 return ANAStats();
1180}
1181
kwibergc13ded52016-06-17 06:00:45 -07001182} // namespace
1183
Karl Wiberg5817d3d2018-04-06 10:06:42 +02001184AudioCodingModule::Config::Config(
1185 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory)
1186 : neteq_config(),
1187 clock(Clock::GetRealTimeClock()),
1188 decoder_factory(decoder_factory) {
kwiberg36a43882016-08-29 05:33:32 -07001189 // Post-decode VAD is disabled by default in NetEq, however, Audio
1190 // Conference Mixer relies on VAD decisions and fails without them.
1191 neteq_config.enable_post_decode_vad = true;
1192}
1193
1194AudioCodingModule::Config::Config(const Config&) = default;
1195AudioCodingModule::Config::~Config() = default;
1196
Henrik Lundin64dad832015-05-11 12:44:23 +02001197AudioCodingModule* AudioCodingModule::Create(const Config& config) {
kwibergc13ded52016-06-17 06:00:45 -07001198 return new AudioCodingModuleImpl(config);
turaj@webrtc.org7959e162013-09-12 18:30:26 +00001199}
1200
turaj@webrtc.org7959e162013-09-12 18:30:26 +00001201int AudioCodingModule::NumberOfCodecs() {
kwibergfce4a942015-10-27 11:40:24 -07001202 return static_cast<int>(acm2::RentACodec::NumberOfCodecs());
turaj@webrtc.org7959e162013-09-12 18:30:26 +00001203}
1204
turaj@webrtc.org7959e162013-09-12 18:30:26 +00001205int AudioCodingModule::Codec(int list_id, CodecInst* codec) {
kwibergfce4a942015-10-27 11:40:24 -07001206 auto codec_id = acm2::RentACodec::CodecIdFromIndex(list_id);
1207 if (!codec_id)
1208 return -1;
1209 auto ci = acm2::RentACodec::CodecInstById(*codec_id);
1210 if (!ci)
1211 return -1;
1212 *codec = *ci;
1213 return 0;
turaj@webrtc.org7959e162013-09-12 18:30:26 +00001214}
1215
turaj@webrtc.org7959e162013-09-12 18:30:26 +00001216int AudioCodingModule::Codec(const char* payload_name,
1217 CodecInst* codec,
1218 int sampling_freq_hz,
Peter Kasting69558702016-01-12 16:26:35 -08001219 size_t channels) {
Danil Chapovalovb6021232018-06-19 13:26:36 +02001220 absl::optional<CodecInst> ci = acm2::RentACodec::CodecInstByParams(
turaj@webrtc.org6d5d2482013-10-06 04:47:28 +00001221 payload_name, sampling_freq_hz, channels);
kwibergfce4a942015-10-27 11:40:24 -07001222 if (ci) {
1223 *codec = *ci;
1224 return 0;
1225 } else {
1226 // We couldn't find a matching codec, so set the parameters to unacceptable
turaj@webrtc.org7959e162013-09-12 18:30:26 +00001227 // values and return.
1228 codec->plname[0] = '\0';
1229 codec->pltype = -1;
1230 codec->pacsize = 0;
1231 codec->rate = 0;
1232 codec->plfreq = 0;
1233 return -1;
1234 }
turaj@webrtc.org7959e162013-09-12 18:30:26 +00001235}
1236
turaj@webrtc.org7959e162013-09-12 18:30:26 +00001237int AudioCodingModule::Codec(const char* payload_name,
1238 int sampling_freq_hz,
Peter Kasting69558702016-01-12 16:26:35 -08001239 size_t channels) {
Danil Chapovalovb6021232018-06-19 13:26:36 +02001240 absl::optional<acm2::RentACodec::CodecId> ci =
Karl Wibergbe579832015-11-10 22:34:18 +01001241 acm2::RentACodec::CodecIdByParams(payload_name, sampling_freq_hz,
1242 channels);
kwibergfce4a942015-10-27 11:40:24 -07001243 if (!ci)
1244 return -1;
Danil Chapovalovb6021232018-06-19 13:26:36 +02001245 absl::optional<int> i = acm2::RentACodec::CodecIndexFromId(*ci);
kwibergfce4a942015-10-27 11:40:24 -07001246 return i ? *i : -1;
turaj@webrtc.org7959e162013-09-12 18:30:26 +00001247}
1248
turaj@webrtc.org7959e162013-09-12 18:30:26 +00001249} // namespace webrtc