blob: a184fc33549843904d61b057889e29ec1292455d [file] [log] [blame]
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001/*
2 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000011#include "webrtc/modules/audio_coding/neteq/neteq_impl.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000012
13#include <assert.h>
14#include <memory.h> // memset
15
16#include <algorithm>
17
18#include "webrtc/common_audio/signal_processing/include/signal_processing_library.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000019#include "webrtc/modules/audio_coding/neteq/accelerate.h"
20#include "webrtc/modules/audio_coding/neteq/background_noise.h"
21#include "webrtc/modules/audio_coding/neteq/buffer_level_filter.h"
22#include "webrtc/modules/audio_coding/neteq/comfort_noise.h"
23#include "webrtc/modules/audio_coding/neteq/decision_logic.h"
24#include "webrtc/modules/audio_coding/neteq/decoder_database.h"
25#include "webrtc/modules/audio_coding/neteq/defines.h"
26#include "webrtc/modules/audio_coding/neteq/delay_manager.h"
27#include "webrtc/modules/audio_coding/neteq/delay_peak_detector.h"
28#include "webrtc/modules/audio_coding/neteq/dtmf_buffer.h"
29#include "webrtc/modules/audio_coding/neteq/dtmf_tone_generator.h"
30#include "webrtc/modules/audio_coding/neteq/expand.h"
31#include "webrtc/modules/audio_coding/neteq/interface/audio_decoder.h"
32#include "webrtc/modules/audio_coding/neteq/merge.h"
33#include "webrtc/modules/audio_coding/neteq/normal.h"
34#include "webrtc/modules/audio_coding/neteq/packet_buffer.h"
35#include "webrtc/modules/audio_coding/neteq/packet.h"
36#include "webrtc/modules/audio_coding/neteq/payload_splitter.h"
37#include "webrtc/modules/audio_coding/neteq/post_decode_vad.h"
38#include "webrtc/modules/audio_coding/neteq/preemptive_expand.h"
39#include "webrtc/modules/audio_coding/neteq/sync_buffer.h"
40#include "webrtc/modules/audio_coding/neteq/timestamp_scaler.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000041#include "webrtc/modules/interface/module_common_types.h"
42#include "webrtc/system_wrappers/interface/critical_section_wrapper.h"
43#include "webrtc/system_wrappers/interface/logging.h"
44
45// Modify the code to obtain backwards bit-exactness. Once bit-exactness is no
46// longer required, this #define should be removed (and the code that it
47// enables).
48#define LEGACY_BITEXACT
49
50namespace webrtc {
51
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +000052NetEqImpl::NetEqImpl(const NetEq::Config& config,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000053 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)
henrik.lundin@webrtc.org2f816bb2014-06-05 10:37:13 +000066 : crit_sect_(CriticalSectionWrapper::CreateCriticalSection()),
67 buffer_level_filter_(buffer_level_filter),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000068 decoder_database_(decoder_database),
69 delay_manager_(delay_manager),
70 delay_peak_detector_(delay_peak_detector),
71 dtmf_buffer_(dtmf_buffer),
72 dtmf_tone_generator_(dtmf_tone_generator),
73 packet_buffer_(packet_buffer),
74 payload_splitter_(payload_splitter),
75 timestamp_scaler_(timestamp_scaler),
76 vad_(new PostDecodeVad()),
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +000077 expand_factory_(expand_factory),
78 accelerate_factory_(accelerate_factory),
79 preemptive_expand_factory_(preemptive_expand_factory),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000080 last_mode_(kModeNormal),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000081 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),
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +000093 background_noise_mode_(config.background_noise_mode),
minyue@webrtc.orgd7301772013-08-29 00:58:14 +000094 decoded_packet_sequence_number_(-1),
95 decoded_packet_timestamp_(0) {
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +000096 int fs = config.sample_rate_hz;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000097 if (fs != 8000 && fs != 16000 && fs != 32000 && fs != 48000) {
98 LOG(LS_ERROR) << "Sample rate " << fs << " Hz not supported. " <<
99 "Changing to 8000 Hz.";
100 fs = 8000;
101 }
andrew@webrtc.org0569d932014-04-09 17:48:48 +0000102 LOG(LS_VERBOSE) << "Create NetEqImpl object with fs = " << fs << ".";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000103 fs_hz_ = fs;
104 fs_mult_ = fs / 8000;
105 output_size_samples_ = kOutputSizeMs * 8 * fs_mult_;
106 decoder_frame_length_ = 3 * output_size_samples_;
107 WebRtcSpl_Init();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000108 if (create_components) {
109 SetSampleRateAndChannels(fs, 1); // Default is 1 channel.
110 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000111}
112
113NetEqImpl::~NetEqImpl() {
114 LOG(LS_INFO) << "Deleting NetEqImpl object.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000115}
116
117int NetEqImpl::InsertPacket(const WebRtcRTPHeader& rtp_header,
118 const uint8_t* payload,
119 int length_bytes,
120 uint32_t receive_timestamp) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000121 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000122 LOG(LS_VERBOSE) << "InsertPacket: ts=" << rtp_header.header.timestamp <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000123 ", sn=" << rtp_header.header.sequenceNumber <<
124 ", pt=" << static_cast<int>(rtp_header.header.payloadType) <<
125 ", ssrc=" << rtp_header.header.ssrc <<
126 ", len=" << length_bytes;
127 int error = InsertPacketInternal(rtp_header, payload, length_bytes,
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000128 receive_timestamp, false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000129 if (error != 0) {
130 LOG_FERR1(LS_WARNING, InsertPacketInternal, error);
131 error_code_ = error;
132 return kFail;
133 }
134 return kOK;
135}
136
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000137int NetEqImpl::InsertSyncPacket(const WebRtcRTPHeader& rtp_header,
138 uint32_t receive_timestamp) {
139 CriticalSectionScoped lock(crit_sect_.get());
140 LOG(LS_VERBOSE) << "InsertPacket-Sync: ts="
141 << rtp_header.header.timestamp <<
142 ", sn=" << rtp_header.header.sequenceNumber <<
143 ", pt=" << static_cast<int>(rtp_header.header.payloadType) <<
144 ", ssrc=" << rtp_header.header.ssrc;
145
146 const uint8_t kSyncPayload[] = { 's', 'y', 'n', 'c' };
147 int error = InsertPacketInternal(
148 rtp_header, kSyncPayload, sizeof(kSyncPayload), receive_timestamp, true);
149
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000150 if (error != 0) {
151 LOG_FERR1(LS_WARNING, InsertPacketInternal, error);
152 error_code_ = error;
153 return kFail;
154 }
155 return kOK;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000156}
157
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000158int NetEqImpl::GetAudio(size_t max_length, int16_t* output_audio,
159 int* samples_per_channel, int* num_channels,
160 NetEqOutputType* type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000161 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000162 LOG(LS_VERBOSE) << "GetAudio";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000163 int error = GetAudioInternal(max_length, output_audio, samples_per_channel,
164 num_channels);
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000165 LOG(LS_VERBOSE) << "Produced " << *samples_per_channel <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000166 " samples/channel for " << *num_channels << " channel(s)";
167 if (error != 0) {
168 LOG_FERR1(LS_WARNING, GetAudioInternal, error);
169 error_code_ = error;
170 return kFail;
171 }
172 if (type) {
173 *type = LastOutputType();
174 }
175 return kOK;
176}
177
178int NetEqImpl::RegisterPayloadType(enum NetEqDecoder codec,
179 uint8_t rtp_payload_type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000180 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000181 LOG_API2(static_cast<int>(rtp_payload_type), codec);
182 int ret = decoder_database_->RegisterPayload(rtp_payload_type, codec);
183 if (ret != DecoderDatabase::kOK) {
184 LOG_FERR2(LS_WARNING, RegisterPayload, rtp_payload_type, codec);
185 switch (ret) {
186 case DecoderDatabase::kInvalidRtpPayloadType:
187 error_code_ = kInvalidRtpPayloadType;
188 break;
189 case DecoderDatabase::kCodecNotSupported:
190 error_code_ = kCodecNotSupported;
191 break;
192 case DecoderDatabase::kDecoderExists:
193 error_code_ = kDecoderExists;
194 break;
195 default:
196 error_code_ = kOtherError;
197 }
198 return kFail;
199 }
200 return kOK;
201}
202
203int NetEqImpl::RegisterExternalDecoder(AudioDecoder* decoder,
204 enum NetEqDecoder codec,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000205 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 }
turaj@webrtc.orga596a382014-04-17 23:30:49 +0000213 const int sample_rate_hz = AudioDecoder::CodecSampleRateHz(codec);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000214 int ret = decoder_database_->InsertExternal(rtp_payload_type, codec,
215 sample_rate_hz, decoder);
216 if (ret != DecoderDatabase::kOK) {
217 LOG_FERR2(LS_WARNING, InsertExternal, rtp_payload_type, codec);
218 switch (ret) {
219 case DecoderDatabase::kInvalidRtpPayloadType:
220 error_code_ = kInvalidRtpPayloadType;
221 break;
222 case DecoderDatabase::kCodecNotSupported:
223 error_code_ = kCodecNotSupported;
224 break;
225 case DecoderDatabase::kDecoderExists:
226 error_code_ = kDecoderExists;
227 break;
228 case DecoderDatabase::kInvalidSampleRate:
229 error_code_ = kInvalidSampleRate;
230 break;
231 case DecoderDatabase::kInvalidPointer:
232 error_code_ = kInvalidPointer;
233 break;
234 default:
235 error_code_ = kOtherError;
236 }
237 return kFail;
238 }
239 return kOK;
240}
241
242int NetEqImpl::RemovePayloadType(uint8_t rtp_payload_type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000243 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000244 LOG_API1(static_cast<int>(rtp_payload_type));
245 int ret = decoder_database_->Remove(rtp_payload_type);
246 if (ret == DecoderDatabase::kOK) {
247 return kOK;
248 } else if (ret == DecoderDatabase::kDecoderNotFound) {
249 error_code_ = kDecoderNotFound;
250 } else {
251 error_code_ = kOtherError;
252 }
253 LOG_FERR1(LS_WARNING, Remove, rtp_payload_type);
254 return kFail;
255}
256
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000257bool NetEqImpl::SetMinimumDelay(int delay_ms) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000258 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000259 if (delay_ms >= 0 && delay_ms < 10000) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000260 assert(delay_manager_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000261 return delay_manager_->SetMinimumDelay(delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000262 }
263 return false;
264}
265
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000266bool NetEqImpl::SetMaximumDelay(int delay_ms) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000267 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000268 if (delay_ms >= 0 && delay_ms < 10000) {
269 assert(delay_manager_.get());
270 return delay_manager_->SetMaximumDelay(delay_ms);
271 }
272 return false;
273}
274
275int NetEqImpl::LeastRequiredDelayMs() const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000276 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000277 assert(delay_manager_.get());
278 return delay_manager_->least_required_delay_ms();
279}
280
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000281void NetEqImpl::SetPlayoutMode(NetEqPlayoutMode mode) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000282 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000283 if (!decision_logic_.get() || mode != decision_logic_->playout_mode()) {
284 // The reset() method calls delete for the old object.
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000285 CreateDecisionLogic(mode);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000286 }
287}
288
289NetEqPlayoutMode NetEqImpl::PlayoutMode() const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000290 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000291 assert(decision_logic_.get());
292 return decision_logic_->playout_mode();
293}
294
295int NetEqImpl::NetworkStatistics(NetEqNetworkStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000296 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000297 assert(decoder_database_.get());
298 const int total_samples_in_buffers = packet_buffer_->NumSamplesInBuffer(
299 decoder_database_.get(), decoder_frame_length_) +
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000300 static_cast<int>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000301 assert(delay_manager_.get());
302 assert(decision_logic_.get());
303 stats_.GetNetworkStatistics(fs_hz_, total_samples_in_buffers,
304 decoder_frame_length_, *delay_manager_.get(),
305 *decision_logic_.get(), stats);
306 return 0;
307}
308
309void NetEqImpl::WaitingTimes(std::vector<int>* waiting_times) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000310 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000311 stats_.WaitingTimes(waiting_times);
312}
313
314void NetEqImpl::GetRtcpStatistics(RtcpStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000315 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000316 if (stats) {
317 rtcp_.GetStatistics(false, stats);
318 }
319}
320
321void NetEqImpl::GetRtcpStatisticsNoReset(RtcpStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000322 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000323 if (stats) {
324 rtcp_.GetStatistics(true, stats);
325 }
326}
327
328void NetEqImpl::EnableVad() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000329 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000330 assert(vad_.get());
331 vad_->Enable();
332}
333
334void NetEqImpl::DisableVad() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000335 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000336 assert(vad_.get());
337 vad_->Disable();
338}
339
wu@webrtc.org94454b72014-06-05 20:34:08 +0000340bool NetEqImpl::GetPlayoutTimestamp(uint32_t* timestamp) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000341 CriticalSectionScoped lock(crit_sect_.get());
wu@webrtc.org94454b72014-06-05 20:34:08 +0000342 if (first_packet_) {
343 // We don't have a valid RTP timestamp until we have decoded our first
344 // RTP packet.
345 return false;
346 }
347 *timestamp = timestamp_scaler_->ToExternal(playout_timestamp_);
348 return true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000349}
350
351int NetEqImpl::LastError() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000352 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000353 return error_code_;
354}
355
356int NetEqImpl::LastDecoderError() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000357 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000358 return decoder_error_code_;
359}
360
361void NetEqImpl::FlushBuffers() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000362 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000363 LOG_API0();
364 packet_buffer_->Flush();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000365 assert(sync_buffer_.get());
366 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000367 sync_buffer_->Flush();
368 sync_buffer_->set_next_index(sync_buffer_->next_index() -
369 expand_->overlap_length());
370 // Set to wait for new codec.
371 first_packet_ = true;
372}
373
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000374void NetEqImpl::PacketBufferStatistics(int* current_num_packets,
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000375 int* max_num_packets) const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000376 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000377 packet_buffer_->BufferStat(current_num_packets, max_num_packets);
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000378}
379
turaj@webrtc.orgff43c852013-09-25 00:07:27 +0000380int NetEqImpl::DecodedRtpInfo(int* sequence_number, uint32_t* timestamp) const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000381 CriticalSectionScoped lock(crit_sect_.get());
minyue@webrtc.orgd7301772013-08-29 00:58:14 +0000382 if (decoded_packet_sequence_number_ < 0)
383 return -1;
384 *sequence_number = decoded_packet_sequence_number_;
385 *timestamp = decoded_packet_timestamp_;
386 return 0;
387}
388
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000389const SyncBuffer* NetEqImpl::sync_buffer_for_test() const {
390 CriticalSectionScoped lock(crit_sect_.get());
391 return sync_buffer_.get();
392}
393
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000394// Methods below this line are private.
395
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000396int NetEqImpl::InsertPacketInternal(const WebRtcRTPHeader& rtp_header,
397 const uint8_t* payload,
398 int length_bytes,
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000399 uint32_t receive_timestamp,
400 bool is_sync_packet) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000401 if (!payload) {
402 LOG_F(LS_ERROR) << "payload == NULL";
403 return kInvalidPointer;
404 }
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000405 // Sanity checks for sync-packets.
406 if (is_sync_packet) {
407 if (decoder_database_->IsDtmf(rtp_header.header.payloadType) ||
408 decoder_database_->IsRed(rtp_header.header.payloadType) ||
409 decoder_database_->IsComfortNoise(rtp_header.header.payloadType)) {
410 LOG_F(LS_ERROR) << "Sync-packet with an unacceptable payload type "
411 << rtp_header.header.payloadType;
412 return kSyncPacketNotAccepted;
413 }
414 if (first_packet_ ||
415 rtp_header.header.payloadType != current_rtp_payload_type_ ||
416 rtp_header.header.ssrc != ssrc_) {
417 // Even if |current_rtp_payload_type_| is 0xFF, sync-packet isn't
418 // accepted.
419 LOG_F(LS_ERROR) << "Changing codec, SSRC or first packet "
420 "with sync-packet.";
421 return kSyncPacketNotAccepted;
422 }
423 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000424 PacketList packet_list;
425 RTPHeader main_header;
426 {
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000427 // Convert to Packet.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000428 // Create |packet| within this separate scope, since it should not be used
429 // directly once it's been inserted in the packet list. This way, |packet|
430 // is not defined outside of this block.
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000431 Packet* packet = new Packet;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000432 packet->header.markerBit = false;
433 packet->header.payloadType = rtp_header.header.payloadType;
434 packet->header.sequenceNumber = rtp_header.header.sequenceNumber;
435 packet->header.timestamp = rtp_header.header.timestamp;
436 packet->header.ssrc = rtp_header.header.ssrc;
437 packet->header.numCSRCs = 0;
438 packet->payload_length = length_bytes;
439 packet->primary = true;
440 packet->waiting_time = 0;
441 packet->payload = new uint8_t[packet->payload_length];
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000442 packet->sync_packet = is_sync_packet;
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +0000443 if (!packet->payload) {
444 LOG_F(LS_ERROR) << "Payload pointer is NULL.";
445 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000446 assert(payload); // Already checked above.
447 memcpy(packet->payload, payload, packet->payload_length);
448 // Insert packet in a packet list.
449 packet_list.push_back(packet);
450 // Save main payloads header for later.
451 memcpy(&main_header, &packet->header, sizeof(main_header));
452 }
453
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000454 bool update_sample_rate_and_channels = false;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000455 // Reinitialize NetEq if it's needed (changed SSRC or first call).
456 if ((main_header.ssrc != ssrc_) || first_packet_) {
457 rtcp_.Init(main_header.sequenceNumber);
458 first_packet_ = false;
459
460 // Flush the packet buffer and DTMF buffer.
461 packet_buffer_->Flush();
462 dtmf_buffer_->Flush();
463
464 // Store new SSRC.
465 ssrc_ = main_header.ssrc;
466
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000467 // Update audio buffer timestamp.
468 sync_buffer_->IncreaseEndTimestamp(main_header.timestamp - timestamp_);
469
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000470 // Update codecs.
471 timestamp_ = main_header.timestamp;
472 current_rtp_payload_type_ = main_header.payloadType;
473
474 // Set MCU to update codec on next SignalMCU call.
475 new_codec_ = true;
476
477 // Reset timestamp scaling.
478 timestamp_scaler_->Reset();
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000479
480 // Triger an update of sampling rate and the number of channels.
481 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000482 }
483
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000484 // Update RTCP statistics, only for regular packets.
485 if (!is_sync_packet)
486 rtcp_.Update(main_header, receive_timestamp);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000487
488 // Check for RED payload type, and separate payloads into several packets.
489 if (decoder_database_->IsRed(main_header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000490 assert(!is_sync_packet); // We had a sanity check for this.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000491 if (payload_splitter_->SplitRed(&packet_list) != PayloadSplitter::kOK) {
492 LOG_FERR1(LS_WARNING, SplitRed, packet_list.size());
493 PacketBuffer::DeleteAllPackets(&packet_list);
494 return kRedundancySplitError;
495 }
496 // Only accept a few RED payloads of the same type as the main data,
497 // DTMF events and CNG.
498 payload_splitter_->CheckRedPayloads(&packet_list, *decoder_database_);
499 // Update the stored main payload header since the main payload has now
500 // changed.
501 memcpy(&main_header, &packet_list.front()->header, sizeof(main_header));
502 }
503
504 // Check payload types.
505 if (decoder_database_->CheckPayloadTypes(packet_list) ==
506 DecoderDatabase::kDecoderNotFound) {
507 LOG_FERR1(LS_WARNING, CheckPayloadTypes, packet_list.size());
508 PacketBuffer::DeleteAllPackets(&packet_list);
509 return kUnknownRtpPayloadType;
510 }
511
512 // Scale timestamp to internal domain (only for some codecs).
513 timestamp_scaler_->ToInternal(&packet_list);
514
515 // Process DTMF payloads. Cycle through the list of packets, and pick out any
516 // DTMF payloads found.
517 PacketList::iterator it = packet_list.begin();
518 while (it != packet_list.end()) {
519 Packet* current_packet = (*it);
520 assert(current_packet);
521 assert(current_packet->payload);
522 if (decoder_database_->IsDtmf(current_packet->header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000523 assert(!current_packet->sync_packet); // We had a sanity check for this.
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000524 DtmfEvent event;
525 int ret = DtmfBuffer::ParseEvent(
526 current_packet->header.timestamp,
527 current_packet->payload,
528 current_packet->payload_length,
529 &event);
530 if (ret != DtmfBuffer::kOK) {
531 LOG_FERR2(LS_WARNING, ParseEvent, ret,
532 current_packet->payload_length);
533 PacketBuffer::DeleteAllPackets(&packet_list);
534 return kDtmfParsingError;
535 }
536 if (dtmf_buffer_->InsertEvent(event) != DtmfBuffer::kOK) {
537 LOG_FERR0(LS_WARNING, InsertEvent);
538 PacketBuffer::DeleteAllPackets(&packet_list);
539 return kDtmfInsertError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000540 }
541 // TODO(hlundin): Let the destructor of Packet handle the payload.
542 delete [] current_packet->payload;
543 delete current_packet;
544 it = packet_list.erase(it);
545 } else {
546 ++it;
547 }
548 }
549
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000550 // Check for FEC in packets, and separate payloads into several packets.
551 int ret = payload_splitter_->SplitFec(&packet_list, decoder_database_.get());
552 if (ret != PayloadSplitter::kOK) {
553 LOG_FERR1(LS_WARNING, SplitFec, packet_list.size());
554 PacketBuffer::DeleteAllPackets(&packet_list);
555 switch (ret) {
556 case PayloadSplitter::kUnknownPayloadType:
557 return kUnknownRtpPayloadType;
558 default:
559 return kOtherError;
560 }
561 }
562
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000563 // Split payloads into smaller chunks. This also verifies that all payloads
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000564 // are of a known payload type. SplitAudio() method is protected against
565 // sync-packets.
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +0000566 ret = payload_splitter_->SplitAudio(&packet_list, *decoder_database_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000567 if (ret != PayloadSplitter::kOK) {
568 LOG_FERR1(LS_WARNING, SplitAudio, packet_list.size());
569 PacketBuffer::DeleteAllPackets(&packet_list);
570 switch (ret) {
571 case PayloadSplitter::kUnknownPayloadType:
572 return kUnknownRtpPayloadType;
573 case PayloadSplitter::kFrameSplitError:
574 return kFrameSplitError;
575 default:
576 return kOtherError;
577 }
578 }
579
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000580 // Update bandwidth estimate, if the packet is not sync-packet.
581 if (!packet_list.empty() && !packet_list.front()->sync_packet) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000582 // The list can be empty here if we got nothing but DTMF payloads.
583 AudioDecoder* decoder =
584 decoder_database_->GetDecoder(main_header.payloadType);
585 assert(decoder); // Should always get a valid object, since we have
586 // already checked that the payload types are known.
587 decoder->IncomingPacket(packet_list.front()->payload,
588 packet_list.front()->payload_length,
589 packet_list.front()->header.sequenceNumber,
590 packet_list.front()->header.timestamp,
591 receive_timestamp);
592 }
593
594 // Insert packets in buffer.
595 int temp_bufsize = packet_buffer_->NumPacketsInBuffer();
596 ret = packet_buffer_->InsertPacketList(
597 &packet_list,
598 *decoder_database_,
599 &current_rtp_payload_type_,
600 &current_cng_rtp_payload_type_);
601 if (ret == PacketBuffer::kFlushed) {
602 // Reset DSP timestamp etc. if packet buffer flushed.
603 new_codec_ = true;
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000604 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000605 LOG_F(LS_WARNING) << "Packet buffer flushed";
606 } else if (ret != PacketBuffer::kOK) {
607 LOG_FERR1(LS_WARNING, InsertPacketList, packet_list.size());
608 PacketBuffer::DeleteAllPackets(&packet_list);
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000609 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000610 }
611 if (current_rtp_payload_type_ != 0xFF) {
612 const DecoderDatabase::DecoderInfo* dec_info =
613 decoder_database_->GetDecoderInfo(current_rtp_payload_type_);
614 if (!dec_info) {
615 assert(false); // Already checked that the payload type is known.
616 }
617 }
618
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000619 if (update_sample_rate_and_channels && !packet_buffer_->Empty()) {
620 // We do not use |current_rtp_payload_type_| to |set payload_type|, but
621 // get the next RTP header from |packet_buffer_| to obtain the payload type.
622 // The reason for it is the following corner case. If NetEq receives a
623 // CNG packet with a sample rate different than the current CNG then it
624 // flushes its buffer, assuming send codec must have been changed. However,
625 // payload type of the hypothetically new send codec is not known.
626 const RTPHeader* rtp_header = packet_buffer_->NextRtpHeader();
627 assert(rtp_header);
628 int payload_type = rtp_header->payloadType;
629 AudioDecoder* decoder = decoder_database_->GetDecoder(payload_type);
630 assert(decoder); // Payloads are already checked to be valid.
631 const DecoderDatabase::DecoderInfo* decoder_info =
632 decoder_database_->GetDecoderInfo(payload_type);
633 assert(decoder_info);
634 if (decoder_info->fs_hz != fs_hz_ ||
635 decoder->channels() != algorithm_buffer_->Channels())
636 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->channels());
637 }
638
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000639 // TODO(hlundin): Move this code to DelayManager class.
640 const DecoderDatabase::DecoderInfo* dec_info =
641 decoder_database_->GetDecoderInfo(main_header.payloadType);
642 assert(dec_info); // Already checked that the payload type is known.
643 delay_manager_->LastDecoderType(dec_info->codec_type);
644 if (delay_manager_->last_pack_cng_or_dtmf() == 0) {
645 // Calculate the total speech length carried in each packet.
646 temp_bufsize = packet_buffer_->NumPacketsInBuffer() - temp_bufsize;
647 temp_bufsize *= decoder_frame_length_;
648
649 if ((temp_bufsize > 0) &&
650 (temp_bufsize != decision_logic_->packet_length_samples())) {
651 decision_logic_->set_packet_length_samples(temp_bufsize);
652 delay_manager_->SetPacketAudioLength((1000 * temp_bufsize) / fs_hz_);
653 }
654
655 // Update statistics.
pbos@webrtc.org0946a562013-04-09 00:28:06 +0000656 if ((int32_t) (main_header.timestamp - timestamp_) >= 0 &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000657 !new_codec_) {
658 // Only update statistics if incoming packet is not older than last played
659 // out packet, and if new codec flag is not set.
660 delay_manager_->Update(main_header.sequenceNumber, main_header.timestamp,
661 fs_hz_);
662 }
663 } else if (delay_manager_->last_pack_cng_or_dtmf() == -1) {
664 // This is first "normal" packet after CNG or DTMF.
665 // Reset packet time counter and measure time until next packet,
666 // but don't update statistics.
667 delay_manager_->set_last_pack_cng_or_dtmf(0);
668 delay_manager_->ResetPacketIatCount();
669 }
670 return 0;
671}
672
673int NetEqImpl::GetAudioInternal(size_t max_length, int16_t* output,
674 int* samples_per_channel, int* num_channels) {
675 PacketList packet_list;
676 DtmfEvent dtmf_event;
677 Operations operation;
678 bool play_dtmf;
679 int return_value = GetDecision(&operation, &packet_list, &dtmf_event,
680 &play_dtmf);
681 if (return_value != 0) {
682 LOG_FERR1(LS_WARNING, GetDecision, return_value);
683 assert(false);
684 last_mode_ = kModeError;
685 return return_value;
686 }
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000687 LOG(LS_VERBOSE) << "GetDecision returned operation=" << operation <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000688 " and " << packet_list.size() << " packet(s)";
689
690 AudioDecoder::SpeechType speech_type;
691 int length = 0;
692 int decode_return_value = Decode(&packet_list, &operation,
693 &length, &speech_type);
694
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000695 assert(vad_.get());
696 bool sid_frame_available =
697 (operation == kRfc3389Cng && !packet_list.empty());
698 vad_->Update(decoded_buffer_.get(), length, speech_type,
699 sid_frame_available, fs_hz_);
700
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000701 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000702 switch (operation) {
703 case kNormal: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000704 DoNormal(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000705 break;
706 }
707 case kMerge: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000708 DoMerge(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000709 break;
710 }
711 case kExpand: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000712 return_value = DoExpand(play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000713 break;
714 }
715 case kAccelerate: {
716 return_value = DoAccelerate(decoded_buffer_.get(), length, speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000717 play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000718 break;
719 }
720 case kPreemptiveExpand: {
721 return_value = DoPreemptiveExpand(decoded_buffer_.get(), length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000722 speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000723 break;
724 }
725 case kRfc3389Cng:
726 case kRfc3389CngNoPacket: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000727 return_value = DoRfc3389Cng(&packet_list, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000728 break;
729 }
730 case kCodecInternalCng: {
731 // This handles the case when there is no transmission and the decoder
732 // should produce internal comfort noise.
733 // TODO(hlundin): Write test for codec-internal CNG.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000734 DoCodecInternalCng();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000735 break;
736 }
737 case kDtmf: {
738 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000739 return_value = DoDtmf(dtmf_event, &play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000740 break;
741 }
742 case kAlternativePlc: {
743 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000744 DoAlternativePlc(false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000745 break;
746 }
747 case kAlternativePlcIncreaseTimestamp: {
748 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000749 DoAlternativePlc(true);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000750 break;
751 }
752 case kAudioRepetitionIncreaseTimestamp: {
753 // TODO(hlundin): Write test for this.
754 sync_buffer_->IncreaseEndTimestamp(output_size_samples_);
755 // Skipping break on purpose. Execution should move on into the
756 // next case.
757 }
758 case kAudioRepetition: {
759 // TODO(hlundin): Write test for this.
760 // Copy last |output_size_samples_| from |sync_buffer_| to
761 // |algorithm_buffer|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000762 algorithm_buffer_->PushBackFromIndex(
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000763 *sync_buffer_, sync_buffer_->Size() - output_size_samples_);
764 expand_->Reset();
765 break;
766 }
767 case kUndefined: {
768 LOG_F(LS_ERROR) << "Invalid operation kUndefined.";
769 assert(false); // This should not happen.
770 last_mode_ = kModeError;
771 return kInvalidOperation;
772 }
773 } // End of switch.
774 if (return_value < 0) {
775 return return_value;
776 }
777
778 if (last_mode_ != kModeRfc3389Cng) {
779 comfort_noise_->Reset();
780 }
781
782 // Copy from |algorithm_buffer| to |sync_buffer_|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000783 sync_buffer_->PushBack(*algorithm_buffer_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000784
785 // Extract data from |sync_buffer_| to |output|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000786 size_t num_output_samples_per_channel = output_size_samples_;
787 size_t num_output_samples = output_size_samples_ * sync_buffer_->Channels();
788 if (num_output_samples > max_length) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000789 LOG(LS_WARNING) << "Output array is too short. " << max_length << " < " <<
790 output_size_samples_ << " * " << sync_buffer_->Channels();
791 num_output_samples = max_length;
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000792 num_output_samples_per_channel = static_cast<int>(
793 max_length / sync_buffer_->Channels());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000794 }
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000795 int samples_from_sync = static_cast<int>(
796 sync_buffer_->GetNextAudioInterleaved(num_output_samples_per_channel,
797 output));
798 *num_channels = static_cast<int>(sync_buffer_->Channels());
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000799 LOG(LS_VERBOSE) << "Sync buffer (" << *num_channels << " channel(s)):" <<
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000800 " insert " << algorithm_buffer_->Size() << " samples, extract " <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000801 samples_from_sync << " samples";
802 if (samples_from_sync != output_size_samples_) {
803 LOG_F(LS_ERROR) << "samples_from_sync != output_size_samples_";
minyue@webrtc.orgdb1cefc2013-08-13 01:39:21 +0000804 // TODO(minyue): treatment of under-run, filling zeros
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000805 memset(output, 0, num_output_samples * sizeof(int16_t));
806 *samples_per_channel = output_size_samples_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000807 return kSampleUnderrun;
808 }
809 *samples_per_channel = output_size_samples_;
810
811 // Should always have overlap samples left in the |sync_buffer_|.
812 assert(sync_buffer_->FutureLength() >= expand_->overlap_length());
813
814 if (play_dtmf) {
815 return_value = DtmfOverdub(dtmf_event, sync_buffer_->Channels(), output);
816 }
817
818 // Update the background noise parameters if last operation wrote data
819 // straight from the decoder to the |sync_buffer_|. That is, none of the
820 // operations that modify the signal can be followed by a parameter update.
821 if ((last_mode_ == kModeNormal) ||
822 (last_mode_ == kModeAccelerateFail) ||
823 (last_mode_ == kModePreemptiveExpandFail) ||
824 (last_mode_ == kModeRfc3389Cng) ||
825 (last_mode_ == kModeCodecInternalCng)) {
826 background_noise_->Update(*sync_buffer_, *vad_.get());
827 }
828
829 if (operation == kDtmf) {
830 // DTMF data was written the end of |sync_buffer_|.
831 // Update index to end of DTMF data in |sync_buffer_|.
832 sync_buffer_->set_dtmf_index(sync_buffer_->Size());
833 }
834
henrik.lundin@webrtc.orged865b52014-03-06 10:28:07 +0000835 if (last_mode_ != kModeExpand) {
836 // If last operation was not expand, calculate the |playout_timestamp_| from
837 // the |sync_buffer_|. However, do not update the |playout_timestamp_| if it
838 // would be moved "backwards".
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000839 uint32_t temp_timestamp = sync_buffer_->end_timestamp() -
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000840 static_cast<uint32_t>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000841 if (static_cast<int32_t>(temp_timestamp - playout_timestamp_) > 0) {
842 playout_timestamp_ = temp_timestamp;
843 }
844 } else {
845 // Use dead reckoning to estimate the |playout_timestamp_|.
846 playout_timestamp_ += output_size_samples_;
847 }
848
849 if (decode_return_value) return decode_return_value;
850 return return_value;
851}
852
853int NetEqImpl::GetDecision(Operations* operation,
854 PacketList* packet_list,
855 DtmfEvent* dtmf_event,
856 bool* play_dtmf) {
857 // Initialize output variables.
858 *play_dtmf = false;
859 *operation = kUndefined;
860
861 // Increment time counters.
862 packet_buffer_->IncrementWaitingTimes();
863 stats_.IncreaseCounter(output_size_samples_, fs_hz_);
864
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000865 assert(sync_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000866 uint32_t end_timestamp = sync_buffer_->end_timestamp();
867 if (!new_codec_) {
868 packet_buffer_->DiscardOldPackets(end_timestamp);
869 }
870 const RTPHeader* header = packet_buffer_->NextRtpHeader();
871
henrik.lundin@webrtc.orgca8cb952014-03-12 10:26:52 +0000872 if (decision_logic_->CngRfc3389On() || last_mode_ == kModeRfc3389Cng) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000873 // Because of timestamp peculiarities, we have to "manually" disallow using
874 // a CNG packet with the same timestamp as the one that was last played.
875 // This can happen when using redundancy and will cause the timing to shift.
henrik.lundin@webrtc.org24779fe2014-03-14 12:40:05 +0000876 while (header && decoder_database_->IsComfortNoise(header->payloadType) &&
877 (end_timestamp >= header->timestamp ||
878 end_timestamp + decision_logic_->generated_noise_samples() >
879 header->timestamp)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000880 // Don't use this packet, discard it.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000881 if (packet_buffer_->DiscardNextPacket() != PacketBuffer::kOK) {
882 assert(false); // Must be ok by design.
883 }
884 // Check buffer again.
885 if (!new_codec_) {
886 packet_buffer_->DiscardOldPackets(end_timestamp);
887 }
888 header = packet_buffer_->NextRtpHeader();
889 }
890 }
891
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000892 assert(expand_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000893 const int samples_left = static_cast<int>(sync_buffer_->FutureLength() -
894 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000895 if (last_mode_ == kModeAccelerateSuccess ||
896 last_mode_ == kModeAccelerateLowEnergy ||
897 last_mode_ == kModePreemptiveExpandSuccess ||
898 last_mode_ == kModePreemptiveExpandLowEnergy) {
899 // Subtract (samples_left + output_size_samples_) from sampleMemory.
900 decision_logic_->AddSampleMemory(-(samples_left + output_size_samples_));
901 }
902
903 // Check if it is time to play a DTMF event.
904 if (dtmf_buffer_->GetEvent(end_timestamp +
905 decision_logic_->generated_noise_samples(),
906 dtmf_event)) {
907 *play_dtmf = true;
908 }
909
910 // Get instruction.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000911 assert(sync_buffer_.get());
912 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000913 *operation = decision_logic_->GetDecision(*sync_buffer_,
914 *expand_,
915 decoder_frame_length_,
916 header,
917 last_mode_,
918 *play_dtmf,
919 &reset_decoder_);
920
921 // Check if we already have enough samples in the |sync_buffer_|. If so,
922 // change decision to normal, unless the decision was merge, accelerate, or
923 // preemptive expand.
924 if (samples_left >= output_size_samples_ &&
925 *operation != kMerge &&
926 *operation != kAccelerate &&
927 *operation != kPreemptiveExpand) {
928 *operation = kNormal;
929 return 0;
930 }
931
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000932 decision_logic_->ExpandDecision(*operation);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000933
934 // Check conditions for reset.
935 if (new_codec_ || *operation == kUndefined) {
936 // The only valid reason to get kUndefined is that new_codec_ is set.
937 assert(new_codec_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000938 if (*play_dtmf && !header) {
939 timestamp_ = dtmf_event->timestamp;
940 } else {
941 assert(header);
942 if (!header) {
943 LOG_F(LS_ERROR) << "Packet missing where it shouldn't.";
944 return -1;
945 }
946 timestamp_ = header->timestamp;
947 if (*operation == kRfc3389CngNoPacket
948#ifndef LEGACY_BITEXACT
949 // Without this check, it can happen that a non-CNG packet is sent to
950 // the CNG decoder as if it was a SID frame. This is clearly a bug,
951 // but is kept for now to maintain bit-exactness with the test
952 // vectors.
953 && decoder_database_->IsComfortNoise(header->payloadType)
954#endif
955 ) {
956 // Change decision to CNG packet, since we do have a CNG packet, but it
957 // was considered too early to use. Now, use it anyway.
958 *operation = kRfc3389Cng;
959 } else if (*operation != kRfc3389Cng) {
960 *operation = kNormal;
961 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000962 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000963 // Adjust |sync_buffer_| timestamp before setting |end_timestamp| to the
964 // new value.
965 sync_buffer_->IncreaseEndTimestamp(timestamp_ - end_timestamp);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000966 end_timestamp = timestamp_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000967 new_codec_ = false;
968 decision_logic_->SoftReset();
969 buffer_level_filter_->Reset();
970 delay_manager_->Reset();
971 stats_.ResetMcu();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000972 }
973
974 int required_samples = output_size_samples_;
975 const int samples_10_ms = 80 * fs_mult_;
976 const int samples_20_ms = 2 * samples_10_ms;
977 const int samples_30_ms = 3 * samples_10_ms;
978
979 switch (*operation) {
980 case kExpand: {
981 timestamp_ = end_timestamp;
982 return 0;
983 }
984 case kRfc3389CngNoPacket:
985 case kCodecInternalCng: {
986 return 0;
987 }
988 case kDtmf: {
989 // TODO(hlundin): Write test for this.
990 // Update timestamp.
991 timestamp_ = end_timestamp;
992 if (decision_logic_->generated_noise_samples() > 0 &&
993 last_mode_ != kModeDtmf) {
994 // Make a jump in timestamp due to the recently played comfort noise.
995 uint32_t timestamp_jump = decision_logic_->generated_noise_samples();
996 sync_buffer_->IncreaseEndTimestamp(timestamp_jump);
997 timestamp_ += timestamp_jump;
998 }
999 decision_logic_->set_generated_noise_samples(0);
1000 return 0;
1001 }
1002 case kAccelerate: {
1003 // In order to do a accelerate we need at least 30 ms of audio data.
1004 if (samples_left >= samples_30_ms) {
1005 // Already have enough data, so we do not need to extract any more.
1006 decision_logic_->set_sample_memory(samples_left);
1007 decision_logic_->set_prev_time_scale(true);
1008 return 0;
1009 } else if (samples_left >= samples_10_ms &&
1010 decoder_frame_length_ >= samples_30_ms) {
1011 // Avoid decoding more data as it might overflow the playout buffer.
1012 *operation = kNormal;
1013 return 0;
1014 } else if (samples_left < samples_20_ms &&
1015 decoder_frame_length_ < samples_30_ms) {
1016 // Build up decoded data by decoding at least 20 ms of audio data. Do
1017 // not perform accelerate yet, but wait until we only need to do one
1018 // decoding.
1019 required_samples = 2 * output_size_samples_;
1020 *operation = kNormal;
1021 }
1022 // If none of the above is true, we have one of two possible situations:
1023 // (1) 20 ms <= samples_left < 30 ms and decoder_frame_length_ < 30 ms; or
1024 // (2) samples_left < 10 ms and decoder_frame_length_ >= 30 ms.
1025 // In either case, we move on with the accelerate decision, and decode one
1026 // frame now.
1027 break;
1028 }
1029 case kPreemptiveExpand: {
1030 // In order to do a preemptive expand we need at least 30 ms of decoded
1031 // audio data.
1032 if ((samples_left >= samples_30_ms) ||
1033 (samples_left >= samples_10_ms &&
1034 decoder_frame_length_ >= samples_30_ms)) {
1035 // Already have enough data, so we do not need to extract any more.
1036 // Or, avoid decoding more data as it might overflow the playout buffer.
1037 // Still try preemptive expand, though.
1038 decision_logic_->set_sample_memory(samples_left);
1039 decision_logic_->set_prev_time_scale(true);
1040 return 0;
1041 }
1042 if (samples_left < samples_20_ms &&
1043 decoder_frame_length_ < samples_30_ms) {
1044 // Build up decoded data by decoding at least 20 ms of audio data.
1045 // Still try to perform preemptive expand.
1046 required_samples = 2 * output_size_samples_;
1047 }
1048 // Move on with the preemptive expand decision.
1049 break;
1050 }
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001051 case kMerge: {
1052 required_samples =
1053 std::max(merge_->RequiredFutureSamples(), required_samples);
1054 break;
1055 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001056 default: {
1057 // Do nothing.
1058 }
1059 }
1060
1061 // Get packets from buffer.
1062 int extracted_samples = 0;
1063 if (header &&
1064 *operation != kAlternativePlc &&
1065 *operation != kAlternativePlcIncreaseTimestamp &&
1066 *operation != kAudioRepetition &&
1067 *operation != kAudioRepetitionIncreaseTimestamp) {
1068 sync_buffer_->IncreaseEndTimestamp(header->timestamp - end_timestamp);
1069 if (decision_logic_->CngOff()) {
1070 // Adjustment of timestamp only corresponds to an actual packet loss
1071 // if comfort noise is not played. If comfort noise was just played,
1072 // this adjustment of timestamp is only done to get back in sync with the
1073 // stream timestamp; no loss to report.
1074 stats_.LostSamples(header->timestamp - end_timestamp);
1075 }
1076
1077 if (*operation != kRfc3389Cng) {
1078 // We are about to decode and use a non-CNG packet.
1079 decision_logic_->SetCngOff();
1080 }
1081 // Reset CNG timestamp as a new packet will be delivered.
1082 // (Also if this is a CNG packet, since playedOutTS is updated.)
1083 decision_logic_->set_generated_noise_samples(0);
1084
1085 extracted_samples = ExtractPackets(required_samples, packet_list);
1086 if (extracted_samples < 0) {
1087 LOG_F(LS_WARNING) << "Failed to extract packets from buffer.";
1088 return kPacketBufferCorruption;
1089 }
1090 }
1091
1092 if (*operation == kAccelerate ||
1093 *operation == kPreemptiveExpand) {
1094 decision_logic_->set_sample_memory(samples_left + extracted_samples);
1095 decision_logic_->set_prev_time_scale(true);
1096 }
1097
1098 if (*operation == kAccelerate) {
1099 // Check that we have enough data (30ms) to do accelerate.
1100 if (extracted_samples + samples_left < samples_30_ms) {
1101 // TODO(hlundin): Write test for this.
1102 // Not enough, do normal operation instead.
1103 *operation = kNormal;
1104 }
1105 }
1106
1107 timestamp_ = end_timestamp;
1108 return 0;
1109}
1110
1111int NetEqImpl::Decode(PacketList* packet_list, Operations* operation,
1112 int* decoded_length,
1113 AudioDecoder::SpeechType* speech_type) {
1114 *speech_type = AudioDecoder::kSpeech;
1115 AudioDecoder* decoder = NULL;
1116 if (!packet_list->empty()) {
1117 const Packet* packet = packet_list->front();
1118 int payload_type = packet->header.payloadType;
1119 if (!decoder_database_->IsComfortNoise(payload_type)) {
1120 decoder = decoder_database_->GetDecoder(payload_type);
1121 assert(decoder);
1122 if (!decoder) {
1123 LOG_FERR1(LS_WARNING, GetDecoder, payload_type);
1124 PacketBuffer::DeleteAllPackets(packet_list);
1125 return kDecoderNotFound;
1126 }
1127 bool decoder_changed;
1128 decoder_database_->SetActiveDecoder(payload_type, &decoder_changed);
1129 if (decoder_changed) {
1130 // We have a new decoder. Re-init some values.
1131 const DecoderDatabase::DecoderInfo* decoder_info = decoder_database_
1132 ->GetDecoderInfo(payload_type);
1133 assert(decoder_info);
1134 if (!decoder_info) {
1135 LOG_FERR1(LS_WARNING, GetDecoderInfo, payload_type);
1136 PacketBuffer::DeleteAllPackets(packet_list);
1137 return kDecoderNotFound;
1138 }
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001139 // If sampling rate or number of channels has changed, we need to make
1140 // a reset.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001141 if (decoder_info->fs_hz != fs_hz_ ||
1142 decoder->channels() != algorithm_buffer_->Channels()) {
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001143 // TODO(tlegrand): Add unittest to cover this event.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001144 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->channels());
1145 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001146 sync_buffer_->set_end_timestamp(timestamp_);
1147 playout_timestamp_ = timestamp_;
1148 }
1149 }
1150 }
1151
1152 if (reset_decoder_) {
1153 // TODO(hlundin): Write test for this.
1154 // Reset decoder.
1155 if (decoder) {
1156 decoder->Init();
1157 }
1158 // Reset comfort noise decoder.
1159 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
1160 if (cng_decoder) {
1161 cng_decoder->Init();
1162 }
1163 reset_decoder_ = false;
1164 }
1165
1166#ifdef LEGACY_BITEXACT
1167 // Due to a bug in old SignalMCU, it could happen that CNG operation was
1168 // decided, but a speech packet was provided. The speech packet will be used
1169 // to update the comfort noise decoder, as if it was a SID frame, which is
1170 // clearly wrong.
1171 if (*operation == kRfc3389Cng) {
1172 return 0;
1173 }
1174#endif
1175
1176 *decoded_length = 0;
1177 // Update codec-internal PLC state.
1178 if ((*operation == kMerge) && decoder && decoder->HasDecodePlc()) {
1179 decoder->DecodePlc(1, &decoded_buffer_[*decoded_length]);
1180 }
1181
1182 int return_value = DecodeLoop(packet_list, operation, decoder,
1183 decoded_length, speech_type);
1184
1185 if (*decoded_length < 0) {
1186 // Error returned from the decoder.
1187 *decoded_length = 0;
1188 sync_buffer_->IncreaseEndTimestamp(decoder_frame_length_);
1189 int error_code = 0;
1190 if (decoder)
1191 error_code = decoder->ErrorCode();
1192 if (error_code != 0) {
1193 // Got some error code from the decoder.
1194 decoder_error_code_ = error_code;
1195 return_value = kDecoderErrorCode;
1196 } else {
1197 // Decoder does not implement error codes. Return generic error.
1198 return_value = kOtherDecoderError;
1199 }
1200 LOG_FERR2(LS_WARNING, DecodeLoop, error_code, packet_list->size());
1201 *operation = kExpand; // Do expansion to get data instead.
1202 }
1203 if (*speech_type != AudioDecoder::kComfortNoise) {
1204 // Don't increment timestamp if codec returned CNG speech type
1205 // since in this case, the we will increment the CNGplayedTS counter.
1206 // Increase with number of samples per channel.
1207 assert(*decoded_length == 0 ||
1208 (decoder && decoder->channels() == sync_buffer_->Channels()));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001209 sync_buffer_->IncreaseEndTimestamp(
1210 *decoded_length / static_cast<int>(sync_buffer_->Channels()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001211 }
1212 return return_value;
1213}
1214
1215int NetEqImpl::DecodeLoop(PacketList* packet_list, Operations* operation,
1216 AudioDecoder* decoder, int* decoded_length,
1217 AudioDecoder::SpeechType* speech_type) {
1218 Packet* packet = NULL;
1219 if (!packet_list->empty()) {
1220 packet = packet_list->front();
1221 }
1222 // Do decoding.
1223 while (packet &&
1224 !decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1225 assert(decoder); // At this point, we must have a decoder object.
1226 // The number of channels in the |sync_buffer_| should be the same as the
1227 // number decoder channels.
1228 assert(sync_buffer_->Channels() == decoder->channels());
1229 assert(decoded_buffer_length_ >= kMaxFrameSize * decoder->channels());
1230 assert(*operation == kNormal || *operation == kAccelerate ||
1231 *operation == kMerge || *operation == kPreemptiveExpand);
1232 packet_list->pop_front();
henrik.lundin@webrtc.org63464a92013-01-30 09:41:56 +00001233 int payload_length = packet->payload_length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001234 int16_t decode_length;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +00001235 if (packet->sync_packet) {
1236 // Decode to silence with the same frame size as the last decode.
1237 LOG(LS_VERBOSE) << "Decoding sync-packet: " <<
1238 " ts=" << packet->header.timestamp <<
1239 ", sn=" << packet->header.sequenceNumber <<
1240 ", pt=" << static_cast<int>(packet->header.payloadType) <<
1241 ", ssrc=" << packet->header.ssrc <<
1242 ", len=" << packet->payload_length;
1243 memset(&decoded_buffer_[*decoded_length], 0, decoder_frame_length_ *
1244 decoder->channels() * sizeof(decoded_buffer_[0]));
1245 decode_length = decoder_frame_length_;
1246 } else if (!packet->primary) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001247 // This is a redundant payload; call the special decoder method.
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +00001248 LOG(LS_VERBOSE) << "Decoding packet (redundant):" <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001249 " 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 decode_length = decoder->DecodeRedundant(
1255 packet->payload, packet->payload_length,
1256 &decoded_buffer_[*decoded_length], speech_type);
1257 } else {
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +00001258 LOG(LS_VERBOSE) << "Decoding packet: ts=" << packet->header.timestamp <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001259 ", sn=" << packet->header.sequenceNumber <<
1260 ", pt=" << static_cast<int>(packet->header.payloadType) <<
1261 ", ssrc=" << packet->header.ssrc <<
1262 ", len=" << packet->payload_length;
1263 decode_length = decoder->Decode(packet->payload,
1264 packet->payload_length,
1265 &decoded_buffer_[*decoded_length],
1266 speech_type);
1267 }
1268
1269 delete[] packet->payload;
1270 delete packet;
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001271 packet = NULL;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001272 if (decode_length > 0) {
1273 *decoded_length += decode_length;
1274 // Update |decoder_frame_length_| with number of samples per channel.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001275 decoder_frame_length_ = decode_length /
1276 static_cast<int>(decoder->channels());
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +00001277 LOG(LS_VERBOSE) << "Decoded " << decode_length << " samples (" <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001278 decoder->channels() << " channel(s) -> " << decoder_frame_length_ <<
1279 " samples per channel)";
1280 } else if (decode_length < 0) {
1281 // Error.
henrik.lundin@webrtc.org63464a92013-01-30 09:41:56 +00001282 LOG_FERR2(LS_WARNING, Decode, decode_length, payload_length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001283 *decoded_length = -1;
1284 PacketBuffer::DeleteAllPackets(packet_list);
1285 break;
1286 }
1287 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1288 // Guard against overflow.
1289 LOG_F(LS_WARNING) << "Decoded too much.";
1290 PacketBuffer::DeleteAllPackets(packet_list);
1291 return kDecodedTooMuch;
1292 }
1293 if (!packet_list->empty()) {
1294 packet = packet_list->front();
1295 } else {
1296 packet = NULL;
1297 }
1298 } // End of decode loop.
1299
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001300 // If the list is not empty at this point, either a decoding error terminated
1301 // the while-loop, or list must hold exactly one CNG packet.
1302 assert(packet_list->empty() || *decoded_length < 0 ||
1303 (packet_list->size() == 1 && packet &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001304 decoder_database_->IsComfortNoise(packet->header.payloadType)));
1305 return 0;
1306}
1307
1308void NetEqImpl::DoNormal(const int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001309 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001310 assert(normal_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001311 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001312 normal_->Process(decoded_buffer, decoded_length, last_mode_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001313 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001314 if (decoded_length != 0) {
1315 last_mode_ = kModeNormal;
1316 }
1317
1318 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1319 if ((speech_type == AudioDecoder::kComfortNoise)
1320 || ((last_mode_ == kModeCodecInternalCng)
1321 && (decoded_length == 0))) {
1322 // TODO(hlundin): Remove second part of || statement above.
1323 last_mode_ = kModeCodecInternalCng;
1324 }
1325
1326 if (!play_dtmf) {
1327 dtmf_tone_generator_->Reset();
1328 }
1329}
1330
1331void NetEqImpl::DoMerge(int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001332 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001333 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001334 assert(merge_.get());
1335 int new_length = merge_->Process(decoded_buffer, decoded_length,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001336 mute_factor_array_.get(),
1337 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001338
1339 // Update in-call and post-call statistics.
1340 if (expand_->MuteFactor(0) == 0) {
1341 // Expand generates only noise.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001342 stats_.ExpandedNoiseSamples(new_length - static_cast<int>(decoded_length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001343 } else {
1344 // Expansion generates more than only noise.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001345 stats_.ExpandedVoiceSamples(new_length - static_cast<int>(decoded_length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001346 }
1347
1348 last_mode_ = kModeMerge;
1349 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1350 if (speech_type == AudioDecoder::kComfortNoise) {
1351 last_mode_ = kModeCodecInternalCng;
1352 }
1353 expand_->Reset();
1354 if (!play_dtmf) {
1355 dtmf_tone_generator_->Reset();
1356 }
1357}
1358
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001359int NetEqImpl::DoExpand(bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001360 while ((sync_buffer_->FutureLength() - expand_->overlap_length()) <
1361 static_cast<size_t>(output_size_samples_)) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001362 algorithm_buffer_->Clear();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001363 int return_value = expand_->Process(algorithm_buffer_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001364 int length = static_cast<int>(algorithm_buffer_->Size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001365
1366 // Update in-call and post-call statistics.
1367 if (expand_->MuteFactor(0) == 0) {
1368 // Expand operation generates only noise.
1369 stats_.ExpandedNoiseSamples(length);
1370 } else {
1371 // Expand operation generates more than only noise.
1372 stats_.ExpandedVoiceSamples(length);
1373 }
1374
1375 last_mode_ = kModeExpand;
1376
1377 if (return_value < 0) {
1378 return return_value;
1379 }
1380
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001381 sync_buffer_->PushBack(*algorithm_buffer_);
1382 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001383 }
1384 if (!play_dtmf) {
1385 dtmf_tone_generator_->Reset();
1386 }
1387 return 0;
1388}
1389
1390int NetEqImpl::DoAccelerate(int16_t* decoded_buffer, size_t decoded_length,
1391 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001392 bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001393 const size_t required_samples = 240 * fs_mult_; // Must have 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001394 size_t borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001395 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001396 size_t decoded_length_per_channel = decoded_length / num_channels;
1397 if (decoded_length_per_channel < required_samples) {
1398 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001399 borrowed_samples_per_channel = static_cast<int>(required_samples -
1400 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001401 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1402 decoded_buffer,
1403 sizeof(int16_t) * decoded_length);
1404 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1405 decoded_buffer);
1406 decoded_length = required_samples * num_channels;
1407 }
1408
1409 int16_t samples_removed;
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001410 Accelerate::ReturnCodes return_code = accelerate_->Process(
1411 decoded_buffer, decoded_length, algorithm_buffer_.get(),
1412 &samples_removed);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001413 stats_.AcceleratedSamples(samples_removed);
1414 switch (return_code) {
1415 case Accelerate::kSuccess:
1416 last_mode_ = kModeAccelerateSuccess;
1417 break;
1418 case Accelerate::kSuccessLowEnergy:
1419 last_mode_ = kModeAccelerateLowEnergy;
1420 break;
1421 case Accelerate::kNoStretch:
1422 last_mode_ = kModeAccelerateFail;
1423 break;
1424 case Accelerate::kError:
1425 // TODO(hlundin): Map to kModeError instead?
1426 last_mode_ = kModeAccelerateFail;
1427 return kAccelerateError;
1428 }
1429
1430 if (borrowed_samples_per_channel > 0) {
1431 // Copy borrowed samples back to the |sync_buffer_|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001432 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001433 if (length < borrowed_samples_per_channel) {
1434 // This destroys the beginning of the buffer, but will not cause any
1435 // problems.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001436 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001437 sync_buffer_->Size() -
1438 borrowed_samples_per_channel);
1439 sync_buffer_->PushFrontZeros(borrowed_samples_per_channel - length);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001440 algorithm_buffer_->PopFront(length);
1441 assert(algorithm_buffer_->Empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001442 } else {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001443 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001444 borrowed_samples_per_channel,
1445 sync_buffer_->Size() -
1446 borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001447 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001448 }
1449 }
1450
1451 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1452 if (speech_type == AudioDecoder::kComfortNoise) {
1453 last_mode_ = kModeCodecInternalCng;
1454 }
1455 if (!play_dtmf) {
1456 dtmf_tone_generator_->Reset();
1457 }
1458 expand_->Reset();
1459 return 0;
1460}
1461
1462int NetEqImpl::DoPreemptiveExpand(int16_t* decoded_buffer,
1463 size_t decoded_length,
1464 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001465 bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001466 const size_t required_samples = 240 * fs_mult_; // Must have 30 ms.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001467 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001468 int borrowed_samples_per_channel = 0;
1469 int old_borrowed_samples_per_channel = 0;
1470 size_t decoded_length_per_channel = decoded_length / num_channels;
1471 if (decoded_length_per_channel < required_samples) {
1472 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001473 borrowed_samples_per_channel = static_cast<int>(required_samples -
1474 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001475 // Calculate how many of these were already played out.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001476 old_borrowed_samples_per_channel = static_cast<int>(
1477 borrowed_samples_per_channel - sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001478 old_borrowed_samples_per_channel = std::max(
1479 0, old_borrowed_samples_per_channel);
1480 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1481 decoded_buffer,
1482 sizeof(int16_t) * decoded_length);
1483 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1484 decoded_buffer);
1485 decoded_length = required_samples * num_channels;
1486 }
1487
1488 int16_t samples_added;
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001489 PreemptiveExpand::ReturnCodes return_code = preemptive_expand_->Process(
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001490 decoded_buffer, static_cast<int>(decoded_length),
1491 old_borrowed_samples_per_channel,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001492 algorithm_buffer_.get(), &samples_added);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001493 stats_.PreemptiveExpandedSamples(samples_added);
1494 switch (return_code) {
1495 case PreemptiveExpand::kSuccess:
1496 last_mode_ = kModePreemptiveExpandSuccess;
1497 break;
1498 case PreemptiveExpand::kSuccessLowEnergy:
1499 last_mode_ = kModePreemptiveExpandLowEnergy;
1500 break;
1501 case PreemptiveExpand::kNoStretch:
1502 last_mode_ = kModePreemptiveExpandFail;
1503 break;
1504 case PreemptiveExpand::kError:
1505 // TODO(hlundin): Map to kModeError instead?
1506 last_mode_ = kModePreemptiveExpandFail;
1507 return kPreemptiveExpandError;
1508 }
1509
1510 if (borrowed_samples_per_channel > 0) {
1511 // Copy borrowed samples back to the |sync_buffer_|.
1512 sync_buffer_->ReplaceAtIndex(
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001513 *algorithm_buffer_, borrowed_samples_per_channel,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001514 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001515 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001516 }
1517
1518 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1519 if (speech_type == AudioDecoder::kComfortNoise) {
1520 last_mode_ = kModeCodecInternalCng;
1521 }
1522 if (!play_dtmf) {
1523 dtmf_tone_generator_->Reset();
1524 }
1525 expand_->Reset();
1526 return 0;
1527}
1528
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001529int NetEqImpl::DoRfc3389Cng(PacketList* packet_list, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001530 if (!packet_list->empty()) {
1531 // Must have exactly one SID frame at this point.
1532 assert(packet_list->size() == 1);
1533 Packet* packet = packet_list->front();
1534 packet_list->pop_front();
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001535 if (!decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1536#ifdef LEGACY_BITEXACT
1537 // This can happen due to a bug in GetDecision. Change the payload type
1538 // to a CNG type, and move on. Note that this means that we are in fact
1539 // sending a non-CNG payload to the comfort noise decoder for decoding.
1540 // Clearly wrong, but will maintain bit-exactness with legacy.
1541 if (fs_hz_ == 8000) {
1542 packet->header.payloadType =
1543 decoder_database_->GetRtpPayloadType(kDecoderCNGnb);
1544 } else if (fs_hz_ == 16000) {
1545 packet->header.payloadType =
1546 decoder_database_->GetRtpPayloadType(kDecoderCNGwb);
1547 } else if (fs_hz_ == 32000) {
1548 packet->header.payloadType =
1549 decoder_database_->GetRtpPayloadType(kDecoderCNGswb32kHz);
1550 } else if (fs_hz_ == 48000) {
1551 packet->header.payloadType =
1552 decoder_database_->GetRtpPayloadType(kDecoderCNGswb48kHz);
1553 }
1554 assert(decoder_database_->IsComfortNoise(packet->header.payloadType));
1555#else
1556 LOG(LS_ERROR) << "Trying to decode non-CNG payload as CNG.";
1557 return kOtherError;
1558#endif
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001559 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001560 // UpdateParameters() deletes |packet|.
1561 if (comfort_noise_->UpdateParameters(packet) ==
1562 ComfortNoise::kInternalError) {
1563 LOG_FERR0(LS_WARNING, UpdateParameters);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001564 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001565 return -comfort_noise_->internal_error_code();
1566 }
1567 }
1568 int cn_return = comfort_noise_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001569 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001570 expand_->Reset();
1571 last_mode_ = kModeRfc3389Cng;
1572 if (!play_dtmf) {
1573 dtmf_tone_generator_->Reset();
1574 }
1575 if (cn_return == ComfortNoise::kInternalError) {
1576 LOG_FERR1(LS_WARNING, comfort_noise_->Generate, cn_return);
1577 decoder_error_code_ = comfort_noise_->internal_error_code();
1578 return kComfortNoiseErrorCode;
1579 } else if (cn_return == ComfortNoise::kUnknownPayloadType) {
1580 LOG_FERR1(LS_WARNING, comfort_noise_->Generate, cn_return);
1581 return kUnknownRtpPayloadType;
1582 }
1583 return 0;
1584}
1585
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001586void NetEqImpl::DoCodecInternalCng() {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001587 int length = 0;
1588 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1589 int16_t decoded_buffer[kMaxFrameSize];
1590 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1591 if (decoder) {
1592 const uint8_t* dummy_payload = NULL;
1593 AudioDecoder::SpeechType speech_type;
1594 length = decoder->Decode(dummy_payload, 0, decoded_buffer, &speech_type);
1595 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001596 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001597 normal_->Process(decoded_buffer, length, last_mode_, mute_factor_array_.get(),
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001598 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001599 last_mode_ = kModeCodecInternalCng;
1600 expand_->Reset();
1601}
1602
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001603int NetEqImpl::DoDtmf(const DtmfEvent& dtmf_event, bool* play_dtmf) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001604 // This block of the code and the block further down, handling |dtmf_switch|
1605 // are commented out. Otherwise playing out-of-band DTMF would fail in VoE
1606 // test, DtmfTest.ManualSuccessfullySendsOutOfBandTelephoneEvents. This is
1607 // equivalent to |dtmf_switch| always be false.
1608 //
1609 // See http://webrtc-codereview.appspot.com/1195004/ for discussion
1610 // On this issue. This change might cause some glitches at the point of
1611 // switch from audio to DTMF. Issue 1545 is filed to track this.
1612 //
1613 // bool dtmf_switch = false;
1614 // if ((last_mode_ != kModeDtmf) && dtmf_tone_generator_->initialized()) {
1615 // // Special case; see below.
1616 // // We must catch this before calling Generate, since |initialized| is
1617 // // modified in that call.
1618 // dtmf_switch = true;
1619 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001620
1621 int dtmf_return_value = 0;
1622 if (!dtmf_tone_generator_->initialized()) {
1623 // Initialize if not already done.
1624 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1625 dtmf_event.volume);
1626 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001627
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001628 if (dtmf_return_value == 0) {
1629 // Generate DTMF signal.
1630 dtmf_return_value = dtmf_tone_generator_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001631 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001632 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001633
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001634 if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001635 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001636 return dtmf_return_value;
1637 }
1638
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001639 // if (dtmf_switch) {
1640 // // This is the special case where the previous operation was DTMF
1641 // // overdub, but the current instruction is "regular" DTMF. We must make
1642 // // sure that the DTMF does not have any discontinuities. The first DTMF
1643 // // sample that we generate now must be played out immediately, therefore
1644 // // it must be copied to the speech buffer.
1645 // // TODO(hlundin): This code seems incorrect. (Legacy.) Write test and
1646 // // verify correct operation.
1647 // assert(false);
1648 // // Must generate enough data to replace all of the |sync_buffer_|
1649 // // "future".
1650 // int required_length = sync_buffer_->FutureLength();
1651 // assert(dtmf_tone_generator_->initialized());
1652 // dtmf_return_value = dtmf_tone_generator_->Generate(required_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001653 // algorithm_buffer_);
1654 // assert((size_t) required_length == algorithm_buffer_->Size());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001655 // if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001656 // algorithm_buffer_->Zeros(output_size_samples_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001657 // return dtmf_return_value;
1658 // }
1659 //
1660 // // Overwrite the "future" part of the speech buffer with the new DTMF
1661 // // data.
1662 // // TODO(hlundin): It seems that this overwriting has gone lost.
1663 // // Not adapted for multi-channel yet.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001664 // assert(algorithm_buffer_->Channels() == 1);
1665 // if (algorithm_buffer_->Channels() != 1) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001666 // LOG(LS_WARNING) << "DTMF not supported for more than one channel";
1667 // return kStereoNotSupported;
1668 // }
1669 // // Shuffle the remaining data to the beginning of algorithm buffer.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001670 // algorithm_buffer_->PopFront(sync_buffer_->FutureLength());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001671 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001672
1673 sync_buffer_->IncreaseEndTimestamp(output_size_samples_);
1674 expand_->Reset();
1675 last_mode_ = kModeDtmf;
1676
1677 // Set to false because the DTMF is already in the algorithm buffer.
1678 *play_dtmf = false;
1679 return 0;
1680}
1681
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001682void NetEqImpl::DoAlternativePlc(bool increase_timestamp) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001683 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1684 int length;
1685 if (decoder && decoder->HasDecodePlc()) {
1686 // Use the decoder's packet-loss concealment.
1687 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1688 int16_t decoded_buffer[kMaxFrameSize];
1689 length = decoder->DecodePlc(1, decoded_buffer);
1690 if (length > 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001691 algorithm_buffer_->PushBackInterleaved(decoded_buffer, length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001692 } else {
1693 length = 0;
1694 }
1695 } else {
1696 // Do simple zero-stuffing.
1697 length = output_size_samples_;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001698 algorithm_buffer_->Zeros(length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001699 // By not advancing the timestamp, NetEq inserts samples.
1700 stats_.AddZeros(length);
1701 }
1702 if (increase_timestamp) {
1703 sync_buffer_->IncreaseEndTimestamp(length);
1704 }
1705 expand_->Reset();
1706}
1707
1708int NetEqImpl::DtmfOverdub(const DtmfEvent& dtmf_event, size_t num_channels,
1709 int16_t* output) const {
1710 size_t out_index = 0;
1711 int overdub_length = output_size_samples_; // Default value.
1712
1713 if (sync_buffer_->dtmf_index() > sync_buffer_->next_index()) {
1714 // Special operation for transition from "DTMF only" to "DTMF overdub".
1715 out_index = std::min(
1716 sync_buffer_->dtmf_index() - sync_buffer_->next_index(),
1717 static_cast<size_t>(output_size_samples_));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001718 overdub_length = output_size_samples_ - static_cast<int>(out_index);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001719 }
1720
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001721 AudioMultiVector dtmf_output(num_channels);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001722 int dtmf_return_value = 0;
1723 if (!dtmf_tone_generator_->initialized()) {
1724 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1725 dtmf_event.volume);
1726 }
1727 if (dtmf_return_value == 0) {
1728 dtmf_return_value = dtmf_tone_generator_->Generate(overdub_length,
1729 &dtmf_output);
1730 assert((size_t) overdub_length == dtmf_output.Size());
1731 }
1732 dtmf_output.ReadInterleaved(overdub_length, &output[out_index]);
1733 return dtmf_return_value < 0 ? dtmf_return_value : 0;
1734}
1735
1736int NetEqImpl::ExtractPackets(int required_samples, PacketList* packet_list) {
1737 bool first_packet = true;
1738 uint8_t prev_payload_type = 0;
1739 uint32_t prev_timestamp = 0;
1740 uint16_t prev_sequence_number = 0;
1741 bool next_packet_available = false;
1742
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001743 const RTPHeader* header = packet_buffer_->NextRtpHeader();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001744 assert(header);
1745 if (!header) {
1746 return -1;
1747 }
turaj@webrtc.org7df97062013-08-02 18:07:13 +00001748 uint32_t first_timestamp = header->timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001749 int extracted_samples = 0;
1750
1751 // Packet extraction loop.
1752 do {
1753 timestamp_ = header->timestamp;
1754 int discard_count = 0;
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001755 Packet* packet = packet_buffer_->GetNextPacket(&discard_count);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001756 // |header| may be invalid after the |packet_buffer_| operation.
1757 header = NULL;
1758 if (!packet) {
1759 LOG_FERR1(LS_ERROR, GetNextPacket, discard_count) <<
1760 "Should always be able to extract a packet here";
1761 assert(false); // Should always be able to extract a packet here.
1762 return -1;
1763 }
1764 stats_.PacketsDiscarded(discard_count);
1765 // Store waiting time in ms; packets->waiting_time is in "output blocks".
1766 stats_.StoreWaitingTime(packet->waiting_time * kOutputSizeMs);
1767 assert(packet->payload_length > 0);
1768 packet_list->push_back(packet); // Store packet in list.
1769
1770 if (first_packet) {
1771 first_packet = false;
minyue@webrtc.orgd7301772013-08-29 00:58:14 +00001772 decoded_packet_sequence_number_ = prev_sequence_number =
1773 packet->header.sequenceNumber;
1774 decoded_packet_timestamp_ = prev_timestamp = packet->header.timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001775 prev_payload_type = packet->header.payloadType;
1776 }
1777
1778 // Store number of extracted samples.
1779 int packet_duration = 0;
1780 AudioDecoder* decoder = decoder_database_->GetDecoder(
1781 packet->header.payloadType);
1782 if (decoder) {
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001783 if (packet->sync_packet) {
1784 packet_duration = decoder_frame_length_;
1785 } else {
1786 packet_duration = packet->primary ?
1787 decoder->PacketDuration(packet->payload, packet->payload_length) :
1788 decoder->PacketDurationRedundant(packet->payload,
1789 packet->payload_length);
1790 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001791 } else {
1792 LOG_FERR1(LS_WARNING, GetDecoder, packet->header.payloadType) <<
1793 "Could not find a decoder for a packet about to be extracted.";
1794 assert(false);
1795 }
1796 if (packet_duration <= 0) {
1797 // Decoder did not return a packet duration. Assume that the packet
1798 // contains the same number of samples as the previous one.
1799 packet_duration = decoder_frame_length_;
1800 }
1801 extracted_samples = packet->header.timestamp - first_timestamp +
1802 packet_duration;
1803
1804 // Check what packet is available next.
1805 header = packet_buffer_->NextRtpHeader();
1806 next_packet_available = false;
1807 if (header && prev_payload_type == header->payloadType) {
1808 int16_t seq_no_diff = header->sequenceNumber - prev_sequence_number;
1809 int32_t ts_diff = header->timestamp - prev_timestamp;
1810 if (seq_no_diff == 1 ||
1811 (seq_no_diff == 0 && ts_diff == decoder_frame_length_)) {
1812 // The next sequence number is available, or the next part of a packet
1813 // that was split into pieces upon insertion.
1814 next_packet_available = true;
1815 }
1816 prev_sequence_number = header->sequenceNumber;
1817 }
1818 } while (extracted_samples < required_samples && next_packet_available);
1819
1820 return extracted_samples;
1821}
1822
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001823void NetEqImpl::UpdatePlcComponents(int fs_hz, size_t channels) {
1824 // Delete objects and create new ones.
1825 expand_.reset(expand_factory_->Create(background_noise_.get(),
1826 sync_buffer_.get(), &random_vector_,
1827 fs_hz, channels));
1828 merge_.reset(new Merge(fs_hz, channels, expand_.get(), sync_buffer_.get()));
1829}
1830
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001831void NetEqImpl::SetSampleRateAndChannels(int fs_hz, size_t channels) {
1832 LOG_API2(fs_hz, channels);
1833 // TODO(hlundin): Change to an enumerator and skip assert.
1834 assert(fs_hz == 8000 || fs_hz == 16000 || fs_hz == 32000 || fs_hz == 48000);
1835 assert(channels > 0);
1836
1837 fs_hz_ = fs_hz;
1838 fs_mult_ = fs_hz / 8000;
1839 output_size_samples_ = kOutputSizeMs * 8 * fs_mult_;
1840 decoder_frame_length_ = 3 * output_size_samples_; // Initialize to 30ms.
1841
1842 last_mode_ = kModeNormal;
1843
1844 // Create a new array of mute factors and set all to 1.
1845 mute_factor_array_.reset(new int16_t[channels]);
1846 for (size_t i = 0; i < channels; ++i) {
1847 mute_factor_array_[i] = 16384; // 1.0 in Q14.
1848 }
1849
1850 // Reset comfort noise decoder, if there is one active.
1851 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
1852 if (cng_decoder) {
1853 cng_decoder->Init();
1854 }
1855
1856 // Reinit post-decode VAD with new sample rate.
1857 assert(vad_.get()); // Cannot be NULL here.
1858 vad_->Init();
1859
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001860 // Delete algorithm buffer and create a new one.
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001861 algorithm_buffer_.reset(new AudioMultiVector(channels));
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001862
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001863 // Delete sync buffer and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001864 sync_buffer_.reset(new SyncBuffer(channels, kSyncBufferSize * fs_mult_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001865
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00001866 // Delete BackgroundNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001867 background_noise_.reset(new BackgroundNoise(channels));
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00001868 background_noise_->set_mode(background_noise_mode_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001869
1870 // Reset random vector.
1871 random_vector_.Reset();
1872
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001873 UpdatePlcComponents(fs_hz, channels);
1874
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001875 // Move index so that we create a small set of future samples (all 0).
1876 sync_buffer_->set_next_index(sync_buffer_->next_index() -
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001877 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001878
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001879 normal_.reset(new Normal(fs_hz, decoder_database_.get(), *background_noise_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001880 expand_.get()));
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +00001881 accelerate_.reset(
1882 accelerate_factory_->Create(fs_hz, channels, *background_noise_));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001883 preemptive_expand_.reset(preemptive_expand_factory_->Create(
1884 fs_hz, channels,
1885 *background_noise_,
1886 static_cast<int>(expand_->overlap_length())));
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001887
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001888 // Delete ComfortNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001889 comfort_noise_.reset(new ComfortNoise(fs_hz, decoder_database_.get(),
1890 sync_buffer_.get()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001891
1892 // Verify that |decoded_buffer_| is long enough.
1893 if (decoded_buffer_length_ < kMaxFrameSize * channels) {
1894 // Reallocate to larger size.
1895 decoded_buffer_length_ = kMaxFrameSize * channels;
1896 decoded_buffer_.reset(new int16_t[decoded_buffer_length_]);
1897 }
1898
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001899 // Create DecisionLogic if it is not created yet, then communicate new sample
1900 // rate and output size to DecisionLogic object.
1901 if (!decision_logic_.get()) {
1902 CreateDecisionLogic(kPlayoutOn);
1903 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001904 decision_logic_->SetSampleRate(fs_hz_, output_size_samples_);
1905}
1906
1907NetEqOutputType NetEqImpl::LastOutputType() {
1908 assert(vad_.get());
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001909 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001910 if (last_mode_ == kModeCodecInternalCng || last_mode_ == kModeRfc3389Cng) {
1911 return kOutputCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001912 } else if (last_mode_ == kModeExpand && expand_->MuteFactor(0) == 0) {
1913 // Expand mode has faded down to background noise only (very long expand).
1914 return kOutputPLCtoCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001915 } else if (last_mode_ == kModeExpand) {
1916 return kOutputPLC;
wu@webrtc.org24301a62013-12-13 19:17:43 +00001917 } else if (vad_->running() && !vad_->active_speech()) {
1918 return kOutputVADPassive;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001919 } else {
1920 return kOutputNormal;
1921 }
1922}
1923
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001924void NetEqImpl::CreateDecisionLogic(NetEqPlayoutMode mode) {
1925 decision_logic_.reset(DecisionLogic::Create(fs_hz_, output_size_samples_,
1926 mode,
1927 decoder_database_.get(),
1928 *packet_buffer_.get(),
1929 delay_manager_.get(),
1930 buffer_level_filter_.get()));
1931}
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001932} // namespace webrtc