blob: 1c534dc60c6c95f2f2a13c45ef4c07738e7f1334 [file] [log] [blame]
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001/*
2 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000011#include "webrtc/modules/audio_coding/neteq/neteq_impl.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000012
13#include <assert.h>
14#include <memory.h> // memset
15
16#include <algorithm>
17
henrik.lundin9c3efd02015-08-27 13:12:22 -070018#include "webrtc/base/checks.h"
Henrik Lundind67a2192015-08-03 12:54:37 +020019#include "webrtc/base/logging.h"
Peter Kastingdce40cf2015-08-24 14:52:23 -070020#include "webrtc/base/safe_conversions.h"
henrik.lundina689b442015-12-17 03:50:05 -080021#include "webrtc/base/trace_event.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000022#include "webrtc/common_audio/signal_processing/include/signal_processing_library.h"
kwiberg@webrtc.orge04a93b2014-12-09 10:12:53 +000023#include "webrtc/modules/audio_coding/codecs/audio_decoder.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000024#include "webrtc/modules/audio_coding/neteq/accelerate.h"
25#include "webrtc/modules/audio_coding/neteq/background_noise.h"
26#include "webrtc/modules/audio_coding/neteq/buffer_level_filter.h"
27#include "webrtc/modules/audio_coding/neteq/comfort_noise.h"
28#include "webrtc/modules/audio_coding/neteq/decision_logic.h"
29#include "webrtc/modules/audio_coding/neteq/decoder_database.h"
30#include "webrtc/modules/audio_coding/neteq/defines.h"
31#include "webrtc/modules/audio_coding/neteq/delay_manager.h"
32#include "webrtc/modules/audio_coding/neteq/delay_peak_detector.h"
33#include "webrtc/modules/audio_coding/neteq/dtmf_buffer.h"
34#include "webrtc/modules/audio_coding/neteq/dtmf_tone_generator.h"
35#include "webrtc/modules/audio_coding/neteq/expand.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000036#include "webrtc/modules/audio_coding/neteq/merge.h"
henrik.lundin48ed9302015-10-29 05:36:24 -070037#include "webrtc/modules/audio_coding/neteq/nack.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000038#include "webrtc/modules/audio_coding/neteq/normal.h"
39#include "webrtc/modules/audio_coding/neteq/packet_buffer.h"
40#include "webrtc/modules/audio_coding/neteq/packet.h"
41#include "webrtc/modules/audio_coding/neteq/payload_splitter.h"
42#include "webrtc/modules/audio_coding/neteq/post_decode_vad.h"
43#include "webrtc/modules/audio_coding/neteq/preemptive_expand.h"
44#include "webrtc/modules/audio_coding/neteq/sync_buffer.h"
45#include "webrtc/modules/audio_coding/neteq/timestamp_scaler.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010046#include "webrtc/modules/include/module_common_types.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010047#include "webrtc/system_wrappers/include/critical_section_wrapper.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000048
49// Modify the code to obtain backwards bit-exactness. Once bit-exactness is no
50// longer required, this #define should be removed (and the code that it
51// enables).
52#define LEGACY_BITEXACT
53
54namespace webrtc {
55
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +000056NetEqImpl::NetEqImpl(const NetEq::Config& config,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000057 BufferLevelFilter* buffer_level_filter,
58 DecoderDatabase* decoder_database,
59 DelayManager* delay_manager,
60 DelayPeakDetector* delay_peak_detector,
61 DtmfBuffer* dtmf_buffer,
62 DtmfToneGenerator* dtmf_tone_generator,
63 PacketBuffer* packet_buffer,
64 PayloadSplitter* payload_splitter,
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +000065 TimestampScaler* timestamp_scaler,
66 AccelerateFactory* accelerate_factory,
67 ExpandFactory* expand_factory,
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +000068 PreemptiveExpandFactory* preemptive_expand_factory,
69 bool create_components)
henrik.lundin@webrtc.org2f816bb2014-06-05 10:37:13 +000070 : crit_sect_(CriticalSectionWrapper::CreateCriticalSection()),
71 buffer_level_filter_(buffer_level_filter),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000072 decoder_database_(decoder_database),
73 delay_manager_(delay_manager),
74 delay_peak_detector_(delay_peak_detector),
75 dtmf_buffer_(dtmf_buffer),
76 dtmf_tone_generator_(dtmf_tone_generator),
77 packet_buffer_(packet_buffer),
78 payload_splitter_(payload_splitter),
79 timestamp_scaler_(timestamp_scaler),
80 vad_(new PostDecodeVad()),
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +000081 expand_factory_(expand_factory),
82 accelerate_factory_(accelerate_factory),
83 preemptive_expand_factory_(preemptive_expand_factory),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000084 last_mode_(kModeNormal),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000085 decoded_buffer_length_(kMaxFrameSize),
86 decoded_buffer_(new int16_t[decoded_buffer_length_]),
87 playout_timestamp_(0),
88 new_codec_(false),
89 timestamp_(0),
90 reset_decoder_(false),
henrik.lundin48ed9302015-10-29 05:36:24 -070091 current_rtp_payload_type_(0xFF), // Invalid RTP payload type.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000092 current_cng_rtp_payload_type_(0xFF), // Invalid RTP payload type.
93 ssrc_(0),
94 first_packet_(true),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000095 error_code_(0),
96 decoder_error_code_(0),
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +000097 background_noise_mode_(config.background_noise_mode),
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +000098 playout_mode_(config.playout_mode),
Henrik Lundincf808d22015-05-27 14:33:29 +020099 enable_fast_accelerate_(config.enable_fast_accelerate),
henrik.lundin48ed9302015-10-29 05:36:24 -0700100 nack_enabled_(false) {
Henrik Lundin905495c2015-05-25 16:58:41 +0200101 LOG(LS_INFO) << "NetEq config: " << config.ToString();
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +0000102 int fs = config.sample_rate_hz;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000103 if (fs != 8000 && fs != 16000 && fs != 32000 && fs != 48000) {
104 LOG(LS_ERROR) << "Sample rate " << fs << " Hz not supported. " <<
105 "Changing to 8000 Hz.";
106 fs = 8000;
107 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000108 fs_hz_ = fs;
109 fs_mult_ = fs / 8000;
henrik.lundind89814b2015-11-23 06:49:25 -0800110 last_output_sample_rate_hz_ = fs;
Peter Kastingdce40cf2015-08-24 14:52:23 -0700111 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000112 decoder_frame_length_ = 3 * output_size_samples_;
113 WebRtcSpl_Init();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000114 if (create_components) {
115 SetSampleRateAndChannels(fs, 1); // Default is 1 channel.
116 }
henrik.lundin9bc26672015-11-02 03:25:57 -0800117 RTC_DCHECK(!vad_->enabled());
118 if (config.enable_post_decode_vad) {
119 vad_->Enable();
120 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000121}
122
Henrik Lundind67a2192015-08-03 12:54:37 +0200123NetEqImpl::~NetEqImpl() = default;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000124
125int NetEqImpl::InsertPacket(const WebRtcRTPHeader& rtp_header,
kwibergee2bac22015-11-11 10:34:00 -0800126 rtc::ArrayView<const uint8_t> payload,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000127 uint32_t receive_timestamp) {
henrik.lundina689b442015-12-17 03:50:05 -0800128 TRACE_EVENT0("webrtc", "NetEqImpl::InsertPacket");
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000129 CriticalSectionScoped lock(crit_sect_.get());
kwibergee2bac22015-11-11 10:34:00 -0800130 int error =
131 InsertPacketInternal(rtp_header, payload, receive_timestamp, false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000132 if (error != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000133 error_code_ = error;
134 return kFail;
135 }
136 return kOK;
137}
138
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000139int NetEqImpl::InsertSyncPacket(const WebRtcRTPHeader& rtp_header,
140 uint32_t receive_timestamp) {
141 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000142 const uint8_t kSyncPayload[] = { 's', 'y', 'n', 'c' };
kwibergee2bac22015-11-11 10:34:00 -0800143 int error =
144 InsertPacketInternal(rtp_header, kSyncPayload, receive_timestamp, true);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000145
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000146 if (error != 0) {
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000147 error_code_ = error;
148 return kFail;
149 }
150 return kOK;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000151}
152
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000153int NetEqImpl::GetAudio(size_t max_length, int16_t* output_audio,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700154 size_t* samples_per_channel, int* num_channels,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000155 NetEqOutputType* type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000156 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000157 int error = GetAudioInternal(max_length, output_audio, samples_per_channel,
158 num_channels);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000159 if (error != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000160 error_code_ = error;
161 return kFail;
162 }
163 if (type) {
164 *type = LastOutputType();
165 }
henrik.lundind89814b2015-11-23 06:49:25 -0800166 last_output_sample_rate_hz_ =
167 rtc::checked_cast<int>(*samples_per_channel * 100);
168 RTC_DCHECK(last_output_sample_rate_hz_ == 8000 ||
169 last_output_sample_rate_hz_ == 16000 ||
170 last_output_sample_rate_hz_ == 32000 ||
171 last_output_sample_rate_hz_ == 48000)
172 << "Unexpected sample rate " << last_output_sample_rate_hz_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000173 return kOK;
174}
175
kwibergee1879c2015-10-29 06:20:28 -0700176int NetEqImpl::RegisterPayloadType(NetEqDecoder codec,
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800177 const std::string& name,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000178 uint8_t rtp_payload_type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000179 CriticalSectionScoped lock(crit_sect_.get());
Henrik Lundind67a2192015-08-03 12:54:37 +0200180 LOG(LS_VERBOSE) << "RegisterPayloadType "
kwibergee1879c2015-10-29 06:20:28 -0700181 << static_cast<int>(rtp_payload_type) << " "
182 << static_cast<int>(codec);
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800183 int ret = decoder_database_->RegisterPayload(rtp_payload_type, codec, name);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000184 if (ret != DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000185 switch (ret) {
186 case DecoderDatabase::kInvalidRtpPayloadType:
187 error_code_ = kInvalidRtpPayloadType;
188 break;
189 case DecoderDatabase::kCodecNotSupported:
190 error_code_ = kCodecNotSupported;
191 break;
192 case DecoderDatabase::kDecoderExists:
193 error_code_ = kDecoderExists;
194 break;
195 default:
196 error_code_ = kOtherError;
197 }
198 return kFail;
199 }
200 return kOK;
201}
202
203int NetEqImpl::RegisterExternalDecoder(AudioDecoder* decoder,
kwibergee1879c2015-10-29 06:20:28 -0700204 NetEqDecoder codec,
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800205 const std::string& codec_name,
Karl Wibergd8399e62015-05-25 14:39:56 +0200206 uint8_t rtp_payload_type,
207 int sample_rate_hz) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000208 CriticalSectionScoped lock(crit_sect_.get());
Henrik Lundind67a2192015-08-03 12:54:37 +0200209 LOG(LS_VERBOSE) << "RegisterExternalDecoder "
kwibergee1879c2015-10-29 06:20:28 -0700210 << static_cast<int>(rtp_payload_type) << " "
211 << static_cast<int>(codec);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000212 if (!decoder) {
213 LOG(LS_ERROR) << "Cannot register external decoder with NULL pointer";
214 assert(false);
215 return kFail;
216 }
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800217 int ret = decoder_database_->InsertExternal(
218 rtp_payload_type, codec, codec_name, sample_rate_hz, decoder);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000219 if (ret != DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000220 switch (ret) {
221 case DecoderDatabase::kInvalidRtpPayloadType:
222 error_code_ = kInvalidRtpPayloadType;
223 break;
224 case DecoderDatabase::kCodecNotSupported:
225 error_code_ = kCodecNotSupported;
226 break;
227 case DecoderDatabase::kDecoderExists:
228 error_code_ = kDecoderExists;
229 break;
230 case DecoderDatabase::kInvalidSampleRate:
231 error_code_ = kInvalidSampleRate;
232 break;
233 case DecoderDatabase::kInvalidPointer:
234 error_code_ = kInvalidPointer;
235 break;
236 default:
237 error_code_ = kOtherError;
238 }
239 return kFail;
240 }
241 return kOK;
242}
243
244int NetEqImpl::RemovePayloadType(uint8_t rtp_payload_type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000245 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000246 int ret = decoder_database_->Remove(rtp_payload_type);
247 if (ret == DecoderDatabase::kOK) {
248 return kOK;
249 } else if (ret == DecoderDatabase::kDecoderNotFound) {
250 error_code_ = kDecoderNotFound;
251 } else {
252 error_code_ = kOtherError;
253 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000254 return kFail;
255}
256
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000257bool NetEqImpl::SetMinimumDelay(int delay_ms) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000258 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000259 if (delay_ms >= 0 && delay_ms < 10000) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000260 assert(delay_manager_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000261 return delay_manager_->SetMinimumDelay(delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000262 }
263 return false;
264}
265
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000266bool NetEqImpl::SetMaximumDelay(int delay_ms) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000267 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000268 if (delay_ms >= 0 && delay_ms < 10000) {
269 assert(delay_manager_.get());
270 return delay_manager_->SetMaximumDelay(delay_ms);
271 }
272 return false;
273}
274
275int NetEqImpl::LeastRequiredDelayMs() const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000276 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000277 assert(delay_manager_.get());
278 return delay_manager_->least_required_delay_ms();
279}
280
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200281int NetEqImpl::SetTargetDelay() {
282 return kNotImplemented;
283}
284
285int NetEqImpl::TargetDelay() {
286 return kNotImplemented;
287}
288
henrik.lundin9c3efd02015-08-27 13:12:22 -0700289int NetEqImpl::CurrentDelayMs() const {
290 CriticalSectionScoped lock(crit_sect_.get());
291 if (fs_hz_ == 0)
292 return 0;
293 // Sum up the samples in the packet buffer with the future length of the sync
294 // buffer, and divide the sum by the sample rate.
295 const size_t delay_samples =
296 packet_buffer_->NumSamplesInBuffer(decoder_database_.get(),
297 decoder_frame_length_) +
298 sync_buffer_->FutureLength();
299 // The division below will truncate.
300 const int delay_ms =
301 static_cast<int>(delay_samples) / rtc::CheckedDivExact(fs_hz_, 1000);
302 return delay_ms;
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200303}
304
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000305// Deprecated.
306// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000307void NetEqImpl::SetPlayoutMode(NetEqPlayoutMode mode) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000308 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000309 if (mode != playout_mode_) {
310 playout_mode_ = mode;
311 CreateDecisionLogic();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000312 }
313}
314
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000315// Deprecated.
316// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000317NetEqPlayoutMode NetEqImpl::PlayoutMode() const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000318 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000319 return playout_mode_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000320}
321
322int NetEqImpl::NetworkStatistics(NetEqNetworkStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000323 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000324 assert(decoder_database_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700325 const size_t total_samples_in_buffers =
Peter Kasting728d9032015-06-11 14:31:38 -0700326 packet_buffer_->NumSamplesInBuffer(decoder_database_.get(),
327 decoder_frame_length_) +
Peter Kastingdce40cf2015-08-24 14:52:23 -0700328 sync_buffer_->FutureLength();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000329 assert(delay_manager_.get());
330 assert(decision_logic_.get());
331 stats_.GetNetworkStatistics(fs_hz_, total_samples_in_buffers,
332 decoder_frame_length_, *delay_manager_.get(),
333 *decision_logic_.get(), stats);
334 return 0;
335}
336
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000337void NetEqImpl::GetRtcpStatistics(RtcpStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000338 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000339 if (stats) {
340 rtcp_.GetStatistics(false, stats);
341 }
342}
343
344void NetEqImpl::GetRtcpStatisticsNoReset(RtcpStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000345 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000346 if (stats) {
347 rtcp_.GetStatistics(true, stats);
348 }
349}
350
351void NetEqImpl::EnableVad() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000352 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000353 assert(vad_.get());
354 vad_->Enable();
355}
356
357void NetEqImpl::DisableVad() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000358 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000359 assert(vad_.get());
360 vad_->Disable();
361}
362
wu@webrtc.org94454b72014-06-05 20:34:08 +0000363bool NetEqImpl::GetPlayoutTimestamp(uint32_t* timestamp) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000364 CriticalSectionScoped lock(crit_sect_.get());
wu@webrtc.org94454b72014-06-05 20:34:08 +0000365 if (first_packet_) {
366 // We don't have a valid RTP timestamp until we have decoded our first
367 // RTP packet.
368 return false;
369 }
370 *timestamp = timestamp_scaler_->ToExternal(playout_timestamp_);
371 return true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000372}
373
henrik.lundind89814b2015-11-23 06:49:25 -0800374int NetEqImpl::last_output_sample_rate_hz() const {
375 CriticalSectionScoped lock(crit_sect_.get());
376 return last_output_sample_rate_hz_;
377}
378
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200379int NetEqImpl::SetTargetNumberOfChannels() {
380 return kNotImplemented;
381}
382
383int NetEqImpl::SetTargetSampleRate() {
384 return kNotImplemented;
385}
386
henrik.lundin@webrtc.orgb0f4b3d2014-11-04 08:53:10 +0000387int NetEqImpl::LastError() const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000388 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000389 return error_code_;
390}
391
392int NetEqImpl::LastDecoderError() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000393 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000394 return decoder_error_code_;
395}
396
397void NetEqImpl::FlushBuffers() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000398 CriticalSectionScoped lock(crit_sect_.get());
Henrik Lundind67a2192015-08-03 12:54:37 +0200399 LOG(LS_VERBOSE) << "FlushBuffers";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000400 packet_buffer_->Flush();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000401 assert(sync_buffer_.get());
402 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000403 sync_buffer_->Flush();
404 sync_buffer_->set_next_index(sync_buffer_->next_index() -
405 expand_->overlap_length());
406 // Set to wait for new codec.
407 first_packet_ = true;
408}
409
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000410void NetEqImpl::PacketBufferStatistics(int* current_num_packets,
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000411 int* max_num_packets) const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000412 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000413 packet_buffer_->BufferStat(current_num_packets, max_num_packets);
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000414}
415
henrik.lundin48ed9302015-10-29 05:36:24 -0700416void NetEqImpl::EnableNack(size_t max_nack_list_size) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000417 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin48ed9302015-10-29 05:36:24 -0700418 if (!nack_enabled_) {
419 const int kNackThresholdPackets = 2;
420 nack_.reset(Nack::Create(kNackThresholdPackets));
421 nack_enabled_ = true;
422 nack_->UpdateSampleRate(fs_hz_);
423 }
424 nack_->SetMaxNackListSize(max_nack_list_size);
425}
426
427void NetEqImpl::DisableNack() {
428 CriticalSectionScoped lock(crit_sect_.get());
429 nack_.reset();
430 nack_enabled_ = false;
431}
432
433std::vector<uint16_t> NetEqImpl::GetNackList(int64_t round_trip_time_ms) const {
434 CriticalSectionScoped lock(crit_sect_.get());
435 if (!nack_enabled_) {
436 return std::vector<uint16_t>();
437 }
438 RTC_DCHECK(nack_.get());
439 return nack_->GetNackList(round_trip_time_ms);
minyue@webrtc.orgd7301772013-08-29 00:58:14 +0000440}
441
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000442const SyncBuffer* NetEqImpl::sync_buffer_for_test() const {
443 CriticalSectionScoped lock(crit_sect_.get());
444 return sync_buffer_.get();
445}
446
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000447// Methods below this line are private.
448
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000449int NetEqImpl::InsertPacketInternal(const WebRtcRTPHeader& rtp_header,
kwibergee2bac22015-11-11 10:34:00 -0800450 rtc::ArrayView<const uint8_t> payload,
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000451 uint32_t receive_timestamp,
452 bool is_sync_packet) {
kwibergee2bac22015-11-11 10:34:00 -0800453 if (payload.empty()) {
454 LOG_F(LS_ERROR) << "payload is empty";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000455 return kInvalidPointer;
456 }
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000457 // Sanity checks for sync-packets.
458 if (is_sync_packet) {
459 if (decoder_database_->IsDtmf(rtp_header.header.payloadType) ||
460 decoder_database_->IsRed(rtp_header.header.payloadType) ||
461 decoder_database_->IsComfortNoise(rtp_header.header.payloadType)) {
462 LOG_F(LS_ERROR) << "Sync-packet with an unacceptable payload type "
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000463 << static_cast<int>(rtp_header.header.payloadType);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000464 return kSyncPacketNotAccepted;
465 }
466 if (first_packet_ ||
467 rtp_header.header.payloadType != current_rtp_payload_type_ ||
468 rtp_header.header.ssrc != ssrc_) {
469 // Even if |current_rtp_payload_type_| is 0xFF, sync-packet isn't
470 // accepted.
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000471 LOG_F(LS_ERROR)
472 << "Changing codec, SSRC or first packet with sync-packet.";
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000473 return kSyncPacketNotAccepted;
474 }
475 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000476 PacketList packet_list;
477 RTPHeader main_header;
478 {
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000479 // Convert to Packet.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000480 // Create |packet| within this separate scope, since it should not be used
481 // directly once it's been inserted in the packet list. This way, |packet|
482 // is not defined outside of this block.
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000483 Packet* packet = new Packet;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000484 packet->header.markerBit = false;
485 packet->header.payloadType = rtp_header.header.payloadType;
486 packet->header.sequenceNumber = rtp_header.header.sequenceNumber;
487 packet->header.timestamp = rtp_header.header.timestamp;
488 packet->header.ssrc = rtp_header.header.ssrc;
489 packet->header.numCSRCs = 0;
kwibergee2bac22015-11-11 10:34:00 -0800490 packet->payload_length = payload.size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000491 packet->primary = true;
492 packet->waiting_time = 0;
493 packet->payload = new uint8_t[packet->payload_length];
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000494 packet->sync_packet = is_sync_packet;
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +0000495 if (!packet->payload) {
496 LOG_F(LS_ERROR) << "Payload pointer is NULL.";
497 }
kwibergee2bac22015-11-11 10:34:00 -0800498 assert(!payload.empty()); // Already checked above.
499 memcpy(packet->payload, payload.data(), packet->payload_length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000500 // Insert packet in a packet list.
501 packet_list.push_back(packet);
502 // Save main payloads header for later.
503 memcpy(&main_header, &packet->header, sizeof(main_header));
504 }
505
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000506 bool update_sample_rate_and_channels = false;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000507 // Reinitialize NetEq if it's needed (changed SSRC or first call).
508 if ((main_header.ssrc != ssrc_) || first_packet_) {
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000509 // Note: |first_packet_| will be cleared further down in this method, once
510 // the packet has been successfully inserted into the packet buffer.
511
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000512 rtcp_.Init(main_header.sequenceNumber);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000513
514 // Flush the packet buffer and DTMF buffer.
515 packet_buffer_->Flush();
516 dtmf_buffer_->Flush();
517
518 // Store new SSRC.
519 ssrc_ = main_header.ssrc;
520
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000521 // Update audio buffer timestamp.
522 sync_buffer_->IncreaseEndTimestamp(main_header.timestamp - timestamp_);
523
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000524 // Update codecs.
525 timestamp_ = main_header.timestamp;
526 current_rtp_payload_type_ = main_header.payloadType;
527
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000528 // Reset timestamp scaling.
529 timestamp_scaler_->Reset();
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000530
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000531 // Trigger an update of sampling rate and the number of channels.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000532 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000533 }
534
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000535 // Update RTCP statistics, only for regular packets.
536 if (!is_sync_packet)
537 rtcp_.Update(main_header, receive_timestamp);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000538
539 // Check for RED payload type, and separate payloads into several packets.
540 if (decoder_database_->IsRed(main_header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000541 assert(!is_sync_packet); // We had a sanity check for this.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000542 if (payload_splitter_->SplitRed(&packet_list) != PayloadSplitter::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000543 PacketBuffer::DeleteAllPackets(&packet_list);
544 return kRedundancySplitError;
545 }
546 // Only accept a few RED payloads of the same type as the main data,
547 // DTMF events and CNG.
548 payload_splitter_->CheckRedPayloads(&packet_list, *decoder_database_);
549 // Update the stored main payload header since the main payload has now
550 // changed.
551 memcpy(&main_header, &packet_list.front()->header, sizeof(main_header));
552 }
553
554 // Check payload types.
555 if (decoder_database_->CheckPayloadTypes(packet_list) ==
556 DecoderDatabase::kDecoderNotFound) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000557 PacketBuffer::DeleteAllPackets(&packet_list);
558 return kUnknownRtpPayloadType;
559 }
560
561 // Scale timestamp to internal domain (only for some codecs).
562 timestamp_scaler_->ToInternal(&packet_list);
563
564 // Process DTMF payloads. Cycle through the list of packets, and pick out any
565 // DTMF payloads found.
566 PacketList::iterator it = packet_list.begin();
567 while (it != packet_list.end()) {
568 Packet* current_packet = (*it);
569 assert(current_packet);
570 assert(current_packet->payload);
571 if (decoder_database_->IsDtmf(current_packet->header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000572 assert(!current_packet->sync_packet); // We had a sanity check for this.
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000573 DtmfEvent event;
574 int ret = DtmfBuffer::ParseEvent(
575 current_packet->header.timestamp,
576 current_packet->payload,
577 current_packet->payload_length,
578 &event);
579 if (ret != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000580 PacketBuffer::DeleteAllPackets(&packet_list);
581 return kDtmfParsingError;
582 }
583 if (dtmf_buffer_->InsertEvent(event) != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000584 PacketBuffer::DeleteAllPackets(&packet_list);
585 return kDtmfInsertError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000586 }
587 // TODO(hlundin): Let the destructor of Packet handle the payload.
588 delete [] current_packet->payload;
589 delete current_packet;
590 it = packet_list.erase(it);
591 } else {
592 ++it;
593 }
594 }
595
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000596 // Check for FEC in packets, and separate payloads into several packets.
597 int ret = payload_splitter_->SplitFec(&packet_list, decoder_database_.get());
598 if (ret != PayloadSplitter::kOK) {
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000599 PacketBuffer::DeleteAllPackets(&packet_list);
600 switch (ret) {
601 case PayloadSplitter::kUnknownPayloadType:
602 return kUnknownRtpPayloadType;
603 default:
604 return kOtherError;
605 }
606 }
607
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000608 // Split payloads into smaller chunks. This also verifies that all payloads
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000609 // are of a known payload type. SplitAudio() method is protected against
610 // sync-packets.
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +0000611 ret = payload_splitter_->SplitAudio(&packet_list, *decoder_database_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000612 if (ret != PayloadSplitter::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000613 PacketBuffer::DeleteAllPackets(&packet_list);
614 switch (ret) {
615 case PayloadSplitter::kUnknownPayloadType:
616 return kUnknownRtpPayloadType;
617 case PayloadSplitter::kFrameSplitError:
618 return kFrameSplitError;
619 default:
620 return kOtherError;
621 }
622 }
623
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000624 // Update bandwidth estimate, if the packet is not sync-packet.
625 if (!packet_list.empty() && !packet_list.front()->sync_packet) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000626 // The list can be empty here if we got nothing but DTMF payloads.
627 AudioDecoder* decoder =
628 decoder_database_->GetDecoder(main_header.payloadType);
629 assert(decoder); // Should always get a valid object, since we have
630 // already checked that the payload types are known.
631 decoder->IncomingPacket(packet_list.front()->payload,
632 packet_list.front()->payload_length,
633 packet_list.front()->header.sequenceNumber,
634 packet_list.front()->header.timestamp,
635 receive_timestamp);
636 }
637
henrik.lundin48ed9302015-10-29 05:36:24 -0700638 if (nack_enabled_) {
639 RTC_DCHECK(nack_);
640 if (update_sample_rate_and_channels) {
641 nack_->Reset();
642 }
643 nack_->UpdateLastReceivedPacket(packet_list.front()->header.sequenceNumber,
644 packet_list.front()->header.timestamp);
645 }
646
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000647 // Insert packets in buffer.
henrik.lundin116c84e2015-08-27 13:14:48 -0700648 const size_t buffer_length_before_insert =
649 packet_buffer_->NumPacketsInBuffer();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000650 ret = packet_buffer_->InsertPacketList(
651 &packet_list,
652 *decoder_database_,
653 &current_rtp_payload_type_,
654 &current_cng_rtp_payload_type_);
655 if (ret == PacketBuffer::kFlushed) {
656 // Reset DSP timestamp etc. if packet buffer flushed.
657 new_codec_ = true;
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000658 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000659 } else if (ret != PacketBuffer::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000660 PacketBuffer::DeleteAllPackets(&packet_list);
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000661 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000662 }
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000663
664 if (first_packet_) {
665 first_packet_ = false;
666 // Update the codec on the next GetAudio call.
667 new_codec_ = true;
668 }
669
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000670 if (current_rtp_payload_type_ != 0xFF) {
671 const DecoderDatabase::DecoderInfo* dec_info =
672 decoder_database_->GetDecoderInfo(current_rtp_payload_type_);
673 if (!dec_info) {
674 assert(false); // Already checked that the payload type is known.
675 }
676 }
677
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000678 if (update_sample_rate_and_channels && !packet_buffer_->Empty()) {
679 // We do not use |current_rtp_payload_type_| to |set payload_type|, but
680 // get the next RTP header from |packet_buffer_| to obtain the payload type.
681 // The reason for it is the following corner case. If NetEq receives a
682 // CNG packet with a sample rate different than the current CNG then it
683 // flushes its buffer, assuming send codec must have been changed. However,
684 // payload type of the hypothetically new send codec is not known.
685 const RTPHeader* rtp_header = packet_buffer_->NextRtpHeader();
686 assert(rtp_header);
687 int payload_type = rtp_header->payloadType;
688 AudioDecoder* decoder = decoder_database_->GetDecoder(payload_type);
689 assert(decoder); // Payloads are already checked to be valid.
690 const DecoderDatabase::DecoderInfo* decoder_info =
691 decoder_database_->GetDecoderInfo(payload_type);
692 assert(decoder_info);
693 if (decoder_info->fs_hz != fs_hz_ ||
henrik.lundin48ed9302015-10-29 05:36:24 -0700694 decoder->Channels() != algorithm_buffer_->Channels()) {
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +0000695 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->Channels());
henrik.lundin48ed9302015-10-29 05:36:24 -0700696 }
697 if (nack_enabled_) {
698 RTC_DCHECK(nack_);
699 // Update the sample rate even if the rate is not new, because of Reset().
700 nack_->UpdateSampleRate(fs_hz_);
701 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000702 }
703
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000704 // TODO(hlundin): Move this code to DelayManager class.
705 const DecoderDatabase::DecoderInfo* dec_info =
706 decoder_database_->GetDecoderInfo(main_header.payloadType);
707 assert(dec_info); // Already checked that the payload type is known.
708 delay_manager_->LastDecoderType(dec_info->codec_type);
709 if (delay_manager_->last_pack_cng_or_dtmf() == 0) {
710 // Calculate the total speech length carried in each packet.
henrik.lundin116c84e2015-08-27 13:14:48 -0700711 const size_t buffer_length_after_insert =
712 packet_buffer_->NumPacketsInBuffer();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000713
henrik.lundin116c84e2015-08-27 13:14:48 -0700714 if (buffer_length_after_insert > buffer_length_before_insert) {
715 const size_t packet_length_samples =
716 (buffer_length_after_insert - buffer_length_before_insert) *
717 decoder_frame_length_;
718 if (packet_length_samples != decision_logic_->packet_length_samples()) {
719 decision_logic_->set_packet_length_samples(packet_length_samples);
720 delay_manager_->SetPacketAudioLength(
721 rtc::checked_cast<int>((1000 * packet_length_samples) / fs_hz_));
722 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000723 }
724
725 // Update statistics.
pbos@webrtc.org0946a562013-04-09 00:28:06 +0000726 if ((int32_t) (main_header.timestamp - timestamp_) >= 0 &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000727 !new_codec_) {
728 // Only update statistics if incoming packet is not older than last played
729 // out packet, and if new codec flag is not set.
730 delay_manager_->Update(main_header.sequenceNumber, main_header.timestamp,
731 fs_hz_);
732 }
733 } else if (delay_manager_->last_pack_cng_or_dtmf() == -1) {
734 // This is first "normal" packet after CNG or DTMF.
735 // Reset packet time counter and measure time until next packet,
736 // but don't update statistics.
737 delay_manager_->set_last_pack_cng_or_dtmf(0);
738 delay_manager_->ResetPacketIatCount();
739 }
740 return 0;
741}
742
Peter Kasting728d9032015-06-11 14:31:38 -0700743int NetEqImpl::GetAudioInternal(size_t max_length,
744 int16_t* output,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700745 size_t* samples_per_channel,
Peter Kasting728d9032015-06-11 14:31:38 -0700746 int* num_channels) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000747 PacketList packet_list;
748 DtmfEvent dtmf_event;
749 Operations operation;
750 bool play_dtmf;
751 int return_value = GetDecision(&operation, &packet_list, &dtmf_event,
752 &play_dtmf);
753 if (return_value != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000754 last_mode_ = kModeError;
755 return return_value;
756 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000757
758 AudioDecoder::SpeechType speech_type;
759 int length = 0;
760 int decode_return_value = Decode(&packet_list, &operation,
761 &length, &speech_type);
762
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000763 assert(vad_.get());
764 bool sid_frame_available =
765 (operation == kRfc3389Cng && !packet_list.empty());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700766 vad_->Update(decoded_buffer_.get(), static_cast<size_t>(length), speech_type,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000767 sid_frame_available, fs_hz_);
768
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000769 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000770 switch (operation) {
771 case kNormal: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000772 DoNormal(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000773 break;
774 }
775 case kMerge: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000776 DoMerge(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000777 break;
778 }
779 case kExpand: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000780 return_value = DoExpand(play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000781 break;
782 }
Henrik Lundincf808d22015-05-27 14:33:29 +0200783 case kAccelerate:
784 case kFastAccelerate: {
785 const bool fast_accelerate =
786 enable_fast_accelerate_ && (operation == kFastAccelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000787 return_value = DoAccelerate(decoded_buffer_.get(), length, speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +0200788 play_dtmf, fast_accelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000789 break;
790 }
791 case kPreemptiveExpand: {
792 return_value = DoPreemptiveExpand(decoded_buffer_.get(), length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000793 speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000794 break;
795 }
796 case kRfc3389Cng:
797 case kRfc3389CngNoPacket: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000798 return_value = DoRfc3389Cng(&packet_list, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000799 break;
800 }
801 case kCodecInternalCng: {
802 // This handles the case when there is no transmission and the decoder
803 // should produce internal comfort noise.
804 // TODO(hlundin): Write test for codec-internal CNG.
minyuel6d92bf52015-09-23 15:20:39 +0200805 DoCodecInternalCng(decoded_buffer_.get(), length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000806 break;
807 }
808 case kDtmf: {
809 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000810 return_value = DoDtmf(dtmf_event, &play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000811 break;
812 }
813 case kAlternativePlc: {
814 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000815 DoAlternativePlc(false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000816 break;
817 }
818 case kAlternativePlcIncreaseTimestamp: {
819 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000820 DoAlternativePlc(true);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000821 break;
822 }
823 case kAudioRepetitionIncreaseTimestamp: {
824 // TODO(hlundin): Write test for this.
Peter Kastingb7e50542015-06-11 12:55:50 -0700825 sync_buffer_->IncreaseEndTimestamp(
826 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000827 // Skipping break on purpose. Execution should move on into the
828 // next case.
kjellander@webrtc.org7d2b6a92015-01-28 18:37:58 +0000829 FALLTHROUGH();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000830 }
831 case kAudioRepetition: {
832 // TODO(hlundin): Write test for this.
833 // Copy last |output_size_samples_| from |sync_buffer_| to
834 // |algorithm_buffer|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000835 algorithm_buffer_->PushBackFromIndex(
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000836 *sync_buffer_, sync_buffer_->Size() - output_size_samples_);
837 expand_->Reset();
838 break;
839 }
840 case kUndefined: {
Henrik Lundind67a2192015-08-03 12:54:37 +0200841 LOG(LS_ERROR) << "Invalid operation kUndefined.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000842 assert(false); // This should not happen.
843 last_mode_ = kModeError;
844 return kInvalidOperation;
845 }
846 } // End of switch.
847 if (return_value < 0) {
848 return return_value;
849 }
850
851 if (last_mode_ != kModeRfc3389Cng) {
852 comfort_noise_->Reset();
853 }
854
855 // Copy from |algorithm_buffer| to |sync_buffer_|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000856 sync_buffer_->PushBack(*algorithm_buffer_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000857
858 // Extract data from |sync_buffer_| to |output|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000859 size_t num_output_samples_per_channel = output_size_samples_;
860 size_t num_output_samples = output_size_samples_ * sync_buffer_->Channels();
861 if (num_output_samples > max_length) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000862 LOG(LS_WARNING) << "Output array is too short. " << max_length << " < " <<
863 output_size_samples_ << " * " << sync_buffer_->Channels();
864 num_output_samples = max_length;
Peter Kastingdce40cf2015-08-24 14:52:23 -0700865 num_output_samples_per_channel = max_length / sync_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000866 }
Peter Kastingdce40cf2015-08-24 14:52:23 -0700867 const size_t samples_from_sync =
868 sync_buffer_->GetNextAudioInterleaved(num_output_samples_per_channel,
869 output);
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000870 *num_channels = static_cast<int>(sync_buffer_->Channels());
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200871 if (sync_buffer_->FutureLength() < expand_->overlap_length()) {
872 // The sync buffer should always contain |overlap_length| samples, but now
873 // too many samples have been extracted. Reinstall the |overlap_length|
874 // lookahead by moving the index.
875 const size_t missing_lookahead_samples =
876 expand_->overlap_length() - sync_buffer_->FutureLength();
henrikg91d6ede2015-09-17 00:24:34 -0700877 RTC_DCHECK_GE(sync_buffer_->next_index(), missing_lookahead_samples);
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200878 sync_buffer_->set_next_index(sync_buffer_->next_index() -
879 missing_lookahead_samples);
880 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000881 if (samples_from_sync != output_size_samples_) {
Henrik Lundind67a2192015-08-03 12:54:37 +0200882 LOG(LS_ERROR) << "samples_from_sync (" << samples_from_sync
883 << ") != output_size_samples_ (" << output_size_samples_
884 << ")";
minyue@webrtc.orgdb1cefc2013-08-13 01:39:21 +0000885 // TODO(minyue): treatment of under-run, filling zeros
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000886 memset(output, 0, num_output_samples * sizeof(int16_t));
887 *samples_per_channel = output_size_samples_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000888 return kSampleUnderrun;
889 }
890 *samples_per_channel = output_size_samples_;
891
892 // Should always have overlap samples left in the |sync_buffer_|.
henrikg91d6ede2015-09-17 00:24:34 -0700893 RTC_DCHECK_GE(sync_buffer_->FutureLength(), expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000894
895 if (play_dtmf) {
896 return_value = DtmfOverdub(dtmf_event, sync_buffer_->Channels(), output);
897 }
898
899 // Update the background noise parameters if last operation wrote data
900 // straight from the decoder to the |sync_buffer_|. That is, none of the
901 // operations that modify the signal can be followed by a parameter update.
902 if ((last_mode_ == kModeNormal) ||
903 (last_mode_ == kModeAccelerateFail) ||
904 (last_mode_ == kModePreemptiveExpandFail) ||
905 (last_mode_ == kModeRfc3389Cng) ||
906 (last_mode_ == kModeCodecInternalCng)) {
907 background_noise_->Update(*sync_buffer_, *vad_.get());
908 }
909
910 if (operation == kDtmf) {
911 // DTMF data was written the end of |sync_buffer_|.
912 // Update index to end of DTMF data in |sync_buffer_|.
913 sync_buffer_->set_dtmf_index(sync_buffer_->Size());
914 }
915
henrik.lundin@webrtc.orged865b52014-03-06 10:28:07 +0000916 if (last_mode_ != kModeExpand) {
917 // If last operation was not expand, calculate the |playout_timestamp_| from
918 // the |sync_buffer_|. However, do not update the |playout_timestamp_| if it
919 // would be moved "backwards".
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000920 uint32_t temp_timestamp = sync_buffer_->end_timestamp() -
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000921 static_cast<uint32_t>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000922 if (static_cast<int32_t>(temp_timestamp - playout_timestamp_) > 0) {
923 playout_timestamp_ = temp_timestamp;
924 }
925 } else {
926 // Use dead reckoning to estimate the |playout_timestamp_|.
Peter Kastingb7e50542015-06-11 12:55:50 -0700927 playout_timestamp_ += static_cast<uint32_t>(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000928 }
929
930 if (decode_return_value) return decode_return_value;
931 return return_value;
932}
933
934int NetEqImpl::GetDecision(Operations* operation,
935 PacketList* packet_list,
936 DtmfEvent* dtmf_event,
937 bool* play_dtmf) {
938 // Initialize output variables.
939 *play_dtmf = false;
940 *operation = kUndefined;
941
942 // Increment time counters.
943 packet_buffer_->IncrementWaitingTimes();
944 stats_.IncreaseCounter(output_size_samples_, fs_hz_);
945
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000946 assert(sync_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000947 uint32_t end_timestamp = sync_buffer_->end_timestamp();
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +0000948 if (!new_codec_) {
949 const uint32_t five_seconds_samples = 5 * fs_hz_;
950 packet_buffer_->DiscardOldPackets(end_timestamp, five_seconds_samples);
951 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000952 const RTPHeader* header = packet_buffer_->NextRtpHeader();
953
henrik.lundin@webrtc.orgca8cb952014-03-12 10:26:52 +0000954 if (decision_logic_->CngRfc3389On() || last_mode_ == kModeRfc3389Cng) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000955 // Because of timestamp peculiarities, we have to "manually" disallow using
956 // a CNG packet with the same timestamp as the one that was last played.
957 // This can happen when using redundancy and will cause the timing to shift.
henrik.lundin@webrtc.org24779fe2014-03-14 12:40:05 +0000958 while (header && decoder_database_->IsComfortNoise(header->payloadType) &&
959 (end_timestamp >= header->timestamp ||
960 end_timestamp + decision_logic_->generated_noise_samples() >
961 header->timestamp)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000962 // Don't use this packet, discard it.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000963 if (packet_buffer_->DiscardNextPacket() != PacketBuffer::kOK) {
964 assert(false); // Must be ok by design.
965 }
966 // Check buffer again.
967 if (!new_codec_) {
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +0000968 packet_buffer_->DiscardOldPackets(end_timestamp, 5 * fs_hz_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000969 }
970 header = packet_buffer_->NextRtpHeader();
971 }
972 }
973
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000974 assert(expand_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000975 const int samples_left = static_cast<int>(sync_buffer_->FutureLength() -
976 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000977 if (last_mode_ == kModeAccelerateSuccess ||
978 last_mode_ == kModeAccelerateLowEnergy ||
979 last_mode_ == kModePreemptiveExpandSuccess ||
980 last_mode_ == kModePreemptiveExpandLowEnergy) {
981 // Subtract (samples_left + output_size_samples_) from sampleMemory.
Peter Kastingdce40cf2015-08-24 14:52:23 -0700982 decision_logic_->AddSampleMemory(
983 -(samples_left + rtc::checked_cast<int>(output_size_samples_)));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000984 }
985
986 // Check if it is time to play a DTMF event.
Peter Kastingb7e50542015-06-11 12:55:50 -0700987 if (dtmf_buffer_->GetEvent(
988 static_cast<uint32_t>(
989 end_timestamp + decision_logic_->generated_noise_samples()),
990 dtmf_event)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000991 *play_dtmf = true;
992 }
993
994 // Get instruction.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000995 assert(sync_buffer_.get());
996 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000997 *operation = decision_logic_->GetDecision(*sync_buffer_,
998 *expand_,
999 decoder_frame_length_,
1000 header,
1001 last_mode_,
1002 *play_dtmf,
1003 &reset_decoder_);
1004
1005 // Check if we already have enough samples in the |sync_buffer_|. If so,
1006 // change decision to normal, unless the decision was merge, accelerate, or
1007 // preemptive expand.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001008 if (samples_left >= rtc::checked_cast<int>(output_size_samples_) &&
1009 *operation != kMerge &&
1010 *operation != kAccelerate &&
1011 *operation != kFastAccelerate &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001012 *operation != kPreemptiveExpand) {
1013 *operation = kNormal;
1014 return 0;
1015 }
1016
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001017 decision_logic_->ExpandDecision(*operation);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001018
1019 // Check conditions for reset.
1020 if (new_codec_ || *operation == kUndefined) {
1021 // The only valid reason to get kUndefined is that new_codec_ is set.
1022 assert(new_codec_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001023 if (*play_dtmf && !header) {
1024 timestamp_ = dtmf_event->timestamp;
1025 } else {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001026 if (!header) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001027 LOG(LS_ERROR) << "Packet missing where it shouldn't.";
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001028 return -1;
1029 }
1030 timestamp_ = header->timestamp;
1031 if (*operation == kRfc3389CngNoPacket
1032#ifndef LEGACY_BITEXACT
1033 // Without this check, it can happen that a non-CNG packet is sent to
1034 // the CNG decoder as if it was a SID frame. This is clearly a bug,
1035 // but is kept for now to maintain bit-exactness with the test
1036 // vectors.
1037 && decoder_database_->IsComfortNoise(header->payloadType)
1038#endif
1039 ) {
1040 // Change decision to CNG packet, since we do have a CNG packet, but it
1041 // was considered too early to use. Now, use it anyway.
1042 *operation = kRfc3389Cng;
1043 } else if (*operation != kRfc3389Cng) {
1044 *operation = kNormal;
1045 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001046 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001047 // Adjust |sync_buffer_| timestamp before setting |end_timestamp| to the
1048 // new value.
1049 sync_buffer_->IncreaseEndTimestamp(timestamp_ - end_timestamp);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001050 end_timestamp = timestamp_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001051 new_codec_ = false;
1052 decision_logic_->SoftReset();
1053 buffer_level_filter_->Reset();
1054 delay_manager_->Reset();
1055 stats_.ResetMcu();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001056 }
1057
Peter Kastingdce40cf2015-08-24 14:52:23 -07001058 size_t required_samples = output_size_samples_;
1059 const size_t samples_10_ms = static_cast<size_t>(80 * fs_mult_);
1060 const size_t samples_20_ms = 2 * samples_10_ms;
1061 const size_t samples_30_ms = 3 * samples_10_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001062
1063 switch (*operation) {
1064 case kExpand: {
1065 timestamp_ = end_timestamp;
1066 return 0;
1067 }
1068 case kRfc3389CngNoPacket:
1069 case kCodecInternalCng: {
1070 return 0;
1071 }
1072 case kDtmf: {
1073 // TODO(hlundin): Write test for this.
1074 // Update timestamp.
1075 timestamp_ = end_timestamp;
1076 if (decision_logic_->generated_noise_samples() > 0 &&
1077 last_mode_ != kModeDtmf) {
1078 // Make a jump in timestamp due to the recently played comfort noise.
Peter Kastingb7e50542015-06-11 12:55:50 -07001079 uint32_t timestamp_jump =
1080 static_cast<uint32_t>(decision_logic_->generated_noise_samples());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001081 sync_buffer_->IncreaseEndTimestamp(timestamp_jump);
1082 timestamp_ += timestamp_jump;
1083 }
1084 decision_logic_->set_generated_noise_samples(0);
1085 return 0;
1086 }
Henrik Lundincf808d22015-05-27 14:33:29 +02001087 case kAccelerate:
1088 case kFastAccelerate: {
1089 // In order to do an accelerate we need at least 30 ms of audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001090 if (samples_left >= static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001091 // Already have enough data, so we do not need to extract any more.
1092 decision_logic_->set_sample_memory(samples_left);
1093 decision_logic_->set_prev_time_scale(true);
1094 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001095 } else if (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001096 decoder_frame_length_ >= samples_30_ms) {
1097 // Avoid decoding more data as it might overflow the playout buffer.
1098 *operation = kNormal;
1099 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001100 } else if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001101 decoder_frame_length_ < samples_30_ms) {
1102 // Build up decoded data by decoding at least 20 ms of audio data. Do
1103 // not perform accelerate yet, but wait until we only need to do one
1104 // decoding.
1105 required_samples = 2 * output_size_samples_;
1106 *operation = kNormal;
1107 }
1108 // If none of the above is true, we have one of two possible situations:
1109 // (1) 20 ms <= samples_left < 30 ms and decoder_frame_length_ < 30 ms; or
1110 // (2) samples_left < 10 ms and decoder_frame_length_ >= 30 ms.
1111 // In either case, we move on with the accelerate decision, and decode one
1112 // frame now.
1113 break;
1114 }
1115 case kPreemptiveExpand: {
1116 // In order to do a preemptive expand we need at least 30 ms of decoded
1117 // audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001118 if ((samples_left >= static_cast<int>(samples_30_ms)) ||
1119 (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001120 decoder_frame_length_ >= samples_30_ms)) {
1121 // Already have enough data, so we do not need to extract any more.
1122 // Or, avoid decoding more data as it might overflow the playout buffer.
1123 // Still try preemptive expand, though.
1124 decision_logic_->set_sample_memory(samples_left);
1125 decision_logic_->set_prev_time_scale(true);
1126 return 0;
1127 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07001128 if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001129 decoder_frame_length_ < samples_30_ms) {
1130 // Build up decoded data by decoding at least 20 ms of audio data.
1131 // Still try to perform preemptive expand.
1132 required_samples = 2 * output_size_samples_;
1133 }
1134 // Move on with the preemptive expand decision.
1135 break;
1136 }
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001137 case kMerge: {
1138 required_samples =
1139 std::max(merge_->RequiredFutureSamples(), required_samples);
1140 break;
1141 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001142 default: {
1143 // Do nothing.
1144 }
1145 }
1146
1147 // Get packets from buffer.
1148 int extracted_samples = 0;
1149 if (header &&
1150 *operation != kAlternativePlc &&
1151 *operation != kAlternativePlcIncreaseTimestamp &&
1152 *operation != kAudioRepetition &&
1153 *operation != kAudioRepetitionIncreaseTimestamp) {
1154 sync_buffer_->IncreaseEndTimestamp(header->timestamp - end_timestamp);
1155 if (decision_logic_->CngOff()) {
1156 // Adjustment of timestamp only corresponds to an actual packet loss
1157 // if comfort noise is not played. If comfort noise was just played,
1158 // this adjustment of timestamp is only done to get back in sync with the
1159 // stream timestamp; no loss to report.
1160 stats_.LostSamples(header->timestamp - end_timestamp);
1161 }
1162
1163 if (*operation != kRfc3389Cng) {
1164 // We are about to decode and use a non-CNG packet.
1165 decision_logic_->SetCngOff();
1166 }
1167 // Reset CNG timestamp as a new packet will be delivered.
1168 // (Also if this is a CNG packet, since playedOutTS is updated.)
1169 decision_logic_->set_generated_noise_samples(0);
1170
1171 extracted_samples = ExtractPackets(required_samples, packet_list);
1172 if (extracted_samples < 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001173 return kPacketBufferCorruption;
1174 }
1175 }
1176
Henrik Lundincf808d22015-05-27 14:33:29 +02001177 if (*operation == kAccelerate || *operation == kFastAccelerate ||
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001178 *operation == kPreemptiveExpand) {
1179 decision_logic_->set_sample_memory(samples_left + extracted_samples);
1180 decision_logic_->set_prev_time_scale(true);
1181 }
1182
Henrik Lundincf808d22015-05-27 14:33:29 +02001183 if (*operation == kAccelerate || *operation == kFastAccelerate) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001184 // Check that we have enough data (30ms) to do accelerate.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001185 if (extracted_samples + samples_left < static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001186 // TODO(hlundin): Write test for this.
1187 // Not enough, do normal operation instead.
1188 *operation = kNormal;
1189 }
1190 }
1191
1192 timestamp_ = end_timestamp;
1193 return 0;
1194}
1195
1196int NetEqImpl::Decode(PacketList* packet_list, Operations* operation,
1197 int* decoded_length,
1198 AudioDecoder::SpeechType* speech_type) {
1199 *speech_type = AudioDecoder::kSpeech;
minyuel6d92bf52015-09-23 15:20:39 +02001200
1201 // When packet_list is empty, we may be in kCodecInternalCng mode, and for
1202 // that we use current active decoder.
1203 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1204
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001205 if (!packet_list->empty()) {
1206 const Packet* packet = packet_list->front();
pkasting@chromium.org0e81fdf2015-02-02 23:54:03 +00001207 uint8_t payload_type = packet->header.payloadType;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001208 if (!decoder_database_->IsComfortNoise(payload_type)) {
1209 decoder = decoder_database_->GetDecoder(payload_type);
1210 assert(decoder);
1211 if (!decoder) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001212 LOG(LS_WARNING) << "Unknown payload type "
1213 << static_cast<int>(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001214 PacketBuffer::DeleteAllPackets(packet_list);
1215 return kDecoderNotFound;
1216 }
1217 bool decoder_changed;
1218 decoder_database_->SetActiveDecoder(payload_type, &decoder_changed);
1219 if (decoder_changed) {
1220 // We have a new decoder. Re-init some values.
1221 const DecoderDatabase::DecoderInfo* decoder_info = decoder_database_
1222 ->GetDecoderInfo(payload_type);
1223 assert(decoder_info);
1224 if (!decoder_info) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001225 LOG(LS_WARNING) << "Unknown payload type "
1226 << static_cast<int>(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001227 PacketBuffer::DeleteAllPackets(packet_list);
1228 return kDecoderNotFound;
1229 }
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001230 // If sampling rate or number of channels has changed, we need to make
1231 // a reset.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001232 if (decoder_info->fs_hz != fs_hz_ ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001233 decoder->Channels() != algorithm_buffer_->Channels()) {
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001234 // TODO(tlegrand): Add unittest to cover this event.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001235 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->Channels());
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001236 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001237 sync_buffer_->set_end_timestamp(timestamp_);
1238 playout_timestamp_ = timestamp_;
1239 }
1240 }
1241 }
1242
1243 if (reset_decoder_) {
1244 // TODO(hlundin): Write test for this.
Karl Wiberg43766482015-08-27 15:22:11 +02001245 if (decoder)
1246 decoder->Reset();
1247
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001248 // Reset comfort noise decoder.
1249 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02001250 if (cng_decoder)
1251 cng_decoder->Reset();
1252
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001253 reset_decoder_ = false;
1254 }
1255
1256#ifdef LEGACY_BITEXACT
1257 // Due to a bug in old SignalMCU, it could happen that CNG operation was
1258 // decided, but a speech packet was provided. The speech packet will be used
1259 // to update the comfort noise decoder, as if it was a SID frame, which is
1260 // clearly wrong.
1261 if (*operation == kRfc3389Cng) {
1262 return 0;
1263 }
1264#endif
1265
1266 *decoded_length = 0;
1267 // Update codec-internal PLC state.
1268 if ((*operation == kMerge) && decoder && decoder->HasDecodePlc()) {
1269 decoder->DecodePlc(1, &decoded_buffer_[*decoded_length]);
1270 }
1271
minyuel6d92bf52015-09-23 15:20:39 +02001272 int return_value;
1273 if (*operation == kCodecInternalCng) {
1274 RTC_DCHECK(packet_list->empty());
1275 return_value = DecodeCng(decoder, decoded_length, speech_type);
1276 } else {
1277 return_value = DecodeLoop(packet_list, *operation, decoder,
1278 decoded_length, speech_type);
1279 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001280
1281 if (*decoded_length < 0) {
1282 // Error returned from the decoder.
1283 *decoded_length = 0;
Peter Kastingb7e50542015-06-11 12:55:50 -07001284 sync_buffer_->IncreaseEndTimestamp(
1285 static_cast<uint32_t>(decoder_frame_length_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001286 int error_code = 0;
1287 if (decoder)
1288 error_code = decoder->ErrorCode();
1289 if (error_code != 0) {
1290 // Got some error code from the decoder.
1291 decoder_error_code_ = error_code;
1292 return_value = kDecoderErrorCode;
Henrik Lundind67a2192015-08-03 12:54:37 +02001293 LOG(LS_WARNING) << "Decoder returned error code: " << error_code;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001294 } else {
1295 // Decoder does not implement error codes. Return generic error.
1296 return_value = kOtherDecoderError;
Henrik Lundind67a2192015-08-03 12:54:37 +02001297 LOG(LS_WARNING) << "Decoder error (no error code)";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001298 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001299 *operation = kExpand; // Do expansion to get data instead.
1300 }
1301 if (*speech_type != AudioDecoder::kComfortNoise) {
1302 // Don't increment timestamp if codec returned CNG speech type
1303 // since in this case, the we will increment the CNGplayedTS counter.
1304 // Increase with number of samples per channel.
1305 assert(*decoded_length == 0 ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001306 (decoder && decoder->Channels() == sync_buffer_->Channels()));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001307 sync_buffer_->IncreaseEndTimestamp(
1308 *decoded_length / static_cast<int>(sync_buffer_->Channels()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001309 }
1310 return return_value;
1311}
1312
minyuel6d92bf52015-09-23 15:20:39 +02001313int NetEqImpl::DecodeCng(AudioDecoder* decoder, int* decoded_length,
1314 AudioDecoder::SpeechType* speech_type) {
1315 if (!decoder) {
1316 // This happens when active decoder is not defined.
1317 *decoded_length = -1;
1318 return 0;
1319 }
1320
1321 while (*decoded_length < rtc::checked_cast<int>(output_size_samples_)) {
1322 const int length = decoder->Decode(
1323 nullptr, 0, fs_hz_,
1324 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1325 &decoded_buffer_[*decoded_length], speech_type);
1326 if (length > 0) {
1327 *decoded_length += length;
minyuel6d92bf52015-09-23 15:20:39 +02001328 } else {
1329 // Error.
1330 LOG(LS_WARNING) << "Failed to decode CNG";
1331 *decoded_length = -1;
1332 break;
1333 }
1334 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1335 // Guard against overflow.
1336 LOG(LS_WARNING) << "Decoded too much CNG.";
1337 return kDecodedTooMuch;
1338 }
1339 }
1340 return 0;
1341}
1342
1343int NetEqImpl::DecodeLoop(PacketList* packet_list, const Operations& operation,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001344 AudioDecoder* decoder, int* decoded_length,
1345 AudioDecoder::SpeechType* speech_type) {
1346 Packet* packet = NULL;
1347 if (!packet_list->empty()) {
1348 packet = packet_list->front();
1349 }
minyuel6d92bf52015-09-23 15:20:39 +02001350
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001351 // Do decoding.
1352 while (packet &&
1353 !decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1354 assert(decoder); // At this point, we must have a decoder object.
1355 // The number of channels in the |sync_buffer_| should be the same as the
1356 // number decoder channels.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001357 assert(sync_buffer_->Channels() == decoder->Channels());
1358 assert(decoded_buffer_length_ >= kMaxFrameSize * decoder->Channels());
minyuel6d92bf52015-09-23 15:20:39 +02001359 assert(operation == kNormal || operation == kAccelerate ||
1360 operation == kFastAccelerate || operation == kMerge ||
1361 operation == kPreemptiveExpand);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001362 packet_list->pop_front();
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001363 size_t payload_length = packet->payload_length;
Peter Kasting36b7cc32015-06-11 19:57:18 -07001364 int decode_length;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +00001365 if (packet->sync_packet) {
1366 // Decode to silence with the same frame size as the last decode.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001367 memset(&decoded_buffer_[*decoded_length], 0,
1368 decoder_frame_length_ * decoder->Channels() *
1369 sizeof(decoded_buffer_[0]));
Peter Kastingdce40cf2015-08-24 14:52:23 -07001370 decode_length = rtc::checked_cast<int>(decoder_frame_length_);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +00001371 } else if (!packet->primary) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001372 // This is a redundant payload; call the special decoder method.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001373 decode_length = decoder->DecodeRedundant(
henrik.lundin@webrtc.org1eda4e32015-02-25 10:02:29 +00001374 packet->payload, packet->payload_length, fs_hz_,
minyue@webrtc.org7f7d7e32015-03-16 12:30:37 +00001375 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001376 &decoded_buffer_[*decoded_length], speech_type);
1377 } else {
henrik.lundin@webrtc.org1eda4e32015-02-25 10:02:29 +00001378 decode_length =
minyue@webrtc.org7f7d7e32015-03-16 12:30:37 +00001379 decoder->Decode(
1380 packet->payload, packet->payload_length, fs_hz_,
1381 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1382 &decoded_buffer_[*decoded_length], speech_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001383 }
1384
1385 delete[] packet->payload;
1386 delete packet;
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001387 packet = NULL;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001388 if (decode_length > 0) {
1389 *decoded_length += decode_length;
1390 // Update |decoder_frame_length_| with number of samples per channel.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001391 decoder_frame_length_ =
Peter Kastingdce40cf2015-08-24 14:52:23 -07001392 static_cast<size_t>(decode_length) / decoder->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001393 } else if (decode_length < 0) {
1394 // Error.
Henrik Lundind67a2192015-08-03 12:54:37 +02001395 LOG(LS_WARNING) << "Decode " << decode_length << " " << payload_length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001396 *decoded_length = -1;
1397 PacketBuffer::DeleteAllPackets(packet_list);
1398 break;
1399 }
1400 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1401 // Guard against overflow.
Henrik Lundind67a2192015-08-03 12:54:37 +02001402 LOG(LS_WARNING) << "Decoded too much.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001403 PacketBuffer::DeleteAllPackets(packet_list);
1404 return kDecodedTooMuch;
1405 }
1406 if (!packet_list->empty()) {
1407 packet = packet_list->front();
1408 } else {
1409 packet = NULL;
1410 }
1411 } // End of decode loop.
1412
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001413 // If the list is not empty at this point, either a decoding error terminated
1414 // the while-loop, or list must hold exactly one CNG packet.
1415 assert(packet_list->empty() || *decoded_length < 0 ||
1416 (packet_list->size() == 1 && packet &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001417 decoder_database_->IsComfortNoise(packet->header.payloadType)));
1418 return 0;
1419}
1420
1421void NetEqImpl::DoNormal(const int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001422 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001423 assert(normal_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001424 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001425 normal_->Process(decoded_buffer, decoded_length, last_mode_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001426 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001427 if (decoded_length != 0) {
1428 last_mode_ = kModeNormal;
1429 }
1430
1431 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1432 if ((speech_type == AudioDecoder::kComfortNoise)
1433 || ((last_mode_ == kModeCodecInternalCng)
1434 && (decoded_length == 0))) {
1435 // TODO(hlundin): Remove second part of || statement above.
1436 last_mode_ = kModeCodecInternalCng;
1437 }
1438
1439 if (!play_dtmf) {
1440 dtmf_tone_generator_->Reset();
1441 }
1442}
1443
1444void NetEqImpl::DoMerge(int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001445 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001446 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001447 assert(merge_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001448 size_t new_length = merge_->Process(decoded_buffer, decoded_length,
1449 mute_factor_array_.get(),
1450 algorithm_buffer_.get());
1451 size_t expand_length_correction = new_length -
1452 decoded_length / algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001453
1454 // Update in-call and post-call statistics.
1455 if (expand_->MuteFactor(0) == 0) {
1456 // Expand generates only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001457 stats_.ExpandedNoiseSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001458 } else {
1459 // Expansion generates more than only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001460 stats_.ExpandedVoiceSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001461 }
1462
1463 last_mode_ = kModeMerge;
1464 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1465 if (speech_type == AudioDecoder::kComfortNoise) {
1466 last_mode_ = kModeCodecInternalCng;
1467 }
1468 expand_->Reset();
1469 if (!play_dtmf) {
1470 dtmf_tone_generator_->Reset();
1471 }
1472}
1473
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001474int NetEqImpl::DoExpand(bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001475 while ((sync_buffer_->FutureLength() - expand_->overlap_length()) <
Peter Kastingdce40cf2015-08-24 14:52:23 -07001476 output_size_samples_) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001477 algorithm_buffer_->Clear();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001478 int return_value = expand_->Process(algorithm_buffer_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001479 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001480
1481 // Update in-call and post-call statistics.
1482 if (expand_->MuteFactor(0) == 0) {
1483 // Expand operation generates only noise.
1484 stats_.ExpandedNoiseSamples(length);
1485 } else {
1486 // Expand operation generates more than only noise.
1487 stats_.ExpandedVoiceSamples(length);
1488 }
1489
1490 last_mode_ = kModeExpand;
1491
1492 if (return_value < 0) {
1493 return return_value;
1494 }
1495
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001496 sync_buffer_->PushBack(*algorithm_buffer_);
1497 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001498 }
1499 if (!play_dtmf) {
1500 dtmf_tone_generator_->Reset();
1501 }
1502 return 0;
1503}
1504
Henrik Lundincf808d22015-05-27 14:33:29 +02001505int NetEqImpl::DoAccelerate(int16_t* decoded_buffer,
1506 size_t decoded_length,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001507 AudioDecoder::SpeechType speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +02001508 bool play_dtmf,
1509 bool fast_accelerate) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001510 const size_t required_samples =
1511 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001512 size_t borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001513 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001514 size_t decoded_length_per_channel = decoded_length / num_channels;
1515 if (decoded_length_per_channel < required_samples) {
1516 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001517 borrowed_samples_per_channel = static_cast<int>(required_samples -
1518 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001519 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1520 decoded_buffer,
1521 sizeof(int16_t) * decoded_length);
1522 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1523 decoded_buffer);
1524 decoded_length = required_samples * num_channels;
1525 }
1526
Peter Kastingdce40cf2015-08-24 14:52:23 -07001527 size_t samples_removed;
Henrik Lundincf808d22015-05-27 14:33:29 +02001528 Accelerate::ReturnCodes return_code =
1529 accelerate_->Process(decoded_buffer, decoded_length, fast_accelerate,
1530 algorithm_buffer_.get(), &samples_removed);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001531 stats_.AcceleratedSamples(samples_removed);
1532 switch (return_code) {
1533 case Accelerate::kSuccess:
1534 last_mode_ = kModeAccelerateSuccess;
1535 break;
1536 case Accelerate::kSuccessLowEnergy:
1537 last_mode_ = kModeAccelerateLowEnergy;
1538 break;
1539 case Accelerate::kNoStretch:
1540 last_mode_ = kModeAccelerateFail;
1541 break;
1542 case Accelerate::kError:
1543 // TODO(hlundin): Map to kModeError instead?
1544 last_mode_ = kModeAccelerateFail;
1545 return kAccelerateError;
1546 }
1547
1548 if (borrowed_samples_per_channel > 0) {
1549 // Copy borrowed samples back to the |sync_buffer_|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001550 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001551 if (length < borrowed_samples_per_channel) {
1552 // This destroys the beginning of the buffer, but will not cause any
1553 // problems.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001554 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001555 sync_buffer_->Size() -
1556 borrowed_samples_per_channel);
1557 sync_buffer_->PushFrontZeros(borrowed_samples_per_channel - length);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001558 algorithm_buffer_->PopFront(length);
1559 assert(algorithm_buffer_->Empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001560 } else {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001561 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001562 borrowed_samples_per_channel,
1563 sync_buffer_->Size() -
1564 borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001565 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001566 }
1567 }
1568
1569 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1570 if (speech_type == AudioDecoder::kComfortNoise) {
1571 last_mode_ = kModeCodecInternalCng;
1572 }
1573 if (!play_dtmf) {
1574 dtmf_tone_generator_->Reset();
1575 }
1576 expand_->Reset();
1577 return 0;
1578}
1579
1580int NetEqImpl::DoPreemptiveExpand(int16_t* decoded_buffer,
1581 size_t decoded_length,
1582 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001583 bool play_dtmf) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001584 const size_t required_samples =
1585 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001586 size_t num_channels = algorithm_buffer_->Channels();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001587 size_t borrowed_samples_per_channel = 0;
1588 size_t old_borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001589 size_t decoded_length_per_channel = decoded_length / num_channels;
1590 if (decoded_length_per_channel < required_samples) {
1591 // Must move data from the |sync_buffer_| in order to get 30 ms.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001592 borrowed_samples_per_channel =
1593 required_samples - decoded_length_per_channel;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001594 // Calculate how many of these were already played out.
Peter Kastingf045e4d2015-06-10 21:15:38 -07001595 old_borrowed_samples_per_channel =
Peter Kastingdce40cf2015-08-24 14:52:23 -07001596 (borrowed_samples_per_channel > sync_buffer_->FutureLength()) ?
1597 (borrowed_samples_per_channel - sync_buffer_->FutureLength()) : 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001598 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1599 decoded_buffer,
1600 sizeof(int16_t) * decoded_length);
1601 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1602 decoded_buffer);
1603 decoded_length = required_samples * num_channels;
1604 }
1605
Peter Kastingdce40cf2015-08-24 14:52:23 -07001606 size_t samples_added;
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001607 PreemptiveExpand::ReturnCodes return_code = preemptive_expand_->Process(
Peter Kastingdce40cf2015-08-24 14:52:23 -07001608 decoded_buffer, decoded_length,
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001609 old_borrowed_samples_per_channel,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001610 algorithm_buffer_.get(), &samples_added);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001611 stats_.PreemptiveExpandedSamples(samples_added);
1612 switch (return_code) {
1613 case PreemptiveExpand::kSuccess:
1614 last_mode_ = kModePreemptiveExpandSuccess;
1615 break;
1616 case PreemptiveExpand::kSuccessLowEnergy:
1617 last_mode_ = kModePreemptiveExpandLowEnergy;
1618 break;
1619 case PreemptiveExpand::kNoStretch:
1620 last_mode_ = kModePreemptiveExpandFail;
1621 break;
1622 case PreemptiveExpand::kError:
1623 // TODO(hlundin): Map to kModeError instead?
1624 last_mode_ = kModePreemptiveExpandFail;
1625 return kPreemptiveExpandError;
1626 }
1627
1628 if (borrowed_samples_per_channel > 0) {
1629 // Copy borrowed samples back to the |sync_buffer_|.
1630 sync_buffer_->ReplaceAtIndex(
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001631 *algorithm_buffer_, borrowed_samples_per_channel,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001632 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001633 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001634 }
1635
1636 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1637 if (speech_type == AudioDecoder::kComfortNoise) {
1638 last_mode_ = kModeCodecInternalCng;
1639 }
1640 if (!play_dtmf) {
1641 dtmf_tone_generator_->Reset();
1642 }
1643 expand_->Reset();
1644 return 0;
1645}
1646
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001647int NetEqImpl::DoRfc3389Cng(PacketList* packet_list, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001648 if (!packet_list->empty()) {
1649 // Must have exactly one SID frame at this point.
1650 assert(packet_list->size() == 1);
1651 Packet* packet = packet_list->front();
1652 packet_list->pop_front();
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001653 if (!decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1654#ifdef LEGACY_BITEXACT
1655 // This can happen due to a bug in GetDecision. Change the payload type
1656 // to a CNG type, and move on. Note that this means that we are in fact
1657 // sending a non-CNG payload to the comfort noise decoder for decoding.
1658 // Clearly wrong, but will maintain bit-exactness with legacy.
1659 if (fs_hz_ == 8000) {
1660 packet->header.payloadType =
kwibergee1879c2015-10-29 06:20:28 -07001661 decoder_database_->GetRtpPayloadType(NetEqDecoder::kDecoderCNGnb);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001662 } else if (fs_hz_ == 16000) {
1663 packet->header.payloadType =
kwibergee1879c2015-10-29 06:20:28 -07001664 decoder_database_->GetRtpPayloadType(NetEqDecoder::kDecoderCNGwb);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001665 } else if (fs_hz_ == 32000) {
kwibergee1879c2015-10-29 06:20:28 -07001666 packet->header.payloadType = decoder_database_->GetRtpPayloadType(
1667 NetEqDecoder::kDecoderCNGswb32kHz);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001668 } else if (fs_hz_ == 48000) {
kwibergee1879c2015-10-29 06:20:28 -07001669 packet->header.payloadType = decoder_database_->GetRtpPayloadType(
1670 NetEqDecoder::kDecoderCNGswb48kHz);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001671 }
1672 assert(decoder_database_->IsComfortNoise(packet->header.payloadType));
1673#else
1674 LOG(LS_ERROR) << "Trying to decode non-CNG payload as CNG.";
1675 return kOtherError;
1676#endif
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001677 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001678 // UpdateParameters() deletes |packet|.
1679 if (comfort_noise_->UpdateParameters(packet) ==
1680 ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001681 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001682 return -comfort_noise_->internal_error_code();
1683 }
1684 }
1685 int cn_return = comfort_noise_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001686 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001687 expand_->Reset();
1688 last_mode_ = kModeRfc3389Cng;
1689 if (!play_dtmf) {
1690 dtmf_tone_generator_->Reset();
1691 }
1692 if (cn_return == ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001693 decoder_error_code_ = comfort_noise_->internal_error_code();
1694 return kComfortNoiseErrorCode;
1695 } else if (cn_return == ComfortNoise::kUnknownPayloadType) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001696 return kUnknownRtpPayloadType;
1697 }
1698 return 0;
1699}
1700
minyuel6d92bf52015-09-23 15:20:39 +02001701void NetEqImpl::DoCodecInternalCng(const int16_t* decoded_buffer,
1702 size_t decoded_length) {
1703 RTC_DCHECK(normal_.get());
1704 RTC_DCHECK(mute_factor_array_.get());
1705 normal_->Process(decoded_buffer, decoded_length, last_mode_,
1706 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001707 last_mode_ = kModeCodecInternalCng;
1708 expand_->Reset();
1709}
1710
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001711int NetEqImpl::DoDtmf(const DtmfEvent& dtmf_event, bool* play_dtmf) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001712 // This block of the code and the block further down, handling |dtmf_switch|
1713 // are commented out. Otherwise playing out-of-band DTMF would fail in VoE
1714 // test, DtmfTest.ManualSuccessfullySendsOutOfBandTelephoneEvents. This is
1715 // equivalent to |dtmf_switch| always be false.
1716 //
1717 // See http://webrtc-codereview.appspot.com/1195004/ for discussion
1718 // On this issue. This change might cause some glitches at the point of
1719 // switch from audio to DTMF. Issue 1545 is filed to track this.
1720 //
1721 // bool dtmf_switch = false;
1722 // if ((last_mode_ != kModeDtmf) && dtmf_tone_generator_->initialized()) {
1723 // // Special case; see below.
1724 // // We must catch this before calling Generate, since |initialized| is
1725 // // modified in that call.
1726 // dtmf_switch = true;
1727 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001728
1729 int dtmf_return_value = 0;
1730 if (!dtmf_tone_generator_->initialized()) {
1731 // Initialize if not already done.
1732 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1733 dtmf_event.volume);
1734 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001735
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001736 if (dtmf_return_value == 0) {
1737 // Generate DTMF signal.
1738 dtmf_return_value = dtmf_tone_generator_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001739 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001740 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001741
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001742 if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001743 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001744 return dtmf_return_value;
1745 }
1746
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001747 // if (dtmf_switch) {
1748 // // This is the special case where the previous operation was DTMF
1749 // // overdub, but the current instruction is "regular" DTMF. We must make
1750 // // sure that the DTMF does not have any discontinuities. The first DTMF
1751 // // sample that we generate now must be played out immediately, therefore
1752 // // it must be copied to the speech buffer.
1753 // // TODO(hlundin): This code seems incorrect. (Legacy.) Write test and
1754 // // verify correct operation.
1755 // assert(false);
1756 // // Must generate enough data to replace all of the |sync_buffer_|
1757 // // "future".
1758 // int required_length = sync_buffer_->FutureLength();
1759 // assert(dtmf_tone_generator_->initialized());
1760 // dtmf_return_value = dtmf_tone_generator_->Generate(required_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001761 // algorithm_buffer_);
1762 // assert((size_t) required_length == algorithm_buffer_->Size());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001763 // if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001764 // algorithm_buffer_->Zeros(output_size_samples_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001765 // return dtmf_return_value;
1766 // }
1767 //
1768 // // Overwrite the "future" part of the speech buffer with the new DTMF
1769 // // data.
1770 // // TODO(hlundin): It seems that this overwriting has gone lost.
1771 // // Not adapted for multi-channel yet.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001772 // assert(algorithm_buffer_->Channels() == 1);
1773 // if (algorithm_buffer_->Channels() != 1) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001774 // LOG(LS_WARNING) << "DTMF not supported for more than one channel";
1775 // return kStereoNotSupported;
1776 // }
1777 // // Shuffle the remaining data to the beginning of algorithm buffer.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001778 // algorithm_buffer_->PopFront(sync_buffer_->FutureLength());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001779 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001780
Peter Kastingb7e50542015-06-11 12:55:50 -07001781 sync_buffer_->IncreaseEndTimestamp(
1782 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001783 expand_->Reset();
1784 last_mode_ = kModeDtmf;
1785
1786 // Set to false because the DTMF is already in the algorithm buffer.
1787 *play_dtmf = false;
1788 return 0;
1789}
1790
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001791void NetEqImpl::DoAlternativePlc(bool increase_timestamp) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001792 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001793 size_t length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001794 if (decoder && decoder->HasDecodePlc()) {
1795 // Use the decoder's packet-loss concealment.
1796 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1797 int16_t decoded_buffer[kMaxFrameSize];
1798 length = decoder->DecodePlc(1, decoded_buffer);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001799 if (length > 0)
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001800 algorithm_buffer_->PushBackInterleaved(decoded_buffer, length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001801 } else {
1802 // Do simple zero-stuffing.
1803 length = output_size_samples_;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001804 algorithm_buffer_->Zeros(length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001805 // By not advancing the timestamp, NetEq inserts samples.
1806 stats_.AddZeros(length);
1807 }
1808 if (increase_timestamp) {
Peter Kastingb7e50542015-06-11 12:55:50 -07001809 sync_buffer_->IncreaseEndTimestamp(static_cast<uint32_t>(length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001810 }
1811 expand_->Reset();
1812}
1813
1814int NetEqImpl::DtmfOverdub(const DtmfEvent& dtmf_event, size_t num_channels,
1815 int16_t* output) const {
1816 size_t out_index = 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001817 size_t overdub_length = output_size_samples_; // Default value.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001818
1819 if (sync_buffer_->dtmf_index() > sync_buffer_->next_index()) {
1820 // Special operation for transition from "DTMF only" to "DTMF overdub".
1821 out_index = std::min(
1822 sync_buffer_->dtmf_index() - sync_buffer_->next_index(),
Peter Kastingdce40cf2015-08-24 14:52:23 -07001823 output_size_samples_);
1824 overdub_length = output_size_samples_ - out_index;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001825 }
1826
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001827 AudioMultiVector dtmf_output(num_channels);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001828 int dtmf_return_value = 0;
1829 if (!dtmf_tone_generator_->initialized()) {
1830 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1831 dtmf_event.volume);
1832 }
1833 if (dtmf_return_value == 0) {
1834 dtmf_return_value = dtmf_tone_generator_->Generate(overdub_length,
1835 &dtmf_output);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001836 assert(overdub_length == dtmf_output.Size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001837 }
1838 dtmf_output.ReadInterleaved(overdub_length, &output[out_index]);
1839 return dtmf_return_value < 0 ? dtmf_return_value : 0;
1840}
1841
Peter Kastingdce40cf2015-08-24 14:52:23 -07001842int NetEqImpl::ExtractPackets(size_t required_samples,
1843 PacketList* packet_list) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001844 bool first_packet = true;
1845 uint8_t prev_payload_type = 0;
1846 uint32_t prev_timestamp = 0;
1847 uint16_t prev_sequence_number = 0;
1848 bool next_packet_available = false;
1849
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001850 const RTPHeader* header = packet_buffer_->NextRtpHeader();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001851 assert(header);
1852 if (!header) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001853 LOG(LS_ERROR) << "Packet buffer unexpectedly empty.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001854 return -1;
1855 }
turaj@webrtc.org7df97062013-08-02 18:07:13 +00001856 uint32_t first_timestamp = header->timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001857 int extracted_samples = 0;
1858
1859 // Packet extraction loop.
1860 do {
1861 timestamp_ = header->timestamp;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001862 size_t discard_count = 0;
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001863 Packet* packet = packet_buffer_->GetNextPacket(&discard_count);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001864 // |header| may be invalid after the |packet_buffer_| operation.
1865 header = NULL;
1866 if (!packet) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001867 LOG(LS_ERROR) << "Should always be able to extract a packet here";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001868 assert(false); // Should always be able to extract a packet here.
1869 return -1;
1870 }
1871 stats_.PacketsDiscarded(discard_count);
1872 // Store waiting time in ms; packets->waiting_time is in "output blocks".
1873 stats_.StoreWaitingTime(packet->waiting_time * kOutputSizeMs);
1874 assert(packet->payload_length > 0);
1875 packet_list->push_back(packet); // Store packet in list.
1876
1877 if (first_packet) {
1878 first_packet = false;
henrik.lundin48ed9302015-10-29 05:36:24 -07001879 if (nack_enabled_) {
1880 RTC_DCHECK(nack_);
1881 // TODO(henrik.lundin): Should we update this for all decoded packets?
1882 nack_->UpdateLastDecodedPacket(packet->header.sequenceNumber,
1883 packet->header.timestamp);
1884 }
1885 prev_sequence_number = packet->header.sequenceNumber;
1886 prev_timestamp = packet->header.timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001887 prev_payload_type = packet->header.payloadType;
1888 }
1889
1890 // Store number of extracted samples.
1891 int packet_duration = 0;
1892 AudioDecoder* decoder = decoder_database_->GetDecoder(
1893 packet->header.payloadType);
1894 if (decoder) {
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001895 if (packet->sync_packet) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001896 packet_duration = rtc::checked_cast<int>(decoder_frame_length_);
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001897 } else {
minyue@webrtc.org2c1bcf22015-02-17 10:17:09 +00001898 if (packet->primary) {
1899 packet_duration = decoder->PacketDuration(packet->payload,
1900 packet->payload_length);
1901 } else {
1902 packet_duration = decoder->
1903 PacketDurationRedundant(packet->payload, packet->payload_length);
1904 stats_.SecondaryDecodedSamples(packet_duration);
1905 }
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001906 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001907 } else {
Henrik Lundind67a2192015-08-03 12:54:37 +02001908 LOG(LS_WARNING) << "Unknown payload type "
1909 << static_cast<int>(packet->header.payloadType);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001910 assert(false);
1911 }
1912 if (packet_duration <= 0) {
1913 // Decoder did not return a packet duration. Assume that the packet
1914 // contains the same number of samples as the previous one.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001915 packet_duration = rtc::checked_cast<int>(decoder_frame_length_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001916 }
1917 extracted_samples = packet->header.timestamp - first_timestamp +
1918 packet_duration;
1919
1920 // Check what packet is available next.
1921 header = packet_buffer_->NextRtpHeader();
1922 next_packet_available = false;
1923 if (header && prev_payload_type == header->payloadType) {
1924 int16_t seq_no_diff = header->sequenceNumber - prev_sequence_number;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001925 size_t ts_diff = header->timestamp - prev_timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001926 if (seq_no_diff == 1 ||
1927 (seq_no_diff == 0 && ts_diff == decoder_frame_length_)) {
1928 // The next sequence number is available, or the next part of a packet
1929 // that was split into pieces upon insertion.
1930 next_packet_available = true;
1931 }
1932 prev_sequence_number = header->sequenceNumber;
1933 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07001934 } while (extracted_samples < rtc::checked_cast<int>(required_samples) &&
1935 next_packet_available);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001936
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00001937 if (extracted_samples > 0) {
1938 // Delete old packets only when we are going to decode something. Otherwise,
1939 // we could end up in the situation where we never decode anything, since
1940 // all incoming packets are considered too old but the buffer will also
1941 // never be flooded and flushed.
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001942 packet_buffer_->DiscardAllOldPackets(timestamp_);
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00001943 }
1944
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001945 return extracted_samples;
1946}
1947
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001948void NetEqImpl::UpdatePlcComponents(int fs_hz, size_t channels) {
1949 // Delete objects and create new ones.
1950 expand_.reset(expand_factory_->Create(background_noise_.get(),
1951 sync_buffer_.get(), &random_vector_,
Henrik Lundinbef77e22015-08-18 14:58:09 +02001952 &stats_, fs_hz, channels));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001953 merge_.reset(new Merge(fs_hz, channels, expand_.get(), sync_buffer_.get()));
1954}
1955
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001956void NetEqImpl::SetSampleRateAndChannels(int fs_hz, size_t channels) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001957 LOG(LS_VERBOSE) << "SetSampleRateAndChannels " << fs_hz << " " << channels;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001958 // TODO(hlundin): Change to an enumerator and skip assert.
1959 assert(fs_hz == 8000 || fs_hz == 16000 || fs_hz == 32000 || fs_hz == 48000);
1960 assert(channels > 0);
1961
1962 fs_hz_ = fs_hz;
1963 fs_mult_ = fs_hz / 8000;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001964 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001965 decoder_frame_length_ = 3 * output_size_samples_; // Initialize to 30ms.
1966
1967 last_mode_ = kModeNormal;
1968
1969 // Create a new array of mute factors and set all to 1.
1970 mute_factor_array_.reset(new int16_t[channels]);
1971 for (size_t i = 0; i < channels; ++i) {
1972 mute_factor_array_[i] = 16384; // 1.0 in Q14.
1973 }
1974
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001975 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02001976 if (cng_decoder)
1977 cng_decoder->Reset();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001978
1979 // Reinit post-decode VAD with new sample rate.
1980 assert(vad_.get()); // Cannot be NULL here.
1981 vad_->Init();
1982
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001983 // Delete algorithm buffer and create a new one.
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001984 algorithm_buffer_.reset(new AudioMultiVector(channels));
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001985
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001986 // Delete sync buffer and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001987 sync_buffer_.reset(new SyncBuffer(channels, kSyncBufferSize * fs_mult_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001988
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00001989 // Delete BackgroundNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001990 background_noise_.reset(new BackgroundNoise(channels));
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00001991 background_noise_->set_mode(background_noise_mode_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001992
1993 // Reset random vector.
1994 random_vector_.Reset();
1995
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001996 UpdatePlcComponents(fs_hz, channels);
1997
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001998 // Move index so that we create a small set of future samples (all 0).
1999 sync_buffer_->set_next_index(sync_buffer_->next_index() -
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002000 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002001
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002002 normal_.reset(new Normal(fs_hz, decoder_database_.get(), *background_noise_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002003 expand_.get()));
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +00002004 accelerate_.reset(
2005 accelerate_factory_->Create(fs_hz, channels, *background_noise_));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002006 preemptive_expand_.reset(preemptive_expand_factory_->Create(
Peter Kastingdce40cf2015-08-24 14:52:23 -07002007 fs_hz, channels, *background_noise_, expand_->overlap_length()));
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002008
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002009 // Delete ComfortNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002010 comfort_noise_.reset(new ComfortNoise(fs_hz, decoder_database_.get(),
2011 sync_buffer_.get()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002012
2013 // Verify that |decoded_buffer_| is long enough.
2014 if (decoded_buffer_length_ < kMaxFrameSize * channels) {
2015 // Reallocate to larger size.
2016 decoded_buffer_length_ = kMaxFrameSize * channels;
2017 decoded_buffer_.reset(new int16_t[decoded_buffer_length_]);
2018 }
2019
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002020 // Create DecisionLogic if it is not created yet, then communicate new sample
2021 // rate and output size to DecisionLogic object.
2022 if (!decision_logic_.get()) {
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002023 CreateDecisionLogic();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002024 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002025 decision_logic_->SetSampleRate(fs_hz_, output_size_samples_);
2026}
2027
2028NetEqOutputType NetEqImpl::LastOutputType() {
2029 assert(vad_.get());
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002030 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002031 if (last_mode_ == kModeCodecInternalCng || last_mode_ == kModeRfc3389Cng) {
2032 return kOutputCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002033 } else if (last_mode_ == kModeExpand && expand_->MuteFactor(0) == 0) {
2034 // Expand mode has faded down to background noise only (very long expand).
2035 return kOutputPLCtoCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002036 } else if (last_mode_ == kModeExpand) {
2037 return kOutputPLC;
wu@webrtc.org24301a62013-12-13 19:17:43 +00002038 } else if (vad_->running() && !vad_->active_speech()) {
2039 return kOutputVADPassive;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002040 } else {
2041 return kOutputNormal;
2042 }
2043}
2044
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002045void NetEqImpl::CreateDecisionLogic() {
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002046 decision_logic_.reset(DecisionLogic::Create(fs_hz_, output_size_samples_,
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002047 playout_mode_,
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002048 decoder_database_.get(),
2049 *packet_buffer_.get(),
2050 delay_manager_.get(),
2051 buffer_level_filter_.get()));
2052}
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002053} // namespace webrtc