blob: f3d1a4f6b87ee20c130c5711fe84de63bdc34459 [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),
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +000094 playout_mode_(config.playout_mode),
minyue@webrtc.orgd7301772013-08-29 00:58:14 +000095 decoded_packet_sequence_number_(-1),
96 decoded_packet_timestamp_(0) {
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +000097 int fs = config.sample_rate_hz;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000098 if (fs != 8000 && fs != 16000 && fs != 32000 && fs != 48000) {
99 LOG(LS_ERROR) << "Sample rate " << fs << " Hz not supported. " <<
100 "Changing to 8000 Hz.";
101 fs = 8000;
102 }
andrew@webrtc.org0569d932014-04-09 17:48:48 +0000103 LOG(LS_VERBOSE) << "Create NetEqImpl object with fs = " << fs << ".";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000104 fs_hz_ = fs;
105 fs_mult_ = fs / 8000;
106 output_size_samples_ = kOutputSizeMs * 8 * fs_mult_;
107 decoder_frame_length_ = 3 * output_size_samples_;
108 WebRtcSpl_Init();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000109 if (create_components) {
110 SetSampleRateAndChannels(fs, 1); // Default is 1 channel.
111 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000112}
113
114NetEqImpl::~NetEqImpl() {
115 LOG(LS_INFO) << "Deleting NetEqImpl object.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000116}
117
118int NetEqImpl::InsertPacket(const WebRtcRTPHeader& rtp_header,
119 const uint8_t* payload,
120 int length_bytes,
121 uint32_t receive_timestamp) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000122 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000123 LOG(LS_VERBOSE) << "InsertPacket: ts=" << rtp_header.header.timestamp <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000124 ", sn=" << rtp_header.header.sequenceNumber <<
125 ", pt=" << static_cast<int>(rtp_header.header.payloadType) <<
126 ", ssrc=" << rtp_header.header.ssrc <<
127 ", len=" << length_bytes;
128 int error = InsertPacketInternal(rtp_header, payload, length_bytes,
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000129 receive_timestamp, false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000130 if (error != 0) {
131 LOG_FERR1(LS_WARNING, InsertPacketInternal, error);
132 error_code_ = error;
133 return kFail;
134 }
135 return kOK;
136}
137
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000138int NetEqImpl::InsertSyncPacket(const WebRtcRTPHeader& rtp_header,
139 uint32_t receive_timestamp) {
140 CriticalSectionScoped lock(crit_sect_.get());
141 LOG(LS_VERBOSE) << "InsertPacket-Sync: ts="
142 << rtp_header.header.timestamp <<
143 ", sn=" << rtp_header.header.sequenceNumber <<
144 ", pt=" << static_cast<int>(rtp_header.header.payloadType) <<
145 ", ssrc=" << rtp_header.header.ssrc;
146
147 const uint8_t kSyncPayload[] = { 's', 'y', 'n', 'c' };
148 int error = InsertPacketInternal(
149 rtp_header, kSyncPayload, sizeof(kSyncPayload), receive_timestamp, true);
150
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000151 if (error != 0) {
152 LOG_FERR1(LS_WARNING, InsertPacketInternal, error);
153 error_code_ = error;
154 return kFail;
155 }
156 return kOK;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000157}
158
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000159int NetEqImpl::GetAudio(size_t max_length, int16_t* output_audio,
160 int* samples_per_channel, int* num_channels,
161 NetEqOutputType* type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000162 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000163 LOG(LS_VERBOSE) << "GetAudio";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000164 int error = GetAudioInternal(max_length, output_audio, samples_per_channel,
165 num_channels);
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000166 LOG(LS_VERBOSE) << "Produced " << *samples_per_channel <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000167 " samples/channel for " << *num_channels << " channel(s)";
168 if (error != 0) {
169 LOG_FERR1(LS_WARNING, GetAudioInternal, error);
170 error_code_ = error;
171 return kFail;
172 }
173 if (type) {
174 *type = LastOutputType();
175 }
176 return kOK;
177}
178
179int NetEqImpl::RegisterPayloadType(enum NetEqDecoder codec,
180 uint8_t rtp_payload_type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000181 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000182 LOG_API2(static_cast<int>(rtp_payload_type), codec);
183 int ret = decoder_database_->RegisterPayload(rtp_payload_type, codec);
184 if (ret != DecoderDatabase::kOK) {
185 LOG_FERR2(LS_WARNING, RegisterPayload, rtp_payload_type, codec);
186 switch (ret) {
187 case DecoderDatabase::kInvalidRtpPayloadType:
188 error_code_ = kInvalidRtpPayloadType;
189 break;
190 case DecoderDatabase::kCodecNotSupported:
191 error_code_ = kCodecNotSupported;
192 break;
193 case DecoderDatabase::kDecoderExists:
194 error_code_ = kDecoderExists;
195 break;
196 default:
197 error_code_ = kOtherError;
198 }
199 return kFail;
200 }
201 return kOK;
202}
203
204int NetEqImpl::RegisterExternalDecoder(AudioDecoder* decoder,
205 enum NetEqDecoder codec,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000206 uint8_t rtp_payload_type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000207 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000208 LOG_API2(static_cast<int>(rtp_payload_type), codec);
209 if (!decoder) {
210 LOG(LS_ERROR) << "Cannot register external decoder with NULL pointer";
211 assert(false);
212 return kFail;
213 }
turaj@webrtc.orga596a382014-04-17 23:30:49 +0000214 const int sample_rate_hz = AudioDecoder::CodecSampleRateHz(codec);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000215 int ret = decoder_database_->InsertExternal(rtp_payload_type, codec,
216 sample_rate_hz, decoder);
217 if (ret != DecoderDatabase::kOK) {
218 LOG_FERR2(LS_WARNING, InsertExternal, rtp_payload_type, codec);
219 switch (ret) {
220 case DecoderDatabase::kInvalidRtpPayloadType:
221 error_code_ = kInvalidRtpPayloadType;
222 break;
223 case DecoderDatabase::kCodecNotSupported:
224 error_code_ = kCodecNotSupported;
225 break;
226 case DecoderDatabase::kDecoderExists:
227 error_code_ = kDecoderExists;
228 break;
229 case DecoderDatabase::kInvalidSampleRate:
230 error_code_ = kInvalidSampleRate;
231 break;
232 case DecoderDatabase::kInvalidPointer:
233 error_code_ = kInvalidPointer;
234 break;
235 default:
236 error_code_ = kOtherError;
237 }
238 return kFail;
239 }
240 return kOK;
241}
242
243int NetEqImpl::RemovePayloadType(uint8_t rtp_payload_type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000244 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000245 LOG_API1(static_cast<int>(rtp_payload_type));
246 int ret = decoder_database_->Remove(rtp_payload_type);
247 if (ret == DecoderDatabase::kOK) {
248 return kOK;
249 } else if (ret == DecoderDatabase::kDecoderNotFound) {
250 error_code_ = kDecoderNotFound;
251 } else {
252 error_code_ = kOtherError;
253 }
254 LOG_FERR1(LS_WARNING, Remove, rtp_payload_type);
255 return kFail;
256}
257
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000258bool NetEqImpl::SetMinimumDelay(int delay_ms) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000259 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000260 if (delay_ms >= 0 && delay_ms < 10000) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000261 assert(delay_manager_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000262 return delay_manager_->SetMinimumDelay(delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000263 }
264 return false;
265}
266
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000267bool NetEqImpl::SetMaximumDelay(int delay_ms) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000268 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000269 if (delay_ms >= 0 && delay_ms < 10000) {
270 assert(delay_manager_.get());
271 return delay_manager_->SetMaximumDelay(delay_ms);
272 }
273 return false;
274}
275
276int NetEqImpl::LeastRequiredDelayMs() const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000277 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000278 assert(delay_manager_.get());
279 return delay_manager_->least_required_delay_ms();
280}
281
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000282// Deprecated.
283// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000284void NetEqImpl::SetPlayoutMode(NetEqPlayoutMode mode) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000285 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000286 if (mode != playout_mode_) {
287 playout_mode_ = mode;
288 CreateDecisionLogic();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000289 }
290}
291
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000292// Deprecated.
293// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000294NetEqPlayoutMode NetEqImpl::PlayoutMode() const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000295 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000296 return playout_mode_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000297}
298
299int NetEqImpl::NetworkStatistics(NetEqNetworkStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000300 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000301 assert(decoder_database_.get());
302 const int total_samples_in_buffers = packet_buffer_->NumSamplesInBuffer(
303 decoder_database_.get(), decoder_frame_length_) +
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000304 static_cast<int>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000305 assert(delay_manager_.get());
306 assert(decision_logic_.get());
307 stats_.GetNetworkStatistics(fs_hz_, total_samples_in_buffers,
308 decoder_frame_length_, *delay_manager_.get(),
309 *decision_logic_.get(), stats);
310 return 0;
311}
312
313void NetEqImpl::WaitingTimes(std::vector<int>* waiting_times) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000314 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000315 stats_.WaitingTimes(waiting_times);
316}
317
318void NetEqImpl::GetRtcpStatistics(RtcpStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000319 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000320 if (stats) {
321 rtcp_.GetStatistics(false, stats);
322 }
323}
324
325void NetEqImpl::GetRtcpStatisticsNoReset(RtcpStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000326 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000327 if (stats) {
328 rtcp_.GetStatistics(true, stats);
329 }
330}
331
332void NetEqImpl::EnableVad() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000333 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000334 assert(vad_.get());
335 vad_->Enable();
336}
337
338void NetEqImpl::DisableVad() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000339 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000340 assert(vad_.get());
341 vad_->Disable();
342}
343
wu@webrtc.org94454b72014-06-05 20:34:08 +0000344bool NetEqImpl::GetPlayoutTimestamp(uint32_t* timestamp) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000345 CriticalSectionScoped lock(crit_sect_.get());
wu@webrtc.org94454b72014-06-05 20:34:08 +0000346 if (first_packet_) {
347 // We don't have a valid RTP timestamp until we have decoded our first
348 // RTP packet.
349 return false;
350 }
351 *timestamp = timestamp_scaler_->ToExternal(playout_timestamp_);
352 return true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000353}
354
henrik.lundin@webrtc.orgb0f4b3d2014-11-04 08:53:10 +0000355int NetEqImpl::LastError() const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000356 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000357 return error_code_;
358}
359
360int NetEqImpl::LastDecoderError() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000361 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000362 return decoder_error_code_;
363}
364
365void NetEqImpl::FlushBuffers() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000366 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000367 LOG_API0();
368 packet_buffer_->Flush();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000369 assert(sync_buffer_.get());
370 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000371 sync_buffer_->Flush();
372 sync_buffer_->set_next_index(sync_buffer_->next_index() -
373 expand_->overlap_length());
374 // Set to wait for new codec.
375 first_packet_ = true;
376}
377
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000378void NetEqImpl::PacketBufferStatistics(int* current_num_packets,
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000379 int* max_num_packets) const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000380 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000381 packet_buffer_->BufferStat(current_num_packets, max_num_packets);
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000382}
383
turaj@webrtc.orgff43c852013-09-25 00:07:27 +0000384int NetEqImpl::DecodedRtpInfo(int* sequence_number, uint32_t* timestamp) const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000385 CriticalSectionScoped lock(crit_sect_.get());
minyue@webrtc.orgd7301772013-08-29 00:58:14 +0000386 if (decoded_packet_sequence_number_ < 0)
387 return -1;
388 *sequence_number = decoded_packet_sequence_number_;
389 *timestamp = decoded_packet_timestamp_;
390 return 0;
391}
392
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000393const SyncBuffer* NetEqImpl::sync_buffer_for_test() const {
394 CriticalSectionScoped lock(crit_sect_.get());
395 return sync_buffer_.get();
396}
397
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000398// Methods below this line are private.
399
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000400int NetEqImpl::InsertPacketInternal(const WebRtcRTPHeader& rtp_header,
401 const uint8_t* payload,
402 int length_bytes,
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000403 uint32_t receive_timestamp,
404 bool is_sync_packet) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000405 if (!payload) {
406 LOG_F(LS_ERROR) << "payload == NULL";
407 return kInvalidPointer;
408 }
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000409 // Sanity checks for sync-packets.
410 if (is_sync_packet) {
411 if (decoder_database_->IsDtmf(rtp_header.header.payloadType) ||
412 decoder_database_->IsRed(rtp_header.header.payloadType) ||
413 decoder_database_->IsComfortNoise(rtp_header.header.payloadType)) {
414 LOG_F(LS_ERROR) << "Sync-packet with an unacceptable payload type "
415 << rtp_header.header.payloadType;
416 return kSyncPacketNotAccepted;
417 }
418 if (first_packet_ ||
419 rtp_header.header.payloadType != current_rtp_payload_type_ ||
420 rtp_header.header.ssrc != ssrc_) {
421 // Even if |current_rtp_payload_type_| is 0xFF, sync-packet isn't
422 // accepted.
423 LOG_F(LS_ERROR) << "Changing codec, SSRC or first packet "
424 "with sync-packet.";
425 return kSyncPacketNotAccepted;
426 }
427 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000428 PacketList packet_list;
429 RTPHeader main_header;
430 {
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000431 // Convert to Packet.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000432 // Create |packet| within this separate scope, since it should not be used
433 // directly once it's been inserted in the packet list. This way, |packet|
434 // is not defined outside of this block.
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000435 Packet* packet = new Packet;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000436 packet->header.markerBit = false;
437 packet->header.payloadType = rtp_header.header.payloadType;
438 packet->header.sequenceNumber = rtp_header.header.sequenceNumber;
439 packet->header.timestamp = rtp_header.header.timestamp;
440 packet->header.ssrc = rtp_header.header.ssrc;
441 packet->header.numCSRCs = 0;
442 packet->payload_length = length_bytes;
443 packet->primary = true;
444 packet->waiting_time = 0;
445 packet->payload = new uint8_t[packet->payload_length];
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000446 packet->sync_packet = is_sync_packet;
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +0000447 if (!packet->payload) {
448 LOG_F(LS_ERROR) << "Payload pointer is NULL.";
449 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000450 assert(payload); // Already checked above.
451 memcpy(packet->payload, payload, packet->payload_length);
452 // Insert packet in a packet list.
453 packet_list.push_back(packet);
454 // Save main payloads header for later.
455 memcpy(&main_header, &packet->header, sizeof(main_header));
456 }
457
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000458 bool update_sample_rate_and_channels = false;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000459 // Reinitialize NetEq if it's needed (changed SSRC or first call).
460 if ((main_header.ssrc != ssrc_) || first_packet_) {
461 rtcp_.Init(main_header.sequenceNumber);
462 first_packet_ = false;
463
464 // Flush the packet buffer and DTMF buffer.
465 packet_buffer_->Flush();
466 dtmf_buffer_->Flush();
467
468 // Store new SSRC.
469 ssrc_ = main_header.ssrc;
470
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000471 // Update audio buffer timestamp.
472 sync_buffer_->IncreaseEndTimestamp(main_header.timestamp - timestamp_);
473
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000474 // Update codecs.
475 timestamp_ = main_header.timestamp;
476 current_rtp_payload_type_ = main_header.payloadType;
477
478 // Set MCU to update codec on next SignalMCU call.
479 new_codec_ = true;
480
481 // Reset timestamp scaling.
482 timestamp_scaler_->Reset();
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000483
484 // Triger an update of sampling rate and the number of channels.
485 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000486 }
487
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000488 // Update RTCP statistics, only for regular packets.
489 if (!is_sync_packet)
490 rtcp_.Update(main_header, receive_timestamp);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000491
492 // Check for RED payload type, and separate payloads into several packets.
493 if (decoder_database_->IsRed(main_header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000494 assert(!is_sync_packet); // We had a sanity check for this.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000495 if (payload_splitter_->SplitRed(&packet_list) != PayloadSplitter::kOK) {
496 LOG_FERR1(LS_WARNING, SplitRed, packet_list.size());
497 PacketBuffer::DeleteAllPackets(&packet_list);
498 return kRedundancySplitError;
499 }
500 // Only accept a few RED payloads of the same type as the main data,
501 // DTMF events and CNG.
502 payload_splitter_->CheckRedPayloads(&packet_list, *decoder_database_);
503 // Update the stored main payload header since the main payload has now
504 // changed.
505 memcpy(&main_header, &packet_list.front()->header, sizeof(main_header));
506 }
507
508 // Check payload types.
509 if (decoder_database_->CheckPayloadTypes(packet_list) ==
510 DecoderDatabase::kDecoderNotFound) {
511 LOG_FERR1(LS_WARNING, CheckPayloadTypes, packet_list.size());
512 PacketBuffer::DeleteAllPackets(&packet_list);
513 return kUnknownRtpPayloadType;
514 }
515
516 // Scale timestamp to internal domain (only for some codecs).
517 timestamp_scaler_->ToInternal(&packet_list);
518
519 // Process DTMF payloads. Cycle through the list of packets, and pick out any
520 // DTMF payloads found.
521 PacketList::iterator it = packet_list.begin();
522 while (it != packet_list.end()) {
523 Packet* current_packet = (*it);
524 assert(current_packet);
525 assert(current_packet->payload);
526 if (decoder_database_->IsDtmf(current_packet->header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000527 assert(!current_packet->sync_packet); // We had a sanity check for this.
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000528 DtmfEvent event;
529 int ret = DtmfBuffer::ParseEvent(
530 current_packet->header.timestamp,
531 current_packet->payload,
532 current_packet->payload_length,
533 &event);
534 if (ret != DtmfBuffer::kOK) {
535 LOG_FERR2(LS_WARNING, ParseEvent, ret,
536 current_packet->payload_length);
537 PacketBuffer::DeleteAllPackets(&packet_list);
538 return kDtmfParsingError;
539 }
540 if (dtmf_buffer_->InsertEvent(event) != DtmfBuffer::kOK) {
541 LOG_FERR0(LS_WARNING, InsertEvent);
542 PacketBuffer::DeleteAllPackets(&packet_list);
543 return kDtmfInsertError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000544 }
545 // TODO(hlundin): Let the destructor of Packet handle the payload.
546 delete [] current_packet->payload;
547 delete current_packet;
548 it = packet_list.erase(it);
549 } else {
550 ++it;
551 }
552 }
553
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000554 // Check for FEC in packets, and separate payloads into several packets.
555 int ret = payload_splitter_->SplitFec(&packet_list, decoder_database_.get());
556 if (ret != PayloadSplitter::kOK) {
557 LOG_FERR1(LS_WARNING, SplitFec, packet_list.size());
558 PacketBuffer::DeleteAllPackets(&packet_list);
559 switch (ret) {
560 case PayloadSplitter::kUnknownPayloadType:
561 return kUnknownRtpPayloadType;
562 default:
563 return kOtherError;
564 }
565 }
566
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000567 // Split payloads into smaller chunks. This also verifies that all payloads
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000568 // are of a known payload type. SplitAudio() method is protected against
569 // sync-packets.
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +0000570 ret = payload_splitter_->SplitAudio(&packet_list, *decoder_database_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000571 if (ret != PayloadSplitter::kOK) {
572 LOG_FERR1(LS_WARNING, SplitAudio, packet_list.size());
573 PacketBuffer::DeleteAllPackets(&packet_list);
574 switch (ret) {
575 case PayloadSplitter::kUnknownPayloadType:
576 return kUnknownRtpPayloadType;
577 case PayloadSplitter::kFrameSplitError:
578 return kFrameSplitError;
579 default:
580 return kOtherError;
581 }
582 }
583
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000584 // Update bandwidth estimate, if the packet is not sync-packet.
585 if (!packet_list.empty() && !packet_list.front()->sync_packet) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000586 // The list can be empty here if we got nothing but DTMF payloads.
587 AudioDecoder* decoder =
588 decoder_database_->GetDecoder(main_header.payloadType);
589 assert(decoder); // Should always get a valid object, since we have
590 // already checked that the payload types are known.
591 decoder->IncomingPacket(packet_list.front()->payload,
592 packet_list.front()->payload_length,
593 packet_list.front()->header.sequenceNumber,
594 packet_list.front()->header.timestamp,
595 receive_timestamp);
596 }
597
598 // Insert packets in buffer.
599 int temp_bufsize = packet_buffer_->NumPacketsInBuffer();
600 ret = packet_buffer_->InsertPacketList(
601 &packet_list,
602 *decoder_database_,
603 &current_rtp_payload_type_,
604 &current_cng_rtp_payload_type_);
605 if (ret == PacketBuffer::kFlushed) {
606 // Reset DSP timestamp etc. if packet buffer flushed.
607 new_codec_ = true;
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000608 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000609 LOG_F(LS_WARNING) << "Packet buffer flushed";
610 } else if (ret != PacketBuffer::kOK) {
611 LOG_FERR1(LS_WARNING, InsertPacketList, packet_list.size());
612 PacketBuffer::DeleteAllPackets(&packet_list);
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000613 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000614 }
615 if (current_rtp_payload_type_ != 0xFF) {
616 const DecoderDatabase::DecoderInfo* dec_info =
617 decoder_database_->GetDecoderInfo(current_rtp_payload_type_);
618 if (!dec_info) {
619 assert(false); // Already checked that the payload type is known.
620 }
621 }
622
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000623 if (update_sample_rate_and_channels && !packet_buffer_->Empty()) {
624 // We do not use |current_rtp_payload_type_| to |set payload_type|, but
625 // get the next RTP header from |packet_buffer_| to obtain the payload type.
626 // The reason for it is the following corner case. If NetEq receives a
627 // CNG packet with a sample rate different than the current CNG then it
628 // flushes its buffer, assuming send codec must have been changed. However,
629 // payload type of the hypothetically new send codec is not known.
630 const RTPHeader* rtp_header = packet_buffer_->NextRtpHeader();
631 assert(rtp_header);
632 int payload_type = rtp_header->payloadType;
633 AudioDecoder* decoder = decoder_database_->GetDecoder(payload_type);
634 assert(decoder); // Payloads are already checked to be valid.
635 const DecoderDatabase::DecoderInfo* decoder_info =
636 decoder_database_->GetDecoderInfo(payload_type);
637 assert(decoder_info);
638 if (decoder_info->fs_hz != fs_hz_ ||
639 decoder->channels() != algorithm_buffer_->Channels())
640 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->channels());
641 }
642
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000643 // TODO(hlundin): Move this code to DelayManager class.
644 const DecoderDatabase::DecoderInfo* dec_info =
645 decoder_database_->GetDecoderInfo(main_header.payloadType);
646 assert(dec_info); // Already checked that the payload type is known.
647 delay_manager_->LastDecoderType(dec_info->codec_type);
648 if (delay_manager_->last_pack_cng_or_dtmf() == 0) {
649 // Calculate the total speech length carried in each packet.
650 temp_bufsize = packet_buffer_->NumPacketsInBuffer() - temp_bufsize;
651 temp_bufsize *= decoder_frame_length_;
652
653 if ((temp_bufsize > 0) &&
654 (temp_bufsize != decision_logic_->packet_length_samples())) {
655 decision_logic_->set_packet_length_samples(temp_bufsize);
656 delay_manager_->SetPacketAudioLength((1000 * temp_bufsize) / fs_hz_);
657 }
658
659 // Update statistics.
pbos@webrtc.org0946a562013-04-09 00:28:06 +0000660 if ((int32_t) (main_header.timestamp - timestamp_) >= 0 &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000661 !new_codec_) {
662 // Only update statistics if incoming packet is not older than last played
663 // out packet, and if new codec flag is not set.
664 delay_manager_->Update(main_header.sequenceNumber, main_header.timestamp,
665 fs_hz_);
666 }
667 } else if (delay_manager_->last_pack_cng_or_dtmf() == -1) {
668 // This is first "normal" packet after CNG or DTMF.
669 // Reset packet time counter and measure time until next packet,
670 // but don't update statistics.
671 delay_manager_->set_last_pack_cng_or_dtmf(0);
672 delay_manager_->ResetPacketIatCount();
673 }
674 return 0;
675}
676
677int NetEqImpl::GetAudioInternal(size_t max_length, int16_t* output,
678 int* samples_per_channel, int* num_channels) {
679 PacketList packet_list;
680 DtmfEvent dtmf_event;
681 Operations operation;
682 bool play_dtmf;
683 int return_value = GetDecision(&operation, &packet_list, &dtmf_event,
684 &play_dtmf);
685 if (return_value != 0) {
686 LOG_FERR1(LS_WARNING, GetDecision, return_value);
687 assert(false);
688 last_mode_ = kModeError;
689 return return_value;
690 }
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000691 LOG(LS_VERBOSE) << "GetDecision returned operation=" << operation <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000692 " and " << packet_list.size() << " packet(s)";
693
694 AudioDecoder::SpeechType speech_type;
695 int length = 0;
696 int decode_return_value = Decode(&packet_list, &operation,
697 &length, &speech_type);
698
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000699 assert(vad_.get());
700 bool sid_frame_available =
701 (operation == kRfc3389Cng && !packet_list.empty());
702 vad_->Update(decoded_buffer_.get(), length, speech_type,
703 sid_frame_available, fs_hz_);
704
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000705 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000706 switch (operation) {
707 case kNormal: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000708 DoNormal(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000709 break;
710 }
711 case kMerge: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000712 DoMerge(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000713 break;
714 }
715 case kExpand: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000716 return_value = DoExpand(play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000717 break;
718 }
719 case kAccelerate: {
720 return_value = DoAccelerate(decoded_buffer_.get(), length, speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000721 play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000722 break;
723 }
724 case kPreemptiveExpand: {
725 return_value = DoPreemptiveExpand(decoded_buffer_.get(), length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000726 speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000727 break;
728 }
729 case kRfc3389Cng:
730 case kRfc3389CngNoPacket: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000731 return_value = DoRfc3389Cng(&packet_list, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000732 break;
733 }
734 case kCodecInternalCng: {
735 // This handles the case when there is no transmission and the decoder
736 // should produce internal comfort noise.
737 // TODO(hlundin): Write test for codec-internal CNG.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000738 DoCodecInternalCng();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000739 break;
740 }
741 case kDtmf: {
742 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000743 return_value = DoDtmf(dtmf_event, &play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000744 break;
745 }
746 case kAlternativePlc: {
747 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000748 DoAlternativePlc(false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000749 break;
750 }
751 case kAlternativePlcIncreaseTimestamp: {
752 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000753 DoAlternativePlc(true);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000754 break;
755 }
756 case kAudioRepetitionIncreaseTimestamp: {
757 // TODO(hlundin): Write test for this.
758 sync_buffer_->IncreaseEndTimestamp(output_size_samples_);
759 // Skipping break on purpose. Execution should move on into the
760 // next case.
761 }
762 case kAudioRepetition: {
763 // TODO(hlundin): Write test for this.
764 // Copy last |output_size_samples_| from |sync_buffer_| to
765 // |algorithm_buffer|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000766 algorithm_buffer_->PushBackFromIndex(
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000767 *sync_buffer_, sync_buffer_->Size() - output_size_samples_);
768 expand_->Reset();
769 break;
770 }
771 case kUndefined: {
772 LOG_F(LS_ERROR) << "Invalid operation kUndefined.";
773 assert(false); // This should not happen.
774 last_mode_ = kModeError;
775 return kInvalidOperation;
776 }
777 } // End of switch.
778 if (return_value < 0) {
779 return return_value;
780 }
781
782 if (last_mode_ != kModeRfc3389Cng) {
783 comfort_noise_->Reset();
784 }
785
786 // Copy from |algorithm_buffer| to |sync_buffer_|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000787 sync_buffer_->PushBack(*algorithm_buffer_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000788
789 // Extract data from |sync_buffer_| to |output|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000790 size_t num_output_samples_per_channel = output_size_samples_;
791 size_t num_output_samples = output_size_samples_ * sync_buffer_->Channels();
792 if (num_output_samples > max_length) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000793 LOG(LS_WARNING) << "Output array is too short. " << max_length << " < " <<
794 output_size_samples_ << " * " << sync_buffer_->Channels();
795 num_output_samples = max_length;
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000796 num_output_samples_per_channel = static_cast<int>(
797 max_length / sync_buffer_->Channels());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000798 }
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000799 int samples_from_sync = static_cast<int>(
800 sync_buffer_->GetNextAudioInterleaved(num_output_samples_per_channel,
801 output));
802 *num_channels = static_cast<int>(sync_buffer_->Channels());
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000803 LOG(LS_VERBOSE) << "Sync buffer (" << *num_channels << " channel(s)):" <<
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000804 " insert " << algorithm_buffer_->Size() << " samples, extract " <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000805 samples_from_sync << " samples";
806 if (samples_from_sync != output_size_samples_) {
807 LOG_F(LS_ERROR) << "samples_from_sync != output_size_samples_";
minyue@webrtc.orgdb1cefc2013-08-13 01:39:21 +0000808 // TODO(minyue): treatment of under-run, filling zeros
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000809 memset(output, 0, num_output_samples * sizeof(int16_t));
810 *samples_per_channel = output_size_samples_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000811 return kSampleUnderrun;
812 }
813 *samples_per_channel = output_size_samples_;
814
815 // Should always have overlap samples left in the |sync_buffer_|.
816 assert(sync_buffer_->FutureLength() >= expand_->overlap_length());
817
818 if (play_dtmf) {
819 return_value = DtmfOverdub(dtmf_event, sync_buffer_->Channels(), output);
820 }
821
822 // Update the background noise parameters if last operation wrote data
823 // straight from the decoder to the |sync_buffer_|. That is, none of the
824 // operations that modify the signal can be followed by a parameter update.
825 if ((last_mode_ == kModeNormal) ||
826 (last_mode_ == kModeAccelerateFail) ||
827 (last_mode_ == kModePreemptiveExpandFail) ||
828 (last_mode_ == kModeRfc3389Cng) ||
829 (last_mode_ == kModeCodecInternalCng)) {
830 background_noise_->Update(*sync_buffer_, *vad_.get());
831 }
832
833 if (operation == kDtmf) {
834 // DTMF data was written the end of |sync_buffer_|.
835 // Update index to end of DTMF data in |sync_buffer_|.
836 sync_buffer_->set_dtmf_index(sync_buffer_->Size());
837 }
838
henrik.lundin@webrtc.orged865b52014-03-06 10:28:07 +0000839 if (last_mode_ != kModeExpand) {
840 // If last operation was not expand, calculate the |playout_timestamp_| from
841 // the |sync_buffer_|. However, do not update the |playout_timestamp_| if it
842 // would be moved "backwards".
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000843 uint32_t temp_timestamp = sync_buffer_->end_timestamp() -
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000844 static_cast<uint32_t>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000845 if (static_cast<int32_t>(temp_timestamp - playout_timestamp_) > 0) {
846 playout_timestamp_ = temp_timestamp;
847 }
848 } else {
849 // Use dead reckoning to estimate the |playout_timestamp_|.
850 playout_timestamp_ += output_size_samples_;
851 }
852
853 if (decode_return_value) return decode_return_value;
854 return return_value;
855}
856
857int NetEqImpl::GetDecision(Operations* operation,
858 PacketList* packet_list,
859 DtmfEvent* dtmf_event,
860 bool* play_dtmf) {
861 // Initialize output variables.
862 *play_dtmf = false;
863 *operation = kUndefined;
864
865 // Increment time counters.
866 packet_buffer_->IncrementWaitingTimes();
867 stats_.IncreaseCounter(output_size_samples_, fs_hz_);
868
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000869 assert(sync_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000870 uint32_t end_timestamp = sync_buffer_->end_timestamp();
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +0000871 if (!new_codec_) {
872 const uint32_t five_seconds_samples = 5 * fs_hz_;
873 packet_buffer_->DiscardOldPackets(end_timestamp, five_seconds_samples);
874 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000875 const RTPHeader* header = packet_buffer_->NextRtpHeader();
876
henrik.lundin@webrtc.orgca8cb952014-03-12 10:26:52 +0000877 if (decision_logic_->CngRfc3389On() || last_mode_ == kModeRfc3389Cng) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000878 // Because of timestamp peculiarities, we have to "manually" disallow using
879 // a CNG packet with the same timestamp as the one that was last played.
880 // This can happen when using redundancy and will cause the timing to shift.
henrik.lundin@webrtc.org24779fe2014-03-14 12:40:05 +0000881 while (header && decoder_database_->IsComfortNoise(header->payloadType) &&
882 (end_timestamp >= header->timestamp ||
883 end_timestamp + decision_logic_->generated_noise_samples() >
884 header->timestamp)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000885 // Don't use this packet, discard it.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000886 if (packet_buffer_->DiscardNextPacket() != PacketBuffer::kOK) {
887 assert(false); // Must be ok by design.
888 }
889 // Check buffer again.
890 if (!new_codec_) {
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +0000891 packet_buffer_->DiscardOldPackets(end_timestamp, 5 * fs_hz_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000892 }
893 header = packet_buffer_->NextRtpHeader();
894 }
895 }
896
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000897 assert(expand_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000898 const int samples_left = static_cast<int>(sync_buffer_->FutureLength() -
899 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000900 if (last_mode_ == kModeAccelerateSuccess ||
901 last_mode_ == kModeAccelerateLowEnergy ||
902 last_mode_ == kModePreemptiveExpandSuccess ||
903 last_mode_ == kModePreemptiveExpandLowEnergy) {
904 // Subtract (samples_left + output_size_samples_) from sampleMemory.
905 decision_logic_->AddSampleMemory(-(samples_left + output_size_samples_));
906 }
907
908 // Check if it is time to play a DTMF event.
909 if (dtmf_buffer_->GetEvent(end_timestamp +
910 decision_logic_->generated_noise_samples(),
911 dtmf_event)) {
912 *play_dtmf = true;
913 }
914
915 // Get instruction.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000916 assert(sync_buffer_.get());
917 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000918 *operation = decision_logic_->GetDecision(*sync_buffer_,
919 *expand_,
920 decoder_frame_length_,
921 header,
922 last_mode_,
923 *play_dtmf,
924 &reset_decoder_);
925
926 // Check if we already have enough samples in the |sync_buffer_|. If so,
927 // change decision to normal, unless the decision was merge, accelerate, or
928 // preemptive expand.
929 if (samples_left >= output_size_samples_ &&
930 *operation != kMerge &&
931 *operation != kAccelerate &&
932 *operation != kPreemptiveExpand) {
933 *operation = kNormal;
934 return 0;
935 }
936
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000937 decision_logic_->ExpandDecision(*operation);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000938
939 // Check conditions for reset.
940 if (new_codec_ || *operation == kUndefined) {
941 // The only valid reason to get kUndefined is that new_codec_ is set.
942 assert(new_codec_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000943 if (*play_dtmf && !header) {
944 timestamp_ = dtmf_event->timestamp;
945 } else {
946 assert(header);
947 if (!header) {
948 LOG_F(LS_ERROR) << "Packet missing where it shouldn't.";
949 return -1;
950 }
951 timestamp_ = header->timestamp;
952 if (*operation == kRfc3389CngNoPacket
953#ifndef LEGACY_BITEXACT
954 // Without this check, it can happen that a non-CNG packet is sent to
955 // the CNG decoder as if it was a SID frame. This is clearly a bug,
956 // but is kept for now to maintain bit-exactness with the test
957 // vectors.
958 && decoder_database_->IsComfortNoise(header->payloadType)
959#endif
960 ) {
961 // Change decision to CNG packet, since we do have a CNG packet, but it
962 // was considered too early to use. Now, use it anyway.
963 *operation = kRfc3389Cng;
964 } else if (*operation != kRfc3389Cng) {
965 *operation = kNormal;
966 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000967 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000968 // Adjust |sync_buffer_| timestamp before setting |end_timestamp| to the
969 // new value.
970 sync_buffer_->IncreaseEndTimestamp(timestamp_ - end_timestamp);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000971 end_timestamp = timestamp_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000972 new_codec_ = false;
973 decision_logic_->SoftReset();
974 buffer_level_filter_->Reset();
975 delay_manager_->Reset();
976 stats_.ResetMcu();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000977 }
978
979 int required_samples = output_size_samples_;
980 const int samples_10_ms = 80 * fs_mult_;
981 const int samples_20_ms = 2 * samples_10_ms;
982 const int samples_30_ms = 3 * samples_10_ms;
983
984 switch (*operation) {
985 case kExpand: {
986 timestamp_ = end_timestamp;
987 return 0;
988 }
989 case kRfc3389CngNoPacket:
990 case kCodecInternalCng: {
991 return 0;
992 }
993 case kDtmf: {
994 // TODO(hlundin): Write test for this.
995 // Update timestamp.
996 timestamp_ = end_timestamp;
997 if (decision_logic_->generated_noise_samples() > 0 &&
998 last_mode_ != kModeDtmf) {
999 // Make a jump in timestamp due to the recently played comfort noise.
1000 uint32_t timestamp_jump = decision_logic_->generated_noise_samples();
1001 sync_buffer_->IncreaseEndTimestamp(timestamp_jump);
1002 timestamp_ += timestamp_jump;
1003 }
1004 decision_logic_->set_generated_noise_samples(0);
1005 return 0;
1006 }
1007 case kAccelerate: {
1008 // In order to do a accelerate we need at least 30 ms of audio data.
1009 if (samples_left >= samples_30_ms) {
1010 // Already have enough data, so we do not need to extract any more.
1011 decision_logic_->set_sample_memory(samples_left);
1012 decision_logic_->set_prev_time_scale(true);
1013 return 0;
1014 } else if (samples_left >= samples_10_ms &&
1015 decoder_frame_length_ >= samples_30_ms) {
1016 // Avoid decoding more data as it might overflow the playout buffer.
1017 *operation = kNormal;
1018 return 0;
1019 } else if (samples_left < samples_20_ms &&
1020 decoder_frame_length_ < samples_30_ms) {
1021 // Build up decoded data by decoding at least 20 ms of audio data. Do
1022 // not perform accelerate yet, but wait until we only need to do one
1023 // decoding.
1024 required_samples = 2 * output_size_samples_;
1025 *operation = kNormal;
1026 }
1027 // If none of the above is true, we have one of two possible situations:
1028 // (1) 20 ms <= samples_left < 30 ms and decoder_frame_length_ < 30 ms; or
1029 // (2) samples_left < 10 ms and decoder_frame_length_ >= 30 ms.
1030 // In either case, we move on with the accelerate decision, and decode one
1031 // frame now.
1032 break;
1033 }
1034 case kPreemptiveExpand: {
1035 // In order to do a preemptive expand we need at least 30 ms of decoded
1036 // audio data.
1037 if ((samples_left >= samples_30_ms) ||
1038 (samples_left >= samples_10_ms &&
1039 decoder_frame_length_ >= samples_30_ms)) {
1040 // Already have enough data, so we do not need to extract any more.
1041 // Or, avoid decoding more data as it might overflow the playout buffer.
1042 // Still try preemptive expand, though.
1043 decision_logic_->set_sample_memory(samples_left);
1044 decision_logic_->set_prev_time_scale(true);
1045 return 0;
1046 }
1047 if (samples_left < samples_20_ms &&
1048 decoder_frame_length_ < samples_30_ms) {
1049 // Build up decoded data by decoding at least 20 ms of audio data.
1050 // Still try to perform preemptive expand.
1051 required_samples = 2 * output_size_samples_;
1052 }
1053 // Move on with the preemptive expand decision.
1054 break;
1055 }
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001056 case kMerge: {
1057 required_samples =
1058 std::max(merge_->RequiredFutureSamples(), required_samples);
1059 break;
1060 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001061 default: {
1062 // Do nothing.
1063 }
1064 }
1065
1066 // Get packets from buffer.
1067 int extracted_samples = 0;
1068 if (header &&
1069 *operation != kAlternativePlc &&
1070 *operation != kAlternativePlcIncreaseTimestamp &&
1071 *operation != kAudioRepetition &&
1072 *operation != kAudioRepetitionIncreaseTimestamp) {
1073 sync_buffer_->IncreaseEndTimestamp(header->timestamp - end_timestamp);
1074 if (decision_logic_->CngOff()) {
1075 // Adjustment of timestamp only corresponds to an actual packet loss
1076 // if comfort noise is not played. If comfort noise was just played,
1077 // this adjustment of timestamp is only done to get back in sync with the
1078 // stream timestamp; no loss to report.
1079 stats_.LostSamples(header->timestamp - end_timestamp);
1080 }
1081
1082 if (*operation != kRfc3389Cng) {
1083 // We are about to decode and use a non-CNG packet.
1084 decision_logic_->SetCngOff();
1085 }
1086 // Reset CNG timestamp as a new packet will be delivered.
1087 // (Also if this is a CNG packet, since playedOutTS is updated.)
1088 decision_logic_->set_generated_noise_samples(0);
1089
1090 extracted_samples = ExtractPackets(required_samples, packet_list);
1091 if (extracted_samples < 0) {
1092 LOG_F(LS_WARNING) << "Failed to extract packets from buffer.";
1093 return kPacketBufferCorruption;
1094 }
1095 }
1096
1097 if (*operation == kAccelerate ||
1098 *operation == kPreemptiveExpand) {
1099 decision_logic_->set_sample_memory(samples_left + extracted_samples);
1100 decision_logic_->set_prev_time_scale(true);
1101 }
1102
1103 if (*operation == kAccelerate) {
1104 // Check that we have enough data (30ms) to do accelerate.
1105 if (extracted_samples + samples_left < samples_30_ms) {
1106 // TODO(hlundin): Write test for this.
1107 // Not enough, do normal operation instead.
1108 *operation = kNormal;
1109 }
1110 }
1111
1112 timestamp_ = end_timestamp;
1113 return 0;
1114}
1115
1116int NetEqImpl::Decode(PacketList* packet_list, Operations* operation,
1117 int* decoded_length,
1118 AudioDecoder::SpeechType* speech_type) {
1119 *speech_type = AudioDecoder::kSpeech;
1120 AudioDecoder* decoder = NULL;
1121 if (!packet_list->empty()) {
1122 const Packet* packet = packet_list->front();
1123 int payload_type = packet->header.payloadType;
1124 if (!decoder_database_->IsComfortNoise(payload_type)) {
1125 decoder = decoder_database_->GetDecoder(payload_type);
1126 assert(decoder);
1127 if (!decoder) {
1128 LOG_FERR1(LS_WARNING, GetDecoder, payload_type);
1129 PacketBuffer::DeleteAllPackets(packet_list);
1130 return kDecoderNotFound;
1131 }
1132 bool decoder_changed;
1133 decoder_database_->SetActiveDecoder(payload_type, &decoder_changed);
1134 if (decoder_changed) {
1135 // We have a new decoder. Re-init some values.
1136 const DecoderDatabase::DecoderInfo* decoder_info = decoder_database_
1137 ->GetDecoderInfo(payload_type);
1138 assert(decoder_info);
1139 if (!decoder_info) {
1140 LOG_FERR1(LS_WARNING, GetDecoderInfo, payload_type);
1141 PacketBuffer::DeleteAllPackets(packet_list);
1142 return kDecoderNotFound;
1143 }
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001144 // If sampling rate or number of channels has changed, we need to make
1145 // a reset.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001146 if (decoder_info->fs_hz != fs_hz_ ||
1147 decoder->channels() != algorithm_buffer_->Channels()) {
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001148 // TODO(tlegrand): Add unittest to cover this event.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001149 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->channels());
1150 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001151 sync_buffer_->set_end_timestamp(timestamp_);
1152 playout_timestamp_ = timestamp_;
1153 }
1154 }
1155 }
1156
1157 if (reset_decoder_) {
1158 // TODO(hlundin): Write test for this.
1159 // Reset decoder.
1160 if (decoder) {
1161 decoder->Init();
1162 }
1163 // Reset comfort noise decoder.
1164 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
1165 if (cng_decoder) {
1166 cng_decoder->Init();
1167 }
1168 reset_decoder_ = false;
1169 }
1170
1171#ifdef LEGACY_BITEXACT
1172 // Due to a bug in old SignalMCU, it could happen that CNG operation was
1173 // decided, but a speech packet was provided. The speech packet will be used
1174 // to update the comfort noise decoder, as if it was a SID frame, which is
1175 // clearly wrong.
1176 if (*operation == kRfc3389Cng) {
1177 return 0;
1178 }
1179#endif
1180
1181 *decoded_length = 0;
1182 // Update codec-internal PLC state.
1183 if ((*operation == kMerge) && decoder && decoder->HasDecodePlc()) {
1184 decoder->DecodePlc(1, &decoded_buffer_[*decoded_length]);
1185 }
1186
1187 int return_value = DecodeLoop(packet_list, operation, decoder,
1188 decoded_length, speech_type);
1189
1190 if (*decoded_length < 0) {
1191 // Error returned from the decoder.
1192 *decoded_length = 0;
1193 sync_buffer_->IncreaseEndTimestamp(decoder_frame_length_);
1194 int error_code = 0;
1195 if (decoder)
1196 error_code = decoder->ErrorCode();
1197 if (error_code != 0) {
1198 // Got some error code from the decoder.
1199 decoder_error_code_ = error_code;
1200 return_value = kDecoderErrorCode;
1201 } else {
1202 // Decoder does not implement error codes. Return generic error.
1203 return_value = kOtherDecoderError;
1204 }
1205 LOG_FERR2(LS_WARNING, DecodeLoop, error_code, packet_list->size());
1206 *operation = kExpand; // Do expansion to get data instead.
1207 }
1208 if (*speech_type != AudioDecoder::kComfortNoise) {
1209 // Don't increment timestamp if codec returned CNG speech type
1210 // since in this case, the we will increment the CNGplayedTS counter.
1211 // Increase with number of samples per channel.
1212 assert(*decoded_length == 0 ||
1213 (decoder && decoder->channels() == sync_buffer_->Channels()));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001214 sync_buffer_->IncreaseEndTimestamp(
1215 *decoded_length / static_cast<int>(sync_buffer_->Channels()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001216 }
1217 return return_value;
1218}
1219
1220int NetEqImpl::DecodeLoop(PacketList* packet_list, Operations* operation,
1221 AudioDecoder* decoder, int* decoded_length,
1222 AudioDecoder::SpeechType* speech_type) {
1223 Packet* packet = NULL;
1224 if (!packet_list->empty()) {
1225 packet = packet_list->front();
1226 }
1227 // Do decoding.
1228 while (packet &&
1229 !decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1230 assert(decoder); // At this point, we must have a decoder object.
1231 // The number of channels in the |sync_buffer_| should be the same as the
1232 // number decoder channels.
1233 assert(sync_buffer_->Channels() == decoder->channels());
1234 assert(decoded_buffer_length_ >= kMaxFrameSize * decoder->channels());
1235 assert(*operation == kNormal || *operation == kAccelerate ||
1236 *operation == kMerge || *operation == kPreemptiveExpand);
1237 packet_list->pop_front();
henrik.lundin@webrtc.org63464a92013-01-30 09:41:56 +00001238 int payload_length = packet->payload_length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001239 int16_t decode_length;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +00001240 if (packet->sync_packet) {
1241 // Decode to silence with the same frame size as the last decode.
1242 LOG(LS_VERBOSE) << "Decoding sync-packet: " <<
1243 " ts=" << packet->header.timestamp <<
1244 ", sn=" << packet->header.sequenceNumber <<
1245 ", pt=" << static_cast<int>(packet->header.payloadType) <<
1246 ", ssrc=" << packet->header.ssrc <<
1247 ", len=" << packet->payload_length;
1248 memset(&decoded_buffer_[*decoded_length], 0, decoder_frame_length_ *
1249 decoder->channels() * sizeof(decoded_buffer_[0]));
1250 decode_length = decoder_frame_length_;
1251 } else if (!packet->primary) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001252 // This is a redundant payload; call the special decoder method.
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +00001253 LOG(LS_VERBOSE) << "Decoding packet (redundant):" <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001254 " ts=" << packet->header.timestamp <<
1255 ", sn=" << packet->header.sequenceNumber <<
1256 ", pt=" << static_cast<int>(packet->header.payloadType) <<
1257 ", ssrc=" << packet->header.ssrc <<
1258 ", len=" << packet->payload_length;
1259 decode_length = decoder->DecodeRedundant(
1260 packet->payload, packet->payload_length,
1261 &decoded_buffer_[*decoded_length], speech_type);
1262 } else {
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +00001263 LOG(LS_VERBOSE) << "Decoding packet: ts=" << packet->header.timestamp <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001264 ", sn=" << packet->header.sequenceNumber <<
1265 ", pt=" << static_cast<int>(packet->header.payloadType) <<
1266 ", ssrc=" << packet->header.ssrc <<
1267 ", len=" << packet->payload_length;
1268 decode_length = decoder->Decode(packet->payload,
1269 packet->payload_length,
1270 &decoded_buffer_[*decoded_length],
1271 speech_type);
1272 }
1273
1274 delete[] packet->payload;
1275 delete packet;
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001276 packet = NULL;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001277 if (decode_length > 0) {
1278 *decoded_length += decode_length;
1279 // Update |decoder_frame_length_| with number of samples per channel.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001280 decoder_frame_length_ = decode_length /
1281 static_cast<int>(decoder->channels());
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +00001282 LOG(LS_VERBOSE) << "Decoded " << decode_length << " samples (" <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001283 decoder->channels() << " channel(s) -> " << decoder_frame_length_ <<
1284 " samples per channel)";
1285 } else if (decode_length < 0) {
1286 // Error.
henrik.lundin@webrtc.org63464a92013-01-30 09:41:56 +00001287 LOG_FERR2(LS_WARNING, Decode, decode_length, payload_length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001288 *decoded_length = -1;
1289 PacketBuffer::DeleteAllPackets(packet_list);
1290 break;
1291 }
1292 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1293 // Guard against overflow.
1294 LOG_F(LS_WARNING) << "Decoded too much.";
1295 PacketBuffer::DeleteAllPackets(packet_list);
1296 return kDecodedTooMuch;
1297 }
1298 if (!packet_list->empty()) {
1299 packet = packet_list->front();
1300 } else {
1301 packet = NULL;
1302 }
1303 } // End of decode loop.
1304
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001305 // If the list is not empty at this point, either a decoding error terminated
1306 // the while-loop, or list must hold exactly one CNG packet.
1307 assert(packet_list->empty() || *decoded_length < 0 ||
1308 (packet_list->size() == 1 && packet &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001309 decoder_database_->IsComfortNoise(packet->header.payloadType)));
1310 return 0;
1311}
1312
1313void NetEqImpl::DoNormal(const int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001314 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001315 assert(normal_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001316 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001317 normal_->Process(decoded_buffer, decoded_length, last_mode_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001318 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001319 if (decoded_length != 0) {
1320 last_mode_ = kModeNormal;
1321 }
1322
1323 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1324 if ((speech_type == AudioDecoder::kComfortNoise)
1325 || ((last_mode_ == kModeCodecInternalCng)
1326 && (decoded_length == 0))) {
1327 // TODO(hlundin): Remove second part of || statement above.
1328 last_mode_ = kModeCodecInternalCng;
1329 }
1330
1331 if (!play_dtmf) {
1332 dtmf_tone_generator_->Reset();
1333 }
1334}
1335
1336void NetEqImpl::DoMerge(int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001337 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001338 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001339 assert(merge_.get());
1340 int new_length = merge_->Process(decoded_buffer, decoded_length,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001341 mute_factor_array_.get(),
1342 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001343
1344 // Update in-call and post-call statistics.
1345 if (expand_->MuteFactor(0) == 0) {
1346 // Expand generates only noise.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001347 stats_.ExpandedNoiseSamples(new_length - static_cast<int>(decoded_length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001348 } else {
1349 // Expansion generates more than only noise.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001350 stats_.ExpandedVoiceSamples(new_length - static_cast<int>(decoded_length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001351 }
1352
1353 last_mode_ = kModeMerge;
1354 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1355 if (speech_type == AudioDecoder::kComfortNoise) {
1356 last_mode_ = kModeCodecInternalCng;
1357 }
1358 expand_->Reset();
1359 if (!play_dtmf) {
1360 dtmf_tone_generator_->Reset();
1361 }
1362}
1363
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001364int NetEqImpl::DoExpand(bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001365 while ((sync_buffer_->FutureLength() - expand_->overlap_length()) <
1366 static_cast<size_t>(output_size_samples_)) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001367 algorithm_buffer_->Clear();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001368 int return_value = expand_->Process(algorithm_buffer_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001369 int length = static_cast<int>(algorithm_buffer_->Size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001370
1371 // Update in-call and post-call statistics.
1372 if (expand_->MuteFactor(0) == 0) {
1373 // Expand operation generates only noise.
1374 stats_.ExpandedNoiseSamples(length);
1375 } else {
1376 // Expand operation generates more than only noise.
1377 stats_.ExpandedVoiceSamples(length);
1378 }
1379
1380 last_mode_ = kModeExpand;
1381
1382 if (return_value < 0) {
1383 return return_value;
1384 }
1385
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001386 sync_buffer_->PushBack(*algorithm_buffer_);
1387 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001388 }
1389 if (!play_dtmf) {
1390 dtmf_tone_generator_->Reset();
1391 }
1392 return 0;
1393}
1394
1395int NetEqImpl::DoAccelerate(int16_t* decoded_buffer, size_t decoded_length,
1396 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001397 bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001398 const size_t required_samples = 240 * fs_mult_; // Must have 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001399 size_t borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001400 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001401 size_t decoded_length_per_channel = decoded_length / num_channels;
1402 if (decoded_length_per_channel < required_samples) {
1403 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001404 borrowed_samples_per_channel = static_cast<int>(required_samples -
1405 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001406 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1407 decoded_buffer,
1408 sizeof(int16_t) * decoded_length);
1409 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1410 decoded_buffer);
1411 decoded_length = required_samples * num_channels;
1412 }
1413
1414 int16_t samples_removed;
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001415 Accelerate::ReturnCodes return_code = accelerate_->Process(
1416 decoded_buffer, decoded_length, algorithm_buffer_.get(),
1417 &samples_removed);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001418 stats_.AcceleratedSamples(samples_removed);
1419 switch (return_code) {
1420 case Accelerate::kSuccess:
1421 last_mode_ = kModeAccelerateSuccess;
1422 break;
1423 case Accelerate::kSuccessLowEnergy:
1424 last_mode_ = kModeAccelerateLowEnergy;
1425 break;
1426 case Accelerate::kNoStretch:
1427 last_mode_ = kModeAccelerateFail;
1428 break;
1429 case Accelerate::kError:
1430 // TODO(hlundin): Map to kModeError instead?
1431 last_mode_ = kModeAccelerateFail;
1432 return kAccelerateError;
1433 }
1434
1435 if (borrowed_samples_per_channel > 0) {
1436 // Copy borrowed samples back to the |sync_buffer_|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001437 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001438 if (length < borrowed_samples_per_channel) {
1439 // This destroys the beginning of the buffer, but will not cause any
1440 // problems.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001441 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001442 sync_buffer_->Size() -
1443 borrowed_samples_per_channel);
1444 sync_buffer_->PushFrontZeros(borrowed_samples_per_channel - length);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001445 algorithm_buffer_->PopFront(length);
1446 assert(algorithm_buffer_->Empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001447 } else {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001448 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001449 borrowed_samples_per_channel,
1450 sync_buffer_->Size() -
1451 borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001452 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001453 }
1454 }
1455
1456 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1457 if (speech_type == AudioDecoder::kComfortNoise) {
1458 last_mode_ = kModeCodecInternalCng;
1459 }
1460 if (!play_dtmf) {
1461 dtmf_tone_generator_->Reset();
1462 }
1463 expand_->Reset();
1464 return 0;
1465}
1466
1467int NetEqImpl::DoPreemptiveExpand(int16_t* decoded_buffer,
1468 size_t decoded_length,
1469 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001470 bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001471 const size_t required_samples = 240 * fs_mult_; // Must have 30 ms.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001472 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001473 int borrowed_samples_per_channel = 0;
1474 int old_borrowed_samples_per_channel = 0;
1475 size_t decoded_length_per_channel = decoded_length / num_channels;
1476 if (decoded_length_per_channel < required_samples) {
1477 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001478 borrowed_samples_per_channel = static_cast<int>(required_samples -
1479 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001480 // Calculate how many of these were already played out.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001481 old_borrowed_samples_per_channel = static_cast<int>(
1482 borrowed_samples_per_channel - sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001483 old_borrowed_samples_per_channel = std::max(
1484 0, old_borrowed_samples_per_channel);
1485 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1486 decoded_buffer,
1487 sizeof(int16_t) * decoded_length);
1488 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1489 decoded_buffer);
1490 decoded_length = required_samples * num_channels;
1491 }
1492
1493 int16_t samples_added;
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001494 PreemptiveExpand::ReturnCodes return_code = preemptive_expand_->Process(
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001495 decoded_buffer, static_cast<int>(decoded_length),
1496 old_borrowed_samples_per_channel,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001497 algorithm_buffer_.get(), &samples_added);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001498 stats_.PreemptiveExpandedSamples(samples_added);
1499 switch (return_code) {
1500 case PreemptiveExpand::kSuccess:
1501 last_mode_ = kModePreemptiveExpandSuccess;
1502 break;
1503 case PreemptiveExpand::kSuccessLowEnergy:
1504 last_mode_ = kModePreemptiveExpandLowEnergy;
1505 break;
1506 case PreemptiveExpand::kNoStretch:
1507 last_mode_ = kModePreemptiveExpandFail;
1508 break;
1509 case PreemptiveExpand::kError:
1510 // TODO(hlundin): Map to kModeError instead?
1511 last_mode_ = kModePreemptiveExpandFail;
1512 return kPreemptiveExpandError;
1513 }
1514
1515 if (borrowed_samples_per_channel > 0) {
1516 // Copy borrowed samples back to the |sync_buffer_|.
1517 sync_buffer_->ReplaceAtIndex(
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001518 *algorithm_buffer_, borrowed_samples_per_channel,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001519 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001520 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001521 }
1522
1523 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1524 if (speech_type == AudioDecoder::kComfortNoise) {
1525 last_mode_ = kModeCodecInternalCng;
1526 }
1527 if (!play_dtmf) {
1528 dtmf_tone_generator_->Reset();
1529 }
1530 expand_->Reset();
1531 return 0;
1532}
1533
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001534int NetEqImpl::DoRfc3389Cng(PacketList* packet_list, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001535 if (!packet_list->empty()) {
1536 // Must have exactly one SID frame at this point.
1537 assert(packet_list->size() == 1);
1538 Packet* packet = packet_list->front();
1539 packet_list->pop_front();
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001540 if (!decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1541#ifdef LEGACY_BITEXACT
1542 // This can happen due to a bug in GetDecision. Change the payload type
1543 // to a CNG type, and move on. Note that this means that we are in fact
1544 // sending a non-CNG payload to the comfort noise decoder for decoding.
1545 // Clearly wrong, but will maintain bit-exactness with legacy.
1546 if (fs_hz_ == 8000) {
1547 packet->header.payloadType =
1548 decoder_database_->GetRtpPayloadType(kDecoderCNGnb);
1549 } else if (fs_hz_ == 16000) {
1550 packet->header.payloadType =
1551 decoder_database_->GetRtpPayloadType(kDecoderCNGwb);
1552 } else if (fs_hz_ == 32000) {
1553 packet->header.payloadType =
1554 decoder_database_->GetRtpPayloadType(kDecoderCNGswb32kHz);
1555 } else if (fs_hz_ == 48000) {
1556 packet->header.payloadType =
1557 decoder_database_->GetRtpPayloadType(kDecoderCNGswb48kHz);
1558 }
1559 assert(decoder_database_->IsComfortNoise(packet->header.payloadType));
1560#else
1561 LOG(LS_ERROR) << "Trying to decode non-CNG payload as CNG.";
1562 return kOtherError;
1563#endif
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001564 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001565 // UpdateParameters() deletes |packet|.
1566 if (comfort_noise_->UpdateParameters(packet) ==
1567 ComfortNoise::kInternalError) {
1568 LOG_FERR0(LS_WARNING, UpdateParameters);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001569 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001570 return -comfort_noise_->internal_error_code();
1571 }
1572 }
1573 int cn_return = comfort_noise_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001574 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001575 expand_->Reset();
1576 last_mode_ = kModeRfc3389Cng;
1577 if (!play_dtmf) {
1578 dtmf_tone_generator_->Reset();
1579 }
1580 if (cn_return == ComfortNoise::kInternalError) {
1581 LOG_FERR1(LS_WARNING, comfort_noise_->Generate, cn_return);
1582 decoder_error_code_ = comfort_noise_->internal_error_code();
1583 return kComfortNoiseErrorCode;
1584 } else if (cn_return == ComfortNoise::kUnknownPayloadType) {
1585 LOG_FERR1(LS_WARNING, comfort_noise_->Generate, cn_return);
1586 return kUnknownRtpPayloadType;
1587 }
1588 return 0;
1589}
1590
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001591void NetEqImpl::DoCodecInternalCng() {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001592 int length = 0;
1593 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1594 int16_t decoded_buffer[kMaxFrameSize];
1595 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1596 if (decoder) {
1597 const uint8_t* dummy_payload = NULL;
1598 AudioDecoder::SpeechType speech_type;
1599 length = decoder->Decode(dummy_payload, 0, decoded_buffer, &speech_type);
1600 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001601 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001602 normal_->Process(decoded_buffer, length, last_mode_, mute_factor_array_.get(),
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001603 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001604 last_mode_ = kModeCodecInternalCng;
1605 expand_->Reset();
1606}
1607
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001608int NetEqImpl::DoDtmf(const DtmfEvent& dtmf_event, bool* play_dtmf) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001609 // This block of the code and the block further down, handling |dtmf_switch|
1610 // are commented out. Otherwise playing out-of-band DTMF would fail in VoE
1611 // test, DtmfTest.ManualSuccessfullySendsOutOfBandTelephoneEvents. This is
1612 // equivalent to |dtmf_switch| always be false.
1613 //
1614 // See http://webrtc-codereview.appspot.com/1195004/ for discussion
1615 // On this issue. This change might cause some glitches at the point of
1616 // switch from audio to DTMF. Issue 1545 is filed to track this.
1617 //
1618 // bool dtmf_switch = false;
1619 // if ((last_mode_ != kModeDtmf) && dtmf_tone_generator_->initialized()) {
1620 // // Special case; see below.
1621 // // We must catch this before calling Generate, since |initialized| is
1622 // // modified in that call.
1623 // dtmf_switch = true;
1624 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001625
1626 int dtmf_return_value = 0;
1627 if (!dtmf_tone_generator_->initialized()) {
1628 // Initialize if not already done.
1629 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1630 dtmf_event.volume);
1631 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001632
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001633 if (dtmf_return_value == 0) {
1634 // Generate DTMF signal.
1635 dtmf_return_value = dtmf_tone_generator_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001636 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001637 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001638
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001639 if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001640 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001641 return dtmf_return_value;
1642 }
1643
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001644 // if (dtmf_switch) {
1645 // // This is the special case where the previous operation was DTMF
1646 // // overdub, but the current instruction is "regular" DTMF. We must make
1647 // // sure that the DTMF does not have any discontinuities. The first DTMF
1648 // // sample that we generate now must be played out immediately, therefore
1649 // // it must be copied to the speech buffer.
1650 // // TODO(hlundin): This code seems incorrect. (Legacy.) Write test and
1651 // // verify correct operation.
1652 // assert(false);
1653 // // Must generate enough data to replace all of the |sync_buffer_|
1654 // // "future".
1655 // int required_length = sync_buffer_->FutureLength();
1656 // assert(dtmf_tone_generator_->initialized());
1657 // dtmf_return_value = dtmf_tone_generator_->Generate(required_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001658 // algorithm_buffer_);
1659 // assert((size_t) required_length == algorithm_buffer_->Size());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001660 // if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001661 // algorithm_buffer_->Zeros(output_size_samples_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001662 // return dtmf_return_value;
1663 // }
1664 //
1665 // // Overwrite the "future" part of the speech buffer with the new DTMF
1666 // // data.
1667 // // TODO(hlundin): It seems that this overwriting has gone lost.
1668 // // Not adapted for multi-channel yet.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001669 // assert(algorithm_buffer_->Channels() == 1);
1670 // if (algorithm_buffer_->Channels() != 1) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001671 // LOG(LS_WARNING) << "DTMF not supported for more than one channel";
1672 // return kStereoNotSupported;
1673 // }
1674 // // Shuffle the remaining data to the beginning of algorithm buffer.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001675 // algorithm_buffer_->PopFront(sync_buffer_->FutureLength());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001676 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001677
1678 sync_buffer_->IncreaseEndTimestamp(output_size_samples_);
1679 expand_->Reset();
1680 last_mode_ = kModeDtmf;
1681
1682 // Set to false because the DTMF is already in the algorithm buffer.
1683 *play_dtmf = false;
1684 return 0;
1685}
1686
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001687void NetEqImpl::DoAlternativePlc(bool increase_timestamp) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001688 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1689 int length;
1690 if (decoder && decoder->HasDecodePlc()) {
1691 // Use the decoder's packet-loss concealment.
1692 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1693 int16_t decoded_buffer[kMaxFrameSize];
1694 length = decoder->DecodePlc(1, decoded_buffer);
1695 if (length > 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001696 algorithm_buffer_->PushBackInterleaved(decoded_buffer, length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001697 } else {
1698 length = 0;
1699 }
1700 } else {
1701 // Do simple zero-stuffing.
1702 length = output_size_samples_;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001703 algorithm_buffer_->Zeros(length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001704 // By not advancing the timestamp, NetEq inserts samples.
1705 stats_.AddZeros(length);
1706 }
1707 if (increase_timestamp) {
1708 sync_buffer_->IncreaseEndTimestamp(length);
1709 }
1710 expand_->Reset();
1711}
1712
1713int NetEqImpl::DtmfOverdub(const DtmfEvent& dtmf_event, size_t num_channels,
1714 int16_t* output) const {
1715 size_t out_index = 0;
1716 int overdub_length = output_size_samples_; // Default value.
1717
1718 if (sync_buffer_->dtmf_index() > sync_buffer_->next_index()) {
1719 // Special operation for transition from "DTMF only" to "DTMF overdub".
1720 out_index = std::min(
1721 sync_buffer_->dtmf_index() - sync_buffer_->next_index(),
1722 static_cast<size_t>(output_size_samples_));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001723 overdub_length = output_size_samples_ - static_cast<int>(out_index);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001724 }
1725
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001726 AudioMultiVector dtmf_output(num_channels);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001727 int dtmf_return_value = 0;
1728 if (!dtmf_tone_generator_->initialized()) {
1729 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1730 dtmf_event.volume);
1731 }
1732 if (dtmf_return_value == 0) {
1733 dtmf_return_value = dtmf_tone_generator_->Generate(overdub_length,
1734 &dtmf_output);
1735 assert((size_t) overdub_length == dtmf_output.Size());
1736 }
1737 dtmf_output.ReadInterleaved(overdub_length, &output[out_index]);
1738 return dtmf_return_value < 0 ? dtmf_return_value : 0;
1739}
1740
1741int NetEqImpl::ExtractPackets(int required_samples, PacketList* packet_list) {
1742 bool first_packet = true;
1743 uint8_t prev_payload_type = 0;
1744 uint32_t prev_timestamp = 0;
1745 uint16_t prev_sequence_number = 0;
1746 bool next_packet_available = false;
1747
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001748 const RTPHeader* header = packet_buffer_->NextRtpHeader();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001749 assert(header);
1750 if (!header) {
1751 return -1;
1752 }
turaj@webrtc.org7df97062013-08-02 18:07:13 +00001753 uint32_t first_timestamp = header->timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001754 int extracted_samples = 0;
1755
1756 // Packet extraction loop.
1757 do {
1758 timestamp_ = header->timestamp;
1759 int discard_count = 0;
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001760 Packet* packet = packet_buffer_->GetNextPacket(&discard_count);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001761 // |header| may be invalid after the |packet_buffer_| operation.
1762 header = NULL;
1763 if (!packet) {
1764 LOG_FERR1(LS_ERROR, GetNextPacket, discard_count) <<
1765 "Should always be able to extract a packet here";
1766 assert(false); // Should always be able to extract a packet here.
1767 return -1;
1768 }
1769 stats_.PacketsDiscarded(discard_count);
1770 // Store waiting time in ms; packets->waiting_time is in "output blocks".
1771 stats_.StoreWaitingTime(packet->waiting_time * kOutputSizeMs);
1772 assert(packet->payload_length > 0);
1773 packet_list->push_back(packet); // Store packet in list.
1774
1775 if (first_packet) {
1776 first_packet = false;
minyue@webrtc.orgd7301772013-08-29 00:58:14 +00001777 decoded_packet_sequence_number_ = prev_sequence_number =
1778 packet->header.sequenceNumber;
1779 decoded_packet_timestamp_ = prev_timestamp = packet->header.timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001780 prev_payload_type = packet->header.payloadType;
1781 }
1782
1783 // Store number of extracted samples.
1784 int packet_duration = 0;
1785 AudioDecoder* decoder = decoder_database_->GetDecoder(
1786 packet->header.payloadType);
1787 if (decoder) {
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001788 if (packet->sync_packet) {
1789 packet_duration = decoder_frame_length_;
1790 } else {
1791 packet_duration = packet->primary ?
1792 decoder->PacketDuration(packet->payload, packet->payload_length) :
1793 decoder->PacketDurationRedundant(packet->payload,
1794 packet->payload_length);
1795 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001796 } else {
1797 LOG_FERR1(LS_WARNING, GetDecoder, packet->header.payloadType) <<
1798 "Could not find a decoder for a packet about to be extracted.";
1799 assert(false);
1800 }
1801 if (packet_duration <= 0) {
1802 // Decoder did not return a packet duration. Assume that the packet
1803 // contains the same number of samples as the previous one.
1804 packet_duration = decoder_frame_length_;
1805 }
1806 extracted_samples = packet->header.timestamp - first_timestamp +
1807 packet_duration;
1808
1809 // Check what packet is available next.
1810 header = packet_buffer_->NextRtpHeader();
1811 next_packet_available = false;
1812 if (header && prev_payload_type == header->payloadType) {
1813 int16_t seq_no_diff = header->sequenceNumber - prev_sequence_number;
1814 int32_t ts_diff = header->timestamp - prev_timestamp;
1815 if (seq_no_diff == 1 ||
1816 (seq_no_diff == 0 && ts_diff == decoder_frame_length_)) {
1817 // The next sequence number is available, or the next part of a packet
1818 // that was split into pieces upon insertion.
1819 next_packet_available = true;
1820 }
1821 prev_sequence_number = header->sequenceNumber;
1822 }
1823 } while (extracted_samples < required_samples && next_packet_available);
1824
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00001825 if (extracted_samples > 0) {
1826 // Delete old packets only when we are going to decode something. Otherwise,
1827 // we could end up in the situation where we never decode anything, since
1828 // all incoming packets are considered too old but the buffer will also
1829 // never be flooded and flushed.
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001830 packet_buffer_->DiscardAllOldPackets(timestamp_);
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00001831 }
1832
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001833 return extracted_samples;
1834}
1835
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001836void NetEqImpl::UpdatePlcComponents(int fs_hz, size_t channels) {
1837 // Delete objects and create new ones.
1838 expand_.reset(expand_factory_->Create(background_noise_.get(),
1839 sync_buffer_.get(), &random_vector_,
1840 fs_hz, channels));
1841 merge_.reset(new Merge(fs_hz, channels, expand_.get(), sync_buffer_.get()));
1842}
1843
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001844void NetEqImpl::SetSampleRateAndChannels(int fs_hz, size_t channels) {
1845 LOG_API2(fs_hz, channels);
1846 // TODO(hlundin): Change to an enumerator and skip assert.
1847 assert(fs_hz == 8000 || fs_hz == 16000 || fs_hz == 32000 || fs_hz == 48000);
1848 assert(channels > 0);
1849
1850 fs_hz_ = fs_hz;
1851 fs_mult_ = fs_hz / 8000;
1852 output_size_samples_ = kOutputSizeMs * 8 * fs_mult_;
1853 decoder_frame_length_ = 3 * output_size_samples_; // Initialize to 30ms.
1854
1855 last_mode_ = kModeNormal;
1856
1857 // Create a new array of mute factors and set all to 1.
1858 mute_factor_array_.reset(new int16_t[channels]);
1859 for (size_t i = 0; i < channels; ++i) {
1860 mute_factor_array_[i] = 16384; // 1.0 in Q14.
1861 }
1862
1863 // Reset comfort noise decoder, if there is one active.
1864 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
1865 if (cng_decoder) {
1866 cng_decoder->Init();
1867 }
1868
1869 // Reinit post-decode VAD with new sample rate.
1870 assert(vad_.get()); // Cannot be NULL here.
1871 vad_->Init();
1872
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001873 // Delete algorithm buffer and create a new one.
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001874 algorithm_buffer_.reset(new AudioMultiVector(channels));
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001875
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001876 // Delete sync buffer and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001877 sync_buffer_.reset(new SyncBuffer(channels, kSyncBufferSize * fs_mult_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001878
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00001879 // Delete BackgroundNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001880 background_noise_.reset(new BackgroundNoise(channels));
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00001881 background_noise_->set_mode(background_noise_mode_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001882
1883 // Reset random vector.
1884 random_vector_.Reset();
1885
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001886 UpdatePlcComponents(fs_hz, channels);
1887
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001888 // Move index so that we create a small set of future samples (all 0).
1889 sync_buffer_->set_next_index(sync_buffer_->next_index() -
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001890 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001891
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001892 normal_.reset(new Normal(fs_hz, decoder_database_.get(), *background_noise_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001893 expand_.get()));
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +00001894 accelerate_.reset(
1895 accelerate_factory_->Create(fs_hz, channels, *background_noise_));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001896 preemptive_expand_.reset(preemptive_expand_factory_->Create(
1897 fs_hz, channels,
1898 *background_noise_,
1899 static_cast<int>(expand_->overlap_length())));
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001900
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001901 // Delete ComfortNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001902 comfort_noise_.reset(new ComfortNoise(fs_hz, decoder_database_.get(),
1903 sync_buffer_.get()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001904
1905 // Verify that |decoded_buffer_| is long enough.
1906 if (decoded_buffer_length_ < kMaxFrameSize * channels) {
1907 // Reallocate to larger size.
1908 decoded_buffer_length_ = kMaxFrameSize * channels;
1909 decoded_buffer_.reset(new int16_t[decoded_buffer_length_]);
1910 }
1911
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001912 // Create DecisionLogic if it is not created yet, then communicate new sample
1913 // rate and output size to DecisionLogic object.
1914 if (!decision_logic_.get()) {
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00001915 CreateDecisionLogic();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001916 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001917 decision_logic_->SetSampleRate(fs_hz_, output_size_samples_);
1918}
1919
1920NetEqOutputType NetEqImpl::LastOutputType() {
1921 assert(vad_.get());
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001922 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001923 if (last_mode_ == kModeCodecInternalCng || last_mode_ == kModeRfc3389Cng) {
1924 return kOutputCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001925 } else if (last_mode_ == kModeExpand && expand_->MuteFactor(0) == 0) {
1926 // Expand mode has faded down to background noise only (very long expand).
1927 return kOutputPLCtoCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001928 } else if (last_mode_ == kModeExpand) {
1929 return kOutputPLC;
wu@webrtc.org24301a62013-12-13 19:17:43 +00001930 } else if (vad_->running() && !vad_->active_speech()) {
1931 return kOutputVADPassive;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001932 } else {
1933 return kOutputNormal;
1934 }
1935}
1936
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00001937void NetEqImpl::CreateDecisionLogic() {
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001938 decision_logic_.reset(DecisionLogic::Create(fs_hz_, output_size_samples_,
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00001939 playout_mode_,
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001940 decoder_database_.get(),
1941 *packet_buffer_.get(),
1942 delay_manager_.get(),
1943 buffer_level_filter_.get()));
1944}
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001945} // namespace webrtc