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