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