2 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
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.
11 #include "webrtc/modules/audio_coding/main/acm2/acm_generic_codec.h"
16 #include "webrtc/common_audio/vad/include/webrtc_vad.h"
17 #include "webrtc/modules/audio_coding/codecs/cng/include/webrtc_cng.h"
18 #include "webrtc/modules/audio_coding/main/acm2/acm_codec_database.h"
19 #include "webrtc/modules/audio_coding/main/acm2/acm_common_defs.h"
20 #include "webrtc/system_wrappers/interface/trace.h"
28 kMaxPLCParamsCNG = WEBRTC_CNG_MAX_LPC_ORDER,
29 kNewCNGNumLPCParams = 8
32 // Interval for sending new CNG parameters (SID frames) is 100 msec.
34 kCngSidIntervalMsec = 100
37 // We set some of the variables to invalid values as a check point
38 // if a proper initialization has happened. Another approach is
39 // to initialize to a default codec that we are sure is always included.
40 ACMGenericCodec::ACMGenericCodec()
41 : in_audio_ix_write_(0),
43 in_timestamp_ix_write_(0),
46 frame_len_smpl_(-1), // invalid value
48 codec_id_(-1), // invalid value
49 num_missed_samples_(0),
50 encoder_exist_(false),
51 encoder_initialized_(false),
52 registered_in_neteq_(false),
53 has_internal_dtx_(false),
59 num_lpc_params_(kNewCNGNumLPCParams),
60 sent_cn_previous_(false),
62 has_internal_fec_(false),
63 codec_wrapper_lock_(*RWLockWrapper::CreateRWLock()),
64 last_timestamp_(0xD87F3F9F),
66 // Initialize VAD vector.
67 for (int i = 0; i < MAX_FRAME_SIZE_10MSEC; i++) {
70 // Nullify memory for encoder and decoder, and set payload type to an
72 memset(&encoder_params_, 0, sizeof(WebRtcACMCodecParams));
73 encoder_params_.codec_inst.pltype = -1;
76 ACMGenericCodec::~ACMGenericCodec() {
77 // Check all the members which are pointers, and if they are not NULL
79 if (ptr_vad_inst_ != NULL) {
80 WebRtcVad_Free(ptr_vad_inst_);
83 if (in_audio_ != NULL) {
87 if (in_timestamp_ != NULL) {
88 delete[] in_timestamp_;
91 if (ptr_dtx_inst_ != NULL) {
92 WebRtcCng_FreeEnc(ptr_dtx_inst_);
95 delete &codec_wrapper_lock_;
98 int32_t ACMGenericCodec::Add10MsData(const uint32_t timestamp,
100 const uint16_t length_smpl,
101 const uint8_t audio_channel) {
102 WriteLockScoped wl(codec_wrapper_lock_);
103 return Add10MsDataSafe(timestamp, data, length_smpl, audio_channel);
106 int32_t ACMGenericCodec::Add10MsDataSafe(const uint32_t timestamp,
108 const uint16_t length_smpl,
109 const uint8_t audio_channel) {
110 // The codec expects to get data in correct sampling rate. Get the sampling
111 // frequency of the codec.
113 if (EncoderSampFreq(&plfreq_hz) < 0) {
117 // Sanity check to make sure the length of the input corresponds to 10 ms.
118 if ((plfreq_hz / 100) != length_smpl) {
119 // This is not 10 ms of audio, given the sampling frequency of the codec.
123 if (last_timestamp_ == timestamp) {
124 // Same timestamp as the last time, overwrite.
125 if ((in_audio_ix_write_ >= length_smpl * audio_channel) &&
126 (in_timestamp_ix_write_ > 0)) {
127 in_audio_ix_write_ -= length_smpl * audio_channel;
128 assert(in_timestamp_ix_write_ >= 0);
130 in_timestamp_ix_write_--;
131 assert(in_audio_ix_write_ >= 0);
132 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceAudioCoding, unique_id_,
133 "Adding 10ms with previous timestamp, overwriting the "
136 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceAudioCoding, unique_id_,
137 "Adding 10ms with previous timestamp, this will sound bad");
141 last_timestamp_ = timestamp;
143 // If the data exceeds the buffer size, we throw away the oldest data and
144 // add the newly received 10 msec at the end.
145 if ((in_audio_ix_write_ + length_smpl * audio_channel) >
146 AUDIO_BUFFER_SIZE_W16) {
147 // Get the number of samples to be overwritten.
148 int16_t missed_samples = in_audio_ix_write_ + length_smpl * audio_channel -
149 AUDIO_BUFFER_SIZE_W16;
151 // Move the data (overwrite the old data).
152 memmove(in_audio_, in_audio_ + missed_samples,
153 (AUDIO_BUFFER_SIZE_W16 - length_smpl * audio_channel) *
156 // Copy the new data.
157 memcpy(in_audio_ + (AUDIO_BUFFER_SIZE_W16 - length_smpl * audio_channel),
158 data, length_smpl * audio_channel * sizeof(int16_t));
160 // Get the number of 10 ms blocks which are overwritten.
161 int16_t missed_10ms_blocks =static_cast<int16_t>(
162 (missed_samples / audio_channel * 100) / plfreq_hz);
164 // Move the timestamps.
165 memmove(in_timestamp_, in_timestamp_ + missed_10ms_blocks,
166 (in_timestamp_ix_write_ - missed_10ms_blocks) * sizeof(uint32_t));
167 in_timestamp_ix_write_ -= missed_10ms_blocks;
168 assert(in_timestamp_ix_write_ >= 0);
170 in_timestamp_[in_timestamp_ix_write_] = timestamp;
171 in_timestamp_ix_write_++;
172 assert(in_timestamp_ix_write_ < TIMESTAMP_BUFFER_SIZE_W32);
175 in_audio_ix_write_ = AUDIO_BUFFER_SIZE_W16;
176 IncreaseNoMissedSamples(missed_samples);
177 return -missed_samples;
180 // Store the input data in our data buffer.
181 memcpy(in_audio_ + in_audio_ix_write_, data,
182 length_smpl * audio_channel * sizeof(int16_t));
183 in_audio_ix_write_ += length_smpl * audio_channel;
184 assert(in_timestamp_ix_write_ < TIMESTAMP_BUFFER_SIZE_W32);
186 in_timestamp_[in_timestamp_ix_write_] = timestamp;
187 in_timestamp_ix_write_++;
188 assert(in_timestamp_ix_write_ < TIMESTAMP_BUFFER_SIZE_W32);
192 bool ACMGenericCodec::HasFrameToEncode() const {
193 ReadLockScoped lockCodec(codec_wrapper_lock_);
194 if (in_audio_ix_write_ < frame_len_smpl_ * num_channels_)
199 int ACMGenericCodec::SetFEC(bool enable_fec) {
200 if (!HasInternalFEC() && enable_fec)
205 int16_t ACMGenericCodec::Encode(uint8_t* bitstream,
206 int16_t* bitstream_len_byte,
208 WebRtcACMEncodingType* encoding_type) {
209 if (!HasFrameToEncode()) {
210 // There is not enough audio
212 *bitstream_len_byte = 0;
213 // Doesn't really matter what this parameter set to
214 *encoding_type = kNoEncoding;
217 WriteLockScoped lockCodec(codec_wrapper_lock_);
219 // Not all codecs accept the whole frame to be pushed into encoder at once.
220 // Some codecs needs to be feed with a specific number of samples different
221 // from the frame size. If this is the case, |myBasicCodingBlockSmpl| will
222 // report a number different from 0, and we will loop over calls to encoder
223 // further down, until we have encode a complete frame.
224 const int16_t my_basic_coding_block_smpl =
225 ACMCodecDB::BasicCodingBlock(codec_id_);
226 if (my_basic_coding_block_smpl < 0 || !encoder_initialized_ ||
228 // This should not happen, but in case it does, report no encoding done.
230 *bitstream_len_byte = 0;
231 *encoding_type = kNoEncoding;
232 WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceAudioCoding, unique_id_,
233 "EncodeSafe: error, basic coding sample block is negative");
236 // This makes the internal encoder read from the beginning of the buffer.
237 in_audio_ix_read_ = 0;
238 *timestamp = in_timestamp_[0];
240 // Process the audio through VAD. The function will set |_vad_labels|.
241 // If VAD is disabled all entries in |_vad_labels| are set to ONE (active).
243 int16_t dtx_processed_samples = 0;
244 status = ProcessFrameVADDTX(bitstream, bitstream_len_byte,
245 &dtx_processed_samples);
248 *bitstream_len_byte = 0;
249 *encoding_type = kNoEncoding;
251 if (dtx_processed_samples > 0) {
252 // Dtx have processed some samples, and even if a bit-stream is generated
253 // we should not do any encoding (normally there won't be enough data).
255 // Setting the following makes sure that the move of audio data and
256 // timestamps done correctly.
257 in_audio_ix_read_ = dtx_processed_samples;
258 // This will let the owner of ACMGenericCodec to know that the
259 // generated bit-stream is DTX to use correct payload type.
260 uint16_t samp_freq_hz;
261 EncoderSampFreq(&samp_freq_hz);
262 if (samp_freq_hz == 8000) {
263 *encoding_type = kPassiveDTXNB;
264 } else if (samp_freq_hz == 16000) {
265 *encoding_type = kPassiveDTXWB;
266 } else if (samp_freq_hz == 32000) {
267 *encoding_type = kPassiveDTXSWB;
268 } else if (samp_freq_hz == 48000) {
269 *encoding_type = kPassiveDTXFB;
272 WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceAudioCoding, unique_id_,
273 "EncodeSafe: Wrong sampling frequency for DTX.");
276 // Transport empty frame if we have an empty bitstream.
277 if ((*bitstream_len_byte == 0) &&
278 (sent_cn_previous_ ||
279 ((in_audio_ix_write_ - in_audio_ix_read_) <= 0))) {
280 // Makes sure we transmit an empty frame.
281 *bitstream_len_byte = 1;
282 *encoding_type = kNoEncoding;
284 sent_cn_previous_ = true;
286 // We should encode the audio frame. Either VAD and/or DTX is off, or the
287 // audio was considered "active".
289 sent_cn_previous_ = false;
290 if (my_basic_coding_block_smpl == 0) {
291 // This codec can handle all allowed frame sizes as basic coding block.
292 status = InternalEncode(bitstream, bitstream_len_byte);
294 // TODO(tlegrand): Maybe reseting the encoder to be fresh for the next
296 WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceAudioCoding,
297 unique_id_, "EncodeSafe: error in internal_encode");
298 *bitstream_len_byte = 0;
299 *encoding_type = kNoEncoding;
302 // A basic-coding-block for this codec is defined so we loop over the
303 // audio with the steps of the basic-coding-block.
304 int16_t tmp_bitstream_len_byte;
306 // Reset the variables which will be incremented in the loop.
307 *bitstream_len_byte = 0;
310 status = InternalEncode(&bitstream[*bitstream_len_byte],
311 &tmp_bitstream_len_byte);
312 *bitstream_len_byte += tmp_bitstream_len_byte;
314 // Guard Against errors and too large payloads.
315 if ((status < 0) || (*bitstream_len_byte > MAX_PAYLOAD_SIZE_BYTE)) {
316 // Error has happened, and even if we are in the middle of a full
317 // frame we have to exit. Before exiting, whatever bits are in the
318 // buffer are probably corrupted, so we ignore them.
319 *bitstream_len_byte = 0;
320 *encoding_type = kNoEncoding;
321 // We might have come here because of the second condition.
323 WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceAudioCoding,
324 unique_id_, "EncodeSafe: error in InternalEncode");
325 // break from the loop
328 done = in_audio_ix_read_ >= frame_len_smpl_ * num_channels_;
332 *encoding_type = (vad_label_[0] == 1) ? kActiveNormalEncoded :
333 kPassiveNormalEncoded;
334 // Transport empty frame if we have an empty bitstream.
335 if ((*bitstream_len_byte == 0) &&
336 ((in_audio_ix_write_ - in_audio_ix_read_) <= 0)) {
337 // Makes sure we transmit an empty frame.
338 *bitstream_len_byte = 1;
339 *encoding_type = kNoEncoding;
345 // Move the timestamp buffer according to the number of 10 ms blocks
347 uint16_t samp_freq_hz;
348 EncoderSampFreq(&samp_freq_hz);
349 int16_t num_10ms_blocks = static_cast<int16_t>(
350 (in_audio_ix_read_ / num_channels_ * 100) / samp_freq_hz);
351 if (in_timestamp_ix_write_ > num_10ms_blocks) {
352 memmove(in_timestamp_, in_timestamp_ + num_10ms_blocks,
353 (in_timestamp_ix_write_ - num_10ms_blocks) * sizeof(int32_t));
355 in_timestamp_ix_write_ -= num_10ms_blocks;
356 assert(in_timestamp_ix_write_ >= 0);
358 // Remove encoded audio and move next audio to be encoded to the beginning
359 // of the buffer. Accordingly, adjust the read and write indices.
360 if (in_audio_ix_read_ < in_audio_ix_write_) {
361 memmove(in_audio_, &in_audio_[in_audio_ix_read_],
362 (in_audio_ix_write_ - in_audio_ix_read_) * sizeof(int16_t));
364 in_audio_ix_write_ -= in_audio_ix_read_;
365 in_audio_ix_read_ = 0;
366 return (status < 0) ? (-1) : (*bitstream_len_byte);
369 bool ACMGenericCodec::EncoderInitialized() {
370 ReadLockScoped rl(codec_wrapper_lock_);
371 return encoder_initialized_;
374 int16_t ACMGenericCodec::EncoderParams(WebRtcACMCodecParams* enc_params) {
375 ReadLockScoped rl(codec_wrapper_lock_);
376 return EncoderParamsSafe(enc_params);
379 int16_t ACMGenericCodec::EncoderParamsSafe(WebRtcACMCodecParams* enc_params) {
380 // Codec parameters are valid only if the encoder is initialized.
381 if (encoder_initialized_) {
382 int32_t current_rate;
383 memcpy(enc_params, &encoder_params_, sizeof(WebRtcACMCodecParams));
384 current_rate = enc_params->codec_inst.rate;
385 CurrentRate(¤t_rate);
386 enc_params->codec_inst.rate = current_rate;
389 enc_params->codec_inst.plname[0] = '\0';
390 enc_params->codec_inst.pltype = -1;
391 enc_params->codec_inst.pacsize = 0;
392 enc_params->codec_inst.rate = 0;
393 WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceAudioCoding, unique_id_,
394 "EncoderParamsSafe: error, encoder not initialized");
399 int16_t ACMGenericCodec::ResetEncoder() {
400 WriteLockScoped lockCodec(codec_wrapper_lock_);
401 return ResetEncoderSafe();
404 int16_t ACMGenericCodec::ResetEncoderSafe() {
405 if (!encoder_exist_ || !encoder_initialized_) {
406 // We don't reset if encoder doesn't exists or isn't initialized yet.
410 in_audio_ix_write_ = 0;
411 in_audio_ix_read_ = 0;
412 in_timestamp_ix_write_ = 0;
413 num_missed_samples_ = 0;
414 memset(in_audio_, 0, AUDIO_BUFFER_SIZE_W16 * sizeof(int16_t));
415 memset(in_timestamp_, 0, TIMESTAMP_BUFFER_SIZE_W32 * sizeof(int32_t));
417 // Store DTX/VAD parameters.
418 bool enable_vad = vad_enabled_;
419 bool enable_dtx = dtx_enabled_;
420 ACMVADMode mode = vad_mode_;
422 // Reset the encoder.
423 if (InternalResetEncoder() < 0) {
424 WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceAudioCoding, unique_id_,
425 "ResetEncoderSafe: error in reset encoder");
429 // Disable DTX & VAD to delete the states and have a fresh start.
434 int status = SetVADSafe(&enable_dtx, &enable_vad, &mode);
435 dtx_enabled_ = enable_dtx;
436 vad_enabled_ = enable_vad;
441 int16_t ACMGenericCodec::InternalResetEncoder() {
442 // Call the codecs internal encoder initialization/reset function.
443 return InternalInitEncoder(&encoder_params_);
446 int16_t ACMGenericCodec::InitEncoder(WebRtcACMCodecParams* codec_params,
447 bool force_initialization) {
448 WriteLockScoped lockCodec(codec_wrapper_lock_);
449 return InitEncoderSafe(codec_params, force_initialization);
452 int16_t ACMGenericCodec::InitEncoderSafe(WebRtcACMCodecParams* codec_params,
453 bool force_initialization) {
454 // Check if we got a valid set of parameters.
456 int codec_number = ACMCodecDB::CodecNumber(codec_params->codec_inst,
458 assert(codec_number >= 0);
460 // Check if the parameters are for this codec.
461 if ((codec_id_ >= 0) && (codec_id_ != codec_number) &&
462 (codec_id_ != mirrorID)) {
463 // The current codec is not the same as the one given by codec_params.
464 WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceAudioCoding, unique_id_,
465 "InitEncoderSafe: current codec is not the same as the one "
466 "given by codec_params");
470 if (encoder_initialized_ && !force_initialization) {
471 // The encoder is already initialized, and we don't want to force
476 if (!encoder_exist_) {
477 // New encoder, start with creating.
478 encoder_initialized_ = false;
479 status = CreateEncoder();
481 WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceAudioCoding, unique_id_,
482 "InitEncoderSafe: cannot create encoder");
485 encoder_exist_ = true;
488 frame_len_smpl_ = codec_params->codec_inst.pacsize;
489 num_channels_ = codec_params->codec_inst.channels;
490 status = InternalInitEncoder(codec_params);
492 WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceAudioCoding, unique_id_,
493 "InitEncoderSafe: error in init encoder");
494 encoder_initialized_ = false;
497 // TODO(turajs): Move these allocations to the constructor issue 2445.
498 // Store encoder parameters.
499 memcpy(&encoder_params_, codec_params, sizeof(WebRtcACMCodecParams));
500 encoder_initialized_ = true;
501 if (in_audio_ == NULL) {
502 in_audio_ = new int16_t[AUDIO_BUFFER_SIZE_W16];
504 if (in_timestamp_ == NULL) {
505 in_timestamp_ = new uint32_t[TIMESTAMP_BUFFER_SIZE_W32];
509 // Fresh start of audio buffer.
510 memset(in_audio_, 0, sizeof(*in_audio_) * AUDIO_BUFFER_SIZE_W16);
511 memset(in_timestamp_, 0, sizeof(*in_timestamp_) * TIMESTAMP_BUFFER_SIZE_W32);
512 in_audio_ix_write_ = 0;
513 in_audio_ix_read_ = 0;
514 in_timestamp_ix_write_ = 0;
516 return SetVADSafe(&codec_params->enable_dtx, &codec_params->enable_vad,
517 &codec_params->vad_mode);
520 void ACMGenericCodec::ResetNoMissedSamples() {
521 WriteLockScoped cs(codec_wrapper_lock_);
522 num_missed_samples_ = 0;
525 void ACMGenericCodec::IncreaseNoMissedSamples(const int16_t num_samples) {
526 num_missed_samples_ += num_samples;
529 // Get the number of missed samples, this can be public.
530 uint32_t ACMGenericCodec::NoMissedSamples() const {
531 ReadLockScoped cs(codec_wrapper_lock_);
532 return num_missed_samples_;
535 void ACMGenericCodec::DestructEncoder() {
536 WriteLockScoped wl(codec_wrapper_lock_);
538 // Disable VAD and delete the instance.
539 if (ptr_vad_inst_ != NULL) {
540 WebRtcVad_Free(ptr_vad_inst_);
541 ptr_vad_inst_ = NULL;
543 vad_enabled_ = false;
544 vad_mode_ = VADNormal;
546 // Disable DTX and delete the instance.
547 dtx_enabled_ = false;
548 if (ptr_dtx_inst_ != NULL) {
549 WebRtcCng_FreeEnc(ptr_dtx_inst_);
550 ptr_dtx_inst_ = NULL;
552 num_lpc_params_ = kNewCNGNumLPCParams;
554 DestructEncoderSafe();
557 int16_t ACMGenericCodec::SetBitRate(const int32_t bitrate_bps) {
558 WriteLockScoped wl(codec_wrapper_lock_);
559 return SetBitRateSafe(bitrate_bps);
562 int16_t ACMGenericCodec::SetBitRateSafe(const int32_t bitrate_bps) {
563 // If the codec can change the bit-rate this function is overloaded.
564 // Otherwise the only acceptable value is the one that is in the database.
565 CodecInst codec_params;
566 if (ACMCodecDB::Codec(codec_id_, &codec_params) < 0) {
567 WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceAudioCoding, unique_id_,
568 "SetBitRateSafe: error in ACMCodecDB::Codec");
571 if (codec_params.rate != bitrate_bps) {
572 WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceAudioCoding, unique_id_,
573 "SetBitRateSafe: rate value is not acceptable");
580 // iSAC specific functions:
581 int32_t ACMGenericCodec::GetEstimatedBandwidth() {
582 WriteLockScoped wl(codec_wrapper_lock_);
583 return GetEstimatedBandwidthSafe();
586 int32_t ACMGenericCodec::GetEstimatedBandwidthSafe() {
587 // All codecs but iSAC will return -1.
591 int32_t ACMGenericCodec::SetEstimatedBandwidth(int32_t estimated_bandwidth) {
592 WriteLockScoped wl(codec_wrapper_lock_);
593 return SetEstimatedBandwidthSafe(estimated_bandwidth);
596 int32_t ACMGenericCodec::SetEstimatedBandwidthSafe(
597 int32_t /*estimated_bandwidth*/) {
598 // All codecs but iSAC will return -1.
601 // End of iSAC specific functions.
603 int32_t ACMGenericCodec::GetRedPayload(uint8_t* red_payload,
604 int16_t* payload_bytes) {
605 WriteLockScoped wl(codec_wrapper_lock_);
606 return GetRedPayloadSafe(red_payload, payload_bytes);
609 int32_t ACMGenericCodec::GetRedPayloadSafe(uint8_t* /* red_payload */,
610 int16_t* /* payload_bytes */) {
611 return -1; // Do nothing by default.
614 int16_t ACMGenericCodec::CreateEncoder() {
616 if (!encoder_exist_) {
617 status = InternalCreateEncoder();
618 // We just created the codec and obviously it is not initialized.
619 encoder_initialized_ = false;
622 WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceAudioCoding, unique_id_,
623 "CreateEncoder: error in internal create encoder");
624 encoder_exist_ = false;
626 encoder_exist_ = true;
631 uint32_t ACMGenericCodec::EarliestTimestamp() const {
632 ReadLockScoped cs(codec_wrapper_lock_);
633 return in_timestamp_[0];
636 int16_t ACMGenericCodec::SetVAD(bool* enable_dtx,
639 WriteLockScoped cs(codec_wrapper_lock_);
640 return SetVADSafe(enable_dtx, enable_vad, mode);
643 int16_t ACMGenericCodec::SetVADSafe(bool* enable_dtx,
646 if (!STR_CASE_CMP(encoder_params_.codec_inst.plname, "OPUS") ||
647 encoder_params_.codec_inst.channels == 2 ) {
648 // VAD/DTX is not supported for Opus (even if sending mono), or other
658 // Make G729 AnnexB a special case.
659 if (!STR_CASE_CMP(encoder_params_.codec_inst.plname, "G729")
660 && !has_internal_dtx_) {
661 if (ACMGenericCodec::EnableDTX() < 0) {
662 WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceAudioCoding, unique_id_,
663 "SetVADSafe: error in enable DTX");
665 *enable_vad = vad_enabled_;
669 if (EnableDTX() < 0) {
670 WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceAudioCoding, unique_id_,
671 "SetVADSafe: error in enable DTX");
673 *enable_vad = vad_enabled_;
678 // If codec does not have internal DTX (normal case) enabling DTX requires
679 // an active VAD. '*enable_dtx == true' overwrites VAD status.
680 // If codec has internal DTX, practically we don't need WebRtc VAD, however,
681 // we let the user to turn it on if they need call-backs on silence.
682 if (!has_internal_dtx_) {
683 // DTX is enabled, and VAD will be activated.
687 // Make G729 AnnexB a special case.
688 if (!STR_CASE_CMP(encoder_params_.codec_inst.plname, "G729")
689 && !has_internal_dtx_) {
690 ACMGenericCodec::DisableDTX();
698 int16_t status = (*enable_vad) ? EnableVAD(*mode) : DisableVAD();
700 // Failed to set VAD, disable DTX.
701 WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceAudioCoding, unique_id_,
702 "SetVADSafe: error in enable VAD");
710 int16_t ACMGenericCodec::EnableDTX() {
711 if (has_internal_dtx_) {
712 // We should not be here if we have internal DTX this function should be
713 // overloaded by the derived class in this case.
717 if (WebRtcCng_CreateEnc(&ptr_dtx_inst_) < 0) {
718 ptr_dtx_inst_ = NULL;
722 EncoderSampFreq(&freq_hz);
723 if (WebRtcCng_InitEnc(ptr_dtx_inst_, freq_hz, kCngSidIntervalMsec,
724 num_lpc_params_) < 0) {
725 // Couldn't initialize, has to return -1, and free the memory.
726 WebRtcCng_FreeEnc(ptr_dtx_inst_);
727 ptr_dtx_inst_ = NULL;
735 int16_t ACMGenericCodec::DisableDTX() {
736 if (has_internal_dtx_) {
737 // We should not be here if we have internal DTX this function should be
738 // overloaded by the derived class in this case.
741 if (ptr_dtx_inst_ != NULL) {
742 WebRtcCng_FreeEnc(ptr_dtx_inst_);
743 ptr_dtx_inst_ = NULL;
745 dtx_enabled_ = false;
749 int16_t ACMGenericCodec::EnableVAD(ACMVADMode mode) {
750 if ((mode < VADNormal) || (mode > VADVeryAggr)) {
751 WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceAudioCoding, unique_id_,
752 "EnableVAD: error in VAD mode range");
757 if (WebRtcVad_Create(&ptr_vad_inst_) < 0) {
758 ptr_vad_inst_ = NULL;
759 WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceAudioCoding, unique_id_,
760 "EnableVAD: error in create VAD");
763 if (WebRtcVad_Init(ptr_vad_inst_) < 0) {
764 WebRtcVad_Free(ptr_vad_inst_);
765 ptr_vad_inst_ = NULL;
766 WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceAudioCoding, unique_id_,
767 "EnableVAD: error in init VAD");
772 // Set the VAD mode to the given value.
773 if (WebRtcVad_set_mode(ptr_vad_inst_, mode) < 0) {
774 // We failed to set the mode and we have to return -1. If we already have a
775 // working VAD (vad_enabled_ == true) then we leave it to work. Otherwise,
776 // the following will be executed.
778 // We just created the instance but cannot set the mode we have to free
780 WebRtcVad_Free(ptr_vad_inst_);
781 ptr_vad_inst_ = NULL;
783 WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceAudioCoding, unique_id_,
784 "EnableVAD: failed to set the VAD mode");
792 int16_t ACMGenericCodec::DisableVAD() {
793 if (ptr_vad_inst_ != NULL) {
794 WebRtcVad_Free(ptr_vad_inst_);
795 ptr_vad_inst_ = NULL;
797 vad_enabled_ = false;
801 int32_t ACMGenericCodec::ReplaceInternalDTX(const bool replace_internal_dtx) {
802 WriteLockScoped cs(codec_wrapper_lock_);
803 return ReplaceInternalDTXSafe(replace_internal_dtx);
806 int32_t ACMGenericCodec::ReplaceInternalDTXSafe(
807 const bool /* replace_internal_dtx */) {
811 int32_t ACMGenericCodec::IsInternalDTXReplaced(bool* internal_dtx_replaced) {
812 WriteLockScoped cs(codec_wrapper_lock_);
813 return IsInternalDTXReplacedSafe(internal_dtx_replaced);
816 int32_t ACMGenericCodec::IsInternalDTXReplacedSafe(
817 bool* internal_dtx_replaced) {
818 *internal_dtx_replaced = false;
822 int16_t ACMGenericCodec::ProcessFrameVADDTX(uint8_t* bitstream,
823 int16_t* bitstream_len_byte,
824 int16_t* samples_processed) {
826 // VAD not enabled, set all |vad_lable_[]| to 1 (speech detected).
827 for (int n = 0; n < MAX_FRAME_SIZE_10MSEC; n++) {
830 *samples_processed = 0;
835 EncoderSampFreq(&freq_hz);
837 // Calculate number of samples in 10 ms blocks, and number ms in one frame.
838 int16_t samples_in_10ms = static_cast<int16_t>(freq_hz / 100);
839 int32_t frame_len_ms = static_cast<int32_t>(frame_len_smpl_) * 1000 / freq_hz;
842 // Vector for storing maximum 30 ms of mono audio at 48 kHz.
845 // Calculate number of VAD-blocks to process, and number of samples in each
847 int num_samples_to_process[2];
848 if (frame_len_ms == 40) {
849 // 20 ms in each VAD block.
850 num_samples_to_process[0] = num_samples_to_process[1] = 2 * samples_in_10ms;
852 // For 10-30 ms framesizes, second VAD block will be size zero ms,
853 // for 50 and 60 ms first VAD block will be 30 ms.
854 num_samples_to_process[0] =
855 (frame_len_ms > 30) ? 3 * samples_in_10ms : frame_len_smpl_;
856 num_samples_to_process[1] = frame_len_smpl_ - num_samples_to_process[0];
860 int loops = (num_samples_to_process[1] > 0) ? 2 : 1;
861 for (int i = 0; i < loops; i++) {
862 // TODO(turajs): Do we need to care about VAD together with stereo?
863 // If stereo, calculate mean of the two channels.
864 if (num_channels_ == 2) {
865 for (int j = 0; j < num_samples_to_process[i]; j++) {
866 audio[j] = (in_audio_[(offset + j) * 2] +
867 in_audio_[(offset + j) * 2 + 1]) / 2;
869 offset = num_samples_to_process[0];
871 // Mono, copy data from in_audio_ to continue work on.
872 memcpy(audio, in_audio_, sizeof(int16_t) * num_samples_to_process[i]);
876 status = static_cast<int16_t>(WebRtcVad_Process(ptr_vad_inst_,
877 static_cast<int>(freq_hz),
879 num_samples_to_process[i]));
880 vad_label_[i] = status;
883 // This will force that the data be removed from the buffer.
884 *samples_processed += num_samples_to_process[i];
888 // If VAD decision non-active, update DTX. NOTE! We only do this if the
889 // first part of a frame gets the VAD decision "inactive". Otherwise DTX
890 // might say it is time to transmit SID frame, but we will encode the whole
891 // frame, because the first part is active.
892 *samples_processed = 0;
893 if ((status == 0) && (i == 0) && dtx_enabled_ && !has_internal_dtx_) {
894 int16_t bitstream_len;
895 int num_10ms_frames = num_samples_to_process[i] / samples_in_10ms;
896 *bitstream_len_byte = 0;
897 for (int n = 0; n < num_10ms_frames; n++) {
898 // This block is (passive) && (vad enabled). If first CNG after
899 // speech, force SID by setting last parameter to "1".
900 status = WebRtcCng_Encode(ptr_dtx_inst_, &audio[n * samples_in_10ms],
901 samples_in_10ms, bitstream, &bitstream_len,
907 // Update previous frame was CNG.
910 *samples_processed += samples_in_10ms * num_channels_;
912 // |bitstream_len_byte| will only be > 0 once per 100 ms.
913 *bitstream_len_byte += bitstream_len;
916 // Check if all samples got processed by the DTX.
917 if (*samples_processed != num_samples_to_process[i] * num_channels_) {
918 // Set to zero since something went wrong. Shouldn't happen.
919 *samples_processed = 0;
922 // Update previous frame was not CNG.
926 if (*samples_processed > 0) {
927 // The block contains inactive speech, and is processed by DTX.
928 // Discontinue running VAD.
936 int16_t ACMGenericCodec::SamplesLeftToEncode() {
937 ReadLockScoped rl(codec_wrapper_lock_);
938 return (frame_len_smpl_ <= in_audio_ix_write_) ? 0 :
939 (frame_len_smpl_ - in_audio_ix_write_);
942 void ACMGenericCodec::SetUniqueID(const uint32_t id) {
946 // This function is replaced by codec specific functions for some codecs.
947 int16_t ACMGenericCodec::EncoderSampFreq(uint16_t* samp_freq_hz) {
949 f = ACMCodecDB::CodecFreq(codec_id_);
951 WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceAudioCoding, unique_id_,
952 "EncoderSampFreq: codec frequency is negative");
955 *samp_freq_hz = static_cast<uint16_t>(f);
960 int32_t ACMGenericCodec::ConfigISACBandwidthEstimator(
961 const uint8_t /* init_frame_size_msec */,
962 const uint16_t /* init_rate_bit_per_sec */,
963 const bool /* enforce_frame_size */) {
964 WEBRTC_TRACE(webrtc::kTraceWarning, webrtc::kTraceAudioCoding, unique_id_,
965 "The send-codec is not iSAC, failed to config iSAC bandwidth "
970 int32_t ACMGenericCodec::SetISACMaxRate(
971 const uint32_t /* max_rate_bit_per_sec */) {
972 WEBRTC_TRACE(webrtc::kTraceWarning, webrtc::kTraceAudioCoding, unique_id_,
973 "The send-codec is not iSAC, failed to set iSAC max rate.");
977 int32_t ACMGenericCodec::SetISACMaxPayloadSize(
978 const uint16_t /* max_payload_len_bytes */) {
979 WEBRTC_TRACE(webrtc::kTraceWarning, webrtc::kTraceAudioCoding, unique_id_,
980 "The send-codec is not iSAC, failed to set iSAC max "
985 int16_t ACMGenericCodec::UpdateEncoderSampFreq(
986 uint16_t /* samp_freq_hz */) {
987 WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceAudioCoding, unique_id_,
988 "It is asked for a change in smapling frequency while the "
989 "current send-codec supports only one sampling rate.");
993 int16_t ACMGenericCodec::REDPayloadISAC(const int32_t /* isac_rate */,
994 const int16_t /* isac_bw_estimate */,
995 uint8_t* /* payload */,
996 int16_t* /* payload_len_bytes */) {
997 WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceAudioCoding, unique_id_,
998 "Error: REDPayloadISAC is an iSAC specific function");
1002 int ACMGenericCodec::SetOpusMaxPlaybackRate(int /* frequency_hz */) {
1003 WEBRTC_TRACE(webrtc::kTraceWarning, webrtc::kTraceAudioCoding, unique_id_,
1004 "The send-codec is not Opus, failed to set maximum playback rate.");
1010 } // namespace webrtc