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