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