blob: 4ffe3e79ea68403d329f69b476bac6fec8ce45e2 [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,
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +000061 TimestampScaler* timestamp_scaler,
62 AccelerateFactory* accelerate_factory,
63 ExpandFactory* expand_factory,
64 PreemptiveExpandFactory* preemptive_expand_factory)
andrew@webrtc.org31628aa2013-10-22 12:50:00 +000065 : buffer_level_filter_(buffer_level_filter),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000066 decoder_database_(decoder_database),
67 delay_manager_(delay_manager),
68 delay_peak_detector_(delay_peak_detector),
69 dtmf_buffer_(dtmf_buffer),
70 dtmf_tone_generator_(dtmf_tone_generator),
71 packet_buffer_(packet_buffer),
72 payload_splitter_(payload_splitter),
73 timestamp_scaler_(timestamp_scaler),
74 vad_(new PostDecodeVad()),
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +000075 expand_factory_(expand_factory),
76 accelerate_factory_(accelerate_factory),
77 preemptive_expand_factory_(preemptive_expand_factory),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000078 last_mode_(kModeNormal),
79 mute_factor_array_(NULL),
80 decoded_buffer_length_(kMaxFrameSize),
81 decoded_buffer_(new int16_t[decoded_buffer_length_]),
82 playout_timestamp_(0),
83 new_codec_(false),
84 timestamp_(0),
85 reset_decoder_(false),
86 current_rtp_payload_type_(0xFF), // Invalid RTP payload type.
87 current_cng_rtp_payload_type_(0xFF), // Invalid RTP payload type.
88 ssrc_(0),
89 first_packet_(true),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000090 error_code_(0),
91 decoder_error_code_(0),
minyue@webrtc.orgd7301772013-08-29 00:58:14 +000092 crit_sect_(CriticalSectionWrapper::CreateCriticalSection()),
93 decoded_packet_sequence_number_(-1),
94 decoded_packet_timestamp_(0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000095 if (fs != 8000 && fs != 16000 && fs != 32000 && fs != 48000) {
96 LOG(LS_ERROR) << "Sample rate " << fs << " Hz not supported. " <<
97 "Changing to 8000 Hz.";
98 fs = 8000;
99 }
100 LOG(LS_INFO) << "Create NetEqImpl object with fs = " << fs << ".";
101 fs_hz_ = fs;
102 fs_mult_ = fs / 8000;
103 output_size_samples_ = kOutputSizeMs * 8 * fs_mult_;
104 decoder_frame_length_ = 3 * output_size_samples_;
105 WebRtcSpl_Init();
106 decision_logic_.reset(DecisionLogic::Create(fs_hz_, output_size_samples_,
107 kPlayoutOn,
108 decoder_database_.get(),
109 *packet_buffer_.get(),
110 delay_manager_.get(),
111 buffer_level_filter_.get()));
112 SetSampleRateAndChannels(fs, 1); // Default is 1 channel.
113}
114
115NetEqImpl::~NetEqImpl() {
116 LOG(LS_INFO) << "Deleting NetEqImpl object.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000117}
118
119int NetEqImpl::InsertPacket(const WebRtcRTPHeader& rtp_header,
120 const uint8_t* payload,
121 int length_bytes,
122 uint32_t receive_timestamp) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000123 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000124 LOG(LS_VERBOSE) << "InsertPacket: ts=" << rtp_header.header.timestamp <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000125 ", sn=" << rtp_header.header.sequenceNumber <<
126 ", pt=" << static_cast<int>(rtp_header.header.payloadType) <<
127 ", ssrc=" << rtp_header.header.ssrc <<
128 ", len=" << length_bytes;
129 int error = InsertPacketInternal(rtp_header, payload, length_bytes,
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000130 receive_timestamp, false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000131 if (error != 0) {
132 LOG_FERR1(LS_WARNING, InsertPacketInternal, error);
133 error_code_ = error;
134 return kFail;
135 }
136 return kOK;
137}
138
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000139int NetEqImpl::InsertSyncPacket(const WebRtcRTPHeader& rtp_header,
140 uint32_t receive_timestamp) {
141 CriticalSectionScoped lock(crit_sect_.get());
142 LOG(LS_VERBOSE) << "InsertPacket-Sync: ts="
143 << rtp_header.header.timestamp <<
144 ", sn=" << rtp_header.header.sequenceNumber <<
145 ", pt=" << static_cast<int>(rtp_header.header.payloadType) <<
146 ", ssrc=" << rtp_header.header.ssrc;
147
148 const uint8_t kSyncPayload[] = { 's', 'y', 'n', 'c' };
149 int error = InsertPacketInternal(
150 rtp_header, kSyncPayload, sizeof(kSyncPayload), receive_timestamp, true);
151
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000152 if (error != 0) {
153 LOG_FERR1(LS_WARNING, InsertPacketInternal, error);
154 error_code_ = error;
155 return kFail;
156 }
157 return kOK;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000158}
159
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000160int NetEqImpl::GetAudio(size_t max_length, int16_t* output_audio,
161 int* samples_per_channel, int* num_channels,
162 NetEqOutputType* type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000163 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000164 LOG(LS_VERBOSE) << "GetAudio";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000165 int error = GetAudioInternal(max_length, output_audio, samples_per_channel,
166 num_channels);
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000167 LOG(LS_VERBOSE) << "Produced " << *samples_per_channel <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000168 " samples/channel for " << *num_channels << " channel(s)";
169 if (error != 0) {
170 LOG_FERR1(LS_WARNING, GetAudioInternal, error);
171 error_code_ = error;
172 return kFail;
173 }
174 if (type) {
175 *type = LastOutputType();
176 }
177 return kOK;
178}
179
180int NetEqImpl::RegisterPayloadType(enum NetEqDecoder codec,
181 uint8_t rtp_payload_type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000182 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000183 LOG_API2(static_cast<int>(rtp_payload_type), codec);
184 int ret = decoder_database_->RegisterPayload(rtp_payload_type, codec);
185 if (ret != DecoderDatabase::kOK) {
186 LOG_FERR2(LS_WARNING, RegisterPayload, rtp_payload_type, codec);
187 switch (ret) {
188 case DecoderDatabase::kInvalidRtpPayloadType:
189 error_code_ = kInvalidRtpPayloadType;
190 break;
191 case DecoderDatabase::kCodecNotSupported:
192 error_code_ = kCodecNotSupported;
193 break;
194 case DecoderDatabase::kDecoderExists:
195 error_code_ = kDecoderExists;
196 break;
197 default:
198 error_code_ = kOtherError;
199 }
200 return kFail;
201 }
202 return kOK;
203}
204
205int NetEqImpl::RegisterExternalDecoder(AudioDecoder* decoder,
206 enum NetEqDecoder codec,
207 int sample_rate_hz,
208 uint8_t rtp_payload_type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000209 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000210 LOG_API2(static_cast<int>(rtp_payload_type), codec);
211 if (!decoder) {
212 LOG(LS_ERROR) << "Cannot register external decoder with NULL pointer";
213 assert(false);
214 return kFail;
215 }
216 int ret = decoder_database_->InsertExternal(rtp_payload_type, codec,
217 sample_rate_hz, decoder);
218 if (ret != DecoderDatabase::kOK) {
219 LOG_FERR2(LS_WARNING, InsertExternal, rtp_payload_type, codec);
220 switch (ret) {
221 case DecoderDatabase::kInvalidRtpPayloadType:
222 error_code_ = kInvalidRtpPayloadType;
223 break;
224 case DecoderDatabase::kCodecNotSupported:
225 error_code_ = kCodecNotSupported;
226 break;
227 case DecoderDatabase::kDecoderExists:
228 error_code_ = kDecoderExists;
229 break;
230 case DecoderDatabase::kInvalidSampleRate:
231 error_code_ = kInvalidSampleRate;
232 break;
233 case DecoderDatabase::kInvalidPointer:
234 error_code_ = kInvalidPointer;
235 break;
236 default:
237 error_code_ = kOtherError;
238 }
239 return kFail;
240 }
241 return kOK;
242}
243
244int NetEqImpl::RemovePayloadType(uint8_t rtp_payload_type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000245 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000246 LOG_API1(static_cast<int>(rtp_payload_type));
247 int ret = decoder_database_->Remove(rtp_payload_type);
248 if (ret == DecoderDatabase::kOK) {
249 return kOK;
250 } else if (ret == DecoderDatabase::kDecoderNotFound) {
251 error_code_ = kDecoderNotFound;
252 } else {
253 error_code_ = kOtherError;
254 }
255 LOG_FERR1(LS_WARNING, Remove, rtp_payload_type);
256 return kFail;
257}
258
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000259bool NetEqImpl::SetMinimumDelay(int delay_ms) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000260 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000261 if (delay_ms >= 0 && delay_ms < 10000) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000262 assert(delay_manager_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000263 return delay_manager_->SetMinimumDelay(delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000264 }
265 return false;
266}
267
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000268bool NetEqImpl::SetMaximumDelay(int delay_ms) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000269 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000270 if (delay_ms >= 0 && delay_ms < 10000) {
271 assert(delay_manager_.get());
272 return delay_manager_->SetMaximumDelay(delay_ms);
273 }
274 return false;
275}
276
277int NetEqImpl::LeastRequiredDelayMs() const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000278 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000279 assert(delay_manager_.get());
280 return delay_manager_->least_required_delay_ms();
281}
282
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000283void NetEqImpl::SetPlayoutMode(NetEqPlayoutMode mode) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000284 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000285 if (!decision_logic_.get() || mode != decision_logic_->playout_mode()) {
286 // The reset() method calls delete for the old object.
287 decision_logic_.reset(DecisionLogic::Create(fs_hz_, output_size_samples_,
288 mode,
289 decoder_database_.get(),
290 *packet_buffer_.get(),
291 delay_manager_.get(),
292 buffer_level_filter_.get()));
293 }
294}
295
296NetEqPlayoutMode NetEqImpl::PlayoutMode() const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000297 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000298 assert(decision_logic_.get());
299 return decision_logic_->playout_mode();
300}
301
302int NetEqImpl::NetworkStatistics(NetEqNetworkStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000303 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000304 assert(decoder_database_.get());
305 const int total_samples_in_buffers = packet_buffer_->NumSamplesInBuffer(
306 decoder_database_.get(), decoder_frame_length_) +
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000307 static_cast<int>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000308 assert(delay_manager_.get());
309 assert(decision_logic_.get());
310 stats_.GetNetworkStatistics(fs_hz_, total_samples_in_buffers,
311 decoder_frame_length_, *delay_manager_.get(),
312 *decision_logic_.get(), stats);
313 return 0;
314}
315
316void NetEqImpl::WaitingTimes(std::vector<int>* waiting_times) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000317 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000318 stats_.WaitingTimes(waiting_times);
319}
320
321void NetEqImpl::GetRtcpStatistics(RtcpStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000322 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000323 if (stats) {
324 rtcp_.GetStatistics(false, stats);
325 }
326}
327
328void NetEqImpl::GetRtcpStatisticsNoReset(RtcpStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000329 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000330 if (stats) {
331 rtcp_.GetStatistics(true, stats);
332 }
333}
334
335void NetEqImpl::EnableVad() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000336 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000337 assert(vad_.get());
338 vad_->Enable();
339}
340
341void NetEqImpl::DisableVad() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000342 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000343 assert(vad_.get());
344 vad_->Disable();
345}
346
347uint32_t NetEqImpl::PlayoutTimestamp() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000348 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000349 return timestamp_scaler_->ToExternal(playout_timestamp_);
350}
351
352int NetEqImpl::LastError() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000353 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000354 return error_code_;
355}
356
357int NetEqImpl::LastDecoderError() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000358 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000359 return decoder_error_code_;
360}
361
362void NetEqImpl::FlushBuffers() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000363 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000364 LOG_API0();
365 packet_buffer_->Flush();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000366 assert(sync_buffer_.get());
367 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000368 sync_buffer_->Flush();
369 sync_buffer_->set_next_index(sync_buffer_->next_index() -
370 expand_->overlap_length());
371 // Set to wait for new codec.
372 first_packet_ = true;
373}
374
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000375void NetEqImpl::PacketBufferStatistics(int* current_num_packets,
376 int* max_num_packets,
377 int* current_memory_size_bytes,
378 int* max_memory_size_bytes) const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000379 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000380 packet_buffer_->BufferStat(current_num_packets, max_num_packets,
381 current_memory_size_bytes, max_memory_size_bytes);
382}
383
turaj@webrtc.orgff43c852013-09-25 00:07:27 +0000384int NetEqImpl::DecodedRtpInfo(int* sequence_number, uint32_t* timestamp) const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000385 CriticalSectionScoped lock(crit_sect_.get());
minyue@webrtc.orgd7301772013-08-29 00:58:14 +0000386 if (decoded_packet_sequence_number_ < 0)
387 return -1;
388 *sequence_number = decoded_packet_sequence_number_;
389 *timestamp = decoded_packet_timestamp_;
390 return 0;
391}
392
turaj@webrtc.orgff43c852013-09-25 00:07:27 +0000393void NetEqImpl::SetBackgroundNoiseMode(NetEqBackgroundNoiseMode mode) {
394 CriticalSectionScoped lock(crit_sect_.get());
395 assert(background_noise_.get());
396 background_noise_->set_mode(mode);
397}
turaj@webrtc.org036b7432013-09-11 18:45:02 +0000398
399NetEqBackgroundNoiseMode NetEqImpl::BackgroundNoiseMode() const {
turaj@webrtc.orgff43c852013-09-25 00:07:27 +0000400 CriticalSectionScoped lock(crit_sect_.get());
401 assert(background_noise_.get());
402 return background_noise_->mode();
turaj@webrtc.org036b7432013-09-11 18:45:02 +0000403}
404
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000405// Methods below this line are private.
406
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000407int NetEqImpl::InsertPacketInternal(const WebRtcRTPHeader& rtp_header,
408 const uint8_t* payload,
409 int length_bytes,
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000410 uint32_t receive_timestamp,
411 bool is_sync_packet) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000412 if (!payload) {
413 LOG_F(LS_ERROR) << "payload == NULL";
414 return kInvalidPointer;
415 }
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000416 // Sanity checks for sync-packets.
417 if (is_sync_packet) {
418 if (decoder_database_->IsDtmf(rtp_header.header.payloadType) ||
419 decoder_database_->IsRed(rtp_header.header.payloadType) ||
420 decoder_database_->IsComfortNoise(rtp_header.header.payloadType)) {
421 LOG_F(LS_ERROR) << "Sync-packet with an unacceptable payload type "
422 << rtp_header.header.payloadType;
423 return kSyncPacketNotAccepted;
424 }
425 if (first_packet_ ||
426 rtp_header.header.payloadType != current_rtp_payload_type_ ||
427 rtp_header.header.ssrc != ssrc_) {
428 // Even if |current_rtp_payload_type_| is 0xFF, sync-packet isn't
429 // accepted.
430 LOG_F(LS_ERROR) << "Changing codec, SSRC or first packet "
431 "with sync-packet.";
432 return kSyncPacketNotAccepted;
433 }
434 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000435 PacketList packet_list;
436 RTPHeader main_header;
437 {
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000438 // Convert to Packet.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000439 // Create |packet| within this separate scope, since it should not be used
440 // directly once it's been inserted in the packet list. This way, |packet|
441 // is not defined outside of this block.
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000442 Packet* packet = new Packet;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000443 packet->header.markerBit = false;
444 packet->header.payloadType = rtp_header.header.payloadType;
445 packet->header.sequenceNumber = rtp_header.header.sequenceNumber;
446 packet->header.timestamp = rtp_header.header.timestamp;
447 packet->header.ssrc = rtp_header.header.ssrc;
448 packet->header.numCSRCs = 0;
449 packet->payload_length = length_bytes;
450 packet->primary = true;
451 packet->waiting_time = 0;
452 packet->payload = new uint8_t[packet->payload_length];
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000453 packet->sync_packet = is_sync_packet;
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +0000454 if (!packet->payload) {
455 LOG_F(LS_ERROR) << "Payload pointer is NULL.";
456 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000457 assert(payload); // Already checked above.
458 memcpy(packet->payload, payload, packet->payload_length);
459 // Insert packet in a packet list.
460 packet_list.push_back(packet);
461 // Save main payloads header for later.
462 memcpy(&main_header, &packet->header, sizeof(main_header));
463 }
464
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000465 bool update_sample_rate_and_channels = false;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000466 // Reinitialize NetEq if it's needed (changed SSRC or first call).
467 if ((main_header.ssrc != ssrc_) || first_packet_) {
468 rtcp_.Init(main_header.sequenceNumber);
469 first_packet_ = false;
470
471 // Flush the packet buffer and DTMF buffer.
472 packet_buffer_->Flush();
473 dtmf_buffer_->Flush();
474
475 // Store new SSRC.
476 ssrc_ = main_header.ssrc;
477
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000478 // Update audio buffer timestamp.
479 sync_buffer_->IncreaseEndTimestamp(main_header.timestamp - timestamp_);
480
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000481 // Update codecs.
482 timestamp_ = main_header.timestamp;
483 current_rtp_payload_type_ = main_header.payloadType;
484
485 // Set MCU to update codec on next SignalMCU call.
486 new_codec_ = true;
487
488 // Reset timestamp scaling.
489 timestamp_scaler_->Reset();
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000490
491 // Triger an update of sampling rate and the number of channels.
492 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000493 }
494
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000495 // Update RTCP statistics, only for regular packets.
496 if (!is_sync_packet)
497 rtcp_.Update(main_header, receive_timestamp);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000498
499 // Check for RED payload type, and separate payloads into several packets.
500 if (decoder_database_->IsRed(main_header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000501 assert(!is_sync_packet); // We had a sanity check for this.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000502 if (payload_splitter_->SplitRed(&packet_list) != PayloadSplitter::kOK) {
503 LOG_FERR1(LS_WARNING, SplitRed, packet_list.size());
504 PacketBuffer::DeleteAllPackets(&packet_list);
505 return kRedundancySplitError;
506 }
507 // Only accept a few RED payloads of the same type as the main data,
508 // DTMF events and CNG.
509 payload_splitter_->CheckRedPayloads(&packet_list, *decoder_database_);
510 // Update the stored main payload header since the main payload has now
511 // changed.
512 memcpy(&main_header, &packet_list.front()->header, sizeof(main_header));
513 }
514
515 // Check payload types.
516 if (decoder_database_->CheckPayloadTypes(packet_list) ==
517 DecoderDatabase::kDecoderNotFound) {
518 LOG_FERR1(LS_WARNING, CheckPayloadTypes, packet_list.size());
519 PacketBuffer::DeleteAllPackets(&packet_list);
520 return kUnknownRtpPayloadType;
521 }
522
523 // Scale timestamp to internal domain (only for some codecs).
524 timestamp_scaler_->ToInternal(&packet_list);
525
526 // Process DTMF payloads. Cycle through the list of packets, and pick out any
527 // DTMF payloads found.
528 PacketList::iterator it = packet_list.begin();
529 while (it != packet_list.end()) {
530 Packet* current_packet = (*it);
531 assert(current_packet);
532 assert(current_packet->payload);
533 if (decoder_database_->IsDtmf(current_packet->header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000534 assert(!current_packet->sync_packet); // We had a sanity check for this.
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000535 DtmfEvent event;
536 int ret = DtmfBuffer::ParseEvent(
537 current_packet->header.timestamp,
538 current_packet->payload,
539 current_packet->payload_length,
540 &event);
541 if (ret != DtmfBuffer::kOK) {
542 LOG_FERR2(LS_WARNING, ParseEvent, ret,
543 current_packet->payload_length);
544 PacketBuffer::DeleteAllPackets(&packet_list);
545 return kDtmfParsingError;
546 }
547 if (dtmf_buffer_->InsertEvent(event) != DtmfBuffer::kOK) {
548 LOG_FERR0(LS_WARNING, InsertEvent);
549 PacketBuffer::DeleteAllPackets(&packet_list);
550 return kDtmfInsertError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000551 }
552 // TODO(hlundin): Let the destructor of Packet handle the payload.
553 delete [] current_packet->payload;
554 delete current_packet;
555 it = packet_list.erase(it);
556 } else {
557 ++it;
558 }
559 }
560
561 // Split payloads into smaller chunks. This also verifies that all payloads
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000562 // are of a known payload type. SplitAudio() method is protected against
563 // sync-packets.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000564 int ret = payload_splitter_->SplitAudio(&packet_list, *decoder_database_);
565 if (ret != PayloadSplitter::kOK) {
566 LOG_FERR1(LS_WARNING, SplitAudio, packet_list.size());
567 PacketBuffer::DeleteAllPackets(&packet_list);
568 switch (ret) {
569 case PayloadSplitter::kUnknownPayloadType:
570 return kUnknownRtpPayloadType;
571 case PayloadSplitter::kFrameSplitError:
572 return kFrameSplitError;
573 default:
574 return kOtherError;
575 }
576 }
577
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000578 // Update bandwidth estimate, if the packet is not sync-packet.
579 if (!packet_list.empty() && !packet_list.front()->sync_packet) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000580 // The list can be empty here if we got nothing but DTMF payloads.
581 AudioDecoder* decoder =
582 decoder_database_->GetDecoder(main_header.payloadType);
583 assert(decoder); // Should always get a valid object, since we have
584 // already checked that the payload types are known.
585 decoder->IncomingPacket(packet_list.front()->payload,
586 packet_list.front()->payload_length,
587 packet_list.front()->header.sequenceNumber,
588 packet_list.front()->header.timestamp,
589 receive_timestamp);
590 }
591
592 // Insert packets in buffer.
593 int temp_bufsize = packet_buffer_->NumPacketsInBuffer();
594 ret = packet_buffer_->InsertPacketList(
595 &packet_list,
596 *decoder_database_,
597 &current_rtp_payload_type_,
598 &current_cng_rtp_payload_type_);
599 if (ret == PacketBuffer::kFlushed) {
600 // Reset DSP timestamp etc. if packet buffer flushed.
601 new_codec_ = true;
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000602 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000603 LOG_F(LS_WARNING) << "Packet buffer flushed";
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000604 } else if (ret == PacketBuffer::kOversizePacket) {
605 LOG_F(LS_WARNING) << "Packet larger than packet buffer";
606 return kOversizePacket;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000607 } else if (ret != PacketBuffer::kOK) {
608 LOG_FERR1(LS_WARNING, InsertPacketList, packet_list.size());
609 PacketBuffer::DeleteAllPackets(&packet_list);
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000610 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000611 }
612 if (current_rtp_payload_type_ != 0xFF) {
613 const DecoderDatabase::DecoderInfo* dec_info =
614 decoder_database_->GetDecoderInfo(current_rtp_payload_type_);
615 if (!dec_info) {
616 assert(false); // Already checked that the payload type is known.
617 }
618 }
619
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000620 if (update_sample_rate_and_channels && !packet_buffer_->Empty()) {
621 // We do not use |current_rtp_payload_type_| to |set payload_type|, but
622 // get the next RTP header from |packet_buffer_| to obtain the payload type.
623 // The reason for it is the following corner case. If NetEq receives a
624 // CNG packet with a sample rate different than the current CNG then it
625 // flushes its buffer, assuming send codec must have been changed. However,
626 // payload type of the hypothetically new send codec is not known.
627 const RTPHeader* rtp_header = packet_buffer_->NextRtpHeader();
628 assert(rtp_header);
629 int payload_type = rtp_header->payloadType;
630 AudioDecoder* decoder = decoder_database_->GetDecoder(payload_type);
631 assert(decoder); // Payloads are already checked to be valid.
632 const DecoderDatabase::DecoderInfo* decoder_info =
633 decoder_database_->GetDecoderInfo(payload_type);
634 assert(decoder_info);
635 if (decoder_info->fs_hz != fs_hz_ ||
636 decoder->channels() != algorithm_buffer_->Channels())
637 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->channels());
638 }
639
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000640 // TODO(hlundin): Move this code to DelayManager class.
641 const DecoderDatabase::DecoderInfo* dec_info =
642 decoder_database_->GetDecoderInfo(main_header.payloadType);
643 assert(dec_info); // Already checked that the payload type is known.
644 delay_manager_->LastDecoderType(dec_info->codec_type);
645 if (delay_manager_->last_pack_cng_or_dtmf() == 0) {
646 // Calculate the total speech length carried in each packet.
647 temp_bufsize = packet_buffer_->NumPacketsInBuffer() - temp_bufsize;
648 temp_bufsize *= decoder_frame_length_;
649
650 if ((temp_bufsize > 0) &&
651 (temp_bufsize != decision_logic_->packet_length_samples())) {
652 decision_logic_->set_packet_length_samples(temp_bufsize);
653 delay_manager_->SetPacketAudioLength((1000 * temp_bufsize) / fs_hz_);
654 }
655
656 // Update statistics.
pbos@webrtc.org0946a562013-04-09 00:28:06 +0000657 if ((int32_t) (main_header.timestamp - timestamp_) >= 0 &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000658 !new_codec_) {
659 // Only update statistics if incoming packet is not older than last played
660 // out packet, and if new codec flag is not set.
661 delay_manager_->Update(main_header.sequenceNumber, main_header.timestamp,
662 fs_hz_);
663 }
664 } else if (delay_manager_->last_pack_cng_or_dtmf() == -1) {
665 // This is first "normal" packet after CNG or DTMF.
666 // Reset packet time counter and measure time until next packet,
667 // but don't update statistics.
668 delay_manager_->set_last_pack_cng_or_dtmf(0);
669 delay_manager_->ResetPacketIatCount();
670 }
671 return 0;
672}
673
674int NetEqImpl::GetAudioInternal(size_t max_length, int16_t* output,
675 int* samples_per_channel, int* num_channels) {
676 PacketList packet_list;
677 DtmfEvent dtmf_event;
678 Operations operation;
679 bool play_dtmf;
680 int return_value = GetDecision(&operation, &packet_list, &dtmf_event,
681 &play_dtmf);
682 if (return_value != 0) {
683 LOG_FERR1(LS_WARNING, GetDecision, return_value);
684 assert(false);
685 last_mode_ = kModeError;
686 return return_value;
687 }
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000688 LOG(LS_VERBOSE) << "GetDecision returned operation=" << operation <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000689 " and " << packet_list.size() << " packet(s)";
690
691 AudioDecoder::SpeechType speech_type;
692 int length = 0;
693 int decode_return_value = Decode(&packet_list, &operation,
694 &length, &speech_type);
695
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000696 assert(vad_.get());
697 bool sid_frame_available =
698 (operation == kRfc3389Cng && !packet_list.empty());
699 vad_->Update(decoded_buffer_.get(), length, speech_type,
700 sid_frame_available, fs_hz_);
701
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000702 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000703 switch (operation) {
704 case kNormal: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000705 DoNormal(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000706 break;
707 }
708 case kMerge: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000709 DoMerge(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000710 break;
711 }
712 case kExpand: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000713 return_value = DoExpand(play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000714 break;
715 }
716 case kAccelerate: {
717 return_value = DoAccelerate(decoded_buffer_.get(), length, speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000718 play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000719 break;
720 }
721 case kPreemptiveExpand: {
722 return_value = DoPreemptiveExpand(decoded_buffer_.get(), length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000723 speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000724 break;
725 }
726 case kRfc3389Cng:
727 case kRfc3389CngNoPacket: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000728 return_value = DoRfc3389Cng(&packet_list, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000729 break;
730 }
731 case kCodecInternalCng: {
732 // This handles the case when there is no transmission and the decoder
733 // should produce internal comfort noise.
734 // TODO(hlundin): Write test for codec-internal CNG.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000735 DoCodecInternalCng();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000736 break;
737 }
738 case kDtmf: {
739 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000740 return_value = DoDtmf(dtmf_event, &play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000741 break;
742 }
743 case kAlternativePlc: {
744 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000745 DoAlternativePlc(false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000746 break;
747 }
748 case kAlternativePlcIncreaseTimestamp: {
749 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000750 DoAlternativePlc(true);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000751 break;
752 }
753 case kAudioRepetitionIncreaseTimestamp: {
754 // TODO(hlundin): Write test for this.
755 sync_buffer_->IncreaseEndTimestamp(output_size_samples_);
756 // Skipping break on purpose. Execution should move on into the
757 // next case.
758 }
759 case kAudioRepetition: {
760 // TODO(hlundin): Write test for this.
761 // Copy last |output_size_samples_| from |sync_buffer_| to
762 // |algorithm_buffer|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000763 algorithm_buffer_->PushBackFromIndex(
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000764 *sync_buffer_, sync_buffer_->Size() - output_size_samples_);
765 expand_->Reset();
766 break;
767 }
768 case kUndefined: {
769 LOG_F(LS_ERROR) << "Invalid operation kUndefined.";
770 assert(false); // This should not happen.
771 last_mode_ = kModeError;
772 return kInvalidOperation;
773 }
774 } // End of switch.
775 if (return_value < 0) {
776 return return_value;
777 }
778
779 if (last_mode_ != kModeRfc3389Cng) {
780 comfort_noise_->Reset();
781 }
782
783 // Copy from |algorithm_buffer| to |sync_buffer_|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000784 sync_buffer_->PushBack(*algorithm_buffer_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000785
786 // Extract data from |sync_buffer_| to |output|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000787 size_t num_output_samples_per_channel = output_size_samples_;
788 size_t num_output_samples = output_size_samples_ * sync_buffer_->Channels();
789 if (num_output_samples > max_length) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000790 LOG(LS_WARNING) << "Output array is too short. " << max_length << " < " <<
791 output_size_samples_ << " * " << sync_buffer_->Channels();
792 num_output_samples = max_length;
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000793 num_output_samples_per_channel = static_cast<int>(
794 max_length / sync_buffer_->Channels());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000795 }
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000796 int samples_from_sync = static_cast<int>(
797 sync_buffer_->GetNextAudioInterleaved(num_output_samples_per_channel,
798 output));
799 *num_channels = static_cast<int>(sync_buffer_->Channels());
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000800 LOG(LS_VERBOSE) << "Sync buffer (" << *num_channels << " channel(s)):" <<
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000801 " insert " << algorithm_buffer_->Size() << " samples, extract " <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000802 samples_from_sync << " samples";
803 if (samples_from_sync != output_size_samples_) {
804 LOG_F(LS_ERROR) << "samples_from_sync != output_size_samples_";
minyue@webrtc.orgdb1cefc2013-08-13 01:39:21 +0000805 // TODO(minyue): treatment of under-run, filling zeros
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000806 memset(output, 0, num_output_samples * sizeof(int16_t));
807 *samples_per_channel = output_size_samples_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000808 return kSampleUnderrun;
809 }
810 *samples_per_channel = output_size_samples_;
811
812 // Should always have overlap samples left in the |sync_buffer_|.
813 assert(sync_buffer_->FutureLength() >= expand_->overlap_length());
814
815 if (play_dtmf) {
816 return_value = DtmfOverdub(dtmf_event, sync_buffer_->Channels(), output);
817 }
818
819 // Update the background noise parameters if last operation wrote data
820 // straight from the decoder to the |sync_buffer_|. That is, none of the
821 // operations that modify the signal can be followed by a parameter update.
822 if ((last_mode_ == kModeNormal) ||
823 (last_mode_ == kModeAccelerateFail) ||
824 (last_mode_ == kModePreemptiveExpandFail) ||
825 (last_mode_ == kModeRfc3389Cng) ||
826 (last_mode_ == kModeCodecInternalCng)) {
827 background_noise_->Update(*sync_buffer_, *vad_.get());
828 }
829
830 if (operation == kDtmf) {
831 // DTMF data was written the end of |sync_buffer_|.
832 // Update index to end of DTMF data in |sync_buffer_|.
833 sync_buffer_->set_dtmf_index(sync_buffer_->Size());
834 }
835
henrik.lundin@webrtc.orged865b52014-03-06 10:28:07 +0000836 if (last_mode_ != kModeExpand) {
837 // If last operation was not expand, calculate the |playout_timestamp_| from
838 // the |sync_buffer_|. However, do not update the |playout_timestamp_| if it
839 // would be moved "backwards".
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000840 uint32_t temp_timestamp = sync_buffer_->end_timestamp() -
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000841 static_cast<uint32_t>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000842 if (static_cast<int32_t>(temp_timestamp - playout_timestamp_) > 0) {
843 playout_timestamp_ = temp_timestamp;
844 }
845 } else {
846 // Use dead reckoning to estimate the |playout_timestamp_|.
847 playout_timestamp_ += output_size_samples_;
848 }
849
850 if (decode_return_value) return decode_return_value;
851 return return_value;
852}
853
854int NetEqImpl::GetDecision(Operations* operation,
855 PacketList* packet_list,
856 DtmfEvent* dtmf_event,
857 bool* play_dtmf) {
858 // Initialize output variables.
859 *play_dtmf = false;
860 *operation = kUndefined;
861
862 // Increment time counters.
863 packet_buffer_->IncrementWaitingTimes();
864 stats_.IncreaseCounter(output_size_samples_, fs_hz_);
865
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000866 assert(sync_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000867 uint32_t end_timestamp = sync_buffer_->end_timestamp();
868 if (!new_codec_) {
869 packet_buffer_->DiscardOldPackets(end_timestamp);
870 }
871 const RTPHeader* header = packet_buffer_->NextRtpHeader();
872
873 if (decision_logic_->CngRfc3389On()) {
874 // Because of timestamp peculiarities, we have to "manually" disallow using
875 // a CNG packet with the same timestamp as the one that was last played.
876 // This can happen when using redundancy and will cause the timing to shift.
877 while (header &&
878 decoder_database_->IsComfortNoise(header->payloadType) &&
879 end_timestamp >= header->timestamp) {
880 // Don't use this packet, discard it.
881 // TODO(hlundin): Write test for this case.
882 if (packet_buffer_->DiscardNextPacket() != PacketBuffer::kOK) {
883 assert(false); // Must be ok by design.
884 }
885 // Check buffer again.
886 if (!new_codec_) {
887 packet_buffer_->DiscardOldPackets(end_timestamp);
888 }
889 header = packet_buffer_->NextRtpHeader();
890 }
891 }
892
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000893 assert(expand_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000894 const int samples_left = static_cast<int>(sync_buffer_->FutureLength() -
895 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000896 if (last_mode_ == kModeAccelerateSuccess ||
897 last_mode_ == kModeAccelerateLowEnergy ||
898 last_mode_ == kModePreemptiveExpandSuccess ||
899 last_mode_ == kModePreemptiveExpandLowEnergy) {
900 // Subtract (samples_left + output_size_samples_) from sampleMemory.
901 decision_logic_->AddSampleMemory(-(samples_left + output_size_samples_));
902 }
903
904 // Check if it is time to play a DTMF event.
905 if (dtmf_buffer_->GetEvent(end_timestamp +
906 decision_logic_->generated_noise_samples(),
907 dtmf_event)) {
908 *play_dtmf = true;
909 }
910
911 // Get instruction.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000912 assert(sync_buffer_.get());
913 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000914 *operation = decision_logic_->GetDecision(*sync_buffer_,
915 *expand_,
916 decoder_frame_length_,
917 header,
918 last_mode_,
919 *play_dtmf,
920 &reset_decoder_);
921
922 // Check if we already have enough samples in the |sync_buffer_|. If so,
923 // change decision to normal, unless the decision was merge, accelerate, or
924 // preemptive expand.
925 if (samples_left >= output_size_samples_ &&
926 *operation != kMerge &&
927 *operation != kAccelerate &&
928 *operation != kPreemptiveExpand) {
929 *operation = kNormal;
930 return 0;
931 }
932
933 decision_logic_->ExpandDecision(*operation == kExpand);
934
935 // Check conditions for reset.
936 if (new_codec_ || *operation == kUndefined) {
937 // The only valid reason to get kUndefined is that new_codec_ is set.
938 assert(new_codec_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000939 if (*play_dtmf && !header) {
940 timestamp_ = dtmf_event->timestamp;
941 } else {
942 assert(header);
943 if (!header) {
944 LOG_F(LS_ERROR) << "Packet missing where it shouldn't.";
945 return -1;
946 }
947 timestamp_ = header->timestamp;
948 if (*operation == kRfc3389CngNoPacket
949#ifndef LEGACY_BITEXACT
950 // Without this check, it can happen that a non-CNG packet is sent to
951 // the CNG decoder as if it was a SID frame. This is clearly a bug,
952 // but is kept for now to maintain bit-exactness with the test
953 // vectors.
954 && decoder_database_->IsComfortNoise(header->payloadType)
955#endif
956 ) {
957 // Change decision to CNG packet, since we do have a CNG packet, but it
958 // was considered too early to use. Now, use it anyway.
959 *operation = kRfc3389Cng;
960 } else if (*operation != kRfc3389Cng) {
961 *operation = kNormal;
962 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000963 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000964 // Adjust |sync_buffer_| timestamp before setting |end_timestamp| to the
965 // new value.
966 sync_buffer_->IncreaseEndTimestamp(timestamp_ - end_timestamp);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000967 end_timestamp = timestamp_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000968 new_codec_ = false;
969 decision_logic_->SoftReset();
970 buffer_level_filter_->Reset();
971 delay_manager_->Reset();
972 stats_.ResetMcu();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000973 }
974
975 int required_samples = output_size_samples_;
976 const int samples_10_ms = 80 * fs_mult_;
977 const int samples_20_ms = 2 * samples_10_ms;
978 const int samples_30_ms = 3 * samples_10_ms;
979
980 switch (*operation) {
981 case kExpand: {
982 timestamp_ = end_timestamp;
983 return 0;
984 }
985 case kRfc3389CngNoPacket:
986 case kCodecInternalCng: {
987 return 0;
988 }
989 case kDtmf: {
990 // TODO(hlundin): Write test for this.
991 // Update timestamp.
992 timestamp_ = end_timestamp;
993 if (decision_logic_->generated_noise_samples() > 0 &&
994 last_mode_ != kModeDtmf) {
995 // Make a jump in timestamp due to the recently played comfort noise.
996 uint32_t timestamp_jump = decision_logic_->generated_noise_samples();
997 sync_buffer_->IncreaseEndTimestamp(timestamp_jump);
998 timestamp_ += timestamp_jump;
999 }
1000 decision_logic_->set_generated_noise_samples(0);
1001 return 0;
1002 }
1003 case kAccelerate: {
1004 // In order to do a accelerate we need at least 30 ms of audio data.
1005 if (samples_left >= samples_30_ms) {
1006 // Already have enough data, so we do not need to extract any more.
1007 decision_logic_->set_sample_memory(samples_left);
1008 decision_logic_->set_prev_time_scale(true);
1009 return 0;
1010 } else if (samples_left >= samples_10_ms &&
1011 decoder_frame_length_ >= samples_30_ms) {
1012 // Avoid decoding more data as it might overflow the playout buffer.
1013 *operation = kNormal;
1014 return 0;
1015 } else if (samples_left < samples_20_ms &&
1016 decoder_frame_length_ < samples_30_ms) {
1017 // Build up decoded data by decoding at least 20 ms of audio data. Do
1018 // not perform accelerate yet, but wait until we only need to do one
1019 // decoding.
1020 required_samples = 2 * output_size_samples_;
1021 *operation = kNormal;
1022 }
1023 // If none of the above is true, we have one of two possible situations:
1024 // (1) 20 ms <= samples_left < 30 ms and decoder_frame_length_ < 30 ms; or
1025 // (2) samples_left < 10 ms and decoder_frame_length_ >= 30 ms.
1026 // In either case, we move on with the accelerate decision, and decode one
1027 // frame now.
1028 break;
1029 }
1030 case kPreemptiveExpand: {
1031 // In order to do a preemptive expand we need at least 30 ms of decoded
1032 // audio data.
1033 if ((samples_left >= samples_30_ms) ||
1034 (samples_left >= samples_10_ms &&
1035 decoder_frame_length_ >= samples_30_ms)) {
1036 // Already have enough data, so we do not need to extract any more.
1037 // Or, avoid decoding more data as it might overflow the playout buffer.
1038 // Still try preemptive expand, though.
1039 decision_logic_->set_sample_memory(samples_left);
1040 decision_logic_->set_prev_time_scale(true);
1041 return 0;
1042 }
1043 if (samples_left < samples_20_ms &&
1044 decoder_frame_length_ < samples_30_ms) {
1045 // Build up decoded data by decoding at least 20 ms of audio data.
1046 // Still try to perform preemptive expand.
1047 required_samples = 2 * output_size_samples_;
1048 }
1049 // Move on with the preemptive expand decision.
1050 break;
1051 }
1052 default: {
1053 // Do nothing.
1054 }
1055 }
1056
1057 // Get packets from buffer.
1058 int extracted_samples = 0;
1059 if (header &&
1060 *operation != kAlternativePlc &&
1061 *operation != kAlternativePlcIncreaseTimestamp &&
1062 *operation != kAudioRepetition &&
1063 *operation != kAudioRepetitionIncreaseTimestamp) {
1064 sync_buffer_->IncreaseEndTimestamp(header->timestamp - end_timestamp);
1065 if (decision_logic_->CngOff()) {
1066 // Adjustment of timestamp only corresponds to an actual packet loss
1067 // if comfort noise is not played. If comfort noise was just played,
1068 // this adjustment of timestamp is only done to get back in sync with the
1069 // stream timestamp; no loss to report.
1070 stats_.LostSamples(header->timestamp - end_timestamp);
1071 }
1072
1073 if (*operation != kRfc3389Cng) {
1074 // We are about to decode and use a non-CNG packet.
1075 decision_logic_->SetCngOff();
1076 }
1077 // Reset CNG timestamp as a new packet will be delivered.
1078 // (Also if this is a CNG packet, since playedOutTS is updated.)
1079 decision_logic_->set_generated_noise_samples(0);
1080
1081 extracted_samples = ExtractPackets(required_samples, packet_list);
1082 if (extracted_samples < 0) {
1083 LOG_F(LS_WARNING) << "Failed to extract packets from buffer.";
1084 return kPacketBufferCorruption;
1085 }
1086 }
1087
1088 if (*operation == kAccelerate ||
1089 *operation == kPreemptiveExpand) {
1090 decision_logic_->set_sample_memory(samples_left + extracted_samples);
1091 decision_logic_->set_prev_time_scale(true);
1092 }
1093
1094 if (*operation == kAccelerate) {
1095 // Check that we have enough data (30ms) to do accelerate.
1096 if (extracted_samples + samples_left < samples_30_ms) {
1097 // TODO(hlundin): Write test for this.
1098 // Not enough, do normal operation instead.
1099 *operation = kNormal;
1100 }
1101 }
1102
1103 timestamp_ = end_timestamp;
1104 return 0;
1105}
1106
1107int NetEqImpl::Decode(PacketList* packet_list, Operations* operation,
1108 int* decoded_length,
1109 AudioDecoder::SpeechType* speech_type) {
1110 *speech_type = AudioDecoder::kSpeech;
1111 AudioDecoder* decoder = NULL;
1112 if (!packet_list->empty()) {
1113 const Packet* packet = packet_list->front();
1114 int payload_type = packet->header.payloadType;
1115 if (!decoder_database_->IsComfortNoise(payload_type)) {
1116 decoder = decoder_database_->GetDecoder(payload_type);
1117 assert(decoder);
1118 if (!decoder) {
1119 LOG_FERR1(LS_WARNING, GetDecoder, payload_type);
1120 PacketBuffer::DeleteAllPackets(packet_list);
1121 return kDecoderNotFound;
1122 }
1123 bool decoder_changed;
1124 decoder_database_->SetActiveDecoder(payload_type, &decoder_changed);
1125 if (decoder_changed) {
1126 // We have a new decoder. Re-init some values.
1127 const DecoderDatabase::DecoderInfo* decoder_info = decoder_database_
1128 ->GetDecoderInfo(payload_type);
1129 assert(decoder_info);
1130 if (!decoder_info) {
1131 LOG_FERR1(LS_WARNING, GetDecoderInfo, payload_type);
1132 PacketBuffer::DeleteAllPackets(packet_list);
1133 return kDecoderNotFound;
1134 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001135 // We should have correct sampling rate and number of channels. They
1136 // are set when packets are inserted.
1137 if (decoder_info->fs_hz != fs_hz_ ||
1138 decoder->channels() != algorithm_buffer_->Channels()) {
1139 LOG_F(LS_ERROR) << "Sampling rate or number of channels mismatch.";
1140 assert(false);
1141 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->channels());
1142 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001143 sync_buffer_->set_end_timestamp(timestamp_);
1144 playout_timestamp_ = timestamp_;
1145 }
1146 }
1147 }
1148
1149 if (reset_decoder_) {
1150 // TODO(hlundin): Write test for this.
1151 // Reset decoder.
1152 if (decoder) {
1153 decoder->Init();
1154 }
1155 // Reset comfort noise decoder.
1156 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
1157 if (cng_decoder) {
1158 cng_decoder->Init();
1159 }
1160 reset_decoder_ = false;
1161 }
1162
1163#ifdef LEGACY_BITEXACT
1164 // Due to a bug in old SignalMCU, it could happen that CNG operation was
1165 // decided, but a speech packet was provided. The speech packet will be used
1166 // to update the comfort noise decoder, as if it was a SID frame, which is
1167 // clearly wrong.
1168 if (*operation == kRfc3389Cng) {
1169 return 0;
1170 }
1171#endif
1172
1173 *decoded_length = 0;
1174 // Update codec-internal PLC state.
1175 if ((*operation == kMerge) && decoder && decoder->HasDecodePlc()) {
1176 decoder->DecodePlc(1, &decoded_buffer_[*decoded_length]);
1177 }
1178
1179 int return_value = DecodeLoop(packet_list, operation, decoder,
1180 decoded_length, speech_type);
1181
1182 if (*decoded_length < 0) {
1183 // Error returned from the decoder.
1184 *decoded_length = 0;
1185 sync_buffer_->IncreaseEndTimestamp(decoder_frame_length_);
1186 int error_code = 0;
1187 if (decoder)
1188 error_code = decoder->ErrorCode();
1189 if (error_code != 0) {
1190 // Got some error code from the decoder.
1191 decoder_error_code_ = error_code;
1192 return_value = kDecoderErrorCode;
1193 } else {
1194 // Decoder does not implement error codes. Return generic error.
1195 return_value = kOtherDecoderError;
1196 }
1197 LOG_FERR2(LS_WARNING, DecodeLoop, error_code, packet_list->size());
1198 *operation = kExpand; // Do expansion to get data instead.
1199 }
1200 if (*speech_type != AudioDecoder::kComfortNoise) {
1201 // Don't increment timestamp if codec returned CNG speech type
1202 // since in this case, the we will increment the CNGplayedTS counter.
1203 // Increase with number of samples per channel.
1204 assert(*decoded_length == 0 ||
1205 (decoder && decoder->channels() == sync_buffer_->Channels()));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001206 sync_buffer_->IncreaseEndTimestamp(
1207 *decoded_length / static_cast<int>(sync_buffer_->Channels()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001208 }
1209 return return_value;
1210}
1211
1212int NetEqImpl::DecodeLoop(PacketList* packet_list, Operations* operation,
1213 AudioDecoder* decoder, int* decoded_length,
1214 AudioDecoder::SpeechType* speech_type) {
1215 Packet* packet = NULL;
1216 if (!packet_list->empty()) {
1217 packet = packet_list->front();
1218 }
1219 // Do decoding.
1220 while (packet &&
1221 !decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1222 assert(decoder); // At this point, we must have a decoder object.
1223 // The number of channels in the |sync_buffer_| should be the same as the
1224 // number decoder channels.
1225 assert(sync_buffer_->Channels() == decoder->channels());
1226 assert(decoded_buffer_length_ >= kMaxFrameSize * decoder->channels());
1227 assert(*operation == kNormal || *operation == kAccelerate ||
1228 *operation == kMerge || *operation == kPreemptiveExpand);
1229 packet_list->pop_front();
henrik.lundin@webrtc.org63464a92013-01-30 09:41:56 +00001230 int payload_length = packet->payload_length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001231 int16_t decode_length;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +00001232 if (packet->sync_packet) {
1233 // Decode to silence with the same frame size as the last decode.
1234 LOG(LS_VERBOSE) << "Decoding sync-packet: " <<
1235 " ts=" << packet->header.timestamp <<
1236 ", sn=" << packet->header.sequenceNumber <<
1237 ", pt=" << static_cast<int>(packet->header.payloadType) <<
1238 ", ssrc=" << packet->header.ssrc <<
1239 ", len=" << packet->payload_length;
1240 memset(&decoded_buffer_[*decoded_length], 0, decoder_frame_length_ *
1241 decoder->channels() * sizeof(decoded_buffer_[0]));
1242 decode_length = decoder_frame_length_;
1243 } else if (!packet->primary) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001244 // This is a redundant payload; call the special decoder method.
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +00001245 LOG(LS_VERBOSE) << "Decoding packet (redundant):" <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001246 " ts=" << packet->header.timestamp <<
1247 ", sn=" << packet->header.sequenceNumber <<
1248 ", pt=" << static_cast<int>(packet->header.payloadType) <<
1249 ", ssrc=" << packet->header.ssrc <<
1250 ", len=" << packet->payload_length;
1251 decode_length = decoder->DecodeRedundant(
1252 packet->payload, packet->payload_length,
1253 &decoded_buffer_[*decoded_length], speech_type);
1254 } else {
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +00001255 LOG(LS_VERBOSE) << "Decoding packet: ts=" << packet->header.timestamp <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001256 ", sn=" << packet->header.sequenceNumber <<
1257 ", pt=" << static_cast<int>(packet->header.payloadType) <<
1258 ", ssrc=" << packet->header.ssrc <<
1259 ", len=" << packet->payload_length;
1260 decode_length = decoder->Decode(packet->payload,
1261 packet->payload_length,
1262 &decoded_buffer_[*decoded_length],
1263 speech_type);
1264 }
1265
1266 delete[] packet->payload;
1267 delete packet;
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001268 packet = NULL;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001269 if (decode_length > 0) {
1270 *decoded_length += decode_length;
1271 // Update |decoder_frame_length_| with number of samples per channel.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001272 decoder_frame_length_ = decode_length /
1273 static_cast<int>(decoder->channels());
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +00001274 LOG(LS_VERBOSE) << "Decoded " << decode_length << " samples (" <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001275 decoder->channels() << " channel(s) -> " << decoder_frame_length_ <<
1276 " samples per channel)";
1277 } else if (decode_length < 0) {
1278 // Error.
henrik.lundin@webrtc.org63464a92013-01-30 09:41:56 +00001279 LOG_FERR2(LS_WARNING, Decode, decode_length, payload_length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001280 *decoded_length = -1;
1281 PacketBuffer::DeleteAllPackets(packet_list);
1282 break;
1283 }
1284 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1285 // Guard against overflow.
1286 LOG_F(LS_WARNING) << "Decoded too much.";
1287 PacketBuffer::DeleteAllPackets(packet_list);
1288 return kDecodedTooMuch;
1289 }
1290 if (!packet_list->empty()) {
1291 packet = packet_list->front();
1292 } else {
1293 packet = NULL;
1294 }
1295 } // End of decode loop.
1296
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001297 // If the list is not empty at this point, either a decoding error terminated
1298 // the while-loop, or list must hold exactly one CNG packet.
1299 assert(packet_list->empty() || *decoded_length < 0 ||
1300 (packet_list->size() == 1 && packet &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001301 decoder_database_->IsComfortNoise(packet->header.payloadType)));
1302 return 0;
1303}
1304
1305void NetEqImpl::DoNormal(const int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001306 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001307 assert(normal_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001308 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001309 normal_->Process(decoded_buffer, decoded_length, last_mode_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001310 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001311 if (decoded_length != 0) {
1312 last_mode_ = kModeNormal;
1313 }
1314
1315 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1316 if ((speech_type == AudioDecoder::kComfortNoise)
1317 || ((last_mode_ == kModeCodecInternalCng)
1318 && (decoded_length == 0))) {
1319 // TODO(hlundin): Remove second part of || statement above.
1320 last_mode_ = kModeCodecInternalCng;
1321 }
1322
1323 if (!play_dtmf) {
1324 dtmf_tone_generator_->Reset();
1325 }
1326}
1327
1328void NetEqImpl::DoMerge(int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001329 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001330 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001331 assert(merge_.get());
1332 int new_length = merge_->Process(decoded_buffer, decoded_length,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001333 mute_factor_array_.get(),
1334 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001335
1336 // Update in-call and post-call statistics.
1337 if (expand_->MuteFactor(0) == 0) {
1338 // Expand generates only noise.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001339 stats_.ExpandedNoiseSamples(new_length - static_cast<int>(decoded_length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001340 } else {
1341 // Expansion generates more than only noise.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001342 stats_.ExpandedVoiceSamples(new_length - static_cast<int>(decoded_length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001343 }
1344
1345 last_mode_ = kModeMerge;
1346 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1347 if (speech_type == AudioDecoder::kComfortNoise) {
1348 last_mode_ = kModeCodecInternalCng;
1349 }
1350 expand_->Reset();
1351 if (!play_dtmf) {
1352 dtmf_tone_generator_->Reset();
1353 }
1354}
1355
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001356int NetEqImpl::DoExpand(bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001357 while ((sync_buffer_->FutureLength() - expand_->overlap_length()) <
1358 static_cast<size_t>(output_size_samples_)) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001359 algorithm_buffer_->Clear();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001360 int return_value = expand_->Process(algorithm_buffer_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001361 int length = static_cast<int>(algorithm_buffer_->Size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001362
1363 // Update in-call and post-call statistics.
1364 if (expand_->MuteFactor(0) == 0) {
1365 // Expand operation generates only noise.
1366 stats_.ExpandedNoiseSamples(length);
1367 } else {
1368 // Expand operation generates more than only noise.
1369 stats_.ExpandedVoiceSamples(length);
1370 }
1371
1372 last_mode_ = kModeExpand;
1373
1374 if (return_value < 0) {
1375 return return_value;
1376 }
1377
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001378 sync_buffer_->PushBack(*algorithm_buffer_);
1379 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001380 }
1381 if (!play_dtmf) {
1382 dtmf_tone_generator_->Reset();
1383 }
1384 return 0;
1385}
1386
1387int NetEqImpl::DoAccelerate(int16_t* decoded_buffer, size_t decoded_length,
1388 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001389 bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001390 const size_t required_samples = 240 * fs_mult_; // Must have 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001391 size_t borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001392 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001393 size_t decoded_length_per_channel = decoded_length / num_channels;
1394 if (decoded_length_per_channel < required_samples) {
1395 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001396 borrowed_samples_per_channel = static_cast<int>(required_samples -
1397 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001398 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1399 decoded_buffer,
1400 sizeof(int16_t) * decoded_length);
1401 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1402 decoded_buffer);
1403 decoded_length = required_samples * num_channels;
1404 }
1405
1406 int16_t samples_removed;
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001407 Accelerate::ReturnCodes return_code = accelerate_->Process(
1408 decoded_buffer, decoded_length, algorithm_buffer_.get(),
1409 &samples_removed);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001410 stats_.AcceleratedSamples(samples_removed);
1411 switch (return_code) {
1412 case Accelerate::kSuccess:
1413 last_mode_ = kModeAccelerateSuccess;
1414 break;
1415 case Accelerate::kSuccessLowEnergy:
1416 last_mode_ = kModeAccelerateLowEnergy;
1417 break;
1418 case Accelerate::kNoStretch:
1419 last_mode_ = kModeAccelerateFail;
1420 break;
1421 case Accelerate::kError:
1422 // TODO(hlundin): Map to kModeError instead?
1423 last_mode_ = kModeAccelerateFail;
1424 return kAccelerateError;
1425 }
1426
1427 if (borrowed_samples_per_channel > 0) {
1428 // Copy borrowed samples back to the |sync_buffer_|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001429 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001430 if (length < borrowed_samples_per_channel) {
1431 // This destroys the beginning of the buffer, but will not cause any
1432 // problems.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001433 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001434 sync_buffer_->Size() -
1435 borrowed_samples_per_channel);
1436 sync_buffer_->PushFrontZeros(borrowed_samples_per_channel - length);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001437 algorithm_buffer_->PopFront(length);
1438 assert(algorithm_buffer_->Empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001439 } else {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001440 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001441 borrowed_samples_per_channel,
1442 sync_buffer_->Size() -
1443 borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001444 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001445 }
1446 }
1447
1448 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1449 if (speech_type == AudioDecoder::kComfortNoise) {
1450 last_mode_ = kModeCodecInternalCng;
1451 }
1452 if (!play_dtmf) {
1453 dtmf_tone_generator_->Reset();
1454 }
1455 expand_->Reset();
1456 return 0;
1457}
1458
1459int NetEqImpl::DoPreemptiveExpand(int16_t* decoded_buffer,
1460 size_t decoded_length,
1461 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001462 bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001463 const size_t required_samples = 240 * fs_mult_; // Must have 30 ms.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001464 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001465 int borrowed_samples_per_channel = 0;
1466 int old_borrowed_samples_per_channel = 0;
1467 size_t decoded_length_per_channel = decoded_length / num_channels;
1468 if (decoded_length_per_channel < required_samples) {
1469 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001470 borrowed_samples_per_channel = static_cast<int>(required_samples -
1471 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001472 // Calculate how many of these were already played out.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001473 old_borrowed_samples_per_channel = static_cast<int>(
1474 borrowed_samples_per_channel - sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001475 old_borrowed_samples_per_channel = std::max(
1476 0, old_borrowed_samples_per_channel);
1477 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1478 decoded_buffer,
1479 sizeof(int16_t) * decoded_length);
1480 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1481 decoded_buffer);
1482 decoded_length = required_samples * num_channels;
1483 }
1484
1485 int16_t samples_added;
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001486 PreemptiveExpand::ReturnCodes return_code = preemptive_expand_->Process(
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001487 decoded_buffer, static_cast<int>(decoded_length),
1488 old_borrowed_samples_per_channel,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001489 algorithm_buffer_.get(), &samples_added);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001490 stats_.PreemptiveExpandedSamples(samples_added);
1491 switch (return_code) {
1492 case PreemptiveExpand::kSuccess:
1493 last_mode_ = kModePreemptiveExpandSuccess;
1494 break;
1495 case PreemptiveExpand::kSuccessLowEnergy:
1496 last_mode_ = kModePreemptiveExpandLowEnergy;
1497 break;
1498 case PreemptiveExpand::kNoStretch:
1499 last_mode_ = kModePreemptiveExpandFail;
1500 break;
1501 case PreemptiveExpand::kError:
1502 // TODO(hlundin): Map to kModeError instead?
1503 last_mode_ = kModePreemptiveExpandFail;
1504 return kPreemptiveExpandError;
1505 }
1506
1507 if (borrowed_samples_per_channel > 0) {
1508 // Copy borrowed samples back to the |sync_buffer_|.
1509 sync_buffer_->ReplaceAtIndex(
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001510 *algorithm_buffer_, borrowed_samples_per_channel,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001511 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001512 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001513 }
1514
1515 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1516 if (speech_type == AudioDecoder::kComfortNoise) {
1517 last_mode_ = kModeCodecInternalCng;
1518 }
1519 if (!play_dtmf) {
1520 dtmf_tone_generator_->Reset();
1521 }
1522 expand_->Reset();
1523 return 0;
1524}
1525
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001526int NetEqImpl::DoRfc3389Cng(PacketList* packet_list, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001527 if (!packet_list->empty()) {
1528 // Must have exactly one SID frame at this point.
1529 assert(packet_list->size() == 1);
1530 Packet* packet = packet_list->front();
1531 packet_list->pop_front();
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001532 if (!decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1533#ifdef LEGACY_BITEXACT
1534 // This can happen due to a bug in GetDecision. Change the payload type
1535 // to a CNG type, and move on. Note that this means that we are in fact
1536 // sending a non-CNG payload to the comfort noise decoder for decoding.
1537 // Clearly wrong, but will maintain bit-exactness with legacy.
1538 if (fs_hz_ == 8000) {
1539 packet->header.payloadType =
1540 decoder_database_->GetRtpPayloadType(kDecoderCNGnb);
1541 } else if (fs_hz_ == 16000) {
1542 packet->header.payloadType =
1543 decoder_database_->GetRtpPayloadType(kDecoderCNGwb);
1544 } else if (fs_hz_ == 32000) {
1545 packet->header.payloadType =
1546 decoder_database_->GetRtpPayloadType(kDecoderCNGswb32kHz);
1547 } else if (fs_hz_ == 48000) {
1548 packet->header.payloadType =
1549 decoder_database_->GetRtpPayloadType(kDecoderCNGswb48kHz);
1550 }
1551 assert(decoder_database_->IsComfortNoise(packet->header.payloadType));
1552#else
1553 LOG(LS_ERROR) << "Trying to decode non-CNG payload as CNG.";
1554 return kOtherError;
1555#endif
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001556 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001557 // UpdateParameters() deletes |packet|.
1558 if (comfort_noise_->UpdateParameters(packet) ==
1559 ComfortNoise::kInternalError) {
1560 LOG_FERR0(LS_WARNING, UpdateParameters);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001561 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001562 return -comfort_noise_->internal_error_code();
1563 }
1564 }
1565 int cn_return = comfort_noise_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001566 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001567 expand_->Reset();
1568 last_mode_ = kModeRfc3389Cng;
1569 if (!play_dtmf) {
1570 dtmf_tone_generator_->Reset();
1571 }
1572 if (cn_return == ComfortNoise::kInternalError) {
1573 LOG_FERR1(LS_WARNING, comfort_noise_->Generate, cn_return);
1574 decoder_error_code_ = comfort_noise_->internal_error_code();
1575 return kComfortNoiseErrorCode;
1576 } else if (cn_return == ComfortNoise::kUnknownPayloadType) {
1577 LOG_FERR1(LS_WARNING, comfort_noise_->Generate, cn_return);
1578 return kUnknownRtpPayloadType;
1579 }
1580 return 0;
1581}
1582
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001583void NetEqImpl::DoCodecInternalCng() {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001584 int length = 0;
1585 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1586 int16_t decoded_buffer[kMaxFrameSize];
1587 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1588 if (decoder) {
1589 const uint8_t* dummy_payload = NULL;
1590 AudioDecoder::SpeechType speech_type;
1591 length = decoder->Decode(dummy_payload, 0, decoded_buffer, &speech_type);
1592 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001593 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001594 normal_->Process(decoded_buffer, length, last_mode_, mute_factor_array_.get(),
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001595 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001596 last_mode_ = kModeCodecInternalCng;
1597 expand_->Reset();
1598}
1599
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001600int NetEqImpl::DoDtmf(const DtmfEvent& dtmf_event, bool* play_dtmf) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001601 // This block of the code and the block further down, handling |dtmf_switch|
1602 // are commented out. Otherwise playing out-of-band DTMF would fail in VoE
1603 // test, DtmfTest.ManualSuccessfullySendsOutOfBandTelephoneEvents. This is
1604 // equivalent to |dtmf_switch| always be false.
1605 //
1606 // See http://webrtc-codereview.appspot.com/1195004/ for discussion
1607 // On this issue. This change might cause some glitches at the point of
1608 // switch from audio to DTMF. Issue 1545 is filed to track this.
1609 //
1610 // bool dtmf_switch = false;
1611 // if ((last_mode_ != kModeDtmf) && dtmf_tone_generator_->initialized()) {
1612 // // Special case; see below.
1613 // // We must catch this before calling Generate, since |initialized| is
1614 // // modified in that call.
1615 // dtmf_switch = true;
1616 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001617
1618 int dtmf_return_value = 0;
1619 if (!dtmf_tone_generator_->initialized()) {
1620 // Initialize if not already done.
1621 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1622 dtmf_event.volume);
1623 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001624
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001625 if (dtmf_return_value == 0) {
1626 // Generate DTMF signal.
1627 dtmf_return_value = dtmf_tone_generator_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001628 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001629 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001630
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001631 if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001632 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001633 return dtmf_return_value;
1634 }
1635
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001636 // if (dtmf_switch) {
1637 // // This is the special case where the previous operation was DTMF
1638 // // overdub, but the current instruction is "regular" DTMF. We must make
1639 // // sure that the DTMF does not have any discontinuities. The first DTMF
1640 // // sample that we generate now must be played out immediately, therefore
1641 // // it must be copied to the speech buffer.
1642 // // TODO(hlundin): This code seems incorrect. (Legacy.) Write test and
1643 // // verify correct operation.
1644 // assert(false);
1645 // // Must generate enough data to replace all of the |sync_buffer_|
1646 // // "future".
1647 // int required_length = sync_buffer_->FutureLength();
1648 // assert(dtmf_tone_generator_->initialized());
1649 // dtmf_return_value = dtmf_tone_generator_->Generate(required_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001650 // algorithm_buffer_);
1651 // assert((size_t) required_length == algorithm_buffer_->Size());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001652 // if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001653 // algorithm_buffer_->Zeros(output_size_samples_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001654 // return dtmf_return_value;
1655 // }
1656 //
1657 // // Overwrite the "future" part of the speech buffer with the new DTMF
1658 // // data.
1659 // // TODO(hlundin): It seems that this overwriting has gone lost.
1660 // // Not adapted for multi-channel yet.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001661 // assert(algorithm_buffer_->Channels() == 1);
1662 // if (algorithm_buffer_->Channels() != 1) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001663 // LOG(LS_WARNING) << "DTMF not supported for more than one channel";
1664 // return kStereoNotSupported;
1665 // }
1666 // // Shuffle the remaining data to the beginning of algorithm buffer.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001667 // algorithm_buffer_->PopFront(sync_buffer_->FutureLength());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001668 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001669
1670 sync_buffer_->IncreaseEndTimestamp(output_size_samples_);
1671 expand_->Reset();
1672 last_mode_ = kModeDtmf;
1673
1674 // Set to false because the DTMF is already in the algorithm buffer.
1675 *play_dtmf = false;
1676 return 0;
1677}
1678
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001679void NetEqImpl::DoAlternativePlc(bool increase_timestamp) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001680 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1681 int length;
1682 if (decoder && decoder->HasDecodePlc()) {
1683 // Use the decoder's packet-loss concealment.
1684 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1685 int16_t decoded_buffer[kMaxFrameSize];
1686 length = decoder->DecodePlc(1, decoded_buffer);
1687 if (length > 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001688 algorithm_buffer_->PushBackInterleaved(decoded_buffer, length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001689 } else {
1690 length = 0;
1691 }
1692 } else {
1693 // Do simple zero-stuffing.
1694 length = output_size_samples_;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001695 algorithm_buffer_->Zeros(length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001696 // By not advancing the timestamp, NetEq inserts samples.
1697 stats_.AddZeros(length);
1698 }
1699 if (increase_timestamp) {
1700 sync_buffer_->IncreaseEndTimestamp(length);
1701 }
1702 expand_->Reset();
1703}
1704
1705int NetEqImpl::DtmfOverdub(const DtmfEvent& dtmf_event, size_t num_channels,
1706 int16_t* output) const {
1707 size_t out_index = 0;
1708 int overdub_length = output_size_samples_; // Default value.
1709
1710 if (sync_buffer_->dtmf_index() > sync_buffer_->next_index()) {
1711 // Special operation for transition from "DTMF only" to "DTMF overdub".
1712 out_index = std::min(
1713 sync_buffer_->dtmf_index() - sync_buffer_->next_index(),
1714 static_cast<size_t>(output_size_samples_));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001715 overdub_length = output_size_samples_ - static_cast<int>(out_index);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001716 }
1717
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001718 AudioMultiVector dtmf_output(num_channels);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001719 int dtmf_return_value = 0;
1720 if (!dtmf_tone_generator_->initialized()) {
1721 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1722 dtmf_event.volume);
1723 }
1724 if (dtmf_return_value == 0) {
1725 dtmf_return_value = dtmf_tone_generator_->Generate(overdub_length,
1726 &dtmf_output);
1727 assert((size_t) overdub_length == dtmf_output.Size());
1728 }
1729 dtmf_output.ReadInterleaved(overdub_length, &output[out_index]);
1730 return dtmf_return_value < 0 ? dtmf_return_value : 0;
1731}
1732
1733int NetEqImpl::ExtractPackets(int required_samples, PacketList* packet_list) {
1734 bool first_packet = true;
1735 uint8_t prev_payload_type = 0;
1736 uint32_t prev_timestamp = 0;
1737 uint16_t prev_sequence_number = 0;
1738 bool next_packet_available = false;
1739
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001740 const RTPHeader* header = packet_buffer_->NextRtpHeader();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001741 assert(header);
1742 if (!header) {
1743 return -1;
1744 }
turaj@webrtc.org7df97062013-08-02 18:07:13 +00001745 uint32_t first_timestamp = header->timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001746 int extracted_samples = 0;
1747
1748 // Packet extraction loop.
1749 do {
1750 timestamp_ = header->timestamp;
1751 int discard_count = 0;
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001752 Packet* packet = packet_buffer_->GetNextPacket(&discard_count);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001753 // |header| may be invalid after the |packet_buffer_| operation.
1754 header = NULL;
1755 if (!packet) {
1756 LOG_FERR1(LS_ERROR, GetNextPacket, discard_count) <<
1757 "Should always be able to extract a packet here";
1758 assert(false); // Should always be able to extract a packet here.
1759 return -1;
1760 }
1761 stats_.PacketsDiscarded(discard_count);
1762 // Store waiting time in ms; packets->waiting_time is in "output blocks".
1763 stats_.StoreWaitingTime(packet->waiting_time * kOutputSizeMs);
1764 assert(packet->payload_length > 0);
1765 packet_list->push_back(packet); // Store packet in list.
1766
1767 if (first_packet) {
1768 first_packet = false;
minyue@webrtc.orgd7301772013-08-29 00:58:14 +00001769 decoded_packet_sequence_number_ = prev_sequence_number =
1770 packet->header.sequenceNumber;
1771 decoded_packet_timestamp_ = prev_timestamp = packet->header.timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001772 prev_payload_type = packet->header.payloadType;
1773 }
1774
1775 // Store number of extracted samples.
1776 int packet_duration = 0;
1777 AudioDecoder* decoder = decoder_database_->GetDecoder(
1778 packet->header.payloadType);
1779 if (decoder) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +00001780 packet_duration = packet->sync_packet ? decoder_frame_length_ :
1781 decoder->PacketDuration(packet->payload, packet->payload_length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001782 } else {
1783 LOG_FERR1(LS_WARNING, GetDecoder, packet->header.payloadType) <<
1784 "Could not find a decoder for a packet about to be extracted.";
1785 assert(false);
1786 }
1787 if (packet_duration <= 0) {
1788 // Decoder did not return a packet duration. Assume that the packet
1789 // contains the same number of samples as the previous one.
1790 packet_duration = decoder_frame_length_;
1791 }
1792 extracted_samples = packet->header.timestamp - first_timestamp +
1793 packet_duration;
1794
1795 // Check what packet is available next.
1796 header = packet_buffer_->NextRtpHeader();
1797 next_packet_available = false;
1798 if (header && prev_payload_type == header->payloadType) {
1799 int16_t seq_no_diff = header->sequenceNumber - prev_sequence_number;
1800 int32_t ts_diff = header->timestamp - prev_timestamp;
1801 if (seq_no_diff == 1 ||
1802 (seq_no_diff == 0 && ts_diff == decoder_frame_length_)) {
1803 // The next sequence number is available, or the next part of a packet
1804 // that was split into pieces upon insertion.
1805 next_packet_available = true;
1806 }
1807 prev_sequence_number = header->sequenceNumber;
1808 }
1809 } while (extracted_samples < required_samples && next_packet_available);
1810
1811 return extracted_samples;
1812}
1813
1814void NetEqImpl::SetSampleRateAndChannels(int fs_hz, size_t channels) {
1815 LOG_API2(fs_hz, channels);
1816 // TODO(hlundin): Change to an enumerator and skip assert.
1817 assert(fs_hz == 8000 || fs_hz == 16000 || fs_hz == 32000 || fs_hz == 48000);
1818 assert(channels > 0);
1819
1820 fs_hz_ = fs_hz;
1821 fs_mult_ = fs_hz / 8000;
1822 output_size_samples_ = kOutputSizeMs * 8 * fs_mult_;
1823 decoder_frame_length_ = 3 * output_size_samples_; // Initialize to 30ms.
1824
1825 last_mode_ = kModeNormal;
1826
1827 // Create a new array of mute factors and set all to 1.
1828 mute_factor_array_.reset(new int16_t[channels]);
1829 for (size_t i = 0; i < channels; ++i) {
1830 mute_factor_array_[i] = 16384; // 1.0 in Q14.
1831 }
1832
1833 // Reset comfort noise decoder, if there is one active.
1834 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
1835 if (cng_decoder) {
1836 cng_decoder->Init();
1837 }
1838
1839 // Reinit post-decode VAD with new sample rate.
1840 assert(vad_.get()); // Cannot be NULL here.
1841 vad_->Init();
1842
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001843 // Delete algorithm buffer and create a new one.
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001844 algorithm_buffer_.reset(new AudioMultiVector(channels));
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001845
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001846 // Delete sync buffer and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001847 sync_buffer_.reset(new SyncBuffer(channels, kSyncBufferSize * fs_mult_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001848
turaj@webrtc.orgff43c852013-09-25 00:07:27 +00001849
1850 // Delete BackgroundNoise object and create a new one, while preserving its
1851 // mode.
1852 NetEqBackgroundNoiseMode current_mode = kBgnOn;
1853 if (background_noise_.get())
1854 current_mode = background_noise_->mode();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001855 background_noise_.reset(new BackgroundNoise(channels));
turaj@webrtc.orgff43c852013-09-25 00:07:27 +00001856 background_noise_->set_mode(current_mode);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001857
1858 // Reset random vector.
1859 random_vector_.Reset();
1860
1861 // Delete Expand object and create a new one.
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +00001862 expand_.reset(expand_factory_->Create(background_noise_.get(),
1863 sync_buffer_.get(), &random_vector_,
1864 fs_hz, channels));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001865 // Move index so that we create a small set of future samples (all 0).
1866 sync_buffer_->set_next_index(sync_buffer_->next_index() -
1867 expand_->overlap_length());
1868
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001869 normal_.reset(new Normal(fs_hz, decoder_database_.get(), *background_noise_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001870 expand_.get()));
1871 merge_.reset(new Merge(fs_hz, channels, expand_.get(), sync_buffer_.get()));
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +00001872 accelerate_.reset(
1873 accelerate_factory_->Create(fs_hz, channels, *background_noise_));
1874 preemptive_expand_.reset(
1875 preemptive_expand_factory_->Create(fs_hz, channels, *background_noise_));
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001876
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001877 // Delete ComfortNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001878 comfort_noise_.reset(new ComfortNoise(fs_hz, decoder_database_.get(),
1879 sync_buffer_.get()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001880
1881 // Verify that |decoded_buffer_| is long enough.
1882 if (decoded_buffer_length_ < kMaxFrameSize * channels) {
1883 // Reallocate to larger size.
1884 decoded_buffer_length_ = kMaxFrameSize * channels;
1885 decoded_buffer_.reset(new int16_t[decoded_buffer_length_]);
1886 }
1887
1888 // Communicate new sample rate and output size to DecisionLogic object.
1889 assert(decision_logic_.get());
1890 decision_logic_->SetSampleRate(fs_hz_, output_size_samples_);
1891}
1892
1893NetEqOutputType NetEqImpl::LastOutputType() {
1894 assert(vad_.get());
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001895 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001896 if (last_mode_ == kModeCodecInternalCng || last_mode_ == kModeRfc3389Cng) {
1897 return kOutputCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001898 } else if (last_mode_ == kModeExpand && expand_->MuteFactor(0) == 0) {
1899 // Expand mode has faded down to background noise only (very long expand).
1900 return kOutputPLCtoCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001901 } else if (last_mode_ == kModeExpand) {
1902 return kOutputPLC;
wu@webrtc.org24301a62013-12-13 19:17:43 +00001903 } else if (vad_->running() && !vad_->active_speech()) {
1904 return kOutputVADPassive;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001905 } else {
1906 return kOutputNormal;
1907 }
1908}
1909
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001910} // namespace webrtc