blob: 40a031421eb96e2bcfed865408ca2c7b8dea9555 [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_);
wu@webrtc.org94454b72014-06-05 20:34:08 +0000406 if (first_packet_) {
407 // We don't have a valid RTP timestamp until we have decoded our first
408 // RTP packet.
henrik.lundin9a410dd2016-04-06 01:39:22 -0700409 return rtc::Optional<uint32_t>();
wu@webrtc.org94454b72014-06-05 20:34:08 +0000410 }
henrik.lundin9a410dd2016-04-06 01:39:22 -0700411 return rtc::Optional<uint32_t>(
412 timestamp_scaler_->ToExternal(playout_timestamp_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000413}
414
henrik.lundind89814b2015-11-23 06:49:25 -0800415int NetEqImpl::last_output_sample_rate_hz() const {
Tommi9090e0b2016-01-20 13:39:36 +0100416 rtc::CritScope lock(&crit_sect_);
henrik.lundind89814b2015-11-23 06:49:25 -0800417 return last_output_sample_rate_hz_;
418}
419
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200420int NetEqImpl::SetTargetNumberOfChannels() {
421 return kNotImplemented;
422}
423
424int NetEqImpl::SetTargetSampleRate() {
425 return kNotImplemented;
426}
427
henrik.lundin@webrtc.orgb0f4b3d2014-11-04 08:53:10 +0000428int NetEqImpl::LastError() const {
Tommi9090e0b2016-01-20 13:39:36 +0100429 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000430 return error_code_;
431}
432
433int NetEqImpl::LastDecoderError() {
Tommi9090e0b2016-01-20 13:39:36 +0100434 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000435 return decoder_error_code_;
436}
437
438void NetEqImpl::FlushBuffers() {
Tommi9090e0b2016-01-20 13:39:36 +0100439 rtc::CritScope lock(&crit_sect_);
Henrik Lundind67a2192015-08-03 12:54:37 +0200440 LOG(LS_VERBOSE) << "FlushBuffers";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000441 packet_buffer_->Flush();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000442 assert(sync_buffer_.get());
443 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000444 sync_buffer_->Flush();
445 sync_buffer_->set_next_index(sync_buffer_->next_index() -
446 expand_->overlap_length());
447 // Set to wait for new codec.
448 first_packet_ = true;
449}
450
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000451void NetEqImpl::PacketBufferStatistics(int* current_num_packets,
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000452 int* max_num_packets) const {
Tommi9090e0b2016-01-20 13:39:36 +0100453 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000454 packet_buffer_->BufferStat(current_num_packets, max_num_packets);
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000455}
456
henrik.lundin48ed9302015-10-29 05:36:24 -0700457void NetEqImpl::EnableNack(size_t max_nack_list_size) {
Tommi9090e0b2016-01-20 13:39:36 +0100458 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700459 if (!nack_enabled_) {
460 const int kNackThresholdPackets = 2;
461 nack_.reset(Nack::Create(kNackThresholdPackets));
462 nack_enabled_ = true;
463 nack_->UpdateSampleRate(fs_hz_);
464 }
465 nack_->SetMaxNackListSize(max_nack_list_size);
466}
467
468void NetEqImpl::DisableNack() {
Tommi9090e0b2016-01-20 13:39:36 +0100469 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700470 nack_.reset();
471 nack_enabled_ = false;
472}
473
474std::vector<uint16_t> NetEqImpl::GetNackList(int64_t round_trip_time_ms) const {
Tommi9090e0b2016-01-20 13:39:36 +0100475 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700476 if (!nack_enabled_) {
477 return std::vector<uint16_t>();
478 }
479 RTC_DCHECK(nack_.get());
480 return nack_->GetNackList(round_trip_time_ms);
minyue@webrtc.orgd7301772013-08-29 00:58:14 +0000481}
482
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000483const SyncBuffer* NetEqImpl::sync_buffer_for_test() const {
Tommi9090e0b2016-01-20 13:39:36 +0100484 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000485 return sync_buffer_.get();
486}
487
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000488// Methods below this line are private.
489
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000490int NetEqImpl::InsertPacketInternal(const WebRtcRTPHeader& rtp_header,
kwibergee2bac22015-11-11 10:34:00 -0800491 rtc::ArrayView<const uint8_t> payload,
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000492 uint32_t receive_timestamp,
493 bool is_sync_packet) {
kwibergee2bac22015-11-11 10:34:00 -0800494 if (payload.empty()) {
495 LOG_F(LS_ERROR) << "payload is empty";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000496 return kInvalidPointer;
497 }
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000498 // Sanity checks for sync-packets.
499 if (is_sync_packet) {
500 if (decoder_database_->IsDtmf(rtp_header.header.payloadType) ||
501 decoder_database_->IsRed(rtp_header.header.payloadType) ||
502 decoder_database_->IsComfortNoise(rtp_header.header.payloadType)) {
503 LOG_F(LS_ERROR) << "Sync-packet with an unacceptable payload type "
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000504 << static_cast<int>(rtp_header.header.payloadType);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000505 return kSyncPacketNotAccepted;
506 }
507 if (first_packet_ ||
508 rtp_header.header.payloadType != current_rtp_payload_type_ ||
509 rtp_header.header.ssrc != ssrc_) {
510 // Even if |current_rtp_payload_type_| is 0xFF, sync-packet isn't
511 // accepted.
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000512 LOG_F(LS_ERROR)
513 << "Changing codec, SSRC or first packet with sync-packet.";
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000514 return kSyncPacketNotAccepted;
515 }
516 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000517 PacketList packet_list;
518 RTPHeader main_header;
519 {
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000520 // Convert to Packet.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000521 // Create |packet| within this separate scope, since it should not be used
522 // directly once it's been inserted in the packet list. This way, |packet|
523 // is not defined outside of this block.
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000524 Packet* packet = new Packet;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000525 packet->header.markerBit = false;
526 packet->header.payloadType = rtp_header.header.payloadType;
527 packet->header.sequenceNumber = rtp_header.header.sequenceNumber;
528 packet->header.timestamp = rtp_header.header.timestamp;
529 packet->header.ssrc = rtp_header.header.ssrc;
530 packet->header.numCSRCs = 0;
kwibergee2bac22015-11-11 10:34:00 -0800531 packet->payload_length = payload.size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000532 packet->primary = true;
533 packet->waiting_time = 0;
534 packet->payload = new uint8_t[packet->payload_length];
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000535 packet->sync_packet = is_sync_packet;
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +0000536 if (!packet->payload) {
537 LOG_F(LS_ERROR) << "Payload pointer is NULL.";
538 }
kwibergee2bac22015-11-11 10:34:00 -0800539 assert(!payload.empty()); // Already checked above.
540 memcpy(packet->payload, payload.data(), packet->payload_length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000541 // Insert packet in a packet list.
542 packet_list.push_back(packet);
543 // Save main payloads header for later.
544 memcpy(&main_header, &packet->header, sizeof(main_header));
545 }
546
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000547 bool update_sample_rate_and_channels = false;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000548 // Reinitialize NetEq if it's needed (changed SSRC or first call).
549 if ((main_header.ssrc != ssrc_) || first_packet_) {
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000550 // Note: |first_packet_| will be cleared further down in this method, once
551 // the packet has been successfully inserted into the packet buffer.
552
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000553 rtcp_.Init(main_header.sequenceNumber);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000554
555 // Flush the packet buffer and DTMF buffer.
556 packet_buffer_->Flush();
557 dtmf_buffer_->Flush();
558
559 // Store new SSRC.
560 ssrc_ = main_header.ssrc;
561
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000562 // Update audio buffer timestamp.
563 sync_buffer_->IncreaseEndTimestamp(main_header.timestamp - timestamp_);
564
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000565 // Update codecs.
566 timestamp_ = main_header.timestamp;
567 current_rtp_payload_type_ = main_header.payloadType;
568
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000569 // Reset timestamp scaling.
570 timestamp_scaler_->Reset();
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000571
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000572 // Trigger an update of sampling rate and the number of channels.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000573 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000574 }
575
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000576 // Update RTCP statistics, only for regular packets.
577 if (!is_sync_packet)
578 rtcp_.Update(main_header, receive_timestamp);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000579
580 // Check for RED payload type, and separate payloads into several packets.
581 if (decoder_database_->IsRed(main_header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000582 assert(!is_sync_packet); // We had a sanity check for this.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000583 if (payload_splitter_->SplitRed(&packet_list) != PayloadSplitter::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000584 PacketBuffer::DeleteAllPackets(&packet_list);
585 return kRedundancySplitError;
586 }
587 // Only accept a few RED payloads of the same type as the main data,
588 // DTMF events and CNG.
589 payload_splitter_->CheckRedPayloads(&packet_list, *decoder_database_);
590 // Update the stored main payload header since the main payload has now
591 // changed.
592 memcpy(&main_header, &packet_list.front()->header, sizeof(main_header));
593 }
594
595 // Check payload types.
596 if (decoder_database_->CheckPayloadTypes(packet_list) ==
597 DecoderDatabase::kDecoderNotFound) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000598 PacketBuffer::DeleteAllPackets(&packet_list);
599 return kUnknownRtpPayloadType;
600 }
601
602 // Scale timestamp to internal domain (only for some codecs).
603 timestamp_scaler_->ToInternal(&packet_list);
604
605 // Process DTMF payloads. Cycle through the list of packets, and pick out any
606 // DTMF payloads found.
607 PacketList::iterator it = packet_list.begin();
608 while (it != packet_list.end()) {
609 Packet* current_packet = (*it);
610 assert(current_packet);
611 assert(current_packet->payload);
612 if (decoder_database_->IsDtmf(current_packet->header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000613 assert(!current_packet->sync_packet); // We had a sanity check for this.
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000614 DtmfEvent event;
615 int ret = DtmfBuffer::ParseEvent(
616 current_packet->header.timestamp,
617 current_packet->payload,
618 current_packet->payload_length,
619 &event);
620 if (ret != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000621 PacketBuffer::DeleteAllPackets(&packet_list);
622 return kDtmfParsingError;
623 }
624 if (dtmf_buffer_->InsertEvent(event) != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000625 PacketBuffer::DeleteAllPackets(&packet_list);
626 return kDtmfInsertError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000627 }
628 // TODO(hlundin): Let the destructor of Packet handle the payload.
629 delete [] current_packet->payload;
630 delete current_packet;
631 it = packet_list.erase(it);
632 } else {
633 ++it;
634 }
635 }
636
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000637 // Check for FEC in packets, and separate payloads into several packets.
638 int ret = payload_splitter_->SplitFec(&packet_list, decoder_database_.get());
639 if (ret != PayloadSplitter::kOK) {
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000640 PacketBuffer::DeleteAllPackets(&packet_list);
641 switch (ret) {
642 case PayloadSplitter::kUnknownPayloadType:
643 return kUnknownRtpPayloadType;
644 default:
645 return kOtherError;
646 }
647 }
648
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000649 // Split payloads into smaller chunks. This also verifies that all payloads
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000650 // are of a known payload type. SplitAudio() method is protected against
651 // sync-packets.
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +0000652 ret = payload_splitter_->SplitAudio(&packet_list, *decoder_database_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000653 if (ret != PayloadSplitter::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000654 PacketBuffer::DeleteAllPackets(&packet_list);
655 switch (ret) {
656 case PayloadSplitter::kUnknownPayloadType:
657 return kUnknownRtpPayloadType;
658 case PayloadSplitter::kFrameSplitError:
659 return kFrameSplitError;
660 default:
661 return kOtherError;
662 }
663 }
664
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000665 // Update bandwidth estimate, if the packet is not sync-packet.
666 if (!packet_list.empty() && !packet_list.front()->sync_packet) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000667 // The list can be empty here if we got nothing but DTMF payloads.
668 AudioDecoder* decoder =
669 decoder_database_->GetDecoder(main_header.payloadType);
670 assert(decoder); // Should always get a valid object, since we have
671 // already checked that the payload types are known.
672 decoder->IncomingPacket(packet_list.front()->payload,
673 packet_list.front()->payload_length,
674 packet_list.front()->header.sequenceNumber,
675 packet_list.front()->header.timestamp,
676 receive_timestamp);
677 }
678
henrik.lundin48ed9302015-10-29 05:36:24 -0700679 if (nack_enabled_) {
680 RTC_DCHECK(nack_);
681 if (update_sample_rate_and_channels) {
682 nack_->Reset();
683 }
684 nack_->UpdateLastReceivedPacket(packet_list.front()->header.sequenceNumber,
685 packet_list.front()->header.timestamp);
686 }
687
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000688 // Insert packets in buffer.
henrik.lundin116c84e2015-08-27 13:14:48 -0700689 const size_t buffer_length_before_insert =
690 packet_buffer_->NumPacketsInBuffer();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000691 ret = packet_buffer_->InsertPacketList(
692 &packet_list,
693 *decoder_database_,
694 &current_rtp_payload_type_,
695 &current_cng_rtp_payload_type_);
696 if (ret == PacketBuffer::kFlushed) {
697 // Reset DSP timestamp etc. if packet buffer flushed.
698 new_codec_ = true;
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000699 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000700 } else if (ret != PacketBuffer::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000701 PacketBuffer::DeleteAllPackets(&packet_list);
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000702 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000703 }
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000704
705 if (first_packet_) {
706 first_packet_ = false;
707 // Update the codec on the next GetAudio call.
708 new_codec_ = true;
709 }
710
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000711 if (current_rtp_payload_type_ != 0xFF) {
712 const DecoderDatabase::DecoderInfo* dec_info =
713 decoder_database_->GetDecoderInfo(current_rtp_payload_type_);
714 if (!dec_info) {
715 assert(false); // Already checked that the payload type is known.
716 }
717 }
718
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000719 if (update_sample_rate_and_channels && !packet_buffer_->Empty()) {
720 // We do not use |current_rtp_payload_type_| to |set payload_type|, but
721 // get the next RTP header from |packet_buffer_| to obtain the payload type.
722 // The reason for it is the following corner case. If NetEq receives a
723 // CNG packet with a sample rate different than the current CNG then it
724 // flushes its buffer, assuming send codec must have been changed. However,
725 // payload type of the hypothetically new send codec is not known.
726 const RTPHeader* rtp_header = packet_buffer_->NextRtpHeader();
727 assert(rtp_header);
728 int payload_type = rtp_header->payloadType;
729 AudioDecoder* decoder = decoder_database_->GetDecoder(payload_type);
730 assert(decoder); // Payloads are already checked to be valid.
731 const DecoderDatabase::DecoderInfo* decoder_info =
732 decoder_database_->GetDecoderInfo(payload_type);
733 assert(decoder_info);
734 if (decoder_info->fs_hz != fs_hz_ ||
henrik.lundin48ed9302015-10-29 05:36:24 -0700735 decoder->Channels() != algorithm_buffer_->Channels()) {
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +0000736 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->Channels());
henrik.lundin48ed9302015-10-29 05:36:24 -0700737 }
738 if (nack_enabled_) {
739 RTC_DCHECK(nack_);
740 // Update the sample rate even if the rate is not new, because of Reset().
741 nack_->UpdateSampleRate(fs_hz_);
742 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000743 }
744
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000745 // TODO(hlundin): Move this code to DelayManager class.
746 const DecoderDatabase::DecoderInfo* dec_info =
747 decoder_database_->GetDecoderInfo(main_header.payloadType);
748 assert(dec_info); // Already checked that the payload type is known.
749 delay_manager_->LastDecoderType(dec_info->codec_type);
750 if (delay_manager_->last_pack_cng_or_dtmf() == 0) {
751 // Calculate the total speech length carried in each packet.
henrik.lundin116c84e2015-08-27 13:14:48 -0700752 const size_t buffer_length_after_insert =
753 packet_buffer_->NumPacketsInBuffer();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000754
henrik.lundin116c84e2015-08-27 13:14:48 -0700755 if (buffer_length_after_insert > buffer_length_before_insert) {
756 const size_t packet_length_samples =
757 (buffer_length_after_insert - buffer_length_before_insert) *
758 decoder_frame_length_;
759 if (packet_length_samples != decision_logic_->packet_length_samples()) {
760 decision_logic_->set_packet_length_samples(packet_length_samples);
761 delay_manager_->SetPacketAudioLength(
762 rtc::checked_cast<int>((1000 * packet_length_samples) / fs_hz_));
763 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000764 }
765
766 // Update statistics.
pbos@webrtc.org0946a562013-04-09 00:28:06 +0000767 if ((int32_t) (main_header.timestamp - timestamp_) >= 0 &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000768 !new_codec_) {
769 // Only update statistics if incoming packet is not older than last played
770 // out packet, and if new codec flag is not set.
771 delay_manager_->Update(main_header.sequenceNumber, main_header.timestamp,
772 fs_hz_);
773 }
774 } else if (delay_manager_->last_pack_cng_or_dtmf() == -1) {
775 // This is first "normal" packet after CNG or DTMF.
776 // Reset packet time counter and measure time until next packet,
777 // but don't update statistics.
778 delay_manager_->set_last_pack_cng_or_dtmf(0);
779 delay_manager_->ResetPacketIatCount();
780 }
781 return 0;
782}
783
henrik.lundin6d8e0112016-03-04 10:34:21 -0800784int NetEqImpl::GetAudioInternal(AudioFrame* audio_frame) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000785 PacketList packet_list;
786 DtmfEvent dtmf_event;
787 Operations operation;
788 bool play_dtmf;
789 int return_value = GetDecision(&operation, &packet_list, &dtmf_event,
790 &play_dtmf);
791 if (return_value != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000792 last_mode_ = kModeError;
793 return return_value;
794 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000795
796 AudioDecoder::SpeechType speech_type;
797 int length = 0;
798 int decode_return_value = Decode(&packet_list, &operation,
799 &length, &speech_type);
800
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000801 assert(vad_.get());
802 bool sid_frame_available =
803 (operation == kRfc3389Cng && !packet_list.empty());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700804 vad_->Update(decoded_buffer_.get(), static_cast<size_t>(length), speech_type,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000805 sid_frame_available, fs_hz_);
806
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000807 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000808 switch (operation) {
809 case kNormal: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000810 DoNormal(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000811 break;
812 }
813 case kMerge: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000814 DoMerge(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000815 break;
816 }
817 case kExpand: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000818 return_value = DoExpand(play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000819 break;
820 }
Henrik Lundincf808d22015-05-27 14:33:29 +0200821 case kAccelerate:
822 case kFastAccelerate: {
823 const bool fast_accelerate =
824 enable_fast_accelerate_ && (operation == kFastAccelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000825 return_value = DoAccelerate(decoded_buffer_.get(), length, speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +0200826 play_dtmf, fast_accelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000827 break;
828 }
829 case kPreemptiveExpand: {
830 return_value = DoPreemptiveExpand(decoded_buffer_.get(), length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000831 speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000832 break;
833 }
834 case kRfc3389Cng:
835 case kRfc3389CngNoPacket: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000836 return_value = DoRfc3389Cng(&packet_list, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000837 break;
838 }
839 case kCodecInternalCng: {
840 // This handles the case when there is no transmission and the decoder
841 // should produce internal comfort noise.
842 // TODO(hlundin): Write test for codec-internal CNG.
minyuel6d92bf52015-09-23 15:20:39 +0200843 DoCodecInternalCng(decoded_buffer_.get(), length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000844 break;
845 }
846 case kDtmf: {
847 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000848 return_value = DoDtmf(dtmf_event, &play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000849 break;
850 }
851 case kAlternativePlc: {
852 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000853 DoAlternativePlc(false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000854 break;
855 }
856 case kAlternativePlcIncreaseTimestamp: {
857 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000858 DoAlternativePlc(true);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000859 break;
860 }
861 case kAudioRepetitionIncreaseTimestamp: {
862 // TODO(hlundin): Write test for this.
Peter Kastingb7e50542015-06-11 12:55:50 -0700863 sync_buffer_->IncreaseEndTimestamp(
864 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000865 // Skipping break on purpose. Execution should move on into the
866 // next case.
kjellander@webrtc.org7d2b6a92015-01-28 18:37:58 +0000867 FALLTHROUGH();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000868 }
869 case kAudioRepetition: {
870 // TODO(hlundin): Write test for this.
871 // Copy last |output_size_samples_| from |sync_buffer_| to
872 // |algorithm_buffer|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000873 algorithm_buffer_->PushBackFromIndex(
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000874 *sync_buffer_, sync_buffer_->Size() - output_size_samples_);
875 expand_->Reset();
876 break;
877 }
878 case kUndefined: {
Henrik Lundind67a2192015-08-03 12:54:37 +0200879 LOG(LS_ERROR) << "Invalid operation kUndefined.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000880 assert(false); // This should not happen.
881 last_mode_ = kModeError;
882 return kInvalidOperation;
883 }
884 } // End of switch.
885 if (return_value < 0) {
886 return return_value;
887 }
888
889 if (last_mode_ != kModeRfc3389Cng) {
890 comfort_noise_->Reset();
891 }
892
893 // Copy from |algorithm_buffer| to |sync_buffer_|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000894 sync_buffer_->PushBack(*algorithm_buffer_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000895
896 // Extract data from |sync_buffer_| to |output|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000897 size_t num_output_samples_per_channel = output_size_samples_;
898 size_t num_output_samples = output_size_samples_ * sync_buffer_->Channels();
henrik.lundin6d8e0112016-03-04 10:34:21 -0800899 if (num_output_samples > AudioFrame::kMaxDataSizeSamples) {
900 LOG(LS_WARNING) << "Output array is too short. "
901 << AudioFrame::kMaxDataSizeSamples << " < "
902 << output_size_samples_ << " * "
903 << sync_buffer_->Channels();
904 num_output_samples = AudioFrame::kMaxDataSizeSamples;
905 num_output_samples_per_channel =
906 AudioFrame::kMaxDataSizeSamples / sync_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000907 }
henrik.lundin6d8e0112016-03-04 10:34:21 -0800908 sync_buffer_->GetNextAudioInterleaved(num_output_samples_per_channel,
909 audio_frame);
910 audio_frame->sample_rate_hz_ = fs_hz_;
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200911 if (sync_buffer_->FutureLength() < expand_->overlap_length()) {
912 // The sync buffer should always contain |overlap_length| samples, but now
913 // too many samples have been extracted. Reinstall the |overlap_length|
914 // lookahead by moving the index.
915 const size_t missing_lookahead_samples =
916 expand_->overlap_length() - sync_buffer_->FutureLength();
henrikg91d6ede2015-09-17 00:24:34 -0700917 RTC_DCHECK_GE(sync_buffer_->next_index(), missing_lookahead_samples);
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200918 sync_buffer_->set_next_index(sync_buffer_->next_index() -
919 missing_lookahead_samples);
920 }
henrik.lundin6d8e0112016-03-04 10:34:21 -0800921 if (audio_frame->samples_per_channel_ != output_size_samples_) {
922 LOG(LS_ERROR) << "audio_frame->samples_per_channel_ ("
923 << audio_frame->samples_per_channel_
Henrik Lundind67a2192015-08-03 12:54:37 +0200924 << ") != output_size_samples_ (" << output_size_samples_
925 << ")";
minyue@webrtc.orgdb1cefc2013-08-13 01:39:21 +0000926 // TODO(minyue): treatment of under-run, filling zeros
henrik.lundin6d8e0112016-03-04 10:34:21 -0800927 memset(audio_frame->data_, 0, num_output_samples * sizeof(int16_t));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000928 return kSampleUnderrun;
929 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000930
931 // Should always have overlap samples left in the |sync_buffer_|.
henrikg91d6ede2015-09-17 00:24:34 -0700932 RTC_DCHECK_GE(sync_buffer_->FutureLength(), expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000933
934 if (play_dtmf) {
henrik.lundin6d8e0112016-03-04 10:34:21 -0800935 return_value =
936 DtmfOverdub(dtmf_event, sync_buffer_->Channels(), audio_frame->data_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000937 }
938
939 // Update the background noise parameters if last operation wrote data
940 // straight from the decoder to the |sync_buffer_|. That is, none of the
941 // operations that modify the signal can be followed by a parameter update.
942 if ((last_mode_ == kModeNormal) ||
943 (last_mode_ == kModeAccelerateFail) ||
944 (last_mode_ == kModePreemptiveExpandFail) ||
945 (last_mode_ == kModeRfc3389Cng) ||
946 (last_mode_ == kModeCodecInternalCng)) {
947 background_noise_->Update(*sync_buffer_, *vad_.get());
948 }
949
950 if (operation == kDtmf) {
951 // DTMF data was written the end of |sync_buffer_|.
952 // Update index to end of DTMF data in |sync_buffer_|.
953 sync_buffer_->set_dtmf_index(sync_buffer_->Size());
954 }
955
henrik.lundin@webrtc.orged865b52014-03-06 10:28:07 +0000956 if (last_mode_ != kModeExpand) {
957 // If last operation was not expand, calculate the |playout_timestamp_| from
958 // the |sync_buffer_|. However, do not update the |playout_timestamp_| if it
959 // would be moved "backwards".
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000960 uint32_t temp_timestamp = sync_buffer_->end_timestamp() -
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000961 static_cast<uint32_t>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000962 if (static_cast<int32_t>(temp_timestamp - playout_timestamp_) > 0) {
963 playout_timestamp_ = temp_timestamp;
964 }
965 } else {
966 // Use dead reckoning to estimate the |playout_timestamp_|.
Peter Kastingb7e50542015-06-11 12:55:50 -0700967 playout_timestamp_ += static_cast<uint32_t>(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000968 }
henrik.lundin15c51e32016-04-06 08:38:56 -0700969 // Set the timestamp in the audio frame to zero before the first packet has
970 // been inserted. Otherwise, subtract the frame size in samples to get the
971 // timestamp of the first sample in the frame (playout_timestamp_ is the
972 // last + 1).
973 audio_frame->timestamp_ =
974 first_packet_
975 ? 0
976 : timestamp_scaler_->ToExternal(playout_timestamp_) -
977 static_cast<uint32_t>(audio_frame->samples_per_channel_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000978
979 if (decode_return_value) return decode_return_value;
980 return return_value;
981}
982
983int NetEqImpl::GetDecision(Operations* operation,
984 PacketList* packet_list,
985 DtmfEvent* dtmf_event,
986 bool* play_dtmf) {
987 // Initialize output variables.
988 *play_dtmf = false;
989 *operation = kUndefined;
990
991 // Increment time counters.
992 packet_buffer_->IncrementWaitingTimes();
993 stats_.IncreaseCounter(output_size_samples_, fs_hz_);
994
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000995 assert(sync_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000996 uint32_t end_timestamp = sync_buffer_->end_timestamp();
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +0000997 if (!new_codec_) {
998 const uint32_t five_seconds_samples = 5 * fs_hz_;
999 packet_buffer_->DiscardOldPackets(end_timestamp, five_seconds_samples);
1000 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001001 const RTPHeader* header = packet_buffer_->NextRtpHeader();
1002
henrik.lundin@webrtc.orgca8cb952014-03-12 10:26:52 +00001003 if (decision_logic_->CngRfc3389On() || last_mode_ == kModeRfc3389Cng) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001004 // Because of timestamp peculiarities, we have to "manually" disallow using
1005 // a CNG packet with the same timestamp as the one that was last played.
1006 // This can happen when using redundancy and will cause the timing to shift.
henrik.lundin@webrtc.org24779fe2014-03-14 12:40:05 +00001007 while (header && decoder_database_->IsComfortNoise(header->payloadType) &&
1008 (end_timestamp >= header->timestamp ||
1009 end_timestamp + decision_logic_->generated_noise_samples() >
1010 header->timestamp)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001011 // Don't use this packet, discard it.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001012 if (packet_buffer_->DiscardNextPacket() != PacketBuffer::kOK) {
1013 assert(false); // Must be ok by design.
1014 }
1015 // Check buffer again.
1016 if (!new_codec_) {
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001017 packet_buffer_->DiscardOldPackets(end_timestamp, 5 * fs_hz_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001018 }
1019 header = packet_buffer_->NextRtpHeader();
1020 }
1021 }
1022
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001023 assert(expand_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001024 const int samples_left = static_cast<int>(sync_buffer_->FutureLength() -
1025 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001026 if (last_mode_ == kModeAccelerateSuccess ||
1027 last_mode_ == kModeAccelerateLowEnergy ||
1028 last_mode_ == kModePreemptiveExpandSuccess ||
1029 last_mode_ == kModePreemptiveExpandLowEnergy) {
1030 // Subtract (samples_left + output_size_samples_) from sampleMemory.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001031 decision_logic_->AddSampleMemory(
1032 -(samples_left + rtc::checked_cast<int>(output_size_samples_)));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001033 }
1034
1035 // Check if it is time to play a DTMF event.
Peter Kastingb7e50542015-06-11 12:55:50 -07001036 if (dtmf_buffer_->GetEvent(
1037 static_cast<uint32_t>(
1038 end_timestamp + decision_logic_->generated_noise_samples()),
1039 dtmf_event)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001040 *play_dtmf = true;
1041 }
1042
1043 // Get instruction.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001044 assert(sync_buffer_.get());
1045 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001046 *operation = decision_logic_->GetDecision(*sync_buffer_,
1047 *expand_,
1048 decoder_frame_length_,
1049 header,
1050 last_mode_,
1051 *play_dtmf,
1052 &reset_decoder_);
1053
1054 // Check if we already have enough samples in the |sync_buffer_|. If so,
1055 // change decision to normal, unless the decision was merge, accelerate, or
1056 // preemptive expand.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001057 if (samples_left >= rtc::checked_cast<int>(output_size_samples_) &&
1058 *operation != kMerge &&
1059 *operation != kAccelerate &&
1060 *operation != kFastAccelerate &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001061 *operation != kPreemptiveExpand) {
1062 *operation = kNormal;
1063 return 0;
1064 }
1065
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001066 decision_logic_->ExpandDecision(*operation);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001067
1068 // Check conditions for reset.
1069 if (new_codec_ || *operation == kUndefined) {
1070 // The only valid reason to get kUndefined is that new_codec_ is set.
1071 assert(new_codec_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001072 if (*play_dtmf && !header) {
1073 timestamp_ = dtmf_event->timestamp;
1074 } else {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001075 if (!header) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001076 LOG(LS_ERROR) << "Packet missing where it shouldn't.";
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001077 return -1;
1078 }
1079 timestamp_ = header->timestamp;
1080 if (*operation == kRfc3389CngNoPacket
1081#ifndef LEGACY_BITEXACT
1082 // Without this check, it can happen that a non-CNG packet is sent to
1083 // the CNG decoder as if it was a SID frame. This is clearly a bug,
1084 // but is kept for now to maintain bit-exactness with the test
1085 // vectors.
1086 && decoder_database_->IsComfortNoise(header->payloadType)
1087#endif
1088 ) {
1089 // Change decision to CNG packet, since we do have a CNG packet, but it
1090 // was considered too early to use. Now, use it anyway.
1091 *operation = kRfc3389Cng;
1092 } else if (*operation != kRfc3389Cng) {
1093 *operation = kNormal;
1094 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001095 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001096 // Adjust |sync_buffer_| timestamp before setting |end_timestamp| to the
1097 // new value.
1098 sync_buffer_->IncreaseEndTimestamp(timestamp_ - end_timestamp);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001099 end_timestamp = timestamp_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001100 new_codec_ = false;
1101 decision_logic_->SoftReset();
1102 buffer_level_filter_->Reset();
1103 delay_manager_->Reset();
1104 stats_.ResetMcu();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001105 }
1106
Peter Kastingdce40cf2015-08-24 14:52:23 -07001107 size_t required_samples = output_size_samples_;
1108 const size_t samples_10_ms = static_cast<size_t>(80 * fs_mult_);
1109 const size_t samples_20_ms = 2 * samples_10_ms;
1110 const size_t samples_30_ms = 3 * samples_10_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001111
1112 switch (*operation) {
1113 case kExpand: {
1114 timestamp_ = end_timestamp;
1115 return 0;
1116 }
1117 case kRfc3389CngNoPacket:
1118 case kCodecInternalCng: {
1119 return 0;
1120 }
1121 case kDtmf: {
1122 // TODO(hlundin): Write test for this.
1123 // Update timestamp.
1124 timestamp_ = end_timestamp;
1125 if (decision_logic_->generated_noise_samples() > 0 &&
1126 last_mode_ != kModeDtmf) {
1127 // Make a jump in timestamp due to the recently played comfort noise.
Peter Kastingb7e50542015-06-11 12:55:50 -07001128 uint32_t timestamp_jump =
1129 static_cast<uint32_t>(decision_logic_->generated_noise_samples());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001130 sync_buffer_->IncreaseEndTimestamp(timestamp_jump);
1131 timestamp_ += timestamp_jump;
1132 }
1133 decision_logic_->set_generated_noise_samples(0);
1134 return 0;
1135 }
Henrik Lundincf808d22015-05-27 14:33:29 +02001136 case kAccelerate:
1137 case kFastAccelerate: {
1138 // In order to do an accelerate we need at least 30 ms of audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001139 if (samples_left >= static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001140 // Already have enough data, so we do not need to extract any more.
1141 decision_logic_->set_sample_memory(samples_left);
1142 decision_logic_->set_prev_time_scale(true);
1143 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001144 } else if (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001145 decoder_frame_length_ >= samples_30_ms) {
1146 // Avoid decoding more data as it might overflow the playout buffer.
1147 *operation = kNormal;
1148 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001149 } else if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001150 decoder_frame_length_ < samples_30_ms) {
1151 // Build up decoded data by decoding at least 20 ms of audio data. Do
1152 // not perform accelerate yet, but wait until we only need to do one
1153 // decoding.
1154 required_samples = 2 * output_size_samples_;
1155 *operation = kNormal;
1156 }
1157 // If none of the above is true, we have one of two possible situations:
1158 // (1) 20 ms <= samples_left < 30 ms and decoder_frame_length_ < 30 ms; or
1159 // (2) samples_left < 10 ms and decoder_frame_length_ >= 30 ms.
1160 // In either case, we move on with the accelerate decision, and decode one
1161 // frame now.
1162 break;
1163 }
1164 case kPreemptiveExpand: {
1165 // In order to do a preemptive expand we need at least 30 ms of decoded
1166 // audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001167 if ((samples_left >= static_cast<int>(samples_30_ms)) ||
1168 (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001169 decoder_frame_length_ >= samples_30_ms)) {
1170 // Already have enough data, so we do not need to extract any more.
1171 // Or, avoid decoding more data as it might overflow the playout buffer.
1172 // Still try preemptive expand, though.
1173 decision_logic_->set_sample_memory(samples_left);
1174 decision_logic_->set_prev_time_scale(true);
1175 return 0;
1176 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07001177 if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001178 decoder_frame_length_ < samples_30_ms) {
1179 // Build up decoded data by decoding at least 20 ms of audio data.
1180 // Still try to perform preemptive expand.
1181 required_samples = 2 * output_size_samples_;
1182 }
1183 // Move on with the preemptive expand decision.
1184 break;
1185 }
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001186 case kMerge: {
1187 required_samples =
1188 std::max(merge_->RequiredFutureSamples(), required_samples);
1189 break;
1190 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001191 default: {
1192 // Do nothing.
1193 }
1194 }
1195
1196 // Get packets from buffer.
1197 int extracted_samples = 0;
1198 if (header &&
1199 *operation != kAlternativePlc &&
1200 *operation != kAlternativePlcIncreaseTimestamp &&
1201 *operation != kAudioRepetition &&
1202 *operation != kAudioRepetitionIncreaseTimestamp) {
1203 sync_buffer_->IncreaseEndTimestamp(header->timestamp - end_timestamp);
1204 if (decision_logic_->CngOff()) {
1205 // Adjustment of timestamp only corresponds to an actual packet loss
1206 // if comfort noise is not played. If comfort noise was just played,
1207 // this adjustment of timestamp is only done to get back in sync with the
1208 // stream timestamp; no loss to report.
1209 stats_.LostSamples(header->timestamp - end_timestamp);
1210 }
1211
1212 if (*operation != kRfc3389Cng) {
1213 // We are about to decode and use a non-CNG packet.
1214 decision_logic_->SetCngOff();
1215 }
1216 // Reset CNG timestamp as a new packet will be delivered.
1217 // (Also if this is a CNG packet, since playedOutTS is updated.)
1218 decision_logic_->set_generated_noise_samples(0);
1219
1220 extracted_samples = ExtractPackets(required_samples, packet_list);
1221 if (extracted_samples < 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001222 return kPacketBufferCorruption;
1223 }
1224 }
1225
Henrik Lundincf808d22015-05-27 14:33:29 +02001226 if (*operation == kAccelerate || *operation == kFastAccelerate ||
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001227 *operation == kPreemptiveExpand) {
1228 decision_logic_->set_sample_memory(samples_left + extracted_samples);
1229 decision_logic_->set_prev_time_scale(true);
1230 }
1231
Henrik Lundincf808d22015-05-27 14:33:29 +02001232 if (*operation == kAccelerate || *operation == kFastAccelerate) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001233 // Check that we have enough data (30ms) to do accelerate.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001234 if (extracted_samples + samples_left < static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001235 // TODO(hlundin): Write test for this.
1236 // Not enough, do normal operation instead.
1237 *operation = kNormal;
1238 }
1239 }
1240
1241 timestamp_ = end_timestamp;
1242 return 0;
1243}
1244
1245int NetEqImpl::Decode(PacketList* packet_list, Operations* operation,
1246 int* decoded_length,
1247 AudioDecoder::SpeechType* speech_type) {
1248 *speech_type = AudioDecoder::kSpeech;
minyuel6d92bf52015-09-23 15:20:39 +02001249
1250 // When packet_list is empty, we may be in kCodecInternalCng mode, and for
1251 // that we use current active decoder.
1252 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1253
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001254 if (!packet_list->empty()) {
1255 const Packet* packet = packet_list->front();
pkasting@chromium.org0e81fdf2015-02-02 23:54:03 +00001256 uint8_t payload_type = packet->header.payloadType;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001257 if (!decoder_database_->IsComfortNoise(payload_type)) {
1258 decoder = decoder_database_->GetDecoder(payload_type);
1259 assert(decoder);
1260 if (!decoder) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001261 LOG(LS_WARNING) << "Unknown payload type "
1262 << static_cast<int>(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001263 PacketBuffer::DeleteAllPackets(packet_list);
1264 return kDecoderNotFound;
1265 }
1266 bool decoder_changed;
1267 decoder_database_->SetActiveDecoder(payload_type, &decoder_changed);
1268 if (decoder_changed) {
1269 // We have a new decoder. Re-init some values.
1270 const DecoderDatabase::DecoderInfo* decoder_info = decoder_database_
1271 ->GetDecoderInfo(payload_type);
1272 assert(decoder_info);
1273 if (!decoder_info) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001274 LOG(LS_WARNING) << "Unknown payload type "
1275 << static_cast<int>(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001276 PacketBuffer::DeleteAllPackets(packet_list);
1277 return kDecoderNotFound;
1278 }
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001279 // If sampling rate or number of channels has changed, we need to make
1280 // a reset.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001281 if (decoder_info->fs_hz != fs_hz_ ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001282 decoder->Channels() != algorithm_buffer_->Channels()) {
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001283 // TODO(tlegrand): Add unittest to cover this event.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001284 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->Channels());
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001285 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001286 sync_buffer_->set_end_timestamp(timestamp_);
1287 playout_timestamp_ = timestamp_;
1288 }
1289 }
1290 }
1291
1292 if (reset_decoder_) {
1293 // TODO(hlundin): Write test for this.
Karl Wiberg43766482015-08-27 15:22:11 +02001294 if (decoder)
1295 decoder->Reset();
1296
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001297 // Reset comfort noise decoder.
1298 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02001299 if (cng_decoder)
1300 cng_decoder->Reset();
1301
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001302 reset_decoder_ = false;
1303 }
1304
1305#ifdef LEGACY_BITEXACT
1306 // Due to a bug in old SignalMCU, it could happen that CNG operation was
1307 // decided, but a speech packet was provided. The speech packet will be used
1308 // to update the comfort noise decoder, as if it was a SID frame, which is
1309 // clearly wrong.
1310 if (*operation == kRfc3389Cng) {
1311 return 0;
1312 }
1313#endif
1314
1315 *decoded_length = 0;
1316 // Update codec-internal PLC state.
1317 if ((*operation == kMerge) && decoder && decoder->HasDecodePlc()) {
1318 decoder->DecodePlc(1, &decoded_buffer_[*decoded_length]);
1319 }
1320
minyuel6d92bf52015-09-23 15:20:39 +02001321 int return_value;
1322 if (*operation == kCodecInternalCng) {
1323 RTC_DCHECK(packet_list->empty());
1324 return_value = DecodeCng(decoder, decoded_length, speech_type);
1325 } else {
1326 return_value = DecodeLoop(packet_list, *operation, decoder,
1327 decoded_length, speech_type);
1328 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001329
1330 if (*decoded_length < 0) {
1331 // Error returned from the decoder.
1332 *decoded_length = 0;
Peter Kastingb7e50542015-06-11 12:55:50 -07001333 sync_buffer_->IncreaseEndTimestamp(
1334 static_cast<uint32_t>(decoder_frame_length_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001335 int error_code = 0;
1336 if (decoder)
1337 error_code = decoder->ErrorCode();
1338 if (error_code != 0) {
1339 // Got some error code from the decoder.
1340 decoder_error_code_ = error_code;
1341 return_value = kDecoderErrorCode;
Henrik Lundind67a2192015-08-03 12:54:37 +02001342 LOG(LS_WARNING) << "Decoder returned error code: " << error_code;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001343 } else {
1344 // Decoder does not implement error codes. Return generic error.
1345 return_value = kOtherDecoderError;
Henrik Lundind67a2192015-08-03 12:54:37 +02001346 LOG(LS_WARNING) << "Decoder error (no error code)";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001347 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001348 *operation = kExpand; // Do expansion to get data instead.
1349 }
1350 if (*speech_type != AudioDecoder::kComfortNoise) {
1351 // Don't increment timestamp if codec returned CNG speech type
1352 // since in this case, the we will increment the CNGplayedTS counter.
1353 // Increase with number of samples per channel.
1354 assert(*decoded_length == 0 ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001355 (decoder && decoder->Channels() == sync_buffer_->Channels()));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001356 sync_buffer_->IncreaseEndTimestamp(
1357 *decoded_length / static_cast<int>(sync_buffer_->Channels()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001358 }
1359 return return_value;
1360}
1361
minyuel6d92bf52015-09-23 15:20:39 +02001362int NetEqImpl::DecodeCng(AudioDecoder* decoder, int* decoded_length,
1363 AudioDecoder::SpeechType* speech_type) {
1364 if (!decoder) {
1365 // This happens when active decoder is not defined.
1366 *decoded_length = -1;
1367 return 0;
1368 }
1369
1370 while (*decoded_length < rtc::checked_cast<int>(output_size_samples_)) {
1371 const int length = decoder->Decode(
1372 nullptr, 0, fs_hz_,
1373 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1374 &decoded_buffer_[*decoded_length], speech_type);
1375 if (length > 0) {
1376 *decoded_length += length;
minyuel6d92bf52015-09-23 15:20:39 +02001377 } else {
1378 // Error.
1379 LOG(LS_WARNING) << "Failed to decode CNG";
1380 *decoded_length = -1;
1381 break;
1382 }
1383 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1384 // Guard against overflow.
1385 LOG(LS_WARNING) << "Decoded too much CNG.";
1386 return kDecodedTooMuch;
1387 }
1388 }
1389 return 0;
1390}
1391
1392int NetEqImpl::DecodeLoop(PacketList* packet_list, const Operations& operation,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001393 AudioDecoder* decoder, int* decoded_length,
1394 AudioDecoder::SpeechType* speech_type) {
1395 Packet* packet = NULL;
1396 if (!packet_list->empty()) {
1397 packet = packet_list->front();
1398 }
minyuel6d92bf52015-09-23 15:20:39 +02001399
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001400 // Do decoding.
1401 while (packet &&
1402 !decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1403 assert(decoder); // At this point, we must have a decoder object.
1404 // The number of channels in the |sync_buffer_| should be the same as the
1405 // number decoder channels.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001406 assert(sync_buffer_->Channels() == decoder->Channels());
1407 assert(decoded_buffer_length_ >= kMaxFrameSize * decoder->Channels());
minyuel6d92bf52015-09-23 15:20:39 +02001408 assert(operation == kNormal || operation == kAccelerate ||
1409 operation == kFastAccelerate || operation == kMerge ||
1410 operation == kPreemptiveExpand);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001411 packet_list->pop_front();
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001412 size_t payload_length = packet->payload_length;
Peter Kasting36b7cc32015-06-11 19:57:18 -07001413 int decode_length;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +00001414 if (packet->sync_packet) {
1415 // Decode to silence with the same frame size as the last decode.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001416 memset(&decoded_buffer_[*decoded_length], 0,
1417 decoder_frame_length_ * decoder->Channels() *
1418 sizeof(decoded_buffer_[0]));
Peter Kastingdce40cf2015-08-24 14:52:23 -07001419 decode_length = rtc::checked_cast<int>(decoder_frame_length_);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +00001420 } else if (!packet->primary) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001421 // This is a redundant payload; call the special decoder method.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001422 decode_length = decoder->DecodeRedundant(
henrik.lundin@webrtc.org1eda4e32015-02-25 10:02:29 +00001423 packet->payload, packet->payload_length, fs_hz_,
minyue@webrtc.org7f7d7e32015-03-16 12:30:37 +00001424 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001425 &decoded_buffer_[*decoded_length], speech_type);
1426 } else {
henrik.lundin@webrtc.org1eda4e32015-02-25 10:02:29 +00001427 decode_length =
minyue@webrtc.org7f7d7e32015-03-16 12:30:37 +00001428 decoder->Decode(
1429 packet->payload, packet->payload_length, fs_hz_,
1430 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1431 &decoded_buffer_[*decoded_length], speech_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001432 }
1433
1434 delete[] packet->payload;
1435 delete packet;
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001436 packet = NULL;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001437 if (decode_length > 0) {
1438 *decoded_length += decode_length;
1439 // Update |decoder_frame_length_| with number of samples per channel.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001440 decoder_frame_length_ =
Peter Kastingdce40cf2015-08-24 14:52:23 -07001441 static_cast<size_t>(decode_length) / decoder->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001442 } else if (decode_length < 0) {
1443 // Error.
Henrik Lundind67a2192015-08-03 12:54:37 +02001444 LOG(LS_WARNING) << "Decode " << decode_length << " " << payload_length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001445 *decoded_length = -1;
1446 PacketBuffer::DeleteAllPackets(packet_list);
1447 break;
1448 }
1449 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1450 // Guard against overflow.
Henrik Lundind67a2192015-08-03 12:54:37 +02001451 LOG(LS_WARNING) << "Decoded too much.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001452 PacketBuffer::DeleteAllPackets(packet_list);
1453 return kDecodedTooMuch;
1454 }
1455 if (!packet_list->empty()) {
1456 packet = packet_list->front();
1457 } else {
1458 packet = NULL;
1459 }
1460 } // End of decode loop.
1461
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001462 // If the list is not empty at this point, either a decoding error terminated
1463 // the while-loop, or list must hold exactly one CNG packet.
1464 assert(packet_list->empty() || *decoded_length < 0 ||
1465 (packet_list->size() == 1 && packet &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001466 decoder_database_->IsComfortNoise(packet->header.payloadType)));
1467 return 0;
1468}
1469
1470void NetEqImpl::DoNormal(const int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001471 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001472 assert(normal_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001473 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001474 normal_->Process(decoded_buffer, decoded_length, last_mode_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001475 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001476 if (decoded_length != 0) {
1477 last_mode_ = kModeNormal;
1478 }
1479
1480 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1481 if ((speech_type == AudioDecoder::kComfortNoise)
1482 || ((last_mode_ == kModeCodecInternalCng)
1483 && (decoded_length == 0))) {
1484 // TODO(hlundin): Remove second part of || statement above.
1485 last_mode_ = kModeCodecInternalCng;
1486 }
1487
1488 if (!play_dtmf) {
1489 dtmf_tone_generator_->Reset();
1490 }
1491}
1492
1493void NetEqImpl::DoMerge(int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001494 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001495 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001496 assert(merge_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001497 size_t new_length = merge_->Process(decoded_buffer, decoded_length,
1498 mute_factor_array_.get(),
1499 algorithm_buffer_.get());
1500 size_t expand_length_correction = new_length -
1501 decoded_length / algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001502
1503 // Update in-call and post-call statistics.
1504 if (expand_->MuteFactor(0) == 0) {
1505 // Expand generates only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001506 stats_.ExpandedNoiseSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001507 } else {
1508 // Expansion generates more than only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001509 stats_.ExpandedVoiceSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001510 }
1511
1512 last_mode_ = kModeMerge;
1513 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1514 if (speech_type == AudioDecoder::kComfortNoise) {
1515 last_mode_ = kModeCodecInternalCng;
1516 }
1517 expand_->Reset();
1518 if (!play_dtmf) {
1519 dtmf_tone_generator_->Reset();
1520 }
1521}
1522
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001523int NetEqImpl::DoExpand(bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001524 while ((sync_buffer_->FutureLength() - expand_->overlap_length()) <
Peter Kastingdce40cf2015-08-24 14:52:23 -07001525 output_size_samples_) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001526 algorithm_buffer_->Clear();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001527 int return_value = expand_->Process(algorithm_buffer_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001528 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001529
1530 // Update in-call and post-call statistics.
1531 if (expand_->MuteFactor(0) == 0) {
1532 // Expand operation generates only noise.
1533 stats_.ExpandedNoiseSamples(length);
1534 } else {
1535 // Expand operation generates more than only noise.
1536 stats_.ExpandedVoiceSamples(length);
1537 }
1538
1539 last_mode_ = kModeExpand;
1540
1541 if (return_value < 0) {
1542 return return_value;
1543 }
1544
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001545 sync_buffer_->PushBack(*algorithm_buffer_);
1546 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001547 }
1548 if (!play_dtmf) {
1549 dtmf_tone_generator_->Reset();
1550 }
1551 return 0;
1552}
1553
Henrik Lundincf808d22015-05-27 14:33:29 +02001554int NetEqImpl::DoAccelerate(int16_t* decoded_buffer,
1555 size_t decoded_length,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001556 AudioDecoder::SpeechType speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +02001557 bool play_dtmf,
1558 bool fast_accelerate) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001559 const size_t required_samples =
1560 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001561 size_t borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001562 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001563 size_t decoded_length_per_channel = decoded_length / num_channels;
1564 if (decoded_length_per_channel < required_samples) {
1565 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001566 borrowed_samples_per_channel = static_cast<int>(required_samples -
1567 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001568 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1569 decoded_buffer,
1570 sizeof(int16_t) * decoded_length);
1571 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1572 decoded_buffer);
1573 decoded_length = required_samples * num_channels;
1574 }
1575
Peter Kastingdce40cf2015-08-24 14:52:23 -07001576 size_t samples_removed;
Henrik Lundincf808d22015-05-27 14:33:29 +02001577 Accelerate::ReturnCodes return_code =
1578 accelerate_->Process(decoded_buffer, decoded_length, fast_accelerate,
1579 algorithm_buffer_.get(), &samples_removed);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001580 stats_.AcceleratedSamples(samples_removed);
1581 switch (return_code) {
1582 case Accelerate::kSuccess:
1583 last_mode_ = kModeAccelerateSuccess;
1584 break;
1585 case Accelerate::kSuccessLowEnergy:
1586 last_mode_ = kModeAccelerateLowEnergy;
1587 break;
1588 case Accelerate::kNoStretch:
1589 last_mode_ = kModeAccelerateFail;
1590 break;
1591 case Accelerate::kError:
1592 // TODO(hlundin): Map to kModeError instead?
1593 last_mode_ = kModeAccelerateFail;
1594 return kAccelerateError;
1595 }
1596
1597 if (borrowed_samples_per_channel > 0) {
1598 // Copy borrowed samples back to the |sync_buffer_|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001599 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001600 if (length < borrowed_samples_per_channel) {
1601 // This destroys the beginning of the buffer, but will not cause any
1602 // problems.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001603 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001604 sync_buffer_->Size() -
1605 borrowed_samples_per_channel);
1606 sync_buffer_->PushFrontZeros(borrowed_samples_per_channel - length);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001607 algorithm_buffer_->PopFront(length);
1608 assert(algorithm_buffer_->Empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001609 } else {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001610 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001611 borrowed_samples_per_channel,
1612 sync_buffer_->Size() -
1613 borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001614 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001615 }
1616 }
1617
1618 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1619 if (speech_type == AudioDecoder::kComfortNoise) {
1620 last_mode_ = kModeCodecInternalCng;
1621 }
1622 if (!play_dtmf) {
1623 dtmf_tone_generator_->Reset();
1624 }
1625 expand_->Reset();
1626 return 0;
1627}
1628
1629int NetEqImpl::DoPreemptiveExpand(int16_t* decoded_buffer,
1630 size_t decoded_length,
1631 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001632 bool play_dtmf) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001633 const size_t required_samples =
1634 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001635 size_t num_channels = algorithm_buffer_->Channels();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001636 size_t borrowed_samples_per_channel = 0;
1637 size_t old_borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001638 size_t decoded_length_per_channel = decoded_length / num_channels;
1639 if (decoded_length_per_channel < required_samples) {
1640 // Must move data from the |sync_buffer_| in order to get 30 ms.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001641 borrowed_samples_per_channel =
1642 required_samples - decoded_length_per_channel;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001643 // Calculate how many of these were already played out.
Peter Kastingf045e4d2015-06-10 21:15:38 -07001644 old_borrowed_samples_per_channel =
Peter Kastingdce40cf2015-08-24 14:52:23 -07001645 (borrowed_samples_per_channel > sync_buffer_->FutureLength()) ?
1646 (borrowed_samples_per_channel - sync_buffer_->FutureLength()) : 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001647 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1648 decoded_buffer,
1649 sizeof(int16_t) * decoded_length);
1650 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1651 decoded_buffer);
1652 decoded_length = required_samples * num_channels;
1653 }
1654
Peter Kastingdce40cf2015-08-24 14:52:23 -07001655 size_t samples_added;
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001656 PreemptiveExpand::ReturnCodes return_code = preemptive_expand_->Process(
Peter Kastingdce40cf2015-08-24 14:52:23 -07001657 decoded_buffer, decoded_length,
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001658 old_borrowed_samples_per_channel,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001659 algorithm_buffer_.get(), &samples_added);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001660 stats_.PreemptiveExpandedSamples(samples_added);
1661 switch (return_code) {
1662 case PreemptiveExpand::kSuccess:
1663 last_mode_ = kModePreemptiveExpandSuccess;
1664 break;
1665 case PreemptiveExpand::kSuccessLowEnergy:
1666 last_mode_ = kModePreemptiveExpandLowEnergy;
1667 break;
1668 case PreemptiveExpand::kNoStretch:
1669 last_mode_ = kModePreemptiveExpandFail;
1670 break;
1671 case PreemptiveExpand::kError:
1672 // TODO(hlundin): Map to kModeError instead?
1673 last_mode_ = kModePreemptiveExpandFail;
1674 return kPreemptiveExpandError;
1675 }
1676
1677 if (borrowed_samples_per_channel > 0) {
1678 // Copy borrowed samples back to the |sync_buffer_|.
1679 sync_buffer_->ReplaceAtIndex(
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001680 *algorithm_buffer_, borrowed_samples_per_channel,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001681 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001682 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001683 }
1684
1685 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1686 if (speech_type == AudioDecoder::kComfortNoise) {
1687 last_mode_ = kModeCodecInternalCng;
1688 }
1689 if (!play_dtmf) {
1690 dtmf_tone_generator_->Reset();
1691 }
1692 expand_->Reset();
1693 return 0;
1694}
1695
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001696int NetEqImpl::DoRfc3389Cng(PacketList* packet_list, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001697 if (!packet_list->empty()) {
1698 // Must have exactly one SID frame at this point.
1699 assert(packet_list->size() == 1);
1700 Packet* packet = packet_list->front();
1701 packet_list->pop_front();
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001702 if (!decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1703#ifdef LEGACY_BITEXACT
1704 // This can happen due to a bug in GetDecision. Change the payload type
1705 // to a CNG type, and move on. Note that this means that we are in fact
1706 // sending a non-CNG payload to the comfort noise decoder for decoding.
1707 // Clearly wrong, but will maintain bit-exactness with legacy.
1708 if (fs_hz_ == 8000) {
1709 packet->header.payloadType =
kwibergee1879c2015-10-29 06:20:28 -07001710 decoder_database_->GetRtpPayloadType(NetEqDecoder::kDecoderCNGnb);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001711 } else if (fs_hz_ == 16000) {
1712 packet->header.payloadType =
kwibergee1879c2015-10-29 06:20:28 -07001713 decoder_database_->GetRtpPayloadType(NetEqDecoder::kDecoderCNGwb);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001714 } else if (fs_hz_ == 32000) {
kwibergee1879c2015-10-29 06:20:28 -07001715 packet->header.payloadType = decoder_database_->GetRtpPayloadType(
1716 NetEqDecoder::kDecoderCNGswb32kHz);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001717 } else if (fs_hz_ == 48000) {
kwibergee1879c2015-10-29 06:20:28 -07001718 packet->header.payloadType = decoder_database_->GetRtpPayloadType(
1719 NetEqDecoder::kDecoderCNGswb48kHz);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001720 }
1721 assert(decoder_database_->IsComfortNoise(packet->header.payloadType));
1722#else
1723 LOG(LS_ERROR) << "Trying to decode non-CNG payload as CNG.";
1724 return kOtherError;
1725#endif
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001726 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001727 // UpdateParameters() deletes |packet|.
1728 if (comfort_noise_->UpdateParameters(packet) ==
1729 ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001730 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001731 return -comfort_noise_->internal_error_code();
1732 }
1733 }
1734 int cn_return = comfort_noise_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001735 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001736 expand_->Reset();
1737 last_mode_ = kModeRfc3389Cng;
1738 if (!play_dtmf) {
1739 dtmf_tone_generator_->Reset();
1740 }
1741 if (cn_return == ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001742 decoder_error_code_ = comfort_noise_->internal_error_code();
1743 return kComfortNoiseErrorCode;
1744 } else if (cn_return == ComfortNoise::kUnknownPayloadType) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001745 return kUnknownRtpPayloadType;
1746 }
1747 return 0;
1748}
1749
minyuel6d92bf52015-09-23 15:20:39 +02001750void NetEqImpl::DoCodecInternalCng(const int16_t* decoded_buffer,
1751 size_t decoded_length) {
1752 RTC_DCHECK(normal_.get());
1753 RTC_DCHECK(mute_factor_array_.get());
1754 normal_->Process(decoded_buffer, decoded_length, last_mode_,
1755 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001756 last_mode_ = kModeCodecInternalCng;
1757 expand_->Reset();
1758}
1759
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001760int NetEqImpl::DoDtmf(const DtmfEvent& dtmf_event, bool* play_dtmf) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001761 // This block of the code and the block further down, handling |dtmf_switch|
1762 // are commented out. Otherwise playing out-of-band DTMF would fail in VoE
1763 // test, DtmfTest.ManualSuccessfullySendsOutOfBandTelephoneEvents. This is
1764 // equivalent to |dtmf_switch| always be false.
1765 //
1766 // See http://webrtc-codereview.appspot.com/1195004/ for discussion
1767 // On this issue. This change might cause some glitches at the point of
1768 // switch from audio to DTMF. Issue 1545 is filed to track this.
1769 //
1770 // bool dtmf_switch = false;
1771 // if ((last_mode_ != kModeDtmf) && dtmf_tone_generator_->initialized()) {
1772 // // Special case; see below.
1773 // // We must catch this before calling Generate, since |initialized| is
1774 // // modified in that call.
1775 // dtmf_switch = true;
1776 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001777
1778 int dtmf_return_value = 0;
1779 if (!dtmf_tone_generator_->initialized()) {
1780 // Initialize if not already done.
1781 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1782 dtmf_event.volume);
1783 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001784
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001785 if (dtmf_return_value == 0) {
1786 // Generate DTMF signal.
1787 dtmf_return_value = dtmf_tone_generator_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001788 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001789 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001790
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001791 if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001792 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001793 return dtmf_return_value;
1794 }
1795
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001796 // if (dtmf_switch) {
1797 // // This is the special case where the previous operation was DTMF
1798 // // overdub, but the current instruction is "regular" DTMF. We must make
1799 // // sure that the DTMF does not have any discontinuities. The first DTMF
1800 // // sample that we generate now must be played out immediately, therefore
1801 // // it must be copied to the speech buffer.
1802 // // TODO(hlundin): This code seems incorrect. (Legacy.) Write test and
1803 // // verify correct operation.
1804 // assert(false);
1805 // // Must generate enough data to replace all of the |sync_buffer_|
1806 // // "future".
1807 // int required_length = sync_buffer_->FutureLength();
1808 // assert(dtmf_tone_generator_->initialized());
1809 // dtmf_return_value = dtmf_tone_generator_->Generate(required_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001810 // algorithm_buffer_);
1811 // assert((size_t) required_length == algorithm_buffer_->Size());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001812 // if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001813 // algorithm_buffer_->Zeros(output_size_samples_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001814 // return dtmf_return_value;
1815 // }
1816 //
1817 // // Overwrite the "future" part of the speech buffer with the new DTMF
1818 // // data.
1819 // // TODO(hlundin): It seems that this overwriting has gone lost.
1820 // // Not adapted for multi-channel yet.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001821 // assert(algorithm_buffer_->Channels() == 1);
1822 // if (algorithm_buffer_->Channels() != 1) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001823 // LOG(LS_WARNING) << "DTMF not supported for more than one channel";
1824 // return kStereoNotSupported;
1825 // }
1826 // // Shuffle the remaining data to the beginning of algorithm buffer.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001827 // algorithm_buffer_->PopFront(sync_buffer_->FutureLength());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001828 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001829
Peter Kastingb7e50542015-06-11 12:55:50 -07001830 sync_buffer_->IncreaseEndTimestamp(
1831 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001832 expand_->Reset();
1833 last_mode_ = kModeDtmf;
1834
1835 // Set to false because the DTMF is already in the algorithm buffer.
1836 *play_dtmf = false;
1837 return 0;
1838}
1839
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001840void NetEqImpl::DoAlternativePlc(bool increase_timestamp) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001841 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001842 size_t length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001843 if (decoder && decoder->HasDecodePlc()) {
1844 // Use the decoder's packet-loss concealment.
1845 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1846 int16_t decoded_buffer[kMaxFrameSize];
1847 length = decoder->DecodePlc(1, decoded_buffer);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001848 if (length > 0)
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001849 algorithm_buffer_->PushBackInterleaved(decoded_buffer, length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001850 } else {
1851 // Do simple zero-stuffing.
1852 length = output_size_samples_;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001853 algorithm_buffer_->Zeros(length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001854 // By not advancing the timestamp, NetEq inserts samples.
1855 stats_.AddZeros(length);
1856 }
1857 if (increase_timestamp) {
Peter Kastingb7e50542015-06-11 12:55:50 -07001858 sync_buffer_->IncreaseEndTimestamp(static_cast<uint32_t>(length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001859 }
1860 expand_->Reset();
1861}
1862
1863int NetEqImpl::DtmfOverdub(const DtmfEvent& dtmf_event, size_t num_channels,
1864 int16_t* output) const {
1865 size_t out_index = 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001866 size_t overdub_length = output_size_samples_; // Default value.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001867
1868 if (sync_buffer_->dtmf_index() > sync_buffer_->next_index()) {
1869 // Special operation for transition from "DTMF only" to "DTMF overdub".
1870 out_index = std::min(
1871 sync_buffer_->dtmf_index() - sync_buffer_->next_index(),
Peter Kastingdce40cf2015-08-24 14:52:23 -07001872 output_size_samples_);
1873 overdub_length = output_size_samples_ - out_index;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001874 }
1875
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001876 AudioMultiVector dtmf_output(num_channels);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001877 int dtmf_return_value = 0;
1878 if (!dtmf_tone_generator_->initialized()) {
1879 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1880 dtmf_event.volume);
1881 }
1882 if (dtmf_return_value == 0) {
1883 dtmf_return_value = dtmf_tone_generator_->Generate(overdub_length,
1884 &dtmf_output);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001885 assert(overdub_length == dtmf_output.Size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001886 }
1887 dtmf_output.ReadInterleaved(overdub_length, &output[out_index]);
1888 return dtmf_return_value < 0 ? dtmf_return_value : 0;
1889}
1890
Peter Kastingdce40cf2015-08-24 14:52:23 -07001891int NetEqImpl::ExtractPackets(size_t required_samples,
1892 PacketList* packet_list) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001893 bool first_packet = true;
1894 uint8_t prev_payload_type = 0;
1895 uint32_t prev_timestamp = 0;
1896 uint16_t prev_sequence_number = 0;
1897 bool next_packet_available = false;
1898
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001899 const RTPHeader* header = packet_buffer_->NextRtpHeader();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001900 assert(header);
1901 if (!header) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001902 LOG(LS_ERROR) << "Packet buffer unexpectedly empty.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001903 return -1;
1904 }
turaj@webrtc.org7df97062013-08-02 18:07:13 +00001905 uint32_t first_timestamp = header->timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001906 int extracted_samples = 0;
1907
1908 // Packet extraction loop.
1909 do {
1910 timestamp_ = header->timestamp;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001911 size_t discard_count = 0;
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001912 Packet* packet = packet_buffer_->GetNextPacket(&discard_count);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001913 // |header| may be invalid after the |packet_buffer_| operation.
1914 header = NULL;
1915 if (!packet) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001916 LOG(LS_ERROR) << "Should always be able to extract a packet here";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001917 assert(false); // Should always be able to extract a packet here.
1918 return -1;
1919 }
1920 stats_.PacketsDiscarded(discard_count);
1921 // Store waiting time in ms; packets->waiting_time is in "output blocks".
1922 stats_.StoreWaitingTime(packet->waiting_time * kOutputSizeMs);
1923 assert(packet->payload_length > 0);
1924 packet_list->push_back(packet); // Store packet in list.
1925
1926 if (first_packet) {
1927 first_packet = false;
henrik.lundin48ed9302015-10-29 05:36:24 -07001928 if (nack_enabled_) {
1929 RTC_DCHECK(nack_);
1930 // TODO(henrik.lundin): Should we update this for all decoded packets?
1931 nack_->UpdateLastDecodedPacket(packet->header.sequenceNumber,
1932 packet->header.timestamp);
1933 }
1934 prev_sequence_number = packet->header.sequenceNumber;
1935 prev_timestamp = packet->header.timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001936 prev_payload_type = packet->header.payloadType;
1937 }
1938
1939 // Store number of extracted samples.
1940 int packet_duration = 0;
1941 AudioDecoder* decoder = decoder_database_->GetDecoder(
1942 packet->header.payloadType);
1943 if (decoder) {
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001944 if (packet->sync_packet) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001945 packet_duration = rtc::checked_cast<int>(decoder_frame_length_);
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001946 } else {
minyue@webrtc.org2c1bcf22015-02-17 10:17:09 +00001947 if (packet->primary) {
1948 packet_duration = decoder->PacketDuration(packet->payload,
1949 packet->payload_length);
1950 } else {
1951 packet_duration = decoder->
1952 PacketDurationRedundant(packet->payload, packet->payload_length);
1953 stats_.SecondaryDecodedSamples(packet_duration);
1954 }
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001955 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001956 } else {
Henrik Lundind67a2192015-08-03 12:54:37 +02001957 LOG(LS_WARNING) << "Unknown payload type "
1958 << static_cast<int>(packet->header.payloadType);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001959 assert(false);
1960 }
1961 if (packet_duration <= 0) {
1962 // Decoder did not return a packet duration. Assume that the packet
1963 // contains the same number of samples as the previous one.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001964 packet_duration = rtc::checked_cast<int>(decoder_frame_length_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001965 }
1966 extracted_samples = packet->header.timestamp - first_timestamp +
1967 packet_duration;
1968
1969 // Check what packet is available next.
1970 header = packet_buffer_->NextRtpHeader();
1971 next_packet_available = false;
1972 if (header && prev_payload_type == header->payloadType) {
1973 int16_t seq_no_diff = header->sequenceNumber - prev_sequence_number;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001974 size_t ts_diff = header->timestamp - prev_timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001975 if (seq_no_diff == 1 ||
1976 (seq_no_diff == 0 && ts_diff == decoder_frame_length_)) {
1977 // The next sequence number is available, or the next part of a packet
1978 // that was split into pieces upon insertion.
1979 next_packet_available = true;
1980 }
1981 prev_sequence_number = header->sequenceNumber;
1982 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07001983 } while (extracted_samples < rtc::checked_cast<int>(required_samples) &&
1984 next_packet_available);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001985
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00001986 if (extracted_samples > 0) {
1987 // Delete old packets only when we are going to decode something. Otherwise,
1988 // we could end up in the situation where we never decode anything, since
1989 // all incoming packets are considered too old but the buffer will also
1990 // never be flooded and flushed.
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001991 packet_buffer_->DiscardAllOldPackets(timestamp_);
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00001992 }
1993
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001994 return extracted_samples;
1995}
1996
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001997void NetEqImpl::UpdatePlcComponents(int fs_hz, size_t channels) {
1998 // Delete objects and create new ones.
1999 expand_.reset(expand_factory_->Create(background_noise_.get(),
2000 sync_buffer_.get(), &random_vector_,
Henrik Lundinbef77e22015-08-18 14:58:09 +02002001 &stats_, fs_hz, channels));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002002 merge_.reset(new Merge(fs_hz, channels, expand_.get(), sync_buffer_.get()));
2003}
2004
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002005void NetEqImpl::SetSampleRateAndChannels(int fs_hz, size_t channels) {
Henrik Lundind67a2192015-08-03 12:54:37 +02002006 LOG(LS_VERBOSE) << "SetSampleRateAndChannels " << fs_hz << " " << channels;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002007 // TODO(hlundin): Change to an enumerator and skip assert.
2008 assert(fs_hz == 8000 || fs_hz == 16000 || fs_hz == 32000 || fs_hz == 48000);
2009 assert(channels > 0);
2010
2011 fs_hz_ = fs_hz;
2012 fs_mult_ = fs_hz / 8000;
Peter Kastingdce40cf2015-08-24 14:52:23 -07002013 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002014 decoder_frame_length_ = 3 * output_size_samples_; // Initialize to 30ms.
2015
2016 last_mode_ = kModeNormal;
2017
2018 // Create a new array of mute factors and set all to 1.
2019 mute_factor_array_.reset(new int16_t[channels]);
2020 for (size_t i = 0; i < channels; ++i) {
2021 mute_factor_array_[i] = 16384; // 1.0 in Q14.
2022 }
2023
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002024 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02002025 if (cng_decoder)
2026 cng_decoder->Reset();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002027
2028 // Reinit post-decode VAD with new sample rate.
2029 assert(vad_.get()); // Cannot be NULL here.
2030 vad_->Init();
2031
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002032 // Delete algorithm buffer and create a new one.
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00002033 algorithm_buffer_.reset(new AudioMultiVector(channels));
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002034
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002035 // Delete sync buffer and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002036 sync_buffer_.reset(new SyncBuffer(channels, kSyncBufferSize * fs_mult_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002037
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00002038 // Delete BackgroundNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002039 background_noise_.reset(new BackgroundNoise(channels));
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00002040 background_noise_->set_mode(background_noise_mode_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002041
2042 // Reset random vector.
2043 random_vector_.Reset();
2044
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002045 UpdatePlcComponents(fs_hz, channels);
2046
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002047 // Move index so that we create a small set of future samples (all 0).
2048 sync_buffer_->set_next_index(sync_buffer_->next_index() -
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002049 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002050
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002051 normal_.reset(new Normal(fs_hz, decoder_database_.get(), *background_noise_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002052 expand_.get()));
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +00002053 accelerate_.reset(
2054 accelerate_factory_->Create(fs_hz, channels, *background_noise_));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002055 preemptive_expand_.reset(preemptive_expand_factory_->Create(
Peter Kastingdce40cf2015-08-24 14:52:23 -07002056 fs_hz, channels, *background_noise_, expand_->overlap_length()));
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002057
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002058 // Delete ComfortNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002059 comfort_noise_.reset(new ComfortNoise(fs_hz, decoder_database_.get(),
2060 sync_buffer_.get()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002061
2062 // Verify that |decoded_buffer_| is long enough.
2063 if (decoded_buffer_length_ < kMaxFrameSize * channels) {
2064 // Reallocate to larger size.
2065 decoded_buffer_length_ = kMaxFrameSize * channels;
2066 decoded_buffer_.reset(new int16_t[decoded_buffer_length_]);
2067 }
2068
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002069 // Create DecisionLogic if it is not created yet, then communicate new sample
2070 // rate and output size to DecisionLogic object.
2071 if (!decision_logic_.get()) {
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002072 CreateDecisionLogic();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002073 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002074 decision_logic_->SetSampleRate(fs_hz_, output_size_samples_);
2075}
2076
henrik.lundin55480f52016-03-08 02:37:57 -08002077NetEqImpl::OutputType NetEqImpl::LastOutputType() {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002078 assert(vad_.get());
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002079 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002080 if (last_mode_ == kModeCodecInternalCng || last_mode_ == kModeRfc3389Cng) {
henrik.lundin55480f52016-03-08 02:37:57 -08002081 return OutputType::kCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002082 } else if (last_mode_ == kModeExpand && expand_->MuteFactor(0) == 0) {
2083 // Expand mode has faded down to background noise only (very long expand).
henrik.lundin55480f52016-03-08 02:37:57 -08002084 return OutputType::kPLCCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002085 } else if (last_mode_ == kModeExpand) {
henrik.lundin55480f52016-03-08 02:37:57 -08002086 return OutputType::kPLC;
wu@webrtc.org24301a62013-12-13 19:17:43 +00002087 } else if (vad_->running() && !vad_->active_speech()) {
henrik.lundin55480f52016-03-08 02:37:57 -08002088 return OutputType::kVadPassive;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002089 } else {
henrik.lundin55480f52016-03-08 02:37:57 -08002090 return OutputType::kNormalSpeech;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002091 }
2092}
2093
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002094void NetEqImpl::CreateDecisionLogic() {
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002095 decision_logic_.reset(DecisionLogic::Create(fs_hz_, output_size_samples_,
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002096 playout_mode_,
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002097 decoder_database_.get(),
2098 *packet_buffer_.get(),
2099 delay_manager_.get(),
2100 buffer_level_filter_.get()));
2101}
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002102} // namespace webrtc