blob: db37e716d66dde966a4cac42f10dd47166c4f42c [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"
Tommid44c0772016-03-11 17:12:32 -080020#include "webrtc/base/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}
henrik.lundinbc89de32016-03-08 05:20:14 -0800192} // namespace
henrik.lundin500c04b2016-03-08 02:36:04 -0800193
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
henrik.lundin15c51e32016-04-06 08:38:56 -0700404rtc::Optional<uint32_t> NetEqImpl::GetPlayoutTimestamp() const {
Tommi9090e0b2016-01-20 13:39:36 +0100405 rtc::CritScope lock(&crit_sect_);
henrik.lundin0d96ab72016-04-06 12:28:26 -0700406 if (first_packet_ || last_mode_ == kModeRfc3389Cng ||
407 last_mode_ == kModeCodecInternalCng) {
wu@webrtc.org94454b72014-06-05 20:34:08 +0000408 // We don't have a valid RTP timestamp until we have decoded our first
henrik.lundin0d96ab72016-04-06 12:28:26 -0700409 // RTP packet. Also, the RTP timestamp is not accurate while playing CNG,
410 // which is indicated by returning an empty value.
henrik.lundin9a410dd2016-04-06 01:39:22 -0700411 return rtc::Optional<uint32_t>();
wu@webrtc.org94454b72014-06-05 20:34:08 +0000412 }
henrik.lundin9a410dd2016-04-06 01:39:22 -0700413 return rtc::Optional<uint32_t>(
414 timestamp_scaler_->ToExternal(playout_timestamp_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000415}
416
henrik.lundind89814b2015-11-23 06:49:25 -0800417int NetEqImpl::last_output_sample_rate_hz() const {
Tommi9090e0b2016-01-20 13:39:36 +0100418 rtc::CritScope lock(&crit_sect_);
henrik.lundind89814b2015-11-23 06:49:25 -0800419 return last_output_sample_rate_hz_;
420}
421
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200422int NetEqImpl::SetTargetNumberOfChannels() {
423 return kNotImplemented;
424}
425
426int NetEqImpl::SetTargetSampleRate() {
427 return kNotImplemented;
428}
429
henrik.lundin@webrtc.orgb0f4b3d2014-11-04 08:53:10 +0000430int NetEqImpl::LastError() const {
Tommi9090e0b2016-01-20 13:39:36 +0100431 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000432 return error_code_;
433}
434
435int NetEqImpl::LastDecoderError() {
Tommi9090e0b2016-01-20 13:39:36 +0100436 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000437 return decoder_error_code_;
438}
439
440void NetEqImpl::FlushBuffers() {
Tommi9090e0b2016-01-20 13:39:36 +0100441 rtc::CritScope lock(&crit_sect_);
Henrik Lundind67a2192015-08-03 12:54:37 +0200442 LOG(LS_VERBOSE) << "FlushBuffers";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000443 packet_buffer_->Flush();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000444 assert(sync_buffer_.get());
445 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000446 sync_buffer_->Flush();
447 sync_buffer_->set_next_index(sync_buffer_->next_index() -
448 expand_->overlap_length());
449 // Set to wait for new codec.
450 first_packet_ = true;
451}
452
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000453void NetEqImpl::PacketBufferStatistics(int* current_num_packets,
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000454 int* max_num_packets) const {
Tommi9090e0b2016-01-20 13:39:36 +0100455 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000456 packet_buffer_->BufferStat(current_num_packets, max_num_packets);
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000457}
458
henrik.lundin48ed9302015-10-29 05:36:24 -0700459void NetEqImpl::EnableNack(size_t max_nack_list_size) {
Tommi9090e0b2016-01-20 13:39:36 +0100460 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700461 if (!nack_enabled_) {
462 const int kNackThresholdPackets = 2;
463 nack_.reset(Nack::Create(kNackThresholdPackets));
464 nack_enabled_ = true;
465 nack_->UpdateSampleRate(fs_hz_);
466 }
467 nack_->SetMaxNackListSize(max_nack_list_size);
468}
469
470void NetEqImpl::DisableNack() {
Tommi9090e0b2016-01-20 13:39:36 +0100471 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700472 nack_.reset();
473 nack_enabled_ = false;
474}
475
476std::vector<uint16_t> NetEqImpl::GetNackList(int64_t round_trip_time_ms) const {
Tommi9090e0b2016-01-20 13:39:36 +0100477 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700478 if (!nack_enabled_) {
479 return std::vector<uint16_t>();
480 }
481 RTC_DCHECK(nack_.get());
482 return nack_->GetNackList(round_trip_time_ms);
minyue@webrtc.orgd7301772013-08-29 00:58:14 +0000483}
484
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000485const SyncBuffer* NetEqImpl::sync_buffer_for_test() const {
Tommi9090e0b2016-01-20 13:39:36 +0100486 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000487 return sync_buffer_.get();
488}
489
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000490// Methods below this line are private.
491
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000492int NetEqImpl::InsertPacketInternal(const WebRtcRTPHeader& rtp_header,
kwibergee2bac22015-11-11 10:34:00 -0800493 rtc::ArrayView<const uint8_t> payload,
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000494 uint32_t receive_timestamp,
495 bool is_sync_packet) {
kwibergee2bac22015-11-11 10:34:00 -0800496 if (payload.empty()) {
497 LOG_F(LS_ERROR) << "payload is empty";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000498 return kInvalidPointer;
499 }
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000500 // Sanity checks for sync-packets.
501 if (is_sync_packet) {
502 if (decoder_database_->IsDtmf(rtp_header.header.payloadType) ||
503 decoder_database_->IsRed(rtp_header.header.payloadType) ||
504 decoder_database_->IsComfortNoise(rtp_header.header.payloadType)) {
505 LOG_F(LS_ERROR) << "Sync-packet with an unacceptable payload type "
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000506 << static_cast<int>(rtp_header.header.payloadType);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000507 return kSyncPacketNotAccepted;
508 }
509 if (first_packet_ ||
510 rtp_header.header.payloadType != current_rtp_payload_type_ ||
511 rtp_header.header.ssrc != ssrc_) {
512 // Even if |current_rtp_payload_type_| is 0xFF, sync-packet isn't
513 // accepted.
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000514 LOG_F(LS_ERROR)
515 << "Changing codec, SSRC or first packet with sync-packet.";
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000516 return kSyncPacketNotAccepted;
517 }
518 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000519 PacketList packet_list;
520 RTPHeader main_header;
521 {
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000522 // Convert to Packet.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000523 // Create |packet| within this separate scope, since it should not be used
524 // directly once it's been inserted in the packet list. This way, |packet|
525 // is not defined outside of this block.
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000526 Packet* packet = new Packet;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000527 packet->header.markerBit = false;
528 packet->header.payloadType = rtp_header.header.payloadType;
529 packet->header.sequenceNumber = rtp_header.header.sequenceNumber;
530 packet->header.timestamp = rtp_header.header.timestamp;
531 packet->header.ssrc = rtp_header.header.ssrc;
532 packet->header.numCSRCs = 0;
kwibergee2bac22015-11-11 10:34:00 -0800533 packet->payload_length = payload.size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000534 packet->primary = true;
535 packet->waiting_time = 0;
536 packet->payload = new uint8_t[packet->payload_length];
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000537 packet->sync_packet = is_sync_packet;
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +0000538 if (!packet->payload) {
539 LOG_F(LS_ERROR) << "Payload pointer is NULL.";
540 }
kwibergee2bac22015-11-11 10:34:00 -0800541 assert(!payload.empty()); // Already checked above.
542 memcpy(packet->payload, payload.data(), packet->payload_length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000543 // Insert packet in a packet list.
544 packet_list.push_back(packet);
545 // Save main payloads header for later.
546 memcpy(&main_header, &packet->header, sizeof(main_header));
547 }
548
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000549 bool update_sample_rate_and_channels = false;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000550 // Reinitialize NetEq if it's needed (changed SSRC or first call).
551 if ((main_header.ssrc != ssrc_) || first_packet_) {
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000552 // Note: |first_packet_| will be cleared further down in this method, once
553 // the packet has been successfully inserted into the packet buffer.
554
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000555 rtcp_.Init(main_header.sequenceNumber);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000556
557 // Flush the packet buffer and DTMF buffer.
558 packet_buffer_->Flush();
559 dtmf_buffer_->Flush();
560
561 // Store new SSRC.
562 ssrc_ = main_header.ssrc;
563
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000564 // Update audio buffer timestamp.
565 sync_buffer_->IncreaseEndTimestamp(main_header.timestamp - timestamp_);
566
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000567 // Update codecs.
568 timestamp_ = main_header.timestamp;
569 current_rtp_payload_type_ = main_header.payloadType;
570
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000571 // Reset timestamp scaling.
572 timestamp_scaler_->Reset();
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000573
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000574 // Trigger an update of sampling rate and the number of channels.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000575 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000576 }
577
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000578 // Update RTCP statistics, only for regular packets.
579 if (!is_sync_packet)
580 rtcp_.Update(main_header, receive_timestamp);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000581
582 // Check for RED payload type, and separate payloads into several packets.
583 if (decoder_database_->IsRed(main_header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000584 assert(!is_sync_packet); // We had a sanity check for this.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000585 if (payload_splitter_->SplitRed(&packet_list) != PayloadSplitter::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000586 PacketBuffer::DeleteAllPackets(&packet_list);
587 return kRedundancySplitError;
588 }
589 // Only accept a few RED payloads of the same type as the main data,
590 // DTMF events and CNG.
591 payload_splitter_->CheckRedPayloads(&packet_list, *decoder_database_);
592 // Update the stored main payload header since the main payload has now
593 // changed.
594 memcpy(&main_header, &packet_list.front()->header, sizeof(main_header));
595 }
596
597 // Check payload types.
598 if (decoder_database_->CheckPayloadTypes(packet_list) ==
599 DecoderDatabase::kDecoderNotFound) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000600 PacketBuffer::DeleteAllPackets(&packet_list);
601 return kUnknownRtpPayloadType;
602 }
603
604 // Scale timestamp to internal domain (only for some codecs).
605 timestamp_scaler_->ToInternal(&packet_list);
606
607 // Process DTMF payloads. Cycle through the list of packets, and pick out any
608 // DTMF payloads found.
609 PacketList::iterator it = packet_list.begin();
610 while (it != packet_list.end()) {
611 Packet* current_packet = (*it);
612 assert(current_packet);
613 assert(current_packet->payload);
614 if (decoder_database_->IsDtmf(current_packet->header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000615 assert(!current_packet->sync_packet); // We had a sanity check for this.
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000616 DtmfEvent event;
617 int ret = DtmfBuffer::ParseEvent(
618 current_packet->header.timestamp,
619 current_packet->payload,
620 current_packet->payload_length,
621 &event);
622 if (ret != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000623 PacketBuffer::DeleteAllPackets(&packet_list);
624 return kDtmfParsingError;
625 }
626 if (dtmf_buffer_->InsertEvent(event) != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000627 PacketBuffer::DeleteAllPackets(&packet_list);
628 return kDtmfInsertError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000629 }
630 // TODO(hlundin): Let the destructor of Packet handle the payload.
631 delete [] current_packet->payload;
632 delete current_packet;
633 it = packet_list.erase(it);
634 } else {
635 ++it;
636 }
637 }
638
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000639 // Check for FEC in packets, and separate payloads into several packets.
640 int ret = payload_splitter_->SplitFec(&packet_list, decoder_database_.get());
641 if (ret != PayloadSplitter::kOK) {
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000642 PacketBuffer::DeleteAllPackets(&packet_list);
643 switch (ret) {
644 case PayloadSplitter::kUnknownPayloadType:
645 return kUnknownRtpPayloadType;
646 default:
647 return kOtherError;
648 }
649 }
650
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000651 // Split payloads into smaller chunks. This also verifies that all payloads
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000652 // are of a known payload type. SplitAudio() method is protected against
653 // sync-packets.
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +0000654 ret = payload_splitter_->SplitAudio(&packet_list, *decoder_database_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000655 if (ret != PayloadSplitter::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000656 PacketBuffer::DeleteAllPackets(&packet_list);
657 switch (ret) {
658 case PayloadSplitter::kUnknownPayloadType:
659 return kUnknownRtpPayloadType;
660 case PayloadSplitter::kFrameSplitError:
661 return kFrameSplitError;
662 default:
663 return kOtherError;
664 }
665 }
666
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000667 // Update bandwidth estimate, if the packet is not sync-packet.
668 if (!packet_list.empty() && !packet_list.front()->sync_packet) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000669 // The list can be empty here if we got nothing but DTMF payloads.
670 AudioDecoder* decoder =
671 decoder_database_->GetDecoder(main_header.payloadType);
672 assert(decoder); // Should always get a valid object, since we have
673 // already checked that the payload types are known.
674 decoder->IncomingPacket(packet_list.front()->payload,
675 packet_list.front()->payload_length,
676 packet_list.front()->header.sequenceNumber,
677 packet_list.front()->header.timestamp,
678 receive_timestamp);
679 }
680
henrik.lundin48ed9302015-10-29 05:36:24 -0700681 if (nack_enabled_) {
682 RTC_DCHECK(nack_);
683 if (update_sample_rate_and_channels) {
684 nack_->Reset();
685 }
686 nack_->UpdateLastReceivedPacket(packet_list.front()->header.sequenceNumber,
687 packet_list.front()->header.timestamp);
688 }
689
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000690 // Insert packets in buffer.
henrik.lundin116c84e2015-08-27 13:14:48 -0700691 const size_t buffer_length_before_insert =
692 packet_buffer_->NumPacketsInBuffer();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000693 ret = packet_buffer_->InsertPacketList(
694 &packet_list,
695 *decoder_database_,
696 &current_rtp_payload_type_,
697 &current_cng_rtp_payload_type_);
698 if (ret == PacketBuffer::kFlushed) {
699 // Reset DSP timestamp etc. if packet buffer flushed.
700 new_codec_ = true;
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000701 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000702 } else if (ret != PacketBuffer::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000703 PacketBuffer::DeleteAllPackets(&packet_list);
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000704 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000705 }
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000706
707 if (first_packet_) {
708 first_packet_ = false;
709 // Update the codec on the next GetAudio call.
710 new_codec_ = true;
711 }
712
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000713 if (current_rtp_payload_type_ != 0xFF) {
714 const DecoderDatabase::DecoderInfo* dec_info =
715 decoder_database_->GetDecoderInfo(current_rtp_payload_type_);
716 if (!dec_info) {
717 assert(false); // Already checked that the payload type is known.
718 }
719 }
720
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000721 if (update_sample_rate_and_channels && !packet_buffer_->Empty()) {
722 // We do not use |current_rtp_payload_type_| to |set payload_type|, but
723 // get the next RTP header from |packet_buffer_| to obtain the payload type.
724 // The reason for it is the following corner case. If NetEq receives a
725 // CNG packet with a sample rate different than the current CNG then it
726 // flushes its buffer, assuming send codec must have been changed. However,
727 // payload type of the hypothetically new send codec is not known.
728 const RTPHeader* rtp_header = packet_buffer_->NextRtpHeader();
729 assert(rtp_header);
730 int payload_type = rtp_header->payloadType;
731 AudioDecoder* decoder = decoder_database_->GetDecoder(payload_type);
732 assert(decoder); // Payloads are already checked to be valid.
733 const DecoderDatabase::DecoderInfo* decoder_info =
734 decoder_database_->GetDecoderInfo(payload_type);
735 assert(decoder_info);
736 if (decoder_info->fs_hz != fs_hz_ ||
henrik.lundin48ed9302015-10-29 05:36:24 -0700737 decoder->Channels() != algorithm_buffer_->Channels()) {
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +0000738 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->Channels());
henrik.lundin48ed9302015-10-29 05:36:24 -0700739 }
740 if (nack_enabled_) {
741 RTC_DCHECK(nack_);
742 // Update the sample rate even if the rate is not new, because of Reset().
743 nack_->UpdateSampleRate(fs_hz_);
744 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000745 }
746
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000747 // TODO(hlundin): Move this code to DelayManager class.
748 const DecoderDatabase::DecoderInfo* dec_info =
749 decoder_database_->GetDecoderInfo(main_header.payloadType);
750 assert(dec_info); // Already checked that the payload type is known.
751 delay_manager_->LastDecoderType(dec_info->codec_type);
752 if (delay_manager_->last_pack_cng_or_dtmf() == 0) {
753 // Calculate the total speech length carried in each packet.
henrik.lundin116c84e2015-08-27 13:14:48 -0700754 const size_t buffer_length_after_insert =
755 packet_buffer_->NumPacketsInBuffer();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000756
henrik.lundin116c84e2015-08-27 13:14:48 -0700757 if (buffer_length_after_insert > buffer_length_before_insert) {
758 const size_t packet_length_samples =
759 (buffer_length_after_insert - buffer_length_before_insert) *
760 decoder_frame_length_;
761 if (packet_length_samples != decision_logic_->packet_length_samples()) {
762 decision_logic_->set_packet_length_samples(packet_length_samples);
763 delay_manager_->SetPacketAudioLength(
764 rtc::checked_cast<int>((1000 * packet_length_samples) / fs_hz_));
765 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000766 }
767
768 // Update statistics.
pbos@webrtc.org0946a562013-04-09 00:28:06 +0000769 if ((int32_t) (main_header.timestamp - timestamp_) >= 0 &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000770 !new_codec_) {
771 // Only update statistics if incoming packet is not older than last played
772 // out packet, and if new codec flag is not set.
773 delay_manager_->Update(main_header.sequenceNumber, main_header.timestamp,
774 fs_hz_);
775 }
776 } else if (delay_manager_->last_pack_cng_or_dtmf() == -1) {
777 // This is first "normal" packet after CNG or DTMF.
778 // Reset packet time counter and measure time until next packet,
779 // but don't update statistics.
780 delay_manager_->set_last_pack_cng_or_dtmf(0);
781 delay_manager_->ResetPacketIatCount();
782 }
783 return 0;
784}
785
henrik.lundin6d8e0112016-03-04 10:34:21 -0800786int NetEqImpl::GetAudioInternal(AudioFrame* audio_frame) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000787 PacketList packet_list;
788 DtmfEvent dtmf_event;
789 Operations operation;
790 bool play_dtmf;
791 int return_value = GetDecision(&operation, &packet_list, &dtmf_event,
792 &play_dtmf);
793 if (return_value != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000794 last_mode_ = kModeError;
795 return return_value;
796 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000797
798 AudioDecoder::SpeechType speech_type;
799 int length = 0;
800 int decode_return_value = Decode(&packet_list, &operation,
801 &length, &speech_type);
802
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000803 assert(vad_.get());
804 bool sid_frame_available =
805 (operation == kRfc3389Cng && !packet_list.empty());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700806 vad_->Update(decoded_buffer_.get(), static_cast<size_t>(length), speech_type,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000807 sid_frame_available, fs_hz_);
808
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000809 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000810 switch (operation) {
811 case kNormal: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000812 DoNormal(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000813 break;
814 }
815 case kMerge: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000816 DoMerge(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000817 break;
818 }
819 case kExpand: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000820 return_value = DoExpand(play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000821 break;
822 }
Henrik Lundincf808d22015-05-27 14:33:29 +0200823 case kAccelerate:
824 case kFastAccelerate: {
825 const bool fast_accelerate =
826 enable_fast_accelerate_ && (operation == kFastAccelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000827 return_value = DoAccelerate(decoded_buffer_.get(), length, speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +0200828 play_dtmf, fast_accelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000829 break;
830 }
831 case kPreemptiveExpand: {
832 return_value = DoPreemptiveExpand(decoded_buffer_.get(), length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000833 speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000834 break;
835 }
836 case kRfc3389Cng:
837 case kRfc3389CngNoPacket: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000838 return_value = DoRfc3389Cng(&packet_list, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000839 break;
840 }
841 case kCodecInternalCng: {
842 // This handles the case when there is no transmission and the decoder
843 // should produce internal comfort noise.
844 // TODO(hlundin): Write test for codec-internal CNG.
minyuel6d92bf52015-09-23 15:20:39 +0200845 DoCodecInternalCng(decoded_buffer_.get(), length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000846 break;
847 }
848 case kDtmf: {
849 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000850 return_value = DoDtmf(dtmf_event, &play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000851 break;
852 }
853 case kAlternativePlc: {
854 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000855 DoAlternativePlc(false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000856 break;
857 }
858 case kAlternativePlcIncreaseTimestamp: {
859 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000860 DoAlternativePlc(true);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000861 break;
862 }
863 case kAudioRepetitionIncreaseTimestamp: {
864 // TODO(hlundin): Write test for this.
Peter Kastingb7e50542015-06-11 12:55:50 -0700865 sync_buffer_->IncreaseEndTimestamp(
866 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000867 // Skipping break on purpose. Execution should move on into the
868 // next case.
kjellander@webrtc.org7d2b6a92015-01-28 18:37:58 +0000869 FALLTHROUGH();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000870 }
871 case kAudioRepetition: {
872 // TODO(hlundin): Write test for this.
873 // Copy last |output_size_samples_| from |sync_buffer_| to
874 // |algorithm_buffer|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000875 algorithm_buffer_->PushBackFromIndex(
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000876 *sync_buffer_, sync_buffer_->Size() - output_size_samples_);
877 expand_->Reset();
878 break;
879 }
880 case kUndefined: {
Henrik Lundind67a2192015-08-03 12:54:37 +0200881 LOG(LS_ERROR) << "Invalid operation kUndefined.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000882 assert(false); // This should not happen.
883 last_mode_ = kModeError;
884 return kInvalidOperation;
885 }
886 } // End of switch.
887 if (return_value < 0) {
888 return return_value;
889 }
890
891 if (last_mode_ != kModeRfc3389Cng) {
892 comfort_noise_->Reset();
893 }
894
895 // Copy from |algorithm_buffer| to |sync_buffer_|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000896 sync_buffer_->PushBack(*algorithm_buffer_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000897
898 // Extract data from |sync_buffer_| to |output|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000899 size_t num_output_samples_per_channel = output_size_samples_;
900 size_t num_output_samples = output_size_samples_ * sync_buffer_->Channels();
henrik.lundin6d8e0112016-03-04 10:34:21 -0800901 if (num_output_samples > AudioFrame::kMaxDataSizeSamples) {
902 LOG(LS_WARNING) << "Output array is too short. "
903 << AudioFrame::kMaxDataSizeSamples << " < "
904 << output_size_samples_ << " * "
905 << sync_buffer_->Channels();
906 num_output_samples = AudioFrame::kMaxDataSizeSamples;
907 num_output_samples_per_channel =
908 AudioFrame::kMaxDataSizeSamples / sync_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000909 }
henrik.lundin6d8e0112016-03-04 10:34:21 -0800910 sync_buffer_->GetNextAudioInterleaved(num_output_samples_per_channel,
911 audio_frame);
912 audio_frame->sample_rate_hz_ = fs_hz_;
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200913 if (sync_buffer_->FutureLength() < expand_->overlap_length()) {
914 // The sync buffer should always contain |overlap_length| samples, but now
915 // too many samples have been extracted. Reinstall the |overlap_length|
916 // lookahead by moving the index.
917 const size_t missing_lookahead_samples =
918 expand_->overlap_length() - sync_buffer_->FutureLength();
henrikg91d6ede2015-09-17 00:24:34 -0700919 RTC_DCHECK_GE(sync_buffer_->next_index(), missing_lookahead_samples);
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200920 sync_buffer_->set_next_index(sync_buffer_->next_index() -
921 missing_lookahead_samples);
922 }
henrik.lundin6d8e0112016-03-04 10:34:21 -0800923 if (audio_frame->samples_per_channel_ != output_size_samples_) {
924 LOG(LS_ERROR) << "audio_frame->samples_per_channel_ ("
925 << audio_frame->samples_per_channel_
Henrik Lundind67a2192015-08-03 12:54:37 +0200926 << ") != output_size_samples_ (" << output_size_samples_
927 << ")";
minyue@webrtc.orgdb1cefc2013-08-13 01:39:21 +0000928 // TODO(minyue): treatment of under-run, filling zeros
henrik.lundin6d8e0112016-03-04 10:34:21 -0800929 memset(audio_frame->data_, 0, num_output_samples * sizeof(int16_t));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000930 return kSampleUnderrun;
931 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000932
933 // Should always have overlap samples left in the |sync_buffer_|.
henrikg91d6ede2015-09-17 00:24:34 -0700934 RTC_DCHECK_GE(sync_buffer_->FutureLength(), expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000935
936 if (play_dtmf) {
henrik.lundin6d8e0112016-03-04 10:34:21 -0800937 return_value =
938 DtmfOverdub(dtmf_event, sync_buffer_->Channels(), audio_frame->data_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000939 }
940
941 // Update the background noise parameters if last operation wrote data
942 // straight from the decoder to the |sync_buffer_|. That is, none of the
943 // operations that modify the signal can be followed by a parameter update.
944 if ((last_mode_ == kModeNormal) ||
945 (last_mode_ == kModeAccelerateFail) ||
946 (last_mode_ == kModePreemptiveExpandFail) ||
947 (last_mode_ == kModeRfc3389Cng) ||
948 (last_mode_ == kModeCodecInternalCng)) {
949 background_noise_->Update(*sync_buffer_, *vad_.get());
950 }
951
952 if (operation == kDtmf) {
953 // DTMF data was written the end of |sync_buffer_|.
954 // Update index to end of DTMF data in |sync_buffer_|.
955 sync_buffer_->set_dtmf_index(sync_buffer_->Size());
956 }
957
henrik.lundin@webrtc.orged865b52014-03-06 10:28:07 +0000958 if (last_mode_ != kModeExpand) {
959 // If last operation was not expand, calculate the |playout_timestamp_| from
960 // the |sync_buffer_|. However, do not update the |playout_timestamp_| if it
961 // would be moved "backwards".
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000962 uint32_t temp_timestamp = sync_buffer_->end_timestamp() -
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000963 static_cast<uint32_t>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000964 if (static_cast<int32_t>(temp_timestamp - playout_timestamp_) > 0) {
965 playout_timestamp_ = temp_timestamp;
966 }
967 } else {
968 // Use dead reckoning to estimate the |playout_timestamp_|.
Peter Kastingb7e50542015-06-11 12:55:50 -0700969 playout_timestamp_ += static_cast<uint32_t>(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000970 }
henrik.lundin15c51e32016-04-06 08:38:56 -0700971 // Set the timestamp in the audio frame to zero before the first packet has
972 // been inserted. Otherwise, subtract the frame size in samples to get the
973 // timestamp of the first sample in the frame (playout_timestamp_ is the
974 // last + 1).
975 audio_frame->timestamp_ =
976 first_packet_
977 ? 0
978 : timestamp_scaler_->ToExternal(playout_timestamp_) -
979 static_cast<uint32_t>(audio_frame->samples_per_channel_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000980
981 if (decode_return_value) return decode_return_value;
982 return return_value;
983}
984
985int NetEqImpl::GetDecision(Operations* operation,
986 PacketList* packet_list,
987 DtmfEvent* dtmf_event,
988 bool* play_dtmf) {
989 // Initialize output variables.
990 *play_dtmf = false;
991 *operation = kUndefined;
992
993 // Increment time counters.
994 packet_buffer_->IncrementWaitingTimes();
995 stats_.IncreaseCounter(output_size_samples_, fs_hz_);
996
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000997 assert(sync_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000998 uint32_t end_timestamp = sync_buffer_->end_timestamp();
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +0000999 if (!new_codec_) {
1000 const uint32_t five_seconds_samples = 5 * fs_hz_;
1001 packet_buffer_->DiscardOldPackets(end_timestamp, five_seconds_samples);
1002 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001003 const RTPHeader* header = packet_buffer_->NextRtpHeader();
1004
henrik.lundin@webrtc.orgca8cb952014-03-12 10:26:52 +00001005 if (decision_logic_->CngRfc3389On() || last_mode_ == kModeRfc3389Cng) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001006 // Because of timestamp peculiarities, we have to "manually" disallow using
1007 // a CNG packet with the same timestamp as the one that was last played.
1008 // This can happen when using redundancy and will cause the timing to shift.
henrik.lundin@webrtc.org24779fe2014-03-14 12:40:05 +00001009 while (header && decoder_database_->IsComfortNoise(header->payloadType) &&
1010 (end_timestamp >= header->timestamp ||
1011 end_timestamp + decision_logic_->generated_noise_samples() >
1012 header->timestamp)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001013 // Don't use this packet, discard it.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001014 if (packet_buffer_->DiscardNextPacket() != PacketBuffer::kOK) {
1015 assert(false); // Must be ok by design.
1016 }
1017 // Check buffer again.
1018 if (!new_codec_) {
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001019 packet_buffer_->DiscardOldPackets(end_timestamp, 5 * fs_hz_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001020 }
1021 header = packet_buffer_->NextRtpHeader();
1022 }
1023 }
1024
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001025 assert(expand_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001026 const int samples_left = static_cast<int>(sync_buffer_->FutureLength() -
1027 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001028 if (last_mode_ == kModeAccelerateSuccess ||
1029 last_mode_ == kModeAccelerateLowEnergy ||
1030 last_mode_ == kModePreemptiveExpandSuccess ||
1031 last_mode_ == kModePreemptiveExpandLowEnergy) {
1032 // Subtract (samples_left + output_size_samples_) from sampleMemory.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001033 decision_logic_->AddSampleMemory(
1034 -(samples_left + rtc::checked_cast<int>(output_size_samples_)));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001035 }
1036
1037 // Check if it is time to play a DTMF event.
Peter Kastingb7e50542015-06-11 12:55:50 -07001038 if (dtmf_buffer_->GetEvent(
1039 static_cast<uint32_t>(
1040 end_timestamp + decision_logic_->generated_noise_samples()),
1041 dtmf_event)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001042 *play_dtmf = true;
1043 }
1044
1045 // Get instruction.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001046 assert(sync_buffer_.get());
1047 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001048 *operation = decision_logic_->GetDecision(*sync_buffer_,
1049 *expand_,
1050 decoder_frame_length_,
1051 header,
1052 last_mode_,
1053 *play_dtmf,
1054 &reset_decoder_);
1055
1056 // Check if we already have enough samples in the |sync_buffer_|. If so,
1057 // change decision to normal, unless the decision was merge, accelerate, or
1058 // preemptive expand.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001059 if (samples_left >= rtc::checked_cast<int>(output_size_samples_) &&
1060 *operation != kMerge &&
1061 *operation != kAccelerate &&
1062 *operation != kFastAccelerate &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001063 *operation != kPreemptiveExpand) {
1064 *operation = kNormal;
1065 return 0;
1066 }
1067
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001068 decision_logic_->ExpandDecision(*operation);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001069
1070 // Check conditions for reset.
1071 if (new_codec_ || *operation == kUndefined) {
1072 // The only valid reason to get kUndefined is that new_codec_ is set.
1073 assert(new_codec_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001074 if (*play_dtmf && !header) {
1075 timestamp_ = dtmf_event->timestamp;
1076 } else {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001077 if (!header) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001078 LOG(LS_ERROR) << "Packet missing where it shouldn't.";
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001079 return -1;
1080 }
1081 timestamp_ = header->timestamp;
1082 if (*operation == kRfc3389CngNoPacket
1083#ifndef LEGACY_BITEXACT
1084 // Without this check, it can happen that a non-CNG packet is sent to
1085 // the CNG decoder as if it was a SID frame. This is clearly a bug,
1086 // but is kept for now to maintain bit-exactness with the test
1087 // vectors.
1088 && decoder_database_->IsComfortNoise(header->payloadType)
1089#endif
1090 ) {
1091 // Change decision to CNG packet, since we do have a CNG packet, but it
1092 // was considered too early to use. Now, use it anyway.
1093 *operation = kRfc3389Cng;
1094 } else if (*operation != kRfc3389Cng) {
1095 *operation = kNormal;
1096 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001097 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001098 // Adjust |sync_buffer_| timestamp before setting |end_timestamp| to the
1099 // new value.
1100 sync_buffer_->IncreaseEndTimestamp(timestamp_ - end_timestamp);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001101 end_timestamp = timestamp_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001102 new_codec_ = false;
1103 decision_logic_->SoftReset();
1104 buffer_level_filter_->Reset();
1105 delay_manager_->Reset();
1106 stats_.ResetMcu();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001107 }
1108
Peter Kastingdce40cf2015-08-24 14:52:23 -07001109 size_t required_samples = output_size_samples_;
1110 const size_t samples_10_ms = static_cast<size_t>(80 * fs_mult_);
1111 const size_t samples_20_ms = 2 * samples_10_ms;
1112 const size_t samples_30_ms = 3 * samples_10_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001113
1114 switch (*operation) {
1115 case kExpand: {
1116 timestamp_ = end_timestamp;
1117 return 0;
1118 }
1119 case kRfc3389CngNoPacket:
1120 case kCodecInternalCng: {
1121 return 0;
1122 }
1123 case kDtmf: {
1124 // TODO(hlundin): Write test for this.
1125 // Update timestamp.
1126 timestamp_ = end_timestamp;
1127 if (decision_logic_->generated_noise_samples() > 0 &&
1128 last_mode_ != kModeDtmf) {
1129 // Make a jump in timestamp due to the recently played comfort noise.
Peter Kastingb7e50542015-06-11 12:55:50 -07001130 uint32_t timestamp_jump =
1131 static_cast<uint32_t>(decision_logic_->generated_noise_samples());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001132 sync_buffer_->IncreaseEndTimestamp(timestamp_jump);
1133 timestamp_ += timestamp_jump;
1134 }
1135 decision_logic_->set_generated_noise_samples(0);
1136 return 0;
1137 }
Henrik Lundincf808d22015-05-27 14:33:29 +02001138 case kAccelerate:
1139 case kFastAccelerate: {
1140 // In order to do an accelerate we need at least 30 ms of audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001141 if (samples_left >= static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001142 // Already have enough data, so we do not need to extract any more.
1143 decision_logic_->set_sample_memory(samples_left);
1144 decision_logic_->set_prev_time_scale(true);
1145 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001146 } else if (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001147 decoder_frame_length_ >= samples_30_ms) {
1148 // Avoid decoding more data as it might overflow the playout buffer.
1149 *operation = kNormal;
1150 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001151 } else if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001152 decoder_frame_length_ < samples_30_ms) {
1153 // Build up decoded data by decoding at least 20 ms of audio data. Do
1154 // not perform accelerate yet, but wait until we only need to do one
1155 // decoding.
1156 required_samples = 2 * output_size_samples_;
1157 *operation = kNormal;
1158 }
1159 // If none of the above is true, we have one of two possible situations:
1160 // (1) 20 ms <= samples_left < 30 ms and decoder_frame_length_ < 30 ms; or
1161 // (2) samples_left < 10 ms and decoder_frame_length_ >= 30 ms.
1162 // In either case, we move on with the accelerate decision, and decode one
1163 // frame now.
1164 break;
1165 }
1166 case kPreemptiveExpand: {
1167 // In order to do a preemptive expand we need at least 30 ms of decoded
1168 // audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001169 if ((samples_left >= static_cast<int>(samples_30_ms)) ||
1170 (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001171 decoder_frame_length_ >= samples_30_ms)) {
1172 // Already have enough data, so we do not need to extract any more.
1173 // Or, avoid decoding more data as it might overflow the playout buffer.
1174 // Still try preemptive expand, though.
1175 decision_logic_->set_sample_memory(samples_left);
1176 decision_logic_->set_prev_time_scale(true);
1177 return 0;
1178 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07001179 if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001180 decoder_frame_length_ < samples_30_ms) {
1181 // Build up decoded data by decoding at least 20 ms of audio data.
1182 // Still try to perform preemptive expand.
1183 required_samples = 2 * output_size_samples_;
1184 }
1185 // Move on with the preemptive expand decision.
1186 break;
1187 }
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001188 case kMerge: {
1189 required_samples =
1190 std::max(merge_->RequiredFutureSamples(), required_samples);
1191 break;
1192 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001193 default: {
1194 // Do nothing.
1195 }
1196 }
1197
1198 // Get packets from buffer.
1199 int extracted_samples = 0;
1200 if (header &&
1201 *operation != kAlternativePlc &&
1202 *operation != kAlternativePlcIncreaseTimestamp &&
1203 *operation != kAudioRepetition &&
1204 *operation != kAudioRepetitionIncreaseTimestamp) {
1205 sync_buffer_->IncreaseEndTimestamp(header->timestamp - end_timestamp);
1206 if (decision_logic_->CngOff()) {
1207 // Adjustment of timestamp only corresponds to an actual packet loss
1208 // if comfort noise is not played. If comfort noise was just played,
1209 // this adjustment of timestamp is only done to get back in sync with the
1210 // stream timestamp; no loss to report.
1211 stats_.LostSamples(header->timestamp - end_timestamp);
1212 }
1213
1214 if (*operation != kRfc3389Cng) {
1215 // We are about to decode and use a non-CNG packet.
1216 decision_logic_->SetCngOff();
1217 }
1218 // Reset CNG timestamp as a new packet will be delivered.
1219 // (Also if this is a CNG packet, since playedOutTS is updated.)
1220 decision_logic_->set_generated_noise_samples(0);
1221
1222 extracted_samples = ExtractPackets(required_samples, packet_list);
1223 if (extracted_samples < 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001224 return kPacketBufferCorruption;
1225 }
1226 }
1227
Henrik Lundincf808d22015-05-27 14:33:29 +02001228 if (*operation == kAccelerate || *operation == kFastAccelerate ||
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001229 *operation == kPreemptiveExpand) {
1230 decision_logic_->set_sample_memory(samples_left + extracted_samples);
1231 decision_logic_->set_prev_time_scale(true);
1232 }
1233
Henrik Lundincf808d22015-05-27 14:33:29 +02001234 if (*operation == kAccelerate || *operation == kFastAccelerate) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001235 // Check that we have enough data (30ms) to do accelerate.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001236 if (extracted_samples + samples_left < static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001237 // TODO(hlundin): Write test for this.
1238 // Not enough, do normal operation instead.
1239 *operation = kNormal;
1240 }
1241 }
1242
1243 timestamp_ = end_timestamp;
1244 return 0;
1245}
1246
1247int NetEqImpl::Decode(PacketList* packet_list, Operations* operation,
1248 int* decoded_length,
1249 AudioDecoder::SpeechType* speech_type) {
1250 *speech_type = AudioDecoder::kSpeech;
minyuel6d92bf52015-09-23 15:20:39 +02001251
1252 // When packet_list is empty, we may be in kCodecInternalCng mode, and for
1253 // that we use current active decoder.
1254 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1255
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001256 if (!packet_list->empty()) {
1257 const Packet* packet = packet_list->front();
pkasting@chromium.org0e81fdf2015-02-02 23:54:03 +00001258 uint8_t payload_type = packet->header.payloadType;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001259 if (!decoder_database_->IsComfortNoise(payload_type)) {
1260 decoder = decoder_database_->GetDecoder(payload_type);
1261 assert(decoder);
1262 if (!decoder) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001263 LOG(LS_WARNING) << "Unknown payload type "
1264 << static_cast<int>(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001265 PacketBuffer::DeleteAllPackets(packet_list);
1266 return kDecoderNotFound;
1267 }
1268 bool decoder_changed;
1269 decoder_database_->SetActiveDecoder(payload_type, &decoder_changed);
1270 if (decoder_changed) {
1271 // We have a new decoder. Re-init some values.
1272 const DecoderDatabase::DecoderInfo* decoder_info = decoder_database_
1273 ->GetDecoderInfo(payload_type);
1274 assert(decoder_info);
1275 if (!decoder_info) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001276 LOG(LS_WARNING) << "Unknown payload type "
1277 << static_cast<int>(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001278 PacketBuffer::DeleteAllPackets(packet_list);
1279 return kDecoderNotFound;
1280 }
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001281 // If sampling rate or number of channels has changed, we need to make
1282 // a reset.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001283 if (decoder_info->fs_hz != fs_hz_ ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001284 decoder->Channels() != algorithm_buffer_->Channels()) {
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001285 // TODO(tlegrand): Add unittest to cover this event.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001286 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->Channels());
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001287 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001288 sync_buffer_->set_end_timestamp(timestamp_);
1289 playout_timestamp_ = timestamp_;
1290 }
1291 }
1292 }
1293
1294 if (reset_decoder_) {
1295 // TODO(hlundin): Write test for this.
Karl Wiberg43766482015-08-27 15:22:11 +02001296 if (decoder)
1297 decoder->Reset();
1298
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001299 // Reset comfort noise decoder.
1300 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02001301 if (cng_decoder)
1302 cng_decoder->Reset();
1303
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001304 reset_decoder_ = false;
1305 }
1306
1307#ifdef LEGACY_BITEXACT
1308 // Due to a bug in old SignalMCU, it could happen that CNG operation was
1309 // decided, but a speech packet was provided. The speech packet will be used
1310 // to update the comfort noise decoder, as if it was a SID frame, which is
1311 // clearly wrong.
1312 if (*operation == kRfc3389Cng) {
1313 return 0;
1314 }
1315#endif
1316
1317 *decoded_length = 0;
1318 // Update codec-internal PLC state.
1319 if ((*operation == kMerge) && decoder && decoder->HasDecodePlc()) {
1320 decoder->DecodePlc(1, &decoded_buffer_[*decoded_length]);
1321 }
1322
minyuel6d92bf52015-09-23 15:20:39 +02001323 int return_value;
1324 if (*operation == kCodecInternalCng) {
1325 RTC_DCHECK(packet_list->empty());
1326 return_value = DecodeCng(decoder, decoded_length, speech_type);
1327 } else {
1328 return_value = DecodeLoop(packet_list, *operation, decoder,
1329 decoded_length, speech_type);
1330 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001331
1332 if (*decoded_length < 0) {
1333 // Error returned from the decoder.
1334 *decoded_length = 0;
Peter Kastingb7e50542015-06-11 12:55:50 -07001335 sync_buffer_->IncreaseEndTimestamp(
1336 static_cast<uint32_t>(decoder_frame_length_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001337 int error_code = 0;
1338 if (decoder)
1339 error_code = decoder->ErrorCode();
1340 if (error_code != 0) {
1341 // Got some error code from the decoder.
1342 decoder_error_code_ = error_code;
1343 return_value = kDecoderErrorCode;
Henrik Lundind67a2192015-08-03 12:54:37 +02001344 LOG(LS_WARNING) << "Decoder returned error code: " << error_code;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001345 } else {
1346 // Decoder does not implement error codes. Return generic error.
1347 return_value = kOtherDecoderError;
Henrik Lundind67a2192015-08-03 12:54:37 +02001348 LOG(LS_WARNING) << "Decoder error (no error code)";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001349 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001350 *operation = kExpand; // Do expansion to get data instead.
1351 }
1352 if (*speech_type != AudioDecoder::kComfortNoise) {
1353 // Don't increment timestamp if codec returned CNG speech type
1354 // since in this case, the we will increment the CNGplayedTS counter.
1355 // Increase with number of samples per channel.
1356 assert(*decoded_length == 0 ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001357 (decoder && decoder->Channels() == sync_buffer_->Channels()));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001358 sync_buffer_->IncreaseEndTimestamp(
1359 *decoded_length / static_cast<int>(sync_buffer_->Channels()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001360 }
1361 return return_value;
1362}
1363
minyuel6d92bf52015-09-23 15:20:39 +02001364int NetEqImpl::DecodeCng(AudioDecoder* decoder, int* decoded_length,
1365 AudioDecoder::SpeechType* speech_type) {
1366 if (!decoder) {
1367 // This happens when active decoder is not defined.
1368 *decoded_length = -1;
1369 return 0;
1370 }
1371
1372 while (*decoded_length < rtc::checked_cast<int>(output_size_samples_)) {
1373 const int length = decoder->Decode(
1374 nullptr, 0, fs_hz_,
1375 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1376 &decoded_buffer_[*decoded_length], speech_type);
1377 if (length > 0) {
1378 *decoded_length += length;
minyuel6d92bf52015-09-23 15:20:39 +02001379 } else {
1380 // Error.
1381 LOG(LS_WARNING) << "Failed to decode CNG";
1382 *decoded_length = -1;
1383 break;
1384 }
1385 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1386 // Guard against overflow.
1387 LOG(LS_WARNING) << "Decoded too much CNG.";
1388 return kDecodedTooMuch;
1389 }
1390 }
1391 return 0;
1392}
1393
1394int NetEqImpl::DecodeLoop(PacketList* packet_list, const Operations& operation,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001395 AudioDecoder* decoder, int* decoded_length,
1396 AudioDecoder::SpeechType* speech_type) {
1397 Packet* packet = NULL;
1398 if (!packet_list->empty()) {
1399 packet = packet_list->front();
1400 }
minyuel6d92bf52015-09-23 15:20:39 +02001401
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001402 // Do decoding.
1403 while (packet &&
1404 !decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1405 assert(decoder); // At this point, we must have a decoder object.
1406 // The number of channels in the |sync_buffer_| should be the same as the
1407 // number decoder channels.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001408 assert(sync_buffer_->Channels() == decoder->Channels());
1409 assert(decoded_buffer_length_ >= kMaxFrameSize * decoder->Channels());
minyuel6d92bf52015-09-23 15:20:39 +02001410 assert(operation == kNormal || operation == kAccelerate ||
1411 operation == kFastAccelerate || operation == kMerge ||
1412 operation == kPreemptiveExpand);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001413 packet_list->pop_front();
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001414 size_t payload_length = packet->payload_length;
Peter Kasting36b7cc32015-06-11 19:57:18 -07001415 int decode_length;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +00001416 if (packet->sync_packet) {
1417 // Decode to silence with the same frame size as the last decode.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001418 memset(&decoded_buffer_[*decoded_length], 0,
1419 decoder_frame_length_ * decoder->Channels() *
1420 sizeof(decoded_buffer_[0]));
Peter Kastingdce40cf2015-08-24 14:52:23 -07001421 decode_length = rtc::checked_cast<int>(decoder_frame_length_);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +00001422 } else if (!packet->primary) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001423 // This is a redundant payload; call the special decoder method.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001424 decode_length = decoder->DecodeRedundant(
henrik.lundin@webrtc.org1eda4e32015-02-25 10:02:29 +00001425 packet->payload, packet->payload_length, fs_hz_,
minyue@webrtc.org7f7d7e32015-03-16 12:30:37 +00001426 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001427 &decoded_buffer_[*decoded_length], speech_type);
1428 } else {
henrik.lundin@webrtc.org1eda4e32015-02-25 10:02:29 +00001429 decode_length =
minyue@webrtc.org7f7d7e32015-03-16 12:30:37 +00001430 decoder->Decode(
1431 packet->payload, packet->payload_length, fs_hz_,
1432 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1433 &decoded_buffer_[*decoded_length], speech_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001434 }
1435
1436 delete[] packet->payload;
1437 delete packet;
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001438 packet = NULL;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001439 if (decode_length > 0) {
1440 *decoded_length += decode_length;
1441 // Update |decoder_frame_length_| with number of samples per channel.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001442 decoder_frame_length_ =
Peter Kastingdce40cf2015-08-24 14:52:23 -07001443 static_cast<size_t>(decode_length) / decoder->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001444 } else if (decode_length < 0) {
1445 // Error.
Henrik Lundind67a2192015-08-03 12:54:37 +02001446 LOG(LS_WARNING) << "Decode " << decode_length << " " << payload_length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001447 *decoded_length = -1;
1448 PacketBuffer::DeleteAllPackets(packet_list);
1449 break;
1450 }
1451 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1452 // Guard against overflow.
Henrik Lundind67a2192015-08-03 12:54:37 +02001453 LOG(LS_WARNING) << "Decoded too much.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001454 PacketBuffer::DeleteAllPackets(packet_list);
1455 return kDecodedTooMuch;
1456 }
1457 if (!packet_list->empty()) {
1458 packet = packet_list->front();
1459 } else {
1460 packet = NULL;
1461 }
1462 } // End of decode loop.
1463
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001464 // If the list is not empty at this point, either a decoding error terminated
1465 // the while-loop, or list must hold exactly one CNG packet.
1466 assert(packet_list->empty() || *decoded_length < 0 ||
1467 (packet_list->size() == 1 && packet &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001468 decoder_database_->IsComfortNoise(packet->header.payloadType)));
1469 return 0;
1470}
1471
1472void NetEqImpl::DoNormal(const int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001473 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001474 assert(normal_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001475 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001476 normal_->Process(decoded_buffer, decoded_length, last_mode_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001477 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001478 if (decoded_length != 0) {
1479 last_mode_ = kModeNormal;
1480 }
1481
1482 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1483 if ((speech_type == AudioDecoder::kComfortNoise)
1484 || ((last_mode_ == kModeCodecInternalCng)
1485 && (decoded_length == 0))) {
1486 // TODO(hlundin): Remove second part of || statement above.
1487 last_mode_ = kModeCodecInternalCng;
1488 }
1489
1490 if (!play_dtmf) {
1491 dtmf_tone_generator_->Reset();
1492 }
1493}
1494
1495void NetEqImpl::DoMerge(int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001496 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001497 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001498 assert(merge_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001499 size_t new_length = merge_->Process(decoded_buffer, decoded_length,
1500 mute_factor_array_.get(),
1501 algorithm_buffer_.get());
1502 size_t expand_length_correction = new_length -
1503 decoded_length / algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001504
1505 // Update in-call and post-call statistics.
1506 if (expand_->MuteFactor(0) == 0) {
1507 // Expand generates only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001508 stats_.ExpandedNoiseSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001509 } else {
1510 // Expansion generates more than only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001511 stats_.ExpandedVoiceSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001512 }
1513
1514 last_mode_ = kModeMerge;
1515 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1516 if (speech_type == AudioDecoder::kComfortNoise) {
1517 last_mode_ = kModeCodecInternalCng;
1518 }
1519 expand_->Reset();
1520 if (!play_dtmf) {
1521 dtmf_tone_generator_->Reset();
1522 }
1523}
1524
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001525int NetEqImpl::DoExpand(bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001526 while ((sync_buffer_->FutureLength() - expand_->overlap_length()) <
Peter Kastingdce40cf2015-08-24 14:52:23 -07001527 output_size_samples_) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001528 algorithm_buffer_->Clear();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001529 int return_value = expand_->Process(algorithm_buffer_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001530 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001531
1532 // Update in-call and post-call statistics.
1533 if (expand_->MuteFactor(0) == 0) {
1534 // Expand operation generates only noise.
1535 stats_.ExpandedNoiseSamples(length);
1536 } else {
1537 // Expand operation generates more than only noise.
1538 stats_.ExpandedVoiceSamples(length);
1539 }
1540
1541 last_mode_ = kModeExpand;
1542
1543 if (return_value < 0) {
1544 return return_value;
1545 }
1546
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001547 sync_buffer_->PushBack(*algorithm_buffer_);
1548 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001549 }
1550 if (!play_dtmf) {
1551 dtmf_tone_generator_->Reset();
1552 }
1553 return 0;
1554}
1555
Henrik Lundincf808d22015-05-27 14:33:29 +02001556int NetEqImpl::DoAccelerate(int16_t* decoded_buffer,
1557 size_t decoded_length,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001558 AudioDecoder::SpeechType speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +02001559 bool play_dtmf,
1560 bool fast_accelerate) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001561 const size_t required_samples =
1562 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001563 size_t borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001564 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001565 size_t decoded_length_per_channel = decoded_length / num_channels;
1566 if (decoded_length_per_channel < required_samples) {
1567 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001568 borrowed_samples_per_channel = static_cast<int>(required_samples -
1569 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001570 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1571 decoded_buffer,
1572 sizeof(int16_t) * decoded_length);
1573 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1574 decoded_buffer);
1575 decoded_length = required_samples * num_channels;
1576 }
1577
Peter Kastingdce40cf2015-08-24 14:52:23 -07001578 size_t samples_removed;
Henrik Lundincf808d22015-05-27 14:33:29 +02001579 Accelerate::ReturnCodes return_code =
1580 accelerate_->Process(decoded_buffer, decoded_length, fast_accelerate,
1581 algorithm_buffer_.get(), &samples_removed);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001582 stats_.AcceleratedSamples(samples_removed);
1583 switch (return_code) {
1584 case Accelerate::kSuccess:
1585 last_mode_ = kModeAccelerateSuccess;
1586 break;
1587 case Accelerate::kSuccessLowEnergy:
1588 last_mode_ = kModeAccelerateLowEnergy;
1589 break;
1590 case Accelerate::kNoStretch:
1591 last_mode_ = kModeAccelerateFail;
1592 break;
1593 case Accelerate::kError:
1594 // TODO(hlundin): Map to kModeError instead?
1595 last_mode_ = kModeAccelerateFail;
1596 return kAccelerateError;
1597 }
1598
1599 if (borrowed_samples_per_channel > 0) {
1600 // Copy borrowed samples back to the |sync_buffer_|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001601 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001602 if (length < borrowed_samples_per_channel) {
1603 // This destroys the beginning of the buffer, but will not cause any
1604 // problems.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001605 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001606 sync_buffer_->Size() -
1607 borrowed_samples_per_channel);
1608 sync_buffer_->PushFrontZeros(borrowed_samples_per_channel - length);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001609 algorithm_buffer_->PopFront(length);
1610 assert(algorithm_buffer_->Empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001611 } else {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001612 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001613 borrowed_samples_per_channel,
1614 sync_buffer_->Size() -
1615 borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001616 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001617 }
1618 }
1619
1620 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1621 if (speech_type == AudioDecoder::kComfortNoise) {
1622 last_mode_ = kModeCodecInternalCng;
1623 }
1624 if (!play_dtmf) {
1625 dtmf_tone_generator_->Reset();
1626 }
1627 expand_->Reset();
1628 return 0;
1629}
1630
1631int NetEqImpl::DoPreemptiveExpand(int16_t* decoded_buffer,
1632 size_t decoded_length,
1633 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001634 bool play_dtmf) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001635 const size_t required_samples =
1636 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001637 size_t num_channels = algorithm_buffer_->Channels();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001638 size_t borrowed_samples_per_channel = 0;
1639 size_t old_borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001640 size_t decoded_length_per_channel = decoded_length / num_channels;
1641 if (decoded_length_per_channel < required_samples) {
1642 // Must move data from the |sync_buffer_| in order to get 30 ms.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001643 borrowed_samples_per_channel =
1644 required_samples - decoded_length_per_channel;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001645 // Calculate how many of these were already played out.
Peter Kastingf045e4d2015-06-10 21:15:38 -07001646 old_borrowed_samples_per_channel =
Peter Kastingdce40cf2015-08-24 14:52:23 -07001647 (borrowed_samples_per_channel > sync_buffer_->FutureLength()) ?
1648 (borrowed_samples_per_channel - sync_buffer_->FutureLength()) : 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001649 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1650 decoded_buffer,
1651 sizeof(int16_t) * decoded_length);
1652 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1653 decoded_buffer);
1654 decoded_length = required_samples * num_channels;
1655 }
1656
Peter Kastingdce40cf2015-08-24 14:52:23 -07001657 size_t samples_added;
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001658 PreemptiveExpand::ReturnCodes return_code = preemptive_expand_->Process(
Peter Kastingdce40cf2015-08-24 14:52:23 -07001659 decoded_buffer, decoded_length,
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001660 old_borrowed_samples_per_channel,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001661 algorithm_buffer_.get(), &samples_added);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001662 stats_.PreemptiveExpandedSamples(samples_added);
1663 switch (return_code) {
1664 case PreemptiveExpand::kSuccess:
1665 last_mode_ = kModePreemptiveExpandSuccess;
1666 break;
1667 case PreemptiveExpand::kSuccessLowEnergy:
1668 last_mode_ = kModePreemptiveExpandLowEnergy;
1669 break;
1670 case PreemptiveExpand::kNoStretch:
1671 last_mode_ = kModePreemptiveExpandFail;
1672 break;
1673 case PreemptiveExpand::kError:
1674 // TODO(hlundin): Map to kModeError instead?
1675 last_mode_ = kModePreemptiveExpandFail;
1676 return kPreemptiveExpandError;
1677 }
1678
1679 if (borrowed_samples_per_channel > 0) {
1680 // Copy borrowed samples back to the |sync_buffer_|.
1681 sync_buffer_->ReplaceAtIndex(
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001682 *algorithm_buffer_, borrowed_samples_per_channel,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001683 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001684 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001685 }
1686
1687 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1688 if (speech_type == AudioDecoder::kComfortNoise) {
1689 last_mode_ = kModeCodecInternalCng;
1690 }
1691 if (!play_dtmf) {
1692 dtmf_tone_generator_->Reset();
1693 }
1694 expand_->Reset();
1695 return 0;
1696}
1697
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001698int NetEqImpl::DoRfc3389Cng(PacketList* packet_list, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001699 if (!packet_list->empty()) {
1700 // Must have exactly one SID frame at this point.
1701 assert(packet_list->size() == 1);
1702 Packet* packet = packet_list->front();
1703 packet_list->pop_front();
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001704 if (!decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1705#ifdef LEGACY_BITEXACT
1706 // This can happen due to a bug in GetDecision. Change the payload type
1707 // to a CNG type, and move on. Note that this means that we are in fact
1708 // sending a non-CNG payload to the comfort noise decoder for decoding.
1709 // Clearly wrong, but will maintain bit-exactness with legacy.
1710 if (fs_hz_ == 8000) {
1711 packet->header.payloadType =
kwibergee1879c2015-10-29 06:20:28 -07001712 decoder_database_->GetRtpPayloadType(NetEqDecoder::kDecoderCNGnb);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001713 } else if (fs_hz_ == 16000) {
1714 packet->header.payloadType =
kwibergee1879c2015-10-29 06:20:28 -07001715 decoder_database_->GetRtpPayloadType(NetEqDecoder::kDecoderCNGwb);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001716 } else if (fs_hz_ == 32000) {
kwibergee1879c2015-10-29 06:20:28 -07001717 packet->header.payloadType = decoder_database_->GetRtpPayloadType(
1718 NetEqDecoder::kDecoderCNGswb32kHz);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001719 } else if (fs_hz_ == 48000) {
kwibergee1879c2015-10-29 06:20:28 -07001720 packet->header.payloadType = decoder_database_->GetRtpPayloadType(
1721 NetEqDecoder::kDecoderCNGswb48kHz);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001722 }
1723 assert(decoder_database_->IsComfortNoise(packet->header.payloadType));
1724#else
1725 LOG(LS_ERROR) << "Trying to decode non-CNG payload as CNG.";
1726 return kOtherError;
1727#endif
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001728 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001729 // UpdateParameters() deletes |packet|.
1730 if (comfort_noise_->UpdateParameters(packet) ==
1731 ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001732 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001733 return -comfort_noise_->internal_error_code();
1734 }
1735 }
1736 int cn_return = comfort_noise_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001737 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001738 expand_->Reset();
1739 last_mode_ = kModeRfc3389Cng;
1740 if (!play_dtmf) {
1741 dtmf_tone_generator_->Reset();
1742 }
1743 if (cn_return == ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001744 decoder_error_code_ = comfort_noise_->internal_error_code();
1745 return kComfortNoiseErrorCode;
1746 } else if (cn_return == ComfortNoise::kUnknownPayloadType) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001747 return kUnknownRtpPayloadType;
1748 }
1749 return 0;
1750}
1751
minyuel6d92bf52015-09-23 15:20:39 +02001752void NetEqImpl::DoCodecInternalCng(const int16_t* decoded_buffer,
1753 size_t decoded_length) {
1754 RTC_DCHECK(normal_.get());
1755 RTC_DCHECK(mute_factor_array_.get());
1756 normal_->Process(decoded_buffer, decoded_length, last_mode_,
1757 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001758 last_mode_ = kModeCodecInternalCng;
1759 expand_->Reset();
1760}
1761
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001762int NetEqImpl::DoDtmf(const DtmfEvent& dtmf_event, bool* play_dtmf) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001763 // This block of the code and the block further down, handling |dtmf_switch|
1764 // are commented out. Otherwise playing out-of-band DTMF would fail in VoE
1765 // test, DtmfTest.ManualSuccessfullySendsOutOfBandTelephoneEvents. This is
1766 // equivalent to |dtmf_switch| always be false.
1767 //
1768 // See http://webrtc-codereview.appspot.com/1195004/ for discussion
1769 // On this issue. This change might cause some glitches at the point of
1770 // switch from audio to DTMF. Issue 1545 is filed to track this.
1771 //
1772 // bool dtmf_switch = false;
1773 // if ((last_mode_ != kModeDtmf) && dtmf_tone_generator_->initialized()) {
1774 // // Special case; see below.
1775 // // We must catch this before calling Generate, since |initialized| is
1776 // // modified in that call.
1777 // dtmf_switch = true;
1778 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001779
1780 int dtmf_return_value = 0;
1781 if (!dtmf_tone_generator_->initialized()) {
1782 // Initialize if not already done.
1783 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1784 dtmf_event.volume);
1785 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001786
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001787 if (dtmf_return_value == 0) {
1788 // Generate DTMF signal.
1789 dtmf_return_value = dtmf_tone_generator_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001790 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001791 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001792
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001793 if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001794 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001795 return dtmf_return_value;
1796 }
1797
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001798 // if (dtmf_switch) {
1799 // // This is the special case where the previous operation was DTMF
1800 // // overdub, but the current instruction is "regular" DTMF. We must make
1801 // // sure that the DTMF does not have any discontinuities. The first DTMF
1802 // // sample that we generate now must be played out immediately, therefore
1803 // // it must be copied to the speech buffer.
1804 // // TODO(hlundin): This code seems incorrect. (Legacy.) Write test and
1805 // // verify correct operation.
1806 // assert(false);
1807 // // Must generate enough data to replace all of the |sync_buffer_|
1808 // // "future".
1809 // int required_length = sync_buffer_->FutureLength();
1810 // assert(dtmf_tone_generator_->initialized());
1811 // dtmf_return_value = dtmf_tone_generator_->Generate(required_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001812 // algorithm_buffer_);
1813 // assert((size_t) required_length == algorithm_buffer_->Size());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001814 // if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001815 // algorithm_buffer_->Zeros(output_size_samples_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001816 // return dtmf_return_value;
1817 // }
1818 //
1819 // // Overwrite the "future" part of the speech buffer with the new DTMF
1820 // // data.
1821 // // TODO(hlundin): It seems that this overwriting has gone lost.
1822 // // Not adapted for multi-channel yet.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001823 // assert(algorithm_buffer_->Channels() == 1);
1824 // if (algorithm_buffer_->Channels() != 1) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001825 // LOG(LS_WARNING) << "DTMF not supported for more than one channel";
1826 // return kStereoNotSupported;
1827 // }
1828 // // Shuffle the remaining data to the beginning of algorithm buffer.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001829 // algorithm_buffer_->PopFront(sync_buffer_->FutureLength());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001830 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001831
Peter Kastingb7e50542015-06-11 12:55:50 -07001832 sync_buffer_->IncreaseEndTimestamp(
1833 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001834 expand_->Reset();
1835 last_mode_ = kModeDtmf;
1836
1837 // Set to false because the DTMF is already in the algorithm buffer.
1838 *play_dtmf = false;
1839 return 0;
1840}
1841
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001842void NetEqImpl::DoAlternativePlc(bool increase_timestamp) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001843 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001844 size_t length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001845 if (decoder && decoder->HasDecodePlc()) {
1846 // Use the decoder's packet-loss concealment.
1847 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1848 int16_t decoded_buffer[kMaxFrameSize];
1849 length = decoder->DecodePlc(1, decoded_buffer);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001850 if (length > 0)
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001851 algorithm_buffer_->PushBackInterleaved(decoded_buffer, length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001852 } else {
1853 // Do simple zero-stuffing.
1854 length = output_size_samples_;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001855 algorithm_buffer_->Zeros(length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001856 // By not advancing the timestamp, NetEq inserts samples.
1857 stats_.AddZeros(length);
1858 }
1859 if (increase_timestamp) {
Peter Kastingb7e50542015-06-11 12:55:50 -07001860 sync_buffer_->IncreaseEndTimestamp(static_cast<uint32_t>(length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001861 }
1862 expand_->Reset();
1863}
1864
1865int NetEqImpl::DtmfOverdub(const DtmfEvent& dtmf_event, size_t num_channels,
1866 int16_t* output) const {
1867 size_t out_index = 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001868 size_t overdub_length = output_size_samples_; // Default value.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001869
1870 if (sync_buffer_->dtmf_index() > sync_buffer_->next_index()) {
1871 // Special operation for transition from "DTMF only" to "DTMF overdub".
1872 out_index = std::min(
1873 sync_buffer_->dtmf_index() - sync_buffer_->next_index(),
Peter Kastingdce40cf2015-08-24 14:52:23 -07001874 output_size_samples_);
1875 overdub_length = output_size_samples_ - out_index;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001876 }
1877
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001878 AudioMultiVector dtmf_output(num_channels);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001879 int dtmf_return_value = 0;
1880 if (!dtmf_tone_generator_->initialized()) {
1881 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1882 dtmf_event.volume);
1883 }
1884 if (dtmf_return_value == 0) {
1885 dtmf_return_value = dtmf_tone_generator_->Generate(overdub_length,
1886 &dtmf_output);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001887 assert(overdub_length == dtmf_output.Size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001888 }
1889 dtmf_output.ReadInterleaved(overdub_length, &output[out_index]);
1890 return dtmf_return_value < 0 ? dtmf_return_value : 0;
1891}
1892
Peter Kastingdce40cf2015-08-24 14:52:23 -07001893int NetEqImpl::ExtractPackets(size_t required_samples,
1894 PacketList* packet_list) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001895 bool first_packet = true;
1896 uint8_t prev_payload_type = 0;
1897 uint32_t prev_timestamp = 0;
1898 uint16_t prev_sequence_number = 0;
1899 bool next_packet_available = false;
1900
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001901 const RTPHeader* header = packet_buffer_->NextRtpHeader();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001902 assert(header);
1903 if (!header) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001904 LOG(LS_ERROR) << "Packet buffer unexpectedly empty.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001905 return -1;
1906 }
turaj@webrtc.org7df97062013-08-02 18:07:13 +00001907 uint32_t first_timestamp = header->timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001908 int extracted_samples = 0;
1909
1910 // Packet extraction loop.
1911 do {
1912 timestamp_ = header->timestamp;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001913 size_t discard_count = 0;
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001914 Packet* packet = packet_buffer_->GetNextPacket(&discard_count);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001915 // |header| may be invalid after the |packet_buffer_| operation.
1916 header = NULL;
1917 if (!packet) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001918 LOG(LS_ERROR) << "Should always be able to extract a packet here";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001919 assert(false); // Should always be able to extract a packet here.
1920 return -1;
1921 }
1922 stats_.PacketsDiscarded(discard_count);
1923 // Store waiting time in ms; packets->waiting_time is in "output blocks".
1924 stats_.StoreWaitingTime(packet->waiting_time * kOutputSizeMs);
1925 assert(packet->payload_length > 0);
1926 packet_list->push_back(packet); // Store packet in list.
1927
1928 if (first_packet) {
1929 first_packet = false;
henrik.lundin48ed9302015-10-29 05:36:24 -07001930 if (nack_enabled_) {
1931 RTC_DCHECK(nack_);
1932 // TODO(henrik.lundin): Should we update this for all decoded packets?
1933 nack_->UpdateLastDecodedPacket(packet->header.sequenceNumber,
1934 packet->header.timestamp);
1935 }
1936 prev_sequence_number = packet->header.sequenceNumber;
1937 prev_timestamp = packet->header.timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001938 prev_payload_type = packet->header.payloadType;
1939 }
1940
1941 // Store number of extracted samples.
1942 int packet_duration = 0;
1943 AudioDecoder* decoder = decoder_database_->GetDecoder(
1944 packet->header.payloadType);
1945 if (decoder) {
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001946 if (packet->sync_packet) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001947 packet_duration = rtc::checked_cast<int>(decoder_frame_length_);
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001948 } else {
minyue@webrtc.org2c1bcf22015-02-17 10:17:09 +00001949 if (packet->primary) {
1950 packet_duration = decoder->PacketDuration(packet->payload,
1951 packet->payload_length);
1952 } else {
1953 packet_duration = decoder->
1954 PacketDurationRedundant(packet->payload, packet->payload_length);
1955 stats_.SecondaryDecodedSamples(packet_duration);
1956 }
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001957 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001958 } else {
Henrik Lundind67a2192015-08-03 12:54:37 +02001959 LOG(LS_WARNING) << "Unknown payload type "
1960 << static_cast<int>(packet->header.payloadType);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001961 assert(false);
1962 }
1963 if (packet_duration <= 0) {
1964 // Decoder did not return a packet duration. Assume that the packet
1965 // contains the same number of samples as the previous one.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001966 packet_duration = rtc::checked_cast<int>(decoder_frame_length_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001967 }
1968 extracted_samples = packet->header.timestamp - first_timestamp +
1969 packet_duration;
1970
1971 // Check what packet is available next.
1972 header = packet_buffer_->NextRtpHeader();
1973 next_packet_available = false;
1974 if (header && prev_payload_type == header->payloadType) {
1975 int16_t seq_no_diff = header->sequenceNumber - prev_sequence_number;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001976 size_t ts_diff = header->timestamp - prev_timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001977 if (seq_no_diff == 1 ||
1978 (seq_no_diff == 0 && ts_diff == decoder_frame_length_)) {
1979 // The next sequence number is available, or the next part of a packet
1980 // that was split into pieces upon insertion.
1981 next_packet_available = true;
1982 }
1983 prev_sequence_number = header->sequenceNumber;
1984 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07001985 } while (extracted_samples < rtc::checked_cast<int>(required_samples) &&
1986 next_packet_available);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001987
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00001988 if (extracted_samples > 0) {
1989 // Delete old packets only when we are going to decode something. Otherwise,
1990 // we could end up in the situation where we never decode anything, since
1991 // all incoming packets are considered too old but the buffer will also
1992 // never be flooded and flushed.
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001993 packet_buffer_->DiscardAllOldPackets(timestamp_);
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00001994 }
1995
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001996 return extracted_samples;
1997}
1998
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001999void NetEqImpl::UpdatePlcComponents(int fs_hz, size_t channels) {
2000 // Delete objects and create new ones.
2001 expand_.reset(expand_factory_->Create(background_noise_.get(),
2002 sync_buffer_.get(), &random_vector_,
Henrik Lundinbef77e22015-08-18 14:58:09 +02002003 &stats_, fs_hz, channels));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002004 merge_.reset(new Merge(fs_hz, channels, expand_.get(), sync_buffer_.get()));
2005}
2006
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002007void NetEqImpl::SetSampleRateAndChannels(int fs_hz, size_t channels) {
Henrik Lundind67a2192015-08-03 12:54:37 +02002008 LOG(LS_VERBOSE) << "SetSampleRateAndChannels " << fs_hz << " " << channels;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002009 // TODO(hlundin): Change to an enumerator and skip assert.
2010 assert(fs_hz == 8000 || fs_hz == 16000 || fs_hz == 32000 || fs_hz == 48000);
2011 assert(channels > 0);
2012
2013 fs_hz_ = fs_hz;
2014 fs_mult_ = fs_hz / 8000;
Peter Kastingdce40cf2015-08-24 14:52:23 -07002015 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002016 decoder_frame_length_ = 3 * output_size_samples_; // Initialize to 30ms.
2017
2018 last_mode_ = kModeNormal;
2019
2020 // Create a new array of mute factors and set all to 1.
2021 mute_factor_array_.reset(new int16_t[channels]);
2022 for (size_t i = 0; i < channels; ++i) {
2023 mute_factor_array_[i] = 16384; // 1.0 in Q14.
2024 }
2025
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002026 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02002027 if (cng_decoder)
2028 cng_decoder->Reset();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002029
2030 // Reinit post-decode VAD with new sample rate.
2031 assert(vad_.get()); // Cannot be NULL here.
2032 vad_->Init();
2033
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002034 // Delete algorithm buffer and create a new one.
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00002035 algorithm_buffer_.reset(new AudioMultiVector(channels));
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002036
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002037 // Delete sync buffer and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002038 sync_buffer_.reset(new SyncBuffer(channels, kSyncBufferSize * fs_mult_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002039
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00002040 // Delete BackgroundNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002041 background_noise_.reset(new BackgroundNoise(channels));
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00002042 background_noise_->set_mode(background_noise_mode_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002043
2044 // Reset random vector.
2045 random_vector_.Reset();
2046
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002047 UpdatePlcComponents(fs_hz, channels);
2048
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002049 // Move index so that we create a small set of future samples (all 0).
2050 sync_buffer_->set_next_index(sync_buffer_->next_index() -
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002051 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002052
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002053 normal_.reset(new Normal(fs_hz, decoder_database_.get(), *background_noise_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002054 expand_.get()));
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +00002055 accelerate_.reset(
2056 accelerate_factory_->Create(fs_hz, channels, *background_noise_));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002057 preemptive_expand_.reset(preemptive_expand_factory_->Create(
Peter Kastingdce40cf2015-08-24 14:52:23 -07002058 fs_hz, channels, *background_noise_, expand_->overlap_length()));
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002059
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002060 // Delete ComfortNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002061 comfort_noise_.reset(new ComfortNoise(fs_hz, decoder_database_.get(),
2062 sync_buffer_.get()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002063
2064 // Verify that |decoded_buffer_| is long enough.
2065 if (decoded_buffer_length_ < kMaxFrameSize * channels) {
2066 // Reallocate to larger size.
2067 decoded_buffer_length_ = kMaxFrameSize * channels;
2068 decoded_buffer_.reset(new int16_t[decoded_buffer_length_]);
2069 }
2070
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002071 // Create DecisionLogic if it is not created yet, then communicate new sample
2072 // rate and output size to DecisionLogic object.
2073 if (!decision_logic_.get()) {
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002074 CreateDecisionLogic();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002075 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002076 decision_logic_->SetSampleRate(fs_hz_, output_size_samples_);
2077}
2078
henrik.lundin55480f52016-03-08 02:37:57 -08002079NetEqImpl::OutputType NetEqImpl::LastOutputType() {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002080 assert(vad_.get());
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002081 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002082 if (last_mode_ == kModeCodecInternalCng || last_mode_ == kModeRfc3389Cng) {
henrik.lundin55480f52016-03-08 02:37:57 -08002083 return OutputType::kCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002084 } else if (last_mode_ == kModeExpand && expand_->MuteFactor(0) == 0) {
2085 // Expand mode has faded down to background noise only (very long expand).
henrik.lundin55480f52016-03-08 02:37:57 -08002086 return OutputType::kPLCCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002087 } else if (last_mode_ == kModeExpand) {
henrik.lundin55480f52016-03-08 02:37:57 -08002088 return OutputType::kPLC;
wu@webrtc.org24301a62013-12-13 19:17:43 +00002089 } else if (vad_->running() && !vad_->active_speech()) {
henrik.lundin55480f52016-03-08 02:37:57 -08002090 return OutputType::kVadPassive;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002091 } else {
henrik.lundin55480f52016-03-08 02:37:57 -08002092 return OutputType::kNormalSpeech;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002093 }
2094}
2095
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002096void NetEqImpl::CreateDecisionLogic() {
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002097 decision_logic_.reset(DecisionLogic::Create(fs_hz_, output_size_samples_,
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002098 playout_mode_,
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002099 decoder_database_.get(),
2100 *packet_buffer_.get(),
2101 delay_manager_.get(),
2102 buffer_level_filter_.get()));
2103}
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002104} // namespace webrtc