blob: 38a5456956212ad35daf2f9d03bbf008268df331 [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
henrik.lundin@webrtc.org1b9df052014-05-28 07:33:39 +000011#include "webrtc/modules/audio_coding/neteq4/neteq_impl.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000012
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"
henrik.lundin@webrtc.org1b9df052014-05-28 07:33:39 +000019#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"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000041#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,
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +000064 PreemptiveExpandFactory* preemptive_expand_factory,
65 bool create_components)
andrew@webrtc.org31628aa2013-10-22 12:50:00 +000066 : buffer_level_filter_(buffer_level_filter),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000067 decoder_database_(decoder_database),
68 delay_manager_(delay_manager),
69 delay_peak_detector_(delay_peak_detector),
70 dtmf_buffer_(dtmf_buffer),
71 dtmf_tone_generator_(dtmf_tone_generator),
72 packet_buffer_(packet_buffer),
73 payload_splitter_(payload_splitter),
74 timestamp_scaler_(timestamp_scaler),
75 vad_(new PostDecodeVad()),
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +000076 expand_factory_(expand_factory),
77 accelerate_factory_(accelerate_factory),
78 preemptive_expand_factory_(preemptive_expand_factory),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000079 last_mode_(kModeNormal),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000080 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();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000106 if (create_components) {
107 SetSampleRateAndChannels(fs, 1); // Default is 1 channel.
108 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000109}
110
111NetEqImpl::~NetEqImpl() {
112 LOG(LS_INFO) << "Deleting NetEqImpl object.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000113}
114
115int NetEqImpl::InsertPacket(const WebRtcRTPHeader& rtp_header,
116 const uint8_t* payload,
117 int length_bytes,
118 uint32_t receive_timestamp) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000119 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000120 LOG(LS_VERBOSE) << "InsertPacket: ts=" << rtp_header.header.timestamp <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000121 ", sn=" << rtp_header.header.sequenceNumber <<
122 ", pt=" << static_cast<int>(rtp_header.header.payloadType) <<
123 ", ssrc=" << rtp_header.header.ssrc <<
124 ", len=" << length_bytes;
125 int error = InsertPacketInternal(rtp_header, payload, length_bytes,
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000126 receive_timestamp, false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000127 if (error != 0) {
128 LOG_FERR1(LS_WARNING, InsertPacketInternal, error);
129 error_code_ = error;
130 return kFail;
131 }
132 return kOK;
133}
134
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000135int NetEqImpl::InsertSyncPacket(const WebRtcRTPHeader& rtp_header,
136 uint32_t receive_timestamp) {
137 CriticalSectionScoped lock(crit_sect_.get());
138 LOG(LS_VERBOSE) << "InsertPacket-Sync: ts="
139 << rtp_header.header.timestamp <<
140 ", sn=" << rtp_header.header.sequenceNumber <<
141 ", pt=" << static_cast<int>(rtp_header.header.payloadType) <<
142 ", ssrc=" << rtp_header.header.ssrc;
143
144 const uint8_t kSyncPayload[] = { 's', 'y', 'n', 'c' };
145 int error = InsertPacketInternal(
146 rtp_header, kSyncPayload, sizeof(kSyncPayload), receive_timestamp, true);
147
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000148 if (error != 0) {
149 LOG_FERR1(LS_WARNING, InsertPacketInternal, error);
150 error_code_ = error;
151 return kFail;
152 }
153 return kOK;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000154}
155
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000156int NetEqImpl::GetAudio(size_t max_length, int16_t* output_audio,
157 int* samples_per_channel, int* num_channels,
158 NetEqOutputType* type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000159 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000160 LOG(LS_VERBOSE) << "GetAudio";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000161 int error = GetAudioInternal(max_length, output_audio, samples_per_channel,
162 num_channels);
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000163 LOG(LS_VERBOSE) << "Produced " << *samples_per_channel <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000164 " samples/channel for " << *num_channels << " channel(s)";
165 if (error != 0) {
166 LOG_FERR1(LS_WARNING, GetAudioInternal, error);
167 error_code_ = error;
168 return kFail;
169 }
170 if (type) {
171 *type = LastOutputType();
172 }
173 return kOK;
174}
175
176int NetEqImpl::RegisterPayloadType(enum NetEqDecoder codec,
177 uint8_t rtp_payload_type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000178 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000179 LOG_API2(static_cast<int>(rtp_payload_type), codec);
180 int ret = decoder_database_->RegisterPayload(rtp_payload_type, codec);
181 if (ret != DecoderDatabase::kOK) {
182 LOG_FERR2(LS_WARNING, RegisterPayload, rtp_payload_type, codec);
183 switch (ret) {
184 case DecoderDatabase::kInvalidRtpPayloadType:
185 error_code_ = kInvalidRtpPayloadType;
186 break;
187 case DecoderDatabase::kCodecNotSupported:
188 error_code_ = kCodecNotSupported;
189 break;
190 case DecoderDatabase::kDecoderExists:
191 error_code_ = kDecoderExists;
192 break;
193 default:
194 error_code_ = kOtherError;
195 }
196 return kFail;
197 }
198 return kOK;
199}
200
201int NetEqImpl::RegisterExternalDecoder(AudioDecoder* decoder,
202 enum NetEqDecoder codec,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000203 uint8_t rtp_payload_type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000204 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000205 LOG_API2(static_cast<int>(rtp_payload_type), codec);
206 if (!decoder) {
207 LOG(LS_ERROR) << "Cannot register external decoder with NULL pointer";
208 assert(false);
209 return kFail;
210 }
turaj@webrtc.orga596a382014-04-17 23:30:49 +0000211 const int sample_rate_hz = AudioDecoder::CodecSampleRateHz(codec);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000212 int ret = decoder_database_->InsertExternal(rtp_payload_type, codec,
213 sample_rate_hz, decoder);
214 if (ret != DecoderDatabase::kOK) {
215 LOG_FERR2(LS_WARNING, InsertExternal, rtp_payload_type, codec);
216 switch (ret) {
217 case DecoderDatabase::kInvalidRtpPayloadType:
218 error_code_ = kInvalidRtpPayloadType;
219 break;
220 case DecoderDatabase::kCodecNotSupported:
221 error_code_ = kCodecNotSupported;
222 break;
223 case DecoderDatabase::kDecoderExists:
224 error_code_ = kDecoderExists;
225 break;
226 case DecoderDatabase::kInvalidSampleRate:
227 error_code_ = kInvalidSampleRate;
228 break;
229 case DecoderDatabase::kInvalidPointer:
230 error_code_ = kInvalidPointer;
231 break;
232 default:
233 error_code_ = kOtherError;
234 }
235 return kFail;
236 }
237 return kOK;
238}
239
240int NetEqImpl::RemovePayloadType(uint8_t rtp_payload_type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000241 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000242 LOG_API1(static_cast<int>(rtp_payload_type));
243 int ret = decoder_database_->Remove(rtp_payload_type);
244 if (ret == DecoderDatabase::kOK) {
245 return kOK;
246 } else if (ret == DecoderDatabase::kDecoderNotFound) {
247 error_code_ = kDecoderNotFound;
248 } else {
249 error_code_ = kOtherError;
250 }
251 LOG_FERR1(LS_WARNING, Remove, rtp_payload_type);
252 return kFail;
253}
254
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000255bool NetEqImpl::SetMinimumDelay(int delay_ms) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000256 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000257 if (delay_ms >= 0 && delay_ms < 10000) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000258 assert(delay_manager_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000259 return delay_manager_->SetMinimumDelay(delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000260 }
261 return false;
262}
263
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000264bool NetEqImpl::SetMaximumDelay(int delay_ms) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000265 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000266 if (delay_ms >= 0 && delay_ms < 10000) {
267 assert(delay_manager_.get());
268 return delay_manager_->SetMaximumDelay(delay_ms);
269 }
270 return false;
271}
272
273int NetEqImpl::LeastRequiredDelayMs() const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000274 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000275 assert(delay_manager_.get());
276 return delay_manager_->least_required_delay_ms();
277}
278
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000279void NetEqImpl::SetPlayoutMode(NetEqPlayoutMode mode) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000280 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000281 if (!decision_logic_.get() || mode != decision_logic_->playout_mode()) {
282 // The reset() method calls delete for the old object.
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000283 CreateDecisionLogic(mode);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000284 }
285}
286
287NetEqPlayoutMode NetEqImpl::PlayoutMode() const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000288 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000289 assert(decision_logic_.get());
290 return decision_logic_->playout_mode();
291}
292
293int NetEqImpl::NetworkStatistics(NetEqNetworkStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000294 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000295 assert(decoder_database_.get());
296 const int total_samples_in_buffers = packet_buffer_->NumSamplesInBuffer(
297 decoder_database_.get(), decoder_frame_length_) +
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000298 static_cast<int>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000299 assert(delay_manager_.get());
300 assert(decision_logic_.get());
301 stats_.GetNetworkStatistics(fs_hz_, total_samples_in_buffers,
302 decoder_frame_length_, *delay_manager_.get(),
303 *decision_logic_.get(), stats);
304 return 0;
305}
306
307void NetEqImpl::WaitingTimes(std::vector<int>* waiting_times) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000308 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000309 stats_.WaitingTimes(waiting_times);
310}
311
312void NetEqImpl::GetRtcpStatistics(RtcpStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000313 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000314 if (stats) {
315 rtcp_.GetStatistics(false, stats);
316 }
317}
318
319void NetEqImpl::GetRtcpStatisticsNoReset(RtcpStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000320 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000321 if (stats) {
322 rtcp_.GetStatistics(true, stats);
323 }
324}
325
326void NetEqImpl::EnableVad() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000327 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000328 assert(vad_.get());
329 vad_->Enable();
330}
331
332void NetEqImpl::DisableVad() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000333 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000334 assert(vad_.get());
335 vad_->Disable();
336}
337
338uint32_t NetEqImpl::PlayoutTimestamp() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000339 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000340 return timestamp_scaler_->ToExternal(playout_timestamp_);
341}
342
343int NetEqImpl::LastError() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000344 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000345 return error_code_;
346}
347
348int NetEqImpl::LastDecoderError() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000349 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000350 return decoder_error_code_;
351}
352
353void NetEqImpl::FlushBuffers() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000354 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000355 LOG_API0();
356 packet_buffer_->Flush();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000357 assert(sync_buffer_.get());
358 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000359 sync_buffer_->Flush();
360 sync_buffer_->set_next_index(sync_buffer_->next_index() -
361 expand_->overlap_length());
362 // Set to wait for new codec.
363 first_packet_ = true;
364}
365
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000366void NetEqImpl::PacketBufferStatistics(int* current_num_packets,
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000367 int* max_num_packets) const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000368 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000369 packet_buffer_->BufferStat(current_num_packets, max_num_packets);
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000370}
371
turaj@webrtc.orgff43c852013-09-25 00:07:27 +0000372int NetEqImpl::DecodedRtpInfo(int* sequence_number, uint32_t* timestamp) const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000373 CriticalSectionScoped lock(crit_sect_.get());
minyue@webrtc.orgd7301772013-08-29 00:58:14 +0000374 if (decoded_packet_sequence_number_ < 0)
375 return -1;
376 *sequence_number = decoded_packet_sequence_number_;
377 *timestamp = decoded_packet_timestamp_;
378 return 0;
379}
380
turaj@webrtc.orgff43c852013-09-25 00:07:27 +0000381void NetEqImpl::SetBackgroundNoiseMode(NetEqBackgroundNoiseMode mode) {
382 CriticalSectionScoped lock(crit_sect_.get());
383 assert(background_noise_.get());
384 background_noise_->set_mode(mode);
385}
turaj@webrtc.org036b7432013-09-11 18:45:02 +0000386
387NetEqBackgroundNoiseMode NetEqImpl::BackgroundNoiseMode() const {
turaj@webrtc.orgff43c852013-09-25 00:07:27 +0000388 CriticalSectionScoped lock(crit_sect_.get());
389 assert(background_noise_.get());
390 return background_noise_->mode();
turaj@webrtc.org036b7432013-09-11 18:45:02 +0000391}
392
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000393const SyncBuffer* NetEqImpl::sync_buffer_for_test() const {
394 CriticalSectionScoped lock(crit_sect_.get());
395 return sync_buffer_.get();
396}
397
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000398// Methods below this line are private.
399
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000400int NetEqImpl::InsertPacketInternal(const WebRtcRTPHeader& rtp_header,
401 const uint8_t* payload,
402 int length_bytes,
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000403 uint32_t receive_timestamp,
404 bool is_sync_packet) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000405 if (!payload) {
406 LOG_F(LS_ERROR) << "payload == NULL";
407 return kInvalidPointer;
408 }
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000409 // Sanity checks for sync-packets.
410 if (is_sync_packet) {
411 if (decoder_database_->IsDtmf(rtp_header.header.payloadType) ||
412 decoder_database_->IsRed(rtp_header.header.payloadType) ||
413 decoder_database_->IsComfortNoise(rtp_header.header.payloadType)) {
414 LOG_F(LS_ERROR) << "Sync-packet with an unacceptable payload type "
415 << rtp_header.header.payloadType;
416 return kSyncPacketNotAccepted;
417 }
418 if (first_packet_ ||
419 rtp_header.header.payloadType != current_rtp_payload_type_ ||
420 rtp_header.header.ssrc != ssrc_) {
421 // Even if |current_rtp_payload_type_| is 0xFF, sync-packet isn't
422 // accepted.
423 LOG_F(LS_ERROR) << "Changing codec, SSRC or first packet "
424 "with sync-packet.";
425 return kSyncPacketNotAccepted;
426 }
427 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000428 PacketList packet_list;
429 RTPHeader main_header;
430 {
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000431 // Convert to Packet.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000432 // Create |packet| within this separate scope, since it should not be used
433 // directly once it's been inserted in the packet list. This way, |packet|
434 // is not defined outside of this block.
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000435 Packet* packet = new Packet;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000436 packet->header.markerBit = false;
437 packet->header.payloadType = rtp_header.header.payloadType;
438 packet->header.sequenceNumber = rtp_header.header.sequenceNumber;
439 packet->header.timestamp = rtp_header.header.timestamp;
440 packet->header.ssrc = rtp_header.header.ssrc;
441 packet->header.numCSRCs = 0;
442 packet->payload_length = length_bytes;
443 packet->primary = true;
444 packet->waiting_time = 0;
445 packet->payload = new uint8_t[packet->payload_length];
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000446 packet->sync_packet = is_sync_packet;
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +0000447 if (!packet->payload) {
448 LOG_F(LS_ERROR) << "Payload pointer is NULL.";
449 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000450 assert(payload); // Already checked above.
451 memcpy(packet->payload, payload, packet->payload_length);
452 // Insert packet in a packet list.
453 packet_list.push_back(packet);
454 // Save main payloads header for later.
455 memcpy(&main_header, &packet->header, sizeof(main_header));
456 }
457
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000458 bool update_sample_rate_and_channels = false;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000459 // Reinitialize NetEq if it's needed (changed SSRC or first call).
460 if ((main_header.ssrc != ssrc_) || first_packet_) {
461 rtcp_.Init(main_header.sequenceNumber);
462 first_packet_ = false;
463
464 // Flush the packet buffer and DTMF buffer.
465 packet_buffer_->Flush();
466 dtmf_buffer_->Flush();
467
468 // Store new SSRC.
469 ssrc_ = main_header.ssrc;
470
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000471 // Update audio buffer timestamp.
472 sync_buffer_->IncreaseEndTimestamp(main_header.timestamp - timestamp_);
473
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000474 // Update codecs.
475 timestamp_ = main_header.timestamp;
476 current_rtp_payload_type_ = main_header.payloadType;
477
478 // Set MCU to update codec on next SignalMCU call.
479 new_codec_ = true;
480
481 // Reset timestamp scaling.
482 timestamp_scaler_->Reset();
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000483
484 // Triger an update of sampling rate and the number of channels.
485 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000486 }
487
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000488 // Update RTCP statistics, only for regular packets.
489 if (!is_sync_packet)
490 rtcp_.Update(main_header, receive_timestamp);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000491
492 // Check for RED payload type, and separate payloads into several packets.
493 if (decoder_database_->IsRed(main_header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000494 assert(!is_sync_packet); // We had a sanity check for this.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000495 if (payload_splitter_->SplitRed(&packet_list) != PayloadSplitter::kOK) {
496 LOG_FERR1(LS_WARNING, SplitRed, packet_list.size());
497 PacketBuffer::DeleteAllPackets(&packet_list);
498 return kRedundancySplitError;
499 }
500 // Only accept a few RED payloads of the same type as the main data,
501 // DTMF events and CNG.
502 payload_splitter_->CheckRedPayloads(&packet_list, *decoder_database_);
503 // Update the stored main payload header since the main payload has now
504 // changed.
505 memcpy(&main_header, &packet_list.front()->header, sizeof(main_header));
506 }
507
508 // Check payload types.
509 if (decoder_database_->CheckPayloadTypes(packet_list) ==
510 DecoderDatabase::kDecoderNotFound) {
511 LOG_FERR1(LS_WARNING, CheckPayloadTypes, packet_list.size());
512 PacketBuffer::DeleteAllPackets(&packet_list);
513 return kUnknownRtpPayloadType;
514 }
515
516 // Scale timestamp to internal domain (only for some codecs).
517 timestamp_scaler_->ToInternal(&packet_list);
518
519 // Process DTMF payloads. Cycle through the list of packets, and pick out any
520 // DTMF payloads found.
521 PacketList::iterator it = packet_list.begin();
522 while (it != packet_list.end()) {
523 Packet* current_packet = (*it);
524 assert(current_packet);
525 assert(current_packet->payload);
526 if (decoder_database_->IsDtmf(current_packet->header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000527 assert(!current_packet->sync_packet); // We had a sanity check for this.
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000528 DtmfEvent event;
529 int ret = DtmfBuffer::ParseEvent(
530 current_packet->header.timestamp,
531 current_packet->payload,
532 current_packet->payload_length,
533 &event);
534 if (ret != DtmfBuffer::kOK) {
535 LOG_FERR2(LS_WARNING, ParseEvent, ret,
536 current_packet->payload_length);
537 PacketBuffer::DeleteAllPackets(&packet_list);
538 return kDtmfParsingError;
539 }
540 if (dtmf_buffer_->InsertEvent(event) != DtmfBuffer::kOK) {
541 LOG_FERR0(LS_WARNING, InsertEvent);
542 PacketBuffer::DeleteAllPackets(&packet_list);
543 return kDtmfInsertError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000544 }
545 // TODO(hlundin): Let the destructor of Packet handle the payload.
546 delete [] current_packet->payload;
547 delete current_packet;
548 it = packet_list.erase(it);
549 } else {
550 ++it;
551 }
552 }
553
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000554 // Check for FEC in packets, and separate payloads into several packets.
555 int ret = payload_splitter_->SplitFec(&packet_list, decoder_database_.get());
556 if (ret != PayloadSplitter::kOK) {
557 LOG_FERR1(LS_WARNING, SplitFec, packet_list.size());
558 PacketBuffer::DeleteAllPackets(&packet_list);
559 switch (ret) {
560 case PayloadSplitter::kUnknownPayloadType:
561 return kUnknownRtpPayloadType;
562 default:
563 return kOtherError;
564 }
565 }
566
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000567 // Split payloads into smaller chunks. This also verifies that all payloads
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000568 // are of a known payload type. SplitAudio() method is protected against
569 // sync-packets.
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +0000570 ret = payload_splitter_->SplitAudio(&packet_list, *decoder_database_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000571 if (ret != PayloadSplitter::kOK) {
572 LOG_FERR1(LS_WARNING, SplitAudio, packet_list.size());
573 PacketBuffer::DeleteAllPackets(&packet_list);
574 switch (ret) {
575 case PayloadSplitter::kUnknownPayloadType:
576 return kUnknownRtpPayloadType;
577 case PayloadSplitter::kFrameSplitError:
578 return kFrameSplitError;
579 default:
580 return kOtherError;
581 }
582 }
583
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000584 // Update bandwidth estimate, if the packet is not sync-packet.
585 if (!packet_list.empty() && !packet_list.front()->sync_packet) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000586 // The list can be empty here if we got nothing but DTMF payloads.
587 AudioDecoder* decoder =
588 decoder_database_->GetDecoder(main_header.payloadType);
589 assert(decoder); // Should always get a valid object, since we have
590 // already checked that the payload types are known.
591 decoder->IncomingPacket(packet_list.front()->payload,
592 packet_list.front()->payload_length,
593 packet_list.front()->header.sequenceNumber,
594 packet_list.front()->header.timestamp,
595 receive_timestamp);
596 }
597
598 // Insert packets in buffer.
599 int temp_bufsize = packet_buffer_->NumPacketsInBuffer();
600 ret = packet_buffer_->InsertPacketList(
601 &packet_list,
602 *decoder_database_,
603 &current_rtp_payload_type_,
604 &current_cng_rtp_payload_type_);
605 if (ret == PacketBuffer::kFlushed) {
606 // Reset DSP timestamp etc. if packet buffer flushed.
607 new_codec_ = true;
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000608 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000609 LOG_F(LS_WARNING) << "Packet buffer flushed";
610 } else if (ret != PacketBuffer::kOK) {
611 LOG_FERR1(LS_WARNING, InsertPacketList, packet_list.size());
612 PacketBuffer::DeleteAllPackets(&packet_list);
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000613 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000614 }
615 if (current_rtp_payload_type_ != 0xFF) {
616 const DecoderDatabase::DecoderInfo* dec_info =
617 decoder_database_->GetDecoderInfo(current_rtp_payload_type_);
618 if (!dec_info) {
619 assert(false); // Already checked that the payload type is known.
620 }
621 }
622
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000623 if (update_sample_rate_and_channels && !packet_buffer_->Empty()) {
624 // We do not use |current_rtp_payload_type_| to |set payload_type|, but
625 // get the next RTP header from |packet_buffer_| to obtain the payload type.
626 // The reason for it is the following corner case. If NetEq receives a
627 // CNG packet with a sample rate different than the current CNG then it
628 // flushes its buffer, assuming send codec must have been changed. However,
629 // payload type of the hypothetically new send codec is not known.
630 const RTPHeader* rtp_header = packet_buffer_->NextRtpHeader();
631 assert(rtp_header);
632 int payload_type = rtp_header->payloadType;
633 AudioDecoder* decoder = decoder_database_->GetDecoder(payload_type);
634 assert(decoder); // Payloads are already checked to be valid.
635 const DecoderDatabase::DecoderInfo* decoder_info =
636 decoder_database_->GetDecoderInfo(payload_type);
637 assert(decoder_info);
638 if (decoder_info->fs_hz != fs_hz_ ||
639 decoder->channels() != algorithm_buffer_->Channels())
640 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->channels());
641 }
642
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000643 // TODO(hlundin): Move this code to DelayManager class.
644 const DecoderDatabase::DecoderInfo* dec_info =
645 decoder_database_->GetDecoderInfo(main_header.payloadType);
646 assert(dec_info); // Already checked that the payload type is known.
647 delay_manager_->LastDecoderType(dec_info->codec_type);
648 if (delay_manager_->last_pack_cng_or_dtmf() == 0) {
649 // Calculate the total speech length carried in each packet.
650 temp_bufsize = packet_buffer_->NumPacketsInBuffer() - temp_bufsize;
651 temp_bufsize *= decoder_frame_length_;
652
653 if ((temp_bufsize > 0) &&
654 (temp_bufsize != decision_logic_->packet_length_samples())) {
655 decision_logic_->set_packet_length_samples(temp_bufsize);
656 delay_manager_->SetPacketAudioLength((1000 * temp_bufsize) / fs_hz_);
657 }
658
659 // Update statistics.
pbos@webrtc.org0946a562013-04-09 00:28:06 +0000660 if ((int32_t) (main_header.timestamp - timestamp_) >= 0 &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000661 !new_codec_) {
662 // Only update statistics if incoming packet is not older than last played
663 // out packet, and if new codec flag is not set.
664 delay_manager_->Update(main_header.sequenceNumber, main_header.timestamp,
665 fs_hz_);
666 }
667 } else if (delay_manager_->last_pack_cng_or_dtmf() == -1) {
668 // This is first "normal" packet after CNG or DTMF.
669 // Reset packet time counter and measure time until next packet,
670 // but don't update statistics.
671 delay_manager_->set_last_pack_cng_or_dtmf(0);
672 delay_manager_->ResetPacketIatCount();
673 }
674 return 0;
675}
676
677int NetEqImpl::GetAudioInternal(size_t max_length, int16_t* output,
678 int* samples_per_channel, int* num_channels) {
679 PacketList packet_list;
680 DtmfEvent dtmf_event;
681 Operations operation;
682 bool play_dtmf;
683 int return_value = GetDecision(&operation, &packet_list, &dtmf_event,
684 &play_dtmf);
685 if (return_value != 0) {
686 LOG_FERR1(LS_WARNING, GetDecision, return_value);
687 assert(false);
688 last_mode_ = kModeError;
689 return return_value;
690 }
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000691 LOG(LS_VERBOSE) << "GetDecision returned operation=" << operation <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000692 " and " << packet_list.size() << " packet(s)";
693
694 AudioDecoder::SpeechType speech_type;
695 int length = 0;
696 int decode_return_value = Decode(&packet_list, &operation,
697 &length, &speech_type);
698
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000699 assert(vad_.get());
700 bool sid_frame_available =
701 (operation == kRfc3389Cng && !packet_list.empty());
702 vad_->Update(decoded_buffer_.get(), length, speech_type,
703 sid_frame_available, fs_hz_);
704
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000705 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000706 switch (operation) {
707 case kNormal: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000708 DoNormal(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000709 break;
710 }
711 case kMerge: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000712 DoMerge(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000713 break;
714 }
715 case kExpand: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000716 return_value = DoExpand(play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000717 break;
718 }
719 case kAccelerate: {
720 return_value = DoAccelerate(decoded_buffer_.get(), length, speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000721 play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000722 break;
723 }
724 case kPreemptiveExpand: {
725 return_value = DoPreemptiveExpand(decoded_buffer_.get(), length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000726 speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000727 break;
728 }
729 case kRfc3389Cng:
730 case kRfc3389CngNoPacket: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000731 return_value = DoRfc3389Cng(&packet_list, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000732 break;
733 }
734 case kCodecInternalCng: {
735 // This handles the case when there is no transmission and the decoder
736 // should produce internal comfort noise.
737 // TODO(hlundin): Write test for codec-internal CNG.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000738 DoCodecInternalCng();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000739 break;
740 }
741 case kDtmf: {
742 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000743 return_value = DoDtmf(dtmf_event, &play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000744 break;
745 }
746 case kAlternativePlc: {
747 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000748 DoAlternativePlc(false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000749 break;
750 }
751 case kAlternativePlcIncreaseTimestamp: {
752 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000753 DoAlternativePlc(true);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000754 break;
755 }
756 case kAudioRepetitionIncreaseTimestamp: {
757 // TODO(hlundin): Write test for this.
758 sync_buffer_->IncreaseEndTimestamp(output_size_samples_);
759 // Skipping break on purpose. Execution should move on into the
760 // next case.
761 }
762 case kAudioRepetition: {
763 // TODO(hlundin): Write test for this.
764 // Copy last |output_size_samples_| from |sync_buffer_| to
765 // |algorithm_buffer|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000766 algorithm_buffer_->PushBackFromIndex(
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000767 *sync_buffer_, sync_buffer_->Size() - output_size_samples_);
768 expand_->Reset();
769 break;
770 }
771 case kUndefined: {
772 LOG_F(LS_ERROR) << "Invalid operation kUndefined.";
773 assert(false); // This should not happen.
774 last_mode_ = kModeError;
775 return kInvalidOperation;
776 }
777 } // End of switch.
778 if (return_value < 0) {
779 return return_value;
780 }
781
782 if (last_mode_ != kModeRfc3389Cng) {
783 comfort_noise_->Reset();
784 }
785
786 // Copy from |algorithm_buffer| to |sync_buffer_|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000787 sync_buffer_->PushBack(*algorithm_buffer_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000788
789 // Extract data from |sync_buffer_| to |output|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000790 size_t num_output_samples_per_channel = output_size_samples_;
791 size_t num_output_samples = output_size_samples_ * sync_buffer_->Channels();
792 if (num_output_samples > max_length) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000793 LOG(LS_WARNING) << "Output array is too short. " << max_length << " < " <<
794 output_size_samples_ << " * " << sync_buffer_->Channels();
795 num_output_samples = max_length;
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000796 num_output_samples_per_channel = static_cast<int>(
797 max_length / sync_buffer_->Channels());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000798 }
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000799 int samples_from_sync = static_cast<int>(
800 sync_buffer_->GetNextAudioInterleaved(num_output_samples_per_channel,
801 output));
802 *num_channels = static_cast<int>(sync_buffer_->Channels());
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000803 LOG(LS_VERBOSE) << "Sync buffer (" << *num_channels << " channel(s)):" <<
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000804 " insert " << algorithm_buffer_->Size() << " samples, extract " <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000805 samples_from_sync << " samples";
806 if (samples_from_sync != output_size_samples_) {
807 LOG_F(LS_ERROR) << "samples_from_sync != output_size_samples_";
minyue@webrtc.orgdb1cefc2013-08-13 01:39:21 +0000808 // TODO(minyue): treatment of under-run, filling zeros
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000809 memset(output, 0, num_output_samples * sizeof(int16_t));
810 *samples_per_channel = output_size_samples_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000811 return kSampleUnderrun;
812 }
813 *samples_per_channel = output_size_samples_;
814
815 // Should always have overlap samples left in the |sync_buffer_|.
816 assert(sync_buffer_->FutureLength() >= expand_->overlap_length());
817
818 if (play_dtmf) {
819 return_value = DtmfOverdub(dtmf_event, sync_buffer_->Channels(), output);
820 }
821
822 // Update the background noise parameters if last operation wrote data
823 // straight from the decoder to the |sync_buffer_|. That is, none of the
824 // operations that modify the signal can be followed by a parameter update.
825 if ((last_mode_ == kModeNormal) ||
826 (last_mode_ == kModeAccelerateFail) ||
827 (last_mode_ == kModePreemptiveExpandFail) ||
828 (last_mode_ == kModeRfc3389Cng) ||
829 (last_mode_ == kModeCodecInternalCng)) {
830 background_noise_->Update(*sync_buffer_, *vad_.get());
831 }
832
833 if (operation == kDtmf) {
834 // DTMF data was written the end of |sync_buffer_|.
835 // Update index to end of DTMF data in |sync_buffer_|.
836 sync_buffer_->set_dtmf_index(sync_buffer_->Size());
837 }
838
henrik.lundin@webrtc.orged865b52014-03-06 10:28:07 +0000839 if (last_mode_ != kModeExpand) {
840 // If last operation was not expand, calculate the |playout_timestamp_| from
841 // the |sync_buffer_|. However, do not update the |playout_timestamp_| if it
842 // would be moved "backwards".
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000843 uint32_t temp_timestamp = sync_buffer_->end_timestamp() -
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000844 static_cast<uint32_t>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000845 if (static_cast<int32_t>(temp_timestamp - playout_timestamp_) > 0) {
846 playout_timestamp_ = temp_timestamp;
847 }
848 } else {
849 // Use dead reckoning to estimate the |playout_timestamp_|.
850 playout_timestamp_ += output_size_samples_;
851 }
852
853 if (decode_return_value) return decode_return_value;
854 return return_value;
855}
856
857int NetEqImpl::GetDecision(Operations* operation,
858 PacketList* packet_list,
859 DtmfEvent* dtmf_event,
860 bool* play_dtmf) {
861 // Initialize output variables.
862 *play_dtmf = false;
863 *operation = kUndefined;
864
865 // Increment time counters.
866 packet_buffer_->IncrementWaitingTimes();
867 stats_.IncreaseCounter(output_size_samples_, fs_hz_);
868
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000869 assert(sync_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000870 uint32_t end_timestamp = sync_buffer_->end_timestamp();
871 if (!new_codec_) {
872 packet_buffer_->DiscardOldPackets(end_timestamp);
873 }
874 const RTPHeader* header = packet_buffer_->NextRtpHeader();
875
henrik.lundin@webrtc.orgca8cb952014-03-12 10:26:52 +0000876 if (decision_logic_->CngRfc3389On() || last_mode_ == kModeRfc3389Cng) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000877 // Because of timestamp peculiarities, we have to "manually" disallow using
878 // a CNG packet with the same timestamp as the one that was last played.
879 // This can happen when using redundancy and will cause the timing to shift.
henrik.lundin@webrtc.org24779fe2014-03-14 12:40:05 +0000880 while (header && decoder_database_->IsComfortNoise(header->payloadType) &&
881 (end_timestamp >= header->timestamp ||
882 end_timestamp + decision_logic_->generated_noise_samples() >
883 header->timestamp)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000884 // Don't use this packet, discard it.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000885 if (packet_buffer_->DiscardNextPacket() != PacketBuffer::kOK) {
886 assert(false); // Must be ok by design.
887 }
888 // Check buffer again.
889 if (!new_codec_) {
890 packet_buffer_->DiscardOldPackets(end_timestamp);
891 }
892 header = packet_buffer_->NextRtpHeader();
893 }
894 }
895
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000896 assert(expand_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000897 const int samples_left = static_cast<int>(sync_buffer_->FutureLength() -
898 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000899 if (last_mode_ == kModeAccelerateSuccess ||
900 last_mode_ == kModeAccelerateLowEnergy ||
901 last_mode_ == kModePreemptiveExpandSuccess ||
902 last_mode_ == kModePreemptiveExpandLowEnergy) {
903 // Subtract (samples_left + output_size_samples_) from sampleMemory.
904 decision_logic_->AddSampleMemory(-(samples_left + output_size_samples_));
905 }
906
907 // Check if it is time to play a DTMF event.
908 if (dtmf_buffer_->GetEvent(end_timestamp +
909 decision_logic_->generated_noise_samples(),
910 dtmf_event)) {
911 *play_dtmf = true;
912 }
913
914 // Get instruction.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000915 assert(sync_buffer_.get());
916 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000917 *operation = decision_logic_->GetDecision(*sync_buffer_,
918 *expand_,
919 decoder_frame_length_,
920 header,
921 last_mode_,
922 *play_dtmf,
923 &reset_decoder_);
924
925 // Check if we already have enough samples in the |sync_buffer_|. If so,
926 // change decision to normal, unless the decision was merge, accelerate, or
927 // preemptive expand.
928 if (samples_left >= output_size_samples_ &&
929 *operation != kMerge &&
930 *operation != kAccelerate &&
931 *operation != kPreemptiveExpand) {
932 *operation = kNormal;
933 return 0;
934 }
935
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000936 decision_logic_->ExpandDecision(*operation);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000937
938 // Check conditions for reset.
939 if (new_codec_ || *operation == kUndefined) {
940 // The only valid reason to get kUndefined is that new_codec_ is set.
941 assert(new_codec_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000942 if (*play_dtmf && !header) {
943 timestamp_ = dtmf_event->timestamp;
944 } else {
945 assert(header);
946 if (!header) {
947 LOG_F(LS_ERROR) << "Packet missing where it shouldn't.";
948 return -1;
949 }
950 timestamp_ = header->timestamp;
951 if (*operation == kRfc3389CngNoPacket
952#ifndef LEGACY_BITEXACT
953 // Without this check, it can happen that a non-CNG packet is sent to
954 // the CNG decoder as if it was a SID frame. This is clearly a bug,
955 // but is kept for now to maintain bit-exactness with the test
956 // vectors.
957 && decoder_database_->IsComfortNoise(header->payloadType)
958#endif
959 ) {
960 // Change decision to CNG packet, since we do have a CNG packet, but it
961 // was considered too early to use. Now, use it anyway.
962 *operation = kRfc3389Cng;
963 } else if (*operation != kRfc3389Cng) {
964 *operation = kNormal;
965 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000966 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000967 // Adjust |sync_buffer_| timestamp before setting |end_timestamp| to the
968 // new value.
969 sync_buffer_->IncreaseEndTimestamp(timestamp_ - end_timestamp);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000970 end_timestamp = timestamp_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000971 new_codec_ = false;
972 decision_logic_->SoftReset();
973 buffer_level_filter_->Reset();
974 delay_manager_->Reset();
975 stats_.ResetMcu();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000976 }
977
978 int required_samples = output_size_samples_;
979 const int samples_10_ms = 80 * fs_mult_;
980 const int samples_20_ms = 2 * samples_10_ms;
981 const int samples_30_ms = 3 * samples_10_ms;
982
983 switch (*operation) {
984 case kExpand: {
985 timestamp_ = end_timestamp;
986 return 0;
987 }
988 case kRfc3389CngNoPacket:
989 case kCodecInternalCng: {
990 return 0;
991 }
992 case kDtmf: {
993 // TODO(hlundin): Write test for this.
994 // Update timestamp.
995 timestamp_ = end_timestamp;
996 if (decision_logic_->generated_noise_samples() > 0 &&
997 last_mode_ != kModeDtmf) {
998 // Make a jump in timestamp due to the recently played comfort noise.
999 uint32_t timestamp_jump = decision_logic_->generated_noise_samples();
1000 sync_buffer_->IncreaseEndTimestamp(timestamp_jump);
1001 timestamp_ += timestamp_jump;
1002 }
1003 decision_logic_->set_generated_noise_samples(0);
1004 return 0;
1005 }
1006 case kAccelerate: {
1007 // In order to do a accelerate we need at least 30 ms of audio data.
1008 if (samples_left >= samples_30_ms) {
1009 // Already have enough data, so we do not need to extract any more.
1010 decision_logic_->set_sample_memory(samples_left);
1011 decision_logic_->set_prev_time_scale(true);
1012 return 0;
1013 } else if (samples_left >= samples_10_ms &&
1014 decoder_frame_length_ >= samples_30_ms) {
1015 // Avoid decoding more data as it might overflow the playout buffer.
1016 *operation = kNormal;
1017 return 0;
1018 } else if (samples_left < samples_20_ms &&
1019 decoder_frame_length_ < samples_30_ms) {
1020 // Build up decoded data by decoding at least 20 ms of audio data. Do
1021 // not perform accelerate yet, but wait until we only need to do one
1022 // decoding.
1023 required_samples = 2 * output_size_samples_;
1024 *operation = kNormal;
1025 }
1026 // If none of the above is true, we have one of two possible situations:
1027 // (1) 20 ms <= samples_left < 30 ms and decoder_frame_length_ < 30 ms; or
1028 // (2) samples_left < 10 ms and decoder_frame_length_ >= 30 ms.
1029 // In either case, we move on with the accelerate decision, and decode one
1030 // frame now.
1031 break;
1032 }
1033 case kPreemptiveExpand: {
1034 // In order to do a preemptive expand we need at least 30 ms of decoded
1035 // audio data.
1036 if ((samples_left >= samples_30_ms) ||
1037 (samples_left >= samples_10_ms &&
1038 decoder_frame_length_ >= samples_30_ms)) {
1039 // Already have enough data, so we do not need to extract any more.
1040 // Or, avoid decoding more data as it might overflow the playout buffer.
1041 // Still try preemptive expand, though.
1042 decision_logic_->set_sample_memory(samples_left);
1043 decision_logic_->set_prev_time_scale(true);
1044 return 0;
1045 }
1046 if (samples_left < samples_20_ms &&
1047 decoder_frame_length_ < samples_30_ms) {
1048 // Build up decoded data by decoding at least 20 ms of audio data.
1049 // Still try to perform preemptive expand.
1050 required_samples = 2 * output_size_samples_;
1051 }
1052 // Move on with the preemptive expand decision.
1053 break;
1054 }
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001055 case kMerge: {
1056 required_samples =
1057 std::max(merge_->RequiredFutureSamples(), required_samples);
1058 break;
1059 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001060 default: {
1061 // Do nothing.
1062 }
1063 }
1064
1065 // Get packets from buffer.
1066 int extracted_samples = 0;
1067 if (header &&
1068 *operation != kAlternativePlc &&
1069 *operation != kAlternativePlcIncreaseTimestamp &&
1070 *operation != kAudioRepetition &&
1071 *operation != kAudioRepetitionIncreaseTimestamp) {
1072 sync_buffer_->IncreaseEndTimestamp(header->timestamp - end_timestamp);
1073 if (decision_logic_->CngOff()) {
1074 // Adjustment of timestamp only corresponds to an actual packet loss
1075 // if comfort noise is not played. If comfort noise was just played,
1076 // this adjustment of timestamp is only done to get back in sync with the
1077 // stream timestamp; no loss to report.
1078 stats_.LostSamples(header->timestamp - end_timestamp);
1079 }
1080
1081 if (*operation != kRfc3389Cng) {
1082 // We are about to decode and use a non-CNG packet.
1083 decision_logic_->SetCngOff();
1084 }
1085 // Reset CNG timestamp as a new packet will be delivered.
1086 // (Also if this is a CNG packet, since playedOutTS is updated.)
1087 decision_logic_->set_generated_noise_samples(0);
1088
1089 extracted_samples = ExtractPackets(required_samples, packet_list);
1090 if (extracted_samples < 0) {
1091 LOG_F(LS_WARNING) << "Failed to extract packets from buffer.";
1092 return kPacketBufferCorruption;
1093 }
1094 }
1095
1096 if (*operation == kAccelerate ||
1097 *operation == kPreemptiveExpand) {
1098 decision_logic_->set_sample_memory(samples_left + extracted_samples);
1099 decision_logic_->set_prev_time_scale(true);
1100 }
1101
1102 if (*operation == kAccelerate) {
1103 // Check that we have enough data (30ms) to do accelerate.
1104 if (extracted_samples + samples_left < samples_30_ms) {
1105 // TODO(hlundin): Write test for this.
1106 // Not enough, do normal operation instead.
1107 *operation = kNormal;
1108 }
1109 }
1110
1111 timestamp_ = end_timestamp;
1112 return 0;
1113}
1114
1115int NetEqImpl::Decode(PacketList* packet_list, Operations* operation,
1116 int* decoded_length,
1117 AudioDecoder::SpeechType* speech_type) {
1118 *speech_type = AudioDecoder::kSpeech;
1119 AudioDecoder* decoder = NULL;
1120 if (!packet_list->empty()) {
1121 const Packet* packet = packet_list->front();
1122 int payload_type = packet->header.payloadType;
1123 if (!decoder_database_->IsComfortNoise(payload_type)) {
1124 decoder = decoder_database_->GetDecoder(payload_type);
1125 assert(decoder);
1126 if (!decoder) {
1127 LOG_FERR1(LS_WARNING, GetDecoder, payload_type);
1128 PacketBuffer::DeleteAllPackets(packet_list);
1129 return kDecoderNotFound;
1130 }
1131 bool decoder_changed;
1132 decoder_database_->SetActiveDecoder(payload_type, &decoder_changed);
1133 if (decoder_changed) {
1134 // We have a new decoder. Re-init some values.
1135 const DecoderDatabase::DecoderInfo* decoder_info = decoder_database_
1136 ->GetDecoderInfo(payload_type);
1137 assert(decoder_info);
1138 if (!decoder_info) {
1139 LOG_FERR1(LS_WARNING, GetDecoderInfo, payload_type);
1140 PacketBuffer::DeleteAllPackets(packet_list);
1141 return kDecoderNotFound;
1142 }
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001143 // If sampling rate or number of channels has changed, we need to make
1144 // a reset.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001145 if (decoder_info->fs_hz != fs_hz_ ||
1146 decoder->channels() != algorithm_buffer_->Channels()) {
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001147 // TODO(tlegrand): Add unittest to cover this event.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001148 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->channels());
1149 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001150 sync_buffer_->set_end_timestamp(timestamp_);
1151 playout_timestamp_ = timestamp_;
1152 }
1153 }
1154 }
1155
1156 if (reset_decoder_) {
1157 // TODO(hlundin): Write test for this.
1158 // Reset decoder.
1159 if (decoder) {
1160 decoder->Init();
1161 }
1162 // Reset comfort noise decoder.
1163 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
1164 if (cng_decoder) {
1165 cng_decoder->Init();
1166 }
1167 reset_decoder_ = false;
1168 }
1169
1170#ifdef LEGACY_BITEXACT
1171 // Due to a bug in old SignalMCU, it could happen that CNG operation was
1172 // decided, but a speech packet was provided. The speech packet will be used
1173 // to update the comfort noise decoder, as if it was a SID frame, which is
1174 // clearly wrong.
1175 if (*operation == kRfc3389Cng) {
1176 return 0;
1177 }
1178#endif
1179
1180 *decoded_length = 0;
1181 // Update codec-internal PLC state.
1182 if ((*operation == kMerge) && decoder && decoder->HasDecodePlc()) {
1183 decoder->DecodePlc(1, &decoded_buffer_[*decoded_length]);
1184 }
1185
1186 int return_value = DecodeLoop(packet_list, operation, decoder,
1187 decoded_length, speech_type);
1188
1189 if (*decoded_length < 0) {
1190 // Error returned from the decoder.
1191 *decoded_length = 0;
1192 sync_buffer_->IncreaseEndTimestamp(decoder_frame_length_);
1193 int error_code = 0;
1194 if (decoder)
1195 error_code = decoder->ErrorCode();
1196 if (error_code != 0) {
1197 // Got some error code from the decoder.
1198 decoder_error_code_ = error_code;
1199 return_value = kDecoderErrorCode;
1200 } else {
1201 // Decoder does not implement error codes. Return generic error.
1202 return_value = kOtherDecoderError;
1203 }
1204 LOG_FERR2(LS_WARNING, DecodeLoop, error_code, packet_list->size());
1205 *operation = kExpand; // Do expansion to get data instead.
1206 }
1207 if (*speech_type != AudioDecoder::kComfortNoise) {
1208 // Don't increment timestamp if codec returned CNG speech type
1209 // since in this case, the we will increment the CNGplayedTS counter.
1210 // Increase with number of samples per channel.
1211 assert(*decoded_length == 0 ||
1212 (decoder && decoder->channels() == sync_buffer_->Channels()));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001213 sync_buffer_->IncreaseEndTimestamp(
1214 *decoded_length / static_cast<int>(sync_buffer_->Channels()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001215 }
1216 return return_value;
1217}
1218
1219int NetEqImpl::DecodeLoop(PacketList* packet_list, Operations* operation,
1220 AudioDecoder* decoder, int* decoded_length,
1221 AudioDecoder::SpeechType* speech_type) {
1222 Packet* packet = NULL;
1223 if (!packet_list->empty()) {
1224 packet = packet_list->front();
1225 }
1226 // Do decoding.
1227 while (packet &&
1228 !decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1229 assert(decoder); // At this point, we must have a decoder object.
1230 // The number of channels in the |sync_buffer_| should be the same as the
1231 // number decoder channels.
1232 assert(sync_buffer_->Channels() == decoder->channels());
1233 assert(decoded_buffer_length_ >= kMaxFrameSize * decoder->channels());
1234 assert(*operation == kNormal || *operation == kAccelerate ||
1235 *operation == kMerge || *operation == kPreemptiveExpand);
1236 packet_list->pop_front();
henrik.lundin@webrtc.org63464a92013-01-30 09:41:56 +00001237 int payload_length = packet->payload_length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001238 int16_t decode_length;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +00001239 if (packet->sync_packet) {
1240 // Decode to silence with the same frame size as the last decode.
1241 LOG(LS_VERBOSE) << "Decoding sync-packet: " <<
1242 " ts=" << packet->header.timestamp <<
1243 ", sn=" << packet->header.sequenceNumber <<
1244 ", pt=" << static_cast<int>(packet->header.payloadType) <<
1245 ", ssrc=" << packet->header.ssrc <<
1246 ", len=" << packet->payload_length;
1247 memset(&decoded_buffer_[*decoded_length], 0, decoder_frame_length_ *
1248 decoder->channels() * sizeof(decoded_buffer_[0]));
1249 decode_length = decoder_frame_length_;
1250 } else if (!packet->primary) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001251 // This is a redundant payload; call the special decoder method.
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +00001252 LOG(LS_VERBOSE) << "Decoding packet (redundant):" <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001253 " ts=" << packet->header.timestamp <<
1254 ", sn=" << packet->header.sequenceNumber <<
1255 ", pt=" << static_cast<int>(packet->header.payloadType) <<
1256 ", ssrc=" << packet->header.ssrc <<
1257 ", len=" << packet->payload_length;
1258 decode_length = decoder->DecodeRedundant(
1259 packet->payload, packet->payload_length,
1260 &decoded_buffer_[*decoded_length], speech_type);
1261 } else {
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +00001262 LOG(LS_VERBOSE) << "Decoding packet: ts=" << packet->header.timestamp <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001263 ", sn=" << packet->header.sequenceNumber <<
1264 ", pt=" << static_cast<int>(packet->header.payloadType) <<
1265 ", ssrc=" << packet->header.ssrc <<
1266 ", len=" << packet->payload_length;
1267 decode_length = decoder->Decode(packet->payload,
1268 packet->payload_length,
1269 &decoded_buffer_[*decoded_length],
1270 speech_type);
1271 }
1272
1273 delete[] packet->payload;
1274 delete packet;
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001275 packet = NULL;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001276 if (decode_length > 0) {
1277 *decoded_length += decode_length;
1278 // Update |decoder_frame_length_| with number of samples per channel.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001279 decoder_frame_length_ = decode_length /
1280 static_cast<int>(decoder->channels());
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +00001281 LOG(LS_VERBOSE) << "Decoded " << decode_length << " samples (" <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001282 decoder->channels() << " channel(s) -> " << decoder_frame_length_ <<
1283 " samples per channel)";
1284 } else if (decode_length < 0) {
1285 // Error.
henrik.lundin@webrtc.org63464a92013-01-30 09:41:56 +00001286 LOG_FERR2(LS_WARNING, Decode, decode_length, payload_length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001287 *decoded_length = -1;
1288 PacketBuffer::DeleteAllPackets(packet_list);
1289 break;
1290 }
1291 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1292 // Guard against overflow.
1293 LOG_F(LS_WARNING) << "Decoded too much.";
1294 PacketBuffer::DeleteAllPackets(packet_list);
1295 return kDecodedTooMuch;
1296 }
1297 if (!packet_list->empty()) {
1298 packet = packet_list->front();
1299 } else {
1300 packet = NULL;
1301 }
1302 } // End of decode loop.
1303
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001304 // If the list is not empty at this point, either a decoding error terminated
1305 // the while-loop, or list must hold exactly one CNG packet.
1306 assert(packet_list->empty() || *decoded_length < 0 ||
1307 (packet_list->size() == 1 && packet &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001308 decoder_database_->IsComfortNoise(packet->header.payloadType)));
1309 return 0;
1310}
1311
1312void NetEqImpl::DoNormal(const int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001313 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001314 assert(normal_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001315 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001316 normal_->Process(decoded_buffer, decoded_length, last_mode_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001317 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001318 if (decoded_length != 0) {
1319 last_mode_ = kModeNormal;
1320 }
1321
1322 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1323 if ((speech_type == AudioDecoder::kComfortNoise)
1324 || ((last_mode_ == kModeCodecInternalCng)
1325 && (decoded_length == 0))) {
1326 // TODO(hlundin): Remove second part of || statement above.
1327 last_mode_ = kModeCodecInternalCng;
1328 }
1329
1330 if (!play_dtmf) {
1331 dtmf_tone_generator_->Reset();
1332 }
1333}
1334
1335void NetEqImpl::DoMerge(int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001336 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001337 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001338 assert(merge_.get());
1339 int new_length = merge_->Process(decoded_buffer, decoded_length,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001340 mute_factor_array_.get(),
1341 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001342
1343 // Update in-call and post-call statistics.
1344 if (expand_->MuteFactor(0) == 0) {
1345 // Expand generates only noise.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001346 stats_.ExpandedNoiseSamples(new_length - static_cast<int>(decoded_length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001347 } else {
1348 // Expansion generates more than only noise.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001349 stats_.ExpandedVoiceSamples(new_length - static_cast<int>(decoded_length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001350 }
1351
1352 last_mode_ = kModeMerge;
1353 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1354 if (speech_type == AudioDecoder::kComfortNoise) {
1355 last_mode_ = kModeCodecInternalCng;
1356 }
1357 expand_->Reset();
1358 if (!play_dtmf) {
1359 dtmf_tone_generator_->Reset();
1360 }
1361}
1362
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001363int NetEqImpl::DoExpand(bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001364 while ((sync_buffer_->FutureLength() - expand_->overlap_length()) <
1365 static_cast<size_t>(output_size_samples_)) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001366 algorithm_buffer_->Clear();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001367 int return_value = expand_->Process(algorithm_buffer_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001368 int length = static_cast<int>(algorithm_buffer_->Size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001369
1370 // Update in-call and post-call statistics.
1371 if (expand_->MuteFactor(0) == 0) {
1372 // Expand operation generates only noise.
1373 stats_.ExpandedNoiseSamples(length);
1374 } else {
1375 // Expand operation generates more than only noise.
1376 stats_.ExpandedVoiceSamples(length);
1377 }
1378
1379 last_mode_ = kModeExpand;
1380
1381 if (return_value < 0) {
1382 return return_value;
1383 }
1384
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001385 sync_buffer_->PushBack(*algorithm_buffer_);
1386 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001387 }
1388 if (!play_dtmf) {
1389 dtmf_tone_generator_->Reset();
1390 }
1391 return 0;
1392}
1393
1394int NetEqImpl::DoAccelerate(int16_t* decoded_buffer, size_t decoded_length,
1395 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001396 bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001397 const size_t required_samples = 240 * fs_mult_; // Must have 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001398 size_t borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001399 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001400 size_t decoded_length_per_channel = decoded_length / num_channels;
1401 if (decoded_length_per_channel < required_samples) {
1402 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001403 borrowed_samples_per_channel = static_cast<int>(required_samples -
1404 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001405 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1406 decoded_buffer,
1407 sizeof(int16_t) * decoded_length);
1408 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1409 decoded_buffer);
1410 decoded_length = required_samples * num_channels;
1411 }
1412
1413 int16_t samples_removed;
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001414 Accelerate::ReturnCodes return_code = accelerate_->Process(
1415 decoded_buffer, decoded_length, algorithm_buffer_.get(),
1416 &samples_removed);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001417 stats_.AcceleratedSamples(samples_removed);
1418 switch (return_code) {
1419 case Accelerate::kSuccess:
1420 last_mode_ = kModeAccelerateSuccess;
1421 break;
1422 case Accelerate::kSuccessLowEnergy:
1423 last_mode_ = kModeAccelerateLowEnergy;
1424 break;
1425 case Accelerate::kNoStretch:
1426 last_mode_ = kModeAccelerateFail;
1427 break;
1428 case Accelerate::kError:
1429 // TODO(hlundin): Map to kModeError instead?
1430 last_mode_ = kModeAccelerateFail;
1431 return kAccelerateError;
1432 }
1433
1434 if (borrowed_samples_per_channel > 0) {
1435 // Copy borrowed samples back to the |sync_buffer_|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001436 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001437 if (length < borrowed_samples_per_channel) {
1438 // This destroys the beginning of the buffer, but will not cause any
1439 // problems.
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 sync_buffer_->Size() -
1442 borrowed_samples_per_channel);
1443 sync_buffer_->PushFrontZeros(borrowed_samples_per_channel - length);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001444 algorithm_buffer_->PopFront(length);
1445 assert(algorithm_buffer_->Empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001446 } else {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001447 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001448 borrowed_samples_per_channel,
1449 sync_buffer_->Size() -
1450 borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001451 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001452 }
1453 }
1454
1455 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1456 if (speech_type == AudioDecoder::kComfortNoise) {
1457 last_mode_ = kModeCodecInternalCng;
1458 }
1459 if (!play_dtmf) {
1460 dtmf_tone_generator_->Reset();
1461 }
1462 expand_->Reset();
1463 return 0;
1464}
1465
1466int NetEqImpl::DoPreemptiveExpand(int16_t* decoded_buffer,
1467 size_t decoded_length,
1468 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001469 bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001470 const size_t required_samples = 240 * fs_mult_; // Must have 30 ms.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001471 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001472 int borrowed_samples_per_channel = 0;
1473 int old_borrowed_samples_per_channel = 0;
1474 size_t decoded_length_per_channel = decoded_length / num_channels;
1475 if (decoded_length_per_channel < required_samples) {
1476 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001477 borrowed_samples_per_channel = static_cast<int>(required_samples -
1478 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001479 // Calculate how many of these were already played out.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001480 old_borrowed_samples_per_channel = static_cast<int>(
1481 borrowed_samples_per_channel - sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001482 old_borrowed_samples_per_channel = std::max(
1483 0, old_borrowed_samples_per_channel);
1484 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1485 decoded_buffer,
1486 sizeof(int16_t) * decoded_length);
1487 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1488 decoded_buffer);
1489 decoded_length = required_samples * num_channels;
1490 }
1491
1492 int16_t samples_added;
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001493 PreemptiveExpand::ReturnCodes return_code = preemptive_expand_->Process(
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001494 decoded_buffer, static_cast<int>(decoded_length),
1495 old_borrowed_samples_per_channel,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001496 algorithm_buffer_.get(), &samples_added);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001497 stats_.PreemptiveExpandedSamples(samples_added);
1498 switch (return_code) {
1499 case PreemptiveExpand::kSuccess:
1500 last_mode_ = kModePreemptiveExpandSuccess;
1501 break;
1502 case PreemptiveExpand::kSuccessLowEnergy:
1503 last_mode_ = kModePreemptiveExpandLowEnergy;
1504 break;
1505 case PreemptiveExpand::kNoStretch:
1506 last_mode_ = kModePreemptiveExpandFail;
1507 break;
1508 case PreemptiveExpand::kError:
1509 // TODO(hlundin): Map to kModeError instead?
1510 last_mode_ = kModePreemptiveExpandFail;
1511 return kPreemptiveExpandError;
1512 }
1513
1514 if (borrowed_samples_per_channel > 0) {
1515 // Copy borrowed samples back to the |sync_buffer_|.
1516 sync_buffer_->ReplaceAtIndex(
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001517 *algorithm_buffer_, borrowed_samples_per_channel,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001518 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001519 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001520 }
1521
1522 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1523 if (speech_type == AudioDecoder::kComfortNoise) {
1524 last_mode_ = kModeCodecInternalCng;
1525 }
1526 if (!play_dtmf) {
1527 dtmf_tone_generator_->Reset();
1528 }
1529 expand_->Reset();
1530 return 0;
1531}
1532
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001533int NetEqImpl::DoRfc3389Cng(PacketList* packet_list, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001534 if (!packet_list->empty()) {
1535 // Must have exactly one SID frame at this point.
1536 assert(packet_list->size() == 1);
1537 Packet* packet = packet_list->front();
1538 packet_list->pop_front();
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001539 if (!decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1540#ifdef LEGACY_BITEXACT
1541 // This can happen due to a bug in GetDecision. Change the payload type
1542 // to a CNG type, and move on. Note that this means that we are in fact
1543 // sending a non-CNG payload to the comfort noise decoder for decoding.
1544 // Clearly wrong, but will maintain bit-exactness with legacy.
1545 if (fs_hz_ == 8000) {
1546 packet->header.payloadType =
1547 decoder_database_->GetRtpPayloadType(kDecoderCNGnb);
1548 } else if (fs_hz_ == 16000) {
1549 packet->header.payloadType =
1550 decoder_database_->GetRtpPayloadType(kDecoderCNGwb);
1551 } else if (fs_hz_ == 32000) {
1552 packet->header.payloadType =
1553 decoder_database_->GetRtpPayloadType(kDecoderCNGswb32kHz);
1554 } else if (fs_hz_ == 48000) {
1555 packet->header.payloadType =
1556 decoder_database_->GetRtpPayloadType(kDecoderCNGswb48kHz);
1557 }
1558 assert(decoder_database_->IsComfortNoise(packet->header.payloadType));
1559#else
1560 LOG(LS_ERROR) << "Trying to decode non-CNG payload as CNG.";
1561 return kOtherError;
1562#endif
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001563 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001564 // UpdateParameters() deletes |packet|.
1565 if (comfort_noise_->UpdateParameters(packet) ==
1566 ComfortNoise::kInternalError) {
1567 LOG_FERR0(LS_WARNING, UpdateParameters);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001568 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001569 return -comfort_noise_->internal_error_code();
1570 }
1571 }
1572 int cn_return = comfort_noise_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001573 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001574 expand_->Reset();
1575 last_mode_ = kModeRfc3389Cng;
1576 if (!play_dtmf) {
1577 dtmf_tone_generator_->Reset();
1578 }
1579 if (cn_return == ComfortNoise::kInternalError) {
1580 LOG_FERR1(LS_WARNING, comfort_noise_->Generate, cn_return);
1581 decoder_error_code_ = comfort_noise_->internal_error_code();
1582 return kComfortNoiseErrorCode;
1583 } else if (cn_return == ComfortNoise::kUnknownPayloadType) {
1584 LOG_FERR1(LS_WARNING, comfort_noise_->Generate, cn_return);
1585 return kUnknownRtpPayloadType;
1586 }
1587 return 0;
1588}
1589
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001590void NetEqImpl::DoCodecInternalCng() {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001591 int length = 0;
1592 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1593 int16_t decoded_buffer[kMaxFrameSize];
1594 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1595 if (decoder) {
1596 const uint8_t* dummy_payload = NULL;
1597 AudioDecoder::SpeechType speech_type;
1598 length = decoder->Decode(dummy_payload, 0, decoded_buffer, &speech_type);
1599 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001600 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001601 normal_->Process(decoded_buffer, length, last_mode_, mute_factor_array_.get(),
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001602 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001603 last_mode_ = kModeCodecInternalCng;
1604 expand_->Reset();
1605}
1606
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001607int NetEqImpl::DoDtmf(const DtmfEvent& dtmf_event, bool* play_dtmf) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001608 // This block of the code and the block further down, handling |dtmf_switch|
1609 // are commented out. Otherwise playing out-of-band DTMF would fail in VoE
1610 // test, DtmfTest.ManualSuccessfullySendsOutOfBandTelephoneEvents. This is
1611 // equivalent to |dtmf_switch| always be false.
1612 //
1613 // See http://webrtc-codereview.appspot.com/1195004/ for discussion
1614 // On this issue. This change might cause some glitches at the point of
1615 // switch from audio to DTMF. Issue 1545 is filed to track this.
1616 //
1617 // bool dtmf_switch = false;
1618 // if ((last_mode_ != kModeDtmf) && dtmf_tone_generator_->initialized()) {
1619 // // Special case; see below.
1620 // // We must catch this before calling Generate, since |initialized| is
1621 // // modified in that call.
1622 // dtmf_switch = true;
1623 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001624
1625 int dtmf_return_value = 0;
1626 if (!dtmf_tone_generator_->initialized()) {
1627 // Initialize if not already done.
1628 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1629 dtmf_event.volume);
1630 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001631
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001632 if (dtmf_return_value == 0) {
1633 // Generate DTMF signal.
1634 dtmf_return_value = dtmf_tone_generator_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001635 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001636 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001637
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001638 if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001639 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001640 return dtmf_return_value;
1641 }
1642
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001643 // if (dtmf_switch) {
1644 // // This is the special case where the previous operation was DTMF
1645 // // overdub, but the current instruction is "regular" DTMF. We must make
1646 // // sure that the DTMF does not have any discontinuities. The first DTMF
1647 // // sample that we generate now must be played out immediately, therefore
1648 // // it must be copied to the speech buffer.
1649 // // TODO(hlundin): This code seems incorrect. (Legacy.) Write test and
1650 // // verify correct operation.
1651 // assert(false);
1652 // // Must generate enough data to replace all of the |sync_buffer_|
1653 // // "future".
1654 // int required_length = sync_buffer_->FutureLength();
1655 // assert(dtmf_tone_generator_->initialized());
1656 // dtmf_return_value = dtmf_tone_generator_->Generate(required_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001657 // algorithm_buffer_);
1658 // assert((size_t) required_length == algorithm_buffer_->Size());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001659 // if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001660 // algorithm_buffer_->Zeros(output_size_samples_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001661 // return dtmf_return_value;
1662 // }
1663 //
1664 // // Overwrite the "future" part of the speech buffer with the new DTMF
1665 // // data.
1666 // // TODO(hlundin): It seems that this overwriting has gone lost.
1667 // // Not adapted for multi-channel yet.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001668 // assert(algorithm_buffer_->Channels() == 1);
1669 // if (algorithm_buffer_->Channels() != 1) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001670 // LOG(LS_WARNING) << "DTMF not supported for more than one channel";
1671 // return kStereoNotSupported;
1672 // }
1673 // // Shuffle the remaining data to the beginning of algorithm buffer.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001674 // algorithm_buffer_->PopFront(sync_buffer_->FutureLength());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001675 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001676
1677 sync_buffer_->IncreaseEndTimestamp(output_size_samples_);
1678 expand_->Reset();
1679 last_mode_ = kModeDtmf;
1680
1681 // Set to false because the DTMF is already in the algorithm buffer.
1682 *play_dtmf = false;
1683 return 0;
1684}
1685
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001686void NetEqImpl::DoAlternativePlc(bool increase_timestamp) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001687 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1688 int length;
1689 if (decoder && decoder->HasDecodePlc()) {
1690 // Use the decoder's packet-loss concealment.
1691 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1692 int16_t decoded_buffer[kMaxFrameSize];
1693 length = decoder->DecodePlc(1, decoded_buffer);
1694 if (length > 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001695 algorithm_buffer_->PushBackInterleaved(decoded_buffer, length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001696 } else {
1697 length = 0;
1698 }
1699 } else {
1700 // Do simple zero-stuffing.
1701 length = output_size_samples_;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001702 algorithm_buffer_->Zeros(length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001703 // By not advancing the timestamp, NetEq inserts samples.
1704 stats_.AddZeros(length);
1705 }
1706 if (increase_timestamp) {
1707 sync_buffer_->IncreaseEndTimestamp(length);
1708 }
1709 expand_->Reset();
1710}
1711
1712int NetEqImpl::DtmfOverdub(const DtmfEvent& dtmf_event, size_t num_channels,
1713 int16_t* output) const {
1714 size_t out_index = 0;
1715 int overdub_length = output_size_samples_; // Default value.
1716
1717 if (sync_buffer_->dtmf_index() > sync_buffer_->next_index()) {
1718 // Special operation for transition from "DTMF only" to "DTMF overdub".
1719 out_index = std::min(
1720 sync_buffer_->dtmf_index() - sync_buffer_->next_index(),
1721 static_cast<size_t>(output_size_samples_));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001722 overdub_length = output_size_samples_ - static_cast<int>(out_index);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001723 }
1724
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001725 AudioMultiVector dtmf_output(num_channels);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001726 int dtmf_return_value = 0;
1727 if (!dtmf_tone_generator_->initialized()) {
1728 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1729 dtmf_event.volume);
1730 }
1731 if (dtmf_return_value == 0) {
1732 dtmf_return_value = dtmf_tone_generator_->Generate(overdub_length,
1733 &dtmf_output);
1734 assert((size_t) overdub_length == dtmf_output.Size());
1735 }
1736 dtmf_output.ReadInterleaved(overdub_length, &output[out_index]);
1737 return dtmf_return_value < 0 ? dtmf_return_value : 0;
1738}
1739
1740int NetEqImpl::ExtractPackets(int required_samples, PacketList* packet_list) {
1741 bool first_packet = true;
1742 uint8_t prev_payload_type = 0;
1743 uint32_t prev_timestamp = 0;
1744 uint16_t prev_sequence_number = 0;
1745 bool next_packet_available = false;
1746
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001747 const RTPHeader* header = packet_buffer_->NextRtpHeader();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001748 assert(header);
1749 if (!header) {
1750 return -1;
1751 }
turaj@webrtc.org7df97062013-08-02 18:07:13 +00001752 uint32_t first_timestamp = header->timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001753 int extracted_samples = 0;
1754
1755 // Packet extraction loop.
1756 do {
1757 timestamp_ = header->timestamp;
1758 int discard_count = 0;
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001759 Packet* packet = packet_buffer_->GetNextPacket(&discard_count);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001760 // |header| may be invalid after the |packet_buffer_| operation.
1761 header = NULL;
1762 if (!packet) {
1763 LOG_FERR1(LS_ERROR, GetNextPacket, discard_count) <<
1764 "Should always be able to extract a packet here";
1765 assert(false); // Should always be able to extract a packet here.
1766 return -1;
1767 }
1768 stats_.PacketsDiscarded(discard_count);
1769 // Store waiting time in ms; packets->waiting_time is in "output blocks".
1770 stats_.StoreWaitingTime(packet->waiting_time * kOutputSizeMs);
1771 assert(packet->payload_length > 0);
1772 packet_list->push_back(packet); // Store packet in list.
1773
1774 if (first_packet) {
1775 first_packet = false;
minyue@webrtc.orgd7301772013-08-29 00:58:14 +00001776 decoded_packet_sequence_number_ = prev_sequence_number =
1777 packet->header.sequenceNumber;
1778 decoded_packet_timestamp_ = prev_timestamp = packet->header.timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001779 prev_payload_type = packet->header.payloadType;
1780 }
1781
1782 // Store number of extracted samples.
1783 int packet_duration = 0;
1784 AudioDecoder* decoder = decoder_database_->GetDecoder(
1785 packet->header.payloadType);
1786 if (decoder) {
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001787 if (packet->sync_packet) {
1788 packet_duration = decoder_frame_length_;
1789 } else {
1790 packet_duration = packet->primary ?
1791 decoder->PacketDuration(packet->payload, packet->payload_length) :
1792 decoder->PacketDurationRedundant(packet->payload,
1793 packet->payload_length);
1794 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001795 } else {
1796 LOG_FERR1(LS_WARNING, GetDecoder, packet->header.payloadType) <<
1797 "Could not find a decoder for a packet about to be extracted.";
1798 assert(false);
1799 }
1800 if (packet_duration <= 0) {
1801 // Decoder did not return a packet duration. Assume that the packet
1802 // contains the same number of samples as the previous one.
1803 packet_duration = decoder_frame_length_;
1804 }
1805 extracted_samples = packet->header.timestamp - first_timestamp +
1806 packet_duration;
1807
1808 // Check what packet is available next.
1809 header = packet_buffer_->NextRtpHeader();
1810 next_packet_available = false;
1811 if (header && prev_payload_type == header->payloadType) {
1812 int16_t seq_no_diff = header->sequenceNumber - prev_sequence_number;
1813 int32_t ts_diff = header->timestamp - prev_timestamp;
1814 if (seq_no_diff == 1 ||
1815 (seq_no_diff == 0 && ts_diff == decoder_frame_length_)) {
1816 // The next sequence number is available, or the next part of a packet
1817 // that was split into pieces upon insertion.
1818 next_packet_available = true;
1819 }
1820 prev_sequence_number = header->sequenceNumber;
1821 }
1822 } while (extracted_samples < required_samples && next_packet_available);
1823
1824 return extracted_samples;
1825}
1826
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001827void NetEqImpl::UpdatePlcComponents(int fs_hz, size_t channels) {
1828 // Delete objects and create new ones.
1829 expand_.reset(expand_factory_->Create(background_noise_.get(),
1830 sync_buffer_.get(), &random_vector_,
1831 fs_hz, channels));
1832 merge_.reset(new Merge(fs_hz, channels, expand_.get(), sync_buffer_.get()));
1833}
1834
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001835void NetEqImpl::SetSampleRateAndChannels(int fs_hz, size_t channels) {
1836 LOG_API2(fs_hz, channels);
1837 // TODO(hlundin): Change to an enumerator and skip assert.
1838 assert(fs_hz == 8000 || fs_hz == 16000 || fs_hz == 32000 || fs_hz == 48000);
1839 assert(channels > 0);
1840
1841 fs_hz_ = fs_hz;
1842 fs_mult_ = fs_hz / 8000;
1843 output_size_samples_ = kOutputSizeMs * 8 * fs_mult_;
1844 decoder_frame_length_ = 3 * output_size_samples_; // Initialize to 30ms.
1845
1846 last_mode_ = kModeNormal;
1847
1848 // Create a new array of mute factors and set all to 1.
1849 mute_factor_array_.reset(new int16_t[channels]);
1850 for (size_t i = 0; i < channels; ++i) {
1851 mute_factor_array_[i] = 16384; // 1.0 in Q14.
1852 }
1853
1854 // Reset comfort noise decoder, if there is one active.
1855 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
1856 if (cng_decoder) {
1857 cng_decoder->Init();
1858 }
1859
1860 // Reinit post-decode VAD with new sample rate.
1861 assert(vad_.get()); // Cannot be NULL here.
1862 vad_->Init();
1863
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001864 // Delete algorithm buffer and create a new one.
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001865 algorithm_buffer_.reset(new AudioMultiVector(channels));
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001866
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001867 // Delete sync buffer and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001868 sync_buffer_.reset(new SyncBuffer(channels, kSyncBufferSize * fs_mult_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001869
turaj@webrtc.orgff43c852013-09-25 00:07:27 +00001870
1871 // Delete BackgroundNoise object and create a new one, while preserving its
1872 // mode.
1873 NetEqBackgroundNoiseMode current_mode = kBgnOn;
1874 if (background_noise_.get())
1875 current_mode = background_noise_->mode();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001876 background_noise_.reset(new BackgroundNoise(channels));
turaj@webrtc.orgff43c852013-09-25 00:07:27 +00001877 background_noise_->set_mode(current_mode);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001878
1879 // Reset random vector.
1880 random_vector_.Reset();
1881
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001882 UpdatePlcComponents(fs_hz, channels);
1883
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001884 // Move index so that we create a small set of future samples (all 0).
1885 sync_buffer_->set_next_index(sync_buffer_->next_index() -
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001886 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001887
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001888 normal_.reset(new Normal(fs_hz, decoder_database_.get(), *background_noise_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001889 expand_.get()));
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +00001890 accelerate_.reset(
1891 accelerate_factory_->Create(fs_hz, channels, *background_noise_));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001892 preemptive_expand_.reset(preemptive_expand_factory_->Create(
1893 fs_hz, channels,
1894 *background_noise_,
1895 static_cast<int>(expand_->overlap_length())));
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001896
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001897 // Delete ComfortNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001898 comfort_noise_.reset(new ComfortNoise(fs_hz, decoder_database_.get(),
1899 sync_buffer_.get()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001900
1901 // Verify that |decoded_buffer_| is long enough.
1902 if (decoded_buffer_length_ < kMaxFrameSize * channels) {
1903 // Reallocate to larger size.
1904 decoded_buffer_length_ = kMaxFrameSize * channels;
1905 decoded_buffer_.reset(new int16_t[decoded_buffer_length_]);
1906 }
1907
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001908 // Create DecisionLogic if it is not created yet, then communicate new sample
1909 // rate and output size to DecisionLogic object.
1910 if (!decision_logic_.get()) {
1911 CreateDecisionLogic(kPlayoutOn);
1912 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001913 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
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001933void NetEqImpl::CreateDecisionLogic(NetEqPlayoutMode mode) {
1934 decision_logic_.reset(DecisionLogic::Create(fs_hz_, output_size_samples_,
1935 mode,
1936 decoder_database_.get(),
1937 *packet_buffer_.get(),
1938 delay_manager_.get(),
1939 buffer_level_filter_.get()));
1940}
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001941} // namespace webrtc