blob: 7620a7f4dc59ab95ad74a75eb3837735b0021e27 [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.orgd94659d2013-01-29 12:09:21 +0000120}
121
122int NetEqImpl::InsertPacket(const WebRtcRTPHeader& rtp_header,
123 const uint8_t* payload,
124 int length_bytes,
125 uint32_t receive_timestamp) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000126 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgb3e905c2013-09-02 09:41:06 +0000127 NETEQ_LOG_VERBOSE << "InsertPacket: ts=" << rtp_header.header.timestamp <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000128 ", sn=" << rtp_header.header.sequenceNumber <<
129 ", pt=" << static_cast<int>(rtp_header.header.payloadType) <<
130 ", ssrc=" << rtp_header.header.ssrc <<
131 ", len=" << length_bytes;
132 int error = InsertPacketInternal(rtp_header, payload, length_bytes,
133 receive_timestamp);
134 if (error != 0) {
135 LOG_FERR1(LS_WARNING, InsertPacketInternal, error);
136 error_code_ = error;
137 return kFail;
138 }
139 return kOK;
140}
141
142int NetEqImpl::GetAudio(size_t max_length, int16_t* output_audio,
143 int* samples_per_channel, int* num_channels,
144 NetEqOutputType* type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000145 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgb3e905c2013-09-02 09:41:06 +0000146 NETEQ_LOG_VERBOSE << "GetAudio";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000147 int error = GetAudioInternal(max_length, output_audio, samples_per_channel,
148 num_channels);
henrik.lundin@webrtc.orgb3e905c2013-09-02 09:41:06 +0000149 NETEQ_LOG_VERBOSE << "Produced " << *samples_per_channel <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000150 " samples/channel for " << *num_channels << " channel(s)";
151 if (error != 0) {
152 LOG_FERR1(LS_WARNING, GetAudioInternal, error);
153 error_code_ = error;
154 return kFail;
155 }
156 if (type) {
157 *type = LastOutputType();
158 }
159 return kOK;
160}
161
162int NetEqImpl::RegisterPayloadType(enum NetEqDecoder codec,
163 uint8_t rtp_payload_type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000164 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000165 LOG_API2(static_cast<int>(rtp_payload_type), codec);
166 int ret = decoder_database_->RegisterPayload(rtp_payload_type, codec);
167 if (ret != DecoderDatabase::kOK) {
168 LOG_FERR2(LS_WARNING, RegisterPayload, rtp_payload_type, codec);
169 switch (ret) {
170 case DecoderDatabase::kInvalidRtpPayloadType:
171 error_code_ = kInvalidRtpPayloadType;
172 break;
173 case DecoderDatabase::kCodecNotSupported:
174 error_code_ = kCodecNotSupported;
175 break;
176 case DecoderDatabase::kDecoderExists:
177 error_code_ = kDecoderExists;
178 break;
179 default:
180 error_code_ = kOtherError;
181 }
182 return kFail;
183 }
184 return kOK;
185}
186
187int NetEqImpl::RegisterExternalDecoder(AudioDecoder* decoder,
188 enum NetEqDecoder codec,
189 int sample_rate_hz,
190 uint8_t rtp_payload_type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000191 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000192 LOG_API2(static_cast<int>(rtp_payload_type), codec);
193 if (!decoder) {
194 LOG(LS_ERROR) << "Cannot register external decoder with NULL pointer";
195 assert(false);
196 return kFail;
197 }
198 int ret = decoder_database_->InsertExternal(rtp_payload_type, codec,
199 sample_rate_hz, decoder);
200 if (ret != DecoderDatabase::kOK) {
201 LOG_FERR2(LS_WARNING, InsertExternal, rtp_payload_type, codec);
202 switch (ret) {
203 case DecoderDatabase::kInvalidRtpPayloadType:
204 error_code_ = kInvalidRtpPayloadType;
205 break;
206 case DecoderDatabase::kCodecNotSupported:
207 error_code_ = kCodecNotSupported;
208 break;
209 case DecoderDatabase::kDecoderExists:
210 error_code_ = kDecoderExists;
211 break;
212 case DecoderDatabase::kInvalidSampleRate:
213 error_code_ = kInvalidSampleRate;
214 break;
215 case DecoderDatabase::kInvalidPointer:
216 error_code_ = kInvalidPointer;
217 break;
218 default:
219 error_code_ = kOtherError;
220 }
221 return kFail;
222 }
223 return kOK;
224}
225
226int NetEqImpl::RemovePayloadType(uint8_t rtp_payload_type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000227 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000228 LOG_API1(static_cast<int>(rtp_payload_type));
229 int ret = decoder_database_->Remove(rtp_payload_type);
230 if (ret == DecoderDatabase::kOK) {
231 return kOK;
232 } else if (ret == DecoderDatabase::kDecoderNotFound) {
233 error_code_ = kDecoderNotFound;
234 } else {
235 error_code_ = kOtherError;
236 }
237 LOG_FERR1(LS_WARNING, Remove, rtp_payload_type);
238 return kFail;
239}
240
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000241bool NetEqImpl::SetMinimumDelay(int delay_ms) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000242 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000243 if (delay_ms >= 0 && delay_ms < 10000) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000244 assert(delay_manager_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000245 return delay_manager_->SetMinimumDelay(delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000246 }
247 return false;
248}
249
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000250bool NetEqImpl::SetMaximumDelay(int delay_ms) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000251 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000252 if (delay_ms >= 0 && delay_ms < 10000) {
253 assert(delay_manager_.get());
254 return delay_manager_->SetMaximumDelay(delay_ms);
255 }
256 return false;
257}
258
259int NetEqImpl::LeastRequiredDelayMs() const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000260 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000261 assert(delay_manager_.get());
262 return delay_manager_->least_required_delay_ms();
263}
264
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000265void NetEqImpl::SetPlayoutMode(NetEqPlayoutMode mode) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000266 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000267 if (!decision_logic_.get() || mode != decision_logic_->playout_mode()) {
268 // The reset() method calls delete for the old object.
269 decision_logic_.reset(DecisionLogic::Create(fs_hz_, output_size_samples_,
270 mode,
271 decoder_database_.get(),
272 *packet_buffer_.get(),
273 delay_manager_.get(),
274 buffer_level_filter_.get()));
275 }
276}
277
278NetEqPlayoutMode NetEqImpl::PlayoutMode() const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000279 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000280 assert(decision_logic_.get());
281 return decision_logic_->playout_mode();
282}
283
284int NetEqImpl::NetworkStatistics(NetEqNetworkStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000285 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000286 assert(decoder_database_.get());
287 const int total_samples_in_buffers = packet_buffer_->NumSamplesInBuffer(
288 decoder_database_.get(), decoder_frame_length_) +
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000289 static_cast<int>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000290 assert(delay_manager_.get());
291 assert(decision_logic_.get());
292 stats_.GetNetworkStatistics(fs_hz_, total_samples_in_buffers,
293 decoder_frame_length_, *delay_manager_.get(),
294 *decision_logic_.get(), stats);
295 return 0;
296}
297
298void NetEqImpl::WaitingTimes(std::vector<int>* waiting_times) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000299 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000300 stats_.WaitingTimes(waiting_times);
301}
302
303void NetEqImpl::GetRtcpStatistics(RtcpStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000304 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000305 if (stats) {
306 rtcp_.GetStatistics(false, stats);
307 }
308}
309
310void NetEqImpl::GetRtcpStatisticsNoReset(RtcpStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000311 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000312 if (stats) {
313 rtcp_.GetStatistics(true, stats);
314 }
315}
316
317void NetEqImpl::EnableVad() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000318 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000319 assert(vad_.get());
320 vad_->Enable();
321}
322
323void NetEqImpl::DisableVad() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000324 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000325 assert(vad_.get());
326 vad_->Disable();
327}
328
329uint32_t NetEqImpl::PlayoutTimestamp() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000330 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000331 return timestamp_scaler_->ToExternal(playout_timestamp_);
332}
333
334int NetEqImpl::LastError() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000335 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000336 return error_code_;
337}
338
339int NetEqImpl::LastDecoderError() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000340 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000341 return decoder_error_code_;
342}
343
344void NetEqImpl::FlushBuffers() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000345 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000346 LOG_API0();
347 packet_buffer_->Flush();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000348 assert(sync_buffer_.get());
349 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000350 sync_buffer_->Flush();
351 sync_buffer_->set_next_index(sync_buffer_->next_index() -
352 expand_->overlap_length());
353 // Set to wait for new codec.
354 first_packet_ = true;
355}
356
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000357void NetEqImpl::PacketBufferStatistics(int* current_num_packets,
358 int* max_num_packets,
359 int* current_memory_size_bytes,
360 int* max_memory_size_bytes) const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000361 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000362 packet_buffer_->BufferStat(current_num_packets, max_num_packets,
363 current_memory_size_bytes, max_memory_size_bytes);
364}
365
minyue@webrtc.orgd7301772013-08-29 00:58:14 +0000366int NetEqImpl::DecodedRtpInfo(int* sequence_number, uint32_t* timestamp) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000367 CriticalSectionScoped lock(crit_sect_.get());
minyue@webrtc.orgd7301772013-08-29 00:58:14 +0000368 if (decoded_packet_sequence_number_ < 0)
369 return -1;
370 *sequence_number = decoded_packet_sequence_number_;
371 *timestamp = decoded_packet_timestamp_;
372 return 0;
373}
374
turaj@webrtc.org036b7432013-09-11 18:45:02 +0000375int NetEqImpl::InsertSyncPacket(const WebRtcRTPHeader& /* rtp_header */,
376 uint32_t /* receive_timestamp */) {
377 return kNotImplemented;
378}
379
380void NetEqImpl::SetBackgroundNoiseMode(NetEqBackgroundNoiseMode /* mode */) {}
381
382NetEqBackgroundNoiseMode NetEqImpl::BackgroundNoiseMode() const {
383 return kBgnOn;
384}
385
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000386// Methods below this line are private.
387
388
389int NetEqImpl::InsertPacketInternal(const WebRtcRTPHeader& rtp_header,
390 const uint8_t* payload,
391 int length_bytes,
392 uint32_t receive_timestamp) {
393 if (!payload) {
394 LOG_F(LS_ERROR) << "payload == NULL";
395 return kInvalidPointer;
396 }
397 PacketList packet_list;
398 RTPHeader main_header;
399 {
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000400 // Convert to Packet.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000401 // Create |packet| within this separate scope, since it should not be used
402 // directly once it's been inserted in the packet list. This way, |packet|
403 // is not defined outside of this block.
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000404 Packet* packet = new Packet;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000405 packet->header.markerBit = false;
406 packet->header.payloadType = rtp_header.header.payloadType;
407 packet->header.sequenceNumber = rtp_header.header.sequenceNumber;
408 packet->header.timestamp = rtp_header.header.timestamp;
409 packet->header.ssrc = rtp_header.header.ssrc;
410 packet->header.numCSRCs = 0;
411 packet->payload_length = length_bytes;
412 packet->primary = true;
413 packet->waiting_time = 0;
414 packet->payload = new uint8_t[packet->payload_length];
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +0000415 if (!packet->payload) {
416 LOG_F(LS_ERROR) << "Payload pointer is NULL.";
417 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000418 assert(payload); // Already checked above.
419 memcpy(packet->payload, payload, packet->payload_length);
420 // Insert packet in a packet list.
421 packet_list.push_back(packet);
422 // Save main payloads header for later.
423 memcpy(&main_header, &packet->header, sizeof(main_header));
424 }
425
426 // Reinitialize NetEq if it's needed (changed SSRC or first call).
427 if ((main_header.ssrc != ssrc_) || first_packet_) {
428 rtcp_.Init(main_header.sequenceNumber);
429 first_packet_ = false;
430
431 // Flush the packet buffer and DTMF buffer.
432 packet_buffer_->Flush();
433 dtmf_buffer_->Flush();
434
435 // Store new SSRC.
436 ssrc_ = main_header.ssrc;
437
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000438 // Update audio buffer timestamp.
439 sync_buffer_->IncreaseEndTimestamp(main_header.timestamp - timestamp_);
440
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000441 // Update codecs.
442 timestamp_ = main_header.timestamp;
443 current_rtp_payload_type_ = main_header.payloadType;
444
445 // Set MCU to update codec on next SignalMCU call.
446 new_codec_ = true;
447
448 // Reset timestamp scaling.
449 timestamp_scaler_->Reset();
450 }
451
452 // Update RTCP statistics.
453 rtcp_.Update(main_header, receive_timestamp);
454
455 // Check for RED payload type, and separate payloads into several packets.
456 if (decoder_database_->IsRed(main_header.payloadType)) {
457 if (payload_splitter_->SplitRed(&packet_list) != PayloadSplitter::kOK) {
458 LOG_FERR1(LS_WARNING, SplitRed, packet_list.size());
459 PacketBuffer::DeleteAllPackets(&packet_list);
460 return kRedundancySplitError;
461 }
462 // Only accept a few RED payloads of the same type as the main data,
463 // DTMF events and CNG.
464 payload_splitter_->CheckRedPayloads(&packet_list, *decoder_database_);
465 // Update the stored main payload header since the main payload has now
466 // changed.
467 memcpy(&main_header, &packet_list.front()->header, sizeof(main_header));
468 }
469
470 // Check payload types.
471 if (decoder_database_->CheckPayloadTypes(packet_list) ==
472 DecoderDatabase::kDecoderNotFound) {
473 LOG_FERR1(LS_WARNING, CheckPayloadTypes, packet_list.size());
474 PacketBuffer::DeleteAllPackets(&packet_list);
475 return kUnknownRtpPayloadType;
476 }
477
478 // Scale timestamp to internal domain (only for some codecs).
479 timestamp_scaler_->ToInternal(&packet_list);
480
481 // Process DTMF payloads. Cycle through the list of packets, and pick out any
482 // DTMF payloads found.
483 PacketList::iterator it = packet_list.begin();
484 while (it != packet_list.end()) {
485 Packet* current_packet = (*it);
486 assert(current_packet);
487 assert(current_packet->payload);
488 if (decoder_database_->IsDtmf(current_packet->header.payloadType)) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000489 DtmfEvent event;
490 int ret = DtmfBuffer::ParseEvent(
491 current_packet->header.timestamp,
492 current_packet->payload,
493 current_packet->payload_length,
494 &event);
495 if (ret != DtmfBuffer::kOK) {
496 LOG_FERR2(LS_WARNING, ParseEvent, ret,
497 current_packet->payload_length);
498 PacketBuffer::DeleteAllPackets(&packet_list);
499 return kDtmfParsingError;
500 }
501 if (dtmf_buffer_->InsertEvent(event) != DtmfBuffer::kOK) {
502 LOG_FERR0(LS_WARNING, InsertEvent);
503 PacketBuffer::DeleteAllPackets(&packet_list);
504 return kDtmfInsertError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000505 }
506 // TODO(hlundin): Let the destructor of Packet handle the payload.
507 delete [] current_packet->payload;
508 delete current_packet;
509 it = packet_list.erase(it);
510 } else {
511 ++it;
512 }
513 }
514
515 // Split payloads into smaller chunks. This also verifies that all payloads
516 // are of a known payload type.
517 int ret = payload_splitter_->SplitAudio(&packet_list, *decoder_database_);
518 if (ret != PayloadSplitter::kOK) {
519 LOG_FERR1(LS_WARNING, SplitAudio, packet_list.size());
520 PacketBuffer::DeleteAllPackets(&packet_list);
521 switch (ret) {
522 case PayloadSplitter::kUnknownPayloadType:
523 return kUnknownRtpPayloadType;
524 case PayloadSplitter::kFrameSplitError:
525 return kFrameSplitError;
526 default:
527 return kOtherError;
528 }
529 }
530
531 // Update bandwidth estimate.
532 if (!packet_list.empty()) {
533 // The list can be empty here if we got nothing but DTMF payloads.
534 AudioDecoder* decoder =
535 decoder_database_->GetDecoder(main_header.payloadType);
536 assert(decoder); // Should always get a valid object, since we have
537 // already checked that the payload types are known.
538 decoder->IncomingPacket(packet_list.front()->payload,
539 packet_list.front()->payload_length,
540 packet_list.front()->header.sequenceNumber,
541 packet_list.front()->header.timestamp,
542 receive_timestamp);
543 }
544
545 // Insert packets in buffer.
546 int temp_bufsize = packet_buffer_->NumPacketsInBuffer();
547 ret = packet_buffer_->InsertPacketList(
548 &packet_list,
549 *decoder_database_,
550 &current_rtp_payload_type_,
551 &current_cng_rtp_payload_type_);
552 if (ret == PacketBuffer::kFlushed) {
553 // Reset DSP timestamp etc. if packet buffer flushed.
554 new_codec_ = true;
555 LOG_F(LS_WARNING) << "Packet buffer flushed";
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000556 } else if (ret == PacketBuffer::kOversizePacket) {
557 LOG_F(LS_WARNING) << "Packet larger than packet buffer";
558 return kOversizePacket;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000559 } else if (ret != PacketBuffer::kOK) {
560 LOG_FERR1(LS_WARNING, InsertPacketList, packet_list.size());
561 PacketBuffer::DeleteAllPackets(&packet_list);
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000562 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000563 }
564 if (current_rtp_payload_type_ != 0xFF) {
565 const DecoderDatabase::DecoderInfo* dec_info =
566 decoder_database_->GetDecoderInfo(current_rtp_payload_type_);
567 if (!dec_info) {
568 assert(false); // Already checked that the payload type is known.
569 }
570 }
571
572 // TODO(hlundin): Move this code to DelayManager class.
573 const DecoderDatabase::DecoderInfo* dec_info =
574 decoder_database_->GetDecoderInfo(main_header.payloadType);
575 assert(dec_info); // Already checked that the payload type is known.
576 delay_manager_->LastDecoderType(dec_info->codec_type);
577 if (delay_manager_->last_pack_cng_or_dtmf() == 0) {
578 // Calculate the total speech length carried in each packet.
579 temp_bufsize = packet_buffer_->NumPacketsInBuffer() - temp_bufsize;
580 temp_bufsize *= decoder_frame_length_;
581
582 if ((temp_bufsize > 0) &&
583 (temp_bufsize != decision_logic_->packet_length_samples())) {
584 decision_logic_->set_packet_length_samples(temp_bufsize);
585 delay_manager_->SetPacketAudioLength((1000 * temp_bufsize) / fs_hz_);
586 }
587
588 // Update statistics.
pbos@webrtc.org0946a562013-04-09 00:28:06 +0000589 if ((int32_t) (main_header.timestamp - timestamp_) >= 0 &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000590 !new_codec_) {
591 // Only update statistics if incoming packet is not older than last played
592 // out packet, and if new codec flag is not set.
593 delay_manager_->Update(main_header.sequenceNumber, main_header.timestamp,
594 fs_hz_);
595 }
596 } else if (delay_manager_->last_pack_cng_or_dtmf() == -1) {
597 // This is first "normal" packet after CNG or DTMF.
598 // Reset packet time counter and measure time until next packet,
599 // but don't update statistics.
600 delay_manager_->set_last_pack_cng_or_dtmf(0);
601 delay_manager_->ResetPacketIatCount();
602 }
603 return 0;
604}
605
606int NetEqImpl::GetAudioInternal(size_t max_length, int16_t* output,
607 int* samples_per_channel, int* num_channels) {
608 PacketList packet_list;
609 DtmfEvent dtmf_event;
610 Operations operation;
611 bool play_dtmf;
612 int return_value = GetDecision(&operation, &packet_list, &dtmf_event,
613 &play_dtmf);
614 if (return_value != 0) {
615 LOG_FERR1(LS_WARNING, GetDecision, return_value);
616 assert(false);
617 last_mode_ = kModeError;
618 return return_value;
619 }
henrik.lundin@webrtc.orgb3e905c2013-09-02 09:41:06 +0000620 NETEQ_LOG_VERBOSE << "GetDecision returned operation=" << operation <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000621 " and " << packet_list.size() << " packet(s)";
622
623 AudioDecoder::SpeechType speech_type;
624 int length = 0;
625 int decode_return_value = Decode(&packet_list, &operation,
626 &length, &speech_type);
627
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000628 assert(vad_.get());
629 bool sid_frame_available =
630 (operation == kRfc3389Cng && !packet_list.empty());
631 vad_->Update(decoded_buffer_.get(), length, speech_type,
632 sid_frame_available, fs_hz_);
633
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000634 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000635 switch (operation) {
636 case kNormal: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000637 DoNormal(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000638 break;
639 }
640 case kMerge: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000641 DoMerge(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000642 break;
643 }
644 case kExpand: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000645 return_value = DoExpand(play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000646 break;
647 }
648 case kAccelerate: {
649 return_value = DoAccelerate(decoded_buffer_.get(), length, speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000650 play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000651 break;
652 }
653 case kPreemptiveExpand: {
654 return_value = DoPreemptiveExpand(decoded_buffer_.get(), length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000655 speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000656 break;
657 }
658 case kRfc3389Cng:
659 case kRfc3389CngNoPacket: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000660 return_value = DoRfc3389Cng(&packet_list, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000661 break;
662 }
663 case kCodecInternalCng: {
664 // This handles the case when there is no transmission and the decoder
665 // should produce internal comfort noise.
666 // TODO(hlundin): Write test for codec-internal CNG.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000667 DoCodecInternalCng();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000668 break;
669 }
670 case kDtmf: {
671 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000672 return_value = DoDtmf(dtmf_event, &play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000673 break;
674 }
675 case kAlternativePlc: {
676 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000677 DoAlternativePlc(false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000678 break;
679 }
680 case kAlternativePlcIncreaseTimestamp: {
681 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000682 DoAlternativePlc(true);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000683 break;
684 }
685 case kAudioRepetitionIncreaseTimestamp: {
686 // TODO(hlundin): Write test for this.
687 sync_buffer_->IncreaseEndTimestamp(output_size_samples_);
688 // Skipping break on purpose. Execution should move on into the
689 // next case.
690 }
691 case kAudioRepetition: {
692 // TODO(hlundin): Write test for this.
693 // Copy last |output_size_samples_| from |sync_buffer_| to
694 // |algorithm_buffer|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000695 algorithm_buffer_->PushBackFromIndex(
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000696 *sync_buffer_, sync_buffer_->Size() - output_size_samples_);
697 expand_->Reset();
698 break;
699 }
700 case kUndefined: {
701 LOG_F(LS_ERROR) << "Invalid operation kUndefined.";
702 assert(false); // This should not happen.
703 last_mode_ = kModeError;
704 return kInvalidOperation;
705 }
706 } // End of switch.
707 if (return_value < 0) {
708 return return_value;
709 }
710
711 if (last_mode_ != kModeRfc3389Cng) {
712 comfort_noise_->Reset();
713 }
714
715 // Copy from |algorithm_buffer| to |sync_buffer_|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000716 sync_buffer_->PushBack(*algorithm_buffer_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000717
718 // Extract data from |sync_buffer_| to |output|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000719 size_t num_output_samples_per_channel = output_size_samples_;
720 size_t num_output_samples = output_size_samples_ * sync_buffer_->Channels();
721 if (num_output_samples > max_length) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000722 LOG(LS_WARNING) << "Output array is too short. " << max_length << " < " <<
723 output_size_samples_ << " * " << sync_buffer_->Channels();
724 num_output_samples = max_length;
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000725 num_output_samples_per_channel = static_cast<int>(
726 max_length / sync_buffer_->Channels());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000727 }
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000728 int samples_from_sync = static_cast<int>(
729 sync_buffer_->GetNextAudioInterleaved(num_output_samples_per_channel,
730 output));
731 *num_channels = static_cast<int>(sync_buffer_->Channels());
henrik.lundin@webrtc.orgb3e905c2013-09-02 09:41:06 +0000732 NETEQ_LOG_VERBOSE << "Sync buffer (" << *num_channels << " channel(s)):" <<
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000733 " insert " << algorithm_buffer_->Size() << " samples, extract " <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000734 samples_from_sync << " samples";
735 if (samples_from_sync != output_size_samples_) {
736 LOG_F(LS_ERROR) << "samples_from_sync != output_size_samples_";
minyue@webrtc.orgdb1cefc2013-08-13 01:39:21 +0000737 // TODO(minyue): treatment of under-run, filling zeros
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000738 memset(output, 0, num_output_samples * sizeof(int16_t));
739 *samples_per_channel = output_size_samples_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000740 return kSampleUnderrun;
741 }
742 *samples_per_channel = output_size_samples_;
743
744 // Should always have overlap samples left in the |sync_buffer_|.
745 assert(sync_buffer_->FutureLength() >= expand_->overlap_length());
746
747 if (play_dtmf) {
748 return_value = DtmfOverdub(dtmf_event, sync_buffer_->Channels(), output);
749 }
750
751 // Update the background noise parameters if last operation wrote data
752 // straight from the decoder to the |sync_buffer_|. That is, none of the
753 // operations that modify the signal can be followed by a parameter update.
754 if ((last_mode_ == kModeNormal) ||
755 (last_mode_ == kModeAccelerateFail) ||
756 (last_mode_ == kModePreemptiveExpandFail) ||
757 (last_mode_ == kModeRfc3389Cng) ||
758 (last_mode_ == kModeCodecInternalCng)) {
759 background_noise_->Update(*sync_buffer_, *vad_.get());
760 }
761
762 if (operation == kDtmf) {
763 // DTMF data was written the end of |sync_buffer_|.
764 // Update index to end of DTMF data in |sync_buffer_|.
765 sync_buffer_->set_dtmf_index(sync_buffer_->Size());
766 }
767
768 if ((last_mode_ != kModeExpand) && (last_mode_ != kModeRfc3389Cng)) {
769 // If last operation was neither expand, nor comfort noise, calculate the
770 // |playout_timestamp_| from the |sync_buffer_|. However, do not update the
771 // |playout_timestamp_| if it would be moved "backwards".
772 uint32_t temp_timestamp = sync_buffer_->end_timestamp() -
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000773 static_cast<uint32_t>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000774 if (static_cast<int32_t>(temp_timestamp - playout_timestamp_) > 0) {
775 playout_timestamp_ = temp_timestamp;
776 }
777 } else {
778 // Use dead reckoning to estimate the |playout_timestamp_|.
779 playout_timestamp_ += output_size_samples_;
780 }
781
782 if (decode_return_value) return decode_return_value;
783 return return_value;
784}
785
786int NetEqImpl::GetDecision(Operations* operation,
787 PacketList* packet_list,
788 DtmfEvent* dtmf_event,
789 bool* play_dtmf) {
790 // Initialize output variables.
791 *play_dtmf = false;
792 *operation = kUndefined;
793
794 // Increment time counters.
795 packet_buffer_->IncrementWaitingTimes();
796 stats_.IncreaseCounter(output_size_samples_, fs_hz_);
797
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000798 assert(sync_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000799 uint32_t end_timestamp = sync_buffer_->end_timestamp();
800 if (!new_codec_) {
801 packet_buffer_->DiscardOldPackets(end_timestamp);
802 }
803 const RTPHeader* header = packet_buffer_->NextRtpHeader();
804
805 if (decision_logic_->CngRfc3389On()) {
806 // Because of timestamp peculiarities, we have to "manually" disallow using
807 // a CNG packet with the same timestamp as the one that was last played.
808 // This can happen when using redundancy and will cause the timing to shift.
809 while (header &&
810 decoder_database_->IsComfortNoise(header->payloadType) &&
811 end_timestamp >= header->timestamp) {
812 // Don't use this packet, discard it.
813 // TODO(hlundin): Write test for this case.
814 if (packet_buffer_->DiscardNextPacket() != PacketBuffer::kOK) {
815 assert(false); // Must be ok by design.
816 }
817 // Check buffer again.
818 if (!new_codec_) {
819 packet_buffer_->DiscardOldPackets(end_timestamp);
820 }
821 header = packet_buffer_->NextRtpHeader();
822 }
823 }
824
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000825 assert(expand_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000826 const int samples_left = static_cast<int>(sync_buffer_->FutureLength() -
827 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000828 if (last_mode_ == kModeAccelerateSuccess ||
829 last_mode_ == kModeAccelerateLowEnergy ||
830 last_mode_ == kModePreemptiveExpandSuccess ||
831 last_mode_ == kModePreemptiveExpandLowEnergy) {
832 // Subtract (samples_left + output_size_samples_) from sampleMemory.
833 decision_logic_->AddSampleMemory(-(samples_left + output_size_samples_));
834 }
835
836 // Check if it is time to play a DTMF event.
837 if (dtmf_buffer_->GetEvent(end_timestamp +
838 decision_logic_->generated_noise_samples(),
839 dtmf_event)) {
840 *play_dtmf = true;
841 }
842
843 // Get instruction.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000844 assert(sync_buffer_.get());
845 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000846 *operation = decision_logic_->GetDecision(*sync_buffer_,
847 *expand_,
848 decoder_frame_length_,
849 header,
850 last_mode_,
851 *play_dtmf,
852 &reset_decoder_);
853
854 // Check if we already have enough samples in the |sync_buffer_|. If so,
855 // change decision to normal, unless the decision was merge, accelerate, or
856 // preemptive expand.
857 if (samples_left >= output_size_samples_ &&
858 *operation != kMerge &&
859 *operation != kAccelerate &&
860 *operation != kPreemptiveExpand) {
861 *operation = kNormal;
862 return 0;
863 }
864
865 decision_logic_->ExpandDecision(*operation == kExpand);
866
867 // Check conditions for reset.
868 if (new_codec_ || *operation == kUndefined) {
869 // The only valid reason to get kUndefined is that new_codec_ is set.
870 assert(new_codec_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000871 if (*play_dtmf && !header) {
872 timestamp_ = dtmf_event->timestamp;
873 } else {
874 assert(header);
875 if (!header) {
876 LOG_F(LS_ERROR) << "Packet missing where it shouldn't.";
877 return -1;
878 }
879 timestamp_ = header->timestamp;
880 if (*operation == kRfc3389CngNoPacket
881#ifndef LEGACY_BITEXACT
882 // Without this check, it can happen that a non-CNG packet is sent to
883 // the CNG decoder as if it was a SID frame. This is clearly a bug,
884 // but is kept for now to maintain bit-exactness with the test
885 // vectors.
886 && decoder_database_->IsComfortNoise(header->payloadType)
887#endif
888 ) {
889 // Change decision to CNG packet, since we do have a CNG packet, but it
890 // was considered too early to use. Now, use it anyway.
891 *operation = kRfc3389Cng;
892 } else if (*operation != kRfc3389Cng) {
893 *operation = kNormal;
894 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000895 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000896 // Adjust |sync_buffer_| timestamp before setting |end_timestamp| to the
897 // new value.
898 sync_buffer_->IncreaseEndTimestamp(timestamp_ - end_timestamp);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000899 end_timestamp = timestamp_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000900 new_codec_ = false;
901 decision_logic_->SoftReset();
902 buffer_level_filter_->Reset();
903 delay_manager_->Reset();
904 stats_.ResetMcu();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000905 }
906
907 int required_samples = output_size_samples_;
908 const int samples_10_ms = 80 * fs_mult_;
909 const int samples_20_ms = 2 * samples_10_ms;
910 const int samples_30_ms = 3 * samples_10_ms;
911
912 switch (*operation) {
913 case kExpand: {
914 timestamp_ = end_timestamp;
915 return 0;
916 }
917 case kRfc3389CngNoPacket:
918 case kCodecInternalCng: {
919 return 0;
920 }
921 case kDtmf: {
922 // TODO(hlundin): Write test for this.
923 // Update timestamp.
924 timestamp_ = end_timestamp;
925 if (decision_logic_->generated_noise_samples() > 0 &&
926 last_mode_ != kModeDtmf) {
927 // Make a jump in timestamp due to the recently played comfort noise.
928 uint32_t timestamp_jump = decision_logic_->generated_noise_samples();
929 sync_buffer_->IncreaseEndTimestamp(timestamp_jump);
930 timestamp_ += timestamp_jump;
931 }
932 decision_logic_->set_generated_noise_samples(0);
933 return 0;
934 }
935 case kAccelerate: {
936 // In order to do a accelerate we need at least 30 ms of audio data.
937 if (samples_left >= samples_30_ms) {
938 // Already have enough data, so we do not need to extract any more.
939 decision_logic_->set_sample_memory(samples_left);
940 decision_logic_->set_prev_time_scale(true);
941 return 0;
942 } else if (samples_left >= samples_10_ms &&
943 decoder_frame_length_ >= samples_30_ms) {
944 // Avoid decoding more data as it might overflow the playout buffer.
945 *operation = kNormal;
946 return 0;
947 } else if (samples_left < samples_20_ms &&
948 decoder_frame_length_ < samples_30_ms) {
949 // Build up decoded data by decoding at least 20 ms of audio data. Do
950 // not perform accelerate yet, but wait until we only need to do one
951 // decoding.
952 required_samples = 2 * output_size_samples_;
953 *operation = kNormal;
954 }
955 // If none of the above is true, we have one of two possible situations:
956 // (1) 20 ms <= samples_left < 30 ms and decoder_frame_length_ < 30 ms; or
957 // (2) samples_left < 10 ms and decoder_frame_length_ >= 30 ms.
958 // In either case, we move on with the accelerate decision, and decode one
959 // frame now.
960 break;
961 }
962 case kPreemptiveExpand: {
963 // In order to do a preemptive expand we need at least 30 ms of decoded
964 // audio data.
965 if ((samples_left >= samples_30_ms) ||
966 (samples_left >= samples_10_ms &&
967 decoder_frame_length_ >= samples_30_ms)) {
968 // Already have enough data, so we do not need to extract any more.
969 // Or, avoid decoding more data as it might overflow the playout buffer.
970 // Still try preemptive expand, though.
971 decision_logic_->set_sample_memory(samples_left);
972 decision_logic_->set_prev_time_scale(true);
973 return 0;
974 }
975 if (samples_left < samples_20_ms &&
976 decoder_frame_length_ < samples_30_ms) {
977 // Build up decoded data by decoding at least 20 ms of audio data.
978 // Still try to perform preemptive expand.
979 required_samples = 2 * output_size_samples_;
980 }
981 // Move on with the preemptive expand decision.
982 break;
983 }
984 default: {
985 // Do nothing.
986 }
987 }
988
989 // Get packets from buffer.
990 int extracted_samples = 0;
991 if (header &&
992 *operation != kAlternativePlc &&
993 *operation != kAlternativePlcIncreaseTimestamp &&
994 *operation != kAudioRepetition &&
995 *operation != kAudioRepetitionIncreaseTimestamp) {
996 sync_buffer_->IncreaseEndTimestamp(header->timestamp - end_timestamp);
997 if (decision_logic_->CngOff()) {
998 // Adjustment of timestamp only corresponds to an actual packet loss
999 // if comfort noise is not played. If comfort noise was just played,
1000 // this adjustment of timestamp is only done to get back in sync with the
1001 // stream timestamp; no loss to report.
1002 stats_.LostSamples(header->timestamp - end_timestamp);
1003 }
1004
1005 if (*operation != kRfc3389Cng) {
1006 // We are about to decode and use a non-CNG packet.
1007 decision_logic_->SetCngOff();
1008 }
1009 // Reset CNG timestamp as a new packet will be delivered.
1010 // (Also if this is a CNG packet, since playedOutTS is updated.)
1011 decision_logic_->set_generated_noise_samples(0);
1012
1013 extracted_samples = ExtractPackets(required_samples, packet_list);
1014 if (extracted_samples < 0) {
1015 LOG_F(LS_WARNING) << "Failed to extract packets from buffer.";
1016 return kPacketBufferCorruption;
1017 }
1018 }
1019
1020 if (*operation == kAccelerate ||
1021 *operation == kPreemptiveExpand) {
1022 decision_logic_->set_sample_memory(samples_left + extracted_samples);
1023 decision_logic_->set_prev_time_scale(true);
1024 }
1025
1026 if (*operation == kAccelerate) {
1027 // Check that we have enough data (30ms) to do accelerate.
1028 if (extracted_samples + samples_left < samples_30_ms) {
1029 // TODO(hlundin): Write test for this.
1030 // Not enough, do normal operation instead.
1031 *operation = kNormal;
1032 }
1033 }
1034
1035 timestamp_ = end_timestamp;
1036 return 0;
1037}
1038
1039int NetEqImpl::Decode(PacketList* packet_list, Operations* operation,
1040 int* decoded_length,
1041 AudioDecoder::SpeechType* speech_type) {
1042 *speech_type = AudioDecoder::kSpeech;
1043 AudioDecoder* decoder = NULL;
1044 if (!packet_list->empty()) {
1045 const Packet* packet = packet_list->front();
1046 int payload_type = packet->header.payloadType;
1047 if (!decoder_database_->IsComfortNoise(payload_type)) {
1048 decoder = decoder_database_->GetDecoder(payload_type);
1049 assert(decoder);
1050 if (!decoder) {
1051 LOG_FERR1(LS_WARNING, GetDecoder, payload_type);
1052 PacketBuffer::DeleteAllPackets(packet_list);
1053 return kDecoderNotFound;
1054 }
1055 bool decoder_changed;
1056 decoder_database_->SetActiveDecoder(payload_type, &decoder_changed);
1057 if (decoder_changed) {
1058 // We have a new decoder. Re-init some values.
1059 const DecoderDatabase::DecoderInfo* decoder_info = decoder_database_
1060 ->GetDecoderInfo(payload_type);
1061 assert(decoder_info);
1062 if (!decoder_info) {
1063 LOG_FERR1(LS_WARNING, GetDecoderInfo, payload_type);
1064 PacketBuffer::DeleteAllPackets(packet_list);
1065 return kDecoderNotFound;
1066 }
1067 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->channels());
1068 sync_buffer_->set_end_timestamp(timestamp_);
1069 playout_timestamp_ = timestamp_;
1070 }
1071 }
1072 }
1073
1074 if (reset_decoder_) {
1075 // TODO(hlundin): Write test for this.
1076 // Reset decoder.
1077 if (decoder) {
1078 decoder->Init();
1079 }
1080 // Reset comfort noise decoder.
1081 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
1082 if (cng_decoder) {
1083 cng_decoder->Init();
1084 }
1085 reset_decoder_ = false;
1086 }
1087
1088#ifdef LEGACY_BITEXACT
1089 // Due to a bug in old SignalMCU, it could happen that CNG operation was
1090 // decided, but a speech packet was provided. The speech packet will be used
1091 // to update the comfort noise decoder, as if it was a SID frame, which is
1092 // clearly wrong.
1093 if (*operation == kRfc3389Cng) {
1094 return 0;
1095 }
1096#endif
1097
1098 *decoded_length = 0;
1099 // Update codec-internal PLC state.
1100 if ((*operation == kMerge) && decoder && decoder->HasDecodePlc()) {
1101 decoder->DecodePlc(1, &decoded_buffer_[*decoded_length]);
1102 }
1103
1104 int return_value = DecodeLoop(packet_list, operation, decoder,
1105 decoded_length, speech_type);
1106
1107 if (*decoded_length < 0) {
1108 // Error returned from the decoder.
1109 *decoded_length = 0;
1110 sync_buffer_->IncreaseEndTimestamp(decoder_frame_length_);
1111 int error_code = 0;
1112 if (decoder)
1113 error_code = decoder->ErrorCode();
1114 if (error_code != 0) {
1115 // Got some error code from the decoder.
1116 decoder_error_code_ = error_code;
1117 return_value = kDecoderErrorCode;
1118 } else {
1119 // Decoder does not implement error codes. Return generic error.
1120 return_value = kOtherDecoderError;
1121 }
1122 LOG_FERR2(LS_WARNING, DecodeLoop, error_code, packet_list->size());
1123 *operation = kExpand; // Do expansion to get data instead.
1124 }
1125 if (*speech_type != AudioDecoder::kComfortNoise) {
1126 // Don't increment timestamp if codec returned CNG speech type
1127 // since in this case, the we will increment the CNGplayedTS counter.
1128 // Increase with number of samples per channel.
1129 assert(*decoded_length == 0 ||
1130 (decoder && decoder->channels() == sync_buffer_->Channels()));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001131 sync_buffer_->IncreaseEndTimestamp(
1132 *decoded_length / static_cast<int>(sync_buffer_->Channels()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001133 }
1134 return return_value;
1135}
1136
1137int NetEqImpl::DecodeLoop(PacketList* packet_list, Operations* operation,
1138 AudioDecoder* decoder, int* decoded_length,
1139 AudioDecoder::SpeechType* speech_type) {
1140 Packet* packet = NULL;
1141 if (!packet_list->empty()) {
1142 packet = packet_list->front();
1143 }
1144 // Do decoding.
1145 while (packet &&
1146 !decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1147 assert(decoder); // At this point, we must have a decoder object.
1148 // The number of channels in the |sync_buffer_| should be the same as the
1149 // number decoder channels.
1150 assert(sync_buffer_->Channels() == decoder->channels());
1151 assert(decoded_buffer_length_ >= kMaxFrameSize * decoder->channels());
1152 assert(*operation == kNormal || *operation == kAccelerate ||
1153 *operation == kMerge || *operation == kPreemptiveExpand);
1154 packet_list->pop_front();
henrik.lundin@webrtc.org63464a92013-01-30 09:41:56 +00001155 int payload_length = packet->payload_length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001156 int16_t decode_length;
1157 if (!packet->primary) {
1158 // This is a redundant payload; call the special decoder method.
henrik.lundin@webrtc.orgb3e905c2013-09-02 09:41:06 +00001159 NETEQ_LOG_VERBOSE << "Decoding packet (redundant):" <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001160 " ts=" << packet->header.timestamp <<
1161 ", sn=" << packet->header.sequenceNumber <<
1162 ", pt=" << static_cast<int>(packet->header.payloadType) <<
1163 ", ssrc=" << packet->header.ssrc <<
1164 ", len=" << packet->payload_length;
1165 decode_length = decoder->DecodeRedundant(
1166 packet->payload, packet->payload_length,
1167 &decoded_buffer_[*decoded_length], speech_type);
1168 } else {
henrik.lundin@webrtc.orgb3e905c2013-09-02 09:41:06 +00001169 NETEQ_LOG_VERBOSE << "Decoding packet: ts=" << packet->header.timestamp <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001170 ", sn=" << packet->header.sequenceNumber <<
1171 ", pt=" << static_cast<int>(packet->header.payloadType) <<
1172 ", ssrc=" << packet->header.ssrc <<
1173 ", len=" << packet->payload_length;
1174 decode_length = decoder->Decode(packet->payload,
1175 packet->payload_length,
1176 &decoded_buffer_[*decoded_length],
1177 speech_type);
1178 }
1179
1180 delete[] packet->payload;
1181 delete packet;
1182 if (decode_length > 0) {
1183 *decoded_length += decode_length;
1184 // Update |decoder_frame_length_| with number of samples per channel.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001185 decoder_frame_length_ = decode_length /
1186 static_cast<int>(decoder->channels());
henrik.lundin@webrtc.orgb3e905c2013-09-02 09:41:06 +00001187 NETEQ_LOG_VERBOSE << "Decoded " << decode_length << " samples (" <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001188 decoder->channels() << " channel(s) -> " << decoder_frame_length_ <<
1189 " samples per channel)";
1190 } else if (decode_length < 0) {
1191 // Error.
henrik.lundin@webrtc.org63464a92013-01-30 09:41:56 +00001192 LOG_FERR2(LS_WARNING, Decode, decode_length, payload_length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001193 *decoded_length = -1;
1194 PacketBuffer::DeleteAllPackets(packet_list);
1195 break;
1196 }
1197 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1198 // Guard against overflow.
1199 LOG_F(LS_WARNING) << "Decoded too much.";
1200 PacketBuffer::DeleteAllPackets(packet_list);
1201 return kDecodedTooMuch;
1202 }
1203 if (!packet_list->empty()) {
1204 packet = packet_list->front();
1205 } else {
1206 packet = NULL;
1207 }
1208 } // End of decode loop.
1209
1210 // If the list is not empty at this point, it must hold exactly one CNG
1211 // packet.
1212 assert(packet_list->empty() ||
1213 (packet_list->size() == 1 &&
1214 decoder_database_->IsComfortNoise(packet->header.payloadType)));
1215 return 0;
1216}
1217
1218void NetEqImpl::DoNormal(const int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001219 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001220 assert(normal_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001221 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001222 normal_->Process(decoded_buffer, decoded_length, last_mode_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001223 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001224 if (decoded_length != 0) {
1225 last_mode_ = kModeNormal;
1226 }
1227
1228 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1229 if ((speech_type == AudioDecoder::kComfortNoise)
1230 || ((last_mode_ == kModeCodecInternalCng)
1231 && (decoded_length == 0))) {
1232 // TODO(hlundin): Remove second part of || statement above.
1233 last_mode_ = kModeCodecInternalCng;
1234 }
1235
1236 if (!play_dtmf) {
1237 dtmf_tone_generator_->Reset();
1238 }
1239}
1240
1241void NetEqImpl::DoMerge(int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001242 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001243 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001244 assert(merge_.get());
1245 int new_length = merge_->Process(decoded_buffer, decoded_length,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001246 mute_factor_array_.get(),
1247 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001248
1249 // Update in-call and post-call statistics.
1250 if (expand_->MuteFactor(0) == 0) {
1251 // Expand generates only noise.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001252 stats_.ExpandedNoiseSamples(new_length - static_cast<int>(decoded_length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001253 } else {
1254 // Expansion generates more than only noise.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001255 stats_.ExpandedVoiceSamples(new_length - static_cast<int>(decoded_length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001256 }
1257
1258 last_mode_ = kModeMerge;
1259 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1260 if (speech_type == AudioDecoder::kComfortNoise) {
1261 last_mode_ = kModeCodecInternalCng;
1262 }
1263 expand_->Reset();
1264 if (!play_dtmf) {
1265 dtmf_tone_generator_->Reset();
1266 }
1267}
1268
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001269int NetEqImpl::DoExpand(bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001270 while ((sync_buffer_->FutureLength() - expand_->overlap_length()) <
1271 static_cast<size_t>(output_size_samples_)) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001272 algorithm_buffer_->Clear();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001273 int return_value = expand_->Process(algorithm_buffer_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001274 int length = static_cast<int>(algorithm_buffer_->Size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001275
1276 // Update in-call and post-call statistics.
1277 if (expand_->MuteFactor(0) == 0) {
1278 // Expand operation generates only noise.
1279 stats_.ExpandedNoiseSamples(length);
1280 } else {
1281 // Expand operation generates more than only noise.
1282 stats_.ExpandedVoiceSamples(length);
1283 }
1284
1285 last_mode_ = kModeExpand;
1286
1287 if (return_value < 0) {
1288 return return_value;
1289 }
1290
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001291 sync_buffer_->PushBack(*algorithm_buffer_);
1292 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001293 }
1294 if (!play_dtmf) {
1295 dtmf_tone_generator_->Reset();
1296 }
1297 return 0;
1298}
1299
1300int NetEqImpl::DoAccelerate(int16_t* decoded_buffer, size_t decoded_length,
1301 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001302 bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001303 const size_t required_samples = 240 * fs_mult_; // Must have 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001304 size_t borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001305 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001306 size_t decoded_length_per_channel = decoded_length / num_channels;
1307 if (decoded_length_per_channel < required_samples) {
1308 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001309 borrowed_samples_per_channel = static_cast<int>(required_samples -
1310 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001311 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1312 decoded_buffer,
1313 sizeof(int16_t) * decoded_length);
1314 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1315 decoded_buffer);
1316 decoded_length = required_samples * num_channels;
1317 }
1318
1319 int16_t samples_removed;
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001320 Accelerate::ReturnCodes return_code = accelerate_->Process(
1321 decoded_buffer, decoded_length, algorithm_buffer_.get(),
1322 &samples_removed);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001323 stats_.AcceleratedSamples(samples_removed);
1324 switch (return_code) {
1325 case Accelerate::kSuccess:
1326 last_mode_ = kModeAccelerateSuccess;
1327 break;
1328 case Accelerate::kSuccessLowEnergy:
1329 last_mode_ = kModeAccelerateLowEnergy;
1330 break;
1331 case Accelerate::kNoStretch:
1332 last_mode_ = kModeAccelerateFail;
1333 break;
1334 case Accelerate::kError:
1335 // TODO(hlundin): Map to kModeError instead?
1336 last_mode_ = kModeAccelerateFail;
1337 return kAccelerateError;
1338 }
1339
1340 if (borrowed_samples_per_channel > 0) {
1341 // Copy borrowed samples back to the |sync_buffer_|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001342 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001343 if (length < borrowed_samples_per_channel) {
1344 // This destroys the beginning of the buffer, but will not cause any
1345 // problems.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001346 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001347 sync_buffer_->Size() -
1348 borrowed_samples_per_channel);
1349 sync_buffer_->PushFrontZeros(borrowed_samples_per_channel - length);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001350 algorithm_buffer_->PopFront(length);
1351 assert(algorithm_buffer_->Empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001352 } else {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001353 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001354 borrowed_samples_per_channel,
1355 sync_buffer_->Size() -
1356 borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001357 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001358 }
1359 }
1360
1361 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1362 if (speech_type == AudioDecoder::kComfortNoise) {
1363 last_mode_ = kModeCodecInternalCng;
1364 }
1365 if (!play_dtmf) {
1366 dtmf_tone_generator_->Reset();
1367 }
1368 expand_->Reset();
1369 return 0;
1370}
1371
1372int NetEqImpl::DoPreemptiveExpand(int16_t* decoded_buffer,
1373 size_t decoded_length,
1374 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001375 bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001376 const size_t required_samples = 240 * fs_mult_; // Must have 30 ms.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001377 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001378 int borrowed_samples_per_channel = 0;
1379 int old_borrowed_samples_per_channel = 0;
1380 size_t decoded_length_per_channel = decoded_length / num_channels;
1381 if (decoded_length_per_channel < required_samples) {
1382 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001383 borrowed_samples_per_channel = static_cast<int>(required_samples -
1384 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001385 // Calculate how many of these were already played out.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001386 old_borrowed_samples_per_channel = static_cast<int>(
1387 borrowed_samples_per_channel - sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001388 old_borrowed_samples_per_channel = std::max(
1389 0, old_borrowed_samples_per_channel);
1390 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1391 decoded_buffer,
1392 sizeof(int16_t) * decoded_length);
1393 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1394 decoded_buffer);
1395 decoded_length = required_samples * num_channels;
1396 }
1397
1398 int16_t samples_added;
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001399 PreemptiveExpand::ReturnCodes return_code = preemptive_expand_->Process(
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001400 decoded_buffer, static_cast<int>(decoded_length),
1401 old_borrowed_samples_per_channel,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001402 algorithm_buffer_.get(), &samples_added);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001403 stats_.PreemptiveExpandedSamples(samples_added);
1404 switch (return_code) {
1405 case PreemptiveExpand::kSuccess:
1406 last_mode_ = kModePreemptiveExpandSuccess;
1407 break;
1408 case PreemptiveExpand::kSuccessLowEnergy:
1409 last_mode_ = kModePreemptiveExpandLowEnergy;
1410 break;
1411 case PreemptiveExpand::kNoStretch:
1412 last_mode_ = kModePreemptiveExpandFail;
1413 break;
1414 case PreemptiveExpand::kError:
1415 // TODO(hlundin): Map to kModeError instead?
1416 last_mode_ = kModePreemptiveExpandFail;
1417 return kPreemptiveExpandError;
1418 }
1419
1420 if (borrowed_samples_per_channel > 0) {
1421 // Copy borrowed samples back to the |sync_buffer_|.
1422 sync_buffer_->ReplaceAtIndex(
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001423 *algorithm_buffer_, borrowed_samples_per_channel,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001424 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001425 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001426 }
1427
1428 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1429 if (speech_type == AudioDecoder::kComfortNoise) {
1430 last_mode_ = kModeCodecInternalCng;
1431 }
1432 if (!play_dtmf) {
1433 dtmf_tone_generator_->Reset();
1434 }
1435 expand_->Reset();
1436 return 0;
1437}
1438
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001439int NetEqImpl::DoRfc3389Cng(PacketList* packet_list, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001440 if (!packet_list->empty()) {
1441 // Must have exactly one SID frame at this point.
1442 assert(packet_list->size() == 1);
1443 Packet* packet = packet_list->front();
1444 packet_list->pop_front();
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001445 if (!decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1446#ifdef LEGACY_BITEXACT
1447 // This can happen due to a bug in GetDecision. Change the payload type
1448 // to a CNG type, and move on. Note that this means that we are in fact
1449 // sending a non-CNG payload to the comfort noise decoder for decoding.
1450 // Clearly wrong, but will maintain bit-exactness with legacy.
1451 if (fs_hz_ == 8000) {
1452 packet->header.payloadType =
1453 decoder_database_->GetRtpPayloadType(kDecoderCNGnb);
1454 } else if (fs_hz_ == 16000) {
1455 packet->header.payloadType =
1456 decoder_database_->GetRtpPayloadType(kDecoderCNGwb);
1457 } else if (fs_hz_ == 32000) {
1458 packet->header.payloadType =
1459 decoder_database_->GetRtpPayloadType(kDecoderCNGswb32kHz);
1460 } else if (fs_hz_ == 48000) {
1461 packet->header.payloadType =
1462 decoder_database_->GetRtpPayloadType(kDecoderCNGswb48kHz);
1463 }
1464 assert(decoder_database_->IsComfortNoise(packet->header.payloadType));
1465#else
1466 LOG(LS_ERROR) << "Trying to decode non-CNG payload as CNG.";
1467 return kOtherError;
1468#endif
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001469 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001470 // UpdateParameters() deletes |packet|.
1471 if (comfort_noise_->UpdateParameters(packet) ==
1472 ComfortNoise::kInternalError) {
1473 LOG_FERR0(LS_WARNING, UpdateParameters);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001474 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001475 return -comfort_noise_->internal_error_code();
1476 }
1477 }
1478 int cn_return = comfort_noise_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001479 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001480 expand_->Reset();
1481 last_mode_ = kModeRfc3389Cng;
1482 if (!play_dtmf) {
1483 dtmf_tone_generator_->Reset();
1484 }
1485 if (cn_return == ComfortNoise::kInternalError) {
1486 LOG_FERR1(LS_WARNING, comfort_noise_->Generate, cn_return);
1487 decoder_error_code_ = comfort_noise_->internal_error_code();
1488 return kComfortNoiseErrorCode;
1489 } else if (cn_return == ComfortNoise::kUnknownPayloadType) {
1490 LOG_FERR1(LS_WARNING, comfort_noise_->Generate, cn_return);
1491 return kUnknownRtpPayloadType;
1492 }
1493 return 0;
1494}
1495
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001496void NetEqImpl::DoCodecInternalCng() {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001497 int length = 0;
1498 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1499 int16_t decoded_buffer[kMaxFrameSize];
1500 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1501 if (decoder) {
1502 const uint8_t* dummy_payload = NULL;
1503 AudioDecoder::SpeechType speech_type;
1504 length = decoder->Decode(dummy_payload, 0, decoded_buffer, &speech_type);
1505 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001506 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001507 normal_->Process(decoded_buffer, length, last_mode_, mute_factor_array_.get(),
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001508 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001509 last_mode_ = kModeCodecInternalCng;
1510 expand_->Reset();
1511}
1512
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001513int NetEqImpl::DoDtmf(const DtmfEvent& dtmf_event, bool* play_dtmf) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001514 // This block of the code and the block further down, handling |dtmf_switch|
1515 // are commented out. Otherwise playing out-of-band DTMF would fail in VoE
1516 // test, DtmfTest.ManualSuccessfullySendsOutOfBandTelephoneEvents. This is
1517 // equivalent to |dtmf_switch| always be false.
1518 //
1519 // See http://webrtc-codereview.appspot.com/1195004/ for discussion
1520 // On this issue. This change might cause some glitches at the point of
1521 // switch from audio to DTMF. Issue 1545 is filed to track this.
1522 //
1523 // bool dtmf_switch = false;
1524 // if ((last_mode_ != kModeDtmf) && dtmf_tone_generator_->initialized()) {
1525 // // Special case; see below.
1526 // // We must catch this before calling Generate, since |initialized| is
1527 // // modified in that call.
1528 // dtmf_switch = true;
1529 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001530
1531 int dtmf_return_value = 0;
1532 if (!dtmf_tone_generator_->initialized()) {
1533 // Initialize if not already done.
1534 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1535 dtmf_event.volume);
1536 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001537
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001538 if (dtmf_return_value == 0) {
1539 // Generate DTMF signal.
1540 dtmf_return_value = dtmf_tone_generator_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001541 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001542 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001543
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001544 if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001545 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001546 return dtmf_return_value;
1547 }
1548
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001549 // if (dtmf_switch) {
1550 // // This is the special case where the previous operation was DTMF
1551 // // overdub, but the current instruction is "regular" DTMF. We must make
1552 // // sure that the DTMF does not have any discontinuities. The first DTMF
1553 // // sample that we generate now must be played out immediately, therefore
1554 // // it must be copied to the speech buffer.
1555 // // TODO(hlundin): This code seems incorrect. (Legacy.) Write test and
1556 // // verify correct operation.
1557 // assert(false);
1558 // // Must generate enough data to replace all of the |sync_buffer_|
1559 // // "future".
1560 // int required_length = sync_buffer_->FutureLength();
1561 // assert(dtmf_tone_generator_->initialized());
1562 // dtmf_return_value = dtmf_tone_generator_->Generate(required_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001563 // algorithm_buffer_);
1564 // assert((size_t) required_length == algorithm_buffer_->Size());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001565 // if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001566 // algorithm_buffer_->Zeros(output_size_samples_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001567 // return dtmf_return_value;
1568 // }
1569 //
1570 // // Overwrite the "future" part of the speech buffer with the new DTMF
1571 // // data.
1572 // // TODO(hlundin): It seems that this overwriting has gone lost.
1573 // // Not adapted for multi-channel yet.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001574 // assert(algorithm_buffer_->Channels() == 1);
1575 // if (algorithm_buffer_->Channels() != 1) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001576 // LOG(LS_WARNING) << "DTMF not supported for more than one channel";
1577 // return kStereoNotSupported;
1578 // }
1579 // // Shuffle the remaining data to the beginning of algorithm buffer.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001580 // algorithm_buffer_->PopFront(sync_buffer_->FutureLength());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001581 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001582
1583 sync_buffer_->IncreaseEndTimestamp(output_size_samples_);
1584 expand_->Reset();
1585 last_mode_ = kModeDtmf;
1586
1587 // Set to false because the DTMF is already in the algorithm buffer.
1588 *play_dtmf = false;
1589 return 0;
1590}
1591
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001592void NetEqImpl::DoAlternativePlc(bool increase_timestamp) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001593 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1594 int length;
1595 if (decoder && decoder->HasDecodePlc()) {
1596 // Use the decoder's packet-loss concealment.
1597 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1598 int16_t decoded_buffer[kMaxFrameSize];
1599 length = decoder->DecodePlc(1, decoded_buffer);
1600 if (length > 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001601 algorithm_buffer_->PushBackInterleaved(decoded_buffer, length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001602 } else {
1603 length = 0;
1604 }
1605 } else {
1606 // Do simple zero-stuffing.
1607 length = output_size_samples_;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001608 algorithm_buffer_->Zeros(length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001609 // By not advancing the timestamp, NetEq inserts samples.
1610 stats_.AddZeros(length);
1611 }
1612 if (increase_timestamp) {
1613 sync_buffer_->IncreaseEndTimestamp(length);
1614 }
1615 expand_->Reset();
1616}
1617
1618int NetEqImpl::DtmfOverdub(const DtmfEvent& dtmf_event, size_t num_channels,
1619 int16_t* output) const {
1620 size_t out_index = 0;
1621 int overdub_length = output_size_samples_; // Default value.
1622
1623 if (sync_buffer_->dtmf_index() > sync_buffer_->next_index()) {
1624 // Special operation for transition from "DTMF only" to "DTMF overdub".
1625 out_index = std::min(
1626 sync_buffer_->dtmf_index() - sync_buffer_->next_index(),
1627 static_cast<size_t>(output_size_samples_));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001628 overdub_length = output_size_samples_ - static_cast<int>(out_index);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001629 }
1630
1631 AudioMultiVector<int16_t> dtmf_output(num_channels);
1632 int dtmf_return_value = 0;
1633 if (!dtmf_tone_generator_->initialized()) {
1634 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1635 dtmf_event.volume);
1636 }
1637 if (dtmf_return_value == 0) {
1638 dtmf_return_value = dtmf_tone_generator_->Generate(overdub_length,
1639 &dtmf_output);
1640 assert((size_t) overdub_length == dtmf_output.Size());
1641 }
1642 dtmf_output.ReadInterleaved(overdub_length, &output[out_index]);
1643 return dtmf_return_value < 0 ? dtmf_return_value : 0;
1644}
1645
1646int NetEqImpl::ExtractPackets(int required_samples, PacketList* packet_list) {
1647 bool first_packet = true;
1648 uint8_t prev_payload_type = 0;
1649 uint32_t prev_timestamp = 0;
1650 uint16_t prev_sequence_number = 0;
1651 bool next_packet_available = false;
1652
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001653 const RTPHeader* header = packet_buffer_->NextRtpHeader();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001654 assert(header);
1655 if (!header) {
1656 return -1;
1657 }
turaj@webrtc.org7df97062013-08-02 18:07:13 +00001658 uint32_t first_timestamp = header->timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001659 int extracted_samples = 0;
1660
1661 // Packet extraction loop.
1662 do {
1663 timestamp_ = header->timestamp;
1664 int discard_count = 0;
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001665 Packet* packet = packet_buffer_->GetNextPacket(&discard_count);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001666 // |header| may be invalid after the |packet_buffer_| operation.
1667 header = NULL;
1668 if (!packet) {
1669 LOG_FERR1(LS_ERROR, GetNextPacket, discard_count) <<
1670 "Should always be able to extract a packet here";
1671 assert(false); // Should always be able to extract a packet here.
1672 return -1;
1673 }
1674 stats_.PacketsDiscarded(discard_count);
1675 // Store waiting time in ms; packets->waiting_time is in "output blocks".
1676 stats_.StoreWaitingTime(packet->waiting_time * kOutputSizeMs);
1677 assert(packet->payload_length > 0);
1678 packet_list->push_back(packet); // Store packet in list.
1679
1680 if (first_packet) {
1681 first_packet = false;
minyue@webrtc.orgd7301772013-08-29 00:58:14 +00001682 decoded_packet_sequence_number_ = prev_sequence_number =
1683 packet->header.sequenceNumber;
1684 decoded_packet_timestamp_ = prev_timestamp = packet->header.timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001685 prev_payload_type = packet->header.payloadType;
1686 }
1687
1688 // Store number of extracted samples.
1689 int packet_duration = 0;
1690 AudioDecoder* decoder = decoder_database_->GetDecoder(
1691 packet->header.payloadType);
1692 if (decoder) {
1693 packet_duration = decoder->PacketDuration(packet->payload,
1694 packet->payload_length);
1695 } else {
1696 LOG_FERR1(LS_WARNING, GetDecoder, packet->header.payloadType) <<
1697 "Could not find a decoder for a packet about to be extracted.";
1698 assert(false);
1699 }
1700 if (packet_duration <= 0) {
1701 // Decoder did not return a packet duration. Assume that the packet
1702 // contains the same number of samples as the previous one.
1703 packet_duration = decoder_frame_length_;
1704 }
1705 extracted_samples = packet->header.timestamp - first_timestamp +
1706 packet_duration;
1707
1708 // Check what packet is available next.
1709 header = packet_buffer_->NextRtpHeader();
1710 next_packet_available = false;
1711 if (header && prev_payload_type == header->payloadType) {
1712 int16_t seq_no_diff = header->sequenceNumber - prev_sequence_number;
1713 int32_t ts_diff = header->timestamp - prev_timestamp;
1714 if (seq_no_diff == 1 ||
1715 (seq_no_diff == 0 && ts_diff == decoder_frame_length_)) {
1716 // The next sequence number is available, or the next part of a packet
1717 // that was split into pieces upon insertion.
1718 next_packet_available = true;
1719 }
1720 prev_sequence_number = header->sequenceNumber;
1721 }
1722 } while (extracted_samples < required_samples && next_packet_available);
1723
1724 return extracted_samples;
1725}
1726
1727void NetEqImpl::SetSampleRateAndChannels(int fs_hz, size_t channels) {
1728 LOG_API2(fs_hz, channels);
1729 // TODO(hlundin): Change to an enumerator and skip assert.
1730 assert(fs_hz == 8000 || fs_hz == 16000 || fs_hz == 32000 || fs_hz == 48000);
1731 assert(channels > 0);
1732
1733 fs_hz_ = fs_hz;
1734 fs_mult_ = fs_hz / 8000;
1735 output_size_samples_ = kOutputSizeMs * 8 * fs_mult_;
1736 decoder_frame_length_ = 3 * output_size_samples_; // Initialize to 30ms.
1737
1738 last_mode_ = kModeNormal;
1739
1740 // Create a new array of mute factors and set all to 1.
1741 mute_factor_array_.reset(new int16_t[channels]);
1742 for (size_t i = 0; i < channels; ++i) {
1743 mute_factor_array_[i] = 16384; // 1.0 in Q14.
1744 }
1745
1746 // Reset comfort noise decoder, if there is one active.
1747 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
1748 if (cng_decoder) {
1749 cng_decoder->Init();
1750 }
1751
1752 // Reinit post-decode VAD with new sample rate.
1753 assert(vad_.get()); // Cannot be NULL here.
1754 vad_->Init();
1755
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001756 // Delete algorithm buffer and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001757 algorithm_buffer_.reset(new AudioMultiVector<int16_t>(channels));
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001758
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001759 // Delete sync buffer and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001760 sync_buffer_.reset(new SyncBuffer(channels, kSyncBufferSize * fs_mult_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001761
1762 // Delete BackgroundNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001763 background_noise_.reset(new BackgroundNoise(channels));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001764
1765 // Reset random vector.
1766 random_vector_.Reset();
1767
1768 // Delete Expand object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001769 expand_.reset(new Expand(background_noise_.get(), sync_buffer_.get(),
1770 &random_vector_, fs_hz, channels));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001771 // Move index so that we create a small set of future samples (all 0).
1772 sync_buffer_->set_next_index(sync_buffer_->next_index() -
1773 expand_->overlap_length());
1774
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001775 normal_.reset(new Normal(fs_hz, decoder_database_.get(), *background_noise_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001776 expand_.get()));
1777 merge_.reset(new Merge(fs_hz, channels, expand_.get(), sync_buffer_.get()));
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001778 accelerate_.reset(new Accelerate(fs_hz, channels, *background_noise_));
1779 preemptive_expand_.reset(new PreemptiveExpand(fs_hz, channels,
1780 *background_noise_));
1781
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001782 // Delete ComfortNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001783 comfort_noise_.reset(new ComfortNoise(fs_hz, decoder_database_.get(),
1784 sync_buffer_.get()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001785
1786 // Verify that |decoded_buffer_| is long enough.
1787 if (decoded_buffer_length_ < kMaxFrameSize * channels) {
1788 // Reallocate to larger size.
1789 decoded_buffer_length_ = kMaxFrameSize * channels;
1790 decoded_buffer_.reset(new int16_t[decoded_buffer_length_]);
1791 }
1792
1793 // Communicate new sample rate and output size to DecisionLogic object.
1794 assert(decision_logic_.get());
1795 decision_logic_->SetSampleRate(fs_hz_, output_size_samples_);
1796}
1797
1798NetEqOutputType NetEqImpl::LastOutputType() {
1799 assert(vad_.get());
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001800 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001801 if (last_mode_ == kModeCodecInternalCng || last_mode_ == kModeRfc3389Cng) {
1802 return kOutputCNG;
1803 } else if (vad_->running() && !vad_->active_speech()) {
1804 return kOutputVADPassive;
1805 } else if (last_mode_ == kModeExpand && expand_->MuteFactor(0) == 0) {
1806 // Expand mode has faded down to background noise only (very long expand).
1807 return kOutputPLCtoCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001808 } else if (last_mode_ == kModeExpand) {
1809 return kOutputPLC;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001810 } else {
1811 return kOutputNormal;
1812 }
1813}
1814
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001815} // namespace webrtc