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