blob: 5fa2cbd5867afe317a15cb639dc9cf012f9d8785 [file] [log] [blame]
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001/*
2 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000011#include "webrtc/modules/audio_coding/neteq/neteq_impl.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000012
13#include <assert.h>
14#include <memory.h> // memset
15
16#include <algorithm>
17
henrik.lundin9c3efd02015-08-27 13:12:22 -070018#include "webrtc/base/checks.h"
Henrik Lundind67a2192015-08-03 12:54:37 +020019#include "webrtc/base/logging.h"
Peter Kastingdce40cf2015-08-24 14:52:23 -070020#include "webrtc/base/safe_conversions.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000021#include "webrtc/common_audio/signal_processing/include/signal_processing_library.h"
kwiberg@webrtc.orge04a93b2014-12-09 10:12:53 +000022#include "webrtc/modules/audio_coding/codecs/audio_decoder.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000023#include "webrtc/modules/audio_coding/neteq/accelerate.h"
24#include "webrtc/modules/audio_coding/neteq/background_noise.h"
25#include "webrtc/modules/audio_coding/neteq/buffer_level_filter.h"
26#include "webrtc/modules/audio_coding/neteq/comfort_noise.h"
27#include "webrtc/modules/audio_coding/neteq/decision_logic.h"
28#include "webrtc/modules/audio_coding/neteq/decoder_database.h"
29#include "webrtc/modules/audio_coding/neteq/defines.h"
30#include "webrtc/modules/audio_coding/neteq/delay_manager.h"
31#include "webrtc/modules/audio_coding/neteq/delay_peak_detector.h"
32#include "webrtc/modules/audio_coding/neteq/dtmf_buffer.h"
33#include "webrtc/modules/audio_coding/neteq/dtmf_tone_generator.h"
34#include "webrtc/modules/audio_coding/neteq/expand.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000035#include "webrtc/modules/audio_coding/neteq/merge.h"
henrik.lundin48ed9302015-10-29 05:36:24 -070036#include "webrtc/modules/audio_coding/neteq/nack.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000037#include "webrtc/modules/audio_coding/neteq/normal.h"
38#include "webrtc/modules/audio_coding/neteq/packet_buffer.h"
39#include "webrtc/modules/audio_coding/neteq/packet.h"
40#include "webrtc/modules/audio_coding/neteq/payload_splitter.h"
41#include "webrtc/modules/audio_coding/neteq/post_decode_vad.h"
42#include "webrtc/modules/audio_coding/neteq/preemptive_expand.h"
43#include "webrtc/modules/audio_coding/neteq/sync_buffer.h"
44#include "webrtc/modules/audio_coding/neteq/timestamp_scaler.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010045#include "webrtc/modules/include/module_common_types.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010046#include "webrtc/system_wrappers/include/critical_section_wrapper.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000047
48// Modify the code to obtain backwards bit-exactness. Once bit-exactness is no
49// longer required, this #define should be removed (and the code that it
50// enables).
51#define LEGACY_BITEXACT
52
53namespace webrtc {
54
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +000055NetEqImpl::NetEqImpl(const NetEq::Config& config,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000056 BufferLevelFilter* buffer_level_filter,
57 DecoderDatabase* decoder_database,
58 DelayManager* delay_manager,
59 DelayPeakDetector* delay_peak_detector,
60 DtmfBuffer* dtmf_buffer,
61 DtmfToneGenerator* dtmf_tone_generator,
62 PacketBuffer* packet_buffer,
63 PayloadSplitter* payload_splitter,
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +000064 TimestampScaler* timestamp_scaler,
65 AccelerateFactory* accelerate_factory,
66 ExpandFactory* expand_factory,
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +000067 PreemptiveExpandFactory* preemptive_expand_factory,
68 bool create_components)
henrik.lundin@webrtc.org2f816bb2014-06-05 10:37:13 +000069 : crit_sect_(CriticalSectionWrapper::CreateCriticalSection()),
70 buffer_level_filter_(buffer_level_filter),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000071 decoder_database_(decoder_database),
72 delay_manager_(delay_manager),
73 delay_peak_detector_(delay_peak_detector),
74 dtmf_buffer_(dtmf_buffer),
75 dtmf_tone_generator_(dtmf_tone_generator),
76 packet_buffer_(packet_buffer),
77 payload_splitter_(payload_splitter),
78 timestamp_scaler_(timestamp_scaler),
79 vad_(new PostDecodeVad()),
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +000080 expand_factory_(expand_factory),
81 accelerate_factory_(accelerate_factory),
82 preemptive_expand_factory_(preemptive_expand_factory),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000083 last_mode_(kModeNormal),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000084 decoded_buffer_length_(kMaxFrameSize),
85 decoded_buffer_(new int16_t[decoded_buffer_length_]),
86 playout_timestamp_(0),
87 new_codec_(false),
88 timestamp_(0),
89 reset_decoder_(false),
henrik.lundin48ed9302015-10-29 05:36:24 -070090 current_rtp_payload_type_(0xFF), // Invalid RTP payload type.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000091 current_cng_rtp_payload_type_(0xFF), // Invalid RTP payload type.
92 ssrc_(0),
93 first_packet_(true),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000094 error_code_(0),
95 decoder_error_code_(0),
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +000096 background_noise_mode_(config.background_noise_mode),
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +000097 playout_mode_(config.playout_mode),
Henrik Lundincf808d22015-05-27 14:33:29 +020098 enable_fast_accelerate_(config.enable_fast_accelerate),
henrik.lundin48ed9302015-10-29 05:36:24 -070099 nack_enabled_(false) {
Henrik Lundin905495c2015-05-25 16:58:41 +0200100 LOG(LS_INFO) << "NetEq config: " << config.ToString();
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +0000101 int fs = config.sample_rate_hz;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000102 if (fs != 8000 && fs != 16000 && fs != 32000 && fs != 48000) {
103 LOG(LS_ERROR) << "Sample rate " << fs << " Hz not supported. " <<
104 "Changing to 8000 Hz.";
105 fs = 8000;
106 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000107 fs_hz_ = fs;
108 fs_mult_ = fs / 8000;
Peter Kastingdce40cf2015-08-24 14:52:23 -0700109 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000110 decoder_frame_length_ = 3 * output_size_samples_;
111 WebRtcSpl_Init();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000112 if (create_components) {
113 SetSampleRateAndChannels(fs, 1); // Default is 1 channel.
114 }
henrik.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.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000126 CriticalSectionScoped lock(crit_sect_.get());
kwibergee2bac22015-11-11 10:34:00 -0800127 int error =
128 InsertPacketInternal(rtp_header, payload, receive_timestamp, false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000129 if (error != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000130 error_code_ = error;
131 return kFail;
132 }
133 return kOK;
134}
135
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000136int NetEqImpl::InsertSyncPacket(const WebRtcRTPHeader& rtp_header,
137 uint32_t receive_timestamp) {
138 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000139 const uint8_t kSyncPayload[] = { 's', 'y', 'n', 'c' };
kwibergee2bac22015-11-11 10:34:00 -0800140 int error =
141 InsertPacketInternal(rtp_header, kSyncPayload, receive_timestamp, true);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000142
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000143 if (error != 0) {
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000144 error_code_ = error;
145 return kFail;
146 }
147 return kOK;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000148}
149
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000150int NetEqImpl::GetAudio(size_t max_length, int16_t* output_audio,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700151 size_t* samples_per_channel, int* num_channels,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000152 NetEqOutputType* type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000153 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000154 int error = GetAudioInternal(max_length, output_audio, samples_per_channel,
155 num_channels);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000156 if (error != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000157 error_code_ = error;
158 return kFail;
159 }
160 if (type) {
161 *type = LastOutputType();
162 }
163 return kOK;
164}
165
kwibergee1879c2015-10-29 06:20:28 -0700166int NetEqImpl::RegisterPayloadType(NetEqDecoder codec,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000167 uint8_t rtp_payload_type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000168 CriticalSectionScoped lock(crit_sect_.get());
Henrik Lundind67a2192015-08-03 12:54:37 +0200169 LOG(LS_VERBOSE) << "RegisterPayloadType "
kwibergee1879c2015-10-29 06:20:28 -0700170 << static_cast<int>(rtp_payload_type) << " "
171 << static_cast<int>(codec);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000172 int ret = decoder_database_->RegisterPayload(rtp_payload_type, codec);
173 if (ret != DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000174 switch (ret) {
175 case DecoderDatabase::kInvalidRtpPayloadType:
176 error_code_ = kInvalidRtpPayloadType;
177 break;
178 case DecoderDatabase::kCodecNotSupported:
179 error_code_ = kCodecNotSupported;
180 break;
181 case DecoderDatabase::kDecoderExists:
182 error_code_ = kDecoderExists;
183 break;
184 default:
185 error_code_ = kOtherError;
186 }
187 return kFail;
188 }
189 return kOK;
190}
191
192int NetEqImpl::RegisterExternalDecoder(AudioDecoder* decoder,
kwibergee1879c2015-10-29 06:20:28 -0700193 NetEqDecoder codec,
Karl Wibergd8399e62015-05-25 14:39:56 +0200194 uint8_t rtp_payload_type,
195 int sample_rate_hz) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000196 CriticalSectionScoped lock(crit_sect_.get());
Henrik Lundind67a2192015-08-03 12:54:37 +0200197 LOG(LS_VERBOSE) << "RegisterExternalDecoder "
kwibergee1879c2015-10-29 06:20:28 -0700198 << static_cast<int>(rtp_payload_type) << " "
199 << static_cast<int>(codec);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000200 if (!decoder) {
201 LOG(LS_ERROR) << "Cannot register external decoder with NULL pointer";
202 assert(false);
203 return kFail;
204 }
205 int ret = decoder_database_->InsertExternal(rtp_payload_type, codec,
206 sample_rate_hz, decoder);
207 if (ret != DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000208 switch (ret) {
209 case DecoderDatabase::kInvalidRtpPayloadType:
210 error_code_ = kInvalidRtpPayloadType;
211 break;
212 case DecoderDatabase::kCodecNotSupported:
213 error_code_ = kCodecNotSupported;
214 break;
215 case DecoderDatabase::kDecoderExists:
216 error_code_ = kDecoderExists;
217 break;
218 case DecoderDatabase::kInvalidSampleRate:
219 error_code_ = kInvalidSampleRate;
220 break;
221 case DecoderDatabase::kInvalidPointer:
222 error_code_ = kInvalidPointer;
223 break;
224 default:
225 error_code_ = kOtherError;
226 }
227 return kFail;
228 }
229 return kOK;
230}
231
232int NetEqImpl::RemovePayloadType(uint8_t rtp_payload_type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000233 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000234 int ret = decoder_database_->Remove(rtp_payload_type);
235 if (ret == DecoderDatabase::kOK) {
236 return kOK;
237 } else if (ret == DecoderDatabase::kDecoderNotFound) {
238 error_code_ = kDecoderNotFound;
239 } else {
240 error_code_ = kOtherError;
241 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000242 return kFail;
243}
244
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000245bool NetEqImpl::SetMinimumDelay(int delay_ms) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000246 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000247 if (delay_ms >= 0 && delay_ms < 10000) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000248 assert(delay_manager_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000249 return delay_manager_->SetMinimumDelay(delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000250 }
251 return false;
252}
253
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000254bool NetEqImpl::SetMaximumDelay(int delay_ms) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000255 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000256 if (delay_ms >= 0 && delay_ms < 10000) {
257 assert(delay_manager_.get());
258 return delay_manager_->SetMaximumDelay(delay_ms);
259 }
260 return false;
261}
262
263int NetEqImpl::LeastRequiredDelayMs() const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000264 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000265 assert(delay_manager_.get());
266 return delay_manager_->least_required_delay_ms();
267}
268
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200269int NetEqImpl::SetTargetDelay() {
270 return kNotImplemented;
271}
272
273int NetEqImpl::TargetDelay() {
274 return kNotImplemented;
275}
276
henrik.lundin9c3efd02015-08-27 13:12:22 -0700277int NetEqImpl::CurrentDelayMs() const {
278 CriticalSectionScoped lock(crit_sect_.get());
279 if (fs_hz_ == 0)
280 return 0;
281 // Sum up the samples in the packet buffer with the future length of the sync
282 // buffer, and divide the sum by the sample rate.
283 const size_t delay_samples =
284 packet_buffer_->NumSamplesInBuffer(decoder_database_.get(),
285 decoder_frame_length_) +
286 sync_buffer_->FutureLength();
287 // The division below will truncate.
288 const int delay_ms =
289 static_cast<int>(delay_samples) / rtc::CheckedDivExact(fs_hz_, 1000);
290 return delay_ms;
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200291}
292
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000293// Deprecated.
294// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000295void NetEqImpl::SetPlayoutMode(NetEqPlayoutMode mode) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000296 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000297 if (mode != playout_mode_) {
298 playout_mode_ = mode;
299 CreateDecisionLogic();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000300 }
301}
302
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000303// Deprecated.
304// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000305NetEqPlayoutMode NetEqImpl::PlayoutMode() const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000306 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000307 return playout_mode_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000308}
309
310int NetEqImpl::NetworkStatistics(NetEqNetworkStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000311 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000312 assert(decoder_database_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700313 const size_t total_samples_in_buffers =
Peter Kasting728d9032015-06-11 14:31:38 -0700314 packet_buffer_->NumSamplesInBuffer(decoder_database_.get(),
315 decoder_frame_length_) +
Peter Kastingdce40cf2015-08-24 14:52:23 -0700316 sync_buffer_->FutureLength();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000317 assert(delay_manager_.get());
318 assert(decision_logic_.get());
319 stats_.GetNetworkStatistics(fs_hz_, total_samples_in_buffers,
320 decoder_frame_length_, *delay_manager_.get(),
321 *decision_logic_.get(), stats);
322 return 0;
323}
324
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000325void NetEqImpl::GetRtcpStatistics(RtcpStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000326 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000327 if (stats) {
328 rtcp_.GetStatistics(false, stats);
329 }
330}
331
332void NetEqImpl::GetRtcpStatisticsNoReset(RtcpStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000333 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000334 if (stats) {
335 rtcp_.GetStatistics(true, stats);
336 }
337}
338
339void NetEqImpl::EnableVad() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000340 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000341 assert(vad_.get());
342 vad_->Enable();
343}
344
345void NetEqImpl::DisableVad() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000346 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000347 assert(vad_.get());
348 vad_->Disable();
349}
350
wu@webrtc.org94454b72014-06-05 20:34:08 +0000351bool NetEqImpl::GetPlayoutTimestamp(uint32_t* timestamp) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000352 CriticalSectionScoped lock(crit_sect_.get());
wu@webrtc.org94454b72014-06-05 20:34:08 +0000353 if (first_packet_) {
354 // We don't have a valid RTP timestamp until we have decoded our first
355 // RTP packet.
356 return false;
357 }
358 *timestamp = timestamp_scaler_->ToExternal(playout_timestamp_);
359 return true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000360}
361
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200362int NetEqImpl::SetTargetNumberOfChannels() {
363 return kNotImplemented;
364}
365
366int NetEqImpl::SetTargetSampleRate() {
367 return kNotImplemented;
368}
369
henrik.lundin@webrtc.orgb0f4b3d2014-11-04 08:53:10 +0000370int NetEqImpl::LastError() const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000371 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000372 return error_code_;
373}
374
375int NetEqImpl::LastDecoderError() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000376 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000377 return decoder_error_code_;
378}
379
380void NetEqImpl::FlushBuffers() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000381 CriticalSectionScoped lock(crit_sect_.get());
Henrik Lundind67a2192015-08-03 12:54:37 +0200382 LOG(LS_VERBOSE) << "FlushBuffers";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000383 packet_buffer_->Flush();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000384 assert(sync_buffer_.get());
385 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000386 sync_buffer_->Flush();
387 sync_buffer_->set_next_index(sync_buffer_->next_index() -
388 expand_->overlap_length());
389 // Set to wait for new codec.
390 first_packet_ = true;
391}
392
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000393void NetEqImpl::PacketBufferStatistics(int* current_num_packets,
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000394 int* max_num_packets) const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000395 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000396 packet_buffer_->BufferStat(current_num_packets, max_num_packets);
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000397}
398
henrik.lundin48ed9302015-10-29 05:36:24 -0700399void NetEqImpl::EnableNack(size_t max_nack_list_size) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000400 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin48ed9302015-10-29 05:36:24 -0700401 if (!nack_enabled_) {
402 const int kNackThresholdPackets = 2;
403 nack_.reset(Nack::Create(kNackThresholdPackets));
404 nack_enabled_ = true;
405 nack_->UpdateSampleRate(fs_hz_);
406 }
407 nack_->SetMaxNackListSize(max_nack_list_size);
408}
409
410void NetEqImpl::DisableNack() {
411 CriticalSectionScoped lock(crit_sect_.get());
412 nack_.reset();
413 nack_enabled_ = false;
414}
415
416std::vector<uint16_t> NetEqImpl::GetNackList(int64_t round_trip_time_ms) const {
417 CriticalSectionScoped lock(crit_sect_.get());
418 if (!nack_enabled_) {
419 return std::vector<uint16_t>();
420 }
421 RTC_DCHECK(nack_.get());
422 return nack_->GetNackList(round_trip_time_ms);
minyue@webrtc.orgd7301772013-08-29 00:58:14 +0000423}
424
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000425const SyncBuffer* NetEqImpl::sync_buffer_for_test() const {
426 CriticalSectionScoped lock(crit_sect_.get());
427 return sync_buffer_.get();
428}
429
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000430// Methods below this line are private.
431
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000432int NetEqImpl::InsertPacketInternal(const WebRtcRTPHeader& rtp_header,
kwibergee2bac22015-11-11 10:34:00 -0800433 rtc::ArrayView<const uint8_t> payload,
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000434 uint32_t receive_timestamp,
435 bool is_sync_packet) {
kwibergee2bac22015-11-11 10:34:00 -0800436 if (payload.empty()) {
437 LOG_F(LS_ERROR) << "payload is empty";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000438 return kInvalidPointer;
439 }
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000440 // Sanity checks for sync-packets.
441 if (is_sync_packet) {
442 if (decoder_database_->IsDtmf(rtp_header.header.payloadType) ||
443 decoder_database_->IsRed(rtp_header.header.payloadType) ||
444 decoder_database_->IsComfortNoise(rtp_header.header.payloadType)) {
445 LOG_F(LS_ERROR) << "Sync-packet with an unacceptable payload type "
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000446 << static_cast<int>(rtp_header.header.payloadType);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000447 return kSyncPacketNotAccepted;
448 }
449 if (first_packet_ ||
450 rtp_header.header.payloadType != current_rtp_payload_type_ ||
451 rtp_header.header.ssrc != ssrc_) {
452 // Even if |current_rtp_payload_type_| is 0xFF, sync-packet isn't
453 // accepted.
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000454 LOG_F(LS_ERROR)
455 << "Changing codec, SSRC or first packet with sync-packet.";
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000456 return kSyncPacketNotAccepted;
457 }
458 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000459 PacketList packet_list;
460 RTPHeader main_header;
461 {
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000462 // Convert to Packet.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000463 // Create |packet| within this separate scope, since it should not be used
464 // directly once it's been inserted in the packet list. This way, |packet|
465 // is not defined outside of this block.
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000466 Packet* packet = new Packet;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000467 packet->header.markerBit = false;
468 packet->header.payloadType = rtp_header.header.payloadType;
469 packet->header.sequenceNumber = rtp_header.header.sequenceNumber;
470 packet->header.timestamp = rtp_header.header.timestamp;
471 packet->header.ssrc = rtp_header.header.ssrc;
472 packet->header.numCSRCs = 0;
kwibergee2bac22015-11-11 10:34:00 -0800473 packet->payload_length = payload.size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000474 packet->primary = true;
475 packet->waiting_time = 0;
476 packet->payload = new uint8_t[packet->payload_length];
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000477 packet->sync_packet = is_sync_packet;
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +0000478 if (!packet->payload) {
479 LOG_F(LS_ERROR) << "Payload pointer is NULL.";
480 }
kwibergee2bac22015-11-11 10:34:00 -0800481 assert(!payload.empty()); // Already checked above.
482 memcpy(packet->payload, payload.data(), packet->payload_length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000483 // Insert packet in a packet list.
484 packet_list.push_back(packet);
485 // Save main payloads header for later.
486 memcpy(&main_header, &packet->header, sizeof(main_header));
487 }
488
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000489 bool update_sample_rate_and_channels = false;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000490 // Reinitialize NetEq if it's needed (changed SSRC or first call).
491 if ((main_header.ssrc != ssrc_) || first_packet_) {
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000492 // Note: |first_packet_| will be cleared further down in this method, once
493 // the packet has been successfully inserted into the packet buffer.
494
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000495 rtcp_.Init(main_header.sequenceNumber);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000496
497 // Flush the packet buffer and DTMF buffer.
498 packet_buffer_->Flush();
499 dtmf_buffer_->Flush();
500
501 // Store new SSRC.
502 ssrc_ = main_header.ssrc;
503
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000504 // Update audio buffer timestamp.
505 sync_buffer_->IncreaseEndTimestamp(main_header.timestamp - timestamp_);
506
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000507 // Update codecs.
508 timestamp_ = main_header.timestamp;
509 current_rtp_payload_type_ = main_header.payloadType;
510
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000511 // Reset timestamp scaling.
512 timestamp_scaler_->Reset();
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000513
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000514 // Trigger an update of sampling rate and the number of channels.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000515 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000516 }
517
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000518 // Update RTCP statistics, only for regular packets.
519 if (!is_sync_packet)
520 rtcp_.Update(main_header, receive_timestamp);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000521
522 // Check for RED payload type, and separate payloads into several packets.
523 if (decoder_database_->IsRed(main_header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000524 assert(!is_sync_packet); // We had a sanity check for this.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000525 if (payload_splitter_->SplitRed(&packet_list) != PayloadSplitter::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000526 PacketBuffer::DeleteAllPackets(&packet_list);
527 return kRedundancySplitError;
528 }
529 // Only accept a few RED payloads of the same type as the main data,
530 // DTMF events and CNG.
531 payload_splitter_->CheckRedPayloads(&packet_list, *decoder_database_);
532 // Update the stored main payload header since the main payload has now
533 // changed.
534 memcpy(&main_header, &packet_list.front()->header, sizeof(main_header));
535 }
536
537 // Check payload types.
538 if (decoder_database_->CheckPayloadTypes(packet_list) ==
539 DecoderDatabase::kDecoderNotFound) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000540 PacketBuffer::DeleteAllPackets(&packet_list);
541 return kUnknownRtpPayloadType;
542 }
543
544 // Scale timestamp to internal domain (only for some codecs).
545 timestamp_scaler_->ToInternal(&packet_list);
546
547 // Process DTMF payloads. Cycle through the list of packets, and pick out any
548 // DTMF payloads found.
549 PacketList::iterator it = packet_list.begin();
550 while (it != packet_list.end()) {
551 Packet* current_packet = (*it);
552 assert(current_packet);
553 assert(current_packet->payload);
554 if (decoder_database_->IsDtmf(current_packet->header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000555 assert(!current_packet->sync_packet); // We had a sanity check for this.
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000556 DtmfEvent event;
557 int ret = DtmfBuffer::ParseEvent(
558 current_packet->header.timestamp,
559 current_packet->payload,
560 current_packet->payload_length,
561 &event);
562 if (ret != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000563 PacketBuffer::DeleteAllPackets(&packet_list);
564 return kDtmfParsingError;
565 }
566 if (dtmf_buffer_->InsertEvent(event) != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000567 PacketBuffer::DeleteAllPackets(&packet_list);
568 return kDtmfInsertError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000569 }
570 // TODO(hlundin): Let the destructor of Packet handle the payload.
571 delete [] current_packet->payload;
572 delete current_packet;
573 it = packet_list.erase(it);
574 } else {
575 ++it;
576 }
577 }
578
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000579 // Check for FEC in packets, and separate payloads into several packets.
580 int ret = payload_splitter_->SplitFec(&packet_list, decoder_database_.get());
581 if (ret != PayloadSplitter::kOK) {
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000582 PacketBuffer::DeleteAllPackets(&packet_list);
583 switch (ret) {
584 case PayloadSplitter::kUnknownPayloadType:
585 return kUnknownRtpPayloadType;
586 default:
587 return kOtherError;
588 }
589 }
590
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000591 // Split payloads into smaller chunks. This also verifies that all payloads
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000592 // are of a known payload type. SplitAudio() method is protected against
593 // sync-packets.
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +0000594 ret = payload_splitter_->SplitAudio(&packet_list, *decoder_database_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000595 if (ret != PayloadSplitter::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000596 PacketBuffer::DeleteAllPackets(&packet_list);
597 switch (ret) {
598 case PayloadSplitter::kUnknownPayloadType:
599 return kUnknownRtpPayloadType;
600 case PayloadSplitter::kFrameSplitError:
601 return kFrameSplitError;
602 default:
603 return kOtherError;
604 }
605 }
606
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000607 // Update bandwidth estimate, if the packet is not sync-packet.
608 if (!packet_list.empty() && !packet_list.front()->sync_packet) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000609 // The list can be empty here if we got nothing but DTMF payloads.
610 AudioDecoder* decoder =
611 decoder_database_->GetDecoder(main_header.payloadType);
612 assert(decoder); // Should always get a valid object, since we have
613 // already checked that the payload types are known.
614 decoder->IncomingPacket(packet_list.front()->payload,
615 packet_list.front()->payload_length,
616 packet_list.front()->header.sequenceNumber,
617 packet_list.front()->header.timestamp,
618 receive_timestamp);
619 }
620
henrik.lundin48ed9302015-10-29 05:36:24 -0700621 if (nack_enabled_) {
622 RTC_DCHECK(nack_);
623 if (update_sample_rate_and_channels) {
624 nack_->Reset();
625 }
626 nack_->UpdateLastReceivedPacket(packet_list.front()->header.sequenceNumber,
627 packet_list.front()->header.timestamp);
628 }
629
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000630 // Insert packets in buffer.
henrik.lundin116c84e2015-08-27 13:14:48 -0700631 const size_t buffer_length_before_insert =
632 packet_buffer_->NumPacketsInBuffer();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000633 ret = packet_buffer_->InsertPacketList(
634 &packet_list,
635 *decoder_database_,
636 &current_rtp_payload_type_,
637 &current_cng_rtp_payload_type_);
638 if (ret == PacketBuffer::kFlushed) {
639 // Reset DSP timestamp etc. if packet buffer flushed.
640 new_codec_ = true;
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000641 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000642 } else if (ret != PacketBuffer::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000643 PacketBuffer::DeleteAllPackets(&packet_list);
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000644 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000645 }
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000646
647 if (first_packet_) {
648 first_packet_ = false;
649 // Update the codec on the next GetAudio call.
650 new_codec_ = true;
651 }
652
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000653 if (current_rtp_payload_type_ != 0xFF) {
654 const DecoderDatabase::DecoderInfo* dec_info =
655 decoder_database_->GetDecoderInfo(current_rtp_payload_type_);
656 if (!dec_info) {
657 assert(false); // Already checked that the payload type is known.
658 }
659 }
660
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000661 if (update_sample_rate_and_channels && !packet_buffer_->Empty()) {
662 // We do not use |current_rtp_payload_type_| to |set payload_type|, but
663 // get the next RTP header from |packet_buffer_| to obtain the payload type.
664 // The reason for it is the following corner case. If NetEq receives a
665 // CNG packet with a sample rate different than the current CNG then it
666 // flushes its buffer, assuming send codec must have been changed. However,
667 // payload type of the hypothetically new send codec is not known.
668 const RTPHeader* rtp_header = packet_buffer_->NextRtpHeader();
669 assert(rtp_header);
670 int payload_type = rtp_header->payloadType;
671 AudioDecoder* decoder = decoder_database_->GetDecoder(payload_type);
672 assert(decoder); // Payloads are already checked to be valid.
673 const DecoderDatabase::DecoderInfo* decoder_info =
674 decoder_database_->GetDecoderInfo(payload_type);
675 assert(decoder_info);
676 if (decoder_info->fs_hz != fs_hz_ ||
henrik.lundin48ed9302015-10-29 05:36:24 -0700677 decoder->Channels() != algorithm_buffer_->Channels()) {
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +0000678 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->Channels());
henrik.lundin48ed9302015-10-29 05:36:24 -0700679 }
680 if (nack_enabled_) {
681 RTC_DCHECK(nack_);
682 // Update the sample rate even if the rate is not new, because of Reset().
683 nack_->UpdateSampleRate(fs_hz_);
684 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000685 }
686
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000687 // TODO(hlundin): Move this code to DelayManager class.
688 const DecoderDatabase::DecoderInfo* dec_info =
689 decoder_database_->GetDecoderInfo(main_header.payloadType);
690 assert(dec_info); // Already checked that the payload type is known.
691 delay_manager_->LastDecoderType(dec_info->codec_type);
692 if (delay_manager_->last_pack_cng_or_dtmf() == 0) {
693 // Calculate the total speech length carried in each packet.
henrik.lundin116c84e2015-08-27 13:14:48 -0700694 const size_t buffer_length_after_insert =
695 packet_buffer_->NumPacketsInBuffer();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000696
henrik.lundin116c84e2015-08-27 13:14:48 -0700697 if (buffer_length_after_insert > buffer_length_before_insert) {
698 const size_t packet_length_samples =
699 (buffer_length_after_insert - buffer_length_before_insert) *
700 decoder_frame_length_;
701 if (packet_length_samples != decision_logic_->packet_length_samples()) {
702 decision_logic_->set_packet_length_samples(packet_length_samples);
703 delay_manager_->SetPacketAudioLength(
704 rtc::checked_cast<int>((1000 * packet_length_samples) / fs_hz_));
705 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000706 }
707
708 // Update statistics.
pbos@webrtc.org0946a562013-04-09 00:28:06 +0000709 if ((int32_t) (main_header.timestamp - timestamp_) >= 0 &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000710 !new_codec_) {
711 // Only update statistics if incoming packet is not older than last played
712 // out packet, and if new codec flag is not set.
713 delay_manager_->Update(main_header.sequenceNumber, main_header.timestamp,
714 fs_hz_);
715 }
716 } else if (delay_manager_->last_pack_cng_or_dtmf() == -1) {
717 // This is first "normal" packet after CNG or DTMF.
718 // Reset packet time counter and measure time until next packet,
719 // but don't update statistics.
720 delay_manager_->set_last_pack_cng_or_dtmf(0);
721 delay_manager_->ResetPacketIatCount();
722 }
723 return 0;
724}
725
Peter Kasting728d9032015-06-11 14:31:38 -0700726int NetEqImpl::GetAudioInternal(size_t max_length,
727 int16_t* output,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700728 size_t* samples_per_channel,
Peter Kasting728d9032015-06-11 14:31:38 -0700729 int* num_channels) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000730 PacketList packet_list;
731 DtmfEvent dtmf_event;
732 Operations operation;
733 bool play_dtmf;
734 int return_value = GetDecision(&operation, &packet_list, &dtmf_event,
735 &play_dtmf);
736 if (return_value != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000737 last_mode_ = kModeError;
738 return return_value;
739 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000740
741 AudioDecoder::SpeechType speech_type;
742 int length = 0;
743 int decode_return_value = Decode(&packet_list, &operation,
744 &length, &speech_type);
745
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000746 assert(vad_.get());
747 bool sid_frame_available =
748 (operation == kRfc3389Cng && !packet_list.empty());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700749 vad_->Update(decoded_buffer_.get(), static_cast<size_t>(length), speech_type,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000750 sid_frame_available, fs_hz_);
751
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000752 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000753 switch (operation) {
754 case kNormal: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000755 DoNormal(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000756 break;
757 }
758 case kMerge: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000759 DoMerge(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000760 break;
761 }
762 case kExpand: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000763 return_value = DoExpand(play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000764 break;
765 }
Henrik Lundincf808d22015-05-27 14:33:29 +0200766 case kAccelerate:
767 case kFastAccelerate: {
768 const bool fast_accelerate =
769 enable_fast_accelerate_ && (operation == kFastAccelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000770 return_value = DoAccelerate(decoded_buffer_.get(), length, speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +0200771 play_dtmf, fast_accelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000772 break;
773 }
774 case kPreemptiveExpand: {
775 return_value = DoPreemptiveExpand(decoded_buffer_.get(), length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000776 speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000777 break;
778 }
779 case kRfc3389Cng:
780 case kRfc3389CngNoPacket: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000781 return_value = DoRfc3389Cng(&packet_list, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000782 break;
783 }
784 case kCodecInternalCng: {
785 // This handles the case when there is no transmission and the decoder
786 // should produce internal comfort noise.
787 // TODO(hlundin): Write test for codec-internal CNG.
minyuel6d92bf52015-09-23 15:20:39 +0200788 DoCodecInternalCng(decoded_buffer_.get(), length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000789 break;
790 }
791 case kDtmf: {
792 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000793 return_value = DoDtmf(dtmf_event, &play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000794 break;
795 }
796 case kAlternativePlc: {
797 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000798 DoAlternativePlc(false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000799 break;
800 }
801 case kAlternativePlcIncreaseTimestamp: {
802 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000803 DoAlternativePlc(true);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000804 break;
805 }
806 case kAudioRepetitionIncreaseTimestamp: {
807 // TODO(hlundin): Write test for this.
Peter Kastingb7e50542015-06-11 12:55:50 -0700808 sync_buffer_->IncreaseEndTimestamp(
809 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000810 // Skipping break on purpose. Execution should move on into the
811 // next case.
kjellander@webrtc.org7d2b6a92015-01-28 18:37:58 +0000812 FALLTHROUGH();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000813 }
814 case kAudioRepetition: {
815 // TODO(hlundin): Write test for this.
816 // Copy last |output_size_samples_| from |sync_buffer_| to
817 // |algorithm_buffer|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000818 algorithm_buffer_->PushBackFromIndex(
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000819 *sync_buffer_, sync_buffer_->Size() - output_size_samples_);
820 expand_->Reset();
821 break;
822 }
823 case kUndefined: {
Henrik Lundind67a2192015-08-03 12:54:37 +0200824 LOG(LS_ERROR) << "Invalid operation kUndefined.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000825 assert(false); // This should not happen.
826 last_mode_ = kModeError;
827 return kInvalidOperation;
828 }
829 } // End of switch.
830 if (return_value < 0) {
831 return return_value;
832 }
833
834 if (last_mode_ != kModeRfc3389Cng) {
835 comfort_noise_->Reset();
836 }
837
838 // Copy from |algorithm_buffer| to |sync_buffer_|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000839 sync_buffer_->PushBack(*algorithm_buffer_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000840
841 // Extract data from |sync_buffer_| to |output|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000842 size_t num_output_samples_per_channel = output_size_samples_;
843 size_t num_output_samples = output_size_samples_ * sync_buffer_->Channels();
844 if (num_output_samples > max_length) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000845 LOG(LS_WARNING) << "Output array is too short. " << max_length << " < " <<
846 output_size_samples_ << " * " << sync_buffer_->Channels();
847 num_output_samples = max_length;
Peter Kastingdce40cf2015-08-24 14:52:23 -0700848 num_output_samples_per_channel = max_length / sync_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000849 }
Peter Kastingdce40cf2015-08-24 14:52:23 -0700850 const size_t samples_from_sync =
851 sync_buffer_->GetNextAudioInterleaved(num_output_samples_per_channel,
852 output);
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000853 *num_channels = static_cast<int>(sync_buffer_->Channels());
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200854 if (sync_buffer_->FutureLength() < expand_->overlap_length()) {
855 // The sync buffer should always contain |overlap_length| samples, but now
856 // too many samples have been extracted. Reinstall the |overlap_length|
857 // lookahead by moving the index.
858 const size_t missing_lookahead_samples =
859 expand_->overlap_length() - sync_buffer_->FutureLength();
henrikg91d6ede2015-09-17 00:24:34 -0700860 RTC_DCHECK_GE(sync_buffer_->next_index(), missing_lookahead_samples);
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200861 sync_buffer_->set_next_index(sync_buffer_->next_index() -
862 missing_lookahead_samples);
863 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000864 if (samples_from_sync != output_size_samples_) {
Henrik Lundind67a2192015-08-03 12:54:37 +0200865 LOG(LS_ERROR) << "samples_from_sync (" << samples_from_sync
866 << ") != output_size_samples_ (" << output_size_samples_
867 << ")";
minyue@webrtc.orgdb1cefc2013-08-13 01:39:21 +0000868 // TODO(minyue): treatment of under-run, filling zeros
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000869 memset(output, 0, num_output_samples * sizeof(int16_t));
870 *samples_per_channel = output_size_samples_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000871 return kSampleUnderrun;
872 }
873 *samples_per_channel = output_size_samples_;
874
875 // Should always have overlap samples left in the |sync_buffer_|.
henrikg91d6ede2015-09-17 00:24:34 -0700876 RTC_DCHECK_GE(sync_buffer_->FutureLength(), expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000877
878 if (play_dtmf) {
879 return_value = DtmfOverdub(dtmf_event, sync_buffer_->Channels(), output);
880 }
881
882 // Update the background noise parameters if last operation wrote data
883 // straight from the decoder to the |sync_buffer_|. That is, none of the
884 // operations that modify the signal can be followed by a parameter update.
885 if ((last_mode_ == kModeNormal) ||
886 (last_mode_ == kModeAccelerateFail) ||
887 (last_mode_ == kModePreemptiveExpandFail) ||
888 (last_mode_ == kModeRfc3389Cng) ||
889 (last_mode_ == kModeCodecInternalCng)) {
890 background_noise_->Update(*sync_buffer_, *vad_.get());
891 }
892
893 if (operation == kDtmf) {
894 // DTMF data was written the end of |sync_buffer_|.
895 // Update index to end of DTMF data in |sync_buffer_|.
896 sync_buffer_->set_dtmf_index(sync_buffer_->Size());
897 }
898
henrik.lundin@webrtc.orged865b52014-03-06 10:28:07 +0000899 if (last_mode_ != kModeExpand) {
900 // If last operation was not expand, calculate the |playout_timestamp_| from
901 // the |sync_buffer_|. However, do not update the |playout_timestamp_| if it
902 // would be moved "backwards".
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000903 uint32_t temp_timestamp = sync_buffer_->end_timestamp() -
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000904 static_cast<uint32_t>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000905 if (static_cast<int32_t>(temp_timestamp - playout_timestamp_) > 0) {
906 playout_timestamp_ = temp_timestamp;
907 }
908 } else {
909 // Use dead reckoning to estimate the |playout_timestamp_|.
Peter Kastingb7e50542015-06-11 12:55:50 -0700910 playout_timestamp_ += static_cast<uint32_t>(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000911 }
912
913 if (decode_return_value) return decode_return_value;
914 return return_value;
915}
916
917int NetEqImpl::GetDecision(Operations* operation,
918 PacketList* packet_list,
919 DtmfEvent* dtmf_event,
920 bool* play_dtmf) {
921 // Initialize output variables.
922 *play_dtmf = false;
923 *operation = kUndefined;
924
925 // Increment time counters.
926 packet_buffer_->IncrementWaitingTimes();
927 stats_.IncreaseCounter(output_size_samples_, fs_hz_);
928
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000929 assert(sync_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000930 uint32_t end_timestamp = sync_buffer_->end_timestamp();
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +0000931 if (!new_codec_) {
932 const uint32_t five_seconds_samples = 5 * fs_hz_;
933 packet_buffer_->DiscardOldPackets(end_timestamp, five_seconds_samples);
934 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000935 const RTPHeader* header = packet_buffer_->NextRtpHeader();
936
henrik.lundin@webrtc.orgca8cb952014-03-12 10:26:52 +0000937 if (decision_logic_->CngRfc3389On() || last_mode_ == kModeRfc3389Cng) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000938 // Because of timestamp peculiarities, we have to "manually" disallow using
939 // a CNG packet with the same timestamp as the one that was last played.
940 // This can happen when using redundancy and will cause the timing to shift.
henrik.lundin@webrtc.org24779fe2014-03-14 12:40:05 +0000941 while (header && decoder_database_->IsComfortNoise(header->payloadType) &&
942 (end_timestamp >= header->timestamp ||
943 end_timestamp + decision_logic_->generated_noise_samples() >
944 header->timestamp)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000945 // Don't use this packet, discard it.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000946 if (packet_buffer_->DiscardNextPacket() != PacketBuffer::kOK) {
947 assert(false); // Must be ok by design.
948 }
949 // Check buffer again.
950 if (!new_codec_) {
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +0000951 packet_buffer_->DiscardOldPackets(end_timestamp, 5 * fs_hz_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000952 }
953 header = packet_buffer_->NextRtpHeader();
954 }
955 }
956
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000957 assert(expand_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000958 const int samples_left = static_cast<int>(sync_buffer_->FutureLength() -
959 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000960 if (last_mode_ == kModeAccelerateSuccess ||
961 last_mode_ == kModeAccelerateLowEnergy ||
962 last_mode_ == kModePreemptiveExpandSuccess ||
963 last_mode_ == kModePreemptiveExpandLowEnergy) {
964 // Subtract (samples_left + output_size_samples_) from sampleMemory.
Peter Kastingdce40cf2015-08-24 14:52:23 -0700965 decision_logic_->AddSampleMemory(
966 -(samples_left + rtc::checked_cast<int>(output_size_samples_)));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000967 }
968
969 // Check if it is time to play a DTMF event.
Peter Kastingb7e50542015-06-11 12:55:50 -0700970 if (dtmf_buffer_->GetEvent(
971 static_cast<uint32_t>(
972 end_timestamp + decision_logic_->generated_noise_samples()),
973 dtmf_event)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000974 *play_dtmf = true;
975 }
976
977 // Get instruction.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000978 assert(sync_buffer_.get());
979 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000980 *operation = decision_logic_->GetDecision(*sync_buffer_,
981 *expand_,
982 decoder_frame_length_,
983 header,
984 last_mode_,
985 *play_dtmf,
986 &reset_decoder_);
987
988 // Check if we already have enough samples in the |sync_buffer_|. If so,
989 // change decision to normal, unless the decision was merge, accelerate, or
990 // preemptive expand.
Peter Kastingdce40cf2015-08-24 14:52:23 -0700991 if (samples_left >= rtc::checked_cast<int>(output_size_samples_) &&
992 *operation != kMerge &&
993 *operation != kAccelerate &&
994 *operation != kFastAccelerate &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000995 *operation != kPreemptiveExpand) {
996 *operation = kNormal;
997 return 0;
998 }
999
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001000 decision_logic_->ExpandDecision(*operation);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001001
1002 // Check conditions for reset.
1003 if (new_codec_ || *operation == kUndefined) {
1004 // The only valid reason to get kUndefined is that new_codec_ is set.
1005 assert(new_codec_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001006 if (*play_dtmf && !header) {
1007 timestamp_ = dtmf_event->timestamp;
1008 } else {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001009 if (!header) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001010 LOG(LS_ERROR) << "Packet missing where it shouldn't.";
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001011 return -1;
1012 }
1013 timestamp_ = header->timestamp;
1014 if (*operation == kRfc3389CngNoPacket
1015#ifndef LEGACY_BITEXACT
1016 // Without this check, it can happen that a non-CNG packet is sent to
1017 // the CNG decoder as if it was a SID frame. This is clearly a bug,
1018 // but is kept for now to maintain bit-exactness with the test
1019 // vectors.
1020 && decoder_database_->IsComfortNoise(header->payloadType)
1021#endif
1022 ) {
1023 // Change decision to CNG packet, since we do have a CNG packet, but it
1024 // was considered too early to use. Now, use it anyway.
1025 *operation = kRfc3389Cng;
1026 } else if (*operation != kRfc3389Cng) {
1027 *operation = kNormal;
1028 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001029 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001030 // Adjust |sync_buffer_| timestamp before setting |end_timestamp| to the
1031 // new value.
1032 sync_buffer_->IncreaseEndTimestamp(timestamp_ - end_timestamp);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001033 end_timestamp = timestamp_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001034 new_codec_ = false;
1035 decision_logic_->SoftReset();
1036 buffer_level_filter_->Reset();
1037 delay_manager_->Reset();
1038 stats_.ResetMcu();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001039 }
1040
Peter Kastingdce40cf2015-08-24 14:52:23 -07001041 size_t required_samples = output_size_samples_;
1042 const size_t samples_10_ms = static_cast<size_t>(80 * fs_mult_);
1043 const size_t samples_20_ms = 2 * samples_10_ms;
1044 const size_t samples_30_ms = 3 * samples_10_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001045
1046 switch (*operation) {
1047 case kExpand: {
1048 timestamp_ = end_timestamp;
1049 return 0;
1050 }
1051 case kRfc3389CngNoPacket:
1052 case kCodecInternalCng: {
1053 return 0;
1054 }
1055 case kDtmf: {
1056 // TODO(hlundin): Write test for this.
1057 // Update timestamp.
1058 timestamp_ = end_timestamp;
1059 if (decision_logic_->generated_noise_samples() > 0 &&
1060 last_mode_ != kModeDtmf) {
1061 // Make a jump in timestamp due to the recently played comfort noise.
Peter Kastingb7e50542015-06-11 12:55:50 -07001062 uint32_t timestamp_jump =
1063 static_cast<uint32_t>(decision_logic_->generated_noise_samples());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001064 sync_buffer_->IncreaseEndTimestamp(timestamp_jump);
1065 timestamp_ += timestamp_jump;
1066 }
1067 decision_logic_->set_generated_noise_samples(0);
1068 return 0;
1069 }
Henrik Lundincf808d22015-05-27 14:33:29 +02001070 case kAccelerate:
1071 case kFastAccelerate: {
1072 // In order to do an accelerate we need at least 30 ms of audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001073 if (samples_left >= static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001074 // Already have enough data, so we do not need to extract any more.
1075 decision_logic_->set_sample_memory(samples_left);
1076 decision_logic_->set_prev_time_scale(true);
1077 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001078 } else if (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001079 decoder_frame_length_ >= samples_30_ms) {
1080 // Avoid decoding more data as it might overflow the playout buffer.
1081 *operation = kNormal;
1082 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001083 } else if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001084 decoder_frame_length_ < samples_30_ms) {
1085 // Build up decoded data by decoding at least 20 ms of audio data. Do
1086 // not perform accelerate yet, but wait until we only need to do one
1087 // decoding.
1088 required_samples = 2 * output_size_samples_;
1089 *operation = kNormal;
1090 }
1091 // If none of the above is true, we have one of two possible situations:
1092 // (1) 20 ms <= samples_left < 30 ms and decoder_frame_length_ < 30 ms; or
1093 // (2) samples_left < 10 ms and decoder_frame_length_ >= 30 ms.
1094 // In either case, we move on with the accelerate decision, and decode one
1095 // frame now.
1096 break;
1097 }
1098 case kPreemptiveExpand: {
1099 // In order to do a preemptive expand we need at least 30 ms of decoded
1100 // audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001101 if ((samples_left >= static_cast<int>(samples_30_ms)) ||
1102 (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001103 decoder_frame_length_ >= samples_30_ms)) {
1104 // Already have enough data, so we do not need to extract any more.
1105 // Or, avoid decoding more data as it might overflow the playout buffer.
1106 // Still try preemptive expand, though.
1107 decision_logic_->set_sample_memory(samples_left);
1108 decision_logic_->set_prev_time_scale(true);
1109 return 0;
1110 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07001111 if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001112 decoder_frame_length_ < samples_30_ms) {
1113 // Build up decoded data by decoding at least 20 ms of audio data.
1114 // Still try to perform preemptive expand.
1115 required_samples = 2 * output_size_samples_;
1116 }
1117 // Move on with the preemptive expand decision.
1118 break;
1119 }
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001120 case kMerge: {
1121 required_samples =
1122 std::max(merge_->RequiredFutureSamples(), required_samples);
1123 break;
1124 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001125 default: {
1126 // Do nothing.
1127 }
1128 }
1129
1130 // Get packets from buffer.
1131 int extracted_samples = 0;
1132 if (header &&
1133 *operation != kAlternativePlc &&
1134 *operation != kAlternativePlcIncreaseTimestamp &&
1135 *operation != kAudioRepetition &&
1136 *operation != kAudioRepetitionIncreaseTimestamp) {
1137 sync_buffer_->IncreaseEndTimestamp(header->timestamp - end_timestamp);
1138 if (decision_logic_->CngOff()) {
1139 // Adjustment of timestamp only corresponds to an actual packet loss
1140 // if comfort noise is not played. If comfort noise was just played,
1141 // this adjustment of timestamp is only done to get back in sync with the
1142 // stream timestamp; no loss to report.
1143 stats_.LostSamples(header->timestamp - end_timestamp);
1144 }
1145
1146 if (*operation != kRfc3389Cng) {
1147 // We are about to decode and use a non-CNG packet.
1148 decision_logic_->SetCngOff();
1149 }
1150 // Reset CNG timestamp as a new packet will be delivered.
1151 // (Also if this is a CNG packet, since playedOutTS is updated.)
1152 decision_logic_->set_generated_noise_samples(0);
1153
1154 extracted_samples = ExtractPackets(required_samples, packet_list);
1155 if (extracted_samples < 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001156 return kPacketBufferCorruption;
1157 }
1158 }
1159
Henrik Lundincf808d22015-05-27 14:33:29 +02001160 if (*operation == kAccelerate || *operation == kFastAccelerate ||
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001161 *operation == kPreemptiveExpand) {
1162 decision_logic_->set_sample_memory(samples_left + extracted_samples);
1163 decision_logic_->set_prev_time_scale(true);
1164 }
1165
Henrik Lundincf808d22015-05-27 14:33:29 +02001166 if (*operation == kAccelerate || *operation == kFastAccelerate) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001167 // Check that we have enough data (30ms) to do accelerate.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001168 if (extracted_samples + samples_left < static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001169 // TODO(hlundin): Write test for this.
1170 // Not enough, do normal operation instead.
1171 *operation = kNormal;
1172 }
1173 }
1174
1175 timestamp_ = end_timestamp;
1176 return 0;
1177}
1178
1179int NetEqImpl::Decode(PacketList* packet_list, Operations* operation,
1180 int* decoded_length,
1181 AudioDecoder::SpeechType* speech_type) {
1182 *speech_type = AudioDecoder::kSpeech;
minyuel6d92bf52015-09-23 15:20:39 +02001183
1184 // When packet_list is empty, we may be in kCodecInternalCng mode, and for
1185 // that we use current active decoder.
1186 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1187
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001188 if (!packet_list->empty()) {
1189 const Packet* packet = packet_list->front();
pkasting@chromium.org0e81fdf2015-02-02 23:54:03 +00001190 uint8_t payload_type = packet->header.payloadType;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001191 if (!decoder_database_->IsComfortNoise(payload_type)) {
1192 decoder = decoder_database_->GetDecoder(payload_type);
1193 assert(decoder);
1194 if (!decoder) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001195 LOG(LS_WARNING) << "Unknown payload type "
1196 << static_cast<int>(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001197 PacketBuffer::DeleteAllPackets(packet_list);
1198 return kDecoderNotFound;
1199 }
1200 bool decoder_changed;
1201 decoder_database_->SetActiveDecoder(payload_type, &decoder_changed);
1202 if (decoder_changed) {
1203 // We have a new decoder. Re-init some values.
1204 const DecoderDatabase::DecoderInfo* decoder_info = decoder_database_
1205 ->GetDecoderInfo(payload_type);
1206 assert(decoder_info);
1207 if (!decoder_info) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001208 LOG(LS_WARNING) << "Unknown payload type "
1209 << static_cast<int>(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001210 PacketBuffer::DeleteAllPackets(packet_list);
1211 return kDecoderNotFound;
1212 }
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001213 // If sampling rate or number of channels has changed, we need to make
1214 // a reset.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001215 if (decoder_info->fs_hz != fs_hz_ ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001216 decoder->Channels() != algorithm_buffer_->Channels()) {
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001217 // TODO(tlegrand): Add unittest to cover this event.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001218 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->Channels());
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001219 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001220 sync_buffer_->set_end_timestamp(timestamp_);
1221 playout_timestamp_ = timestamp_;
1222 }
1223 }
1224 }
1225
1226 if (reset_decoder_) {
1227 // TODO(hlundin): Write test for this.
Karl Wiberg43766482015-08-27 15:22:11 +02001228 if (decoder)
1229 decoder->Reset();
1230
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001231 // Reset comfort noise decoder.
1232 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02001233 if (cng_decoder)
1234 cng_decoder->Reset();
1235
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001236 reset_decoder_ = false;
1237 }
1238
1239#ifdef LEGACY_BITEXACT
1240 // Due to a bug in old SignalMCU, it could happen that CNG operation was
1241 // decided, but a speech packet was provided. The speech packet will be used
1242 // to update the comfort noise decoder, as if it was a SID frame, which is
1243 // clearly wrong.
1244 if (*operation == kRfc3389Cng) {
1245 return 0;
1246 }
1247#endif
1248
1249 *decoded_length = 0;
1250 // Update codec-internal PLC state.
1251 if ((*operation == kMerge) && decoder && decoder->HasDecodePlc()) {
1252 decoder->DecodePlc(1, &decoded_buffer_[*decoded_length]);
1253 }
1254
minyuel6d92bf52015-09-23 15:20:39 +02001255 int return_value;
1256 if (*operation == kCodecInternalCng) {
1257 RTC_DCHECK(packet_list->empty());
1258 return_value = DecodeCng(decoder, decoded_length, speech_type);
1259 } else {
1260 return_value = DecodeLoop(packet_list, *operation, decoder,
1261 decoded_length, speech_type);
1262 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001263
1264 if (*decoded_length < 0) {
1265 // Error returned from the decoder.
1266 *decoded_length = 0;
Peter Kastingb7e50542015-06-11 12:55:50 -07001267 sync_buffer_->IncreaseEndTimestamp(
1268 static_cast<uint32_t>(decoder_frame_length_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001269 int error_code = 0;
1270 if (decoder)
1271 error_code = decoder->ErrorCode();
1272 if (error_code != 0) {
1273 // Got some error code from the decoder.
1274 decoder_error_code_ = error_code;
1275 return_value = kDecoderErrorCode;
Henrik Lundind67a2192015-08-03 12:54:37 +02001276 LOG(LS_WARNING) << "Decoder returned error code: " << error_code;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001277 } else {
1278 // Decoder does not implement error codes. Return generic error.
1279 return_value = kOtherDecoderError;
Henrik Lundind67a2192015-08-03 12:54:37 +02001280 LOG(LS_WARNING) << "Decoder error (no error code)";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001281 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001282 *operation = kExpand; // Do expansion to get data instead.
1283 }
1284 if (*speech_type != AudioDecoder::kComfortNoise) {
1285 // Don't increment timestamp if codec returned CNG speech type
1286 // since in this case, the we will increment the CNGplayedTS counter.
1287 // Increase with number of samples per channel.
1288 assert(*decoded_length == 0 ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001289 (decoder && decoder->Channels() == sync_buffer_->Channels()));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001290 sync_buffer_->IncreaseEndTimestamp(
1291 *decoded_length / static_cast<int>(sync_buffer_->Channels()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001292 }
1293 return return_value;
1294}
1295
minyuel6d92bf52015-09-23 15:20:39 +02001296int NetEqImpl::DecodeCng(AudioDecoder* decoder, int* decoded_length,
1297 AudioDecoder::SpeechType* speech_type) {
1298 if (!decoder) {
1299 // This happens when active decoder is not defined.
1300 *decoded_length = -1;
1301 return 0;
1302 }
1303
1304 while (*decoded_length < rtc::checked_cast<int>(output_size_samples_)) {
1305 const int length = decoder->Decode(
1306 nullptr, 0, fs_hz_,
1307 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1308 &decoded_buffer_[*decoded_length], speech_type);
1309 if (length > 0) {
1310 *decoded_length += length;
minyuel6d92bf52015-09-23 15:20:39 +02001311 } else {
1312 // Error.
1313 LOG(LS_WARNING) << "Failed to decode CNG";
1314 *decoded_length = -1;
1315 break;
1316 }
1317 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1318 // Guard against overflow.
1319 LOG(LS_WARNING) << "Decoded too much CNG.";
1320 return kDecodedTooMuch;
1321 }
1322 }
1323 return 0;
1324}
1325
1326int NetEqImpl::DecodeLoop(PacketList* packet_list, const Operations& operation,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001327 AudioDecoder* decoder, int* decoded_length,
1328 AudioDecoder::SpeechType* speech_type) {
1329 Packet* packet = NULL;
1330 if (!packet_list->empty()) {
1331 packet = packet_list->front();
1332 }
minyuel6d92bf52015-09-23 15:20:39 +02001333
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001334 // Do decoding.
1335 while (packet &&
1336 !decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1337 assert(decoder); // At this point, we must have a decoder object.
1338 // The number of channels in the |sync_buffer_| should be the same as the
1339 // number decoder channels.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001340 assert(sync_buffer_->Channels() == decoder->Channels());
1341 assert(decoded_buffer_length_ >= kMaxFrameSize * decoder->Channels());
minyuel6d92bf52015-09-23 15:20:39 +02001342 assert(operation == kNormal || operation == kAccelerate ||
1343 operation == kFastAccelerate || operation == kMerge ||
1344 operation == kPreemptiveExpand);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001345 packet_list->pop_front();
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001346 size_t payload_length = packet->payload_length;
Peter Kasting36b7cc32015-06-11 19:57:18 -07001347 int decode_length;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +00001348 if (packet->sync_packet) {
1349 // Decode to silence with the same frame size as the last decode.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001350 memset(&decoded_buffer_[*decoded_length], 0,
1351 decoder_frame_length_ * decoder->Channels() *
1352 sizeof(decoded_buffer_[0]));
Peter Kastingdce40cf2015-08-24 14:52:23 -07001353 decode_length = rtc::checked_cast<int>(decoder_frame_length_);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +00001354 } else if (!packet->primary) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001355 // This is a redundant payload; call the special decoder method.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001356 decode_length = decoder->DecodeRedundant(
henrik.lundin@webrtc.org1eda4e32015-02-25 10:02:29 +00001357 packet->payload, packet->payload_length, fs_hz_,
minyue@webrtc.org7f7d7e32015-03-16 12:30:37 +00001358 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001359 &decoded_buffer_[*decoded_length], speech_type);
1360 } else {
henrik.lundin@webrtc.org1eda4e32015-02-25 10:02:29 +00001361 decode_length =
minyue@webrtc.org7f7d7e32015-03-16 12:30:37 +00001362 decoder->Decode(
1363 packet->payload, packet->payload_length, fs_hz_,
1364 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1365 &decoded_buffer_[*decoded_length], speech_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001366 }
1367
1368 delete[] packet->payload;
1369 delete packet;
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001370 packet = NULL;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001371 if (decode_length > 0) {
1372 *decoded_length += decode_length;
1373 // Update |decoder_frame_length_| with number of samples per channel.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001374 decoder_frame_length_ =
Peter Kastingdce40cf2015-08-24 14:52:23 -07001375 static_cast<size_t>(decode_length) / decoder->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001376 } else if (decode_length < 0) {
1377 // Error.
Henrik Lundind67a2192015-08-03 12:54:37 +02001378 LOG(LS_WARNING) << "Decode " << decode_length << " " << payload_length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001379 *decoded_length = -1;
1380 PacketBuffer::DeleteAllPackets(packet_list);
1381 break;
1382 }
1383 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1384 // Guard against overflow.
Henrik Lundind67a2192015-08-03 12:54:37 +02001385 LOG(LS_WARNING) << "Decoded too much.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001386 PacketBuffer::DeleteAllPackets(packet_list);
1387 return kDecodedTooMuch;
1388 }
1389 if (!packet_list->empty()) {
1390 packet = packet_list->front();
1391 } else {
1392 packet = NULL;
1393 }
1394 } // End of decode loop.
1395
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001396 // If the list is not empty at this point, either a decoding error terminated
1397 // the while-loop, or list must hold exactly one CNG packet.
1398 assert(packet_list->empty() || *decoded_length < 0 ||
1399 (packet_list->size() == 1 && packet &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001400 decoder_database_->IsComfortNoise(packet->header.payloadType)));
1401 return 0;
1402}
1403
1404void NetEqImpl::DoNormal(const int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001405 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001406 assert(normal_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001407 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001408 normal_->Process(decoded_buffer, decoded_length, last_mode_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001409 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001410 if (decoded_length != 0) {
1411 last_mode_ = kModeNormal;
1412 }
1413
1414 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1415 if ((speech_type == AudioDecoder::kComfortNoise)
1416 || ((last_mode_ == kModeCodecInternalCng)
1417 && (decoded_length == 0))) {
1418 // TODO(hlundin): Remove second part of || statement above.
1419 last_mode_ = kModeCodecInternalCng;
1420 }
1421
1422 if (!play_dtmf) {
1423 dtmf_tone_generator_->Reset();
1424 }
1425}
1426
1427void NetEqImpl::DoMerge(int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001428 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001429 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001430 assert(merge_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001431 size_t new_length = merge_->Process(decoded_buffer, decoded_length,
1432 mute_factor_array_.get(),
1433 algorithm_buffer_.get());
1434 size_t expand_length_correction = new_length -
1435 decoded_length / algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001436
1437 // Update in-call and post-call statistics.
1438 if (expand_->MuteFactor(0) == 0) {
1439 // Expand generates only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001440 stats_.ExpandedNoiseSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001441 } else {
1442 // Expansion generates more than only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001443 stats_.ExpandedVoiceSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001444 }
1445
1446 last_mode_ = kModeMerge;
1447 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1448 if (speech_type == AudioDecoder::kComfortNoise) {
1449 last_mode_ = kModeCodecInternalCng;
1450 }
1451 expand_->Reset();
1452 if (!play_dtmf) {
1453 dtmf_tone_generator_->Reset();
1454 }
1455}
1456
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001457int NetEqImpl::DoExpand(bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001458 while ((sync_buffer_->FutureLength() - expand_->overlap_length()) <
Peter Kastingdce40cf2015-08-24 14:52:23 -07001459 output_size_samples_) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001460 algorithm_buffer_->Clear();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001461 int return_value = expand_->Process(algorithm_buffer_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001462 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001463
1464 // Update in-call and post-call statistics.
1465 if (expand_->MuteFactor(0) == 0) {
1466 // Expand operation generates only noise.
1467 stats_.ExpandedNoiseSamples(length);
1468 } else {
1469 // Expand operation generates more than only noise.
1470 stats_.ExpandedVoiceSamples(length);
1471 }
1472
1473 last_mode_ = kModeExpand;
1474
1475 if (return_value < 0) {
1476 return return_value;
1477 }
1478
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001479 sync_buffer_->PushBack(*algorithm_buffer_);
1480 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001481 }
1482 if (!play_dtmf) {
1483 dtmf_tone_generator_->Reset();
1484 }
1485 return 0;
1486}
1487
Henrik Lundincf808d22015-05-27 14:33:29 +02001488int NetEqImpl::DoAccelerate(int16_t* decoded_buffer,
1489 size_t decoded_length,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001490 AudioDecoder::SpeechType speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +02001491 bool play_dtmf,
1492 bool fast_accelerate) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001493 const size_t required_samples =
1494 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001495 size_t borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001496 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001497 size_t decoded_length_per_channel = decoded_length / num_channels;
1498 if (decoded_length_per_channel < required_samples) {
1499 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001500 borrowed_samples_per_channel = static_cast<int>(required_samples -
1501 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001502 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1503 decoded_buffer,
1504 sizeof(int16_t) * decoded_length);
1505 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1506 decoded_buffer);
1507 decoded_length = required_samples * num_channels;
1508 }
1509
Peter Kastingdce40cf2015-08-24 14:52:23 -07001510 size_t samples_removed;
Henrik Lundincf808d22015-05-27 14:33:29 +02001511 Accelerate::ReturnCodes return_code =
1512 accelerate_->Process(decoded_buffer, decoded_length, fast_accelerate,
1513 algorithm_buffer_.get(), &samples_removed);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001514 stats_.AcceleratedSamples(samples_removed);
1515 switch (return_code) {
1516 case Accelerate::kSuccess:
1517 last_mode_ = kModeAccelerateSuccess;
1518 break;
1519 case Accelerate::kSuccessLowEnergy:
1520 last_mode_ = kModeAccelerateLowEnergy;
1521 break;
1522 case Accelerate::kNoStretch:
1523 last_mode_ = kModeAccelerateFail;
1524 break;
1525 case Accelerate::kError:
1526 // TODO(hlundin): Map to kModeError instead?
1527 last_mode_ = kModeAccelerateFail;
1528 return kAccelerateError;
1529 }
1530
1531 if (borrowed_samples_per_channel > 0) {
1532 // Copy borrowed samples back to the |sync_buffer_|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001533 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001534 if (length < borrowed_samples_per_channel) {
1535 // This destroys the beginning of the buffer, but will not cause any
1536 // problems.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001537 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001538 sync_buffer_->Size() -
1539 borrowed_samples_per_channel);
1540 sync_buffer_->PushFrontZeros(borrowed_samples_per_channel - length);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001541 algorithm_buffer_->PopFront(length);
1542 assert(algorithm_buffer_->Empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001543 } else {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001544 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001545 borrowed_samples_per_channel,
1546 sync_buffer_->Size() -
1547 borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001548 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001549 }
1550 }
1551
1552 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1553 if (speech_type == AudioDecoder::kComfortNoise) {
1554 last_mode_ = kModeCodecInternalCng;
1555 }
1556 if (!play_dtmf) {
1557 dtmf_tone_generator_->Reset();
1558 }
1559 expand_->Reset();
1560 return 0;
1561}
1562
1563int NetEqImpl::DoPreemptiveExpand(int16_t* decoded_buffer,
1564 size_t decoded_length,
1565 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001566 bool play_dtmf) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001567 const size_t required_samples =
1568 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001569 size_t num_channels = algorithm_buffer_->Channels();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001570 size_t borrowed_samples_per_channel = 0;
1571 size_t old_borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001572 size_t decoded_length_per_channel = decoded_length / num_channels;
1573 if (decoded_length_per_channel < required_samples) {
1574 // Must move data from the |sync_buffer_| in order to get 30 ms.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001575 borrowed_samples_per_channel =
1576 required_samples - decoded_length_per_channel;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001577 // Calculate how many of these were already played out.
Peter Kastingf045e4d2015-06-10 21:15:38 -07001578 old_borrowed_samples_per_channel =
Peter Kastingdce40cf2015-08-24 14:52:23 -07001579 (borrowed_samples_per_channel > sync_buffer_->FutureLength()) ?
1580 (borrowed_samples_per_channel - sync_buffer_->FutureLength()) : 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001581 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1582 decoded_buffer,
1583 sizeof(int16_t) * decoded_length);
1584 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1585 decoded_buffer);
1586 decoded_length = required_samples * num_channels;
1587 }
1588
Peter Kastingdce40cf2015-08-24 14:52:23 -07001589 size_t samples_added;
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001590 PreemptiveExpand::ReturnCodes return_code = preemptive_expand_->Process(
Peter Kastingdce40cf2015-08-24 14:52:23 -07001591 decoded_buffer, decoded_length,
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001592 old_borrowed_samples_per_channel,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001593 algorithm_buffer_.get(), &samples_added);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001594 stats_.PreemptiveExpandedSamples(samples_added);
1595 switch (return_code) {
1596 case PreemptiveExpand::kSuccess:
1597 last_mode_ = kModePreemptiveExpandSuccess;
1598 break;
1599 case PreemptiveExpand::kSuccessLowEnergy:
1600 last_mode_ = kModePreemptiveExpandLowEnergy;
1601 break;
1602 case PreemptiveExpand::kNoStretch:
1603 last_mode_ = kModePreemptiveExpandFail;
1604 break;
1605 case PreemptiveExpand::kError:
1606 // TODO(hlundin): Map to kModeError instead?
1607 last_mode_ = kModePreemptiveExpandFail;
1608 return kPreemptiveExpandError;
1609 }
1610
1611 if (borrowed_samples_per_channel > 0) {
1612 // Copy borrowed samples back to the |sync_buffer_|.
1613 sync_buffer_->ReplaceAtIndex(
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001614 *algorithm_buffer_, borrowed_samples_per_channel,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001615 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001616 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001617 }
1618
1619 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1620 if (speech_type == AudioDecoder::kComfortNoise) {
1621 last_mode_ = kModeCodecInternalCng;
1622 }
1623 if (!play_dtmf) {
1624 dtmf_tone_generator_->Reset();
1625 }
1626 expand_->Reset();
1627 return 0;
1628}
1629
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001630int NetEqImpl::DoRfc3389Cng(PacketList* packet_list, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001631 if (!packet_list->empty()) {
1632 // Must have exactly one SID frame at this point.
1633 assert(packet_list->size() == 1);
1634 Packet* packet = packet_list->front();
1635 packet_list->pop_front();
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001636 if (!decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1637#ifdef LEGACY_BITEXACT
1638 // This can happen due to a bug in GetDecision. Change the payload type
1639 // to a CNG type, and move on. Note that this means that we are in fact
1640 // sending a non-CNG payload to the comfort noise decoder for decoding.
1641 // Clearly wrong, but will maintain bit-exactness with legacy.
1642 if (fs_hz_ == 8000) {
1643 packet->header.payloadType =
kwibergee1879c2015-10-29 06:20:28 -07001644 decoder_database_->GetRtpPayloadType(NetEqDecoder::kDecoderCNGnb);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001645 } else if (fs_hz_ == 16000) {
1646 packet->header.payloadType =
kwibergee1879c2015-10-29 06:20:28 -07001647 decoder_database_->GetRtpPayloadType(NetEqDecoder::kDecoderCNGwb);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001648 } else if (fs_hz_ == 32000) {
kwibergee1879c2015-10-29 06:20:28 -07001649 packet->header.payloadType = decoder_database_->GetRtpPayloadType(
1650 NetEqDecoder::kDecoderCNGswb32kHz);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001651 } else if (fs_hz_ == 48000) {
kwibergee1879c2015-10-29 06:20:28 -07001652 packet->header.payloadType = decoder_database_->GetRtpPayloadType(
1653 NetEqDecoder::kDecoderCNGswb48kHz);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001654 }
1655 assert(decoder_database_->IsComfortNoise(packet->header.payloadType));
1656#else
1657 LOG(LS_ERROR) << "Trying to decode non-CNG payload as CNG.";
1658 return kOtherError;
1659#endif
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001660 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001661 // UpdateParameters() deletes |packet|.
1662 if (comfort_noise_->UpdateParameters(packet) ==
1663 ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001664 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001665 return -comfort_noise_->internal_error_code();
1666 }
1667 }
1668 int cn_return = comfort_noise_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001669 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001670 expand_->Reset();
1671 last_mode_ = kModeRfc3389Cng;
1672 if (!play_dtmf) {
1673 dtmf_tone_generator_->Reset();
1674 }
1675 if (cn_return == ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001676 decoder_error_code_ = comfort_noise_->internal_error_code();
1677 return kComfortNoiseErrorCode;
1678 } else if (cn_return == ComfortNoise::kUnknownPayloadType) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001679 return kUnknownRtpPayloadType;
1680 }
1681 return 0;
1682}
1683
minyuel6d92bf52015-09-23 15:20:39 +02001684void NetEqImpl::DoCodecInternalCng(const int16_t* decoded_buffer,
1685 size_t decoded_length) {
1686 RTC_DCHECK(normal_.get());
1687 RTC_DCHECK(mute_factor_array_.get());
1688 normal_->Process(decoded_buffer, decoded_length, last_mode_,
1689 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001690 last_mode_ = kModeCodecInternalCng;
1691 expand_->Reset();
1692}
1693
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001694int NetEqImpl::DoDtmf(const DtmfEvent& dtmf_event, bool* play_dtmf) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001695 // This block of the code and the block further down, handling |dtmf_switch|
1696 // are commented out. Otherwise playing out-of-band DTMF would fail in VoE
1697 // test, DtmfTest.ManualSuccessfullySendsOutOfBandTelephoneEvents. This is
1698 // equivalent to |dtmf_switch| always be false.
1699 //
1700 // See http://webrtc-codereview.appspot.com/1195004/ for discussion
1701 // On this issue. This change might cause some glitches at the point of
1702 // switch from audio to DTMF. Issue 1545 is filed to track this.
1703 //
1704 // bool dtmf_switch = false;
1705 // if ((last_mode_ != kModeDtmf) && dtmf_tone_generator_->initialized()) {
1706 // // Special case; see below.
1707 // // We must catch this before calling Generate, since |initialized| is
1708 // // modified in that call.
1709 // dtmf_switch = true;
1710 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001711
1712 int dtmf_return_value = 0;
1713 if (!dtmf_tone_generator_->initialized()) {
1714 // Initialize if not already done.
1715 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1716 dtmf_event.volume);
1717 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001718
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001719 if (dtmf_return_value == 0) {
1720 // Generate DTMF signal.
1721 dtmf_return_value = dtmf_tone_generator_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001722 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001723 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001724
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001725 if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001726 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001727 return dtmf_return_value;
1728 }
1729
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001730 // if (dtmf_switch) {
1731 // // This is the special case where the previous operation was DTMF
1732 // // overdub, but the current instruction is "regular" DTMF. We must make
1733 // // sure that the DTMF does not have any discontinuities. The first DTMF
1734 // // sample that we generate now must be played out immediately, therefore
1735 // // it must be copied to the speech buffer.
1736 // // TODO(hlundin): This code seems incorrect. (Legacy.) Write test and
1737 // // verify correct operation.
1738 // assert(false);
1739 // // Must generate enough data to replace all of the |sync_buffer_|
1740 // // "future".
1741 // int required_length = sync_buffer_->FutureLength();
1742 // assert(dtmf_tone_generator_->initialized());
1743 // dtmf_return_value = dtmf_tone_generator_->Generate(required_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001744 // algorithm_buffer_);
1745 // assert((size_t) required_length == algorithm_buffer_->Size());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001746 // if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001747 // algorithm_buffer_->Zeros(output_size_samples_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001748 // return dtmf_return_value;
1749 // }
1750 //
1751 // // Overwrite the "future" part of the speech buffer with the new DTMF
1752 // // data.
1753 // // TODO(hlundin): It seems that this overwriting has gone lost.
1754 // // Not adapted for multi-channel yet.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001755 // assert(algorithm_buffer_->Channels() == 1);
1756 // if (algorithm_buffer_->Channels() != 1) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001757 // LOG(LS_WARNING) << "DTMF not supported for more than one channel";
1758 // return kStereoNotSupported;
1759 // }
1760 // // Shuffle the remaining data to the beginning of algorithm buffer.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001761 // algorithm_buffer_->PopFront(sync_buffer_->FutureLength());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001762 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001763
Peter Kastingb7e50542015-06-11 12:55:50 -07001764 sync_buffer_->IncreaseEndTimestamp(
1765 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001766 expand_->Reset();
1767 last_mode_ = kModeDtmf;
1768
1769 // Set to false because the DTMF is already in the algorithm buffer.
1770 *play_dtmf = false;
1771 return 0;
1772}
1773
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001774void NetEqImpl::DoAlternativePlc(bool increase_timestamp) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001775 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001776 size_t length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001777 if (decoder && decoder->HasDecodePlc()) {
1778 // Use the decoder's packet-loss concealment.
1779 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1780 int16_t decoded_buffer[kMaxFrameSize];
1781 length = decoder->DecodePlc(1, decoded_buffer);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001782 if (length > 0)
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001783 algorithm_buffer_->PushBackInterleaved(decoded_buffer, length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001784 } else {
1785 // Do simple zero-stuffing.
1786 length = output_size_samples_;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001787 algorithm_buffer_->Zeros(length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001788 // By not advancing the timestamp, NetEq inserts samples.
1789 stats_.AddZeros(length);
1790 }
1791 if (increase_timestamp) {
Peter Kastingb7e50542015-06-11 12:55:50 -07001792 sync_buffer_->IncreaseEndTimestamp(static_cast<uint32_t>(length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001793 }
1794 expand_->Reset();
1795}
1796
1797int NetEqImpl::DtmfOverdub(const DtmfEvent& dtmf_event, size_t num_channels,
1798 int16_t* output) const {
1799 size_t out_index = 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001800 size_t overdub_length = output_size_samples_; // Default value.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001801
1802 if (sync_buffer_->dtmf_index() > sync_buffer_->next_index()) {
1803 // Special operation for transition from "DTMF only" to "DTMF overdub".
1804 out_index = std::min(
1805 sync_buffer_->dtmf_index() - sync_buffer_->next_index(),
Peter Kastingdce40cf2015-08-24 14:52:23 -07001806 output_size_samples_);
1807 overdub_length = output_size_samples_ - out_index;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001808 }
1809
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001810 AudioMultiVector dtmf_output(num_channels);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001811 int dtmf_return_value = 0;
1812 if (!dtmf_tone_generator_->initialized()) {
1813 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1814 dtmf_event.volume);
1815 }
1816 if (dtmf_return_value == 0) {
1817 dtmf_return_value = dtmf_tone_generator_->Generate(overdub_length,
1818 &dtmf_output);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001819 assert(overdub_length == dtmf_output.Size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001820 }
1821 dtmf_output.ReadInterleaved(overdub_length, &output[out_index]);
1822 return dtmf_return_value < 0 ? dtmf_return_value : 0;
1823}
1824
Peter Kastingdce40cf2015-08-24 14:52:23 -07001825int NetEqImpl::ExtractPackets(size_t required_samples,
1826 PacketList* packet_list) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001827 bool first_packet = true;
1828 uint8_t prev_payload_type = 0;
1829 uint32_t prev_timestamp = 0;
1830 uint16_t prev_sequence_number = 0;
1831 bool next_packet_available = false;
1832
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001833 const RTPHeader* header = packet_buffer_->NextRtpHeader();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001834 assert(header);
1835 if (!header) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001836 LOG(LS_ERROR) << "Packet buffer unexpectedly empty.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001837 return -1;
1838 }
turaj@webrtc.org7df97062013-08-02 18:07:13 +00001839 uint32_t first_timestamp = header->timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001840 int extracted_samples = 0;
1841
1842 // Packet extraction loop.
1843 do {
1844 timestamp_ = header->timestamp;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001845 size_t discard_count = 0;
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001846 Packet* packet = packet_buffer_->GetNextPacket(&discard_count);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001847 // |header| may be invalid after the |packet_buffer_| operation.
1848 header = NULL;
1849 if (!packet) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001850 LOG(LS_ERROR) << "Should always be able to extract a packet here";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001851 assert(false); // Should always be able to extract a packet here.
1852 return -1;
1853 }
1854 stats_.PacketsDiscarded(discard_count);
1855 // Store waiting time in ms; packets->waiting_time is in "output blocks".
1856 stats_.StoreWaitingTime(packet->waiting_time * kOutputSizeMs);
1857 assert(packet->payload_length > 0);
1858 packet_list->push_back(packet); // Store packet in list.
1859
1860 if (first_packet) {
1861 first_packet = false;
henrik.lundin48ed9302015-10-29 05:36:24 -07001862 if (nack_enabled_) {
1863 RTC_DCHECK(nack_);
1864 // TODO(henrik.lundin): Should we update this for all decoded packets?
1865 nack_->UpdateLastDecodedPacket(packet->header.sequenceNumber,
1866 packet->header.timestamp);
1867 }
1868 prev_sequence_number = packet->header.sequenceNumber;
1869 prev_timestamp = packet->header.timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001870 prev_payload_type = packet->header.payloadType;
1871 }
1872
1873 // Store number of extracted samples.
1874 int packet_duration = 0;
1875 AudioDecoder* decoder = decoder_database_->GetDecoder(
1876 packet->header.payloadType);
1877 if (decoder) {
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001878 if (packet->sync_packet) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001879 packet_duration = rtc::checked_cast<int>(decoder_frame_length_);
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001880 } else {
minyue@webrtc.org2c1bcf22015-02-17 10:17:09 +00001881 if (packet->primary) {
1882 packet_duration = decoder->PacketDuration(packet->payload,
1883 packet->payload_length);
1884 } else {
1885 packet_duration = decoder->
1886 PacketDurationRedundant(packet->payload, packet->payload_length);
1887 stats_.SecondaryDecodedSamples(packet_duration);
1888 }
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001889 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001890 } else {
Henrik Lundind67a2192015-08-03 12:54:37 +02001891 LOG(LS_WARNING) << "Unknown payload type "
1892 << static_cast<int>(packet->header.payloadType);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001893 assert(false);
1894 }
1895 if (packet_duration <= 0) {
1896 // Decoder did not return a packet duration. Assume that the packet
1897 // contains the same number of samples as the previous one.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001898 packet_duration = rtc::checked_cast<int>(decoder_frame_length_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001899 }
1900 extracted_samples = packet->header.timestamp - first_timestamp +
1901 packet_duration;
1902
1903 // Check what packet is available next.
1904 header = packet_buffer_->NextRtpHeader();
1905 next_packet_available = false;
1906 if (header && prev_payload_type == header->payloadType) {
1907 int16_t seq_no_diff = header->sequenceNumber - prev_sequence_number;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001908 size_t ts_diff = header->timestamp - prev_timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001909 if (seq_no_diff == 1 ||
1910 (seq_no_diff == 0 && ts_diff == decoder_frame_length_)) {
1911 // The next sequence number is available, or the next part of a packet
1912 // that was split into pieces upon insertion.
1913 next_packet_available = true;
1914 }
1915 prev_sequence_number = header->sequenceNumber;
1916 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07001917 } while (extracted_samples < rtc::checked_cast<int>(required_samples) &&
1918 next_packet_available);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001919
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00001920 if (extracted_samples > 0) {
1921 // Delete old packets only when we are going to decode something. Otherwise,
1922 // we could end up in the situation where we never decode anything, since
1923 // all incoming packets are considered too old but the buffer will also
1924 // never be flooded and flushed.
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001925 packet_buffer_->DiscardAllOldPackets(timestamp_);
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00001926 }
1927
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001928 return extracted_samples;
1929}
1930
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001931void NetEqImpl::UpdatePlcComponents(int fs_hz, size_t channels) {
1932 // Delete objects and create new ones.
1933 expand_.reset(expand_factory_->Create(background_noise_.get(),
1934 sync_buffer_.get(), &random_vector_,
Henrik Lundinbef77e22015-08-18 14:58:09 +02001935 &stats_, fs_hz, channels));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001936 merge_.reset(new Merge(fs_hz, channels, expand_.get(), sync_buffer_.get()));
1937}
1938
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001939void NetEqImpl::SetSampleRateAndChannels(int fs_hz, size_t channels) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001940 LOG(LS_VERBOSE) << "SetSampleRateAndChannels " << fs_hz << " " << channels;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001941 // TODO(hlundin): Change to an enumerator and skip assert.
1942 assert(fs_hz == 8000 || fs_hz == 16000 || fs_hz == 32000 || fs_hz == 48000);
1943 assert(channels > 0);
1944
1945 fs_hz_ = fs_hz;
1946 fs_mult_ = fs_hz / 8000;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001947 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001948 decoder_frame_length_ = 3 * output_size_samples_; // Initialize to 30ms.
1949
1950 last_mode_ = kModeNormal;
1951
1952 // Create a new array of mute factors and set all to 1.
1953 mute_factor_array_.reset(new int16_t[channels]);
1954 for (size_t i = 0; i < channels; ++i) {
1955 mute_factor_array_[i] = 16384; // 1.0 in Q14.
1956 }
1957
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001958 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02001959 if (cng_decoder)
1960 cng_decoder->Reset();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001961
1962 // Reinit post-decode VAD with new sample rate.
1963 assert(vad_.get()); // Cannot be NULL here.
1964 vad_->Init();
1965
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001966 // Delete algorithm buffer and create a new one.
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001967 algorithm_buffer_.reset(new AudioMultiVector(channels));
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001968
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001969 // Delete sync buffer and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001970 sync_buffer_.reset(new SyncBuffer(channels, kSyncBufferSize * fs_mult_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001971
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00001972 // Delete BackgroundNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001973 background_noise_.reset(new BackgroundNoise(channels));
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00001974 background_noise_->set_mode(background_noise_mode_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001975
1976 // Reset random vector.
1977 random_vector_.Reset();
1978
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001979 UpdatePlcComponents(fs_hz, channels);
1980
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001981 // Move index so that we create a small set of future samples (all 0).
1982 sync_buffer_->set_next_index(sync_buffer_->next_index() -
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001983 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001984
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001985 normal_.reset(new Normal(fs_hz, decoder_database_.get(), *background_noise_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001986 expand_.get()));
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +00001987 accelerate_.reset(
1988 accelerate_factory_->Create(fs_hz, channels, *background_noise_));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001989 preemptive_expand_.reset(preemptive_expand_factory_->Create(
Peter Kastingdce40cf2015-08-24 14:52:23 -07001990 fs_hz, channels, *background_noise_, expand_->overlap_length()));
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001991
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001992 // Delete ComfortNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001993 comfort_noise_.reset(new ComfortNoise(fs_hz, decoder_database_.get(),
1994 sync_buffer_.get()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001995
1996 // Verify that |decoded_buffer_| is long enough.
1997 if (decoded_buffer_length_ < kMaxFrameSize * channels) {
1998 // Reallocate to larger size.
1999 decoded_buffer_length_ = kMaxFrameSize * channels;
2000 decoded_buffer_.reset(new int16_t[decoded_buffer_length_]);
2001 }
2002
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002003 // Create DecisionLogic if it is not created yet, then communicate new sample
2004 // rate and output size to DecisionLogic object.
2005 if (!decision_logic_.get()) {
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002006 CreateDecisionLogic();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002007 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002008 decision_logic_->SetSampleRate(fs_hz_, output_size_samples_);
2009}
2010
2011NetEqOutputType NetEqImpl::LastOutputType() {
2012 assert(vad_.get());
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002013 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002014 if (last_mode_ == kModeCodecInternalCng || last_mode_ == kModeRfc3389Cng) {
2015 return kOutputCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002016 } else if (last_mode_ == kModeExpand && expand_->MuteFactor(0) == 0) {
2017 // Expand mode has faded down to background noise only (very long expand).
2018 return kOutputPLCtoCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002019 } else if (last_mode_ == kModeExpand) {
2020 return kOutputPLC;
wu@webrtc.org24301a62013-12-13 19:17:43 +00002021 } else if (vad_->running() && !vad_->active_speech()) {
2022 return kOutputVADPassive;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002023 } else {
2024 return kOutputNormal;
2025 }
2026}
2027
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002028void NetEqImpl::CreateDecisionLogic() {
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002029 decision_logic_.reset(DecisionLogic::Create(fs_hz_, output_size_samples_,
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002030 playout_mode_,
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002031 decoder_database_.get(),
2032 *packet_buffer_.get(),
2033 delay_manager_.get(),
2034 buffer_level_filter_.get()));
2035}
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002036} // namespace webrtc