blob: 0fe911ba3f2f4cb9088725debaee8ce79b011ea8 [file] [log] [blame]
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001/*
2 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000011#include "webrtc/modules/audio_coding/neteq/neteq_impl.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000012
13#include <assert.h>
14#include <memory.h> // memset
15
16#include <algorithm>
17
henrik.lundin9c3efd02015-08-27 13:12:22 -070018#include "webrtc/base/checks.h"
Henrik Lundind67a2192015-08-03 12:54:37 +020019#include "webrtc/base/logging.h"
Peter Kastingdce40cf2015-08-24 14:52:23 -070020#include "webrtc/base/safe_conversions.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000021#include "webrtc/common_audio/signal_processing/include/signal_processing_library.h"
kwiberg@webrtc.orge04a93b2014-12-09 10:12:53 +000022#include "webrtc/modules/audio_coding/codecs/audio_decoder.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000023#include "webrtc/modules/audio_coding/neteq/accelerate.h"
24#include "webrtc/modules/audio_coding/neteq/background_noise.h"
25#include "webrtc/modules/audio_coding/neteq/buffer_level_filter.h"
26#include "webrtc/modules/audio_coding/neteq/comfort_noise.h"
27#include "webrtc/modules/audio_coding/neteq/decision_logic.h"
28#include "webrtc/modules/audio_coding/neteq/decoder_database.h"
29#include "webrtc/modules/audio_coding/neteq/defines.h"
30#include "webrtc/modules/audio_coding/neteq/delay_manager.h"
31#include "webrtc/modules/audio_coding/neteq/delay_peak_detector.h"
32#include "webrtc/modules/audio_coding/neteq/dtmf_buffer.h"
33#include "webrtc/modules/audio_coding/neteq/dtmf_tone_generator.h"
34#include "webrtc/modules/audio_coding/neteq/expand.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000035#include "webrtc/modules/audio_coding/neteq/merge.h"
henrik.lundin48ed9302015-10-29 05:36:24 -070036#include "webrtc/modules/audio_coding/neteq/nack.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000037#include "webrtc/modules/audio_coding/neteq/normal.h"
38#include "webrtc/modules/audio_coding/neteq/packet_buffer.h"
39#include "webrtc/modules/audio_coding/neteq/packet.h"
40#include "webrtc/modules/audio_coding/neteq/payload_splitter.h"
41#include "webrtc/modules/audio_coding/neteq/post_decode_vad.h"
42#include "webrtc/modules/audio_coding/neteq/preemptive_expand.h"
43#include "webrtc/modules/audio_coding/neteq/sync_buffer.h"
44#include "webrtc/modules/audio_coding/neteq/timestamp_scaler.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010045#include "webrtc/modules/include/module_common_types.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010046#include "webrtc/system_wrappers/include/critical_section_wrapper.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000047
48// Modify the code to obtain backwards bit-exactness. Once bit-exactness is no
49// longer required, this #define should be removed (and the code that it
50// enables).
51#define LEGACY_BITEXACT
52
53namespace webrtc {
54
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +000055NetEqImpl::NetEqImpl(const NetEq::Config& config,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000056 BufferLevelFilter* buffer_level_filter,
57 DecoderDatabase* decoder_database,
58 DelayManager* delay_manager,
59 DelayPeakDetector* delay_peak_detector,
60 DtmfBuffer* dtmf_buffer,
61 DtmfToneGenerator* dtmf_tone_generator,
62 PacketBuffer* packet_buffer,
63 PayloadSplitter* payload_splitter,
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +000064 TimestampScaler* timestamp_scaler,
65 AccelerateFactory* accelerate_factory,
66 ExpandFactory* expand_factory,
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +000067 PreemptiveExpandFactory* preemptive_expand_factory,
68 bool create_components)
henrik.lundin@webrtc.org2f816bb2014-06-05 10:37:13 +000069 : crit_sect_(CriticalSectionWrapper::CreateCriticalSection()),
70 buffer_level_filter_(buffer_level_filter),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000071 decoder_database_(decoder_database),
72 delay_manager_(delay_manager),
73 delay_peak_detector_(delay_peak_detector),
74 dtmf_buffer_(dtmf_buffer),
75 dtmf_tone_generator_(dtmf_tone_generator),
76 packet_buffer_(packet_buffer),
77 payload_splitter_(payload_splitter),
78 timestamp_scaler_(timestamp_scaler),
79 vad_(new PostDecodeVad()),
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +000080 expand_factory_(expand_factory),
81 accelerate_factory_(accelerate_factory),
82 preemptive_expand_factory_(preemptive_expand_factory),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000083 last_mode_(kModeNormal),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000084 decoded_buffer_length_(kMaxFrameSize),
85 decoded_buffer_(new int16_t[decoded_buffer_length_]),
86 playout_timestamp_(0),
87 new_codec_(false),
88 timestamp_(0),
89 reset_decoder_(false),
henrik.lundin48ed9302015-10-29 05:36:24 -070090 current_rtp_payload_type_(0xFF), // Invalid RTP payload type.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000091 current_cng_rtp_payload_type_(0xFF), // Invalid RTP payload type.
92 ssrc_(0),
93 first_packet_(true),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000094 error_code_(0),
95 decoder_error_code_(0),
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +000096 background_noise_mode_(config.background_noise_mode),
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +000097 playout_mode_(config.playout_mode),
Henrik Lundincf808d22015-05-27 14:33:29 +020098 enable_fast_accelerate_(config.enable_fast_accelerate),
henrik.lundin48ed9302015-10-29 05:36:24 -070099 nack_enabled_(false) {
Henrik Lundin905495c2015-05-25 16:58:41 +0200100 LOG(LS_INFO) << "NetEq config: " << config.ToString();
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +0000101 int fs = config.sample_rate_hz;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000102 if (fs != 8000 && fs != 16000 && fs != 32000 && fs != 48000) {
103 LOG(LS_ERROR) << "Sample rate " << fs << " Hz not supported. " <<
104 "Changing to 8000 Hz.";
105 fs = 8000;
106 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000107 fs_hz_ = fs;
108 fs_mult_ = fs / 8000;
henrik.lundind89814b2015-11-23 06:49:25 -0800109 last_output_sample_rate_hz_ = fs;
Peter Kastingdce40cf2015-08-24 14:52:23 -0700110 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000111 decoder_frame_length_ = 3 * output_size_samples_;
112 WebRtcSpl_Init();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000113 if (create_components) {
114 SetSampleRateAndChannels(fs, 1); // Default is 1 channel.
115 }
henrik.lundin9bc26672015-11-02 03:25:57 -0800116 RTC_DCHECK(!vad_->enabled());
117 if (config.enable_post_decode_vad) {
118 vad_->Enable();
119 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000120}
121
Henrik Lundind67a2192015-08-03 12:54:37 +0200122NetEqImpl::~NetEqImpl() = default;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000123
124int NetEqImpl::InsertPacket(const WebRtcRTPHeader& rtp_header,
kwibergee2bac22015-11-11 10:34:00 -0800125 rtc::ArrayView<const uint8_t> payload,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000126 uint32_t receive_timestamp) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000127 CriticalSectionScoped lock(crit_sect_.get());
kwibergee2bac22015-11-11 10:34:00 -0800128 int error =
129 InsertPacketInternal(rtp_header, payload, receive_timestamp, false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000130 if (error != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000131 error_code_ = error;
132 return kFail;
133 }
134 return kOK;
135}
136
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000137int NetEqImpl::InsertSyncPacket(const WebRtcRTPHeader& rtp_header,
138 uint32_t receive_timestamp) {
139 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000140 const uint8_t kSyncPayload[] = { 's', 'y', 'n', 'c' };
kwibergee2bac22015-11-11 10:34:00 -0800141 int error =
142 InsertPacketInternal(rtp_header, kSyncPayload, receive_timestamp, true);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000143
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000144 if (error != 0) {
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000145 error_code_ = error;
146 return kFail;
147 }
148 return kOK;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000149}
150
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000151int NetEqImpl::GetAudio(size_t max_length, int16_t* output_audio,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700152 size_t* samples_per_channel, int* num_channels,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000153 NetEqOutputType* type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000154 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000155 int error = GetAudioInternal(max_length, output_audio, samples_per_channel,
156 num_channels);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000157 if (error != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000158 error_code_ = error;
159 return kFail;
160 }
161 if (type) {
162 *type = LastOutputType();
163 }
henrik.lundind89814b2015-11-23 06:49:25 -0800164 last_output_sample_rate_hz_ =
165 rtc::checked_cast<int>(*samples_per_channel * 100);
166 RTC_DCHECK(last_output_sample_rate_hz_ == 8000 ||
167 last_output_sample_rate_hz_ == 16000 ||
168 last_output_sample_rate_hz_ == 32000 ||
169 last_output_sample_rate_hz_ == 48000)
170 << "Unexpected sample rate " << last_output_sample_rate_hz_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000171 return kOK;
172}
173
kwibergee1879c2015-10-29 06:20:28 -0700174int NetEqImpl::RegisterPayloadType(NetEqDecoder codec,
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800175 const std::string& name,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000176 uint8_t rtp_payload_type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000177 CriticalSectionScoped lock(crit_sect_.get());
Henrik Lundind67a2192015-08-03 12:54:37 +0200178 LOG(LS_VERBOSE) << "RegisterPayloadType "
kwibergee1879c2015-10-29 06:20:28 -0700179 << static_cast<int>(rtp_payload_type) << " "
180 << static_cast<int>(codec);
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800181 int ret = decoder_database_->RegisterPayload(rtp_payload_type, codec, name);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000182 if (ret != DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000183 switch (ret) {
184 case DecoderDatabase::kInvalidRtpPayloadType:
185 error_code_ = kInvalidRtpPayloadType;
186 break;
187 case DecoderDatabase::kCodecNotSupported:
188 error_code_ = kCodecNotSupported;
189 break;
190 case DecoderDatabase::kDecoderExists:
191 error_code_ = kDecoderExists;
192 break;
193 default:
194 error_code_ = kOtherError;
195 }
196 return kFail;
197 }
198 return kOK;
199}
200
201int NetEqImpl::RegisterExternalDecoder(AudioDecoder* decoder,
kwibergee1879c2015-10-29 06:20:28 -0700202 NetEqDecoder codec,
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800203 const std::string& codec_name,
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 "
kwibergee1879c2015-10-29 06:20:28 -0700208 << static_cast<int>(rtp_payload_type) << " "
209 << static_cast<int>(codec);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000210 if (!decoder) {
211 LOG(LS_ERROR) << "Cannot register external decoder with NULL pointer";
212 assert(false);
213 return kFail;
214 }
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800215 int ret = decoder_database_->InsertExternal(
216 rtp_payload_type, codec, codec_name, sample_rate_hz, decoder);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000217 if (ret != DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000218 switch (ret) {
219 case DecoderDatabase::kInvalidRtpPayloadType:
220 error_code_ = kInvalidRtpPayloadType;
221 break;
222 case DecoderDatabase::kCodecNotSupported:
223 error_code_ = kCodecNotSupported;
224 break;
225 case DecoderDatabase::kDecoderExists:
226 error_code_ = kDecoderExists;
227 break;
228 case DecoderDatabase::kInvalidSampleRate:
229 error_code_ = kInvalidSampleRate;
230 break;
231 case DecoderDatabase::kInvalidPointer:
232 error_code_ = kInvalidPointer;
233 break;
234 default:
235 error_code_ = kOtherError;
236 }
237 return kFail;
238 }
239 return kOK;
240}
241
242int NetEqImpl::RemovePayloadType(uint8_t rtp_payload_type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000243 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000244 int ret = decoder_database_->Remove(rtp_payload_type);
245 if (ret == DecoderDatabase::kOK) {
246 return kOK;
247 } else if (ret == DecoderDatabase::kDecoderNotFound) {
248 error_code_ = kDecoderNotFound;
249 } else {
250 error_code_ = kOtherError;
251 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000252 return kFail;
253}
254
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000255bool NetEqImpl::SetMinimumDelay(int delay_ms) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000256 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000257 if (delay_ms >= 0 && delay_ms < 10000) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000258 assert(delay_manager_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000259 return delay_manager_->SetMinimumDelay(delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000260 }
261 return false;
262}
263
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000264bool NetEqImpl::SetMaximumDelay(int delay_ms) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000265 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000266 if (delay_ms >= 0 && delay_ms < 10000) {
267 assert(delay_manager_.get());
268 return delay_manager_->SetMaximumDelay(delay_ms);
269 }
270 return false;
271}
272
273int NetEqImpl::LeastRequiredDelayMs() const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000274 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000275 assert(delay_manager_.get());
276 return delay_manager_->least_required_delay_ms();
277}
278
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200279int NetEqImpl::SetTargetDelay() {
280 return kNotImplemented;
281}
282
283int NetEqImpl::TargetDelay() {
284 return kNotImplemented;
285}
286
henrik.lundin9c3efd02015-08-27 13:12:22 -0700287int NetEqImpl::CurrentDelayMs() const {
288 CriticalSectionScoped lock(crit_sect_.get());
289 if (fs_hz_ == 0)
290 return 0;
291 // Sum up the samples in the packet buffer with the future length of the sync
292 // buffer, and divide the sum by the sample rate.
293 const size_t delay_samples =
294 packet_buffer_->NumSamplesInBuffer(decoder_database_.get(),
295 decoder_frame_length_) +
296 sync_buffer_->FutureLength();
297 // The division below will truncate.
298 const int delay_ms =
299 static_cast<int>(delay_samples) / rtc::CheckedDivExact(fs_hz_, 1000);
300 return delay_ms;
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200301}
302
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000303// Deprecated.
304// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000305void NetEqImpl::SetPlayoutMode(NetEqPlayoutMode mode) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000306 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000307 if (mode != playout_mode_) {
308 playout_mode_ = mode;
309 CreateDecisionLogic();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000310 }
311}
312
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000313// Deprecated.
314// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000315NetEqPlayoutMode NetEqImpl::PlayoutMode() const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000316 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000317 return playout_mode_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000318}
319
320int NetEqImpl::NetworkStatistics(NetEqNetworkStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000321 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000322 assert(decoder_database_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700323 const size_t total_samples_in_buffers =
Peter Kasting728d9032015-06-11 14:31:38 -0700324 packet_buffer_->NumSamplesInBuffer(decoder_database_.get(),
325 decoder_frame_length_) +
Peter Kastingdce40cf2015-08-24 14:52:23 -0700326 sync_buffer_->FutureLength();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000327 assert(delay_manager_.get());
328 assert(decision_logic_.get());
329 stats_.GetNetworkStatistics(fs_hz_, total_samples_in_buffers,
330 decoder_frame_length_, *delay_manager_.get(),
331 *decision_logic_.get(), stats);
332 return 0;
333}
334
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000335void NetEqImpl::GetRtcpStatistics(RtcpStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000336 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000337 if (stats) {
338 rtcp_.GetStatistics(false, stats);
339 }
340}
341
342void NetEqImpl::GetRtcpStatisticsNoReset(RtcpStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000343 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000344 if (stats) {
345 rtcp_.GetStatistics(true, stats);
346 }
347}
348
349void NetEqImpl::EnableVad() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000350 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000351 assert(vad_.get());
352 vad_->Enable();
353}
354
355void NetEqImpl::DisableVad() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000356 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000357 assert(vad_.get());
358 vad_->Disable();
359}
360
wu@webrtc.org94454b72014-06-05 20:34:08 +0000361bool NetEqImpl::GetPlayoutTimestamp(uint32_t* timestamp) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000362 CriticalSectionScoped lock(crit_sect_.get());
wu@webrtc.org94454b72014-06-05 20:34:08 +0000363 if (first_packet_) {
364 // We don't have a valid RTP timestamp until we have decoded our first
365 // RTP packet.
366 return false;
367 }
368 *timestamp = timestamp_scaler_->ToExternal(playout_timestamp_);
369 return true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000370}
371
henrik.lundind89814b2015-11-23 06:49:25 -0800372int NetEqImpl::last_output_sample_rate_hz() const {
373 CriticalSectionScoped lock(crit_sect_.get());
374 return last_output_sample_rate_hz_;
375}
376
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200377int NetEqImpl::SetTargetNumberOfChannels() {
378 return kNotImplemented;
379}
380
381int NetEqImpl::SetTargetSampleRate() {
382 return kNotImplemented;
383}
384
henrik.lundin@webrtc.orgb0f4b3d2014-11-04 08:53:10 +0000385int NetEqImpl::LastError() const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000386 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000387 return error_code_;
388}
389
390int NetEqImpl::LastDecoderError() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000391 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000392 return decoder_error_code_;
393}
394
395void NetEqImpl::FlushBuffers() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000396 CriticalSectionScoped lock(crit_sect_.get());
Henrik Lundind67a2192015-08-03 12:54:37 +0200397 LOG(LS_VERBOSE) << "FlushBuffers";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000398 packet_buffer_->Flush();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000399 assert(sync_buffer_.get());
400 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000401 sync_buffer_->Flush();
402 sync_buffer_->set_next_index(sync_buffer_->next_index() -
403 expand_->overlap_length());
404 // Set to wait for new codec.
405 first_packet_ = true;
406}
407
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000408void NetEqImpl::PacketBufferStatistics(int* current_num_packets,
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000409 int* max_num_packets) const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000410 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000411 packet_buffer_->BufferStat(current_num_packets, max_num_packets);
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000412}
413
henrik.lundin48ed9302015-10-29 05:36:24 -0700414void NetEqImpl::EnableNack(size_t max_nack_list_size) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000415 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin48ed9302015-10-29 05:36:24 -0700416 if (!nack_enabled_) {
417 const int kNackThresholdPackets = 2;
418 nack_.reset(Nack::Create(kNackThresholdPackets));
419 nack_enabled_ = true;
420 nack_->UpdateSampleRate(fs_hz_);
421 }
422 nack_->SetMaxNackListSize(max_nack_list_size);
423}
424
425void NetEqImpl::DisableNack() {
426 CriticalSectionScoped lock(crit_sect_.get());
427 nack_.reset();
428 nack_enabled_ = false;
429}
430
431std::vector<uint16_t> NetEqImpl::GetNackList(int64_t round_trip_time_ms) const {
432 CriticalSectionScoped lock(crit_sect_.get());
433 if (!nack_enabled_) {
434 return std::vector<uint16_t>();
435 }
436 RTC_DCHECK(nack_.get());
437 return nack_->GetNackList(round_trip_time_ms);
minyue@webrtc.orgd7301772013-08-29 00:58:14 +0000438}
439
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000440const SyncBuffer* NetEqImpl::sync_buffer_for_test() const {
441 CriticalSectionScoped lock(crit_sect_.get());
442 return sync_buffer_.get();
443}
444
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000445// Methods below this line are private.
446
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000447int NetEqImpl::InsertPacketInternal(const WebRtcRTPHeader& rtp_header,
kwibergee2bac22015-11-11 10:34:00 -0800448 rtc::ArrayView<const uint8_t> payload,
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000449 uint32_t receive_timestamp,
450 bool is_sync_packet) {
kwibergee2bac22015-11-11 10:34:00 -0800451 if (payload.empty()) {
452 LOG_F(LS_ERROR) << "payload is empty";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000453 return kInvalidPointer;
454 }
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000455 // Sanity checks for sync-packets.
456 if (is_sync_packet) {
457 if (decoder_database_->IsDtmf(rtp_header.header.payloadType) ||
458 decoder_database_->IsRed(rtp_header.header.payloadType) ||
459 decoder_database_->IsComfortNoise(rtp_header.header.payloadType)) {
460 LOG_F(LS_ERROR) << "Sync-packet with an unacceptable payload type "
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000461 << static_cast<int>(rtp_header.header.payloadType);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000462 return kSyncPacketNotAccepted;
463 }
464 if (first_packet_ ||
465 rtp_header.header.payloadType != current_rtp_payload_type_ ||
466 rtp_header.header.ssrc != ssrc_) {
467 // Even if |current_rtp_payload_type_| is 0xFF, sync-packet isn't
468 // accepted.
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000469 LOG_F(LS_ERROR)
470 << "Changing codec, SSRC or first packet with sync-packet.";
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000471 return kSyncPacketNotAccepted;
472 }
473 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000474 PacketList packet_list;
475 RTPHeader main_header;
476 {
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000477 // Convert to Packet.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000478 // Create |packet| within this separate scope, since it should not be used
479 // directly once it's been inserted in the packet list. This way, |packet|
480 // is not defined outside of this block.
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000481 Packet* packet = new Packet;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000482 packet->header.markerBit = false;
483 packet->header.payloadType = rtp_header.header.payloadType;
484 packet->header.sequenceNumber = rtp_header.header.sequenceNumber;
485 packet->header.timestamp = rtp_header.header.timestamp;
486 packet->header.ssrc = rtp_header.header.ssrc;
487 packet->header.numCSRCs = 0;
kwibergee2bac22015-11-11 10:34:00 -0800488 packet->payload_length = payload.size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000489 packet->primary = true;
490 packet->waiting_time = 0;
491 packet->payload = new uint8_t[packet->payload_length];
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000492 packet->sync_packet = is_sync_packet;
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +0000493 if (!packet->payload) {
494 LOG_F(LS_ERROR) << "Payload pointer is NULL.";
495 }
kwibergee2bac22015-11-11 10:34:00 -0800496 assert(!payload.empty()); // Already checked above.
497 memcpy(packet->payload, payload.data(), packet->payload_length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000498 // Insert packet in a packet list.
499 packet_list.push_back(packet);
500 // Save main payloads header for later.
501 memcpy(&main_header, &packet->header, sizeof(main_header));
502 }
503
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000504 bool update_sample_rate_and_channels = false;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000505 // Reinitialize NetEq if it's needed (changed SSRC or first call).
506 if ((main_header.ssrc != ssrc_) || first_packet_) {
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000507 // Note: |first_packet_| will be cleared further down in this method, once
508 // the packet has been successfully inserted into the packet buffer.
509
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000510 rtcp_.Init(main_header.sequenceNumber);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000511
512 // Flush the packet buffer and DTMF buffer.
513 packet_buffer_->Flush();
514 dtmf_buffer_->Flush();
515
516 // Store new SSRC.
517 ssrc_ = main_header.ssrc;
518
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000519 // Update audio buffer timestamp.
520 sync_buffer_->IncreaseEndTimestamp(main_header.timestamp - timestamp_);
521
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000522 // Update codecs.
523 timestamp_ = main_header.timestamp;
524 current_rtp_payload_type_ = main_header.payloadType;
525
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000526 // Reset timestamp scaling.
527 timestamp_scaler_->Reset();
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000528
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000529 // Trigger an update of sampling rate and the number of channels.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000530 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000531 }
532
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000533 // Update RTCP statistics, only for regular packets.
534 if (!is_sync_packet)
535 rtcp_.Update(main_header, receive_timestamp);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000536
537 // Check for RED payload type, and separate payloads into several packets.
538 if (decoder_database_->IsRed(main_header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000539 assert(!is_sync_packet); // We had a sanity check for this.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000540 if (payload_splitter_->SplitRed(&packet_list) != PayloadSplitter::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000541 PacketBuffer::DeleteAllPackets(&packet_list);
542 return kRedundancySplitError;
543 }
544 // Only accept a few RED payloads of the same type as the main data,
545 // DTMF events and CNG.
546 payload_splitter_->CheckRedPayloads(&packet_list, *decoder_database_);
547 // Update the stored main payload header since the main payload has now
548 // changed.
549 memcpy(&main_header, &packet_list.front()->header, sizeof(main_header));
550 }
551
552 // Check payload types.
553 if (decoder_database_->CheckPayloadTypes(packet_list) ==
554 DecoderDatabase::kDecoderNotFound) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000555 PacketBuffer::DeleteAllPackets(&packet_list);
556 return kUnknownRtpPayloadType;
557 }
558
559 // Scale timestamp to internal domain (only for some codecs).
560 timestamp_scaler_->ToInternal(&packet_list);
561
562 // Process DTMF payloads. Cycle through the list of packets, and pick out any
563 // DTMF payloads found.
564 PacketList::iterator it = packet_list.begin();
565 while (it != packet_list.end()) {
566 Packet* current_packet = (*it);
567 assert(current_packet);
568 assert(current_packet->payload);
569 if (decoder_database_->IsDtmf(current_packet->header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000570 assert(!current_packet->sync_packet); // We had a sanity check for this.
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000571 DtmfEvent event;
572 int ret = DtmfBuffer::ParseEvent(
573 current_packet->header.timestamp,
574 current_packet->payload,
575 current_packet->payload_length,
576 &event);
577 if (ret != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000578 PacketBuffer::DeleteAllPackets(&packet_list);
579 return kDtmfParsingError;
580 }
581 if (dtmf_buffer_->InsertEvent(event) != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000582 PacketBuffer::DeleteAllPackets(&packet_list);
583 return kDtmfInsertError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000584 }
585 // TODO(hlundin): Let the destructor of Packet handle the payload.
586 delete [] current_packet->payload;
587 delete current_packet;
588 it = packet_list.erase(it);
589 } else {
590 ++it;
591 }
592 }
593
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000594 // Check for FEC in packets, and separate payloads into several packets.
595 int ret = payload_splitter_->SplitFec(&packet_list, decoder_database_.get());
596 if (ret != PayloadSplitter::kOK) {
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000597 PacketBuffer::DeleteAllPackets(&packet_list);
598 switch (ret) {
599 case PayloadSplitter::kUnknownPayloadType:
600 return kUnknownRtpPayloadType;
601 default:
602 return kOtherError;
603 }
604 }
605
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000606 // Split payloads into smaller chunks. This also verifies that all payloads
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000607 // are of a known payload type. SplitAudio() method is protected against
608 // sync-packets.
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +0000609 ret = payload_splitter_->SplitAudio(&packet_list, *decoder_database_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000610 if (ret != PayloadSplitter::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000611 PacketBuffer::DeleteAllPackets(&packet_list);
612 switch (ret) {
613 case PayloadSplitter::kUnknownPayloadType:
614 return kUnknownRtpPayloadType;
615 case PayloadSplitter::kFrameSplitError:
616 return kFrameSplitError;
617 default:
618 return kOtherError;
619 }
620 }
621
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000622 // Update bandwidth estimate, if the packet is not sync-packet.
623 if (!packet_list.empty() && !packet_list.front()->sync_packet) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000624 // The list can be empty here if we got nothing but DTMF payloads.
625 AudioDecoder* decoder =
626 decoder_database_->GetDecoder(main_header.payloadType);
627 assert(decoder); // Should always get a valid object, since we have
628 // already checked that the payload types are known.
629 decoder->IncomingPacket(packet_list.front()->payload,
630 packet_list.front()->payload_length,
631 packet_list.front()->header.sequenceNumber,
632 packet_list.front()->header.timestamp,
633 receive_timestamp);
634 }
635
henrik.lundin48ed9302015-10-29 05:36:24 -0700636 if (nack_enabled_) {
637 RTC_DCHECK(nack_);
638 if (update_sample_rate_and_channels) {
639 nack_->Reset();
640 }
641 nack_->UpdateLastReceivedPacket(packet_list.front()->header.sequenceNumber,
642 packet_list.front()->header.timestamp);
643 }
644
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000645 // Insert packets in buffer.
henrik.lundin116c84e2015-08-27 13:14:48 -0700646 const size_t buffer_length_before_insert =
647 packet_buffer_->NumPacketsInBuffer();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000648 ret = packet_buffer_->InsertPacketList(
649 &packet_list,
650 *decoder_database_,
651 &current_rtp_payload_type_,
652 &current_cng_rtp_payload_type_);
653 if (ret == PacketBuffer::kFlushed) {
654 // Reset DSP timestamp etc. if packet buffer flushed.
655 new_codec_ = true;
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000656 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000657 } else if (ret != PacketBuffer::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000658 PacketBuffer::DeleteAllPackets(&packet_list);
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000659 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000660 }
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000661
662 if (first_packet_) {
663 first_packet_ = false;
664 // Update the codec on the next GetAudio call.
665 new_codec_ = true;
666 }
667
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000668 if (current_rtp_payload_type_ != 0xFF) {
669 const DecoderDatabase::DecoderInfo* dec_info =
670 decoder_database_->GetDecoderInfo(current_rtp_payload_type_);
671 if (!dec_info) {
672 assert(false); // Already checked that the payload type is known.
673 }
674 }
675
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000676 if (update_sample_rate_and_channels && !packet_buffer_->Empty()) {
677 // We do not use |current_rtp_payload_type_| to |set payload_type|, but
678 // get the next RTP header from |packet_buffer_| to obtain the payload type.
679 // The reason for it is the following corner case. If NetEq receives a
680 // CNG packet with a sample rate different than the current CNG then it
681 // flushes its buffer, assuming send codec must have been changed. However,
682 // payload type of the hypothetically new send codec is not known.
683 const RTPHeader* rtp_header = packet_buffer_->NextRtpHeader();
684 assert(rtp_header);
685 int payload_type = rtp_header->payloadType;
686 AudioDecoder* decoder = decoder_database_->GetDecoder(payload_type);
687 assert(decoder); // Payloads are already checked to be valid.
688 const DecoderDatabase::DecoderInfo* decoder_info =
689 decoder_database_->GetDecoderInfo(payload_type);
690 assert(decoder_info);
691 if (decoder_info->fs_hz != fs_hz_ ||
henrik.lundin48ed9302015-10-29 05:36:24 -0700692 decoder->Channels() != algorithm_buffer_->Channels()) {
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +0000693 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->Channels());
henrik.lundin48ed9302015-10-29 05:36:24 -0700694 }
695 if (nack_enabled_) {
696 RTC_DCHECK(nack_);
697 // Update the sample rate even if the rate is not new, because of Reset().
698 nack_->UpdateSampleRate(fs_hz_);
699 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000700 }
701
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000702 // TODO(hlundin): Move this code to DelayManager class.
703 const DecoderDatabase::DecoderInfo* dec_info =
704 decoder_database_->GetDecoderInfo(main_header.payloadType);
705 assert(dec_info); // Already checked that the payload type is known.
706 delay_manager_->LastDecoderType(dec_info->codec_type);
707 if (delay_manager_->last_pack_cng_or_dtmf() == 0) {
708 // Calculate the total speech length carried in each packet.
henrik.lundin116c84e2015-08-27 13:14:48 -0700709 const size_t buffer_length_after_insert =
710 packet_buffer_->NumPacketsInBuffer();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000711
henrik.lundin116c84e2015-08-27 13:14:48 -0700712 if (buffer_length_after_insert > buffer_length_before_insert) {
713 const size_t packet_length_samples =
714 (buffer_length_after_insert - buffer_length_before_insert) *
715 decoder_frame_length_;
716 if (packet_length_samples != decision_logic_->packet_length_samples()) {
717 decision_logic_->set_packet_length_samples(packet_length_samples);
718 delay_manager_->SetPacketAudioLength(
719 rtc::checked_cast<int>((1000 * packet_length_samples) / fs_hz_));
720 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000721 }
722
723 // Update statistics.
pbos@webrtc.org0946a562013-04-09 00:28:06 +0000724 if ((int32_t) (main_header.timestamp - timestamp_) >= 0 &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000725 !new_codec_) {
726 // Only update statistics if incoming packet is not older than last played
727 // out packet, and if new codec flag is not set.
728 delay_manager_->Update(main_header.sequenceNumber, main_header.timestamp,
729 fs_hz_);
730 }
731 } else if (delay_manager_->last_pack_cng_or_dtmf() == -1) {
732 // This is first "normal" packet after CNG or DTMF.
733 // Reset packet time counter and measure time until next packet,
734 // but don't update statistics.
735 delay_manager_->set_last_pack_cng_or_dtmf(0);
736 delay_manager_->ResetPacketIatCount();
737 }
738 return 0;
739}
740
Peter Kasting728d9032015-06-11 14:31:38 -0700741int NetEqImpl::GetAudioInternal(size_t max_length,
742 int16_t* output,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700743 size_t* samples_per_channel,
Peter Kasting728d9032015-06-11 14:31:38 -0700744 int* num_channels) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000745 PacketList packet_list;
746 DtmfEvent dtmf_event;
747 Operations operation;
748 bool play_dtmf;
749 int return_value = GetDecision(&operation, &packet_list, &dtmf_event,
750 &play_dtmf);
751 if (return_value != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000752 last_mode_ = kModeError;
753 return return_value;
754 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000755
756 AudioDecoder::SpeechType speech_type;
757 int length = 0;
758 int decode_return_value = Decode(&packet_list, &operation,
759 &length, &speech_type);
760
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000761 assert(vad_.get());
762 bool sid_frame_available =
763 (operation == kRfc3389Cng && !packet_list.empty());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700764 vad_->Update(decoded_buffer_.get(), static_cast<size_t>(length), speech_type,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000765 sid_frame_available, fs_hz_);
766
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000767 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000768 switch (operation) {
769 case kNormal: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000770 DoNormal(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000771 break;
772 }
773 case kMerge: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000774 DoMerge(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000775 break;
776 }
777 case kExpand: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000778 return_value = DoExpand(play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000779 break;
780 }
Henrik Lundincf808d22015-05-27 14:33:29 +0200781 case kAccelerate:
782 case kFastAccelerate: {
783 const bool fast_accelerate =
784 enable_fast_accelerate_ && (operation == kFastAccelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000785 return_value = DoAccelerate(decoded_buffer_.get(), length, speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +0200786 play_dtmf, fast_accelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000787 break;
788 }
789 case kPreemptiveExpand: {
790 return_value = DoPreemptiveExpand(decoded_buffer_.get(), length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000791 speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000792 break;
793 }
794 case kRfc3389Cng:
795 case kRfc3389CngNoPacket: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000796 return_value = DoRfc3389Cng(&packet_list, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000797 break;
798 }
799 case kCodecInternalCng: {
800 // This handles the case when there is no transmission and the decoder
801 // should produce internal comfort noise.
802 // TODO(hlundin): Write test for codec-internal CNG.
minyuel6d92bf52015-09-23 15:20:39 +0200803 DoCodecInternalCng(decoded_buffer_.get(), length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000804 break;
805 }
806 case kDtmf: {
807 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000808 return_value = DoDtmf(dtmf_event, &play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000809 break;
810 }
811 case kAlternativePlc: {
812 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000813 DoAlternativePlc(false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000814 break;
815 }
816 case kAlternativePlcIncreaseTimestamp: {
817 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000818 DoAlternativePlc(true);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000819 break;
820 }
821 case kAudioRepetitionIncreaseTimestamp: {
822 // TODO(hlundin): Write test for this.
Peter Kastingb7e50542015-06-11 12:55:50 -0700823 sync_buffer_->IncreaseEndTimestamp(
824 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000825 // Skipping break on purpose. Execution should move on into the
826 // next case.
kjellander@webrtc.org7d2b6a92015-01-28 18:37:58 +0000827 FALLTHROUGH();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000828 }
829 case kAudioRepetition: {
830 // TODO(hlundin): Write test for this.
831 // Copy last |output_size_samples_| from |sync_buffer_| to
832 // |algorithm_buffer|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000833 algorithm_buffer_->PushBackFromIndex(
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000834 *sync_buffer_, sync_buffer_->Size() - output_size_samples_);
835 expand_->Reset();
836 break;
837 }
838 case kUndefined: {
Henrik Lundind67a2192015-08-03 12:54:37 +0200839 LOG(LS_ERROR) << "Invalid operation kUndefined.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000840 assert(false); // This should not happen.
841 last_mode_ = kModeError;
842 return kInvalidOperation;
843 }
844 } // End of switch.
845 if (return_value < 0) {
846 return return_value;
847 }
848
849 if (last_mode_ != kModeRfc3389Cng) {
850 comfort_noise_->Reset();
851 }
852
853 // Copy from |algorithm_buffer| to |sync_buffer_|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000854 sync_buffer_->PushBack(*algorithm_buffer_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000855
856 // Extract data from |sync_buffer_| to |output|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000857 size_t num_output_samples_per_channel = output_size_samples_;
858 size_t num_output_samples = output_size_samples_ * sync_buffer_->Channels();
859 if (num_output_samples > max_length) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000860 LOG(LS_WARNING) << "Output array is too short. " << max_length << " < " <<
861 output_size_samples_ << " * " << sync_buffer_->Channels();
862 num_output_samples = max_length;
Peter Kastingdce40cf2015-08-24 14:52:23 -0700863 num_output_samples_per_channel = max_length / sync_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000864 }
Peter Kastingdce40cf2015-08-24 14:52:23 -0700865 const size_t samples_from_sync =
866 sync_buffer_->GetNextAudioInterleaved(num_output_samples_per_channel,
867 output);
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000868 *num_channels = static_cast<int>(sync_buffer_->Channels());
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200869 if (sync_buffer_->FutureLength() < expand_->overlap_length()) {
870 // The sync buffer should always contain |overlap_length| samples, but now
871 // too many samples have been extracted. Reinstall the |overlap_length|
872 // lookahead by moving the index.
873 const size_t missing_lookahead_samples =
874 expand_->overlap_length() - sync_buffer_->FutureLength();
henrikg91d6ede2015-09-17 00:24:34 -0700875 RTC_DCHECK_GE(sync_buffer_->next_index(), missing_lookahead_samples);
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200876 sync_buffer_->set_next_index(sync_buffer_->next_index() -
877 missing_lookahead_samples);
878 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000879 if (samples_from_sync != output_size_samples_) {
Henrik Lundind67a2192015-08-03 12:54:37 +0200880 LOG(LS_ERROR) << "samples_from_sync (" << samples_from_sync
881 << ") != output_size_samples_ (" << output_size_samples_
882 << ")";
minyue@webrtc.orgdb1cefc2013-08-13 01:39:21 +0000883 // TODO(minyue): treatment of under-run, filling zeros
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000884 memset(output, 0, num_output_samples * sizeof(int16_t));
885 *samples_per_channel = output_size_samples_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000886 return kSampleUnderrun;
887 }
888 *samples_per_channel = output_size_samples_;
889
890 // Should always have overlap samples left in the |sync_buffer_|.
henrikg91d6ede2015-09-17 00:24:34 -0700891 RTC_DCHECK_GE(sync_buffer_->FutureLength(), expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000892
893 if (play_dtmf) {
894 return_value = DtmfOverdub(dtmf_event, sync_buffer_->Channels(), output);
895 }
896
897 // Update the background noise parameters if last operation wrote data
898 // straight from the decoder to the |sync_buffer_|. That is, none of the
899 // operations that modify the signal can be followed by a parameter update.
900 if ((last_mode_ == kModeNormal) ||
901 (last_mode_ == kModeAccelerateFail) ||
902 (last_mode_ == kModePreemptiveExpandFail) ||
903 (last_mode_ == kModeRfc3389Cng) ||
904 (last_mode_ == kModeCodecInternalCng)) {
905 background_noise_->Update(*sync_buffer_, *vad_.get());
906 }
907
908 if (operation == kDtmf) {
909 // DTMF data was written the end of |sync_buffer_|.
910 // Update index to end of DTMF data in |sync_buffer_|.
911 sync_buffer_->set_dtmf_index(sync_buffer_->Size());
912 }
913
henrik.lundin@webrtc.orged865b52014-03-06 10:28:07 +0000914 if (last_mode_ != kModeExpand) {
915 // If last operation was not expand, calculate the |playout_timestamp_| from
916 // the |sync_buffer_|. However, do not update the |playout_timestamp_| if it
917 // would be moved "backwards".
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000918 uint32_t temp_timestamp = sync_buffer_->end_timestamp() -
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000919 static_cast<uint32_t>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000920 if (static_cast<int32_t>(temp_timestamp - playout_timestamp_) > 0) {
921 playout_timestamp_ = temp_timestamp;
922 }
923 } else {
924 // Use dead reckoning to estimate the |playout_timestamp_|.
Peter Kastingb7e50542015-06-11 12:55:50 -0700925 playout_timestamp_ += static_cast<uint32_t>(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000926 }
927
928 if (decode_return_value) return decode_return_value;
929 return return_value;
930}
931
932int NetEqImpl::GetDecision(Operations* operation,
933 PacketList* packet_list,
934 DtmfEvent* dtmf_event,
935 bool* play_dtmf) {
936 // Initialize output variables.
937 *play_dtmf = false;
938 *operation = kUndefined;
939
940 // Increment time counters.
941 packet_buffer_->IncrementWaitingTimes();
942 stats_.IncreaseCounter(output_size_samples_, fs_hz_);
943
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000944 assert(sync_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000945 uint32_t end_timestamp = sync_buffer_->end_timestamp();
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +0000946 if (!new_codec_) {
947 const uint32_t five_seconds_samples = 5 * fs_hz_;
948 packet_buffer_->DiscardOldPackets(end_timestamp, five_seconds_samples);
949 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000950 const RTPHeader* header = packet_buffer_->NextRtpHeader();
951
henrik.lundin@webrtc.orgca8cb952014-03-12 10:26:52 +0000952 if (decision_logic_->CngRfc3389On() || last_mode_ == kModeRfc3389Cng) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000953 // Because of timestamp peculiarities, we have to "manually" disallow using
954 // a CNG packet with the same timestamp as the one that was last played.
955 // This can happen when using redundancy and will cause the timing to shift.
henrik.lundin@webrtc.org24779fe2014-03-14 12:40:05 +0000956 while (header && decoder_database_->IsComfortNoise(header->payloadType) &&
957 (end_timestamp >= header->timestamp ||
958 end_timestamp + decision_logic_->generated_noise_samples() >
959 header->timestamp)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000960 // Don't use this packet, discard it.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000961 if (packet_buffer_->DiscardNextPacket() != PacketBuffer::kOK) {
962 assert(false); // Must be ok by design.
963 }
964 // Check buffer again.
965 if (!new_codec_) {
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +0000966 packet_buffer_->DiscardOldPackets(end_timestamp, 5 * fs_hz_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000967 }
968 header = packet_buffer_->NextRtpHeader();
969 }
970 }
971
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000972 assert(expand_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000973 const int samples_left = static_cast<int>(sync_buffer_->FutureLength() -
974 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000975 if (last_mode_ == kModeAccelerateSuccess ||
976 last_mode_ == kModeAccelerateLowEnergy ||
977 last_mode_ == kModePreemptiveExpandSuccess ||
978 last_mode_ == kModePreemptiveExpandLowEnergy) {
979 // Subtract (samples_left + output_size_samples_) from sampleMemory.
Peter Kastingdce40cf2015-08-24 14:52:23 -0700980 decision_logic_->AddSampleMemory(
981 -(samples_left + rtc::checked_cast<int>(output_size_samples_)));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000982 }
983
984 // Check if it is time to play a DTMF event.
Peter Kastingb7e50542015-06-11 12:55:50 -0700985 if (dtmf_buffer_->GetEvent(
986 static_cast<uint32_t>(
987 end_timestamp + decision_logic_->generated_noise_samples()),
988 dtmf_event)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000989 *play_dtmf = true;
990 }
991
992 // Get instruction.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000993 assert(sync_buffer_.get());
994 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000995 *operation = decision_logic_->GetDecision(*sync_buffer_,
996 *expand_,
997 decoder_frame_length_,
998 header,
999 last_mode_,
1000 *play_dtmf,
1001 &reset_decoder_);
1002
1003 // Check if we already have enough samples in the |sync_buffer_|. If so,
1004 // change decision to normal, unless the decision was merge, accelerate, or
1005 // preemptive expand.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001006 if (samples_left >= rtc::checked_cast<int>(output_size_samples_) &&
1007 *operation != kMerge &&
1008 *operation != kAccelerate &&
1009 *operation != kFastAccelerate &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001010 *operation != kPreemptiveExpand) {
1011 *operation = kNormal;
1012 return 0;
1013 }
1014
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001015 decision_logic_->ExpandDecision(*operation);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001016
1017 // Check conditions for reset.
1018 if (new_codec_ || *operation == kUndefined) {
1019 // The only valid reason to get kUndefined is that new_codec_ is set.
1020 assert(new_codec_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001021 if (*play_dtmf && !header) {
1022 timestamp_ = dtmf_event->timestamp;
1023 } else {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001024 if (!header) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001025 LOG(LS_ERROR) << "Packet missing where it shouldn't.";
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001026 return -1;
1027 }
1028 timestamp_ = header->timestamp;
1029 if (*operation == kRfc3389CngNoPacket
1030#ifndef LEGACY_BITEXACT
1031 // Without this check, it can happen that a non-CNG packet is sent to
1032 // the CNG decoder as if it was a SID frame. This is clearly a bug,
1033 // but is kept for now to maintain bit-exactness with the test
1034 // vectors.
1035 && decoder_database_->IsComfortNoise(header->payloadType)
1036#endif
1037 ) {
1038 // Change decision to CNG packet, since we do have a CNG packet, but it
1039 // was considered too early to use. Now, use it anyway.
1040 *operation = kRfc3389Cng;
1041 } else if (*operation != kRfc3389Cng) {
1042 *operation = kNormal;
1043 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001044 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001045 // Adjust |sync_buffer_| timestamp before setting |end_timestamp| to the
1046 // new value.
1047 sync_buffer_->IncreaseEndTimestamp(timestamp_ - end_timestamp);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001048 end_timestamp = timestamp_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001049 new_codec_ = false;
1050 decision_logic_->SoftReset();
1051 buffer_level_filter_->Reset();
1052 delay_manager_->Reset();
1053 stats_.ResetMcu();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001054 }
1055
Peter Kastingdce40cf2015-08-24 14:52:23 -07001056 size_t required_samples = output_size_samples_;
1057 const size_t samples_10_ms = static_cast<size_t>(80 * fs_mult_);
1058 const size_t samples_20_ms = 2 * samples_10_ms;
1059 const size_t samples_30_ms = 3 * samples_10_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001060
1061 switch (*operation) {
1062 case kExpand: {
1063 timestamp_ = end_timestamp;
1064 return 0;
1065 }
1066 case kRfc3389CngNoPacket:
1067 case kCodecInternalCng: {
1068 return 0;
1069 }
1070 case kDtmf: {
1071 // TODO(hlundin): Write test for this.
1072 // Update timestamp.
1073 timestamp_ = end_timestamp;
1074 if (decision_logic_->generated_noise_samples() > 0 &&
1075 last_mode_ != kModeDtmf) {
1076 // Make a jump in timestamp due to the recently played comfort noise.
Peter Kastingb7e50542015-06-11 12:55:50 -07001077 uint32_t timestamp_jump =
1078 static_cast<uint32_t>(decision_logic_->generated_noise_samples());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001079 sync_buffer_->IncreaseEndTimestamp(timestamp_jump);
1080 timestamp_ += timestamp_jump;
1081 }
1082 decision_logic_->set_generated_noise_samples(0);
1083 return 0;
1084 }
Henrik Lundincf808d22015-05-27 14:33:29 +02001085 case kAccelerate:
1086 case kFastAccelerate: {
1087 // In order to do an accelerate we need at least 30 ms of audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001088 if (samples_left >= static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001089 // Already have enough data, so we do not need to extract any more.
1090 decision_logic_->set_sample_memory(samples_left);
1091 decision_logic_->set_prev_time_scale(true);
1092 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001093 } else if (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001094 decoder_frame_length_ >= samples_30_ms) {
1095 // Avoid decoding more data as it might overflow the playout buffer.
1096 *operation = kNormal;
1097 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001098 } else if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001099 decoder_frame_length_ < samples_30_ms) {
1100 // Build up decoded data by decoding at least 20 ms of audio data. Do
1101 // not perform accelerate yet, but wait until we only need to do one
1102 // decoding.
1103 required_samples = 2 * output_size_samples_;
1104 *operation = kNormal;
1105 }
1106 // If none of the above is true, we have one of two possible situations:
1107 // (1) 20 ms <= samples_left < 30 ms and decoder_frame_length_ < 30 ms; or
1108 // (2) samples_left < 10 ms and decoder_frame_length_ >= 30 ms.
1109 // In either case, we move on with the accelerate decision, and decode one
1110 // frame now.
1111 break;
1112 }
1113 case kPreemptiveExpand: {
1114 // In order to do a preemptive expand we need at least 30 ms of decoded
1115 // audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001116 if ((samples_left >= static_cast<int>(samples_30_ms)) ||
1117 (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001118 decoder_frame_length_ >= samples_30_ms)) {
1119 // Already have enough data, so we do not need to extract any more.
1120 // Or, avoid decoding more data as it might overflow the playout buffer.
1121 // Still try preemptive expand, though.
1122 decision_logic_->set_sample_memory(samples_left);
1123 decision_logic_->set_prev_time_scale(true);
1124 return 0;
1125 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07001126 if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001127 decoder_frame_length_ < samples_30_ms) {
1128 // Build up decoded data by decoding at least 20 ms of audio data.
1129 // Still try to perform preemptive expand.
1130 required_samples = 2 * output_size_samples_;
1131 }
1132 // Move on with the preemptive expand decision.
1133 break;
1134 }
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001135 case kMerge: {
1136 required_samples =
1137 std::max(merge_->RequiredFutureSamples(), required_samples);
1138 break;
1139 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001140 default: {
1141 // Do nothing.
1142 }
1143 }
1144
1145 // Get packets from buffer.
1146 int extracted_samples = 0;
1147 if (header &&
1148 *operation != kAlternativePlc &&
1149 *operation != kAlternativePlcIncreaseTimestamp &&
1150 *operation != kAudioRepetition &&
1151 *operation != kAudioRepetitionIncreaseTimestamp) {
1152 sync_buffer_->IncreaseEndTimestamp(header->timestamp - end_timestamp);
1153 if (decision_logic_->CngOff()) {
1154 // Adjustment of timestamp only corresponds to an actual packet loss
1155 // if comfort noise is not played. If comfort noise was just played,
1156 // this adjustment of timestamp is only done to get back in sync with the
1157 // stream timestamp; no loss to report.
1158 stats_.LostSamples(header->timestamp - end_timestamp);
1159 }
1160
1161 if (*operation != kRfc3389Cng) {
1162 // We are about to decode and use a non-CNG packet.
1163 decision_logic_->SetCngOff();
1164 }
1165 // Reset CNG timestamp as a new packet will be delivered.
1166 // (Also if this is a CNG packet, since playedOutTS is updated.)
1167 decision_logic_->set_generated_noise_samples(0);
1168
1169 extracted_samples = ExtractPackets(required_samples, packet_list);
1170 if (extracted_samples < 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001171 return kPacketBufferCorruption;
1172 }
1173 }
1174
Henrik Lundincf808d22015-05-27 14:33:29 +02001175 if (*operation == kAccelerate || *operation == kFastAccelerate ||
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001176 *operation == kPreemptiveExpand) {
1177 decision_logic_->set_sample_memory(samples_left + extracted_samples);
1178 decision_logic_->set_prev_time_scale(true);
1179 }
1180
Henrik Lundincf808d22015-05-27 14:33:29 +02001181 if (*operation == kAccelerate || *operation == kFastAccelerate) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001182 // Check that we have enough data (30ms) to do accelerate.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001183 if (extracted_samples + samples_left < static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001184 // TODO(hlundin): Write test for this.
1185 // Not enough, do normal operation instead.
1186 *operation = kNormal;
1187 }
1188 }
1189
1190 timestamp_ = end_timestamp;
1191 return 0;
1192}
1193
1194int NetEqImpl::Decode(PacketList* packet_list, Operations* operation,
1195 int* decoded_length,
1196 AudioDecoder::SpeechType* speech_type) {
1197 *speech_type = AudioDecoder::kSpeech;
minyuel6d92bf52015-09-23 15:20:39 +02001198
1199 // When packet_list is empty, we may be in kCodecInternalCng mode, and for
1200 // that we use current active decoder.
1201 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1202
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001203 if (!packet_list->empty()) {
1204 const Packet* packet = packet_list->front();
pkasting@chromium.org0e81fdf2015-02-02 23:54:03 +00001205 uint8_t payload_type = packet->header.payloadType;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001206 if (!decoder_database_->IsComfortNoise(payload_type)) {
1207 decoder = decoder_database_->GetDecoder(payload_type);
1208 assert(decoder);
1209 if (!decoder) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001210 LOG(LS_WARNING) << "Unknown payload type "
1211 << static_cast<int>(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001212 PacketBuffer::DeleteAllPackets(packet_list);
1213 return kDecoderNotFound;
1214 }
1215 bool decoder_changed;
1216 decoder_database_->SetActiveDecoder(payload_type, &decoder_changed);
1217 if (decoder_changed) {
1218 // We have a new decoder. Re-init some values.
1219 const DecoderDatabase::DecoderInfo* decoder_info = decoder_database_
1220 ->GetDecoderInfo(payload_type);
1221 assert(decoder_info);
1222 if (!decoder_info) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001223 LOG(LS_WARNING) << "Unknown payload type "
1224 << static_cast<int>(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001225 PacketBuffer::DeleteAllPackets(packet_list);
1226 return kDecoderNotFound;
1227 }
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001228 // If sampling rate or number of channels has changed, we need to make
1229 // a reset.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001230 if (decoder_info->fs_hz != fs_hz_ ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001231 decoder->Channels() != algorithm_buffer_->Channels()) {
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001232 // TODO(tlegrand): Add unittest to cover this event.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001233 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->Channels());
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001234 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001235 sync_buffer_->set_end_timestamp(timestamp_);
1236 playout_timestamp_ = timestamp_;
1237 }
1238 }
1239 }
1240
1241 if (reset_decoder_) {
1242 // TODO(hlundin): Write test for this.
Karl Wiberg43766482015-08-27 15:22:11 +02001243 if (decoder)
1244 decoder->Reset();
1245
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001246 // Reset comfort noise decoder.
1247 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02001248 if (cng_decoder)
1249 cng_decoder->Reset();
1250
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001251 reset_decoder_ = false;
1252 }
1253
1254#ifdef LEGACY_BITEXACT
1255 // Due to a bug in old SignalMCU, it could happen that CNG operation was
1256 // decided, but a speech packet was provided. The speech packet will be used
1257 // to update the comfort noise decoder, as if it was a SID frame, which is
1258 // clearly wrong.
1259 if (*operation == kRfc3389Cng) {
1260 return 0;
1261 }
1262#endif
1263
1264 *decoded_length = 0;
1265 // Update codec-internal PLC state.
1266 if ((*operation == kMerge) && decoder && decoder->HasDecodePlc()) {
1267 decoder->DecodePlc(1, &decoded_buffer_[*decoded_length]);
1268 }
1269
minyuel6d92bf52015-09-23 15:20:39 +02001270 int return_value;
1271 if (*operation == kCodecInternalCng) {
1272 RTC_DCHECK(packet_list->empty());
1273 return_value = DecodeCng(decoder, decoded_length, speech_type);
1274 } else {
1275 return_value = DecodeLoop(packet_list, *operation, decoder,
1276 decoded_length, speech_type);
1277 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001278
1279 if (*decoded_length < 0) {
1280 // Error returned from the decoder.
1281 *decoded_length = 0;
Peter Kastingb7e50542015-06-11 12:55:50 -07001282 sync_buffer_->IncreaseEndTimestamp(
1283 static_cast<uint32_t>(decoder_frame_length_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001284 int error_code = 0;
1285 if (decoder)
1286 error_code = decoder->ErrorCode();
1287 if (error_code != 0) {
1288 // Got some error code from the decoder.
1289 decoder_error_code_ = error_code;
1290 return_value = kDecoderErrorCode;
Henrik Lundind67a2192015-08-03 12:54:37 +02001291 LOG(LS_WARNING) << "Decoder returned error code: " << error_code;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001292 } else {
1293 // Decoder does not implement error codes. Return generic error.
1294 return_value = kOtherDecoderError;
Henrik Lundind67a2192015-08-03 12:54:37 +02001295 LOG(LS_WARNING) << "Decoder error (no error code)";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001296 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001297 *operation = kExpand; // Do expansion to get data instead.
1298 }
1299 if (*speech_type != AudioDecoder::kComfortNoise) {
1300 // Don't increment timestamp if codec returned CNG speech type
1301 // since in this case, the we will increment the CNGplayedTS counter.
1302 // Increase with number of samples per channel.
1303 assert(*decoded_length == 0 ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001304 (decoder && decoder->Channels() == sync_buffer_->Channels()));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001305 sync_buffer_->IncreaseEndTimestamp(
1306 *decoded_length / static_cast<int>(sync_buffer_->Channels()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001307 }
1308 return return_value;
1309}
1310
minyuel6d92bf52015-09-23 15:20:39 +02001311int NetEqImpl::DecodeCng(AudioDecoder* decoder, int* decoded_length,
1312 AudioDecoder::SpeechType* speech_type) {
1313 if (!decoder) {
1314 // This happens when active decoder is not defined.
1315 *decoded_length = -1;
1316 return 0;
1317 }
1318
1319 while (*decoded_length < rtc::checked_cast<int>(output_size_samples_)) {
1320 const int length = decoder->Decode(
1321 nullptr, 0, fs_hz_,
1322 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1323 &decoded_buffer_[*decoded_length], speech_type);
1324 if (length > 0) {
1325 *decoded_length += length;
minyuel6d92bf52015-09-23 15:20:39 +02001326 } else {
1327 // Error.
1328 LOG(LS_WARNING) << "Failed to decode CNG";
1329 *decoded_length = -1;
1330 break;
1331 }
1332 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1333 // Guard against overflow.
1334 LOG(LS_WARNING) << "Decoded too much CNG.";
1335 return kDecodedTooMuch;
1336 }
1337 }
1338 return 0;
1339}
1340
1341int NetEqImpl::DecodeLoop(PacketList* packet_list, const Operations& operation,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001342 AudioDecoder* decoder, int* decoded_length,
1343 AudioDecoder::SpeechType* speech_type) {
1344 Packet* packet = NULL;
1345 if (!packet_list->empty()) {
1346 packet = packet_list->front();
1347 }
minyuel6d92bf52015-09-23 15:20:39 +02001348
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001349 // Do decoding.
1350 while (packet &&
1351 !decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1352 assert(decoder); // At this point, we must have a decoder object.
1353 // The number of channels in the |sync_buffer_| should be the same as the
1354 // number decoder channels.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001355 assert(sync_buffer_->Channels() == decoder->Channels());
1356 assert(decoded_buffer_length_ >= kMaxFrameSize * decoder->Channels());
minyuel6d92bf52015-09-23 15:20:39 +02001357 assert(operation == kNormal || operation == kAccelerate ||
1358 operation == kFastAccelerate || operation == kMerge ||
1359 operation == kPreemptiveExpand);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001360 packet_list->pop_front();
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001361 size_t payload_length = packet->payload_length;
Peter Kasting36b7cc32015-06-11 19:57:18 -07001362 int decode_length;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +00001363 if (packet->sync_packet) {
1364 // Decode to silence with the same frame size as the last decode.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001365 memset(&decoded_buffer_[*decoded_length], 0,
1366 decoder_frame_length_ * decoder->Channels() *
1367 sizeof(decoded_buffer_[0]));
Peter Kastingdce40cf2015-08-24 14:52:23 -07001368 decode_length = rtc::checked_cast<int>(decoder_frame_length_);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +00001369 } else if (!packet->primary) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001370 // This is a redundant payload; call the special decoder method.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001371 decode_length = decoder->DecodeRedundant(
henrik.lundin@webrtc.org1eda4e32015-02-25 10:02:29 +00001372 packet->payload, packet->payload_length, fs_hz_,
minyue@webrtc.org7f7d7e32015-03-16 12:30:37 +00001373 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001374 &decoded_buffer_[*decoded_length], speech_type);
1375 } else {
henrik.lundin@webrtc.org1eda4e32015-02-25 10:02:29 +00001376 decode_length =
minyue@webrtc.org7f7d7e32015-03-16 12:30:37 +00001377 decoder->Decode(
1378 packet->payload, packet->payload_length, fs_hz_,
1379 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1380 &decoded_buffer_[*decoded_length], speech_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001381 }
1382
1383 delete[] packet->payload;
1384 delete packet;
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001385 packet = NULL;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001386 if (decode_length > 0) {
1387 *decoded_length += decode_length;
1388 // Update |decoder_frame_length_| with number of samples per channel.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001389 decoder_frame_length_ =
Peter Kastingdce40cf2015-08-24 14:52:23 -07001390 static_cast<size_t>(decode_length) / decoder->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001391 } else if (decode_length < 0) {
1392 // Error.
Henrik Lundind67a2192015-08-03 12:54:37 +02001393 LOG(LS_WARNING) << "Decode " << decode_length << " " << payload_length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001394 *decoded_length = -1;
1395 PacketBuffer::DeleteAllPackets(packet_list);
1396 break;
1397 }
1398 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1399 // Guard against overflow.
Henrik Lundind67a2192015-08-03 12:54:37 +02001400 LOG(LS_WARNING) << "Decoded too much.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001401 PacketBuffer::DeleteAllPackets(packet_list);
1402 return kDecodedTooMuch;
1403 }
1404 if (!packet_list->empty()) {
1405 packet = packet_list->front();
1406 } else {
1407 packet = NULL;
1408 }
1409 } // End of decode loop.
1410
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001411 // If the list is not empty at this point, either a decoding error terminated
1412 // the while-loop, or list must hold exactly one CNG packet.
1413 assert(packet_list->empty() || *decoded_length < 0 ||
1414 (packet_list->size() == 1 && packet &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001415 decoder_database_->IsComfortNoise(packet->header.payloadType)));
1416 return 0;
1417}
1418
1419void NetEqImpl::DoNormal(const int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001420 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001421 assert(normal_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001422 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001423 normal_->Process(decoded_buffer, decoded_length, last_mode_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001424 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001425 if (decoded_length != 0) {
1426 last_mode_ = kModeNormal;
1427 }
1428
1429 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1430 if ((speech_type == AudioDecoder::kComfortNoise)
1431 || ((last_mode_ == kModeCodecInternalCng)
1432 && (decoded_length == 0))) {
1433 // TODO(hlundin): Remove second part of || statement above.
1434 last_mode_ = kModeCodecInternalCng;
1435 }
1436
1437 if (!play_dtmf) {
1438 dtmf_tone_generator_->Reset();
1439 }
1440}
1441
1442void NetEqImpl::DoMerge(int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001443 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001444 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001445 assert(merge_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001446 size_t new_length = merge_->Process(decoded_buffer, decoded_length,
1447 mute_factor_array_.get(),
1448 algorithm_buffer_.get());
1449 size_t expand_length_correction = new_length -
1450 decoded_length / algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001451
1452 // Update in-call and post-call statistics.
1453 if (expand_->MuteFactor(0) == 0) {
1454 // Expand generates only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001455 stats_.ExpandedNoiseSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001456 } else {
1457 // Expansion generates more than only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001458 stats_.ExpandedVoiceSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001459 }
1460
1461 last_mode_ = kModeMerge;
1462 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1463 if (speech_type == AudioDecoder::kComfortNoise) {
1464 last_mode_ = kModeCodecInternalCng;
1465 }
1466 expand_->Reset();
1467 if (!play_dtmf) {
1468 dtmf_tone_generator_->Reset();
1469 }
1470}
1471
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001472int NetEqImpl::DoExpand(bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001473 while ((sync_buffer_->FutureLength() - expand_->overlap_length()) <
Peter Kastingdce40cf2015-08-24 14:52:23 -07001474 output_size_samples_) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001475 algorithm_buffer_->Clear();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001476 int return_value = expand_->Process(algorithm_buffer_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001477 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001478
1479 // Update in-call and post-call statistics.
1480 if (expand_->MuteFactor(0) == 0) {
1481 // Expand operation generates only noise.
1482 stats_.ExpandedNoiseSamples(length);
1483 } else {
1484 // Expand operation generates more than only noise.
1485 stats_.ExpandedVoiceSamples(length);
1486 }
1487
1488 last_mode_ = kModeExpand;
1489
1490 if (return_value < 0) {
1491 return return_value;
1492 }
1493
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001494 sync_buffer_->PushBack(*algorithm_buffer_);
1495 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001496 }
1497 if (!play_dtmf) {
1498 dtmf_tone_generator_->Reset();
1499 }
1500 return 0;
1501}
1502
Henrik Lundincf808d22015-05-27 14:33:29 +02001503int NetEqImpl::DoAccelerate(int16_t* decoded_buffer,
1504 size_t decoded_length,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001505 AudioDecoder::SpeechType speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +02001506 bool play_dtmf,
1507 bool fast_accelerate) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001508 const size_t required_samples =
1509 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001510 size_t borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001511 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001512 size_t decoded_length_per_channel = decoded_length / num_channels;
1513 if (decoded_length_per_channel < required_samples) {
1514 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001515 borrowed_samples_per_channel = static_cast<int>(required_samples -
1516 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001517 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1518 decoded_buffer,
1519 sizeof(int16_t) * decoded_length);
1520 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1521 decoded_buffer);
1522 decoded_length = required_samples * num_channels;
1523 }
1524
Peter Kastingdce40cf2015-08-24 14:52:23 -07001525 size_t samples_removed;
Henrik Lundincf808d22015-05-27 14:33:29 +02001526 Accelerate::ReturnCodes return_code =
1527 accelerate_->Process(decoded_buffer, decoded_length, fast_accelerate,
1528 algorithm_buffer_.get(), &samples_removed);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001529 stats_.AcceleratedSamples(samples_removed);
1530 switch (return_code) {
1531 case Accelerate::kSuccess:
1532 last_mode_ = kModeAccelerateSuccess;
1533 break;
1534 case Accelerate::kSuccessLowEnergy:
1535 last_mode_ = kModeAccelerateLowEnergy;
1536 break;
1537 case Accelerate::kNoStretch:
1538 last_mode_ = kModeAccelerateFail;
1539 break;
1540 case Accelerate::kError:
1541 // TODO(hlundin): Map to kModeError instead?
1542 last_mode_ = kModeAccelerateFail;
1543 return kAccelerateError;
1544 }
1545
1546 if (borrowed_samples_per_channel > 0) {
1547 // Copy borrowed samples back to the |sync_buffer_|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001548 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001549 if (length < borrowed_samples_per_channel) {
1550 // This destroys the beginning of the buffer, but will not cause any
1551 // problems.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001552 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001553 sync_buffer_->Size() -
1554 borrowed_samples_per_channel);
1555 sync_buffer_->PushFrontZeros(borrowed_samples_per_channel - length);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001556 algorithm_buffer_->PopFront(length);
1557 assert(algorithm_buffer_->Empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001558 } else {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001559 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001560 borrowed_samples_per_channel,
1561 sync_buffer_->Size() -
1562 borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001563 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001564 }
1565 }
1566
1567 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1568 if (speech_type == AudioDecoder::kComfortNoise) {
1569 last_mode_ = kModeCodecInternalCng;
1570 }
1571 if (!play_dtmf) {
1572 dtmf_tone_generator_->Reset();
1573 }
1574 expand_->Reset();
1575 return 0;
1576}
1577
1578int NetEqImpl::DoPreemptiveExpand(int16_t* decoded_buffer,
1579 size_t decoded_length,
1580 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001581 bool play_dtmf) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001582 const size_t required_samples =
1583 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001584 size_t num_channels = algorithm_buffer_->Channels();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001585 size_t borrowed_samples_per_channel = 0;
1586 size_t old_borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001587 size_t decoded_length_per_channel = decoded_length / num_channels;
1588 if (decoded_length_per_channel < required_samples) {
1589 // Must move data from the |sync_buffer_| in order to get 30 ms.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001590 borrowed_samples_per_channel =
1591 required_samples - decoded_length_per_channel;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001592 // Calculate how many of these were already played out.
Peter Kastingf045e4d2015-06-10 21:15:38 -07001593 old_borrowed_samples_per_channel =
Peter Kastingdce40cf2015-08-24 14:52:23 -07001594 (borrowed_samples_per_channel > sync_buffer_->FutureLength()) ?
1595 (borrowed_samples_per_channel - sync_buffer_->FutureLength()) : 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001596 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1597 decoded_buffer,
1598 sizeof(int16_t) * decoded_length);
1599 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1600 decoded_buffer);
1601 decoded_length = required_samples * num_channels;
1602 }
1603
Peter Kastingdce40cf2015-08-24 14:52:23 -07001604 size_t samples_added;
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001605 PreemptiveExpand::ReturnCodes return_code = preemptive_expand_->Process(
Peter Kastingdce40cf2015-08-24 14:52:23 -07001606 decoded_buffer, decoded_length,
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001607 old_borrowed_samples_per_channel,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001608 algorithm_buffer_.get(), &samples_added);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001609 stats_.PreemptiveExpandedSamples(samples_added);
1610 switch (return_code) {
1611 case PreemptiveExpand::kSuccess:
1612 last_mode_ = kModePreemptiveExpandSuccess;
1613 break;
1614 case PreemptiveExpand::kSuccessLowEnergy:
1615 last_mode_ = kModePreemptiveExpandLowEnergy;
1616 break;
1617 case PreemptiveExpand::kNoStretch:
1618 last_mode_ = kModePreemptiveExpandFail;
1619 break;
1620 case PreemptiveExpand::kError:
1621 // TODO(hlundin): Map to kModeError instead?
1622 last_mode_ = kModePreemptiveExpandFail;
1623 return kPreemptiveExpandError;
1624 }
1625
1626 if (borrowed_samples_per_channel > 0) {
1627 // Copy borrowed samples back to the |sync_buffer_|.
1628 sync_buffer_->ReplaceAtIndex(
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001629 *algorithm_buffer_, borrowed_samples_per_channel,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001630 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001631 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001632 }
1633
1634 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1635 if (speech_type == AudioDecoder::kComfortNoise) {
1636 last_mode_ = kModeCodecInternalCng;
1637 }
1638 if (!play_dtmf) {
1639 dtmf_tone_generator_->Reset();
1640 }
1641 expand_->Reset();
1642 return 0;
1643}
1644
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001645int NetEqImpl::DoRfc3389Cng(PacketList* packet_list, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001646 if (!packet_list->empty()) {
1647 // Must have exactly one SID frame at this point.
1648 assert(packet_list->size() == 1);
1649 Packet* packet = packet_list->front();
1650 packet_list->pop_front();
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001651 if (!decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1652#ifdef LEGACY_BITEXACT
1653 // This can happen due to a bug in GetDecision. Change the payload type
1654 // to a CNG type, and move on. Note that this means that we are in fact
1655 // sending a non-CNG payload to the comfort noise decoder for decoding.
1656 // Clearly wrong, but will maintain bit-exactness with legacy.
1657 if (fs_hz_ == 8000) {
1658 packet->header.payloadType =
kwibergee1879c2015-10-29 06:20:28 -07001659 decoder_database_->GetRtpPayloadType(NetEqDecoder::kDecoderCNGnb);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001660 } else if (fs_hz_ == 16000) {
1661 packet->header.payloadType =
kwibergee1879c2015-10-29 06:20:28 -07001662 decoder_database_->GetRtpPayloadType(NetEqDecoder::kDecoderCNGwb);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001663 } else if (fs_hz_ == 32000) {
kwibergee1879c2015-10-29 06:20:28 -07001664 packet->header.payloadType = decoder_database_->GetRtpPayloadType(
1665 NetEqDecoder::kDecoderCNGswb32kHz);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001666 } else if (fs_hz_ == 48000) {
kwibergee1879c2015-10-29 06:20:28 -07001667 packet->header.payloadType = decoder_database_->GetRtpPayloadType(
1668 NetEqDecoder::kDecoderCNGswb48kHz);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001669 }
1670 assert(decoder_database_->IsComfortNoise(packet->header.payloadType));
1671#else
1672 LOG(LS_ERROR) << "Trying to decode non-CNG payload as CNG.";
1673 return kOtherError;
1674#endif
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001675 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001676 // UpdateParameters() deletes |packet|.
1677 if (comfort_noise_->UpdateParameters(packet) ==
1678 ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001679 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001680 return -comfort_noise_->internal_error_code();
1681 }
1682 }
1683 int cn_return = comfort_noise_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001684 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001685 expand_->Reset();
1686 last_mode_ = kModeRfc3389Cng;
1687 if (!play_dtmf) {
1688 dtmf_tone_generator_->Reset();
1689 }
1690 if (cn_return == ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001691 decoder_error_code_ = comfort_noise_->internal_error_code();
1692 return kComfortNoiseErrorCode;
1693 } else if (cn_return == ComfortNoise::kUnknownPayloadType) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001694 return kUnknownRtpPayloadType;
1695 }
1696 return 0;
1697}
1698
minyuel6d92bf52015-09-23 15:20:39 +02001699void NetEqImpl::DoCodecInternalCng(const int16_t* decoded_buffer,
1700 size_t decoded_length) {
1701 RTC_DCHECK(normal_.get());
1702 RTC_DCHECK(mute_factor_array_.get());
1703 normal_->Process(decoded_buffer, decoded_length, last_mode_,
1704 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001705 last_mode_ = kModeCodecInternalCng;
1706 expand_->Reset();
1707}
1708
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001709int NetEqImpl::DoDtmf(const DtmfEvent& dtmf_event, bool* play_dtmf) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001710 // This block of the code and the block further down, handling |dtmf_switch|
1711 // are commented out. Otherwise playing out-of-band DTMF would fail in VoE
1712 // test, DtmfTest.ManualSuccessfullySendsOutOfBandTelephoneEvents. This is
1713 // equivalent to |dtmf_switch| always be false.
1714 //
1715 // See http://webrtc-codereview.appspot.com/1195004/ for discussion
1716 // On this issue. This change might cause some glitches at the point of
1717 // switch from audio to DTMF. Issue 1545 is filed to track this.
1718 //
1719 // bool dtmf_switch = false;
1720 // if ((last_mode_ != kModeDtmf) && dtmf_tone_generator_->initialized()) {
1721 // // Special case; see below.
1722 // // We must catch this before calling Generate, since |initialized| is
1723 // // modified in that call.
1724 // dtmf_switch = true;
1725 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001726
1727 int dtmf_return_value = 0;
1728 if (!dtmf_tone_generator_->initialized()) {
1729 // Initialize if not already done.
1730 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1731 dtmf_event.volume);
1732 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001733
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001734 if (dtmf_return_value == 0) {
1735 // Generate DTMF signal.
1736 dtmf_return_value = dtmf_tone_generator_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001737 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001738 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001739
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001740 if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001741 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001742 return dtmf_return_value;
1743 }
1744
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001745 // if (dtmf_switch) {
1746 // // This is the special case where the previous operation was DTMF
1747 // // overdub, but the current instruction is "regular" DTMF. We must make
1748 // // sure that the DTMF does not have any discontinuities. The first DTMF
1749 // // sample that we generate now must be played out immediately, therefore
1750 // // it must be copied to the speech buffer.
1751 // // TODO(hlundin): This code seems incorrect. (Legacy.) Write test and
1752 // // verify correct operation.
1753 // assert(false);
1754 // // Must generate enough data to replace all of the |sync_buffer_|
1755 // // "future".
1756 // int required_length = sync_buffer_->FutureLength();
1757 // assert(dtmf_tone_generator_->initialized());
1758 // dtmf_return_value = dtmf_tone_generator_->Generate(required_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001759 // algorithm_buffer_);
1760 // assert((size_t) required_length == algorithm_buffer_->Size());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001761 // if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001762 // algorithm_buffer_->Zeros(output_size_samples_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001763 // return dtmf_return_value;
1764 // }
1765 //
1766 // // Overwrite the "future" part of the speech buffer with the new DTMF
1767 // // data.
1768 // // TODO(hlundin): It seems that this overwriting has gone lost.
1769 // // Not adapted for multi-channel yet.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001770 // assert(algorithm_buffer_->Channels() == 1);
1771 // if (algorithm_buffer_->Channels() != 1) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001772 // LOG(LS_WARNING) << "DTMF not supported for more than one channel";
1773 // return kStereoNotSupported;
1774 // }
1775 // // Shuffle the remaining data to the beginning of algorithm buffer.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001776 // algorithm_buffer_->PopFront(sync_buffer_->FutureLength());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001777 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001778
Peter Kastingb7e50542015-06-11 12:55:50 -07001779 sync_buffer_->IncreaseEndTimestamp(
1780 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001781 expand_->Reset();
1782 last_mode_ = kModeDtmf;
1783
1784 // Set to false because the DTMF is already in the algorithm buffer.
1785 *play_dtmf = false;
1786 return 0;
1787}
1788
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001789void NetEqImpl::DoAlternativePlc(bool increase_timestamp) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001790 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001791 size_t length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001792 if (decoder && decoder->HasDecodePlc()) {
1793 // Use the decoder's packet-loss concealment.
1794 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1795 int16_t decoded_buffer[kMaxFrameSize];
1796 length = decoder->DecodePlc(1, decoded_buffer);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001797 if (length > 0)
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001798 algorithm_buffer_->PushBackInterleaved(decoded_buffer, length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001799 } else {
1800 // Do simple zero-stuffing.
1801 length = output_size_samples_;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001802 algorithm_buffer_->Zeros(length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001803 // By not advancing the timestamp, NetEq inserts samples.
1804 stats_.AddZeros(length);
1805 }
1806 if (increase_timestamp) {
Peter Kastingb7e50542015-06-11 12:55:50 -07001807 sync_buffer_->IncreaseEndTimestamp(static_cast<uint32_t>(length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001808 }
1809 expand_->Reset();
1810}
1811
1812int NetEqImpl::DtmfOverdub(const DtmfEvent& dtmf_event, size_t num_channels,
1813 int16_t* output) const {
1814 size_t out_index = 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001815 size_t overdub_length = output_size_samples_; // Default value.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001816
1817 if (sync_buffer_->dtmf_index() > sync_buffer_->next_index()) {
1818 // Special operation for transition from "DTMF only" to "DTMF overdub".
1819 out_index = std::min(
1820 sync_buffer_->dtmf_index() - sync_buffer_->next_index(),
Peter Kastingdce40cf2015-08-24 14:52:23 -07001821 output_size_samples_);
1822 overdub_length = output_size_samples_ - out_index;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001823 }
1824
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001825 AudioMultiVector dtmf_output(num_channels);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001826 int dtmf_return_value = 0;
1827 if (!dtmf_tone_generator_->initialized()) {
1828 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1829 dtmf_event.volume);
1830 }
1831 if (dtmf_return_value == 0) {
1832 dtmf_return_value = dtmf_tone_generator_->Generate(overdub_length,
1833 &dtmf_output);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001834 assert(overdub_length == dtmf_output.Size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001835 }
1836 dtmf_output.ReadInterleaved(overdub_length, &output[out_index]);
1837 return dtmf_return_value < 0 ? dtmf_return_value : 0;
1838}
1839
Peter Kastingdce40cf2015-08-24 14:52:23 -07001840int NetEqImpl::ExtractPackets(size_t required_samples,
1841 PacketList* packet_list) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001842 bool first_packet = true;
1843 uint8_t prev_payload_type = 0;
1844 uint32_t prev_timestamp = 0;
1845 uint16_t prev_sequence_number = 0;
1846 bool next_packet_available = false;
1847
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001848 const RTPHeader* header = packet_buffer_->NextRtpHeader();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001849 assert(header);
1850 if (!header) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001851 LOG(LS_ERROR) << "Packet buffer unexpectedly empty.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001852 return -1;
1853 }
turaj@webrtc.org7df97062013-08-02 18:07:13 +00001854 uint32_t first_timestamp = header->timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001855 int extracted_samples = 0;
1856
1857 // Packet extraction loop.
1858 do {
1859 timestamp_ = header->timestamp;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001860 size_t discard_count = 0;
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001861 Packet* packet = packet_buffer_->GetNextPacket(&discard_count);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001862 // |header| may be invalid after the |packet_buffer_| operation.
1863 header = NULL;
1864 if (!packet) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001865 LOG(LS_ERROR) << "Should always be able to extract a packet here";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001866 assert(false); // Should always be able to extract a packet here.
1867 return -1;
1868 }
1869 stats_.PacketsDiscarded(discard_count);
1870 // Store waiting time in ms; packets->waiting_time is in "output blocks".
1871 stats_.StoreWaitingTime(packet->waiting_time * kOutputSizeMs);
1872 assert(packet->payload_length > 0);
1873 packet_list->push_back(packet); // Store packet in list.
1874
1875 if (first_packet) {
1876 first_packet = false;
henrik.lundin48ed9302015-10-29 05:36:24 -07001877 if (nack_enabled_) {
1878 RTC_DCHECK(nack_);
1879 // TODO(henrik.lundin): Should we update this for all decoded packets?
1880 nack_->UpdateLastDecodedPacket(packet->header.sequenceNumber,
1881 packet->header.timestamp);
1882 }
1883 prev_sequence_number = packet->header.sequenceNumber;
1884 prev_timestamp = packet->header.timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001885 prev_payload_type = packet->header.payloadType;
1886 }
1887
1888 // Store number of extracted samples.
1889 int packet_duration = 0;
1890 AudioDecoder* decoder = decoder_database_->GetDecoder(
1891 packet->header.payloadType);
1892 if (decoder) {
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001893 if (packet->sync_packet) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001894 packet_duration = rtc::checked_cast<int>(decoder_frame_length_);
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001895 } else {
minyue@webrtc.org2c1bcf22015-02-17 10:17:09 +00001896 if (packet->primary) {
1897 packet_duration = decoder->PacketDuration(packet->payload,
1898 packet->payload_length);
1899 } else {
1900 packet_duration = decoder->
1901 PacketDurationRedundant(packet->payload, packet->payload_length);
1902 stats_.SecondaryDecodedSamples(packet_duration);
1903 }
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001904 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001905 } else {
Henrik Lundind67a2192015-08-03 12:54:37 +02001906 LOG(LS_WARNING) << "Unknown payload type "
1907 << static_cast<int>(packet->header.payloadType);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001908 assert(false);
1909 }
1910 if (packet_duration <= 0) {
1911 // Decoder did not return a packet duration. Assume that the packet
1912 // contains the same number of samples as the previous one.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001913 packet_duration = rtc::checked_cast<int>(decoder_frame_length_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001914 }
1915 extracted_samples = packet->header.timestamp - first_timestamp +
1916 packet_duration;
1917
1918 // Check what packet is available next.
1919 header = packet_buffer_->NextRtpHeader();
1920 next_packet_available = false;
1921 if (header && prev_payload_type == header->payloadType) {
1922 int16_t seq_no_diff = header->sequenceNumber - prev_sequence_number;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001923 size_t ts_diff = header->timestamp - prev_timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001924 if (seq_no_diff == 1 ||
1925 (seq_no_diff == 0 && ts_diff == decoder_frame_length_)) {
1926 // The next sequence number is available, or the next part of a packet
1927 // that was split into pieces upon insertion.
1928 next_packet_available = true;
1929 }
1930 prev_sequence_number = header->sequenceNumber;
1931 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07001932 } while (extracted_samples < rtc::checked_cast<int>(required_samples) &&
1933 next_packet_available);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001934
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00001935 if (extracted_samples > 0) {
1936 // Delete old packets only when we are going to decode something. Otherwise,
1937 // we could end up in the situation where we never decode anything, since
1938 // all incoming packets are considered too old but the buffer will also
1939 // never be flooded and flushed.
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001940 packet_buffer_->DiscardAllOldPackets(timestamp_);
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00001941 }
1942
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001943 return extracted_samples;
1944}
1945
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001946void NetEqImpl::UpdatePlcComponents(int fs_hz, size_t channels) {
1947 // Delete objects and create new ones.
1948 expand_.reset(expand_factory_->Create(background_noise_.get(),
1949 sync_buffer_.get(), &random_vector_,
Henrik Lundinbef77e22015-08-18 14:58:09 +02001950 &stats_, fs_hz, channels));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001951 merge_.reset(new Merge(fs_hz, channels, expand_.get(), sync_buffer_.get()));
1952}
1953
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001954void NetEqImpl::SetSampleRateAndChannels(int fs_hz, size_t channels) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001955 LOG(LS_VERBOSE) << "SetSampleRateAndChannels " << fs_hz << " " << channels;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001956 // TODO(hlundin): Change to an enumerator and skip assert.
1957 assert(fs_hz == 8000 || fs_hz == 16000 || fs_hz == 32000 || fs_hz == 48000);
1958 assert(channels > 0);
1959
1960 fs_hz_ = fs_hz;
1961 fs_mult_ = fs_hz / 8000;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001962 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001963 decoder_frame_length_ = 3 * output_size_samples_; // Initialize to 30ms.
1964
1965 last_mode_ = kModeNormal;
1966
1967 // Create a new array of mute factors and set all to 1.
1968 mute_factor_array_.reset(new int16_t[channels]);
1969 for (size_t i = 0; i < channels; ++i) {
1970 mute_factor_array_[i] = 16384; // 1.0 in Q14.
1971 }
1972
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001973 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02001974 if (cng_decoder)
1975 cng_decoder->Reset();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001976
1977 // Reinit post-decode VAD with new sample rate.
1978 assert(vad_.get()); // Cannot be NULL here.
1979 vad_->Init();
1980
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001981 // Delete algorithm buffer and create a new one.
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001982 algorithm_buffer_.reset(new AudioMultiVector(channels));
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001983
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001984 // Delete sync buffer and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001985 sync_buffer_.reset(new SyncBuffer(channels, kSyncBufferSize * fs_mult_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001986
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00001987 // Delete BackgroundNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001988 background_noise_.reset(new BackgroundNoise(channels));
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00001989 background_noise_->set_mode(background_noise_mode_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001990
1991 // Reset random vector.
1992 random_vector_.Reset();
1993
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001994 UpdatePlcComponents(fs_hz, channels);
1995
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001996 // Move index so that we create a small set of future samples (all 0).
1997 sync_buffer_->set_next_index(sync_buffer_->next_index() -
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001998 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001999
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002000 normal_.reset(new Normal(fs_hz, decoder_database_.get(), *background_noise_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002001 expand_.get()));
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +00002002 accelerate_.reset(
2003 accelerate_factory_->Create(fs_hz, channels, *background_noise_));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002004 preemptive_expand_.reset(preemptive_expand_factory_->Create(
Peter Kastingdce40cf2015-08-24 14:52:23 -07002005 fs_hz, channels, *background_noise_, expand_->overlap_length()));
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002006
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002007 // Delete ComfortNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002008 comfort_noise_.reset(new ComfortNoise(fs_hz, decoder_database_.get(),
2009 sync_buffer_.get()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002010
2011 // Verify that |decoded_buffer_| is long enough.
2012 if (decoded_buffer_length_ < kMaxFrameSize * channels) {
2013 // Reallocate to larger size.
2014 decoded_buffer_length_ = kMaxFrameSize * channels;
2015 decoded_buffer_.reset(new int16_t[decoded_buffer_length_]);
2016 }
2017
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002018 // Create DecisionLogic if it is not created yet, then communicate new sample
2019 // rate and output size to DecisionLogic object.
2020 if (!decision_logic_.get()) {
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002021 CreateDecisionLogic();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002022 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002023 decision_logic_->SetSampleRate(fs_hz_, output_size_samples_);
2024}
2025
2026NetEqOutputType NetEqImpl::LastOutputType() {
2027 assert(vad_.get());
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002028 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002029 if (last_mode_ == kModeCodecInternalCng || last_mode_ == kModeRfc3389Cng) {
2030 return kOutputCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002031 } else if (last_mode_ == kModeExpand && expand_->MuteFactor(0) == 0) {
2032 // Expand mode has faded down to background noise only (very long expand).
2033 return kOutputPLCtoCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002034 } else if (last_mode_ == kModeExpand) {
2035 return kOutputPLC;
wu@webrtc.org24301a62013-12-13 19:17:43 +00002036 } else if (vad_->running() && !vad_->active_speech()) {
2037 return kOutputVADPassive;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002038 } else {
2039 return kOutputNormal;
2040 }
2041}
2042
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002043void NetEqImpl::CreateDecisionLogic() {
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002044 decision_logic_.reset(DecisionLogic::Create(fs_hz_, output_size_samples_,
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002045 playout_mode_,
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002046 decoder_database_.get(),
2047 *packet_buffer_.get(),
2048 delay_manager_.get(),
2049 buffer_level_filter_.get()));
2050}
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002051} // namespace webrtc