blob: 8ab6205ec0ddc0c8081a21e7e7fea91e1cf892de [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 }
andrew@webrtc.org0569d932014-04-09 17:48:48 +0000100 LOG(LS_VERBOSE) << "Create NetEqImpl object with fs = " << fs << ".";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000101 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.orgb287d962014-04-07 21:21:45 +0000405const SyncBuffer* NetEqImpl::sync_buffer_for_test() const {
406 CriticalSectionScoped lock(crit_sect_.get());
407 return sync_buffer_.get();
408}
409
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000410// Methods below this line are private.
411
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000412int NetEqImpl::InsertPacketInternal(const WebRtcRTPHeader& rtp_header,
413 const uint8_t* payload,
414 int length_bytes,
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000415 uint32_t receive_timestamp,
416 bool is_sync_packet) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000417 if (!payload) {
418 LOG_F(LS_ERROR) << "payload == NULL";
419 return kInvalidPointer;
420 }
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000421 // Sanity checks for sync-packets.
422 if (is_sync_packet) {
423 if (decoder_database_->IsDtmf(rtp_header.header.payloadType) ||
424 decoder_database_->IsRed(rtp_header.header.payloadType) ||
425 decoder_database_->IsComfortNoise(rtp_header.header.payloadType)) {
426 LOG_F(LS_ERROR) << "Sync-packet with an unacceptable payload type "
427 << rtp_header.header.payloadType;
428 return kSyncPacketNotAccepted;
429 }
430 if (first_packet_ ||
431 rtp_header.header.payloadType != current_rtp_payload_type_ ||
432 rtp_header.header.ssrc != ssrc_) {
433 // Even if |current_rtp_payload_type_| is 0xFF, sync-packet isn't
434 // accepted.
435 LOG_F(LS_ERROR) << "Changing codec, SSRC or first packet "
436 "with sync-packet.";
437 return kSyncPacketNotAccepted;
438 }
439 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000440 PacketList packet_list;
441 RTPHeader main_header;
442 {
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000443 // Convert to Packet.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000444 // Create |packet| within this separate scope, since it should not be used
445 // directly once it's been inserted in the packet list. This way, |packet|
446 // is not defined outside of this block.
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000447 Packet* packet = new Packet;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000448 packet->header.markerBit = false;
449 packet->header.payloadType = rtp_header.header.payloadType;
450 packet->header.sequenceNumber = rtp_header.header.sequenceNumber;
451 packet->header.timestamp = rtp_header.header.timestamp;
452 packet->header.ssrc = rtp_header.header.ssrc;
453 packet->header.numCSRCs = 0;
454 packet->payload_length = length_bytes;
455 packet->primary = true;
456 packet->waiting_time = 0;
457 packet->payload = new uint8_t[packet->payload_length];
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000458 packet->sync_packet = is_sync_packet;
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +0000459 if (!packet->payload) {
460 LOG_F(LS_ERROR) << "Payload pointer is NULL.";
461 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000462 assert(payload); // Already checked above.
463 memcpy(packet->payload, payload, packet->payload_length);
464 // Insert packet in a packet list.
465 packet_list.push_back(packet);
466 // Save main payloads header for later.
467 memcpy(&main_header, &packet->header, sizeof(main_header));
468 }
469
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000470 bool update_sample_rate_and_channels = false;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000471 // Reinitialize NetEq if it's needed (changed SSRC or first call).
472 if ((main_header.ssrc != ssrc_) || first_packet_) {
473 rtcp_.Init(main_header.sequenceNumber);
474 first_packet_ = false;
475
476 // Flush the packet buffer and DTMF buffer.
477 packet_buffer_->Flush();
478 dtmf_buffer_->Flush();
479
480 // Store new SSRC.
481 ssrc_ = main_header.ssrc;
482
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000483 // Update audio buffer timestamp.
484 sync_buffer_->IncreaseEndTimestamp(main_header.timestamp - timestamp_);
485
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000486 // Update codecs.
487 timestamp_ = main_header.timestamp;
488 current_rtp_payload_type_ = main_header.payloadType;
489
490 // Set MCU to update codec on next SignalMCU call.
491 new_codec_ = true;
492
493 // Reset timestamp scaling.
494 timestamp_scaler_->Reset();
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000495
496 // Triger an update of sampling rate and the number of channels.
497 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000498 }
499
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000500 // Update RTCP statistics, only for regular packets.
501 if (!is_sync_packet)
502 rtcp_.Update(main_header, receive_timestamp);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000503
504 // Check for RED payload type, and separate payloads into several packets.
505 if (decoder_database_->IsRed(main_header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000506 assert(!is_sync_packet); // We had a sanity check for this.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000507 if (payload_splitter_->SplitRed(&packet_list) != PayloadSplitter::kOK) {
508 LOG_FERR1(LS_WARNING, SplitRed, packet_list.size());
509 PacketBuffer::DeleteAllPackets(&packet_list);
510 return kRedundancySplitError;
511 }
512 // Only accept a few RED payloads of the same type as the main data,
513 // DTMF events and CNG.
514 payload_splitter_->CheckRedPayloads(&packet_list, *decoder_database_);
515 // Update the stored main payload header since the main payload has now
516 // changed.
517 memcpy(&main_header, &packet_list.front()->header, sizeof(main_header));
518 }
519
520 // Check payload types.
521 if (decoder_database_->CheckPayloadTypes(packet_list) ==
522 DecoderDatabase::kDecoderNotFound) {
523 LOG_FERR1(LS_WARNING, CheckPayloadTypes, packet_list.size());
524 PacketBuffer::DeleteAllPackets(&packet_list);
525 return kUnknownRtpPayloadType;
526 }
527
528 // Scale timestamp to internal domain (only for some codecs).
529 timestamp_scaler_->ToInternal(&packet_list);
530
531 // Process DTMF payloads. Cycle through the list of packets, and pick out any
532 // DTMF payloads found.
533 PacketList::iterator it = packet_list.begin();
534 while (it != packet_list.end()) {
535 Packet* current_packet = (*it);
536 assert(current_packet);
537 assert(current_packet->payload);
538 if (decoder_database_->IsDtmf(current_packet->header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000539 assert(!current_packet->sync_packet); // We had a sanity check for this.
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000540 DtmfEvent event;
541 int ret = DtmfBuffer::ParseEvent(
542 current_packet->header.timestamp,
543 current_packet->payload,
544 current_packet->payload_length,
545 &event);
546 if (ret != DtmfBuffer::kOK) {
547 LOG_FERR2(LS_WARNING, ParseEvent, ret,
548 current_packet->payload_length);
549 PacketBuffer::DeleteAllPackets(&packet_list);
550 return kDtmfParsingError;
551 }
552 if (dtmf_buffer_->InsertEvent(event) != DtmfBuffer::kOK) {
553 LOG_FERR0(LS_WARNING, InsertEvent);
554 PacketBuffer::DeleteAllPackets(&packet_list);
555 return kDtmfInsertError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000556 }
557 // TODO(hlundin): Let the destructor of Packet handle the payload.
558 delete [] current_packet->payload;
559 delete current_packet;
560 it = packet_list.erase(it);
561 } else {
562 ++it;
563 }
564 }
565
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000566 // Check for FEC in packets, and separate payloads into several packets.
567 int ret = payload_splitter_->SplitFec(&packet_list, decoder_database_.get());
568 if (ret != PayloadSplitter::kOK) {
569 LOG_FERR1(LS_WARNING, SplitFec, packet_list.size());
570 PacketBuffer::DeleteAllPackets(&packet_list);
571 switch (ret) {
572 case PayloadSplitter::kUnknownPayloadType:
573 return kUnknownRtpPayloadType;
574 default:
575 return kOtherError;
576 }
577 }
578
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000579 // Split payloads into smaller chunks. This also verifies that all payloads
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000580 // are of a known payload type. SplitAudio() method is protected against
581 // sync-packets.
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +0000582 ret = payload_splitter_->SplitAudio(&packet_list, *decoder_database_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000583 if (ret != PayloadSplitter::kOK) {
584 LOG_FERR1(LS_WARNING, SplitAudio, packet_list.size());
585 PacketBuffer::DeleteAllPackets(&packet_list);
586 switch (ret) {
587 case PayloadSplitter::kUnknownPayloadType:
588 return kUnknownRtpPayloadType;
589 case PayloadSplitter::kFrameSplitError:
590 return kFrameSplitError;
591 default:
592 return kOtherError;
593 }
594 }
595
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000596 // Update bandwidth estimate, if the packet is not sync-packet.
597 if (!packet_list.empty() && !packet_list.front()->sync_packet) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000598 // The list can be empty here if we got nothing but DTMF payloads.
599 AudioDecoder* decoder =
600 decoder_database_->GetDecoder(main_header.payloadType);
601 assert(decoder); // Should always get a valid object, since we have
602 // already checked that the payload types are known.
603 decoder->IncomingPacket(packet_list.front()->payload,
604 packet_list.front()->payload_length,
605 packet_list.front()->header.sequenceNumber,
606 packet_list.front()->header.timestamp,
607 receive_timestamp);
608 }
609
610 // Insert packets in buffer.
611 int temp_bufsize = packet_buffer_->NumPacketsInBuffer();
612 ret = packet_buffer_->InsertPacketList(
613 &packet_list,
614 *decoder_database_,
615 &current_rtp_payload_type_,
616 &current_cng_rtp_payload_type_);
617 if (ret == PacketBuffer::kFlushed) {
618 // Reset DSP timestamp etc. if packet buffer flushed.
619 new_codec_ = true;
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000620 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000621 LOG_F(LS_WARNING) << "Packet buffer flushed";
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000622 } else if (ret == PacketBuffer::kOversizePacket) {
623 LOG_F(LS_WARNING) << "Packet larger than packet buffer";
624 return kOversizePacket;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000625 } else if (ret != PacketBuffer::kOK) {
626 LOG_FERR1(LS_WARNING, InsertPacketList, packet_list.size());
627 PacketBuffer::DeleteAllPackets(&packet_list);
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000628 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000629 }
630 if (current_rtp_payload_type_ != 0xFF) {
631 const DecoderDatabase::DecoderInfo* dec_info =
632 decoder_database_->GetDecoderInfo(current_rtp_payload_type_);
633 if (!dec_info) {
634 assert(false); // Already checked that the payload type is known.
635 }
636 }
637
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000638 if (update_sample_rate_and_channels && !packet_buffer_->Empty()) {
639 // We do not use |current_rtp_payload_type_| to |set payload_type|, but
640 // get the next RTP header from |packet_buffer_| to obtain the payload type.
641 // The reason for it is the following corner case. If NetEq receives a
642 // CNG packet with a sample rate different than the current CNG then it
643 // flushes its buffer, assuming send codec must have been changed. However,
644 // payload type of the hypothetically new send codec is not known.
645 const RTPHeader* rtp_header = packet_buffer_->NextRtpHeader();
646 assert(rtp_header);
647 int payload_type = rtp_header->payloadType;
648 AudioDecoder* decoder = decoder_database_->GetDecoder(payload_type);
649 assert(decoder); // Payloads are already checked to be valid.
650 const DecoderDatabase::DecoderInfo* decoder_info =
651 decoder_database_->GetDecoderInfo(payload_type);
652 assert(decoder_info);
653 if (decoder_info->fs_hz != fs_hz_ ||
654 decoder->channels() != algorithm_buffer_->Channels())
655 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->channels());
656 }
657
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000658 // TODO(hlundin): Move this code to DelayManager class.
659 const DecoderDatabase::DecoderInfo* dec_info =
660 decoder_database_->GetDecoderInfo(main_header.payloadType);
661 assert(dec_info); // Already checked that the payload type is known.
662 delay_manager_->LastDecoderType(dec_info->codec_type);
663 if (delay_manager_->last_pack_cng_or_dtmf() == 0) {
664 // Calculate the total speech length carried in each packet.
665 temp_bufsize = packet_buffer_->NumPacketsInBuffer() - temp_bufsize;
666 temp_bufsize *= decoder_frame_length_;
667
668 if ((temp_bufsize > 0) &&
669 (temp_bufsize != decision_logic_->packet_length_samples())) {
670 decision_logic_->set_packet_length_samples(temp_bufsize);
671 delay_manager_->SetPacketAudioLength((1000 * temp_bufsize) / fs_hz_);
672 }
673
674 // Update statistics.
pbos@webrtc.org0946a562013-04-09 00:28:06 +0000675 if ((int32_t) (main_header.timestamp - timestamp_) >= 0 &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000676 !new_codec_) {
677 // Only update statistics if incoming packet is not older than last played
678 // out packet, and if new codec flag is not set.
679 delay_manager_->Update(main_header.sequenceNumber, main_header.timestamp,
680 fs_hz_);
681 }
682 } else if (delay_manager_->last_pack_cng_or_dtmf() == -1) {
683 // This is first "normal" packet after CNG or DTMF.
684 // Reset packet time counter and measure time until next packet,
685 // but don't update statistics.
686 delay_manager_->set_last_pack_cng_or_dtmf(0);
687 delay_manager_->ResetPacketIatCount();
688 }
689 return 0;
690}
691
692int NetEqImpl::GetAudioInternal(size_t max_length, int16_t* output,
693 int* samples_per_channel, int* num_channels) {
694 PacketList packet_list;
695 DtmfEvent dtmf_event;
696 Operations operation;
697 bool play_dtmf;
698 int return_value = GetDecision(&operation, &packet_list, &dtmf_event,
699 &play_dtmf);
700 if (return_value != 0) {
701 LOG_FERR1(LS_WARNING, GetDecision, return_value);
702 assert(false);
703 last_mode_ = kModeError;
704 return return_value;
705 }
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000706 LOG(LS_VERBOSE) << "GetDecision returned operation=" << operation <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000707 " and " << packet_list.size() << " packet(s)";
708
709 AudioDecoder::SpeechType speech_type;
710 int length = 0;
711 int decode_return_value = Decode(&packet_list, &operation,
712 &length, &speech_type);
713
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000714 assert(vad_.get());
715 bool sid_frame_available =
716 (operation == kRfc3389Cng && !packet_list.empty());
717 vad_->Update(decoded_buffer_.get(), length, speech_type,
718 sid_frame_available, fs_hz_);
719
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000720 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000721 switch (operation) {
722 case kNormal: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000723 DoNormal(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000724 break;
725 }
726 case kMerge: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000727 DoMerge(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000728 break;
729 }
730 case kExpand: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000731 return_value = DoExpand(play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000732 break;
733 }
734 case kAccelerate: {
735 return_value = DoAccelerate(decoded_buffer_.get(), length, speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000736 play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000737 break;
738 }
739 case kPreemptiveExpand: {
740 return_value = DoPreemptiveExpand(decoded_buffer_.get(), length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000741 speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000742 break;
743 }
744 case kRfc3389Cng:
745 case kRfc3389CngNoPacket: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000746 return_value = DoRfc3389Cng(&packet_list, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000747 break;
748 }
749 case kCodecInternalCng: {
750 // This handles the case when there is no transmission and the decoder
751 // should produce internal comfort noise.
752 // TODO(hlundin): Write test for codec-internal CNG.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000753 DoCodecInternalCng();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000754 break;
755 }
756 case kDtmf: {
757 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000758 return_value = DoDtmf(dtmf_event, &play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000759 break;
760 }
761 case kAlternativePlc: {
762 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000763 DoAlternativePlc(false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000764 break;
765 }
766 case kAlternativePlcIncreaseTimestamp: {
767 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000768 DoAlternativePlc(true);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000769 break;
770 }
771 case kAudioRepetitionIncreaseTimestamp: {
772 // TODO(hlundin): Write test for this.
773 sync_buffer_->IncreaseEndTimestamp(output_size_samples_);
774 // Skipping break on purpose. Execution should move on into the
775 // next case.
776 }
777 case kAudioRepetition: {
778 // TODO(hlundin): Write test for this.
779 // Copy last |output_size_samples_| from |sync_buffer_| to
780 // |algorithm_buffer|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000781 algorithm_buffer_->PushBackFromIndex(
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000782 *sync_buffer_, sync_buffer_->Size() - output_size_samples_);
783 expand_->Reset();
784 break;
785 }
786 case kUndefined: {
787 LOG_F(LS_ERROR) << "Invalid operation kUndefined.";
788 assert(false); // This should not happen.
789 last_mode_ = kModeError;
790 return kInvalidOperation;
791 }
792 } // End of switch.
793 if (return_value < 0) {
794 return return_value;
795 }
796
797 if (last_mode_ != kModeRfc3389Cng) {
798 comfort_noise_->Reset();
799 }
800
801 // Copy from |algorithm_buffer| to |sync_buffer_|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000802 sync_buffer_->PushBack(*algorithm_buffer_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000803
804 // Extract data from |sync_buffer_| to |output|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000805 size_t num_output_samples_per_channel = output_size_samples_;
806 size_t num_output_samples = output_size_samples_ * sync_buffer_->Channels();
807 if (num_output_samples > max_length) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000808 LOG(LS_WARNING) << "Output array is too short. " << max_length << " < " <<
809 output_size_samples_ << " * " << sync_buffer_->Channels();
810 num_output_samples = max_length;
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000811 num_output_samples_per_channel = static_cast<int>(
812 max_length / sync_buffer_->Channels());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000813 }
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000814 int samples_from_sync = static_cast<int>(
815 sync_buffer_->GetNextAudioInterleaved(num_output_samples_per_channel,
816 output));
817 *num_channels = static_cast<int>(sync_buffer_->Channels());
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000818 LOG(LS_VERBOSE) << "Sync buffer (" << *num_channels << " channel(s)):" <<
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000819 " insert " << algorithm_buffer_->Size() << " samples, extract " <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000820 samples_from_sync << " samples";
821 if (samples_from_sync != output_size_samples_) {
822 LOG_F(LS_ERROR) << "samples_from_sync != output_size_samples_";
minyue@webrtc.orgdb1cefc2013-08-13 01:39:21 +0000823 // TODO(minyue): treatment of under-run, filling zeros
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000824 memset(output, 0, num_output_samples * sizeof(int16_t));
825 *samples_per_channel = output_size_samples_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000826 return kSampleUnderrun;
827 }
828 *samples_per_channel = output_size_samples_;
829
830 // Should always have overlap samples left in the |sync_buffer_|.
831 assert(sync_buffer_->FutureLength() >= expand_->overlap_length());
832
833 if (play_dtmf) {
834 return_value = DtmfOverdub(dtmf_event, sync_buffer_->Channels(), output);
835 }
836
837 // Update the background noise parameters if last operation wrote data
838 // straight from the decoder to the |sync_buffer_|. That is, none of the
839 // operations that modify the signal can be followed by a parameter update.
840 if ((last_mode_ == kModeNormal) ||
841 (last_mode_ == kModeAccelerateFail) ||
842 (last_mode_ == kModePreemptiveExpandFail) ||
843 (last_mode_ == kModeRfc3389Cng) ||
844 (last_mode_ == kModeCodecInternalCng)) {
845 background_noise_->Update(*sync_buffer_, *vad_.get());
846 }
847
848 if (operation == kDtmf) {
849 // DTMF data was written the end of |sync_buffer_|.
850 // Update index to end of DTMF data in |sync_buffer_|.
851 sync_buffer_->set_dtmf_index(sync_buffer_->Size());
852 }
853
henrik.lundin@webrtc.orged865b52014-03-06 10:28:07 +0000854 if (last_mode_ != kModeExpand) {
855 // If last operation was not expand, calculate the |playout_timestamp_| from
856 // the |sync_buffer_|. However, do not update the |playout_timestamp_| if it
857 // would be moved "backwards".
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000858 uint32_t temp_timestamp = sync_buffer_->end_timestamp() -
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000859 static_cast<uint32_t>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000860 if (static_cast<int32_t>(temp_timestamp - playout_timestamp_) > 0) {
861 playout_timestamp_ = temp_timestamp;
862 }
863 } else {
864 // Use dead reckoning to estimate the |playout_timestamp_|.
865 playout_timestamp_ += output_size_samples_;
866 }
867
868 if (decode_return_value) return decode_return_value;
869 return return_value;
870}
871
872int NetEqImpl::GetDecision(Operations* operation,
873 PacketList* packet_list,
874 DtmfEvent* dtmf_event,
875 bool* play_dtmf) {
876 // Initialize output variables.
877 *play_dtmf = false;
878 *operation = kUndefined;
879
880 // Increment time counters.
881 packet_buffer_->IncrementWaitingTimes();
882 stats_.IncreaseCounter(output_size_samples_, fs_hz_);
883
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000884 assert(sync_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000885 uint32_t end_timestamp = sync_buffer_->end_timestamp();
886 if (!new_codec_) {
887 packet_buffer_->DiscardOldPackets(end_timestamp);
888 }
889 const RTPHeader* header = packet_buffer_->NextRtpHeader();
890
henrik.lundin@webrtc.orgca8cb952014-03-12 10:26:52 +0000891 if (decision_logic_->CngRfc3389On() || last_mode_ == kModeRfc3389Cng) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000892 // Because of timestamp peculiarities, we have to "manually" disallow using
893 // a CNG packet with the same timestamp as the one that was last played.
894 // This can happen when using redundancy and will cause the timing to shift.
henrik.lundin@webrtc.org24779fe2014-03-14 12:40:05 +0000895 while (header && decoder_database_->IsComfortNoise(header->payloadType) &&
896 (end_timestamp >= header->timestamp ||
897 end_timestamp + decision_logic_->generated_noise_samples() >
898 header->timestamp)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000899 // Don't use this packet, discard it.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000900 if (packet_buffer_->DiscardNextPacket() != PacketBuffer::kOK) {
901 assert(false); // Must be ok by design.
902 }
903 // Check buffer again.
904 if (!new_codec_) {
905 packet_buffer_->DiscardOldPackets(end_timestamp);
906 }
907 header = packet_buffer_->NextRtpHeader();
908 }
909 }
910
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000911 assert(expand_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000912 const int samples_left = static_cast<int>(sync_buffer_->FutureLength() -
913 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000914 if (last_mode_ == kModeAccelerateSuccess ||
915 last_mode_ == kModeAccelerateLowEnergy ||
916 last_mode_ == kModePreemptiveExpandSuccess ||
917 last_mode_ == kModePreemptiveExpandLowEnergy) {
918 // Subtract (samples_left + output_size_samples_) from sampleMemory.
919 decision_logic_->AddSampleMemory(-(samples_left + output_size_samples_));
920 }
921
922 // Check if it is time to play a DTMF event.
923 if (dtmf_buffer_->GetEvent(end_timestamp +
924 decision_logic_->generated_noise_samples(),
925 dtmf_event)) {
926 *play_dtmf = true;
927 }
928
929 // Get instruction.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000930 assert(sync_buffer_.get());
931 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000932 *operation = decision_logic_->GetDecision(*sync_buffer_,
933 *expand_,
934 decoder_frame_length_,
935 header,
936 last_mode_,
937 *play_dtmf,
938 &reset_decoder_);
939
940 // Check if we already have enough samples in the |sync_buffer_|. If so,
941 // change decision to normal, unless the decision was merge, accelerate, or
942 // preemptive expand.
943 if (samples_left >= output_size_samples_ &&
944 *operation != kMerge &&
945 *operation != kAccelerate &&
946 *operation != kPreemptiveExpand) {
947 *operation = kNormal;
948 return 0;
949 }
950
951 decision_logic_->ExpandDecision(*operation == kExpand);
952
953 // Check conditions for reset.
954 if (new_codec_ || *operation == kUndefined) {
955 // The only valid reason to get kUndefined is that new_codec_ is set.
956 assert(new_codec_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000957 if (*play_dtmf && !header) {
958 timestamp_ = dtmf_event->timestamp;
959 } else {
960 assert(header);
961 if (!header) {
962 LOG_F(LS_ERROR) << "Packet missing where it shouldn't.";
963 return -1;
964 }
965 timestamp_ = header->timestamp;
966 if (*operation == kRfc3389CngNoPacket
967#ifndef LEGACY_BITEXACT
968 // Without this check, it can happen that a non-CNG packet is sent to
969 // the CNG decoder as if it was a SID frame. This is clearly a bug,
970 // but is kept for now to maintain bit-exactness with the test
971 // vectors.
972 && decoder_database_->IsComfortNoise(header->payloadType)
973#endif
974 ) {
975 // Change decision to CNG packet, since we do have a CNG packet, but it
976 // was considered too early to use. Now, use it anyway.
977 *operation = kRfc3389Cng;
978 } else if (*operation != kRfc3389Cng) {
979 *operation = kNormal;
980 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000981 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000982 // Adjust |sync_buffer_| timestamp before setting |end_timestamp| to the
983 // new value.
984 sync_buffer_->IncreaseEndTimestamp(timestamp_ - end_timestamp);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000985 end_timestamp = timestamp_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000986 new_codec_ = false;
987 decision_logic_->SoftReset();
988 buffer_level_filter_->Reset();
989 delay_manager_->Reset();
990 stats_.ResetMcu();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000991 }
992
993 int required_samples = output_size_samples_;
994 const int samples_10_ms = 80 * fs_mult_;
995 const int samples_20_ms = 2 * samples_10_ms;
996 const int samples_30_ms = 3 * samples_10_ms;
997
998 switch (*operation) {
999 case kExpand: {
1000 timestamp_ = end_timestamp;
1001 return 0;
1002 }
1003 case kRfc3389CngNoPacket:
1004 case kCodecInternalCng: {
1005 return 0;
1006 }
1007 case kDtmf: {
1008 // TODO(hlundin): Write test for this.
1009 // Update timestamp.
1010 timestamp_ = end_timestamp;
1011 if (decision_logic_->generated_noise_samples() > 0 &&
1012 last_mode_ != kModeDtmf) {
1013 // Make a jump in timestamp due to the recently played comfort noise.
1014 uint32_t timestamp_jump = decision_logic_->generated_noise_samples();
1015 sync_buffer_->IncreaseEndTimestamp(timestamp_jump);
1016 timestamp_ += timestamp_jump;
1017 }
1018 decision_logic_->set_generated_noise_samples(0);
1019 return 0;
1020 }
1021 case kAccelerate: {
1022 // In order to do a accelerate we need at least 30 ms of audio data.
1023 if (samples_left >= samples_30_ms) {
1024 // Already have enough data, so we do not need to extract any more.
1025 decision_logic_->set_sample_memory(samples_left);
1026 decision_logic_->set_prev_time_scale(true);
1027 return 0;
1028 } else if (samples_left >= samples_10_ms &&
1029 decoder_frame_length_ >= samples_30_ms) {
1030 // Avoid decoding more data as it might overflow the playout buffer.
1031 *operation = kNormal;
1032 return 0;
1033 } else if (samples_left < samples_20_ms &&
1034 decoder_frame_length_ < samples_30_ms) {
1035 // Build up decoded data by decoding at least 20 ms of audio data. Do
1036 // not perform accelerate yet, but wait until we only need to do one
1037 // decoding.
1038 required_samples = 2 * output_size_samples_;
1039 *operation = kNormal;
1040 }
1041 // If none of the above is true, we have one of two possible situations:
1042 // (1) 20 ms <= samples_left < 30 ms and decoder_frame_length_ < 30 ms; or
1043 // (2) samples_left < 10 ms and decoder_frame_length_ >= 30 ms.
1044 // In either case, we move on with the accelerate decision, and decode one
1045 // frame now.
1046 break;
1047 }
1048 case kPreemptiveExpand: {
1049 // In order to do a preemptive expand we need at least 30 ms of decoded
1050 // audio data.
1051 if ((samples_left >= samples_30_ms) ||
1052 (samples_left >= samples_10_ms &&
1053 decoder_frame_length_ >= samples_30_ms)) {
1054 // Already have enough data, so we do not need to extract any more.
1055 // Or, avoid decoding more data as it might overflow the playout buffer.
1056 // Still try preemptive expand, though.
1057 decision_logic_->set_sample_memory(samples_left);
1058 decision_logic_->set_prev_time_scale(true);
1059 return 0;
1060 }
1061 if (samples_left < samples_20_ms &&
1062 decoder_frame_length_ < samples_30_ms) {
1063 // Build up decoded data by decoding at least 20 ms of audio data.
1064 // Still try to perform preemptive expand.
1065 required_samples = 2 * output_size_samples_;
1066 }
1067 // Move on with the preemptive expand decision.
1068 break;
1069 }
1070 default: {
1071 // Do nothing.
1072 }
1073 }
1074
1075 // Get packets from buffer.
1076 int extracted_samples = 0;
1077 if (header &&
1078 *operation != kAlternativePlc &&
1079 *operation != kAlternativePlcIncreaseTimestamp &&
1080 *operation != kAudioRepetition &&
1081 *operation != kAudioRepetitionIncreaseTimestamp) {
1082 sync_buffer_->IncreaseEndTimestamp(header->timestamp - end_timestamp);
1083 if (decision_logic_->CngOff()) {
1084 // Adjustment of timestamp only corresponds to an actual packet loss
1085 // if comfort noise is not played. If comfort noise was just played,
1086 // this adjustment of timestamp is only done to get back in sync with the
1087 // stream timestamp; no loss to report.
1088 stats_.LostSamples(header->timestamp - end_timestamp);
1089 }
1090
1091 if (*operation != kRfc3389Cng) {
1092 // We are about to decode and use a non-CNG packet.
1093 decision_logic_->SetCngOff();
1094 }
1095 // Reset CNG timestamp as a new packet will be delivered.
1096 // (Also if this is a CNG packet, since playedOutTS is updated.)
1097 decision_logic_->set_generated_noise_samples(0);
1098
1099 extracted_samples = ExtractPackets(required_samples, packet_list);
1100 if (extracted_samples < 0) {
1101 LOG_F(LS_WARNING) << "Failed to extract packets from buffer.";
1102 return kPacketBufferCorruption;
1103 }
1104 }
1105
1106 if (*operation == kAccelerate ||
1107 *operation == kPreemptiveExpand) {
1108 decision_logic_->set_sample_memory(samples_left + extracted_samples);
1109 decision_logic_->set_prev_time_scale(true);
1110 }
1111
1112 if (*operation == kAccelerate) {
1113 // Check that we have enough data (30ms) to do accelerate.
1114 if (extracted_samples + samples_left < samples_30_ms) {
1115 // TODO(hlundin): Write test for this.
1116 // Not enough, do normal operation instead.
1117 *operation = kNormal;
1118 }
1119 }
1120
1121 timestamp_ = end_timestamp;
1122 return 0;
1123}
1124
1125int NetEqImpl::Decode(PacketList* packet_list, Operations* operation,
1126 int* decoded_length,
1127 AudioDecoder::SpeechType* speech_type) {
1128 *speech_type = AudioDecoder::kSpeech;
1129 AudioDecoder* decoder = NULL;
1130 if (!packet_list->empty()) {
1131 const Packet* packet = packet_list->front();
1132 int payload_type = packet->header.payloadType;
1133 if (!decoder_database_->IsComfortNoise(payload_type)) {
1134 decoder = decoder_database_->GetDecoder(payload_type);
1135 assert(decoder);
1136 if (!decoder) {
1137 LOG_FERR1(LS_WARNING, GetDecoder, payload_type);
1138 PacketBuffer::DeleteAllPackets(packet_list);
1139 return kDecoderNotFound;
1140 }
1141 bool decoder_changed;
1142 decoder_database_->SetActiveDecoder(payload_type, &decoder_changed);
1143 if (decoder_changed) {
1144 // We have a new decoder. Re-init some values.
1145 const DecoderDatabase::DecoderInfo* decoder_info = decoder_database_
1146 ->GetDecoderInfo(payload_type);
1147 assert(decoder_info);
1148 if (!decoder_info) {
1149 LOG_FERR1(LS_WARNING, GetDecoderInfo, payload_type);
1150 PacketBuffer::DeleteAllPackets(packet_list);
1151 return kDecoderNotFound;
1152 }
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001153 // If sampling rate or number of channels has changed, we need to make
1154 // a reset.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001155 if (decoder_info->fs_hz != fs_hz_ ||
1156 decoder->channels() != algorithm_buffer_->Channels()) {
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001157 // TODO(tlegrand): Add unittest to cover this event.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001158 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->channels());
1159 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001160 sync_buffer_->set_end_timestamp(timestamp_);
1161 playout_timestamp_ = timestamp_;
1162 }
1163 }
1164 }
1165
1166 if (reset_decoder_) {
1167 // TODO(hlundin): Write test for this.
1168 // Reset decoder.
1169 if (decoder) {
1170 decoder->Init();
1171 }
1172 // Reset comfort noise decoder.
1173 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
1174 if (cng_decoder) {
1175 cng_decoder->Init();
1176 }
1177 reset_decoder_ = false;
1178 }
1179
1180#ifdef LEGACY_BITEXACT
1181 // Due to a bug in old SignalMCU, it could happen that CNG operation was
1182 // decided, but a speech packet was provided. The speech packet will be used
1183 // to update the comfort noise decoder, as if it was a SID frame, which is
1184 // clearly wrong.
1185 if (*operation == kRfc3389Cng) {
1186 return 0;
1187 }
1188#endif
1189
1190 *decoded_length = 0;
1191 // Update codec-internal PLC state.
1192 if ((*operation == kMerge) && decoder && decoder->HasDecodePlc()) {
1193 decoder->DecodePlc(1, &decoded_buffer_[*decoded_length]);
1194 }
1195
1196 int return_value = DecodeLoop(packet_list, operation, decoder,
1197 decoded_length, speech_type);
1198
1199 if (*decoded_length < 0) {
1200 // Error returned from the decoder.
1201 *decoded_length = 0;
1202 sync_buffer_->IncreaseEndTimestamp(decoder_frame_length_);
1203 int error_code = 0;
1204 if (decoder)
1205 error_code = decoder->ErrorCode();
1206 if (error_code != 0) {
1207 // Got some error code from the decoder.
1208 decoder_error_code_ = error_code;
1209 return_value = kDecoderErrorCode;
1210 } else {
1211 // Decoder does not implement error codes. Return generic error.
1212 return_value = kOtherDecoderError;
1213 }
1214 LOG_FERR2(LS_WARNING, DecodeLoop, error_code, packet_list->size());
1215 *operation = kExpand; // Do expansion to get data instead.
1216 }
1217 if (*speech_type != AudioDecoder::kComfortNoise) {
1218 // Don't increment timestamp if codec returned CNG speech type
1219 // since in this case, the we will increment the CNGplayedTS counter.
1220 // Increase with number of samples per channel.
1221 assert(*decoded_length == 0 ||
1222 (decoder && decoder->channels() == sync_buffer_->Channels()));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001223 sync_buffer_->IncreaseEndTimestamp(
1224 *decoded_length / static_cast<int>(sync_buffer_->Channels()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001225 }
1226 return return_value;
1227}
1228
1229int NetEqImpl::DecodeLoop(PacketList* packet_list, Operations* operation,
1230 AudioDecoder* decoder, int* decoded_length,
1231 AudioDecoder::SpeechType* speech_type) {
1232 Packet* packet = NULL;
1233 if (!packet_list->empty()) {
1234 packet = packet_list->front();
1235 }
1236 // Do decoding.
1237 while (packet &&
1238 !decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1239 assert(decoder); // At this point, we must have a decoder object.
1240 // The number of channels in the |sync_buffer_| should be the same as the
1241 // number decoder channels.
1242 assert(sync_buffer_->Channels() == decoder->channels());
1243 assert(decoded_buffer_length_ >= kMaxFrameSize * decoder->channels());
1244 assert(*operation == kNormal || *operation == kAccelerate ||
1245 *operation == kMerge || *operation == kPreemptiveExpand);
1246 packet_list->pop_front();
henrik.lundin@webrtc.org63464a92013-01-30 09:41:56 +00001247 int payload_length = packet->payload_length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001248 int16_t decode_length;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +00001249 if (packet->sync_packet) {
1250 // Decode to silence with the same frame size as the last decode.
1251 LOG(LS_VERBOSE) << "Decoding sync-packet: " <<
1252 " ts=" << packet->header.timestamp <<
1253 ", sn=" << packet->header.sequenceNumber <<
1254 ", pt=" << static_cast<int>(packet->header.payloadType) <<
1255 ", ssrc=" << packet->header.ssrc <<
1256 ", len=" << packet->payload_length;
1257 memset(&decoded_buffer_[*decoded_length], 0, decoder_frame_length_ *
1258 decoder->channels() * sizeof(decoded_buffer_[0]));
1259 decode_length = decoder_frame_length_;
1260 } else if (!packet->primary) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001261 // This is a redundant payload; call the special decoder method.
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +00001262 LOG(LS_VERBOSE) << "Decoding packet (redundant):" <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001263 " ts=" << packet->header.timestamp <<
1264 ", sn=" << packet->header.sequenceNumber <<
1265 ", pt=" << static_cast<int>(packet->header.payloadType) <<
1266 ", ssrc=" << packet->header.ssrc <<
1267 ", len=" << packet->payload_length;
1268 decode_length = decoder->DecodeRedundant(
1269 packet->payload, packet->payload_length,
1270 &decoded_buffer_[*decoded_length], speech_type);
1271 } else {
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +00001272 LOG(LS_VERBOSE) << "Decoding packet: ts=" << packet->header.timestamp <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001273 ", sn=" << packet->header.sequenceNumber <<
1274 ", pt=" << static_cast<int>(packet->header.payloadType) <<
1275 ", ssrc=" << packet->header.ssrc <<
1276 ", len=" << packet->payload_length;
1277 decode_length = decoder->Decode(packet->payload,
1278 packet->payload_length,
1279 &decoded_buffer_[*decoded_length],
1280 speech_type);
1281 }
1282
1283 delete[] packet->payload;
1284 delete packet;
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001285 packet = NULL;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001286 if (decode_length > 0) {
1287 *decoded_length += decode_length;
1288 // Update |decoder_frame_length_| with number of samples per channel.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001289 decoder_frame_length_ = decode_length /
1290 static_cast<int>(decoder->channels());
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +00001291 LOG(LS_VERBOSE) << "Decoded " << decode_length << " samples (" <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001292 decoder->channels() << " channel(s) -> " << decoder_frame_length_ <<
1293 " samples per channel)";
1294 } else if (decode_length < 0) {
1295 // Error.
henrik.lundin@webrtc.org63464a92013-01-30 09:41:56 +00001296 LOG_FERR2(LS_WARNING, Decode, decode_length, payload_length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001297 *decoded_length = -1;
1298 PacketBuffer::DeleteAllPackets(packet_list);
1299 break;
1300 }
1301 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1302 // Guard against overflow.
1303 LOG_F(LS_WARNING) << "Decoded too much.";
1304 PacketBuffer::DeleteAllPackets(packet_list);
1305 return kDecodedTooMuch;
1306 }
1307 if (!packet_list->empty()) {
1308 packet = packet_list->front();
1309 } else {
1310 packet = NULL;
1311 }
1312 } // End of decode loop.
1313
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001314 // If the list is not empty at this point, either a decoding error terminated
1315 // the while-loop, or list must hold exactly one CNG packet.
1316 assert(packet_list->empty() || *decoded_length < 0 ||
1317 (packet_list->size() == 1 && packet &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001318 decoder_database_->IsComfortNoise(packet->header.payloadType)));
1319 return 0;
1320}
1321
1322void NetEqImpl::DoNormal(const int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001323 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001324 assert(normal_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001325 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001326 normal_->Process(decoded_buffer, decoded_length, last_mode_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001327 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001328 if (decoded_length != 0) {
1329 last_mode_ = kModeNormal;
1330 }
1331
1332 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1333 if ((speech_type == AudioDecoder::kComfortNoise)
1334 || ((last_mode_ == kModeCodecInternalCng)
1335 && (decoded_length == 0))) {
1336 // TODO(hlundin): Remove second part of || statement above.
1337 last_mode_ = kModeCodecInternalCng;
1338 }
1339
1340 if (!play_dtmf) {
1341 dtmf_tone_generator_->Reset();
1342 }
1343}
1344
1345void NetEqImpl::DoMerge(int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001346 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001347 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001348 assert(merge_.get());
1349 int new_length = merge_->Process(decoded_buffer, decoded_length,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001350 mute_factor_array_.get(),
1351 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001352
1353 // Update in-call and post-call statistics.
1354 if (expand_->MuteFactor(0) == 0) {
1355 // Expand generates only noise.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001356 stats_.ExpandedNoiseSamples(new_length - static_cast<int>(decoded_length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001357 } else {
1358 // Expansion generates more than only noise.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001359 stats_.ExpandedVoiceSamples(new_length - static_cast<int>(decoded_length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001360 }
1361
1362 last_mode_ = kModeMerge;
1363 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1364 if (speech_type == AudioDecoder::kComfortNoise) {
1365 last_mode_ = kModeCodecInternalCng;
1366 }
1367 expand_->Reset();
1368 if (!play_dtmf) {
1369 dtmf_tone_generator_->Reset();
1370 }
1371}
1372
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001373int NetEqImpl::DoExpand(bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001374 while ((sync_buffer_->FutureLength() - expand_->overlap_length()) <
1375 static_cast<size_t>(output_size_samples_)) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001376 algorithm_buffer_->Clear();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001377 int return_value = expand_->Process(algorithm_buffer_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001378 int length = static_cast<int>(algorithm_buffer_->Size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001379
1380 // Update in-call and post-call statistics.
1381 if (expand_->MuteFactor(0) == 0) {
1382 // Expand operation generates only noise.
1383 stats_.ExpandedNoiseSamples(length);
1384 } else {
1385 // Expand operation generates more than only noise.
1386 stats_.ExpandedVoiceSamples(length);
1387 }
1388
1389 last_mode_ = kModeExpand;
1390
1391 if (return_value < 0) {
1392 return return_value;
1393 }
1394
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001395 sync_buffer_->PushBack(*algorithm_buffer_);
1396 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001397 }
1398 if (!play_dtmf) {
1399 dtmf_tone_generator_->Reset();
1400 }
1401 return 0;
1402}
1403
1404int NetEqImpl::DoAccelerate(int16_t* decoded_buffer, size_t decoded_length,
1405 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001406 bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001407 const size_t required_samples = 240 * fs_mult_; // Must have 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001408 size_t borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001409 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001410 size_t decoded_length_per_channel = decoded_length / num_channels;
1411 if (decoded_length_per_channel < required_samples) {
1412 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001413 borrowed_samples_per_channel = static_cast<int>(required_samples -
1414 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001415 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1416 decoded_buffer,
1417 sizeof(int16_t) * decoded_length);
1418 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1419 decoded_buffer);
1420 decoded_length = required_samples * num_channels;
1421 }
1422
1423 int16_t samples_removed;
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001424 Accelerate::ReturnCodes return_code = accelerate_->Process(
1425 decoded_buffer, decoded_length, algorithm_buffer_.get(),
1426 &samples_removed);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001427 stats_.AcceleratedSamples(samples_removed);
1428 switch (return_code) {
1429 case Accelerate::kSuccess:
1430 last_mode_ = kModeAccelerateSuccess;
1431 break;
1432 case Accelerate::kSuccessLowEnergy:
1433 last_mode_ = kModeAccelerateLowEnergy;
1434 break;
1435 case Accelerate::kNoStretch:
1436 last_mode_ = kModeAccelerateFail;
1437 break;
1438 case Accelerate::kError:
1439 // TODO(hlundin): Map to kModeError instead?
1440 last_mode_ = kModeAccelerateFail;
1441 return kAccelerateError;
1442 }
1443
1444 if (borrowed_samples_per_channel > 0) {
1445 // Copy borrowed samples back to the |sync_buffer_|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001446 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001447 if (length < borrowed_samples_per_channel) {
1448 // This destroys the beginning of the buffer, but will not cause any
1449 // problems.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001450 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001451 sync_buffer_->Size() -
1452 borrowed_samples_per_channel);
1453 sync_buffer_->PushFrontZeros(borrowed_samples_per_channel - length);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001454 algorithm_buffer_->PopFront(length);
1455 assert(algorithm_buffer_->Empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001456 } else {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001457 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001458 borrowed_samples_per_channel,
1459 sync_buffer_->Size() -
1460 borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001461 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001462 }
1463 }
1464
1465 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1466 if (speech_type == AudioDecoder::kComfortNoise) {
1467 last_mode_ = kModeCodecInternalCng;
1468 }
1469 if (!play_dtmf) {
1470 dtmf_tone_generator_->Reset();
1471 }
1472 expand_->Reset();
1473 return 0;
1474}
1475
1476int NetEqImpl::DoPreemptiveExpand(int16_t* decoded_buffer,
1477 size_t decoded_length,
1478 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001479 bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001480 const size_t required_samples = 240 * fs_mult_; // Must have 30 ms.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001481 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001482 int borrowed_samples_per_channel = 0;
1483 int old_borrowed_samples_per_channel = 0;
1484 size_t decoded_length_per_channel = decoded_length / num_channels;
1485 if (decoded_length_per_channel < required_samples) {
1486 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001487 borrowed_samples_per_channel = static_cast<int>(required_samples -
1488 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001489 // Calculate how many of these were already played out.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001490 old_borrowed_samples_per_channel = static_cast<int>(
1491 borrowed_samples_per_channel - sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001492 old_borrowed_samples_per_channel = std::max(
1493 0, old_borrowed_samples_per_channel);
1494 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1495 decoded_buffer,
1496 sizeof(int16_t) * decoded_length);
1497 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1498 decoded_buffer);
1499 decoded_length = required_samples * num_channels;
1500 }
1501
1502 int16_t samples_added;
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001503 PreemptiveExpand::ReturnCodes return_code = preemptive_expand_->Process(
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001504 decoded_buffer, static_cast<int>(decoded_length),
1505 old_borrowed_samples_per_channel,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001506 algorithm_buffer_.get(), &samples_added);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001507 stats_.PreemptiveExpandedSamples(samples_added);
1508 switch (return_code) {
1509 case PreemptiveExpand::kSuccess:
1510 last_mode_ = kModePreemptiveExpandSuccess;
1511 break;
1512 case PreemptiveExpand::kSuccessLowEnergy:
1513 last_mode_ = kModePreemptiveExpandLowEnergy;
1514 break;
1515 case PreemptiveExpand::kNoStretch:
1516 last_mode_ = kModePreemptiveExpandFail;
1517 break;
1518 case PreemptiveExpand::kError:
1519 // TODO(hlundin): Map to kModeError instead?
1520 last_mode_ = kModePreemptiveExpandFail;
1521 return kPreemptiveExpandError;
1522 }
1523
1524 if (borrowed_samples_per_channel > 0) {
1525 // Copy borrowed samples back to the |sync_buffer_|.
1526 sync_buffer_->ReplaceAtIndex(
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001527 *algorithm_buffer_, borrowed_samples_per_channel,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001528 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001529 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001530 }
1531
1532 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1533 if (speech_type == AudioDecoder::kComfortNoise) {
1534 last_mode_ = kModeCodecInternalCng;
1535 }
1536 if (!play_dtmf) {
1537 dtmf_tone_generator_->Reset();
1538 }
1539 expand_->Reset();
1540 return 0;
1541}
1542
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001543int NetEqImpl::DoRfc3389Cng(PacketList* packet_list, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001544 if (!packet_list->empty()) {
1545 // Must have exactly one SID frame at this point.
1546 assert(packet_list->size() == 1);
1547 Packet* packet = packet_list->front();
1548 packet_list->pop_front();
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001549 if (!decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1550#ifdef LEGACY_BITEXACT
1551 // This can happen due to a bug in GetDecision. Change the payload type
1552 // to a CNG type, and move on. Note that this means that we are in fact
1553 // sending a non-CNG payload to the comfort noise decoder for decoding.
1554 // Clearly wrong, but will maintain bit-exactness with legacy.
1555 if (fs_hz_ == 8000) {
1556 packet->header.payloadType =
1557 decoder_database_->GetRtpPayloadType(kDecoderCNGnb);
1558 } else if (fs_hz_ == 16000) {
1559 packet->header.payloadType =
1560 decoder_database_->GetRtpPayloadType(kDecoderCNGwb);
1561 } else if (fs_hz_ == 32000) {
1562 packet->header.payloadType =
1563 decoder_database_->GetRtpPayloadType(kDecoderCNGswb32kHz);
1564 } else if (fs_hz_ == 48000) {
1565 packet->header.payloadType =
1566 decoder_database_->GetRtpPayloadType(kDecoderCNGswb48kHz);
1567 }
1568 assert(decoder_database_->IsComfortNoise(packet->header.payloadType));
1569#else
1570 LOG(LS_ERROR) << "Trying to decode non-CNG payload as CNG.";
1571 return kOtherError;
1572#endif
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001573 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001574 // UpdateParameters() deletes |packet|.
1575 if (comfort_noise_->UpdateParameters(packet) ==
1576 ComfortNoise::kInternalError) {
1577 LOG_FERR0(LS_WARNING, UpdateParameters);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001578 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001579 return -comfort_noise_->internal_error_code();
1580 }
1581 }
1582 int cn_return = comfort_noise_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001583 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001584 expand_->Reset();
1585 last_mode_ = kModeRfc3389Cng;
1586 if (!play_dtmf) {
1587 dtmf_tone_generator_->Reset();
1588 }
1589 if (cn_return == ComfortNoise::kInternalError) {
1590 LOG_FERR1(LS_WARNING, comfort_noise_->Generate, cn_return);
1591 decoder_error_code_ = comfort_noise_->internal_error_code();
1592 return kComfortNoiseErrorCode;
1593 } else if (cn_return == ComfortNoise::kUnknownPayloadType) {
1594 LOG_FERR1(LS_WARNING, comfort_noise_->Generate, cn_return);
1595 return kUnknownRtpPayloadType;
1596 }
1597 return 0;
1598}
1599
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001600void NetEqImpl::DoCodecInternalCng() {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001601 int length = 0;
1602 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1603 int16_t decoded_buffer[kMaxFrameSize];
1604 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1605 if (decoder) {
1606 const uint8_t* dummy_payload = NULL;
1607 AudioDecoder::SpeechType speech_type;
1608 length = decoder->Decode(dummy_payload, 0, decoded_buffer, &speech_type);
1609 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001610 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001611 normal_->Process(decoded_buffer, length, last_mode_, mute_factor_array_.get(),
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001612 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001613 last_mode_ = kModeCodecInternalCng;
1614 expand_->Reset();
1615}
1616
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001617int NetEqImpl::DoDtmf(const DtmfEvent& dtmf_event, bool* play_dtmf) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001618 // This block of the code and the block further down, handling |dtmf_switch|
1619 // are commented out. Otherwise playing out-of-band DTMF would fail in VoE
1620 // test, DtmfTest.ManualSuccessfullySendsOutOfBandTelephoneEvents. This is
1621 // equivalent to |dtmf_switch| always be false.
1622 //
1623 // See http://webrtc-codereview.appspot.com/1195004/ for discussion
1624 // On this issue. This change might cause some glitches at the point of
1625 // switch from audio to DTMF. Issue 1545 is filed to track this.
1626 //
1627 // bool dtmf_switch = false;
1628 // if ((last_mode_ != kModeDtmf) && dtmf_tone_generator_->initialized()) {
1629 // // Special case; see below.
1630 // // We must catch this before calling Generate, since |initialized| is
1631 // // modified in that call.
1632 // dtmf_switch = true;
1633 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001634
1635 int dtmf_return_value = 0;
1636 if (!dtmf_tone_generator_->initialized()) {
1637 // Initialize if not already done.
1638 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1639 dtmf_event.volume);
1640 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001641
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001642 if (dtmf_return_value == 0) {
1643 // Generate DTMF signal.
1644 dtmf_return_value = dtmf_tone_generator_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001645 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001646 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001647
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001648 if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001649 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001650 return dtmf_return_value;
1651 }
1652
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001653 // if (dtmf_switch) {
1654 // // This is the special case where the previous operation was DTMF
1655 // // overdub, but the current instruction is "regular" DTMF. We must make
1656 // // sure that the DTMF does not have any discontinuities. The first DTMF
1657 // // sample that we generate now must be played out immediately, therefore
1658 // // it must be copied to the speech buffer.
1659 // // TODO(hlundin): This code seems incorrect. (Legacy.) Write test and
1660 // // verify correct operation.
1661 // assert(false);
1662 // // Must generate enough data to replace all of the |sync_buffer_|
1663 // // "future".
1664 // int required_length = sync_buffer_->FutureLength();
1665 // assert(dtmf_tone_generator_->initialized());
1666 // dtmf_return_value = dtmf_tone_generator_->Generate(required_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001667 // algorithm_buffer_);
1668 // assert((size_t) required_length == algorithm_buffer_->Size());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001669 // if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001670 // algorithm_buffer_->Zeros(output_size_samples_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001671 // return dtmf_return_value;
1672 // }
1673 //
1674 // // Overwrite the "future" part of the speech buffer with the new DTMF
1675 // // data.
1676 // // TODO(hlundin): It seems that this overwriting has gone lost.
1677 // // Not adapted for multi-channel yet.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001678 // assert(algorithm_buffer_->Channels() == 1);
1679 // if (algorithm_buffer_->Channels() != 1) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001680 // LOG(LS_WARNING) << "DTMF not supported for more than one channel";
1681 // return kStereoNotSupported;
1682 // }
1683 // // Shuffle the remaining data to the beginning of algorithm buffer.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001684 // algorithm_buffer_->PopFront(sync_buffer_->FutureLength());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001685 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001686
1687 sync_buffer_->IncreaseEndTimestamp(output_size_samples_);
1688 expand_->Reset();
1689 last_mode_ = kModeDtmf;
1690
1691 // Set to false because the DTMF is already in the algorithm buffer.
1692 *play_dtmf = false;
1693 return 0;
1694}
1695
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001696void NetEqImpl::DoAlternativePlc(bool increase_timestamp) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001697 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1698 int length;
1699 if (decoder && decoder->HasDecodePlc()) {
1700 // Use the decoder's packet-loss concealment.
1701 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1702 int16_t decoded_buffer[kMaxFrameSize];
1703 length = decoder->DecodePlc(1, decoded_buffer);
1704 if (length > 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001705 algorithm_buffer_->PushBackInterleaved(decoded_buffer, length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001706 } else {
1707 length = 0;
1708 }
1709 } else {
1710 // Do simple zero-stuffing.
1711 length = output_size_samples_;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001712 algorithm_buffer_->Zeros(length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001713 // By not advancing the timestamp, NetEq inserts samples.
1714 stats_.AddZeros(length);
1715 }
1716 if (increase_timestamp) {
1717 sync_buffer_->IncreaseEndTimestamp(length);
1718 }
1719 expand_->Reset();
1720}
1721
1722int NetEqImpl::DtmfOverdub(const DtmfEvent& dtmf_event, size_t num_channels,
1723 int16_t* output) const {
1724 size_t out_index = 0;
1725 int overdub_length = output_size_samples_; // Default value.
1726
1727 if (sync_buffer_->dtmf_index() > sync_buffer_->next_index()) {
1728 // Special operation for transition from "DTMF only" to "DTMF overdub".
1729 out_index = std::min(
1730 sync_buffer_->dtmf_index() - sync_buffer_->next_index(),
1731 static_cast<size_t>(output_size_samples_));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001732 overdub_length = output_size_samples_ - static_cast<int>(out_index);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001733 }
1734
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001735 AudioMultiVector dtmf_output(num_channels);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001736 int dtmf_return_value = 0;
1737 if (!dtmf_tone_generator_->initialized()) {
1738 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1739 dtmf_event.volume);
1740 }
1741 if (dtmf_return_value == 0) {
1742 dtmf_return_value = dtmf_tone_generator_->Generate(overdub_length,
1743 &dtmf_output);
1744 assert((size_t) overdub_length == dtmf_output.Size());
1745 }
1746 dtmf_output.ReadInterleaved(overdub_length, &output[out_index]);
1747 return dtmf_return_value < 0 ? dtmf_return_value : 0;
1748}
1749
1750int NetEqImpl::ExtractPackets(int required_samples, PacketList* packet_list) {
1751 bool first_packet = true;
1752 uint8_t prev_payload_type = 0;
1753 uint32_t prev_timestamp = 0;
1754 uint16_t prev_sequence_number = 0;
1755 bool next_packet_available = false;
1756
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001757 const RTPHeader* header = packet_buffer_->NextRtpHeader();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001758 assert(header);
1759 if (!header) {
1760 return -1;
1761 }
turaj@webrtc.org7df97062013-08-02 18:07:13 +00001762 uint32_t first_timestamp = header->timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001763 int extracted_samples = 0;
1764
1765 // Packet extraction loop.
1766 do {
1767 timestamp_ = header->timestamp;
1768 int discard_count = 0;
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001769 Packet* packet = packet_buffer_->GetNextPacket(&discard_count);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001770 // |header| may be invalid after the |packet_buffer_| operation.
1771 header = NULL;
1772 if (!packet) {
1773 LOG_FERR1(LS_ERROR, GetNextPacket, discard_count) <<
1774 "Should always be able to extract a packet here";
1775 assert(false); // Should always be able to extract a packet here.
1776 return -1;
1777 }
1778 stats_.PacketsDiscarded(discard_count);
1779 // Store waiting time in ms; packets->waiting_time is in "output blocks".
1780 stats_.StoreWaitingTime(packet->waiting_time * kOutputSizeMs);
1781 assert(packet->payload_length > 0);
1782 packet_list->push_back(packet); // Store packet in list.
1783
1784 if (first_packet) {
1785 first_packet = false;
minyue@webrtc.orgd7301772013-08-29 00:58:14 +00001786 decoded_packet_sequence_number_ = prev_sequence_number =
1787 packet->header.sequenceNumber;
1788 decoded_packet_timestamp_ = prev_timestamp = packet->header.timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001789 prev_payload_type = packet->header.payloadType;
1790 }
1791
1792 // Store number of extracted samples.
1793 int packet_duration = 0;
1794 AudioDecoder* decoder = decoder_database_->GetDecoder(
1795 packet->header.payloadType);
1796 if (decoder) {
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001797 if (packet->sync_packet) {
1798 packet_duration = decoder_frame_length_;
1799 } else {
1800 packet_duration = packet->primary ?
1801 decoder->PacketDuration(packet->payload, packet->payload_length) :
1802 decoder->PacketDurationRedundant(packet->payload,
1803 packet->payload_length);
1804 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001805 } else {
1806 LOG_FERR1(LS_WARNING, GetDecoder, packet->header.payloadType) <<
1807 "Could not find a decoder for a packet about to be extracted.";
1808 assert(false);
1809 }
1810 if (packet_duration <= 0) {
1811 // Decoder did not return a packet duration. Assume that the packet
1812 // contains the same number of samples as the previous one.
1813 packet_duration = decoder_frame_length_;
1814 }
1815 extracted_samples = packet->header.timestamp - first_timestamp +
1816 packet_duration;
1817
1818 // Check what packet is available next.
1819 header = packet_buffer_->NextRtpHeader();
1820 next_packet_available = false;
1821 if (header && prev_payload_type == header->payloadType) {
1822 int16_t seq_no_diff = header->sequenceNumber - prev_sequence_number;
1823 int32_t ts_diff = header->timestamp - prev_timestamp;
1824 if (seq_no_diff == 1 ||
1825 (seq_no_diff == 0 && ts_diff == decoder_frame_length_)) {
1826 // The next sequence number is available, or the next part of a packet
1827 // that was split into pieces upon insertion.
1828 next_packet_available = true;
1829 }
1830 prev_sequence_number = header->sequenceNumber;
1831 }
1832 } while (extracted_samples < required_samples && next_packet_available);
1833
1834 return extracted_samples;
1835}
1836
1837void NetEqImpl::SetSampleRateAndChannels(int fs_hz, size_t channels) {
1838 LOG_API2(fs_hz, channels);
1839 // TODO(hlundin): Change to an enumerator and skip assert.
1840 assert(fs_hz == 8000 || fs_hz == 16000 || fs_hz == 32000 || fs_hz == 48000);
1841 assert(channels > 0);
1842
1843 fs_hz_ = fs_hz;
1844 fs_mult_ = fs_hz / 8000;
1845 output_size_samples_ = kOutputSizeMs * 8 * fs_mult_;
1846 decoder_frame_length_ = 3 * output_size_samples_; // Initialize to 30ms.
1847
1848 last_mode_ = kModeNormal;
1849
1850 // Create a new array of mute factors and set all to 1.
1851 mute_factor_array_.reset(new int16_t[channels]);
1852 for (size_t i = 0; i < channels; ++i) {
1853 mute_factor_array_[i] = 16384; // 1.0 in Q14.
1854 }
1855
1856 // Reset comfort noise decoder, if there is one active.
1857 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
1858 if (cng_decoder) {
1859 cng_decoder->Init();
1860 }
1861
1862 // Reinit post-decode VAD with new sample rate.
1863 assert(vad_.get()); // Cannot be NULL here.
1864 vad_->Init();
1865
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001866 // Delete algorithm buffer and create a new one.
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001867 algorithm_buffer_.reset(new AudioMultiVector(channels));
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001868
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001869 // Delete sync buffer and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001870 sync_buffer_.reset(new SyncBuffer(channels, kSyncBufferSize * fs_mult_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001871
turaj@webrtc.orgff43c852013-09-25 00:07:27 +00001872
1873 // Delete BackgroundNoise object and create a new one, while preserving its
1874 // mode.
1875 NetEqBackgroundNoiseMode current_mode = kBgnOn;
1876 if (background_noise_.get())
1877 current_mode = background_noise_->mode();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001878 background_noise_.reset(new BackgroundNoise(channels));
turaj@webrtc.orgff43c852013-09-25 00:07:27 +00001879 background_noise_->set_mode(current_mode);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001880
1881 // Reset random vector.
1882 random_vector_.Reset();
1883
1884 // Delete Expand object and create a new one.
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +00001885 expand_.reset(expand_factory_->Create(background_noise_.get(),
1886 sync_buffer_.get(), &random_vector_,
1887 fs_hz, channels));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001888 // Move index so that we create a small set of future samples (all 0).
1889 sync_buffer_->set_next_index(sync_buffer_->next_index() -
1890 expand_->overlap_length());
1891
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001892 normal_.reset(new Normal(fs_hz, decoder_database_.get(), *background_noise_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001893 expand_.get()));
1894 merge_.reset(new Merge(fs_hz, channels, expand_.get(), sync_buffer_.get()));
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +00001895 accelerate_.reset(
1896 accelerate_factory_->Create(fs_hz, channels, *background_noise_));
1897 preemptive_expand_.reset(
1898 preemptive_expand_factory_->Create(fs_hz, channels, *background_noise_));
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001899
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001900 // Delete ComfortNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001901 comfort_noise_.reset(new ComfortNoise(fs_hz, decoder_database_.get(),
1902 sync_buffer_.get()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001903
1904 // Verify that |decoded_buffer_| is long enough.
1905 if (decoded_buffer_length_ < kMaxFrameSize * channels) {
1906 // Reallocate to larger size.
1907 decoded_buffer_length_ = kMaxFrameSize * channels;
1908 decoded_buffer_.reset(new int16_t[decoded_buffer_length_]);
1909 }
1910
1911 // Communicate new sample rate and output size to DecisionLogic object.
1912 assert(decision_logic_.get());
1913 decision_logic_->SetSampleRate(fs_hz_, output_size_samples_);
1914}
1915
1916NetEqOutputType NetEqImpl::LastOutputType() {
1917 assert(vad_.get());
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001918 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001919 if (last_mode_ == kModeCodecInternalCng || last_mode_ == kModeRfc3389Cng) {
1920 return kOutputCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001921 } else if (last_mode_ == kModeExpand && expand_->MuteFactor(0) == 0) {
1922 // Expand mode has faded down to background noise only (very long expand).
1923 return kOutputPLCtoCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001924 } else if (last_mode_ == kModeExpand) {
1925 return kOutputPLC;
wu@webrtc.org24301a62013-12-13 19:17:43 +00001926 } else if (vad_->running() && !vad_->active_speech()) {
1927 return kOutputVADPassive;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001928 } else {
1929 return kOutputNormal;
1930 }
1931}
1932
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001933} // namespace webrtc