blob: 4545810b56c100d17c8051788970d11c7b53edb2 [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
kwiberg24c7c122016-09-28 11:57:10 -070053 void QueryEncoder(
54 rtc::FunctionView<void(const AudioEncoder*)> query) override;
ivoc85228d62016-07-27 04:53:47 -070055
kwibergc13ded52016-06-17 06:00:45 -070056 // Get current send codec.
57 rtc::Optional<CodecInst> SendCodec() const override;
58
59 // Get current send frequency.
60 int SendFrequency() const override;
61
62 // Sets the bitrate to the specified value in bits/sec. In case the codec does
63 // not support the requested value it will choose an appropriate value
64 // instead.
65 void SetBitRate(int bitrate_bps) override;
66
67 // Register a transport callback which will be
68 // called to deliver the encoded buffers.
69 int RegisterTransportCallback(AudioPacketizationCallback* transport) override;
70
71 // Add 10 ms of raw (PCM) audio data to the encoder.
72 int Add10MsData(const AudioFrame& audio_frame) override;
73
74 /////////////////////////////////////////
75 // (RED) Redundant Coding
76 //
77
78 // Configure RED status i.e. on/off.
79 int SetREDStatus(bool enable_red) override;
80
81 // Get RED status.
82 bool REDStatus() const override;
83
84 /////////////////////////////////////////
85 // (FEC) Forward Error Correction (codec internal)
86 //
87
88 // Configure FEC status i.e. on/off.
89 int SetCodecFEC(bool enabled_codec_fec) override;
90
91 // Get FEC status.
92 bool CodecFEC() const override;
93
94 // Set target packet loss rate
95 int SetPacketLossRate(int loss_rate) override;
96
97 /////////////////////////////////////////
98 // (VAD) Voice Activity Detection
99 // and
100 // (CNG) Comfort Noise Generation
101 //
102
103 int SetVAD(bool enable_dtx = true,
104 bool enable_vad = false,
105 ACMVADMode mode = VADNormal) override;
106
107 int VAD(bool* dtx_enabled,
108 bool* vad_enabled,
109 ACMVADMode* mode) const override;
110
111 int RegisterVADCallback(ACMVADCallback* vad_callback) override;
112
113 /////////////////////////////////////////
114 // Receiver
115 //
116
117 // Initialize receiver, resets codec database etc.
118 int InitializeReceiver() override;
119
120 // Get current receive frequency.
121 int ReceiveFrequency() const override;
122
123 // Get current playout frequency.
124 int PlayoutFrequency() const override;
125
kwiberg1c07c702017-03-27 07:15:49 -0700126 void SetReceiveCodecs(const std::map<int, SdpAudioFormat>& codecs) override;
127
kwiberg5adaf732016-10-04 09:33:27 -0700128 bool RegisterReceiveCodec(int rtp_payload_type,
129 const SdpAudioFormat& audio_format) override;
130
kwibergc13ded52016-06-17 06:00:45 -0700131 int RegisterReceiveCodec(const CodecInst& receive_codec) override;
132 int RegisterReceiveCodec(
133 const CodecInst& receive_codec,
kwiberg24c7c122016-09-28 11:57:10 -0700134 rtc::FunctionView<std::unique_ptr<AudioDecoder>()> isac_factory) override;
kwibergc13ded52016-06-17 06:00:45 -0700135
136 int RegisterExternalReceiveCodec(int rtp_payload_type,
137 AudioDecoder* external_decoder,
138 int sample_rate_hz,
139 int num_channels,
140 const std::string& name) override;
141
142 // Get current received codec.
143 int ReceiveCodec(CodecInst* current_codec) const override;
144
ossue280cde2016-10-12 11:04:10 -0700145 rtc::Optional<SdpAudioFormat> ReceiveFormat() const override;
146
kwibergc13ded52016-06-17 06:00:45 -0700147 // Incoming packet from network parsed and ready for decode.
148 int IncomingPacket(const uint8_t* incoming_payload,
149 const size_t payload_length,
150 const WebRtcRTPHeader& rtp_info) override;
151
kwibergc13ded52016-06-17 06:00:45 -0700152 // Minimum playout delay.
153 int SetMinimumPlayoutDelay(int time_ms) override;
154
155 // Maximum playout delay.
156 int SetMaximumPlayoutDelay(int time_ms) override;
157
158 // Smallest latency NetEq will maintain.
159 int LeastRequiredDelayMs() const override;
160
161 RTC_DEPRECATED int32_t PlayoutTimestamp(uint32_t* timestamp) override;
162
163 rtc::Optional<uint32_t> PlayoutTimestamp() override;
164
henrik.lundinb3f1c5d2016-08-22 15:39:53 -0700165 int FilteredCurrentDelayMs() const override;
166
Henrik Lundinabbff892017-11-29 09:14:04 +0100167 int TargetDelayMs() const override;
168
kwibergc13ded52016-06-17 06:00:45 -0700169 // Get 10 milliseconds of raw audio data to play out, and
170 // automatic resample to the requested frequency if > 0.
171 int PlayoutData10Ms(int desired_freq_hz,
172 AudioFrame* audio_frame,
173 bool* muted) override;
174 int PlayoutData10Ms(int desired_freq_hz, AudioFrame* audio_frame) override;
175
176 /////////////////////////////////////////
177 // Statistics
178 //
179
180 int GetNetworkStatistics(NetworkStatistics* statistics) override;
181
182 int SetOpusApplication(OpusApplicationMode application) override;
183
184 // If current send codec is Opus, informs it about the maximum playback rate
185 // the receiver will render.
186 int SetOpusMaxPlaybackRate(int frequency_hz) override;
187
188 int EnableOpusDtx() override;
189
190 int DisableOpusDtx() override;
191
192 int UnregisterReceiveCodec(uint8_t payload_type) override;
193
194 int EnableNack(size_t max_nack_list_size) override;
195
196 void DisableNack() override;
197
198 std::vector<uint16_t> GetNackList(int64_t round_trip_time_ms) const override;
199
200 void GetDecodingCallStatistics(AudioDecodingCallStats* stats) const override;
201
ivoce1198e02017-09-08 08:13:19 -0700202 ANAStats GetANAStats() const override;
203
kwibergc13ded52016-06-17 06:00:45 -0700204 private:
205 struct InputData {
206 uint32_t input_timestamp;
207 const int16_t* audio;
208 size_t length_per_channel;
209 size_t audio_channel;
210 // If a re-mix is required (up or down), this buffer will store a re-mixed
211 // version of the input.
212 int16_t buffer[WEBRTC_10MS_PCM_AUDIO];
213 };
214
215 // This member class writes values to the named UMA histogram, but only if
216 // the value has changed since the last time (and always for the first call).
217 class ChangeLogger {
218 public:
219 explicit ChangeLogger(const std::string& histogram_name)
220 : histogram_name_(histogram_name) {}
221 // Logs the new value if it is different from the last logged value, or if
222 // this is the first call.
223 void MaybeLog(int value);
224
225 private:
226 int last_value_ = 0;
227 int first_time_ = true;
228 const std::string histogram_name_;
229 };
230
231 int RegisterReceiveCodecUnlocked(
232 const CodecInst& codec,
kwiberg24c7c122016-09-28 11:57:10 -0700233 rtc::FunctionView<std::unique_ptr<AudioDecoder>()> isac_factory)
danilchap56359be2017-09-07 07:53:45 -0700234 RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700235
236 int Add10MsDataInternal(const AudioFrame& audio_frame, InputData* input_data)
danilchap56359be2017-09-07 07:53:45 -0700237 RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700238 int Encode(const InputData& input_data)
danilchap56359be2017-09-07 07:53:45 -0700239 RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700240
danilchap56359be2017-09-07 07:53:45 -0700241 int InitializeReceiverSafe() RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700242
243 bool HaveValidEncoder(const char* caller_name) const
danilchap56359be2017-09-07 07:53:45 -0700244 RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700245
246 // Preprocessing of input audio, including resampling and down-mixing if
247 // required, before pushing audio into encoder's buffer.
248 //
249 // in_frame: input audio-frame
250 // ptr_out: pointer to output audio_frame. If no preprocessing is required
251 // |ptr_out| will be pointing to |in_frame|, otherwise pointing to
252 // |preprocess_frame_|.
253 //
254 // Return value:
255 // -1: if encountering an error.
256 // 0: otherwise.
257 int PreprocessToAddData(const AudioFrame& in_frame,
258 const AudioFrame** ptr_out)
danilchap56359be2017-09-07 07:53:45 -0700259 RTC_EXCLUSIVE_LOCKS_REQUIRED(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700260
261 // Change required states after starting to receive the codec corresponding
262 // to |index|.
263 int UpdateUponReceivingCodec(int index);
264
265 rtc::CriticalSection acm_crit_sect_;
danilchap56359be2017-09-07 07:53:45 -0700266 rtc::Buffer encode_buffer_ RTC_GUARDED_BY(acm_crit_sect_);
danilchap56359be2017-09-07 07:53:45 -0700267 uint32_t expected_codec_ts_ RTC_GUARDED_BY(acm_crit_sect_);
268 uint32_t expected_in_ts_ RTC_GUARDED_BY(acm_crit_sect_);
269 acm2::ACMResampler resampler_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700270 acm2::AcmReceiver receiver_; // AcmReceiver has it's own internal lock.
danilchap56359be2017-09-07 07:53:45 -0700271 ChangeLogger bitrate_logger_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700272
danilchap56359be2017-09-07 07:53:45 -0700273 std::unique_ptr<EncoderFactory> encoder_factory_
274 RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700275
276 // Current encoder stack, either obtained from
277 // encoder_factory_->rent_a_codec.RentEncoderStack or provided by a call to
278 // RegisterEncoder.
danilchap56359be2017-09-07 07:53:45 -0700279 std::unique_ptr<AudioEncoder> encoder_stack_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700280
danilchap56359be2017-09-07 07:53:45 -0700281 std::unique_ptr<AudioDecoder> isac_decoder_16k_
282 RTC_GUARDED_BY(acm_crit_sect_);
283 std::unique_ptr<AudioDecoder> isac_decoder_32k_
284 RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700285
286 // This is to keep track of CN instances where we can send DTMFs.
danilchap56359be2017-09-07 07:53:45 -0700287 uint8_t previous_pltype_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700288
danilchap56359be2017-09-07 07:53:45 -0700289 bool receiver_initialized_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700290
danilchap56359be2017-09-07 07:53:45 -0700291 AudioFrame preprocess_frame_ RTC_GUARDED_BY(acm_crit_sect_);
292 bool first_10ms_data_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700293
danilchap56359be2017-09-07 07:53:45 -0700294 bool first_frame_ RTC_GUARDED_BY(acm_crit_sect_);
295 uint32_t last_timestamp_ RTC_GUARDED_BY(acm_crit_sect_);
296 uint32_t last_rtp_timestamp_ RTC_GUARDED_BY(acm_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700297
298 rtc::CriticalSection callback_crit_sect_;
299 AudioPacketizationCallback* packetization_callback_
danilchap56359be2017-09-07 07:53:45 -0700300 RTC_GUARDED_BY(callback_crit_sect_);
301 ACMVADCallback* vad_callback_ RTC_GUARDED_BY(callback_crit_sect_);
kwibergc13ded52016-06-17 06:00:45 -0700302
303 int codec_histogram_bins_log_[static_cast<size_t>(
304 AudioEncoder::CodecType::kMaxLoggedAudioCodecTypes)];
305 int number_of_consecutive_empty_packets_;
306};
307
308// Adds a codec usage sample to the histogram.
309void UpdateCodecTypeHistogram(size_t codec_type) {
310 RTC_HISTOGRAM_ENUMERATION(
311 "WebRTC.Audio.Encoder.CodecType", static_cast<int>(codec_type),
312 static_cast<int>(
313 webrtc::AudioEncoder::CodecType::kMaxLoggedAudioCodecTypes));
314}
315
kwibergc13ded52016-06-17 06:00:45 -0700316// Stereo-to-mono can be used as in-place.
317int DownMix(const AudioFrame& frame,
318 size_t length_out_buff,
319 int16_t* out_buff) {
yujo36b1a5f2017-06-12 12:45:32 -0700320 RTC_DCHECK_EQ(frame.num_channels_, 2);
321 RTC_DCHECK_GE(length_out_buff, frame.samples_per_channel_);
322
323 if (!frame.muted()) {
324 const int16_t* frame_data = frame.data();
325 for (size_t n = 0; n < frame.samples_per_channel_; ++n) {
326 out_buff[n] = static_cast<int16_t>(
327 (static_cast<int32_t>(frame_data[2 * n]) +
328 static_cast<int32_t>(frame_data[2 * n + 1])) >> 1);
329 }
330 } else {
Jonathan Yu36344a02017-07-30 01:55:34 -0700331 std::fill(out_buff, out_buff + frame.samples_per_channel_, 0);
kwibergc13ded52016-06-17 06:00:45 -0700332 }
kwibergc13ded52016-06-17 06:00:45 -0700333 return 0;
334}
335
336// Mono-to-stereo can be used as in-place.
337int UpMix(const AudioFrame& frame, size_t length_out_buff, int16_t* out_buff) {
yujo36b1a5f2017-06-12 12:45:32 -0700338 RTC_DCHECK_EQ(frame.num_channels_, 1);
339 RTC_DCHECK_GE(length_out_buff, 2 * frame.samples_per_channel_);
340
341 if (!frame.muted()) {
342 const int16_t* frame_data = frame.data();
343 for (size_t n = frame.samples_per_channel_; n != 0; --n) {
344 size_t i = n - 1;
345 int16_t sample = frame_data[i];
346 out_buff[2 * i + 1] = sample;
347 out_buff[2 * i] = sample;
348 }
349 } else {
Jonathan Yu36344a02017-07-30 01:55:34 -0700350 std::fill(out_buff, out_buff + frame.samples_per_channel_ * 2, 0);
kwibergc13ded52016-06-17 06:00:45 -0700351 }
352 return 0;
353}
354
355void ConvertEncodedInfoToFragmentationHeader(
356 const AudioEncoder::EncodedInfo& info,
357 RTPFragmentationHeader* frag) {
358 if (info.redundant.empty()) {
359 frag->fragmentationVectorSize = 0;
360 return;
361 }
362
363 frag->VerifyAndAllocateFragmentationHeader(
364 static_cast<uint16_t>(info.redundant.size()));
365 frag->fragmentationVectorSize = static_cast<uint16_t>(info.redundant.size());
366 size_t offset = 0;
367 for (size_t i = 0; i < info.redundant.size(); ++i) {
368 frag->fragmentationOffset[i] = offset;
369 offset += info.redundant[i].encoded_bytes;
370 frag->fragmentationLength[i] = info.redundant[i].encoded_bytes;
kwibergd3edd772017-03-01 18:52:48 -0800371 frag->fragmentationTimeDiff[i] = rtc::dchecked_cast<uint16_t>(
kwibergc13ded52016-06-17 06:00:45 -0700372 info.encoded_timestamp - info.redundant[i].encoded_timestamp);
373 frag->fragmentationPlType[i] = info.redundant[i].payload_type;
374 }
375}
376
377// Wraps a raw AudioEncoder pointer. The idea is that you can put one of these
378// in a unique_ptr, to protect the contained raw pointer from being deleted
379// when the unique_ptr expires. (This is of course a bad idea in general, but
380// backwards compatibility.)
381class RawAudioEncoderWrapper final : public AudioEncoder {
382 public:
383 RawAudioEncoderWrapper(AudioEncoder* enc) : enc_(enc) {}
384 int SampleRateHz() const override { return enc_->SampleRateHz(); }
385 size_t NumChannels() const override { return enc_->NumChannels(); }
386 int RtpTimestampRateHz() const override { return enc_->RtpTimestampRateHz(); }
387 size_t Num10MsFramesInNextPacket() const override {
388 return enc_->Num10MsFramesInNextPacket();
389 }
390 size_t Max10MsFramesInAPacket() const override {
391 return enc_->Max10MsFramesInAPacket();
392 }
393 int GetTargetBitrate() const override { return enc_->GetTargetBitrate(); }
394 EncodedInfo EncodeImpl(uint32_t rtp_timestamp,
395 rtc::ArrayView<const int16_t> audio,
396 rtc::Buffer* encoded) override {
397 return enc_->Encode(rtp_timestamp, audio, encoded);
398 }
399 void Reset() override { return enc_->Reset(); }
400 bool SetFec(bool enable) override { return enc_->SetFec(enable); }
401 bool SetDtx(bool enable) override { return enc_->SetDtx(enable); }
402 bool SetApplication(Application application) override {
403 return enc_->SetApplication(application);
404 }
405 void SetMaxPlaybackRate(int frequency_hz) override {
406 return enc_->SetMaxPlaybackRate(frequency_hz);
407 }
kwibergc13ded52016-06-17 06:00:45 -0700408
409 private:
410 AudioEncoder* enc_;
411};
412
413// Return false on error.
414bool CreateSpeechEncoderIfNecessary(EncoderFactory* ef) {
415 auto* sp = ef->codec_manager.GetStackParams();
416 if (sp->speech_encoder) {
417 // Do nothing; we already have a speech encoder.
418 } else if (ef->codec_manager.GetCodecInst()) {
419 RTC_DCHECK(!ef->external_speech_encoder);
420 // We have no speech encoder, but we have a specification for making one.
421 std::unique_ptr<AudioEncoder> enc =
422 ef->rent_a_codec.RentEncoder(*ef->codec_manager.GetCodecInst());
423 if (!enc)
424 return false; // Encoder spec was bad.
425 sp->speech_encoder = std::move(enc);
426 } else if (ef->external_speech_encoder) {
427 RTC_DCHECK(!ef->codec_manager.GetCodecInst());
428 // We have an external speech encoder.
429 sp->speech_encoder = std::unique_ptr<AudioEncoder>(
430 new RawAudioEncoderWrapper(ef->external_speech_encoder));
431 }
432 return true;
433}
434
435void AudioCodingModuleImpl::ChangeLogger::MaybeLog(int value) {
436 if (value != last_value_ || first_time_) {
437 first_time_ = false;
438 last_value_ = value;
439 RTC_HISTOGRAM_COUNTS_SPARSE_100(histogram_name_, value);
440 }
441}
442
443AudioCodingModuleImpl::AudioCodingModuleImpl(
444 const AudioCodingModule::Config& config)
solenbergc7b4a452017-09-28 07:37:11 -0700445 : expected_codec_ts_(0xD87F3F9F),
kwibergc13ded52016-06-17 06:00:45 -0700446 expected_in_ts_(0xD87F3F9F),
447 receiver_(config),
448 bitrate_logger_("WebRTC.Audio.TargetBitrateInKbps"),
449 encoder_factory_(new EncoderFactory),
450 encoder_stack_(nullptr),
451 previous_pltype_(255),
452 receiver_initialized_(false),
453 first_10ms_data_(false),
454 first_frame_(true),
455 packetization_callback_(NULL),
456 vad_callback_(NULL),
457 codec_histogram_bins_log_(),
458 number_of_consecutive_empty_packets_(0) {
459 if (InitializeReceiverSafe() < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100460 RTC_LOG(LS_ERROR) << "Cannot initialize receiver";
kwibergc13ded52016-06-17 06:00:45 -0700461 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100462 RTC_LOG(LS_INFO) << "Created";
kwibergc13ded52016-06-17 06:00:45 -0700463}
464
465AudioCodingModuleImpl::~AudioCodingModuleImpl() = default;
466
467int32_t AudioCodingModuleImpl::Encode(const InputData& input_data) {
468 AudioEncoder::EncodedInfo encoded_info;
469 uint8_t previous_pltype;
470
471 // Check if there is an encoder before.
472 if (!HaveValidEncoder("Process"))
473 return -1;
474
ossu63fb95a2016-07-06 09:34:22 -0700475 if(!first_frame_) {
deadbeeffcada902016-08-24 12:45:13 -0700476 RTC_DCHECK(IsNewerTimestamp(input_data.input_timestamp, last_timestamp_))
ossu63fb95a2016-07-06 09:34:22 -0700477 << "Time should not move backwards";
478 }
479
kwibergc13ded52016-06-17 06:00:45 -0700480 // Scale the timestamp to the codec's RTP timestamp rate.
481 uint32_t rtp_timestamp =
482 first_frame_ ? input_data.input_timestamp
483 : last_rtp_timestamp_ +
484 rtc::CheckedDivExact(
485 input_data.input_timestamp - last_timestamp_,
486 static_cast<uint32_t>(rtc::CheckedDivExact(
487 encoder_stack_->SampleRateHz(),
488 encoder_stack_->RtpTimestampRateHz())));
489 last_timestamp_ = input_data.input_timestamp;
490 last_rtp_timestamp_ = rtp_timestamp;
491 first_frame_ = false;
492
493 // Clear the buffer before reuse - encoded data will get appended.
494 encode_buffer_.Clear();
495 encoded_info = encoder_stack_->Encode(
496 rtp_timestamp, rtc::ArrayView<const int16_t>(
497 input_data.audio, input_data.audio_channel *
498 input_data.length_per_channel),
499 &encode_buffer_);
500
501 bitrate_logger_.MaybeLog(encoder_stack_->GetTargetBitrate() / 1000);
502 if (encode_buffer_.size() == 0 && !encoded_info.send_even_if_empty) {
503 // Not enough data.
504 return 0;
505 }
506 previous_pltype = previous_pltype_; // Read it while we have the critsect.
507
508 // Log codec type to histogram once every 500 packets.
509 if (encoded_info.encoded_bytes == 0) {
510 ++number_of_consecutive_empty_packets_;
511 } else {
512 size_t codec_type = static_cast<size_t>(encoded_info.encoder_type);
513 codec_histogram_bins_log_[codec_type] +=
514 number_of_consecutive_empty_packets_ + 1;
515 number_of_consecutive_empty_packets_ = 0;
516 if (codec_histogram_bins_log_[codec_type] >= 500) {
517 codec_histogram_bins_log_[codec_type] -= 500;
518 UpdateCodecTypeHistogram(codec_type);
519 }
520 }
521
522 RTPFragmentationHeader my_fragmentation;
523 ConvertEncodedInfoToFragmentationHeader(encoded_info, &my_fragmentation);
524 FrameType frame_type;
525 if (encode_buffer_.size() == 0 && encoded_info.send_even_if_empty) {
526 frame_type = kEmptyFrame;
527 encoded_info.payload_type = previous_pltype;
528 } else {
kwibergaf476c72016-11-28 15:21:39 -0800529 RTC_DCHECK_GT(encode_buffer_.size(), 0);
kwibergc13ded52016-06-17 06:00:45 -0700530 frame_type = encoded_info.speech ? kAudioFrameSpeech : kAudioFrameCN;
531 }
532
533 {
534 rtc::CritScope lock(&callback_crit_sect_);
535 if (packetization_callback_) {
536 packetization_callback_->SendData(
537 frame_type, encoded_info.payload_type, encoded_info.encoded_timestamp,
538 encode_buffer_.data(), encode_buffer_.size(),
539 my_fragmentation.fragmentationVectorSize > 0 ? &my_fragmentation
540 : nullptr);
541 }
542
543 if (vad_callback_) {
544 // Callback with VAD decision.
545 vad_callback_->InFrameType(frame_type);
546 }
547 }
548 previous_pltype_ = encoded_info.payload_type;
549 return static_cast<int32_t>(encode_buffer_.size());
550}
551
552/////////////////////////////////////////
553// Sender
554//
555
556// Can be called multiple times for Codec, CNG, RED.
557int AudioCodingModuleImpl::RegisterSendCodec(const CodecInst& send_codec) {
558 rtc::CritScope lock(&acm_crit_sect_);
559 if (!encoder_factory_->codec_manager.RegisterEncoder(send_codec)) {
560 return -1;
561 }
562 if (encoder_factory_->codec_manager.GetCodecInst()) {
563 encoder_factory_->external_speech_encoder = nullptr;
564 }
565 if (!CreateSpeechEncoderIfNecessary(encoder_factory_.get())) {
566 return -1;
567 }
568 auto* sp = encoder_factory_->codec_manager.GetStackParams();
569 if (sp->speech_encoder)
570 encoder_stack_ = encoder_factory_->rent_a_codec.RentEncoderStack(sp);
571 return 0;
572}
573
574void AudioCodingModuleImpl::RegisterExternalSendCodec(
575 AudioEncoder* external_speech_encoder) {
576 rtc::CritScope lock(&acm_crit_sect_);
577 encoder_factory_->codec_manager.UnsetCodecInst();
578 encoder_factory_->external_speech_encoder = external_speech_encoder;
579 RTC_CHECK(CreateSpeechEncoderIfNecessary(encoder_factory_.get()));
580 auto* sp = encoder_factory_->codec_manager.GetStackParams();
581 RTC_CHECK(sp->speech_encoder);
582 encoder_stack_ = encoder_factory_->rent_a_codec.RentEncoderStack(sp);
583}
584
585void AudioCodingModuleImpl::ModifyEncoder(
kwiberg24c7c122016-09-28 11:57:10 -0700586 rtc::FunctionView<void(std::unique_ptr<AudioEncoder>*)> modifier) {
kwibergc13ded52016-06-17 06:00:45 -0700587 rtc::CritScope lock(&acm_crit_sect_);
588
589 // Wipe the encoder factory, so that everything that relies on it will fail.
590 // We don't want the complexity of supporting swapping back and forth.
591 if (encoder_factory_) {
592 encoder_factory_.reset();
593 RTC_CHECK(!encoder_stack_); // Ensure we hadn't started using the factory.
594 }
595
596 modifier(&encoder_stack_);
597}
598
ivoc85228d62016-07-27 04:53:47 -0700599void AudioCodingModuleImpl::QueryEncoder(
kwiberg24c7c122016-09-28 11:57:10 -0700600 rtc::FunctionView<void(const AudioEncoder*)> query) {
ivoc85228d62016-07-27 04:53:47 -0700601 rtc::CritScope lock(&acm_crit_sect_);
602 query(encoder_stack_.get());
603}
604
kwibergc13ded52016-06-17 06:00:45 -0700605// Get current send codec.
606rtc::Optional<CodecInst> AudioCodingModuleImpl::SendCodec() const {
607 rtc::CritScope lock(&acm_crit_sect_);
608 if (encoder_factory_) {
609 auto* ci = encoder_factory_->codec_manager.GetCodecInst();
610 if (ci) {
Oskar Sundbom12ab00b2017-11-16 15:31:38 +0100611 return *ci;
kwibergc13ded52016-06-17 06:00:45 -0700612 }
613 CreateSpeechEncoderIfNecessary(encoder_factory_.get());
614 const std::unique_ptr<AudioEncoder>& enc =
615 encoder_factory_->codec_manager.GetStackParams()->speech_encoder;
616 if (enc) {
Oskar Sundbom12ab00b2017-11-16 15:31:38 +0100617 return acm2::CodecManager::ForgeCodecInst(enc.get());
kwibergc13ded52016-06-17 06:00:45 -0700618 }
Oskar Sundbom12ab00b2017-11-16 15:31:38 +0100619 return rtc::nullopt;
kwibergc13ded52016-06-17 06:00:45 -0700620 } else {
621 return encoder_stack_
622 ? rtc::Optional<CodecInst>(
623 acm2::CodecManager::ForgeCodecInst(encoder_stack_.get()))
Oskar Sundbom12ab00b2017-11-16 15:31:38 +0100624 : rtc::nullopt;
kwibergc13ded52016-06-17 06:00:45 -0700625 }
626}
627
628// Get current send frequency.
629int AudioCodingModuleImpl::SendFrequency() const {
kwibergc13ded52016-06-17 06:00:45 -0700630 rtc::CritScope lock(&acm_crit_sect_);
631
632 if (!encoder_stack_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100633 RTC_LOG(LS_ERROR) << "SendFrequency Failed, no codec is registered";
kwibergc13ded52016-06-17 06:00:45 -0700634 return -1;
635 }
636
637 return encoder_stack_->SampleRateHz();
638}
639
640void AudioCodingModuleImpl::SetBitRate(int bitrate_bps) {
641 rtc::CritScope lock(&acm_crit_sect_);
642 if (encoder_stack_) {
Oskar Sundbom12ab00b2017-11-16 15:31:38 +0100643 encoder_stack_->OnReceivedUplinkBandwidth(bitrate_bps, rtc::nullopt);
kwibergc13ded52016-06-17 06:00:45 -0700644 }
645}
646
647// Register a transport callback which will be called to deliver
648// the encoded buffers.
649int AudioCodingModuleImpl::RegisterTransportCallback(
650 AudioPacketizationCallback* transport) {
651 rtc::CritScope lock(&callback_crit_sect_);
652 packetization_callback_ = transport;
653 return 0;
654}
655
656// Add 10MS of raw (PCM) audio data to the encoder.
657int AudioCodingModuleImpl::Add10MsData(const AudioFrame& audio_frame) {
658 InputData input_data;
659 rtc::CritScope lock(&acm_crit_sect_);
660 int r = Add10MsDataInternal(audio_frame, &input_data);
661 return r < 0 ? r : Encode(input_data);
662}
663
664int AudioCodingModuleImpl::Add10MsDataInternal(const AudioFrame& audio_frame,
665 InputData* input_data) {
666 if (audio_frame.samples_per_channel_ == 0) {
667 assert(false);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100668 RTC_LOG(LS_ERROR) << "Cannot Add 10 ms audio, payload length is zero";
kwibergc13ded52016-06-17 06:00:45 -0700669 return -1;
670 }
671
672 if (audio_frame.sample_rate_hz_ > 48000) {
673 assert(false);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100674 RTC_LOG(LS_ERROR) << "Cannot Add 10 ms audio, input frequency not valid";
kwibergc13ded52016-06-17 06:00:45 -0700675 return -1;
676 }
677
678 // If the length and frequency matches. We currently just support raw PCM.
679 if (static_cast<size_t>(audio_frame.sample_rate_hz_ / 100) !=
680 audio_frame.samples_per_channel_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100681 RTC_LOG(LS_ERROR)
Alex Loiko300ec8c2017-05-30 17:23:28 +0200682 << "Cannot Add 10 ms audio, input frequency and length doesn't match";
kwibergc13ded52016-06-17 06:00:45 -0700683 return -1;
684 }
685
686 if (audio_frame.num_channels_ != 1 && audio_frame.num_channels_ != 2) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100687 RTC_LOG(LS_ERROR) << "Cannot Add 10 ms audio, invalid number of channels.";
kwibergc13ded52016-06-17 06:00:45 -0700688 return -1;
689 }
690
691 // Do we have a codec registered?
692 if (!HaveValidEncoder("Add10MsData")) {
693 return -1;
694 }
695
696 const AudioFrame* ptr_frame;
697 // Perform a resampling, also down-mix if it is required and can be
698 // performed before resampling (a down mix prior to resampling will take
699 // place if both primary and secondary encoders are mono and input is in
700 // stereo).
701 if (PreprocessToAddData(audio_frame, &ptr_frame) < 0) {
702 return -1;
703 }
704
705 // Check whether we need an up-mix or down-mix?
706 const size_t current_num_channels = encoder_stack_->NumChannels();
707 const bool same_num_channels =
708 ptr_frame->num_channels_ == current_num_channels;
709
710 if (!same_num_channels) {
711 if (ptr_frame->num_channels_ == 1) {
712 if (UpMix(*ptr_frame, WEBRTC_10MS_PCM_AUDIO, input_data->buffer) < 0)
713 return -1;
714 } else {
715 if (DownMix(*ptr_frame, WEBRTC_10MS_PCM_AUDIO, input_data->buffer) < 0)
716 return -1;
717 }
718 }
719
720 // When adding data to encoders this pointer is pointing to an audio buffer
721 // with correct number of channels.
yujo36b1a5f2017-06-12 12:45:32 -0700722 const int16_t* ptr_audio = ptr_frame->data();
kwibergc13ded52016-06-17 06:00:45 -0700723
724 // For pushing data to primary, point the |ptr_audio| to correct buffer.
725 if (!same_num_channels)
726 ptr_audio = input_data->buffer;
727
yujo36b1a5f2017-06-12 12:45:32 -0700728 // TODO(yujo): Skip encode of muted frames.
kwibergc13ded52016-06-17 06:00:45 -0700729 input_data->input_timestamp = ptr_frame->timestamp_;
730 input_data->audio = ptr_audio;
731 input_data->length_per_channel = ptr_frame->samples_per_channel_;
732 input_data->audio_channel = current_num_channels;
733
734 return 0;
735}
736
737// Perform a resampling and down-mix if required. We down-mix only if
738// encoder is mono and input is stereo. In case of dual-streaming, both
739// encoders has to be mono for down-mix to take place.
740// |*ptr_out| will point to the pre-processed audio-frame. If no pre-processing
741// is required, |*ptr_out| points to |in_frame|.
yujo36b1a5f2017-06-12 12:45:32 -0700742// TODO(yujo): Make this more efficient for muted frames.
kwibergc13ded52016-06-17 06:00:45 -0700743int AudioCodingModuleImpl::PreprocessToAddData(const AudioFrame& in_frame,
744 const AudioFrame** ptr_out) {
745 const bool resample =
746 in_frame.sample_rate_hz_ != encoder_stack_->SampleRateHz();
747
748 // This variable is true if primary codec and secondary codec (if exists)
749 // are both mono and input is stereo.
750 // TODO(henrik.lundin): This condition should probably be
751 // in_frame.num_channels_ > encoder_stack_->NumChannels()
752 const bool down_mix =
753 in_frame.num_channels_ == 2 && encoder_stack_->NumChannels() == 1;
754
755 if (!first_10ms_data_) {
756 expected_in_ts_ = in_frame.timestamp_;
757 expected_codec_ts_ = in_frame.timestamp_;
758 first_10ms_data_ = true;
759 } else if (in_frame.timestamp_ != expected_in_ts_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100760 RTC_LOG(LS_WARNING) << "Unexpected input timestamp: " << in_frame.timestamp_
761 << ", expected: " << expected_in_ts_;
kwibergc13ded52016-06-17 06:00:45 -0700762 expected_codec_ts_ +=
763 (in_frame.timestamp_ - expected_in_ts_) *
764 static_cast<uint32_t>(
765 static_cast<double>(encoder_stack_->SampleRateHz()) /
766 static_cast<double>(in_frame.sample_rate_hz_));
767 expected_in_ts_ = in_frame.timestamp_;
768 }
769
770
771 if (!down_mix && !resample) {
772 // No pre-processing is required.
ossu63fb95a2016-07-06 09:34:22 -0700773 if (expected_in_ts_ == expected_codec_ts_) {
774 // If we've never resampled, we can use the input frame as-is
775 *ptr_out = &in_frame;
776 } else {
777 // Otherwise we'll need to alter the timestamp. Since in_frame is const,
778 // we'll have to make a copy of it.
779 preprocess_frame_.CopyFrom(in_frame);
780 preprocess_frame_.timestamp_ = expected_codec_ts_;
781 *ptr_out = &preprocess_frame_;
782 }
783
kwibergc13ded52016-06-17 06:00:45 -0700784 expected_in_ts_ += static_cast<uint32_t>(in_frame.samples_per_channel_);
785 expected_codec_ts_ += static_cast<uint32_t>(in_frame.samples_per_channel_);
kwibergc13ded52016-06-17 06:00:45 -0700786 return 0;
787 }
788
789 *ptr_out = &preprocess_frame_;
790 preprocess_frame_.num_channels_ = in_frame.num_channels_;
791 int16_t audio[WEBRTC_10MS_PCM_AUDIO];
yujo36b1a5f2017-06-12 12:45:32 -0700792 const int16_t* src_ptr_audio = in_frame.data();
kwibergc13ded52016-06-17 06:00:45 -0700793 if (down_mix) {
794 // If a resampling is required the output of a down-mix is written into a
795 // local buffer, otherwise, it will be written to the output frame.
yujo36b1a5f2017-06-12 12:45:32 -0700796 int16_t* dest_ptr_audio = resample ?
797 audio : preprocess_frame_.mutable_data();
kwibergc13ded52016-06-17 06:00:45 -0700798 if (DownMix(in_frame, WEBRTC_10MS_PCM_AUDIO, dest_ptr_audio) < 0)
799 return -1;
800 preprocess_frame_.num_channels_ = 1;
801 // Set the input of the resampler is the down-mixed signal.
802 src_ptr_audio = audio;
803 }
804
805 preprocess_frame_.timestamp_ = expected_codec_ts_;
806 preprocess_frame_.samples_per_channel_ = in_frame.samples_per_channel_;
807 preprocess_frame_.sample_rate_hz_ = in_frame.sample_rate_hz_;
808 // If it is required, we have to do a resampling.
809 if (resample) {
810 // The result of the resampler is written to output frame.
yujo36b1a5f2017-06-12 12:45:32 -0700811 int16_t* dest_ptr_audio = preprocess_frame_.mutable_data();
kwibergc13ded52016-06-17 06:00:45 -0700812
813 int samples_per_channel = resampler_.Resample10Msec(
814 src_ptr_audio, in_frame.sample_rate_hz_, encoder_stack_->SampleRateHz(),
815 preprocess_frame_.num_channels_, AudioFrame::kMaxDataSizeSamples,
816 dest_ptr_audio);
817
818 if (samples_per_channel < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100819 RTC_LOG(LS_ERROR) << "Cannot add 10 ms audio, resampling failed";
kwibergc13ded52016-06-17 06:00:45 -0700820 return -1;
821 }
822 preprocess_frame_.samples_per_channel_ =
823 static_cast<size_t>(samples_per_channel);
824 preprocess_frame_.sample_rate_hz_ = encoder_stack_->SampleRateHz();
825 }
826
827 expected_codec_ts_ +=
828 static_cast<uint32_t>(preprocess_frame_.samples_per_channel_);
829 expected_in_ts_ += static_cast<uint32_t>(in_frame.samples_per_channel_);
830
831 return 0;
832}
833
834/////////////////////////////////////////
835// (RED) Redundant Coding
836//
837
838bool AudioCodingModuleImpl::REDStatus() const {
839 rtc::CritScope lock(&acm_crit_sect_);
840 return encoder_factory_->codec_manager.GetStackParams()->use_red;
841}
842
843// Configure RED status i.e on/off.
844int AudioCodingModuleImpl::SetREDStatus(bool enable_red) {
845#ifdef WEBRTC_CODEC_RED
846 rtc::CritScope lock(&acm_crit_sect_);
847 CreateSpeechEncoderIfNecessary(encoder_factory_.get());
848 if (!encoder_factory_->codec_manager.SetCopyRed(enable_red)) {
849 return -1;
850 }
851 auto* sp = encoder_factory_->codec_manager.GetStackParams();
852 if (sp->speech_encoder)
853 encoder_stack_ = encoder_factory_->rent_a_codec.RentEncoderStack(sp);
854 return 0;
855#else
Mirko Bonadei675513b2017-11-09 11:09:25 +0100856 RTC_LOG(LS_WARNING) << " WEBRTC_CODEC_RED is undefined";
kwibergc13ded52016-06-17 06:00:45 -0700857 return -1;
858#endif
859}
860
861/////////////////////////////////////////
862// (FEC) Forward Error Correction (codec internal)
863//
864
865bool AudioCodingModuleImpl::CodecFEC() const {
866 rtc::CritScope lock(&acm_crit_sect_);
867 return encoder_factory_->codec_manager.GetStackParams()->use_codec_fec;
868}
869
870int AudioCodingModuleImpl::SetCodecFEC(bool enable_codec_fec) {
871 rtc::CritScope lock(&acm_crit_sect_);
872 CreateSpeechEncoderIfNecessary(encoder_factory_.get());
873 if (!encoder_factory_->codec_manager.SetCodecFEC(enable_codec_fec)) {
874 return -1;
875 }
876 auto* sp = encoder_factory_->codec_manager.GetStackParams();
877 if (sp->speech_encoder)
878 encoder_stack_ = encoder_factory_->rent_a_codec.RentEncoderStack(sp);
879 if (enable_codec_fec) {
880 return sp->use_codec_fec ? 0 : -1;
881 } else {
882 RTC_DCHECK(!sp->use_codec_fec);
883 return 0;
884 }
885}
886
887int AudioCodingModuleImpl::SetPacketLossRate(int loss_rate) {
888 rtc::CritScope lock(&acm_crit_sect_);
889 if (HaveValidEncoder("SetPacketLossRate")) {
minyue4b9a2cb2016-11-30 06:49:59 -0800890 encoder_stack_->OnReceivedUplinkPacketLossFraction(loss_rate / 100.0);
kwibergc13ded52016-06-17 06:00:45 -0700891 }
892 return 0;
893}
894
895/////////////////////////////////////////
896// (VAD) Voice Activity Detection
897//
898int AudioCodingModuleImpl::SetVAD(bool enable_dtx,
899 bool enable_vad,
900 ACMVADMode mode) {
901 // Note: |enable_vad| is not used; VAD is enabled based on the DTX setting.
902 RTC_DCHECK_EQ(enable_dtx, enable_vad);
903 rtc::CritScope lock(&acm_crit_sect_);
904 CreateSpeechEncoderIfNecessary(encoder_factory_.get());
905 if (!encoder_factory_->codec_manager.SetVAD(enable_dtx, mode)) {
906 return -1;
907 }
908 auto* sp = encoder_factory_->codec_manager.GetStackParams();
909 if (sp->speech_encoder)
910 encoder_stack_ = encoder_factory_->rent_a_codec.RentEncoderStack(sp);
911 return 0;
912}
913
914// Get VAD/DTX settings.
915int AudioCodingModuleImpl::VAD(bool* dtx_enabled, bool* vad_enabled,
916 ACMVADMode* mode) const {
917 rtc::CritScope lock(&acm_crit_sect_);
918 const auto* sp = encoder_factory_->codec_manager.GetStackParams();
919 *dtx_enabled = *vad_enabled = sp->use_cng;
920 *mode = sp->vad_mode;
921 return 0;
922}
923
924/////////////////////////////////////////
925// Receiver
926//
927
928int AudioCodingModuleImpl::InitializeReceiver() {
929 rtc::CritScope lock(&acm_crit_sect_);
930 return InitializeReceiverSafe();
931}
932
933// Initialize receiver, resets codec database etc.
934int AudioCodingModuleImpl::InitializeReceiverSafe() {
935 // If the receiver is already initialized then we want to destroy any
936 // existing decoders. After a call to this function, we should have a clean
937 // start-up.
kwiberg6b19b562016-09-20 04:02:25 -0700938 if (receiver_initialized_)
939 receiver_.RemoveAllCodecs();
kwibergc13ded52016-06-17 06:00:45 -0700940 receiver_.ResetInitialDelay();
941 receiver_.SetMinimumDelay(0);
942 receiver_.SetMaximumDelay(0);
943 receiver_.FlushBuffers();
944
kwibergc13ded52016-06-17 06:00:45 -0700945 receiver_initialized_ = true;
946 return 0;
947}
948
949// Get current receive frequency.
950int AudioCodingModuleImpl::ReceiveFrequency() const {
951 const auto last_packet_sample_rate = receiver_.last_packet_sample_rate_hz();
952 return last_packet_sample_rate ? *last_packet_sample_rate
953 : receiver_.last_output_sample_rate_hz();
954}
955
956// Get current playout frequency.
957int AudioCodingModuleImpl::PlayoutFrequency() const {
kwibergc13ded52016-06-17 06:00:45 -0700958 return receiver_.last_output_sample_rate_hz();
959}
960
kwiberg1c07c702017-03-27 07:15:49 -0700961void AudioCodingModuleImpl::SetReceiveCodecs(
962 const std::map<int, SdpAudioFormat>& codecs) {
963 rtc::CritScope lock(&acm_crit_sect_);
964 receiver_.SetCodecs(codecs);
965}
966
kwiberg5adaf732016-10-04 09:33:27 -0700967bool AudioCodingModuleImpl::RegisterReceiveCodec(
968 int rtp_payload_type,
969 const SdpAudioFormat& audio_format) {
970 rtc::CritScope lock(&acm_crit_sect_);
971 RTC_DCHECK(receiver_initialized_);
972
973 if (!acm2::RentACodec::IsPayloadTypeValid(rtp_payload_type)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100974 RTC_LOG_F(LS_ERROR) << "Invalid payload-type " << rtp_payload_type
975 << " for decoder.";
kwiberg5adaf732016-10-04 09:33:27 -0700976 return false;
977 }
978
979 return receiver_.AddCodec(rtp_payload_type, audio_format);
980}
981
kwibergc13ded52016-06-17 06:00:45 -0700982int AudioCodingModuleImpl::RegisterReceiveCodec(const CodecInst& codec) {
983 rtc::CritScope lock(&acm_crit_sect_);
984 auto* ef = encoder_factory_.get();
985 return RegisterReceiveCodecUnlocked(
986 codec, [&] { return ef->rent_a_codec.RentIsacDecoder(codec.plfreq); });
987}
988
989int AudioCodingModuleImpl::RegisterReceiveCodec(
990 const CodecInst& codec,
kwiberg24c7c122016-09-28 11:57:10 -0700991 rtc::FunctionView<std::unique_ptr<AudioDecoder>()> isac_factory) {
kwibergc13ded52016-06-17 06:00:45 -0700992 rtc::CritScope lock(&acm_crit_sect_);
993 return RegisterReceiveCodecUnlocked(codec, isac_factory);
994}
995
996int AudioCodingModuleImpl::RegisterReceiveCodecUnlocked(
997 const CodecInst& codec,
kwiberg24c7c122016-09-28 11:57:10 -0700998 rtc::FunctionView<std::unique_ptr<AudioDecoder>()> isac_factory) {
kwibergc13ded52016-06-17 06:00:45 -0700999 RTC_DCHECK(receiver_initialized_);
1000 if (codec.channels > 2) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001001 RTC_LOG_F(LS_ERROR) << "Unsupported number of channels: " << codec.channels;
kwibergc13ded52016-06-17 06:00:45 -07001002 return -1;
1003 }
1004
1005 auto codec_id = acm2::RentACodec::CodecIdByParams(codec.plname, codec.plfreq,
1006 codec.channels);
1007 if (!codec_id) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001008 RTC_LOG_F(LS_ERROR)
1009 << "Wrong codec params to be registered as receive codec";
kwibergc13ded52016-06-17 06:00:45 -07001010 return -1;
1011 }
1012 auto codec_index = acm2::RentACodec::CodecIndexFromId(*codec_id);
1013 RTC_CHECK(codec_index) << "Invalid codec ID: " << static_cast<int>(*codec_id);
1014
1015 // Check if the payload-type is valid.
1016 if (!acm2::RentACodec::IsPayloadTypeValid(codec.pltype)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001017 RTC_LOG_F(LS_ERROR) << "Invalid payload type " << codec.pltype << " for "
1018 << codec.plname;
kwibergc13ded52016-06-17 06:00:45 -07001019 return -1;
1020 }
1021
1022 AudioDecoder* isac_decoder = nullptr;
1023 if (STR_CASE_CMP(codec.plname, "isac") == 0) {
1024 std::unique_ptr<AudioDecoder>& saved_isac_decoder =
1025 codec.plfreq == 16000 ? isac_decoder_16k_ : isac_decoder_32k_;
1026 if (!saved_isac_decoder) {
1027 saved_isac_decoder = isac_factory();
1028 }
1029 isac_decoder = saved_isac_decoder.get();
1030 }
1031 return receiver_.AddCodec(*codec_index, codec.pltype, codec.channels,
1032 codec.plfreq, isac_decoder, codec.plname);
1033}
1034
1035int AudioCodingModuleImpl::RegisterExternalReceiveCodec(
1036 int rtp_payload_type,
1037 AudioDecoder* external_decoder,
1038 int sample_rate_hz,
1039 int num_channels,
1040 const std::string& name) {
1041 rtc::CritScope lock(&acm_crit_sect_);
1042 RTC_DCHECK(receiver_initialized_);
1043 if (num_channels > 2 || num_channels < 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001044 RTC_LOG_F(LS_ERROR) << "Unsupported number of channels: " << num_channels;
kwibergc13ded52016-06-17 06:00:45 -07001045 return -1;
1046 }
1047
1048 // Check if the payload-type is valid.
1049 if (!acm2::RentACodec::IsPayloadTypeValid(rtp_payload_type)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001050 RTC_LOG_F(LS_ERROR) << "Invalid payload-type " << rtp_payload_type
1051 << " for external decoder.";
kwibergc13ded52016-06-17 06:00:45 -07001052 return -1;
1053 }
1054
1055 return receiver_.AddCodec(-1 /* external */, rtp_payload_type, num_channels,
1056 sample_rate_hz, external_decoder, name);
1057}
1058
1059// Get current received codec.
1060int AudioCodingModuleImpl::ReceiveCodec(CodecInst* current_codec) const {
1061 rtc::CritScope lock(&acm_crit_sect_);
1062 return receiver_.LastAudioCodec(current_codec);
1063}
1064
ossue280cde2016-10-12 11:04:10 -07001065rtc::Optional<SdpAudioFormat> AudioCodingModuleImpl::ReceiveFormat() const {
1066 rtc::CritScope lock(&acm_crit_sect_);
1067 return receiver_.LastAudioFormat();
1068}
1069
kwibergc13ded52016-06-17 06:00:45 -07001070// Incoming packet from network parsed and ready for decode.
1071int AudioCodingModuleImpl::IncomingPacket(const uint8_t* incoming_payload,
1072 const size_t payload_length,
1073 const WebRtcRTPHeader& rtp_header) {
henrik.lundinb8c55b12017-05-10 07:38:01 -07001074 RTC_DCHECK_EQ(payload_length == 0, incoming_payload == nullptr);
kwibergc13ded52016-06-17 06:00:45 -07001075 return receiver_.InsertPacket(
1076 rtp_header,
1077 rtc::ArrayView<const uint8_t>(incoming_payload, payload_length));
1078}
1079
1080// Minimum playout delay (Used for lip-sync).
1081int AudioCodingModuleImpl::SetMinimumPlayoutDelay(int time_ms) {
1082 if ((time_ms < 0) || (time_ms > 10000)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001083 RTC_LOG(LS_ERROR) << "Delay must be in the range of 0-10000 milliseconds.";
kwibergc13ded52016-06-17 06:00:45 -07001084 return -1;
1085 }
1086 return receiver_.SetMinimumDelay(time_ms);
1087}
1088
1089int AudioCodingModuleImpl::SetMaximumPlayoutDelay(int time_ms) {
1090 if ((time_ms < 0) || (time_ms > 10000)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001091 RTC_LOG(LS_ERROR) << "Delay must be in the range of 0-10000 milliseconds.";
kwibergc13ded52016-06-17 06:00:45 -07001092 return -1;
1093 }
1094 return receiver_.SetMaximumDelay(time_ms);
1095}
1096
1097// Get 10 milliseconds of raw audio data to play out.
1098// Automatic resample to the requested frequency.
1099int AudioCodingModuleImpl::PlayoutData10Ms(int desired_freq_hz,
1100 AudioFrame* audio_frame,
1101 bool* muted) {
1102 // GetAudio always returns 10 ms, at the requested sample rate.
1103 if (receiver_.GetAudio(desired_freq_hz, audio_frame, muted) != 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001104 RTC_LOG(LS_ERROR) << "PlayoutData failed, RecOut Failed";
kwibergc13ded52016-06-17 06:00:45 -07001105 return -1;
1106 }
kwibergc13ded52016-06-17 06:00:45 -07001107 return 0;
1108}
1109
1110int AudioCodingModuleImpl::PlayoutData10Ms(int desired_freq_hz,
1111 AudioFrame* audio_frame) {
1112 bool muted;
1113 int ret = PlayoutData10Ms(desired_freq_hz, audio_frame, &muted);
1114 RTC_DCHECK(!muted);
1115 return ret;
1116}
1117
1118/////////////////////////////////////////
1119// Statistics
1120//
1121
1122// TODO(turajs) change the return value to void. Also change the corresponding
1123// NetEq function.
1124int AudioCodingModuleImpl::GetNetworkStatistics(NetworkStatistics* statistics) {
1125 receiver_.GetNetworkStatistics(statistics);
1126 return 0;
1127}
1128
1129int AudioCodingModuleImpl::RegisterVADCallback(ACMVADCallback* vad_callback) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001130 RTC_LOG(LS_VERBOSE) << "RegisterVADCallback()";
kwibergc13ded52016-06-17 06:00:45 -07001131 rtc::CritScope lock(&callback_crit_sect_);
1132 vad_callback_ = vad_callback;
1133 return 0;
1134}
1135
kwibergc13ded52016-06-17 06:00:45 -07001136int AudioCodingModuleImpl::SetOpusApplication(OpusApplicationMode application) {
1137 rtc::CritScope lock(&acm_crit_sect_);
1138 if (!HaveValidEncoder("SetOpusApplication")) {
1139 return -1;
1140 }
1141 AudioEncoder::Application app;
1142 switch (application) {
1143 case kVoip:
1144 app = AudioEncoder::Application::kSpeech;
1145 break;
1146 case kAudio:
1147 app = AudioEncoder::Application::kAudio;
1148 break;
1149 default:
1150 FATAL();
1151 return 0;
1152 }
1153 return encoder_stack_->SetApplication(app) ? 0 : -1;
1154}
1155
1156// Informs Opus encoder of the maximum playback rate the receiver will render.
1157int AudioCodingModuleImpl::SetOpusMaxPlaybackRate(int frequency_hz) {
1158 rtc::CritScope lock(&acm_crit_sect_);
1159 if (!HaveValidEncoder("SetOpusMaxPlaybackRate")) {
1160 return -1;
1161 }
1162 encoder_stack_->SetMaxPlaybackRate(frequency_hz);
1163 return 0;
1164}
1165
1166int AudioCodingModuleImpl::EnableOpusDtx() {
1167 rtc::CritScope lock(&acm_crit_sect_);
1168 if (!HaveValidEncoder("EnableOpusDtx")) {
1169 return -1;
1170 }
1171 return encoder_stack_->SetDtx(true) ? 0 : -1;
1172}
1173
1174int AudioCodingModuleImpl::DisableOpusDtx() {
1175 rtc::CritScope lock(&acm_crit_sect_);
1176 if (!HaveValidEncoder("DisableOpusDtx")) {
1177 return -1;
1178 }
1179 return encoder_stack_->SetDtx(false) ? 0 : -1;
1180}
1181
1182int32_t AudioCodingModuleImpl::PlayoutTimestamp(uint32_t* timestamp) {
1183 rtc::Optional<uint32_t> ts = PlayoutTimestamp();
1184 if (!ts)
1185 return -1;
1186 *timestamp = *ts;
1187 return 0;
1188}
1189
1190rtc::Optional<uint32_t> AudioCodingModuleImpl::PlayoutTimestamp() {
1191 return receiver_.GetPlayoutTimestamp();
1192}
1193
henrik.lundinb3f1c5d2016-08-22 15:39:53 -07001194int AudioCodingModuleImpl::FilteredCurrentDelayMs() const {
1195 return receiver_.FilteredCurrentDelayMs();
1196}
1197
Henrik Lundinabbff892017-11-29 09:14:04 +01001198int AudioCodingModuleImpl::TargetDelayMs() const {
1199 return receiver_.TargetDelayMs();
1200}
1201
kwibergc13ded52016-06-17 06:00:45 -07001202bool AudioCodingModuleImpl::HaveValidEncoder(const char* caller_name) const {
1203 if (!encoder_stack_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001204 RTC_LOG(LS_ERROR) << caller_name << " failed: No send codec is registered.";
kwibergc13ded52016-06-17 06:00:45 -07001205 return false;
1206 }
1207 return true;
1208}
1209
1210int AudioCodingModuleImpl::UnregisterReceiveCodec(uint8_t payload_type) {
1211 return receiver_.RemoveCodec(payload_type);
1212}
1213
1214int AudioCodingModuleImpl::EnableNack(size_t max_nack_list_size) {
1215 return receiver_.EnableNack(max_nack_list_size);
1216}
1217
1218void AudioCodingModuleImpl::DisableNack() {
1219 receiver_.DisableNack();
1220}
1221
1222std::vector<uint16_t> AudioCodingModuleImpl::GetNackList(
1223 int64_t round_trip_time_ms) const {
1224 return receiver_.GetNackList(round_trip_time_ms);
1225}
1226
1227int AudioCodingModuleImpl::LeastRequiredDelayMs() const {
1228 return receiver_.LeastRequiredDelayMs();
1229}
1230
1231void AudioCodingModuleImpl::GetDecodingCallStatistics(
1232 AudioDecodingCallStats* call_stats) const {
1233 receiver_.GetDecodingCallStatistics(call_stats);
1234}
1235
ivoce1198e02017-09-08 08:13:19 -07001236ANAStats AudioCodingModuleImpl::GetANAStats() const {
1237 rtc::CritScope lock(&acm_crit_sect_);
1238 if (encoder_stack_)
1239 return encoder_stack_->GetANAStats();
1240 // If no encoder is set, return default stats.
1241 return ANAStats();
1242}
1243
kwibergc13ded52016-06-17 06:00:45 -07001244} // namespace
1245
Karl Wiberg5817d3d2018-04-06 10:06:42 +02001246AudioCodingModule::Config::Config(
1247 rtc::scoped_refptr<AudioDecoderFactory> decoder_factory)
1248 : neteq_config(),
1249 clock(Clock::GetRealTimeClock()),
1250 decoder_factory(decoder_factory) {
kwiberg36a43882016-08-29 05:33:32 -07001251 // Post-decode VAD is disabled by default in NetEq, however, Audio
1252 // Conference Mixer relies on VAD decisions and fails without them.
1253 neteq_config.enable_post_decode_vad = true;
1254}
1255
1256AudioCodingModule::Config::Config(const Config&) = default;
1257AudioCodingModule::Config::~Config() = default;
1258
Henrik Lundin64dad832015-05-11 12:44:23 +02001259AudioCodingModule* AudioCodingModule::Create(const Config& config) {
kwibergc13ded52016-06-17 06:00:45 -07001260 return new AudioCodingModuleImpl(config);
turaj@webrtc.org7959e162013-09-12 18:30:26 +00001261}
1262
turaj@webrtc.org7959e162013-09-12 18:30:26 +00001263int AudioCodingModule::NumberOfCodecs() {
kwibergfce4a942015-10-27 11:40:24 -07001264 return static_cast<int>(acm2::RentACodec::NumberOfCodecs());
turaj@webrtc.org7959e162013-09-12 18:30:26 +00001265}
1266
turaj@webrtc.org7959e162013-09-12 18:30:26 +00001267int AudioCodingModule::Codec(int list_id, CodecInst* codec) {
kwibergfce4a942015-10-27 11:40:24 -07001268 auto codec_id = acm2::RentACodec::CodecIdFromIndex(list_id);
1269 if (!codec_id)
1270 return -1;
1271 auto ci = acm2::RentACodec::CodecInstById(*codec_id);
1272 if (!ci)
1273 return -1;
1274 *codec = *ci;
1275 return 0;
turaj@webrtc.org7959e162013-09-12 18:30:26 +00001276}
1277
turaj@webrtc.org7959e162013-09-12 18:30:26 +00001278int AudioCodingModule::Codec(const char* payload_name,
1279 CodecInst* codec,
1280 int sampling_freq_hz,
Peter Kasting69558702016-01-12 16:26:35 -08001281 size_t channels) {
Karl Wibergbe579832015-11-10 22:34:18 +01001282 rtc::Optional<CodecInst> ci = acm2::RentACodec::CodecInstByParams(
turaj@webrtc.org6d5d2482013-10-06 04:47:28 +00001283 payload_name, sampling_freq_hz, channels);
kwibergfce4a942015-10-27 11:40:24 -07001284 if (ci) {
1285 *codec = *ci;
1286 return 0;
1287 } else {
1288 // We couldn't find a matching codec, so set the parameters to unacceptable
turaj@webrtc.org7959e162013-09-12 18:30:26 +00001289 // values and return.
1290 codec->plname[0] = '\0';
1291 codec->pltype = -1;
1292 codec->pacsize = 0;
1293 codec->rate = 0;
1294 codec->plfreq = 0;
1295 return -1;
1296 }
turaj@webrtc.org7959e162013-09-12 18:30:26 +00001297}
1298
turaj@webrtc.org7959e162013-09-12 18:30:26 +00001299int AudioCodingModule::Codec(const char* payload_name,
1300 int sampling_freq_hz,
Peter Kasting69558702016-01-12 16:26:35 -08001301 size_t channels) {
Karl Wibergbe579832015-11-10 22:34:18 +01001302 rtc::Optional<acm2::RentACodec::CodecId> ci =
1303 acm2::RentACodec::CodecIdByParams(payload_name, sampling_freq_hz,
1304 channels);
kwibergfce4a942015-10-27 11:40:24 -07001305 if (!ci)
1306 return -1;
Karl Wibergbe579832015-11-10 22:34:18 +01001307 rtc::Optional<int> i = acm2::RentACodec::CodecIndexFromId(*ci);
kwibergfce4a942015-10-27 11:40:24 -07001308 return i ? *i : -1;
turaj@webrtc.org7959e162013-09-12 18:30:26 +00001309}
1310
1311// Checks the validity of the parameters of the given codec
1312bool AudioCodingModule::IsCodecValid(const CodecInst& codec) {
kwibergfce4a942015-10-27 11:40:24 -07001313 bool valid = acm2::RentACodec::IsCodecValid(codec);
1314 if (!valid)
Mirko Bonadei675513b2017-11-09 11:09:25 +01001315 RTC_LOG(LS_ERROR) << "Invalid codec setting";
kwibergfce4a942015-10-27 11:40:24 -07001316 return valid;
turaj@webrtc.org7959e162013-09-12 18:30:26 +00001317}
1318
turaj@webrtc.org7959e162013-09-12 18:30:26 +00001319} // namespace webrtc