blob: 92ce41e2eaf404c88f8bd455da92395d12a817c3 [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
henrik.lundin9c3efd02015-08-27 13:12:22 -070018#include "webrtc/base/checks.h"
Henrik Lundind67a2192015-08-03 12:54:37 +020019#include "webrtc/base/logging.h"
Peter Kastingdce40cf2015-08-24 14:52:23 -070020#include "webrtc/base/safe_conversions.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000021#include "webrtc/common_audio/signal_processing/include/signal_processing_library.h"
kwiberg@webrtc.orge04a93b2014-12-09 10:12:53 +000022#include "webrtc/modules/audio_coding/codecs/audio_decoder.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000023#include "webrtc/modules/audio_coding/neteq/accelerate.h"
24#include "webrtc/modules/audio_coding/neteq/background_noise.h"
25#include "webrtc/modules/audio_coding/neteq/buffer_level_filter.h"
26#include "webrtc/modules/audio_coding/neteq/comfort_noise.h"
27#include "webrtc/modules/audio_coding/neteq/decision_logic.h"
28#include "webrtc/modules/audio_coding/neteq/decoder_database.h"
29#include "webrtc/modules/audio_coding/neteq/defines.h"
30#include "webrtc/modules/audio_coding/neteq/delay_manager.h"
31#include "webrtc/modules/audio_coding/neteq/delay_peak_detector.h"
32#include "webrtc/modules/audio_coding/neteq/dtmf_buffer.h"
33#include "webrtc/modules/audio_coding/neteq/dtmf_tone_generator.h"
34#include "webrtc/modules/audio_coding/neteq/expand.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000035#include "webrtc/modules/audio_coding/neteq/merge.h"
henrik.lundin48ed9302015-10-29 05:36:24 -070036#include "webrtc/modules/audio_coding/neteq/nack.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000037#include "webrtc/modules/audio_coding/neteq/normal.h"
38#include "webrtc/modules/audio_coding/neteq/packet_buffer.h"
39#include "webrtc/modules/audio_coding/neteq/packet.h"
40#include "webrtc/modules/audio_coding/neteq/payload_splitter.h"
41#include "webrtc/modules/audio_coding/neteq/post_decode_vad.h"
42#include "webrtc/modules/audio_coding/neteq/preemptive_expand.h"
43#include "webrtc/modules/audio_coding/neteq/sync_buffer.h"
44#include "webrtc/modules/audio_coding/neteq/timestamp_scaler.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000045#include "webrtc/modules/interface/module_common_types.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010046#include "webrtc/system_wrappers/include/critical_section_wrapper.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000047
48// Modify the code to obtain backwards bit-exactness. Once bit-exactness is no
49// longer required, this #define should be removed (and the code that it
50// enables).
51#define LEGACY_BITEXACT
52
53namespace webrtc {
54
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +000055NetEqImpl::NetEqImpl(const NetEq::Config& config,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000056 BufferLevelFilter* buffer_level_filter,
57 DecoderDatabase* decoder_database,
58 DelayManager* delay_manager,
59 DelayPeakDetector* delay_peak_detector,
60 DtmfBuffer* dtmf_buffer,
61 DtmfToneGenerator* dtmf_tone_generator,
62 PacketBuffer* packet_buffer,
63 PayloadSplitter* payload_splitter,
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +000064 TimestampScaler* timestamp_scaler,
65 AccelerateFactory* accelerate_factory,
66 ExpandFactory* expand_factory,
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +000067 PreemptiveExpandFactory* preemptive_expand_factory,
68 bool create_components)
henrik.lundin@webrtc.org2f816bb2014-06-05 10:37:13 +000069 : crit_sect_(CriticalSectionWrapper::CreateCriticalSection()),
70 buffer_level_filter_(buffer_level_filter),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000071 decoder_database_(decoder_database),
72 delay_manager_(delay_manager),
73 delay_peak_detector_(delay_peak_detector),
74 dtmf_buffer_(dtmf_buffer),
75 dtmf_tone_generator_(dtmf_tone_generator),
76 packet_buffer_(packet_buffer),
77 payload_splitter_(payload_splitter),
78 timestamp_scaler_(timestamp_scaler),
79 vad_(new PostDecodeVad()),
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +000080 expand_factory_(expand_factory),
81 accelerate_factory_(accelerate_factory),
82 preemptive_expand_factory_(preemptive_expand_factory),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000083 last_mode_(kModeNormal),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000084 decoded_buffer_length_(kMaxFrameSize),
85 decoded_buffer_(new int16_t[decoded_buffer_length_]),
86 playout_timestamp_(0),
87 new_codec_(false),
88 timestamp_(0),
89 reset_decoder_(false),
henrik.lundin48ed9302015-10-29 05:36:24 -070090 current_rtp_payload_type_(0xFF), // Invalid RTP payload type.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000091 current_cng_rtp_payload_type_(0xFF), // Invalid RTP payload type.
92 ssrc_(0),
93 first_packet_(true),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000094 error_code_(0),
95 decoder_error_code_(0),
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +000096 background_noise_mode_(config.background_noise_mode),
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +000097 playout_mode_(config.playout_mode),
Henrik Lundincf808d22015-05-27 14:33:29 +020098 enable_fast_accelerate_(config.enable_fast_accelerate),
henrik.lundin48ed9302015-10-29 05:36:24 -070099 nack_enabled_(false) {
Henrik Lundin905495c2015-05-25 16:58:41 +0200100 LOG(LS_INFO) << "NetEq config: " << config.ToString();
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +0000101 int fs = config.sample_rate_hz;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000102 if (fs != 8000 && fs != 16000 && fs != 32000 && fs != 48000) {
103 LOG(LS_ERROR) << "Sample rate " << fs << " Hz not supported. " <<
104 "Changing to 8000 Hz.";
105 fs = 8000;
106 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000107 fs_hz_ = fs;
108 fs_mult_ = fs / 8000;
Peter Kastingdce40cf2015-08-24 14:52:23 -0700109 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000110 decoder_frame_length_ = 3 * output_size_samples_;
111 WebRtcSpl_Init();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000112 if (create_components) {
113 SetSampleRateAndChannels(fs, 1); // Default is 1 channel.
114 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000115}
116
Henrik Lundind67a2192015-08-03 12:54:37 +0200117NetEqImpl::~NetEqImpl() = default;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000118
119int NetEqImpl::InsertPacket(const WebRtcRTPHeader& rtp_header,
120 const uint8_t* payload,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000121 size_t length_bytes,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000122 uint32_t receive_timestamp) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000123 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000124 LOG(LS_VERBOSE) << "InsertPacket: ts=" << rtp_header.header.timestamp <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000125 ", sn=" << rtp_header.header.sequenceNumber <<
126 ", pt=" << static_cast<int>(rtp_header.header.payloadType) <<
127 ", ssrc=" << rtp_header.header.ssrc <<
128 ", len=" << length_bytes;
129 int error = InsertPacketInternal(rtp_header, payload, length_bytes,
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000130 receive_timestamp, false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000131 if (error != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000132 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) {
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000152 error_code_ = error;
153 return kFail;
154 }
155 return kOK;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000156}
157
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000158int NetEqImpl::GetAudio(size_t max_length, int16_t* output_audio,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700159 size_t* samples_per_channel, int* num_channels,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000160 NetEqOutputType* type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000161 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000162 LOG(LS_VERBOSE) << "GetAudio";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000163 int error = GetAudioInternal(max_length, output_audio, samples_per_channel,
164 num_channels);
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000165 LOG(LS_VERBOSE) << "Produced " << *samples_per_channel <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000166 " samples/channel for " << *num_channels << " channel(s)";
167 if (error != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000168 error_code_ = error;
169 return kFail;
170 }
171 if (type) {
172 *type = LastOutputType();
173 }
174 return kOK;
175}
176
kwibergee1879c2015-10-29 06:20:28 -0700177int NetEqImpl::RegisterPayloadType(NetEqDecoder codec,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000178 uint8_t rtp_payload_type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000179 CriticalSectionScoped lock(crit_sect_.get());
Henrik Lundind67a2192015-08-03 12:54:37 +0200180 LOG(LS_VERBOSE) << "RegisterPayloadType "
kwibergee1879c2015-10-29 06:20:28 -0700181 << static_cast<int>(rtp_payload_type) << " "
182 << static_cast<int>(codec);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000183 int ret = decoder_database_->RegisterPayload(rtp_payload_type, codec);
184 if (ret != DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000185 switch (ret) {
186 case DecoderDatabase::kInvalidRtpPayloadType:
187 error_code_ = kInvalidRtpPayloadType;
188 break;
189 case DecoderDatabase::kCodecNotSupported:
190 error_code_ = kCodecNotSupported;
191 break;
192 case DecoderDatabase::kDecoderExists:
193 error_code_ = kDecoderExists;
194 break;
195 default:
196 error_code_ = kOtherError;
197 }
198 return kFail;
199 }
200 return kOK;
201}
202
203int NetEqImpl::RegisterExternalDecoder(AudioDecoder* decoder,
kwibergee1879c2015-10-29 06:20:28 -0700204 NetEqDecoder codec,
Karl Wibergd8399e62015-05-25 14:39:56 +0200205 uint8_t rtp_payload_type,
206 int sample_rate_hz) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000207 CriticalSectionScoped lock(crit_sect_.get());
Henrik Lundind67a2192015-08-03 12:54:37 +0200208 LOG(LS_VERBOSE) << "RegisterExternalDecoder "
kwibergee1879c2015-10-29 06:20:28 -0700209 << static_cast<int>(rtp_payload_type) << " "
210 << static_cast<int>(codec);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000211 if (!decoder) {
212 LOG(LS_ERROR) << "Cannot register external decoder with NULL pointer";
213 assert(false);
214 return kFail;
215 }
216 int ret = decoder_database_->InsertExternal(rtp_payload_type, codec,
217 sample_rate_hz, decoder);
218 if (ret != DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000219 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 int ret = decoder_database_->Remove(rtp_payload_type);
246 if (ret == DecoderDatabase::kOK) {
247 return kOK;
248 } else if (ret == DecoderDatabase::kDecoderNotFound) {
249 error_code_ = kDecoderNotFound;
250 } else {
251 error_code_ = kOtherError;
252 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000253 return kFail;
254}
255
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000256bool NetEqImpl::SetMinimumDelay(int delay_ms) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000257 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000258 if (delay_ms >= 0 && delay_ms < 10000) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000259 assert(delay_manager_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000260 return delay_manager_->SetMinimumDelay(delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000261 }
262 return false;
263}
264
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000265bool NetEqImpl::SetMaximumDelay(int delay_ms) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000266 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000267 if (delay_ms >= 0 && delay_ms < 10000) {
268 assert(delay_manager_.get());
269 return delay_manager_->SetMaximumDelay(delay_ms);
270 }
271 return false;
272}
273
274int NetEqImpl::LeastRequiredDelayMs() const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000275 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000276 assert(delay_manager_.get());
277 return delay_manager_->least_required_delay_ms();
278}
279
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200280int NetEqImpl::SetTargetDelay() {
281 return kNotImplemented;
282}
283
284int NetEqImpl::TargetDelay() {
285 return kNotImplemented;
286}
287
henrik.lundin9c3efd02015-08-27 13:12:22 -0700288int NetEqImpl::CurrentDelayMs() const {
289 CriticalSectionScoped lock(crit_sect_.get());
290 if (fs_hz_ == 0)
291 return 0;
292 // Sum up the samples in the packet buffer with the future length of the sync
293 // buffer, and divide the sum by the sample rate.
294 const size_t delay_samples =
295 packet_buffer_->NumSamplesInBuffer(decoder_database_.get(),
296 decoder_frame_length_) +
297 sync_buffer_->FutureLength();
298 // The division below will truncate.
299 const int delay_ms =
300 static_cast<int>(delay_samples) / rtc::CheckedDivExact(fs_hz_, 1000);
301 return delay_ms;
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200302}
303
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000304// Deprecated.
305// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000306void NetEqImpl::SetPlayoutMode(NetEqPlayoutMode mode) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000307 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000308 if (mode != playout_mode_) {
309 playout_mode_ = mode;
310 CreateDecisionLogic();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000311 }
312}
313
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000314// Deprecated.
315// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000316NetEqPlayoutMode NetEqImpl::PlayoutMode() const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000317 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000318 return playout_mode_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000319}
320
321int NetEqImpl::NetworkStatistics(NetEqNetworkStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000322 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000323 assert(decoder_database_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700324 const size_t total_samples_in_buffers =
Peter Kasting728d9032015-06-11 14:31:38 -0700325 packet_buffer_->NumSamplesInBuffer(decoder_database_.get(),
326 decoder_frame_length_) +
Peter Kastingdce40cf2015-08-24 14:52:23 -0700327 sync_buffer_->FutureLength();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000328 assert(delay_manager_.get());
329 assert(decision_logic_.get());
330 stats_.GetNetworkStatistics(fs_hz_, total_samples_in_buffers,
331 decoder_frame_length_, *delay_manager_.get(),
332 *decision_logic_.get(), stats);
333 return 0;
334}
335
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000336void NetEqImpl::GetRtcpStatistics(RtcpStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000337 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000338 if (stats) {
339 rtcp_.GetStatistics(false, stats);
340 }
341}
342
343void NetEqImpl::GetRtcpStatisticsNoReset(RtcpStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000344 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000345 if (stats) {
346 rtcp_.GetStatistics(true, stats);
347 }
348}
349
350void NetEqImpl::EnableVad() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000351 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000352 assert(vad_.get());
353 vad_->Enable();
354}
355
356void NetEqImpl::DisableVad() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000357 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000358 assert(vad_.get());
359 vad_->Disable();
360}
361
wu@webrtc.org94454b72014-06-05 20:34:08 +0000362bool NetEqImpl::GetPlayoutTimestamp(uint32_t* timestamp) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000363 CriticalSectionScoped lock(crit_sect_.get());
wu@webrtc.org94454b72014-06-05 20:34:08 +0000364 if (first_packet_) {
365 // We don't have a valid RTP timestamp until we have decoded our first
366 // RTP packet.
367 return false;
368 }
369 *timestamp = timestamp_scaler_->ToExternal(playout_timestamp_);
370 return true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000371}
372
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200373int NetEqImpl::SetTargetNumberOfChannels() {
374 return kNotImplemented;
375}
376
377int NetEqImpl::SetTargetSampleRate() {
378 return kNotImplemented;
379}
380
henrik.lundin@webrtc.orgb0f4b3d2014-11-04 08:53:10 +0000381int NetEqImpl::LastError() const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000382 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000383 return error_code_;
384}
385
386int NetEqImpl::LastDecoderError() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000387 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000388 return decoder_error_code_;
389}
390
391void NetEqImpl::FlushBuffers() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000392 CriticalSectionScoped lock(crit_sect_.get());
Henrik Lundind67a2192015-08-03 12:54:37 +0200393 LOG(LS_VERBOSE) << "FlushBuffers";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000394 packet_buffer_->Flush();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000395 assert(sync_buffer_.get());
396 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000397 sync_buffer_->Flush();
398 sync_buffer_->set_next_index(sync_buffer_->next_index() -
399 expand_->overlap_length());
400 // Set to wait for new codec.
401 first_packet_ = true;
402}
403
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000404void NetEqImpl::PacketBufferStatistics(int* current_num_packets,
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000405 int* max_num_packets) const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000406 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000407 packet_buffer_->BufferStat(current_num_packets, max_num_packets);
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000408}
409
henrik.lundin48ed9302015-10-29 05:36:24 -0700410void NetEqImpl::EnableNack(size_t max_nack_list_size) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000411 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin48ed9302015-10-29 05:36:24 -0700412 if (!nack_enabled_) {
413 const int kNackThresholdPackets = 2;
414 nack_.reset(Nack::Create(kNackThresholdPackets));
415 nack_enabled_ = true;
416 nack_->UpdateSampleRate(fs_hz_);
417 }
418 nack_->SetMaxNackListSize(max_nack_list_size);
419}
420
421void NetEqImpl::DisableNack() {
422 CriticalSectionScoped lock(crit_sect_.get());
423 nack_.reset();
424 nack_enabled_ = false;
425}
426
427std::vector<uint16_t> NetEqImpl::GetNackList(int64_t round_trip_time_ms) const {
428 CriticalSectionScoped lock(crit_sect_.get());
429 if (!nack_enabled_) {
430 return std::vector<uint16_t>();
431 }
432 RTC_DCHECK(nack_.get());
433 return nack_->GetNackList(round_trip_time_ms);
minyue@webrtc.orgd7301772013-08-29 00:58:14 +0000434}
435
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000436const SyncBuffer* NetEqImpl::sync_buffer_for_test() const {
437 CriticalSectionScoped lock(crit_sect_.get());
438 return sync_buffer_.get();
439}
440
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000441// Methods below this line are private.
442
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000443int NetEqImpl::InsertPacketInternal(const WebRtcRTPHeader& rtp_header,
444 const uint8_t* payload,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000445 size_t length_bytes,
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000446 uint32_t receive_timestamp,
447 bool is_sync_packet) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000448 if (!payload) {
449 LOG_F(LS_ERROR) << "payload == NULL";
450 return kInvalidPointer;
451 }
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000452 // Sanity checks for sync-packets.
453 if (is_sync_packet) {
454 if (decoder_database_->IsDtmf(rtp_header.header.payloadType) ||
455 decoder_database_->IsRed(rtp_header.header.payloadType) ||
456 decoder_database_->IsComfortNoise(rtp_header.header.payloadType)) {
457 LOG_F(LS_ERROR) << "Sync-packet with an unacceptable payload type "
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000458 << static_cast<int>(rtp_header.header.payloadType);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000459 return kSyncPacketNotAccepted;
460 }
461 if (first_packet_ ||
462 rtp_header.header.payloadType != current_rtp_payload_type_ ||
463 rtp_header.header.ssrc != ssrc_) {
464 // Even if |current_rtp_payload_type_| is 0xFF, sync-packet isn't
465 // accepted.
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000466 LOG_F(LS_ERROR)
467 << "Changing codec, SSRC or first packet with sync-packet.";
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000468 return kSyncPacketNotAccepted;
469 }
470 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000471 PacketList packet_list;
472 RTPHeader main_header;
473 {
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000474 // Convert to Packet.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000475 // Create |packet| within this separate scope, since it should not be used
476 // directly once it's been inserted in the packet list. This way, |packet|
477 // is not defined outside of this block.
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000478 Packet* packet = new Packet;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000479 packet->header.markerBit = false;
480 packet->header.payloadType = rtp_header.header.payloadType;
481 packet->header.sequenceNumber = rtp_header.header.sequenceNumber;
482 packet->header.timestamp = rtp_header.header.timestamp;
483 packet->header.ssrc = rtp_header.header.ssrc;
484 packet->header.numCSRCs = 0;
485 packet->payload_length = length_bytes;
486 packet->primary = true;
487 packet->waiting_time = 0;
488 packet->payload = new uint8_t[packet->payload_length];
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000489 packet->sync_packet = is_sync_packet;
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +0000490 if (!packet->payload) {
491 LOG_F(LS_ERROR) << "Payload pointer is NULL.";
492 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000493 assert(payload); // Already checked above.
494 memcpy(packet->payload, payload, packet->payload_length);
495 // Insert packet in a packet list.
496 packet_list.push_back(packet);
497 // Save main payloads header for later.
498 memcpy(&main_header, &packet->header, sizeof(main_header));
499 }
500
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000501 bool update_sample_rate_and_channels = false;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000502 // Reinitialize NetEq if it's needed (changed SSRC or first call).
503 if ((main_header.ssrc != ssrc_) || first_packet_) {
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000504 // Note: |first_packet_| will be cleared further down in this method, once
505 // the packet has been successfully inserted into the packet buffer.
506
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000507 rtcp_.Init(main_header.sequenceNumber);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000508
509 // Flush the packet buffer and DTMF buffer.
510 packet_buffer_->Flush();
511 dtmf_buffer_->Flush();
512
513 // Store new SSRC.
514 ssrc_ = main_header.ssrc;
515
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000516 // Update audio buffer timestamp.
517 sync_buffer_->IncreaseEndTimestamp(main_header.timestamp - timestamp_);
518
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000519 // Update codecs.
520 timestamp_ = main_header.timestamp;
521 current_rtp_payload_type_ = main_header.payloadType;
522
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000523 // Reset timestamp scaling.
524 timestamp_scaler_->Reset();
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000525
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000526 // Trigger an update of sampling rate and the number of channels.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000527 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000528 }
529
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000530 // Update RTCP statistics, only for regular packets.
531 if (!is_sync_packet)
532 rtcp_.Update(main_header, receive_timestamp);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000533
534 // Check for RED payload type, and separate payloads into several packets.
535 if (decoder_database_->IsRed(main_header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000536 assert(!is_sync_packet); // We had a sanity check for this.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000537 if (payload_splitter_->SplitRed(&packet_list) != PayloadSplitter::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000538 PacketBuffer::DeleteAllPackets(&packet_list);
539 return kRedundancySplitError;
540 }
541 // Only accept a few RED payloads of the same type as the main data,
542 // DTMF events and CNG.
543 payload_splitter_->CheckRedPayloads(&packet_list, *decoder_database_);
544 // Update the stored main payload header since the main payload has now
545 // changed.
546 memcpy(&main_header, &packet_list.front()->header, sizeof(main_header));
547 }
548
549 // Check payload types.
550 if (decoder_database_->CheckPayloadTypes(packet_list) ==
551 DecoderDatabase::kDecoderNotFound) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000552 PacketBuffer::DeleteAllPackets(&packet_list);
553 return kUnknownRtpPayloadType;
554 }
555
556 // Scale timestamp to internal domain (only for some codecs).
557 timestamp_scaler_->ToInternal(&packet_list);
558
559 // Process DTMF payloads. Cycle through the list of packets, and pick out any
560 // DTMF payloads found.
561 PacketList::iterator it = packet_list.begin();
562 while (it != packet_list.end()) {
563 Packet* current_packet = (*it);
564 assert(current_packet);
565 assert(current_packet->payload);
566 if (decoder_database_->IsDtmf(current_packet->header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000567 assert(!current_packet->sync_packet); // We had a sanity check for this.
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000568 DtmfEvent event;
569 int ret = DtmfBuffer::ParseEvent(
570 current_packet->header.timestamp,
571 current_packet->payload,
572 current_packet->payload_length,
573 &event);
574 if (ret != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000575 PacketBuffer::DeleteAllPackets(&packet_list);
576 return kDtmfParsingError;
577 }
578 if (dtmf_buffer_->InsertEvent(event) != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000579 PacketBuffer::DeleteAllPackets(&packet_list);
580 return kDtmfInsertError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000581 }
582 // TODO(hlundin): Let the destructor of Packet handle the payload.
583 delete [] current_packet->payload;
584 delete current_packet;
585 it = packet_list.erase(it);
586 } else {
587 ++it;
588 }
589 }
590
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000591 // Check for FEC in packets, and separate payloads into several packets.
592 int ret = payload_splitter_->SplitFec(&packet_list, decoder_database_.get());
593 if (ret != PayloadSplitter::kOK) {
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000594 PacketBuffer::DeleteAllPackets(&packet_list);
595 switch (ret) {
596 case PayloadSplitter::kUnknownPayloadType:
597 return kUnknownRtpPayloadType;
598 default:
599 return kOtherError;
600 }
601 }
602
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000603 // Split payloads into smaller chunks. This also verifies that all payloads
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000604 // are of a known payload type. SplitAudio() method is protected against
605 // sync-packets.
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +0000606 ret = payload_splitter_->SplitAudio(&packet_list, *decoder_database_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000607 if (ret != PayloadSplitter::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000608 PacketBuffer::DeleteAllPackets(&packet_list);
609 switch (ret) {
610 case PayloadSplitter::kUnknownPayloadType:
611 return kUnknownRtpPayloadType;
612 case PayloadSplitter::kFrameSplitError:
613 return kFrameSplitError;
614 default:
615 return kOtherError;
616 }
617 }
618
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000619 // Update bandwidth estimate, if the packet is not sync-packet.
620 if (!packet_list.empty() && !packet_list.front()->sync_packet) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000621 // The list can be empty here if we got nothing but DTMF payloads.
622 AudioDecoder* decoder =
623 decoder_database_->GetDecoder(main_header.payloadType);
624 assert(decoder); // Should always get a valid object, since we have
625 // already checked that the payload types are known.
626 decoder->IncomingPacket(packet_list.front()->payload,
627 packet_list.front()->payload_length,
628 packet_list.front()->header.sequenceNumber,
629 packet_list.front()->header.timestamp,
630 receive_timestamp);
631 }
632
henrik.lundin48ed9302015-10-29 05:36:24 -0700633 if (nack_enabled_) {
634 RTC_DCHECK(nack_);
635 if (update_sample_rate_and_channels) {
636 nack_->Reset();
637 }
638 nack_->UpdateLastReceivedPacket(packet_list.front()->header.sequenceNumber,
639 packet_list.front()->header.timestamp);
640 }
641
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000642 // Insert packets in buffer.
henrik.lundin116c84e2015-08-27 13:14:48 -0700643 const size_t buffer_length_before_insert =
644 packet_buffer_->NumPacketsInBuffer();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000645 ret = packet_buffer_->InsertPacketList(
646 &packet_list,
647 *decoder_database_,
648 &current_rtp_payload_type_,
649 &current_cng_rtp_payload_type_);
650 if (ret == PacketBuffer::kFlushed) {
651 // Reset DSP timestamp etc. if packet buffer flushed.
652 new_codec_ = true;
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000653 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000654 } else if (ret != PacketBuffer::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000655 PacketBuffer::DeleteAllPackets(&packet_list);
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000656 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000657 }
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000658
659 if (first_packet_) {
660 first_packet_ = false;
661 // Update the codec on the next GetAudio call.
662 new_codec_ = true;
663 }
664
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000665 if (current_rtp_payload_type_ != 0xFF) {
666 const DecoderDatabase::DecoderInfo* dec_info =
667 decoder_database_->GetDecoderInfo(current_rtp_payload_type_);
668 if (!dec_info) {
669 assert(false); // Already checked that the payload type is known.
670 }
671 }
672
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000673 if (update_sample_rate_and_channels && !packet_buffer_->Empty()) {
674 // We do not use |current_rtp_payload_type_| to |set payload_type|, but
675 // get the next RTP header from |packet_buffer_| to obtain the payload type.
676 // The reason for it is the following corner case. If NetEq receives a
677 // CNG packet with a sample rate different than the current CNG then it
678 // flushes its buffer, assuming send codec must have been changed. However,
679 // payload type of the hypothetically new send codec is not known.
680 const RTPHeader* rtp_header = packet_buffer_->NextRtpHeader();
681 assert(rtp_header);
682 int payload_type = rtp_header->payloadType;
683 AudioDecoder* decoder = decoder_database_->GetDecoder(payload_type);
684 assert(decoder); // Payloads are already checked to be valid.
685 const DecoderDatabase::DecoderInfo* decoder_info =
686 decoder_database_->GetDecoderInfo(payload_type);
687 assert(decoder_info);
688 if (decoder_info->fs_hz != fs_hz_ ||
henrik.lundin48ed9302015-10-29 05:36:24 -0700689 decoder->Channels() != algorithm_buffer_->Channels()) {
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +0000690 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->Channels());
henrik.lundin48ed9302015-10-29 05:36:24 -0700691 }
692 if (nack_enabled_) {
693 RTC_DCHECK(nack_);
694 // Update the sample rate even if the rate is not new, because of Reset().
695 nack_->UpdateSampleRate(fs_hz_);
696 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000697 }
698
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000699 // TODO(hlundin): Move this code to DelayManager class.
700 const DecoderDatabase::DecoderInfo* dec_info =
701 decoder_database_->GetDecoderInfo(main_header.payloadType);
702 assert(dec_info); // Already checked that the payload type is known.
703 delay_manager_->LastDecoderType(dec_info->codec_type);
704 if (delay_manager_->last_pack_cng_or_dtmf() == 0) {
705 // Calculate the total speech length carried in each packet.
henrik.lundin116c84e2015-08-27 13:14:48 -0700706 const size_t buffer_length_after_insert =
707 packet_buffer_->NumPacketsInBuffer();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000708
henrik.lundin116c84e2015-08-27 13:14:48 -0700709 if (buffer_length_after_insert > buffer_length_before_insert) {
710 const size_t packet_length_samples =
711 (buffer_length_after_insert - buffer_length_before_insert) *
712 decoder_frame_length_;
713 if (packet_length_samples != decision_logic_->packet_length_samples()) {
714 decision_logic_->set_packet_length_samples(packet_length_samples);
715 delay_manager_->SetPacketAudioLength(
716 rtc::checked_cast<int>((1000 * packet_length_samples) / fs_hz_));
717 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000718 }
719
720 // Update statistics.
pbos@webrtc.org0946a562013-04-09 00:28:06 +0000721 if ((int32_t) (main_header.timestamp - timestamp_) >= 0 &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000722 !new_codec_) {
723 // Only update statistics if incoming packet is not older than last played
724 // out packet, and if new codec flag is not set.
725 delay_manager_->Update(main_header.sequenceNumber, main_header.timestamp,
726 fs_hz_);
727 }
728 } else if (delay_manager_->last_pack_cng_or_dtmf() == -1) {
729 // This is first "normal" packet after CNG or DTMF.
730 // Reset packet time counter and measure time until next packet,
731 // but don't update statistics.
732 delay_manager_->set_last_pack_cng_or_dtmf(0);
733 delay_manager_->ResetPacketIatCount();
734 }
735 return 0;
736}
737
Peter Kasting728d9032015-06-11 14:31:38 -0700738int NetEqImpl::GetAudioInternal(size_t max_length,
739 int16_t* output,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700740 size_t* samples_per_channel,
Peter Kasting728d9032015-06-11 14:31:38 -0700741 int* num_channels) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000742 PacketList packet_list;
743 DtmfEvent dtmf_event;
744 Operations operation;
745 bool play_dtmf;
746 int return_value = GetDecision(&operation, &packet_list, &dtmf_event,
747 &play_dtmf);
748 if (return_value != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000749 last_mode_ = kModeError;
750 return return_value;
751 }
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000752 LOG(LS_VERBOSE) << "GetDecision returned operation=" << operation <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000753 " and " << packet_list.size() << " packet(s)";
754
755 AudioDecoder::SpeechType speech_type;
756 int length = 0;
757 int decode_return_value = Decode(&packet_list, &operation,
758 &length, &speech_type);
759
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000760 assert(vad_.get());
761 bool sid_frame_available =
762 (operation == kRfc3389Cng && !packet_list.empty());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700763 vad_->Update(decoded_buffer_.get(), static_cast<size_t>(length), speech_type,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000764 sid_frame_available, fs_hz_);
765
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000766 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000767 switch (operation) {
768 case kNormal: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000769 DoNormal(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000770 break;
771 }
772 case kMerge: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000773 DoMerge(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000774 break;
775 }
776 case kExpand: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000777 return_value = DoExpand(play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000778 break;
779 }
Henrik Lundincf808d22015-05-27 14:33:29 +0200780 case kAccelerate:
781 case kFastAccelerate: {
782 const bool fast_accelerate =
783 enable_fast_accelerate_ && (operation == kFastAccelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000784 return_value = DoAccelerate(decoded_buffer_.get(), length, speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +0200785 play_dtmf, fast_accelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000786 break;
787 }
788 case kPreemptiveExpand: {
789 return_value = DoPreemptiveExpand(decoded_buffer_.get(), length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000790 speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000791 break;
792 }
793 case kRfc3389Cng:
794 case kRfc3389CngNoPacket: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000795 return_value = DoRfc3389Cng(&packet_list, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000796 break;
797 }
798 case kCodecInternalCng: {
799 // This handles the case when there is no transmission and the decoder
800 // should produce internal comfort noise.
801 // TODO(hlundin): Write test for codec-internal CNG.
minyuel6d92bf52015-09-23 15:20:39 +0200802 DoCodecInternalCng(decoded_buffer_.get(), length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000803 break;
804 }
805 case kDtmf: {
806 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000807 return_value = DoDtmf(dtmf_event, &play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000808 break;
809 }
810 case kAlternativePlc: {
811 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000812 DoAlternativePlc(false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000813 break;
814 }
815 case kAlternativePlcIncreaseTimestamp: {
816 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000817 DoAlternativePlc(true);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000818 break;
819 }
820 case kAudioRepetitionIncreaseTimestamp: {
821 // TODO(hlundin): Write test for this.
Peter Kastingb7e50542015-06-11 12:55:50 -0700822 sync_buffer_->IncreaseEndTimestamp(
823 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000824 // Skipping break on purpose. Execution should move on into the
825 // next case.
kjellander@webrtc.org7d2b6a92015-01-28 18:37:58 +0000826 FALLTHROUGH();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000827 }
828 case kAudioRepetition: {
829 // TODO(hlundin): Write test for this.
830 // Copy last |output_size_samples_| from |sync_buffer_| to
831 // |algorithm_buffer|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000832 algorithm_buffer_->PushBackFromIndex(
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000833 *sync_buffer_, sync_buffer_->Size() - output_size_samples_);
834 expand_->Reset();
835 break;
836 }
837 case kUndefined: {
Henrik Lundind67a2192015-08-03 12:54:37 +0200838 LOG(LS_ERROR) << "Invalid operation kUndefined.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000839 assert(false); // This should not happen.
840 last_mode_ = kModeError;
841 return kInvalidOperation;
842 }
843 } // End of switch.
844 if (return_value < 0) {
845 return return_value;
846 }
847
848 if (last_mode_ != kModeRfc3389Cng) {
849 comfort_noise_->Reset();
850 }
851
852 // Copy from |algorithm_buffer| to |sync_buffer_|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000853 sync_buffer_->PushBack(*algorithm_buffer_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000854
855 // Extract data from |sync_buffer_| to |output|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000856 size_t num_output_samples_per_channel = output_size_samples_;
857 size_t num_output_samples = output_size_samples_ * sync_buffer_->Channels();
858 if (num_output_samples > max_length) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000859 LOG(LS_WARNING) << "Output array is too short. " << max_length << " < " <<
860 output_size_samples_ << " * " << sync_buffer_->Channels();
861 num_output_samples = max_length;
Peter Kastingdce40cf2015-08-24 14:52:23 -0700862 num_output_samples_per_channel = max_length / sync_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000863 }
Peter Kastingdce40cf2015-08-24 14:52:23 -0700864 const size_t samples_from_sync =
865 sync_buffer_->GetNextAudioInterleaved(num_output_samples_per_channel,
866 output);
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000867 *num_channels = static_cast<int>(sync_buffer_->Channels());
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000868 LOG(LS_VERBOSE) << "Sync buffer (" << *num_channels << " channel(s)):" <<
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000869 " insert " << algorithm_buffer_->Size() << " samples, extract " <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000870 samples_from_sync << " samples";
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200871 if (sync_buffer_->FutureLength() < expand_->overlap_length()) {
872 // The sync buffer should always contain |overlap_length| samples, but now
873 // too many samples have been extracted. Reinstall the |overlap_length|
874 // lookahead by moving the index.
875 const size_t missing_lookahead_samples =
876 expand_->overlap_length() - sync_buffer_->FutureLength();
henrikg91d6ede2015-09-17 00:24:34 -0700877 RTC_DCHECK_GE(sync_buffer_->next_index(), missing_lookahead_samples);
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200878 sync_buffer_->set_next_index(sync_buffer_->next_index() -
879 missing_lookahead_samples);
880 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000881 if (samples_from_sync != output_size_samples_) {
Henrik Lundind67a2192015-08-03 12:54:37 +0200882 LOG(LS_ERROR) << "samples_from_sync (" << samples_from_sync
883 << ") != output_size_samples_ (" << output_size_samples_
884 << ")";
minyue@webrtc.orgdb1cefc2013-08-13 01:39:21 +0000885 // TODO(minyue): treatment of under-run, filling zeros
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000886 memset(output, 0, num_output_samples * sizeof(int16_t));
887 *samples_per_channel = output_size_samples_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000888 return kSampleUnderrun;
889 }
890 *samples_per_channel = output_size_samples_;
891
892 // Should always have overlap samples left in the |sync_buffer_|.
henrikg91d6ede2015-09-17 00:24:34 -0700893 RTC_DCHECK_GE(sync_buffer_->FutureLength(), expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000894
895 if (play_dtmf) {
896 return_value = DtmfOverdub(dtmf_event, sync_buffer_->Channels(), output);
897 }
898
899 // Update the background noise parameters if last operation wrote data
900 // straight from the decoder to the |sync_buffer_|. That is, none of the
901 // operations that modify the signal can be followed by a parameter update.
902 if ((last_mode_ == kModeNormal) ||
903 (last_mode_ == kModeAccelerateFail) ||
904 (last_mode_ == kModePreemptiveExpandFail) ||
905 (last_mode_ == kModeRfc3389Cng) ||
906 (last_mode_ == kModeCodecInternalCng)) {
907 background_noise_->Update(*sync_buffer_, *vad_.get());
908 }
909
910 if (operation == kDtmf) {
911 // DTMF data was written the end of |sync_buffer_|.
912 // Update index to end of DTMF data in |sync_buffer_|.
913 sync_buffer_->set_dtmf_index(sync_buffer_->Size());
914 }
915
henrik.lundin@webrtc.orged865b52014-03-06 10:28:07 +0000916 if (last_mode_ != kModeExpand) {
917 // If last operation was not expand, calculate the |playout_timestamp_| from
918 // the |sync_buffer_|. However, do not update the |playout_timestamp_| if it
919 // would be moved "backwards".
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000920 uint32_t temp_timestamp = sync_buffer_->end_timestamp() -
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000921 static_cast<uint32_t>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000922 if (static_cast<int32_t>(temp_timestamp - playout_timestamp_) > 0) {
923 playout_timestamp_ = temp_timestamp;
924 }
925 } else {
926 // Use dead reckoning to estimate the |playout_timestamp_|.
Peter Kastingb7e50542015-06-11 12:55:50 -0700927 playout_timestamp_ += static_cast<uint32_t>(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000928 }
929
930 if (decode_return_value) return decode_return_value;
931 return return_value;
932}
933
934int NetEqImpl::GetDecision(Operations* operation,
935 PacketList* packet_list,
936 DtmfEvent* dtmf_event,
937 bool* play_dtmf) {
938 // Initialize output variables.
939 *play_dtmf = false;
940 *operation = kUndefined;
941
942 // Increment time counters.
943 packet_buffer_->IncrementWaitingTimes();
944 stats_.IncreaseCounter(output_size_samples_, fs_hz_);
945
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000946 assert(sync_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000947 uint32_t end_timestamp = sync_buffer_->end_timestamp();
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +0000948 if (!new_codec_) {
949 const uint32_t five_seconds_samples = 5 * fs_hz_;
950 packet_buffer_->DiscardOldPackets(end_timestamp, five_seconds_samples);
951 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000952 const RTPHeader* header = packet_buffer_->NextRtpHeader();
953
henrik.lundin@webrtc.orgca8cb952014-03-12 10:26:52 +0000954 if (decision_logic_->CngRfc3389On() || last_mode_ == kModeRfc3389Cng) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000955 // Because of timestamp peculiarities, we have to "manually" disallow using
956 // a CNG packet with the same timestamp as the one that was last played.
957 // This can happen when using redundancy and will cause the timing to shift.
henrik.lundin@webrtc.org24779fe2014-03-14 12:40:05 +0000958 while (header && decoder_database_->IsComfortNoise(header->payloadType) &&
959 (end_timestamp >= header->timestamp ||
960 end_timestamp + decision_logic_->generated_noise_samples() >
961 header->timestamp)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000962 // Don't use this packet, discard it.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000963 if (packet_buffer_->DiscardNextPacket() != PacketBuffer::kOK) {
964 assert(false); // Must be ok by design.
965 }
966 // Check buffer again.
967 if (!new_codec_) {
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +0000968 packet_buffer_->DiscardOldPackets(end_timestamp, 5 * fs_hz_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000969 }
970 header = packet_buffer_->NextRtpHeader();
971 }
972 }
973
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000974 assert(expand_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000975 const int samples_left = static_cast<int>(sync_buffer_->FutureLength() -
976 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000977 if (last_mode_ == kModeAccelerateSuccess ||
978 last_mode_ == kModeAccelerateLowEnergy ||
979 last_mode_ == kModePreemptiveExpandSuccess ||
980 last_mode_ == kModePreemptiveExpandLowEnergy) {
981 // Subtract (samples_left + output_size_samples_) from sampleMemory.
Peter Kastingdce40cf2015-08-24 14:52:23 -0700982 decision_logic_->AddSampleMemory(
983 -(samples_left + rtc::checked_cast<int>(output_size_samples_)));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000984 }
985
986 // Check if it is time to play a DTMF event.
Peter Kastingb7e50542015-06-11 12:55:50 -0700987 if (dtmf_buffer_->GetEvent(
988 static_cast<uint32_t>(
989 end_timestamp + decision_logic_->generated_noise_samples()),
990 dtmf_event)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000991 *play_dtmf = true;
992 }
993
994 // Get instruction.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000995 assert(sync_buffer_.get());
996 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000997 *operation = decision_logic_->GetDecision(*sync_buffer_,
998 *expand_,
999 decoder_frame_length_,
1000 header,
1001 last_mode_,
1002 *play_dtmf,
1003 &reset_decoder_);
1004
1005 // Check if we already have enough samples in the |sync_buffer_|. If so,
1006 // change decision to normal, unless the decision was merge, accelerate, or
1007 // preemptive expand.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001008 if (samples_left >= rtc::checked_cast<int>(output_size_samples_) &&
1009 *operation != kMerge &&
1010 *operation != kAccelerate &&
1011 *operation != kFastAccelerate &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001012 *operation != kPreemptiveExpand) {
1013 *operation = kNormal;
1014 return 0;
1015 }
1016
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001017 decision_logic_->ExpandDecision(*operation);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001018
1019 // Check conditions for reset.
1020 if (new_codec_ || *operation == kUndefined) {
1021 // The only valid reason to get kUndefined is that new_codec_ is set.
1022 assert(new_codec_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001023 if (*play_dtmf && !header) {
1024 timestamp_ = dtmf_event->timestamp;
1025 } else {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001026 if (!header) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001027 LOG(LS_ERROR) << "Packet missing where it shouldn't.";
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001028 return -1;
1029 }
1030 timestamp_ = header->timestamp;
1031 if (*operation == kRfc3389CngNoPacket
1032#ifndef LEGACY_BITEXACT
1033 // Without this check, it can happen that a non-CNG packet is sent to
1034 // the CNG decoder as if it was a SID frame. This is clearly a bug,
1035 // but is kept for now to maintain bit-exactness with the test
1036 // vectors.
1037 && decoder_database_->IsComfortNoise(header->payloadType)
1038#endif
1039 ) {
1040 // Change decision to CNG packet, since we do have a CNG packet, but it
1041 // was considered too early to use. Now, use it anyway.
1042 *operation = kRfc3389Cng;
1043 } else if (*operation != kRfc3389Cng) {
1044 *operation = kNormal;
1045 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001046 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001047 // Adjust |sync_buffer_| timestamp before setting |end_timestamp| to the
1048 // new value.
1049 sync_buffer_->IncreaseEndTimestamp(timestamp_ - end_timestamp);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001050 end_timestamp = timestamp_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001051 new_codec_ = false;
1052 decision_logic_->SoftReset();
1053 buffer_level_filter_->Reset();
1054 delay_manager_->Reset();
1055 stats_.ResetMcu();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001056 }
1057
Peter Kastingdce40cf2015-08-24 14:52:23 -07001058 size_t required_samples = output_size_samples_;
1059 const size_t samples_10_ms = static_cast<size_t>(80 * fs_mult_);
1060 const size_t samples_20_ms = 2 * samples_10_ms;
1061 const size_t samples_30_ms = 3 * samples_10_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001062
1063 switch (*operation) {
1064 case kExpand: {
1065 timestamp_ = end_timestamp;
1066 return 0;
1067 }
1068 case kRfc3389CngNoPacket:
1069 case kCodecInternalCng: {
1070 return 0;
1071 }
1072 case kDtmf: {
1073 // TODO(hlundin): Write test for this.
1074 // Update timestamp.
1075 timestamp_ = end_timestamp;
1076 if (decision_logic_->generated_noise_samples() > 0 &&
1077 last_mode_ != kModeDtmf) {
1078 // Make a jump in timestamp due to the recently played comfort noise.
Peter Kastingb7e50542015-06-11 12:55:50 -07001079 uint32_t timestamp_jump =
1080 static_cast<uint32_t>(decision_logic_->generated_noise_samples());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001081 sync_buffer_->IncreaseEndTimestamp(timestamp_jump);
1082 timestamp_ += timestamp_jump;
1083 }
1084 decision_logic_->set_generated_noise_samples(0);
1085 return 0;
1086 }
Henrik Lundincf808d22015-05-27 14:33:29 +02001087 case kAccelerate:
1088 case kFastAccelerate: {
1089 // In order to do an accelerate we need at least 30 ms of audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001090 if (samples_left >= static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001091 // Already have enough data, so we do not need to extract any more.
1092 decision_logic_->set_sample_memory(samples_left);
1093 decision_logic_->set_prev_time_scale(true);
1094 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001095 } else if (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001096 decoder_frame_length_ >= samples_30_ms) {
1097 // Avoid decoding more data as it might overflow the playout buffer.
1098 *operation = kNormal;
1099 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001100 } else if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001101 decoder_frame_length_ < samples_30_ms) {
1102 // Build up decoded data by decoding at least 20 ms of audio data. Do
1103 // not perform accelerate yet, but wait until we only need to do one
1104 // decoding.
1105 required_samples = 2 * output_size_samples_;
1106 *operation = kNormal;
1107 }
1108 // If none of the above is true, we have one of two possible situations:
1109 // (1) 20 ms <= samples_left < 30 ms and decoder_frame_length_ < 30 ms; or
1110 // (2) samples_left < 10 ms and decoder_frame_length_ >= 30 ms.
1111 // In either case, we move on with the accelerate decision, and decode one
1112 // frame now.
1113 break;
1114 }
1115 case kPreemptiveExpand: {
1116 // In order to do a preemptive expand we need at least 30 ms of decoded
1117 // audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001118 if ((samples_left >= static_cast<int>(samples_30_ms)) ||
1119 (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001120 decoder_frame_length_ >= samples_30_ms)) {
1121 // Already have enough data, so we do not need to extract any more.
1122 // Or, avoid decoding more data as it might overflow the playout buffer.
1123 // Still try preemptive expand, though.
1124 decision_logic_->set_sample_memory(samples_left);
1125 decision_logic_->set_prev_time_scale(true);
1126 return 0;
1127 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07001128 if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001129 decoder_frame_length_ < samples_30_ms) {
1130 // Build up decoded data by decoding at least 20 ms of audio data.
1131 // Still try to perform preemptive expand.
1132 required_samples = 2 * output_size_samples_;
1133 }
1134 // Move on with the preemptive expand decision.
1135 break;
1136 }
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001137 case kMerge: {
1138 required_samples =
1139 std::max(merge_->RequiredFutureSamples(), required_samples);
1140 break;
1141 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001142 default: {
1143 // Do nothing.
1144 }
1145 }
1146
1147 // Get packets from buffer.
1148 int extracted_samples = 0;
1149 if (header &&
1150 *operation != kAlternativePlc &&
1151 *operation != kAlternativePlcIncreaseTimestamp &&
1152 *operation != kAudioRepetition &&
1153 *operation != kAudioRepetitionIncreaseTimestamp) {
1154 sync_buffer_->IncreaseEndTimestamp(header->timestamp - end_timestamp);
1155 if (decision_logic_->CngOff()) {
1156 // Adjustment of timestamp only corresponds to an actual packet loss
1157 // if comfort noise is not played. If comfort noise was just played,
1158 // this adjustment of timestamp is only done to get back in sync with the
1159 // stream timestamp; no loss to report.
1160 stats_.LostSamples(header->timestamp - end_timestamp);
1161 }
1162
1163 if (*operation != kRfc3389Cng) {
1164 // We are about to decode and use a non-CNG packet.
1165 decision_logic_->SetCngOff();
1166 }
1167 // Reset CNG timestamp as a new packet will be delivered.
1168 // (Also if this is a CNG packet, since playedOutTS is updated.)
1169 decision_logic_->set_generated_noise_samples(0);
1170
1171 extracted_samples = ExtractPackets(required_samples, packet_list);
1172 if (extracted_samples < 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001173 return kPacketBufferCorruption;
1174 }
1175 }
1176
Henrik Lundincf808d22015-05-27 14:33:29 +02001177 if (*operation == kAccelerate || *operation == kFastAccelerate ||
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001178 *operation == kPreemptiveExpand) {
1179 decision_logic_->set_sample_memory(samples_left + extracted_samples);
1180 decision_logic_->set_prev_time_scale(true);
1181 }
1182
Henrik Lundincf808d22015-05-27 14:33:29 +02001183 if (*operation == kAccelerate || *operation == kFastAccelerate) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001184 // Check that we have enough data (30ms) to do accelerate.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001185 if (extracted_samples + samples_left < static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001186 // TODO(hlundin): Write test for this.
1187 // Not enough, do normal operation instead.
1188 *operation = kNormal;
1189 }
1190 }
1191
1192 timestamp_ = end_timestamp;
1193 return 0;
1194}
1195
1196int NetEqImpl::Decode(PacketList* packet_list, Operations* operation,
1197 int* decoded_length,
1198 AudioDecoder::SpeechType* speech_type) {
1199 *speech_type = AudioDecoder::kSpeech;
minyuel6d92bf52015-09-23 15:20:39 +02001200
1201 // When packet_list is empty, we may be in kCodecInternalCng mode, and for
1202 // that we use current active decoder.
1203 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1204
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001205 if (!packet_list->empty()) {
1206 const Packet* packet = packet_list->front();
pkasting@chromium.org0e81fdf2015-02-02 23:54:03 +00001207 uint8_t payload_type = packet->header.payloadType;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001208 if (!decoder_database_->IsComfortNoise(payload_type)) {
1209 decoder = decoder_database_->GetDecoder(payload_type);
1210 assert(decoder);
1211 if (!decoder) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001212 LOG(LS_WARNING) << "Unknown payload type "
1213 << static_cast<int>(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001214 PacketBuffer::DeleteAllPackets(packet_list);
1215 return kDecoderNotFound;
1216 }
1217 bool decoder_changed;
1218 decoder_database_->SetActiveDecoder(payload_type, &decoder_changed);
1219 if (decoder_changed) {
1220 // We have a new decoder. Re-init some values.
1221 const DecoderDatabase::DecoderInfo* decoder_info = decoder_database_
1222 ->GetDecoderInfo(payload_type);
1223 assert(decoder_info);
1224 if (!decoder_info) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001225 LOG(LS_WARNING) << "Unknown payload type "
1226 << static_cast<int>(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001227 PacketBuffer::DeleteAllPackets(packet_list);
1228 return kDecoderNotFound;
1229 }
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001230 // If sampling rate or number of channels has changed, we need to make
1231 // a reset.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001232 if (decoder_info->fs_hz != fs_hz_ ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001233 decoder->Channels() != algorithm_buffer_->Channels()) {
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001234 // TODO(tlegrand): Add unittest to cover this event.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001235 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->Channels());
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001236 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001237 sync_buffer_->set_end_timestamp(timestamp_);
1238 playout_timestamp_ = timestamp_;
1239 }
1240 }
1241 }
1242
1243 if (reset_decoder_) {
1244 // TODO(hlundin): Write test for this.
Karl Wiberg43766482015-08-27 15:22:11 +02001245 if (decoder)
1246 decoder->Reset();
1247
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001248 // Reset comfort noise decoder.
1249 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02001250 if (cng_decoder)
1251 cng_decoder->Reset();
1252
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001253 reset_decoder_ = false;
1254 }
1255
1256#ifdef LEGACY_BITEXACT
1257 // Due to a bug in old SignalMCU, it could happen that CNG operation was
1258 // decided, but a speech packet was provided. The speech packet will be used
1259 // to update the comfort noise decoder, as if it was a SID frame, which is
1260 // clearly wrong.
1261 if (*operation == kRfc3389Cng) {
1262 return 0;
1263 }
1264#endif
1265
1266 *decoded_length = 0;
1267 // Update codec-internal PLC state.
1268 if ((*operation == kMerge) && decoder && decoder->HasDecodePlc()) {
1269 decoder->DecodePlc(1, &decoded_buffer_[*decoded_length]);
1270 }
1271
minyuel6d92bf52015-09-23 15:20:39 +02001272 int return_value;
1273 if (*operation == kCodecInternalCng) {
1274 RTC_DCHECK(packet_list->empty());
1275 return_value = DecodeCng(decoder, decoded_length, speech_type);
1276 } else {
1277 return_value = DecodeLoop(packet_list, *operation, decoder,
1278 decoded_length, speech_type);
1279 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001280
1281 if (*decoded_length < 0) {
1282 // Error returned from the decoder.
1283 *decoded_length = 0;
Peter Kastingb7e50542015-06-11 12:55:50 -07001284 sync_buffer_->IncreaseEndTimestamp(
1285 static_cast<uint32_t>(decoder_frame_length_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001286 int error_code = 0;
1287 if (decoder)
1288 error_code = decoder->ErrorCode();
1289 if (error_code != 0) {
1290 // Got some error code from the decoder.
1291 decoder_error_code_ = error_code;
1292 return_value = kDecoderErrorCode;
Henrik Lundind67a2192015-08-03 12:54:37 +02001293 LOG(LS_WARNING) << "Decoder returned error code: " << error_code;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001294 } else {
1295 // Decoder does not implement error codes. Return generic error.
1296 return_value = kOtherDecoderError;
Henrik Lundind67a2192015-08-03 12:54:37 +02001297 LOG(LS_WARNING) << "Decoder error (no error code)";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001298 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001299 *operation = kExpand; // Do expansion to get data instead.
1300 }
1301 if (*speech_type != AudioDecoder::kComfortNoise) {
1302 // Don't increment timestamp if codec returned CNG speech type
1303 // since in this case, the we will increment the CNGplayedTS counter.
1304 // Increase with number of samples per channel.
1305 assert(*decoded_length == 0 ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001306 (decoder && decoder->Channels() == sync_buffer_->Channels()));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001307 sync_buffer_->IncreaseEndTimestamp(
1308 *decoded_length / static_cast<int>(sync_buffer_->Channels()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001309 }
1310 return return_value;
1311}
1312
minyuel6d92bf52015-09-23 15:20:39 +02001313int NetEqImpl::DecodeCng(AudioDecoder* decoder, int* decoded_length,
1314 AudioDecoder::SpeechType* speech_type) {
1315 if (!decoder) {
1316 // This happens when active decoder is not defined.
1317 *decoded_length = -1;
1318 return 0;
1319 }
1320
1321 while (*decoded_length < rtc::checked_cast<int>(output_size_samples_)) {
1322 const int length = decoder->Decode(
1323 nullptr, 0, fs_hz_,
1324 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1325 &decoded_buffer_[*decoded_length], speech_type);
1326 if (length > 0) {
1327 *decoded_length += length;
1328 LOG(LS_VERBOSE) << "Decoded " << length << " CNG samples";
1329 } else {
1330 // Error.
1331 LOG(LS_WARNING) << "Failed to decode CNG";
1332 *decoded_length = -1;
1333 break;
1334 }
1335 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1336 // Guard against overflow.
1337 LOG(LS_WARNING) << "Decoded too much CNG.";
1338 return kDecodedTooMuch;
1339 }
1340 }
1341 return 0;
1342}
1343
1344int NetEqImpl::DecodeLoop(PacketList* packet_list, const Operations& operation,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001345 AudioDecoder* decoder, int* decoded_length,
1346 AudioDecoder::SpeechType* speech_type) {
1347 Packet* packet = NULL;
1348 if (!packet_list->empty()) {
1349 packet = packet_list->front();
1350 }
minyuel6d92bf52015-09-23 15:20:39 +02001351
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001352 // Do decoding.
1353 while (packet &&
1354 !decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1355 assert(decoder); // At this point, we must have a decoder object.
1356 // The number of channels in the |sync_buffer_| should be the same as the
1357 // number decoder channels.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001358 assert(sync_buffer_->Channels() == decoder->Channels());
1359 assert(decoded_buffer_length_ >= kMaxFrameSize * decoder->Channels());
minyuel6d92bf52015-09-23 15:20:39 +02001360 assert(operation == kNormal || operation == kAccelerate ||
1361 operation == kFastAccelerate || operation == kMerge ||
1362 operation == kPreemptiveExpand);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001363 packet_list->pop_front();
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001364 size_t payload_length = packet->payload_length;
Peter Kasting36b7cc32015-06-11 19:57:18 -07001365 int decode_length;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +00001366 if (packet->sync_packet) {
1367 // Decode to silence with the same frame size as the last decode.
1368 LOG(LS_VERBOSE) << "Decoding sync-packet: " <<
1369 " ts=" << packet->header.timestamp <<
1370 ", sn=" << packet->header.sequenceNumber <<
1371 ", pt=" << static_cast<int>(packet->header.payloadType) <<
1372 ", ssrc=" << packet->header.ssrc <<
1373 ", len=" << packet->payload_length;
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001374 memset(&decoded_buffer_[*decoded_length], 0,
1375 decoder_frame_length_ * decoder->Channels() *
1376 sizeof(decoded_buffer_[0]));
Peter Kastingdce40cf2015-08-24 14:52:23 -07001377 decode_length = rtc::checked_cast<int>(decoder_frame_length_);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +00001378 } else if (!packet->primary) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001379 // This is a redundant payload; call the special decoder method.
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +00001380 LOG(LS_VERBOSE) << "Decoding packet (redundant):" <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001381 " ts=" << packet->header.timestamp <<
1382 ", sn=" << packet->header.sequenceNumber <<
1383 ", pt=" << static_cast<int>(packet->header.payloadType) <<
1384 ", ssrc=" << packet->header.ssrc <<
1385 ", len=" << packet->payload_length;
1386 decode_length = decoder->DecodeRedundant(
henrik.lundin@webrtc.org1eda4e32015-02-25 10:02:29 +00001387 packet->payload, packet->payload_length, fs_hz_,
minyue@webrtc.org7f7d7e32015-03-16 12:30:37 +00001388 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001389 &decoded_buffer_[*decoded_length], speech_type);
1390 } else {
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +00001391 LOG(LS_VERBOSE) << "Decoding packet: ts=" << packet->header.timestamp <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001392 ", sn=" << packet->header.sequenceNumber <<
1393 ", pt=" << static_cast<int>(packet->header.payloadType) <<
1394 ", ssrc=" << packet->header.ssrc <<
1395 ", len=" << packet->payload_length;
henrik.lundin@webrtc.org1eda4e32015-02-25 10:02:29 +00001396 decode_length =
minyue@webrtc.org7f7d7e32015-03-16 12:30:37 +00001397 decoder->Decode(
1398 packet->payload, packet->payload_length, fs_hz_,
1399 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1400 &decoded_buffer_[*decoded_length], speech_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001401 }
1402
1403 delete[] packet->payload;
1404 delete packet;
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001405 packet = NULL;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001406 if (decode_length > 0) {
1407 *decoded_length += decode_length;
1408 // Update |decoder_frame_length_| with number of samples per channel.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001409 decoder_frame_length_ =
Peter Kastingdce40cf2015-08-24 14:52:23 -07001410 static_cast<size_t>(decode_length) / decoder->Channels();
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001411 LOG(LS_VERBOSE) << "Decoded " << decode_length << " samples ("
1412 << decoder->Channels() << " channel(s) -> "
1413 << decoder_frame_length_ << " samples per channel)";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001414 } else if (decode_length < 0) {
1415 // Error.
Henrik Lundind67a2192015-08-03 12:54:37 +02001416 LOG(LS_WARNING) << "Decode " << decode_length << " " << payload_length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001417 *decoded_length = -1;
1418 PacketBuffer::DeleteAllPackets(packet_list);
1419 break;
1420 }
1421 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1422 // Guard against overflow.
Henrik Lundind67a2192015-08-03 12:54:37 +02001423 LOG(LS_WARNING) << "Decoded too much.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001424 PacketBuffer::DeleteAllPackets(packet_list);
1425 return kDecodedTooMuch;
1426 }
1427 if (!packet_list->empty()) {
1428 packet = packet_list->front();
1429 } else {
1430 packet = NULL;
1431 }
1432 } // End of decode loop.
1433
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001434 // If the list is not empty at this point, either a decoding error terminated
1435 // the while-loop, or list must hold exactly one CNG packet.
1436 assert(packet_list->empty() || *decoded_length < 0 ||
1437 (packet_list->size() == 1 && packet &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001438 decoder_database_->IsComfortNoise(packet->header.payloadType)));
1439 return 0;
1440}
1441
1442void NetEqImpl::DoNormal(const int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001443 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001444 assert(normal_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001445 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001446 normal_->Process(decoded_buffer, decoded_length, last_mode_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001447 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001448 if (decoded_length != 0) {
1449 last_mode_ = kModeNormal;
1450 }
1451
1452 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1453 if ((speech_type == AudioDecoder::kComfortNoise)
1454 || ((last_mode_ == kModeCodecInternalCng)
1455 && (decoded_length == 0))) {
1456 // TODO(hlundin): Remove second part of || statement above.
1457 last_mode_ = kModeCodecInternalCng;
1458 }
1459
1460 if (!play_dtmf) {
1461 dtmf_tone_generator_->Reset();
1462 }
1463}
1464
1465void NetEqImpl::DoMerge(int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001466 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001467 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001468 assert(merge_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001469 size_t new_length = merge_->Process(decoded_buffer, decoded_length,
1470 mute_factor_array_.get(),
1471 algorithm_buffer_.get());
1472 size_t expand_length_correction = new_length -
1473 decoded_length / algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001474
1475 // Update in-call and post-call statistics.
1476 if (expand_->MuteFactor(0) == 0) {
1477 // Expand generates only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001478 stats_.ExpandedNoiseSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001479 } else {
1480 // Expansion generates more than only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001481 stats_.ExpandedVoiceSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001482 }
1483
1484 last_mode_ = kModeMerge;
1485 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1486 if (speech_type == AudioDecoder::kComfortNoise) {
1487 last_mode_ = kModeCodecInternalCng;
1488 }
1489 expand_->Reset();
1490 if (!play_dtmf) {
1491 dtmf_tone_generator_->Reset();
1492 }
1493}
1494
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001495int NetEqImpl::DoExpand(bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001496 while ((sync_buffer_->FutureLength() - expand_->overlap_length()) <
Peter Kastingdce40cf2015-08-24 14:52:23 -07001497 output_size_samples_) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001498 algorithm_buffer_->Clear();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001499 int return_value = expand_->Process(algorithm_buffer_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001500 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001501
1502 // Update in-call and post-call statistics.
1503 if (expand_->MuteFactor(0) == 0) {
1504 // Expand operation generates only noise.
1505 stats_.ExpandedNoiseSamples(length);
1506 } else {
1507 // Expand operation generates more than only noise.
1508 stats_.ExpandedVoiceSamples(length);
1509 }
1510
1511 last_mode_ = kModeExpand;
1512
1513 if (return_value < 0) {
1514 return return_value;
1515 }
1516
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001517 sync_buffer_->PushBack(*algorithm_buffer_);
1518 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001519 }
1520 if (!play_dtmf) {
1521 dtmf_tone_generator_->Reset();
1522 }
1523 return 0;
1524}
1525
Henrik Lundincf808d22015-05-27 14:33:29 +02001526int NetEqImpl::DoAccelerate(int16_t* decoded_buffer,
1527 size_t decoded_length,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001528 AudioDecoder::SpeechType speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +02001529 bool play_dtmf,
1530 bool fast_accelerate) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001531 const size_t required_samples =
1532 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001533 size_t borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001534 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001535 size_t decoded_length_per_channel = decoded_length / num_channels;
1536 if (decoded_length_per_channel < required_samples) {
1537 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001538 borrowed_samples_per_channel = static_cast<int>(required_samples -
1539 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001540 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1541 decoded_buffer,
1542 sizeof(int16_t) * decoded_length);
1543 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1544 decoded_buffer);
1545 decoded_length = required_samples * num_channels;
1546 }
1547
Peter Kastingdce40cf2015-08-24 14:52:23 -07001548 size_t samples_removed;
Henrik Lundincf808d22015-05-27 14:33:29 +02001549 Accelerate::ReturnCodes return_code =
1550 accelerate_->Process(decoded_buffer, decoded_length, fast_accelerate,
1551 algorithm_buffer_.get(), &samples_removed);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001552 stats_.AcceleratedSamples(samples_removed);
1553 switch (return_code) {
1554 case Accelerate::kSuccess:
1555 last_mode_ = kModeAccelerateSuccess;
1556 break;
1557 case Accelerate::kSuccessLowEnergy:
1558 last_mode_ = kModeAccelerateLowEnergy;
1559 break;
1560 case Accelerate::kNoStretch:
1561 last_mode_ = kModeAccelerateFail;
1562 break;
1563 case Accelerate::kError:
1564 // TODO(hlundin): Map to kModeError instead?
1565 last_mode_ = kModeAccelerateFail;
1566 return kAccelerateError;
1567 }
1568
1569 if (borrowed_samples_per_channel > 0) {
1570 // Copy borrowed samples back to the |sync_buffer_|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001571 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001572 if (length < borrowed_samples_per_channel) {
1573 // This destroys the beginning of the buffer, but will not cause any
1574 // problems.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001575 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001576 sync_buffer_->Size() -
1577 borrowed_samples_per_channel);
1578 sync_buffer_->PushFrontZeros(borrowed_samples_per_channel - length);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001579 algorithm_buffer_->PopFront(length);
1580 assert(algorithm_buffer_->Empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001581 } else {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001582 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001583 borrowed_samples_per_channel,
1584 sync_buffer_->Size() -
1585 borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001586 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001587 }
1588 }
1589
1590 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1591 if (speech_type == AudioDecoder::kComfortNoise) {
1592 last_mode_ = kModeCodecInternalCng;
1593 }
1594 if (!play_dtmf) {
1595 dtmf_tone_generator_->Reset();
1596 }
1597 expand_->Reset();
1598 return 0;
1599}
1600
1601int NetEqImpl::DoPreemptiveExpand(int16_t* decoded_buffer,
1602 size_t decoded_length,
1603 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001604 bool play_dtmf) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001605 const size_t required_samples =
1606 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001607 size_t num_channels = algorithm_buffer_->Channels();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001608 size_t borrowed_samples_per_channel = 0;
1609 size_t old_borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001610 size_t decoded_length_per_channel = decoded_length / num_channels;
1611 if (decoded_length_per_channel < required_samples) {
1612 // Must move data from the |sync_buffer_| in order to get 30 ms.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001613 borrowed_samples_per_channel =
1614 required_samples - decoded_length_per_channel;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001615 // Calculate how many of these were already played out.
Peter Kastingf045e4d2015-06-10 21:15:38 -07001616 old_borrowed_samples_per_channel =
Peter Kastingdce40cf2015-08-24 14:52:23 -07001617 (borrowed_samples_per_channel > sync_buffer_->FutureLength()) ?
1618 (borrowed_samples_per_channel - sync_buffer_->FutureLength()) : 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001619 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1620 decoded_buffer,
1621 sizeof(int16_t) * decoded_length);
1622 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1623 decoded_buffer);
1624 decoded_length = required_samples * num_channels;
1625 }
1626
Peter Kastingdce40cf2015-08-24 14:52:23 -07001627 size_t samples_added;
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001628 PreemptiveExpand::ReturnCodes return_code = preemptive_expand_->Process(
Peter Kastingdce40cf2015-08-24 14:52:23 -07001629 decoded_buffer, decoded_length,
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001630 old_borrowed_samples_per_channel,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001631 algorithm_buffer_.get(), &samples_added);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001632 stats_.PreemptiveExpandedSamples(samples_added);
1633 switch (return_code) {
1634 case PreemptiveExpand::kSuccess:
1635 last_mode_ = kModePreemptiveExpandSuccess;
1636 break;
1637 case PreemptiveExpand::kSuccessLowEnergy:
1638 last_mode_ = kModePreemptiveExpandLowEnergy;
1639 break;
1640 case PreemptiveExpand::kNoStretch:
1641 last_mode_ = kModePreemptiveExpandFail;
1642 break;
1643 case PreemptiveExpand::kError:
1644 // TODO(hlundin): Map to kModeError instead?
1645 last_mode_ = kModePreemptiveExpandFail;
1646 return kPreemptiveExpandError;
1647 }
1648
1649 if (borrowed_samples_per_channel > 0) {
1650 // Copy borrowed samples back to the |sync_buffer_|.
1651 sync_buffer_->ReplaceAtIndex(
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001652 *algorithm_buffer_, borrowed_samples_per_channel,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001653 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001654 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001655 }
1656
1657 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1658 if (speech_type == AudioDecoder::kComfortNoise) {
1659 last_mode_ = kModeCodecInternalCng;
1660 }
1661 if (!play_dtmf) {
1662 dtmf_tone_generator_->Reset();
1663 }
1664 expand_->Reset();
1665 return 0;
1666}
1667
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001668int NetEqImpl::DoRfc3389Cng(PacketList* packet_list, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001669 if (!packet_list->empty()) {
1670 // Must have exactly one SID frame at this point.
1671 assert(packet_list->size() == 1);
1672 Packet* packet = packet_list->front();
1673 packet_list->pop_front();
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001674 if (!decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1675#ifdef LEGACY_BITEXACT
1676 // This can happen due to a bug in GetDecision. Change the payload type
1677 // to a CNG type, and move on. Note that this means that we are in fact
1678 // sending a non-CNG payload to the comfort noise decoder for decoding.
1679 // Clearly wrong, but will maintain bit-exactness with legacy.
1680 if (fs_hz_ == 8000) {
1681 packet->header.payloadType =
kwibergee1879c2015-10-29 06:20:28 -07001682 decoder_database_->GetRtpPayloadType(NetEqDecoder::kDecoderCNGnb);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001683 } else if (fs_hz_ == 16000) {
1684 packet->header.payloadType =
kwibergee1879c2015-10-29 06:20:28 -07001685 decoder_database_->GetRtpPayloadType(NetEqDecoder::kDecoderCNGwb);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001686 } else if (fs_hz_ == 32000) {
kwibergee1879c2015-10-29 06:20:28 -07001687 packet->header.payloadType = decoder_database_->GetRtpPayloadType(
1688 NetEqDecoder::kDecoderCNGswb32kHz);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001689 } else if (fs_hz_ == 48000) {
kwibergee1879c2015-10-29 06:20:28 -07001690 packet->header.payloadType = decoder_database_->GetRtpPayloadType(
1691 NetEqDecoder::kDecoderCNGswb48kHz);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001692 }
1693 assert(decoder_database_->IsComfortNoise(packet->header.payloadType));
1694#else
1695 LOG(LS_ERROR) << "Trying to decode non-CNG payload as CNG.";
1696 return kOtherError;
1697#endif
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001698 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001699 // UpdateParameters() deletes |packet|.
1700 if (comfort_noise_->UpdateParameters(packet) ==
1701 ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001702 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001703 return -comfort_noise_->internal_error_code();
1704 }
1705 }
1706 int cn_return = comfort_noise_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001707 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001708 expand_->Reset();
1709 last_mode_ = kModeRfc3389Cng;
1710 if (!play_dtmf) {
1711 dtmf_tone_generator_->Reset();
1712 }
1713 if (cn_return == ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001714 decoder_error_code_ = comfort_noise_->internal_error_code();
1715 return kComfortNoiseErrorCode;
1716 } else if (cn_return == ComfortNoise::kUnknownPayloadType) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001717 return kUnknownRtpPayloadType;
1718 }
1719 return 0;
1720}
1721
minyuel6d92bf52015-09-23 15:20:39 +02001722void NetEqImpl::DoCodecInternalCng(const int16_t* decoded_buffer,
1723 size_t decoded_length) {
1724 RTC_DCHECK(normal_.get());
1725 RTC_DCHECK(mute_factor_array_.get());
1726 normal_->Process(decoded_buffer, decoded_length, last_mode_,
1727 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001728 last_mode_ = kModeCodecInternalCng;
1729 expand_->Reset();
1730}
1731
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001732int NetEqImpl::DoDtmf(const DtmfEvent& dtmf_event, bool* play_dtmf) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001733 // This block of the code and the block further down, handling |dtmf_switch|
1734 // are commented out. Otherwise playing out-of-band DTMF would fail in VoE
1735 // test, DtmfTest.ManualSuccessfullySendsOutOfBandTelephoneEvents. This is
1736 // equivalent to |dtmf_switch| always be false.
1737 //
1738 // See http://webrtc-codereview.appspot.com/1195004/ for discussion
1739 // On this issue. This change might cause some glitches at the point of
1740 // switch from audio to DTMF. Issue 1545 is filed to track this.
1741 //
1742 // bool dtmf_switch = false;
1743 // if ((last_mode_ != kModeDtmf) && dtmf_tone_generator_->initialized()) {
1744 // // Special case; see below.
1745 // // We must catch this before calling Generate, since |initialized| is
1746 // // modified in that call.
1747 // dtmf_switch = true;
1748 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001749
1750 int dtmf_return_value = 0;
1751 if (!dtmf_tone_generator_->initialized()) {
1752 // Initialize if not already done.
1753 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1754 dtmf_event.volume);
1755 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001756
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001757 if (dtmf_return_value == 0) {
1758 // Generate DTMF signal.
1759 dtmf_return_value = dtmf_tone_generator_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001760 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001761 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001762
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001763 if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001764 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001765 return dtmf_return_value;
1766 }
1767
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001768 // if (dtmf_switch) {
1769 // // This is the special case where the previous operation was DTMF
1770 // // overdub, but the current instruction is "regular" DTMF. We must make
1771 // // sure that the DTMF does not have any discontinuities. The first DTMF
1772 // // sample that we generate now must be played out immediately, therefore
1773 // // it must be copied to the speech buffer.
1774 // // TODO(hlundin): This code seems incorrect. (Legacy.) Write test and
1775 // // verify correct operation.
1776 // assert(false);
1777 // // Must generate enough data to replace all of the |sync_buffer_|
1778 // // "future".
1779 // int required_length = sync_buffer_->FutureLength();
1780 // assert(dtmf_tone_generator_->initialized());
1781 // dtmf_return_value = dtmf_tone_generator_->Generate(required_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001782 // algorithm_buffer_);
1783 // assert((size_t) required_length == algorithm_buffer_->Size());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001784 // if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001785 // algorithm_buffer_->Zeros(output_size_samples_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001786 // return dtmf_return_value;
1787 // }
1788 //
1789 // // Overwrite the "future" part of the speech buffer with the new DTMF
1790 // // data.
1791 // // TODO(hlundin): It seems that this overwriting has gone lost.
1792 // // Not adapted for multi-channel yet.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001793 // assert(algorithm_buffer_->Channels() == 1);
1794 // if (algorithm_buffer_->Channels() != 1) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001795 // LOG(LS_WARNING) << "DTMF not supported for more than one channel";
1796 // return kStereoNotSupported;
1797 // }
1798 // // Shuffle the remaining data to the beginning of algorithm buffer.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001799 // algorithm_buffer_->PopFront(sync_buffer_->FutureLength());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001800 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001801
Peter Kastingb7e50542015-06-11 12:55:50 -07001802 sync_buffer_->IncreaseEndTimestamp(
1803 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001804 expand_->Reset();
1805 last_mode_ = kModeDtmf;
1806
1807 // Set to false because the DTMF is already in the algorithm buffer.
1808 *play_dtmf = false;
1809 return 0;
1810}
1811
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001812void NetEqImpl::DoAlternativePlc(bool increase_timestamp) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001813 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001814 size_t length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001815 if (decoder && decoder->HasDecodePlc()) {
1816 // Use the decoder's packet-loss concealment.
1817 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1818 int16_t decoded_buffer[kMaxFrameSize];
1819 length = decoder->DecodePlc(1, decoded_buffer);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001820 if (length > 0)
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001821 algorithm_buffer_->PushBackInterleaved(decoded_buffer, length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001822 } else {
1823 // Do simple zero-stuffing.
1824 length = output_size_samples_;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001825 algorithm_buffer_->Zeros(length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001826 // By not advancing the timestamp, NetEq inserts samples.
1827 stats_.AddZeros(length);
1828 }
1829 if (increase_timestamp) {
Peter Kastingb7e50542015-06-11 12:55:50 -07001830 sync_buffer_->IncreaseEndTimestamp(static_cast<uint32_t>(length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001831 }
1832 expand_->Reset();
1833}
1834
1835int NetEqImpl::DtmfOverdub(const DtmfEvent& dtmf_event, size_t num_channels,
1836 int16_t* output) const {
1837 size_t out_index = 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001838 size_t overdub_length = output_size_samples_; // Default value.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001839
1840 if (sync_buffer_->dtmf_index() > sync_buffer_->next_index()) {
1841 // Special operation for transition from "DTMF only" to "DTMF overdub".
1842 out_index = std::min(
1843 sync_buffer_->dtmf_index() - sync_buffer_->next_index(),
Peter Kastingdce40cf2015-08-24 14:52:23 -07001844 output_size_samples_);
1845 overdub_length = output_size_samples_ - out_index;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001846 }
1847
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001848 AudioMultiVector dtmf_output(num_channels);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001849 int dtmf_return_value = 0;
1850 if (!dtmf_tone_generator_->initialized()) {
1851 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1852 dtmf_event.volume);
1853 }
1854 if (dtmf_return_value == 0) {
1855 dtmf_return_value = dtmf_tone_generator_->Generate(overdub_length,
1856 &dtmf_output);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001857 assert(overdub_length == dtmf_output.Size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001858 }
1859 dtmf_output.ReadInterleaved(overdub_length, &output[out_index]);
1860 return dtmf_return_value < 0 ? dtmf_return_value : 0;
1861}
1862
Peter Kastingdce40cf2015-08-24 14:52:23 -07001863int NetEqImpl::ExtractPackets(size_t required_samples,
1864 PacketList* packet_list) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001865 bool first_packet = true;
1866 uint8_t prev_payload_type = 0;
1867 uint32_t prev_timestamp = 0;
1868 uint16_t prev_sequence_number = 0;
1869 bool next_packet_available = false;
1870
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001871 const RTPHeader* header = packet_buffer_->NextRtpHeader();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001872 assert(header);
1873 if (!header) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001874 LOG(LS_ERROR) << "Packet buffer unexpectedly empty.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001875 return -1;
1876 }
turaj@webrtc.org7df97062013-08-02 18:07:13 +00001877 uint32_t first_timestamp = header->timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001878 int extracted_samples = 0;
1879
1880 // Packet extraction loop.
1881 do {
1882 timestamp_ = header->timestamp;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001883 size_t discard_count = 0;
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001884 Packet* packet = packet_buffer_->GetNextPacket(&discard_count);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001885 // |header| may be invalid after the |packet_buffer_| operation.
1886 header = NULL;
1887 if (!packet) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001888 LOG(LS_ERROR) << "Should always be able to extract a packet here";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001889 assert(false); // Should always be able to extract a packet here.
1890 return -1;
1891 }
1892 stats_.PacketsDiscarded(discard_count);
1893 // Store waiting time in ms; packets->waiting_time is in "output blocks".
1894 stats_.StoreWaitingTime(packet->waiting_time * kOutputSizeMs);
1895 assert(packet->payload_length > 0);
1896 packet_list->push_back(packet); // Store packet in list.
1897
1898 if (first_packet) {
1899 first_packet = false;
henrik.lundin48ed9302015-10-29 05:36:24 -07001900 if (nack_enabled_) {
1901 RTC_DCHECK(nack_);
1902 // TODO(henrik.lundin): Should we update this for all decoded packets?
1903 nack_->UpdateLastDecodedPacket(packet->header.sequenceNumber,
1904 packet->header.timestamp);
1905 }
1906 prev_sequence_number = packet->header.sequenceNumber;
1907 prev_timestamp = packet->header.timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001908 prev_payload_type = packet->header.payloadType;
1909 }
1910
1911 // Store number of extracted samples.
1912 int packet_duration = 0;
1913 AudioDecoder* decoder = decoder_database_->GetDecoder(
1914 packet->header.payloadType);
1915 if (decoder) {
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001916 if (packet->sync_packet) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001917 packet_duration = rtc::checked_cast<int>(decoder_frame_length_);
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001918 } else {
minyue@webrtc.org2c1bcf22015-02-17 10:17:09 +00001919 if (packet->primary) {
1920 packet_duration = decoder->PacketDuration(packet->payload,
1921 packet->payload_length);
1922 } else {
1923 packet_duration = decoder->
1924 PacketDurationRedundant(packet->payload, packet->payload_length);
1925 stats_.SecondaryDecodedSamples(packet_duration);
1926 }
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001927 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001928 } else {
Henrik Lundind67a2192015-08-03 12:54:37 +02001929 LOG(LS_WARNING) << "Unknown payload type "
1930 << static_cast<int>(packet->header.payloadType);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001931 assert(false);
1932 }
1933 if (packet_duration <= 0) {
1934 // Decoder did not return a packet duration. Assume that the packet
1935 // contains the same number of samples as the previous one.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001936 packet_duration = rtc::checked_cast<int>(decoder_frame_length_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001937 }
1938 extracted_samples = packet->header.timestamp - first_timestamp +
1939 packet_duration;
1940
1941 // Check what packet is available next.
1942 header = packet_buffer_->NextRtpHeader();
1943 next_packet_available = false;
1944 if (header && prev_payload_type == header->payloadType) {
1945 int16_t seq_no_diff = header->sequenceNumber - prev_sequence_number;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001946 size_t ts_diff = header->timestamp - prev_timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001947 if (seq_no_diff == 1 ||
1948 (seq_no_diff == 0 && ts_diff == decoder_frame_length_)) {
1949 // The next sequence number is available, or the next part of a packet
1950 // that was split into pieces upon insertion.
1951 next_packet_available = true;
1952 }
1953 prev_sequence_number = header->sequenceNumber;
1954 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07001955 } while (extracted_samples < rtc::checked_cast<int>(required_samples) &&
1956 next_packet_available);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001957
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00001958 if (extracted_samples > 0) {
1959 // Delete old packets only when we are going to decode something. Otherwise,
1960 // we could end up in the situation where we never decode anything, since
1961 // all incoming packets are considered too old but the buffer will also
1962 // never be flooded and flushed.
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001963 packet_buffer_->DiscardAllOldPackets(timestamp_);
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00001964 }
1965
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001966 return extracted_samples;
1967}
1968
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001969void NetEqImpl::UpdatePlcComponents(int fs_hz, size_t channels) {
1970 // Delete objects and create new ones.
1971 expand_.reset(expand_factory_->Create(background_noise_.get(),
1972 sync_buffer_.get(), &random_vector_,
Henrik Lundinbef77e22015-08-18 14:58:09 +02001973 &stats_, fs_hz, channels));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001974 merge_.reset(new Merge(fs_hz, channels, expand_.get(), sync_buffer_.get()));
1975}
1976
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001977void NetEqImpl::SetSampleRateAndChannels(int fs_hz, size_t channels) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001978 LOG(LS_VERBOSE) << "SetSampleRateAndChannels " << fs_hz << " " << channels;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001979 // TODO(hlundin): Change to an enumerator and skip assert.
1980 assert(fs_hz == 8000 || fs_hz == 16000 || fs_hz == 32000 || fs_hz == 48000);
1981 assert(channels > 0);
1982
1983 fs_hz_ = fs_hz;
1984 fs_mult_ = fs_hz / 8000;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001985 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001986 decoder_frame_length_ = 3 * output_size_samples_; // Initialize to 30ms.
1987
1988 last_mode_ = kModeNormal;
1989
1990 // Create a new array of mute factors and set all to 1.
1991 mute_factor_array_.reset(new int16_t[channels]);
1992 for (size_t i = 0; i < channels; ++i) {
1993 mute_factor_array_[i] = 16384; // 1.0 in Q14.
1994 }
1995
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001996 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02001997 if (cng_decoder)
1998 cng_decoder->Reset();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001999
2000 // Reinit post-decode VAD with new sample rate.
2001 assert(vad_.get()); // Cannot be NULL here.
2002 vad_->Init();
2003
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002004 // Delete algorithm buffer and create a new one.
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00002005 algorithm_buffer_.reset(new AudioMultiVector(channels));
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002006
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002007 // Delete sync buffer and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002008 sync_buffer_.reset(new SyncBuffer(channels, kSyncBufferSize * fs_mult_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002009
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00002010 // Delete BackgroundNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002011 background_noise_.reset(new BackgroundNoise(channels));
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00002012 background_noise_->set_mode(background_noise_mode_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002013
2014 // Reset random vector.
2015 random_vector_.Reset();
2016
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002017 UpdatePlcComponents(fs_hz, channels);
2018
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002019 // Move index so that we create a small set of future samples (all 0).
2020 sync_buffer_->set_next_index(sync_buffer_->next_index() -
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002021 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002022
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002023 normal_.reset(new Normal(fs_hz, decoder_database_.get(), *background_noise_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002024 expand_.get()));
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +00002025 accelerate_.reset(
2026 accelerate_factory_->Create(fs_hz, channels, *background_noise_));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002027 preemptive_expand_.reset(preemptive_expand_factory_->Create(
Peter Kastingdce40cf2015-08-24 14:52:23 -07002028 fs_hz, channels, *background_noise_, expand_->overlap_length()));
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002029
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002030 // Delete ComfortNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002031 comfort_noise_.reset(new ComfortNoise(fs_hz, decoder_database_.get(),
2032 sync_buffer_.get()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002033
2034 // Verify that |decoded_buffer_| is long enough.
2035 if (decoded_buffer_length_ < kMaxFrameSize * channels) {
2036 // Reallocate to larger size.
2037 decoded_buffer_length_ = kMaxFrameSize * channels;
2038 decoded_buffer_.reset(new int16_t[decoded_buffer_length_]);
2039 }
2040
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002041 // Create DecisionLogic if it is not created yet, then communicate new sample
2042 // rate and output size to DecisionLogic object.
2043 if (!decision_logic_.get()) {
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002044 CreateDecisionLogic();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002045 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002046 decision_logic_->SetSampleRate(fs_hz_, output_size_samples_);
2047}
2048
2049NetEqOutputType NetEqImpl::LastOutputType() {
2050 assert(vad_.get());
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002051 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002052 if (last_mode_ == kModeCodecInternalCng || last_mode_ == kModeRfc3389Cng) {
2053 return kOutputCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002054 } else if (last_mode_ == kModeExpand && expand_->MuteFactor(0) == 0) {
2055 // Expand mode has faded down to background noise only (very long expand).
2056 return kOutputPLCtoCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002057 } else if (last_mode_ == kModeExpand) {
2058 return kOutputPLC;
wu@webrtc.org24301a62013-12-13 19:17:43 +00002059 } else if (vad_->running() && !vad_->active_speech()) {
2060 return kOutputVADPassive;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002061 } else {
2062 return kOutputNormal;
2063 }
2064}
2065
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002066void NetEqImpl::CreateDecisionLogic() {
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002067 decision_logic_.reset(DecisionLogic::Create(fs_hz_, output_size_samples_,
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002068 playout_mode_,
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002069 decoder_database_.get(),
2070 *packet_buffer_.get(),
2071 delay_manager_.get(),
2072 buffer_level_filter_.get()));
2073}
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002074} // namespace webrtc