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