blob: fc74f2de8bcdffbd855071ea61e155a7f55eeae0 [file] [log] [blame]
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001/*
2 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000011#include "webrtc/modules/audio_coding/neteq/neteq_impl.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000012
13#include <assert.h>
14#include <memory.h> // memset
15
16#include <algorithm>
17
henrik.lundin9c3efd02015-08-27 13:12:22 -070018#include "webrtc/base/checks.h"
Henrik Lundind67a2192015-08-03 12:54:37 +020019#include "webrtc/base/logging.h"
Peter Kastingdce40cf2015-08-24 14:52:23 -070020#include "webrtc/base/safe_conversions.h"
henrik.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,
153 NetEqOutputType type,
154 AudioFrame::VADActivity last_vad_activity,
155 AudioFrame* audio_frame) {
156 switch (type) {
157 case kOutputNormal: {
158 audio_frame->speech_type_ = AudioFrame::kNormalSpeech;
159 audio_frame->vad_activity_ = AudioFrame::kVadActive;
160 break;
161 }
162 case kOutputVADPassive: {
163 // 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 }
169 case kOutputCNG: {
170 audio_frame->speech_type_ = AudioFrame::kCNG;
171 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
172 break;
173 }
174 case kOutputPLC: {
175 audio_frame->speech_type_ = AudioFrame::kPLC;
176 audio_frame->vad_activity_ = last_vad_activity;
177 break;
178 }
179 case kOutputPLCtoCNG: {
180 audio_frame->speech_type_ = AudioFrame::kPLCCNG;
181 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
182 break;
183 }
184 default:
185 RTC_NOTREACHED();
186 }
187 if (!vad_enabled) {
188 // Always set kVadUnknown when receive VAD is inactive.
189 audio_frame->vad_activity_ = AudioFrame::kVadUnknown;
190 }
191}
192}
193
henrik.lundin6d8e0112016-03-04 10:34:21 -0800194int NetEqImpl::GetAudio(AudioFrame* audio_frame, NetEqOutputType* type) {
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 }
205 if (type) {
206 *type = LastOutputType();
207 }
henrik.lundin500c04b2016-03-08 02:36:04 -0800208 SetAudioFrameActivityAndType(vad_->enabled(), LastOutputType(),
209 last_vad_activity_, audio_frame);
210 last_vad_activity_ = audio_frame->vad_activity_;
henrik.lundin6d8e0112016-03-04 10:34:21 -0800211 last_output_sample_rate_hz_ = audio_frame->sample_rate_hz_;
henrik.lundind89814b2015-11-23 06:49:25 -0800212 RTC_DCHECK(last_output_sample_rate_hz_ == 8000 ||
213 last_output_sample_rate_hz_ == 16000 ||
214 last_output_sample_rate_hz_ == 32000 ||
215 last_output_sample_rate_hz_ == 48000)
216 << "Unexpected sample rate " << last_output_sample_rate_hz_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000217 return kOK;
218}
219
kwibergee1879c2015-10-29 06:20:28 -0700220int NetEqImpl::RegisterPayloadType(NetEqDecoder codec,
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800221 const std::string& name,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000222 uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100223 rtc::CritScope lock(&crit_sect_);
Henrik Lundind67a2192015-08-03 12:54:37 +0200224 LOG(LS_VERBOSE) << "RegisterPayloadType "
kwibergee1879c2015-10-29 06:20:28 -0700225 << static_cast<int>(rtp_payload_type) << " "
226 << static_cast<int>(codec);
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800227 int ret = decoder_database_->RegisterPayload(rtp_payload_type, codec, name);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000228 if (ret != DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000229 switch (ret) {
230 case DecoderDatabase::kInvalidRtpPayloadType:
231 error_code_ = kInvalidRtpPayloadType;
232 break;
233 case DecoderDatabase::kCodecNotSupported:
234 error_code_ = kCodecNotSupported;
235 break;
236 case DecoderDatabase::kDecoderExists:
237 error_code_ = kDecoderExists;
238 break;
239 default:
240 error_code_ = kOtherError;
241 }
242 return kFail;
243 }
244 return kOK;
245}
246
247int NetEqImpl::RegisterExternalDecoder(AudioDecoder* decoder,
kwibergee1879c2015-10-29 06:20:28 -0700248 NetEqDecoder codec,
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800249 const std::string& codec_name,
Karl Wibergd8399e62015-05-25 14:39:56 +0200250 uint8_t rtp_payload_type,
251 int sample_rate_hz) {
Tommi9090e0b2016-01-20 13:39:36 +0100252 rtc::CritScope lock(&crit_sect_);
Henrik Lundind67a2192015-08-03 12:54:37 +0200253 LOG(LS_VERBOSE) << "RegisterExternalDecoder "
kwibergee1879c2015-10-29 06:20:28 -0700254 << static_cast<int>(rtp_payload_type) << " "
255 << static_cast<int>(codec);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000256 if (!decoder) {
257 LOG(LS_ERROR) << "Cannot register external decoder with NULL pointer";
258 assert(false);
259 return kFail;
260 }
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800261 int ret = decoder_database_->InsertExternal(
262 rtp_payload_type, codec, codec_name, sample_rate_hz, decoder);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000263 if (ret != DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000264 switch (ret) {
265 case DecoderDatabase::kInvalidRtpPayloadType:
266 error_code_ = kInvalidRtpPayloadType;
267 break;
268 case DecoderDatabase::kCodecNotSupported:
269 error_code_ = kCodecNotSupported;
270 break;
271 case DecoderDatabase::kDecoderExists:
272 error_code_ = kDecoderExists;
273 break;
274 case DecoderDatabase::kInvalidSampleRate:
275 error_code_ = kInvalidSampleRate;
276 break;
277 case DecoderDatabase::kInvalidPointer:
278 error_code_ = kInvalidPointer;
279 break;
280 default:
281 error_code_ = kOtherError;
282 }
283 return kFail;
284 }
285 return kOK;
286}
287
288int NetEqImpl::RemovePayloadType(uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100289 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000290 int ret = decoder_database_->Remove(rtp_payload_type);
291 if (ret == DecoderDatabase::kOK) {
292 return kOK;
293 } else if (ret == DecoderDatabase::kDecoderNotFound) {
294 error_code_ = kDecoderNotFound;
295 } else {
296 error_code_ = kOtherError;
297 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000298 return kFail;
299}
300
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000301bool NetEqImpl::SetMinimumDelay(int delay_ms) {
Tommi9090e0b2016-01-20 13:39:36 +0100302 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000303 if (delay_ms >= 0 && delay_ms < 10000) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000304 assert(delay_manager_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000305 return delay_manager_->SetMinimumDelay(delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000306 }
307 return false;
308}
309
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000310bool NetEqImpl::SetMaximumDelay(int delay_ms) {
Tommi9090e0b2016-01-20 13:39:36 +0100311 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000312 if (delay_ms >= 0 && delay_ms < 10000) {
313 assert(delay_manager_.get());
314 return delay_manager_->SetMaximumDelay(delay_ms);
315 }
316 return false;
317}
318
319int NetEqImpl::LeastRequiredDelayMs() const {
Tommi9090e0b2016-01-20 13:39:36 +0100320 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000321 assert(delay_manager_.get());
322 return delay_manager_->least_required_delay_ms();
323}
324
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200325int NetEqImpl::SetTargetDelay() {
326 return kNotImplemented;
327}
328
329int NetEqImpl::TargetDelay() {
330 return kNotImplemented;
331}
332
henrik.lundin9c3efd02015-08-27 13:12:22 -0700333int NetEqImpl::CurrentDelayMs() const {
Tommi9090e0b2016-01-20 13:39:36 +0100334 rtc::CritScope lock(&crit_sect_);
henrik.lundin9c3efd02015-08-27 13:12:22 -0700335 if (fs_hz_ == 0)
336 return 0;
337 // Sum up the samples in the packet buffer with the future length of the sync
338 // buffer, and divide the sum by the sample rate.
339 const size_t delay_samples =
340 packet_buffer_->NumSamplesInBuffer(decoder_database_.get(),
341 decoder_frame_length_) +
342 sync_buffer_->FutureLength();
343 // The division below will truncate.
344 const int delay_ms =
345 static_cast<int>(delay_samples) / rtc::CheckedDivExact(fs_hz_, 1000);
346 return delay_ms;
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200347}
348
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000349// Deprecated.
350// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000351void NetEqImpl::SetPlayoutMode(NetEqPlayoutMode mode) {
Tommi9090e0b2016-01-20 13:39:36 +0100352 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000353 if (mode != playout_mode_) {
354 playout_mode_ = mode;
355 CreateDecisionLogic();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000356 }
357}
358
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000359// Deprecated.
360// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000361NetEqPlayoutMode NetEqImpl::PlayoutMode() const {
Tommi9090e0b2016-01-20 13:39:36 +0100362 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000363 return playout_mode_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000364}
365
366int NetEqImpl::NetworkStatistics(NetEqNetworkStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100367 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000368 assert(decoder_database_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700369 const size_t total_samples_in_buffers =
Peter Kasting728d9032015-06-11 14:31:38 -0700370 packet_buffer_->NumSamplesInBuffer(decoder_database_.get(),
371 decoder_frame_length_) +
Peter Kastingdce40cf2015-08-24 14:52:23 -0700372 sync_buffer_->FutureLength();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000373 assert(delay_manager_.get());
374 assert(decision_logic_.get());
375 stats_.GetNetworkStatistics(fs_hz_, total_samples_in_buffers,
376 decoder_frame_length_, *delay_manager_.get(),
377 *decision_logic_.get(), stats);
378 return 0;
379}
380
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000381void NetEqImpl::GetRtcpStatistics(RtcpStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100382 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000383 if (stats) {
384 rtcp_.GetStatistics(false, stats);
385 }
386}
387
388void NetEqImpl::GetRtcpStatisticsNoReset(RtcpStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100389 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000390 if (stats) {
391 rtcp_.GetStatistics(true, stats);
392 }
393}
394
395void NetEqImpl::EnableVad() {
Tommi9090e0b2016-01-20 13:39:36 +0100396 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000397 assert(vad_.get());
398 vad_->Enable();
399}
400
401void NetEqImpl::DisableVad() {
Tommi9090e0b2016-01-20 13:39:36 +0100402 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000403 assert(vad_.get());
404 vad_->Disable();
405}
406
wu@webrtc.org94454b72014-06-05 20:34:08 +0000407bool NetEqImpl::GetPlayoutTimestamp(uint32_t* timestamp) {
Tommi9090e0b2016-01-20 13:39:36 +0100408 rtc::CritScope lock(&crit_sect_);
wu@webrtc.org94454b72014-06-05 20:34:08 +0000409 if (first_packet_) {
410 // We don't have a valid RTP timestamp until we have decoded our first
411 // RTP packet.
412 return false;
413 }
414 *timestamp = timestamp_scaler_->ToExternal(playout_timestamp_);
415 return true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000416}
417
henrik.lundind89814b2015-11-23 06:49:25 -0800418int NetEqImpl::last_output_sample_rate_hz() const {
Tommi9090e0b2016-01-20 13:39:36 +0100419 rtc::CritScope lock(&crit_sect_);
henrik.lundind89814b2015-11-23 06:49:25 -0800420 return last_output_sample_rate_hz_;
421}
422
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200423int NetEqImpl::SetTargetNumberOfChannels() {
424 return kNotImplemented;
425}
426
427int NetEqImpl::SetTargetSampleRate() {
428 return kNotImplemented;
429}
430
henrik.lundin@webrtc.orgb0f4b3d2014-11-04 08:53:10 +0000431int NetEqImpl::LastError() const {
Tommi9090e0b2016-01-20 13:39:36 +0100432 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000433 return error_code_;
434}
435
436int NetEqImpl::LastDecoderError() {
Tommi9090e0b2016-01-20 13:39:36 +0100437 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000438 return decoder_error_code_;
439}
440
441void NetEqImpl::FlushBuffers() {
Tommi9090e0b2016-01-20 13:39:36 +0100442 rtc::CritScope lock(&crit_sect_);
Henrik Lundind67a2192015-08-03 12:54:37 +0200443 LOG(LS_VERBOSE) << "FlushBuffers";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000444 packet_buffer_->Flush();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000445 assert(sync_buffer_.get());
446 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000447 sync_buffer_->Flush();
448 sync_buffer_->set_next_index(sync_buffer_->next_index() -
449 expand_->overlap_length());
450 // Set to wait for new codec.
451 first_packet_ = true;
452}
453
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000454void NetEqImpl::PacketBufferStatistics(int* current_num_packets,
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000455 int* max_num_packets) const {
Tommi9090e0b2016-01-20 13:39:36 +0100456 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000457 packet_buffer_->BufferStat(current_num_packets, max_num_packets);
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000458}
459
henrik.lundin48ed9302015-10-29 05:36:24 -0700460void NetEqImpl::EnableNack(size_t max_nack_list_size) {
Tommi9090e0b2016-01-20 13:39:36 +0100461 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700462 if (!nack_enabled_) {
463 const int kNackThresholdPackets = 2;
464 nack_.reset(Nack::Create(kNackThresholdPackets));
465 nack_enabled_ = true;
466 nack_->UpdateSampleRate(fs_hz_);
467 }
468 nack_->SetMaxNackListSize(max_nack_list_size);
469}
470
471void NetEqImpl::DisableNack() {
Tommi9090e0b2016-01-20 13:39:36 +0100472 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700473 nack_.reset();
474 nack_enabled_ = false;
475}
476
477std::vector<uint16_t> NetEqImpl::GetNackList(int64_t round_trip_time_ms) const {
Tommi9090e0b2016-01-20 13:39:36 +0100478 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700479 if (!nack_enabled_) {
480 return std::vector<uint16_t>();
481 }
482 RTC_DCHECK(nack_.get());
483 return nack_->GetNackList(round_trip_time_ms);
minyue@webrtc.orgd7301772013-08-29 00:58:14 +0000484}
485
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000486const SyncBuffer* NetEqImpl::sync_buffer_for_test() const {
Tommi9090e0b2016-01-20 13:39:36 +0100487 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000488 return sync_buffer_.get();
489}
490
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000491// Methods below this line are private.
492
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000493int NetEqImpl::InsertPacketInternal(const WebRtcRTPHeader& rtp_header,
kwibergee2bac22015-11-11 10:34:00 -0800494 rtc::ArrayView<const uint8_t> payload,
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000495 uint32_t receive_timestamp,
496 bool is_sync_packet) {
kwibergee2bac22015-11-11 10:34:00 -0800497 if (payload.empty()) {
498 LOG_F(LS_ERROR) << "payload is empty";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000499 return kInvalidPointer;
500 }
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000501 // Sanity checks for sync-packets.
502 if (is_sync_packet) {
503 if (decoder_database_->IsDtmf(rtp_header.header.payloadType) ||
504 decoder_database_->IsRed(rtp_header.header.payloadType) ||
505 decoder_database_->IsComfortNoise(rtp_header.header.payloadType)) {
506 LOG_F(LS_ERROR) << "Sync-packet with an unacceptable payload type "
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000507 << static_cast<int>(rtp_header.header.payloadType);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000508 return kSyncPacketNotAccepted;
509 }
510 if (first_packet_ ||
511 rtp_header.header.payloadType != current_rtp_payload_type_ ||
512 rtp_header.header.ssrc != ssrc_) {
513 // Even if |current_rtp_payload_type_| is 0xFF, sync-packet isn't
514 // accepted.
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000515 LOG_F(LS_ERROR)
516 << "Changing codec, SSRC or first packet with sync-packet.";
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000517 return kSyncPacketNotAccepted;
518 }
519 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000520 PacketList packet_list;
521 RTPHeader main_header;
522 {
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000523 // Convert to Packet.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000524 // Create |packet| within this separate scope, since it should not be used
525 // directly once it's been inserted in the packet list. This way, |packet|
526 // is not defined outside of this block.
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000527 Packet* packet = new Packet;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000528 packet->header.markerBit = false;
529 packet->header.payloadType = rtp_header.header.payloadType;
530 packet->header.sequenceNumber = rtp_header.header.sequenceNumber;
531 packet->header.timestamp = rtp_header.header.timestamp;
532 packet->header.ssrc = rtp_header.header.ssrc;
533 packet->header.numCSRCs = 0;
kwibergee2bac22015-11-11 10:34:00 -0800534 packet->payload_length = payload.size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000535 packet->primary = true;
536 packet->waiting_time = 0;
537 packet->payload = new uint8_t[packet->payload_length];
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000538 packet->sync_packet = is_sync_packet;
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +0000539 if (!packet->payload) {
540 LOG_F(LS_ERROR) << "Payload pointer is NULL.";
541 }
kwibergee2bac22015-11-11 10:34:00 -0800542 assert(!payload.empty()); // Already checked above.
543 memcpy(packet->payload, payload.data(), packet->payload_length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000544 // Insert packet in a packet list.
545 packet_list.push_back(packet);
546 // Save main payloads header for later.
547 memcpy(&main_header, &packet->header, sizeof(main_header));
548 }
549
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000550 bool update_sample_rate_and_channels = false;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000551 // Reinitialize NetEq if it's needed (changed SSRC or first call).
552 if ((main_header.ssrc != ssrc_) || first_packet_) {
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000553 // Note: |first_packet_| will be cleared further down in this method, once
554 // the packet has been successfully inserted into the packet buffer.
555
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000556 rtcp_.Init(main_header.sequenceNumber);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000557
558 // Flush the packet buffer and DTMF buffer.
559 packet_buffer_->Flush();
560 dtmf_buffer_->Flush();
561
562 // Store new SSRC.
563 ssrc_ = main_header.ssrc;
564
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000565 // Update audio buffer timestamp.
566 sync_buffer_->IncreaseEndTimestamp(main_header.timestamp - timestamp_);
567
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000568 // Update codecs.
569 timestamp_ = main_header.timestamp;
570 current_rtp_payload_type_ = main_header.payloadType;
571
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000572 // Reset timestamp scaling.
573 timestamp_scaler_->Reset();
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000574
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000575 // Trigger an update of sampling rate and the number of channels.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000576 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000577 }
578
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000579 // Update RTCP statistics, only for regular packets.
580 if (!is_sync_packet)
581 rtcp_.Update(main_header, receive_timestamp);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000582
583 // Check for RED payload type, and separate payloads into several packets.
584 if (decoder_database_->IsRed(main_header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000585 assert(!is_sync_packet); // We had a sanity check for this.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000586 if (payload_splitter_->SplitRed(&packet_list) != PayloadSplitter::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000587 PacketBuffer::DeleteAllPackets(&packet_list);
588 return kRedundancySplitError;
589 }
590 // Only accept a few RED payloads of the same type as the main data,
591 // DTMF events and CNG.
592 payload_splitter_->CheckRedPayloads(&packet_list, *decoder_database_);
593 // Update the stored main payload header since the main payload has now
594 // changed.
595 memcpy(&main_header, &packet_list.front()->header, sizeof(main_header));
596 }
597
598 // Check payload types.
599 if (decoder_database_->CheckPayloadTypes(packet_list) ==
600 DecoderDatabase::kDecoderNotFound) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000601 PacketBuffer::DeleteAllPackets(&packet_list);
602 return kUnknownRtpPayloadType;
603 }
604
605 // Scale timestamp to internal domain (only for some codecs).
606 timestamp_scaler_->ToInternal(&packet_list);
607
608 // Process DTMF payloads. Cycle through the list of packets, and pick out any
609 // DTMF payloads found.
610 PacketList::iterator it = packet_list.begin();
611 while (it != packet_list.end()) {
612 Packet* current_packet = (*it);
613 assert(current_packet);
614 assert(current_packet->payload);
615 if (decoder_database_->IsDtmf(current_packet->header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000616 assert(!current_packet->sync_packet); // We had a sanity check for this.
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000617 DtmfEvent event;
618 int ret = DtmfBuffer::ParseEvent(
619 current_packet->header.timestamp,
620 current_packet->payload,
621 current_packet->payload_length,
622 &event);
623 if (ret != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000624 PacketBuffer::DeleteAllPackets(&packet_list);
625 return kDtmfParsingError;
626 }
627 if (dtmf_buffer_->InsertEvent(event) != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000628 PacketBuffer::DeleteAllPackets(&packet_list);
629 return kDtmfInsertError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000630 }
631 // TODO(hlundin): Let the destructor of Packet handle the payload.
632 delete [] current_packet->payload;
633 delete current_packet;
634 it = packet_list.erase(it);
635 } else {
636 ++it;
637 }
638 }
639
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000640 // Check for FEC in packets, and separate payloads into several packets.
641 int ret = payload_splitter_->SplitFec(&packet_list, decoder_database_.get());
642 if (ret != PayloadSplitter::kOK) {
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000643 PacketBuffer::DeleteAllPackets(&packet_list);
644 switch (ret) {
645 case PayloadSplitter::kUnknownPayloadType:
646 return kUnknownRtpPayloadType;
647 default:
648 return kOtherError;
649 }
650 }
651
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000652 // Split payloads into smaller chunks. This also verifies that all payloads
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000653 // are of a known payload type. SplitAudio() method is protected against
654 // sync-packets.
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +0000655 ret = payload_splitter_->SplitAudio(&packet_list, *decoder_database_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000656 if (ret != PayloadSplitter::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000657 PacketBuffer::DeleteAllPackets(&packet_list);
658 switch (ret) {
659 case PayloadSplitter::kUnknownPayloadType:
660 return kUnknownRtpPayloadType;
661 case PayloadSplitter::kFrameSplitError:
662 return kFrameSplitError;
663 default:
664 return kOtherError;
665 }
666 }
667
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000668 // Update bandwidth estimate, if the packet is not sync-packet.
669 if (!packet_list.empty() && !packet_list.front()->sync_packet) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000670 // The list can be empty here if we got nothing but DTMF payloads.
671 AudioDecoder* decoder =
672 decoder_database_->GetDecoder(main_header.payloadType);
673 assert(decoder); // Should always get a valid object, since we have
674 // already checked that the payload types are known.
675 decoder->IncomingPacket(packet_list.front()->payload,
676 packet_list.front()->payload_length,
677 packet_list.front()->header.sequenceNumber,
678 packet_list.front()->header.timestamp,
679 receive_timestamp);
680 }
681
henrik.lundin48ed9302015-10-29 05:36:24 -0700682 if (nack_enabled_) {
683 RTC_DCHECK(nack_);
684 if (update_sample_rate_and_channels) {
685 nack_->Reset();
686 }
687 nack_->UpdateLastReceivedPacket(packet_list.front()->header.sequenceNumber,
688 packet_list.front()->header.timestamp);
689 }
690
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000691 // Insert packets in buffer.
henrik.lundin116c84e2015-08-27 13:14:48 -0700692 const size_t buffer_length_before_insert =
693 packet_buffer_->NumPacketsInBuffer();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000694 ret = packet_buffer_->InsertPacketList(
695 &packet_list,
696 *decoder_database_,
697 &current_rtp_payload_type_,
698 &current_cng_rtp_payload_type_);
699 if (ret == PacketBuffer::kFlushed) {
700 // Reset DSP timestamp etc. if packet buffer flushed.
701 new_codec_ = true;
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000702 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000703 } else if (ret != PacketBuffer::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000704 PacketBuffer::DeleteAllPackets(&packet_list);
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000705 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000706 }
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000707
708 if (first_packet_) {
709 first_packet_ = false;
710 // Update the codec on the next GetAudio call.
711 new_codec_ = true;
712 }
713
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000714 if (current_rtp_payload_type_ != 0xFF) {
715 const DecoderDatabase::DecoderInfo* dec_info =
716 decoder_database_->GetDecoderInfo(current_rtp_payload_type_);
717 if (!dec_info) {
718 assert(false); // Already checked that the payload type is known.
719 }
720 }
721
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000722 if (update_sample_rate_and_channels && !packet_buffer_->Empty()) {
723 // We do not use |current_rtp_payload_type_| to |set payload_type|, but
724 // get the next RTP header from |packet_buffer_| to obtain the payload type.
725 // The reason for it is the following corner case. If NetEq receives a
726 // CNG packet with a sample rate different than the current CNG then it
727 // flushes its buffer, assuming send codec must have been changed. However,
728 // payload type of the hypothetically new send codec is not known.
729 const RTPHeader* rtp_header = packet_buffer_->NextRtpHeader();
730 assert(rtp_header);
731 int payload_type = rtp_header->payloadType;
732 AudioDecoder* decoder = decoder_database_->GetDecoder(payload_type);
733 assert(decoder); // Payloads are already checked to be valid.
734 const DecoderDatabase::DecoderInfo* decoder_info =
735 decoder_database_->GetDecoderInfo(payload_type);
736 assert(decoder_info);
737 if (decoder_info->fs_hz != fs_hz_ ||
henrik.lundin48ed9302015-10-29 05:36:24 -0700738 decoder->Channels() != algorithm_buffer_->Channels()) {
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +0000739 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->Channels());
henrik.lundin48ed9302015-10-29 05:36:24 -0700740 }
741 if (nack_enabled_) {
742 RTC_DCHECK(nack_);
743 // Update the sample rate even if the rate is not new, because of Reset().
744 nack_->UpdateSampleRate(fs_hz_);
745 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000746 }
747
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000748 // TODO(hlundin): Move this code to DelayManager class.
749 const DecoderDatabase::DecoderInfo* dec_info =
750 decoder_database_->GetDecoderInfo(main_header.payloadType);
751 assert(dec_info); // Already checked that the payload type is known.
752 delay_manager_->LastDecoderType(dec_info->codec_type);
753 if (delay_manager_->last_pack_cng_or_dtmf() == 0) {
754 // Calculate the total speech length carried in each packet.
henrik.lundin116c84e2015-08-27 13:14:48 -0700755 const size_t buffer_length_after_insert =
756 packet_buffer_->NumPacketsInBuffer();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000757
henrik.lundin116c84e2015-08-27 13:14:48 -0700758 if (buffer_length_after_insert > buffer_length_before_insert) {
759 const size_t packet_length_samples =
760 (buffer_length_after_insert - buffer_length_before_insert) *
761 decoder_frame_length_;
762 if (packet_length_samples != decision_logic_->packet_length_samples()) {
763 decision_logic_->set_packet_length_samples(packet_length_samples);
764 delay_manager_->SetPacketAudioLength(
765 rtc::checked_cast<int>((1000 * packet_length_samples) / fs_hz_));
766 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000767 }
768
769 // Update statistics.
pbos@webrtc.org0946a562013-04-09 00:28:06 +0000770 if ((int32_t) (main_header.timestamp - timestamp_) >= 0 &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000771 !new_codec_) {
772 // Only update statistics if incoming packet is not older than last played
773 // out packet, and if new codec flag is not set.
774 delay_manager_->Update(main_header.sequenceNumber, main_header.timestamp,
775 fs_hz_);
776 }
777 } else if (delay_manager_->last_pack_cng_or_dtmf() == -1) {
778 // This is first "normal" packet after CNG or DTMF.
779 // Reset packet time counter and measure time until next packet,
780 // but don't update statistics.
781 delay_manager_->set_last_pack_cng_or_dtmf(0);
782 delay_manager_->ResetPacketIatCount();
783 }
784 return 0;
785}
786
henrik.lundin6d8e0112016-03-04 10:34:21 -0800787int NetEqImpl::GetAudioInternal(AudioFrame* audio_frame) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000788 PacketList packet_list;
789 DtmfEvent dtmf_event;
790 Operations operation;
791 bool play_dtmf;
792 int return_value = GetDecision(&operation, &packet_list, &dtmf_event,
793 &play_dtmf);
794 if (return_value != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000795 last_mode_ = kModeError;
796 return return_value;
797 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000798
799 AudioDecoder::SpeechType speech_type;
800 int length = 0;
801 int decode_return_value = Decode(&packet_list, &operation,
802 &length, &speech_type);
803
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000804 assert(vad_.get());
805 bool sid_frame_available =
806 (operation == kRfc3389Cng && !packet_list.empty());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700807 vad_->Update(decoded_buffer_.get(), static_cast<size_t>(length), speech_type,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000808 sid_frame_available, fs_hz_);
809
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000810 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000811 switch (operation) {
812 case kNormal: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000813 DoNormal(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000814 break;
815 }
816 case kMerge: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000817 DoMerge(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000818 break;
819 }
820 case kExpand: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000821 return_value = DoExpand(play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000822 break;
823 }
Henrik Lundincf808d22015-05-27 14:33:29 +0200824 case kAccelerate:
825 case kFastAccelerate: {
826 const bool fast_accelerate =
827 enable_fast_accelerate_ && (operation == kFastAccelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000828 return_value = DoAccelerate(decoded_buffer_.get(), length, speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +0200829 play_dtmf, fast_accelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000830 break;
831 }
832 case kPreemptiveExpand: {
833 return_value = DoPreemptiveExpand(decoded_buffer_.get(), length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000834 speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000835 break;
836 }
837 case kRfc3389Cng:
838 case kRfc3389CngNoPacket: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000839 return_value = DoRfc3389Cng(&packet_list, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000840 break;
841 }
842 case kCodecInternalCng: {
843 // This handles the case when there is no transmission and the decoder
844 // should produce internal comfort noise.
845 // TODO(hlundin): Write test for codec-internal CNG.
minyuel6d92bf52015-09-23 15:20:39 +0200846 DoCodecInternalCng(decoded_buffer_.get(), length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000847 break;
848 }
849 case kDtmf: {
850 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000851 return_value = DoDtmf(dtmf_event, &play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000852 break;
853 }
854 case kAlternativePlc: {
855 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000856 DoAlternativePlc(false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000857 break;
858 }
859 case kAlternativePlcIncreaseTimestamp: {
860 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000861 DoAlternativePlc(true);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000862 break;
863 }
864 case kAudioRepetitionIncreaseTimestamp: {
865 // TODO(hlundin): Write test for this.
Peter Kastingb7e50542015-06-11 12:55:50 -0700866 sync_buffer_->IncreaseEndTimestamp(
867 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000868 // Skipping break on purpose. Execution should move on into the
869 // next case.
kjellander@webrtc.org7d2b6a92015-01-28 18:37:58 +0000870 FALLTHROUGH();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000871 }
872 case kAudioRepetition: {
873 // TODO(hlundin): Write test for this.
874 // Copy last |output_size_samples_| from |sync_buffer_| to
875 // |algorithm_buffer|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000876 algorithm_buffer_->PushBackFromIndex(
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000877 *sync_buffer_, sync_buffer_->Size() - output_size_samples_);
878 expand_->Reset();
879 break;
880 }
881 case kUndefined: {
Henrik Lundind67a2192015-08-03 12:54:37 +0200882 LOG(LS_ERROR) << "Invalid operation kUndefined.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000883 assert(false); // This should not happen.
884 last_mode_ = kModeError;
885 return kInvalidOperation;
886 }
887 } // End of switch.
888 if (return_value < 0) {
889 return return_value;
890 }
891
892 if (last_mode_ != kModeRfc3389Cng) {
893 comfort_noise_->Reset();
894 }
895
896 // Copy from |algorithm_buffer| to |sync_buffer_|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000897 sync_buffer_->PushBack(*algorithm_buffer_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000898
899 // Extract data from |sync_buffer_| to |output|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000900 size_t num_output_samples_per_channel = output_size_samples_;
901 size_t num_output_samples = output_size_samples_ * sync_buffer_->Channels();
henrik.lundin6d8e0112016-03-04 10:34:21 -0800902 if (num_output_samples > AudioFrame::kMaxDataSizeSamples) {
903 LOG(LS_WARNING) << "Output array is too short. "
904 << AudioFrame::kMaxDataSizeSamples << " < "
905 << output_size_samples_ << " * "
906 << sync_buffer_->Channels();
907 num_output_samples = AudioFrame::kMaxDataSizeSamples;
908 num_output_samples_per_channel =
909 AudioFrame::kMaxDataSizeSamples / sync_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000910 }
henrik.lundin6d8e0112016-03-04 10:34:21 -0800911 sync_buffer_->GetNextAudioInterleaved(num_output_samples_per_channel,
912 audio_frame);
913 audio_frame->sample_rate_hz_ = fs_hz_;
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200914 if (sync_buffer_->FutureLength() < expand_->overlap_length()) {
915 // The sync buffer should always contain |overlap_length| samples, but now
916 // too many samples have been extracted. Reinstall the |overlap_length|
917 // lookahead by moving the index.
918 const size_t missing_lookahead_samples =
919 expand_->overlap_length() - sync_buffer_->FutureLength();
henrikg91d6ede2015-09-17 00:24:34 -0700920 RTC_DCHECK_GE(sync_buffer_->next_index(), missing_lookahead_samples);
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200921 sync_buffer_->set_next_index(sync_buffer_->next_index() -
922 missing_lookahead_samples);
923 }
henrik.lundin6d8e0112016-03-04 10:34:21 -0800924 if (audio_frame->samples_per_channel_ != output_size_samples_) {
925 LOG(LS_ERROR) << "audio_frame->samples_per_channel_ ("
926 << audio_frame->samples_per_channel_
Henrik Lundind67a2192015-08-03 12:54:37 +0200927 << ") != output_size_samples_ (" << output_size_samples_
928 << ")";
minyue@webrtc.orgdb1cefc2013-08-13 01:39:21 +0000929 // TODO(minyue): treatment of under-run, filling zeros
henrik.lundin6d8e0112016-03-04 10:34:21 -0800930 memset(audio_frame->data_, 0, num_output_samples * sizeof(int16_t));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000931 return kSampleUnderrun;
932 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000933
934 // Should always have overlap samples left in the |sync_buffer_|.
henrikg91d6ede2015-09-17 00:24:34 -0700935 RTC_DCHECK_GE(sync_buffer_->FutureLength(), expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000936
937 if (play_dtmf) {
henrik.lundin6d8e0112016-03-04 10:34:21 -0800938 return_value =
939 DtmfOverdub(dtmf_event, sync_buffer_->Channels(), audio_frame->data_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000940 }
941
942 // Update the background noise parameters if last operation wrote data
943 // straight from the decoder to the |sync_buffer_|. That is, none of the
944 // operations that modify the signal can be followed by a parameter update.
945 if ((last_mode_ == kModeNormal) ||
946 (last_mode_ == kModeAccelerateFail) ||
947 (last_mode_ == kModePreemptiveExpandFail) ||
948 (last_mode_ == kModeRfc3389Cng) ||
949 (last_mode_ == kModeCodecInternalCng)) {
950 background_noise_->Update(*sync_buffer_, *vad_.get());
951 }
952
953 if (operation == kDtmf) {
954 // DTMF data was written the end of |sync_buffer_|.
955 // Update index to end of DTMF data in |sync_buffer_|.
956 sync_buffer_->set_dtmf_index(sync_buffer_->Size());
957 }
958
henrik.lundin@webrtc.orged865b52014-03-06 10:28:07 +0000959 if (last_mode_ != kModeExpand) {
960 // If last operation was not expand, calculate the |playout_timestamp_| from
961 // the |sync_buffer_|. However, do not update the |playout_timestamp_| if it
962 // would be moved "backwards".
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000963 uint32_t temp_timestamp = sync_buffer_->end_timestamp() -
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000964 static_cast<uint32_t>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000965 if (static_cast<int32_t>(temp_timestamp - playout_timestamp_) > 0) {
966 playout_timestamp_ = temp_timestamp;
967 }
968 } else {
969 // Use dead reckoning to estimate the |playout_timestamp_|.
Peter Kastingb7e50542015-06-11 12:55:50 -0700970 playout_timestamp_ += static_cast<uint32_t>(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000971 }
972
973 if (decode_return_value) return decode_return_value;
974 return return_value;
975}
976
977int NetEqImpl::GetDecision(Operations* operation,
978 PacketList* packet_list,
979 DtmfEvent* dtmf_event,
980 bool* play_dtmf) {
981 // Initialize output variables.
982 *play_dtmf = false;
983 *operation = kUndefined;
984
985 // Increment time counters.
986 packet_buffer_->IncrementWaitingTimes();
987 stats_.IncreaseCounter(output_size_samples_, fs_hz_);
988
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000989 assert(sync_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000990 uint32_t end_timestamp = sync_buffer_->end_timestamp();
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +0000991 if (!new_codec_) {
992 const uint32_t five_seconds_samples = 5 * fs_hz_;
993 packet_buffer_->DiscardOldPackets(end_timestamp, five_seconds_samples);
994 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000995 const RTPHeader* header = packet_buffer_->NextRtpHeader();
996
henrik.lundin@webrtc.orgca8cb952014-03-12 10:26:52 +0000997 if (decision_logic_->CngRfc3389On() || last_mode_ == kModeRfc3389Cng) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000998 // Because of timestamp peculiarities, we have to "manually" disallow using
999 // a CNG packet with the same timestamp as the one that was last played.
1000 // This can happen when using redundancy and will cause the timing to shift.
henrik.lundin@webrtc.org24779fe2014-03-14 12:40:05 +00001001 while (header && decoder_database_->IsComfortNoise(header->payloadType) &&
1002 (end_timestamp >= header->timestamp ||
1003 end_timestamp + decision_logic_->generated_noise_samples() >
1004 header->timestamp)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001005 // Don't use this packet, discard it.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001006 if (packet_buffer_->DiscardNextPacket() != PacketBuffer::kOK) {
1007 assert(false); // Must be ok by design.
1008 }
1009 // Check buffer again.
1010 if (!new_codec_) {
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001011 packet_buffer_->DiscardOldPackets(end_timestamp, 5 * fs_hz_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001012 }
1013 header = packet_buffer_->NextRtpHeader();
1014 }
1015 }
1016
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001017 assert(expand_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001018 const int samples_left = static_cast<int>(sync_buffer_->FutureLength() -
1019 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001020 if (last_mode_ == kModeAccelerateSuccess ||
1021 last_mode_ == kModeAccelerateLowEnergy ||
1022 last_mode_ == kModePreemptiveExpandSuccess ||
1023 last_mode_ == kModePreemptiveExpandLowEnergy) {
1024 // Subtract (samples_left + output_size_samples_) from sampleMemory.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001025 decision_logic_->AddSampleMemory(
1026 -(samples_left + rtc::checked_cast<int>(output_size_samples_)));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001027 }
1028
1029 // Check if it is time to play a DTMF event.
Peter Kastingb7e50542015-06-11 12:55:50 -07001030 if (dtmf_buffer_->GetEvent(
1031 static_cast<uint32_t>(
1032 end_timestamp + decision_logic_->generated_noise_samples()),
1033 dtmf_event)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001034 *play_dtmf = true;
1035 }
1036
1037 // Get instruction.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001038 assert(sync_buffer_.get());
1039 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001040 *operation = decision_logic_->GetDecision(*sync_buffer_,
1041 *expand_,
1042 decoder_frame_length_,
1043 header,
1044 last_mode_,
1045 *play_dtmf,
1046 &reset_decoder_);
1047
1048 // Check if we already have enough samples in the |sync_buffer_|. If so,
1049 // change decision to normal, unless the decision was merge, accelerate, or
1050 // preemptive expand.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001051 if (samples_left >= rtc::checked_cast<int>(output_size_samples_) &&
1052 *operation != kMerge &&
1053 *operation != kAccelerate &&
1054 *operation != kFastAccelerate &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001055 *operation != kPreemptiveExpand) {
1056 *operation = kNormal;
1057 return 0;
1058 }
1059
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001060 decision_logic_->ExpandDecision(*operation);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001061
1062 // Check conditions for reset.
1063 if (new_codec_ || *operation == kUndefined) {
1064 // The only valid reason to get kUndefined is that new_codec_ is set.
1065 assert(new_codec_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001066 if (*play_dtmf && !header) {
1067 timestamp_ = dtmf_event->timestamp;
1068 } else {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001069 if (!header) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001070 LOG(LS_ERROR) << "Packet missing where it shouldn't.";
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001071 return -1;
1072 }
1073 timestamp_ = header->timestamp;
1074 if (*operation == kRfc3389CngNoPacket
1075#ifndef LEGACY_BITEXACT
1076 // Without this check, it can happen that a non-CNG packet is sent to
1077 // the CNG decoder as if it was a SID frame. This is clearly a bug,
1078 // but is kept for now to maintain bit-exactness with the test
1079 // vectors.
1080 && decoder_database_->IsComfortNoise(header->payloadType)
1081#endif
1082 ) {
1083 // Change decision to CNG packet, since we do have a CNG packet, but it
1084 // was considered too early to use. Now, use it anyway.
1085 *operation = kRfc3389Cng;
1086 } else if (*operation != kRfc3389Cng) {
1087 *operation = kNormal;
1088 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001089 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001090 // Adjust |sync_buffer_| timestamp before setting |end_timestamp| to the
1091 // new value.
1092 sync_buffer_->IncreaseEndTimestamp(timestamp_ - end_timestamp);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001093 end_timestamp = timestamp_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001094 new_codec_ = false;
1095 decision_logic_->SoftReset();
1096 buffer_level_filter_->Reset();
1097 delay_manager_->Reset();
1098 stats_.ResetMcu();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001099 }
1100
Peter Kastingdce40cf2015-08-24 14:52:23 -07001101 size_t required_samples = output_size_samples_;
1102 const size_t samples_10_ms = static_cast<size_t>(80 * fs_mult_);
1103 const size_t samples_20_ms = 2 * samples_10_ms;
1104 const size_t samples_30_ms = 3 * samples_10_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001105
1106 switch (*operation) {
1107 case kExpand: {
1108 timestamp_ = end_timestamp;
1109 return 0;
1110 }
1111 case kRfc3389CngNoPacket:
1112 case kCodecInternalCng: {
1113 return 0;
1114 }
1115 case kDtmf: {
1116 // TODO(hlundin): Write test for this.
1117 // Update timestamp.
1118 timestamp_ = end_timestamp;
1119 if (decision_logic_->generated_noise_samples() > 0 &&
1120 last_mode_ != kModeDtmf) {
1121 // Make a jump in timestamp due to the recently played comfort noise.
Peter Kastingb7e50542015-06-11 12:55:50 -07001122 uint32_t timestamp_jump =
1123 static_cast<uint32_t>(decision_logic_->generated_noise_samples());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001124 sync_buffer_->IncreaseEndTimestamp(timestamp_jump);
1125 timestamp_ += timestamp_jump;
1126 }
1127 decision_logic_->set_generated_noise_samples(0);
1128 return 0;
1129 }
Henrik Lundincf808d22015-05-27 14:33:29 +02001130 case kAccelerate:
1131 case kFastAccelerate: {
1132 // In order to do an accelerate we need at least 30 ms of audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001133 if (samples_left >= static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001134 // Already have enough data, so we do not need to extract any more.
1135 decision_logic_->set_sample_memory(samples_left);
1136 decision_logic_->set_prev_time_scale(true);
1137 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001138 } else if (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001139 decoder_frame_length_ >= samples_30_ms) {
1140 // Avoid decoding more data as it might overflow the playout buffer.
1141 *operation = kNormal;
1142 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001143 } else if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001144 decoder_frame_length_ < samples_30_ms) {
1145 // Build up decoded data by decoding at least 20 ms of audio data. Do
1146 // not perform accelerate yet, but wait until we only need to do one
1147 // decoding.
1148 required_samples = 2 * output_size_samples_;
1149 *operation = kNormal;
1150 }
1151 // If none of the above is true, we have one of two possible situations:
1152 // (1) 20 ms <= samples_left < 30 ms and decoder_frame_length_ < 30 ms; or
1153 // (2) samples_left < 10 ms and decoder_frame_length_ >= 30 ms.
1154 // In either case, we move on with the accelerate decision, and decode one
1155 // frame now.
1156 break;
1157 }
1158 case kPreemptiveExpand: {
1159 // In order to do a preemptive expand we need at least 30 ms of decoded
1160 // audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001161 if ((samples_left >= static_cast<int>(samples_30_ms)) ||
1162 (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001163 decoder_frame_length_ >= samples_30_ms)) {
1164 // Already have enough data, so we do not need to extract any more.
1165 // Or, avoid decoding more data as it might overflow the playout buffer.
1166 // Still try preemptive expand, though.
1167 decision_logic_->set_sample_memory(samples_left);
1168 decision_logic_->set_prev_time_scale(true);
1169 return 0;
1170 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07001171 if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001172 decoder_frame_length_ < samples_30_ms) {
1173 // Build up decoded data by decoding at least 20 ms of audio data.
1174 // Still try to perform preemptive expand.
1175 required_samples = 2 * output_size_samples_;
1176 }
1177 // Move on with the preemptive expand decision.
1178 break;
1179 }
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001180 case kMerge: {
1181 required_samples =
1182 std::max(merge_->RequiredFutureSamples(), required_samples);
1183 break;
1184 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001185 default: {
1186 // Do nothing.
1187 }
1188 }
1189
1190 // Get packets from buffer.
1191 int extracted_samples = 0;
1192 if (header &&
1193 *operation != kAlternativePlc &&
1194 *operation != kAlternativePlcIncreaseTimestamp &&
1195 *operation != kAudioRepetition &&
1196 *operation != kAudioRepetitionIncreaseTimestamp) {
1197 sync_buffer_->IncreaseEndTimestamp(header->timestamp - end_timestamp);
1198 if (decision_logic_->CngOff()) {
1199 // Adjustment of timestamp only corresponds to an actual packet loss
1200 // if comfort noise is not played. If comfort noise was just played,
1201 // this adjustment of timestamp is only done to get back in sync with the
1202 // stream timestamp; no loss to report.
1203 stats_.LostSamples(header->timestamp - end_timestamp);
1204 }
1205
1206 if (*operation != kRfc3389Cng) {
1207 // We are about to decode and use a non-CNG packet.
1208 decision_logic_->SetCngOff();
1209 }
1210 // Reset CNG timestamp as a new packet will be delivered.
1211 // (Also if this is a CNG packet, since playedOutTS is updated.)
1212 decision_logic_->set_generated_noise_samples(0);
1213
1214 extracted_samples = ExtractPackets(required_samples, packet_list);
1215 if (extracted_samples < 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001216 return kPacketBufferCorruption;
1217 }
1218 }
1219
Henrik Lundincf808d22015-05-27 14:33:29 +02001220 if (*operation == kAccelerate || *operation == kFastAccelerate ||
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001221 *operation == kPreemptiveExpand) {
1222 decision_logic_->set_sample_memory(samples_left + extracted_samples);
1223 decision_logic_->set_prev_time_scale(true);
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 // Check that we have enough data (30ms) to do accelerate.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001228 if (extracted_samples + samples_left < static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001229 // TODO(hlundin): Write test for this.
1230 // Not enough, do normal operation instead.
1231 *operation = kNormal;
1232 }
1233 }
1234
1235 timestamp_ = end_timestamp;
1236 return 0;
1237}
1238
1239int NetEqImpl::Decode(PacketList* packet_list, Operations* operation,
1240 int* decoded_length,
1241 AudioDecoder::SpeechType* speech_type) {
1242 *speech_type = AudioDecoder::kSpeech;
minyuel6d92bf52015-09-23 15:20:39 +02001243
1244 // When packet_list is empty, we may be in kCodecInternalCng mode, and for
1245 // that we use current active decoder.
1246 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1247
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001248 if (!packet_list->empty()) {
1249 const Packet* packet = packet_list->front();
pkasting@chromium.org0e81fdf2015-02-02 23:54:03 +00001250 uint8_t payload_type = packet->header.payloadType;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001251 if (!decoder_database_->IsComfortNoise(payload_type)) {
1252 decoder = decoder_database_->GetDecoder(payload_type);
1253 assert(decoder);
1254 if (!decoder) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001255 LOG(LS_WARNING) << "Unknown payload type "
1256 << static_cast<int>(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001257 PacketBuffer::DeleteAllPackets(packet_list);
1258 return kDecoderNotFound;
1259 }
1260 bool decoder_changed;
1261 decoder_database_->SetActiveDecoder(payload_type, &decoder_changed);
1262 if (decoder_changed) {
1263 // We have a new decoder. Re-init some values.
1264 const DecoderDatabase::DecoderInfo* decoder_info = decoder_database_
1265 ->GetDecoderInfo(payload_type);
1266 assert(decoder_info);
1267 if (!decoder_info) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001268 LOG(LS_WARNING) << "Unknown payload type "
1269 << static_cast<int>(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001270 PacketBuffer::DeleteAllPackets(packet_list);
1271 return kDecoderNotFound;
1272 }
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001273 // If sampling rate or number of channels has changed, we need to make
1274 // a reset.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001275 if (decoder_info->fs_hz != fs_hz_ ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001276 decoder->Channels() != algorithm_buffer_->Channels()) {
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001277 // TODO(tlegrand): Add unittest to cover this event.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001278 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->Channels());
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001279 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001280 sync_buffer_->set_end_timestamp(timestamp_);
1281 playout_timestamp_ = timestamp_;
1282 }
1283 }
1284 }
1285
1286 if (reset_decoder_) {
1287 // TODO(hlundin): Write test for this.
Karl Wiberg43766482015-08-27 15:22:11 +02001288 if (decoder)
1289 decoder->Reset();
1290
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001291 // Reset comfort noise decoder.
1292 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02001293 if (cng_decoder)
1294 cng_decoder->Reset();
1295
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001296 reset_decoder_ = false;
1297 }
1298
1299#ifdef LEGACY_BITEXACT
1300 // Due to a bug in old SignalMCU, it could happen that CNG operation was
1301 // decided, but a speech packet was provided. The speech packet will be used
1302 // to update the comfort noise decoder, as if it was a SID frame, which is
1303 // clearly wrong.
1304 if (*operation == kRfc3389Cng) {
1305 return 0;
1306 }
1307#endif
1308
1309 *decoded_length = 0;
1310 // Update codec-internal PLC state.
1311 if ((*operation == kMerge) && decoder && decoder->HasDecodePlc()) {
1312 decoder->DecodePlc(1, &decoded_buffer_[*decoded_length]);
1313 }
1314
minyuel6d92bf52015-09-23 15:20:39 +02001315 int return_value;
1316 if (*operation == kCodecInternalCng) {
1317 RTC_DCHECK(packet_list->empty());
1318 return_value = DecodeCng(decoder, decoded_length, speech_type);
1319 } else {
1320 return_value = DecodeLoop(packet_list, *operation, decoder,
1321 decoded_length, speech_type);
1322 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001323
1324 if (*decoded_length < 0) {
1325 // Error returned from the decoder.
1326 *decoded_length = 0;
Peter Kastingb7e50542015-06-11 12:55:50 -07001327 sync_buffer_->IncreaseEndTimestamp(
1328 static_cast<uint32_t>(decoder_frame_length_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001329 int error_code = 0;
1330 if (decoder)
1331 error_code = decoder->ErrorCode();
1332 if (error_code != 0) {
1333 // Got some error code from the decoder.
1334 decoder_error_code_ = error_code;
1335 return_value = kDecoderErrorCode;
Henrik Lundind67a2192015-08-03 12:54:37 +02001336 LOG(LS_WARNING) << "Decoder returned error code: " << error_code;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001337 } else {
1338 // Decoder does not implement error codes. Return generic error.
1339 return_value = kOtherDecoderError;
Henrik Lundind67a2192015-08-03 12:54:37 +02001340 LOG(LS_WARNING) << "Decoder error (no error code)";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001341 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001342 *operation = kExpand; // Do expansion to get data instead.
1343 }
1344 if (*speech_type != AudioDecoder::kComfortNoise) {
1345 // Don't increment timestamp if codec returned CNG speech type
1346 // since in this case, the we will increment the CNGplayedTS counter.
1347 // Increase with number of samples per channel.
1348 assert(*decoded_length == 0 ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001349 (decoder && decoder->Channels() == sync_buffer_->Channels()));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001350 sync_buffer_->IncreaseEndTimestamp(
1351 *decoded_length / static_cast<int>(sync_buffer_->Channels()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001352 }
1353 return return_value;
1354}
1355
minyuel6d92bf52015-09-23 15:20:39 +02001356int NetEqImpl::DecodeCng(AudioDecoder* decoder, int* decoded_length,
1357 AudioDecoder::SpeechType* speech_type) {
1358 if (!decoder) {
1359 // This happens when active decoder is not defined.
1360 *decoded_length = -1;
1361 return 0;
1362 }
1363
1364 while (*decoded_length < rtc::checked_cast<int>(output_size_samples_)) {
1365 const int length = decoder->Decode(
1366 nullptr, 0, fs_hz_,
1367 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1368 &decoded_buffer_[*decoded_length], speech_type);
1369 if (length > 0) {
1370 *decoded_length += length;
minyuel6d92bf52015-09-23 15:20:39 +02001371 } else {
1372 // Error.
1373 LOG(LS_WARNING) << "Failed to decode CNG";
1374 *decoded_length = -1;
1375 break;
1376 }
1377 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1378 // Guard against overflow.
1379 LOG(LS_WARNING) << "Decoded too much CNG.";
1380 return kDecodedTooMuch;
1381 }
1382 }
1383 return 0;
1384}
1385
1386int NetEqImpl::DecodeLoop(PacketList* packet_list, const Operations& operation,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001387 AudioDecoder* decoder, int* decoded_length,
1388 AudioDecoder::SpeechType* speech_type) {
1389 Packet* packet = NULL;
1390 if (!packet_list->empty()) {
1391 packet = packet_list->front();
1392 }
minyuel6d92bf52015-09-23 15:20:39 +02001393
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001394 // Do decoding.
1395 while (packet &&
1396 !decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1397 assert(decoder); // At this point, we must have a decoder object.
1398 // The number of channels in the |sync_buffer_| should be the same as the
1399 // number decoder channels.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001400 assert(sync_buffer_->Channels() == decoder->Channels());
1401 assert(decoded_buffer_length_ >= kMaxFrameSize * decoder->Channels());
minyuel6d92bf52015-09-23 15:20:39 +02001402 assert(operation == kNormal || operation == kAccelerate ||
1403 operation == kFastAccelerate || operation == kMerge ||
1404 operation == kPreemptiveExpand);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001405 packet_list->pop_front();
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001406 size_t payload_length = packet->payload_length;
Peter Kasting36b7cc32015-06-11 19:57:18 -07001407 int decode_length;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +00001408 if (packet->sync_packet) {
1409 // Decode to silence with the same frame size as the last decode.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001410 memset(&decoded_buffer_[*decoded_length], 0,
1411 decoder_frame_length_ * decoder->Channels() *
1412 sizeof(decoded_buffer_[0]));
Peter Kastingdce40cf2015-08-24 14:52:23 -07001413 decode_length = rtc::checked_cast<int>(decoder_frame_length_);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +00001414 } else if (!packet->primary) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001415 // This is a redundant payload; call the special decoder method.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001416 decode_length = decoder->DecodeRedundant(
henrik.lundin@webrtc.org1eda4e32015-02-25 10:02:29 +00001417 packet->payload, packet->payload_length, fs_hz_,
minyue@webrtc.org7f7d7e32015-03-16 12:30:37 +00001418 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001419 &decoded_buffer_[*decoded_length], speech_type);
1420 } else {
henrik.lundin@webrtc.org1eda4e32015-02-25 10:02:29 +00001421 decode_length =
minyue@webrtc.org7f7d7e32015-03-16 12:30:37 +00001422 decoder->Decode(
1423 packet->payload, packet->payload_length, fs_hz_,
1424 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1425 &decoded_buffer_[*decoded_length], speech_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001426 }
1427
1428 delete[] packet->payload;
1429 delete packet;
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001430 packet = NULL;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001431 if (decode_length > 0) {
1432 *decoded_length += decode_length;
1433 // Update |decoder_frame_length_| with number of samples per channel.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001434 decoder_frame_length_ =
Peter Kastingdce40cf2015-08-24 14:52:23 -07001435 static_cast<size_t>(decode_length) / decoder->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001436 } else if (decode_length < 0) {
1437 // Error.
Henrik Lundind67a2192015-08-03 12:54:37 +02001438 LOG(LS_WARNING) << "Decode " << decode_length << " " << payload_length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001439 *decoded_length = -1;
1440 PacketBuffer::DeleteAllPackets(packet_list);
1441 break;
1442 }
1443 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1444 // Guard against overflow.
Henrik Lundind67a2192015-08-03 12:54:37 +02001445 LOG(LS_WARNING) << "Decoded too much.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001446 PacketBuffer::DeleteAllPackets(packet_list);
1447 return kDecodedTooMuch;
1448 }
1449 if (!packet_list->empty()) {
1450 packet = packet_list->front();
1451 } else {
1452 packet = NULL;
1453 }
1454 } // End of decode loop.
1455
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001456 // If the list is not empty at this point, either a decoding error terminated
1457 // the while-loop, or list must hold exactly one CNG packet.
1458 assert(packet_list->empty() || *decoded_length < 0 ||
1459 (packet_list->size() == 1 && packet &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001460 decoder_database_->IsComfortNoise(packet->header.payloadType)));
1461 return 0;
1462}
1463
1464void NetEqImpl::DoNormal(const int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001465 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001466 assert(normal_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001467 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001468 normal_->Process(decoded_buffer, decoded_length, last_mode_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001469 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001470 if (decoded_length != 0) {
1471 last_mode_ = kModeNormal;
1472 }
1473
1474 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1475 if ((speech_type == AudioDecoder::kComfortNoise)
1476 || ((last_mode_ == kModeCodecInternalCng)
1477 && (decoded_length == 0))) {
1478 // TODO(hlundin): Remove second part of || statement above.
1479 last_mode_ = kModeCodecInternalCng;
1480 }
1481
1482 if (!play_dtmf) {
1483 dtmf_tone_generator_->Reset();
1484 }
1485}
1486
1487void NetEqImpl::DoMerge(int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001488 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001489 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001490 assert(merge_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001491 size_t new_length = merge_->Process(decoded_buffer, decoded_length,
1492 mute_factor_array_.get(),
1493 algorithm_buffer_.get());
1494 size_t expand_length_correction = new_length -
1495 decoded_length / algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001496
1497 // Update in-call and post-call statistics.
1498 if (expand_->MuteFactor(0) == 0) {
1499 // Expand generates only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001500 stats_.ExpandedNoiseSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001501 } else {
1502 // Expansion generates more than only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001503 stats_.ExpandedVoiceSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001504 }
1505
1506 last_mode_ = kModeMerge;
1507 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1508 if (speech_type == AudioDecoder::kComfortNoise) {
1509 last_mode_ = kModeCodecInternalCng;
1510 }
1511 expand_->Reset();
1512 if (!play_dtmf) {
1513 dtmf_tone_generator_->Reset();
1514 }
1515}
1516
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001517int NetEqImpl::DoExpand(bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001518 while ((sync_buffer_->FutureLength() - expand_->overlap_length()) <
Peter Kastingdce40cf2015-08-24 14:52:23 -07001519 output_size_samples_) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001520 algorithm_buffer_->Clear();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001521 int return_value = expand_->Process(algorithm_buffer_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001522 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001523
1524 // Update in-call and post-call statistics.
1525 if (expand_->MuteFactor(0) == 0) {
1526 // Expand operation generates only noise.
1527 stats_.ExpandedNoiseSamples(length);
1528 } else {
1529 // Expand operation generates more than only noise.
1530 stats_.ExpandedVoiceSamples(length);
1531 }
1532
1533 last_mode_ = kModeExpand;
1534
1535 if (return_value < 0) {
1536 return return_value;
1537 }
1538
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001539 sync_buffer_->PushBack(*algorithm_buffer_);
1540 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001541 }
1542 if (!play_dtmf) {
1543 dtmf_tone_generator_->Reset();
1544 }
1545 return 0;
1546}
1547
Henrik Lundincf808d22015-05-27 14:33:29 +02001548int NetEqImpl::DoAccelerate(int16_t* decoded_buffer,
1549 size_t decoded_length,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001550 AudioDecoder::SpeechType speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +02001551 bool play_dtmf,
1552 bool fast_accelerate) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001553 const size_t required_samples =
1554 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001555 size_t borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001556 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001557 size_t decoded_length_per_channel = decoded_length / num_channels;
1558 if (decoded_length_per_channel < required_samples) {
1559 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001560 borrowed_samples_per_channel = static_cast<int>(required_samples -
1561 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001562 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1563 decoded_buffer,
1564 sizeof(int16_t) * decoded_length);
1565 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1566 decoded_buffer);
1567 decoded_length = required_samples * num_channels;
1568 }
1569
Peter Kastingdce40cf2015-08-24 14:52:23 -07001570 size_t samples_removed;
Henrik Lundincf808d22015-05-27 14:33:29 +02001571 Accelerate::ReturnCodes return_code =
1572 accelerate_->Process(decoded_buffer, decoded_length, fast_accelerate,
1573 algorithm_buffer_.get(), &samples_removed);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001574 stats_.AcceleratedSamples(samples_removed);
1575 switch (return_code) {
1576 case Accelerate::kSuccess:
1577 last_mode_ = kModeAccelerateSuccess;
1578 break;
1579 case Accelerate::kSuccessLowEnergy:
1580 last_mode_ = kModeAccelerateLowEnergy;
1581 break;
1582 case Accelerate::kNoStretch:
1583 last_mode_ = kModeAccelerateFail;
1584 break;
1585 case Accelerate::kError:
1586 // TODO(hlundin): Map to kModeError instead?
1587 last_mode_ = kModeAccelerateFail;
1588 return kAccelerateError;
1589 }
1590
1591 if (borrowed_samples_per_channel > 0) {
1592 // Copy borrowed samples back to the |sync_buffer_|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001593 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001594 if (length < borrowed_samples_per_channel) {
1595 // This destroys the beginning of the buffer, but will not cause any
1596 // problems.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001597 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001598 sync_buffer_->Size() -
1599 borrowed_samples_per_channel);
1600 sync_buffer_->PushFrontZeros(borrowed_samples_per_channel - length);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001601 algorithm_buffer_->PopFront(length);
1602 assert(algorithm_buffer_->Empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001603 } else {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001604 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001605 borrowed_samples_per_channel,
1606 sync_buffer_->Size() -
1607 borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001608 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001609 }
1610 }
1611
1612 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1613 if (speech_type == AudioDecoder::kComfortNoise) {
1614 last_mode_ = kModeCodecInternalCng;
1615 }
1616 if (!play_dtmf) {
1617 dtmf_tone_generator_->Reset();
1618 }
1619 expand_->Reset();
1620 return 0;
1621}
1622
1623int NetEqImpl::DoPreemptiveExpand(int16_t* decoded_buffer,
1624 size_t decoded_length,
1625 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001626 bool play_dtmf) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001627 const size_t required_samples =
1628 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001629 size_t num_channels = algorithm_buffer_->Channels();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001630 size_t borrowed_samples_per_channel = 0;
1631 size_t old_borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001632 size_t decoded_length_per_channel = decoded_length / num_channels;
1633 if (decoded_length_per_channel < required_samples) {
1634 // Must move data from the |sync_buffer_| in order to get 30 ms.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001635 borrowed_samples_per_channel =
1636 required_samples - decoded_length_per_channel;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001637 // Calculate how many of these were already played out.
Peter Kastingf045e4d2015-06-10 21:15:38 -07001638 old_borrowed_samples_per_channel =
Peter Kastingdce40cf2015-08-24 14:52:23 -07001639 (borrowed_samples_per_channel > sync_buffer_->FutureLength()) ?
1640 (borrowed_samples_per_channel - sync_buffer_->FutureLength()) : 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001641 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1642 decoded_buffer,
1643 sizeof(int16_t) * decoded_length);
1644 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1645 decoded_buffer);
1646 decoded_length = required_samples * num_channels;
1647 }
1648
Peter Kastingdce40cf2015-08-24 14:52:23 -07001649 size_t samples_added;
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001650 PreemptiveExpand::ReturnCodes return_code = preemptive_expand_->Process(
Peter Kastingdce40cf2015-08-24 14:52:23 -07001651 decoded_buffer, decoded_length,
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001652 old_borrowed_samples_per_channel,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001653 algorithm_buffer_.get(), &samples_added);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001654 stats_.PreemptiveExpandedSamples(samples_added);
1655 switch (return_code) {
1656 case PreemptiveExpand::kSuccess:
1657 last_mode_ = kModePreemptiveExpandSuccess;
1658 break;
1659 case PreemptiveExpand::kSuccessLowEnergy:
1660 last_mode_ = kModePreemptiveExpandLowEnergy;
1661 break;
1662 case PreemptiveExpand::kNoStretch:
1663 last_mode_ = kModePreemptiveExpandFail;
1664 break;
1665 case PreemptiveExpand::kError:
1666 // TODO(hlundin): Map to kModeError instead?
1667 last_mode_ = kModePreemptiveExpandFail;
1668 return kPreemptiveExpandError;
1669 }
1670
1671 if (borrowed_samples_per_channel > 0) {
1672 // Copy borrowed samples back to the |sync_buffer_|.
1673 sync_buffer_->ReplaceAtIndex(
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001674 *algorithm_buffer_, borrowed_samples_per_channel,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001675 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001676 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001677 }
1678
1679 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1680 if (speech_type == AudioDecoder::kComfortNoise) {
1681 last_mode_ = kModeCodecInternalCng;
1682 }
1683 if (!play_dtmf) {
1684 dtmf_tone_generator_->Reset();
1685 }
1686 expand_->Reset();
1687 return 0;
1688}
1689
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001690int NetEqImpl::DoRfc3389Cng(PacketList* packet_list, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001691 if (!packet_list->empty()) {
1692 // Must have exactly one SID frame at this point.
1693 assert(packet_list->size() == 1);
1694 Packet* packet = packet_list->front();
1695 packet_list->pop_front();
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001696 if (!decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1697#ifdef LEGACY_BITEXACT
1698 // This can happen due to a bug in GetDecision. Change the payload type
1699 // to a CNG type, and move on. Note that this means that we are in fact
1700 // sending a non-CNG payload to the comfort noise decoder for decoding.
1701 // Clearly wrong, but will maintain bit-exactness with legacy.
1702 if (fs_hz_ == 8000) {
1703 packet->header.payloadType =
kwibergee1879c2015-10-29 06:20:28 -07001704 decoder_database_->GetRtpPayloadType(NetEqDecoder::kDecoderCNGnb);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001705 } else if (fs_hz_ == 16000) {
1706 packet->header.payloadType =
kwibergee1879c2015-10-29 06:20:28 -07001707 decoder_database_->GetRtpPayloadType(NetEqDecoder::kDecoderCNGwb);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001708 } else if (fs_hz_ == 32000) {
kwibergee1879c2015-10-29 06:20:28 -07001709 packet->header.payloadType = decoder_database_->GetRtpPayloadType(
1710 NetEqDecoder::kDecoderCNGswb32kHz);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001711 } else if (fs_hz_ == 48000) {
kwibergee1879c2015-10-29 06:20:28 -07001712 packet->header.payloadType = decoder_database_->GetRtpPayloadType(
1713 NetEqDecoder::kDecoderCNGswb48kHz);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001714 }
1715 assert(decoder_database_->IsComfortNoise(packet->header.payloadType));
1716#else
1717 LOG(LS_ERROR) << "Trying to decode non-CNG payload as CNG.";
1718 return kOtherError;
1719#endif
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001720 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001721 // UpdateParameters() deletes |packet|.
1722 if (comfort_noise_->UpdateParameters(packet) ==
1723 ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001724 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001725 return -comfort_noise_->internal_error_code();
1726 }
1727 }
1728 int cn_return = comfort_noise_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001729 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001730 expand_->Reset();
1731 last_mode_ = kModeRfc3389Cng;
1732 if (!play_dtmf) {
1733 dtmf_tone_generator_->Reset();
1734 }
1735 if (cn_return == ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001736 decoder_error_code_ = comfort_noise_->internal_error_code();
1737 return kComfortNoiseErrorCode;
1738 } else if (cn_return == ComfortNoise::kUnknownPayloadType) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001739 return kUnknownRtpPayloadType;
1740 }
1741 return 0;
1742}
1743
minyuel6d92bf52015-09-23 15:20:39 +02001744void NetEqImpl::DoCodecInternalCng(const int16_t* decoded_buffer,
1745 size_t decoded_length) {
1746 RTC_DCHECK(normal_.get());
1747 RTC_DCHECK(mute_factor_array_.get());
1748 normal_->Process(decoded_buffer, decoded_length, last_mode_,
1749 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001750 last_mode_ = kModeCodecInternalCng;
1751 expand_->Reset();
1752}
1753
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001754int NetEqImpl::DoDtmf(const DtmfEvent& dtmf_event, bool* play_dtmf) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001755 // This block of the code and the block further down, handling |dtmf_switch|
1756 // are commented out. Otherwise playing out-of-band DTMF would fail in VoE
1757 // test, DtmfTest.ManualSuccessfullySendsOutOfBandTelephoneEvents. This is
1758 // equivalent to |dtmf_switch| always be false.
1759 //
1760 // See http://webrtc-codereview.appspot.com/1195004/ for discussion
1761 // On this issue. This change might cause some glitches at the point of
1762 // switch from audio to DTMF. Issue 1545 is filed to track this.
1763 //
1764 // bool dtmf_switch = false;
1765 // if ((last_mode_ != kModeDtmf) && dtmf_tone_generator_->initialized()) {
1766 // // Special case; see below.
1767 // // We must catch this before calling Generate, since |initialized| is
1768 // // modified in that call.
1769 // dtmf_switch = true;
1770 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001771
1772 int dtmf_return_value = 0;
1773 if (!dtmf_tone_generator_->initialized()) {
1774 // Initialize if not already done.
1775 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1776 dtmf_event.volume);
1777 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001778
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001779 if (dtmf_return_value == 0) {
1780 // Generate DTMF signal.
1781 dtmf_return_value = dtmf_tone_generator_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001782 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001783 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001784
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001785 if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001786 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001787 return dtmf_return_value;
1788 }
1789
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001790 // if (dtmf_switch) {
1791 // // This is the special case where the previous operation was DTMF
1792 // // overdub, but the current instruction is "regular" DTMF. We must make
1793 // // sure that the DTMF does not have any discontinuities. The first DTMF
1794 // // sample that we generate now must be played out immediately, therefore
1795 // // it must be copied to the speech buffer.
1796 // // TODO(hlundin): This code seems incorrect. (Legacy.) Write test and
1797 // // verify correct operation.
1798 // assert(false);
1799 // // Must generate enough data to replace all of the |sync_buffer_|
1800 // // "future".
1801 // int required_length = sync_buffer_->FutureLength();
1802 // assert(dtmf_tone_generator_->initialized());
1803 // dtmf_return_value = dtmf_tone_generator_->Generate(required_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001804 // algorithm_buffer_);
1805 // assert((size_t) required_length == algorithm_buffer_->Size());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001806 // if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001807 // algorithm_buffer_->Zeros(output_size_samples_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001808 // return dtmf_return_value;
1809 // }
1810 //
1811 // // Overwrite the "future" part of the speech buffer with the new DTMF
1812 // // data.
1813 // // TODO(hlundin): It seems that this overwriting has gone lost.
1814 // // Not adapted for multi-channel yet.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001815 // assert(algorithm_buffer_->Channels() == 1);
1816 // if (algorithm_buffer_->Channels() != 1) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001817 // LOG(LS_WARNING) << "DTMF not supported for more than one channel";
1818 // return kStereoNotSupported;
1819 // }
1820 // // Shuffle the remaining data to the beginning of algorithm buffer.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001821 // algorithm_buffer_->PopFront(sync_buffer_->FutureLength());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001822 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001823
Peter Kastingb7e50542015-06-11 12:55:50 -07001824 sync_buffer_->IncreaseEndTimestamp(
1825 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001826 expand_->Reset();
1827 last_mode_ = kModeDtmf;
1828
1829 // Set to false because the DTMF is already in the algorithm buffer.
1830 *play_dtmf = false;
1831 return 0;
1832}
1833
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001834void NetEqImpl::DoAlternativePlc(bool increase_timestamp) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001835 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001836 size_t length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001837 if (decoder && decoder->HasDecodePlc()) {
1838 // Use the decoder's packet-loss concealment.
1839 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1840 int16_t decoded_buffer[kMaxFrameSize];
1841 length = decoder->DecodePlc(1, decoded_buffer);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001842 if (length > 0)
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001843 algorithm_buffer_->PushBackInterleaved(decoded_buffer, length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001844 } else {
1845 // Do simple zero-stuffing.
1846 length = output_size_samples_;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001847 algorithm_buffer_->Zeros(length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001848 // By not advancing the timestamp, NetEq inserts samples.
1849 stats_.AddZeros(length);
1850 }
1851 if (increase_timestamp) {
Peter Kastingb7e50542015-06-11 12:55:50 -07001852 sync_buffer_->IncreaseEndTimestamp(static_cast<uint32_t>(length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001853 }
1854 expand_->Reset();
1855}
1856
1857int NetEqImpl::DtmfOverdub(const DtmfEvent& dtmf_event, size_t num_channels,
1858 int16_t* output) const {
1859 size_t out_index = 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001860 size_t overdub_length = output_size_samples_; // Default value.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001861
1862 if (sync_buffer_->dtmf_index() > sync_buffer_->next_index()) {
1863 // Special operation for transition from "DTMF only" to "DTMF overdub".
1864 out_index = std::min(
1865 sync_buffer_->dtmf_index() - sync_buffer_->next_index(),
Peter Kastingdce40cf2015-08-24 14:52:23 -07001866 output_size_samples_);
1867 overdub_length = output_size_samples_ - out_index;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001868 }
1869
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001870 AudioMultiVector dtmf_output(num_channels);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001871 int dtmf_return_value = 0;
1872 if (!dtmf_tone_generator_->initialized()) {
1873 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1874 dtmf_event.volume);
1875 }
1876 if (dtmf_return_value == 0) {
1877 dtmf_return_value = dtmf_tone_generator_->Generate(overdub_length,
1878 &dtmf_output);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001879 assert(overdub_length == dtmf_output.Size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001880 }
1881 dtmf_output.ReadInterleaved(overdub_length, &output[out_index]);
1882 return dtmf_return_value < 0 ? dtmf_return_value : 0;
1883}
1884
Peter Kastingdce40cf2015-08-24 14:52:23 -07001885int NetEqImpl::ExtractPackets(size_t required_samples,
1886 PacketList* packet_list) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001887 bool first_packet = true;
1888 uint8_t prev_payload_type = 0;
1889 uint32_t prev_timestamp = 0;
1890 uint16_t prev_sequence_number = 0;
1891 bool next_packet_available = false;
1892
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001893 const RTPHeader* header = packet_buffer_->NextRtpHeader();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001894 assert(header);
1895 if (!header) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001896 LOG(LS_ERROR) << "Packet buffer unexpectedly empty.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001897 return -1;
1898 }
turaj@webrtc.org7df97062013-08-02 18:07:13 +00001899 uint32_t first_timestamp = header->timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001900 int extracted_samples = 0;
1901
1902 // Packet extraction loop.
1903 do {
1904 timestamp_ = header->timestamp;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001905 size_t discard_count = 0;
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001906 Packet* packet = packet_buffer_->GetNextPacket(&discard_count);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001907 // |header| may be invalid after the |packet_buffer_| operation.
1908 header = NULL;
1909 if (!packet) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001910 LOG(LS_ERROR) << "Should always be able to extract a packet here";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001911 assert(false); // Should always be able to extract a packet here.
1912 return -1;
1913 }
1914 stats_.PacketsDiscarded(discard_count);
1915 // Store waiting time in ms; packets->waiting_time is in "output blocks".
1916 stats_.StoreWaitingTime(packet->waiting_time * kOutputSizeMs);
1917 assert(packet->payload_length > 0);
1918 packet_list->push_back(packet); // Store packet in list.
1919
1920 if (first_packet) {
1921 first_packet = false;
henrik.lundin48ed9302015-10-29 05:36:24 -07001922 if (nack_enabled_) {
1923 RTC_DCHECK(nack_);
1924 // TODO(henrik.lundin): Should we update this for all decoded packets?
1925 nack_->UpdateLastDecodedPacket(packet->header.sequenceNumber,
1926 packet->header.timestamp);
1927 }
1928 prev_sequence_number = packet->header.sequenceNumber;
1929 prev_timestamp = packet->header.timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001930 prev_payload_type = packet->header.payloadType;
1931 }
1932
1933 // Store number of extracted samples.
1934 int packet_duration = 0;
1935 AudioDecoder* decoder = decoder_database_->GetDecoder(
1936 packet->header.payloadType);
1937 if (decoder) {
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001938 if (packet->sync_packet) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001939 packet_duration = rtc::checked_cast<int>(decoder_frame_length_);
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001940 } else {
minyue@webrtc.org2c1bcf22015-02-17 10:17:09 +00001941 if (packet->primary) {
1942 packet_duration = decoder->PacketDuration(packet->payload,
1943 packet->payload_length);
1944 } else {
1945 packet_duration = decoder->
1946 PacketDurationRedundant(packet->payload, packet->payload_length);
1947 stats_.SecondaryDecodedSamples(packet_duration);
1948 }
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001949 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001950 } else {
Henrik Lundind67a2192015-08-03 12:54:37 +02001951 LOG(LS_WARNING) << "Unknown payload type "
1952 << static_cast<int>(packet->header.payloadType);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001953 assert(false);
1954 }
1955 if (packet_duration <= 0) {
1956 // Decoder did not return a packet duration. Assume that the packet
1957 // contains the same number of samples as the previous one.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001958 packet_duration = rtc::checked_cast<int>(decoder_frame_length_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001959 }
1960 extracted_samples = packet->header.timestamp - first_timestamp +
1961 packet_duration;
1962
1963 // Check what packet is available next.
1964 header = packet_buffer_->NextRtpHeader();
1965 next_packet_available = false;
1966 if (header && prev_payload_type == header->payloadType) {
1967 int16_t seq_no_diff = header->sequenceNumber - prev_sequence_number;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001968 size_t ts_diff = header->timestamp - prev_timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001969 if (seq_no_diff == 1 ||
1970 (seq_no_diff == 0 && ts_diff == decoder_frame_length_)) {
1971 // The next sequence number is available, or the next part of a packet
1972 // that was split into pieces upon insertion.
1973 next_packet_available = true;
1974 }
1975 prev_sequence_number = header->sequenceNumber;
1976 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07001977 } while (extracted_samples < rtc::checked_cast<int>(required_samples) &&
1978 next_packet_available);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001979
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00001980 if (extracted_samples > 0) {
1981 // Delete old packets only when we are going to decode something. Otherwise,
1982 // we could end up in the situation where we never decode anything, since
1983 // all incoming packets are considered too old but the buffer will also
1984 // never be flooded and flushed.
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001985 packet_buffer_->DiscardAllOldPackets(timestamp_);
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00001986 }
1987
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001988 return extracted_samples;
1989}
1990
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001991void NetEqImpl::UpdatePlcComponents(int fs_hz, size_t channels) {
1992 // Delete objects and create new ones.
1993 expand_.reset(expand_factory_->Create(background_noise_.get(),
1994 sync_buffer_.get(), &random_vector_,
Henrik Lundinbef77e22015-08-18 14:58:09 +02001995 &stats_, fs_hz, channels));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001996 merge_.reset(new Merge(fs_hz, channels, expand_.get(), sync_buffer_.get()));
1997}
1998
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001999void NetEqImpl::SetSampleRateAndChannels(int fs_hz, size_t channels) {
Henrik Lundind67a2192015-08-03 12:54:37 +02002000 LOG(LS_VERBOSE) << "SetSampleRateAndChannels " << fs_hz << " " << channels;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002001 // TODO(hlundin): Change to an enumerator and skip assert.
2002 assert(fs_hz == 8000 || fs_hz == 16000 || fs_hz == 32000 || fs_hz == 48000);
2003 assert(channels > 0);
2004
2005 fs_hz_ = fs_hz;
2006 fs_mult_ = fs_hz / 8000;
Peter Kastingdce40cf2015-08-24 14:52:23 -07002007 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002008 decoder_frame_length_ = 3 * output_size_samples_; // Initialize to 30ms.
2009
2010 last_mode_ = kModeNormal;
2011
2012 // Create a new array of mute factors and set all to 1.
2013 mute_factor_array_.reset(new int16_t[channels]);
2014 for (size_t i = 0; i < channels; ++i) {
2015 mute_factor_array_[i] = 16384; // 1.0 in Q14.
2016 }
2017
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002018 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02002019 if (cng_decoder)
2020 cng_decoder->Reset();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002021
2022 // Reinit post-decode VAD with new sample rate.
2023 assert(vad_.get()); // Cannot be NULL here.
2024 vad_->Init();
2025
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002026 // Delete algorithm buffer and create a new one.
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00002027 algorithm_buffer_.reset(new AudioMultiVector(channels));
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002028
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002029 // Delete sync buffer and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002030 sync_buffer_.reset(new SyncBuffer(channels, kSyncBufferSize * fs_mult_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002031
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00002032 // Delete BackgroundNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002033 background_noise_.reset(new BackgroundNoise(channels));
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00002034 background_noise_->set_mode(background_noise_mode_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002035
2036 // Reset random vector.
2037 random_vector_.Reset();
2038
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002039 UpdatePlcComponents(fs_hz, channels);
2040
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002041 // Move index so that we create a small set of future samples (all 0).
2042 sync_buffer_->set_next_index(sync_buffer_->next_index() -
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002043 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002044
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002045 normal_.reset(new Normal(fs_hz, decoder_database_.get(), *background_noise_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002046 expand_.get()));
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +00002047 accelerate_.reset(
2048 accelerate_factory_->Create(fs_hz, channels, *background_noise_));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002049 preemptive_expand_.reset(preemptive_expand_factory_->Create(
Peter Kastingdce40cf2015-08-24 14:52:23 -07002050 fs_hz, channels, *background_noise_, expand_->overlap_length()));
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002051
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002052 // Delete ComfortNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002053 comfort_noise_.reset(new ComfortNoise(fs_hz, decoder_database_.get(),
2054 sync_buffer_.get()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002055
2056 // Verify that |decoded_buffer_| is long enough.
2057 if (decoded_buffer_length_ < kMaxFrameSize * channels) {
2058 // Reallocate to larger size.
2059 decoded_buffer_length_ = kMaxFrameSize * channels;
2060 decoded_buffer_.reset(new int16_t[decoded_buffer_length_]);
2061 }
2062
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002063 // Create DecisionLogic if it is not created yet, then communicate new sample
2064 // rate and output size to DecisionLogic object.
2065 if (!decision_logic_.get()) {
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002066 CreateDecisionLogic();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002067 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002068 decision_logic_->SetSampleRate(fs_hz_, output_size_samples_);
2069}
2070
2071NetEqOutputType NetEqImpl::LastOutputType() {
2072 assert(vad_.get());
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002073 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002074 if (last_mode_ == kModeCodecInternalCng || last_mode_ == kModeRfc3389Cng) {
2075 return kOutputCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002076 } else if (last_mode_ == kModeExpand && expand_->MuteFactor(0) == 0) {
2077 // Expand mode has faded down to background noise only (very long expand).
2078 return kOutputPLCtoCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002079 } else if (last_mode_ == kModeExpand) {
2080 return kOutputPLC;
wu@webrtc.org24301a62013-12-13 19:17:43 +00002081 } else if (vad_->running() && !vad_->active_speech()) {
2082 return kOutputVADPassive;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002083 } else {
2084 return kOutputNormal;
2085 }
2086}
2087
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002088void NetEqImpl::CreateDecisionLogic() {
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002089 decision_logic_.reset(DecisionLogic::Create(fs_hz_, output_size_samples_,
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002090 playout_mode_,
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002091 decoder_database_.get(),
2092 *packet_buffer_.get(),
2093 delay_manager_.get(),
2094 buffer_level_filter_.get()));
2095}
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002096} // namespace webrtc