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