blob: 5508d08702625dfb8d9e1b1b48a2b2faefd4d204 [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];
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +0000377 if (!packet->payload) {
378 LOG_F(LS_ERROR) << "Payload pointer is NULL.";
379 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000380 assert(payload); // Already checked above.
381 memcpy(packet->payload, payload, packet->payload_length);
382 // Insert packet in a packet list.
383 packet_list.push_back(packet);
384 // Save main payloads header for later.
385 memcpy(&main_header, &packet->header, sizeof(main_header));
386 }
387
388 // Reinitialize NetEq if it's needed (changed SSRC or first call).
389 if ((main_header.ssrc != ssrc_) || first_packet_) {
390 rtcp_.Init(main_header.sequenceNumber);
391 first_packet_ = false;
392
393 // Flush the packet buffer and DTMF buffer.
394 packet_buffer_->Flush();
395 dtmf_buffer_->Flush();
396
397 // Store new SSRC.
398 ssrc_ = main_header.ssrc;
399
400 // Update codecs.
401 timestamp_ = main_header.timestamp;
402 current_rtp_payload_type_ = main_header.payloadType;
403
404 // Set MCU to update codec on next SignalMCU call.
405 new_codec_ = true;
406
407 // Reset timestamp scaling.
408 timestamp_scaler_->Reset();
409 }
410
411 // Update RTCP statistics.
412 rtcp_.Update(main_header, receive_timestamp);
413
414 // Check for RED payload type, and separate payloads into several packets.
415 if (decoder_database_->IsRed(main_header.payloadType)) {
416 if (payload_splitter_->SplitRed(&packet_list) != PayloadSplitter::kOK) {
417 LOG_FERR1(LS_WARNING, SplitRed, packet_list.size());
418 PacketBuffer::DeleteAllPackets(&packet_list);
419 return kRedundancySplitError;
420 }
421 // Only accept a few RED payloads of the same type as the main data,
422 // DTMF events and CNG.
423 payload_splitter_->CheckRedPayloads(&packet_list, *decoder_database_);
424 // Update the stored main payload header since the main payload has now
425 // changed.
426 memcpy(&main_header, &packet_list.front()->header, sizeof(main_header));
427 }
428
429 // Check payload types.
430 if (decoder_database_->CheckPayloadTypes(packet_list) ==
431 DecoderDatabase::kDecoderNotFound) {
432 LOG_FERR1(LS_WARNING, CheckPayloadTypes, packet_list.size());
433 PacketBuffer::DeleteAllPackets(&packet_list);
434 return kUnknownRtpPayloadType;
435 }
436
437 // Scale timestamp to internal domain (only for some codecs).
438 timestamp_scaler_->ToInternal(&packet_list);
439
440 // Process DTMF payloads. Cycle through the list of packets, and pick out any
441 // DTMF payloads found.
442 PacketList::iterator it = packet_list.begin();
443 while (it != packet_list.end()) {
444 Packet* current_packet = (*it);
445 assert(current_packet);
446 assert(current_packet->payload);
447 if (decoder_database_->IsDtmf(current_packet->header.payloadType)) {
448 if (dtmf_enabled_) {
449 DtmfEvent event;
450 int ret = DtmfBuffer::ParseEvent(
451 current_packet->header.timestamp,
452 current_packet->payload,
453 current_packet->payload_length,
454 &event);
455 if (ret != DtmfBuffer::kOK) {
456 LOG_FERR2(LS_WARNING, ParseEvent, ret,
457 current_packet->payload_length);
458 PacketBuffer::DeleteAllPackets(&packet_list);
459 return kDtmfParsingError;
460 }
461 if (dtmf_buffer_->InsertEvent(event) != DtmfBuffer::kOK) {
462 LOG_FERR0(LS_WARNING, InsertEvent);
463 PacketBuffer::DeleteAllPackets(&packet_list);
464 return kDtmfInsertError;
465 }
466 }
467 // TODO(hlundin): Let the destructor of Packet handle the payload.
468 delete [] current_packet->payload;
469 delete current_packet;
470 it = packet_list.erase(it);
471 } else {
472 ++it;
473 }
474 }
475
476 // Split payloads into smaller chunks. This also verifies that all payloads
477 // are of a known payload type.
478 int ret = payload_splitter_->SplitAudio(&packet_list, *decoder_database_);
479 if (ret != PayloadSplitter::kOK) {
480 LOG_FERR1(LS_WARNING, SplitAudio, packet_list.size());
481 PacketBuffer::DeleteAllPackets(&packet_list);
482 switch (ret) {
483 case PayloadSplitter::kUnknownPayloadType:
484 return kUnknownRtpPayloadType;
485 case PayloadSplitter::kFrameSplitError:
486 return kFrameSplitError;
487 default:
488 return kOtherError;
489 }
490 }
491
492 // Update bandwidth estimate.
493 if (!packet_list.empty()) {
494 // The list can be empty here if we got nothing but DTMF payloads.
495 AudioDecoder* decoder =
496 decoder_database_->GetDecoder(main_header.payloadType);
497 assert(decoder); // Should always get a valid object, since we have
498 // already checked that the payload types are known.
499 decoder->IncomingPacket(packet_list.front()->payload,
500 packet_list.front()->payload_length,
501 packet_list.front()->header.sequenceNumber,
502 packet_list.front()->header.timestamp,
503 receive_timestamp);
504 }
505
506 // Insert packets in buffer.
507 int temp_bufsize = packet_buffer_->NumPacketsInBuffer();
508 ret = packet_buffer_->InsertPacketList(
509 &packet_list,
510 *decoder_database_,
511 &current_rtp_payload_type_,
512 &current_cng_rtp_payload_type_);
513 if (ret == PacketBuffer::kFlushed) {
514 // Reset DSP timestamp etc. if packet buffer flushed.
515 new_codec_ = true;
516 LOG_F(LS_WARNING) << "Packet buffer flushed";
517 } else if (ret != PacketBuffer::kOK) {
518 LOG_FERR1(LS_WARNING, InsertPacketList, packet_list.size());
519 PacketBuffer::DeleteAllPackets(&packet_list);
520 assert(false);
521 // TODO(hlundin): Take care of error codes.
522 }
523 if (current_rtp_payload_type_ != 0xFF) {
524 const DecoderDatabase::DecoderInfo* dec_info =
525 decoder_database_->GetDecoderInfo(current_rtp_payload_type_);
526 if (!dec_info) {
527 assert(false); // Already checked that the payload type is known.
528 }
529 }
530
531 // TODO(hlundin): Move this code to DelayManager class.
532 const DecoderDatabase::DecoderInfo* dec_info =
533 decoder_database_->GetDecoderInfo(main_header.payloadType);
534 assert(dec_info); // Already checked that the payload type is known.
535 delay_manager_->LastDecoderType(dec_info->codec_type);
536 if (delay_manager_->last_pack_cng_or_dtmf() == 0) {
537 // Calculate the total speech length carried in each packet.
538 temp_bufsize = packet_buffer_->NumPacketsInBuffer() - temp_bufsize;
539 temp_bufsize *= decoder_frame_length_;
540
541 if ((temp_bufsize > 0) &&
542 (temp_bufsize != decision_logic_->packet_length_samples())) {
543 decision_logic_->set_packet_length_samples(temp_bufsize);
544 delay_manager_->SetPacketAudioLength((1000 * temp_bufsize) / fs_hz_);
545 }
546
547 // Update statistics.
548 if ((WebRtc_Word32) (main_header.timestamp - timestamp_) >= 0 &&
549 !new_codec_) {
550 // Only update statistics if incoming packet is not older than last played
551 // out packet, and if new codec flag is not set.
552 delay_manager_->Update(main_header.sequenceNumber, main_header.timestamp,
553 fs_hz_);
554 }
555 } else if (delay_manager_->last_pack_cng_or_dtmf() == -1) {
556 // This is first "normal" packet after CNG or DTMF.
557 // Reset packet time counter and measure time until next packet,
558 // but don't update statistics.
559 delay_manager_->set_last_pack_cng_or_dtmf(0);
560 delay_manager_->ResetPacketIatCount();
561 }
562 return 0;
563}
564
565int NetEqImpl::GetAudioInternal(size_t max_length, int16_t* output,
566 int* samples_per_channel, int* num_channels) {
567 PacketList packet_list;
568 DtmfEvent dtmf_event;
569 Operations operation;
570 bool play_dtmf;
571 int return_value = GetDecision(&operation, &packet_list, &dtmf_event,
572 &play_dtmf);
573 if (return_value != 0) {
574 LOG_FERR1(LS_WARNING, GetDecision, return_value);
575 assert(false);
576 last_mode_ = kModeError;
577 return return_value;
578 }
579 LOG(LS_VERBOSE) << "GetDecision returned operation=" << operation <<
580 " and " << packet_list.size() << " packet(s)";
581
582 AudioDecoder::SpeechType speech_type;
583 int length = 0;
584 int decode_return_value = Decode(&packet_list, &operation,
585 &length, &speech_type);
586
587
588 assert(vad_.get());
589 bool sid_frame_available =
590 (operation == kRfc3389Cng && !packet_list.empty());
591 vad_->Update(decoded_buffer_.get(), length, speech_type,
592 sid_frame_available, fs_hz_);
593
594 AudioMultiVector<int16_t> algorithm_buffer(sync_buffer_->Channels());
595 switch (operation) {
596 case kNormal: {
597 DoNormal(decoded_buffer_.get(), length, speech_type, play_dtmf,
598 &algorithm_buffer);
599 break;
600 }
601 case kMerge: {
602 DoMerge(decoded_buffer_.get(), length, speech_type, play_dtmf,
603 &algorithm_buffer);
604 break;
605 }
606 case kExpand: {
607 return_value = DoExpand(play_dtmf, &algorithm_buffer);
608 break;
609 }
610 case kAccelerate: {
611 return_value = DoAccelerate(decoded_buffer_.get(), length, speech_type,
612 play_dtmf, &algorithm_buffer);
613 break;
614 }
615 case kPreemptiveExpand: {
616 return_value = DoPreemptiveExpand(decoded_buffer_.get(), length,
617 speech_type, play_dtmf,
618 &algorithm_buffer);
619 break;
620 }
621 case kRfc3389Cng:
622 case kRfc3389CngNoPacket: {
623 return_value = DoRfc3389Cng(&packet_list, play_dtmf, &algorithm_buffer);
624 break;
625 }
626 case kCodecInternalCng: {
627 // This handles the case when there is no transmission and the decoder
628 // should produce internal comfort noise.
629 // TODO(hlundin): Write test for codec-internal CNG.
630 DoCodecInternalCng(&algorithm_buffer);
631 break;
632 }
633 case kDtmf: {
634 // TODO(hlundin): Write test for this.
635 return_value = DoDtmf(dtmf_event, &play_dtmf, &algorithm_buffer);
636 break;
637 }
638 case kAlternativePlc: {
639 // TODO(hlundin): Write test for this.
640 DoAlternativePlc(false, &algorithm_buffer);
641 break;
642 }
643 case kAlternativePlcIncreaseTimestamp: {
644 // TODO(hlundin): Write test for this.
645 DoAlternativePlc(true, &algorithm_buffer);
646 break;
647 }
648 case kAudioRepetitionIncreaseTimestamp: {
649 // TODO(hlundin): Write test for this.
650 sync_buffer_->IncreaseEndTimestamp(output_size_samples_);
651 // Skipping break on purpose. Execution should move on into the
652 // next case.
653 }
654 case kAudioRepetition: {
655 // TODO(hlundin): Write test for this.
656 // Copy last |output_size_samples_| from |sync_buffer_| to
657 // |algorithm_buffer|.
658 algorithm_buffer.PushBackFromIndex(
659 *sync_buffer_, sync_buffer_->Size() - output_size_samples_);
660 expand_->Reset();
661 break;
662 }
663 case kUndefined: {
664 LOG_F(LS_ERROR) << "Invalid operation kUndefined.";
665 assert(false); // This should not happen.
666 last_mode_ = kModeError;
667 return kInvalidOperation;
668 }
669 } // End of switch.
670 if (return_value < 0) {
671 return return_value;
672 }
673
674 if (last_mode_ != kModeRfc3389Cng) {
675 comfort_noise_->Reset();
676 }
677
678 // Copy from |algorithm_buffer| to |sync_buffer_|.
679 sync_buffer_->PushBack(algorithm_buffer);
680
681 // Extract data from |sync_buffer_| to |output|.
682 int num_output_samples_per_channel = output_size_samples_;
683 int num_output_samples = output_size_samples_ * sync_buffer_->Channels();
684 if (num_output_samples > static_cast<int>(max_length)) {
685 LOG(LS_WARNING) << "Output array is too short. " << max_length << " < " <<
686 output_size_samples_ << " * " << sync_buffer_->Channels();
687 num_output_samples = max_length;
688 num_output_samples_per_channel = max_length / sync_buffer_->Channels();
689 }
690 int samples_from_sync = sync_buffer_->GetNextAudioInterleaved(
691 num_output_samples_per_channel, output);
692 *num_channels = sync_buffer_->Channels();
693 LOG(LS_VERBOSE) << "Sync buffer (" << *num_channels << " channel(s)):" <<
694 " insert " << algorithm_buffer.Size() << " samples, extract " <<
695 samples_from_sync << " samples";
696 if (samples_from_sync != output_size_samples_) {
697 LOG_F(LS_ERROR) << "samples_from_sync != output_size_samples_";
698 assert(false);
699 memset(output, 0, num_output_samples * sizeof(int16_t));
700 *samples_per_channel = output_size_samples_;
701 last_mode_ = kModeError;
702 return kSampleUnderrun;
703 }
704 *samples_per_channel = output_size_samples_;
705
706 // Should always have overlap samples left in the |sync_buffer_|.
707 assert(sync_buffer_->FutureLength() >= expand_->overlap_length());
708
709 if (play_dtmf) {
710 return_value = DtmfOverdub(dtmf_event, sync_buffer_->Channels(), output);
711 }
712
713 // Update the background noise parameters if last operation wrote data
714 // straight from the decoder to the |sync_buffer_|. That is, none of the
715 // operations that modify the signal can be followed by a parameter update.
716 if ((last_mode_ == kModeNormal) ||
717 (last_mode_ == kModeAccelerateFail) ||
718 (last_mode_ == kModePreemptiveExpandFail) ||
719 (last_mode_ == kModeRfc3389Cng) ||
720 (last_mode_ == kModeCodecInternalCng)) {
721 background_noise_->Update(*sync_buffer_, *vad_.get());
722 }
723
724 if (operation == kDtmf) {
725 // DTMF data was written the end of |sync_buffer_|.
726 // Update index to end of DTMF data in |sync_buffer_|.
727 sync_buffer_->set_dtmf_index(sync_buffer_->Size());
728 }
729
730 if ((last_mode_ != kModeExpand) && (last_mode_ != kModeRfc3389Cng)) {
731 // If last operation was neither expand, nor comfort noise, calculate the
732 // |playout_timestamp_| from the |sync_buffer_|. However, do not update the
733 // |playout_timestamp_| if it would be moved "backwards".
734 uint32_t temp_timestamp = sync_buffer_->end_timestamp() -
735 sync_buffer_->FutureLength();
736 if (static_cast<int32_t>(temp_timestamp - playout_timestamp_) > 0) {
737 playout_timestamp_ = temp_timestamp;
738 }
739 } else {
740 // Use dead reckoning to estimate the |playout_timestamp_|.
741 playout_timestamp_ += output_size_samples_;
742 }
743
744 if (decode_return_value) return decode_return_value;
745 return return_value;
746}
747
748int NetEqImpl::GetDecision(Operations* operation,
749 PacketList* packet_list,
750 DtmfEvent* dtmf_event,
751 bool* play_dtmf) {
752 // Initialize output variables.
753 *play_dtmf = false;
754 *operation = kUndefined;
755
756 // Increment time counters.
757 packet_buffer_->IncrementWaitingTimes();
758 stats_.IncreaseCounter(output_size_samples_, fs_hz_);
759
760 assert(sync_buffer_);
761 uint32_t end_timestamp = sync_buffer_->end_timestamp();
762 if (!new_codec_) {
763 packet_buffer_->DiscardOldPackets(end_timestamp);
764 }
765 const RTPHeader* header = packet_buffer_->NextRtpHeader();
766
767 if (decision_logic_->CngRfc3389On()) {
768 // Because of timestamp peculiarities, we have to "manually" disallow using
769 // a CNG packet with the same timestamp as the one that was last played.
770 // This can happen when using redundancy and will cause the timing to shift.
771 while (header &&
772 decoder_database_->IsComfortNoise(header->payloadType) &&
773 end_timestamp >= header->timestamp) {
774 // Don't use this packet, discard it.
775 // TODO(hlundin): Write test for this case.
776 if (packet_buffer_->DiscardNextPacket() != PacketBuffer::kOK) {
777 assert(false); // Must be ok by design.
778 }
779 // Check buffer again.
780 if (!new_codec_) {
781 packet_buffer_->DiscardOldPackets(end_timestamp);
782 }
783 header = packet_buffer_->NextRtpHeader();
784 }
785 }
786
787 assert(expand_);
788 const int samples_left = sync_buffer_->FutureLength() -
789 expand_->overlap_length();
790 if (last_mode_ == kModeAccelerateSuccess ||
791 last_mode_ == kModeAccelerateLowEnergy ||
792 last_mode_ == kModePreemptiveExpandSuccess ||
793 last_mode_ == kModePreemptiveExpandLowEnergy) {
794 // Subtract (samples_left + output_size_samples_) from sampleMemory.
795 decision_logic_->AddSampleMemory(-(samples_left + output_size_samples_));
796 }
797
798 // Check if it is time to play a DTMF event.
799 if (dtmf_buffer_->GetEvent(end_timestamp +
800 decision_logic_->generated_noise_samples(),
801 dtmf_event)) {
802 *play_dtmf = true;
803 }
804
805 // Get instruction.
806 assert(sync_buffer_);
807 assert(expand_);
808 *operation = decision_logic_->GetDecision(*sync_buffer_,
809 *expand_,
810 decoder_frame_length_,
811 header,
812 last_mode_,
813 *play_dtmf,
814 &reset_decoder_);
815
816 // Check if we already have enough samples in the |sync_buffer_|. If so,
817 // change decision to normal, unless the decision was merge, accelerate, or
818 // preemptive expand.
819 if (samples_left >= output_size_samples_ &&
820 *operation != kMerge &&
821 *operation != kAccelerate &&
822 *operation != kPreemptiveExpand) {
823 *operation = kNormal;
824 return 0;
825 }
826
827 decision_logic_->ExpandDecision(*operation == kExpand);
828
829 // Check conditions for reset.
830 if (new_codec_ || *operation == kUndefined) {
831 // The only valid reason to get kUndefined is that new_codec_ is set.
832 assert(new_codec_);
833 assert(header);
834 if (!header) {
835 LOG_F(LS_ERROR) << "Packet missing where it shouldn't.";
836 return -1;
837 }
838 timestamp_ = header->timestamp;
839 // Adjust |sync_buffer_| timestamp before setting |end_timestamp| to the
840 // new value.
841 sync_buffer_->IncreaseEndTimestamp(timestamp_ - end_timestamp);
842 end_timestamp = header->timestamp;
843 new_codec_ = false;
844 decision_logic_->SoftReset();
845 buffer_level_filter_->Reset();
846 delay_manager_->Reset();
847 stats_.ResetMcu();
848
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +0000849 if (*operation == kRfc3389CngNoPacket
850#ifndef LEGACY_BITEXACT
851 // Without this check, it can happen that a non-CNG packet is sent to
852 // the CNG decoder as if it was a SID frame. This is clearly a bug,
853 // but is kept for now to maintain bit-exactness with the test vectors.
854 && decoder_database_->IsComfortNoise(header->payloadType)
855#endif
856 ) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000857 // Change decision to CNG packet, since we do have a CNG packet, but it
858 // was considered too early to use. Now, use it anyway.
859 *operation = kRfc3389Cng;
860 } else if (*operation != kRfc3389Cng) {
861 *operation = kNormal;
862 }
863 }
864
865 int required_samples = output_size_samples_;
866 const int samples_10_ms = 80 * fs_mult_;
867 const int samples_20_ms = 2 * samples_10_ms;
868 const int samples_30_ms = 3 * samples_10_ms;
869
870 switch (*operation) {
871 case kExpand: {
872 timestamp_ = end_timestamp;
873 return 0;
874 }
875 case kRfc3389CngNoPacket:
876 case kCodecInternalCng: {
877 return 0;
878 }
879 case kDtmf: {
880 // TODO(hlundin): Write test for this.
881 // Update timestamp.
882 timestamp_ = end_timestamp;
883 if (decision_logic_->generated_noise_samples() > 0 &&
884 last_mode_ != kModeDtmf) {
885 // Make a jump in timestamp due to the recently played comfort noise.
886 uint32_t timestamp_jump = decision_logic_->generated_noise_samples();
887 sync_buffer_->IncreaseEndTimestamp(timestamp_jump);
888 timestamp_ += timestamp_jump;
889 }
890 decision_logic_->set_generated_noise_samples(0);
891 return 0;
892 }
893 case kAccelerate: {
894 // In order to do a accelerate we need at least 30 ms of audio data.
895 if (samples_left >= samples_30_ms) {
896 // Already have enough data, so we do not need to extract any more.
897 decision_logic_->set_sample_memory(samples_left);
898 decision_logic_->set_prev_time_scale(true);
899 return 0;
900 } else if (samples_left >= samples_10_ms &&
901 decoder_frame_length_ >= samples_30_ms) {
902 // Avoid decoding more data as it might overflow the playout buffer.
903 *operation = kNormal;
904 return 0;
905 } else if (samples_left < samples_20_ms &&
906 decoder_frame_length_ < samples_30_ms) {
907 // Build up decoded data by decoding at least 20 ms of audio data. Do
908 // not perform accelerate yet, but wait until we only need to do one
909 // decoding.
910 required_samples = 2 * output_size_samples_;
911 *operation = kNormal;
912 }
913 // If none of the above is true, we have one of two possible situations:
914 // (1) 20 ms <= samples_left < 30 ms and decoder_frame_length_ < 30 ms; or
915 // (2) samples_left < 10 ms and decoder_frame_length_ >= 30 ms.
916 // In either case, we move on with the accelerate decision, and decode one
917 // frame now.
918 break;
919 }
920 case kPreemptiveExpand: {
921 // In order to do a preemptive expand we need at least 30 ms of decoded
922 // audio data.
923 if ((samples_left >= samples_30_ms) ||
924 (samples_left >= samples_10_ms &&
925 decoder_frame_length_ >= samples_30_ms)) {
926 // Already have enough data, so we do not need to extract any more.
927 // Or, avoid decoding more data as it might overflow the playout buffer.
928 // Still try preemptive expand, though.
929 decision_logic_->set_sample_memory(samples_left);
930 decision_logic_->set_prev_time_scale(true);
931 return 0;
932 }
933 if (samples_left < samples_20_ms &&
934 decoder_frame_length_ < samples_30_ms) {
935 // Build up decoded data by decoding at least 20 ms of audio data.
936 // Still try to perform preemptive expand.
937 required_samples = 2 * output_size_samples_;
938 }
939 // Move on with the preemptive expand decision.
940 break;
941 }
942 default: {
943 // Do nothing.
944 }
945 }
946
947 // Get packets from buffer.
948 int extracted_samples = 0;
949 if (header &&
950 *operation != kAlternativePlc &&
951 *operation != kAlternativePlcIncreaseTimestamp &&
952 *operation != kAudioRepetition &&
953 *operation != kAudioRepetitionIncreaseTimestamp) {
954 sync_buffer_->IncreaseEndTimestamp(header->timestamp - end_timestamp);
955 if (decision_logic_->CngOff()) {
956 // Adjustment of timestamp only corresponds to an actual packet loss
957 // if comfort noise is not played. If comfort noise was just played,
958 // this adjustment of timestamp is only done to get back in sync with the
959 // stream timestamp; no loss to report.
960 stats_.LostSamples(header->timestamp - end_timestamp);
961 }
962
963 if (*operation != kRfc3389Cng) {
964 // We are about to decode and use a non-CNG packet.
965 decision_logic_->SetCngOff();
966 }
967 // Reset CNG timestamp as a new packet will be delivered.
968 // (Also if this is a CNG packet, since playedOutTS is updated.)
969 decision_logic_->set_generated_noise_samples(0);
970
971 extracted_samples = ExtractPackets(required_samples, packet_list);
972 if (extracted_samples < 0) {
973 LOG_F(LS_WARNING) << "Failed to extract packets from buffer.";
974 return kPacketBufferCorruption;
975 }
976 }
977
978 if (*operation == kAccelerate ||
979 *operation == kPreemptiveExpand) {
980 decision_logic_->set_sample_memory(samples_left + extracted_samples);
981 decision_logic_->set_prev_time_scale(true);
982 }
983
984 if (*operation == kAccelerate) {
985 // Check that we have enough data (30ms) to do accelerate.
986 if (extracted_samples + samples_left < samples_30_ms) {
987 // TODO(hlundin): Write test for this.
988 // Not enough, do normal operation instead.
989 *operation = kNormal;
990 }
991 }
992
993 timestamp_ = end_timestamp;
994 return 0;
995}
996
997int NetEqImpl::Decode(PacketList* packet_list, Operations* operation,
998 int* decoded_length,
999 AudioDecoder::SpeechType* speech_type) {
1000 *speech_type = AudioDecoder::kSpeech;
1001 AudioDecoder* decoder = NULL;
1002 if (!packet_list->empty()) {
1003 const Packet* packet = packet_list->front();
1004 int payload_type = packet->header.payloadType;
1005 if (!decoder_database_->IsComfortNoise(payload_type)) {
1006 decoder = decoder_database_->GetDecoder(payload_type);
1007 assert(decoder);
1008 if (!decoder) {
1009 LOG_FERR1(LS_WARNING, GetDecoder, payload_type);
1010 PacketBuffer::DeleteAllPackets(packet_list);
1011 return kDecoderNotFound;
1012 }
1013 bool decoder_changed;
1014 decoder_database_->SetActiveDecoder(payload_type, &decoder_changed);
1015 if (decoder_changed) {
1016 // We have a new decoder. Re-init some values.
1017 const DecoderDatabase::DecoderInfo* decoder_info = decoder_database_
1018 ->GetDecoderInfo(payload_type);
1019 assert(decoder_info);
1020 if (!decoder_info) {
1021 LOG_FERR1(LS_WARNING, GetDecoderInfo, payload_type);
1022 PacketBuffer::DeleteAllPackets(packet_list);
1023 return kDecoderNotFound;
1024 }
1025 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->channels());
1026 sync_buffer_->set_end_timestamp(timestamp_);
1027 playout_timestamp_ = timestamp_;
1028 }
1029 }
1030 }
1031
1032 if (reset_decoder_) {
1033 // TODO(hlundin): Write test for this.
1034 // Reset decoder.
1035 if (decoder) {
1036 decoder->Init();
1037 }
1038 // Reset comfort noise decoder.
1039 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
1040 if (cng_decoder) {
1041 cng_decoder->Init();
1042 }
1043 reset_decoder_ = false;
1044 }
1045
1046#ifdef LEGACY_BITEXACT
1047 // Due to a bug in old SignalMCU, it could happen that CNG operation was
1048 // decided, but a speech packet was provided. The speech packet will be used
1049 // to update the comfort noise decoder, as if it was a SID frame, which is
1050 // clearly wrong.
1051 if (*operation == kRfc3389Cng) {
1052 return 0;
1053 }
1054#endif
1055
1056 *decoded_length = 0;
1057 // Update codec-internal PLC state.
1058 if ((*operation == kMerge) && decoder && decoder->HasDecodePlc()) {
1059 decoder->DecodePlc(1, &decoded_buffer_[*decoded_length]);
1060 }
1061
1062 int return_value = DecodeLoop(packet_list, operation, decoder,
1063 decoded_length, speech_type);
1064
1065 if (*decoded_length < 0) {
1066 // Error returned from the decoder.
1067 *decoded_length = 0;
1068 sync_buffer_->IncreaseEndTimestamp(decoder_frame_length_);
1069 int error_code = 0;
1070 if (decoder)
1071 error_code = decoder->ErrorCode();
1072 if (error_code != 0) {
1073 // Got some error code from the decoder.
1074 decoder_error_code_ = error_code;
1075 return_value = kDecoderErrorCode;
1076 } else {
1077 // Decoder does not implement error codes. Return generic error.
1078 return_value = kOtherDecoderError;
1079 }
1080 LOG_FERR2(LS_WARNING, DecodeLoop, error_code, packet_list->size());
1081 *operation = kExpand; // Do expansion to get data instead.
1082 }
1083 if (*speech_type != AudioDecoder::kComfortNoise) {
1084 // Don't increment timestamp if codec returned CNG speech type
1085 // since in this case, the we will increment the CNGplayedTS counter.
1086 // Increase with number of samples per channel.
1087 assert(*decoded_length == 0 ||
1088 (decoder && decoder->channels() == sync_buffer_->Channels()));
1089 sync_buffer_->IncreaseEndTimestamp(*decoded_length /
1090 sync_buffer_->Channels());
1091 }
1092 return return_value;
1093}
1094
1095int NetEqImpl::DecodeLoop(PacketList* packet_list, Operations* operation,
1096 AudioDecoder* decoder, int* decoded_length,
1097 AudioDecoder::SpeechType* speech_type) {
1098 Packet* packet = NULL;
1099 if (!packet_list->empty()) {
1100 packet = packet_list->front();
1101 }
1102 // Do decoding.
1103 while (packet &&
1104 !decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1105 assert(decoder); // At this point, we must have a decoder object.
1106 // The number of channels in the |sync_buffer_| should be the same as the
1107 // number decoder channels.
1108 assert(sync_buffer_->Channels() == decoder->channels());
1109 assert(decoded_buffer_length_ >= kMaxFrameSize * decoder->channels());
1110 assert(*operation == kNormal || *operation == kAccelerate ||
1111 *operation == kMerge || *operation == kPreemptiveExpand);
1112 packet_list->pop_front();
henrik.lundin@webrtc.org63464a92013-01-30 09:41:56 +00001113 int payload_length = packet->payload_length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001114 int16_t decode_length;
1115 if (!packet->primary) {
1116 // This is a redundant payload; call the special decoder method.
1117 LOG(LS_VERBOSE) << "Decoding packet (redundant):" <<
1118 " 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->DecodeRedundant(
1124 packet->payload, packet->payload_length,
1125 &decoded_buffer_[*decoded_length], speech_type);
1126 } else {
1127 LOG(LS_VERBOSE) << "Decoding packet: ts=" << packet->header.timestamp <<
1128 ", sn=" << packet->header.sequenceNumber <<
1129 ", pt=" << static_cast<int>(packet->header.payloadType) <<
1130 ", ssrc=" << packet->header.ssrc <<
1131 ", len=" << packet->payload_length;
1132 decode_length = decoder->Decode(packet->payload,
1133 packet->payload_length,
1134 &decoded_buffer_[*decoded_length],
1135 speech_type);
1136 }
1137
1138 delete[] packet->payload;
1139 delete packet;
1140 if (decode_length > 0) {
1141 *decoded_length += decode_length;
1142 // Update |decoder_frame_length_| with number of samples per channel.
1143 decoder_frame_length_ = decode_length / decoder->channels();
1144 LOG(LS_VERBOSE) << "Decoded " << decode_length << " samples (" <<
1145 decoder->channels() << " channel(s) -> " << decoder_frame_length_ <<
1146 " samples per channel)";
1147 } else if (decode_length < 0) {
1148 // Error.
henrik.lundin@webrtc.org63464a92013-01-30 09:41:56 +00001149 LOG_FERR2(LS_WARNING, Decode, decode_length, payload_length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001150 *decoded_length = -1;
1151 PacketBuffer::DeleteAllPackets(packet_list);
1152 break;
1153 }
1154 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1155 // Guard against overflow.
1156 LOG_F(LS_WARNING) << "Decoded too much.";
1157 PacketBuffer::DeleteAllPackets(packet_list);
1158 return kDecodedTooMuch;
1159 }
1160 if (!packet_list->empty()) {
1161 packet = packet_list->front();
1162 } else {
1163 packet = NULL;
1164 }
1165 } // End of decode loop.
1166
1167 // If the list is not empty at this point, it must hold exactly one CNG
1168 // packet.
1169 assert(packet_list->empty() ||
1170 (packet_list->size() == 1 &&
1171 decoder_database_->IsComfortNoise(packet->header.payloadType)));
1172 return 0;
1173}
1174
1175void NetEqImpl::DoNormal(const int16_t* decoded_buffer, size_t decoded_length,
1176 AudioDecoder::SpeechType speech_type, bool play_dtmf,
1177 AudioMultiVector<int16_t>* algorithm_buffer) {
1178 assert(decoder_database_.get());
1179 assert(background_noise_);
1180 assert(expand_);
1181 Normal normal(fs_hz_, decoder_database_.get(), *background_noise_, expand_);
1182 assert(mute_factor_array_.get());
1183 normal.Process(decoded_buffer, decoded_length, last_mode_,
1184 mute_factor_array_.get(), algorithm_buffer);
1185 if (decoded_length != 0) {
1186 last_mode_ = kModeNormal;
1187 }
1188
1189 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1190 if ((speech_type == AudioDecoder::kComfortNoise)
1191 || ((last_mode_ == kModeCodecInternalCng)
1192 && (decoded_length == 0))) {
1193 // TODO(hlundin): Remove second part of || statement above.
1194 last_mode_ = kModeCodecInternalCng;
1195 }
1196
1197 if (!play_dtmf) {
1198 dtmf_tone_generator_->Reset();
1199 }
1200}
1201
1202void NetEqImpl::DoMerge(int16_t* decoded_buffer, size_t decoded_length,
1203 AudioDecoder::SpeechType speech_type, bool play_dtmf,
1204 AudioMultiVector<int16_t>* algorithm_buffer) {
1205 Merge merge(fs_hz_, algorithm_buffer->Channels(), expand_, sync_buffer_);
1206 assert(mute_factor_array_.get());
1207 int new_length = merge.Process(decoded_buffer, decoded_length,
1208 mute_factor_array_.get(), algorithm_buffer);
1209
1210 // Update in-call and post-call statistics.
1211 if (expand_->MuteFactor(0) == 0) {
1212 // Expand generates only noise.
1213 stats_.ExpandedNoiseSamples(new_length - decoded_length);
1214 } else {
1215 // Expansion generates more than only noise.
1216 stats_.ExpandedVoiceSamples(new_length - decoded_length);
1217 }
1218
1219 last_mode_ = kModeMerge;
1220 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1221 if (speech_type == AudioDecoder::kComfortNoise) {
1222 last_mode_ = kModeCodecInternalCng;
1223 }
1224 expand_->Reset();
1225 if (!play_dtmf) {
1226 dtmf_tone_generator_->Reset();
1227 }
1228}
1229
1230int NetEqImpl::DoExpand(bool play_dtmf,
1231 AudioMultiVector<int16_t>* algorithm_buffer) {
1232 while ((sync_buffer_->FutureLength() - expand_->overlap_length()) <
1233 static_cast<size_t>(output_size_samples_)) {
1234 algorithm_buffer->Clear();
1235 int return_value = expand_->Process(algorithm_buffer);
1236 int length = algorithm_buffer->Size();
1237
1238 // Update in-call and post-call statistics.
1239 if (expand_->MuteFactor(0) == 0) {
1240 // Expand operation generates only noise.
1241 stats_.ExpandedNoiseSamples(length);
1242 } else {
1243 // Expand operation generates more than only noise.
1244 stats_.ExpandedVoiceSamples(length);
1245 }
1246
1247 last_mode_ = kModeExpand;
1248
1249 if (return_value < 0) {
1250 return return_value;
1251 }
1252
1253 sync_buffer_->PushBack(*algorithm_buffer);
1254 algorithm_buffer->Clear();
1255 }
1256 if (!play_dtmf) {
1257 dtmf_tone_generator_->Reset();
1258 }
1259 return 0;
1260}
1261
1262int NetEqImpl::DoAccelerate(int16_t* decoded_buffer, size_t decoded_length,
1263 AudioDecoder::SpeechType speech_type,
1264 bool play_dtmf,
1265 AudioMultiVector<int16_t>* algorithm_buffer) {
1266 const size_t required_samples = 240 * fs_mult_; // Must have 30 ms.
1267 int borrowed_samples_per_channel = 0;
1268 size_t num_channels = algorithm_buffer->Channels();
1269 size_t decoded_length_per_channel = decoded_length / num_channels;
1270 if (decoded_length_per_channel < required_samples) {
1271 // Must move data from the |sync_buffer_| in order to get 30 ms.
1272 borrowed_samples_per_channel = required_samples -
1273 decoded_length_per_channel;
1274 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1275 decoded_buffer,
1276 sizeof(int16_t) * decoded_length);
1277 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1278 decoded_buffer);
1279 decoded_length = required_samples * num_channels;
1280 }
1281
1282 int16_t samples_removed;
1283 Accelerate accelerate(fs_hz_, num_channels, *background_noise_);
1284 Accelerate::ReturnCodes return_code = accelerate.Process(decoded_buffer,
1285 decoded_length,
1286 algorithm_buffer,
1287 &samples_removed);
1288 stats_.AcceleratedSamples(samples_removed);
1289 switch (return_code) {
1290 case Accelerate::kSuccess:
1291 last_mode_ = kModeAccelerateSuccess;
1292 break;
1293 case Accelerate::kSuccessLowEnergy:
1294 last_mode_ = kModeAccelerateLowEnergy;
1295 break;
1296 case Accelerate::kNoStretch:
1297 last_mode_ = kModeAccelerateFail;
1298 break;
1299 case Accelerate::kError:
1300 // TODO(hlundin): Map to kModeError instead?
1301 last_mode_ = kModeAccelerateFail;
1302 return kAccelerateError;
1303 }
1304
1305 if (borrowed_samples_per_channel > 0) {
1306 // Copy borrowed samples back to the |sync_buffer_|.
1307 int length = algorithm_buffer->Size();
1308 if (length < borrowed_samples_per_channel) {
1309 // This destroys the beginning of the buffer, but will not cause any
1310 // problems.
1311 sync_buffer_->ReplaceAtIndex(*algorithm_buffer,
1312 sync_buffer_->Size() -
1313 borrowed_samples_per_channel);
1314 sync_buffer_->PushFrontZeros(borrowed_samples_per_channel - length);
1315 algorithm_buffer->PopFront(length);
1316 assert(algorithm_buffer->Empty());
1317 } else {
1318 sync_buffer_->ReplaceAtIndex(*algorithm_buffer,
1319 borrowed_samples_per_channel,
1320 sync_buffer_->Size() -
1321 borrowed_samples_per_channel);
1322 algorithm_buffer->PopFront(borrowed_samples_per_channel);
1323 }
1324 }
1325
1326 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1327 if (speech_type == AudioDecoder::kComfortNoise) {
1328 last_mode_ = kModeCodecInternalCng;
1329 }
1330 if (!play_dtmf) {
1331 dtmf_tone_generator_->Reset();
1332 }
1333 expand_->Reset();
1334 return 0;
1335}
1336
1337int NetEqImpl::DoPreemptiveExpand(int16_t* decoded_buffer,
1338 size_t decoded_length,
1339 AudioDecoder::SpeechType speech_type,
1340 bool play_dtmf,
1341 AudioMultiVector<int16_t>* algorithm_buffer) {
1342 const size_t required_samples = 240 * fs_mult_; // Must have 30 ms.
1343 size_t num_channels = algorithm_buffer->Channels();
1344 int borrowed_samples_per_channel = 0;
1345 int old_borrowed_samples_per_channel = 0;
1346 size_t decoded_length_per_channel = decoded_length / num_channels;
1347 if (decoded_length_per_channel < required_samples) {
1348 // Must move data from the |sync_buffer_| in order to get 30 ms.
1349 borrowed_samples_per_channel = required_samples -
1350 decoded_length_per_channel;
1351 // Calculate how many of these were already played out.
1352 old_borrowed_samples_per_channel = borrowed_samples_per_channel -
1353 sync_buffer_->FutureLength();
1354 old_borrowed_samples_per_channel = std::max(
1355 0, old_borrowed_samples_per_channel);
1356 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1357 decoded_buffer,
1358 sizeof(int16_t) * decoded_length);
1359 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1360 decoded_buffer);
1361 decoded_length = required_samples * num_channels;
1362 }
1363
1364 int16_t samples_added;
1365 PreemptiveExpand preemptive_expand(fs_hz_, num_channels, *background_noise_);
1366 PreemptiveExpand::ReturnCodes return_code = preemptive_expand.Process(
1367 decoded_buffer, decoded_length, old_borrowed_samples_per_channel,
1368 algorithm_buffer, &samples_added);
1369 stats_.PreemptiveExpandedSamples(samples_added);
1370 switch (return_code) {
1371 case PreemptiveExpand::kSuccess:
1372 last_mode_ = kModePreemptiveExpandSuccess;
1373 break;
1374 case PreemptiveExpand::kSuccessLowEnergy:
1375 last_mode_ = kModePreemptiveExpandLowEnergy;
1376 break;
1377 case PreemptiveExpand::kNoStretch:
1378 last_mode_ = kModePreemptiveExpandFail;
1379 break;
1380 case PreemptiveExpand::kError:
1381 // TODO(hlundin): Map to kModeError instead?
1382 last_mode_ = kModePreemptiveExpandFail;
1383 return kPreemptiveExpandError;
1384 }
1385
1386 if (borrowed_samples_per_channel > 0) {
1387 // Copy borrowed samples back to the |sync_buffer_|.
1388 sync_buffer_->ReplaceAtIndex(
1389 *algorithm_buffer, borrowed_samples_per_channel,
1390 sync_buffer_->Size() - borrowed_samples_per_channel);
1391 algorithm_buffer->PopFront(borrowed_samples_per_channel);
1392 }
1393
1394 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1395 if (speech_type == AudioDecoder::kComfortNoise) {
1396 last_mode_ = kModeCodecInternalCng;
1397 }
1398 if (!play_dtmf) {
1399 dtmf_tone_generator_->Reset();
1400 }
1401 expand_->Reset();
1402 return 0;
1403}
1404
1405int NetEqImpl::DoRfc3389Cng(PacketList* packet_list, bool play_dtmf,
1406 AudioMultiVector<int16_t>* algorithm_buffer) {
1407 if (!packet_list->empty()) {
1408 // Must have exactly one SID frame at this point.
1409 assert(packet_list->size() == 1);
1410 Packet* packet = packet_list->front();
1411 packet_list->pop_front();
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001412 if (!decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1413#ifdef LEGACY_BITEXACT
1414 // This can happen due to a bug in GetDecision. Change the payload type
1415 // to a CNG type, and move on. Note that this means that we are in fact
1416 // sending a non-CNG payload to the comfort noise decoder for decoding.
1417 // Clearly wrong, but will maintain bit-exactness with legacy.
1418 if (fs_hz_ == 8000) {
1419 packet->header.payloadType =
1420 decoder_database_->GetRtpPayloadType(kDecoderCNGnb);
1421 } else if (fs_hz_ == 16000) {
1422 packet->header.payloadType =
1423 decoder_database_->GetRtpPayloadType(kDecoderCNGwb);
1424 } else if (fs_hz_ == 32000) {
1425 packet->header.payloadType =
1426 decoder_database_->GetRtpPayloadType(kDecoderCNGswb32kHz);
1427 } else if (fs_hz_ == 48000) {
1428 packet->header.payloadType =
1429 decoder_database_->GetRtpPayloadType(kDecoderCNGswb48kHz);
1430 }
1431 assert(decoder_database_->IsComfortNoise(packet->header.payloadType));
1432#else
1433 LOG(LS_ERROR) << "Trying to decode non-CNG payload as CNG.";
1434 return kOtherError;
1435#endif
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001436 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001437 // UpdateParameters() deletes |packet|.
1438 if (comfort_noise_->UpdateParameters(packet) ==
1439 ComfortNoise::kInternalError) {
1440 LOG_FERR0(LS_WARNING, UpdateParameters);
1441 algorithm_buffer->Zeros(output_size_samples_);
1442 return -comfort_noise_->internal_error_code();
1443 }
1444 }
1445 int cn_return = comfort_noise_->Generate(output_size_samples_,
1446 algorithm_buffer);
1447 expand_->Reset();
1448 last_mode_ = kModeRfc3389Cng;
1449 if (!play_dtmf) {
1450 dtmf_tone_generator_->Reset();
1451 }
1452 if (cn_return == ComfortNoise::kInternalError) {
1453 LOG_FERR1(LS_WARNING, comfort_noise_->Generate, cn_return);
1454 decoder_error_code_ = comfort_noise_->internal_error_code();
1455 return kComfortNoiseErrorCode;
1456 } else if (cn_return == ComfortNoise::kUnknownPayloadType) {
1457 LOG_FERR1(LS_WARNING, comfort_noise_->Generate, cn_return);
1458 return kUnknownRtpPayloadType;
1459 }
1460 return 0;
1461}
1462
1463void NetEqImpl::DoCodecInternalCng(
1464 AudioMultiVector<int16_t>* algorithm_buffer) {
1465 int length = 0;
1466 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1467 int16_t decoded_buffer[kMaxFrameSize];
1468 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1469 if (decoder) {
1470 const uint8_t* dummy_payload = NULL;
1471 AudioDecoder::SpeechType speech_type;
1472 length = decoder->Decode(dummy_payload, 0, decoded_buffer, &speech_type);
1473 }
1474 Normal normal(fs_hz_, decoder_database_.get(), *background_noise_, expand_);
1475 assert(mute_factor_array_.get());
1476 normal.Process(decoded_buffer, length, last_mode_, mute_factor_array_.get(),
1477 algorithm_buffer);
1478 last_mode_ = kModeCodecInternalCng;
1479 expand_->Reset();
1480}
1481
1482int NetEqImpl::DoDtmf(const DtmfEvent& dtmf_event, bool* play_dtmf,
1483 AudioMultiVector<int16_t>* algorithm_buffer) {
1484 bool dtmf_switch = false;
1485 if ((last_mode_ != kModeDtmf) && !dtmf_tone_generator_->initialized()) {
1486 // Special case; see below.
1487 // We must catch this before calling Generate, since |initialized| is
1488 // modified in that call.
1489 dtmf_switch = true;
1490 }
1491
1492 int dtmf_return_value = 0;
1493 if (!dtmf_tone_generator_->initialized()) {
1494 // Initialize if not already done.
1495 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1496 dtmf_event.volume);
1497 }
1498 if (dtmf_return_value == 0) {
1499 // Generate DTMF signal.
1500 dtmf_return_value = dtmf_tone_generator_->Generate(output_size_samples_,
1501 algorithm_buffer);
1502 }
1503 if (dtmf_return_value < 0) {
1504 algorithm_buffer->Zeros(output_size_samples_);
1505 return dtmf_return_value;
1506 }
1507
1508 if (dtmf_switch) {
1509 // This is the special case where the previous operation was DTMF overdub,
1510 // but the current instruction is "regular" DTMF. We must make sure that the
1511 // DTMF does not have any discontinuities. The first DTMF sample that we
1512 // generate now must be played out immediately, wherefore it must be copied
1513 // to the speech buffer.
1514 // TODO(hlundin): This code seems incorrect. (Legacy.) Write test and
1515 // verify correct operation.
1516 assert(false);
1517 // Must generate enough data to replace all of the |sync_buffer_| "future".
1518 int required_length = sync_buffer_->FutureLength();
1519 assert(dtmf_tone_generator_->initialized());
1520 dtmf_return_value = dtmf_tone_generator_->Generate(required_length,
1521 algorithm_buffer);
1522 assert((size_t) required_length == algorithm_buffer->Size());
1523 if (dtmf_return_value < 0) {
1524 algorithm_buffer->Zeros(output_size_samples_);
1525 return dtmf_return_value;
1526 }
1527
1528 // Overwrite the "future" part of the speech buffer with the new DTMF data.
1529 // TODO(hlundin): It seems that this overwriting has gone lost.
1530 // Not adapted for multi-channel yet.
1531 assert(algorithm_buffer->Channels() == 1);
1532 if (algorithm_buffer->Channels() != 1) {
1533 LOG(LS_WARNING) << "DTMF not supported for more than one channel";
1534 return kStereoNotSupported;
1535 }
1536 // Shuffle the remaining data to the beginning of algorithm buffer.
1537 algorithm_buffer->PopFront(sync_buffer_->FutureLength());
1538 }
1539
1540 sync_buffer_->IncreaseEndTimestamp(output_size_samples_);
1541 expand_->Reset();
1542 last_mode_ = kModeDtmf;
1543
1544 // Set to false because the DTMF is already in the algorithm buffer.
1545 *play_dtmf = false;
1546 return 0;
1547}
1548
1549void NetEqImpl::DoAlternativePlc(bool increase_timestamp,
1550 AudioMultiVector<int16_t>* algorithm_buffer) {
1551 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1552 int length;
1553 if (decoder && decoder->HasDecodePlc()) {
1554 // Use the decoder's packet-loss concealment.
1555 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1556 int16_t decoded_buffer[kMaxFrameSize];
1557 length = decoder->DecodePlc(1, decoded_buffer);
1558 if (length > 0) {
1559 algorithm_buffer->PushBackInterleaved(decoded_buffer, length);
1560 } else {
1561 length = 0;
1562 }
1563 } else {
1564 // Do simple zero-stuffing.
1565 length = output_size_samples_;
1566 algorithm_buffer->Zeros(length);
1567 // By not advancing the timestamp, NetEq inserts samples.
1568 stats_.AddZeros(length);
1569 }
1570 if (increase_timestamp) {
1571 sync_buffer_->IncreaseEndTimestamp(length);
1572 }
1573 expand_->Reset();
1574}
1575
1576int NetEqImpl::DtmfOverdub(const DtmfEvent& dtmf_event, size_t num_channels,
1577 int16_t* output) const {
1578 size_t out_index = 0;
1579 int overdub_length = output_size_samples_; // Default value.
1580
1581 if (sync_buffer_->dtmf_index() > sync_buffer_->next_index()) {
1582 // Special operation for transition from "DTMF only" to "DTMF overdub".
1583 out_index = std::min(
1584 sync_buffer_->dtmf_index() - sync_buffer_->next_index(),
1585 static_cast<size_t>(output_size_samples_));
1586 overdub_length = output_size_samples_ - out_index;
1587 }
1588
1589 AudioMultiVector<int16_t> dtmf_output(num_channels);
1590 int dtmf_return_value = 0;
1591 if (!dtmf_tone_generator_->initialized()) {
1592 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1593 dtmf_event.volume);
1594 }
1595 if (dtmf_return_value == 0) {
1596 dtmf_return_value = dtmf_tone_generator_->Generate(overdub_length,
1597 &dtmf_output);
1598 assert((size_t) overdub_length == dtmf_output.Size());
1599 }
1600 dtmf_output.ReadInterleaved(overdub_length, &output[out_index]);
1601 return dtmf_return_value < 0 ? dtmf_return_value : 0;
1602}
1603
1604int NetEqImpl::ExtractPackets(int required_samples, PacketList* packet_list) {
1605 bool first_packet = true;
1606 uint8_t prev_payload_type = 0;
1607 uint32_t prev_timestamp = 0;
1608 uint16_t prev_sequence_number = 0;
1609 bool next_packet_available = false;
1610
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001611 const RTPHeader* header = packet_buffer_->NextRtpHeader();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001612 assert(header);
1613 if (!header) {
1614 return -1;
1615 }
1616 int32_t first_timestamp = header->timestamp;
1617 int extracted_samples = 0;
1618
1619 // Packet extraction loop.
1620 do {
1621 timestamp_ = header->timestamp;
1622 int discard_count = 0;
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001623 Packet* packet = packet_buffer_->GetNextPacket(&discard_count);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001624 // |header| may be invalid after the |packet_buffer_| operation.
1625 header = NULL;
1626 if (!packet) {
1627 LOG_FERR1(LS_ERROR, GetNextPacket, discard_count) <<
1628 "Should always be able to extract a packet here";
1629 assert(false); // Should always be able to extract a packet here.
1630 return -1;
1631 }
1632 stats_.PacketsDiscarded(discard_count);
1633 // Store waiting time in ms; packets->waiting_time is in "output blocks".
1634 stats_.StoreWaitingTime(packet->waiting_time * kOutputSizeMs);
1635 assert(packet->payload_length > 0);
1636 packet_list->push_back(packet); // Store packet in list.
1637
1638 if (first_packet) {
1639 first_packet = false;
1640 prev_sequence_number = packet->header.sequenceNumber;
1641 prev_timestamp = packet->header.timestamp;
1642 prev_payload_type = packet->header.payloadType;
1643 }
1644
1645 // Store number of extracted samples.
1646 int packet_duration = 0;
1647 AudioDecoder* decoder = decoder_database_->GetDecoder(
1648 packet->header.payloadType);
1649 if (decoder) {
1650 packet_duration = decoder->PacketDuration(packet->payload,
1651 packet->payload_length);
1652 } else {
1653 LOG_FERR1(LS_WARNING, GetDecoder, packet->header.payloadType) <<
1654 "Could not find a decoder for a packet about to be extracted.";
1655 assert(false);
1656 }
1657 if (packet_duration <= 0) {
1658 // Decoder did not return a packet duration. Assume that the packet
1659 // contains the same number of samples as the previous one.
1660 packet_duration = decoder_frame_length_;
1661 }
1662 extracted_samples = packet->header.timestamp - first_timestamp +
1663 packet_duration;
1664
1665 // Check what packet is available next.
1666 header = packet_buffer_->NextRtpHeader();
1667 next_packet_available = false;
1668 if (header && prev_payload_type == header->payloadType) {
1669 int16_t seq_no_diff = header->sequenceNumber - prev_sequence_number;
1670 int32_t ts_diff = header->timestamp - prev_timestamp;
1671 if (seq_no_diff == 1 ||
1672 (seq_no_diff == 0 && ts_diff == decoder_frame_length_)) {
1673 // The next sequence number is available, or the next part of a packet
1674 // that was split into pieces upon insertion.
1675 next_packet_available = true;
1676 }
1677 prev_sequence_number = header->sequenceNumber;
1678 }
1679 } while (extracted_samples < required_samples && next_packet_available);
1680
1681 return extracted_samples;
1682}
1683
1684void NetEqImpl::SetSampleRateAndChannels(int fs_hz, size_t channels) {
1685 LOG_API2(fs_hz, channels);
1686 // TODO(hlundin): Change to an enumerator and skip assert.
1687 assert(fs_hz == 8000 || fs_hz == 16000 || fs_hz == 32000 || fs_hz == 48000);
1688 assert(channels > 0);
1689
1690 fs_hz_ = fs_hz;
1691 fs_mult_ = fs_hz / 8000;
1692 output_size_samples_ = kOutputSizeMs * 8 * fs_mult_;
1693 decoder_frame_length_ = 3 * output_size_samples_; // Initialize to 30ms.
1694
1695 last_mode_ = kModeNormal;
1696
1697 // Create a new array of mute factors and set all to 1.
1698 mute_factor_array_.reset(new int16_t[channels]);
1699 for (size_t i = 0; i < channels; ++i) {
1700 mute_factor_array_[i] = 16384; // 1.0 in Q14.
1701 }
1702
1703 // Reset comfort noise decoder, if there is one active.
1704 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
1705 if (cng_decoder) {
1706 cng_decoder->Init();
1707 }
1708
1709 // Reinit post-decode VAD with new sample rate.
1710 assert(vad_.get()); // Cannot be NULL here.
1711 vad_->Init();
1712
1713 // Delete sync buffer and create a new one.
1714 if (sync_buffer_) {
1715 delete sync_buffer_;
1716 }
1717 sync_buffer_ = new SyncBuffer(channels, kSyncBufferSize * fs_mult_);
1718
1719 // Delete BackgroundNoise object and create a new one.
1720 if (background_noise_) {
1721 delete background_noise_;
1722 }
1723 background_noise_ = new BackgroundNoise(channels);
1724
1725 // Reset random vector.
1726 random_vector_.Reset();
1727
1728 // Delete Expand object and create a new one.
1729 if (expand_) {
1730 delete expand_;
1731 }
1732 expand_ = new Expand(background_noise_, sync_buffer_, &random_vector_, fs_hz,
1733 channels);
1734 // Move index so that we create a small set of future samples (all 0).
1735 sync_buffer_->set_next_index(sync_buffer_->next_index() -
1736 expand_->overlap_length());
1737
1738 // Delete ComfortNoise object and create a new one.
1739 if (comfort_noise_) {
1740 delete comfort_noise_;
1741 }
1742 comfort_noise_ = new ComfortNoise(fs_hz, decoder_database_.get(),
1743 sync_buffer_);
1744
1745 // Verify that |decoded_buffer_| is long enough.
1746 if (decoded_buffer_length_ < kMaxFrameSize * channels) {
1747 // Reallocate to larger size.
1748 decoded_buffer_length_ = kMaxFrameSize * channels;
1749 decoded_buffer_.reset(new int16_t[decoded_buffer_length_]);
1750 }
1751
1752 // Communicate new sample rate and output size to DecisionLogic object.
1753 assert(decision_logic_.get());
1754 decision_logic_->SetSampleRate(fs_hz_, output_size_samples_);
1755}
1756
1757NetEqOutputType NetEqImpl::LastOutputType() {
1758 assert(vad_.get());
1759 assert(expand_);
1760 if (last_mode_ == kModeCodecInternalCng || last_mode_ == kModeRfc3389Cng) {
1761 return kOutputCNG;
1762 } else if (vad_->running() && !vad_->active_speech()) {
1763 return kOutputVADPassive;
1764 } else if (last_mode_ == kModeExpand && expand_->MuteFactor(0) == 0) {
1765 // Expand mode has faded down to background noise only (very long expand).
1766 return kOutputPLCtoCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001767 } else if (last_mode_ == kModeExpand) {
1768 return kOutputPLC;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001769 } else {
1770 return kOutputNormal;
1771 }
1772}
1773
1774} // namespace webrtc