blob: 29569573f72a5db8b0384866c7c4d8c5dea0f491 [file] [log] [blame]
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001/*
2 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
11#include "webrtc/modules/audio_coding/neteq4/neteq_impl.h"
12
13#include <assert.h>
14#include <memory.h> // memset
15
16#include <algorithm>
17
18#include "webrtc/common_audio/signal_processing/include/signal_processing_library.h"
19#include "webrtc/modules/audio_coding/neteq4/accelerate.h"
20#include "webrtc/modules/audio_coding/neteq4/background_noise.h"
21#include "webrtc/modules/audio_coding/neteq4/buffer_level_filter.h"
22#include "webrtc/modules/audio_coding/neteq4/comfort_noise.h"
23#include "webrtc/modules/audio_coding/neteq4/decision_logic.h"
24#include "webrtc/modules/audio_coding/neteq4/decoder_database.h"
25#include "webrtc/modules/audio_coding/neteq4/defines.h"
26#include "webrtc/modules/audio_coding/neteq4/delay_manager.h"
27#include "webrtc/modules/audio_coding/neteq4/delay_peak_detector.h"
28#include "webrtc/modules/audio_coding/neteq4/dtmf_buffer.h"
29#include "webrtc/modules/audio_coding/neteq4/dtmf_tone_generator.h"
30#include "webrtc/modules/audio_coding/neteq4/expand.h"
31#include "webrtc/modules/audio_coding/neteq4/interface/audio_decoder.h"
32#include "webrtc/modules/audio_coding/neteq4/merge.h"
33#include "webrtc/modules/audio_coding/neteq4/normal.h"
34#include "webrtc/modules/audio_coding/neteq4/packet_buffer.h"
35#include "webrtc/modules/audio_coding/neteq4/packet.h"
36#include "webrtc/modules/audio_coding/neteq4/payload_splitter.h"
37#include "webrtc/modules/audio_coding/neteq4/post_decode_vad.h"
38#include "webrtc/modules/audio_coding/neteq4/preemptive_expand.h"
39#include "webrtc/modules/audio_coding/neteq4/sync_buffer.h"
40#include "webrtc/modules/audio_coding/neteq4/timestamp_scaler.h"
41#include "webrtc/modules/interface/module_common_types.h"
42#include "webrtc/system_wrappers/interface/critical_section_wrapper.h"
43#include "webrtc/system_wrappers/interface/logging.h"
44
45// Modify the code to obtain backwards bit-exactness. Once bit-exactness is no
46// longer required, this #define should be removed (and the code that it
47// enables).
48#define LEGACY_BITEXACT
49
50namespace webrtc {
51
52NetEqImpl::NetEqImpl(int fs,
53 BufferLevelFilter* buffer_level_filter,
54 DecoderDatabase* decoder_database,
55 DelayManager* delay_manager,
56 DelayPeakDetector* delay_peak_detector,
57 DtmfBuffer* dtmf_buffer,
58 DtmfToneGenerator* dtmf_tone_generator,
59 PacketBuffer* packet_buffer,
60 PayloadSplitter* payload_splitter,
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +000061 TimestampScaler* timestamp_scaler,
62 AccelerateFactory* accelerate_factory,
63 ExpandFactory* expand_factory,
64 PreemptiveExpandFactory* preemptive_expand_factory)
andrew@webrtc.org31628aa2013-10-22 12:50:00 +000065 : buffer_level_filter_(buffer_level_filter),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000066 decoder_database_(decoder_database),
67 delay_manager_(delay_manager),
68 delay_peak_detector_(delay_peak_detector),
69 dtmf_buffer_(dtmf_buffer),
70 dtmf_tone_generator_(dtmf_tone_generator),
71 packet_buffer_(packet_buffer),
72 payload_splitter_(payload_splitter),
73 timestamp_scaler_(timestamp_scaler),
74 vad_(new PostDecodeVad()),
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +000075 expand_factory_(expand_factory),
76 accelerate_factory_(accelerate_factory),
77 preemptive_expand_factory_(preemptive_expand_factory),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000078 last_mode_(kModeNormal),
79 mute_factor_array_(NULL),
80 decoded_buffer_length_(kMaxFrameSize),
81 decoded_buffer_(new int16_t[decoded_buffer_length_]),
82 playout_timestamp_(0),
83 new_codec_(false),
84 timestamp_(0),
85 reset_decoder_(false),
86 current_rtp_payload_type_(0xFF), // Invalid RTP payload type.
87 current_cng_rtp_payload_type_(0xFF), // Invalid RTP payload type.
88 ssrc_(0),
89 first_packet_(true),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000090 error_code_(0),
91 decoder_error_code_(0),
minyue@webrtc.orgd7301772013-08-29 00:58:14 +000092 crit_sect_(CriticalSectionWrapper::CreateCriticalSection()),
93 decoded_packet_sequence_number_(-1),
94 decoded_packet_timestamp_(0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000095 if (fs != 8000 && fs != 16000 && fs != 32000 && fs != 48000) {
96 LOG(LS_ERROR) << "Sample rate " << fs << " Hz not supported. " <<
97 "Changing to 8000 Hz.";
98 fs = 8000;
99 }
100 LOG(LS_INFO) << "Create NetEqImpl object with fs = " << fs << ".";
101 fs_hz_ = fs;
102 fs_mult_ = fs / 8000;
103 output_size_samples_ = kOutputSizeMs * 8 * fs_mult_;
104 decoder_frame_length_ = 3 * output_size_samples_;
105 WebRtcSpl_Init();
106 decision_logic_.reset(DecisionLogic::Create(fs_hz_, output_size_samples_,
107 kPlayoutOn,
108 decoder_database_.get(),
109 *packet_buffer_.get(),
110 delay_manager_.get(),
111 buffer_level_filter_.get()));
112 SetSampleRateAndChannels(fs, 1); // Default is 1 channel.
113}
114
115NetEqImpl::~NetEqImpl() {
116 LOG(LS_INFO) << "Deleting NetEqImpl object.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000117}
118
119int NetEqImpl::InsertPacket(const WebRtcRTPHeader& rtp_header,
120 const uint8_t* payload,
121 int length_bytes,
122 uint32_t receive_timestamp) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000123 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000124 LOG(LS_VERBOSE) << "InsertPacket: ts=" << rtp_header.header.timestamp <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000125 ", sn=" << rtp_header.header.sequenceNumber <<
126 ", pt=" << static_cast<int>(rtp_header.header.payloadType) <<
127 ", ssrc=" << rtp_header.header.ssrc <<
128 ", len=" << length_bytes;
129 int error = InsertPacketInternal(rtp_header, payload, length_bytes,
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000130 receive_timestamp, false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000131 if (error != 0) {
132 LOG_FERR1(LS_WARNING, InsertPacketInternal, error);
133 error_code_ = error;
134 return kFail;
135 }
136 return kOK;
137}
138
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000139int NetEqImpl::InsertSyncPacket(const WebRtcRTPHeader& rtp_header,
140 uint32_t receive_timestamp) {
141 CriticalSectionScoped lock(crit_sect_.get());
142 LOG(LS_VERBOSE) << "InsertPacket-Sync: ts="
143 << rtp_header.header.timestamp <<
144 ", sn=" << rtp_header.header.sequenceNumber <<
145 ", pt=" << static_cast<int>(rtp_header.header.payloadType) <<
146 ", ssrc=" << rtp_header.header.ssrc;
147
148 const uint8_t kSyncPayload[] = { 's', 'y', 'n', 'c' };
149 int error = InsertPacketInternal(
150 rtp_header, kSyncPayload, sizeof(kSyncPayload), receive_timestamp, true);
151
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000152 if (error != 0) {
153 LOG_FERR1(LS_WARNING, InsertPacketInternal, error);
154 error_code_ = error;
155 return kFail;
156 }
157 return kOK;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000158}
159
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000160int NetEqImpl::GetAudio(size_t max_length, int16_t* output_audio,
161 int* samples_per_channel, int* num_channels,
162 NetEqOutputType* type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000163 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000164 LOG(LS_VERBOSE) << "GetAudio";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000165 int error = GetAudioInternal(max_length, output_audio, samples_per_channel,
166 num_channels);
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000167 LOG(LS_VERBOSE) << "Produced " << *samples_per_channel <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000168 " samples/channel for " << *num_channels << " channel(s)";
169 if (error != 0) {
170 LOG_FERR1(LS_WARNING, GetAudioInternal, error);
171 error_code_ = error;
172 return kFail;
173 }
174 if (type) {
175 *type = LastOutputType();
176 }
177 return kOK;
178}
179
180int NetEqImpl::RegisterPayloadType(enum NetEqDecoder codec,
181 uint8_t rtp_payload_type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000182 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000183 LOG_API2(static_cast<int>(rtp_payload_type), codec);
184 int ret = decoder_database_->RegisterPayload(rtp_payload_type, codec);
185 if (ret != DecoderDatabase::kOK) {
186 LOG_FERR2(LS_WARNING, RegisterPayload, rtp_payload_type, codec);
187 switch (ret) {
188 case DecoderDatabase::kInvalidRtpPayloadType:
189 error_code_ = kInvalidRtpPayloadType;
190 break;
191 case DecoderDatabase::kCodecNotSupported:
192 error_code_ = kCodecNotSupported;
193 break;
194 case DecoderDatabase::kDecoderExists:
195 error_code_ = kDecoderExists;
196 break;
197 default:
198 error_code_ = kOtherError;
199 }
200 return kFail;
201 }
202 return kOK;
203}
204
205int NetEqImpl::RegisterExternalDecoder(AudioDecoder* decoder,
206 enum NetEqDecoder codec,
207 int sample_rate_hz,
208 uint8_t rtp_payload_type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000209 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000210 LOG_API2(static_cast<int>(rtp_payload_type), codec);
211 if (!decoder) {
212 LOG(LS_ERROR) << "Cannot register external decoder with NULL pointer";
213 assert(false);
214 return kFail;
215 }
216 int ret = decoder_database_->InsertExternal(rtp_payload_type, codec,
217 sample_rate_hz, decoder);
218 if (ret != DecoderDatabase::kOK) {
219 LOG_FERR2(LS_WARNING, InsertExternal, rtp_payload_type, codec);
220 switch (ret) {
221 case DecoderDatabase::kInvalidRtpPayloadType:
222 error_code_ = kInvalidRtpPayloadType;
223 break;
224 case DecoderDatabase::kCodecNotSupported:
225 error_code_ = kCodecNotSupported;
226 break;
227 case DecoderDatabase::kDecoderExists:
228 error_code_ = kDecoderExists;
229 break;
230 case DecoderDatabase::kInvalidSampleRate:
231 error_code_ = kInvalidSampleRate;
232 break;
233 case DecoderDatabase::kInvalidPointer:
234 error_code_ = kInvalidPointer;
235 break;
236 default:
237 error_code_ = kOtherError;
238 }
239 return kFail;
240 }
241 return kOK;
242}
243
244int NetEqImpl::RemovePayloadType(uint8_t rtp_payload_type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000245 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000246 LOG_API1(static_cast<int>(rtp_payload_type));
247 int ret = decoder_database_->Remove(rtp_payload_type);
248 if (ret == DecoderDatabase::kOK) {
249 return kOK;
250 } else if (ret == DecoderDatabase::kDecoderNotFound) {
251 error_code_ = kDecoderNotFound;
252 } else {
253 error_code_ = kOtherError;
254 }
255 LOG_FERR1(LS_WARNING, Remove, rtp_payload_type);
256 return kFail;
257}
258
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000259bool NetEqImpl::SetMinimumDelay(int delay_ms) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000260 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000261 if (delay_ms >= 0 && delay_ms < 10000) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000262 assert(delay_manager_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000263 return delay_manager_->SetMinimumDelay(delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000264 }
265 return false;
266}
267
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000268bool NetEqImpl::SetMaximumDelay(int delay_ms) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000269 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000270 if (delay_ms >= 0 && delay_ms < 10000) {
271 assert(delay_manager_.get());
272 return delay_manager_->SetMaximumDelay(delay_ms);
273 }
274 return false;
275}
276
277int NetEqImpl::LeastRequiredDelayMs() const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000278 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000279 assert(delay_manager_.get());
280 return delay_manager_->least_required_delay_ms();
281}
282
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000283void NetEqImpl::SetPlayoutMode(NetEqPlayoutMode mode) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000284 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000285 if (!decision_logic_.get() || mode != decision_logic_->playout_mode()) {
286 // The reset() method calls delete for the old object.
287 decision_logic_.reset(DecisionLogic::Create(fs_hz_, output_size_samples_,
288 mode,
289 decoder_database_.get(),
290 *packet_buffer_.get(),
291 delay_manager_.get(),
292 buffer_level_filter_.get()));
293 }
294}
295
296NetEqPlayoutMode NetEqImpl::PlayoutMode() const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000297 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000298 assert(decision_logic_.get());
299 return decision_logic_->playout_mode();
300}
301
302int NetEqImpl::NetworkStatistics(NetEqNetworkStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000303 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000304 assert(decoder_database_.get());
305 const int total_samples_in_buffers = packet_buffer_->NumSamplesInBuffer(
306 decoder_database_.get(), decoder_frame_length_) +
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000307 static_cast<int>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000308 assert(delay_manager_.get());
309 assert(decision_logic_.get());
310 stats_.GetNetworkStatistics(fs_hz_, total_samples_in_buffers,
311 decoder_frame_length_, *delay_manager_.get(),
312 *decision_logic_.get(), stats);
313 return 0;
314}
315
316void NetEqImpl::WaitingTimes(std::vector<int>* waiting_times) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000317 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000318 stats_.WaitingTimes(waiting_times);
319}
320
321void NetEqImpl::GetRtcpStatistics(RtcpStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000322 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000323 if (stats) {
324 rtcp_.GetStatistics(false, stats);
325 }
326}
327
328void NetEqImpl::GetRtcpStatisticsNoReset(RtcpStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000329 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000330 if (stats) {
331 rtcp_.GetStatistics(true, stats);
332 }
333}
334
335void NetEqImpl::EnableVad() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000336 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000337 assert(vad_.get());
338 vad_->Enable();
339}
340
341void NetEqImpl::DisableVad() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000342 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000343 assert(vad_.get());
344 vad_->Disable();
345}
346
347uint32_t NetEqImpl::PlayoutTimestamp() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000348 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000349 return timestamp_scaler_->ToExternal(playout_timestamp_);
350}
351
352int NetEqImpl::LastError() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000353 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000354 return error_code_;
355}
356
357int NetEqImpl::LastDecoderError() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000358 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000359 return decoder_error_code_;
360}
361
362void NetEqImpl::FlushBuffers() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000363 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000364 LOG_API0();
365 packet_buffer_->Flush();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000366 assert(sync_buffer_.get());
367 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000368 sync_buffer_->Flush();
369 sync_buffer_->set_next_index(sync_buffer_->next_index() -
370 expand_->overlap_length());
371 // Set to wait for new codec.
372 first_packet_ = true;
373}
374
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000375void NetEqImpl::PacketBufferStatistics(int* current_num_packets,
376 int* max_num_packets,
377 int* current_memory_size_bytes,
378 int* max_memory_size_bytes) const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000379 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000380 packet_buffer_->BufferStat(current_num_packets, max_num_packets,
381 current_memory_size_bytes, max_memory_size_bytes);
382}
383
turaj@webrtc.orgff43c852013-09-25 00:07:27 +0000384int NetEqImpl::DecodedRtpInfo(int* sequence_number, uint32_t* timestamp) const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000385 CriticalSectionScoped lock(crit_sect_.get());
minyue@webrtc.orgd7301772013-08-29 00:58:14 +0000386 if (decoded_packet_sequence_number_ < 0)
387 return -1;
388 *sequence_number = decoded_packet_sequence_number_;
389 *timestamp = decoded_packet_timestamp_;
390 return 0;
391}
392
turaj@webrtc.orgff43c852013-09-25 00:07:27 +0000393void NetEqImpl::SetBackgroundNoiseMode(NetEqBackgroundNoiseMode mode) {
394 CriticalSectionScoped lock(crit_sect_.get());
395 assert(background_noise_.get());
396 background_noise_->set_mode(mode);
397}
turaj@webrtc.org036b7432013-09-11 18:45:02 +0000398
399NetEqBackgroundNoiseMode NetEqImpl::BackgroundNoiseMode() const {
turaj@webrtc.orgff43c852013-09-25 00:07:27 +0000400 CriticalSectionScoped lock(crit_sect_.get());
401 assert(background_noise_.get());
402 return background_noise_->mode();
turaj@webrtc.org036b7432013-09-11 18:45:02 +0000403}
404
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000405// Methods below this line are private.
406
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000407int NetEqImpl::InsertPacketInternal(const WebRtcRTPHeader& rtp_header,
408 const uint8_t* payload,
409 int length_bytes,
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000410 uint32_t receive_timestamp,
411 bool is_sync_packet) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000412 if (!payload) {
413 LOG_F(LS_ERROR) << "payload == NULL";
414 return kInvalidPointer;
415 }
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000416 // Sanity checks for sync-packets.
417 if (is_sync_packet) {
418 if (decoder_database_->IsDtmf(rtp_header.header.payloadType) ||
419 decoder_database_->IsRed(rtp_header.header.payloadType) ||
420 decoder_database_->IsComfortNoise(rtp_header.header.payloadType)) {
421 LOG_F(LS_ERROR) << "Sync-packet with an unacceptable payload type "
422 << rtp_header.header.payloadType;
423 return kSyncPacketNotAccepted;
424 }
425 if (first_packet_ ||
426 rtp_header.header.payloadType != current_rtp_payload_type_ ||
427 rtp_header.header.ssrc != ssrc_) {
428 // Even if |current_rtp_payload_type_| is 0xFF, sync-packet isn't
429 // accepted.
430 LOG_F(LS_ERROR) << "Changing codec, SSRC or first packet "
431 "with sync-packet.";
432 return kSyncPacketNotAccepted;
433 }
434 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000435 PacketList packet_list;
436 RTPHeader main_header;
437 {
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000438 // Convert to Packet.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000439 // Create |packet| within this separate scope, since it should not be used
440 // directly once it's been inserted in the packet list. This way, |packet|
441 // is not defined outside of this block.
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000442 Packet* packet = new Packet;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000443 packet->header.markerBit = false;
444 packet->header.payloadType = rtp_header.header.payloadType;
445 packet->header.sequenceNumber = rtp_header.header.sequenceNumber;
446 packet->header.timestamp = rtp_header.header.timestamp;
447 packet->header.ssrc = rtp_header.header.ssrc;
448 packet->header.numCSRCs = 0;
449 packet->payload_length = length_bytes;
450 packet->primary = true;
451 packet->waiting_time = 0;
452 packet->payload = new uint8_t[packet->payload_length];
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000453 packet->sync_packet = is_sync_packet;
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +0000454 if (!packet->payload) {
455 LOG_F(LS_ERROR) << "Payload pointer is NULL.";
456 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000457 assert(payload); // Already checked above.
458 memcpy(packet->payload, payload, packet->payload_length);
459 // Insert packet in a packet list.
460 packet_list.push_back(packet);
461 // Save main payloads header for later.
462 memcpy(&main_header, &packet->header, sizeof(main_header));
463 }
464
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000465 bool update_sample_rate_and_channels = false;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000466 // Reinitialize NetEq if it's needed (changed SSRC or first call).
467 if ((main_header.ssrc != ssrc_) || first_packet_) {
468 rtcp_.Init(main_header.sequenceNumber);
469 first_packet_ = false;
470
471 // Flush the packet buffer and DTMF buffer.
472 packet_buffer_->Flush();
473 dtmf_buffer_->Flush();
474
475 // Store new SSRC.
476 ssrc_ = main_header.ssrc;
477
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000478 // Update audio buffer timestamp.
479 sync_buffer_->IncreaseEndTimestamp(main_header.timestamp - timestamp_);
480
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000481 // Update codecs.
482 timestamp_ = main_header.timestamp;
483 current_rtp_payload_type_ = main_header.payloadType;
484
485 // Set MCU to update codec on next SignalMCU call.
486 new_codec_ = true;
487
488 // Reset timestamp scaling.
489 timestamp_scaler_->Reset();
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000490
491 // Triger an update of sampling rate and the number of channels.
492 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000493 }
494
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000495 // Update RTCP statistics, only for regular packets.
496 if (!is_sync_packet)
497 rtcp_.Update(main_header, receive_timestamp);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000498
499 // Check for RED payload type, and separate payloads into several packets.
500 if (decoder_database_->IsRed(main_header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000501 assert(!is_sync_packet); // We had a sanity check for this.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000502 if (payload_splitter_->SplitRed(&packet_list) != PayloadSplitter::kOK) {
503 LOG_FERR1(LS_WARNING, SplitRed, packet_list.size());
504 PacketBuffer::DeleteAllPackets(&packet_list);
505 return kRedundancySplitError;
506 }
507 // Only accept a few RED payloads of the same type as the main data,
508 // DTMF events and CNG.
509 payload_splitter_->CheckRedPayloads(&packet_list, *decoder_database_);
510 // Update the stored main payload header since the main payload has now
511 // changed.
512 memcpy(&main_header, &packet_list.front()->header, sizeof(main_header));
513 }
514
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +0000515 // Check for FEC in packets, and separate payloads into several packets.
516 int ret = payload_splitter_->SplitFec(&packet_list, decoder_database_.get());
517 if (ret != PayloadSplitter::kOK) {
518 LOG_FERR1(LS_WARNING, SplitFec, packet_list.size());
519 PacketBuffer::DeleteAllPackets(&packet_list);
520 switch (ret) {
521 case PayloadSplitter::kUnknownPayloadType:
522 return kUnknownRtpPayloadType;
523 default:
524 return kOtherError;
525 }
526 }
527
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000528 // Check payload types.
529 if (decoder_database_->CheckPayloadTypes(packet_list) ==
530 DecoderDatabase::kDecoderNotFound) {
531 LOG_FERR1(LS_WARNING, CheckPayloadTypes, packet_list.size());
532 PacketBuffer::DeleteAllPackets(&packet_list);
533 return kUnknownRtpPayloadType;
534 }
535
536 // Scale timestamp to internal domain (only for some codecs).
537 timestamp_scaler_->ToInternal(&packet_list);
538
539 // Process DTMF payloads. Cycle through the list of packets, and pick out any
540 // DTMF payloads found.
541 PacketList::iterator it = packet_list.begin();
542 while (it != packet_list.end()) {
543 Packet* current_packet = (*it);
544 assert(current_packet);
545 assert(current_packet->payload);
546 if (decoder_database_->IsDtmf(current_packet->header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000547 assert(!current_packet->sync_packet); // We had a sanity check for this.
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000548 DtmfEvent event;
549 int ret = DtmfBuffer::ParseEvent(
550 current_packet->header.timestamp,
551 current_packet->payload,
552 current_packet->payload_length,
553 &event);
554 if (ret != DtmfBuffer::kOK) {
555 LOG_FERR2(LS_WARNING, ParseEvent, ret,
556 current_packet->payload_length);
557 PacketBuffer::DeleteAllPackets(&packet_list);
558 return kDtmfParsingError;
559 }
560 if (dtmf_buffer_->InsertEvent(event) != DtmfBuffer::kOK) {
561 LOG_FERR0(LS_WARNING, InsertEvent);
562 PacketBuffer::DeleteAllPackets(&packet_list);
563 return kDtmfInsertError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000564 }
565 // TODO(hlundin): Let the destructor of Packet handle the payload.
566 delete [] current_packet->payload;
567 delete current_packet;
568 it = packet_list.erase(it);
569 } else {
570 ++it;
571 }
572 }
573
574 // Split payloads into smaller chunks. This also verifies that all payloads
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000575 // are of a known payload type. SplitAudio() method is protected against
576 // sync-packets.
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +0000577 ret = payload_splitter_->SplitAudio(&packet_list, *decoder_database_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000578 if (ret != PayloadSplitter::kOK) {
579 LOG_FERR1(LS_WARNING, SplitAudio, packet_list.size());
580 PacketBuffer::DeleteAllPackets(&packet_list);
581 switch (ret) {
582 case PayloadSplitter::kUnknownPayloadType:
583 return kUnknownRtpPayloadType;
584 case PayloadSplitter::kFrameSplitError:
585 return kFrameSplitError;
586 default:
587 return kOtherError;
588 }
589 }
590
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000591 // Update bandwidth estimate, if the packet is not sync-packet.
592 if (!packet_list.empty() && !packet_list.front()->sync_packet) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000593 // The list can be empty here if we got nothing but DTMF payloads.
594 AudioDecoder* decoder =
595 decoder_database_->GetDecoder(main_header.payloadType);
596 assert(decoder); // Should always get a valid object, since we have
597 // already checked that the payload types are known.
598 decoder->IncomingPacket(packet_list.front()->payload,
599 packet_list.front()->payload_length,
600 packet_list.front()->header.sequenceNumber,
601 packet_list.front()->header.timestamp,
602 receive_timestamp);
603 }
604
605 // Insert packets in buffer.
606 int temp_bufsize = packet_buffer_->NumPacketsInBuffer();
607 ret = packet_buffer_->InsertPacketList(
608 &packet_list,
609 *decoder_database_,
610 &current_rtp_payload_type_,
611 &current_cng_rtp_payload_type_);
612 if (ret == PacketBuffer::kFlushed) {
613 // Reset DSP timestamp etc. if packet buffer flushed.
614 new_codec_ = true;
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000615 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000616 LOG_F(LS_WARNING) << "Packet buffer flushed";
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000617 } else if (ret == PacketBuffer::kOversizePacket) {
618 LOG_F(LS_WARNING) << "Packet larger than packet buffer";
619 return kOversizePacket;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000620 } else if (ret != PacketBuffer::kOK) {
621 LOG_FERR1(LS_WARNING, InsertPacketList, packet_list.size());
622 PacketBuffer::DeleteAllPackets(&packet_list);
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000623 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000624 }
625 if (current_rtp_payload_type_ != 0xFF) {
626 const DecoderDatabase::DecoderInfo* dec_info =
627 decoder_database_->GetDecoderInfo(current_rtp_payload_type_);
628 if (!dec_info) {
629 assert(false); // Already checked that the payload type is known.
630 }
631 }
632
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000633 if (update_sample_rate_and_channels && !packet_buffer_->Empty()) {
634 // We do not use |current_rtp_payload_type_| to |set payload_type|, but
635 // get the next RTP header from |packet_buffer_| to obtain the payload type.
636 // The reason for it is the following corner case. If NetEq receives a
637 // CNG packet with a sample rate different than the current CNG then it
638 // flushes its buffer, assuming send codec must have been changed. However,
639 // payload type of the hypothetically new send codec is not known.
640 const RTPHeader* rtp_header = packet_buffer_->NextRtpHeader();
641 assert(rtp_header);
642 int payload_type = rtp_header->payloadType;
643 AudioDecoder* decoder = decoder_database_->GetDecoder(payload_type);
644 assert(decoder); // Payloads are already checked to be valid.
645 const DecoderDatabase::DecoderInfo* decoder_info =
646 decoder_database_->GetDecoderInfo(payload_type);
647 assert(decoder_info);
648 if (decoder_info->fs_hz != fs_hz_ ||
649 decoder->channels() != algorithm_buffer_->Channels())
650 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->channels());
651 }
652
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000653 // TODO(hlundin): Move this code to DelayManager class.
654 const DecoderDatabase::DecoderInfo* dec_info =
655 decoder_database_->GetDecoderInfo(main_header.payloadType);
656 assert(dec_info); // Already checked that the payload type is known.
657 delay_manager_->LastDecoderType(dec_info->codec_type);
658 if (delay_manager_->last_pack_cng_or_dtmf() == 0) {
659 // Calculate the total speech length carried in each packet.
660 temp_bufsize = packet_buffer_->NumPacketsInBuffer() - temp_bufsize;
661 temp_bufsize *= decoder_frame_length_;
662
663 if ((temp_bufsize > 0) &&
664 (temp_bufsize != decision_logic_->packet_length_samples())) {
665 decision_logic_->set_packet_length_samples(temp_bufsize);
666 delay_manager_->SetPacketAudioLength((1000 * temp_bufsize) / fs_hz_);
667 }
668
669 // Update statistics.
pbos@webrtc.org0946a562013-04-09 00:28:06 +0000670 if ((int32_t) (main_header.timestamp - timestamp_) >= 0 &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000671 !new_codec_) {
672 // Only update statistics if incoming packet is not older than last played
673 // out packet, and if new codec flag is not set.
674 delay_manager_->Update(main_header.sequenceNumber, main_header.timestamp,
675 fs_hz_);
676 }
677 } else if (delay_manager_->last_pack_cng_or_dtmf() == -1) {
678 // This is first "normal" packet after CNG or DTMF.
679 // Reset packet time counter and measure time until next packet,
680 // but don't update statistics.
681 delay_manager_->set_last_pack_cng_or_dtmf(0);
682 delay_manager_->ResetPacketIatCount();
683 }
684 return 0;
685}
686
687int NetEqImpl::GetAudioInternal(size_t max_length, int16_t* output,
688 int* samples_per_channel, int* num_channels) {
689 PacketList packet_list;
690 DtmfEvent dtmf_event;
691 Operations operation;
692 bool play_dtmf;
693 int return_value = GetDecision(&operation, &packet_list, &dtmf_event,
694 &play_dtmf);
695 if (return_value != 0) {
696 LOG_FERR1(LS_WARNING, GetDecision, return_value);
697 assert(false);
698 last_mode_ = kModeError;
699 return return_value;
700 }
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000701 LOG(LS_VERBOSE) << "GetDecision returned operation=" << operation <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000702 " and " << packet_list.size() << " packet(s)";
703
704 AudioDecoder::SpeechType speech_type;
705 int length = 0;
706 int decode_return_value = Decode(&packet_list, &operation,
707 &length, &speech_type);
708
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000709 assert(vad_.get());
710 bool sid_frame_available =
711 (operation == kRfc3389Cng && !packet_list.empty());
712 vad_->Update(decoded_buffer_.get(), length, speech_type,
713 sid_frame_available, fs_hz_);
714
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000715 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000716 switch (operation) {
717 case kNormal: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000718 DoNormal(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000719 break;
720 }
721 case kMerge: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000722 DoMerge(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000723 break;
724 }
725 case kExpand: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000726 return_value = DoExpand(play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000727 break;
728 }
729 case kAccelerate: {
730 return_value = DoAccelerate(decoded_buffer_.get(), length, speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000731 play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000732 break;
733 }
734 case kPreemptiveExpand: {
735 return_value = DoPreemptiveExpand(decoded_buffer_.get(), length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000736 speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000737 break;
738 }
739 case kRfc3389Cng:
740 case kRfc3389CngNoPacket: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000741 return_value = DoRfc3389Cng(&packet_list, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000742 break;
743 }
744 case kCodecInternalCng: {
745 // This handles the case when there is no transmission and the decoder
746 // should produce internal comfort noise.
747 // TODO(hlundin): Write test for codec-internal CNG.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000748 DoCodecInternalCng();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000749 break;
750 }
751 case kDtmf: {
752 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000753 return_value = DoDtmf(dtmf_event, &play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000754 break;
755 }
756 case kAlternativePlc: {
757 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000758 DoAlternativePlc(false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000759 break;
760 }
761 case kAlternativePlcIncreaseTimestamp: {
762 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000763 DoAlternativePlc(true);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000764 break;
765 }
766 case kAudioRepetitionIncreaseTimestamp: {
767 // TODO(hlundin): Write test for this.
768 sync_buffer_->IncreaseEndTimestamp(output_size_samples_);
769 // Skipping break on purpose. Execution should move on into the
770 // next case.
771 }
772 case kAudioRepetition: {
773 // TODO(hlundin): Write test for this.
774 // Copy last |output_size_samples_| from |sync_buffer_| to
775 // |algorithm_buffer|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000776 algorithm_buffer_->PushBackFromIndex(
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000777 *sync_buffer_, sync_buffer_->Size() - output_size_samples_);
778 expand_->Reset();
779 break;
780 }
781 case kUndefined: {
782 LOG_F(LS_ERROR) << "Invalid operation kUndefined.";
783 assert(false); // This should not happen.
784 last_mode_ = kModeError;
785 return kInvalidOperation;
786 }
787 } // End of switch.
788 if (return_value < 0) {
789 return return_value;
790 }
791
792 if (last_mode_ != kModeRfc3389Cng) {
793 comfort_noise_->Reset();
794 }
795
796 // Copy from |algorithm_buffer| to |sync_buffer_|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000797 sync_buffer_->PushBack(*algorithm_buffer_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000798
799 // Extract data from |sync_buffer_| to |output|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000800 size_t num_output_samples_per_channel = output_size_samples_;
801 size_t num_output_samples = output_size_samples_ * sync_buffer_->Channels();
802 if (num_output_samples > max_length) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000803 LOG(LS_WARNING) << "Output array is too short. " << max_length << " < " <<
804 output_size_samples_ << " * " << sync_buffer_->Channels();
805 num_output_samples = max_length;
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000806 num_output_samples_per_channel = static_cast<int>(
807 max_length / sync_buffer_->Channels());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000808 }
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000809 int samples_from_sync = static_cast<int>(
810 sync_buffer_->GetNextAudioInterleaved(num_output_samples_per_channel,
811 output));
812 *num_channels = static_cast<int>(sync_buffer_->Channels());
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000813 LOG(LS_VERBOSE) << "Sync buffer (" << *num_channels << " channel(s)):" <<
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000814 " insert " << algorithm_buffer_->Size() << " samples, extract " <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000815 samples_from_sync << " samples";
816 if (samples_from_sync != output_size_samples_) {
817 LOG_F(LS_ERROR) << "samples_from_sync != output_size_samples_";
minyue@webrtc.orgdb1cefc2013-08-13 01:39:21 +0000818 // TODO(minyue): treatment of under-run, filling zeros
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000819 memset(output, 0, num_output_samples * sizeof(int16_t));
820 *samples_per_channel = output_size_samples_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000821 return kSampleUnderrun;
822 }
823 *samples_per_channel = output_size_samples_;
824
825 // Should always have overlap samples left in the |sync_buffer_|.
826 assert(sync_buffer_->FutureLength() >= expand_->overlap_length());
827
828 if (play_dtmf) {
829 return_value = DtmfOverdub(dtmf_event, sync_buffer_->Channels(), output);
830 }
831
832 // Update the background noise parameters if last operation wrote data
833 // straight from the decoder to the |sync_buffer_|. That is, none of the
834 // operations that modify the signal can be followed by a parameter update.
835 if ((last_mode_ == kModeNormal) ||
836 (last_mode_ == kModeAccelerateFail) ||
837 (last_mode_ == kModePreemptiveExpandFail) ||
838 (last_mode_ == kModeRfc3389Cng) ||
839 (last_mode_ == kModeCodecInternalCng)) {
840 background_noise_->Update(*sync_buffer_, *vad_.get());
841 }
842
843 if (operation == kDtmf) {
844 // DTMF data was written the end of |sync_buffer_|.
845 // Update index to end of DTMF data in |sync_buffer_|.
846 sync_buffer_->set_dtmf_index(sync_buffer_->Size());
847 }
848
henrik.lundin@webrtc.orged865b52014-03-06 10:28:07 +0000849 if (last_mode_ != kModeExpand) {
850 // If last operation was not expand, calculate the |playout_timestamp_| from
851 // the |sync_buffer_|. However, do not update the |playout_timestamp_| if it
852 // would be moved "backwards".
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000853 uint32_t temp_timestamp = sync_buffer_->end_timestamp() -
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000854 static_cast<uint32_t>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000855 if (static_cast<int32_t>(temp_timestamp - playout_timestamp_) > 0) {
856 playout_timestamp_ = temp_timestamp;
857 }
858 } else {
859 // Use dead reckoning to estimate the |playout_timestamp_|.
860 playout_timestamp_ += output_size_samples_;
861 }
862
863 if (decode_return_value) return decode_return_value;
864 return return_value;
865}
866
867int NetEqImpl::GetDecision(Operations* operation,
868 PacketList* packet_list,
869 DtmfEvent* dtmf_event,
870 bool* play_dtmf) {
871 // Initialize output variables.
872 *play_dtmf = false;
873 *operation = kUndefined;
874
875 // Increment time counters.
876 packet_buffer_->IncrementWaitingTimes();
877 stats_.IncreaseCounter(output_size_samples_, fs_hz_);
878
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000879 assert(sync_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000880 uint32_t end_timestamp = sync_buffer_->end_timestamp();
881 if (!new_codec_) {
882 packet_buffer_->DiscardOldPackets(end_timestamp);
883 }
884 const RTPHeader* header = packet_buffer_->NextRtpHeader();
885
henrik.lundin@webrtc.orgca8cb952014-03-12 10:26:52 +0000886 if (decision_logic_->CngRfc3389On() || last_mode_ == kModeRfc3389Cng) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000887 // Because of timestamp peculiarities, we have to "manually" disallow using
888 // a CNG packet with the same timestamp as the one that was last played.
889 // This can happen when using redundancy and will cause the timing to shift.
henrik.lundin@webrtc.org24779fe2014-03-14 12:40:05 +0000890 while (header && decoder_database_->IsComfortNoise(header->payloadType) &&
891 (end_timestamp >= header->timestamp ||
892 end_timestamp + decision_logic_->generated_noise_samples() >
893 header->timestamp)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000894 // Don't use this packet, discard it.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000895 if (packet_buffer_->DiscardNextPacket() != PacketBuffer::kOK) {
896 assert(false); // Must be ok by design.
897 }
898 // Check buffer again.
899 if (!new_codec_) {
900 packet_buffer_->DiscardOldPackets(end_timestamp);
901 }
902 header = packet_buffer_->NextRtpHeader();
903 }
904 }
905
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000906 assert(expand_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000907 const int samples_left = static_cast<int>(sync_buffer_->FutureLength() -
908 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000909 if (last_mode_ == kModeAccelerateSuccess ||
910 last_mode_ == kModeAccelerateLowEnergy ||
911 last_mode_ == kModePreemptiveExpandSuccess ||
912 last_mode_ == kModePreemptiveExpandLowEnergy) {
913 // Subtract (samples_left + output_size_samples_) from sampleMemory.
914 decision_logic_->AddSampleMemory(-(samples_left + output_size_samples_));
915 }
916
917 // Check if it is time to play a DTMF event.
918 if (dtmf_buffer_->GetEvent(end_timestamp +
919 decision_logic_->generated_noise_samples(),
920 dtmf_event)) {
921 *play_dtmf = true;
922 }
923
924 // Get instruction.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000925 assert(sync_buffer_.get());
926 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000927 *operation = decision_logic_->GetDecision(*sync_buffer_,
928 *expand_,
929 decoder_frame_length_,
930 header,
931 last_mode_,
932 *play_dtmf,
933 &reset_decoder_);
934
935 // Check if we already have enough samples in the |sync_buffer_|. If so,
936 // change decision to normal, unless the decision was merge, accelerate, or
937 // preemptive expand.
938 if (samples_left >= output_size_samples_ &&
939 *operation != kMerge &&
940 *operation != kAccelerate &&
941 *operation != kPreemptiveExpand) {
942 *operation = kNormal;
943 return 0;
944 }
945
946 decision_logic_->ExpandDecision(*operation == kExpand);
947
948 // Check conditions for reset.
949 if (new_codec_ || *operation == kUndefined) {
950 // The only valid reason to get kUndefined is that new_codec_ is set.
951 assert(new_codec_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000952 if (*play_dtmf && !header) {
953 timestamp_ = dtmf_event->timestamp;
954 } else {
955 assert(header);
956 if (!header) {
957 LOG_F(LS_ERROR) << "Packet missing where it shouldn't.";
958 return -1;
959 }
960 timestamp_ = header->timestamp;
961 if (*operation == kRfc3389CngNoPacket
962#ifndef LEGACY_BITEXACT
963 // Without this check, it can happen that a non-CNG packet is sent to
964 // the CNG decoder as if it was a SID frame. This is clearly a bug,
965 // but is kept for now to maintain bit-exactness with the test
966 // vectors.
967 && decoder_database_->IsComfortNoise(header->payloadType)
968#endif
969 ) {
970 // Change decision to CNG packet, since we do have a CNG packet, but it
971 // was considered too early to use. Now, use it anyway.
972 *operation = kRfc3389Cng;
973 } else if (*operation != kRfc3389Cng) {
974 *operation = kNormal;
975 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000976 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000977 // Adjust |sync_buffer_| timestamp before setting |end_timestamp| to the
978 // new value.
979 sync_buffer_->IncreaseEndTimestamp(timestamp_ - end_timestamp);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000980 end_timestamp = timestamp_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000981 new_codec_ = false;
982 decision_logic_->SoftReset();
983 buffer_level_filter_->Reset();
984 delay_manager_->Reset();
985 stats_.ResetMcu();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000986 }
987
988 int required_samples = output_size_samples_;
989 const int samples_10_ms = 80 * fs_mult_;
990 const int samples_20_ms = 2 * samples_10_ms;
991 const int samples_30_ms = 3 * samples_10_ms;
992
993 switch (*operation) {
994 case kExpand: {
995 timestamp_ = end_timestamp;
996 return 0;
997 }
998 case kRfc3389CngNoPacket:
999 case kCodecInternalCng: {
1000 return 0;
1001 }
1002 case kDtmf: {
1003 // TODO(hlundin): Write test for this.
1004 // Update timestamp.
1005 timestamp_ = end_timestamp;
1006 if (decision_logic_->generated_noise_samples() > 0 &&
1007 last_mode_ != kModeDtmf) {
1008 // Make a jump in timestamp due to the recently played comfort noise.
1009 uint32_t timestamp_jump = decision_logic_->generated_noise_samples();
1010 sync_buffer_->IncreaseEndTimestamp(timestamp_jump);
1011 timestamp_ += timestamp_jump;
1012 }
1013 decision_logic_->set_generated_noise_samples(0);
1014 return 0;
1015 }
1016 case kAccelerate: {
1017 // In order to do a accelerate we need at least 30 ms of audio data.
1018 if (samples_left >= samples_30_ms) {
1019 // Already have enough data, so we do not need to extract any more.
1020 decision_logic_->set_sample_memory(samples_left);
1021 decision_logic_->set_prev_time_scale(true);
1022 return 0;
1023 } else if (samples_left >= samples_10_ms &&
1024 decoder_frame_length_ >= samples_30_ms) {
1025 // Avoid decoding more data as it might overflow the playout buffer.
1026 *operation = kNormal;
1027 return 0;
1028 } else if (samples_left < samples_20_ms &&
1029 decoder_frame_length_ < samples_30_ms) {
1030 // Build up decoded data by decoding at least 20 ms of audio data. Do
1031 // not perform accelerate yet, but wait until we only need to do one
1032 // decoding.
1033 required_samples = 2 * output_size_samples_;
1034 *operation = kNormal;
1035 }
1036 // If none of the above is true, we have one of two possible situations:
1037 // (1) 20 ms <= samples_left < 30 ms and decoder_frame_length_ < 30 ms; or
1038 // (2) samples_left < 10 ms and decoder_frame_length_ >= 30 ms.
1039 // In either case, we move on with the accelerate decision, and decode one
1040 // frame now.
1041 break;
1042 }
1043 case kPreemptiveExpand: {
1044 // In order to do a preemptive expand we need at least 30 ms of decoded
1045 // audio data.
1046 if ((samples_left >= samples_30_ms) ||
1047 (samples_left >= samples_10_ms &&
1048 decoder_frame_length_ >= samples_30_ms)) {
1049 // Already have enough data, so we do not need to extract any more.
1050 // Or, avoid decoding more data as it might overflow the playout buffer.
1051 // Still try preemptive expand, though.
1052 decision_logic_->set_sample_memory(samples_left);
1053 decision_logic_->set_prev_time_scale(true);
1054 return 0;
1055 }
1056 if (samples_left < samples_20_ms &&
1057 decoder_frame_length_ < samples_30_ms) {
1058 // Build up decoded data by decoding at least 20 ms of audio data.
1059 // Still try to perform preemptive expand.
1060 required_samples = 2 * output_size_samples_;
1061 }
1062 // Move on with the preemptive expand decision.
1063 break;
1064 }
1065 default: {
1066 // Do nothing.
1067 }
1068 }
1069
1070 // Get packets from buffer.
1071 int extracted_samples = 0;
1072 if (header &&
1073 *operation != kAlternativePlc &&
1074 *operation != kAlternativePlcIncreaseTimestamp &&
1075 *operation != kAudioRepetition &&
1076 *operation != kAudioRepetitionIncreaseTimestamp) {
1077 sync_buffer_->IncreaseEndTimestamp(header->timestamp - end_timestamp);
1078 if (decision_logic_->CngOff()) {
1079 // Adjustment of timestamp only corresponds to an actual packet loss
1080 // if comfort noise is not played. If comfort noise was just played,
1081 // this adjustment of timestamp is only done to get back in sync with the
1082 // stream timestamp; no loss to report.
1083 stats_.LostSamples(header->timestamp - end_timestamp);
1084 }
1085
1086 if (*operation != kRfc3389Cng) {
1087 // We are about to decode and use a non-CNG packet.
1088 decision_logic_->SetCngOff();
1089 }
1090 // Reset CNG timestamp as a new packet will be delivered.
1091 // (Also if this is a CNG packet, since playedOutTS is updated.)
1092 decision_logic_->set_generated_noise_samples(0);
1093
1094 extracted_samples = ExtractPackets(required_samples, packet_list);
1095 if (extracted_samples < 0) {
1096 LOG_F(LS_WARNING) << "Failed to extract packets from buffer.";
1097 return kPacketBufferCorruption;
1098 }
1099 }
1100
1101 if (*operation == kAccelerate ||
1102 *operation == kPreemptiveExpand) {
1103 decision_logic_->set_sample_memory(samples_left + extracted_samples);
1104 decision_logic_->set_prev_time_scale(true);
1105 }
1106
1107 if (*operation == kAccelerate) {
1108 // Check that we have enough data (30ms) to do accelerate.
1109 if (extracted_samples + samples_left < samples_30_ms) {
1110 // TODO(hlundin): Write test for this.
1111 // Not enough, do normal operation instead.
1112 *operation = kNormal;
1113 }
1114 }
1115
1116 timestamp_ = end_timestamp;
1117 return 0;
1118}
1119
1120int NetEqImpl::Decode(PacketList* packet_list, Operations* operation,
1121 int* decoded_length,
1122 AudioDecoder::SpeechType* speech_type) {
1123 *speech_type = AudioDecoder::kSpeech;
1124 AudioDecoder* decoder = NULL;
1125 if (!packet_list->empty()) {
1126 const Packet* packet = packet_list->front();
1127 int payload_type = packet->header.payloadType;
1128 if (!decoder_database_->IsComfortNoise(payload_type)) {
1129 decoder = decoder_database_->GetDecoder(payload_type);
1130 assert(decoder);
1131 if (!decoder) {
1132 LOG_FERR1(LS_WARNING, GetDecoder, payload_type);
1133 PacketBuffer::DeleteAllPackets(packet_list);
1134 return kDecoderNotFound;
1135 }
1136 bool decoder_changed;
1137 decoder_database_->SetActiveDecoder(payload_type, &decoder_changed);
1138 if (decoder_changed) {
1139 // We have a new decoder. Re-init some values.
1140 const DecoderDatabase::DecoderInfo* decoder_info = decoder_database_
1141 ->GetDecoderInfo(payload_type);
1142 assert(decoder_info);
1143 if (!decoder_info) {
1144 LOG_FERR1(LS_WARNING, GetDecoderInfo, payload_type);
1145 PacketBuffer::DeleteAllPackets(packet_list);
1146 return kDecoderNotFound;
1147 }
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001148 // If sampling rate or number of channels has changed, we need to make
1149 // a reset.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001150 if (decoder_info->fs_hz != fs_hz_ ||
1151 decoder->channels() != algorithm_buffer_->Channels()) {
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001152 // TODO(tlegrand): Add unittest to cover this event.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001153 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->channels());
1154 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001155 sync_buffer_->set_end_timestamp(timestamp_);
1156 playout_timestamp_ = timestamp_;
1157 }
1158 }
1159 }
1160
1161 if (reset_decoder_) {
1162 // TODO(hlundin): Write test for this.
1163 // Reset decoder.
1164 if (decoder) {
1165 decoder->Init();
1166 }
1167 // Reset comfort noise decoder.
1168 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
1169 if (cng_decoder) {
1170 cng_decoder->Init();
1171 }
1172 reset_decoder_ = false;
1173 }
1174
1175#ifdef LEGACY_BITEXACT
1176 // Due to a bug in old SignalMCU, it could happen that CNG operation was
1177 // decided, but a speech packet was provided. The speech packet will be used
1178 // to update the comfort noise decoder, as if it was a SID frame, which is
1179 // clearly wrong.
1180 if (*operation == kRfc3389Cng) {
1181 return 0;
1182 }
1183#endif
1184
1185 *decoded_length = 0;
1186 // Update codec-internal PLC state.
1187 if ((*operation == kMerge) && decoder && decoder->HasDecodePlc()) {
1188 decoder->DecodePlc(1, &decoded_buffer_[*decoded_length]);
1189 }
1190
1191 int return_value = DecodeLoop(packet_list, operation, decoder,
1192 decoded_length, speech_type);
1193
1194 if (*decoded_length < 0) {
1195 // Error returned from the decoder.
1196 *decoded_length = 0;
1197 sync_buffer_->IncreaseEndTimestamp(decoder_frame_length_);
1198 int error_code = 0;
1199 if (decoder)
1200 error_code = decoder->ErrorCode();
1201 if (error_code != 0) {
1202 // Got some error code from the decoder.
1203 decoder_error_code_ = error_code;
1204 return_value = kDecoderErrorCode;
1205 } else {
1206 // Decoder does not implement error codes. Return generic error.
1207 return_value = kOtherDecoderError;
1208 }
1209 LOG_FERR2(LS_WARNING, DecodeLoop, error_code, packet_list->size());
1210 *operation = kExpand; // Do expansion to get data instead.
1211 }
1212 if (*speech_type != AudioDecoder::kComfortNoise) {
1213 // Don't increment timestamp if codec returned CNG speech type
1214 // since in this case, the we will increment the CNGplayedTS counter.
1215 // Increase with number of samples per channel.
1216 assert(*decoded_length == 0 ||
1217 (decoder && decoder->channels() == sync_buffer_->Channels()));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001218 sync_buffer_->IncreaseEndTimestamp(
1219 *decoded_length / static_cast<int>(sync_buffer_->Channels()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001220 }
1221 return return_value;
1222}
1223
1224int NetEqImpl::DecodeLoop(PacketList* packet_list, Operations* operation,
1225 AudioDecoder* decoder, int* decoded_length,
1226 AudioDecoder::SpeechType* speech_type) {
1227 Packet* packet = NULL;
1228 if (!packet_list->empty()) {
1229 packet = packet_list->front();
1230 }
1231 // Do decoding.
1232 while (packet &&
1233 !decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1234 assert(decoder); // At this point, we must have a decoder object.
1235 // The number of channels in the |sync_buffer_| should be the same as the
1236 // number decoder channels.
1237 assert(sync_buffer_->Channels() == decoder->channels());
1238 assert(decoded_buffer_length_ >= kMaxFrameSize * decoder->channels());
1239 assert(*operation == kNormal || *operation == kAccelerate ||
1240 *operation == kMerge || *operation == kPreemptiveExpand);
1241 packet_list->pop_front();
henrik.lundin@webrtc.org63464a92013-01-30 09:41:56 +00001242 int payload_length = packet->payload_length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001243 int16_t decode_length;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +00001244 if (packet->sync_packet) {
1245 // Decode to silence with the same frame size as the last decode.
1246 LOG(LS_VERBOSE) << "Decoding sync-packet: " <<
1247 " ts=" << packet->header.timestamp <<
1248 ", sn=" << packet->header.sequenceNumber <<
1249 ", pt=" << static_cast<int>(packet->header.payloadType) <<
1250 ", ssrc=" << packet->header.ssrc <<
1251 ", len=" << packet->payload_length;
1252 memset(&decoded_buffer_[*decoded_length], 0, decoder_frame_length_ *
1253 decoder->channels() * sizeof(decoded_buffer_[0]));
1254 decode_length = decoder_frame_length_;
1255 } else if (!packet->primary) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001256 // This is a redundant payload; call the special decoder method.
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +00001257 LOG(LS_VERBOSE) << "Decoding packet (redundant):" <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001258 " ts=" << packet->header.timestamp <<
1259 ", sn=" << packet->header.sequenceNumber <<
1260 ", pt=" << static_cast<int>(packet->header.payloadType) <<
1261 ", ssrc=" << packet->header.ssrc <<
1262 ", len=" << packet->payload_length;
1263 decode_length = decoder->DecodeRedundant(
1264 packet->payload, packet->payload_length,
1265 &decoded_buffer_[*decoded_length], speech_type);
1266 } else {
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +00001267 LOG(LS_VERBOSE) << "Decoding packet: ts=" << packet->header.timestamp <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001268 ", sn=" << packet->header.sequenceNumber <<
1269 ", pt=" << static_cast<int>(packet->header.payloadType) <<
1270 ", ssrc=" << packet->header.ssrc <<
1271 ", len=" << packet->payload_length;
1272 decode_length = decoder->Decode(packet->payload,
1273 packet->payload_length,
1274 &decoded_buffer_[*decoded_length],
1275 speech_type);
1276 }
1277
1278 delete[] packet->payload;
1279 delete packet;
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001280 packet = NULL;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001281 if (decode_length > 0) {
1282 *decoded_length += decode_length;
1283 // Update |decoder_frame_length_| with number of samples per channel.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001284 decoder_frame_length_ = decode_length /
1285 static_cast<int>(decoder->channels());
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +00001286 LOG(LS_VERBOSE) << "Decoded " << decode_length << " samples (" <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001287 decoder->channels() << " channel(s) -> " << decoder_frame_length_ <<
1288 " samples per channel)";
1289 } else if (decode_length < 0) {
1290 // Error.
henrik.lundin@webrtc.org63464a92013-01-30 09:41:56 +00001291 LOG_FERR2(LS_WARNING, Decode, decode_length, payload_length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001292 *decoded_length = -1;
1293 PacketBuffer::DeleteAllPackets(packet_list);
1294 break;
1295 }
1296 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1297 // Guard against overflow.
1298 LOG_F(LS_WARNING) << "Decoded too much.";
1299 PacketBuffer::DeleteAllPackets(packet_list);
1300 return kDecodedTooMuch;
1301 }
1302 if (!packet_list->empty()) {
1303 packet = packet_list->front();
1304 } else {
1305 packet = NULL;
1306 }
1307 } // End of decode loop.
1308
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001309 // If the list is not empty at this point, either a decoding error terminated
1310 // the while-loop, or list must hold exactly one CNG packet.
1311 assert(packet_list->empty() || *decoded_length < 0 ||
1312 (packet_list->size() == 1 && packet &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001313 decoder_database_->IsComfortNoise(packet->header.payloadType)));
1314 return 0;
1315}
1316
1317void NetEqImpl::DoNormal(const int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001318 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001319 assert(normal_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001320 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001321 normal_->Process(decoded_buffer, decoded_length, last_mode_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001322 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001323 if (decoded_length != 0) {
1324 last_mode_ = kModeNormal;
1325 }
1326
1327 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1328 if ((speech_type == AudioDecoder::kComfortNoise)
1329 || ((last_mode_ == kModeCodecInternalCng)
1330 && (decoded_length == 0))) {
1331 // TODO(hlundin): Remove second part of || statement above.
1332 last_mode_ = kModeCodecInternalCng;
1333 }
1334
1335 if (!play_dtmf) {
1336 dtmf_tone_generator_->Reset();
1337 }
1338}
1339
1340void NetEqImpl::DoMerge(int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001341 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001342 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001343 assert(merge_.get());
1344 int new_length = merge_->Process(decoded_buffer, decoded_length,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001345 mute_factor_array_.get(),
1346 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001347
1348 // Update in-call and post-call statistics.
1349 if (expand_->MuteFactor(0) == 0) {
1350 // Expand generates only noise.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001351 stats_.ExpandedNoiseSamples(new_length - static_cast<int>(decoded_length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001352 } else {
1353 // Expansion generates more than only noise.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001354 stats_.ExpandedVoiceSamples(new_length - static_cast<int>(decoded_length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001355 }
1356
1357 last_mode_ = kModeMerge;
1358 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1359 if (speech_type == AudioDecoder::kComfortNoise) {
1360 last_mode_ = kModeCodecInternalCng;
1361 }
1362 expand_->Reset();
1363 if (!play_dtmf) {
1364 dtmf_tone_generator_->Reset();
1365 }
1366}
1367
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001368int NetEqImpl::DoExpand(bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001369 while ((sync_buffer_->FutureLength() - expand_->overlap_length()) <
1370 static_cast<size_t>(output_size_samples_)) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001371 algorithm_buffer_->Clear();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001372 int return_value = expand_->Process(algorithm_buffer_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001373 int length = static_cast<int>(algorithm_buffer_->Size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001374
1375 // Update in-call and post-call statistics.
1376 if (expand_->MuteFactor(0) == 0) {
1377 // Expand operation generates only noise.
1378 stats_.ExpandedNoiseSamples(length);
1379 } else {
1380 // Expand operation generates more than only noise.
1381 stats_.ExpandedVoiceSamples(length);
1382 }
1383
1384 last_mode_ = kModeExpand;
1385
1386 if (return_value < 0) {
1387 return return_value;
1388 }
1389
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001390 sync_buffer_->PushBack(*algorithm_buffer_);
1391 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001392 }
1393 if (!play_dtmf) {
1394 dtmf_tone_generator_->Reset();
1395 }
1396 return 0;
1397}
1398
1399int NetEqImpl::DoAccelerate(int16_t* decoded_buffer, size_t decoded_length,
1400 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001401 bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001402 const size_t required_samples = 240 * fs_mult_; // Must have 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001403 size_t borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001404 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001405 size_t decoded_length_per_channel = decoded_length / num_channels;
1406 if (decoded_length_per_channel < required_samples) {
1407 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001408 borrowed_samples_per_channel = static_cast<int>(required_samples -
1409 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001410 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1411 decoded_buffer,
1412 sizeof(int16_t) * decoded_length);
1413 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1414 decoded_buffer);
1415 decoded_length = required_samples * num_channels;
1416 }
1417
1418 int16_t samples_removed;
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001419 Accelerate::ReturnCodes return_code = accelerate_->Process(
1420 decoded_buffer, decoded_length, algorithm_buffer_.get(),
1421 &samples_removed);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001422 stats_.AcceleratedSamples(samples_removed);
1423 switch (return_code) {
1424 case Accelerate::kSuccess:
1425 last_mode_ = kModeAccelerateSuccess;
1426 break;
1427 case Accelerate::kSuccessLowEnergy:
1428 last_mode_ = kModeAccelerateLowEnergy;
1429 break;
1430 case Accelerate::kNoStretch:
1431 last_mode_ = kModeAccelerateFail;
1432 break;
1433 case Accelerate::kError:
1434 // TODO(hlundin): Map to kModeError instead?
1435 last_mode_ = kModeAccelerateFail;
1436 return kAccelerateError;
1437 }
1438
1439 if (borrowed_samples_per_channel > 0) {
1440 // Copy borrowed samples back to the |sync_buffer_|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001441 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001442 if (length < borrowed_samples_per_channel) {
1443 // This destroys the beginning of the buffer, but will not cause any
1444 // problems.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001445 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001446 sync_buffer_->Size() -
1447 borrowed_samples_per_channel);
1448 sync_buffer_->PushFrontZeros(borrowed_samples_per_channel - length);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001449 algorithm_buffer_->PopFront(length);
1450 assert(algorithm_buffer_->Empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001451 } else {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001452 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001453 borrowed_samples_per_channel,
1454 sync_buffer_->Size() -
1455 borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001456 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001457 }
1458 }
1459
1460 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1461 if (speech_type == AudioDecoder::kComfortNoise) {
1462 last_mode_ = kModeCodecInternalCng;
1463 }
1464 if (!play_dtmf) {
1465 dtmf_tone_generator_->Reset();
1466 }
1467 expand_->Reset();
1468 return 0;
1469}
1470
1471int NetEqImpl::DoPreemptiveExpand(int16_t* decoded_buffer,
1472 size_t decoded_length,
1473 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001474 bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001475 const size_t required_samples = 240 * fs_mult_; // Must have 30 ms.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001476 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001477 int borrowed_samples_per_channel = 0;
1478 int old_borrowed_samples_per_channel = 0;
1479 size_t decoded_length_per_channel = decoded_length / num_channels;
1480 if (decoded_length_per_channel < required_samples) {
1481 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001482 borrowed_samples_per_channel = static_cast<int>(required_samples -
1483 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001484 // Calculate how many of these were already played out.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001485 old_borrowed_samples_per_channel = static_cast<int>(
1486 borrowed_samples_per_channel - sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001487 old_borrowed_samples_per_channel = std::max(
1488 0, old_borrowed_samples_per_channel);
1489 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1490 decoded_buffer,
1491 sizeof(int16_t) * decoded_length);
1492 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1493 decoded_buffer);
1494 decoded_length = required_samples * num_channels;
1495 }
1496
1497 int16_t samples_added;
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001498 PreemptiveExpand::ReturnCodes return_code = preemptive_expand_->Process(
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001499 decoded_buffer, static_cast<int>(decoded_length),
1500 old_borrowed_samples_per_channel,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001501 algorithm_buffer_.get(), &samples_added);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001502 stats_.PreemptiveExpandedSamples(samples_added);
1503 switch (return_code) {
1504 case PreemptiveExpand::kSuccess:
1505 last_mode_ = kModePreemptiveExpandSuccess;
1506 break;
1507 case PreemptiveExpand::kSuccessLowEnergy:
1508 last_mode_ = kModePreemptiveExpandLowEnergy;
1509 break;
1510 case PreemptiveExpand::kNoStretch:
1511 last_mode_ = kModePreemptiveExpandFail;
1512 break;
1513 case PreemptiveExpand::kError:
1514 // TODO(hlundin): Map to kModeError instead?
1515 last_mode_ = kModePreemptiveExpandFail;
1516 return kPreemptiveExpandError;
1517 }
1518
1519 if (borrowed_samples_per_channel > 0) {
1520 // Copy borrowed samples back to the |sync_buffer_|.
1521 sync_buffer_->ReplaceAtIndex(
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001522 *algorithm_buffer_, borrowed_samples_per_channel,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001523 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001524 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001525 }
1526
1527 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1528 if (speech_type == AudioDecoder::kComfortNoise) {
1529 last_mode_ = kModeCodecInternalCng;
1530 }
1531 if (!play_dtmf) {
1532 dtmf_tone_generator_->Reset();
1533 }
1534 expand_->Reset();
1535 return 0;
1536}
1537
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001538int NetEqImpl::DoRfc3389Cng(PacketList* packet_list, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001539 if (!packet_list->empty()) {
1540 // Must have exactly one SID frame at this point.
1541 assert(packet_list->size() == 1);
1542 Packet* packet = packet_list->front();
1543 packet_list->pop_front();
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001544 if (!decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1545#ifdef LEGACY_BITEXACT
1546 // This can happen due to a bug in GetDecision. Change the payload type
1547 // to a CNG type, and move on. Note that this means that we are in fact
1548 // sending a non-CNG payload to the comfort noise decoder for decoding.
1549 // Clearly wrong, but will maintain bit-exactness with legacy.
1550 if (fs_hz_ == 8000) {
1551 packet->header.payloadType =
1552 decoder_database_->GetRtpPayloadType(kDecoderCNGnb);
1553 } else if (fs_hz_ == 16000) {
1554 packet->header.payloadType =
1555 decoder_database_->GetRtpPayloadType(kDecoderCNGwb);
1556 } else if (fs_hz_ == 32000) {
1557 packet->header.payloadType =
1558 decoder_database_->GetRtpPayloadType(kDecoderCNGswb32kHz);
1559 } else if (fs_hz_ == 48000) {
1560 packet->header.payloadType =
1561 decoder_database_->GetRtpPayloadType(kDecoderCNGswb48kHz);
1562 }
1563 assert(decoder_database_->IsComfortNoise(packet->header.payloadType));
1564#else
1565 LOG(LS_ERROR) << "Trying to decode non-CNG payload as CNG.";
1566 return kOtherError;
1567#endif
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001568 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001569 // UpdateParameters() deletes |packet|.
1570 if (comfort_noise_->UpdateParameters(packet) ==
1571 ComfortNoise::kInternalError) {
1572 LOG_FERR0(LS_WARNING, UpdateParameters);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001573 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001574 return -comfort_noise_->internal_error_code();
1575 }
1576 }
1577 int cn_return = comfort_noise_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001578 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001579 expand_->Reset();
1580 last_mode_ = kModeRfc3389Cng;
1581 if (!play_dtmf) {
1582 dtmf_tone_generator_->Reset();
1583 }
1584 if (cn_return == ComfortNoise::kInternalError) {
1585 LOG_FERR1(LS_WARNING, comfort_noise_->Generate, cn_return);
1586 decoder_error_code_ = comfort_noise_->internal_error_code();
1587 return kComfortNoiseErrorCode;
1588 } else if (cn_return == ComfortNoise::kUnknownPayloadType) {
1589 LOG_FERR1(LS_WARNING, comfort_noise_->Generate, cn_return);
1590 return kUnknownRtpPayloadType;
1591 }
1592 return 0;
1593}
1594
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001595void NetEqImpl::DoCodecInternalCng() {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001596 int length = 0;
1597 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1598 int16_t decoded_buffer[kMaxFrameSize];
1599 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1600 if (decoder) {
1601 const uint8_t* dummy_payload = NULL;
1602 AudioDecoder::SpeechType speech_type;
1603 length = decoder->Decode(dummy_payload, 0, decoded_buffer, &speech_type);
1604 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001605 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001606 normal_->Process(decoded_buffer, length, last_mode_, mute_factor_array_.get(),
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001607 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001608 last_mode_ = kModeCodecInternalCng;
1609 expand_->Reset();
1610}
1611
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001612int NetEqImpl::DoDtmf(const DtmfEvent& dtmf_event, bool* play_dtmf) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001613 // This block of the code and the block further down, handling |dtmf_switch|
1614 // are commented out. Otherwise playing out-of-band DTMF would fail in VoE
1615 // test, DtmfTest.ManualSuccessfullySendsOutOfBandTelephoneEvents. This is
1616 // equivalent to |dtmf_switch| always be false.
1617 //
1618 // See http://webrtc-codereview.appspot.com/1195004/ for discussion
1619 // On this issue. This change might cause some glitches at the point of
1620 // switch from audio to DTMF. Issue 1545 is filed to track this.
1621 //
1622 // bool dtmf_switch = false;
1623 // if ((last_mode_ != kModeDtmf) && dtmf_tone_generator_->initialized()) {
1624 // // Special case; see below.
1625 // // We must catch this before calling Generate, since |initialized| is
1626 // // modified in that call.
1627 // dtmf_switch = true;
1628 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001629
1630 int dtmf_return_value = 0;
1631 if (!dtmf_tone_generator_->initialized()) {
1632 // Initialize if not already done.
1633 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1634 dtmf_event.volume);
1635 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001636
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001637 if (dtmf_return_value == 0) {
1638 // Generate DTMF signal.
1639 dtmf_return_value = dtmf_tone_generator_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001640 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001641 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001642
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001643 if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001644 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001645 return dtmf_return_value;
1646 }
1647
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001648 // if (dtmf_switch) {
1649 // // This is the special case where the previous operation was DTMF
1650 // // overdub, but the current instruction is "regular" DTMF. We must make
1651 // // sure that the DTMF does not have any discontinuities. The first DTMF
1652 // // sample that we generate now must be played out immediately, therefore
1653 // // it must be copied to the speech buffer.
1654 // // TODO(hlundin): This code seems incorrect. (Legacy.) Write test and
1655 // // verify correct operation.
1656 // assert(false);
1657 // // Must generate enough data to replace all of the |sync_buffer_|
1658 // // "future".
1659 // int required_length = sync_buffer_->FutureLength();
1660 // assert(dtmf_tone_generator_->initialized());
1661 // dtmf_return_value = dtmf_tone_generator_->Generate(required_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001662 // algorithm_buffer_);
1663 // assert((size_t) required_length == algorithm_buffer_->Size());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001664 // if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001665 // algorithm_buffer_->Zeros(output_size_samples_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001666 // return dtmf_return_value;
1667 // }
1668 //
1669 // // Overwrite the "future" part of the speech buffer with the new DTMF
1670 // // data.
1671 // // TODO(hlundin): It seems that this overwriting has gone lost.
1672 // // Not adapted for multi-channel yet.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001673 // assert(algorithm_buffer_->Channels() == 1);
1674 // if (algorithm_buffer_->Channels() != 1) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001675 // LOG(LS_WARNING) << "DTMF not supported for more than one channel";
1676 // return kStereoNotSupported;
1677 // }
1678 // // Shuffle the remaining data to the beginning of algorithm buffer.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001679 // algorithm_buffer_->PopFront(sync_buffer_->FutureLength());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001680 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001681
1682 sync_buffer_->IncreaseEndTimestamp(output_size_samples_);
1683 expand_->Reset();
1684 last_mode_ = kModeDtmf;
1685
1686 // Set to false because the DTMF is already in the algorithm buffer.
1687 *play_dtmf = false;
1688 return 0;
1689}
1690
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001691void NetEqImpl::DoAlternativePlc(bool increase_timestamp) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001692 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1693 int length;
1694 if (decoder && decoder->HasDecodePlc()) {
1695 // Use the decoder's packet-loss concealment.
1696 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1697 int16_t decoded_buffer[kMaxFrameSize];
1698 length = decoder->DecodePlc(1, decoded_buffer);
1699 if (length > 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001700 algorithm_buffer_->PushBackInterleaved(decoded_buffer, length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001701 } else {
1702 length = 0;
1703 }
1704 } else {
1705 // Do simple zero-stuffing.
1706 length = output_size_samples_;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001707 algorithm_buffer_->Zeros(length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001708 // By not advancing the timestamp, NetEq inserts samples.
1709 stats_.AddZeros(length);
1710 }
1711 if (increase_timestamp) {
1712 sync_buffer_->IncreaseEndTimestamp(length);
1713 }
1714 expand_->Reset();
1715}
1716
1717int NetEqImpl::DtmfOverdub(const DtmfEvent& dtmf_event, size_t num_channels,
1718 int16_t* output) const {
1719 size_t out_index = 0;
1720 int overdub_length = output_size_samples_; // Default value.
1721
1722 if (sync_buffer_->dtmf_index() > sync_buffer_->next_index()) {
1723 // Special operation for transition from "DTMF only" to "DTMF overdub".
1724 out_index = std::min(
1725 sync_buffer_->dtmf_index() - sync_buffer_->next_index(),
1726 static_cast<size_t>(output_size_samples_));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001727 overdub_length = output_size_samples_ - static_cast<int>(out_index);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001728 }
1729
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001730 AudioMultiVector dtmf_output(num_channels);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001731 int dtmf_return_value = 0;
1732 if (!dtmf_tone_generator_->initialized()) {
1733 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1734 dtmf_event.volume);
1735 }
1736 if (dtmf_return_value == 0) {
1737 dtmf_return_value = dtmf_tone_generator_->Generate(overdub_length,
1738 &dtmf_output);
1739 assert((size_t) overdub_length == dtmf_output.Size());
1740 }
1741 dtmf_output.ReadInterleaved(overdub_length, &output[out_index]);
1742 return dtmf_return_value < 0 ? dtmf_return_value : 0;
1743}
1744
1745int NetEqImpl::ExtractPackets(int required_samples, PacketList* packet_list) {
1746 bool first_packet = true;
1747 uint8_t prev_payload_type = 0;
1748 uint32_t prev_timestamp = 0;
1749 uint16_t prev_sequence_number = 0;
1750 bool next_packet_available = false;
1751
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001752 const RTPHeader* header = packet_buffer_->NextRtpHeader();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001753 assert(header);
1754 if (!header) {
1755 return -1;
1756 }
turaj@webrtc.org7df97062013-08-02 18:07:13 +00001757 uint32_t first_timestamp = header->timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001758 int extracted_samples = 0;
1759
1760 // Packet extraction loop.
1761 do {
1762 timestamp_ = header->timestamp;
1763 int discard_count = 0;
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001764 Packet* packet = packet_buffer_->GetNextPacket(&discard_count);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001765 // |header| may be invalid after the |packet_buffer_| operation.
1766 header = NULL;
1767 if (!packet) {
1768 LOG_FERR1(LS_ERROR, GetNextPacket, discard_count) <<
1769 "Should always be able to extract a packet here";
1770 assert(false); // Should always be able to extract a packet here.
1771 return -1;
1772 }
1773 stats_.PacketsDiscarded(discard_count);
1774 // Store waiting time in ms; packets->waiting_time is in "output blocks".
1775 stats_.StoreWaitingTime(packet->waiting_time * kOutputSizeMs);
1776 assert(packet->payload_length > 0);
1777 packet_list->push_back(packet); // Store packet in list.
1778
1779 if (first_packet) {
1780 first_packet = false;
minyue@webrtc.orgd7301772013-08-29 00:58:14 +00001781 decoded_packet_sequence_number_ = prev_sequence_number =
1782 packet->header.sequenceNumber;
1783 decoded_packet_timestamp_ = prev_timestamp = packet->header.timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001784 prev_payload_type = packet->header.payloadType;
1785 }
1786
1787 // Store number of extracted samples.
1788 int packet_duration = 0;
1789 AudioDecoder* decoder = decoder_database_->GetDecoder(
1790 packet->header.payloadType);
1791 if (decoder) {
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001792 if (packet->sync_packet) {
1793 packet_duration = decoder_frame_length_;
1794 } else {
1795 packet_duration = packet->primary ?
1796 decoder->PacketDuration(packet->payload, packet->payload_length) :
1797 decoder->PacketDurationRedundant(packet->payload,
1798 packet->payload_length);
1799 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001800 } else {
1801 LOG_FERR1(LS_WARNING, GetDecoder, packet->header.payloadType) <<
1802 "Could not find a decoder for a packet about to be extracted.";
1803 assert(false);
1804 }
1805 if (packet_duration <= 0) {
1806 // Decoder did not return a packet duration. Assume that the packet
1807 // contains the same number of samples as the previous one.
1808 packet_duration = decoder_frame_length_;
1809 }
1810 extracted_samples = packet->header.timestamp - first_timestamp +
1811 packet_duration;
1812
1813 // Check what packet is available next.
1814 header = packet_buffer_->NextRtpHeader();
1815 next_packet_available = false;
1816 if (header && prev_payload_type == header->payloadType) {
1817 int16_t seq_no_diff = header->sequenceNumber - prev_sequence_number;
1818 int32_t ts_diff = header->timestamp - prev_timestamp;
1819 if (seq_no_diff == 1 ||
1820 (seq_no_diff == 0 && ts_diff == decoder_frame_length_)) {
1821 // The next sequence number is available, or the next part of a packet
1822 // that was split into pieces upon insertion.
1823 next_packet_available = true;
1824 }
1825 prev_sequence_number = header->sequenceNumber;
1826 }
1827 } while (extracted_samples < required_samples && next_packet_available);
1828
1829 return extracted_samples;
1830}
1831
1832void NetEqImpl::SetSampleRateAndChannels(int fs_hz, size_t channels) {
1833 LOG_API2(fs_hz, channels);
1834 // TODO(hlundin): Change to an enumerator and skip assert.
1835 assert(fs_hz == 8000 || fs_hz == 16000 || fs_hz == 32000 || fs_hz == 48000);
1836 assert(channels > 0);
1837
1838 fs_hz_ = fs_hz;
1839 fs_mult_ = fs_hz / 8000;
1840 output_size_samples_ = kOutputSizeMs * 8 * fs_mult_;
1841 decoder_frame_length_ = 3 * output_size_samples_; // Initialize to 30ms.
1842
1843 last_mode_ = kModeNormal;
1844
1845 // Create a new array of mute factors and set all to 1.
1846 mute_factor_array_.reset(new int16_t[channels]);
1847 for (size_t i = 0; i < channels; ++i) {
1848 mute_factor_array_[i] = 16384; // 1.0 in Q14.
1849 }
1850
1851 // Reset comfort noise decoder, if there is one active.
1852 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
1853 if (cng_decoder) {
1854 cng_decoder->Init();
1855 }
1856
1857 // Reinit post-decode VAD with new sample rate.
1858 assert(vad_.get()); // Cannot be NULL here.
1859 vad_->Init();
1860
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001861 // Delete algorithm buffer and create a new one.
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001862 algorithm_buffer_.reset(new AudioMultiVector(channels));
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001863
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001864 // Delete sync buffer and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001865 sync_buffer_.reset(new SyncBuffer(channels, kSyncBufferSize * fs_mult_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001866
turaj@webrtc.orgff43c852013-09-25 00:07:27 +00001867
1868 // Delete BackgroundNoise object and create a new one, while preserving its
1869 // mode.
1870 NetEqBackgroundNoiseMode current_mode = kBgnOn;
1871 if (background_noise_.get())
1872 current_mode = background_noise_->mode();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001873 background_noise_.reset(new BackgroundNoise(channels));
turaj@webrtc.orgff43c852013-09-25 00:07:27 +00001874 background_noise_->set_mode(current_mode);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001875
1876 // Reset random vector.
1877 random_vector_.Reset();
1878
1879 // Delete Expand object and create a new one.
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +00001880 expand_.reset(expand_factory_->Create(background_noise_.get(),
1881 sync_buffer_.get(), &random_vector_,
1882 fs_hz, channels));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001883 // Move index so that we create a small set of future samples (all 0).
1884 sync_buffer_->set_next_index(sync_buffer_->next_index() -
1885 expand_->overlap_length());
1886
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001887 normal_.reset(new Normal(fs_hz, decoder_database_.get(), *background_noise_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001888 expand_.get()));
1889 merge_.reset(new Merge(fs_hz, channels, expand_.get(), sync_buffer_.get()));
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +00001890 accelerate_.reset(
1891 accelerate_factory_->Create(fs_hz, channels, *background_noise_));
1892 preemptive_expand_.reset(
1893 preemptive_expand_factory_->Create(fs_hz, channels, *background_noise_));
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001894
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001895 // Delete ComfortNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001896 comfort_noise_.reset(new ComfortNoise(fs_hz, decoder_database_.get(),
1897 sync_buffer_.get()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001898
1899 // Verify that |decoded_buffer_| is long enough.
1900 if (decoded_buffer_length_ < kMaxFrameSize * channels) {
1901 // Reallocate to larger size.
1902 decoded_buffer_length_ = kMaxFrameSize * channels;
1903 decoded_buffer_.reset(new int16_t[decoded_buffer_length_]);
1904 }
1905
1906 // Communicate new sample rate and output size to DecisionLogic object.
1907 assert(decision_logic_.get());
1908 decision_logic_->SetSampleRate(fs_hz_, output_size_samples_);
1909}
1910
1911NetEqOutputType NetEqImpl::LastOutputType() {
1912 assert(vad_.get());
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001913 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001914 if (last_mode_ == kModeCodecInternalCng || last_mode_ == kModeRfc3389Cng) {
1915 return kOutputCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001916 } else if (last_mode_ == kModeExpand && expand_->MuteFactor(0) == 0) {
1917 // Expand mode has faded down to background noise only (very long expand).
1918 return kOutputPLCtoCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001919 } else if (last_mode_ == kModeExpand) {
1920 return kOutputPLC;
wu@webrtc.org24301a62013-12-13 19:17:43 +00001921 } else if (vad_->running() && !vad_->active_speech()) {
1922 return kOutputVADPassive;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001923 } else {
1924 return kOutputNormal;
1925 }
1926}
1927
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001928} // namespace webrtc