Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / third_party / webrtc / modules / audio_coding / main / acm2 / acm_generic_codec.cc
1 /*
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
11 #include "webrtc/modules/audio_coding/main/acm2/acm_generic_codec.h"
12
13 #include <assert.h>
14 #include <string.h>
15
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"
21
22 namespace webrtc {
23
24 namespace acm2 {
25
26 // Enum for CNG
27 enum {
28   kMaxPLCParamsCNG = WEBRTC_CNG_MAX_LPC_ORDER,
29   kNewCNGNumLPCParams = 8
30 };
31
32 // Interval for sending new CNG parameters (SID frames) is 100 msec.
33 enum {
34   kCngSidIntervalMsec = 100
35 };
36
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),
42       in_audio_ix_read_(0),
43       in_timestamp_ix_write_(0),
44       in_audio_(NULL),
45       in_timestamp_(NULL),
46       frame_len_smpl_(-1),  // invalid value
47       num_channels_(1),
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),
54       ptr_vad_inst_(NULL),
55       vad_enabled_(false),
56       vad_mode_(VADNormal),
57       dtx_enabled_(false),
58       ptr_dtx_inst_(NULL),
59       num_lpc_params_(kNewCNGNumLPCParams),
60       sent_cn_previous_(false),
61       prev_frame_cng_(0),
62       has_internal_fec_(false),
63       codec_wrapper_lock_(*RWLockWrapper::CreateRWLock()),
64       last_timestamp_(0xD87F3F9F),
65       unique_id_(0) {
66   // Initialize VAD vector.
67   for (int i = 0; i < MAX_FRAME_SIZE_10MSEC; i++) {
68     vad_label_[i] = 0;
69   }
70   // Nullify memory for encoder and decoder, and set payload type to an
71   // invalid value.
72   memset(&encoder_params_, 0, sizeof(WebRtcACMCodecParams));
73   encoder_params_.codec_inst.pltype = -1;
74 }
75
76 ACMGenericCodec::~ACMGenericCodec() {
77   // Check all the members which are pointers, and if they are not NULL
78   // delete/free them.
79   if (ptr_vad_inst_ != NULL) {
80     WebRtcVad_Free(ptr_vad_inst_);
81     ptr_vad_inst_ = NULL;
82   }
83   if (in_audio_ != NULL) {
84     delete[] in_audio_;
85     in_audio_ = NULL;
86   }
87   if (in_timestamp_ != NULL) {
88     delete[] in_timestamp_;
89     in_timestamp_ = NULL;
90   }
91   if (ptr_dtx_inst_ != NULL) {
92     WebRtcCng_FreeEnc(ptr_dtx_inst_);
93     ptr_dtx_inst_ = NULL;
94   }
95   delete &codec_wrapper_lock_;
96 }
97
98 int32_t ACMGenericCodec::Add10MsData(const uint32_t timestamp,
99                                      const int16_t* data,
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);
104 }
105
106 int32_t ACMGenericCodec::Add10MsDataSafe(const uint32_t timestamp,
107                                          const int16_t* data,
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.
112   uint16_t plfreq_hz;
113   if (EncoderSampFreq(&plfreq_hz) < 0) {
114     return -1;
115   }
116
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.
120     return -1;
121   }
122
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);
129
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 "
134                    "previous 10ms");
135     } else {
136       WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceAudioCoding, unique_id_,
137                    "Adding 10ms with previous timestamp, this will sound bad");
138     }
139   }
140
141   last_timestamp_ = timestamp;
142
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;
150
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) *
154             sizeof(int16_t));
155
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));
159
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);
163
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);
169
170     in_timestamp_[in_timestamp_ix_write_] = timestamp;
171     in_timestamp_ix_write_++;
172     assert(in_timestamp_ix_write_ < TIMESTAMP_BUFFER_SIZE_W32);
173
174     // Buffer is full.
175     in_audio_ix_write_ = AUDIO_BUFFER_SIZE_W16;
176     IncreaseNoMissedSamples(missed_samples);
177     return -missed_samples;
178   }
179
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);
185
186   in_timestamp_[in_timestamp_ix_write_] = timestamp;
187   in_timestamp_ix_write_++;
188   assert(in_timestamp_ix_write_ < TIMESTAMP_BUFFER_SIZE_W32);
189   return 0;
190 }
191
192 bool ACMGenericCodec::HasFrameToEncode() const {
193   ReadLockScoped lockCodec(codec_wrapper_lock_);
194   if (in_audio_ix_write_ < frame_len_smpl_ * num_channels_)
195     return false;
196   return true;
197 }
198
199 int ACMGenericCodec::SetFEC(bool enable_fec) {
200   if (!HasInternalFEC() && enable_fec)
201     return -1;
202   return 0;
203 }
204
205 int16_t ACMGenericCodec::Encode(uint8_t* bitstream,
206                                 int16_t* bitstream_len_byte,
207                                 uint32_t* timestamp,
208                                 WebRtcACMEncodingType* encoding_type) {
209   if (!HasFrameToEncode()) {
210     // There is not enough audio
211     *timestamp = 0;
212     *bitstream_len_byte = 0;
213     // Doesn't really matter what this parameter set to
214     *encoding_type = kNoEncoding;
215     return 0;
216   }
217   WriteLockScoped lockCodec(codec_wrapper_lock_);
218
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_ ||
227       !encoder_exist_) {
228     // This should not happen, but in case it does, report no encoding done.
229     *timestamp = 0;
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");
234     return -1;
235   }
236   // This makes the internal encoder read from the beginning of the buffer.
237   in_audio_ix_read_ = 0;
238   *timestamp = in_timestamp_[0];
239
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).
242   int16_t status = 0;
243   int16_t dtx_processed_samples = 0;
244   status = ProcessFrameVADDTX(bitstream, bitstream_len_byte,
245                               &dtx_processed_samples);
246   if (status < 0) {
247     *timestamp = 0;
248     *bitstream_len_byte = 0;
249     *encoding_type = kNoEncoding;
250   } else {
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).
254
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;
270       } else {
271         status = -1;
272         WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceAudioCoding, unique_id_,
273                      "EncodeSafe: Wrong sampling frequency for DTX.");
274       }
275
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;
283       }
284       sent_cn_previous_ = true;
285     } else {
286       // We should encode the audio frame. Either VAD and/or DTX is off, or the
287       // audio was considered "active".
288
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);
293         if (status < 0) {
294           // TODO(tlegrand): Maybe reseting the encoder to be fresh for the next
295           // frame.
296           WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceAudioCoding,
297                        unique_id_, "EncodeSafe: error in internal_encode");
298           *bitstream_len_byte = 0;
299           *encoding_type = kNoEncoding;
300         }
301       } else {
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;
305
306         // Reset the variables which will be incremented in the loop.
307         *bitstream_len_byte = 0;
308         bool done = false;
309         while (!done) {
310           status = InternalEncode(&bitstream[*bitstream_len_byte],
311                                   &tmp_bitstream_len_byte);
312           *bitstream_len_byte += tmp_bitstream_len_byte;
313
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.
322             status = -1;
323             WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceAudioCoding,
324                          unique_id_, "EncodeSafe: error in InternalEncode");
325             // break from the loop
326             break;
327           }
328           done = in_audio_ix_read_ >= frame_len_smpl_ * num_channels_;
329         }
330       }
331       if (status >= 0) {
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;
340         }
341       }
342     }
343   }
344
345   // Move the timestamp buffer according to the number of 10 ms blocks
346   // which are read.
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));
354   }
355   in_timestamp_ix_write_ -= num_10ms_blocks;
356   assert(in_timestamp_ix_write_ >= 0);
357
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));
363   }
364   in_audio_ix_write_ -= in_audio_ix_read_;
365   in_audio_ix_read_ = 0;
366   return (status < 0) ? (-1) : (*bitstream_len_byte);
367 }
368
369 bool ACMGenericCodec::EncoderInitialized() {
370   ReadLockScoped rl(codec_wrapper_lock_);
371   return encoder_initialized_;
372 }
373
374 int16_t ACMGenericCodec::EncoderParams(WebRtcACMCodecParams* enc_params) {
375   ReadLockScoped rl(codec_wrapper_lock_);
376   return EncoderParamsSafe(enc_params);
377 }
378
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(&current_rate);
386     enc_params->codec_inst.rate = current_rate;
387     return 0;
388   } else {
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");
395     return -1;
396   }
397 }
398
399 int16_t ACMGenericCodec::ResetEncoder() {
400   WriteLockScoped lockCodec(codec_wrapper_lock_);
401   return ResetEncoderSafe();
402 }
403
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.
407     return 0;
408   }
409
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));
416
417   // Store DTX/VAD parameters.
418   bool enable_vad = vad_enabled_;
419   bool enable_dtx = dtx_enabled_;
420   ACMVADMode mode = vad_mode_;
421
422   // Reset the encoder.
423   if (InternalResetEncoder() < 0) {
424     WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceAudioCoding, unique_id_,
425                  "ResetEncoderSafe: error in reset encoder");
426     return -1;
427   }
428
429   // Disable DTX & VAD to delete the states and have a fresh start.
430   DisableDTX();
431   DisableVAD();
432
433   // Set DTX/VAD.
434   int status = SetVADSafe(&enable_dtx, &enable_vad, &mode);
435   dtx_enabled_ = enable_dtx;
436   vad_enabled_ = enable_vad;
437   vad_mode_ = mode;
438   return status;
439 }
440
441 int16_t ACMGenericCodec::InternalResetEncoder() {
442   // Call the codecs internal encoder initialization/reset function.
443   return InternalInitEncoder(&encoder_params_);
444 }
445
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);
450 }
451
452 int16_t ACMGenericCodec::InitEncoderSafe(WebRtcACMCodecParams* codec_params,
453                                          bool force_initialization) {
454   // Check if we got a valid set of parameters.
455   int mirrorID;
456   int codec_number = ACMCodecDB::CodecNumber(codec_params->codec_inst,
457                                              &mirrorID);
458   assert(codec_number >= 0);
459
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");
467     return -1;
468   }
469
470   if (encoder_initialized_ && !force_initialization) {
471     // The encoder is already initialized, and we don't want to force
472     // initialization.
473     return 0;
474   }
475   int16_t status;
476   if (!encoder_exist_) {
477     // New encoder, start with creating.
478     encoder_initialized_ = false;
479     status = CreateEncoder();
480     if (status < 0) {
481       WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceAudioCoding, unique_id_,
482                    "InitEncoderSafe: cannot create encoder");
483       return -1;
484     } else {
485       encoder_exist_ = true;
486     }
487   }
488   frame_len_smpl_ = codec_params->codec_inst.pacsize;
489   num_channels_ = codec_params->codec_inst.channels;
490   status = InternalInitEncoder(codec_params);
491   if (status < 0) {
492     WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceAudioCoding, unique_id_,
493                  "InitEncoderSafe: error in init encoder");
494     encoder_initialized_ = false;
495     return -1;
496   } else {
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];
503     }
504     if (in_timestamp_ == NULL) {
505       in_timestamp_ = new uint32_t[TIMESTAMP_BUFFER_SIZE_W32];
506     }
507   }
508
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;
515
516   return SetVADSafe(&codec_params->enable_dtx, &codec_params->enable_vad,
517                     &codec_params->vad_mode);
518 }
519
520 void ACMGenericCodec::ResetNoMissedSamples() {
521   WriteLockScoped cs(codec_wrapper_lock_);
522   num_missed_samples_ = 0;
523 }
524
525 void ACMGenericCodec::IncreaseNoMissedSamples(const int16_t num_samples) {
526   num_missed_samples_ += num_samples;
527 }
528
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_;
533 }
534
535 void ACMGenericCodec::DestructEncoder() {
536   WriteLockScoped wl(codec_wrapper_lock_);
537
538   // Disable VAD and delete the instance.
539   if (ptr_vad_inst_ != NULL) {
540     WebRtcVad_Free(ptr_vad_inst_);
541     ptr_vad_inst_ = NULL;
542   }
543   vad_enabled_ = false;
544   vad_mode_ = VADNormal;
545
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;
551   }
552   num_lpc_params_ = kNewCNGNumLPCParams;
553
554   DestructEncoderSafe();
555 }
556
557 int16_t ACMGenericCodec::SetBitRate(const int32_t bitrate_bps) {
558   WriteLockScoped wl(codec_wrapper_lock_);
559   return SetBitRateSafe(bitrate_bps);
560 }
561
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");
569     return -1;
570   }
571   if (codec_params.rate != bitrate_bps) {
572     WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceAudioCoding, unique_id_,
573                  "SetBitRateSafe: rate value is not acceptable");
574     return -1;
575   } else {
576     return 0;
577   }
578 }
579
580 // iSAC specific functions:
581 int32_t ACMGenericCodec::GetEstimatedBandwidth() {
582   WriteLockScoped wl(codec_wrapper_lock_);
583   return GetEstimatedBandwidthSafe();
584 }
585
586 int32_t ACMGenericCodec::GetEstimatedBandwidthSafe() {
587   // All codecs but iSAC will return -1.
588   return -1;
589 }
590
591 int32_t ACMGenericCodec::SetEstimatedBandwidth(int32_t estimated_bandwidth) {
592   WriteLockScoped wl(codec_wrapper_lock_);
593   return SetEstimatedBandwidthSafe(estimated_bandwidth);
594 }
595
596 int32_t ACMGenericCodec::SetEstimatedBandwidthSafe(
597     int32_t /*estimated_bandwidth*/) {
598   // All codecs but iSAC will return -1.
599   return -1;
600 }
601 // End of iSAC specific functions.
602
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);
607 }
608
609 int32_t ACMGenericCodec::GetRedPayloadSafe(uint8_t* /* red_payload */,
610                                            int16_t* /* payload_bytes */) {
611   return -1;  // Do nothing by default.
612 }
613
614 int16_t ACMGenericCodec::CreateEncoder() {
615   int16_t status = 0;
616   if (!encoder_exist_) {
617     status = InternalCreateEncoder();
618     // We just created the codec and obviously it is not initialized.
619     encoder_initialized_ = false;
620   }
621   if (status < 0) {
622     WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceAudioCoding, unique_id_,
623                  "CreateEncoder: error in internal create encoder");
624     encoder_exist_ = false;
625   } else {
626     encoder_exist_ = true;
627   }
628   return status;
629 }
630
631 uint32_t ACMGenericCodec::EarliestTimestamp() const {
632   ReadLockScoped cs(codec_wrapper_lock_);
633   return in_timestamp_[0];
634 }
635
636 int16_t ACMGenericCodec::SetVAD(bool* enable_dtx,
637                                 bool* enable_vad,
638                                 ACMVADMode* mode) {
639   WriteLockScoped cs(codec_wrapper_lock_);
640   return SetVADSafe(enable_dtx, enable_vad, mode);
641 }
642
643 int16_t ACMGenericCodec::SetVADSafe(bool* enable_dtx,
644                                     bool* enable_vad,
645                                     ACMVADMode* mode) {
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
649     // stereo codecs.
650     DisableDTX();
651     DisableVAD();
652     *enable_dtx = false;
653     *enable_vad = false;
654     return 0;
655   }
656
657   if (*enable_dtx) {
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");
664         *enable_dtx = false;
665         *enable_vad = vad_enabled_;
666         return -1;
667       }
668     } else {
669       if (EnableDTX() < 0) {
670         WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceAudioCoding, unique_id_,
671                      "SetVADSafe: error in enable DTX");
672         *enable_dtx = false;
673         *enable_vad = vad_enabled_;
674         return -1;
675       }
676     }
677
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.
684       *enable_vad = true;
685     }
686   } else {
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();
691       *enable_dtx = false;
692     } else {
693       DisableDTX();
694       *enable_dtx = false;
695     }
696   }
697
698   int16_t status = (*enable_vad) ? EnableVAD(*mode) : DisableVAD();
699   if (status < 0) {
700     // Failed to set VAD, disable DTX.
701     WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceAudioCoding, unique_id_,
702     "SetVADSafe: error in enable VAD");
703     DisableDTX();
704     *enable_dtx = false;
705     *enable_vad = false;
706   }
707   return status;
708 }
709
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.
714     return -1;
715   }
716   if (!dtx_enabled_) {
717     if (WebRtcCng_CreateEnc(&ptr_dtx_inst_) < 0) {
718       ptr_dtx_inst_ = NULL;
719       return -1;
720     }
721     uint16_t freq_hz;
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;
728       return -1;
729     }
730     dtx_enabled_ = true;
731   }
732   return 0;
733 }
734
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.
739     return -1;
740   }
741   if (ptr_dtx_inst_ != NULL) {
742     WebRtcCng_FreeEnc(ptr_dtx_inst_);
743     ptr_dtx_inst_ = NULL;
744   }
745   dtx_enabled_ = false;
746   return 0;
747 }
748
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");
753     return -1;
754   }
755
756   if (!vad_enabled_) {
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");
761       return -1;
762     }
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");
768       return -1;
769     }
770   }
771
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.
777     if (!vad_enabled_) {
778       // We just created the instance but cannot set the mode we have to free
779       // the memory.
780       WebRtcVad_Free(ptr_vad_inst_);
781       ptr_vad_inst_ = NULL;
782     }
783     WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceAudioCoding, unique_id_,
784                  "EnableVAD: failed to set the VAD mode");
785     return -1;
786   }
787   vad_mode_ = mode;
788   vad_enabled_ = true;
789   return 0;
790 }
791
792 int16_t ACMGenericCodec::DisableVAD() {
793   if (ptr_vad_inst_ != NULL) {
794     WebRtcVad_Free(ptr_vad_inst_);
795     ptr_vad_inst_ = NULL;
796   }
797   vad_enabled_ = false;
798   return 0;
799 }
800
801 int32_t ACMGenericCodec::ReplaceInternalDTX(const bool replace_internal_dtx) {
802   WriteLockScoped cs(codec_wrapper_lock_);
803   return ReplaceInternalDTXSafe(replace_internal_dtx);
804 }
805
806 int32_t ACMGenericCodec::ReplaceInternalDTXSafe(
807     const bool /* replace_internal_dtx */) {
808   return -1;
809 }
810
811 int32_t ACMGenericCodec::IsInternalDTXReplaced(bool* internal_dtx_replaced) {
812   WriteLockScoped cs(codec_wrapper_lock_);
813   return IsInternalDTXReplacedSafe(internal_dtx_replaced);
814 }
815
816 int32_t ACMGenericCodec::IsInternalDTXReplacedSafe(
817     bool* internal_dtx_replaced) {
818   *internal_dtx_replaced = false;
819   return 0;
820 }
821
822 int16_t ACMGenericCodec::ProcessFrameVADDTX(uint8_t* bitstream,
823                                             int16_t* bitstream_len_byte,
824                                             int16_t* samples_processed) {
825   if (!vad_enabled_) {
826     // VAD not enabled, set all |vad_lable_[]| to 1 (speech detected).
827     for (int n = 0; n < MAX_FRAME_SIZE_10MSEC; n++) {
828       vad_label_[n] = 1;
829     }
830     *samples_processed = 0;
831     return 0;
832   }
833
834   uint16_t freq_hz;
835   EncoderSampFreq(&freq_hz);
836
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;
840   int16_t status = -1;
841
842   // Vector for storing maximum 30 ms of mono audio at 48 kHz.
843   int16_t audio[1440];
844
845   // Calculate number of VAD-blocks to process, and number of samples in each
846   // block.
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;
851   } else {
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];
857   }
858
859   int offset = 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;
868       }
869       offset = num_samples_to_process[0];
870     } else {
871       // Mono, copy data from in_audio_ to continue work on.
872       memcpy(audio, in_audio_, sizeof(int16_t) * num_samples_to_process[i]);
873     }
874
875     // Call VAD.
876     status = static_cast<int16_t>(WebRtcVad_Process(ptr_vad_inst_,
877                                                     static_cast<int>(freq_hz),
878                                                     audio,
879                                                     num_samples_to_process[i]));
880     vad_label_[i] = status;
881
882     if (status < 0) {
883       // This will force that the data be removed from the buffer.
884       *samples_processed += num_samples_to_process[i];
885       return -1;
886     }
887
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,
902                                   !prev_frame_cng_);
903         if (status < 0) {
904           return -1;
905         }
906
907         // Update previous frame was CNG.
908         prev_frame_cng_ = 1;
909
910         *samples_processed += samples_in_10ms * num_channels_;
911
912         // |bitstream_len_byte| will only be > 0 once per 100 ms.
913         *bitstream_len_byte += bitstream_len;
914       }
915
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;
920       }
921     } else {
922       // Update previous frame was not CNG.
923       prev_frame_cng_ = 0;
924     }
925
926     if (*samples_processed > 0) {
927       // The block contains inactive speech, and is processed by DTX.
928       // Discontinue running VAD.
929       break;
930     }
931   }
932
933   return status;
934 }
935
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_);
940 }
941
942 void ACMGenericCodec::SetUniqueID(const uint32_t id) {
943   unique_id_ = id;
944 }
945
946 // This function is replaced by codec specific functions for some codecs.
947 int16_t ACMGenericCodec::EncoderSampFreq(uint16_t* samp_freq_hz) {
948   int32_t f;
949   f = ACMCodecDB::CodecFreq(codec_id_);
950   if (f < 0) {
951     WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceAudioCoding, unique_id_,
952                  "EncoderSampFreq: codec frequency is negative");
953     return -1;
954   } else {
955     *samp_freq_hz = static_cast<uint16_t>(f);
956     return 0;
957   }
958 }
959
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 "
966                "estimator.");
967   return -1;
968 }
969
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.");
974   return -1;
975 }
976
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 "
981                "payload-size.");
982   return -1;
983 }
984
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.");
990   return -1;
991 }
992
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");
999   return -1;
1000 }
1001
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.");
1005   return -1;
1006 }
1007
1008 }  // namespace acm2
1009
1010 }  // namespace webrtc