blob: e16f0830fd89e153e2d90f4c1cfd728363cd788a [file] [log] [blame]
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +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
11#include "webrtc/modules/audio_coding/neteq4/neteq_impl.h"
12
13#include <assert.h>
14#include <memory.h> // memset
15
16#include <algorithm>
17
18#include "webrtc/common_audio/signal_processing/include/signal_processing_library.h"
19#include "webrtc/modules/audio_coding/neteq4/accelerate.h"
20#include "webrtc/modules/audio_coding/neteq4/background_noise.h"
21#include "webrtc/modules/audio_coding/neteq4/buffer_level_filter.h"
22#include "webrtc/modules/audio_coding/neteq4/comfort_noise.h"
23#include "webrtc/modules/audio_coding/neteq4/decision_logic.h"
24#include "webrtc/modules/audio_coding/neteq4/decoder_database.h"
25#include "webrtc/modules/audio_coding/neteq4/defines.h"
26#include "webrtc/modules/audio_coding/neteq4/delay_manager.h"
27#include "webrtc/modules/audio_coding/neteq4/delay_peak_detector.h"
28#include "webrtc/modules/audio_coding/neteq4/dtmf_buffer.h"
29#include "webrtc/modules/audio_coding/neteq4/dtmf_tone_generator.h"
30#include "webrtc/modules/audio_coding/neteq4/expand.h"
31#include "webrtc/modules/audio_coding/neteq4/interface/audio_decoder.h"
32#include "webrtc/modules/audio_coding/neteq4/merge.h"
33#include "webrtc/modules/audio_coding/neteq4/normal.h"
34#include "webrtc/modules/audio_coding/neteq4/packet_buffer.h"
35#include "webrtc/modules/audio_coding/neteq4/packet.h"
36#include "webrtc/modules/audio_coding/neteq4/payload_splitter.h"
37#include "webrtc/modules/audio_coding/neteq4/post_decode_vad.h"
38#include "webrtc/modules/audio_coding/neteq4/preemptive_expand.h"
39#include "webrtc/modules/audio_coding/neteq4/sync_buffer.h"
40#include "webrtc/modules/audio_coding/neteq4/timestamp_scaler.h"
41#include "webrtc/modules/interface/module_common_types.h"
42#include "webrtc/system_wrappers/interface/critical_section_wrapper.h"
43#include "webrtc/system_wrappers/interface/logging.h"
44
45// Modify the code to obtain backwards bit-exactness. Once bit-exactness is no
46// longer required, this #define should be removed (and the code that it
47// enables).
48#define LEGACY_BITEXACT
49
50namespace webrtc {
51
52NetEqImpl::NetEqImpl(int fs,
53 BufferLevelFilter* buffer_level_filter,
54 DecoderDatabase* decoder_database,
55 DelayManager* delay_manager,
56 DelayPeakDetector* delay_peak_detector,
57 DtmfBuffer* dtmf_buffer,
58 DtmfToneGenerator* dtmf_tone_generator,
59 PacketBuffer* packet_buffer,
60 PayloadSplitter* payload_splitter,
61 TimestampScaler* timestamp_scaler)
62 : background_noise_(NULL),
63 buffer_level_filter_(buffer_level_filter),
64 decoder_database_(decoder_database),
65 delay_manager_(delay_manager),
66 delay_peak_detector_(delay_peak_detector),
67 dtmf_buffer_(dtmf_buffer),
68 dtmf_tone_generator_(dtmf_tone_generator),
69 packet_buffer_(packet_buffer),
70 payload_splitter_(payload_splitter),
71 timestamp_scaler_(timestamp_scaler),
72 vad_(new PostDecodeVad()),
73 sync_buffer_(NULL),
74 expand_(NULL),
75 comfort_noise_(NULL),
76 last_mode_(kModeNormal),
77 mute_factor_array_(NULL),
78 decoded_buffer_length_(kMaxFrameSize),
79 decoded_buffer_(new int16_t[decoded_buffer_length_]),
80 playout_timestamp_(0),
81 new_codec_(false),
82 timestamp_(0),
83 reset_decoder_(false),
84 current_rtp_payload_type_(0xFF), // Invalid RTP payload type.
85 current_cng_rtp_payload_type_(0xFF), // Invalid RTP payload type.
86 ssrc_(0),
87 first_packet_(true),
88 dtmf_enabled_(true),
89 error_code_(0),
90 decoder_error_code_(0),
91 crit_sect_(CriticalSectionWrapper::CreateCriticalSection()) {
92 if (fs != 8000 && fs != 16000 && fs != 32000 && fs != 48000) {
93 LOG(LS_ERROR) << "Sample rate " << fs << " Hz not supported. " <<
94 "Changing to 8000 Hz.";
95 fs = 8000;
96 }
97 LOG(LS_INFO) << "Create NetEqImpl object with fs = " << fs << ".";
98 fs_hz_ = fs;
99 fs_mult_ = fs / 8000;
100 output_size_samples_ = kOutputSizeMs * 8 * fs_mult_;
101 decoder_frame_length_ = 3 * output_size_samples_;
102 WebRtcSpl_Init();
103 decision_logic_.reset(DecisionLogic::Create(fs_hz_, output_size_samples_,
104 kPlayoutOn,
105 decoder_database_.get(),
106 *packet_buffer_.get(),
107 delay_manager_.get(),
108 buffer_level_filter_.get()));
109 SetSampleRateAndChannels(fs, 1); // Default is 1 channel.
110}
111
112NetEqImpl::~NetEqImpl() {
113 LOG(LS_INFO) << "Deleting NetEqImpl object.";
114 delete sync_buffer_;
115 delete background_noise_;
116 delete expand_;
117 delete comfort_noise_;
118 delete crit_sect_;
119}
120
121int NetEqImpl::InsertPacket(const WebRtcRTPHeader& rtp_header,
122 const uint8_t* payload,
123 int length_bytes,
124 uint32_t receive_timestamp) {
125 CriticalSectionScoped lock(crit_sect_);
126 LOG(LS_VERBOSE) << "InsertPacket: ts=" << rtp_header.header.timestamp <<
127 ", sn=" << rtp_header.header.sequenceNumber <<
128 ", pt=" << static_cast<int>(rtp_header.header.payloadType) <<
129 ", ssrc=" << rtp_header.header.ssrc <<
130 ", len=" << length_bytes;
131 int error = InsertPacketInternal(rtp_header, payload, length_bytes,
132 receive_timestamp);
133 if (error != 0) {
134 LOG_FERR1(LS_WARNING, InsertPacketInternal, error);
135 error_code_ = error;
136 return kFail;
137 }
138 return kOK;
139}
140
141int NetEqImpl::GetAudio(size_t max_length, int16_t* output_audio,
142 int* samples_per_channel, int* num_channels,
143 NetEqOutputType* type) {
144 CriticalSectionScoped lock(crit_sect_);
145 LOG(LS_VERBOSE) << "GetAudio";
146 int error = GetAudioInternal(max_length, output_audio, samples_per_channel,
147 num_channels);
148 LOG(LS_VERBOSE) << "Produced " << *samples_per_channel <<
149 " samples/channel for " << *num_channels << " channel(s)";
150 if (error != 0) {
151 LOG_FERR1(LS_WARNING, GetAudioInternal, error);
152 error_code_ = error;
153 return kFail;
154 }
155 if (type) {
156 *type = LastOutputType();
157 }
158 return kOK;
159}
160
161int NetEqImpl::RegisterPayloadType(enum NetEqDecoder codec,
162 uint8_t rtp_payload_type) {
163 CriticalSectionScoped lock(crit_sect_);
164 LOG_API2(static_cast<int>(rtp_payload_type), codec);
165 int ret = decoder_database_->RegisterPayload(rtp_payload_type, codec);
166 if (ret != DecoderDatabase::kOK) {
167 LOG_FERR2(LS_WARNING, RegisterPayload, rtp_payload_type, codec);
168 switch (ret) {
169 case DecoderDatabase::kInvalidRtpPayloadType:
170 error_code_ = kInvalidRtpPayloadType;
171 break;
172 case DecoderDatabase::kCodecNotSupported:
173 error_code_ = kCodecNotSupported;
174 break;
175 case DecoderDatabase::kDecoderExists:
176 error_code_ = kDecoderExists;
177 break;
178 default:
179 error_code_ = kOtherError;
180 }
181 return kFail;
182 }
183 return kOK;
184}
185
186int NetEqImpl::RegisterExternalDecoder(AudioDecoder* decoder,
187 enum NetEqDecoder codec,
188 int sample_rate_hz,
189 uint8_t rtp_payload_type) {
190 CriticalSectionScoped lock(crit_sect_);
191 LOG_API2(static_cast<int>(rtp_payload_type), codec);
192 if (!decoder) {
193 LOG(LS_ERROR) << "Cannot register external decoder with NULL pointer";
194 assert(false);
195 return kFail;
196 }
197 int ret = decoder_database_->InsertExternal(rtp_payload_type, codec,
198 sample_rate_hz, decoder);
199 if (ret != DecoderDatabase::kOK) {
200 LOG_FERR2(LS_WARNING, InsertExternal, rtp_payload_type, codec);
201 switch (ret) {
202 case DecoderDatabase::kInvalidRtpPayloadType:
203 error_code_ = kInvalidRtpPayloadType;
204 break;
205 case DecoderDatabase::kCodecNotSupported:
206 error_code_ = kCodecNotSupported;
207 break;
208 case DecoderDatabase::kDecoderExists:
209 error_code_ = kDecoderExists;
210 break;
211 case DecoderDatabase::kInvalidSampleRate:
212 error_code_ = kInvalidSampleRate;
213 break;
214 case DecoderDatabase::kInvalidPointer:
215 error_code_ = kInvalidPointer;
216 break;
217 default:
218 error_code_ = kOtherError;
219 }
220 return kFail;
221 }
222 return kOK;
223}
224
225int NetEqImpl::RemovePayloadType(uint8_t rtp_payload_type) {
226 CriticalSectionScoped lock(crit_sect_);
227 LOG_API1(static_cast<int>(rtp_payload_type));
228 int ret = decoder_database_->Remove(rtp_payload_type);
229 if (ret == DecoderDatabase::kOK) {
230 return kOK;
231 } else if (ret == DecoderDatabase::kDecoderNotFound) {
232 error_code_ = kDecoderNotFound;
233 } else {
234 error_code_ = kOtherError;
235 }
236 LOG_FERR1(LS_WARNING, Remove, rtp_payload_type);
237 return kFail;
238}
239
240bool NetEqImpl::SetExtraDelay(int extra_delay_ms) {
241 CriticalSectionScoped lock(crit_sect_);
242 if (extra_delay_ms >= 0 && extra_delay_ms < 10000) {
243 assert(delay_manager_.get());
244 delay_manager_->set_extra_delay_ms(extra_delay_ms);
245 return true;
246 }
247 return false;
248}
249
250int NetEqImpl::EnableDtmf() {
251 CriticalSectionScoped lock(crit_sect_);
252 dtmf_enabled_ = true;
253 return kOK;
254}
255
256void NetEqImpl::SetPlayoutMode(NetEqPlayoutMode mode) {
257 CriticalSectionScoped lock(crit_sect_);
258 if (!decision_logic_.get() || mode != decision_logic_->playout_mode()) {
259 // The reset() method calls delete for the old object.
260 decision_logic_.reset(DecisionLogic::Create(fs_hz_, output_size_samples_,
261 mode,
262 decoder_database_.get(),
263 *packet_buffer_.get(),
264 delay_manager_.get(),
265 buffer_level_filter_.get()));
266 }
267}
268
269NetEqPlayoutMode NetEqImpl::PlayoutMode() const {
270 CriticalSectionScoped lock(crit_sect_);
271 assert(decision_logic_.get());
272 return decision_logic_->playout_mode();
273}
274
275int NetEqImpl::NetworkStatistics(NetEqNetworkStatistics* stats) {
276 CriticalSectionScoped lock(crit_sect_);
277 assert(decoder_database_.get());
278 const int total_samples_in_buffers = packet_buffer_->NumSamplesInBuffer(
279 decoder_database_.get(), decoder_frame_length_) +
280 sync_buffer_->FutureLength();
281 assert(delay_manager_.get());
282 assert(decision_logic_.get());
283 stats_.GetNetworkStatistics(fs_hz_, total_samples_in_buffers,
284 decoder_frame_length_, *delay_manager_.get(),
285 *decision_logic_.get(), stats);
286 return 0;
287}
288
289void NetEqImpl::WaitingTimes(std::vector<int>* waiting_times) {
290 CriticalSectionScoped lock(crit_sect_);
291 stats_.WaitingTimes(waiting_times);
292}
293
294void NetEqImpl::GetRtcpStatistics(RtcpStatistics* stats) {
295 CriticalSectionScoped lock(crit_sect_);
296 if (stats) {
297 rtcp_.GetStatistics(false, stats);
298 }
299}
300
301void NetEqImpl::GetRtcpStatisticsNoReset(RtcpStatistics* stats) {
302 CriticalSectionScoped lock(crit_sect_);
303 if (stats) {
304 rtcp_.GetStatistics(true, stats);
305 }
306}
307
308void NetEqImpl::EnableVad() {
309 CriticalSectionScoped lock(crit_sect_);
310 assert(vad_.get());
311 vad_->Enable();
312}
313
314void NetEqImpl::DisableVad() {
315 CriticalSectionScoped lock(crit_sect_);
316 assert(vad_.get());
317 vad_->Disable();
318}
319
320uint32_t NetEqImpl::PlayoutTimestamp() {
321 CriticalSectionScoped lock(crit_sect_);
322 return timestamp_scaler_->ToExternal(playout_timestamp_);
323}
324
325int NetEqImpl::LastError() {
326 CriticalSectionScoped lock(crit_sect_);
327 return error_code_;
328}
329
330int NetEqImpl::LastDecoderError() {
331 CriticalSectionScoped lock(crit_sect_);
332 return decoder_error_code_;
333}
334
335void NetEqImpl::FlushBuffers() {
336 CriticalSectionScoped lock(crit_sect_);
337 LOG_API0();
338 packet_buffer_->Flush();
339 assert(sync_buffer_);
340 assert(expand_);
341 sync_buffer_->Flush();
342 sync_buffer_->set_next_index(sync_buffer_->next_index() -
343 expand_->overlap_length());
344 // Set to wait for new codec.
345 first_packet_ = true;
346}
347
348// Methods below this line are private.
349
350
351int NetEqImpl::InsertPacketInternal(const WebRtcRTPHeader& rtp_header,
352 const uint8_t* payload,
353 int length_bytes,
354 uint32_t receive_timestamp) {
355 if (!payload) {
356 LOG_F(LS_ERROR) << "payload == NULL";
357 return kInvalidPointer;
358 }
359 PacketList packet_list;
360 RTPHeader main_header;
361 {
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000362 // Convert to Packet.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000363 // Create |packet| within this separate scope, since it should not be used
364 // directly once it's been inserted in the packet list. This way, |packet|
365 // is not defined outside of this block.
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000366 Packet* packet = new Packet;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000367 packet->header.markerBit = false;
368 packet->header.payloadType = rtp_header.header.payloadType;
369 packet->header.sequenceNumber = rtp_header.header.sequenceNumber;
370 packet->header.timestamp = rtp_header.header.timestamp;
371 packet->header.ssrc = rtp_header.header.ssrc;
372 packet->header.numCSRCs = 0;
373 packet->payload_length = length_bytes;
374 packet->primary = true;
375 packet->waiting_time = 0;
376 packet->payload = new uint8_t[packet->payload_length];
377 LOG_F(LS_ERROR) << "Payload pointer is NULL.";
378 assert(payload); // Already checked above.
379 memcpy(packet->payload, payload, packet->payload_length);
380 // Insert packet in a packet list.
381 packet_list.push_back(packet);
382 // Save main payloads header for later.
383 memcpy(&main_header, &packet->header, sizeof(main_header));
384 }
385
386 // Reinitialize NetEq if it's needed (changed SSRC or first call).
387 if ((main_header.ssrc != ssrc_) || first_packet_) {
388 rtcp_.Init(main_header.sequenceNumber);
389 first_packet_ = false;
390
391 // Flush the packet buffer and DTMF buffer.
392 packet_buffer_->Flush();
393 dtmf_buffer_->Flush();
394
395 // Store new SSRC.
396 ssrc_ = main_header.ssrc;
397
398 // Update codecs.
399 timestamp_ = main_header.timestamp;
400 current_rtp_payload_type_ = main_header.payloadType;
401
402 // Set MCU to update codec on next SignalMCU call.
403 new_codec_ = true;
404
405 // Reset timestamp scaling.
406 timestamp_scaler_->Reset();
407 }
408
409 // Update RTCP statistics.
410 rtcp_.Update(main_header, receive_timestamp);
411
412 // Check for RED payload type, and separate payloads into several packets.
413 if (decoder_database_->IsRed(main_header.payloadType)) {
414 if (payload_splitter_->SplitRed(&packet_list) != PayloadSplitter::kOK) {
415 LOG_FERR1(LS_WARNING, SplitRed, packet_list.size());
416 PacketBuffer::DeleteAllPackets(&packet_list);
417 return kRedundancySplitError;
418 }
419 // Only accept a few RED payloads of the same type as the main data,
420 // DTMF events and CNG.
421 payload_splitter_->CheckRedPayloads(&packet_list, *decoder_database_);
422 // Update the stored main payload header since the main payload has now
423 // changed.
424 memcpy(&main_header, &packet_list.front()->header, sizeof(main_header));
425 }
426
427 // Check payload types.
428 if (decoder_database_->CheckPayloadTypes(packet_list) ==
429 DecoderDatabase::kDecoderNotFound) {
430 LOG_FERR1(LS_WARNING, CheckPayloadTypes, packet_list.size());
431 PacketBuffer::DeleteAllPackets(&packet_list);
432 return kUnknownRtpPayloadType;
433 }
434
435 // Scale timestamp to internal domain (only for some codecs).
436 timestamp_scaler_->ToInternal(&packet_list);
437
438 // Process DTMF payloads. Cycle through the list of packets, and pick out any
439 // DTMF payloads found.
440 PacketList::iterator it = packet_list.begin();
441 while (it != packet_list.end()) {
442 Packet* current_packet = (*it);
443 assert(current_packet);
444 assert(current_packet->payload);
445 if (decoder_database_->IsDtmf(current_packet->header.payloadType)) {
446 if (dtmf_enabled_) {
447 DtmfEvent event;
448 int ret = DtmfBuffer::ParseEvent(
449 current_packet->header.timestamp,
450 current_packet->payload,
451 current_packet->payload_length,
452 &event);
453 if (ret != DtmfBuffer::kOK) {
454 LOG_FERR2(LS_WARNING, ParseEvent, ret,
455 current_packet->payload_length);
456 PacketBuffer::DeleteAllPackets(&packet_list);
457 return kDtmfParsingError;
458 }
459 if (dtmf_buffer_->InsertEvent(event) != DtmfBuffer::kOK) {
460 LOG_FERR0(LS_WARNING, InsertEvent);
461 PacketBuffer::DeleteAllPackets(&packet_list);
462 return kDtmfInsertError;
463 }
464 }
465 // TODO(hlundin): Let the destructor of Packet handle the payload.
466 delete [] current_packet->payload;
467 delete current_packet;
468 it = packet_list.erase(it);
469 } else {
470 ++it;
471 }
472 }
473
474 // Split payloads into smaller chunks. This also verifies that all payloads
475 // are of a known payload type.
476 int ret = payload_splitter_->SplitAudio(&packet_list, *decoder_database_);
477 if (ret != PayloadSplitter::kOK) {
478 LOG_FERR1(LS_WARNING, SplitAudio, packet_list.size());
479 PacketBuffer::DeleteAllPackets(&packet_list);
480 switch (ret) {
481 case PayloadSplitter::kUnknownPayloadType:
482 return kUnknownRtpPayloadType;
483 case PayloadSplitter::kFrameSplitError:
484 return kFrameSplitError;
485 default:
486 return kOtherError;
487 }
488 }
489
490 // Update bandwidth estimate.
491 if (!packet_list.empty()) {
492 // The list can be empty here if we got nothing but DTMF payloads.
493 AudioDecoder* decoder =
494 decoder_database_->GetDecoder(main_header.payloadType);
495 assert(decoder); // Should always get a valid object, since we have
496 // already checked that the payload types are known.
497 decoder->IncomingPacket(packet_list.front()->payload,
498 packet_list.front()->payload_length,
499 packet_list.front()->header.sequenceNumber,
500 packet_list.front()->header.timestamp,
501 receive_timestamp);
502 }
503
504 // Insert packets in buffer.
505 int temp_bufsize = packet_buffer_->NumPacketsInBuffer();
506 ret = packet_buffer_->InsertPacketList(
507 &packet_list,
508 *decoder_database_,
509 &current_rtp_payload_type_,
510 &current_cng_rtp_payload_type_);
511 if (ret == PacketBuffer::kFlushed) {
512 // Reset DSP timestamp etc. if packet buffer flushed.
513 new_codec_ = true;
514 LOG_F(LS_WARNING) << "Packet buffer flushed";
515 } else if (ret != PacketBuffer::kOK) {
516 LOG_FERR1(LS_WARNING, InsertPacketList, packet_list.size());
517 PacketBuffer::DeleteAllPackets(&packet_list);
518 assert(false);
519 // TODO(hlundin): Take care of error codes.
520 }
521 if (current_rtp_payload_type_ != 0xFF) {
522 const DecoderDatabase::DecoderInfo* dec_info =
523 decoder_database_->GetDecoderInfo(current_rtp_payload_type_);
524 if (!dec_info) {
525 assert(false); // Already checked that the payload type is known.
526 }
527 }
528
529 // TODO(hlundin): Move this code to DelayManager class.
530 const DecoderDatabase::DecoderInfo* dec_info =
531 decoder_database_->GetDecoderInfo(main_header.payloadType);
532 assert(dec_info); // Already checked that the payload type is known.
533 delay_manager_->LastDecoderType(dec_info->codec_type);
534 if (delay_manager_->last_pack_cng_or_dtmf() == 0) {
535 // Calculate the total speech length carried in each packet.
536 temp_bufsize = packet_buffer_->NumPacketsInBuffer() - temp_bufsize;
537 temp_bufsize *= decoder_frame_length_;
538
539 if ((temp_bufsize > 0) &&
540 (temp_bufsize != decision_logic_->packet_length_samples())) {
541 decision_logic_->set_packet_length_samples(temp_bufsize);
542 delay_manager_->SetPacketAudioLength((1000 * temp_bufsize) / fs_hz_);
543 }
544
545 // Update statistics.
546 if ((WebRtc_Word32) (main_header.timestamp - timestamp_) >= 0 &&
547 !new_codec_) {
548 // Only update statistics if incoming packet is not older than last played
549 // out packet, and if new codec flag is not set.
550 delay_manager_->Update(main_header.sequenceNumber, main_header.timestamp,
551 fs_hz_);
552 }
553 } else if (delay_manager_->last_pack_cng_or_dtmf() == -1) {
554 // This is first "normal" packet after CNG or DTMF.
555 // Reset packet time counter and measure time until next packet,
556 // but don't update statistics.
557 delay_manager_->set_last_pack_cng_or_dtmf(0);
558 delay_manager_->ResetPacketIatCount();
559 }
560 return 0;
561}
562
563int NetEqImpl::GetAudioInternal(size_t max_length, int16_t* output,
564 int* samples_per_channel, int* num_channels) {
565 PacketList packet_list;
566 DtmfEvent dtmf_event;
567 Operations operation;
568 bool play_dtmf;
569 int return_value = GetDecision(&operation, &packet_list, &dtmf_event,
570 &play_dtmf);
571 if (return_value != 0) {
572 LOG_FERR1(LS_WARNING, GetDecision, return_value);
573 assert(false);
574 last_mode_ = kModeError;
575 return return_value;
576 }
577 LOG(LS_VERBOSE) << "GetDecision returned operation=" << operation <<
578 " and " << packet_list.size() << " packet(s)";
579
580 AudioDecoder::SpeechType speech_type;
581 int length = 0;
582 int decode_return_value = Decode(&packet_list, &operation,
583 &length, &speech_type);
584
585
586 assert(vad_.get());
587 bool sid_frame_available =
588 (operation == kRfc3389Cng && !packet_list.empty());
589 vad_->Update(decoded_buffer_.get(), length, speech_type,
590 sid_frame_available, fs_hz_);
591
592 AudioMultiVector<int16_t> algorithm_buffer(sync_buffer_->Channels());
593 switch (operation) {
594 case kNormal: {
595 DoNormal(decoded_buffer_.get(), length, speech_type, play_dtmf,
596 &algorithm_buffer);
597 break;
598 }
599 case kMerge: {
600 DoMerge(decoded_buffer_.get(), length, speech_type, play_dtmf,
601 &algorithm_buffer);
602 break;
603 }
604 case kExpand: {
605 return_value = DoExpand(play_dtmf, &algorithm_buffer);
606 break;
607 }
608 case kAccelerate: {
609 return_value = DoAccelerate(decoded_buffer_.get(), length, speech_type,
610 play_dtmf, &algorithm_buffer);
611 break;
612 }
613 case kPreemptiveExpand: {
614 return_value = DoPreemptiveExpand(decoded_buffer_.get(), length,
615 speech_type, play_dtmf,
616 &algorithm_buffer);
617 break;
618 }
619 case kRfc3389Cng:
620 case kRfc3389CngNoPacket: {
621 return_value = DoRfc3389Cng(&packet_list, play_dtmf, &algorithm_buffer);
622 break;
623 }
624 case kCodecInternalCng: {
625 // This handles the case when there is no transmission and the decoder
626 // should produce internal comfort noise.
627 // TODO(hlundin): Write test for codec-internal CNG.
628 DoCodecInternalCng(&algorithm_buffer);
629 break;
630 }
631 case kDtmf: {
632 // TODO(hlundin): Write test for this.
633 return_value = DoDtmf(dtmf_event, &play_dtmf, &algorithm_buffer);
634 break;
635 }
636 case kAlternativePlc: {
637 // TODO(hlundin): Write test for this.
638 DoAlternativePlc(false, &algorithm_buffer);
639 break;
640 }
641 case kAlternativePlcIncreaseTimestamp: {
642 // TODO(hlundin): Write test for this.
643 DoAlternativePlc(true, &algorithm_buffer);
644 break;
645 }
646 case kAudioRepetitionIncreaseTimestamp: {
647 // TODO(hlundin): Write test for this.
648 sync_buffer_->IncreaseEndTimestamp(output_size_samples_);
649 // Skipping break on purpose. Execution should move on into the
650 // next case.
651 }
652 case kAudioRepetition: {
653 // TODO(hlundin): Write test for this.
654 // Copy last |output_size_samples_| from |sync_buffer_| to
655 // |algorithm_buffer|.
656 algorithm_buffer.PushBackFromIndex(
657 *sync_buffer_, sync_buffer_->Size() - output_size_samples_);
658 expand_->Reset();
659 break;
660 }
661 case kUndefined: {
662 LOG_F(LS_ERROR) << "Invalid operation kUndefined.";
663 assert(false); // This should not happen.
664 last_mode_ = kModeError;
665 return kInvalidOperation;
666 }
667 } // End of switch.
668 if (return_value < 0) {
669 return return_value;
670 }
671
672 if (last_mode_ != kModeRfc3389Cng) {
673 comfort_noise_->Reset();
674 }
675
676 // Copy from |algorithm_buffer| to |sync_buffer_|.
677 sync_buffer_->PushBack(algorithm_buffer);
678
679 // Extract data from |sync_buffer_| to |output|.
680 int num_output_samples_per_channel = output_size_samples_;
681 int num_output_samples = output_size_samples_ * sync_buffer_->Channels();
682 if (num_output_samples > static_cast<int>(max_length)) {
683 LOG(LS_WARNING) << "Output array is too short. " << max_length << " < " <<
684 output_size_samples_ << " * " << sync_buffer_->Channels();
685 num_output_samples = max_length;
686 num_output_samples_per_channel = max_length / sync_buffer_->Channels();
687 }
688 int samples_from_sync = sync_buffer_->GetNextAudioInterleaved(
689 num_output_samples_per_channel, output);
690 *num_channels = sync_buffer_->Channels();
691 LOG(LS_VERBOSE) << "Sync buffer (" << *num_channels << " channel(s)):" <<
692 " insert " << algorithm_buffer.Size() << " samples, extract " <<
693 samples_from_sync << " samples";
694 if (samples_from_sync != output_size_samples_) {
695 LOG_F(LS_ERROR) << "samples_from_sync != output_size_samples_";
696 assert(false);
697 memset(output, 0, num_output_samples * sizeof(int16_t));
698 *samples_per_channel = output_size_samples_;
699 last_mode_ = kModeError;
700 return kSampleUnderrun;
701 }
702 *samples_per_channel = output_size_samples_;
703
704 // Should always have overlap samples left in the |sync_buffer_|.
705 assert(sync_buffer_->FutureLength() >= expand_->overlap_length());
706
707 if (play_dtmf) {
708 return_value = DtmfOverdub(dtmf_event, sync_buffer_->Channels(), output);
709 }
710
711 // Update the background noise parameters if last operation wrote data
712 // straight from the decoder to the |sync_buffer_|. That is, none of the
713 // operations that modify the signal can be followed by a parameter update.
714 if ((last_mode_ == kModeNormal) ||
715 (last_mode_ == kModeAccelerateFail) ||
716 (last_mode_ == kModePreemptiveExpandFail) ||
717 (last_mode_ == kModeRfc3389Cng) ||
718 (last_mode_ == kModeCodecInternalCng)) {
719 background_noise_->Update(*sync_buffer_, *vad_.get());
720 }
721
722 if (operation == kDtmf) {
723 // DTMF data was written the end of |sync_buffer_|.
724 // Update index to end of DTMF data in |sync_buffer_|.
725 sync_buffer_->set_dtmf_index(sync_buffer_->Size());
726 }
727
728 if ((last_mode_ != kModeExpand) && (last_mode_ != kModeRfc3389Cng)) {
729 // If last operation was neither expand, nor comfort noise, calculate the
730 // |playout_timestamp_| from the |sync_buffer_|. However, do not update the
731 // |playout_timestamp_| if it would be moved "backwards".
732 uint32_t temp_timestamp = sync_buffer_->end_timestamp() -
733 sync_buffer_->FutureLength();
734 if (static_cast<int32_t>(temp_timestamp - playout_timestamp_) > 0) {
735 playout_timestamp_ = temp_timestamp;
736 }
737 } else {
738 // Use dead reckoning to estimate the |playout_timestamp_|.
739 playout_timestamp_ += output_size_samples_;
740 }
741
742 if (decode_return_value) return decode_return_value;
743 return return_value;
744}
745
746int NetEqImpl::GetDecision(Operations* operation,
747 PacketList* packet_list,
748 DtmfEvent* dtmf_event,
749 bool* play_dtmf) {
750 // Initialize output variables.
751 *play_dtmf = false;
752 *operation = kUndefined;
753
754 // Increment time counters.
755 packet_buffer_->IncrementWaitingTimes();
756 stats_.IncreaseCounter(output_size_samples_, fs_hz_);
757
758 assert(sync_buffer_);
759 uint32_t end_timestamp = sync_buffer_->end_timestamp();
760 if (!new_codec_) {
761 packet_buffer_->DiscardOldPackets(end_timestamp);
762 }
763 const RTPHeader* header = packet_buffer_->NextRtpHeader();
764
765 if (decision_logic_->CngRfc3389On()) {
766 // Because of timestamp peculiarities, we have to "manually" disallow using
767 // a CNG packet with the same timestamp as the one that was last played.
768 // This can happen when using redundancy and will cause the timing to shift.
769 while (header &&
770 decoder_database_->IsComfortNoise(header->payloadType) &&
771 end_timestamp >= header->timestamp) {
772 // Don't use this packet, discard it.
773 // TODO(hlundin): Write test for this case.
774 if (packet_buffer_->DiscardNextPacket() != PacketBuffer::kOK) {
775 assert(false); // Must be ok by design.
776 }
777 // Check buffer again.
778 if (!new_codec_) {
779 packet_buffer_->DiscardOldPackets(end_timestamp);
780 }
781 header = packet_buffer_->NextRtpHeader();
782 }
783 }
784
785 assert(expand_);
786 const int samples_left = sync_buffer_->FutureLength() -
787 expand_->overlap_length();
788 if (last_mode_ == kModeAccelerateSuccess ||
789 last_mode_ == kModeAccelerateLowEnergy ||
790 last_mode_ == kModePreemptiveExpandSuccess ||
791 last_mode_ == kModePreemptiveExpandLowEnergy) {
792 // Subtract (samples_left + output_size_samples_) from sampleMemory.
793 decision_logic_->AddSampleMemory(-(samples_left + output_size_samples_));
794 }
795
796 // Check if it is time to play a DTMF event.
797 if (dtmf_buffer_->GetEvent(end_timestamp +
798 decision_logic_->generated_noise_samples(),
799 dtmf_event)) {
800 *play_dtmf = true;
801 }
802
803 // Get instruction.
804 assert(sync_buffer_);
805 assert(expand_);
806 *operation = decision_logic_->GetDecision(*sync_buffer_,
807 *expand_,
808 decoder_frame_length_,
809 header,
810 last_mode_,
811 *play_dtmf,
812 &reset_decoder_);
813
814 // Check if we already have enough samples in the |sync_buffer_|. If so,
815 // change decision to normal, unless the decision was merge, accelerate, or
816 // preemptive expand.
817 if (samples_left >= output_size_samples_ &&
818 *operation != kMerge &&
819 *operation != kAccelerate &&
820 *operation != kPreemptiveExpand) {
821 *operation = kNormal;
822 return 0;
823 }
824
825 decision_logic_->ExpandDecision(*operation == kExpand);
826
827 // Check conditions for reset.
828 if (new_codec_ || *operation == kUndefined) {
829 // The only valid reason to get kUndefined is that new_codec_ is set.
830 assert(new_codec_);
831 assert(header);
832 if (!header) {
833 LOG_F(LS_ERROR) << "Packet missing where it shouldn't.";
834 return -1;
835 }
836 timestamp_ = header->timestamp;
837 // Adjust |sync_buffer_| timestamp before setting |end_timestamp| to the
838 // new value.
839 sync_buffer_->IncreaseEndTimestamp(timestamp_ - end_timestamp);
840 end_timestamp = header->timestamp;
841 new_codec_ = false;
842 decision_logic_->SoftReset();
843 buffer_level_filter_->Reset();
844 delay_manager_->Reset();
845 stats_.ResetMcu();
846
847 if (*operation == kRfc3389CngNoPacket) {
848 // Change decision to CNG packet, since we do have a CNG packet, but it
849 // was considered too early to use. Now, use it anyway.
850 *operation = kRfc3389Cng;
851 } else if (*operation != kRfc3389Cng) {
852 *operation = kNormal;
853 }
854 }
855
856 int required_samples = output_size_samples_;
857 const int samples_10_ms = 80 * fs_mult_;
858 const int samples_20_ms = 2 * samples_10_ms;
859 const int samples_30_ms = 3 * samples_10_ms;
860
861 switch (*operation) {
862 case kExpand: {
863 timestamp_ = end_timestamp;
864 return 0;
865 }
866 case kRfc3389CngNoPacket:
867 case kCodecInternalCng: {
868 return 0;
869 }
870 case kDtmf: {
871 // TODO(hlundin): Write test for this.
872 // Update timestamp.
873 timestamp_ = end_timestamp;
874 if (decision_logic_->generated_noise_samples() > 0 &&
875 last_mode_ != kModeDtmf) {
876 // Make a jump in timestamp due to the recently played comfort noise.
877 uint32_t timestamp_jump = decision_logic_->generated_noise_samples();
878 sync_buffer_->IncreaseEndTimestamp(timestamp_jump);
879 timestamp_ += timestamp_jump;
880 }
881 decision_logic_->set_generated_noise_samples(0);
882 return 0;
883 }
884 case kAccelerate: {
885 // In order to do a accelerate we need at least 30 ms of audio data.
886 if (samples_left >= samples_30_ms) {
887 // Already have enough data, so we do not need to extract any more.
888 decision_logic_->set_sample_memory(samples_left);
889 decision_logic_->set_prev_time_scale(true);
890 return 0;
891 } else if (samples_left >= samples_10_ms &&
892 decoder_frame_length_ >= samples_30_ms) {
893 // Avoid decoding more data as it might overflow the playout buffer.
894 *operation = kNormal;
895 return 0;
896 } else if (samples_left < samples_20_ms &&
897 decoder_frame_length_ < samples_30_ms) {
898 // Build up decoded data by decoding at least 20 ms of audio data. Do
899 // not perform accelerate yet, but wait until we only need to do one
900 // decoding.
901 required_samples = 2 * output_size_samples_;
902 *operation = kNormal;
903 }
904 // If none of the above is true, we have one of two possible situations:
905 // (1) 20 ms <= samples_left < 30 ms and decoder_frame_length_ < 30 ms; or
906 // (2) samples_left < 10 ms and decoder_frame_length_ >= 30 ms.
907 // In either case, we move on with the accelerate decision, and decode one
908 // frame now.
909 break;
910 }
911 case kPreemptiveExpand: {
912 // In order to do a preemptive expand we need at least 30 ms of decoded
913 // audio data.
914 if ((samples_left >= samples_30_ms) ||
915 (samples_left >= samples_10_ms &&
916 decoder_frame_length_ >= samples_30_ms)) {
917 // Already have enough data, so we do not need to extract any more.
918 // Or, avoid decoding more data as it might overflow the playout buffer.
919 // Still try preemptive expand, though.
920 decision_logic_->set_sample_memory(samples_left);
921 decision_logic_->set_prev_time_scale(true);
922 return 0;
923 }
924 if (samples_left < samples_20_ms &&
925 decoder_frame_length_ < samples_30_ms) {
926 // Build up decoded data by decoding at least 20 ms of audio data.
927 // Still try to perform preemptive expand.
928 required_samples = 2 * output_size_samples_;
929 }
930 // Move on with the preemptive expand decision.
931 break;
932 }
933 default: {
934 // Do nothing.
935 }
936 }
937
938 // Get packets from buffer.
939 int extracted_samples = 0;
940 if (header &&
941 *operation != kAlternativePlc &&
942 *operation != kAlternativePlcIncreaseTimestamp &&
943 *operation != kAudioRepetition &&
944 *operation != kAudioRepetitionIncreaseTimestamp) {
945 sync_buffer_->IncreaseEndTimestamp(header->timestamp - end_timestamp);
946 if (decision_logic_->CngOff()) {
947 // Adjustment of timestamp only corresponds to an actual packet loss
948 // if comfort noise is not played. If comfort noise was just played,
949 // this adjustment of timestamp is only done to get back in sync with the
950 // stream timestamp; no loss to report.
951 stats_.LostSamples(header->timestamp - end_timestamp);
952 }
953
954 if (*operation != kRfc3389Cng) {
955 // We are about to decode and use a non-CNG packet.
956 decision_logic_->SetCngOff();
957 }
958 // Reset CNG timestamp as a new packet will be delivered.
959 // (Also if this is a CNG packet, since playedOutTS is updated.)
960 decision_logic_->set_generated_noise_samples(0);
961
962 extracted_samples = ExtractPackets(required_samples, packet_list);
963 if (extracted_samples < 0) {
964 LOG_F(LS_WARNING) << "Failed to extract packets from buffer.";
965 return kPacketBufferCorruption;
966 }
967 }
968
969 if (*operation == kAccelerate ||
970 *operation == kPreemptiveExpand) {
971 decision_logic_->set_sample_memory(samples_left + extracted_samples);
972 decision_logic_->set_prev_time_scale(true);
973 }
974
975 if (*operation == kAccelerate) {
976 // Check that we have enough data (30ms) to do accelerate.
977 if (extracted_samples + samples_left < samples_30_ms) {
978 // TODO(hlundin): Write test for this.
979 // Not enough, do normal operation instead.
980 *operation = kNormal;
981 }
982 }
983
984 timestamp_ = end_timestamp;
985 return 0;
986}
987
988int NetEqImpl::Decode(PacketList* packet_list, Operations* operation,
989 int* decoded_length,
990 AudioDecoder::SpeechType* speech_type) {
991 *speech_type = AudioDecoder::kSpeech;
992 AudioDecoder* decoder = NULL;
993 if (!packet_list->empty()) {
994 const Packet* packet = packet_list->front();
995 int payload_type = packet->header.payloadType;
996 if (!decoder_database_->IsComfortNoise(payload_type)) {
997 decoder = decoder_database_->GetDecoder(payload_type);
998 assert(decoder);
999 if (!decoder) {
1000 LOG_FERR1(LS_WARNING, GetDecoder, payload_type);
1001 PacketBuffer::DeleteAllPackets(packet_list);
1002 return kDecoderNotFound;
1003 }
1004 bool decoder_changed;
1005 decoder_database_->SetActiveDecoder(payload_type, &decoder_changed);
1006 if (decoder_changed) {
1007 // We have a new decoder. Re-init some values.
1008 const DecoderDatabase::DecoderInfo* decoder_info = decoder_database_
1009 ->GetDecoderInfo(payload_type);
1010 assert(decoder_info);
1011 if (!decoder_info) {
1012 LOG_FERR1(LS_WARNING, GetDecoderInfo, payload_type);
1013 PacketBuffer::DeleteAllPackets(packet_list);
1014 return kDecoderNotFound;
1015 }
1016 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->channels());
1017 sync_buffer_->set_end_timestamp(timestamp_);
1018 playout_timestamp_ = timestamp_;
1019 }
1020 }
1021 }
1022
1023 if (reset_decoder_) {
1024 // TODO(hlundin): Write test for this.
1025 // Reset decoder.
1026 if (decoder) {
1027 decoder->Init();
1028 }
1029 // Reset comfort noise decoder.
1030 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
1031 if (cng_decoder) {
1032 cng_decoder->Init();
1033 }
1034 reset_decoder_ = false;
1035 }
1036
1037#ifdef LEGACY_BITEXACT
1038 // Due to a bug in old SignalMCU, it could happen that CNG operation was
1039 // decided, but a speech packet was provided. The speech packet will be used
1040 // to update the comfort noise decoder, as if it was a SID frame, which is
1041 // clearly wrong.
1042 if (*operation == kRfc3389Cng) {
1043 return 0;
1044 }
1045#endif
1046
1047 *decoded_length = 0;
1048 // Update codec-internal PLC state.
1049 if ((*operation == kMerge) && decoder && decoder->HasDecodePlc()) {
1050 decoder->DecodePlc(1, &decoded_buffer_[*decoded_length]);
1051 }
1052
1053 int return_value = DecodeLoop(packet_list, operation, decoder,
1054 decoded_length, speech_type);
1055
1056 if (*decoded_length < 0) {
1057 // Error returned from the decoder.
1058 *decoded_length = 0;
1059 sync_buffer_->IncreaseEndTimestamp(decoder_frame_length_);
1060 int error_code = 0;
1061 if (decoder)
1062 error_code = decoder->ErrorCode();
1063 if (error_code != 0) {
1064 // Got some error code from the decoder.
1065 decoder_error_code_ = error_code;
1066 return_value = kDecoderErrorCode;
1067 } else {
1068 // Decoder does not implement error codes. Return generic error.
1069 return_value = kOtherDecoderError;
1070 }
1071 LOG_FERR2(LS_WARNING, DecodeLoop, error_code, packet_list->size());
1072 *operation = kExpand; // Do expansion to get data instead.
1073 }
1074 if (*speech_type != AudioDecoder::kComfortNoise) {
1075 // Don't increment timestamp if codec returned CNG speech type
1076 // since in this case, the we will increment the CNGplayedTS counter.
1077 // Increase with number of samples per channel.
1078 assert(*decoded_length == 0 ||
1079 (decoder && decoder->channels() == sync_buffer_->Channels()));
1080 sync_buffer_->IncreaseEndTimestamp(*decoded_length /
1081 sync_buffer_->Channels());
1082 }
1083 return return_value;
1084}
1085
1086int NetEqImpl::DecodeLoop(PacketList* packet_list, Operations* operation,
1087 AudioDecoder* decoder, int* decoded_length,
1088 AudioDecoder::SpeechType* speech_type) {
1089 Packet* packet = NULL;
1090 if (!packet_list->empty()) {
1091 packet = packet_list->front();
1092 }
1093 // Do decoding.
1094 while (packet &&
1095 !decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1096 assert(decoder); // At this point, we must have a decoder object.
1097 // The number of channels in the |sync_buffer_| should be the same as the
1098 // number decoder channels.
1099 assert(sync_buffer_->Channels() == decoder->channels());
1100 assert(decoded_buffer_length_ >= kMaxFrameSize * decoder->channels());
1101 assert(*operation == kNormal || *operation == kAccelerate ||
1102 *operation == kMerge || *operation == kPreemptiveExpand);
1103 packet_list->pop_front();
henrik.lundin@webrtc.org63464a92013-01-30 09:41:56 +00001104 int payload_length = packet->payload_length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001105 int16_t decode_length;
1106 if (!packet->primary) {
1107 // This is a redundant payload; call the special decoder method.
1108 LOG(LS_VERBOSE) << "Decoding packet (redundant):" <<
1109 " ts=" << packet->header.timestamp <<
1110 ", sn=" << packet->header.sequenceNumber <<
1111 ", pt=" << static_cast<int>(packet->header.payloadType) <<
1112 ", ssrc=" << packet->header.ssrc <<
1113 ", len=" << packet->payload_length;
1114 decode_length = decoder->DecodeRedundant(
1115 packet->payload, packet->payload_length,
1116 &decoded_buffer_[*decoded_length], speech_type);
1117 } else {
1118 LOG(LS_VERBOSE) << "Decoding packet: ts=" << packet->header.timestamp <<
1119 ", sn=" << packet->header.sequenceNumber <<
1120 ", pt=" << static_cast<int>(packet->header.payloadType) <<
1121 ", ssrc=" << packet->header.ssrc <<
1122 ", len=" << packet->payload_length;
1123 decode_length = decoder->Decode(packet->payload,
1124 packet->payload_length,
1125 &decoded_buffer_[*decoded_length],
1126 speech_type);
1127 }
1128
1129 delete[] packet->payload;
1130 delete packet;
1131 if (decode_length > 0) {
1132 *decoded_length += decode_length;
1133 // Update |decoder_frame_length_| with number of samples per channel.
1134 decoder_frame_length_ = decode_length / decoder->channels();
1135 LOG(LS_VERBOSE) << "Decoded " << decode_length << " samples (" <<
1136 decoder->channels() << " channel(s) -> " << decoder_frame_length_ <<
1137 " samples per channel)";
1138 } else if (decode_length < 0) {
1139 // Error.
henrik.lundin@webrtc.org63464a92013-01-30 09:41:56 +00001140 LOG_FERR2(LS_WARNING, Decode, decode_length, payload_length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001141 *decoded_length = -1;
1142 PacketBuffer::DeleteAllPackets(packet_list);
1143 break;
1144 }
1145 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1146 // Guard against overflow.
1147 LOG_F(LS_WARNING) << "Decoded too much.";
1148 PacketBuffer::DeleteAllPackets(packet_list);
1149 return kDecodedTooMuch;
1150 }
1151 if (!packet_list->empty()) {
1152 packet = packet_list->front();
1153 } else {
1154 packet = NULL;
1155 }
1156 } // End of decode loop.
1157
1158 // If the list is not empty at this point, it must hold exactly one CNG
1159 // packet.
1160 assert(packet_list->empty() ||
1161 (packet_list->size() == 1 &&
1162 decoder_database_->IsComfortNoise(packet->header.payloadType)));
1163 return 0;
1164}
1165
1166void NetEqImpl::DoNormal(const int16_t* decoded_buffer, size_t decoded_length,
1167 AudioDecoder::SpeechType speech_type, bool play_dtmf,
1168 AudioMultiVector<int16_t>* algorithm_buffer) {
1169 assert(decoder_database_.get());
1170 assert(background_noise_);
1171 assert(expand_);
1172 Normal normal(fs_hz_, decoder_database_.get(), *background_noise_, expand_);
1173 assert(mute_factor_array_.get());
1174 normal.Process(decoded_buffer, decoded_length, last_mode_,
1175 mute_factor_array_.get(), algorithm_buffer);
1176 if (decoded_length != 0) {
1177 last_mode_ = kModeNormal;
1178 }
1179
1180 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1181 if ((speech_type == AudioDecoder::kComfortNoise)
1182 || ((last_mode_ == kModeCodecInternalCng)
1183 && (decoded_length == 0))) {
1184 // TODO(hlundin): Remove second part of || statement above.
1185 last_mode_ = kModeCodecInternalCng;
1186 }
1187
1188 if (!play_dtmf) {
1189 dtmf_tone_generator_->Reset();
1190 }
1191}
1192
1193void NetEqImpl::DoMerge(int16_t* decoded_buffer, size_t decoded_length,
1194 AudioDecoder::SpeechType speech_type, bool play_dtmf,
1195 AudioMultiVector<int16_t>* algorithm_buffer) {
1196 Merge merge(fs_hz_, algorithm_buffer->Channels(), expand_, sync_buffer_);
1197 assert(mute_factor_array_.get());
1198 int new_length = merge.Process(decoded_buffer, decoded_length,
1199 mute_factor_array_.get(), algorithm_buffer);
1200
1201 // Update in-call and post-call statistics.
1202 if (expand_->MuteFactor(0) == 0) {
1203 // Expand generates only noise.
1204 stats_.ExpandedNoiseSamples(new_length - decoded_length);
1205 } else {
1206 // Expansion generates more than only noise.
1207 stats_.ExpandedVoiceSamples(new_length - decoded_length);
1208 }
1209
1210 last_mode_ = kModeMerge;
1211 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1212 if (speech_type == AudioDecoder::kComfortNoise) {
1213 last_mode_ = kModeCodecInternalCng;
1214 }
1215 expand_->Reset();
1216 if (!play_dtmf) {
1217 dtmf_tone_generator_->Reset();
1218 }
1219}
1220
1221int NetEqImpl::DoExpand(bool play_dtmf,
1222 AudioMultiVector<int16_t>* algorithm_buffer) {
1223 while ((sync_buffer_->FutureLength() - expand_->overlap_length()) <
1224 static_cast<size_t>(output_size_samples_)) {
1225 algorithm_buffer->Clear();
1226 int return_value = expand_->Process(algorithm_buffer);
1227 int length = algorithm_buffer->Size();
1228
1229 // Update in-call and post-call statistics.
1230 if (expand_->MuteFactor(0) == 0) {
1231 // Expand operation generates only noise.
1232 stats_.ExpandedNoiseSamples(length);
1233 } else {
1234 // Expand operation generates more than only noise.
1235 stats_.ExpandedVoiceSamples(length);
1236 }
1237
1238 last_mode_ = kModeExpand;
1239
1240 if (return_value < 0) {
1241 return return_value;
1242 }
1243
1244 sync_buffer_->PushBack(*algorithm_buffer);
1245 algorithm_buffer->Clear();
1246 }
1247 if (!play_dtmf) {
1248 dtmf_tone_generator_->Reset();
1249 }
1250 return 0;
1251}
1252
1253int NetEqImpl::DoAccelerate(int16_t* decoded_buffer, size_t decoded_length,
1254 AudioDecoder::SpeechType speech_type,
1255 bool play_dtmf,
1256 AudioMultiVector<int16_t>* algorithm_buffer) {
1257 const size_t required_samples = 240 * fs_mult_; // Must have 30 ms.
1258 int borrowed_samples_per_channel = 0;
1259 size_t num_channels = algorithm_buffer->Channels();
1260 size_t decoded_length_per_channel = decoded_length / num_channels;
1261 if (decoded_length_per_channel < required_samples) {
1262 // Must move data from the |sync_buffer_| in order to get 30 ms.
1263 borrowed_samples_per_channel = required_samples -
1264 decoded_length_per_channel;
1265 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1266 decoded_buffer,
1267 sizeof(int16_t) * decoded_length);
1268 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1269 decoded_buffer);
1270 decoded_length = required_samples * num_channels;
1271 }
1272
1273 int16_t samples_removed;
1274 Accelerate accelerate(fs_hz_, num_channels, *background_noise_);
1275 Accelerate::ReturnCodes return_code = accelerate.Process(decoded_buffer,
1276 decoded_length,
1277 algorithm_buffer,
1278 &samples_removed);
1279 stats_.AcceleratedSamples(samples_removed);
1280 switch (return_code) {
1281 case Accelerate::kSuccess:
1282 last_mode_ = kModeAccelerateSuccess;
1283 break;
1284 case Accelerate::kSuccessLowEnergy:
1285 last_mode_ = kModeAccelerateLowEnergy;
1286 break;
1287 case Accelerate::kNoStretch:
1288 last_mode_ = kModeAccelerateFail;
1289 break;
1290 case Accelerate::kError:
1291 // TODO(hlundin): Map to kModeError instead?
1292 last_mode_ = kModeAccelerateFail;
1293 return kAccelerateError;
1294 }
1295
1296 if (borrowed_samples_per_channel > 0) {
1297 // Copy borrowed samples back to the |sync_buffer_|.
1298 int length = algorithm_buffer->Size();
1299 if (length < borrowed_samples_per_channel) {
1300 // This destroys the beginning of the buffer, but will not cause any
1301 // problems.
1302 sync_buffer_->ReplaceAtIndex(*algorithm_buffer,
1303 sync_buffer_->Size() -
1304 borrowed_samples_per_channel);
1305 sync_buffer_->PushFrontZeros(borrowed_samples_per_channel - length);
1306 algorithm_buffer->PopFront(length);
1307 assert(algorithm_buffer->Empty());
1308 } else {
1309 sync_buffer_->ReplaceAtIndex(*algorithm_buffer,
1310 borrowed_samples_per_channel,
1311 sync_buffer_->Size() -
1312 borrowed_samples_per_channel);
1313 algorithm_buffer->PopFront(borrowed_samples_per_channel);
1314 }
1315 }
1316
1317 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1318 if (speech_type == AudioDecoder::kComfortNoise) {
1319 last_mode_ = kModeCodecInternalCng;
1320 }
1321 if (!play_dtmf) {
1322 dtmf_tone_generator_->Reset();
1323 }
1324 expand_->Reset();
1325 return 0;
1326}
1327
1328int NetEqImpl::DoPreemptiveExpand(int16_t* decoded_buffer,
1329 size_t decoded_length,
1330 AudioDecoder::SpeechType speech_type,
1331 bool play_dtmf,
1332 AudioMultiVector<int16_t>* algorithm_buffer) {
1333 const size_t required_samples = 240 * fs_mult_; // Must have 30 ms.
1334 size_t num_channels = algorithm_buffer->Channels();
1335 int borrowed_samples_per_channel = 0;
1336 int old_borrowed_samples_per_channel = 0;
1337 size_t decoded_length_per_channel = decoded_length / num_channels;
1338 if (decoded_length_per_channel < required_samples) {
1339 // Must move data from the |sync_buffer_| in order to get 30 ms.
1340 borrowed_samples_per_channel = required_samples -
1341 decoded_length_per_channel;
1342 // Calculate how many of these were already played out.
1343 old_borrowed_samples_per_channel = borrowed_samples_per_channel -
1344 sync_buffer_->FutureLength();
1345 old_borrowed_samples_per_channel = std::max(
1346 0, old_borrowed_samples_per_channel);
1347 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1348 decoded_buffer,
1349 sizeof(int16_t) * decoded_length);
1350 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1351 decoded_buffer);
1352 decoded_length = required_samples * num_channels;
1353 }
1354
1355 int16_t samples_added;
1356 PreemptiveExpand preemptive_expand(fs_hz_, num_channels, *background_noise_);
1357 PreemptiveExpand::ReturnCodes return_code = preemptive_expand.Process(
1358 decoded_buffer, decoded_length, old_borrowed_samples_per_channel,
1359 algorithm_buffer, &samples_added);
1360 stats_.PreemptiveExpandedSamples(samples_added);
1361 switch (return_code) {
1362 case PreemptiveExpand::kSuccess:
1363 last_mode_ = kModePreemptiveExpandSuccess;
1364 break;
1365 case PreemptiveExpand::kSuccessLowEnergy:
1366 last_mode_ = kModePreemptiveExpandLowEnergy;
1367 break;
1368 case PreemptiveExpand::kNoStretch:
1369 last_mode_ = kModePreemptiveExpandFail;
1370 break;
1371 case PreemptiveExpand::kError:
1372 // TODO(hlundin): Map to kModeError instead?
1373 last_mode_ = kModePreemptiveExpandFail;
1374 return kPreemptiveExpandError;
1375 }
1376
1377 if (borrowed_samples_per_channel > 0) {
1378 // Copy borrowed samples back to the |sync_buffer_|.
1379 sync_buffer_->ReplaceAtIndex(
1380 *algorithm_buffer, borrowed_samples_per_channel,
1381 sync_buffer_->Size() - borrowed_samples_per_channel);
1382 algorithm_buffer->PopFront(borrowed_samples_per_channel);
1383 }
1384
1385 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1386 if (speech_type == AudioDecoder::kComfortNoise) {
1387 last_mode_ = kModeCodecInternalCng;
1388 }
1389 if (!play_dtmf) {
1390 dtmf_tone_generator_->Reset();
1391 }
1392 expand_->Reset();
1393 return 0;
1394}
1395
1396int NetEqImpl::DoRfc3389Cng(PacketList* packet_list, bool play_dtmf,
1397 AudioMultiVector<int16_t>* algorithm_buffer) {
1398 if (!packet_list->empty()) {
1399 // Must have exactly one SID frame at this point.
1400 assert(packet_list->size() == 1);
1401 Packet* packet = packet_list->front();
1402 packet_list->pop_front();
1403 // Temp hack to get correct PT for CNG.
1404 // TODO(hlundin): Update universal.rtp and remove this hack.
1405 if (fs_hz_ == 16000) {
1406 packet->header.payloadType = 98;
1407 } else if (fs_hz_ == 32000) {
1408 packet->header.payloadType = 99;
1409 }
1410 // End of hack.
1411 // UpdateParameters() deletes |packet|.
1412 if (comfort_noise_->UpdateParameters(packet) ==
1413 ComfortNoise::kInternalError) {
1414 LOG_FERR0(LS_WARNING, UpdateParameters);
1415 algorithm_buffer->Zeros(output_size_samples_);
1416 return -comfort_noise_->internal_error_code();
1417 }
1418 }
1419 int cn_return = comfort_noise_->Generate(output_size_samples_,
1420 algorithm_buffer);
1421 expand_->Reset();
1422 last_mode_ = kModeRfc3389Cng;
1423 if (!play_dtmf) {
1424 dtmf_tone_generator_->Reset();
1425 }
1426 if (cn_return == ComfortNoise::kInternalError) {
1427 LOG_FERR1(LS_WARNING, comfort_noise_->Generate, cn_return);
1428 decoder_error_code_ = comfort_noise_->internal_error_code();
1429 return kComfortNoiseErrorCode;
1430 } else if (cn_return == ComfortNoise::kUnknownPayloadType) {
1431 LOG_FERR1(LS_WARNING, comfort_noise_->Generate, cn_return);
1432 return kUnknownRtpPayloadType;
1433 }
1434 return 0;
1435}
1436
1437void NetEqImpl::DoCodecInternalCng(
1438 AudioMultiVector<int16_t>* algorithm_buffer) {
1439 int length = 0;
1440 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1441 int16_t decoded_buffer[kMaxFrameSize];
1442 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1443 if (decoder) {
1444 const uint8_t* dummy_payload = NULL;
1445 AudioDecoder::SpeechType speech_type;
1446 length = decoder->Decode(dummy_payload, 0, decoded_buffer, &speech_type);
1447 }
1448 Normal normal(fs_hz_, decoder_database_.get(), *background_noise_, expand_);
1449 assert(mute_factor_array_.get());
1450 normal.Process(decoded_buffer, length, last_mode_, mute_factor_array_.get(),
1451 algorithm_buffer);
1452 last_mode_ = kModeCodecInternalCng;
1453 expand_->Reset();
1454}
1455
1456int NetEqImpl::DoDtmf(const DtmfEvent& dtmf_event, bool* play_dtmf,
1457 AudioMultiVector<int16_t>* algorithm_buffer) {
1458 bool dtmf_switch = false;
1459 if ((last_mode_ != kModeDtmf) && !dtmf_tone_generator_->initialized()) {
1460 // Special case; see below.
1461 // We must catch this before calling Generate, since |initialized| is
1462 // modified in that call.
1463 dtmf_switch = true;
1464 }
1465
1466 int dtmf_return_value = 0;
1467 if (!dtmf_tone_generator_->initialized()) {
1468 // Initialize if not already done.
1469 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1470 dtmf_event.volume);
1471 }
1472 if (dtmf_return_value == 0) {
1473 // Generate DTMF signal.
1474 dtmf_return_value = dtmf_tone_generator_->Generate(output_size_samples_,
1475 algorithm_buffer);
1476 }
1477 if (dtmf_return_value < 0) {
1478 algorithm_buffer->Zeros(output_size_samples_);
1479 return dtmf_return_value;
1480 }
1481
1482 if (dtmf_switch) {
1483 // This is the special case where the previous operation was DTMF overdub,
1484 // but the current instruction is "regular" DTMF. We must make sure that the
1485 // DTMF does not have any discontinuities. The first DTMF sample that we
1486 // generate now must be played out immediately, wherefore it must be copied
1487 // to the speech buffer.
1488 // TODO(hlundin): This code seems incorrect. (Legacy.) Write test and
1489 // verify correct operation.
1490 assert(false);
1491 // Must generate enough data to replace all of the |sync_buffer_| "future".
1492 int required_length = sync_buffer_->FutureLength();
1493 assert(dtmf_tone_generator_->initialized());
1494 dtmf_return_value = dtmf_tone_generator_->Generate(required_length,
1495 algorithm_buffer);
1496 assert((size_t) required_length == algorithm_buffer->Size());
1497 if (dtmf_return_value < 0) {
1498 algorithm_buffer->Zeros(output_size_samples_);
1499 return dtmf_return_value;
1500 }
1501
1502 // Overwrite the "future" part of the speech buffer with the new DTMF data.
1503 // TODO(hlundin): It seems that this overwriting has gone lost.
1504 // Not adapted for multi-channel yet.
1505 assert(algorithm_buffer->Channels() == 1);
1506 if (algorithm_buffer->Channels() != 1) {
1507 LOG(LS_WARNING) << "DTMF not supported for more than one channel";
1508 return kStereoNotSupported;
1509 }
1510 // Shuffle the remaining data to the beginning of algorithm buffer.
1511 algorithm_buffer->PopFront(sync_buffer_->FutureLength());
1512 }
1513
1514 sync_buffer_->IncreaseEndTimestamp(output_size_samples_);
1515 expand_->Reset();
1516 last_mode_ = kModeDtmf;
1517
1518 // Set to false because the DTMF is already in the algorithm buffer.
1519 *play_dtmf = false;
1520 return 0;
1521}
1522
1523void NetEqImpl::DoAlternativePlc(bool increase_timestamp,
1524 AudioMultiVector<int16_t>* algorithm_buffer) {
1525 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1526 int length;
1527 if (decoder && decoder->HasDecodePlc()) {
1528 // Use the decoder's packet-loss concealment.
1529 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1530 int16_t decoded_buffer[kMaxFrameSize];
1531 length = decoder->DecodePlc(1, decoded_buffer);
1532 if (length > 0) {
1533 algorithm_buffer->PushBackInterleaved(decoded_buffer, length);
1534 } else {
1535 length = 0;
1536 }
1537 } else {
1538 // Do simple zero-stuffing.
1539 length = output_size_samples_;
1540 algorithm_buffer->Zeros(length);
1541 // By not advancing the timestamp, NetEq inserts samples.
1542 stats_.AddZeros(length);
1543 }
1544 if (increase_timestamp) {
1545 sync_buffer_->IncreaseEndTimestamp(length);
1546 }
1547 expand_->Reset();
1548}
1549
1550int NetEqImpl::DtmfOverdub(const DtmfEvent& dtmf_event, size_t num_channels,
1551 int16_t* output) const {
1552 size_t out_index = 0;
1553 int overdub_length = output_size_samples_; // Default value.
1554
1555 if (sync_buffer_->dtmf_index() > sync_buffer_->next_index()) {
1556 // Special operation for transition from "DTMF only" to "DTMF overdub".
1557 out_index = std::min(
1558 sync_buffer_->dtmf_index() - sync_buffer_->next_index(),
1559 static_cast<size_t>(output_size_samples_));
1560 overdub_length = output_size_samples_ - out_index;
1561 }
1562
1563 AudioMultiVector<int16_t> dtmf_output(num_channels);
1564 int dtmf_return_value = 0;
1565 if (!dtmf_tone_generator_->initialized()) {
1566 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1567 dtmf_event.volume);
1568 }
1569 if (dtmf_return_value == 0) {
1570 dtmf_return_value = dtmf_tone_generator_->Generate(overdub_length,
1571 &dtmf_output);
1572 assert((size_t) overdub_length == dtmf_output.Size());
1573 }
1574 dtmf_output.ReadInterleaved(overdub_length, &output[out_index]);
1575 return dtmf_return_value < 0 ? dtmf_return_value : 0;
1576}
1577
1578int NetEqImpl::ExtractPackets(int required_samples, PacketList* packet_list) {
1579 bool first_packet = true;
1580 uint8_t prev_payload_type = 0;
1581 uint32_t prev_timestamp = 0;
1582 uint16_t prev_sequence_number = 0;
1583 bool next_packet_available = false;
1584
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001585 const RTPHeader* header = packet_buffer_->NextRtpHeader();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001586 assert(header);
1587 if (!header) {
1588 return -1;
1589 }
1590 int32_t first_timestamp = header->timestamp;
1591 int extracted_samples = 0;
1592
1593 // Packet extraction loop.
1594 do {
1595 timestamp_ = header->timestamp;
1596 int discard_count = 0;
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001597 Packet* packet = packet_buffer_->GetNextPacket(&discard_count);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001598 // |header| may be invalid after the |packet_buffer_| operation.
1599 header = NULL;
1600 if (!packet) {
1601 LOG_FERR1(LS_ERROR, GetNextPacket, discard_count) <<
1602 "Should always be able to extract a packet here";
1603 assert(false); // Should always be able to extract a packet here.
1604 return -1;
1605 }
1606 stats_.PacketsDiscarded(discard_count);
1607 // Store waiting time in ms; packets->waiting_time is in "output blocks".
1608 stats_.StoreWaitingTime(packet->waiting_time * kOutputSizeMs);
1609 assert(packet->payload_length > 0);
1610 packet_list->push_back(packet); // Store packet in list.
1611
1612 if (first_packet) {
1613 first_packet = false;
1614 prev_sequence_number = packet->header.sequenceNumber;
1615 prev_timestamp = packet->header.timestamp;
1616 prev_payload_type = packet->header.payloadType;
1617 }
1618
1619 // Store number of extracted samples.
1620 int packet_duration = 0;
1621 AudioDecoder* decoder = decoder_database_->GetDecoder(
1622 packet->header.payloadType);
1623 if (decoder) {
1624 packet_duration = decoder->PacketDuration(packet->payload,
1625 packet->payload_length);
1626 } else {
1627 LOG_FERR1(LS_WARNING, GetDecoder, packet->header.payloadType) <<
1628 "Could not find a decoder for a packet about to be extracted.";
1629 assert(false);
1630 }
1631 if (packet_duration <= 0) {
1632 // Decoder did not return a packet duration. Assume that the packet
1633 // contains the same number of samples as the previous one.
1634 packet_duration = decoder_frame_length_;
1635 }
1636 extracted_samples = packet->header.timestamp - first_timestamp +
1637 packet_duration;
1638
1639 // Check what packet is available next.
1640 header = packet_buffer_->NextRtpHeader();
1641 next_packet_available = false;
1642 if (header && prev_payload_type == header->payloadType) {
1643 int16_t seq_no_diff = header->sequenceNumber - prev_sequence_number;
1644 int32_t ts_diff = header->timestamp - prev_timestamp;
1645 if (seq_no_diff == 1 ||
1646 (seq_no_diff == 0 && ts_diff == decoder_frame_length_)) {
1647 // The next sequence number is available, or the next part of a packet
1648 // that was split into pieces upon insertion.
1649 next_packet_available = true;
1650 }
1651 prev_sequence_number = header->sequenceNumber;
1652 }
1653 } while (extracted_samples < required_samples && next_packet_available);
1654
1655 return extracted_samples;
1656}
1657
1658void NetEqImpl::SetSampleRateAndChannels(int fs_hz, size_t channels) {
1659 LOG_API2(fs_hz, channels);
1660 // TODO(hlundin): Change to an enumerator and skip assert.
1661 assert(fs_hz == 8000 || fs_hz == 16000 || fs_hz == 32000 || fs_hz == 48000);
1662 assert(channels > 0);
1663
1664 fs_hz_ = fs_hz;
1665 fs_mult_ = fs_hz / 8000;
1666 output_size_samples_ = kOutputSizeMs * 8 * fs_mult_;
1667 decoder_frame_length_ = 3 * output_size_samples_; // Initialize to 30ms.
1668
1669 last_mode_ = kModeNormal;
1670
1671 // Create a new array of mute factors and set all to 1.
1672 mute_factor_array_.reset(new int16_t[channels]);
1673 for (size_t i = 0; i < channels; ++i) {
1674 mute_factor_array_[i] = 16384; // 1.0 in Q14.
1675 }
1676
1677 // Reset comfort noise decoder, if there is one active.
1678 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
1679 if (cng_decoder) {
1680 cng_decoder->Init();
1681 }
1682
1683 // Reinit post-decode VAD with new sample rate.
1684 assert(vad_.get()); // Cannot be NULL here.
1685 vad_->Init();
1686
1687 // Delete sync buffer and create a new one.
1688 if (sync_buffer_) {
1689 delete sync_buffer_;
1690 }
1691 sync_buffer_ = new SyncBuffer(channels, kSyncBufferSize * fs_mult_);
1692
1693 // Delete BackgroundNoise object and create a new one.
1694 if (background_noise_) {
1695 delete background_noise_;
1696 }
1697 background_noise_ = new BackgroundNoise(channels);
1698
1699 // Reset random vector.
1700 random_vector_.Reset();
1701
1702 // Delete Expand object and create a new one.
1703 if (expand_) {
1704 delete expand_;
1705 }
1706 expand_ = new Expand(background_noise_, sync_buffer_, &random_vector_, fs_hz,
1707 channels);
1708 // Move index so that we create a small set of future samples (all 0).
1709 sync_buffer_->set_next_index(sync_buffer_->next_index() -
1710 expand_->overlap_length());
1711
1712 // Delete ComfortNoise object and create a new one.
1713 if (comfort_noise_) {
1714 delete comfort_noise_;
1715 }
1716 comfort_noise_ = new ComfortNoise(fs_hz, decoder_database_.get(),
1717 sync_buffer_);
1718
1719 // Verify that |decoded_buffer_| is long enough.
1720 if (decoded_buffer_length_ < kMaxFrameSize * channels) {
1721 // Reallocate to larger size.
1722 decoded_buffer_length_ = kMaxFrameSize * channels;
1723 decoded_buffer_.reset(new int16_t[decoded_buffer_length_]);
1724 }
1725
1726 // Communicate new sample rate and output size to DecisionLogic object.
1727 assert(decision_logic_.get());
1728 decision_logic_->SetSampleRate(fs_hz_, output_size_samples_);
1729}
1730
1731NetEqOutputType NetEqImpl::LastOutputType() {
1732 assert(vad_.get());
1733 assert(expand_);
1734 if (last_mode_ == kModeCodecInternalCng || last_mode_ == kModeRfc3389Cng) {
1735 return kOutputCNG;
1736 } else if (vad_->running() && !vad_->active_speech()) {
1737 return kOutputVADPassive;
1738 } else if (last_mode_ == kModeExpand && expand_->MuteFactor(0) == 0) {
1739 // Expand mode has faded down to background noise only (very long expand).
1740 return kOutputPLCtoCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001741 } else if (last_mode_ == kModeExpand) {
1742 return kOutputPLC;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001743 } else {
1744 return kOutputNormal;
1745 }
1746}
1747
1748} // namespace webrtc