blob: a6666a6d35c37856bb33085ebad65dbc516972b6 [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"
hbosde1c81b2016-03-08 04:46:00 -080020#include "webrtc/base/numerics/safe_conversions.h"
henrik.lundina689b442015-12-17 03:50:05 -080021#include "webrtc/base/trace_event.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000022#include "webrtc/common_audio/signal_processing/include/signal_processing_library.h"
kwiberg@webrtc.orge04a93b2014-12-09 10:12:53 +000023#include "webrtc/modules/audio_coding/codecs/audio_decoder.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000024#include "webrtc/modules/audio_coding/neteq/accelerate.h"
25#include "webrtc/modules/audio_coding/neteq/background_noise.h"
26#include "webrtc/modules/audio_coding/neteq/buffer_level_filter.h"
27#include "webrtc/modules/audio_coding/neteq/comfort_noise.h"
28#include "webrtc/modules/audio_coding/neteq/decision_logic.h"
29#include "webrtc/modules/audio_coding/neteq/decoder_database.h"
30#include "webrtc/modules/audio_coding/neteq/defines.h"
31#include "webrtc/modules/audio_coding/neteq/delay_manager.h"
32#include "webrtc/modules/audio_coding/neteq/delay_peak_detector.h"
33#include "webrtc/modules/audio_coding/neteq/dtmf_buffer.h"
34#include "webrtc/modules/audio_coding/neteq/dtmf_tone_generator.h"
35#include "webrtc/modules/audio_coding/neteq/expand.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000036#include "webrtc/modules/audio_coding/neteq/merge.h"
henrik.lundin48ed9302015-10-29 05:36:24 -070037#include "webrtc/modules/audio_coding/neteq/nack.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000038#include "webrtc/modules/audio_coding/neteq/normal.h"
39#include "webrtc/modules/audio_coding/neteq/packet_buffer.h"
40#include "webrtc/modules/audio_coding/neteq/packet.h"
41#include "webrtc/modules/audio_coding/neteq/payload_splitter.h"
42#include "webrtc/modules/audio_coding/neteq/post_decode_vad.h"
43#include "webrtc/modules/audio_coding/neteq/preemptive_expand.h"
44#include "webrtc/modules/audio_coding/neteq/sync_buffer.h"
45#include "webrtc/modules/audio_coding/neteq/timestamp_scaler.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010046#include "webrtc/modules/include/module_common_types.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)
Tommi9090e0b2016-01-20 13:39:36 +010069 : buffer_level_filter_(buffer_level_filter),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000070 decoder_database_(decoder_database),
71 delay_manager_(delay_manager),
72 delay_peak_detector_(delay_peak_detector),
73 dtmf_buffer_(dtmf_buffer),
74 dtmf_tone_generator_(dtmf_tone_generator),
75 packet_buffer_(packet_buffer),
76 payload_splitter_(payload_splitter),
77 timestamp_scaler_(timestamp_scaler),
78 vad_(new PostDecodeVad()),
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +000079 expand_factory_(expand_factory),
80 accelerate_factory_(accelerate_factory),
81 preemptive_expand_factory_(preemptive_expand_factory),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000082 last_mode_(kModeNormal),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000083 decoded_buffer_length_(kMaxFrameSize),
84 decoded_buffer_(new int16_t[decoded_buffer_length_]),
85 playout_timestamp_(0),
86 new_codec_(false),
87 timestamp_(0),
88 reset_decoder_(false),
henrik.lundin48ed9302015-10-29 05:36:24 -070089 current_rtp_payload_type_(0xFF), // Invalid RTP payload type.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000090 current_cng_rtp_payload_type_(0xFF), // Invalid RTP payload type.
91 ssrc_(0),
92 first_packet_(true),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000093 error_code_(0),
94 decoder_error_code_(0),
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +000095 background_noise_mode_(config.background_noise_mode),
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +000096 playout_mode_(config.playout_mode),
Henrik Lundincf808d22015-05-27 14:33:29 +020097 enable_fast_accelerate_(config.enable_fast_accelerate),
henrik.lundin48ed9302015-10-29 05:36:24 -070098 nack_enabled_(false) {
Henrik Lundin905495c2015-05-25 16:58:41 +020099 LOG(LS_INFO) << "NetEq config: " << config.ToString();
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +0000100 int fs = config.sample_rate_hz;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000101 if (fs != 8000 && fs != 16000 && fs != 32000 && fs != 48000) {
102 LOG(LS_ERROR) << "Sample rate " << fs << " Hz not supported. " <<
103 "Changing to 8000 Hz.";
104 fs = 8000;
105 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000106 fs_hz_ = fs;
107 fs_mult_ = fs / 8000;
henrik.lundind89814b2015-11-23 06:49:25 -0800108 last_output_sample_rate_hz_ = fs;
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.lundin9bc26672015-11-02 03:25:57 -0800115 RTC_DCHECK(!vad_->enabled());
116 if (config.enable_post_decode_vad) {
117 vad_->Enable();
118 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000119}
120
Henrik Lundind67a2192015-08-03 12:54:37 +0200121NetEqImpl::~NetEqImpl() = default;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000122
123int NetEqImpl::InsertPacket(const WebRtcRTPHeader& rtp_header,
kwibergee2bac22015-11-11 10:34:00 -0800124 rtc::ArrayView<const uint8_t> payload,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000125 uint32_t receive_timestamp) {
henrik.lundina689b442015-12-17 03:50:05 -0800126 TRACE_EVENT0("webrtc", "NetEqImpl::InsertPacket");
Tommi9090e0b2016-01-20 13:39:36 +0100127 rtc::CritScope lock(&crit_sect_);
kwibergee2bac22015-11-11 10:34:00 -0800128 int error =
129 InsertPacketInternal(rtp_header, payload, receive_timestamp, false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000130 if (error != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000131 error_code_ = error;
132 return kFail;
133 }
134 return kOK;
135}
136
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000137int NetEqImpl::InsertSyncPacket(const WebRtcRTPHeader& rtp_header,
138 uint32_t receive_timestamp) {
Tommi9090e0b2016-01-20 13:39:36 +0100139 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000140 const uint8_t kSyncPayload[] = { 's', 'y', 'n', 'c' };
kwibergee2bac22015-11-11 10:34:00 -0800141 int error =
142 InsertPacketInternal(rtp_header, kSyncPayload, receive_timestamp, true);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000143
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000144 if (error != 0) {
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000145 error_code_ = error;
146 return kFail;
147 }
148 return kOK;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000149}
150
henrik.lundin500c04b2016-03-08 02:36:04 -0800151namespace {
152void SetAudioFrameActivityAndType(bool vad_enabled,
henrik.lundin55480f52016-03-08 02:37:57 -0800153 NetEqImpl::OutputType type,
henrik.lundin500c04b2016-03-08 02:36:04 -0800154 AudioFrame::VADActivity last_vad_activity,
155 AudioFrame* audio_frame) {
156 switch (type) {
henrik.lundin55480f52016-03-08 02:37:57 -0800157 case NetEqImpl::OutputType::kNormalSpeech: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800158 audio_frame->speech_type_ = AudioFrame::kNormalSpeech;
159 audio_frame->vad_activity_ = AudioFrame::kVadActive;
160 break;
161 }
henrik.lundin55480f52016-03-08 02:37:57 -0800162 case NetEqImpl::OutputType::kVadPassive: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800163 // This should only be reached if the VAD is enabled.
164 RTC_DCHECK(vad_enabled);
165 audio_frame->speech_type_ = AudioFrame::kNormalSpeech;
166 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
167 break;
168 }
henrik.lundin55480f52016-03-08 02:37:57 -0800169 case NetEqImpl::OutputType::kCNG: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800170 audio_frame->speech_type_ = AudioFrame::kCNG;
171 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
172 break;
173 }
henrik.lundin55480f52016-03-08 02:37:57 -0800174 case NetEqImpl::OutputType::kPLC: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800175 audio_frame->speech_type_ = AudioFrame::kPLC;
176 audio_frame->vad_activity_ = last_vad_activity;
177 break;
178 }
henrik.lundin55480f52016-03-08 02:37:57 -0800179 case NetEqImpl::OutputType::kPLCCNG: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800180 audio_frame->speech_type_ = AudioFrame::kPLCCNG;
181 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
182 break;
183 }
184 default:
185 RTC_NOTREACHED();
186 }
187 if (!vad_enabled) {
188 // Always set kVadUnknown when receive VAD is inactive.
189 audio_frame->vad_activity_ = AudioFrame::kVadUnknown;
190 }
191}
192}
193
henrik.lundin55480f52016-03-08 02:37:57 -0800194int NetEqImpl::GetAudio(AudioFrame* audio_frame) {
henrik.lundine1ca1672016-01-08 03:50:08 -0800195 TRACE_EVENT0("webrtc", "NetEqImpl::GetAudio");
Tommi9090e0b2016-01-20 13:39:36 +0100196 rtc::CritScope lock(&crit_sect_);
henrik.lundin6d8e0112016-03-04 10:34:21 -0800197 int error = GetAudioInternal(audio_frame);
198 RTC_DCHECK_EQ(
199 audio_frame->sample_rate_hz_,
200 rtc::checked_cast<int>(audio_frame->samples_per_channel_ * 100));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000201 if (error != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000202 error_code_ = error;
203 return kFail;
204 }
henrik.lundin500c04b2016-03-08 02:36:04 -0800205 SetAudioFrameActivityAndType(vad_->enabled(), LastOutputType(),
206 last_vad_activity_, audio_frame);
207 last_vad_activity_ = audio_frame->vad_activity_;
henrik.lundin6d8e0112016-03-04 10:34:21 -0800208 last_output_sample_rate_hz_ = audio_frame->sample_rate_hz_;
henrik.lundind89814b2015-11-23 06:49:25 -0800209 RTC_DCHECK(last_output_sample_rate_hz_ == 8000 ||
210 last_output_sample_rate_hz_ == 16000 ||
211 last_output_sample_rate_hz_ == 32000 ||
212 last_output_sample_rate_hz_ == 48000)
213 << "Unexpected sample rate " << last_output_sample_rate_hz_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000214 return kOK;
215}
216
kwibergee1879c2015-10-29 06:20:28 -0700217int NetEqImpl::RegisterPayloadType(NetEqDecoder codec,
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800218 const std::string& name,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000219 uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100220 rtc::CritScope lock(&crit_sect_);
Henrik Lundind67a2192015-08-03 12:54:37 +0200221 LOG(LS_VERBOSE) << "RegisterPayloadType "
kwibergee1879c2015-10-29 06:20:28 -0700222 << static_cast<int>(rtp_payload_type) << " "
223 << static_cast<int>(codec);
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800224 int ret = decoder_database_->RegisterPayload(rtp_payload_type, codec, name);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000225 if (ret != DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000226 switch (ret) {
227 case DecoderDatabase::kInvalidRtpPayloadType:
228 error_code_ = kInvalidRtpPayloadType;
229 break;
230 case DecoderDatabase::kCodecNotSupported:
231 error_code_ = kCodecNotSupported;
232 break;
233 case DecoderDatabase::kDecoderExists:
234 error_code_ = kDecoderExists;
235 break;
236 default:
237 error_code_ = kOtherError;
238 }
239 return kFail;
240 }
241 return kOK;
242}
243
244int NetEqImpl::RegisterExternalDecoder(AudioDecoder* decoder,
kwibergee1879c2015-10-29 06:20:28 -0700245 NetEqDecoder codec,
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800246 const std::string& codec_name,
Karl Wibergd8399e62015-05-25 14:39:56 +0200247 uint8_t rtp_payload_type,
248 int sample_rate_hz) {
Tommi9090e0b2016-01-20 13:39:36 +0100249 rtc::CritScope lock(&crit_sect_);
Henrik Lundind67a2192015-08-03 12:54:37 +0200250 LOG(LS_VERBOSE) << "RegisterExternalDecoder "
kwibergee1879c2015-10-29 06:20:28 -0700251 << static_cast<int>(rtp_payload_type) << " "
252 << static_cast<int>(codec);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000253 if (!decoder) {
254 LOG(LS_ERROR) << "Cannot register external decoder with NULL pointer";
255 assert(false);
256 return kFail;
257 }
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800258 int ret = decoder_database_->InsertExternal(
259 rtp_payload_type, codec, codec_name, sample_rate_hz, decoder);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000260 if (ret != DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000261 switch (ret) {
262 case DecoderDatabase::kInvalidRtpPayloadType:
263 error_code_ = kInvalidRtpPayloadType;
264 break;
265 case DecoderDatabase::kCodecNotSupported:
266 error_code_ = kCodecNotSupported;
267 break;
268 case DecoderDatabase::kDecoderExists:
269 error_code_ = kDecoderExists;
270 break;
271 case DecoderDatabase::kInvalidSampleRate:
272 error_code_ = kInvalidSampleRate;
273 break;
274 case DecoderDatabase::kInvalidPointer:
275 error_code_ = kInvalidPointer;
276 break;
277 default:
278 error_code_ = kOtherError;
279 }
280 return kFail;
281 }
282 return kOK;
283}
284
285int NetEqImpl::RemovePayloadType(uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100286 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000287 int ret = decoder_database_->Remove(rtp_payload_type);
288 if (ret == DecoderDatabase::kOK) {
289 return kOK;
290 } else if (ret == DecoderDatabase::kDecoderNotFound) {
291 error_code_ = kDecoderNotFound;
292 } else {
293 error_code_ = kOtherError;
294 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000295 return kFail;
296}
297
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000298bool NetEqImpl::SetMinimumDelay(int delay_ms) {
Tommi9090e0b2016-01-20 13:39:36 +0100299 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000300 if (delay_ms >= 0 && delay_ms < 10000) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000301 assert(delay_manager_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000302 return delay_manager_->SetMinimumDelay(delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000303 }
304 return false;
305}
306
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000307bool NetEqImpl::SetMaximumDelay(int delay_ms) {
Tommi9090e0b2016-01-20 13:39:36 +0100308 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000309 if (delay_ms >= 0 && delay_ms < 10000) {
310 assert(delay_manager_.get());
311 return delay_manager_->SetMaximumDelay(delay_ms);
312 }
313 return false;
314}
315
316int NetEqImpl::LeastRequiredDelayMs() const {
Tommi9090e0b2016-01-20 13:39:36 +0100317 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000318 assert(delay_manager_.get());
319 return delay_manager_->least_required_delay_ms();
320}
321
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200322int NetEqImpl::SetTargetDelay() {
323 return kNotImplemented;
324}
325
326int NetEqImpl::TargetDelay() {
327 return kNotImplemented;
328}
329
henrik.lundin9c3efd02015-08-27 13:12:22 -0700330int NetEqImpl::CurrentDelayMs() const {
Tommi9090e0b2016-01-20 13:39:36 +0100331 rtc::CritScope lock(&crit_sect_);
henrik.lundin9c3efd02015-08-27 13:12:22 -0700332 if (fs_hz_ == 0)
333 return 0;
334 // Sum up the samples in the packet buffer with the future length of the sync
335 // buffer, and divide the sum by the sample rate.
336 const size_t delay_samples =
337 packet_buffer_->NumSamplesInBuffer(decoder_database_.get(),
338 decoder_frame_length_) +
339 sync_buffer_->FutureLength();
340 // The division below will truncate.
341 const int delay_ms =
342 static_cast<int>(delay_samples) / rtc::CheckedDivExact(fs_hz_, 1000);
343 return delay_ms;
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200344}
345
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000346// Deprecated.
347// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000348void NetEqImpl::SetPlayoutMode(NetEqPlayoutMode mode) {
Tommi9090e0b2016-01-20 13:39:36 +0100349 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000350 if (mode != playout_mode_) {
351 playout_mode_ = mode;
352 CreateDecisionLogic();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000353 }
354}
355
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000356// Deprecated.
357// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000358NetEqPlayoutMode NetEqImpl::PlayoutMode() const {
Tommi9090e0b2016-01-20 13:39:36 +0100359 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000360 return playout_mode_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000361}
362
363int NetEqImpl::NetworkStatistics(NetEqNetworkStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100364 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000365 assert(decoder_database_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700366 const size_t total_samples_in_buffers =
Peter Kasting728d9032015-06-11 14:31:38 -0700367 packet_buffer_->NumSamplesInBuffer(decoder_database_.get(),
368 decoder_frame_length_) +
Peter Kastingdce40cf2015-08-24 14:52:23 -0700369 sync_buffer_->FutureLength();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000370 assert(delay_manager_.get());
371 assert(decision_logic_.get());
372 stats_.GetNetworkStatistics(fs_hz_, total_samples_in_buffers,
373 decoder_frame_length_, *delay_manager_.get(),
374 *decision_logic_.get(), stats);
375 return 0;
376}
377
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000378void NetEqImpl::GetRtcpStatistics(RtcpStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100379 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000380 if (stats) {
381 rtcp_.GetStatistics(false, stats);
382 }
383}
384
385void NetEqImpl::GetRtcpStatisticsNoReset(RtcpStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100386 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000387 if (stats) {
388 rtcp_.GetStatistics(true, stats);
389 }
390}
391
392void NetEqImpl::EnableVad() {
Tommi9090e0b2016-01-20 13:39:36 +0100393 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000394 assert(vad_.get());
395 vad_->Enable();
396}
397
398void NetEqImpl::DisableVad() {
Tommi9090e0b2016-01-20 13:39:36 +0100399 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000400 assert(vad_.get());
401 vad_->Disable();
402}
403
wu@webrtc.org94454b72014-06-05 20:34:08 +0000404bool NetEqImpl::GetPlayoutTimestamp(uint32_t* timestamp) {
Tommi9090e0b2016-01-20 13:39:36 +0100405 rtc::CritScope lock(&crit_sect_);
wu@webrtc.org94454b72014-06-05 20:34:08 +0000406 if (first_packet_) {
407 // We don't have a valid RTP timestamp until we have decoded our first
408 // RTP packet.
409 return false;
410 }
411 *timestamp = timestamp_scaler_->ToExternal(playout_timestamp_);
412 return true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000413}
414
henrik.lundind89814b2015-11-23 06:49:25 -0800415int NetEqImpl::last_output_sample_rate_hz() const {
Tommi9090e0b2016-01-20 13:39:36 +0100416 rtc::CritScope lock(&crit_sect_);
henrik.lundind89814b2015-11-23 06:49:25 -0800417 return last_output_sample_rate_hz_;
418}
419
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200420int NetEqImpl::SetTargetNumberOfChannels() {
421 return kNotImplemented;
422}
423
424int NetEqImpl::SetTargetSampleRate() {
425 return kNotImplemented;
426}
427
henrik.lundin@webrtc.orgb0f4b3d2014-11-04 08:53:10 +0000428int NetEqImpl::LastError() const {
Tommi9090e0b2016-01-20 13:39:36 +0100429 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000430 return error_code_;
431}
432
433int NetEqImpl::LastDecoderError() {
Tommi9090e0b2016-01-20 13:39:36 +0100434 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000435 return decoder_error_code_;
436}
437
438void NetEqImpl::FlushBuffers() {
Tommi9090e0b2016-01-20 13:39:36 +0100439 rtc::CritScope lock(&crit_sect_);
Henrik Lundind67a2192015-08-03 12:54:37 +0200440 LOG(LS_VERBOSE) << "FlushBuffers";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000441 packet_buffer_->Flush();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000442 assert(sync_buffer_.get());
443 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000444 sync_buffer_->Flush();
445 sync_buffer_->set_next_index(sync_buffer_->next_index() -
446 expand_->overlap_length());
447 // Set to wait for new codec.
448 first_packet_ = true;
449}
450
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000451void NetEqImpl::PacketBufferStatistics(int* current_num_packets,
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000452 int* max_num_packets) const {
Tommi9090e0b2016-01-20 13:39:36 +0100453 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000454 packet_buffer_->BufferStat(current_num_packets, max_num_packets);
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000455}
456
henrik.lundin48ed9302015-10-29 05:36:24 -0700457void NetEqImpl::EnableNack(size_t max_nack_list_size) {
Tommi9090e0b2016-01-20 13:39:36 +0100458 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700459 if (!nack_enabled_) {
460 const int kNackThresholdPackets = 2;
461 nack_.reset(Nack::Create(kNackThresholdPackets));
462 nack_enabled_ = true;
463 nack_->UpdateSampleRate(fs_hz_);
464 }
465 nack_->SetMaxNackListSize(max_nack_list_size);
466}
467
468void NetEqImpl::DisableNack() {
Tommi9090e0b2016-01-20 13:39:36 +0100469 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700470 nack_.reset();
471 nack_enabled_ = false;
472}
473
474std::vector<uint16_t> NetEqImpl::GetNackList(int64_t round_trip_time_ms) const {
Tommi9090e0b2016-01-20 13:39:36 +0100475 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700476 if (!nack_enabled_) {
477 return std::vector<uint16_t>();
478 }
479 RTC_DCHECK(nack_.get());
480 return nack_->GetNackList(round_trip_time_ms);
minyue@webrtc.orgd7301772013-08-29 00:58:14 +0000481}
482
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000483const SyncBuffer* NetEqImpl::sync_buffer_for_test() const {
Tommi9090e0b2016-01-20 13:39:36 +0100484 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000485 return sync_buffer_.get();
486}
487
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000488// Methods below this line are private.
489
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000490int NetEqImpl::InsertPacketInternal(const WebRtcRTPHeader& rtp_header,
kwibergee2bac22015-11-11 10:34:00 -0800491 rtc::ArrayView<const uint8_t> payload,
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000492 uint32_t receive_timestamp,
493 bool is_sync_packet) {
kwibergee2bac22015-11-11 10:34:00 -0800494 if (payload.empty()) {
495 LOG_F(LS_ERROR) << "payload is empty";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000496 return kInvalidPointer;
497 }
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000498 // Sanity checks for sync-packets.
499 if (is_sync_packet) {
500 if (decoder_database_->IsDtmf(rtp_header.header.payloadType) ||
501 decoder_database_->IsRed(rtp_header.header.payloadType) ||
502 decoder_database_->IsComfortNoise(rtp_header.header.payloadType)) {
503 LOG_F(LS_ERROR) << "Sync-packet with an unacceptable payload type "
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000504 << static_cast<int>(rtp_header.header.payloadType);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000505 return kSyncPacketNotAccepted;
506 }
507 if (first_packet_ ||
508 rtp_header.header.payloadType != current_rtp_payload_type_ ||
509 rtp_header.header.ssrc != ssrc_) {
510 // Even if |current_rtp_payload_type_| is 0xFF, sync-packet isn't
511 // accepted.
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000512 LOG_F(LS_ERROR)
513 << "Changing codec, SSRC or first packet with sync-packet.";
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000514 return kSyncPacketNotAccepted;
515 }
516 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000517 PacketList packet_list;
518 RTPHeader main_header;
519 {
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000520 // Convert to Packet.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000521 // Create |packet| within this separate scope, since it should not be used
522 // directly once it's been inserted in the packet list. This way, |packet|
523 // is not defined outside of this block.
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000524 Packet* packet = new Packet;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000525 packet->header.markerBit = false;
526 packet->header.payloadType = rtp_header.header.payloadType;
527 packet->header.sequenceNumber = rtp_header.header.sequenceNumber;
528 packet->header.timestamp = rtp_header.header.timestamp;
529 packet->header.ssrc = rtp_header.header.ssrc;
530 packet->header.numCSRCs = 0;
kwibergee2bac22015-11-11 10:34:00 -0800531 packet->payload_length = payload.size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000532 packet->primary = true;
533 packet->waiting_time = 0;
534 packet->payload = new uint8_t[packet->payload_length];
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000535 packet->sync_packet = is_sync_packet;
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +0000536 if (!packet->payload) {
537 LOG_F(LS_ERROR) << "Payload pointer is NULL.";
538 }
kwibergee2bac22015-11-11 10:34:00 -0800539 assert(!payload.empty()); // Already checked above.
540 memcpy(packet->payload, payload.data(), packet->payload_length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000541 // Insert packet in a packet list.
542 packet_list.push_back(packet);
543 // Save main payloads header for later.
544 memcpy(&main_header, &packet->header, sizeof(main_header));
545 }
546
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000547 bool update_sample_rate_and_channels = false;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000548 // Reinitialize NetEq if it's needed (changed SSRC or first call).
549 if ((main_header.ssrc != ssrc_) || first_packet_) {
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000550 // Note: |first_packet_| will be cleared further down in this method, once
551 // the packet has been successfully inserted into the packet buffer.
552
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000553 rtcp_.Init(main_header.sequenceNumber);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000554
555 // Flush the packet buffer and DTMF buffer.
556 packet_buffer_->Flush();
557 dtmf_buffer_->Flush();
558
559 // Store new SSRC.
560 ssrc_ = main_header.ssrc;
561
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000562 // Update audio buffer timestamp.
563 sync_buffer_->IncreaseEndTimestamp(main_header.timestamp - timestamp_);
564
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000565 // Update codecs.
566 timestamp_ = main_header.timestamp;
567 current_rtp_payload_type_ = main_header.payloadType;
568
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000569 // Reset timestamp scaling.
570 timestamp_scaler_->Reset();
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000571
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000572 // Trigger an update of sampling rate and the number of channels.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000573 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000574 }
575
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000576 // Update RTCP statistics, only for regular packets.
577 if (!is_sync_packet)
578 rtcp_.Update(main_header, receive_timestamp);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000579
580 // Check for RED payload type, and separate payloads into several packets.
581 if (decoder_database_->IsRed(main_header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000582 assert(!is_sync_packet); // We had a sanity check for this.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000583 if (payload_splitter_->SplitRed(&packet_list) != PayloadSplitter::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000584 PacketBuffer::DeleteAllPackets(&packet_list);
585 return kRedundancySplitError;
586 }
587 // Only accept a few RED payloads of the same type as the main data,
588 // DTMF events and CNG.
589 payload_splitter_->CheckRedPayloads(&packet_list, *decoder_database_);
590 // Update the stored main payload header since the main payload has now
591 // changed.
592 memcpy(&main_header, &packet_list.front()->header, sizeof(main_header));
593 }
594
595 // Check payload types.
596 if (decoder_database_->CheckPayloadTypes(packet_list) ==
597 DecoderDatabase::kDecoderNotFound) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000598 PacketBuffer::DeleteAllPackets(&packet_list);
599 return kUnknownRtpPayloadType;
600 }
601
602 // Scale timestamp to internal domain (only for some codecs).
603 timestamp_scaler_->ToInternal(&packet_list);
604
605 // Process DTMF payloads. Cycle through the list of packets, and pick out any
606 // DTMF payloads found.
607 PacketList::iterator it = packet_list.begin();
608 while (it != packet_list.end()) {
609 Packet* current_packet = (*it);
610 assert(current_packet);
611 assert(current_packet->payload);
612 if (decoder_database_->IsDtmf(current_packet->header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000613 assert(!current_packet->sync_packet); // We had a sanity check for this.
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000614 DtmfEvent event;
615 int ret = DtmfBuffer::ParseEvent(
616 current_packet->header.timestamp,
617 current_packet->payload,
618 current_packet->payload_length,
619 &event);
620 if (ret != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000621 PacketBuffer::DeleteAllPackets(&packet_list);
622 return kDtmfParsingError;
623 }
624 if (dtmf_buffer_->InsertEvent(event) != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000625 PacketBuffer::DeleteAllPackets(&packet_list);
626 return kDtmfInsertError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000627 }
628 // TODO(hlundin): Let the destructor of Packet handle the payload.
629 delete [] current_packet->payload;
630 delete current_packet;
631 it = packet_list.erase(it);
632 } else {
633 ++it;
634 }
635 }
636
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000637 // Check for FEC in packets, and separate payloads into several packets.
638 int ret = payload_splitter_->SplitFec(&packet_list, decoder_database_.get());
639 if (ret != PayloadSplitter::kOK) {
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000640 PacketBuffer::DeleteAllPackets(&packet_list);
641 switch (ret) {
642 case PayloadSplitter::kUnknownPayloadType:
643 return kUnknownRtpPayloadType;
644 default:
645 return kOtherError;
646 }
647 }
648
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000649 // Split payloads into smaller chunks. This also verifies that all payloads
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000650 // are of a known payload type. SplitAudio() method is protected against
651 // sync-packets.
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +0000652 ret = payload_splitter_->SplitAudio(&packet_list, *decoder_database_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000653 if (ret != PayloadSplitter::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000654 PacketBuffer::DeleteAllPackets(&packet_list);
655 switch (ret) {
656 case PayloadSplitter::kUnknownPayloadType:
657 return kUnknownRtpPayloadType;
658 case PayloadSplitter::kFrameSplitError:
659 return kFrameSplitError;
660 default:
661 return kOtherError;
662 }
663 }
664
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000665 // Update bandwidth estimate, if the packet is not sync-packet.
666 if (!packet_list.empty() && !packet_list.front()->sync_packet) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000667 // The list can be empty here if we got nothing but DTMF payloads.
668 AudioDecoder* decoder =
669 decoder_database_->GetDecoder(main_header.payloadType);
670 assert(decoder); // Should always get a valid object, since we have
671 // already checked that the payload types are known.
672 decoder->IncomingPacket(packet_list.front()->payload,
673 packet_list.front()->payload_length,
674 packet_list.front()->header.sequenceNumber,
675 packet_list.front()->header.timestamp,
676 receive_timestamp);
677 }
678
henrik.lundin48ed9302015-10-29 05:36:24 -0700679 if (nack_enabled_) {
680 RTC_DCHECK(nack_);
681 if (update_sample_rate_and_channels) {
682 nack_->Reset();
683 }
684 nack_->UpdateLastReceivedPacket(packet_list.front()->header.sequenceNumber,
685 packet_list.front()->header.timestamp);
686 }
687
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000688 // Insert packets in buffer.
henrik.lundin116c84e2015-08-27 13:14:48 -0700689 const size_t buffer_length_before_insert =
690 packet_buffer_->NumPacketsInBuffer();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000691 ret = packet_buffer_->InsertPacketList(
692 &packet_list,
693 *decoder_database_,
694 &current_rtp_payload_type_,
695 &current_cng_rtp_payload_type_);
696 if (ret == PacketBuffer::kFlushed) {
697 // Reset DSP timestamp etc. if packet buffer flushed.
698 new_codec_ = true;
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000699 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000700 } else if (ret != PacketBuffer::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000701 PacketBuffer::DeleteAllPackets(&packet_list);
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000702 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000703 }
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000704
705 if (first_packet_) {
706 first_packet_ = false;
707 // Update the codec on the next GetAudio call.
708 new_codec_ = true;
709 }
710
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000711 if (current_rtp_payload_type_ != 0xFF) {
712 const DecoderDatabase::DecoderInfo* dec_info =
713 decoder_database_->GetDecoderInfo(current_rtp_payload_type_);
714 if (!dec_info) {
715 assert(false); // Already checked that the payload type is known.
716 }
717 }
718
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000719 if (update_sample_rate_and_channels && !packet_buffer_->Empty()) {
720 // We do not use |current_rtp_payload_type_| to |set payload_type|, but
721 // get the next RTP header from |packet_buffer_| to obtain the payload type.
722 // The reason for it is the following corner case. If NetEq receives a
723 // CNG packet with a sample rate different than the current CNG then it
724 // flushes its buffer, assuming send codec must have been changed. However,
725 // payload type of the hypothetically new send codec is not known.
726 const RTPHeader* rtp_header = packet_buffer_->NextRtpHeader();
727 assert(rtp_header);
728 int payload_type = rtp_header->payloadType;
729 AudioDecoder* decoder = decoder_database_->GetDecoder(payload_type);
730 assert(decoder); // Payloads are already checked to be valid.
731 const DecoderDatabase::DecoderInfo* decoder_info =
732 decoder_database_->GetDecoderInfo(payload_type);
733 assert(decoder_info);
734 if (decoder_info->fs_hz != fs_hz_ ||
henrik.lundin48ed9302015-10-29 05:36:24 -0700735 decoder->Channels() != algorithm_buffer_->Channels()) {
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +0000736 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->Channels());
henrik.lundin48ed9302015-10-29 05:36:24 -0700737 }
738 if (nack_enabled_) {
739 RTC_DCHECK(nack_);
740 // Update the sample rate even if the rate is not new, because of Reset().
741 nack_->UpdateSampleRate(fs_hz_);
742 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000743 }
744
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000745 // TODO(hlundin): Move this code to DelayManager class.
746 const DecoderDatabase::DecoderInfo* dec_info =
747 decoder_database_->GetDecoderInfo(main_header.payloadType);
748 assert(dec_info); // Already checked that the payload type is known.
749 delay_manager_->LastDecoderType(dec_info->codec_type);
750 if (delay_manager_->last_pack_cng_or_dtmf() == 0) {
751 // Calculate the total speech length carried in each packet.
henrik.lundin116c84e2015-08-27 13:14:48 -0700752 const size_t buffer_length_after_insert =
753 packet_buffer_->NumPacketsInBuffer();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000754
henrik.lundin116c84e2015-08-27 13:14:48 -0700755 if (buffer_length_after_insert > buffer_length_before_insert) {
756 const size_t packet_length_samples =
757 (buffer_length_after_insert - buffer_length_before_insert) *
758 decoder_frame_length_;
759 if (packet_length_samples != decision_logic_->packet_length_samples()) {
760 decision_logic_->set_packet_length_samples(packet_length_samples);
761 delay_manager_->SetPacketAudioLength(
762 rtc::checked_cast<int>((1000 * packet_length_samples) / fs_hz_));
763 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000764 }
765
766 // Update statistics.
pbos@webrtc.org0946a562013-04-09 00:28:06 +0000767 if ((int32_t) (main_header.timestamp - timestamp_) >= 0 &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000768 !new_codec_) {
769 // Only update statistics if incoming packet is not older than last played
770 // out packet, and if new codec flag is not set.
771 delay_manager_->Update(main_header.sequenceNumber, main_header.timestamp,
772 fs_hz_);
773 }
774 } else if (delay_manager_->last_pack_cng_or_dtmf() == -1) {
775 // This is first "normal" packet after CNG or DTMF.
776 // Reset packet time counter and measure time until next packet,
777 // but don't update statistics.
778 delay_manager_->set_last_pack_cng_or_dtmf(0);
779 delay_manager_->ResetPacketIatCount();
780 }
781 return 0;
782}
783
henrik.lundin6d8e0112016-03-04 10:34:21 -0800784int NetEqImpl::GetAudioInternal(AudioFrame* audio_frame) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000785 PacketList packet_list;
786 DtmfEvent dtmf_event;
787 Operations operation;
788 bool play_dtmf;
789 int return_value = GetDecision(&operation, &packet_list, &dtmf_event,
790 &play_dtmf);
791 if (return_value != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000792 last_mode_ = kModeError;
793 return return_value;
794 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000795
796 AudioDecoder::SpeechType speech_type;
797 int length = 0;
798 int decode_return_value = Decode(&packet_list, &operation,
799 &length, &speech_type);
800
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000801 assert(vad_.get());
802 bool sid_frame_available =
803 (operation == kRfc3389Cng && !packet_list.empty());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700804 vad_->Update(decoded_buffer_.get(), static_cast<size_t>(length), speech_type,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000805 sid_frame_available, fs_hz_);
806
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000807 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000808 switch (operation) {
809 case kNormal: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000810 DoNormal(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000811 break;
812 }
813 case kMerge: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000814 DoMerge(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000815 break;
816 }
817 case kExpand: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000818 return_value = DoExpand(play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000819 break;
820 }
Henrik Lundincf808d22015-05-27 14:33:29 +0200821 case kAccelerate:
822 case kFastAccelerate: {
823 const bool fast_accelerate =
824 enable_fast_accelerate_ && (operation == kFastAccelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000825 return_value = DoAccelerate(decoded_buffer_.get(), length, speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +0200826 play_dtmf, fast_accelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000827 break;
828 }
829 case kPreemptiveExpand: {
830 return_value = DoPreemptiveExpand(decoded_buffer_.get(), length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000831 speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000832 break;
833 }
834 case kRfc3389Cng:
835 case kRfc3389CngNoPacket: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000836 return_value = DoRfc3389Cng(&packet_list, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000837 break;
838 }
839 case kCodecInternalCng: {
840 // This handles the case when there is no transmission and the decoder
841 // should produce internal comfort noise.
842 // TODO(hlundin): Write test for codec-internal CNG.
minyuel6d92bf52015-09-23 15:20:39 +0200843 DoCodecInternalCng(decoded_buffer_.get(), length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000844 break;
845 }
846 case kDtmf: {
847 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000848 return_value = DoDtmf(dtmf_event, &play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000849 break;
850 }
851 case kAlternativePlc: {
852 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000853 DoAlternativePlc(false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000854 break;
855 }
856 case kAlternativePlcIncreaseTimestamp: {
857 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000858 DoAlternativePlc(true);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000859 break;
860 }
861 case kAudioRepetitionIncreaseTimestamp: {
862 // TODO(hlundin): Write test for this.
Peter Kastingb7e50542015-06-11 12:55:50 -0700863 sync_buffer_->IncreaseEndTimestamp(
864 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000865 // Skipping break on purpose. Execution should move on into the
866 // next case.
kjellander@webrtc.org7d2b6a92015-01-28 18:37:58 +0000867 FALLTHROUGH();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000868 }
869 case kAudioRepetition: {
870 // TODO(hlundin): Write test for this.
871 // Copy last |output_size_samples_| from |sync_buffer_| to
872 // |algorithm_buffer|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000873 algorithm_buffer_->PushBackFromIndex(
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000874 *sync_buffer_, sync_buffer_->Size() - output_size_samples_);
875 expand_->Reset();
876 break;
877 }
878 case kUndefined: {
Henrik Lundind67a2192015-08-03 12:54:37 +0200879 LOG(LS_ERROR) << "Invalid operation kUndefined.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000880 assert(false); // This should not happen.
881 last_mode_ = kModeError;
882 return kInvalidOperation;
883 }
884 } // End of switch.
885 if (return_value < 0) {
886 return return_value;
887 }
888
889 if (last_mode_ != kModeRfc3389Cng) {
890 comfort_noise_->Reset();
891 }
892
893 // Copy from |algorithm_buffer| to |sync_buffer_|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000894 sync_buffer_->PushBack(*algorithm_buffer_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000895
896 // Extract data from |sync_buffer_| to |output|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000897 size_t num_output_samples_per_channel = output_size_samples_;
898 size_t num_output_samples = output_size_samples_ * sync_buffer_->Channels();
henrik.lundin6d8e0112016-03-04 10:34:21 -0800899 if (num_output_samples > AudioFrame::kMaxDataSizeSamples) {
900 LOG(LS_WARNING) << "Output array is too short. "
901 << AudioFrame::kMaxDataSizeSamples << " < "
902 << output_size_samples_ << " * "
903 << sync_buffer_->Channels();
904 num_output_samples = AudioFrame::kMaxDataSizeSamples;
905 num_output_samples_per_channel =
906 AudioFrame::kMaxDataSizeSamples / sync_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000907 }
henrik.lundin6d8e0112016-03-04 10:34:21 -0800908 sync_buffer_->GetNextAudioInterleaved(num_output_samples_per_channel,
909 audio_frame);
910 audio_frame->sample_rate_hz_ = fs_hz_;
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200911 if (sync_buffer_->FutureLength() < expand_->overlap_length()) {
912 // The sync buffer should always contain |overlap_length| samples, but now
913 // too many samples have been extracted. Reinstall the |overlap_length|
914 // lookahead by moving the index.
915 const size_t missing_lookahead_samples =
916 expand_->overlap_length() - sync_buffer_->FutureLength();
henrikg91d6ede2015-09-17 00:24:34 -0700917 RTC_DCHECK_GE(sync_buffer_->next_index(), missing_lookahead_samples);
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200918 sync_buffer_->set_next_index(sync_buffer_->next_index() -
919 missing_lookahead_samples);
920 }
henrik.lundin6d8e0112016-03-04 10:34:21 -0800921 if (audio_frame->samples_per_channel_ != output_size_samples_) {
922 LOG(LS_ERROR) << "audio_frame->samples_per_channel_ ("
923 << audio_frame->samples_per_channel_
Henrik Lundind67a2192015-08-03 12:54:37 +0200924 << ") != output_size_samples_ (" << output_size_samples_
925 << ")";
minyue@webrtc.orgdb1cefc2013-08-13 01:39:21 +0000926 // TODO(minyue): treatment of under-run, filling zeros
henrik.lundin6d8e0112016-03-04 10:34:21 -0800927 memset(audio_frame->data_, 0, num_output_samples * sizeof(int16_t));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000928 return kSampleUnderrun;
929 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000930
931 // Should always have overlap samples left in the |sync_buffer_|.
henrikg91d6ede2015-09-17 00:24:34 -0700932 RTC_DCHECK_GE(sync_buffer_->FutureLength(), expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000933
934 if (play_dtmf) {
henrik.lundin6d8e0112016-03-04 10:34:21 -0800935 return_value =
936 DtmfOverdub(dtmf_event, sync_buffer_->Channels(), audio_frame->data_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000937 }
938
939 // Update the background noise parameters if last operation wrote data
940 // straight from the decoder to the |sync_buffer_|. That is, none of the
941 // operations that modify the signal can be followed by a parameter update.
942 if ((last_mode_ == kModeNormal) ||
943 (last_mode_ == kModeAccelerateFail) ||
944 (last_mode_ == kModePreemptiveExpandFail) ||
945 (last_mode_ == kModeRfc3389Cng) ||
946 (last_mode_ == kModeCodecInternalCng)) {
947 background_noise_->Update(*sync_buffer_, *vad_.get());
948 }
949
950 if (operation == kDtmf) {
951 // DTMF data was written the end of |sync_buffer_|.
952 // Update index to end of DTMF data in |sync_buffer_|.
953 sync_buffer_->set_dtmf_index(sync_buffer_->Size());
954 }
955
henrik.lundin@webrtc.orged865b52014-03-06 10:28:07 +0000956 if (last_mode_ != kModeExpand) {
957 // If last operation was not expand, calculate the |playout_timestamp_| from
958 // the |sync_buffer_|. However, do not update the |playout_timestamp_| if it
959 // would be moved "backwards".
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000960 uint32_t temp_timestamp = sync_buffer_->end_timestamp() -
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000961 static_cast<uint32_t>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000962 if (static_cast<int32_t>(temp_timestamp - playout_timestamp_) > 0) {
963 playout_timestamp_ = temp_timestamp;
964 }
965 } else {
966 // Use dead reckoning to estimate the |playout_timestamp_|.
Peter Kastingb7e50542015-06-11 12:55:50 -0700967 playout_timestamp_ += static_cast<uint32_t>(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000968 }
969
970 if (decode_return_value) return decode_return_value;
971 return return_value;
972}
973
974int NetEqImpl::GetDecision(Operations* operation,
975 PacketList* packet_list,
976 DtmfEvent* dtmf_event,
977 bool* play_dtmf) {
978 // Initialize output variables.
979 *play_dtmf = false;
980 *operation = kUndefined;
981
982 // Increment time counters.
983 packet_buffer_->IncrementWaitingTimes();
984 stats_.IncreaseCounter(output_size_samples_, fs_hz_);
985
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000986 assert(sync_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000987 uint32_t end_timestamp = sync_buffer_->end_timestamp();
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +0000988 if (!new_codec_) {
989 const uint32_t five_seconds_samples = 5 * fs_hz_;
990 packet_buffer_->DiscardOldPackets(end_timestamp, five_seconds_samples);
991 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000992 const RTPHeader* header = packet_buffer_->NextRtpHeader();
993
henrik.lundin@webrtc.orgca8cb952014-03-12 10:26:52 +0000994 if (decision_logic_->CngRfc3389On() || last_mode_ == kModeRfc3389Cng) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000995 // Because of timestamp peculiarities, we have to "manually" disallow using
996 // a CNG packet with the same timestamp as the one that was last played.
997 // This can happen when using redundancy and will cause the timing to shift.
henrik.lundin@webrtc.org24779fe2014-03-14 12:40:05 +0000998 while (header && decoder_database_->IsComfortNoise(header->payloadType) &&
999 (end_timestamp >= header->timestamp ||
1000 end_timestamp + decision_logic_->generated_noise_samples() >
1001 header->timestamp)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001002 // Don't use this packet, discard it.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001003 if (packet_buffer_->DiscardNextPacket() != PacketBuffer::kOK) {
1004 assert(false); // Must be ok by design.
1005 }
1006 // Check buffer again.
1007 if (!new_codec_) {
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001008 packet_buffer_->DiscardOldPackets(end_timestamp, 5 * fs_hz_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001009 }
1010 header = packet_buffer_->NextRtpHeader();
1011 }
1012 }
1013
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001014 assert(expand_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001015 const int samples_left = static_cast<int>(sync_buffer_->FutureLength() -
1016 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001017 if (last_mode_ == kModeAccelerateSuccess ||
1018 last_mode_ == kModeAccelerateLowEnergy ||
1019 last_mode_ == kModePreemptiveExpandSuccess ||
1020 last_mode_ == kModePreemptiveExpandLowEnergy) {
1021 // Subtract (samples_left + output_size_samples_) from sampleMemory.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001022 decision_logic_->AddSampleMemory(
1023 -(samples_left + rtc::checked_cast<int>(output_size_samples_)));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001024 }
1025
1026 // Check if it is time to play a DTMF event.
Peter Kastingb7e50542015-06-11 12:55:50 -07001027 if (dtmf_buffer_->GetEvent(
1028 static_cast<uint32_t>(
1029 end_timestamp + decision_logic_->generated_noise_samples()),
1030 dtmf_event)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001031 *play_dtmf = true;
1032 }
1033
1034 // Get instruction.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001035 assert(sync_buffer_.get());
1036 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001037 *operation = decision_logic_->GetDecision(*sync_buffer_,
1038 *expand_,
1039 decoder_frame_length_,
1040 header,
1041 last_mode_,
1042 *play_dtmf,
1043 &reset_decoder_);
1044
1045 // Check if we already have enough samples in the |sync_buffer_|. If so,
1046 // change decision to normal, unless the decision was merge, accelerate, or
1047 // preemptive expand.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001048 if (samples_left >= rtc::checked_cast<int>(output_size_samples_) &&
1049 *operation != kMerge &&
1050 *operation != kAccelerate &&
1051 *operation != kFastAccelerate &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001052 *operation != kPreemptiveExpand) {
1053 *operation = kNormal;
1054 return 0;
1055 }
1056
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001057 decision_logic_->ExpandDecision(*operation);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001058
1059 // Check conditions for reset.
1060 if (new_codec_ || *operation == kUndefined) {
1061 // The only valid reason to get kUndefined is that new_codec_ is set.
1062 assert(new_codec_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001063 if (*play_dtmf && !header) {
1064 timestamp_ = dtmf_event->timestamp;
1065 } else {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001066 if (!header) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001067 LOG(LS_ERROR) << "Packet missing where it shouldn't.";
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001068 return -1;
1069 }
1070 timestamp_ = header->timestamp;
1071 if (*operation == kRfc3389CngNoPacket
1072#ifndef LEGACY_BITEXACT
1073 // Without this check, it can happen that a non-CNG packet is sent to
1074 // the CNG decoder as if it was a SID frame. This is clearly a bug,
1075 // but is kept for now to maintain bit-exactness with the test
1076 // vectors.
1077 && decoder_database_->IsComfortNoise(header->payloadType)
1078#endif
1079 ) {
1080 // Change decision to CNG packet, since we do have a CNG packet, but it
1081 // was considered too early to use. Now, use it anyway.
1082 *operation = kRfc3389Cng;
1083 } else if (*operation != kRfc3389Cng) {
1084 *operation = kNormal;
1085 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001086 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001087 // Adjust |sync_buffer_| timestamp before setting |end_timestamp| to the
1088 // new value.
1089 sync_buffer_->IncreaseEndTimestamp(timestamp_ - end_timestamp);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001090 end_timestamp = timestamp_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001091 new_codec_ = false;
1092 decision_logic_->SoftReset();
1093 buffer_level_filter_->Reset();
1094 delay_manager_->Reset();
1095 stats_.ResetMcu();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001096 }
1097
Peter Kastingdce40cf2015-08-24 14:52:23 -07001098 size_t required_samples = output_size_samples_;
1099 const size_t samples_10_ms = static_cast<size_t>(80 * fs_mult_);
1100 const size_t samples_20_ms = 2 * samples_10_ms;
1101 const size_t samples_30_ms = 3 * samples_10_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001102
1103 switch (*operation) {
1104 case kExpand: {
1105 timestamp_ = end_timestamp;
1106 return 0;
1107 }
1108 case kRfc3389CngNoPacket:
1109 case kCodecInternalCng: {
1110 return 0;
1111 }
1112 case kDtmf: {
1113 // TODO(hlundin): Write test for this.
1114 // Update timestamp.
1115 timestamp_ = end_timestamp;
1116 if (decision_logic_->generated_noise_samples() > 0 &&
1117 last_mode_ != kModeDtmf) {
1118 // Make a jump in timestamp due to the recently played comfort noise.
Peter Kastingb7e50542015-06-11 12:55:50 -07001119 uint32_t timestamp_jump =
1120 static_cast<uint32_t>(decision_logic_->generated_noise_samples());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001121 sync_buffer_->IncreaseEndTimestamp(timestamp_jump);
1122 timestamp_ += timestamp_jump;
1123 }
1124 decision_logic_->set_generated_noise_samples(0);
1125 return 0;
1126 }
Henrik Lundincf808d22015-05-27 14:33:29 +02001127 case kAccelerate:
1128 case kFastAccelerate: {
1129 // In order to do an accelerate we need at least 30 ms of audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001130 if (samples_left >= static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001131 // Already have enough data, so we do not need to extract any more.
1132 decision_logic_->set_sample_memory(samples_left);
1133 decision_logic_->set_prev_time_scale(true);
1134 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001135 } else if (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001136 decoder_frame_length_ >= samples_30_ms) {
1137 // Avoid decoding more data as it might overflow the playout buffer.
1138 *operation = kNormal;
1139 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001140 } else if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001141 decoder_frame_length_ < samples_30_ms) {
1142 // Build up decoded data by decoding at least 20 ms of audio data. Do
1143 // not perform accelerate yet, but wait until we only need to do one
1144 // decoding.
1145 required_samples = 2 * output_size_samples_;
1146 *operation = kNormal;
1147 }
1148 // If none of the above is true, we have one of two possible situations:
1149 // (1) 20 ms <= samples_left < 30 ms and decoder_frame_length_ < 30 ms; or
1150 // (2) samples_left < 10 ms and decoder_frame_length_ >= 30 ms.
1151 // In either case, we move on with the accelerate decision, and decode one
1152 // frame now.
1153 break;
1154 }
1155 case kPreemptiveExpand: {
1156 // In order to do a preemptive expand we need at least 30 ms of decoded
1157 // audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001158 if ((samples_left >= static_cast<int>(samples_30_ms)) ||
1159 (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001160 decoder_frame_length_ >= samples_30_ms)) {
1161 // Already have enough data, so we do not need to extract any more.
1162 // Or, avoid decoding more data as it might overflow the playout buffer.
1163 // Still try preemptive expand, though.
1164 decision_logic_->set_sample_memory(samples_left);
1165 decision_logic_->set_prev_time_scale(true);
1166 return 0;
1167 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07001168 if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001169 decoder_frame_length_ < samples_30_ms) {
1170 // Build up decoded data by decoding at least 20 ms of audio data.
1171 // Still try to perform preemptive expand.
1172 required_samples = 2 * output_size_samples_;
1173 }
1174 // Move on with the preemptive expand decision.
1175 break;
1176 }
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001177 case kMerge: {
1178 required_samples =
1179 std::max(merge_->RequiredFutureSamples(), required_samples);
1180 break;
1181 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001182 default: {
1183 // Do nothing.
1184 }
1185 }
1186
1187 // Get packets from buffer.
1188 int extracted_samples = 0;
1189 if (header &&
1190 *operation != kAlternativePlc &&
1191 *operation != kAlternativePlcIncreaseTimestamp &&
1192 *operation != kAudioRepetition &&
1193 *operation != kAudioRepetitionIncreaseTimestamp) {
1194 sync_buffer_->IncreaseEndTimestamp(header->timestamp - end_timestamp);
1195 if (decision_logic_->CngOff()) {
1196 // Adjustment of timestamp only corresponds to an actual packet loss
1197 // if comfort noise is not played. If comfort noise was just played,
1198 // this adjustment of timestamp is only done to get back in sync with the
1199 // stream timestamp; no loss to report.
1200 stats_.LostSamples(header->timestamp - end_timestamp);
1201 }
1202
1203 if (*operation != kRfc3389Cng) {
1204 // We are about to decode and use a non-CNG packet.
1205 decision_logic_->SetCngOff();
1206 }
1207 // Reset CNG timestamp as a new packet will be delivered.
1208 // (Also if this is a CNG packet, since playedOutTS is updated.)
1209 decision_logic_->set_generated_noise_samples(0);
1210
1211 extracted_samples = ExtractPackets(required_samples, packet_list);
1212 if (extracted_samples < 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001213 return kPacketBufferCorruption;
1214 }
1215 }
1216
Henrik Lundincf808d22015-05-27 14:33:29 +02001217 if (*operation == kAccelerate || *operation == kFastAccelerate ||
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001218 *operation == kPreemptiveExpand) {
1219 decision_logic_->set_sample_memory(samples_left + extracted_samples);
1220 decision_logic_->set_prev_time_scale(true);
1221 }
1222
Henrik Lundincf808d22015-05-27 14:33:29 +02001223 if (*operation == kAccelerate || *operation == kFastAccelerate) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001224 // Check that we have enough data (30ms) to do accelerate.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001225 if (extracted_samples + samples_left < static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001226 // TODO(hlundin): Write test for this.
1227 // Not enough, do normal operation instead.
1228 *operation = kNormal;
1229 }
1230 }
1231
1232 timestamp_ = end_timestamp;
1233 return 0;
1234}
1235
1236int NetEqImpl::Decode(PacketList* packet_list, Operations* operation,
1237 int* decoded_length,
1238 AudioDecoder::SpeechType* speech_type) {
1239 *speech_type = AudioDecoder::kSpeech;
minyuel6d92bf52015-09-23 15:20:39 +02001240
1241 // When packet_list is empty, we may be in kCodecInternalCng mode, and for
1242 // that we use current active decoder.
1243 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1244
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001245 if (!packet_list->empty()) {
1246 const Packet* packet = packet_list->front();
pkasting@chromium.org0e81fdf2015-02-02 23:54:03 +00001247 uint8_t payload_type = packet->header.payloadType;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001248 if (!decoder_database_->IsComfortNoise(payload_type)) {
1249 decoder = decoder_database_->GetDecoder(payload_type);
1250 assert(decoder);
1251 if (!decoder) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001252 LOG(LS_WARNING) << "Unknown payload type "
1253 << static_cast<int>(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001254 PacketBuffer::DeleteAllPackets(packet_list);
1255 return kDecoderNotFound;
1256 }
1257 bool decoder_changed;
1258 decoder_database_->SetActiveDecoder(payload_type, &decoder_changed);
1259 if (decoder_changed) {
1260 // We have a new decoder. Re-init some values.
1261 const DecoderDatabase::DecoderInfo* decoder_info = decoder_database_
1262 ->GetDecoderInfo(payload_type);
1263 assert(decoder_info);
1264 if (!decoder_info) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001265 LOG(LS_WARNING) << "Unknown payload type "
1266 << static_cast<int>(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001267 PacketBuffer::DeleteAllPackets(packet_list);
1268 return kDecoderNotFound;
1269 }
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001270 // If sampling rate or number of channels has changed, we need to make
1271 // a reset.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001272 if (decoder_info->fs_hz != fs_hz_ ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001273 decoder->Channels() != algorithm_buffer_->Channels()) {
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001274 // TODO(tlegrand): Add unittest to cover this event.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001275 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->Channels());
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001276 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001277 sync_buffer_->set_end_timestamp(timestamp_);
1278 playout_timestamp_ = timestamp_;
1279 }
1280 }
1281 }
1282
1283 if (reset_decoder_) {
1284 // TODO(hlundin): Write test for this.
Karl Wiberg43766482015-08-27 15:22:11 +02001285 if (decoder)
1286 decoder->Reset();
1287
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001288 // Reset comfort noise decoder.
1289 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02001290 if (cng_decoder)
1291 cng_decoder->Reset();
1292
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001293 reset_decoder_ = false;
1294 }
1295
1296#ifdef LEGACY_BITEXACT
1297 // Due to a bug in old SignalMCU, it could happen that CNG operation was
1298 // decided, but a speech packet was provided. The speech packet will be used
1299 // to update the comfort noise decoder, as if it was a SID frame, which is
1300 // clearly wrong.
1301 if (*operation == kRfc3389Cng) {
1302 return 0;
1303 }
1304#endif
1305
1306 *decoded_length = 0;
1307 // Update codec-internal PLC state.
1308 if ((*operation == kMerge) && decoder && decoder->HasDecodePlc()) {
1309 decoder->DecodePlc(1, &decoded_buffer_[*decoded_length]);
1310 }
1311
minyuel6d92bf52015-09-23 15:20:39 +02001312 int return_value;
1313 if (*operation == kCodecInternalCng) {
1314 RTC_DCHECK(packet_list->empty());
1315 return_value = DecodeCng(decoder, decoded_length, speech_type);
1316 } else {
1317 return_value = DecodeLoop(packet_list, *operation, decoder,
1318 decoded_length, speech_type);
1319 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001320
1321 if (*decoded_length < 0) {
1322 // Error returned from the decoder.
1323 *decoded_length = 0;
Peter Kastingb7e50542015-06-11 12:55:50 -07001324 sync_buffer_->IncreaseEndTimestamp(
1325 static_cast<uint32_t>(decoder_frame_length_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001326 int error_code = 0;
1327 if (decoder)
1328 error_code = decoder->ErrorCode();
1329 if (error_code != 0) {
1330 // Got some error code from the decoder.
1331 decoder_error_code_ = error_code;
1332 return_value = kDecoderErrorCode;
Henrik Lundind67a2192015-08-03 12:54:37 +02001333 LOG(LS_WARNING) << "Decoder returned error code: " << error_code;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001334 } else {
1335 // Decoder does not implement error codes. Return generic error.
1336 return_value = kOtherDecoderError;
Henrik Lundind67a2192015-08-03 12:54:37 +02001337 LOG(LS_WARNING) << "Decoder error (no error code)";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001338 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001339 *operation = kExpand; // Do expansion to get data instead.
1340 }
1341 if (*speech_type != AudioDecoder::kComfortNoise) {
1342 // Don't increment timestamp if codec returned CNG speech type
1343 // since in this case, the we will increment the CNGplayedTS counter.
1344 // Increase with number of samples per channel.
1345 assert(*decoded_length == 0 ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001346 (decoder && decoder->Channels() == sync_buffer_->Channels()));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001347 sync_buffer_->IncreaseEndTimestamp(
1348 *decoded_length / static_cast<int>(sync_buffer_->Channels()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001349 }
1350 return return_value;
1351}
1352
minyuel6d92bf52015-09-23 15:20:39 +02001353int NetEqImpl::DecodeCng(AudioDecoder* decoder, int* decoded_length,
1354 AudioDecoder::SpeechType* speech_type) {
1355 if (!decoder) {
1356 // This happens when active decoder is not defined.
1357 *decoded_length = -1;
1358 return 0;
1359 }
1360
1361 while (*decoded_length < rtc::checked_cast<int>(output_size_samples_)) {
1362 const int length = decoder->Decode(
1363 nullptr, 0, fs_hz_,
1364 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1365 &decoded_buffer_[*decoded_length], speech_type);
1366 if (length > 0) {
1367 *decoded_length += length;
minyuel6d92bf52015-09-23 15:20:39 +02001368 } else {
1369 // Error.
1370 LOG(LS_WARNING) << "Failed to decode CNG";
1371 *decoded_length = -1;
1372 break;
1373 }
1374 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1375 // Guard against overflow.
1376 LOG(LS_WARNING) << "Decoded too much CNG.";
1377 return kDecodedTooMuch;
1378 }
1379 }
1380 return 0;
1381}
1382
1383int NetEqImpl::DecodeLoop(PacketList* packet_list, const Operations& operation,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001384 AudioDecoder* decoder, int* decoded_length,
1385 AudioDecoder::SpeechType* speech_type) {
1386 Packet* packet = NULL;
1387 if (!packet_list->empty()) {
1388 packet = packet_list->front();
1389 }
minyuel6d92bf52015-09-23 15:20:39 +02001390
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001391 // Do decoding.
1392 while (packet &&
1393 !decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1394 assert(decoder); // At this point, we must have a decoder object.
1395 // The number of channels in the |sync_buffer_| should be the same as the
1396 // number decoder channels.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001397 assert(sync_buffer_->Channels() == decoder->Channels());
1398 assert(decoded_buffer_length_ >= kMaxFrameSize * decoder->Channels());
minyuel6d92bf52015-09-23 15:20:39 +02001399 assert(operation == kNormal || operation == kAccelerate ||
1400 operation == kFastAccelerate || operation == kMerge ||
1401 operation == kPreemptiveExpand);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001402 packet_list->pop_front();
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001403 size_t payload_length = packet->payload_length;
Peter Kasting36b7cc32015-06-11 19:57:18 -07001404 int decode_length;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +00001405 if (packet->sync_packet) {
1406 // Decode to silence with the same frame size as the last decode.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001407 memset(&decoded_buffer_[*decoded_length], 0,
1408 decoder_frame_length_ * decoder->Channels() *
1409 sizeof(decoded_buffer_[0]));
Peter Kastingdce40cf2015-08-24 14:52:23 -07001410 decode_length = rtc::checked_cast<int>(decoder_frame_length_);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +00001411 } else if (!packet->primary) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001412 // This is a redundant payload; call the special decoder method.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001413 decode_length = decoder->DecodeRedundant(
henrik.lundin@webrtc.org1eda4e32015-02-25 10:02:29 +00001414 packet->payload, packet->payload_length, fs_hz_,
minyue@webrtc.org7f7d7e32015-03-16 12:30:37 +00001415 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001416 &decoded_buffer_[*decoded_length], speech_type);
1417 } else {
henrik.lundin@webrtc.org1eda4e32015-02-25 10:02:29 +00001418 decode_length =
minyue@webrtc.org7f7d7e32015-03-16 12:30:37 +00001419 decoder->Decode(
1420 packet->payload, packet->payload_length, fs_hz_,
1421 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1422 &decoded_buffer_[*decoded_length], speech_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001423 }
1424
1425 delete[] packet->payload;
1426 delete packet;
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001427 packet = NULL;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001428 if (decode_length > 0) {
1429 *decoded_length += decode_length;
1430 // Update |decoder_frame_length_| with number of samples per channel.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001431 decoder_frame_length_ =
Peter Kastingdce40cf2015-08-24 14:52:23 -07001432 static_cast<size_t>(decode_length) / decoder->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001433 } else if (decode_length < 0) {
1434 // Error.
Henrik Lundind67a2192015-08-03 12:54:37 +02001435 LOG(LS_WARNING) << "Decode " << decode_length << " " << payload_length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001436 *decoded_length = -1;
1437 PacketBuffer::DeleteAllPackets(packet_list);
1438 break;
1439 }
1440 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1441 // Guard against overflow.
Henrik Lundind67a2192015-08-03 12:54:37 +02001442 LOG(LS_WARNING) << "Decoded too much.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001443 PacketBuffer::DeleteAllPackets(packet_list);
1444 return kDecodedTooMuch;
1445 }
1446 if (!packet_list->empty()) {
1447 packet = packet_list->front();
1448 } else {
1449 packet = NULL;
1450 }
1451 } // End of decode loop.
1452
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001453 // If the list is not empty at this point, either a decoding error terminated
1454 // the while-loop, or list must hold exactly one CNG packet.
1455 assert(packet_list->empty() || *decoded_length < 0 ||
1456 (packet_list->size() == 1 && packet &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001457 decoder_database_->IsComfortNoise(packet->header.payloadType)));
1458 return 0;
1459}
1460
1461void NetEqImpl::DoNormal(const int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001462 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001463 assert(normal_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001464 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001465 normal_->Process(decoded_buffer, decoded_length, last_mode_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001466 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001467 if (decoded_length != 0) {
1468 last_mode_ = kModeNormal;
1469 }
1470
1471 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1472 if ((speech_type == AudioDecoder::kComfortNoise)
1473 || ((last_mode_ == kModeCodecInternalCng)
1474 && (decoded_length == 0))) {
1475 // TODO(hlundin): Remove second part of || statement above.
1476 last_mode_ = kModeCodecInternalCng;
1477 }
1478
1479 if (!play_dtmf) {
1480 dtmf_tone_generator_->Reset();
1481 }
1482}
1483
1484void NetEqImpl::DoMerge(int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001485 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001486 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001487 assert(merge_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001488 size_t new_length = merge_->Process(decoded_buffer, decoded_length,
1489 mute_factor_array_.get(),
1490 algorithm_buffer_.get());
1491 size_t expand_length_correction = new_length -
1492 decoded_length / algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001493
1494 // Update in-call and post-call statistics.
1495 if (expand_->MuteFactor(0) == 0) {
1496 // Expand generates only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001497 stats_.ExpandedNoiseSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001498 } else {
1499 // Expansion generates more than only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001500 stats_.ExpandedVoiceSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001501 }
1502
1503 last_mode_ = kModeMerge;
1504 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1505 if (speech_type == AudioDecoder::kComfortNoise) {
1506 last_mode_ = kModeCodecInternalCng;
1507 }
1508 expand_->Reset();
1509 if (!play_dtmf) {
1510 dtmf_tone_generator_->Reset();
1511 }
1512}
1513
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001514int NetEqImpl::DoExpand(bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001515 while ((sync_buffer_->FutureLength() - expand_->overlap_length()) <
Peter Kastingdce40cf2015-08-24 14:52:23 -07001516 output_size_samples_) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001517 algorithm_buffer_->Clear();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001518 int return_value = expand_->Process(algorithm_buffer_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001519 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001520
1521 // Update in-call and post-call statistics.
1522 if (expand_->MuteFactor(0) == 0) {
1523 // Expand operation generates only noise.
1524 stats_.ExpandedNoiseSamples(length);
1525 } else {
1526 // Expand operation generates more than only noise.
1527 stats_.ExpandedVoiceSamples(length);
1528 }
1529
1530 last_mode_ = kModeExpand;
1531
1532 if (return_value < 0) {
1533 return return_value;
1534 }
1535
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001536 sync_buffer_->PushBack(*algorithm_buffer_);
1537 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001538 }
1539 if (!play_dtmf) {
1540 dtmf_tone_generator_->Reset();
1541 }
1542 return 0;
1543}
1544
Henrik Lundincf808d22015-05-27 14:33:29 +02001545int NetEqImpl::DoAccelerate(int16_t* decoded_buffer,
1546 size_t decoded_length,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001547 AudioDecoder::SpeechType speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +02001548 bool play_dtmf,
1549 bool fast_accelerate) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001550 const size_t required_samples =
1551 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001552 size_t borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001553 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001554 size_t decoded_length_per_channel = decoded_length / num_channels;
1555 if (decoded_length_per_channel < required_samples) {
1556 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001557 borrowed_samples_per_channel = static_cast<int>(required_samples -
1558 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001559 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1560 decoded_buffer,
1561 sizeof(int16_t) * decoded_length);
1562 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1563 decoded_buffer);
1564 decoded_length = required_samples * num_channels;
1565 }
1566
Peter Kastingdce40cf2015-08-24 14:52:23 -07001567 size_t samples_removed;
Henrik Lundincf808d22015-05-27 14:33:29 +02001568 Accelerate::ReturnCodes return_code =
1569 accelerate_->Process(decoded_buffer, decoded_length, fast_accelerate,
1570 algorithm_buffer_.get(), &samples_removed);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001571 stats_.AcceleratedSamples(samples_removed);
1572 switch (return_code) {
1573 case Accelerate::kSuccess:
1574 last_mode_ = kModeAccelerateSuccess;
1575 break;
1576 case Accelerate::kSuccessLowEnergy:
1577 last_mode_ = kModeAccelerateLowEnergy;
1578 break;
1579 case Accelerate::kNoStretch:
1580 last_mode_ = kModeAccelerateFail;
1581 break;
1582 case Accelerate::kError:
1583 // TODO(hlundin): Map to kModeError instead?
1584 last_mode_ = kModeAccelerateFail;
1585 return kAccelerateError;
1586 }
1587
1588 if (borrowed_samples_per_channel > 0) {
1589 // Copy borrowed samples back to the |sync_buffer_|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001590 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001591 if (length < borrowed_samples_per_channel) {
1592 // This destroys the beginning of the buffer, but will not cause any
1593 // problems.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001594 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001595 sync_buffer_->Size() -
1596 borrowed_samples_per_channel);
1597 sync_buffer_->PushFrontZeros(borrowed_samples_per_channel - length);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001598 algorithm_buffer_->PopFront(length);
1599 assert(algorithm_buffer_->Empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001600 } else {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001601 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001602 borrowed_samples_per_channel,
1603 sync_buffer_->Size() -
1604 borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001605 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001606 }
1607 }
1608
1609 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1610 if (speech_type == AudioDecoder::kComfortNoise) {
1611 last_mode_ = kModeCodecInternalCng;
1612 }
1613 if (!play_dtmf) {
1614 dtmf_tone_generator_->Reset();
1615 }
1616 expand_->Reset();
1617 return 0;
1618}
1619
1620int NetEqImpl::DoPreemptiveExpand(int16_t* decoded_buffer,
1621 size_t decoded_length,
1622 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001623 bool play_dtmf) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001624 const size_t required_samples =
1625 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001626 size_t num_channels = algorithm_buffer_->Channels();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001627 size_t borrowed_samples_per_channel = 0;
1628 size_t old_borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001629 size_t decoded_length_per_channel = decoded_length / num_channels;
1630 if (decoded_length_per_channel < required_samples) {
1631 // Must move data from the |sync_buffer_| in order to get 30 ms.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001632 borrowed_samples_per_channel =
1633 required_samples - decoded_length_per_channel;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001634 // Calculate how many of these were already played out.
Peter Kastingf045e4d2015-06-10 21:15:38 -07001635 old_borrowed_samples_per_channel =
Peter Kastingdce40cf2015-08-24 14:52:23 -07001636 (borrowed_samples_per_channel > sync_buffer_->FutureLength()) ?
1637 (borrowed_samples_per_channel - sync_buffer_->FutureLength()) : 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001638 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1639 decoded_buffer,
1640 sizeof(int16_t) * decoded_length);
1641 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1642 decoded_buffer);
1643 decoded_length = required_samples * num_channels;
1644 }
1645
Peter Kastingdce40cf2015-08-24 14:52:23 -07001646 size_t samples_added;
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001647 PreemptiveExpand::ReturnCodes return_code = preemptive_expand_->Process(
Peter Kastingdce40cf2015-08-24 14:52:23 -07001648 decoded_buffer, decoded_length,
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001649 old_borrowed_samples_per_channel,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001650 algorithm_buffer_.get(), &samples_added);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001651 stats_.PreemptiveExpandedSamples(samples_added);
1652 switch (return_code) {
1653 case PreemptiveExpand::kSuccess:
1654 last_mode_ = kModePreemptiveExpandSuccess;
1655 break;
1656 case PreemptiveExpand::kSuccessLowEnergy:
1657 last_mode_ = kModePreemptiveExpandLowEnergy;
1658 break;
1659 case PreemptiveExpand::kNoStretch:
1660 last_mode_ = kModePreemptiveExpandFail;
1661 break;
1662 case PreemptiveExpand::kError:
1663 // TODO(hlundin): Map to kModeError instead?
1664 last_mode_ = kModePreemptiveExpandFail;
1665 return kPreemptiveExpandError;
1666 }
1667
1668 if (borrowed_samples_per_channel > 0) {
1669 // Copy borrowed samples back to the |sync_buffer_|.
1670 sync_buffer_->ReplaceAtIndex(
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001671 *algorithm_buffer_, borrowed_samples_per_channel,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001672 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001673 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001674 }
1675
1676 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1677 if (speech_type == AudioDecoder::kComfortNoise) {
1678 last_mode_ = kModeCodecInternalCng;
1679 }
1680 if (!play_dtmf) {
1681 dtmf_tone_generator_->Reset();
1682 }
1683 expand_->Reset();
1684 return 0;
1685}
1686
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001687int NetEqImpl::DoRfc3389Cng(PacketList* packet_list, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001688 if (!packet_list->empty()) {
1689 // Must have exactly one SID frame at this point.
1690 assert(packet_list->size() == 1);
1691 Packet* packet = packet_list->front();
1692 packet_list->pop_front();
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001693 if (!decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1694#ifdef LEGACY_BITEXACT
1695 // This can happen due to a bug in GetDecision. Change the payload type
1696 // to a CNG type, and move on. Note that this means that we are in fact
1697 // sending a non-CNG payload to the comfort noise decoder for decoding.
1698 // Clearly wrong, but will maintain bit-exactness with legacy.
1699 if (fs_hz_ == 8000) {
1700 packet->header.payloadType =
kwibergee1879c2015-10-29 06:20:28 -07001701 decoder_database_->GetRtpPayloadType(NetEqDecoder::kDecoderCNGnb);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001702 } else if (fs_hz_ == 16000) {
1703 packet->header.payloadType =
kwibergee1879c2015-10-29 06:20:28 -07001704 decoder_database_->GetRtpPayloadType(NetEqDecoder::kDecoderCNGwb);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001705 } else if (fs_hz_ == 32000) {
kwibergee1879c2015-10-29 06:20:28 -07001706 packet->header.payloadType = decoder_database_->GetRtpPayloadType(
1707 NetEqDecoder::kDecoderCNGswb32kHz);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001708 } else if (fs_hz_ == 48000) {
kwibergee1879c2015-10-29 06:20:28 -07001709 packet->header.payloadType = decoder_database_->GetRtpPayloadType(
1710 NetEqDecoder::kDecoderCNGswb48kHz);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001711 }
1712 assert(decoder_database_->IsComfortNoise(packet->header.payloadType));
1713#else
1714 LOG(LS_ERROR) << "Trying to decode non-CNG payload as CNG.";
1715 return kOtherError;
1716#endif
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001717 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001718 // UpdateParameters() deletes |packet|.
1719 if (comfort_noise_->UpdateParameters(packet) ==
1720 ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001721 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001722 return -comfort_noise_->internal_error_code();
1723 }
1724 }
1725 int cn_return = comfort_noise_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001726 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001727 expand_->Reset();
1728 last_mode_ = kModeRfc3389Cng;
1729 if (!play_dtmf) {
1730 dtmf_tone_generator_->Reset();
1731 }
1732 if (cn_return == ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001733 decoder_error_code_ = comfort_noise_->internal_error_code();
1734 return kComfortNoiseErrorCode;
1735 } else if (cn_return == ComfortNoise::kUnknownPayloadType) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001736 return kUnknownRtpPayloadType;
1737 }
1738 return 0;
1739}
1740
minyuel6d92bf52015-09-23 15:20:39 +02001741void NetEqImpl::DoCodecInternalCng(const int16_t* decoded_buffer,
1742 size_t decoded_length) {
1743 RTC_DCHECK(normal_.get());
1744 RTC_DCHECK(mute_factor_array_.get());
1745 normal_->Process(decoded_buffer, decoded_length, last_mode_,
1746 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001747 last_mode_ = kModeCodecInternalCng;
1748 expand_->Reset();
1749}
1750
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001751int NetEqImpl::DoDtmf(const DtmfEvent& dtmf_event, bool* play_dtmf) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001752 // This block of the code and the block further down, handling |dtmf_switch|
1753 // are commented out. Otherwise playing out-of-band DTMF would fail in VoE
1754 // test, DtmfTest.ManualSuccessfullySendsOutOfBandTelephoneEvents. This is
1755 // equivalent to |dtmf_switch| always be false.
1756 //
1757 // See http://webrtc-codereview.appspot.com/1195004/ for discussion
1758 // On this issue. This change might cause some glitches at the point of
1759 // switch from audio to DTMF. Issue 1545 is filed to track this.
1760 //
1761 // bool dtmf_switch = false;
1762 // if ((last_mode_ != kModeDtmf) && dtmf_tone_generator_->initialized()) {
1763 // // Special case; see below.
1764 // // We must catch this before calling Generate, since |initialized| is
1765 // // modified in that call.
1766 // dtmf_switch = true;
1767 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001768
1769 int dtmf_return_value = 0;
1770 if (!dtmf_tone_generator_->initialized()) {
1771 // Initialize if not already done.
1772 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1773 dtmf_event.volume);
1774 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001775
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001776 if (dtmf_return_value == 0) {
1777 // Generate DTMF signal.
1778 dtmf_return_value = dtmf_tone_generator_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001779 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001780 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001781
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001782 if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001783 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001784 return dtmf_return_value;
1785 }
1786
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001787 // if (dtmf_switch) {
1788 // // This is the special case where the previous operation was DTMF
1789 // // overdub, but the current instruction is "regular" DTMF. We must make
1790 // // sure that the DTMF does not have any discontinuities. The first DTMF
1791 // // sample that we generate now must be played out immediately, therefore
1792 // // it must be copied to the speech buffer.
1793 // // TODO(hlundin): This code seems incorrect. (Legacy.) Write test and
1794 // // verify correct operation.
1795 // assert(false);
1796 // // Must generate enough data to replace all of the |sync_buffer_|
1797 // // "future".
1798 // int required_length = sync_buffer_->FutureLength();
1799 // assert(dtmf_tone_generator_->initialized());
1800 // dtmf_return_value = dtmf_tone_generator_->Generate(required_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001801 // algorithm_buffer_);
1802 // assert((size_t) required_length == algorithm_buffer_->Size());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001803 // if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001804 // algorithm_buffer_->Zeros(output_size_samples_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001805 // return dtmf_return_value;
1806 // }
1807 //
1808 // // Overwrite the "future" part of the speech buffer with the new DTMF
1809 // // data.
1810 // // TODO(hlundin): It seems that this overwriting has gone lost.
1811 // // Not adapted for multi-channel yet.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001812 // assert(algorithm_buffer_->Channels() == 1);
1813 // if (algorithm_buffer_->Channels() != 1) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001814 // LOG(LS_WARNING) << "DTMF not supported for more than one channel";
1815 // return kStereoNotSupported;
1816 // }
1817 // // Shuffle the remaining data to the beginning of algorithm buffer.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001818 // algorithm_buffer_->PopFront(sync_buffer_->FutureLength());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001819 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001820
Peter Kastingb7e50542015-06-11 12:55:50 -07001821 sync_buffer_->IncreaseEndTimestamp(
1822 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001823 expand_->Reset();
1824 last_mode_ = kModeDtmf;
1825
1826 // Set to false because the DTMF is already in the algorithm buffer.
1827 *play_dtmf = false;
1828 return 0;
1829}
1830
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001831void NetEqImpl::DoAlternativePlc(bool increase_timestamp) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001832 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001833 size_t length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001834 if (decoder && decoder->HasDecodePlc()) {
1835 // Use the decoder's packet-loss concealment.
1836 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1837 int16_t decoded_buffer[kMaxFrameSize];
1838 length = decoder->DecodePlc(1, decoded_buffer);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001839 if (length > 0)
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001840 algorithm_buffer_->PushBackInterleaved(decoded_buffer, length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001841 } else {
1842 // Do simple zero-stuffing.
1843 length = output_size_samples_;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001844 algorithm_buffer_->Zeros(length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001845 // By not advancing the timestamp, NetEq inserts samples.
1846 stats_.AddZeros(length);
1847 }
1848 if (increase_timestamp) {
Peter Kastingb7e50542015-06-11 12:55:50 -07001849 sync_buffer_->IncreaseEndTimestamp(static_cast<uint32_t>(length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001850 }
1851 expand_->Reset();
1852}
1853
1854int NetEqImpl::DtmfOverdub(const DtmfEvent& dtmf_event, size_t num_channels,
1855 int16_t* output) const {
1856 size_t out_index = 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001857 size_t overdub_length = output_size_samples_; // Default value.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001858
1859 if (sync_buffer_->dtmf_index() > sync_buffer_->next_index()) {
1860 // Special operation for transition from "DTMF only" to "DTMF overdub".
1861 out_index = std::min(
1862 sync_buffer_->dtmf_index() - sync_buffer_->next_index(),
Peter Kastingdce40cf2015-08-24 14:52:23 -07001863 output_size_samples_);
1864 overdub_length = output_size_samples_ - out_index;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001865 }
1866
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001867 AudioMultiVector dtmf_output(num_channels);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001868 int dtmf_return_value = 0;
1869 if (!dtmf_tone_generator_->initialized()) {
1870 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1871 dtmf_event.volume);
1872 }
1873 if (dtmf_return_value == 0) {
1874 dtmf_return_value = dtmf_tone_generator_->Generate(overdub_length,
1875 &dtmf_output);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001876 assert(overdub_length == dtmf_output.Size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001877 }
1878 dtmf_output.ReadInterleaved(overdub_length, &output[out_index]);
1879 return dtmf_return_value < 0 ? dtmf_return_value : 0;
1880}
1881
Peter Kastingdce40cf2015-08-24 14:52:23 -07001882int NetEqImpl::ExtractPackets(size_t required_samples,
1883 PacketList* packet_list) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001884 bool first_packet = true;
1885 uint8_t prev_payload_type = 0;
1886 uint32_t prev_timestamp = 0;
1887 uint16_t prev_sequence_number = 0;
1888 bool next_packet_available = false;
1889
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001890 const RTPHeader* header = packet_buffer_->NextRtpHeader();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001891 assert(header);
1892 if (!header) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001893 LOG(LS_ERROR) << "Packet buffer unexpectedly empty.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001894 return -1;
1895 }
turaj@webrtc.org7df97062013-08-02 18:07:13 +00001896 uint32_t first_timestamp = header->timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001897 int extracted_samples = 0;
1898
1899 // Packet extraction loop.
1900 do {
1901 timestamp_ = header->timestamp;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001902 size_t discard_count = 0;
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001903 Packet* packet = packet_buffer_->GetNextPacket(&discard_count);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001904 // |header| may be invalid after the |packet_buffer_| operation.
1905 header = NULL;
1906 if (!packet) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001907 LOG(LS_ERROR) << "Should always be able to extract a packet here";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001908 assert(false); // Should always be able to extract a packet here.
1909 return -1;
1910 }
1911 stats_.PacketsDiscarded(discard_count);
1912 // Store waiting time in ms; packets->waiting_time is in "output blocks".
1913 stats_.StoreWaitingTime(packet->waiting_time * kOutputSizeMs);
1914 assert(packet->payload_length > 0);
1915 packet_list->push_back(packet); // Store packet in list.
1916
1917 if (first_packet) {
1918 first_packet = false;
henrik.lundin48ed9302015-10-29 05:36:24 -07001919 if (nack_enabled_) {
1920 RTC_DCHECK(nack_);
1921 // TODO(henrik.lundin): Should we update this for all decoded packets?
1922 nack_->UpdateLastDecodedPacket(packet->header.sequenceNumber,
1923 packet->header.timestamp);
1924 }
1925 prev_sequence_number = packet->header.sequenceNumber;
1926 prev_timestamp = packet->header.timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001927 prev_payload_type = packet->header.payloadType;
1928 }
1929
1930 // Store number of extracted samples.
1931 int packet_duration = 0;
1932 AudioDecoder* decoder = decoder_database_->GetDecoder(
1933 packet->header.payloadType);
1934 if (decoder) {
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001935 if (packet->sync_packet) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001936 packet_duration = rtc::checked_cast<int>(decoder_frame_length_);
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001937 } else {
minyue@webrtc.org2c1bcf22015-02-17 10:17:09 +00001938 if (packet->primary) {
1939 packet_duration = decoder->PacketDuration(packet->payload,
1940 packet->payload_length);
1941 } else {
1942 packet_duration = decoder->
1943 PacketDurationRedundant(packet->payload, packet->payload_length);
1944 stats_.SecondaryDecodedSamples(packet_duration);
1945 }
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001946 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001947 } else {
Henrik Lundind67a2192015-08-03 12:54:37 +02001948 LOG(LS_WARNING) << "Unknown payload type "
1949 << static_cast<int>(packet->header.payloadType);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001950 assert(false);
1951 }
1952 if (packet_duration <= 0) {
1953 // Decoder did not return a packet duration. Assume that the packet
1954 // contains the same number of samples as the previous one.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001955 packet_duration = rtc::checked_cast<int>(decoder_frame_length_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001956 }
1957 extracted_samples = packet->header.timestamp - first_timestamp +
1958 packet_duration;
1959
1960 // Check what packet is available next.
1961 header = packet_buffer_->NextRtpHeader();
1962 next_packet_available = false;
1963 if (header && prev_payload_type == header->payloadType) {
1964 int16_t seq_no_diff = header->sequenceNumber - prev_sequence_number;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001965 size_t ts_diff = header->timestamp - prev_timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001966 if (seq_no_diff == 1 ||
1967 (seq_no_diff == 0 && ts_diff == decoder_frame_length_)) {
1968 // The next sequence number is available, or the next part of a packet
1969 // that was split into pieces upon insertion.
1970 next_packet_available = true;
1971 }
1972 prev_sequence_number = header->sequenceNumber;
1973 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07001974 } while (extracted_samples < rtc::checked_cast<int>(required_samples) &&
1975 next_packet_available);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001976
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00001977 if (extracted_samples > 0) {
1978 // Delete old packets only when we are going to decode something. Otherwise,
1979 // we could end up in the situation where we never decode anything, since
1980 // all incoming packets are considered too old but the buffer will also
1981 // never be flooded and flushed.
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001982 packet_buffer_->DiscardAllOldPackets(timestamp_);
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00001983 }
1984
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001985 return extracted_samples;
1986}
1987
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001988void NetEqImpl::UpdatePlcComponents(int fs_hz, size_t channels) {
1989 // Delete objects and create new ones.
1990 expand_.reset(expand_factory_->Create(background_noise_.get(),
1991 sync_buffer_.get(), &random_vector_,
Henrik Lundinbef77e22015-08-18 14:58:09 +02001992 &stats_, fs_hz, channels));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001993 merge_.reset(new Merge(fs_hz, channels, expand_.get(), sync_buffer_.get()));
1994}
1995
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001996void NetEqImpl::SetSampleRateAndChannels(int fs_hz, size_t channels) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001997 LOG(LS_VERBOSE) << "SetSampleRateAndChannels " << fs_hz << " " << channels;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001998 // TODO(hlundin): Change to an enumerator and skip assert.
1999 assert(fs_hz == 8000 || fs_hz == 16000 || fs_hz == 32000 || fs_hz == 48000);
2000 assert(channels > 0);
2001
2002 fs_hz_ = fs_hz;
2003 fs_mult_ = fs_hz / 8000;
Peter Kastingdce40cf2015-08-24 14:52:23 -07002004 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002005 decoder_frame_length_ = 3 * output_size_samples_; // Initialize to 30ms.
2006
2007 last_mode_ = kModeNormal;
2008
2009 // Create a new array of mute factors and set all to 1.
2010 mute_factor_array_.reset(new int16_t[channels]);
2011 for (size_t i = 0; i < channels; ++i) {
2012 mute_factor_array_[i] = 16384; // 1.0 in Q14.
2013 }
2014
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002015 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02002016 if (cng_decoder)
2017 cng_decoder->Reset();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002018
2019 // Reinit post-decode VAD with new sample rate.
2020 assert(vad_.get()); // Cannot be NULL here.
2021 vad_->Init();
2022
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002023 // Delete algorithm buffer and create a new one.
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00002024 algorithm_buffer_.reset(new AudioMultiVector(channels));
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002025
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002026 // Delete sync buffer and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002027 sync_buffer_.reset(new SyncBuffer(channels, kSyncBufferSize * fs_mult_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002028
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00002029 // Delete BackgroundNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002030 background_noise_.reset(new BackgroundNoise(channels));
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00002031 background_noise_->set_mode(background_noise_mode_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002032
2033 // Reset random vector.
2034 random_vector_.Reset();
2035
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002036 UpdatePlcComponents(fs_hz, channels);
2037
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002038 // Move index so that we create a small set of future samples (all 0).
2039 sync_buffer_->set_next_index(sync_buffer_->next_index() -
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002040 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002041
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002042 normal_.reset(new Normal(fs_hz, decoder_database_.get(), *background_noise_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002043 expand_.get()));
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +00002044 accelerate_.reset(
2045 accelerate_factory_->Create(fs_hz, channels, *background_noise_));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002046 preemptive_expand_.reset(preemptive_expand_factory_->Create(
Peter Kastingdce40cf2015-08-24 14:52:23 -07002047 fs_hz, channels, *background_noise_, expand_->overlap_length()));
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002048
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002049 // Delete ComfortNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002050 comfort_noise_.reset(new ComfortNoise(fs_hz, decoder_database_.get(),
2051 sync_buffer_.get()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002052
2053 // Verify that |decoded_buffer_| is long enough.
2054 if (decoded_buffer_length_ < kMaxFrameSize * channels) {
2055 // Reallocate to larger size.
2056 decoded_buffer_length_ = kMaxFrameSize * channels;
2057 decoded_buffer_.reset(new int16_t[decoded_buffer_length_]);
2058 }
2059
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002060 // Create DecisionLogic if it is not created yet, then communicate new sample
2061 // rate and output size to DecisionLogic object.
2062 if (!decision_logic_.get()) {
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002063 CreateDecisionLogic();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002064 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002065 decision_logic_->SetSampleRate(fs_hz_, output_size_samples_);
2066}
2067
henrik.lundin55480f52016-03-08 02:37:57 -08002068NetEqImpl::OutputType NetEqImpl::LastOutputType() {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002069 assert(vad_.get());
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002070 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002071 if (last_mode_ == kModeCodecInternalCng || last_mode_ == kModeRfc3389Cng) {
henrik.lundin55480f52016-03-08 02:37:57 -08002072 return OutputType::kCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002073 } else if (last_mode_ == kModeExpand && expand_->MuteFactor(0) == 0) {
2074 // Expand mode has faded down to background noise only (very long expand).
henrik.lundin55480f52016-03-08 02:37:57 -08002075 return OutputType::kPLCCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002076 } else if (last_mode_ == kModeExpand) {
henrik.lundin55480f52016-03-08 02:37:57 -08002077 return OutputType::kPLC;
wu@webrtc.org24301a62013-12-13 19:17:43 +00002078 } else if (vad_->running() && !vad_->active_speech()) {
henrik.lundin55480f52016-03-08 02:37:57 -08002079 return OutputType::kVadPassive;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002080 } else {
henrik.lundin55480f52016-03-08 02:37:57 -08002081 return OutputType::kNormalSpeech;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002082 }
2083}
2084
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002085void NetEqImpl::CreateDecisionLogic() {
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002086 decision_logic_.reset(DecisionLogic::Create(fs_hz_, output_size_samples_,
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002087 playout_mode_,
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002088 decoder_database_.get(),
2089 *packet_buffer_.get(),
2090 delay_manager_.get(),
2091 buffer_level_filter_.get()));
2092}
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002093} // namespace webrtc