blob: ecd1ad9fabe7971312309928aae015b7f43bfb5b [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.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000045#include "webrtc/modules/interface/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.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000115}
116
Henrik Lundind67a2192015-08-03 12:54:37 +0200117NetEqImpl::~NetEqImpl() = default;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000118
119int NetEqImpl::InsertPacket(const WebRtcRTPHeader& rtp_header,
120 const uint8_t* payload,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000121 size_t length_bytes,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000122 uint32_t receive_timestamp) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000123 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000124 LOG(LS_VERBOSE) << "InsertPacket: ts=" << rtp_header.header.timestamp <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000125 ", sn=" << rtp_header.header.sequenceNumber <<
126 ", pt=" << static_cast<int>(rtp_header.header.payloadType) <<
127 ", ssrc=" << rtp_header.header.ssrc <<
128 ", len=" << length_bytes;
129 int error = InsertPacketInternal(rtp_header, payload, length_bytes,
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000130 receive_timestamp, false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000131 if (error != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000132 error_code_ = error;
133 return kFail;
134 }
135 return kOK;
136}
137
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000138int NetEqImpl::InsertSyncPacket(const WebRtcRTPHeader& rtp_header,
139 uint32_t receive_timestamp) {
140 CriticalSectionScoped lock(crit_sect_.get());
141 LOG(LS_VERBOSE) << "InsertPacket-Sync: ts="
142 << rtp_header.header.timestamp <<
143 ", sn=" << rtp_header.header.sequenceNumber <<
144 ", pt=" << static_cast<int>(rtp_header.header.payloadType) <<
145 ", ssrc=" << rtp_header.header.ssrc;
146
147 const uint8_t kSyncPayload[] = { 's', 'y', 'n', 'c' };
148 int error = InsertPacketInternal(
149 rtp_header, kSyncPayload, sizeof(kSyncPayload), receive_timestamp, true);
150
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000151 if (error != 0) {
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000152 error_code_ = error;
153 return kFail;
154 }
155 return kOK;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000156}
157
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000158int NetEqImpl::GetAudio(size_t max_length, int16_t* output_audio,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700159 size_t* samples_per_channel, int* num_channels,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000160 NetEqOutputType* type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000161 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000162 LOG(LS_VERBOSE) << "GetAudio";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000163 int error = GetAudioInternal(max_length, output_audio, samples_per_channel,
164 num_channels);
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000165 LOG(LS_VERBOSE) << "Produced " << *samples_per_channel <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000166 " samples/channel for " << *num_channels << " channel(s)";
167 if (error != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000168 error_code_ = error;
169 return kFail;
170 }
171 if (type) {
172 *type = LastOutputType();
173 }
174 return kOK;
175}
176
177int NetEqImpl::RegisterPayloadType(enum NetEqDecoder codec,
178 uint8_t rtp_payload_type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000179 CriticalSectionScoped lock(crit_sect_.get());
Henrik Lundind67a2192015-08-03 12:54:37 +0200180 LOG(LS_VERBOSE) << "RegisterPayloadType "
181 << static_cast<int>(rtp_payload_type) << " " << codec;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000182 int ret = decoder_database_->RegisterPayload(rtp_payload_type, codec);
183 if (ret != DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000184 switch (ret) {
185 case DecoderDatabase::kInvalidRtpPayloadType:
186 error_code_ = kInvalidRtpPayloadType;
187 break;
188 case DecoderDatabase::kCodecNotSupported:
189 error_code_ = kCodecNotSupported;
190 break;
191 case DecoderDatabase::kDecoderExists:
192 error_code_ = kDecoderExists;
193 break;
194 default:
195 error_code_ = kOtherError;
196 }
197 return kFail;
198 }
199 return kOK;
200}
201
202int NetEqImpl::RegisterExternalDecoder(AudioDecoder* decoder,
203 enum NetEqDecoder codec,
Karl Wibergd8399e62015-05-25 14:39:56 +0200204 uint8_t rtp_payload_type,
205 int sample_rate_hz) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000206 CriticalSectionScoped lock(crit_sect_.get());
Henrik Lundind67a2192015-08-03 12:54:37 +0200207 LOG(LS_VERBOSE) << "RegisterExternalDecoder "
208 << static_cast<int>(rtp_payload_type) << " " << codec;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000209 if (!decoder) {
210 LOG(LS_ERROR) << "Cannot register external decoder with NULL pointer";
211 assert(false);
212 return kFail;
213 }
214 int ret = decoder_database_->InsertExternal(rtp_payload_type, codec,
215 sample_rate_hz, decoder);
216 if (ret != DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000217 switch (ret) {
218 case DecoderDatabase::kInvalidRtpPayloadType:
219 error_code_ = kInvalidRtpPayloadType;
220 break;
221 case DecoderDatabase::kCodecNotSupported:
222 error_code_ = kCodecNotSupported;
223 break;
224 case DecoderDatabase::kDecoderExists:
225 error_code_ = kDecoderExists;
226 break;
227 case DecoderDatabase::kInvalidSampleRate:
228 error_code_ = kInvalidSampleRate;
229 break;
230 case DecoderDatabase::kInvalidPointer:
231 error_code_ = kInvalidPointer;
232 break;
233 default:
234 error_code_ = kOtherError;
235 }
236 return kFail;
237 }
238 return kOK;
239}
240
241int NetEqImpl::RemovePayloadType(uint8_t rtp_payload_type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000242 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000243 int ret = decoder_database_->Remove(rtp_payload_type);
244 if (ret == DecoderDatabase::kOK) {
245 return kOK;
246 } else if (ret == DecoderDatabase::kDecoderNotFound) {
247 error_code_ = kDecoderNotFound;
248 } else {
249 error_code_ = kOtherError;
250 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000251 return kFail;
252}
253
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000254bool NetEqImpl::SetMinimumDelay(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) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000257 assert(delay_manager_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000258 return delay_manager_->SetMinimumDelay(delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000259 }
260 return false;
261}
262
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000263bool NetEqImpl::SetMaximumDelay(int delay_ms) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000264 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000265 if (delay_ms >= 0 && delay_ms < 10000) {
266 assert(delay_manager_.get());
267 return delay_manager_->SetMaximumDelay(delay_ms);
268 }
269 return false;
270}
271
272int NetEqImpl::LeastRequiredDelayMs() const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000273 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000274 assert(delay_manager_.get());
275 return delay_manager_->least_required_delay_ms();
276}
277
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200278int NetEqImpl::SetTargetDelay() {
279 return kNotImplemented;
280}
281
282int NetEqImpl::TargetDelay() {
283 return kNotImplemented;
284}
285
henrik.lundin9c3efd02015-08-27 13:12:22 -0700286int NetEqImpl::CurrentDelayMs() const {
287 CriticalSectionScoped lock(crit_sect_.get());
288 if (fs_hz_ == 0)
289 return 0;
290 // Sum up the samples in the packet buffer with the future length of the sync
291 // buffer, and divide the sum by the sample rate.
292 const size_t delay_samples =
293 packet_buffer_->NumSamplesInBuffer(decoder_database_.get(),
294 decoder_frame_length_) +
295 sync_buffer_->FutureLength();
296 // The division below will truncate.
297 const int delay_ms =
298 static_cast<int>(delay_samples) / rtc::CheckedDivExact(fs_hz_, 1000);
299 return delay_ms;
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200300}
301
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000302// Deprecated.
303// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000304void NetEqImpl::SetPlayoutMode(NetEqPlayoutMode mode) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000305 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000306 if (mode != playout_mode_) {
307 playout_mode_ = mode;
308 CreateDecisionLogic();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000309 }
310}
311
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000312// Deprecated.
313// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000314NetEqPlayoutMode NetEqImpl::PlayoutMode() const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000315 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000316 return playout_mode_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000317}
318
319int NetEqImpl::NetworkStatistics(NetEqNetworkStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000320 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000321 assert(decoder_database_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700322 const size_t total_samples_in_buffers =
Peter Kasting728d9032015-06-11 14:31:38 -0700323 packet_buffer_->NumSamplesInBuffer(decoder_database_.get(),
324 decoder_frame_length_) +
Peter Kastingdce40cf2015-08-24 14:52:23 -0700325 sync_buffer_->FutureLength();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000326 assert(delay_manager_.get());
327 assert(decision_logic_.get());
328 stats_.GetNetworkStatistics(fs_hz_, total_samples_in_buffers,
329 decoder_frame_length_, *delay_manager_.get(),
330 *decision_logic_.get(), stats);
331 return 0;
332}
333
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000334void NetEqImpl::GetRtcpStatistics(RtcpStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000335 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000336 if (stats) {
337 rtcp_.GetStatistics(false, stats);
338 }
339}
340
341void NetEqImpl::GetRtcpStatisticsNoReset(RtcpStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000342 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000343 if (stats) {
344 rtcp_.GetStatistics(true, stats);
345 }
346}
347
348void NetEqImpl::EnableVad() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000349 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000350 assert(vad_.get());
351 vad_->Enable();
352}
353
354void NetEqImpl::DisableVad() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000355 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000356 assert(vad_.get());
357 vad_->Disable();
358}
359
wu@webrtc.org94454b72014-06-05 20:34:08 +0000360bool NetEqImpl::GetPlayoutTimestamp(uint32_t* timestamp) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000361 CriticalSectionScoped lock(crit_sect_.get());
wu@webrtc.org94454b72014-06-05 20:34:08 +0000362 if (first_packet_) {
363 // We don't have a valid RTP timestamp until we have decoded our first
364 // RTP packet.
365 return false;
366 }
367 *timestamp = timestamp_scaler_->ToExternal(playout_timestamp_);
368 return true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000369}
370
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200371int NetEqImpl::SetTargetNumberOfChannels() {
372 return kNotImplemented;
373}
374
375int NetEqImpl::SetTargetSampleRate() {
376 return kNotImplemented;
377}
378
henrik.lundin@webrtc.orgb0f4b3d2014-11-04 08:53:10 +0000379int NetEqImpl::LastError() const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000380 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000381 return error_code_;
382}
383
384int NetEqImpl::LastDecoderError() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000385 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000386 return decoder_error_code_;
387}
388
389void NetEqImpl::FlushBuffers() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000390 CriticalSectionScoped lock(crit_sect_.get());
Henrik Lundind67a2192015-08-03 12:54:37 +0200391 LOG(LS_VERBOSE) << "FlushBuffers";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000392 packet_buffer_->Flush();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000393 assert(sync_buffer_.get());
394 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000395 sync_buffer_->Flush();
396 sync_buffer_->set_next_index(sync_buffer_->next_index() -
397 expand_->overlap_length());
398 // Set to wait for new codec.
399 first_packet_ = true;
400}
401
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000402void NetEqImpl::PacketBufferStatistics(int* current_num_packets,
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000403 int* max_num_packets) const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000404 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000405 packet_buffer_->BufferStat(current_num_packets, max_num_packets);
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000406}
407
henrik.lundin48ed9302015-10-29 05:36:24 -0700408void NetEqImpl::EnableNack(size_t max_nack_list_size) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000409 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin48ed9302015-10-29 05:36:24 -0700410 if (!nack_enabled_) {
411 const int kNackThresholdPackets = 2;
412 nack_.reset(Nack::Create(kNackThresholdPackets));
413 nack_enabled_ = true;
414 nack_->UpdateSampleRate(fs_hz_);
415 }
416 nack_->SetMaxNackListSize(max_nack_list_size);
417}
418
419void NetEqImpl::DisableNack() {
420 CriticalSectionScoped lock(crit_sect_.get());
421 nack_.reset();
422 nack_enabled_ = false;
423}
424
425std::vector<uint16_t> NetEqImpl::GetNackList(int64_t round_trip_time_ms) const {
426 CriticalSectionScoped lock(crit_sect_.get());
427 if (!nack_enabled_) {
428 return std::vector<uint16_t>();
429 }
430 RTC_DCHECK(nack_.get());
431 return nack_->GetNackList(round_trip_time_ms);
minyue@webrtc.orgd7301772013-08-29 00:58:14 +0000432}
433
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000434const SyncBuffer* NetEqImpl::sync_buffer_for_test() const {
435 CriticalSectionScoped lock(crit_sect_.get());
436 return sync_buffer_.get();
437}
438
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000439// Methods below this line are private.
440
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000441int NetEqImpl::InsertPacketInternal(const WebRtcRTPHeader& rtp_header,
442 const uint8_t* payload,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000443 size_t length_bytes,
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000444 uint32_t receive_timestamp,
445 bool is_sync_packet) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000446 if (!payload) {
447 LOG_F(LS_ERROR) << "payload == NULL";
448 return kInvalidPointer;
449 }
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000450 // Sanity checks for sync-packets.
451 if (is_sync_packet) {
452 if (decoder_database_->IsDtmf(rtp_header.header.payloadType) ||
453 decoder_database_->IsRed(rtp_header.header.payloadType) ||
454 decoder_database_->IsComfortNoise(rtp_header.header.payloadType)) {
455 LOG_F(LS_ERROR) << "Sync-packet with an unacceptable payload type "
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000456 << static_cast<int>(rtp_header.header.payloadType);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000457 return kSyncPacketNotAccepted;
458 }
459 if (first_packet_ ||
460 rtp_header.header.payloadType != current_rtp_payload_type_ ||
461 rtp_header.header.ssrc != ssrc_) {
462 // Even if |current_rtp_payload_type_| is 0xFF, sync-packet isn't
463 // accepted.
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000464 LOG_F(LS_ERROR)
465 << "Changing codec, SSRC or first packet with sync-packet.";
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000466 return kSyncPacketNotAccepted;
467 }
468 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000469 PacketList packet_list;
470 RTPHeader main_header;
471 {
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000472 // Convert to Packet.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000473 // Create |packet| within this separate scope, since it should not be used
474 // directly once it's been inserted in the packet list. This way, |packet|
475 // is not defined outside of this block.
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000476 Packet* packet = new Packet;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000477 packet->header.markerBit = false;
478 packet->header.payloadType = rtp_header.header.payloadType;
479 packet->header.sequenceNumber = rtp_header.header.sequenceNumber;
480 packet->header.timestamp = rtp_header.header.timestamp;
481 packet->header.ssrc = rtp_header.header.ssrc;
482 packet->header.numCSRCs = 0;
483 packet->payload_length = length_bytes;
484 packet->primary = true;
485 packet->waiting_time = 0;
486 packet->payload = new uint8_t[packet->payload_length];
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000487 packet->sync_packet = is_sync_packet;
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +0000488 if (!packet->payload) {
489 LOG_F(LS_ERROR) << "Payload pointer is NULL.";
490 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000491 assert(payload); // Already checked above.
492 memcpy(packet->payload, payload, packet->payload_length);
493 // Insert packet in a packet list.
494 packet_list.push_back(packet);
495 // Save main payloads header for later.
496 memcpy(&main_header, &packet->header, sizeof(main_header));
497 }
498
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000499 bool update_sample_rate_and_channels = false;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000500 // Reinitialize NetEq if it's needed (changed SSRC or first call).
501 if ((main_header.ssrc != ssrc_) || first_packet_) {
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000502 // Note: |first_packet_| will be cleared further down in this method, once
503 // the packet has been successfully inserted into the packet buffer.
504
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000505 rtcp_.Init(main_header.sequenceNumber);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000506
507 // Flush the packet buffer and DTMF buffer.
508 packet_buffer_->Flush();
509 dtmf_buffer_->Flush();
510
511 // Store new SSRC.
512 ssrc_ = main_header.ssrc;
513
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000514 // Update audio buffer timestamp.
515 sync_buffer_->IncreaseEndTimestamp(main_header.timestamp - timestamp_);
516
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000517 // Update codecs.
518 timestamp_ = main_header.timestamp;
519 current_rtp_payload_type_ = main_header.payloadType;
520
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000521 // Reset timestamp scaling.
522 timestamp_scaler_->Reset();
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000523
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000524 // Trigger an update of sampling rate and the number of channels.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000525 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000526 }
527
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000528 // Update RTCP statistics, only for regular packets.
529 if (!is_sync_packet)
530 rtcp_.Update(main_header, receive_timestamp);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000531
532 // Check for RED payload type, and separate payloads into several packets.
533 if (decoder_database_->IsRed(main_header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000534 assert(!is_sync_packet); // We had a sanity check for this.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000535 if (payload_splitter_->SplitRed(&packet_list) != PayloadSplitter::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000536 PacketBuffer::DeleteAllPackets(&packet_list);
537 return kRedundancySplitError;
538 }
539 // Only accept a few RED payloads of the same type as the main data,
540 // DTMF events and CNG.
541 payload_splitter_->CheckRedPayloads(&packet_list, *decoder_database_);
542 // Update the stored main payload header since the main payload has now
543 // changed.
544 memcpy(&main_header, &packet_list.front()->header, sizeof(main_header));
545 }
546
547 // Check payload types.
548 if (decoder_database_->CheckPayloadTypes(packet_list) ==
549 DecoderDatabase::kDecoderNotFound) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000550 PacketBuffer::DeleteAllPackets(&packet_list);
551 return kUnknownRtpPayloadType;
552 }
553
554 // Scale timestamp to internal domain (only for some codecs).
555 timestamp_scaler_->ToInternal(&packet_list);
556
557 // Process DTMF payloads. Cycle through the list of packets, and pick out any
558 // DTMF payloads found.
559 PacketList::iterator it = packet_list.begin();
560 while (it != packet_list.end()) {
561 Packet* current_packet = (*it);
562 assert(current_packet);
563 assert(current_packet->payload);
564 if (decoder_database_->IsDtmf(current_packet->header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000565 assert(!current_packet->sync_packet); // We had a sanity check for this.
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000566 DtmfEvent event;
567 int ret = DtmfBuffer::ParseEvent(
568 current_packet->header.timestamp,
569 current_packet->payload,
570 current_packet->payload_length,
571 &event);
572 if (ret != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000573 PacketBuffer::DeleteAllPackets(&packet_list);
574 return kDtmfParsingError;
575 }
576 if (dtmf_buffer_->InsertEvent(event) != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000577 PacketBuffer::DeleteAllPackets(&packet_list);
578 return kDtmfInsertError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000579 }
580 // TODO(hlundin): Let the destructor of Packet handle the payload.
581 delete [] current_packet->payload;
582 delete current_packet;
583 it = packet_list.erase(it);
584 } else {
585 ++it;
586 }
587 }
588
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000589 // Check for FEC in packets, and separate payloads into several packets.
590 int ret = payload_splitter_->SplitFec(&packet_list, decoder_database_.get());
591 if (ret != PayloadSplitter::kOK) {
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000592 PacketBuffer::DeleteAllPackets(&packet_list);
593 switch (ret) {
594 case PayloadSplitter::kUnknownPayloadType:
595 return kUnknownRtpPayloadType;
596 default:
597 return kOtherError;
598 }
599 }
600
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000601 // Split payloads into smaller chunks. This also verifies that all payloads
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000602 // are of a known payload type. SplitAudio() method is protected against
603 // sync-packets.
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +0000604 ret = payload_splitter_->SplitAudio(&packet_list, *decoder_database_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000605 if (ret != PayloadSplitter::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000606 PacketBuffer::DeleteAllPackets(&packet_list);
607 switch (ret) {
608 case PayloadSplitter::kUnknownPayloadType:
609 return kUnknownRtpPayloadType;
610 case PayloadSplitter::kFrameSplitError:
611 return kFrameSplitError;
612 default:
613 return kOtherError;
614 }
615 }
616
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000617 // Update bandwidth estimate, if the packet is not sync-packet.
618 if (!packet_list.empty() && !packet_list.front()->sync_packet) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000619 // The list can be empty here if we got nothing but DTMF payloads.
620 AudioDecoder* decoder =
621 decoder_database_->GetDecoder(main_header.payloadType);
622 assert(decoder); // Should always get a valid object, since we have
623 // already checked that the payload types are known.
624 decoder->IncomingPacket(packet_list.front()->payload,
625 packet_list.front()->payload_length,
626 packet_list.front()->header.sequenceNumber,
627 packet_list.front()->header.timestamp,
628 receive_timestamp);
629 }
630
henrik.lundin48ed9302015-10-29 05:36:24 -0700631 if (nack_enabled_) {
632 RTC_DCHECK(nack_);
633 if (update_sample_rate_and_channels) {
634 nack_->Reset();
635 }
636 nack_->UpdateLastReceivedPacket(packet_list.front()->header.sequenceNumber,
637 packet_list.front()->header.timestamp);
638 }
639
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000640 // Insert packets in buffer.
henrik.lundin116c84e2015-08-27 13:14:48 -0700641 const size_t buffer_length_before_insert =
642 packet_buffer_->NumPacketsInBuffer();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000643 ret = packet_buffer_->InsertPacketList(
644 &packet_list,
645 *decoder_database_,
646 &current_rtp_payload_type_,
647 &current_cng_rtp_payload_type_);
648 if (ret == PacketBuffer::kFlushed) {
649 // Reset DSP timestamp etc. if packet buffer flushed.
650 new_codec_ = true;
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000651 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000652 } else if (ret != PacketBuffer::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000653 PacketBuffer::DeleteAllPackets(&packet_list);
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000654 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000655 }
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000656
657 if (first_packet_) {
658 first_packet_ = false;
659 // Update the codec on the next GetAudio call.
660 new_codec_ = true;
661 }
662
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000663 if (current_rtp_payload_type_ != 0xFF) {
664 const DecoderDatabase::DecoderInfo* dec_info =
665 decoder_database_->GetDecoderInfo(current_rtp_payload_type_);
666 if (!dec_info) {
667 assert(false); // Already checked that the payload type is known.
668 }
669 }
670
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000671 if (update_sample_rate_and_channels && !packet_buffer_->Empty()) {
672 // We do not use |current_rtp_payload_type_| to |set payload_type|, but
673 // get the next RTP header from |packet_buffer_| to obtain the payload type.
674 // The reason for it is the following corner case. If NetEq receives a
675 // CNG packet with a sample rate different than the current CNG then it
676 // flushes its buffer, assuming send codec must have been changed. However,
677 // payload type of the hypothetically new send codec is not known.
678 const RTPHeader* rtp_header = packet_buffer_->NextRtpHeader();
679 assert(rtp_header);
680 int payload_type = rtp_header->payloadType;
681 AudioDecoder* decoder = decoder_database_->GetDecoder(payload_type);
682 assert(decoder); // Payloads are already checked to be valid.
683 const DecoderDatabase::DecoderInfo* decoder_info =
684 decoder_database_->GetDecoderInfo(payload_type);
685 assert(decoder_info);
686 if (decoder_info->fs_hz != fs_hz_ ||
henrik.lundin48ed9302015-10-29 05:36:24 -0700687 decoder->Channels() != algorithm_buffer_->Channels()) {
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +0000688 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->Channels());
henrik.lundin48ed9302015-10-29 05:36:24 -0700689 }
690 if (nack_enabled_) {
691 RTC_DCHECK(nack_);
692 // Update the sample rate even if the rate is not new, because of Reset().
693 nack_->UpdateSampleRate(fs_hz_);
694 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000695 }
696
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000697 // TODO(hlundin): Move this code to DelayManager class.
698 const DecoderDatabase::DecoderInfo* dec_info =
699 decoder_database_->GetDecoderInfo(main_header.payloadType);
700 assert(dec_info); // Already checked that the payload type is known.
701 delay_manager_->LastDecoderType(dec_info->codec_type);
702 if (delay_manager_->last_pack_cng_or_dtmf() == 0) {
703 // Calculate the total speech length carried in each packet.
henrik.lundin116c84e2015-08-27 13:14:48 -0700704 const size_t buffer_length_after_insert =
705 packet_buffer_->NumPacketsInBuffer();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000706
henrik.lundin116c84e2015-08-27 13:14:48 -0700707 if (buffer_length_after_insert > buffer_length_before_insert) {
708 const size_t packet_length_samples =
709 (buffer_length_after_insert - buffer_length_before_insert) *
710 decoder_frame_length_;
711 if (packet_length_samples != decision_logic_->packet_length_samples()) {
712 decision_logic_->set_packet_length_samples(packet_length_samples);
713 delay_manager_->SetPacketAudioLength(
714 rtc::checked_cast<int>((1000 * packet_length_samples) / fs_hz_));
715 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000716 }
717
718 // Update statistics.
pbos@webrtc.org0946a562013-04-09 00:28:06 +0000719 if ((int32_t) (main_header.timestamp - timestamp_) >= 0 &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000720 !new_codec_) {
721 // Only update statistics if incoming packet is not older than last played
722 // out packet, and if new codec flag is not set.
723 delay_manager_->Update(main_header.sequenceNumber, main_header.timestamp,
724 fs_hz_);
725 }
726 } else if (delay_manager_->last_pack_cng_or_dtmf() == -1) {
727 // This is first "normal" packet after CNG or DTMF.
728 // Reset packet time counter and measure time until next packet,
729 // but don't update statistics.
730 delay_manager_->set_last_pack_cng_or_dtmf(0);
731 delay_manager_->ResetPacketIatCount();
732 }
733 return 0;
734}
735
Peter Kasting728d9032015-06-11 14:31:38 -0700736int NetEqImpl::GetAudioInternal(size_t max_length,
737 int16_t* output,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700738 size_t* samples_per_channel,
Peter Kasting728d9032015-06-11 14:31:38 -0700739 int* num_channels) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000740 PacketList packet_list;
741 DtmfEvent dtmf_event;
742 Operations operation;
743 bool play_dtmf;
744 int return_value = GetDecision(&operation, &packet_list, &dtmf_event,
745 &play_dtmf);
746 if (return_value != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000747 last_mode_ = kModeError;
748 return return_value;
749 }
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000750 LOG(LS_VERBOSE) << "GetDecision returned operation=" << operation <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000751 " and " << packet_list.size() << " packet(s)";
752
753 AudioDecoder::SpeechType speech_type;
754 int length = 0;
755 int decode_return_value = Decode(&packet_list, &operation,
756 &length, &speech_type);
757
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000758 assert(vad_.get());
759 bool sid_frame_available =
760 (operation == kRfc3389Cng && !packet_list.empty());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700761 vad_->Update(decoded_buffer_.get(), static_cast<size_t>(length), speech_type,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000762 sid_frame_available, fs_hz_);
763
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000764 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000765 switch (operation) {
766 case kNormal: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000767 DoNormal(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000768 break;
769 }
770 case kMerge: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000771 DoMerge(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000772 break;
773 }
774 case kExpand: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000775 return_value = DoExpand(play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000776 break;
777 }
Henrik Lundincf808d22015-05-27 14:33:29 +0200778 case kAccelerate:
779 case kFastAccelerate: {
780 const bool fast_accelerate =
781 enable_fast_accelerate_ && (operation == kFastAccelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000782 return_value = DoAccelerate(decoded_buffer_.get(), length, speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +0200783 play_dtmf, fast_accelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000784 break;
785 }
786 case kPreemptiveExpand: {
787 return_value = DoPreemptiveExpand(decoded_buffer_.get(), length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000788 speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000789 break;
790 }
791 case kRfc3389Cng:
792 case kRfc3389CngNoPacket: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000793 return_value = DoRfc3389Cng(&packet_list, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000794 break;
795 }
796 case kCodecInternalCng: {
797 // This handles the case when there is no transmission and the decoder
798 // should produce internal comfort noise.
799 // TODO(hlundin): Write test for codec-internal CNG.
minyuel6d92bf52015-09-23 15:20:39 +0200800 DoCodecInternalCng(decoded_buffer_.get(), length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000801 break;
802 }
803 case kDtmf: {
804 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000805 return_value = DoDtmf(dtmf_event, &play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000806 break;
807 }
808 case kAlternativePlc: {
809 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000810 DoAlternativePlc(false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000811 break;
812 }
813 case kAlternativePlcIncreaseTimestamp: {
814 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000815 DoAlternativePlc(true);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000816 break;
817 }
818 case kAudioRepetitionIncreaseTimestamp: {
819 // TODO(hlundin): Write test for this.
Peter Kastingb7e50542015-06-11 12:55:50 -0700820 sync_buffer_->IncreaseEndTimestamp(
821 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000822 // Skipping break on purpose. Execution should move on into the
823 // next case.
kjellander@webrtc.org7d2b6a92015-01-28 18:37:58 +0000824 FALLTHROUGH();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000825 }
826 case kAudioRepetition: {
827 // TODO(hlundin): Write test for this.
828 // Copy last |output_size_samples_| from |sync_buffer_| to
829 // |algorithm_buffer|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000830 algorithm_buffer_->PushBackFromIndex(
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000831 *sync_buffer_, sync_buffer_->Size() - output_size_samples_);
832 expand_->Reset();
833 break;
834 }
835 case kUndefined: {
Henrik Lundind67a2192015-08-03 12:54:37 +0200836 LOG(LS_ERROR) << "Invalid operation kUndefined.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000837 assert(false); // This should not happen.
838 last_mode_ = kModeError;
839 return kInvalidOperation;
840 }
841 } // End of switch.
842 if (return_value < 0) {
843 return return_value;
844 }
845
846 if (last_mode_ != kModeRfc3389Cng) {
847 comfort_noise_->Reset();
848 }
849
850 // Copy from |algorithm_buffer| to |sync_buffer_|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000851 sync_buffer_->PushBack(*algorithm_buffer_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000852
853 // Extract data from |sync_buffer_| to |output|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000854 size_t num_output_samples_per_channel = output_size_samples_;
855 size_t num_output_samples = output_size_samples_ * sync_buffer_->Channels();
856 if (num_output_samples > max_length) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000857 LOG(LS_WARNING) << "Output array is too short. " << max_length << " < " <<
858 output_size_samples_ << " * " << sync_buffer_->Channels();
859 num_output_samples = max_length;
Peter Kastingdce40cf2015-08-24 14:52:23 -0700860 num_output_samples_per_channel = max_length / sync_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000861 }
Peter Kastingdce40cf2015-08-24 14:52:23 -0700862 const size_t samples_from_sync =
863 sync_buffer_->GetNextAudioInterleaved(num_output_samples_per_channel,
864 output);
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000865 *num_channels = static_cast<int>(sync_buffer_->Channels());
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000866 LOG(LS_VERBOSE) << "Sync buffer (" << *num_channels << " channel(s)):" <<
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000867 " insert " << algorithm_buffer_->Size() << " samples, extract " <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000868 samples_from_sync << " samples";
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200869 if (sync_buffer_->FutureLength() < expand_->overlap_length()) {
870 // The sync buffer should always contain |overlap_length| samples, but now
871 // too many samples have been extracted. Reinstall the |overlap_length|
872 // lookahead by moving the index.
873 const size_t missing_lookahead_samples =
874 expand_->overlap_length() - sync_buffer_->FutureLength();
henrikg91d6ede2015-09-17 00:24:34 -0700875 RTC_DCHECK_GE(sync_buffer_->next_index(), missing_lookahead_samples);
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200876 sync_buffer_->set_next_index(sync_buffer_->next_index() -
877 missing_lookahead_samples);
878 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000879 if (samples_from_sync != output_size_samples_) {
Henrik Lundind67a2192015-08-03 12:54:37 +0200880 LOG(LS_ERROR) << "samples_from_sync (" << samples_from_sync
881 << ") != output_size_samples_ (" << output_size_samples_
882 << ")";
minyue@webrtc.orgdb1cefc2013-08-13 01:39:21 +0000883 // TODO(minyue): treatment of under-run, filling zeros
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000884 memset(output, 0, num_output_samples * sizeof(int16_t));
885 *samples_per_channel = output_size_samples_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000886 return kSampleUnderrun;
887 }
888 *samples_per_channel = output_size_samples_;
889
890 // Should always have overlap samples left in the |sync_buffer_|.
henrikg91d6ede2015-09-17 00:24:34 -0700891 RTC_DCHECK_GE(sync_buffer_->FutureLength(), expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000892
893 if (play_dtmf) {
894 return_value = DtmfOverdub(dtmf_event, sync_buffer_->Channels(), output);
895 }
896
897 // Update the background noise parameters if last operation wrote data
898 // straight from the decoder to the |sync_buffer_|. That is, none of the
899 // operations that modify the signal can be followed by a parameter update.
900 if ((last_mode_ == kModeNormal) ||
901 (last_mode_ == kModeAccelerateFail) ||
902 (last_mode_ == kModePreemptiveExpandFail) ||
903 (last_mode_ == kModeRfc3389Cng) ||
904 (last_mode_ == kModeCodecInternalCng)) {
905 background_noise_->Update(*sync_buffer_, *vad_.get());
906 }
907
908 if (operation == kDtmf) {
909 // DTMF data was written the end of |sync_buffer_|.
910 // Update index to end of DTMF data in |sync_buffer_|.
911 sync_buffer_->set_dtmf_index(sync_buffer_->Size());
912 }
913
henrik.lundin@webrtc.orged865b52014-03-06 10:28:07 +0000914 if (last_mode_ != kModeExpand) {
915 // If last operation was not expand, calculate the |playout_timestamp_| from
916 // the |sync_buffer_|. However, do not update the |playout_timestamp_| if it
917 // would be moved "backwards".
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000918 uint32_t temp_timestamp = sync_buffer_->end_timestamp() -
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000919 static_cast<uint32_t>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000920 if (static_cast<int32_t>(temp_timestamp - playout_timestamp_) > 0) {
921 playout_timestamp_ = temp_timestamp;
922 }
923 } else {
924 // Use dead reckoning to estimate the |playout_timestamp_|.
Peter Kastingb7e50542015-06-11 12:55:50 -0700925 playout_timestamp_ += static_cast<uint32_t>(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000926 }
927
928 if (decode_return_value) return decode_return_value;
929 return return_value;
930}
931
932int NetEqImpl::GetDecision(Operations* operation,
933 PacketList* packet_list,
934 DtmfEvent* dtmf_event,
935 bool* play_dtmf) {
936 // Initialize output variables.
937 *play_dtmf = false;
938 *operation = kUndefined;
939
940 // Increment time counters.
941 packet_buffer_->IncrementWaitingTimes();
942 stats_.IncreaseCounter(output_size_samples_, fs_hz_);
943
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000944 assert(sync_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000945 uint32_t end_timestamp = sync_buffer_->end_timestamp();
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +0000946 if (!new_codec_) {
947 const uint32_t five_seconds_samples = 5 * fs_hz_;
948 packet_buffer_->DiscardOldPackets(end_timestamp, five_seconds_samples);
949 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000950 const RTPHeader* header = packet_buffer_->NextRtpHeader();
951
henrik.lundin@webrtc.orgca8cb952014-03-12 10:26:52 +0000952 if (decision_logic_->CngRfc3389On() || last_mode_ == kModeRfc3389Cng) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000953 // Because of timestamp peculiarities, we have to "manually" disallow using
954 // a CNG packet with the same timestamp as the one that was last played.
955 // This can happen when using redundancy and will cause the timing to shift.
henrik.lundin@webrtc.org24779fe2014-03-14 12:40:05 +0000956 while (header && decoder_database_->IsComfortNoise(header->payloadType) &&
957 (end_timestamp >= header->timestamp ||
958 end_timestamp + decision_logic_->generated_noise_samples() >
959 header->timestamp)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000960 // Don't use this packet, discard it.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000961 if (packet_buffer_->DiscardNextPacket() != PacketBuffer::kOK) {
962 assert(false); // Must be ok by design.
963 }
964 // Check buffer again.
965 if (!new_codec_) {
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +0000966 packet_buffer_->DiscardOldPackets(end_timestamp, 5 * fs_hz_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000967 }
968 header = packet_buffer_->NextRtpHeader();
969 }
970 }
971
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000972 assert(expand_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000973 const int samples_left = static_cast<int>(sync_buffer_->FutureLength() -
974 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000975 if (last_mode_ == kModeAccelerateSuccess ||
976 last_mode_ == kModeAccelerateLowEnergy ||
977 last_mode_ == kModePreemptiveExpandSuccess ||
978 last_mode_ == kModePreemptiveExpandLowEnergy) {
979 // Subtract (samples_left + output_size_samples_) from sampleMemory.
Peter Kastingdce40cf2015-08-24 14:52:23 -0700980 decision_logic_->AddSampleMemory(
981 -(samples_left + rtc::checked_cast<int>(output_size_samples_)));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000982 }
983
984 // Check if it is time to play a DTMF event.
Peter Kastingb7e50542015-06-11 12:55:50 -0700985 if (dtmf_buffer_->GetEvent(
986 static_cast<uint32_t>(
987 end_timestamp + decision_logic_->generated_noise_samples()),
988 dtmf_event)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000989 *play_dtmf = true;
990 }
991
992 // Get instruction.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000993 assert(sync_buffer_.get());
994 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000995 *operation = decision_logic_->GetDecision(*sync_buffer_,
996 *expand_,
997 decoder_frame_length_,
998 header,
999 last_mode_,
1000 *play_dtmf,
1001 &reset_decoder_);
1002
1003 // Check if we already have enough samples in the |sync_buffer_|. If so,
1004 // change decision to normal, unless the decision was merge, accelerate, or
1005 // preemptive expand.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001006 if (samples_left >= rtc::checked_cast<int>(output_size_samples_) &&
1007 *operation != kMerge &&
1008 *operation != kAccelerate &&
1009 *operation != kFastAccelerate &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001010 *operation != kPreemptiveExpand) {
1011 *operation = kNormal;
1012 return 0;
1013 }
1014
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001015 decision_logic_->ExpandDecision(*operation);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001016
1017 // Check conditions for reset.
1018 if (new_codec_ || *operation == kUndefined) {
1019 // The only valid reason to get kUndefined is that new_codec_ is set.
1020 assert(new_codec_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001021 if (*play_dtmf && !header) {
1022 timestamp_ = dtmf_event->timestamp;
1023 } else {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001024 if (!header) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001025 LOG(LS_ERROR) << "Packet missing where it shouldn't.";
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001026 return -1;
1027 }
1028 timestamp_ = header->timestamp;
1029 if (*operation == kRfc3389CngNoPacket
1030#ifndef LEGACY_BITEXACT
1031 // Without this check, it can happen that a non-CNG packet is sent to
1032 // the CNG decoder as if it was a SID frame. This is clearly a bug,
1033 // but is kept for now to maintain bit-exactness with the test
1034 // vectors.
1035 && decoder_database_->IsComfortNoise(header->payloadType)
1036#endif
1037 ) {
1038 // Change decision to CNG packet, since we do have a CNG packet, but it
1039 // was considered too early to use. Now, use it anyway.
1040 *operation = kRfc3389Cng;
1041 } else if (*operation != kRfc3389Cng) {
1042 *operation = kNormal;
1043 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001044 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001045 // Adjust |sync_buffer_| timestamp before setting |end_timestamp| to the
1046 // new value.
1047 sync_buffer_->IncreaseEndTimestamp(timestamp_ - end_timestamp);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001048 end_timestamp = timestamp_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001049 new_codec_ = false;
1050 decision_logic_->SoftReset();
1051 buffer_level_filter_->Reset();
1052 delay_manager_->Reset();
1053 stats_.ResetMcu();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001054 }
1055
Peter Kastingdce40cf2015-08-24 14:52:23 -07001056 size_t required_samples = output_size_samples_;
1057 const size_t samples_10_ms = static_cast<size_t>(80 * fs_mult_);
1058 const size_t samples_20_ms = 2 * samples_10_ms;
1059 const size_t samples_30_ms = 3 * samples_10_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001060
1061 switch (*operation) {
1062 case kExpand: {
1063 timestamp_ = end_timestamp;
1064 return 0;
1065 }
1066 case kRfc3389CngNoPacket:
1067 case kCodecInternalCng: {
1068 return 0;
1069 }
1070 case kDtmf: {
1071 // TODO(hlundin): Write test for this.
1072 // Update timestamp.
1073 timestamp_ = end_timestamp;
1074 if (decision_logic_->generated_noise_samples() > 0 &&
1075 last_mode_ != kModeDtmf) {
1076 // Make a jump in timestamp due to the recently played comfort noise.
Peter Kastingb7e50542015-06-11 12:55:50 -07001077 uint32_t timestamp_jump =
1078 static_cast<uint32_t>(decision_logic_->generated_noise_samples());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001079 sync_buffer_->IncreaseEndTimestamp(timestamp_jump);
1080 timestamp_ += timestamp_jump;
1081 }
1082 decision_logic_->set_generated_noise_samples(0);
1083 return 0;
1084 }
Henrik Lundincf808d22015-05-27 14:33:29 +02001085 case kAccelerate:
1086 case kFastAccelerate: {
1087 // In order to do an accelerate we need at least 30 ms of audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001088 if (samples_left >= static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001089 // Already have enough data, so we do not need to extract any more.
1090 decision_logic_->set_sample_memory(samples_left);
1091 decision_logic_->set_prev_time_scale(true);
1092 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001093 } else if (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001094 decoder_frame_length_ >= samples_30_ms) {
1095 // Avoid decoding more data as it might overflow the playout buffer.
1096 *operation = kNormal;
1097 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001098 } else if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001099 decoder_frame_length_ < samples_30_ms) {
1100 // Build up decoded data by decoding at least 20 ms of audio data. Do
1101 // not perform accelerate yet, but wait until we only need to do one
1102 // decoding.
1103 required_samples = 2 * output_size_samples_;
1104 *operation = kNormal;
1105 }
1106 // If none of the above is true, we have one of two possible situations:
1107 // (1) 20 ms <= samples_left < 30 ms and decoder_frame_length_ < 30 ms; or
1108 // (2) samples_left < 10 ms and decoder_frame_length_ >= 30 ms.
1109 // In either case, we move on with the accelerate decision, and decode one
1110 // frame now.
1111 break;
1112 }
1113 case kPreemptiveExpand: {
1114 // In order to do a preemptive expand we need at least 30 ms of decoded
1115 // audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001116 if ((samples_left >= static_cast<int>(samples_30_ms)) ||
1117 (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001118 decoder_frame_length_ >= samples_30_ms)) {
1119 // Already have enough data, so we do not need to extract any more.
1120 // Or, avoid decoding more data as it might overflow the playout buffer.
1121 // Still try preemptive expand, though.
1122 decision_logic_->set_sample_memory(samples_left);
1123 decision_logic_->set_prev_time_scale(true);
1124 return 0;
1125 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07001126 if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001127 decoder_frame_length_ < samples_30_ms) {
1128 // Build up decoded data by decoding at least 20 ms of audio data.
1129 // Still try to perform preemptive expand.
1130 required_samples = 2 * output_size_samples_;
1131 }
1132 // Move on with the preemptive expand decision.
1133 break;
1134 }
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001135 case kMerge: {
1136 required_samples =
1137 std::max(merge_->RequiredFutureSamples(), required_samples);
1138 break;
1139 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001140 default: {
1141 // Do nothing.
1142 }
1143 }
1144
1145 // Get packets from buffer.
1146 int extracted_samples = 0;
1147 if (header &&
1148 *operation != kAlternativePlc &&
1149 *operation != kAlternativePlcIncreaseTimestamp &&
1150 *operation != kAudioRepetition &&
1151 *operation != kAudioRepetitionIncreaseTimestamp) {
1152 sync_buffer_->IncreaseEndTimestamp(header->timestamp - end_timestamp);
1153 if (decision_logic_->CngOff()) {
1154 // Adjustment of timestamp only corresponds to an actual packet loss
1155 // if comfort noise is not played. If comfort noise was just played,
1156 // this adjustment of timestamp is only done to get back in sync with the
1157 // stream timestamp; no loss to report.
1158 stats_.LostSamples(header->timestamp - end_timestamp);
1159 }
1160
1161 if (*operation != kRfc3389Cng) {
1162 // We are about to decode and use a non-CNG packet.
1163 decision_logic_->SetCngOff();
1164 }
1165 // Reset CNG timestamp as a new packet will be delivered.
1166 // (Also if this is a CNG packet, since playedOutTS is updated.)
1167 decision_logic_->set_generated_noise_samples(0);
1168
1169 extracted_samples = ExtractPackets(required_samples, packet_list);
1170 if (extracted_samples < 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001171 return kPacketBufferCorruption;
1172 }
1173 }
1174
Henrik Lundincf808d22015-05-27 14:33:29 +02001175 if (*operation == kAccelerate || *operation == kFastAccelerate ||
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001176 *operation == kPreemptiveExpand) {
1177 decision_logic_->set_sample_memory(samples_left + extracted_samples);
1178 decision_logic_->set_prev_time_scale(true);
1179 }
1180
Henrik Lundincf808d22015-05-27 14:33:29 +02001181 if (*operation == kAccelerate || *operation == kFastAccelerate) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001182 // Check that we have enough data (30ms) to do accelerate.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001183 if (extracted_samples + samples_left < static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001184 // TODO(hlundin): Write test for this.
1185 // Not enough, do normal operation instead.
1186 *operation = kNormal;
1187 }
1188 }
1189
1190 timestamp_ = end_timestamp;
1191 return 0;
1192}
1193
1194int NetEqImpl::Decode(PacketList* packet_list, Operations* operation,
1195 int* decoded_length,
1196 AudioDecoder::SpeechType* speech_type) {
1197 *speech_type = AudioDecoder::kSpeech;
minyuel6d92bf52015-09-23 15:20:39 +02001198
1199 // When packet_list is empty, we may be in kCodecInternalCng mode, and for
1200 // that we use current active decoder.
1201 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1202
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001203 if (!packet_list->empty()) {
1204 const Packet* packet = packet_list->front();
pkasting@chromium.org0e81fdf2015-02-02 23:54:03 +00001205 uint8_t payload_type = packet->header.payloadType;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001206 if (!decoder_database_->IsComfortNoise(payload_type)) {
1207 decoder = decoder_database_->GetDecoder(payload_type);
1208 assert(decoder);
1209 if (!decoder) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001210 LOG(LS_WARNING) << "Unknown payload type "
1211 << static_cast<int>(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001212 PacketBuffer::DeleteAllPackets(packet_list);
1213 return kDecoderNotFound;
1214 }
1215 bool decoder_changed;
1216 decoder_database_->SetActiveDecoder(payload_type, &decoder_changed);
1217 if (decoder_changed) {
1218 // We have a new decoder. Re-init some values.
1219 const DecoderDatabase::DecoderInfo* decoder_info = decoder_database_
1220 ->GetDecoderInfo(payload_type);
1221 assert(decoder_info);
1222 if (!decoder_info) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001223 LOG(LS_WARNING) << "Unknown payload type "
1224 << static_cast<int>(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001225 PacketBuffer::DeleteAllPackets(packet_list);
1226 return kDecoderNotFound;
1227 }
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001228 // If sampling rate or number of channels has changed, we need to make
1229 // a reset.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001230 if (decoder_info->fs_hz != fs_hz_ ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001231 decoder->Channels() != algorithm_buffer_->Channels()) {
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001232 // TODO(tlegrand): Add unittest to cover this event.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001233 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->Channels());
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001234 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001235 sync_buffer_->set_end_timestamp(timestamp_);
1236 playout_timestamp_ = timestamp_;
1237 }
1238 }
1239 }
1240
1241 if (reset_decoder_) {
1242 // TODO(hlundin): Write test for this.
Karl Wiberg43766482015-08-27 15:22:11 +02001243 if (decoder)
1244 decoder->Reset();
1245
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001246 // Reset comfort noise decoder.
1247 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02001248 if (cng_decoder)
1249 cng_decoder->Reset();
1250
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001251 reset_decoder_ = false;
1252 }
1253
1254#ifdef LEGACY_BITEXACT
1255 // Due to a bug in old SignalMCU, it could happen that CNG operation was
1256 // decided, but a speech packet was provided. The speech packet will be used
1257 // to update the comfort noise decoder, as if it was a SID frame, which is
1258 // clearly wrong.
1259 if (*operation == kRfc3389Cng) {
1260 return 0;
1261 }
1262#endif
1263
1264 *decoded_length = 0;
1265 // Update codec-internal PLC state.
1266 if ((*operation == kMerge) && decoder && decoder->HasDecodePlc()) {
1267 decoder->DecodePlc(1, &decoded_buffer_[*decoded_length]);
1268 }
1269
minyuel6d92bf52015-09-23 15:20:39 +02001270 int return_value;
1271 if (*operation == kCodecInternalCng) {
1272 RTC_DCHECK(packet_list->empty());
1273 return_value = DecodeCng(decoder, decoded_length, speech_type);
1274 } else {
1275 return_value = DecodeLoop(packet_list, *operation, decoder,
1276 decoded_length, speech_type);
1277 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001278
1279 if (*decoded_length < 0) {
1280 // Error returned from the decoder.
1281 *decoded_length = 0;
Peter Kastingb7e50542015-06-11 12:55:50 -07001282 sync_buffer_->IncreaseEndTimestamp(
1283 static_cast<uint32_t>(decoder_frame_length_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001284 int error_code = 0;
1285 if (decoder)
1286 error_code = decoder->ErrorCode();
1287 if (error_code != 0) {
1288 // Got some error code from the decoder.
1289 decoder_error_code_ = error_code;
1290 return_value = kDecoderErrorCode;
Henrik Lundind67a2192015-08-03 12:54:37 +02001291 LOG(LS_WARNING) << "Decoder returned error code: " << error_code;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001292 } else {
1293 // Decoder does not implement error codes. Return generic error.
1294 return_value = kOtherDecoderError;
Henrik Lundind67a2192015-08-03 12:54:37 +02001295 LOG(LS_WARNING) << "Decoder error (no error code)";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001296 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001297 *operation = kExpand; // Do expansion to get data instead.
1298 }
1299 if (*speech_type != AudioDecoder::kComfortNoise) {
1300 // Don't increment timestamp if codec returned CNG speech type
1301 // since in this case, the we will increment the CNGplayedTS counter.
1302 // Increase with number of samples per channel.
1303 assert(*decoded_length == 0 ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001304 (decoder && decoder->Channels() == sync_buffer_->Channels()));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001305 sync_buffer_->IncreaseEndTimestamp(
1306 *decoded_length / static_cast<int>(sync_buffer_->Channels()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001307 }
1308 return return_value;
1309}
1310
minyuel6d92bf52015-09-23 15:20:39 +02001311int NetEqImpl::DecodeCng(AudioDecoder* decoder, int* decoded_length,
1312 AudioDecoder::SpeechType* speech_type) {
1313 if (!decoder) {
1314 // This happens when active decoder is not defined.
1315 *decoded_length = -1;
1316 return 0;
1317 }
1318
1319 while (*decoded_length < rtc::checked_cast<int>(output_size_samples_)) {
1320 const int length = decoder->Decode(
1321 nullptr, 0, fs_hz_,
1322 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1323 &decoded_buffer_[*decoded_length], speech_type);
1324 if (length > 0) {
1325 *decoded_length += length;
1326 LOG(LS_VERBOSE) << "Decoded " << length << " CNG samples";
1327 } else {
1328 // Error.
1329 LOG(LS_WARNING) << "Failed to decode CNG";
1330 *decoded_length = -1;
1331 break;
1332 }
1333 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1334 // Guard against overflow.
1335 LOG(LS_WARNING) << "Decoded too much CNG.";
1336 return kDecodedTooMuch;
1337 }
1338 }
1339 return 0;
1340}
1341
1342int NetEqImpl::DecodeLoop(PacketList* packet_list, const Operations& operation,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001343 AudioDecoder* decoder, int* decoded_length,
1344 AudioDecoder::SpeechType* speech_type) {
1345 Packet* packet = NULL;
1346 if (!packet_list->empty()) {
1347 packet = packet_list->front();
1348 }
minyuel6d92bf52015-09-23 15:20:39 +02001349
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001350 // Do decoding.
1351 while (packet &&
1352 !decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1353 assert(decoder); // At this point, we must have a decoder object.
1354 // The number of channels in the |sync_buffer_| should be the same as the
1355 // number decoder channels.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001356 assert(sync_buffer_->Channels() == decoder->Channels());
1357 assert(decoded_buffer_length_ >= kMaxFrameSize * decoder->Channels());
minyuel6d92bf52015-09-23 15:20:39 +02001358 assert(operation == kNormal || operation == kAccelerate ||
1359 operation == kFastAccelerate || operation == kMerge ||
1360 operation == kPreemptiveExpand);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001361 packet_list->pop_front();
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001362 size_t payload_length = packet->payload_length;
Peter Kasting36b7cc32015-06-11 19:57:18 -07001363 int decode_length;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +00001364 if (packet->sync_packet) {
1365 // Decode to silence with the same frame size as the last decode.
1366 LOG(LS_VERBOSE) << "Decoding sync-packet: " <<
1367 " ts=" << packet->header.timestamp <<
1368 ", sn=" << packet->header.sequenceNumber <<
1369 ", pt=" << static_cast<int>(packet->header.payloadType) <<
1370 ", ssrc=" << packet->header.ssrc <<
1371 ", len=" << packet->payload_length;
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001372 memset(&decoded_buffer_[*decoded_length], 0,
1373 decoder_frame_length_ * decoder->Channels() *
1374 sizeof(decoded_buffer_[0]));
Peter Kastingdce40cf2015-08-24 14:52:23 -07001375 decode_length = rtc::checked_cast<int>(decoder_frame_length_);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +00001376 } else if (!packet->primary) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001377 // This is a redundant payload; call the special decoder method.
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +00001378 LOG(LS_VERBOSE) << "Decoding packet (redundant):" <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001379 " ts=" << packet->header.timestamp <<
1380 ", sn=" << packet->header.sequenceNumber <<
1381 ", pt=" << static_cast<int>(packet->header.payloadType) <<
1382 ", ssrc=" << packet->header.ssrc <<
1383 ", len=" << packet->payload_length;
1384 decode_length = decoder->DecodeRedundant(
henrik.lundin@webrtc.org1eda4e32015-02-25 10:02:29 +00001385 packet->payload, packet->payload_length, fs_hz_,
minyue@webrtc.org7f7d7e32015-03-16 12:30:37 +00001386 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001387 &decoded_buffer_[*decoded_length], speech_type);
1388 } else {
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +00001389 LOG(LS_VERBOSE) << "Decoding packet: ts=" << packet->header.timestamp <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001390 ", sn=" << packet->header.sequenceNumber <<
1391 ", pt=" << static_cast<int>(packet->header.payloadType) <<
1392 ", ssrc=" << packet->header.ssrc <<
1393 ", len=" << packet->payload_length;
henrik.lundin@webrtc.org1eda4e32015-02-25 10:02:29 +00001394 decode_length =
minyue@webrtc.org7f7d7e32015-03-16 12:30:37 +00001395 decoder->Decode(
1396 packet->payload, packet->payload_length, fs_hz_,
1397 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1398 &decoded_buffer_[*decoded_length], speech_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001399 }
1400
1401 delete[] packet->payload;
1402 delete packet;
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001403 packet = NULL;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001404 if (decode_length > 0) {
1405 *decoded_length += decode_length;
1406 // Update |decoder_frame_length_| with number of samples per channel.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001407 decoder_frame_length_ =
Peter Kastingdce40cf2015-08-24 14:52:23 -07001408 static_cast<size_t>(decode_length) / decoder->Channels();
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001409 LOG(LS_VERBOSE) << "Decoded " << decode_length << " samples ("
1410 << decoder->Channels() << " channel(s) -> "
1411 << decoder_frame_length_ << " samples per channel)";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001412 } else if (decode_length < 0) {
1413 // Error.
Henrik Lundind67a2192015-08-03 12:54:37 +02001414 LOG(LS_WARNING) << "Decode " << decode_length << " " << payload_length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001415 *decoded_length = -1;
1416 PacketBuffer::DeleteAllPackets(packet_list);
1417 break;
1418 }
1419 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1420 // Guard against overflow.
Henrik Lundind67a2192015-08-03 12:54:37 +02001421 LOG(LS_WARNING) << "Decoded too much.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001422 PacketBuffer::DeleteAllPackets(packet_list);
1423 return kDecodedTooMuch;
1424 }
1425 if (!packet_list->empty()) {
1426 packet = packet_list->front();
1427 } else {
1428 packet = NULL;
1429 }
1430 } // End of decode loop.
1431
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001432 // If the list is not empty at this point, either a decoding error terminated
1433 // the while-loop, or list must hold exactly one CNG packet.
1434 assert(packet_list->empty() || *decoded_length < 0 ||
1435 (packet_list->size() == 1 && packet &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001436 decoder_database_->IsComfortNoise(packet->header.payloadType)));
1437 return 0;
1438}
1439
1440void NetEqImpl::DoNormal(const int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001441 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001442 assert(normal_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001443 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001444 normal_->Process(decoded_buffer, decoded_length, last_mode_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001445 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001446 if (decoded_length != 0) {
1447 last_mode_ = kModeNormal;
1448 }
1449
1450 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1451 if ((speech_type == AudioDecoder::kComfortNoise)
1452 || ((last_mode_ == kModeCodecInternalCng)
1453 && (decoded_length == 0))) {
1454 // TODO(hlundin): Remove second part of || statement above.
1455 last_mode_ = kModeCodecInternalCng;
1456 }
1457
1458 if (!play_dtmf) {
1459 dtmf_tone_generator_->Reset();
1460 }
1461}
1462
1463void NetEqImpl::DoMerge(int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001464 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001465 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001466 assert(merge_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001467 size_t new_length = merge_->Process(decoded_buffer, decoded_length,
1468 mute_factor_array_.get(),
1469 algorithm_buffer_.get());
1470 size_t expand_length_correction = new_length -
1471 decoded_length / algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001472
1473 // Update in-call and post-call statistics.
1474 if (expand_->MuteFactor(0) == 0) {
1475 // Expand generates only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001476 stats_.ExpandedNoiseSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001477 } else {
1478 // Expansion generates more than only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001479 stats_.ExpandedVoiceSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001480 }
1481
1482 last_mode_ = kModeMerge;
1483 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1484 if (speech_type == AudioDecoder::kComfortNoise) {
1485 last_mode_ = kModeCodecInternalCng;
1486 }
1487 expand_->Reset();
1488 if (!play_dtmf) {
1489 dtmf_tone_generator_->Reset();
1490 }
1491}
1492
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001493int NetEqImpl::DoExpand(bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001494 while ((sync_buffer_->FutureLength() - expand_->overlap_length()) <
Peter Kastingdce40cf2015-08-24 14:52:23 -07001495 output_size_samples_) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001496 algorithm_buffer_->Clear();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001497 int return_value = expand_->Process(algorithm_buffer_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001498 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001499
1500 // Update in-call and post-call statistics.
1501 if (expand_->MuteFactor(0) == 0) {
1502 // Expand operation generates only noise.
1503 stats_.ExpandedNoiseSamples(length);
1504 } else {
1505 // Expand operation generates more than only noise.
1506 stats_.ExpandedVoiceSamples(length);
1507 }
1508
1509 last_mode_ = kModeExpand;
1510
1511 if (return_value < 0) {
1512 return return_value;
1513 }
1514
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001515 sync_buffer_->PushBack(*algorithm_buffer_);
1516 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001517 }
1518 if (!play_dtmf) {
1519 dtmf_tone_generator_->Reset();
1520 }
1521 return 0;
1522}
1523
Henrik Lundincf808d22015-05-27 14:33:29 +02001524int NetEqImpl::DoAccelerate(int16_t* decoded_buffer,
1525 size_t decoded_length,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001526 AudioDecoder::SpeechType speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +02001527 bool play_dtmf,
1528 bool fast_accelerate) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001529 const size_t required_samples =
1530 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001531 size_t borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001532 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001533 size_t decoded_length_per_channel = decoded_length / num_channels;
1534 if (decoded_length_per_channel < required_samples) {
1535 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001536 borrowed_samples_per_channel = static_cast<int>(required_samples -
1537 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001538 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1539 decoded_buffer,
1540 sizeof(int16_t) * decoded_length);
1541 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1542 decoded_buffer);
1543 decoded_length = required_samples * num_channels;
1544 }
1545
Peter Kastingdce40cf2015-08-24 14:52:23 -07001546 size_t samples_removed;
Henrik Lundincf808d22015-05-27 14:33:29 +02001547 Accelerate::ReturnCodes return_code =
1548 accelerate_->Process(decoded_buffer, decoded_length, fast_accelerate,
1549 algorithm_buffer_.get(), &samples_removed);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001550 stats_.AcceleratedSamples(samples_removed);
1551 switch (return_code) {
1552 case Accelerate::kSuccess:
1553 last_mode_ = kModeAccelerateSuccess;
1554 break;
1555 case Accelerate::kSuccessLowEnergy:
1556 last_mode_ = kModeAccelerateLowEnergy;
1557 break;
1558 case Accelerate::kNoStretch:
1559 last_mode_ = kModeAccelerateFail;
1560 break;
1561 case Accelerate::kError:
1562 // TODO(hlundin): Map to kModeError instead?
1563 last_mode_ = kModeAccelerateFail;
1564 return kAccelerateError;
1565 }
1566
1567 if (borrowed_samples_per_channel > 0) {
1568 // Copy borrowed samples back to the |sync_buffer_|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001569 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001570 if (length < borrowed_samples_per_channel) {
1571 // This destroys the beginning of the buffer, but will not cause any
1572 // problems.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001573 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001574 sync_buffer_->Size() -
1575 borrowed_samples_per_channel);
1576 sync_buffer_->PushFrontZeros(borrowed_samples_per_channel - length);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001577 algorithm_buffer_->PopFront(length);
1578 assert(algorithm_buffer_->Empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001579 } else {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001580 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001581 borrowed_samples_per_channel,
1582 sync_buffer_->Size() -
1583 borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001584 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001585 }
1586 }
1587
1588 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1589 if (speech_type == AudioDecoder::kComfortNoise) {
1590 last_mode_ = kModeCodecInternalCng;
1591 }
1592 if (!play_dtmf) {
1593 dtmf_tone_generator_->Reset();
1594 }
1595 expand_->Reset();
1596 return 0;
1597}
1598
1599int NetEqImpl::DoPreemptiveExpand(int16_t* decoded_buffer,
1600 size_t decoded_length,
1601 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001602 bool play_dtmf) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001603 const size_t required_samples =
1604 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001605 size_t num_channels = algorithm_buffer_->Channels();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001606 size_t borrowed_samples_per_channel = 0;
1607 size_t old_borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001608 size_t decoded_length_per_channel = decoded_length / num_channels;
1609 if (decoded_length_per_channel < required_samples) {
1610 // Must move data from the |sync_buffer_| in order to get 30 ms.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001611 borrowed_samples_per_channel =
1612 required_samples - decoded_length_per_channel;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001613 // Calculate how many of these were already played out.
Peter Kastingf045e4d2015-06-10 21:15:38 -07001614 old_borrowed_samples_per_channel =
Peter Kastingdce40cf2015-08-24 14:52:23 -07001615 (borrowed_samples_per_channel > sync_buffer_->FutureLength()) ?
1616 (borrowed_samples_per_channel - sync_buffer_->FutureLength()) : 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001617 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1618 decoded_buffer,
1619 sizeof(int16_t) * decoded_length);
1620 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1621 decoded_buffer);
1622 decoded_length = required_samples * num_channels;
1623 }
1624
Peter Kastingdce40cf2015-08-24 14:52:23 -07001625 size_t samples_added;
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001626 PreemptiveExpand::ReturnCodes return_code = preemptive_expand_->Process(
Peter Kastingdce40cf2015-08-24 14:52:23 -07001627 decoded_buffer, decoded_length,
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001628 old_borrowed_samples_per_channel,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001629 algorithm_buffer_.get(), &samples_added);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001630 stats_.PreemptiveExpandedSamples(samples_added);
1631 switch (return_code) {
1632 case PreemptiveExpand::kSuccess:
1633 last_mode_ = kModePreemptiveExpandSuccess;
1634 break;
1635 case PreemptiveExpand::kSuccessLowEnergy:
1636 last_mode_ = kModePreemptiveExpandLowEnergy;
1637 break;
1638 case PreemptiveExpand::kNoStretch:
1639 last_mode_ = kModePreemptiveExpandFail;
1640 break;
1641 case PreemptiveExpand::kError:
1642 // TODO(hlundin): Map to kModeError instead?
1643 last_mode_ = kModePreemptiveExpandFail;
1644 return kPreemptiveExpandError;
1645 }
1646
1647 if (borrowed_samples_per_channel > 0) {
1648 // Copy borrowed samples back to the |sync_buffer_|.
1649 sync_buffer_->ReplaceAtIndex(
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001650 *algorithm_buffer_, borrowed_samples_per_channel,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001651 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001652 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001653 }
1654
1655 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1656 if (speech_type == AudioDecoder::kComfortNoise) {
1657 last_mode_ = kModeCodecInternalCng;
1658 }
1659 if (!play_dtmf) {
1660 dtmf_tone_generator_->Reset();
1661 }
1662 expand_->Reset();
1663 return 0;
1664}
1665
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001666int NetEqImpl::DoRfc3389Cng(PacketList* packet_list, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001667 if (!packet_list->empty()) {
1668 // Must have exactly one SID frame at this point.
1669 assert(packet_list->size() == 1);
1670 Packet* packet = packet_list->front();
1671 packet_list->pop_front();
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001672 if (!decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1673#ifdef LEGACY_BITEXACT
1674 // This can happen due to a bug in GetDecision. Change the payload type
1675 // to a CNG type, and move on. Note that this means that we are in fact
1676 // sending a non-CNG payload to the comfort noise decoder for decoding.
1677 // Clearly wrong, but will maintain bit-exactness with legacy.
1678 if (fs_hz_ == 8000) {
1679 packet->header.payloadType =
1680 decoder_database_->GetRtpPayloadType(kDecoderCNGnb);
1681 } else if (fs_hz_ == 16000) {
1682 packet->header.payloadType =
1683 decoder_database_->GetRtpPayloadType(kDecoderCNGwb);
1684 } else if (fs_hz_ == 32000) {
1685 packet->header.payloadType =
1686 decoder_database_->GetRtpPayloadType(kDecoderCNGswb32kHz);
1687 } else if (fs_hz_ == 48000) {
1688 packet->header.payloadType =
1689 decoder_database_->GetRtpPayloadType(kDecoderCNGswb48kHz);
1690 }
1691 assert(decoder_database_->IsComfortNoise(packet->header.payloadType));
1692#else
1693 LOG(LS_ERROR) << "Trying to decode non-CNG payload as CNG.";
1694 return kOtherError;
1695#endif
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001696 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001697 // UpdateParameters() deletes |packet|.
1698 if (comfort_noise_->UpdateParameters(packet) ==
1699 ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001700 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001701 return -comfort_noise_->internal_error_code();
1702 }
1703 }
1704 int cn_return = comfort_noise_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001705 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001706 expand_->Reset();
1707 last_mode_ = kModeRfc3389Cng;
1708 if (!play_dtmf) {
1709 dtmf_tone_generator_->Reset();
1710 }
1711 if (cn_return == ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001712 decoder_error_code_ = comfort_noise_->internal_error_code();
1713 return kComfortNoiseErrorCode;
1714 } else if (cn_return == ComfortNoise::kUnknownPayloadType) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001715 return kUnknownRtpPayloadType;
1716 }
1717 return 0;
1718}
1719
minyuel6d92bf52015-09-23 15:20:39 +02001720void NetEqImpl::DoCodecInternalCng(const int16_t* decoded_buffer,
1721 size_t decoded_length) {
1722 RTC_DCHECK(normal_.get());
1723 RTC_DCHECK(mute_factor_array_.get());
1724 normal_->Process(decoded_buffer, decoded_length, last_mode_,
1725 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001726 last_mode_ = kModeCodecInternalCng;
1727 expand_->Reset();
1728}
1729
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001730int NetEqImpl::DoDtmf(const DtmfEvent& dtmf_event, bool* play_dtmf) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001731 // This block of the code and the block further down, handling |dtmf_switch|
1732 // are commented out. Otherwise playing out-of-band DTMF would fail in VoE
1733 // test, DtmfTest.ManualSuccessfullySendsOutOfBandTelephoneEvents. This is
1734 // equivalent to |dtmf_switch| always be false.
1735 //
1736 // See http://webrtc-codereview.appspot.com/1195004/ for discussion
1737 // On this issue. This change might cause some glitches at the point of
1738 // switch from audio to DTMF. Issue 1545 is filed to track this.
1739 //
1740 // bool dtmf_switch = false;
1741 // if ((last_mode_ != kModeDtmf) && dtmf_tone_generator_->initialized()) {
1742 // // Special case; see below.
1743 // // We must catch this before calling Generate, since |initialized| is
1744 // // modified in that call.
1745 // dtmf_switch = true;
1746 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001747
1748 int dtmf_return_value = 0;
1749 if (!dtmf_tone_generator_->initialized()) {
1750 // Initialize if not already done.
1751 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1752 dtmf_event.volume);
1753 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001754
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001755 if (dtmf_return_value == 0) {
1756 // Generate DTMF signal.
1757 dtmf_return_value = dtmf_tone_generator_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001758 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001759 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001760
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001761 if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001762 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001763 return dtmf_return_value;
1764 }
1765
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001766 // if (dtmf_switch) {
1767 // // This is the special case where the previous operation was DTMF
1768 // // overdub, but the current instruction is "regular" DTMF. We must make
1769 // // sure that the DTMF does not have any discontinuities. The first DTMF
1770 // // sample that we generate now must be played out immediately, therefore
1771 // // it must be copied to the speech buffer.
1772 // // TODO(hlundin): This code seems incorrect. (Legacy.) Write test and
1773 // // verify correct operation.
1774 // assert(false);
1775 // // Must generate enough data to replace all of the |sync_buffer_|
1776 // // "future".
1777 // int required_length = sync_buffer_->FutureLength();
1778 // assert(dtmf_tone_generator_->initialized());
1779 // dtmf_return_value = dtmf_tone_generator_->Generate(required_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001780 // algorithm_buffer_);
1781 // assert((size_t) required_length == algorithm_buffer_->Size());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001782 // if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001783 // algorithm_buffer_->Zeros(output_size_samples_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001784 // return dtmf_return_value;
1785 // }
1786 //
1787 // // Overwrite the "future" part of the speech buffer with the new DTMF
1788 // // data.
1789 // // TODO(hlundin): It seems that this overwriting has gone lost.
1790 // // Not adapted for multi-channel yet.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001791 // assert(algorithm_buffer_->Channels() == 1);
1792 // if (algorithm_buffer_->Channels() != 1) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001793 // LOG(LS_WARNING) << "DTMF not supported for more than one channel";
1794 // return kStereoNotSupported;
1795 // }
1796 // // Shuffle the remaining data to the beginning of algorithm buffer.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001797 // algorithm_buffer_->PopFront(sync_buffer_->FutureLength());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001798 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001799
Peter Kastingb7e50542015-06-11 12:55:50 -07001800 sync_buffer_->IncreaseEndTimestamp(
1801 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001802 expand_->Reset();
1803 last_mode_ = kModeDtmf;
1804
1805 // Set to false because the DTMF is already in the algorithm buffer.
1806 *play_dtmf = false;
1807 return 0;
1808}
1809
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001810void NetEqImpl::DoAlternativePlc(bool increase_timestamp) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001811 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001812 size_t length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001813 if (decoder && decoder->HasDecodePlc()) {
1814 // Use the decoder's packet-loss concealment.
1815 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1816 int16_t decoded_buffer[kMaxFrameSize];
1817 length = decoder->DecodePlc(1, decoded_buffer);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001818 if (length > 0)
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001819 algorithm_buffer_->PushBackInterleaved(decoded_buffer, length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001820 } else {
1821 // Do simple zero-stuffing.
1822 length = output_size_samples_;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001823 algorithm_buffer_->Zeros(length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001824 // By not advancing the timestamp, NetEq inserts samples.
1825 stats_.AddZeros(length);
1826 }
1827 if (increase_timestamp) {
Peter Kastingb7e50542015-06-11 12:55:50 -07001828 sync_buffer_->IncreaseEndTimestamp(static_cast<uint32_t>(length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001829 }
1830 expand_->Reset();
1831}
1832
1833int NetEqImpl::DtmfOverdub(const DtmfEvent& dtmf_event, size_t num_channels,
1834 int16_t* output) const {
1835 size_t out_index = 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001836 size_t overdub_length = output_size_samples_; // Default value.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001837
1838 if (sync_buffer_->dtmf_index() > sync_buffer_->next_index()) {
1839 // Special operation for transition from "DTMF only" to "DTMF overdub".
1840 out_index = std::min(
1841 sync_buffer_->dtmf_index() - sync_buffer_->next_index(),
Peter Kastingdce40cf2015-08-24 14:52:23 -07001842 output_size_samples_);
1843 overdub_length = output_size_samples_ - out_index;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001844 }
1845
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001846 AudioMultiVector dtmf_output(num_channels);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001847 int dtmf_return_value = 0;
1848 if (!dtmf_tone_generator_->initialized()) {
1849 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1850 dtmf_event.volume);
1851 }
1852 if (dtmf_return_value == 0) {
1853 dtmf_return_value = dtmf_tone_generator_->Generate(overdub_length,
1854 &dtmf_output);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001855 assert(overdub_length == dtmf_output.Size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001856 }
1857 dtmf_output.ReadInterleaved(overdub_length, &output[out_index]);
1858 return dtmf_return_value < 0 ? dtmf_return_value : 0;
1859}
1860
Peter Kastingdce40cf2015-08-24 14:52:23 -07001861int NetEqImpl::ExtractPackets(size_t required_samples,
1862 PacketList* packet_list) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001863 bool first_packet = true;
1864 uint8_t prev_payload_type = 0;
1865 uint32_t prev_timestamp = 0;
1866 uint16_t prev_sequence_number = 0;
1867 bool next_packet_available = false;
1868
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001869 const RTPHeader* header = packet_buffer_->NextRtpHeader();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001870 assert(header);
1871 if (!header) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001872 LOG(LS_ERROR) << "Packet buffer unexpectedly empty.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001873 return -1;
1874 }
turaj@webrtc.org7df97062013-08-02 18:07:13 +00001875 uint32_t first_timestamp = header->timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001876 int extracted_samples = 0;
1877
1878 // Packet extraction loop.
1879 do {
1880 timestamp_ = header->timestamp;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001881 size_t discard_count = 0;
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001882 Packet* packet = packet_buffer_->GetNextPacket(&discard_count);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001883 // |header| may be invalid after the |packet_buffer_| operation.
1884 header = NULL;
1885 if (!packet) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001886 LOG(LS_ERROR) << "Should always be able to extract a packet here";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001887 assert(false); // Should always be able to extract a packet here.
1888 return -1;
1889 }
1890 stats_.PacketsDiscarded(discard_count);
1891 // Store waiting time in ms; packets->waiting_time is in "output blocks".
1892 stats_.StoreWaitingTime(packet->waiting_time * kOutputSizeMs);
1893 assert(packet->payload_length > 0);
1894 packet_list->push_back(packet); // Store packet in list.
1895
1896 if (first_packet) {
1897 first_packet = false;
henrik.lundin48ed9302015-10-29 05:36:24 -07001898 if (nack_enabled_) {
1899 RTC_DCHECK(nack_);
1900 // TODO(henrik.lundin): Should we update this for all decoded packets?
1901 nack_->UpdateLastDecodedPacket(packet->header.sequenceNumber,
1902 packet->header.timestamp);
1903 }
1904 prev_sequence_number = packet->header.sequenceNumber;
1905 prev_timestamp = packet->header.timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001906 prev_payload_type = packet->header.payloadType;
1907 }
1908
1909 // Store number of extracted samples.
1910 int packet_duration = 0;
1911 AudioDecoder* decoder = decoder_database_->GetDecoder(
1912 packet->header.payloadType);
1913 if (decoder) {
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001914 if (packet->sync_packet) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001915 packet_duration = rtc::checked_cast<int>(decoder_frame_length_);
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001916 } else {
minyue@webrtc.org2c1bcf22015-02-17 10:17:09 +00001917 if (packet->primary) {
1918 packet_duration = decoder->PacketDuration(packet->payload,
1919 packet->payload_length);
1920 } else {
1921 packet_duration = decoder->
1922 PacketDurationRedundant(packet->payload, packet->payload_length);
1923 stats_.SecondaryDecodedSamples(packet_duration);
1924 }
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001925 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001926 } else {
Henrik Lundind67a2192015-08-03 12:54:37 +02001927 LOG(LS_WARNING) << "Unknown payload type "
1928 << static_cast<int>(packet->header.payloadType);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001929 assert(false);
1930 }
1931 if (packet_duration <= 0) {
1932 // Decoder did not return a packet duration. Assume that the packet
1933 // contains the same number of samples as the previous one.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001934 packet_duration = rtc::checked_cast<int>(decoder_frame_length_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001935 }
1936 extracted_samples = packet->header.timestamp - first_timestamp +
1937 packet_duration;
1938
1939 // Check what packet is available next.
1940 header = packet_buffer_->NextRtpHeader();
1941 next_packet_available = false;
1942 if (header && prev_payload_type == header->payloadType) {
1943 int16_t seq_no_diff = header->sequenceNumber - prev_sequence_number;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001944 size_t ts_diff = header->timestamp - prev_timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001945 if (seq_no_diff == 1 ||
1946 (seq_no_diff == 0 && ts_diff == decoder_frame_length_)) {
1947 // The next sequence number is available, or the next part of a packet
1948 // that was split into pieces upon insertion.
1949 next_packet_available = true;
1950 }
1951 prev_sequence_number = header->sequenceNumber;
1952 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07001953 } while (extracted_samples < rtc::checked_cast<int>(required_samples) &&
1954 next_packet_available);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001955
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00001956 if (extracted_samples > 0) {
1957 // Delete old packets only when we are going to decode something. Otherwise,
1958 // we could end up in the situation where we never decode anything, since
1959 // all incoming packets are considered too old but the buffer will also
1960 // never be flooded and flushed.
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001961 packet_buffer_->DiscardAllOldPackets(timestamp_);
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00001962 }
1963
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001964 return extracted_samples;
1965}
1966
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001967void NetEqImpl::UpdatePlcComponents(int fs_hz, size_t channels) {
1968 // Delete objects and create new ones.
1969 expand_.reset(expand_factory_->Create(background_noise_.get(),
1970 sync_buffer_.get(), &random_vector_,
Henrik Lundinbef77e22015-08-18 14:58:09 +02001971 &stats_, fs_hz, channels));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001972 merge_.reset(new Merge(fs_hz, channels, expand_.get(), sync_buffer_.get()));
1973}
1974
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001975void NetEqImpl::SetSampleRateAndChannels(int fs_hz, size_t channels) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001976 LOG(LS_VERBOSE) << "SetSampleRateAndChannels " << fs_hz << " " << channels;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001977 // TODO(hlundin): Change to an enumerator and skip assert.
1978 assert(fs_hz == 8000 || fs_hz == 16000 || fs_hz == 32000 || fs_hz == 48000);
1979 assert(channels > 0);
1980
1981 fs_hz_ = fs_hz;
1982 fs_mult_ = fs_hz / 8000;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001983 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001984 decoder_frame_length_ = 3 * output_size_samples_; // Initialize to 30ms.
1985
1986 last_mode_ = kModeNormal;
1987
1988 // Create a new array of mute factors and set all to 1.
1989 mute_factor_array_.reset(new int16_t[channels]);
1990 for (size_t i = 0; i < channels; ++i) {
1991 mute_factor_array_[i] = 16384; // 1.0 in Q14.
1992 }
1993
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001994 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02001995 if (cng_decoder)
1996 cng_decoder->Reset();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001997
1998 // Reinit post-decode VAD with new sample rate.
1999 assert(vad_.get()); // Cannot be NULL here.
2000 vad_->Init();
2001
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002002 // Delete algorithm buffer and create a new one.
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00002003 algorithm_buffer_.reset(new AudioMultiVector(channels));
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002004
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002005 // Delete sync buffer and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002006 sync_buffer_.reset(new SyncBuffer(channels, kSyncBufferSize * fs_mult_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002007
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00002008 // Delete BackgroundNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002009 background_noise_.reset(new BackgroundNoise(channels));
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00002010 background_noise_->set_mode(background_noise_mode_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002011
2012 // Reset random vector.
2013 random_vector_.Reset();
2014
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002015 UpdatePlcComponents(fs_hz, channels);
2016
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002017 // Move index so that we create a small set of future samples (all 0).
2018 sync_buffer_->set_next_index(sync_buffer_->next_index() -
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002019 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002020
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002021 normal_.reset(new Normal(fs_hz, decoder_database_.get(), *background_noise_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002022 expand_.get()));
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +00002023 accelerate_.reset(
2024 accelerate_factory_->Create(fs_hz, channels, *background_noise_));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002025 preemptive_expand_.reset(preemptive_expand_factory_->Create(
Peter Kastingdce40cf2015-08-24 14:52:23 -07002026 fs_hz, channels, *background_noise_, expand_->overlap_length()));
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002027
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002028 // Delete ComfortNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002029 comfort_noise_.reset(new ComfortNoise(fs_hz, decoder_database_.get(),
2030 sync_buffer_.get()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002031
2032 // Verify that |decoded_buffer_| is long enough.
2033 if (decoded_buffer_length_ < kMaxFrameSize * channels) {
2034 // Reallocate to larger size.
2035 decoded_buffer_length_ = kMaxFrameSize * channels;
2036 decoded_buffer_.reset(new int16_t[decoded_buffer_length_]);
2037 }
2038
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002039 // Create DecisionLogic if it is not created yet, then communicate new sample
2040 // rate and output size to DecisionLogic object.
2041 if (!decision_logic_.get()) {
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002042 CreateDecisionLogic();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002043 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002044 decision_logic_->SetSampleRate(fs_hz_, output_size_samples_);
2045}
2046
2047NetEqOutputType NetEqImpl::LastOutputType() {
2048 assert(vad_.get());
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002049 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002050 if (last_mode_ == kModeCodecInternalCng || last_mode_ == kModeRfc3389Cng) {
2051 return kOutputCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002052 } else if (last_mode_ == kModeExpand && expand_->MuteFactor(0) == 0) {
2053 // Expand mode has faded down to background noise only (very long expand).
2054 return kOutputPLCtoCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002055 } else if (last_mode_ == kModeExpand) {
2056 return kOutputPLC;
wu@webrtc.org24301a62013-12-13 19:17:43 +00002057 } else if (vad_->running() && !vad_->active_speech()) {
2058 return kOutputVADPassive;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002059 } else {
2060 return kOutputNormal;
2061 }
2062}
2063
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002064void NetEqImpl::CreateDecisionLogic() {
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002065 decision_logic_.reset(DecisionLogic::Create(fs_hz_, output_size_samples_,
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002066 playout_mode_,
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002067 decoder_database_.get(),
2068 *packet_buffer_.get(),
2069 delay_manager_.get(),
2070 buffer_level_filter_.get()));
2071}
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002072} // namespace webrtc