blob: e407ee83ec05803cc0c7c866a8407a07fed66f61 [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,
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),
80 mute_factor_array_(NULL),
81 decoded_buffer_length_(kMaxFrameSize),
82 decoded_buffer_(new int16_t[decoded_buffer_length_]),
83 playout_timestamp_(0),
84 new_codec_(false),
85 timestamp_(0),
86 reset_decoder_(false),
87 current_rtp_payload_type_(0xFF), // Invalid RTP payload type.
88 current_cng_rtp_payload_type_(0xFF), // Invalid RTP payload type.
89 ssrc_(0),
90 first_packet_(true),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000091 error_code_(0),
92 decoder_error_code_(0),
minyue@webrtc.orgd7301772013-08-29 00:58:14 +000093 crit_sect_(CriticalSectionWrapper::CreateCriticalSection()),
94 decoded_packet_sequence_number_(-1),
95 decoded_packet_timestamp_(0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000096 if (fs != 8000 && fs != 16000 && fs != 32000 && fs != 48000) {
97 LOG(LS_ERROR) << "Sample rate " << fs << " Hz not supported. " <<
98 "Changing to 8000 Hz.";
99 fs = 8000;
100 }
andrew@webrtc.org0569d932014-04-09 17:48:48 +0000101 LOG(LS_VERBOSE) << "Create NetEqImpl object with fs = " << fs << ".";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000102 fs_hz_ = fs;
103 fs_mult_ = fs / 8000;
104 output_size_samples_ = kOutputSizeMs * 8 * fs_mult_;
105 decoder_frame_length_ = 3 * output_size_samples_;
106 WebRtcSpl_Init();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000107 if (create_components) {
108 SetSampleRateAndChannels(fs, 1); // Default is 1 channel.
109 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000110}
111
112NetEqImpl::~NetEqImpl() {
113 LOG(LS_INFO) << "Deleting NetEqImpl object.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000114}
115
116int NetEqImpl::InsertPacket(const WebRtcRTPHeader& rtp_header,
117 const uint8_t* payload,
118 int length_bytes,
119 uint32_t receive_timestamp) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000120 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000121 LOG(LS_VERBOSE) << "InsertPacket: ts=" << rtp_header.header.timestamp <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000122 ", sn=" << rtp_header.header.sequenceNumber <<
123 ", pt=" << static_cast<int>(rtp_header.header.payloadType) <<
124 ", ssrc=" << rtp_header.header.ssrc <<
125 ", len=" << length_bytes;
126 int error = InsertPacketInternal(rtp_header, payload, length_bytes,
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000127 receive_timestamp, false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000128 if (error != 0) {
129 LOG_FERR1(LS_WARNING, InsertPacketInternal, error);
130 error_code_ = error;
131 return kFail;
132 }
133 return kOK;
134}
135
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000136int NetEqImpl::InsertSyncPacket(const WebRtcRTPHeader& rtp_header,
137 uint32_t receive_timestamp) {
138 CriticalSectionScoped lock(crit_sect_.get());
139 LOG(LS_VERBOSE) << "InsertPacket-Sync: ts="
140 << rtp_header.header.timestamp <<
141 ", sn=" << rtp_header.header.sequenceNumber <<
142 ", pt=" << static_cast<int>(rtp_header.header.payloadType) <<
143 ", ssrc=" << rtp_header.header.ssrc;
144
145 const uint8_t kSyncPayload[] = { 's', 'y', 'n', 'c' };
146 int error = InsertPacketInternal(
147 rtp_header, kSyncPayload, sizeof(kSyncPayload), receive_timestamp, true);
148
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000149 if (error != 0) {
150 LOG_FERR1(LS_WARNING, InsertPacketInternal, error);
151 error_code_ = error;
152 return kFail;
153 }
154 return kOK;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000155}
156
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000157int NetEqImpl::GetAudio(size_t max_length, int16_t* output_audio,
158 int* samples_per_channel, int* num_channels,
159 NetEqOutputType* type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000160 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000161 LOG(LS_VERBOSE) << "GetAudio";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000162 int error = GetAudioInternal(max_length, output_audio, samples_per_channel,
163 num_channels);
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000164 LOG(LS_VERBOSE) << "Produced " << *samples_per_channel <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000165 " samples/channel for " << *num_channels << " channel(s)";
166 if (error != 0) {
167 LOG_FERR1(LS_WARNING, GetAudioInternal, error);
168 error_code_ = error;
169 return kFail;
170 }
171 if (type) {
172 *type = LastOutputType();
173 }
174 return kOK;
175}
176
177int NetEqImpl::RegisterPayloadType(enum NetEqDecoder codec,
178 uint8_t rtp_payload_type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000179 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000180 LOG_API2(static_cast<int>(rtp_payload_type), codec);
181 int ret = decoder_database_->RegisterPayload(rtp_payload_type, codec);
182 if (ret != DecoderDatabase::kOK) {
183 LOG_FERR2(LS_WARNING, RegisterPayload, rtp_payload_type, codec);
184 switch (ret) {
185 case DecoderDatabase::kInvalidRtpPayloadType:
186 error_code_ = kInvalidRtpPayloadType;
187 break;
188 case DecoderDatabase::kCodecNotSupported:
189 error_code_ = kCodecNotSupported;
190 break;
191 case DecoderDatabase::kDecoderExists:
192 error_code_ = kDecoderExists;
193 break;
194 default:
195 error_code_ = kOtherError;
196 }
197 return kFail;
198 }
199 return kOK;
200}
201
202int NetEqImpl::RegisterExternalDecoder(AudioDecoder* decoder,
203 enum NetEqDecoder codec,
204 int sample_rate_hz,
205 uint8_t rtp_payload_type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000206 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000207 LOG_API2(static_cast<int>(rtp_payload_type), codec);
208 if (!decoder) {
209 LOG(LS_ERROR) << "Cannot register external decoder with NULL pointer";
210 assert(false);
211 return kFail;
212 }
213 int ret = decoder_database_->InsertExternal(rtp_payload_type, codec,
214 sample_rate_hz, decoder);
215 if (ret != DecoderDatabase::kOK) {
216 LOG_FERR2(LS_WARNING, InsertExternal, rtp_payload_type, codec);
217 switch (ret) {
218 case DecoderDatabase::kInvalidRtpPayloadType:
219 error_code_ = kInvalidRtpPayloadType;
220 break;
221 case DecoderDatabase::kCodecNotSupported:
222 error_code_ = kCodecNotSupported;
223 break;
224 case DecoderDatabase::kDecoderExists:
225 error_code_ = kDecoderExists;
226 break;
227 case DecoderDatabase::kInvalidSampleRate:
228 error_code_ = kInvalidSampleRate;
229 break;
230 case DecoderDatabase::kInvalidPointer:
231 error_code_ = kInvalidPointer;
232 break;
233 default:
234 error_code_ = kOtherError;
235 }
236 return kFail;
237 }
238 return kOK;
239}
240
241int NetEqImpl::RemovePayloadType(uint8_t rtp_payload_type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000242 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000243 LOG_API1(static_cast<int>(rtp_payload_type));
244 int ret = decoder_database_->Remove(rtp_payload_type);
245 if (ret == DecoderDatabase::kOK) {
246 return kOK;
247 } else if (ret == DecoderDatabase::kDecoderNotFound) {
248 error_code_ = kDecoderNotFound;
249 } else {
250 error_code_ = kOtherError;
251 }
252 LOG_FERR1(LS_WARNING, Remove, rtp_payload_type);
253 return kFail;
254}
255
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000256bool NetEqImpl::SetMinimumDelay(int delay_ms) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000257 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000258 if (delay_ms >= 0 && delay_ms < 10000) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000259 assert(delay_manager_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000260 return delay_manager_->SetMinimumDelay(delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000261 }
262 return false;
263}
264
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000265bool NetEqImpl::SetMaximumDelay(int delay_ms) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000266 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000267 if (delay_ms >= 0 && delay_ms < 10000) {
268 assert(delay_manager_.get());
269 return delay_manager_->SetMaximumDelay(delay_ms);
270 }
271 return false;
272}
273
274int NetEqImpl::LeastRequiredDelayMs() const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000275 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000276 assert(delay_manager_.get());
277 return delay_manager_->least_required_delay_ms();
278}
279
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000280void NetEqImpl::SetPlayoutMode(NetEqPlayoutMode mode) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000281 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000282 if (!decision_logic_.get() || mode != decision_logic_->playout_mode()) {
283 // The reset() method calls delete for the old object.
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000284 CreateDecisionLogic(mode);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000285 }
286}
287
288NetEqPlayoutMode NetEqImpl::PlayoutMode() const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000289 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000290 assert(decision_logic_.get());
291 return decision_logic_->playout_mode();
292}
293
294int NetEqImpl::NetworkStatistics(NetEqNetworkStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000295 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000296 assert(decoder_database_.get());
297 const int total_samples_in_buffers = packet_buffer_->NumSamplesInBuffer(
298 decoder_database_.get(), decoder_frame_length_) +
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000299 static_cast<int>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000300 assert(delay_manager_.get());
301 assert(decision_logic_.get());
302 stats_.GetNetworkStatistics(fs_hz_, total_samples_in_buffers,
303 decoder_frame_length_, *delay_manager_.get(),
304 *decision_logic_.get(), stats);
305 return 0;
306}
307
308void NetEqImpl::WaitingTimes(std::vector<int>* waiting_times) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000309 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000310 stats_.WaitingTimes(waiting_times);
311}
312
313void NetEqImpl::GetRtcpStatistics(RtcpStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000314 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000315 if (stats) {
316 rtcp_.GetStatistics(false, stats);
317 }
318}
319
320void NetEqImpl::GetRtcpStatisticsNoReset(RtcpStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000321 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000322 if (stats) {
323 rtcp_.GetStatistics(true, stats);
324 }
325}
326
327void NetEqImpl::EnableVad() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000328 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000329 assert(vad_.get());
330 vad_->Enable();
331}
332
333void NetEqImpl::DisableVad() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000334 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000335 assert(vad_.get());
336 vad_->Disable();
337}
338
339uint32_t NetEqImpl::PlayoutTimestamp() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000340 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000341 return timestamp_scaler_->ToExternal(playout_timestamp_);
342}
343
344int NetEqImpl::LastError() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000345 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000346 return error_code_;
347}
348
349int NetEqImpl::LastDecoderError() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000350 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000351 return decoder_error_code_;
352}
353
354void NetEqImpl::FlushBuffers() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000355 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000356 LOG_API0();
357 packet_buffer_->Flush();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000358 assert(sync_buffer_.get());
359 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000360 sync_buffer_->Flush();
361 sync_buffer_->set_next_index(sync_buffer_->next_index() -
362 expand_->overlap_length());
363 // Set to wait for new codec.
364 first_packet_ = true;
365}
366
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000367void NetEqImpl::PacketBufferStatistics(int* current_num_packets,
368 int* max_num_packets,
369 int* current_memory_size_bytes,
370 int* max_memory_size_bytes) const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000371 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000372 packet_buffer_->BufferStat(current_num_packets, max_num_packets,
373 current_memory_size_bytes, max_memory_size_bytes);
374}
375
turaj@webrtc.orgff43c852013-09-25 00:07:27 +0000376int NetEqImpl::DecodedRtpInfo(int* sequence_number, uint32_t* timestamp) const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000377 CriticalSectionScoped lock(crit_sect_.get());
minyue@webrtc.orgd7301772013-08-29 00:58:14 +0000378 if (decoded_packet_sequence_number_ < 0)
379 return -1;
380 *sequence_number = decoded_packet_sequence_number_;
381 *timestamp = decoded_packet_timestamp_;
382 return 0;
383}
384
turaj@webrtc.orgff43c852013-09-25 00:07:27 +0000385void NetEqImpl::SetBackgroundNoiseMode(NetEqBackgroundNoiseMode mode) {
386 CriticalSectionScoped lock(crit_sect_.get());
387 assert(background_noise_.get());
388 background_noise_->set_mode(mode);
389}
turaj@webrtc.org036b7432013-09-11 18:45:02 +0000390
391NetEqBackgroundNoiseMode NetEqImpl::BackgroundNoiseMode() const {
turaj@webrtc.orgff43c852013-09-25 00:07:27 +0000392 CriticalSectionScoped lock(crit_sect_.get());
393 assert(background_noise_.get());
394 return background_noise_->mode();
turaj@webrtc.org036b7432013-09-11 18:45:02 +0000395}
396
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000397const SyncBuffer* NetEqImpl::sync_buffer_for_test() const {
398 CriticalSectionScoped lock(crit_sect_.get());
399 return sync_buffer_.get();
400}
401
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000402// Methods below this line are private.
403
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000404int NetEqImpl::InsertPacketInternal(const WebRtcRTPHeader& rtp_header,
405 const uint8_t* payload,
406 int length_bytes,
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000407 uint32_t receive_timestamp,
408 bool is_sync_packet) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000409 if (!payload) {
410 LOG_F(LS_ERROR) << "payload == NULL";
411 return kInvalidPointer;
412 }
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000413 // Sanity checks for sync-packets.
414 if (is_sync_packet) {
415 if (decoder_database_->IsDtmf(rtp_header.header.payloadType) ||
416 decoder_database_->IsRed(rtp_header.header.payloadType) ||
417 decoder_database_->IsComfortNoise(rtp_header.header.payloadType)) {
418 LOG_F(LS_ERROR) << "Sync-packet with an unacceptable payload type "
419 << rtp_header.header.payloadType;
420 return kSyncPacketNotAccepted;
421 }
422 if (first_packet_ ||
423 rtp_header.header.payloadType != current_rtp_payload_type_ ||
424 rtp_header.header.ssrc != ssrc_) {
425 // Even if |current_rtp_payload_type_| is 0xFF, sync-packet isn't
426 // accepted.
427 LOG_F(LS_ERROR) << "Changing codec, SSRC or first packet "
428 "with sync-packet.";
429 return kSyncPacketNotAccepted;
430 }
431 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000432 PacketList packet_list;
433 RTPHeader main_header;
434 {
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000435 // Convert to Packet.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000436 // Create |packet| within this separate scope, since it should not be used
437 // directly once it's been inserted in the packet list. This way, |packet|
438 // is not defined outside of this block.
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000439 Packet* packet = new Packet;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000440 packet->header.markerBit = false;
441 packet->header.payloadType = rtp_header.header.payloadType;
442 packet->header.sequenceNumber = rtp_header.header.sequenceNumber;
443 packet->header.timestamp = rtp_header.header.timestamp;
444 packet->header.ssrc = rtp_header.header.ssrc;
445 packet->header.numCSRCs = 0;
446 packet->payload_length = length_bytes;
447 packet->primary = true;
448 packet->waiting_time = 0;
449 packet->payload = new uint8_t[packet->payload_length];
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000450 packet->sync_packet = is_sync_packet;
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +0000451 if (!packet->payload) {
452 LOG_F(LS_ERROR) << "Payload pointer is NULL.";
453 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000454 assert(payload); // Already checked above.
455 memcpy(packet->payload, payload, packet->payload_length);
456 // Insert packet in a packet list.
457 packet_list.push_back(packet);
458 // Save main payloads header for later.
459 memcpy(&main_header, &packet->header, sizeof(main_header));
460 }
461
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000462 bool update_sample_rate_and_channels = false;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000463 // Reinitialize NetEq if it's needed (changed SSRC or first call).
464 if ((main_header.ssrc != ssrc_) || first_packet_) {
465 rtcp_.Init(main_header.sequenceNumber);
466 first_packet_ = false;
467
468 // Flush the packet buffer and DTMF buffer.
469 packet_buffer_->Flush();
470 dtmf_buffer_->Flush();
471
472 // Store new SSRC.
473 ssrc_ = main_header.ssrc;
474
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000475 // Update audio buffer timestamp.
476 sync_buffer_->IncreaseEndTimestamp(main_header.timestamp - timestamp_);
477
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000478 // Update codecs.
479 timestamp_ = main_header.timestamp;
480 current_rtp_payload_type_ = main_header.payloadType;
481
482 // Set MCU to update codec on next SignalMCU call.
483 new_codec_ = true;
484
485 // Reset timestamp scaling.
486 timestamp_scaler_->Reset();
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000487
488 // Triger an update of sampling rate and the number of channels.
489 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000490 }
491
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000492 // Update RTCP statistics, only for regular packets.
493 if (!is_sync_packet)
494 rtcp_.Update(main_header, receive_timestamp);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000495
496 // Check for RED payload type, and separate payloads into several packets.
497 if (decoder_database_->IsRed(main_header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000498 assert(!is_sync_packet); // We had a sanity check for this.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000499 if (payload_splitter_->SplitRed(&packet_list) != PayloadSplitter::kOK) {
500 LOG_FERR1(LS_WARNING, SplitRed, packet_list.size());
501 PacketBuffer::DeleteAllPackets(&packet_list);
502 return kRedundancySplitError;
503 }
504 // Only accept a few RED payloads of the same type as the main data,
505 // DTMF events and CNG.
506 payload_splitter_->CheckRedPayloads(&packet_list, *decoder_database_);
507 // Update the stored main payload header since the main payload has now
508 // changed.
509 memcpy(&main_header, &packet_list.front()->header, sizeof(main_header));
510 }
511
512 // Check payload types.
513 if (decoder_database_->CheckPayloadTypes(packet_list) ==
514 DecoderDatabase::kDecoderNotFound) {
515 LOG_FERR1(LS_WARNING, CheckPayloadTypes, packet_list.size());
516 PacketBuffer::DeleteAllPackets(&packet_list);
517 return kUnknownRtpPayloadType;
518 }
519
520 // Scale timestamp to internal domain (only for some codecs).
521 timestamp_scaler_->ToInternal(&packet_list);
522
523 // Process DTMF payloads. Cycle through the list of packets, and pick out any
524 // DTMF payloads found.
525 PacketList::iterator it = packet_list.begin();
526 while (it != packet_list.end()) {
527 Packet* current_packet = (*it);
528 assert(current_packet);
529 assert(current_packet->payload);
530 if (decoder_database_->IsDtmf(current_packet->header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000531 assert(!current_packet->sync_packet); // We had a sanity check for this.
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000532 DtmfEvent event;
533 int ret = DtmfBuffer::ParseEvent(
534 current_packet->header.timestamp,
535 current_packet->payload,
536 current_packet->payload_length,
537 &event);
538 if (ret != DtmfBuffer::kOK) {
539 LOG_FERR2(LS_WARNING, ParseEvent, ret,
540 current_packet->payload_length);
541 PacketBuffer::DeleteAllPackets(&packet_list);
542 return kDtmfParsingError;
543 }
544 if (dtmf_buffer_->InsertEvent(event) != DtmfBuffer::kOK) {
545 LOG_FERR0(LS_WARNING, InsertEvent);
546 PacketBuffer::DeleteAllPackets(&packet_list);
547 return kDtmfInsertError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000548 }
549 // TODO(hlundin): Let the destructor of Packet handle the payload.
550 delete [] current_packet->payload;
551 delete current_packet;
552 it = packet_list.erase(it);
553 } else {
554 ++it;
555 }
556 }
557
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000558 // Check for FEC in packets, and separate payloads into several packets.
559 int ret = payload_splitter_->SplitFec(&packet_list, decoder_database_.get());
560 if (ret != PayloadSplitter::kOK) {
561 LOG_FERR1(LS_WARNING, SplitFec, packet_list.size());
562 PacketBuffer::DeleteAllPackets(&packet_list);
563 switch (ret) {
564 case PayloadSplitter::kUnknownPayloadType:
565 return kUnknownRtpPayloadType;
566 default:
567 return kOtherError;
568 }
569 }
570
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000571 // Split payloads into smaller chunks. This also verifies that all payloads
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000572 // are of a known payload type. SplitAudio() method is protected against
573 // sync-packets.
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +0000574 ret = payload_splitter_->SplitAudio(&packet_list, *decoder_database_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000575 if (ret != PayloadSplitter::kOK) {
576 LOG_FERR1(LS_WARNING, SplitAudio, packet_list.size());
577 PacketBuffer::DeleteAllPackets(&packet_list);
578 switch (ret) {
579 case PayloadSplitter::kUnknownPayloadType:
580 return kUnknownRtpPayloadType;
581 case PayloadSplitter::kFrameSplitError:
582 return kFrameSplitError;
583 default:
584 return kOtherError;
585 }
586 }
587
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000588 // Update bandwidth estimate, if the packet is not sync-packet.
589 if (!packet_list.empty() && !packet_list.front()->sync_packet) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000590 // The list can be empty here if we got nothing but DTMF payloads.
591 AudioDecoder* decoder =
592 decoder_database_->GetDecoder(main_header.payloadType);
593 assert(decoder); // Should always get a valid object, since we have
594 // already checked that the payload types are known.
595 decoder->IncomingPacket(packet_list.front()->payload,
596 packet_list.front()->payload_length,
597 packet_list.front()->header.sequenceNumber,
598 packet_list.front()->header.timestamp,
599 receive_timestamp);
600 }
601
602 // Insert packets in buffer.
603 int temp_bufsize = packet_buffer_->NumPacketsInBuffer();
604 ret = packet_buffer_->InsertPacketList(
605 &packet_list,
606 *decoder_database_,
607 &current_rtp_payload_type_,
608 &current_cng_rtp_payload_type_);
609 if (ret == PacketBuffer::kFlushed) {
610 // Reset DSP timestamp etc. if packet buffer flushed.
611 new_codec_ = true;
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000612 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000613 LOG_F(LS_WARNING) << "Packet buffer flushed";
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000614 } else if (ret == PacketBuffer::kOversizePacket) {
615 LOG_F(LS_WARNING) << "Packet larger than packet buffer";
616 return kOversizePacket;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000617 } else if (ret != PacketBuffer::kOK) {
618 LOG_FERR1(LS_WARNING, InsertPacketList, packet_list.size());
619 PacketBuffer::DeleteAllPackets(&packet_list);
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000620 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000621 }
622 if (current_rtp_payload_type_ != 0xFF) {
623 const DecoderDatabase::DecoderInfo* dec_info =
624 decoder_database_->GetDecoderInfo(current_rtp_payload_type_);
625 if (!dec_info) {
626 assert(false); // Already checked that the payload type is known.
627 }
628 }
629
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000630 if (update_sample_rate_and_channels && !packet_buffer_->Empty()) {
631 // We do not use |current_rtp_payload_type_| to |set payload_type|, but
632 // get the next RTP header from |packet_buffer_| to obtain the payload type.
633 // The reason for it is the following corner case. If NetEq receives a
634 // CNG packet with a sample rate different than the current CNG then it
635 // flushes its buffer, assuming send codec must have been changed. However,
636 // payload type of the hypothetically new send codec is not known.
637 const RTPHeader* rtp_header = packet_buffer_->NextRtpHeader();
638 assert(rtp_header);
639 int payload_type = rtp_header->payloadType;
640 AudioDecoder* decoder = decoder_database_->GetDecoder(payload_type);
641 assert(decoder); // Payloads are already checked to be valid.
642 const DecoderDatabase::DecoderInfo* decoder_info =
643 decoder_database_->GetDecoderInfo(payload_type);
644 assert(decoder_info);
645 if (decoder_info->fs_hz != fs_hz_ ||
646 decoder->channels() != algorithm_buffer_->Channels())
647 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->channels());
648 }
649
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000650 // TODO(hlundin): Move this code to DelayManager class.
651 const DecoderDatabase::DecoderInfo* dec_info =
652 decoder_database_->GetDecoderInfo(main_header.payloadType);
653 assert(dec_info); // Already checked that the payload type is known.
654 delay_manager_->LastDecoderType(dec_info->codec_type);
655 if (delay_manager_->last_pack_cng_or_dtmf() == 0) {
656 // Calculate the total speech length carried in each packet.
657 temp_bufsize = packet_buffer_->NumPacketsInBuffer() - temp_bufsize;
658 temp_bufsize *= decoder_frame_length_;
659
660 if ((temp_bufsize > 0) &&
661 (temp_bufsize != decision_logic_->packet_length_samples())) {
662 decision_logic_->set_packet_length_samples(temp_bufsize);
663 delay_manager_->SetPacketAudioLength((1000 * temp_bufsize) / fs_hz_);
664 }
665
666 // Update statistics.
pbos@webrtc.org0946a562013-04-09 00:28:06 +0000667 if ((int32_t) (main_header.timestamp - timestamp_) >= 0 &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000668 !new_codec_) {
669 // Only update statistics if incoming packet is not older than last played
670 // out packet, and if new codec flag is not set.
671 delay_manager_->Update(main_header.sequenceNumber, main_header.timestamp,
672 fs_hz_);
673 }
674 } else if (delay_manager_->last_pack_cng_or_dtmf() == -1) {
675 // This is first "normal" packet after CNG or DTMF.
676 // Reset packet time counter and measure time until next packet,
677 // but don't update statistics.
678 delay_manager_->set_last_pack_cng_or_dtmf(0);
679 delay_manager_->ResetPacketIatCount();
680 }
681 return 0;
682}
683
684int NetEqImpl::GetAudioInternal(size_t max_length, int16_t* output,
685 int* samples_per_channel, int* num_channels) {
686 PacketList packet_list;
687 DtmfEvent dtmf_event;
688 Operations operation;
689 bool play_dtmf;
690 int return_value = GetDecision(&operation, &packet_list, &dtmf_event,
691 &play_dtmf);
692 if (return_value != 0) {
693 LOG_FERR1(LS_WARNING, GetDecision, return_value);
694 assert(false);
695 last_mode_ = kModeError;
696 return return_value;
697 }
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000698 LOG(LS_VERBOSE) << "GetDecision returned operation=" << operation <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000699 " and " << packet_list.size() << " packet(s)";
700
701 AudioDecoder::SpeechType speech_type;
702 int length = 0;
703 int decode_return_value = Decode(&packet_list, &operation,
704 &length, &speech_type);
705
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000706 assert(vad_.get());
707 bool sid_frame_available =
708 (operation == kRfc3389Cng && !packet_list.empty());
709 vad_->Update(decoded_buffer_.get(), length, speech_type,
710 sid_frame_available, fs_hz_);
711
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000712 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000713 switch (operation) {
714 case kNormal: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000715 DoNormal(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000716 break;
717 }
718 case kMerge: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000719 DoMerge(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000720 break;
721 }
722 case kExpand: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000723 return_value = DoExpand(play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000724 break;
725 }
726 case kAccelerate: {
727 return_value = DoAccelerate(decoded_buffer_.get(), length, speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000728 play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000729 break;
730 }
731 case kPreemptiveExpand: {
732 return_value = DoPreemptiveExpand(decoded_buffer_.get(), length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000733 speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000734 break;
735 }
736 case kRfc3389Cng:
737 case kRfc3389CngNoPacket: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000738 return_value = DoRfc3389Cng(&packet_list, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000739 break;
740 }
741 case kCodecInternalCng: {
742 // This handles the case when there is no transmission and the decoder
743 // should produce internal comfort noise.
744 // TODO(hlundin): Write test for codec-internal CNG.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000745 DoCodecInternalCng();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000746 break;
747 }
748 case kDtmf: {
749 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000750 return_value = DoDtmf(dtmf_event, &play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000751 break;
752 }
753 case kAlternativePlc: {
754 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000755 DoAlternativePlc(false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000756 break;
757 }
758 case kAlternativePlcIncreaseTimestamp: {
759 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000760 DoAlternativePlc(true);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000761 break;
762 }
763 case kAudioRepetitionIncreaseTimestamp: {
764 // TODO(hlundin): Write test for this.
765 sync_buffer_->IncreaseEndTimestamp(output_size_samples_);
766 // Skipping break on purpose. Execution should move on into the
767 // next case.
768 }
769 case kAudioRepetition: {
770 // TODO(hlundin): Write test for this.
771 // Copy last |output_size_samples_| from |sync_buffer_| to
772 // |algorithm_buffer|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000773 algorithm_buffer_->PushBackFromIndex(
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000774 *sync_buffer_, sync_buffer_->Size() - output_size_samples_);
775 expand_->Reset();
776 break;
777 }
778 case kUndefined: {
779 LOG_F(LS_ERROR) << "Invalid operation kUndefined.";
780 assert(false); // This should not happen.
781 last_mode_ = kModeError;
782 return kInvalidOperation;
783 }
784 } // End of switch.
785 if (return_value < 0) {
786 return return_value;
787 }
788
789 if (last_mode_ != kModeRfc3389Cng) {
790 comfort_noise_->Reset();
791 }
792
793 // Copy from |algorithm_buffer| to |sync_buffer_|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000794 sync_buffer_->PushBack(*algorithm_buffer_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000795
796 // Extract data from |sync_buffer_| to |output|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000797 size_t num_output_samples_per_channel = output_size_samples_;
798 size_t num_output_samples = output_size_samples_ * sync_buffer_->Channels();
799 if (num_output_samples > max_length) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000800 LOG(LS_WARNING) << "Output array is too short. " << max_length << " < " <<
801 output_size_samples_ << " * " << sync_buffer_->Channels();
802 num_output_samples = max_length;
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000803 num_output_samples_per_channel = static_cast<int>(
804 max_length / sync_buffer_->Channels());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000805 }
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000806 int samples_from_sync = static_cast<int>(
807 sync_buffer_->GetNextAudioInterleaved(num_output_samples_per_channel,
808 output));
809 *num_channels = static_cast<int>(sync_buffer_->Channels());
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000810 LOG(LS_VERBOSE) << "Sync buffer (" << *num_channels << " channel(s)):" <<
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000811 " insert " << algorithm_buffer_->Size() << " samples, extract " <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000812 samples_from_sync << " samples";
813 if (samples_from_sync != output_size_samples_) {
814 LOG_F(LS_ERROR) << "samples_from_sync != output_size_samples_";
minyue@webrtc.orgdb1cefc2013-08-13 01:39:21 +0000815 // TODO(minyue): treatment of under-run, filling zeros
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000816 memset(output, 0, num_output_samples * sizeof(int16_t));
817 *samples_per_channel = output_size_samples_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000818 return kSampleUnderrun;
819 }
820 *samples_per_channel = output_size_samples_;
821
822 // Should always have overlap samples left in the |sync_buffer_|.
823 assert(sync_buffer_->FutureLength() >= expand_->overlap_length());
824
825 if (play_dtmf) {
826 return_value = DtmfOverdub(dtmf_event, sync_buffer_->Channels(), output);
827 }
828
829 // Update the background noise parameters if last operation wrote data
830 // straight from the decoder to the |sync_buffer_|. That is, none of the
831 // operations that modify the signal can be followed by a parameter update.
832 if ((last_mode_ == kModeNormal) ||
833 (last_mode_ == kModeAccelerateFail) ||
834 (last_mode_ == kModePreemptiveExpandFail) ||
835 (last_mode_ == kModeRfc3389Cng) ||
836 (last_mode_ == kModeCodecInternalCng)) {
837 background_noise_->Update(*sync_buffer_, *vad_.get());
838 }
839
840 if (operation == kDtmf) {
841 // DTMF data was written the end of |sync_buffer_|.
842 // Update index to end of DTMF data in |sync_buffer_|.
843 sync_buffer_->set_dtmf_index(sync_buffer_->Size());
844 }
845
henrik.lundin@webrtc.orged865b52014-03-06 10:28:07 +0000846 if (last_mode_ != kModeExpand) {
847 // If last operation was not expand, calculate the |playout_timestamp_| from
848 // the |sync_buffer_|. However, do not update the |playout_timestamp_| if it
849 // would be moved "backwards".
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000850 uint32_t temp_timestamp = sync_buffer_->end_timestamp() -
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000851 static_cast<uint32_t>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000852 if (static_cast<int32_t>(temp_timestamp - playout_timestamp_) > 0) {
853 playout_timestamp_ = temp_timestamp;
854 }
855 } else {
856 // Use dead reckoning to estimate the |playout_timestamp_|.
857 playout_timestamp_ += output_size_samples_;
858 }
859
860 if (decode_return_value) return decode_return_value;
861 return return_value;
862}
863
864int NetEqImpl::GetDecision(Operations* operation,
865 PacketList* packet_list,
866 DtmfEvent* dtmf_event,
867 bool* play_dtmf) {
868 // Initialize output variables.
869 *play_dtmf = false;
870 *operation = kUndefined;
871
872 // Increment time counters.
873 packet_buffer_->IncrementWaitingTimes();
874 stats_.IncreaseCounter(output_size_samples_, fs_hz_);
875
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000876 assert(sync_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000877 uint32_t end_timestamp = sync_buffer_->end_timestamp();
878 if (!new_codec_) {
879 packet_buffer_->DiscardOldPackets(end_timestamp);
880 }
881 const RTPHeader* header = packet_buffer_->NextRtpHeader();
882
henrik.lundin@webrtc.orgca8cb952014-03-12 10:26:52 +0000883 if (decision_logic_->CngRfc3389On() || last_mode_ == kModeRfc3389Cng) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000884 // Because of timestamp peculiarities, we have to "manually" disallow using
885 // a CNG packet with the same timestamp as the one that was last played.
886 // This can happen when using redundancy and will cause the timing to shift.
henrik.lundin@webrtc.org24779fe2014-03-14 12:40:05 +0000887 while (header && decoder_database_->IsComfortNoise(header->payloadType) &&
888 (end_timestamp >= header->timestamp ||
889 end_timestamp + decision_logic_->generated_noise_samples() >
890 header->timestamp)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000891 // Don't use this packet, discard it.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000892 if (packet_buffer_->DiscardNextPacket() != PacketBuffer::kOK) {
893 assert(false); // Must be ok by design.
894 }
895 // Check buffer again.
896 if (!new_codec_) {
897 packet_buffer_->DiscardOldPackets(end_timestamp);
898 }
899 header = packet_buffer_->NextRtpHeader();
900 }
901 }
902
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000903 assert(expand_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000904 const int samples_left = static_cast<int>(sync_buffer_->FutureLength() -
905 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000906 if (last_mode_ == kModeAccelerateSuccess ||
907 last_mode_ == kModeAccelerateLowEnergy ||
908 last_mode_ == kModePreemptiveExpandSuccess ||
909 last_mode_ == kModePreemptiveExpandLowEnergy) {
910 // Subtract (samples_left + output_size_samples_) from sampleMemory.
911 decision_logic_->AddSampleMemory(-(samples_left + output_size_samples_));
912 }
913
914 // Check if it is time to play a DTMF event.
915 if (dtmf_buffer_->GetEvent(end_timestamp +
916 decision_logic_->generated_noise_samples(),
917 dtmf_event)) {
918 *play_dtmf = true;
919 }
920
921 // Get instruction.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000922 assert(sync_buffer_.get());
923 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000924 *operation = decision_logic_->GetDecision(*sync_buffer_,
925 *expand_,
926 decoder_frame_length_,
927 header,
928 last_mode_,
929 *play_dtmf,
930 &reset_decoder_);
931
932 // Check if we already have enough samples in the |sync_buffer_|. If so,
933 // change decision to normal, unless the decision was merge, accelerate, or
934 // preemptive expand.
935 if (samples_left >= output_size_samples_ &&
936 *operation != kMerge &&
937 *operation != kAccelerate &&
938 *operation != kPreemptiveExpand) {
939 *operation = kNormal;
940 return 0;
941 }
942
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000943 decision_logic_->ExpandDecision(*operation);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000944
945 // Check conditions for reset.
946 if (new_codec_ || *operation == kUndefined) {
947 // The only valid reason to get kUndefined is that new_codec_ is set.
948 assert(new_codec_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000949 if (*play_dtmf && !header) {
950 timestamp_ = dtmf_event->timestamp;
951 } else {
952 assert(header);
953 if (!header) {
954 LOG_F(LS_ERROR) << "Packet missing where it shouldn't.";
955 return -1;
956 }
957 timestamp_ = header->timestamp;
958 if (*operation == kRfc3389CngNoPacket
959#ifndef LEGACY_BITEXACT
960 // Without this check, it can happen that a non-CNG packet is sent to
961 // the CNG decoder as if it was a SID frame. This is clearly a bug,
962 // but is kept for now to maintain bit-exactness with the test
963 // vectors.
964 && decoder_database_->IsComfortNoise(header->payloadType)
965#endif
966 ) {
967 // Change decision to CNG packet, since we do have a CNG packet, but it
968 // was considered too early to use. Now, use it anyway.
969 *operation = kRfc3389Cng;
970 } else if (*operation != kRfc3389Cng) {
971 *operation = kNormal;
972 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000973 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000974 // Adjust |sync_buffer_| timestamp before setting |end_timestamp| to the
975 // new value.
976 sync_buffer_->IncreaseEndTimestamp(timestamp_ - end_timestamp);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000977 end_timestamp = timestamp_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000978 new_codec_ = false;
979 decision_logic_->SoftReset();
980 buffer_level_filter_->Reset();
981 delay_manager_->Reset();
982 stats_.ResetMcu();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000983 }
984
985 int required_samples = output_size_samples_;
986 const int samples_10_ms = 80 * fs_mult_;
987 const int samples_20_ms = 2 * samples_10_ms;
988 const int samples_30_ms = 3 * samples_10_ms;
989
990 switch (*operation) {
991 case kExpand: {
992 timestamp_ = end_timestamp;
993 return 0;
994 }
995 case kRfc3389CngNoPacket:
996 case kCodecInternalCng: {
997 return 0;
998 }
999 case kDtmf: {
1000 // TODO(hlundin): Write test for this.
1001 // Update timestamp.
1002 timestamp_ = end_timestamp;
1003 if (decision_logic_->generated_noise_samples() > 0 &&
1004 last_mode_ != kModeDtmf) {
1005 // Make a jump in timestamp due to the recently played comfort noise.
1006 uint32_t timestamp_jump = decision_logic_->generated_noise_samples();
1007 sync_buffer_->IncreaseEndTimestamp(timestamp_jump);
1008 timestamp_ += timestamp_jump;
1009 }
1010 decision_logic_->set_generated_noise_samples(0);
1011 return 0;
1012 }
1013 case kAccelerate: {
1014 // In order to do a accelerate we need at least 30 ms of audio data.
1015 if (samples_left >= samples_30_ms) {
1016 // Already have enough data, so we do not need to extract any more.
1017 decision_logic_->set_sample_memory(samples_left);
1018 decision_logic_->set_prev_time_scale(true);
1019 return 0;
1020 } else if (samples_left >= samples_10_ms &&
1021 decoder_frame_length_ >= samples_30_ms) {
1022 // Avoid decoding more data as it might overflow the playout buffer.
1023 *operation = kNormal;
1024 return 0;
1025 } else if (samples_left < samples_20_ms &&
1026 decoder_frame_length_ < samples_30_ms) {
1027 // Build up decoded data by decoding at least 20 ms of audio data. Do
1028 // not perform accelerate yet, but wait until we only need to do one
1029 // decoding.
1030 required_samples = 2 * output_size_samples_;
1031 *operation = kNormal;
1032 }
1033 // If none of the above is true, we have one of two possible situations:
1034 // (1) 20 ms <= samples_left < 30 ms and decoder_frame_length_ < 30 ms; or
1035 // (2) samples_left < 10 ms and decoder_frame_length_ >= 30 ms.
1036 // In either case, we move on with the accelerate decision, and decode one
1037 // frame now.
1038 break;
1039 }
1040 case kPreemptiveExpand: {
1041 // In order to do a preemptive expand we need at least 30 ms of decoded
1042 // audio data.
1043 if ((samples_left >= samples_30_ms) ||
1044 (samples_left >= samples_10_ms &&
1045 decoder_frame_length_ >= samples_30_ms)) {
1046 // Already have enough data, so we do not need to extract any more.
1047 // Or, avoid decoding more data as it might overflow the playout buffer.
1048 // Still try preemptive expand, though.
1049 decision_logic_->set_sample_memory(samples_left);
1050 decision_logic_->set_prev_time_scale(true);
1051 return 0;
1052 }
1053 if (samples_left < samples_20_ms &&
1054 decoder_frame_length_ < samples_30_ms) {
1055 // Build up decoded data by decoding at least 20 ms of audio data.
1056 // Still try to perform preemptive expand.
1057 required_samples = 2 * output_size_samples_;
1058 }
1059 // Move on with the preemptive expand decision.
1060 break;
1061 }
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001062 case kMerge: {
1063 required_samples =
1064 std::max(merge_->RequiredFutureSamples(), required_samples);
1065 break;
1066 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001067 default: {
1068 // Do nothing.
1069 }
1070 }
1071
1072 // Get packets from buffer.
1073 int extracted_samples = 0;
1074 if (header &&
1075 *operation != kAlternativePlc &&
1076 *operation != kAlternativePlcIncreaseTimestamp &&
1077 *operation != kAudioRepetition &&
1078 *operation != kAudioRepetitionIncreaseTimestamp) {
1079 sync_buffer_->IncreaseEndTimestamp(header->timestamp - end_timestamp);
1080 if (decision_logic_->CngOff()) {
1081 // Adjustment of timestamp only corresponds to an actual packet loss
1082 // if comfort noise is not played. If comfort noise was just played,
1083 // this adjustment of timestamp is only done to get back in sync with the
1084 // stream timestamp; no loss to report.
1085 stats_.LostSamples(header->timestamp - end_timestamp);
1086 }
1087
1088 if (*operation != kRfc3389Cng) {
1089 // We are about to decode and use a non-CNG packet.
1090 decision_logic_->SetCngOff();
1091 }
1092 // Reset CNG timestamp as a new packet will be delivered.
1093 // (Also if this is a CNG packet, since playedOutTS is updated.)
1094 decision_logic_->set_generated_noise_samples(0);
1095
1096 extracted_samples = ExtractPackets(required_samples, packet_list);
1097 if (extracted_samples < 0) {
1098 LOG_F(LS_WARNING) << "Failed to extract packets from buffer.";
1099 return kPacketBufferCorruption;
1100 }
1101 }
1102
1103 if (*operation == kAccelerate ||
1104 *operation == kPreemptiveExpand) {
1105 decision_logic_->set_sample_memory(samples_left + extracted_samples);
1106 decision_logic_->set_prev_time_scale(true);
1107 }
1108
1109 if (*operation == kAccelerate) {
1110 // Check that we have enough data (30ms) to do accelerate.
1111 if (extracted_samples + samples_left < samples_30_ms) {
1112 // TODO(hlundin): Write test for this.
1113 // Not enough, do normal operation instead.
1114 *operation = kNormal;
1115 }
1116 }
1117
1118 timestamp_ = end_timestamp;
1119 return 0;
1120}
1121
1122int NetEqImpl::Decode(PacketList* packet_list, Operations* operation,
1123 int* decoded_length,
1124 AudioDecoder::SpeechType* speech_type) {
1125 *speech_type = AudioDecoder::kSpeech;
1126 AudioDecoder* decoder = NULL;
1127 if (!packet_list->empty()) {
1128 const Packet* packet = packet_list->front();
1129 int payload_type = packet->header.payloadType;
1130 if (!decoder_database_->IsComfortNoise(payload_type)) {
1131 decoder = decoder_database_->GetDecoder(payload_type);
1132 assert(decoder);
1133 if (!decoder) {
1134 LOG_FERR1(LS_WARNING, GetDecoder, payload_type);
1135 PacketBuffer::DeleteAllPackets(packet_list);
1136 return kDecoderNotFound;
1137 }
1138 bool decoder_changed;
1139 decoder_database_->SetActiveDecoder(payload_type, &decoder_changed);
1140 if (decoder_changed) {
1141 // We have a new decoder. Re-init some values.
1142 const DecoderDatabase::DecoderInfo* decoder_info = decoder_database_
1143 ->GetDecoderInfo(payload_type);
1144 assert(decoder_info);
1145 if (!decoder_info) {
1146 LOG_FERR1(LS_WARNING, GetDecoderInfo, payload_type);
1147 PacketBuffer::DeleteAllPackets(packet_list);
1148 return kDecoderNotFound;
1149 }
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001150 // If sampling rate or number of channels has changed, we need to make
1151 // a reset.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001152 if (decoder_info->fs_hz != fs_hz_ ||
1153 decoder->channels() != algorithm_buffer_->Channels()) {
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001154 // TODO(tlegrand): Add unittest to cover this event.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001155 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->channels());
1156 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001157 sync_buffer_->set_end_timestamp(timestamp_);
1158 playout_timestamp_ = timestamp_;
1159 }
1160 }
1161 }
1162
1163 if (reset_decoder_) {
1164 // TODO(hlundin): Write test for this.
1165 // Reset decoder.
1166 if (decoder) {
1167 decoder->Init();
1168 }
1169 // Reset comfort noise decoder.
1170 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
1171 if (cng_decoder) {
1172 cng_decoder->Init();
1173 }
1174 reset_decoder_ = false;
1175 }
1176
1177#ifdef LEGACY_BITEXACT
1178 // Due to a bug in old SignalMCU, it could happen that CNG operation was
1179 // decided, but a speech packet was provided. The speech packet will be used
1180 // to update the comfort noise decoder, as if it was a SID frame, which is
1181 // clearly wrong.
1182 if (*operation == kRfc3389Cng) {
1183 return 0;
1184 }
1185#endif
1186
1187 *decoded_length = 0;
1188 // Update codec-internal PLC state.
1189 if ((*operation == kMerge) && decoder && decoder->HasDecodePlc()) {
1190 decoder->DecodePlc(1, &decoded_buffer_[*decoded_length]);
1191 }
1192
1193 int return_value = DecodeLoop(packet_list, operation, decoder,
1194 decoded_length, speech_type);
1195
1196 if (*decoded_length < 0) {
1197 // Error returned from the decoder.
1198 *decoded_length = 0;
1199 sync_buffer_->IncreaseEndTimestamp(decoder_frame_length_);
1200 int error_code = 0;
1201 if (decoder)
1202 error_code = decoder->ErrorCode();
1203 if (error_code != 0) {
1204 // Got some error code from the decoder.
1205 decoder_error_code_ = error_code;
1206 return_value = kDecoderErrorCode;
1207 } else {
1208 // Decoder does not implement error codes. Return generic error.
1209 return_value = kOtherDecoderError;
1210 }
1211 LOG_FERR2(LS_WARNING, DecodeLoop, error_code, packet_list->size());
1212 *operation = kExpand; // Do expansion to get data instead.
1213 }
1214 if (*speech_type != AudioDecoder::kComfortNoise) {
1215 // Don't increment timestamp if codec returned CNG speech type
1216 // since in this case, the we will increment the CNGplayedTS counter.
1217 // Increase with number of samples per channel.
1218 assert(*decoded_length == 0 ||
1219 (decoder && decoder->channels() == sync_buffer_->Channels()));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001220 sync_buffer_->IncreaseEndTimestamp(
1221 *decoded_length / static_cast<int>(sync_buffer_->Channels()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001222 }
1223 return return_value;
1224}
1225
1226int NetEqImpl::DecodeLoop(PacketList* packet_list, Operations* operation,
1227 AudioDecoder* decoder, int* decoded_length,
1228 AudioDecoder::SpeechType* speech_type) {
1229 Packet* packet = NULL;
1230 if (!packet_list->empty()) {
1231 packet = packet_list->front();
1232 }
1233 // Do decoding.
1234 while (packet &&
1235 !decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1236 assert(decoder); // At this point, we must have a decoder object.
1237 // The number of channels in the |sync_buffer_| should be the same as the
1238 // number decoder channels.
1239 assert(sync_buffer_->Channels() == decoder->channels());
1240 assert(decoded_buffer_length_ >= kMaxFrameSize * decoder->channels());
1241 assert(*operation == kNormal || *operation == kAccelerate ||
1242 *operation == kMerge || *operation == kPreemptiveExpand);
1243 packet_list->pop_front();
henrik.lundin@webrtc.org63464a92013-01-30 09:41:56 +00001244 int payload_length = packet->payload_length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001245 int16_t decode_length;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +00001246 if (packet->sync_packet) {
1247 // Decode to silence with the same frame size as the last decode.
1248 LOG(LS_VERBOSE) << "Decoding sync-packet: " <<
1249 " ts=" << packet->header.timestamp <<
1250 ", sn=" << packet->header.sequenceNumber <<
1251 ", pt=" << static_cast<int>(packet->header.payloadType) <<
1252 ", ssrc=" << packet->header.ssrc <<
1253 ", len=" << packet->payload_length;
1254 memset(&decoded_buffer_[*decoded_length], 0, decoder_frame_length_ *
1255 decoder->channels() * sizeof(decoded_buffer_[0]));
1256 decode_length = decoder_frame_length_;
1257 } else if (!packet->primary) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001258 // This is a redundant payload; call the special decoder method.
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +00001259 LOG(LS_VERBOSE) << "Decoding packet (redundant):" <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001260 " ts=" << packet->header.timestamp <<
1261 ", sn=" << packet->header.sequenceNumber <<
1262 ", pt=" << static_cast<int>(packet->header.payloadType) <<
1263 ", ssrc=" << packet->header.ssrc <<
1264 ", len=" << packet->payload_length;
1265 decode_length = decoder->DecodeRedundant(
1266 packet->payload, packet->payload_length,
1267 &decoded_buffer_[*decoded_length], speech_type);
1268 } else {
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +00001269 LOG(LS_VERBOSE) << "Decoding packet: ts=" << packet->header.timestamp <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001270 ", sn=" << packet->header.sequenceNumber <<
1271 ", pt=" << static_cast<int>(packet->header.payloadType) <<
1272 ", ssrc=" << packet->header.ssrc <<
1273 ", len=" << packet->payload_length;
1274 decode_length = decoder->Decode(packet->payload,
1275 packet->payload_length,
1276 &decoded_buffer_[*decoded_length],
1277 speech_type);
1278 }
1279
1280 delete[] packet->payload;
1281 delete packet;
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001282 packet = NULL;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001283 if (decode_length > 0) {
1284 *decoded_length += decode_length;
1285 // Update |decoder_frame_length_| with number of samples per channel.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001286 decoder_frame_length_ = decode_length /
1287 static_cast<int>(decoder->channels());
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +00001288 LOG(LS_VERBOSE) << "Decoded " << decode_length << " samples (" <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001289 decoder->channels() << " channel(s) -> " << decoder_frame_length_ <<
1290 " samples per channel)";
1291 } else if (decode_length < 0) {
1292 // Error.
henrik.lundin@webrtc.org63464a92013-01-30 09:41:56 +00001293 LOG_FERR2(LS_WARNING, Decode, decode_length, payload_length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001294 *decoded_length = -1;
1295 PacketBuffer::DeleteAllPackets(packet_list);
1296 break;
1297 }
1298 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1299 // Guard against overflow.
1300 LOG_F(LS_WARNING) << "Decoded too much.";
1301 PacketBuffer::DeleteAllPackets(packet_list);
1302 return kDecodedTooMuch;
1303 }
1304 if (!packet_list->empty()) {
1305 packet = packet_list->front();
1306 } else {
1307 packet = NULL;
1308 }
1309 } // End of decode loop.
1310
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001311 // If the list is not empty at this point, either a decoding error terminated
1312 // the while-loop, or list must hold exactly one CNG packet.
1313 assert(packet_list->empty() || *decoded_length < 0 ||
1314 (packet_list->size() == 1 && packet &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001315 decoder_database_->IsComfortNoise(packet->header.payloadType)));
1316 return 0;
1317}
1318
1319void NetEqImpl::DoNormal(const int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001320 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001321 assert(normal_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001322 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001323 normal_->Process(decoded_buffer, decoded_length, last_mode_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001324 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001325 if (decoded_length != 0) {
1326 last_mode_ = kModeNormal;
1327 }
1328
1329 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1330 if ((speech_type == AudioDecoder::kComfortNoise)
1331 || ((last_mode_ == kModeCodecInternalCng)
1332 && (decoded_length == 0))) {
1333 // TODO(hlundin): Remove second part of || statement above.
1334 last_mode_ = kModeCodecInternalCng;
1335 }
1336
1337 if (!play_dtmf) {
1338 dtmf_tone_generator_->Reset();
1339 }
1340}
1341
1342void NetEqImpl::DoMerge(int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001343 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001344 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001345 assert(merge_.get());
1346 int new_length = merge_->Process(decoded_buffer, decoded_length,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001347 mute_factor_array_.get(),
1348 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001349
1350 // Update in-call and post-call statistics.
1351 if (expand_->MuteFactor(0) == 0) {
1352 // Expand generates only noise.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001353 stats_.ExpandedNoiseSamples(new_length - static_cast<int>(decoded_length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001354 } else {
1355 // Expansion generates more than only noise.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001356 stats_.ExpandedVoiceSamples(new_length - static_cast<int>(decoded_length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001357 }
1358
1359 last_mode_ = kModeMerge;
1360 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1361 if (speech_type == AudioDecoder::kComfortNoise) {
1362 last_mode_ = kModeCodecInternalCng;
1363 }
1364 expand_->Reset();
1365 if (!play_dtmf) {
1366 dtmf_tone_generator_->Reset();
1367 }
1368}
1369
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001370int NetEqImpl::DoExpand(bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001371 while ((sync_buffer_->FutureLength() - expand_->overlap_length()) <
1372 static_cast<size_t>(output_size_samples_)) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001373 algorithm_buffer_->Clear();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001374 int return_value = expand_->Process(algorithm_buffer_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001375 int length = static_cast<int>(algorithm_buffer_->Size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001376
1377 // Update in-call and post-call statistics.
1378 if (expand_->MuteFactor(0) == 0) {
1379 // Expand operation generates only noise.
1380 stats_.ExpandedNoiseSamples(length);
1381 } else {
1382 // Expand operation generates more than only noise.
1383 stats_.ExpandedVoiceSamples(length);
1384 }
1385
1386 last_mode_ = kModeExpand;
1387
1388 if (return_value < 0) {
1389 return return_value;
1390 }
1391
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001392 sync_buffer_->PushBack(*algorithm_buffer_);
1393 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001394 }
1395 if (!play_dtmf) {
1396 dtmf_tone_generator_->Reset();
1397 }
1398 return 0;
1399}
1400
1401int NetEqImpl::DoAccelerate(int16_t* decoded_buffer, size_t decoded_length,
1402 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001403 bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001404 const size_t required_samples = 240 * fs_mult_; // Must have 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001405 size_t borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001406 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001407 size_t decoded_length_per_channel = decoded_length / num_channels;
1408 if (decoded_length_per_channel < required_samples) {
1409 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001410 borrowed_samples_per_channel = static_cast<int>(required_samples -
1411 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001412 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1413 decoded_buffer,
1414 sizeof(int16_t) * decoded_length);
1415 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1416 decoded_buffer);
1417 decoded_length = required_samples * num_channels;
1418 }
1419
1420 int16_t samples_removed;
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001421 Accelerate::ReturnCodes return_code = accelerate_->Process(
1422 decoded_buffer, decoded_length, algorithm_buffer_.get(),
1423 &samples_removed);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001424 stats_.AcceleratedSamples(samples_removed);
1425 switch (return_code) {
1426 case Accelerate::kSuccess:
1427 last_mode_ = kModeAccelerateSuccess;
1428 break;
1429 case Accelerate::kSuccessLowEnergy:
1430 last_mode_ = kModeAccelerateLowEnergy;
1431 break;
1432 case Accelerate::kNoStretch:
1433 last_mode_ = kModeAccelerateFail;
1434 break;
1435 case Accelerate::kError:
1436 // TODO(hlundin): Map to kModeError instead?
1437 last_mode_ = kModeAccelerateFail;
1438 return kAccelerateError;
1439 }
1440
1441 if (borrowed_samples_per_channel > 0) {
1442 // Copy borrowed samples back to the |sync_buffer_|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001443 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001444 if (length < borrowed_samples_per_channel) {
1445 // This destroys the beginning of the buffer, but will not cause any
1446 // problems.
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 sync_buffer_->Size() -
1449 borrowed_samples_per_channel);
1450 sync_buffer_->PushFrontZeros(borrowed_samples_per_channel - length);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001451 algorithm_buffer_->PopFront(length);
1452 assert(algorithm_buffer_->Empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001453 } else {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001454 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001455 borrowed_samples_per_channel,
1456 sync_buffer_->Size() -
1457 borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001458 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001459 }
1460 }
1461
1462 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1463 if (speech_type == AudioDecoder::kComfortNoise) {
1464 last_mode_ = kModeCodecInternalCng;
1465 }
1466 if (!play_dtmf) {
1467 dtmf_tone_generator_->Reset();
1468 }
1469 expand_->Reset();
1470 return 0;
1471}
1472
1473int NetEqImpl::DoPreemptiveExpand(int16_t* decoded_buffer,
1474 size_t decoded_length,
1475 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001476 bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001477 const size_t required_samples = 240 * fs_mult_; // Must have 30 ms.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001478 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001479 int borrowed_samples_per_channel = 0;
1480 int old_borrowed_samples_per_channel = 0;
1481 size_t decoded_length_per_channel = decoded_length / num_channels;
1482 if (decoded_length_per_channel < required_samples) {
1483 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001484 borrowed_samples_per_channel = static_cast<int>(required_samples -
1485 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001486 // Calculate how many of these were already played out.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001487 old_borrowed_samples_per_channel = static_cast<int>(
1488 borrowed_samples_per_channel - sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001489 old_borrowed_samples_per_channel = std::max(
1490 0, old_borrowed_samples_per_channel);
1491 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1492 decoded_buffer,
1493 sizeof(int16_t) * decoded_length);
1494 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1495 decoded_buffer);
1496 decoded_length = required_samples * num_channels;
1497 }
1498
1499 int16_t samples_added;
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001500 PreemptiveExpand::ReturnCodes return_code = preemptive_expand_->Process(
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001501 decoded_buffer, static_cast<int>(decoded_length),
1502 old_borrowed_samples_per_channel,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001503 algorithm_buffer_.get(), &samples_added);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001504 stats_.PreemptiveExpandedSamples(samples_added);
1505 switch (return_code) {
1506 case PreemptiveExpand::kSuccess:
1507 last_mode_ = kModePreemptiveExpandSuccess;
1508 break;
1509 case PreemptiveExpand::kSuccessLowEnergy:
1510 last_mode_ = kModePreemptiveExpandLowEnergy;
1511 break;
1512 case PreemptiveExpand::kNoStretch:
1513 last_mode_ = kModePreemptiveExpandFail;
1514 break;
1515 case PreemptiveExpand::kError:
1516 // TODO(hlundin): Map to kModeError instead?
1517 last_mode_ = kModePreemptiveExpandFail;
1518 return kPreemptiveExpandError;
1519 }
1520
1521 if (borrowed_samples_per_channel > 0) {
1522 // Copy borrowed samples back to the |sync_buffer_|.
1523 sync_buffer_->ReplaceAtIndex(
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001524 *algorithm_buffer_, borrowed_samples_per_channel,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001525 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001526 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001527 }
1528
1529 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1530 if (speech_type == AudioDecoder::kComfortNoise) {
1531 last_mode_ = kModeCodecInternalCng;
1532 }
1533 if (!play_dtmf) {
1534 dtmf_tone_generator_->Reset();
1535 }
1536 expand_->Reset();
1537 return 0;
1538}
1539
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001540int NetEqImpl::DoRfc3389Cng(PacketList* packet_list, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001541 if (!packet_list->empty()) {
1542 // Must have exactly one SID frame at this point.
1543 assert(packet_list->size() == 1);
1544 Packet* packet = packet_list->front();
1545 packet_list->pop_front();
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001546 if (!decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1547#ifdef LEGACY_BITEXACT
1548 // This can happen due to a bug in GetDecision. Change the payload type
1549 // to a CNG type, and move on. Note that this means that we are in fact
1550 // sending a non-CNG payload to the comfort noise decoder for decoding.
1551 // Clearly wrong, but will maintain bit-exactness with legacy.
1552 if (fs_hz_ == 8000) {
1553 packet->header.payloadType =
1554 decoder_database_->GetRtpPayloadType(kDecoderCNGnb);
1555 } else if (fs_hz_ == 16000) {
1556 packet->header.payloadType =
1557 decoder_database_->GetRtpPayloadType(kDecoderCNGwb);
1558 } else if (fs_hz_ == 32000) {
1559 packet->header.payloadType =
1560 decoder_database_->GetRtpPayloadType(kDecoderCNGswb32kHz);
1561 } else if (fs_hz_ == 48000) {
1562 packet->header.payloadType =
1563 decoder_database_->GetRtpPayloadType(kDecoderCNGswb48kHz);
1564 }
1565 assert(decoder_database_->IsComfortNoise(packet->header.payloadType));
1566#else
1567 LOG(LS_ERROR) << "Trying to decode non-CNG payload as CNG.";
1568 return kOtherError;
1569#endif
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001570 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001571 // UpdateParameters() deletes |packet|.
1572 if (comfort_noise_->UpdateParameters(packet) ==
1573 ComfortNoise::kInternalError) {
1574 LOG_FERR0(LS_WARNING, UpdateParameters);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001575 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001576 return -comfort_noise_->internal_error_code();
1577 }
1578 }
1579 int cn_return = comfort_noise_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001580 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001581 expand_->Reset();
1582 last_mode_ = kModeRfc3389Cng;
1583 if (!play_dtmf) {
1584 dtmf_tone_generator_->Reset();
1585 }
1586 if (cn_return == ComfortNoise::kInternalError) {
1587 LOG_FERR1(LS_WARNING, comfort_noise_->Generate, cn_return);
1588 decoder_error_code_ = comfort_noise_->internal_error_code();
1589 return kComfortNoiseErrorCode;
1590 } else if (cn_return == ComfortNoise::kUnknownPayloadType) {
1591 LOG_FERR1(LS_WARNING, comfort_noise_->Generate, cn_return);
1592 return kUnknownRtpPayloadType;
1593 }
1594 return 0;
1595}
1596
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001597void NetEqImpl::DoCodecInternalCng() {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001598 int length = 0;
1599 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1600 int16_t decoded_buffer[kMaxFrameSize];
1601 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1602 if (decoder) {
1603 const uint8_t* dummy_payload = NULL;
1604 AudioDecoder::SpeechType speech_type;
1605 length = decoder->Decode(dummy_payload, 0, decoded_buffer, &speech_type);
1606 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001607 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001608 normal_->Process(decoded_buffer, length, last_mode_, mute_factor_array_.get(),
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001609 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001610 last_mode_ = kModeCodecInternalCng;
1611 expand_->Reset();
1612}
1613
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001614int NetEqImpl::DoDtmf(const DtmfEvent& dtmf_event, bool* play_dtmf) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001615 // This block of the code and the block further down, handling |dtmf_switch|
1616 // are commented out. Otherwise playing out-of-band DTMF would fail in VoE
1617 // test, DtmfTest.ManualSuccessfullySendsOutOfBandTelephoneEvents. This is
1618 // equivalent to |dtmf_switch| always be false.
1619 //
1620 // See http://webrtc-codereview.appspot.com/1195004/ for discussion
1621 // On this issue. This change might cause some glitches at the point of
1622 // switch from audio to DTMF. Issue 1545 is filed to track this.
1623 //
1624 // bool dtmf_switch = false;
1625 // if ((last_mode_ != kModeDtmf) && dtmf_tone_generator_->initialized()) {
1626 // // Special case; see below.
1627 // // We must catch this before calling Generate, since |initialized| is
1628 // // modified in that call.
1629 // dtmf_switch = true;
1630 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001631
1632 int dtmf_return_value = 0;
1633 if (!dtmf_tone_generator_->initialized()) {
1634 // Initialize if not already done.
1635 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1636 dtmf_event.volume);
1637 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001638
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001639 if (dtmf_return_value == 0) {
1640 // Generate DTMF signal.
1641 dtmf_return_value = dtmf_tone_generator_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001642 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001643 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001644
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001645 if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001646 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001647 return dtmf_return_value;
1648 }
1649
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001650 // if (dtmf_switch) {
1651 // // This is the special case where the previous operation was DTMF
1652 // // overdub, but the current instruction is "regular" DTMF. We must make
1653 // // sure that the DTMF does not have any discontinuities. The first DTMF
1654 // // sample that we generate now must be played out immediately, therefore
1655 // // it must be copied to the speech buffer.
1656 // // TODO(hlundin): This code seems incorrect. (Legacy.) Write test and
1657 // // verify correct operation.
1658 // assert(false);
1659 // // Must generate enough data to replace all of the |sync_buffer_|
1660 // // "future".
1661 // int required_length = sync_buffer_->FutureLength();
1662 // assert(dtmf_tone_generator_->initialized());
1663 // dtmf_return_value = dtmf_tone_generator_->Generate(required_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001664 // algorithm_buffer_);
1665 // assert((size_t) required_length == algorithm_buffer_->Size());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001666 // if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001667 // algorithm_buffer_->Zeros(output_size_samples_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001668 // return dtmf_return_value;
1669 // }
1670 //
1671 // // Overwrite the "future" part of the speech buffer with the new DTMF
1672 // // data.
1673 // // TODO(hlundin): It seems that this overwriting has gone lost.
1674 // // Not adapted for multi-channel yet.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001675 // assert(algorithm_buffer_->Channels() == 1);
1676 // if (algorithm_buffer_->Channels() != 1) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001677 // LOG(LS_WARNING) << "DTMF not supported for more than one channel";
1678 // return kStereoNotSupported;
1679 // }
1680 // // Shuffle the remaining data to the beginning of algorithm buffer.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001681 // algorithm_buffer_->PopFront(sync_buffer_->FutureLength());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001682 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001683
1684 sync_buffer_->IncreaseEndTimestamp(output_size_samples_);
1685 expand_->Reset();
1686 last_mode_ = kModeDtmf;
1687
1688 // Set to false because the DTMF is already in the algorithm buffer.
1689 *play_dtmf = false;
1690 return 0;
1691}
1692
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001693void NetEqImpl::DoAlternativePlc(bool increase_timestamp) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001694 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1695 int length;
1696 if (decoder && decoder->HasDecodePlc()) {
1697 // Use the decoder's packet-loss concealment.
1698 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1699 int16_t decoded_buffer[kMaxFrameSize];
1700 length = decoder->DecodePlc(1, decoded_buffer);
1701 if (length > 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001702 algorithm_buffer_->PushBackInterleaved(decoded_buffer, length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001703 } else {
1704 length = 0;
1705 }
1706 } else {
1707 // Do simple zero-stuffing.
1708 length = output_size_samples_;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001709 algorithm_buffer_->Zeros(length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001710 // By not advancing the timestamp, NetEq inserts samples.
1711 stats_.AddZeros(length);
1712 }
1713 if (increase_timestamp) {
1714 sync_buffer_->IncreaseEndTimestamp(length);
1715 }
1716 expand_->Reset();
1717}
1718
1719int NetEqImpl::DtmfOverdub(const DtmfEvent& dtmf_event, size_t num_channels,
1720 int16_t* output) const {
1721 size_t out_index = 0;
1722 int overdub_length = output_size_samples_; // Default value.
1723
1724 if (sync_buffer_->dtmf_index() > sync_buffer_->next_index()) {
1725 // Special operation for transition from "DTMF only" to "DTMF overdub".
1726 out_index = std::min(
1727 sync_buffer_->dtmf_index() - sync_buffer_->next_index(),
1728 static_cast<size_t>(output_size_samples_));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001729 overdub_length = output_size_samples_ - static_cast<int>(out_index);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001730 }
1731
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001732 AudioMultiVector dtmf_output(num_channels);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001733 int dtmf_return_value = 0;
1734 if (!dtmf_tone_generator_->initialized()) {
1735 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1736 dtmf_event.volume);
1737 }
1738 if (dtmf_return_value == 0) {
1739 dtmf_return_value = dtmf_tone_generator_->Generate(overdub_length,
1740 &dtmf_output);
1741 assert((size_t) overdub_length == dtmf_output.Size());
1742 }
1743 dtmf_output.ReadInterleaved(overdub_length, &output[out_index]);
1744 return dtmf_return_value < 0 ? dtmf_return_value : 0;
1745}
1746
1747int NetEqImpl::ExtractPackets(int required_samples, PacketList* packet_list) {
1748 bool first_packet = true;
1749 uint8_t prev_payload_type = 0;
1750 uint32_t prev_timestamp = 0;
1751 uint16_t prev_sequence_number = 0;
1752 bool next_packet_available = false;
1753
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001754 const RTPHeader* header = packet_buffer_->NextRtpHeader();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001755 assert(header);
1756 if (!header) {
1757 return -1;
1758 }
turaj@webrtc.org7df97062013-08-02 18:07:13 +00001759 uint32_t first_timestamp = header->timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001760 int extracted_samples = 0;
1761
1762 // Packet extraction loop.
1763 do {
1764 timestamp_ = header->timestamp;
1765 int discard_count = 0;
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001766 Packet* packet = packet_buffer_->GetNextPacket(&discard_count);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001767 // |header| may be invalid after the |packet_buffer_| operation.
1768 header = NULL;
1769 if (!packet) {
1770 LOG_FERR1(LS_ERROR, GetNextPacket, discard_count) <<
1771 "Should always be able to extract a packet here";
1772 assert(false); // Should always be able to extract a packet here.
1773 return -1;
1774 }
1775 stats_.PacketsDiscarded(discard_count);
1776 // Store waiting time in ms; packets->waiting_time is in "output blocks".
1777 stats_.StoreWaitingTime(packet->waiting_time * kOutputSizeMs);
1778 assert(packet->payload_length > 0);
1779 packet_list->push_back(packet); // Store packet in list.
1780
1781 if (first_packet) {
1782 first_packet = false;
minyue@webrtc.orgd7301772013-08-29 00:58:14 +00001783 decoded_packet_sequence_number_ = prev_sequence_number =
1784 packet->header.sequenceNumber;
1785 decoded_packet_timestamp_ = prev_timestamp = packet->header.timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001786 prev_payload_type = packet->header.payloadType;
1787 }
1788
1789 // Store number of extracted samples.
1790 int packet_duration = 0;
1791 AudioDecoder* decoder = decoder_database_->GetDecoder(
1792 packet->header.payloadType);
1793 if (decoder) {
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001794 if (packet->sync_packet) {
1795 packet_duration = decoder_frame_length_;
1796 } else {
1797 packet_duration = packet->primary ?
1798 decoder->PacketDuration(packet->payload, packet->payload_length) :
1799 decoder->PacketDurationRedundant(packet->payload,
1800 packet->payload_length);
1801 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001802 } else {
1803 LOG_FERR1(LS_WARNING, GetDecoder, packet->header.payloadType) <<
1804 "Could not find a decoder for a packet about to be extracted.";
1805 assert(false);
1806 }
1807 if (packet_duration <= 0) {
1808 // Decoder did not return a packet duration. Assume that the packet
1809 // contains the same number of samples as the previous one.
1810 packet_duration = decoder_frame_length_;
1811 }
1812 extracted_samples = packet->header.timestamp - first_timestamp +
1813 packet_duration;
1814
1815 // Check what packet is available next.
1816 header = packet_buffer_->NextRtpHeader();
1817 next_packet_available = false;
1818 if (header && prev_payload_type == header->payloadType) {
1819 int16_t seq_no_diff = header->sequenceNumber - prev_sequence_number;
1820 int32_t ts_diff = header->timestamp - prev_timestamp;
1821 if (seq_no_diff == 1 ||
1822 (seq_no_diff == 0 && ts_diff == decoder_frame_length_)) {
1823 // The next sequence number is available, or the next part of a packet
1824 // that was split into pieces upon insertion.
1825 next_packet_available = true;
1826 }
1827 prev_sequence_number = header->sequenceNumber;
1828 }
1829 } while (extracted_samples < required_samples && next_packet_available);
1830
1831 return extracted_samples;
1832}
1833
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001834void NetEqImpl::UpdatePlcComponents(int fs_hz, size_t channels) {
1835 // Delete objects and create new ones.
1836 expand_.reset(expand_factory_->Create(background_noise_.get(),
1837 sync_buffer_.get(), &random_vector_,
1838 fs_hz, channels));
1839 merge_.reset(new Merge(fs_hz, channels, expand_.get(), sync_buffer_.get()));
1840}
1841
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001842void NetEqImpl::SetSampleRateAndChannels(int fs_hz, size_t channels) {
1843 LOG_API2(fs_hz, channels);
1844 // TODO(hlundin): Change to an enumerator and skip assert.
1845 assert(fs_hz == 8000 || fs_hz == 16000 || fs_hz == 32000 || fs_hz == 48000);
1846 assert(channels > 0);
1847
1848 fs_hz_ = fs_hz;
1849 fs_mult_ = fs_hz / 8000;
1850 output_size_samples_ = kOutputSizeMs * 8 * fs_mult_;
1851 decoder_frame_length_ = 3 * output_size_samples_; // Initialize to 30ms.
1852
1853 last_mode_ = kModeNormal;
1854
1855 // Create a new array of mute factors and set all to 1.
1856 mute_factor_array_.reset(new int16_t[channels]);
1857 for (size_t i = 0; i < channels; ++i) {
1858 mute_factor_array_[i] = 16384; // 1.0 in Q14.
1859 }
1860
1861 // Reset comfort noise decoder, if there is one active.
1862 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
1863 if (cng_decoder) {
1864 cng_decoder->Init();
1865 }
1866
1867 // Reinit post-decode VAD with new sample rate.
1868 assert(vad_.get()); // Cannot be NULL here.
1869 vad_->Init();
1870
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001871 // Delete algorithm buffer and create a new one.
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001872 algorithm_buffer_.reset(new AudioMultiVector(channels));
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001873
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001874 // Delete sync buffer and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001875 sync_buffer_.reset(new SyncBuffer(channels, kSyncBufferSize * fs_mult_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001876
turaj@webrtc.orgff43c852013-09-25 00:07:27 +00001877
1878 // Delete BackgroundNoise object and create a new one, while preserving its
1879 // mode.
1880 NetEqBackgroundNoiseMode current_mode = kBgnOn;
1881 if (background_noise_.get())
1882 current_mode = background_noise_->mode();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001883 background_noise_.reset(new BackgroundNoise(channels));
turaj@webrtc.orgff43c852013-09-25 00:07:27 +00001884 background_noise_->set_mode(current_mode);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001885
1886 // Reset random vector.
1887 random_vector_.Reset();
1888
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001889 UpdatePlcComponents(fs_hz, channels);
1890
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001891 // Move index so that we create a small set of future samples (all 0).
1892 sync_buffer_->set_next_index(sync_buffer_->next_index() -
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001893 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001894
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001895 normal_.reset(new Normal(fs_hz, decoder_database_.get(), *background_noise_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001896 expand_.get()));
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +00001897 accelerate_.reset(
1898 accelerate_factory_->Create(fs_hz, channels, *background_noise_));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001899 preemptive_expand_.reset(preemptive_expand_factory_->Create(
1900 fs_hz, channels,
1901 *background_noise_,
1902 static_cast<int>(expand_->overlap_length())));
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001903
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001904 // Delete ComfortNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001905 comfort_noise_.reset(new ComfortNoise(fs_hz, decoder_database_.get(),
1906 sync_buffer_.get()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001907
1908 // Verify that |decoded_buffer_| is long enough.
1909 if (decoded_buffer_length_ < kMaxFrameSize * channels) {
1910 // Reallocate to larger size.
1911 decoded_buffer_length_ = kMaxFrameSize * channels;
1912 decoded_buffer_.reset(new int16_t[decoded_buffer_length_]);
1913 }
1914
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001915 // Create DecisionLogic if it is not created yet, then communicate new sample
1916 // rate and output size to DecisionLogic object.
1917 if (!decision_logic_.get()) {
1918 CreateDecisionLogic(kPlayoutOn);
1919 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001920 decision_logic_->SetSampleRate(fs_hz_, output_size_samples_);
1921}
1922
1923NetEqOutputType NetEqImpl::LastOutputType() {
1924 assert(vad_.get());
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001925 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001926 if (last_mode_ == kModeCodecInternalCng || last_mode_ == kModeRfc3389Cng) {
1927 return kOutputCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001928 } else if (last_mode_ == kModeExpand && expand_->MuteFactor(0) == 0) {
1929 // Expand mode has faded down to background noise only (very long expand).
1930 return kOutputPLCtoCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001931 } else if (last_mode_ == kModeExpand) {
1932 return kOutputPLC;
wu@webrtc.org24301a62013-12-13 19:17:43 +00001933 } else if (vad_->running() && !vad_->active_speech()) {
1934 return kOutputVADPassive;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001935 } else {
1936 return kOutputNormal;
1937 }
1938}
1939
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001940void NetEqImpl::CreateDecisionLogic(NetEqPlayoutMode mode) {
1941 decision_logic_.reset(DecisionLogic::Create(fs_hz_, output_size_samples_,
1942 mode,
1943 decoder_database_.get(),
1944 *packet_buffer_.get(),
1945 delay_manager_.get(),
1946 buffer_level_filter_.get()));
1947}
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001948} // namespace webrtc