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