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