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