blob: ead08f12fb1bb0665ae140d06eaa9d19b2ad00b2 [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"
36#include "webrtc/modules/audio_coding/neteq/normal.h"
37#include "webrtc/modules/audio_coding/neteq/packet_buffer.h"
38#include "webrtc/modules/audio_coding/neteq/packet.h"
39#include "webrtc/modules/audio_coding/neteq/payload_splitter.h"
40#include "webrtc/modules/audio_coding/neteq/post_decode_vad.h"
41#include "webrtc/modules/audio_coding/neteq/preemptive_expand.h"
42#include "webrtc/modules/audio_coding/neteq/sync_buffer.h"
43#include "webrtc/modules/audio_coding/neteq/timestamp_scaler.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000044#include "webrtc/modules/interface/module_common_types.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010045#include "webrtc/system_wrappers/include/critical_section_wrapper.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000046
47// Modify the code to obtain backwards bit-exactness. Once bit-exactness is no
48// longer required, this #define should be removed (and the code that it
49// enables).
50#define LEGACY_BITEXACT
51
52namespace webrtc {
53
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +000054NetEqImpl::NetEqImpl(const NetEq::Config& config,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000055 BufferLevelFilter* buffer_level_filter,
56 DecoderDatabase* decoder_database,
57 DelayManager* delay_manager,
58 DelayPeakDetector* delay_peak_detector,
59 DtmfBuffer* dtmf_buffer,
60 DtmfToneGenerator* dtmf_tone_generator,
61 PacketBuffer* packet_buffer,
62 PayloadSplitter* payload_splitter,
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +000063 TimestampScaler* timestamp_scaler,
64 AccelerateFactory* accelerate_factory,
65 ExpandFactory* expand_factory,
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +000066 PreemptiveExpandFactory* preemptive_expand_factory,
67 bool create_components)
henrik.lundin@webrtc.org2f816bb2014-06-05 10:37:13 +000068 : crit_sect_(CriticalSectionWrapper::CreateCriticalSection()),
69 buffer_level_filter_(buffer_level_filter),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000070 decoder_database_(decoder_database),
71 delay_manager_(delay_manager),
72 delay_peak_detector_(delay_peak_detector),
73 dtmf_buffer_(dtmf_buffer),
74 dtmf_tone_generator_(dtmf_tone_generator),
75 packet_buffer_(packet_buffer),
76 payload_splitter_(payload_splitter),
77 timestamp_scaler_(timestamp_scaler),
78 vad_(new PostDecodeVad()),
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +000079 expand_factory_(expand_factory),
80 accelerate_factory_(accelerate_factory),
81 preemptive_expand_factory_(preemptive_expand_factory),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000082 last_mode_(kModeNormal),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000083 decoded_buffer_length_(kMaxFrameSize),
84 decoded_buffer_(new int16_t[decoded_buffer_length_]),
85 playout_timestamp_(0),
86 new_codec_(false),
87 timestamp_(0),
88 reset_decoder_(false),
89 current_rtp_payload_type_(0xFF), // Invalid RTP payload type.
90 current_cng_rtp_payload_type_(0xFF), // Invalid RTP payload type.
91 ssrc_(0),
92 first_packet_(true),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000093 error_code_(0),
94 decoder_error_code_(0),
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +000095 background_noise_mode_(config.background_noise_mode),
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +000096 playout_mode_(config.playout_mode),
Henrik Lundincf808d22015-05-27 14:33:29 +020097 enable_fast_accelerate_(config.enable_fast_accelerate),
minyue@webrtc.orgd7301772013-08-29 00:58:14 +000098 decoded_packet_sequence_number_(-1),
99 decoded_packet_timestamp_(0) {
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
turaj@webrtc.orgff43c852013-09-25 00:07:27 +0000408int NetEqImpl::DecodedRtpInfo(int* sequence_number, uint32_t* timestamp) const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000409 CriticalSectionScoped lock(crit_sect_.get());
minyue@webrtc.orgd7301772013-08-29 00:58:14 +0000410 if (decoded_packet_sequence_number_ < 0)
411 return -1;
412 *sequence_number = decoded_packet_sequence_number_;
413 *timestamp = decoded_packet_timestamp_;
414 return 0;
415}
416
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000417const SyncBuffer* NetEqImpl::sync_buffer_for_test() const {
418 CriticalSectionScoped lock(crit_sect_.get());
419 return sync_buffer_.get();
420}
421
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000422// Methods below this line are private.
423
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000424int NetEqImpl::InsertPacketInternal(const WebRtcRTPHeader& rtp_header,
425 const uint8_t* payload,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000426 size_t length_bytes,
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000427 uint32_t receive_timestamp,
428 bool is_sync_packet) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000429 if (!payload) {
430 LOG_F(LS_ERROR) << "payload == NULL";
431 return kInvalidPointer;
432 }
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000433 // Sanity checks for sync-packets.
434 if (is_sync_packet) {
435 if (decoder_database_->IsDtmf(rtp_header.header.payloadType) ||
436 decoder_database_->IsRed(rtp_header.header.payloadType) ||
437 decoder_database_->IsComfortNoise(rtp_header.header.payloadType)) {
438 LOG_F(LS_ERROR) << "Sync-packet with an unacceptable payload type "
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000439 << static_cast<int>(rtp_header.header.payloadType);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000440 return kSyncPacketNotAccepted;
441 }
442 if (first_packet_ ||
443 rtp_header.header.payloadType != current_rtp_payload_type_ ||
444 rtp_header.header.ssrc != ssrc_) {
445 // Even if |current_rtp_payload_type_| is 0xFF, sync-packet isn't
446 // accepted.
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000447 LOG_F(LS_ERROR)
448 << "Changing codec, SSRC or first packet with sync-packet.";
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000449 return kSyncPacketNotAccepted;
450 }
451 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000452 PacketList packet_list;
453 RTPHeader main_header;
454 {
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000455 // Convert to Packet.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000456 // Create |packet| within this separate scope, since it should not be used
457 // directly once it's been inserted in the packet list. This way, |packet|
458 // is not defined outside of this block.
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000459 Packet* packet = new Packet;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000460 packet->header.markerBit = false;
461 packet->header.payloadType = rtp_header.header.payloadType;
462 packet->header.sequenceNumber = rtp_header.header.sequenceNumber;
463 packet->header.timestamp = rtp_header.header.timestamp;
464 packet->header.ssrc = rtp_header.header.ssrc;
465 packet->header.numCSRCs = 0;
466 packet->payload_length = length_bytes;
467 packet->primary = true;
468 packet->waiting_time = 0;
469 packet->payload = new uint8_t[packet->payload_length];
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000470 packet->sync_packet = is_sync_packet;
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +0000471 if (!packet->payload) {
472 LOG_F(LS_ERROR) << "Payload pointer is NULL.";
473 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000474 assert(payload); // Already checked above.
475 memcpy(packet->payload, payload, packet->payload_length);
476 // Insert packet in a packet list.
477 packet_list.push_back(packet);
478 // Save main payloads header for later.
479 memcpy(&main_header, &packet->header, sizeof(main_header));
480 }
481
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000482 bool update_sample_rate_and_channels = false;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000483 // Reinitialize NetEq if it's needed (changed SSRC or first call).
484 if ((main_header.ssrc != ssrc_) || first_packet_) {
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000485 // Note: |first_packet_| will be cleared further down in this method, once
486 // the packet has been successfully inserted into the packet buffer.
487
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000488 rtcp_.Init(main_header.sequenceNumber);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000489
490 // Flush the packet buffer and DTMF buffer.
491 packet_buffer_->Flush();
492 dtmf_buffer_->Flush();
493
494 // Store new SSRC.
495 ssrc_ = main_header.ssrc;
496
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000497 // Update audio buffer timestamp.
498 sync_buffer_->IncreaseEndTimestamp(main_header.timestamp - timestamp_);
499
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000500 // Update codecs.
501 timestamp_ = main_header.timestamp;
502 current_rtp_payload_type_ = main_header.payloadType;
503
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000504 // Reset timestamp scaling.
505 timestamp_scaler_->Reset();
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000506
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000507 // Trigger an update of sampling rate and the number of channels.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000508 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000509 }
510
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000511 // Update RTCP statistics, only for regular packets.
512 if (!is_sync_packet)
513 rtcp_.Update(main_header, receive_timestamp);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000514
515 // Check for RED payload type, and separate payloads into several packets.
516 if (decoder_database_->IsRed(main_header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000517 assert(!is_sync_packet); // We had a sanity check for this.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000518 if (payload_splitter_->SplitRed(&packet_list) != PayloadSplitter::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000519 PacketBuffer::DeleteAllPackets(&packet_list);
520 return kRedundancySplitError;
521 }
522 // Only accept a few RED payloads of the same type as the main data,
523 // DTMF events and CNG.
524 payload_splitter_->CheckRedPayloads(&packet_list, *decoder_database_);
525 // Update the stored main payload header since the main payload has now
526 // changed.
527 memcpy(&main_header, &packet_list.front()->header, sizeof(main_header));
528 }
529
530 // Check payload types.
531 if (decoder_database_->CheckPayloadTypes(packet_list) ==
532 DecoderDatabase::kDecoderNotFound) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000533 PacketBuffer::DeleteAllPackets(&packet_list);
534 return kUnknownRtpPayloadType;
535 }
536
537 // Scale timestamp to internal domain (only for some codecs).
538 timestamp_scaler_->ToInternal(&packet_list);
539
540 // Process DTMF payloads. Cycle through the list of packets, and pick out any
541 // DTMF payloads found.
542 PacketList::iterator it = packet_list.begin();
543 while (it != packet_list.end()) {
544 Packet* current_packet = (*it);
545 assert(current_packet);
546 assert(current_packet->payload);
547 if (decoder_database_->IsDtmf(current_packet->header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000548 assert(!current_packet->sync_packet); // We had a sanity check for this.
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000549 DtmfEvent event;
550 int ret = DtmfBuffer::ParseEvent(
551 current_packet->header.timestamp,
552 current_packet->payload,
553 current_packet->payload_length,
554 &event);
555 if (ret != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000556 PacketBuffer::DeleteAllPackets(&packet_list);
557 return kDtmfParsingError;
558 }
559 if (dtmf_buffer_->InsertEvent(event) != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000560 PacketBuffer::DeleteAllPackets(&packet_list);
561 return kDtmfInsertError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000562 }
563 // TODO(hlundin): Let the destructor of Packet handle the payload.
564 delete [] current_packet->payload;
565 delete current_packet;
566 it = packet_list.erase(it);
567 } else {
568 ++it;
569 }
570 }
571
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000572 // Check for FEC in packets, and separate payloads into several packets.
573 int ret = payload_splitter_->SplitFec(&packet_list, decoder_database_.get());
574 if (ret != PayloadSplitter::kOK) {
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000575 PacketBuffer::DeleteAllPackets(&packet_list);
576 switch (ret) {
577 case PayloadSplitter::kUnknownPayloadType:
578 return kUnknownRtpPayloadType;
579 default:
580 return kOtherError;
581 }
582 }
583
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000584 // Split payloads into smaller chunks. This also verifies that all payloads
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000585 // are of a known payload type. SplitAudio() method is protected against
586 // sync-packets.
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +0000587 ret = payload_splitter_->SplitAudio(&packet_list, *decoder_database_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000588 if (ret != PayloadSplitter::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000589 PacketBuffer::DeleteAllPackets(&packet_list);
590 switch (ret) {
591 case PayloadSplitter::kUnknownPayloadType:
592 return kUnknownRtpPayloadType;
593 case PayloadSplitter::kFrameSplitError:
594 return kFrameSplitError;
595 default:
596 return kOtherError;
597 }
598 }
599
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000600 // Update bandwidth estimate, if the packet is not sync-packet.
601 if (!packet_list.empty() && !packet_list.front()->sync_packet) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000602 // The list can be empty here if we got nothing but DTMF payloads.
603 AudioDecoder* decoder =
604 decoder_database_->GetDecoder(main_header.payloadType);
605 assert(decoder); // Should always get a valid object, since we have
606 // already checked that the payload types are known.
607 decoder->IncomingPacket(packet_list.front()->payload,
608 packet_list.front()->payload_length,
609 packet_list.front()->header.sequenceNumber,
610 packet_list.front()->header.timestamp,
611 receive_timestamp);
612 }
613
614 // Insert packets in buffer.
henrik.lundin116c84e2015-08-27 13:14:48 -0700615 const size_t buffer_length_before_insert =
616 packet_buffer_->NumPacketsInBuffer();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000617 ret = packet_buffer_->InsertPacketList(
618 &packet_list,
619 *decoder_database_,
620 &current_rtp_payload_type_,
621 &current_cng_rtp_payload_type_);
622 if (ret == PacketBuffer::kFlushed) {
623 // Reset DSP timestamp etc. if packet buffer flushed.
624 new_codec_ = true;
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000625 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000626 } else if (ret != PacketBuffer::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000627 PacketBuffer::DeleteAllPackets(&packet_list);
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000628 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000629 }
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000630
631 if (first_packet_) {
632 first_packet_ = false;
633 // Update the codec on the next GetAudio call.
634 new_codec_ = true;
635 }
636
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000637 if (current_rtp_payload_type_ != 0xFF) {
638 const DecoderDatabase::DecoderInfo* dec_info =
639 decoder_database_->GetDecoderInfo(current_rtp_payload_type_);
640 if (!dec_info) {
641 assert(false); // Already checked that the payload type is known.
642 }
643 }
644
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000645 if (update_sample_rate_and_channels && !packet_buffer_->Empty()) {
646 // We do not use |current_rtp_payload_type_| to |set payload_type|, but
647 // get the next RTP header from |packet_buffer_| to obtain the payload type.
648 // The reason for it is the following corner case. If NetEq receives a
649 // CNG packet with a sample rate different than the current CNG then it
650 // flushes its buffer, assuming send codec must have been changed. However,
651 // payload type of the hypothetically new send codec is not known.
652 const RTPHeader* rtp_header = packet_buffer_->NextRtpHeader();
653 assert(rtp_header);
654 int payload_type = rtp_header->payloadType;
655 AudioDecoder* decoder = decoder_database_->GetDecoder(payload_type);
656 assert(decoder); // Payloads are already checked to be valid.
657 const DecoderDatabase::DecoderInfo* decoder_info =
658 decoder_database_->GetDecoderInfo(payload_type);
659 assert(decoder_info);
660 if (decoder_info->fs_hz != fs_hz_ ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +0000661 decoder->Channels() != algorithm_buffer_->Channels())
662 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->Channels());
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000663 }
664
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000665 // TODO(hlundin): Move this code to DelayManager class.
666 const DecoderDatabase::DecoderInfo* dec_info =
667 decoder_database_->GetDecoderInfo(main_header.payloadType);
668 assert(dec_info); // Already checked that the payload type is known.
669 delay_manager_->LastDecoderType(dec_info->codec_type);
670 if (delay_manager_->last_pack_cng_or_dtmf() == 0) {
671 // Calculate the total speech length carried in each packet.
henrik.lundin116c84e2015-08-27 13:14:48 -0700672 const size_t buffer_length_after_insert =
673 packet_buffer_->NumPacketsInBuffer();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000674
henrik.lundin116c84e2015-08-27 13:14:48 -0700675 if (buffer_length_after_insert > buffer_length_before_insert) {
676 const size_t packet_length_samples =
677 (buffer_length_after_insert - buffer_length_before_insert) *
678 decoder_frame_length_;
679 if (packet_length_samples != decision_logic_->packet_length_samples()) {
680 decision_logic_->set_packet_length_samples(packet_length_samples);
681 delay_manager_->SetPacketAudioLength(
682 rtc::checked_cast<int>((1000 * packet_length_samples) / fs_hz_));
683 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000684 }
685
686 // Update statistics.
pbos@webrtc.org0946a562013-04-09 00:28:06 +0000687 if ((int32_t) (main_header.timestamp - timestamp_) >= 0 &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000688 !new_codec_) {
689 // Only update statistics if incoming packet is not older than last played
690 // out packet, and if new codec flag is not set.
691 delay_manager_->Update(main_header.sequenceNumber, main_header.timestamp,
692 fs_hz_);
693 }
694 } else if (delay_manager_->last_pack_cng_or_dtmf() == -1) {
695 // This is first "normal" packet after CNG or DTMF.
696 // Reset packet time counter and measure time until next packet,
697 // but don't update statistics.
698 delay_manager_->set_last_pack_cng_or_dtmf(0);
699 delay_manager_->ResetPacketIatCount();
700 }
701 return 0;
702}
703
Peter Kasting728d9032015-06-11 14:31:38 -0700704int NetEqImpl::GetAudioInternal(size_t max_length,
705 int16_t* output,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700706 size_t* samples_per_channel,
Peter Kasting728d9032015-06-11 14:31:38 -0700707 int* num_channels) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000708 PacketList packet_list;
709 DtmfEvent dtmf_event;
710 Operations operation;
711 bool play_dtmf;
712 int return_value = GetDecision(&operation, &packet_list, &dtmf_event,
713 &play_dtmf);
714 if (return_value != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000715 last_mode_ = kModeError;
716 return return_value;
717 }
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000718 LOG(LS_VERBOSE) << "GetDecision returned operation=" << operation <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000719 " and " << packet_list.size() << " packet(s)";
720
721 AudioDecoder::SpeechType speech_type;
722 int length = 0;
723 int decode_return_value = Decode(&packet_list, &operation,
724 &length, &speech_type);
725
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000726 assert(vad_.get());
727 bool sid_frame_available =
728 (operation == kRfc3389Cng && !packet_list.empty());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700729 vad_->Update(decoded_buffer_.get(), static_cast<size_t>(length), speech_type,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000730 sid_frame_available, fs_hz_);
731
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000732 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000733 switch (operation) {
734 case kNormal: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000735 DoNormal(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000736 break;
737 }
738 case kMerge: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000739 DoMerge(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000740 break;
741 }
742 case kExpand: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000743 return_value = DoExpand(play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000744 break;
745 }
Henrik Lundincf808d22015-05-27 14:33:29 +0200746 case kAccelerate:
747 case kFastAccelerate: {
748 const bool fast_accelerate =
749 enable_fast_accelerate_ && (operation == kFastAccelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000750 return_value = DoAccelerate(decoded_buffer_.get(), length, speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +0200751 play_dtmf, fast_accelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000752 break;
753 }
754 case kPreemptiveExpand: {
755 return_value = DoPreemptiveExpand(decoded_buffer_.get(), length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000756 speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000757 break;
758 }
759 case kRfc3389Cng:
760 case kRfc3389CngNoPacket: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000761 return_value = DoRfc3389Cng(&packet_list, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000762 break;
763 }
764 case kCodecInternalCng: {
765 // This handles the case when there is no transmission and the decoder
766 // should produce internal comfort noise.
767 // TODO(hlundin): Write test for codec-internal CNG.
minyuel6d92bf52015-09-23 15:20:39 +0200768 DoCodecInternalCng(decoded_buffer_.get(), length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000769 break;
770 }
771 case kDtmf: {
772 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000773 return_value = DoDtmf(dtmf_event, &play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000774 break;
775 }
776 case kAlternativePlc: {
777 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000778 DoAlternativePlc(false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000779 break;
780 }
781 case kAlternativePlcIncreaseTimestamp: {
782 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000783 DoAlternativePlc(true);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000784 break;
785 }
786 case kAudioRepetitionIncreaseTimestamp: {
787 // TODO(hlundin): Write test for this.
Peter Kastingb7e50542015-06-11 12:55:50 -0700788 sync_buffer_->IncreaseEndTimestamp(
789 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000790 // Skipping break on purpose. Execution should move on into the
791 // next case.
kjellander@webrtc.org7d2b6a92015-01-28 18:37:58 +0000792 FALLTHROUGH();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000793 }
794 case kAudioRepetition: {
795 // TODO(hlundin): Write test for this.
796 // Copy last |output_size_samples_| from |sync_buffer_| to
797 // |algorithm_buffer|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000798 algorithm_buffer_->PushBackFromIndex(
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000799 *sync_buffer_, sync_buffer_->Size() - output_size_samples_);
800 expand_->Reset();
801 break;
802 }
803 case kUndefined: {
Henrik Lundind67a2192015-08-03 12:54:37 +0200804 LOG(LS_ERROR) << "Invalid operation kUndefined.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000805 assert(false); // This should not happen.
806 last_mode_ = kModeError;
807 return kInvalidOperation;
808 }
809 } // End of switch.
810 if (return_value < 0) {
811 return return_value;
812 }
813
814 if (last_mode_ != kModeRfc3389Cng) {
815 comfort_noise_->Reset();
816 }
817
818 // Copy from |algorithm_buffer| to |sync_buffer_|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000819 sync_buffer_->PushBack(*algorithm_buffer_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000820
821 // Extract data from |sync_buffer_| to |output|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000822 size_t num_output_samples_per_channel = output_size_samples_;
823 size_t num_output_samples = output_size_samples_ * sync_buffer_->Channels();
824 if (num_output_samples > max_length) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000825 LOG(LS_WARNING) << "Output array is too short. " << max_length << " < " <<
826 output_size_samples_ << " * " << sync_buffer_->Channels();
827 num_output_samples = max_length;
Peter Kastingdce40cf2015-08-24 14:52:23 -0700828 num_output_samples_per_channel = max_length / sync_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000829 }
Peter Kastingdce40cf2015-08-24 14:52:23 -0700830 const size_t samples_from_sync =
831 sync_buffer_->GetNextAudioInterleaved(num_output_samples_per_channel,
832 output);
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000833 *num_channels = static_cast<int>(sync_buffer_->Channels());
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000834 LOG(LS_VERBOSE) << "Sync buffer (" << *num_channels << " channel(s)):" <<
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000835 " insert " << algorithm_buffer_->Size() << " samples, extract " <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000836 samples_from_sync << " samples";
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200837 if (sync_buffer_->FutureLength() < expand_->overlap_length()) {
838 // The sync buffer should always contain |overlap_length| samples, but now
839 // too many samples have been extracted. Reinstall the |overlap_length|
840 // lookahead by moving the index.
841 const size_t missing_lookahead_samples =
842 expand_->overlap_length() - sync_buffer_->FutureLength();
henrikg91d6ede2015-09-17 00:24:34 -0700843 RTC_DCHECK_GE(sync_buffer_->next_index(), missing_lookahead_samples);
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200844 sync_buffer_->set_next_index(sync_buffer_->next_index() -
845 missing_lookahead_samples);
846 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000847 if (samples_from_sync != output_size_samples_) {
Henrik Lundind67a2192015-08-03 12:54:37 +0200848 LOG(LS_ERROR) << "samples_from_sync (" << samples_from_sync
849 << ") != output_size_samples_ (" << output_size_samples_
850 << ")";
minyue@webrtc.orgdb1cefc2013-08-13 01:39:21 +0000851 // TODO(minyue): treatment of under-run, filling zeros
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000852 memset(output, 0, num_output_samples * sizeof(int16_t));
853 *samples_per_channel = output_size_samples_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000854 return kSampleUnderrun;
855 }
856 *samples_per_channel = output_size_samples_;
857
858 // Should always have overlap samples left in the |sync_buffer_|.
henrikg91d6ede2015-09-17 00:24:34 -0700859 RTC_DCHECK_GE(sync_buffer_->FutureLength(), expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000860
861 if (play_dtmf) {
862 return_value = DtmfOverdub(dtmf_event, sync_buffer_->Channels(), output);
863 }
864
865 // Update the background noise parameters if last operation wrote data
866 // straight from the decoder to the |sync_buffer_|. That is, none of the
867 // operations that modify the signal can be followed by a parameter update.
868 if ((last_mode_ == kModeNormal) ||
869 (last_mode_ == kModeAccelerateFail) ||
870 (last_mode_ == kModePreemptiveExpandFail) ||
871 (last_mode_ == kModeRfc3389Cng) ||
872 (last_mode_ == kModeCodecInternalCng)) {
873 background_noise_->Update(*sync_buffer_, *vad_.get());
874 }
875
876 if (operation == kDtmf) {
877 // DTMF data was written the end of |sync_buffer_|.
878 // Update index to end of DTMF data in |sync_buffer_|.
879 sync_buffer_->set_dtmf_index(sync_buffer_->Size());
880 }
881
henrik.lundin@webrtc.orged865b52014-03-06 10:28:07 +0000882 if (last_mode_ != kModeExpand) {
883 // If last operation was not expand, calculate the |playout_timestamp_| from
884 // the |sync_buffer_|. However, do not update the |playout_timestamp_| if it
885 // would be moved "backwards".
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000886 uint32_t temp_timestamp = sync_buffer_->end_timestamp() -
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000887 static_cast<uint32_t>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000888 if (static_cast<int32_t>(temp_timestamp - playout_timestamp_) > 0) {
889 playout_timestamp_ = temp_timestamp;
890 }
891 } else {
892 // Use dead reckoning to estimate the |playout_timestamp_|.
Peter Kastingb7e50542015-06-11 12:55:50 -0700893 playout_timestamp_ += static_cast<uint32_t>(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000894 }
895
896 if (decode_return_value) return decode_return_value;
897 return return_value;
898}
899
900int NetEqImpl::GetDecision(Operations* operation,
901 PacketList* packet_list,
902 DtmfEvent* dtmf_event,
903 bool* play_dtmf) {
904 // Initialize output variables.
905 *play_dtmf = false;
906 *operation = kUndefined;
907
908 // Increment time counters.
909 packet_buffer_->IncrementWaitingTimes();
910 stats_.IncreaseCounter(output_size_samples_, fs_hz_);
911
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000912 assert(sync_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000913 uint32_t end_timestamp = sync_buffer_->end_timestamp();
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +0000914 if (!new_codec_) {
915 const uint32_t five_seconds_samples = 5 * fs_hz_;
916 packet_buffer_->DiscardOldPackets(end_timestamp, five_seconds_samples);
917 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000918 const RTPHeader* header = packet_buffer_->NextRtpHeader();
919
henrik.lundin@webrtc.orgca8cb952014-03-12 10:26:52 +0000920 if (decision_logic_->CngRfc3389On() || last_mode_ == kModeRfc3389Cng) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000921 // Because of timestamp peculiarities, we have to "manually" disallow using
922 // a CNG packet with the same timestamp as the one that was last played.
923 // This can happen when using redundancy and will cause the timing to shift.
henrik.lundin@webrtc.org24779fe2014-03-14 12:40:05 +0000924 while (header && decoder_database_->IsComfortNoise(header->payloadType) &&
925 (end_timestamp >= header->timestamp ||
926 end_timestamp + decision_logic_->generated_noise_samples() >
927 header->timestamp)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000928 // Don't use this packet, discard it.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000929 if (packet_buffer_->DiscardNextPacket() != PacketBuffer::kOK) {
930 assert(false); // Must be ok by design.
931 }
932 // Check buffer again.
933 if (!new_codec_) {
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +0000934 packet_buffer_->DiscardOldPackets(end_timestamp, 5 * fs_hz_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000935 }
936 header = packet_buffer_->NextRtpHeader();
937 }
938 }
939
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000940 assert(expand_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000941 const int samples_left = static_cast<int>(sync_buffer_->FutureLength() -
942 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000943 if (last_mode_ == kModeAccelerateSuccess ||
944 last_mode_ == kModeAccelerateLowEnergy ||
945 last_mode_ == kModePreemptiveExpandSuccess ||
946 last_mode_ == kModePreemptiveExpandLowEnergy) {
947 // Subtract (samples_left + output_size_samples_) from sampleMemory.
Peter Kastingdce40cf2015-08-24 14:52:23 -0700948 decision_logic_->AddSampleMemory(
949 -(samples_left + rtc::checked_cast<int>(output_size_samples_)));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000950 }
951
952 // Check if it is time to play a DTMF event.
Peter Kastingb7e50542015-06-11 12:55:50 -0700953 if (dtmf_buffer_->GetEvent(
954 static_cast<uint32_t>(
955 end_timestamp + decision_logic_->generated_noise_samples()),
956 dtmf_event)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000957 *play_dtmf = true;
958 }
959
960 // Get instruction.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000961 assert(sync_buffer_.get());
962 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000963 *operation = decision_logic_->GetDecision(*sync_buffer_,
964 *expand_,
965 decoder_frame_length_,
966 header,
967 last_mode_,
968 *play_dtmf,
969 &reset_decoder_);
970
971 // Check if we already have enough samples in the |sync_buffer_|. If so,
972 // change decision to normal, unless the decision was merge, accelerate, or
973 // preemptive expand.
Peter Kastingdce40cf2015-08-24 14:52:23 -0700974 if (samples_left >= rtc::checked_cast<int>(output_size_samples_) &&
975 *operation != kMerge &&
976 *operation != kAccelerate &&
977 *operation != kFastAccelerate &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000978 *operation != kPreemptiveExpand) {
979 *operation = kNormal;
980 return 0;
981 }
982
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000983 decision_logic_->ExpandDecision(*operation);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000984
985 // Check conditions for reset.
986 if (new_codec_ || *operation == kUndefined) {
987 // The only valid reason to get kUndefined is that new_codec_ is set.
988 assert(new_codec_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000989 if (*play_dtmf && !header) {
990 timestamp_ = dtmf_event->timestamp;
991 } else {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000992 if (!header) {
Henrik Lundind67a2192015-08-03 12:54:37 +0200993 LOG(LS_ERROR) << "Packet missing where it shouldn't.";
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000994 return -1;
995 }
996 timestamp_ = header->timestamp;
997 if (*operation == kRfc3389CngNoPacket
998#ifndef LEGACY_BITEXACT
999 // Without this check, it can happen that a non-CNG packet is sent to
1000 // the CNG decoder as if it was a SID frame. This is clearly a bug,
1001 // but is kept for now to maintain bit-exactness with the test
1002 // vectors.
1003 && decoder_database_->IsComfortNoise(header->payloadType)
1004#endif
1005 ) {
1006 // Change decision to CNG packet, since we do have a CNG packet, but it
1007 // was considered too early to use. Now, use it anyway.
1008 *operation = kRfc3389Cng;
1009 } else if (*operation != kRfc3389Cng) {
1010 *operation = kNormal;
1011 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001012 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001013 // Adjust |sync_buffer_| timestamp before setting |end_timestamp| to the
1014 // new value.
1015 sync_buffer_->IncreaseEndTimestamp(timestamp_ - end_timestamp);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001016 end_timestamp = timestamp_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001017 new_codec_ = false;
1018 decision_logic_->SoftReset();
1019 buffer_level_filter_->Reset();
1020 delay_manager_->Reset();
1021 stats_.ResetMcu();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001022 }
1023
Peter Kastingdce40cf2015-08-24 14:52:23 -07001024 size_t required_samples = output_size_samples_;
1025 const size_t samples_10_ms = static_cast<size_t>(80 * fs_mult_);
1026 const size_t samples_20_ms = 2 * samples_10_ms;
1027 const size_t samples_30_ms = 3 * samples_10_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001028
1029 switch (*operation) {
1030 case kExpand: {
1031 timestamp_ = end_timestamp;
1032 return 0;
1033 }
1034 case kRfc3389CngNoPacket:
1035 case kCodecInternalCng: {
1036 return 0;
1037 }
1038 case kDtmf: {
1039 // TODO(hlundin): Write test for this.
1040 // Update timestamp.
1041 timestamp_ = end_timestamp;
1042 if (decision_logic_->generated_noise_samples() > 0 &&
1043 last_mode_ != kModeDtmf) {
1044 // Make a jump in timestamp due to the recently played comfort noise.
Peter Kastingb7e50542015-06-11 12:55:50 -07001045 uint32_t timestamp_jump =
1046 static_cast<uint32_t>(decision_logic_->generated_noise_samples());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001047 sync_buffer_->IncreaseEndTimestamp(timestamp_jump);
1048 timestamp_ += timestamp_jump;
1049 }
1050 decision_logic_->set_generated_noise_samples(0);
1051 return 0;
1052 }
Henrik Lundincf808d22015-05-27 14:33:29 +02001053 case kAccelerate:
1054 case kFastAccelerate: {
1055 // In order to do an accelerate we need at least 30 ms of audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001056 if (samples_left >= static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001057 // Already have enough data, so we do not need to extract any more.
1058 decision_logic_->set_sample_memory(samples_left);
1059 decision_logic_->set_prev_time_scale(true);
1060 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001061 } else if (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001062 decoder_frame_length_ >= samples_30_ms) {
1063 // Avoid decoding more data as it might overflow the playout buffer.
1064 *operation = kNormal;
1065 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001066 } else if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001067 decoder_frame_length_ < samples_30_ms) {
1068 // Build up decoded data by decoding at least 20 ms of audio data. Do
1069 // not perform accelerate yet, but wait until we only need to do one
1070 // decoding.
1071 required_samples = 2 * output_size_samples_;
1072 *operation = kNormal;
1073 }
1074 // If none of the above is true, we have one of two possible situations:
1075 // (1) 20 ms <= samples_left < 30 ms and decoder_frame_length_ < 30 ms; or
1076 // (2) samples_left < 10 ms and decoder_frame_length_ >= 30 ms.
1077 // In either case, we move on with the accelerate decision, and decode one
1078 // frame now.
1079 break;
1080 }
1081 case kPreemptiveExpand: {
1082 // In order to do a preemptive expand we need at least 30 ms of decoded
1083 // audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001084 if ((samples_left >= static_cast<int>(samples_30_ms)) ||
1085 (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001086 decoder_frame_length_ >= samples_30_ms)) {
1087 // Already have enough data, so we do not need to extract any more.
1088 // Or, avoid decoding more data as it might overflow the playout buffer.
1089 // Still try preemptive expand, though.
1090 decision_logic_->set_sample_memory(samples_left);
1091 decision_logic_->set_prev_time_scale(true);
1092 return 0;
1093 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07001094 if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001095 decoder_frame_length_ < samples_30_ms) {
1096 // Build up decoded data by decoding at least 20 ms of audio data.
1097 // Still try to perform preemptive expand.
1098 required_samples = 2 * output_size_samples_;
1099 }
1100 // Move on with the preemptive expand decision.
1101 break;
1102 }
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001103 case kMerge: {
1104 required_samples =
1105 std::max(merge_->RequiredFutureSamples(), required_samples);
1106 break;
1107 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001108 default: {
1109 // Do nothing.
1110 }
1111 }
1112
1113 // Get packets from buffer.
1114 int extracted_samples = 0;
1115 if (header &&
1116 *operation != kAlternativePlc &&
1117 *operation != kAlternativePlcIncreaseTimestamp &&
1118 *operation != kAudioRepetition &&
1119 *operation != kAudioRepetitionIncreaseTimestamp) {
1120 sync_buffer_->IncreaseEndTimestamp(header->timestamp - end_timestamp);
1121 if (decision_logic_->CngOff()) {
1122 // Adjustment of timestamp only corresponds to an actual packet loss
1123 // if comfort noise is not played. If comfort noise was just played,
1124 // this adjustment of timestamp is only done to get back in sync with the
1125 // stream timestamp; no loss to report.
1126 stats_.LostSamples(header->timestamp - end_timestamp);
1127 }
1128
1129 if (*operation != kRfc3389Cng) {
1130 // We are about to decode and use a non-CNG packet.
1131 decision_logic_->SetCngOff();
1132 }
1133 // Reset CNG timestamp as a new packet will be delivered.
1134 // (Also if this is a CNG packet, since playedOutTS is updated.)
1135 decision_logic_->set_generated_noise_samples(0);
1136
1137 extracted_samples = ExtractPackets(required_samples, packet_list);
1138 if (extracted_samples < 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001139 return kPacketBufferCorruption;
1140 }
1141 }
1142
Henrik Lundincf808d22015-05-27 14:33:29 +02001143 if (*operation == kAccelerate || *operation == kFastAccelerate ||
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001144 *operation == kPreemptiveExpand) {
1145 decision_logic_->set_sample_memory(samples_left + extracted_samples);
1146 decision_logic_->set_prev_time_scale(true);
1147 }
1148
Henrik Lundincf808d22015-05-27 14:33:29 +02001149 if (*operation == kAccelerate || *operation == kFastAccelerate) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001150 // Check that we have enough data (30ms) to do accelerate.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001151 if (extracted_samples + samples_left < static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001152 // TODO(hlundin): Write test for this.
1153 // Not enough, do normal operation instead.
1154 *operation = kNormal;
1155 }
1156 }
1157
1158 timestamp_ = end_timestamp;
1159 return 0;
1160}
1161
1162int NetEqImpl::Decode(PacketList* packet_list, Operations* operation,
1163 int* decoded_length,
1164 AudioDecoder::SpeechType* speech_type) {
1165 *speech_type = AudioDecoder::kSpeech;
minyuel6d92bf52015-09-23 15:20:39 +02001166
1167 // When packet_list is empty, we may be in kCodecInternalCng mode, and for
1168 // that we use current active decoder.
1169 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1170
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001171 if (!packet_list->empty()) {
1172 const Packet* packet = packet_list->front();
pkasting@chromium.org0e81fdf2015-02-02 23:54:03 +00001173 uint8_t payload_type = packet->header.payloadType;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001174 if (!decoder_database_->IsComfortNoise(payload_type)) {
1175 decoder = decoder_database_->GetDecoder(payload_type);
1176 assert(decoder);
1177 if (!decoder) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001178 LOG(LS_WARNING) << "Unknown payload type "
1179 << static_cast<int>(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001180 PacketBuffer::DeleteAllPackets(packet_list);
1181 return kDecoderNotFound;
1182 }
1183 bool decoder_changed;
1184 decoder_database_->SetActiveDecoder(payload_type, &decoder_changed);
1185 if (decoder_changed) {
1186 // We have a new decoder. Re-init some values.
1187 const DecoderDatabase::DecoderInfo* decoder_info = decoder_database_
1188 ->GetDecoderInfo(payload_type);
1189 assert(decoder_info);
1190 if (!decoder_info) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001191 LOG(LS_WARNING) << "Unknown payload type "
1192 << static_cast<int>(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001193 PacketBuffer::DeleteAllPackets(packet_list);
1194 return kDecoderNotFound;
1195 }
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001196 // If sampling rate or number of channels has changed, we need to make
1197 // a reset.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001198 if (decoder_info->fs_hz != fs_hz_ ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001199 decoder->Channels() != algorithm_buffer_->Channels()) {
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001200 // TODO(tlegrand): Add unittest to cover this event.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001201 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->Channels());
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001202 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001203 sync_buffer_->set_end_timestamp(timestamp_);
1204 playout_timestamp_ = timestamp_;
1205 }
1206 }
1207 }
1208
1209 if (reset_decoder_) {
1210 // TODO(hlundin): Write test for this.
Karl Wiberg43766482015-08-27 15:22:11 +02001211 if (decoder)
1212 decoder->Reset();
1213
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001214 // Reset comfort noise decoder.
1215 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02001216 if (cng_decoder)
1217 cng_decoder->Reset();
1218
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001219 reset_decoder_ = false;
1220 }
1221
1222#ifdef LEGACY_BITEXACT
1223 // Due to a bug in old SignalMCU, it could happen that CNG operation was
1224 // decided, but a speech packet was provided. The speech packet will be used
1225 // to update the comfort noise decoder, as if it was a SID frame, which is
1226 // clearly wrong.
1227 if (*operation == kRfc3389Cng) {
1228 return 0;
1229 }
1230#endif
1231
1232 *decoded_length = 0;
1233 // Update codec-internal PLC state.
1234 if ((*operation == kMerge) && decoder && decoder->HasDecodePlc()) {
1235 decoder->DecodePlc(1, &decoded_buffer_[*decoded_length]);
1236 }
1237
minyuel6d92bf52015-09-23 15:20:39 +02001238 int return_value;
1239 if (*operation == kCodecInternalCng) {
1240 RTC_DCHECK(packet_list->empty());
1241 return_value = DecodeCng(decoder, decoded_length, speech_type);
1242 } else {
1243 return_value = DecodeLoop(packet_list, *operation, decoder,
1244 decoded_length, speech_type);
1245 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001246
1247 if (*decoded_length < 0) {
1248 // Error returned from the decoder.
1249 *decoded_length = 0;
Peter Kastingb7e50542015-06-11 12:55:50 -07001250 sync_buffer_->IncreaseEndTimestamp(
1251 static_cast<uint32_t>(decoder_frame_length_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001252 int error_code = 0;
1253 if (decoder)
1254 error_code = decoder->ErrorCode();
1255 if (error_code != 0) {
1256 // Got some error code from the decoder.
1257 decoder_error_code_ = error_code;
1258 return_value = kDecoderErrorCode;
Henrik Lundind67a2192015-08-03 12:54:37 +02001259 LOG(LS_WARNING) << "Decoder returned error code: " << error_code;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001260 } else {
1261 // Decoder does not implement error codes. Return generic error.
1262 return_value = kOtherDecoderError;
Henrik Lundind67a2192015-08-03 12:54:37 +02001263 LOG(LS_WARNING) << "Decoder error (no error code)";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001264 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001265 *operation = kExpand; // Do expansion to get data instead.
1266 }
1267 if (*speech_type != AudioDecoder::kComfortNoise) {
1268 // Don't increment timestamp if codec returned CNG speech type
1269 // since in this case, the we will increment the CNGplayedTS counter.
1270 // Increase with number of samples per channel.
1271 assert(*decoded_length == 0 ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001272 (decoder && decoder->Channels() == sync_buffer_->Channels()));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001273 sync_buffer_->IncreaseEndTimestamp(
1274 *decoded_length / static_cast<int>(sync_buffer_->Channels()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001275 }
1276 return return_value;
1277}
1278
minyuel6d92bf52015-09-23 15:20:39 +02001279int NetEqImpl::DecodeCng(AudioDecoder* decoder, int* decoded_length,
1280 AudioDecoder::SpeechType* speech_type) {
1281 if (!decoder) {
1282 // This happens when active decoder is not defined.
1283 *decoded_length = -1;
1284 return 0;
1285 }
1286
1287 while (*decoded_length < rtc::checked_cast<int>(output_size_samples_)) {
1288 const int length = decoder->Decode(
1289 nullptr, 0, fs_hz_,
1290 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1291 &decoded_buffer_[*decoded_length], speech_type);
1292 if (length > 0) {
1293 *decoded_length += length;
1294 LOG(LS_VERBOSE) << "Decoded " << length << " CNG samples";
1295 } else {
1296 // Error.
1297 LOG(LS_WARNING) << "Failed to decode CNG";
1298 *decoded_length = -1;
1299 break;
1300 }
1301 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1302 // Guard against overflow.
1303 LOG(LS_WARNING) << "Decoded too much CNG.";
1304 return kDecodedTooMuch;
1305 }
1306 }
1307 return 0;
1308}
1309
1310int NetEqImpl::DecodeLoop(PacketList* packet_list, const Operations& operation,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001311 AudioDecoder* decoder, int* decoded_length,
1312 AudioDecoder::SpeechType* speech_type) {
1313 Packet* packet = NULL;
1314 if (!packet_list->empty()) {
1315 packet = packet_list->front();
1316 }
minyuel6d92bf52015-09-23 15:20:39 +02001317
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001318 // Do decoding.
1319 while (packet &&
1320 !decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1321 assert(decoder); // At this point, we must have a decoder object.
1322 // The number of channels in the |sync_buffer_| should be the same as the
1323 // number decoder channels.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001324 assert(sync_buffer_->Channels() == decoder->Channels());
1325 assert(decoded_buffer_length_ >= kMaxFrameSize * decoder->Channels());
minyuel6d92bf52015-09-23 15:20:39 +02001326 assert(operation == kNormal || operation == kAccelerate ||
1327 operation == kFastAccelerate || operation == kMerge ||
1328 operation == kPreemptiveExpand);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001329 packet_list->pop_front();
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001330 size_t payload_length = packet->payload_length;
Peter Kasting36b7cc32015-06-11 19:57:18 -07001331 int decode_length;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +00001332 if (packet->sync_packet) {
1333 // Decode to silence with the same frame size as the last decode.
1334 LOG(LS_VERBOSE) << "Decoding sync-packet: " <<
1335 " ts=" << packet->header.timestamp <<
1336 ", sn=" << packet->header.sequenceNumber <<
1337 ", pt=" << static_cast<int>(packet->header.payloadType) <<
1338 ", ssrc=" << packet->header.ssrc <<
1339 ", len=" << packet->payload_length;
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001340 memset(&decoded_buffer_[*decoded_length], 0,
1341 decoder_frame_length_ * decoder->Channels() *
1342 sizeof(decoded_buffer_[0]));
Peter Kastingdce40cf2015-08-24 14:52:23 -07001343 decode_length = rtc::checked_cast<int>(decoder_frame_length_);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +00001344 } else if (!packet->primary) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001345 // This is a redundant payload; call the special decoder method.
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +00001346 LOG(LS_VERBOSE) << "Decoding packet (redundant):" <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001347 " ts=" << packet->header.timestamp <<
1348 ", sn=" << packet->header.sequenceNumber <<
1349 ", pt=" << static_cast<int>(packet->header.payloadType) <<
1350 ", ssrc=" << packet->header.ssrc <<
1351 ", len=" << packet->payload_length;
1352 decode_length = decoder->DecodeRedundant(
henrik.lundin@webrtc.org1eda4e32015-02-25 10:02:29 +00001353 packet->payload, packet->payload_length, fs_hz_,
minyue@webrtc.org7f7d7e32015-03-16 12:30:37 +00001354 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001355 &decoded_buffer_[*decoded_length], speech_type);
1356 } else {
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +00001357 LOG(LS_VERBOSE) << "Decoding packet: ts=" << packet->header.timestamp <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001358 ", sn=" << packet->header.sequenceNumber <<
1359 ", pt=" << static_cast<int>(packet->header.payloadType) <<
1360 ", ssrc=" << packet->header.ssrc <<
1361 ", len=" << packet->payload_length;
henrik.lundin@webrtc.org1eda4e32015-02-25 10:02:29 +00001362 decode_length =
minyue@webrtc.org7f7d7e32015-03-16 12:30:37 +00001363 decoder->Decode(
1364 packet->payload, packet->payload_length, fs_hz_,
1365 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1366 &decoded_buffer_[*decoded_length], speech_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001367 }
1368
1369 delete[] packet->payload;
1370 delete packet;
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001371 packet = NULL;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001372 if (decode_length > 0) {
1373 *decoded_length += decode_length;
1374 // Update |decoder_frame_length_| with number of samples per channel.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001375 decoder_frame_length_ =
Peter Kastingdce40cf2015-08-24 14:52:23 -07001376 static_cast<size_t>(decode_length) / decoder->Channels();
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001377 LOG(LS_VERBOSE) << "Decoded " << decode_length << " samples ("
1378 << decoder->Channels() << " channel(s) -> "
1379 << decoder_frame_length_ << " samples per channel)";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001380 } else if (decode_length < 0) {
1381 // Error.
Henrik Lundind67a2192015-08-03 12:54:37 +02001382 LOG(LS_WARNING) << "Decode " << decode_length << " " << payload_length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001383 *decoded_length = -1;
1384 PacketBuffer::DeleteAllPackets(packet_list);
1385 break;
1386 }
1387 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1388 // Guard against overflow.
Henrik Lundind67a2192015-08-03 12:54:37 +02001389 LOG(LS_WARNING) << "Decoded too much.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001390 PacketBuffer::DeleteAllPackets(packet_list);
1391 return kDecodedTooMuch;
1392 }
1393 if (!packet_list->empty()) {
1394 packet = packet_list->front();
1395 } else {
1396 packet = NULL;
1397 }
1398 } // End of decode loop.
1399
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001400 // If the list is not empty at this point, either a decoding error terminated
1401 // the while-loop, or list must hold exactly one CNG packet.
1402 assert(packet_list->empty() || *decoded_length < 0 ||
1403 (packet_list->size() == 1 && packet &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001404 decoder_database_->IsComfortNoise(packet->header.payloadType)));
1405 return 0;
1406}
1407
1408void NetEqImpl::DoNormal(const int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001409 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001410 assert(normal_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001411 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001412 normal_->Process(decoded_buffer, decoded_length, last_mode_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001413 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001414 if (decoded_length != 0) {
1415 last_mode_ = kModeNormal;
1416 }
1417
1418 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1419 if ((speech_type == AudioDecoder::kComfortNoise)
1420 || ((last_mode_ == kModeCodecInternalCng)
1421 && (decoded_length == 0))) {
1422 // TODO(hlundin): Remove second part of || statement above.
1423 last_mode_ = kModeCodecInternalCng;
1424 }
1425
1426 if (!play_dtmf) {
1427 dtmf_tone_generator_->Reset();
1428 }
1429}
1430
1431void NetEqImpl::DoMerge(int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001432 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001433 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001434 assert(merge_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001435 size_t new_length = merge_->Process(decoded_buffer, decoded_length,
1436 mute_factor_array_.get(),
1437 algorithm_buffer_.get());
1438 size_t expand_length_correction = new_length -
1439 decoded_length / algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001440
1441 // Update in-call and post-call statistics.
1442 if (expand_->MuteFactor(0) == 0) {
1443 // Expand generates only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001444 stats_.ExpandedNoiseSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001445 } else {
1446 // Expansion generates more than only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001447 stats_.ExpandedVoiceSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001448 }
1449
1450 last_mode_ = kModeMerge;
1451 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1452 if (speech_type == AudioDecoder::kComfortNoise) {
1453 last_mode_ = kModeCodecInternalCng;
1454 }
1455 expand_->Reset();
1456 if (!play_dtmf) {
1457 dtmf_tone_generator_->Reset();
1458 }
1459}
1460
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001461int NetEqImpl::DoExpand(bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001462 while ((sync_buffer_->FutureLength() - expand_->overlap_length()) <
Peter Kastingdce40cf2015-08-24 14:52:23 -07001463 output_size_samples_) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001464 algorithm_buffer_->Clear();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001465 int return_value = expand_->Process(algorithm_buffer_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001466 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001467
1468 // Update in-call and post-call statistics.
1469 if (expand_->MuteFactor(0) == 0) {
1470 // Expand operation generates only noise.
1471 stats_.ExpandedNoiseSamples(length);
1472 } else {
1473 // Expand operation generates more than only noise.
1474 stats_.ExpandedVoiceSamples(length);
1475 }
1476
1477 last_mode_ = kModeExpand;
1478
1479 if (return_value < 0) {
1480 return return_value;
1481 }
1482
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001483 sync_buffer_->PushBack(*algorithm_buffer_);
1484 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001485 }
1486 if (!play_dtmf) {
1487 dtmf_tone_generator_->Reset();
1488 }
1489 return 0;
1490}
1491
Henrik Lundincf808d22015-05-27 14:33:29 +02001492int NetEqImpl::DoAccelerate(int16_t* decoded_buffer,
1493 size_t decoded_length,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001494 AudioDecoder::SpeechType speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +02001495 bool play_dtmf,
1496 bool fast_accelerate) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001497 const size_t required_samples =
1498 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001499 size_t borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001500 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001501 size_t decoded_length_per_channel = decoded_length / num_channels;
1502 if (decoded_length_per_channel < required_samples) {
1503 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001504 borrowed_samples_per_channel = static_cast<int>(required_samples -
1505 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001506 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1507 decoded_buffer,
1508 sizeof(int16_t) * decoded_length);
1509 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1510 decoded_buffer);
1511 decoded_length = required_samples * num_channels;
1512 }
1513
Peter Kastingdce40cf2015-08-24 14:52:23 -07001514 size_t samples_removed;
Henrik Lundincf808d22015-05-27 14:33:29 +02001515 Accelerate::ReturnCodes return_code =
1516 accelerate_->Process(decoded_buffer, decoded_length, fast_accelerate,
1517 algorithm_buffer_.get(), &samples_removed);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001518 stats_.AcceleratedSamples(samples_removed);
1519 switch (return_code) {
1520 case Accelerate::kSuccess:
1521 last_mode_ = kModeAccelerateSuccess;
1522 break;
1523 case Accelerate::kSuccessLowEnergy:
1524 last_mode_ = kModeAccelerateLowEnergy;
1525 break;
1526 case Accelerate::kNoStretch:
1527 last_mode_ = kModeAccelerateFail;
1528 break;
1529 case Accelerate::kError:
1530 // TODO(hlundin): Map to kModeError instead?
1531 last_mode_ = kModeAccelerateFail;
1532 return kAccelerateError;
1533 }
1534
1535 if (borrowed_samples_per_channel > 0) {
1536 // Copy borrowed samples back to the |sync_buffer_|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001537 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001538 if (length < borrowed_samples_per_channel) {
1539 // This destroys the beginning of the buffer, but will not cause any
1540 // problems.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001541 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001542 sync_buffer_->Size() -
1543 borrowed_samples_per_channel);
1544 sync_buffer_->PushFrontZeros(borrowed_samples_per_channel - length);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001545 algorithm_buffer_->PopFront(length);
1546 assert(algorithm_buffer_->Empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001547 } else {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001548 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001549 borrowed_samples_per_channel,
1550 sync_buffer_->Size() -
1551 borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001552 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001553 }
1554 }
1555
1556 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1557 if (speech_type == AudioDecoder::kComfortNoise) {
1558 last_mode_ = kModeCodecInternalCng;
1559 }
1560 if (!play_dtmf) {
1561 dtmf_tone_generator_->Reset();
1562 }
1563 expand_->Reset();
1564 return 0;
1565}
1566
1567int NetEqImpl::DoPreemptiveExpand(int16_t* decoded_buffer,
1568 size_t decoded_length,
1569 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001570 bool play_dtmf) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001571 const size_t required_samples =
1572 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001573 size_t num_channels = algorithm_buffer_->Channels();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001574 size_t borrowed_samples_per_channel = 0;
1575 size_t old_borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001576 size_t decoded_length_per_channel = decoded_length / num_channels;
1577 if (decoded_length_per_channel < required_samples) {
1578 // Must move data from the |sync_buffer_| in order to get 30 ms.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001579 borrowed_samples_per_channel =
1580 required_samples - decoded_length_per_channel;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001581 // Calculate how many of these were already played out.
Peter Kastingf045e4d2015-06-10 21:15:38 -07001582 old_borrowed_samples_per_channel =
Peter Kastingdce40cf2015-08-24 14:52:23 -07001583 (borrowed_samples_per_channel > sync_buffer_->FutureLength()) ?
1584 (borrowed_samples_per_channel - sync_buffer_->FutureLength()) : 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001585 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1586 decoded_buffer,
1587 sizeof(int16_t) * decoded_length);
1588 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1589 decoded_buffer);
1590 decoded_length = required_samples * num_channels;
1591 }
1592
Peter Kastingdce40cf2015-08-24 14:52:23 -07001593 size_t samples_added;
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001594 PreemptiveExpand::ReturnCodes return_code = preemptive_expand_->Process(
Peter Kastingdce40cf2015-08-24 14:52:23 -07001595 decoded_buffer, decoded_length,
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001596 old_borrowed_samples_per_channel,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001597 algorithm_buffer_.get(), &samples_added);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001598 stats_.PreemptiveExpandedSamples(samples_added);
1599 switch (return_code) {
1600 case PreemptiveExpand::kSuccess:
1601 last_mode_ = kModePreemptiveExpandSuccess;
1602 break;
1603 case PreemptiveExpand::kSuccessLowEnergy:
1604 last_mode_ = kModePreemptiveExpandLowEnergy;
1605 break;
1606 case PreemptiveExpand::kNoStretch:
1607 last_mode_ = kModePreemptiveExpandFail;
1608 break;
1609 case PreemptiveExpand::kError:
1610 // TODO(hlundin): Map to kModeError instead?
1611 last_mode_ = kModePreemptiveExpandFail;
1612 return kPreemptiveExpandError;
1613 }
1614
1615 if (borrowed_samples_per_channel > 0) {
1616 // Copy borrowed samples back to the |sync_buffer_|.
1617 sync_buffer_->ReplaceAtIndex(
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001618 *algorithm_buffer_, borrowed_samples_per_channel,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001619 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001620 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001621 }
1622
1623 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1624 if (speech_type == AudioDecoder::kComfortNoise) {
1625 last_mode_ = kModeCodecInternalCng;
1626 }
1627 if (!play_dtmf) {
1628 dtmf_tone_generator_->Reset();
1629 }
1630 expand_->Reset();
1631 return 0;
1632}
1633
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001634int NetEqImpl::DoRfc3389Cng(PacketList* packet_list, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001635 if (!packet_list->empty()) {
1636 // Must have exactly one SID frame at this point.
1637 assert(packet_list->size() == 1);
1638 Packet* packet = packet_list->front();
1639 packet_list->pop_front();
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001640 if (!decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1641#ifdef LEGACY_BITEXACT
1642 // This can happen due to a bug in GetDecision. Change the payload type
1643 // to a CNG type, and move on. Note that this means that we are in fact
1644 // sending a non-CNG payload to the comfort noise decoder for decoding.
1645 // Clearly wrong, but will maintain bit-exactness with legacy.
1646 if (fs_hz_ == 8000) {
1647 packet->header.payloadType =
1648 decoder_database_->GetRtpPayloadType(kDecoderCNGnb);
1649 } else if (fs_hz_ == 16000) {
1650 packet->header.payloadType =
1651 decoder_database_->GetRtpPayloadType(kDecoderCNGwb);
1652 } else if (fs_hz_ == 32000) {
1653 packet->header.payloadType =
1654 decoder_database_->GetRtpPayloadType(kDecoderCNGswb32kHz);
1655 } else if (fs_hz_ == 48000) {
1656 packet->header.payloadType =
1657 decoder_database_->GetRtpPayloadType(kDecoderCNGswb48kHz);
1658 }
1659 assert(decoder_database_->IsComfortNoise(packet->header.payloadType));
1660#else
1661 LOG(LS_ERROR) << "Trying to decode non-CNG payload as CNG.";
1662 return kOtherError;
1663#endif
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001664 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001665 // UpdateParameters() deletes |packet|.
1666 if (comfort_noise_->UpdateParameters(packet) ==
1667 ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001668 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001669 return -comfort_noise_->internal_error_code();
1670 }
1671 }
1672 int cn_return = comfort_noise_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001673 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001674 expand_->Reset();
1675 last_mode_ = kModeRfc3389Cng;
1676 if (!play_dtmf) {
1677 dtmf_tone_generator_->Reset();
1678 }
1679 if (cn_return == ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001680 decoder_error_code_ = comfort_noise_->internal_error_code();
1681 return kComfortNoiseErrorCode;
1682 } else if (cn_return == ComfortNoise::kUnknownPayloadType) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001683 return kUnknownRtpPayloadType;
1684 }
1685 return 0;
1686}
1687
minyuel6d92bf52015-09-23 15:20:39 +02001688void NetEqImpl::DoCodecInternalCng(const int16_t* decoded_buffer,
1689 size_t decoded_length) {
1690 RTC_DCHECK(normal_.get());
1691 RTC_DCHECK(mute_factor_array_.get());
1692 normal_->Process(decoded_buffer, decoded_length, last_mode_,
1693 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001694 last_mode_ = kModeCodecInternalCng;
1695 expand_->Reset();
1696}
1697
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001698int NetEqImpl::DoDtmf(const DtmfEvent& dtmf_event, bool* play_dtmf) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001699 // This block of the code and the block further down, handling |dtmf_switch|
1700 // are commented out. Otherwise playing out-of-band DTMF would fail in VoE
1701 // test, DtmfTest.ManualSuccessfullySendsOutOfBandTelephoneEvents. This is
1702 // equivalent to |dtmf_switch| always be false.
1703 //
1704 // See http://webrtc-codereview.appspot.com/1195004/ for discussion
1705 // On this issue. This change might cause some glitches at the point of
1706 // switch from audio to DTMF. Issue 1545 is filed to track this.
1707 //
1708 // bool dtmf_switch = false;
1709 // if ((last_mode_ != kModeDtmf) && dtmf_tone_generator_->initialized()) {
1710 // // Special case; see below.
1711 // // We must catch this before calling Generate, since |initialized| is
1712 // // modified in that call.
1713 // dtmf_switch = true;
1714 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001715
1716 int dtmf_return_value = 0;
1717 if (!dtmf_tone_generator_->initialized()) {
1718 // Initialize if not already done.
1719 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1720 dtmf_event.volume);
1721 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001722
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001723 if (dtmf_return_value == 0) {
1724 // Generate DTMF signal.
1725 dtmf_return_value = dtmf_tone_generator_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001726 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001727 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001728
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001729 if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001730 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001731 return dtmf_return_value;
1732 }
1733
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001734 // if (dtmf_switch) {
1735 // // This is the special case where the previous operation was DTMF
1736 // // overdub, but the current instruction is "regular" DTMF. We must make
1737 // // sure that the DTMF does not have any discontinuities. The first DTMF
1738 // // sample that we generate now must be played out immediately, therefore
1739 // // it must be copied to the speech buffer.
1740 // // TODO(hlundin): This code seems incorrect. (Legacy.) Write test and
1741 // // verify correct operation.
1742 // assert(false);
1743 // // Must generate enough data to replace all of the |sync_buffer_|
1744 // // "future".
1745 // int required_length = sync_buffer_->FutureLength();
1746 // assert(dtmf_tone_generator_->initialized());
1747 // dtmf_return_value = dtmf_tone_generator_->Generate(required_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001748 // algorithm_buffer_);
1749 // assert((size_t) required_length == algorithm_buffer_->Size());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001750 // if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001751 // algorithm_buffer_->Zeros(output_size_samples_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001752 // return dtmf_return_value;
1753 // }
1754 //
1755 // // Overwrite the "future" part of the speech buffer with the new DTMF
1756 // // data.
1757 // // TODO(hlundin): It seems that this overwriting has gone lost.
1758 // // Not adapted for multi-channel yet.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001759 // assert(algorithm_buffer_->Channels() == 1);
1760 // if (algorithm_buffer_->Channels() != 1) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001761 // LOG(LS_WARNING) << "DTMF not supported for more than one channel";
1762 // return kStereoNotSupported;
1763 // }
1764 // // Shuffle the remaining data to the beginning of algorithm buffer.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001765 // algorithm_buffer_->PopFront(sync_buffer_->FutureLength());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001766 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001767
Peter Kastingb7e50542015-06-11 12:55:50 -07001768 sync_buffer_->IncreaseEndTimestamp(
1769 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001770 expand_->Reset();
1771 last_mode_ = kModeDtmf;
1772
1773 // Set to false because the DTMF is already in the algorithm buffer.
1774 *play_dtmf = false;
1775 return 0;
1776}
1777
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001778void NetEqImpl::DoAlternativePlc(bool increase_timestamp) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001779 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001780 size_t length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001781 if (decoder && decoder->HasDecodePlc()) {
1782 // Use the decoder's packet-loss concealment.
1783 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1784 int16_t decoded_buffer[kMaxFrameSize];
1785 length = decoder->DecodePlc(1, decoded_buffer);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001786 if (length > 0)
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001787 algorithm_buffer_->PushBackInterleaved(decoded_buffer, length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001788 } else {
1789 // Do simple zero-stuffing.
1790 length = output_size_samples_;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001791 algorithm_buffer_->Zeros(length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001792 // By not advancing the timestamp, NetEq inserts samples.
1793 stats_.AddZeros(length);
1794 }
1795 if (increase_timestamp) {
Peter Kastingb7e50542015-06-11 12:55:50 -07001796 sync_buffer_->IncreaseEndTimestamp(static_cast<uint32_t>(length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001797 }
1798 expand_->Reset();
1799}
1800
1801int NetEqImpl::DtmfOverdub(const DtmfEvent& dtmf_event, size_t num_channels,
1802 int16_t* output) const {
1803 size_t out_index = 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001804 size_t overdub_length = output_size_samples_; // Default value.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001805
1806 if (sync_buffer_->dtmf_index() > sync_buffer_->next_index()) {
1807 // Special operation for transition from "DTMF only" to "DTMF overdub".
1808 out_index = std::min(
1809 sync_buffer_->dtmf_index() - sync_buffer_->next_index(),
Peter Kastingdce40cf2015-08-24 14:52:23 -07001810 output_size_samples_);
1811 overdub_length = output_size_samples_ - out_index;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001812 }
1813
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001814 AudioMultiVector dtmf_output(num_channels);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001815 int dtmf_return_value = 0;
1816 if (!dtmf_tone_generator_->initialized()) {
1817 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1818 dtmf_event.volume);
1819 }
1820 if (dtmf_return_value == 0) {
1821 dtmf_return_value = dtmf_tone_generator_->Generate(overdub_length,
1822 &dtmf_output);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001823 assert(overdub_length == dtmf_output.Size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001824 }
1825 dtmf_output.ReadInterleaved(overdub_length, &output[out_index]);
1826 return dtmf_return_value < 0 ? dtmf_return_value : 0;
1827}
1828
Peter Kastingdce40cf2015-08-24 14:52:23 -07001829int NetEqImpl::ExtractPackets(size_t required_samples,
1830 PacketList* packet_list) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001831 bool first_packet = true;
1832 uint8_t prev_payload_type = 0;
1833 uint32_t prev_timestamp = 0;
1834 uint16_t prev_sequence_number = 0;
1835 bool next_packet_available = false;
1836
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001837 const RTPHeader* header = packet_buffer_->NextRtpHeader();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001838 assert(header);
1839 if (!header) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001840 LOG(LS_ERROR) << "Packet buffer unexpectedly empty.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001841 return -1;
1842 }
turaj@webrtc.org7df97062013-08-02 18:07:13 +00001843 uint32_t first_timestamp = header->timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001844 int extracted_samples = 0;
1845
1846 // Packet extraction loop.
1847 do {
1848 timestamp_ = header->timestamp;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001849 size_t discard_count = 0;
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001850 Packet* packet = packet_buffer_->GetNextPacket(&discard_count);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001851 // |header| may be invalid after the |packet_buffer_| operation.
1852 header = NULL;
1853 if (!packet) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001854 LOG(LS_ERROR) << "Should always be able to extract a packet here";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001855 assert(false); // Should always be able to extract a packet here.
1856 return -1;
1857 }
1858 stats_.PacketsDiscarded(discard_count);
1859 // Store waiting time in ms; packets->waiting_time is in "output blocks".
1860 stats_.StoreWaitingTime(packet->waiting_time * kOutputSizeMs);
1861 assert(packet->payload_length > 0);
1862 packet_list->push_back(packet); // Store packet in list.
1863
1864 if (first_packet) {
1865 first_packet = false;
minyue@webrtc.orgd7301772013-08-29 00:58:14 +00001866 decoded_packet_sequence_number_ = prev_sequence_number =
1867 packet->header.sequenceNumber;
1868 decoded_packet_timestamp_ = prev_timestamp = packet->header.timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001869 prev_payload_type = packet->header.payloadType;
1870 }
1871
1872 // Store number of extracted samples.
1873 int packet_duration = 0;
1874 AudioDecoder* decoder = decoder_database_->GetDecoder(
1875 packet->header.payloadType);
1876 if (decoder) {
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001877 if (packet->sync_packet) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001878 packet_duration = rtc::checked_cast<int>(decoder_frame_length_);
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001879 } else {
minyue@webrtc.org2c1bcf22015-02-17 10:17:09 +00001880 if (packet->primary) {
1881 packet_duration = decoder->PacketDuration(packet->payload,
1882 packet->payload_length);
1883 } else {
1884 packet_duration = decoder->
1885 PacketDurationRedundant(packet->payload, packet->payload_length);
1886 stats_.SecondaryDecodedSamples(packet_duration);
1887 }
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001888 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001889 } else {
Henrik Lundind67a2192015-08-03 12:54:37 +02001890 LOG(LS_WARNING) << "Unknown payload type "
1891 << static_cast<int>(packet->header.payloadType);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001892 assert(false);
1893 }
1894 if (packet_duration <= 0) {
1895 // Decoder did not return a packet duration. Assume that the packet
1896 // contains the same number of samples as the previous one.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001897 packet_duration = rtc::checked_cast<int>(decoder_frame_length_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001898 }
1899 extracted_samples = packet->header.timestamp - first_timestamp +
1900 packet_duration;
1901
1902 // Check what packet is available next.
1903 header = packet_buffer_->NextRtpHeader();
1904 next_packet_available = false;
1905 if (header && prev_payload_type == header->payloadType) {
1906 int16_t seq_no_diff = header->sequenceNumber - prev_sequence_number;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001907 size_t ts_diff = header->timestamp - prev_timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001908 if (seq_no_diff == 1 ||
1909 (seq_no_diff == 0 && ts_diff == decoder_frame_length_)) {
1910 // The next sequence number is available, or the next part of a packet
1911 // that was split into pieces upon insertion.
1912 next_packet_available = true;
1913 }
1914 prev_sequence_number = header->sequenceNumber;
1915 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07001916 } while (extracted_samples < rtc::checked_cast<int>(required_samples) &&
1917 next_packet_available);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001918
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00001919 if (extracted_samples > 0) {
1920 // Delete old packets only when we are going to decode something. Otherwise,
1921 // we could end up in the situation where we never decode anything, since
1922 // all incoming packets are considered too old but the buffer will also
1923 // never be flooded and flushed.
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001924 packet_buffer_->DiscardAllOldPackets(timestamp_);
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00001925 }
1926
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001927 return extracted_samples;
1928}
1929
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001930void NetEqImpl::UpdatePlcComponents(int fs_hz, size_t channels) {
1931 // Delete objects and create new ones.
1932 expand_.reset(expand_factory_->Create(background_noise_.get(),
1933 sync_buffer_.get(), &random_vector_,
Henrik Lundinbef77e22015-08-18 14:58:09 +02001934 &stats_, fs_hz, channels));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001935 merge_.reset(new Merge(fs_hz, channels, expand_.get(), sync_buffer_.get()));
1936}
1937
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001938void NetEqImpl::SetSampleRateAndChannels(int fs_hz, size_t channels) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001939 LOG(LS_VERBOSE) << "SetSampleRateAndChannels " << fs_hz << " " << channels;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001940 // TODO(hlundin): Change to an enumerator and skip assert.
1941 assert(fs_hz == 8000 || fs_hz == 16000 || fs_hz == 32000 || fs_hz == 48000);
1942 assert(channels > 0);
1943
1944 fs_hz_ = fs_hz;
1945 fs_mult_ = fs_hz / 8000;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001946 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001947 decoder_frame_length_ = 3 * output_size_samples_; // Initialize to 30ms.
1948
1949 last_mode_ = kModeNormal;
1950
1951 // Create a new array of mute factors and set all to 1.
1952 mute_factor_array_.reset(new int16_t[channels]);
1953 for (size_t i = 0; i < channels; ++i) {
1954 mute_factor_array_[i] = 16384; // 1.0 in Q14.
1955 }
1956
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001957 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02001958 if (cng_decoder)
1959 cng_decoder->Reset();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001960
1961 // Reinit post-decode VAD with new sample rate.
1962 assert(vad_.get()); // Cannot be NULL here.
1963 vad_->Init();
1964
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001965 // Delete algorithm buffer and create a new one.
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001966 algorithm_buffer_.reset(new AudioMultiVector(channels));
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001967
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001968 // Delete sync buffer and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001969 sync_buffer_.reset(new SyncBuffer(channels, kSyncBufferSize * fs_mult_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001970
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00001971 // Delete BackgroundNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001972 background_noise_.reset(new BackgroundNoise(channels));
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00001973 background_noise_->set_mode(background_noise_mode_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001974
1975 // Reset random vector.
1976 random_vector_.Reset();
1977
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001978 UpdatePlcComponents(fs_hz, channels);
1979
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001980 // Move index so that we create a small set of future samples (all 0).
1981 sync_buffer_->set_next_index(sync_buffer_->next_index() -
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001982 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001983
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001984 normal_.reset(new Normal(fs_hz, decoder_database_.get(), *background_noise_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001985 expand_.get()));
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +00001986 accelerate_.reset(
1987 accelerate_factory_->Create(fs_hz, channels, *background_noise_));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001988 preemptive_expand_.reset(preemptive_expand_factory_->Create(
Peter Kastingdce40cf2015-08-24 14:52:23 -07001989 fs_hz, channels, *background_noise_, expand_->overlap_length()));
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001990
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001991 // Delete ComfortNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001992 comfort_noise_.reset(new ComfortNoise(fs_hz, decoder_database_.get(),
1993 sync_buffer_.get()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001994
1995 // Verify that |decoded_buffer_| is long enough.
1996 if (decoded_buffer_length_ < kMaxFrameSize * channels) {
1997 // Reallocate to larger size.
1998 decoded_buffer_length_ = kMaxFrameSize * channels;
1999 decoded_buffer_.reset(new int16_t[decoded_buffer_length_]);
2000 }
2001
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002002 // Create DecisionLogic if it is not created yet, then communicate new sample
2003 // rate and output size to DecisionLogic object.
2004 if (!decision_logic_.get()) {
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002005 CreateDecisionLogic();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002006 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002007 decision_logic_->SetSampleRate(fs_hz_, output_size_samples_);
2008}
2009
2010NetEqOutputType NetEqImpl::LastOutputType() {
2011 assert(vad_.get());
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002012 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002013 if (last_mode_ == kModeCodecInternalCng || last_mode_ == kModeRfc3389Cng) {
2014 return kOutputCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002015 } else if (last_mode_ == kModeExpand && expand_->MuteFactor(0) == 0) {
2016 // Expand mode has faded down to background noise only (very long expand).
2017 return kOutputPLCtoCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002018 } else if (last_mode_ == kModeExpand) {
2019 return kOutputPLC;
wu@webrtc.org24301a62013-12-13 19:17:43 +00002020 } else if (vad_->running() && !vad_->active_speech()) {
2021 return kOutputVADPassive;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002022 } else {
2023 return kOutputNormal;
2024 }
2025}
2026
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002027void NetEqImpl::CreateDecisionLogic() {
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002028 decision_logic_.reset(DecisionLogic::Create(fs_hz_, output_size_samples_,
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002029 playout_mode_,
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002030 decoder_database_.get(),
2031 *packet_buffer_.get(),
2032 delay_manager_.get(),
2033 buffer_level_filter_.get()));
2034}
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002035} // namespace webrtc