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