blob: ed0c83f08b4826f379dbb7b3c1b999781e4121a2 [file] [log] [blame]
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001/*
2 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000011#include "webrtc/modules/audio_coding/neteq/neteq_impl.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000012
13#include <assert.h>
14#include <memory.h> // memset
15
16#include <algorithm>
17
henrik.lundin9c3efd02015-08-27 13:12:22 -070018#include "webrtc/base/checks.h"
Henrik Lundind67a2192015-08-03 12:54:37 +020019#include "webrtc/base/logging.h"
Peter Kastingdce40cf2015-08-24 14:52:23 -070020#include "webrtc/base/safe_conversions.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000021#include "webrtc/common_audio/signal_processing/include/signal_processing_library.h"
kwiberg@webrtc.orge04a93b2014-12-09 10:12:53 +000022#include "webrtc/modules/audio_coding/codecs/audio_decoder.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000023#include "webrtc/modules/audio_coding/neteq/accelerate.h"
24#include "webrtc/modules/audio_coding/neteq/background_noise.h"
25#include "webrtc/modules/audio_coding/neteq/buffer_level_filter.h"
26#include "webrtc/modules/audio_coding/neteq/comfort_noise.h"
27#include "webrtc/modules/audio_coding/neteq/decision_logic.h"
28#include "webrtc/modules/audio_coding/neteq/decoder_database.h"
29#include "webrtc/modules/audio_coding/neteq/defines.h"
30#include "webrtc/modules/audio_coding/neteq/delay_manager.h"
31#include "webrtc/modules/audio_coding/neteq/delay_peak_detector.h"
32#include "webrtc/modules/audio_coding/neteq/dtmf_buffer.h"
33#include "webrtc/modules/audio_coding/neteq/dtmf_tone_generator.h"
34#include "webrtc/modules/audio_coding/neteq/expand.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000035#include "webrtc/modules/audio_coding/neteq/merge.h"
henrik.lundin48ed9302015-10-29 05:36:24 -070036#include "webrtc/modules/audio_coding/neteq/nack.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000037#include "webrtc/modules/audio_coding/neteq/normal.h"
38#include "webrtc/modules/audio_coding/neteq/packet_buffer.h"
39#include "webrtc/modules/audio_coding/neteq/packet.h"
40#include "webrtc/modules/audio_coding/neteq/payload_splitter.h"
41#include "webrtc/modules/audio_coding/neteq/post_decode_vad.h"
42#include "webrtc/modules/audio_coding/neteq/preemptive_expand.h"
43#include "webrtc/modules/audio_coding/neteq/sync_buffer.h"
44#include "webrtc/modules/audio_coding/neteq/timestamp_scaler.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010045#include "webrtc/modules/include/module_common_types.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010046#include "webrtc/system_wrappers/include/critical_section_wrapper.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000047
48// Modify the code to obtain backwards bit-exactness. Once bit-exactness is no
49// longer required, this #define should be removed (and the code that it
50// enables).
51#define LEGACY_BITEXACT
52
53namespace webrtc {
54
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +000055NetEqImpl::NetEqImpl(const NetEq::Config& config,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000056 BufferLevelFilter* buffer_level_filter,
57 DecoderDatabase* decoder_database,
58 DelayManager* delay_manager,
59 DelayPeakDetector* delay_peak_detector,
60 DtmfBuffer* dtmf_buffer,
61 DtmfToneGenerator* dtmf_tone_generator,
62 PacketBuffer* packet_buffer,
63 PayloadSplitter* payload_splitter,
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +000064 TimestampScaler* timestamp_scaler,
65 AccelerateFactory* accelerate_factory,
66 ExpandFactory* expand_factory,
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +000067 PreemptiveExpandFactory* preemptive_expand_factory,
68 bool create_components)
henrik.lundin@webrtc.org2f816bb2014-06-05 10:37:13 +000069 : crit_sect_(CriticalSectionWrapper::CreateCriticalSection()),
70 buffer_level_filter_(buffer_level_filter),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000071 decoder_database_(decoder_database),
72 delay_manager_(delay_manager),
73 delay_peak_detector_(delay_peak_detector),
74 dtmf_buffer_(dtmf_buffer),
75 dtmf_tone_generator_(dtmf_tone_generator),
76 packet_buffer_(packet_buffer),
77 payload_splitter_(payload_splitter),
78 timestamp_scaler_(timestamp_scaler),
79 vad_(new PostDecodeVad()),
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +000080 expand_factory_(expand_factory),
81 accelerate_factory_(accelerate_factory),
82 preemptive_expand_factory_(preemptive_expand_factory),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000083 last_mode_(kModeNormal),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000084 decoded_buffer_length_(kMaxFrameSize),
85 decoded_buffer_(new int16_t[decoded_buffer_length_]),
86 playout_timestamp_(0),
87 new_codec_(false),
88 timestamp_(0),
89 reset_decoder_(false),
henrik.lundin48ed9302015-10-29 05:36:24 -070090 current_rtp_payload_type_(0xFF), // Invalid RTP payload type.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000091 current_cng_rtp_payload_type_(0xFF), // Invalid RTP payload type.
92 ssrc_(0),
93 first_packet_(true),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000094 error_code_(0),
95 decoder_error_code_(0),
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +000096 background_noise_mode_(config.background_noise_mode),
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +000097 playout_mode_(config.playout_mode),
Henrik Lundincf808d22015-05-27 14:33:29 +020098 enable_fast_accelerate_(config.enable_fast_accelerate),
henrik.lundin48ed9302015-10-29 05:36:24 -070099 nack_enabled_(false) {
Henrik Lundin905495c2015-05-25 16:58:41 +0200100 LOG(LS_INFO) << "NetEq config: " << config.ToString();
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +0000101 int fs = config.sample_rate_hz;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000102 if (fs != 8000 && fs != 16000 && fs != 32000 && fs != 48000) {
103 LOG(LS_ERROR) << "Sample rate " << fs << " Hz not supported. " <<
104 "Changing to 8000 Hz.";
105 fs = 8000;
106 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000107 fs_hz_ = fs;
108 fs_mult_ = fs / 8000;
henrik.lundind89814b2015-11-23 06:49:25 -0800109 last_output_sample_rate_hz_ = fs;
Peter Kastingdce40cf2015-08-24 14:52:23 -0700110 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000111 decoder_frame_length_ = 3 * output_size_samples_;
112 WebRtcSpl_Init();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000113 if (create_components) {
114 SetSampleRateAndChannels(fs, 1); // Default is 1 channel.
115 }
henrik.lundin9bc26672015-11-02 03:25:57 -0800116 RTC_DCHECK(!vad_->enabled());
117 if (config.enable_post_decode_vad) {
118 vad_->Enable();
119 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000120}
121
Henrik Lundind67a2192015-08-03 12:54:37 +0200122NetEqImpl::~NetEqImpl() = default;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000123
124int NetEqImpl::InsertPacket(const WebRtcRTPHeader& rtp_header,
kwibergee2bac22015-11-11 10:34:00 -0800125 rtc::ArrayView<const uint8_t> payload,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000126 uint32_t receive_timestamp) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000127 CriticalSectionScoped lock(crit_sect_.get());
kwibergee2bac22015-11-11 10:34:00 -0800128 int error =
129 InsertPacketInternal(rtp_header, payload, receive_timestamp, false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000130 if (error != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000131 error_code_ = error;
132 return kFail;
133 }
134 return kOK;
135}
136
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000137int NetEqImpl::InsertSyncPacket(const WebRtcRTPHeader& rtp_header,
138 uint32_t receive_timestamp) {
139 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000140 const uint8_t kSyncPayload[] = { 's', 'y', 'n', 'c' };
kwibergee2bac22015-11-11 10:34:00 -0800141 int error =
142 InsertPacketInternal(rtp_header, kSyncPayload, receive_timestamp, true);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000143
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000144 if (error != 0) {
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000145 error_code_ = error;
146 return kFail;
147 }
148 return kOK;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000149}
150
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000151int NetEqImpl::GetAudio(size_t max_length, int16_t* output_audio,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700152 size_t* samples_per_channel, int* num_channels,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000153 NetEqOutputType* type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000154 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000155 int error = GetAudioInternal(max_length, output_audio, samples_per_channel,
156 num_channels);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000157 if (error != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000158 error_code_ = error;
159 return kFail;
160 }
161 if (type) {
162 *type = LastOutputType();
163 }
henrik.lundind89814b2015-11-23 06:49:25 -0800164 last_output_sample_rate_hz_ =
165 rtc::checked_cast<int>(*samples_per_channel * 100);
166 RTC_DCHECK(last_output_sample_rate_hz_ == 8000 ||
167 last_output_sample_rate_hz_ == 16000 ||
168 last_output_sample_rate_hz_ == 32000 ||
169 last_output_sample_rate_hz_ == 48000)
170 << "Unexpected sample rate " << last_output_sample_rate_hz_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000171 return kOK;
172}
173
kwibergee1879c2015-10-29 06:20:28 -0700174int NetEqImpl::RegisterPayloadType(NetEqDecoder codec,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000175 uint8_t rtp_payload_type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000176 CriticalSectionScoped lock(crit_sect_.get());
Henrik Lundind67a2192015-08-03 12:54:37 +0200177 LOG(LS_VERBOSE) << "RegisterPayloadType "
kwibergee1879c2015-10-29 06:20:28 -0700178 << static_cast<int>(rtp_payload_type) << " "
179 << static_cast<int>(codec);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000180 int ret = decoder_database_->RegisterPayload(rtp_payload_type, codec);
181 if (ret != DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000182 switch (ret) {
183 case DecoderDatabase::kInvalidRtpPayloadType:
184 error_code_ = kInvalidRtpPayloadType;
185 break;
186 case DecoderDatabase::kCodecNotSupported:
187 error_code_ = kCodecNotSupported;
188 break;
189 case DecoderDatabase::kDecoderExists:
190 error_code_ = kDecoderExists;
191 break;
192 default:
193 error_code_ = kOtherError;
194 }
195 return kFail;
196 }
197 return kOK;
198}
199
200int NetEqImpl::RegisterExternalDecoder(AudioDecoder* decoder,
kwibergee1879c2015-10-29 06:20:28 -0700201 NetEqDecoder codec,
Karl Wibergd8399e62015-05-25 14:39:56 +0200202 uint8_t rtp_payload_type,
203 int sample_rate_hz) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000204 CriticalSectionScoped lock(crit_sect_.get());
Henrik Lundind67a2192015-08-03 12:54:37 +0200205 LOG(LS_VERBOSE) << "RegisterExternalDecoder "
kwibergee1879c2015-10-29 06:20:28 -0700206 << static_cast<int>(rtp_payload_type) << " "
207 << static_cast<int>(codec);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000208 if (!decoder) {
209 LOG(LS_ERROR) << "Cannot register external decoder with NULL pointer";
210 assert(false);
211 return kFail;
212 }
213 int ret = decoder_database_->InsertExternal(rtp_payload_type, codec,
214 sample_rate_hz, decoder);
215 if (ret != DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000216 switch (ret) {
217 case DecoderDatabase::kInvalidRtpPayloadType:
218 error_code_ = kInvalidRtpPayloadType;
219 break;
220 case DecoderDatabase::kCodecNotSupported:
221 error_code_ = kCodecNotSupported;
222 break;
223 case DecoderDatabase::kDecoderExists:
224 error_code_ = kDecoderExists;
225 break;
226 case DecoderDatabase::kInvalidSampleRate:
227 error_code_ = kInvalidSampleRate;
228 break;
229 case DecoderDatabase::kInvalidPointer:
230 error_code_ = kInvalidPointer;
231 break;
232 default:
233 error_code_ = kOtherError;
234 }
235 return kFail;
236 }
237 return kOK;
238}
239
240int NetEqImpl::RemovePayloadType(uint8_t rtp_payload_type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000241 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000242 int ret = decoder_database_->Remove(rtp_payload_type);
243 if (ret == DecoderDatabase::kOK) {
244 return kOK;
245 } else if (ret == DecoderDatabase::kDecoderNotFound) {
246 error_code_ = kDecoderNotFound;
247 } else {
248 error_code_ = kOtherError;
249 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000250 return kFail;
251}
252
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000253bool NetEqImpl::SetMinimumDelay(int delay_ms) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000254 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000255 if (delay_ms >= 0 && delay_ms < 10000) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000256 assert(delay_manager_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000257 return delay_manager_->SetMinimumDelay(delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000258 }
259 return false;
260}
261
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000262bool NetEqImpl::SetMaximumDelay(int delay_ms) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000263 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000264 if (delay_ms >= 0 && delay_ms < 10000) {
265 assert(delay_manager_.get());
266 return delay_manager_->SetMaximumDelay(delay_ms);
267 }
268 return false;
269}
270
271int NetEqImpl::LeastRequiredDelayMs() const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000272 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000273 assert(delay_manager_.get());
274 return delay_manager_->least_required_delay_ms();
275}
276
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200277int NetEqImpl::SetTargetDelay() {
278 return kNotImplemented;
279}
280
281int NetEqImpl::TargetDelay() {
282 return kNotImplemented;
283}
284
henrik.lundin9c3efd02015-08-27 13:12:22 -0700285int NetEqImpl::CurrentDelayMs() const {
286 CriticalSectionScoped lock(crit_sect_.get());
287 if (fs_hz_ == 0)
288 return 0;
289 // Sum up the samples in the packet buffer with the future length of the sync
290 // buffer, and divide the sum by the sample rate.
291 const size_t delay_samples =
292 packet_buffer_->NumSamplesInBuffer(decoder_database_.get(),
293 decoder_frame_length_) +
294 sync_buffer_->FutureLength();
295 // The division below will truncate.
296 const int delay_ms =
297 static_cast<int>(delay_samples) / rtc::CheckedDivExact(fs_hz_, 1000);
298 return delay_ms;
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200299}
300
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000301// Deprecated.
302// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000303void NetEqImpl::SetPlayoutMode(NetEqPlayoutMode mode) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000304 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000305 if (mode != playout_mode_) {
306 playout_mode_ = mode;
307 CreateDecisionLogic();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000308 }
309}
310
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000311// Deprecated.
312// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000313NetEqPlayoutMode NetEqImpl::PlayoutMode() const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000314 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000315 return playout_mode_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000316}
317
318int NetEqImpl::NetworkStatistics(NetEqNetworkStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000319 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000320 assert(decoder_database_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700321 const size_t total_samples_in_buffers =
Peter Kasting728d9032015-06-11 14:31:38 -0700322 packet_buffer_->NumSamplesInBuffer(decoder_database_.get(),
323 decoder_frame_length_) +
Peter Kastingdce40cf2015-08-24 14:52:23 -0700324 sync_buffer_->FutureLength();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000325 assert(delay_manager_.get());
326 assert(decision_logic_.get());
327 stats_.GetNetworkStatistics(fs_hz_, total_samples_in_buffers,
328 decoder_frame_length_, *delay_manager_.get(),
329 *decision_logic_.get(), stats);
330 return 0;
331}
332
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000333void NetEqImpl::GetRtcpStatistics(RtcpStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000334 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000335 if (stats) {
336 rtcp_.GetStatistics(false, stats);
337 }
338}
339
340void NetEqImpl::GetRtcpStatisticsNoReset(RtcpStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000341 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000342 if (stats) {
343 rtcp_.GetStatistics(true, stats);
344 }
345}
346
347void NetEqImpl::EnableVad() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000348 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000349 assert(vad_.get());
350 vad_->Enable();
351}
352
353void NetEqImpl::DisableVad() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000354 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000355 assert(vad_.get());
356 vad_->Disable();
357}
358
wu@webrtc.org94454b72014-06-05 20:34:08 +0000359bool NetEqImpl::GetPlayoutTimestamp(uint32_t* timestamp) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000360 CriticalSectionScoped lock(crit_sect_.get());
wu@webrtc.org94454b72014-06-05 20:34:08 +0000361 if (first_packet_) {
362 // We don't have a valid RTP timestamp until we have decoded our first
363 // RTP packet.
364 return false;
365 }
366 *timestamp = timestamp_scaler_->ToExternal(playout_timestamp_);
367 return true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000368}
369
henrik.lundind89814b2015-11-23 06:49:25 -0800370int NetEqImpl::last_output_sample_rate_hz() const {
371 CriticalSectionScoped lock(crit_sect_.get());
372 return last_output_sample_rate_hz_;
373}
374
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200375int NetEqImpl::SetTargetNumberOfChannels() {
376 return kNotImplemented;
377}
378
379int NetEqImpl::SetTargetSampleRate() {
380 return kNotImplemented;
381}
382
henrik.lundin@webrtc.orgb0f4b3d2014-11-04 08:53:10 +0000383int NetEqImpl::LastError() const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000384 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000385 return error_code_;
386}
387
388int NetEqImpl::LastDecoderError() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000389 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000390 return decoder_error_code_;
391}
392
393void NetEqImpl::FlushBuffers() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000394 CriticalSectionScoped lock(crit_sect_.get());
Henrik Lundind67a2192015-08-03 12:54:37 +0200395 LOG(LS_VERBOSE) << "FlushBuffers";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000396 packet_buffer_->Flush();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000397 assert(sync_buffer_.get());
398 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000399 sync_buffer_->Flush();
400 sync_buffer_->set_next_index(sync_buffer_->next_index() -
401 expand_->overlap_length());
402 // Set to wait for new codec.
403 first_packet_ = true;
404}
405
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000406void NetEqImpl::PacketBufferStatistics(int* current_num_packets,
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000407 int* max_num_packets) const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000408 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000409 packet_buffer_->BufferStat(current_num_packets, max_num_packets);
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000410}
411
henrik.lundin48ed9302015-10-29 05:36:24 -0700412void NetEqImpl::EnableNack(size_t max_nack_list_size) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000413 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin48ed9302015-10-29 05:36:24 -0700414 if (!nack_enabled_) {
415 const int kNackThresholdPackets = 2;
416 nack_.reset(Nack::Create(kNackThresholdPackets));
417 nack_enabled_ = true;
418 nack_->UpdateSampleRate(fs_hz_);
419 }
420 nack_->SetMaxNackListSize(max_nack_list_size);
421}
422
423void NetEqImpl::DisableNack() {
424 CriticalSectionScoped lock(crit_sect_.get());
425 nack_.reset();
426 nack_enabled_ = false;
427}
428
429std::vector<uint16_t> NetEqImpl::GetNackList(int64_t round_trip_time_ms) const {
430 CriticalSectionScoped lock(crit_sect_.get());
431 if (!nack_enabled_) {
432 return std::vector<uint16_t>();
433 }
434 RTC_DCHECK(nack_.get());
435 return nack_->GetNackList(round_trip_time_ms);
minyue@webrtc.orgd7301772013-08-29 00:58:14 +0000436}
437
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000438const SyncBuffer* NetEqImpl::sync_buffer_for_test() const {
439 CriticalSectionScoped lock(crit_sect_.get());
440 return sync_buffer_.get();
441}
442
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000443// Methods below this line are private.
444
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000445int NetEqImpl::InsertPacketInternal(const WebRtcRTPHeader& rtp_header,
kwibergee2bac22015-11-11 10:34:00 -0800446 rtc::ArrayView<const uint8_t> payload,
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000447 uint32_t receive_timestamp,
448 bool is_sync_packet) {
kwibergee2bac22015-11-11 10:34:00 -0800449 if (payload.empty()) {
450 LOG_F(LS_ERROR) << "payload is empty";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000451 return kInvalidPointer;
452 }
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000453 // Sanity checks for sync-packets.
454 if (is_sync_packet) {
455 if (decoder_database_->IsDtmf(rtp_header.header.payloadType) ||
456 decoder_database_->IsRed(rtp_header.header.payloadType) ||
457 decoder_database_->IsComfortNoise(rtp_header.header.payloadType)) {
458 LOG_F(LS_ERROR) << "Sync-packet with an unacceptable payload type "
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000459 << static_cast<int>(rtp_header.header.payloadType);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000460 return kSyncPacketNotAccepted;
461 }
462 if (first_packet_ ||
463 rtp_header.header.payloadType != current_rtp_payload_type_ ||
464 rtp_header.header.ssrc != ssrc_) {
465 // Even if |current_rtp_payload_type_| is 0xFF, sync-packet isn't
466 // accepted.
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000467 LOG_F(LS_ERROR)
468 << "Changing codec, SSRC or first packet with sync-packet.";
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000469 return kSyncPacketNotAccepted;
470 }
471 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000472 PacketList packet_list;
473 RTPHeader main_header;
474 {
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000475 // Convert to Packet.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000476 // Create |packet| within this separate scope, since it should not be used
477 // directly once it's been inserted in the packet list. This way, |packet|
478 // is not defined outside of this block.
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000479 Packet* packet = new Packet;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000480 packet->header.markerBit = false;
481 packet->header.payloadType = rtp_header.header.payloadType;
482 packet->header.sequenceNumber = rtp_header.header.sequenceNumber;
483 packet->header.timestamp = rtp_header.header.timestamp;
484 packet->header.ssrc = rtp_header.header.ssrc;
485 packet->header.numCSRCs = 0;
kwibergee2bac22015-11-11 10:34:00 -0800486 packet->payload_length = payload.size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000487 packet->primary = true;
488 packet->waiting_time = 0;
489 packet->payload = new uint8_t[packet->payload_length];
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000490 packet->sync_packet = is_sync_packet;
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +0000491 if (!packet->payload) {
492 LOG_F(LS_ERROR) << "Payload pointer is NULL.";
493 }
kwibergee2bac22015-11-11 10:34:00 -0800494 assert(!payload.empty()); // Already checked above.
495 memcpy(packet->payload, payload.data(), packet->payload_length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000496 // Insert packet in a packet list.
497 packet_list.push_back(packet);
498 // Save main payloads header for later.
499 memcpy(&main_header, &packet->header, sizeof(main_header));
500 }
501
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000502 bool update_sample_rate_and_channels = false;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000503 // Reinitialize NetEq if it's needed (changed SSRC or first call).
504 if ((main_header.ssrc != ssrc_) || first_packet_) {
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000505 // Note: |first_packet_| will be cleared further down in this method, once
506 // the packet has been successfully inserted into the packet buffer.
507
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000508 rtcp_.Init(main_header.sequenceNumber);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000509
510 // Flush the packet buffer and DTMF buffer.
511 packet_buffer_->Flush();
512 dtmf_buffer_->Flush();
513
514 // Store new SSRC.
515 ssrc_ = main_header.ssrc;
516
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000517 // Update audio buffer timestamp.
518 sync_buffer_->IncreaseEndTimestamp(main_header.timestamp - timestamp_);
519
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000520 // Update codecs.
521 timestamp_ = main_header.timestamp;
522 current_rtp_payload_type_ = main_header.payloadType;
523
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000524 // Reset timestamp scaling.
525 timestamp_scaler_->Reset();
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000526
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000527 // Trigger an update of sampling rate and the number of channels.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000528 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000529 }
530
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000531 // Update RTCP statistics, only for regular packets.
532 if (!is_sync_packet)
533 rtcp_.Update(main_header, receive_timestamp);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000534
535 // Check for RED payload type, and separate payloads into several packets.
536 if (decoder_database_->IsRed(main_header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000537 assert(!is_sync_packet); // We had a sanity check for this.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000538 if (payload_splitter_->SplitRed(&packet_list) != PayloadSplitter::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000539 PacketBuffer::DeleteAllPackets(&packet_list);
540 return kRedundancySplitError;
541 }
542 // Only accept a few RED payloads of the same type as the main data,
543 // DTMF events and CNG.
544 payload_splitter_->CheckRedPayloads(&packet_list, *decoder_database_);
545 // Update the stored main payload header since the main payload has now
546 // changed.
547 memcpy(&main_header, &packet_list.front()->header, sizeof(main_header));
548 }
549
550 // Check payload types.
551 if (decoder_database_->CheckPayloadTypes(packet_list) ==
552 DecoderDatabase::kDecoderNotFound) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000553 PacketBuffer::DeleteAllPackets(&packet_list);
554 return kUnknownRtpPayloadType;
555 }
556
557 // Scale timestamp to internal domain (only for some codecs).
558 timestamp_scaler_->ToInternal(&packet_list);
559
560 // Process DTMF payloads. Cycle through the list of packets, and pick out any
561 // DTMF payloads found.
562 PacketList::iterator it = packet_list.begin();
563 while (it != packet_list.end()) {
564 Packet* current_packet = (*it);
565 assert(current_packet);
566 assert(current_packet->payload);
567 if (decoder_database_->IsDtmf(current_packet->header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000568 assert(!current_packet->sync_packet); // We had a sanity check for this.
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000569 DtmfEvent event;
570 int ret = DtmfBuffer::ParseEvent(
571 current_packet->header.timestamp,
572 current_packet->payload,
573 current_packet->payload_length,
574 &event);
575 if (ret != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000576 PacketBuffer::DeleteAllPackets(&packet_list);
577 return kDtmfParsingError;
578 }
579 if (dtmf_buffer_->InsertEvent(event) != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000580 PacketBuffer::DeleteAllPackets(&packet_list);
581 return kDtmfInsertError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000582 }
583 // TODO(hlundin): Let the destructor of Packet handle the payload.
584 delete [] current_packet->payload;
585 delete current_packet;
586 it = packet_list.erase(it);
587 } else {
588 ++it;
589 }
590 }
591
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000592 // Check for FEC in packets, and separate payloads into several packets.
593 int ret = payload_splitter_->SplitFec(&packet_list, decoder_database_.get());
594 if (ret != PayloadSplitter::kOK) {
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000595 PacketBuffer::DeleteAllPackets(&packet_list);
596 switch (ret) {
597 case PayloadSplitter::kUnknownPayloadType:
598 return kUnknownRtpPayloadType;
599 default:
600 return kOtherError;
601 }
602 }
603
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000604 // Split payloads into smaller chunks. This also verifies that all payloads
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000605 // are of a known payload type. SplitAudio() method is protected against
606 // sync-packets.
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +0000607 ret = payload_splitter_->SplitAudio(&packet_list, *decoder_database_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000608 if (ret != PayloadSplitter::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000609 PacketBuffer::DeleteAllPackets(&packet_list);
610 switch (ret) {
611 case PayloadSplitter::kUnknownPayloadType:
612 return kUnknownRtpPayloadType;
613 case PayloadSplitter::kFrameSplitError:
614 return kFrameSplitError;
615 default:
616 return kOtherError;
617 }
618 }
619
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000620 // Update bandwidth estimate, if the packet is not sync-packet.
621 if (!packet_list.empty() && !packet_list.front()->sync_packet) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000622 // The list can be empty here if we got nothing but DTMF payloads.
623 AudioDecoder* decoder =
624 decoder_database_->GetDecoder(main_header.payloadType);
625 assert(decoder); // Should always get a valid object, since we have
626 // already checked that the payload types are known.
627 decoder->IncomingPacket(packet_list.front()->payload,
628 packet_list.front()->payload_length,
629 packet_list.front()->header.sequenceNumber,
630 packet_list.front()->header.timestamp,
631 receive_timestamp);
632 }
633
henrik.lundin48ed9302015-10-29 05:36:24 -0700634 if (nack_enabled_) {
635 RTC_DCHECK(nack_);
636 if (update_sample_rate_and_channels) {
637 nack_->Reset();
638 }
639 nack_->UpdateLastReceivedPacket(packet_list.front()->header.sequenceNumber,
640 packet_list.front()->header.timestamp);
641 }
642
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000643 // Insert packets in buffer.
henrik.lundin116c84e2015-08-27 13:14:48 -0700644 const size_t buffer_length_before_insert =
645 packet_buffer_->NumPacketsInBuffer();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000646 ret = packet_buffer_->InsertPacketList(
647 &packet_list,
648 *decoder_database_,
649 &current_rtp_payload_type_,
650 &current_cng_rtp_payload_type_);
651 if (ret == PacketBuffer::kFlushed) {
652 // Reset DSP timestamp etc. if packet buffer flushed.
653 new_codec_ = true;
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000654 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000655 } else if (ret != PacketBuffer::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000656 PacketBuffer::DeleteAllPackets(&packet_list);
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000657 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000658 }
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000659
660 if (first_packet_) {
661 first_packet_ = false;
662 // Update the codec on the next GetAudio call.
663 new_codec_ = true;
664 }
665
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000666 if (current_rtp_payload_type_ != 0xFF) {
667 const DecoderDatabase::DecoderInfo* dec_info =
668 decoder_database_->GetDecoderInfo(current_rtp_payload_type_);
669 if (!dec_info) {
670 assert(false); // Already checked that the payload type is known.
671 }
672 }
673
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000674 if (update_sample_rate_and_channels && !packet_buffer_->Empty()) {
675 // We do not use |current_rtp_payload_type_| to |set payload_type|, but
676 // get the next RTP header from |packet_buffer_| to obtain the payload type.
677 // The reason for it is the following corner case. If NetEq receives a
678 // CNG packet with a sample rate different than the current CNG then it
679 // flushes its buffer, assuming send codec must have been changed. However,
680 // payload type of the hypothetically new send codec is not known.
681 const RTPHeader* rtp_header = packet_buffer_->NextRtpHeader();
682 assert(rtp_header);
683 int payload_type = rtp_header->payloadType;
684 AudioDecoder* decoder = decoder_database_->GetDecoder(payload_type);
685 assert(decoder); // Payloads are already checked to be valid.
686 const DecoderDatabase::DecoderInfo* decoder_info =
687 decoder_database_->GetDecoderInfo(payload_type);
688 assert(decoder_info);
689 if (decoder_info->fs_hz != fs_hz_ ||
henrik.lundin48ed9302015-10-29 05:36:24 -0700690 decoder->Channels() != algorithm_buffer_->Channels()) {
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +0000691 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->Channels());
henrik.lundin48ed9302015-10-29 05:36:24 -0700692 }
693 if (nack_enabled_) {
694 RTC_DCHECK(nack_);
695 // Update the sample rate even if the rate is not new, because of Reset().
696 nack_->UpdateSampleRate(fs_hz_);
697 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000698 }
699
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000700 // TODO(hlundin): Move this code to DelayManager class.
701 const DecoderDatabase::DecoderInfo* dec_info =
702 decoder_database_->GetDecoderInfo(main_header.payloadType);
703 assert(dec_info); // Already checked that the payload type is known.
704 delay_manager_->LastDecoderType(dec_info->codec_type);
705 if (delay_manager_->last_pack_cng_or_dtmf() == 0) {
706 // Calculate the total speech length carried in each packet.
henrik.lundin116c84e2015-08-27 13:14:48 -0700707 const size_t buffer_length_after_insert =
708 packet_buffer_->NumPacketsInBuffer();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000709
henrik.lundin116c84e2015-08-27 13:14:48 -0700710 if (buffer_length_after_insert > buffer_length_before_insert) {
711 const size_t packet_length_samples =
712 (buffer_length_after_insert - buffer_length_before_insert) *
713 decoder_frame_length_;
714 if (packet_length_samples != decision_logic_->packet_length_samples()) {
715 decision_logic_->set_packet_length_samples(packet_length_samples);
716 delay_manager_->SetPacketAudioLength(
717 rtc::checked_cast<int>((1000 * packet_length_samples) / fs_hz_));
718 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000719 }
720
721 // Update statistics.
pbos@webrtc.org0946a562013-04-09 00:28:06 +0000722 if ((int32_t) (main_header.timestamp - timestamp_) >= 0 &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000723 !new_codec_) {
724 // Only update statistics if incoming packet is not older than last played
725 // out packet, and if new codec flag is not set.
726 delay_manager_->Update(main_header.sequenceNumber, main_header.timestamp,
727 fs_hz_);
728 }
729 } else if (delay_manager_->last_pack_cng_or_dtmf() == -1) {
730 // This is first "normal" packet after CNG or DTMF.
731 // Reset packet time counter and measure time until next packet,
732 // but don't update statistics.
733 delay_manager_->set_last_pack_cng_or_dtmf(0);
734 delay_manager_->ResetPacketIatCount();
735 }
736 return 0;
737}
738
Peter Kasting728d9032015-06-11 14:31:38 -0700739int NetEqImpl::GetAudioInternal(size_t max_length,
740 int16_t* output,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700741 size_t* samples_per_channel,
Peter Kasting728d9032015-06-11 14:31:38 -0700742 int* num_channels) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000743 PacketList packet_list;
744 DtmfEvent dtmf_event;
745 Operations operation;
746 bool play_dtmf;
747 int return_value = GetDecision(&operation, &packet_list, &dtmf_event,
748 &play_dtmf);
749 if (return_value != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000750 last_mode_ = kModeError;
751 return return_value;
752 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000753
754 AudioDecoder::SpeechType speech_type;
755 int length = 0;
756 int decode_return_value = Decode(&packet_list, &operation,
757 &length, &speech_type);
758
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000759 assert(vad_.get());
760 bool sid_frame_available =
761 (operation == kRfc3389Cng && !packet_list.empty());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700762 vad_->Update(decoded_buffer_.get(), static_cast<size_t>(length), speech_type,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000763 sid_frame_available, fs_hz_);
764
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000765 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000766 switch (operation) {
767 case kNormal: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000768 DoNormal(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000769 break;
770 }
771 case kMerge: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000772 DoMerge(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000773 break;
774 }
775 case kExpand: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000776 return_value = DoExpand(play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000777 break;
778 }
Henrik Lundincf808d22015-05-27 14:33:29 +0200779 case kAccelerate:
780 case kFastAccelerate: {
781 const bool fast_accelerate =
782 enable_fast_accelerate_ && (operation == kFastAccelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000783 return_value = DoAccelerate(decoded_buffer_.get(), length, speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +0200784 play_dtmf, fast_accelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000785 break;
786 }
787 case kPreemptiveExpand: {
788 return_value = DoPreemptiveExpand(decoded_buffer_.get(), length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000789 speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000790 break;
791 }
792 case kRfc3389Cng:
793 case kRfc3389CngNoPacket: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000794 return_value = DoRfc3389Cng(&packet_list, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000795 break;
796 }
797 case kCodecInternalCng: {
798 // This handles the case when there is no transmission and the decoder
799 // should produce internal comfort noise.
800 // TODO(hlundin): Write test for codec-internal CNG.
minyuel6d92bf52015-09-23 15:20:39 +0200801 DoCodecInternalCng(decoded_buffer_.get(), length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000802 break;
803 }
804 case kDtmf: {
805 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000806 return_value = DoDtmf(dtmf_event, &play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000807 break;
808 }
809 case kAlternativePlc: {
810 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000811 DoAlternativePlc(false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000812 break;
813 }
814 case kAlternativePlcIncreaseTimestamp: {
815 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000816 DoAlternativePlc(true);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000817 break;
818 }
819 case kAudioRepetitionIncreaseTimestamp: {
820 // TODO(hlundin): Write test for this.
Peter Kastingb7e50542015-06-11 12:55:50 -0700821 sync_buffer_->IncreaseEndTimestamp(
822 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000823 // Skipping break on purpose. Execution should move on into the
824 // next case.
kjellander@webrtc.org7d2b6a92015-01-28 18:37:58 +0000825 FALLTHROUGH();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000826 }
827 case kAudioRepetition: {
828 // TODO(hlundin): Write test for this.
829 // Copy last |output_size_samples_| from |sync_buffer_| to
830 // |algorithm_buffer|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000831 algorithm_buffer_->PushBackFromIndex(
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000832 *sync_buffer_, sync_buffer_->Size() - output_size_samples_);
833 expand_->Reset();
834 break;
835 }
836 case kUndefined: {
Henrik Lundind67a2192015-08-03 12:54:37 +0200837 LOG(LS_ERROR) << "Invalid operation kUndefined.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000838 assert(false); // This should not happen.
839 last_mode_ = kModeError;
840 return kInvalidOperation;
841 }
842 } // End of switch.
843 if (return_value < 0) {
844 return return_value;
845 }
846
847 if (last_mode_ != kModeRfc3389Cng) {
848 comfort_noise_->Reset();
849 }
850
851 // Copy from |algorithm_buffer| to |sync_buffer_|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000852 sync_buffer_->PushBack(*algorithm_buffer_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000853
854 // Extract data from |sync_buffer_| to |output|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000855 size_t num_output_samples_per_channel = output_size_samples_;
856 size_t num_output_samples = output_size_samples_ * sync_buffer_->Channels();
857 if (num_output_samples > max_length) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000858 LOG(LS_WARNING) << "Output array is too short. " << max_length << " < " <<
859 output_size_samples_ << " * " << sync_buffer_->Channels();
860 num_output_samples = max_length;
Peter Kastingdce40cf2015-08-24 14:52:23 -0700861 num_output_samples_per_channel = max_length / sync_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000862 }
Peter Kastingdce40cf2015-08-24 14:52:23 -0700863 const size_t samples_from_sync =
864 sync_buffer_->GetNextAudioInterleaved(num_output_samples_per_channel,
865 output);
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000866 *num_channels = static_cast<int>(sync_buffer_->Channels());
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200867 if (sync_buffer_->FutureLength() < expand_->overlap_length()) {
868 // The sync buffer should always contain |overlap_length| samples, but now
869 // too many samples have been extracted. Reinstall the |overlap_length|
870 // lookahead by moving the index.
871 const size_t missing_lookahead_samples =
872 expand_->overlap_length() - sync_buffer_->FutureLength();
henrikg91d6ede2015-09-17 00:24:34 -0700873 RTC_DCHECK_GE(sync_buffer_->next_index(), missing_lookahead_samples);
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200874 sync_buffer_->set_next_index(sync_buffer_->next_index() -
875 missing_lookahead_samples);
876 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000877 if (samples_from_sync != output_size_samples_) {
Henrik Lundind67a2192015-08-03 12:54:37 +0200878 LOG(LS_ERROR) << "samples_from_sync (" << samples_from_sync
879 << ") != output_size_samples_ (" << output_size_samples_
880 << ")";
minyue@webrtc.orgdb1cefc2013-08-13 01:39:21 +0000881 // TODO(minyue): treatment of under-run, filling zeros
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000882 memset(output, 0, num_output_samples * sizeof(int16_t));
883 *samples_per_channel = output_size_samples_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000884 return kSampleUnderrun;
885 }
886 *samples_per_channel = output_size_samples_;
887
888 // Should always have overlap samples left in the |sync_buffer_|.
henrikg91d6ede2015-09-17 00:24:34 -0700889 RTC_DCHECK_GE(sync_buffer_->FutureLength(), expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000890
891 if (play_dtmf) {
892 return_value = DtmfOverdub(dtmf_event, sync_buffer_->Channels(), output);
893 }
894
895 // Update the background noise parameters if last operation wrote data
896 // straight from the decoder to the |sync_buffer_|. That is, none of the
897 // operations that modify the signal can be followed by a parameter update.
898 if ((last_mode_ == kModeNormal) ||
899 (last_mode_ == kModeAccelerateFail) ||
900 (last_mode_ == kModePreemptiveExpandFail) ||
901 (last_mode_ == kModeRfc3389Cng) ||
902 (last_mode_ == kModeCodecInternalCng)) {
903 background_noise_->Update(*sync_buffer_, *vad_.get());
904 }
905
906 if (operation == kDtmf) {
907 // DTMF data was written the end of |sync_buffer_|.
908 // Update index to end of DTMF data in |sync_buffer_|.
909 sync_buffer_->set_dtmf_index(sync_buffer_->Size());
910 }
911
henrik.lundin@webrtc.orged865b52014-03-06 10:28:07 +0000912 if (last_mode_ != kModeExpand) {
913 // If last operation was not expand, calculate the |playout_timestamp_| from
914 // the |sync_buffer_|. However, do not update the |playout_timestamp_| if it
915 // would be moved "backwards".
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000916 uint32_t temp_timestamp = sync_buffer_->end_timestamp() -
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000917 static_cast<uint32_t>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000918 if (static_cast<int32_t>(temp_timestamp - playout_timestamp_) > 0) {
919 playout_timestamp_ = temp_timestamp;
920 }
921 } else {
922 // Use dead reckoning to estimate the |playout_timestamp_|.
Peter Kastingb7e50542015-06-11 12:55:50 -0700923 playout_timestamp_ += static_cast<uint32_t>(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000924 }
925
926 if (decode_return_value) return decode_return_value;
927 return return_value;
928}
929
930int NetEqImpl::GetDecision(Operations* operation,
931 PacketList* packet_list,
932 DtmfEvent* dtmf_event,
933 bool* play_dtmf) {
934 // Initialize output variables.
935 *play_dtmf = false;
936 *operation = kUndefined;
937
938 // Increment time counters.
939 packet_buffer_->IncrementWaitingTimes();
940 stats_.IncreaseCounter(output_size_samples_, fs_hz_);
941
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000942 assert(sync_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000943 uint32_t end_timestamp = sync_buffer_->end_timestamp();
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +0000944 if (!new_codec_) {
945 const uint32_t five_seconds_samples = 5 * fs_hz_;
946 packet_buffer_->DiscardOldPackets(end_timestamp, five_seconds_samples);
947 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000948 const RTPHeader* header = packet_buffer_->NextRtpHeader();
949
henrik.lundin@webrtc.orgca8cb952014-03-12 10:26:52 +0000950 if (decision_logic_->CngRfc3389On() || last_mode_ == kModeRfc3389Cng) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000951 // Because of timestamp peculiarities, we have to "manually" disallow using
952 // a CNG packet with the same timestamp as the one that was last played.
953 // This can happen when using redundancy and will cause the timing to shift.
henrik.lundin@webrtc.org24779fe2014-03-14 12:40:05 +0000954 while (header && decoder_database_->IsComfortNoise(header->payloadType) &&
955 (end_timestamp >= header->timestamp ||
956 end_timestamp + decision_logic_->generated_noise_samples() >
957 header->timestamp)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000958 // Don't use this packet, discard it.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000959 if (packet_buffer_->DiscardNextPacket() != PacketBuffer::kOK) {
960 assert(false); // Must be ok by design.
961 }
962 // Check buffer again.
963 if (!new_codec_) {
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +0000964 packet_buffer_->DiscardOldPackets(end_timestamp, 5 * fs_hz_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000965 }
966 header = packet_buffer_->NextRtpHeader();
967 }
968 }
969
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000970 assert(expand_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000971 const int samples_left = static_cast<int>(sync_buffer_->FutureLength() -
972 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000973 if (last_mode_ == kModeAccelerateSuccess ||
974 last_mode_ == kModeAccelerateLowEnergy ||
975 last_mode_ == kModePreemptiveExpandSuccess ||
976 last_mode_ == kModePreemptiveExpandLowEnergy) {
977 // Subtract (samples_left + output_size_samples_) from sampleMemory.
Peter Kastingdce40cf2015-08-24 14:52:23 -0700978 decision_logic_->AddSampleMemory(
979 -(samples_left + rtc::checked_cast<int>(output_size_samples_)));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000980 }
981
982 // Check if it is time to play a DTMF event.
Peter Kastingb7e50542015-06-11 12:55:50 -0700983 if (dtmf_buffer_->GetEvent(
984 static_cast<uint32_t>(
985 end_timestamp + decision_logic_->generated_noise_samples()),
986 dtmf_event)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000987 *play_dtmf = true;
988 }
989
990 // Get instruction.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000991 assert(sync_buffer_.get());
992 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000993 *operation = decision_logic_->GetDecision(*sync_buffer_,
994 *expand_,
995 decoder_frame_length_,
996 header,
997 last_mode_,
998 *play_dtmf,
999 &reset_decoder_);
1000
1001 // Check if we already have enough samples in the |sync_buffer_|. If so,
1002 // change decision to normal, unless the decision was merge, accelerate, or
1003 // preemptive expand.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001004 if (samples_left >= rtc::checked_cast<int>(output_size_samples_) &&
1005 *operation != kMerge &&
1006 *operation != kAccelerate &&
1007 *operation != kFastAccelerate &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001008 *operation != kPreemptiveExpand) {
1009 *operation = kNormal;
1010 return 0;
1011 }
1012
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001013 decision_logic_->ExpandDecision(*operation);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001014
1015 // Check conditions for reset.
1016 if (new_codec_ || *operation == kUndefined) {
1017 // The only valid reason to get kUndefined is that new_codec_ is set.
1018 assert(new_codec_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001019 if (*play_dtmf && !header) {
1020 timestamp_ = dtmf_event->timestamp;
1021 } else {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001022 if (!header) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001023 LOG(LS_ERROR) << "Packet missing where it shouldn't.";
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001024 return -1;
1025 }
1026 timestamp_ = header->timestamp;
1027 if (*operation == kRfc3389CngNoPacket
1028#ifndef LEGACY_BITEXACT
1029 // Without this check, it can happen that a non-CNG packet is sent to
1030 // the CNG decoder as if it was a SID frame. This is clearly a bug,
1031 // but is kept for now to maintain bit-exactness with the test
1032 // vectors.
1033 && decoder_database_->IsComfortNoise(header->payloadType)
1034#endif
1035 ) {
1036 // Change decision to CNG packet, since we do have a CNG packet, but it
1037 // was considered too early to use. Now, use it anyway.
1038 *operation = kRfc3389Cng;
1039 } else if (*operation != kRfc3389Cng) {
1040 *operation = kNormal;
1041 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001042 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001043 // Adjust |sync_buffer_| timestamp before setting |end_timestamp| to the
1044 // new value.
1045 sync_buffer_->IncreaseEndTimestamp(timestamp_ - end_timestamp);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001046 end_timestamp = timestamp_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001047 new_codec_ = false;
1048 decision_logic_->SoftReset();
1049 buffer_level_filter_->Reset();
1050 delay_manager_->Reset();
1051 stats_.ResetMcu();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001052 }
1053
Peter Kastingdce40cf2015-08-24 14:52:23 -07001054 size_t required_samples = output_size_samples_;
1055 const size_t samples_10_ms = static_cast<size_t>(80 * fs_mult_);
1056 const size_t samples_20_ms = 2 * samples_10_ms;
1057 const size_t samples_30_ms = 3 * samples_10_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001058
1059 switch (*operation) {
1060 case kExpand: {
1061 timestamp_ = end_timestamp;
1062 return 0;
1063 }
1064 case kRfc3389CngNoPacket:
1065 case kCodecInternalCng: {
1066 return 0;
1067 }
1068 case kDtmf: {
1069 // TODO(hlundin): Write test for this.
1070 // Update timestamp.
1071 timestamp_ = end_timestamp;
1072 if (decision_logic_->generated_noise_samples() > 0 &&
1073 last_mode_ != kModeDtmf) {
1074 // Make a jump in timestamp due to the recently played comfort noise.
Peter Kastingb7e50542015-06-11 12:55:50 -07001075 uint32_t timestamp_jump =
1076 static_cast<uint32_t>(decision_logic_->generated_noise_samples());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001077 sync_buffer_->IncreaseEndTimestamp(timestamp_jump);
1078 timestamp_ += timestamp_jump;
1079 }
1080 decision_logic_->set_generated_noise_samples(0);
1081 return 0;
1082 }
Henrik Lundincf808d22015-05-27 14:33:29 +02001083 case kAccelerate:
1084 case kFastAccelerate: {
1085 // In order to do an accelerate we need at least 30 ms of audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001086 if (samples_left >= static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001087 // Already have enough data, so we do not need to extract any more.
1088 decision_logic_->set_sample_memory(samples_left);
1089 decision_logic_->set_prev_time_scale(true);
1090 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001091 } else if (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001092 decoder_frame_length_ >= samples_30_ms) {
1093 // Avoid decoding more data as it might overflow the playout buffer.
1094 *operation = kNormal;
1095 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001096 } else if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001097 decoder_frame_length_ < samples_30_ms) {
1098 // Build up decoded data by decoding at least 20 ms of audio data. Do
1099 // not perform accelerate yet, but wait until we only need to do one
1100 // decoding.
1101 required_samples = 2 * output_size_samples_;
1102 *operation = kNormal;
1103 }
1104 // If none of the above is true, we have one of two possible situations:
1105 // (1) 20 ms <= samples_left < 30 ms and decoder_frame_length_ < 30 ms; or
1106 // (2) samples_left < 10 ms and decoder_frame_length_ >= 30 ms.
1107 // In either case, we move on with the accelerate decision, and decode one
1108 // frame now.
1109 break;
1110 }
1111 case kPreemptiveExpand: {
1112 // In order to do a preemptive expand we need at least 30 ms of decoded
1113 // audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001114 if ((samples_left >= static_cast<int>(samples_30_ms)) ||
1115 (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001116 decoder_frame_length_ >= samples_30_ms)) {
1117 // Already have enough data, so we do not need to extract any more.
1118 // Or, avoid decoding more data as it might overflow the playout buffer.
1119 // Still try preemptive expand, though.
1120 decision_logic_->set_sample_memory(samples_left);
1121 decision_logic_->set_prev_time_scale(true);
1122 return 0;
1123 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07001124 if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001125 decoder_frame_length_ < samples_30_ms) {
1126 // Build up decoded data by decoding at least 20 ms of audio data.
1127 // Still try to perform preemptive expand.
1128 required_samples = 2 * output_size_samples_;
1129 }
1130 // Move on with the preemptive expand decision.
1131 break;
1132 }
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001133 case kMerge: {
1134 required_samples =
1135 std::max(merge_->RequiredFutureSamples(), required_samples);
1136 break;
1137 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001138 default: {
1139 // Do nothing.
1140 }
1141 }
1142
1143 // Get packets from buffer.
1144 int extracted_samples = 0;
1145 if (header &&
1146 *operation != kAlternativePlc &&
1147 *operation != kAlternativePlcIncreaseTimestamp &&
1148 *operation != kAudioRepetition &&
1149 *operation != kAudioRepetitionIncreaseTimestamp) {
1150 sync_buffer_->IncreaseEndTimestamp(header->timestamp - end_timestamp);
1151 if (decision_logic_->CngOff()) {
1152 // Adjustment of timestamp only corresponds to an actual packet loss
1153 // if comfort noise is not played. If comfort noise was just played,
1154 // this adjustment of timestamp is only done to get back in sync with the
1155 // stream timestamp; no loss to report.
1156 stats_.LostSamples(header->timestamp - end_timestamp);
1157 }
1158
1159 if (*operation != kRfc3389Cng) {
1160 // We are about to decode and use a non-CNG packet.
1161 decision_logic_->SetCngOff();
1162 }
1163 // Reset CNG timestamp as a new packet will be delivered.
1164 // (Also if this is a CNG packet, since playedOutTS is updated.)
1165 decision_logic_->set_generated_noise_samples(0);
1166
1167 extracted_samples = ExtractPackets(required_samples, packet_list);
1168 if (extracted_samples < 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001169 return kPacketBufferCorruption;
1170 }
1171 }
1172
Henrik Lundincf808d22015-05-27 14:33:29 +02001173 if (*operation == kAccelerate || *operation == kFastAccelerate ||
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001174 *operation == kPreemptiveExpand) {
1175 decision_logic_->set_sample_memory(samples_left + extracted_samples);
1176 decision_logic_->set_prev_time_scale(true);
1177 }
1178
Henrik Lundincf808d22015-05-27 14:33:29 +02001179 if (*operation == kAccelerate || *operation == kFastAccelerate) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001180 // Check that we have enough data (30ms) to do accelerate.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001181 if (extracted_samples + samples_left < static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001182 // TODO(hlundin): Write test for this.
1183 // Not enough, do normal operation instead.
1184 *operation = kNormal;
1185 }
1186 }
1187
1188 timestamp_ = end_timestamp;
1189 return 0;
1190}
1191
1192int NetEqImpl::Decode(PacketList* packet_list, Operations* operation,
1193 int* decoded_length,
1194 AudioDecoder::SpeechType* speech_type) {
1195 *speech_type = AudioDecoder::kSpeech;
minyuel6d92bf52015-09-23 15:20:39 +02001196
1197 // When packet_list is empty, we may be in kCodecInternalCng mode, and for
1198 // that we use current active decoder.
1199 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1200
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001201 if (!packet_list->empty()) {
1202 const Packet* packet = packet_list->front();
pkasting@chromium.org0e81fdf2015-02-02 23:54:03 +00001203 uint8_t payload_type = packet->header.payloadType;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001204 if (!decoder_database_->IsComfortNoise(payload_type)) {
1205 decoder = decoder_database_->GetDecoder(payload_type);
1206 assert(decoder);
1207 if (!decoder) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001208 LOG(LS_WARNING) << "Unknown payload type "
1209 << static_cast<int>(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001210 PacketBuffer::DeleteAllPackets(packet_list);
1211 return kDecoderNotFound;
1212 }
1213 bool decoder_changed;
1214 decoder_database_->SetActiveDecoder(payload_type, &decoder_changed);
1215 if (decoder_changed) {
1216 // We have a new decoder. Re-init some values.
1217 const DecoderDatabase::DecoderInfo* decoder_info = decoder_database_
1218 ->GetDecoderInfo(payload_type);
1219 assert(decoder_info);
1220 if (!decoder_info) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001221 LOG(LS_WARNING) << "Unknown payload type "
1222 << static_cast<int>(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001223 PacketBuffer::DeleteAllPackets(packet_list);
1224 return kDecoderNotFound;
1225 }
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001226 // If sampling rate or number of channels has changed, we need to make
1227 // a reset.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001228 if (decoder_info->fs_hz != fs_hz_ ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001229 decoder->Channels() != algorithm_buffer_->Channels()) {
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001230 // TODO(tlegrand): Add unittest to cover this event.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001231 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->Channels());
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001232 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001233 sync_buffer_->set_end_timestamp(timestamp_);
1234 playout_timestamp_ = timestamp_;
1235 }
1236 }
1237 }
1238
1239 if (reset_decoder_) {
1240 // TODO(hlundin): Write test for this.
Karl Wiberg43766482015-08-27 15:22:11 +02001241 if (decoder)
1242 decoder->Reset();
1243
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001244 // Reset comfort noise decoder.
1245 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02001246 if (cng_decoder)
1247 cng_decoder->Reset();
1248
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001249 reset_decoder_ = false;
1250 }
1251
1252#ifdef LEGACY_BITEXACT
1253 // Due to a bug in old SignalMCU, it could happen that CNG operation was
1254 // decided, but a speech packet was provided. The speech packet will be used
1255 // to update the comfort noise decoder, as if it was a SID frame, which is
1256 // clearly wrong.
1257 if (*operation == kRfc3389Cng) {
1258 return 0;
1259 }
1260#endif
1261
1262 *decoded_length = 0;
1263 // Update codec-internal PLC state.
1264 if ((*operation == kMerge) && decoder && decoder->HasDecodePlc()) {
1265 decoder->DecodePlc(1, &decoded_buffer_[*decoded_length]);
1266 }
1267
minyuel6d92bf52015-09-23 15:20:39 +02001268 int return_value;
1269 if (*operation == kCodecInternalCng) {
1270 RTC_DCHECK(packet_list->empty());
1271 return_value = DecodeCng(decoder, decoded_length, speech_type);
1272 } else {
1273 return_value = DecodeLoop(packet_list, *operation, decoder,
1274 decoded_length, speech_type);
1275 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001276
1277 if (*decoded_length < 0) {
1278 // Error returned from the decoder.
1279 *decoded_length = 0;
Peter Kastingb7e50542015-06-11 12:55:50 -07001280 sync_buffer_->IncreaseEndTimestamp(
1281 static_cast<uint32_t>(decoder_frame_length_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001282 int error_code = 0;
1283 if (decoder)
1284 error_code = decoder->ErrorCode();
1285 if (error_code != 0) {
1286 // Got some error code from the decoder.
1287 decoder_error_code_ = error_code;
1288 return_value = kDecoderErrorCode;
Henrik Lundind67a2192015-08-03 12:54:37 +02001289 LOG(LS_WARNING) << "Decoder returned error code: " << error_code;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001290 } else {
1291 // Decoder does not implement error codes. Return generic error.
1292 return_value = kOtherDecoderError;
Henrik Lundind67a2192015-08-03 12:54:37 +02001293 LOG(LS_WARNING) << "Decoder error (no error code)";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001294 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001295 *operation = kExpand; // Do expansion to get data instead.
1296 }
1297 if (*speech_type != AudioDecoder::kComfortNoise) {
1298 // Don't increment timestamp if codec returned CNG speech type
1299 // since in this case, the we will increment the CNGplayedTS counter.
1300 // Increase with number of samples per channel.
1301 assert(*decoded_length == 0 ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001302 (decoder && decoder->Channels() == sync_buffer_->Channels()));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001303 sync_buffer_->IncreaseEndTimestamp(
1304 *decoded_length / static_cast<int>(sync_buffer_->Channels()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001305 }
1306 return return_value;
1307}
1308
minyuel6d92bf52015-09-23 15:20:39 +02001309int NetEqImpl::DecodeCng(AudioDecoder* decoder, int* decoded_length,
1310 AudioDecoder::SpeechType* speech_type) {
1311 if (!decoder) {
1312 // This happens when active decoder is not defined.
1313 *decoded_length = -1;
1314 return 0;
1315 }
1316
1317 while (*decoded_length < rtc::checked_cast<int>(output_size_samples_)) {
1318 const int length = decoder->Decode(
1319 nullptr, 0, fs_hz_,
1320 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1321 &decoded_buffer_[*decoded_length], speech_type);
1322 if (length > 0) {
1323 *decoded_length += length;
minyuel6d92bf52015-09-23 15:20:39 +02001324 } else {
1325 // Error.
1326 LOG(LS_WARNING) << "Failed to decode CNG";
1327 *decoded_length = -1;
1328 break;
1329 }
1330 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1331 // Guard against overflow.
1332 LOG(LS_WARNING) << "Decoded too much CNG.";
1333 return kDecodedTooMuch;
1334 }
1335 }
1336 return 0;
1337}
1338
1339int NetEqImpl::DecodeLoop(PacketList* packet_list, const Operations& operation,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001340 AudioDecoder* decoder, int* decoded_length,
1341 AudioDecoder::SpeechType* speech_type) {
1342 Packet* packet = NULL;
1343 if (!packet_list->empty()) {
1344 packet = packet_list->front();
1345 }
minyuel6d92bf52015-09-23 15:20:39 +02001346
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001347 // Do decoding.
1348 while (packet &&
1349 !decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1350 assert(decoder); // At this point, we must have a decoder object.
1351 // The number of channels in the |sync_buffer_| should be the same as the
1352 // number decoder channels.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001353 assert(sync_buffer_->Channels() == decoder->Channels());
1354 assert(decoded_buffer_length_ >= kMaxFrameSize * decoder->Channels());
minyuel6d92bf52015-09-23 15:20:39 +02001355 assert(operation == kNormal || operation == kAccelerate ||
1356 operation == kFastAccelerate || operation == kMerge ||
1357 operation == kPreemptiveExpand);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001358 packet_list->pop_front();
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001359 size_t payload_length = packet->payload_length;
Peter Kasting36b7cc32015-06-11 19:57:18 -07001360 int decode_length;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +00001361 if (packet->sync_packet) {
1362 // Decode to silence with the same frame size as the last decode.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001363 memset(&decoded_buffer_[*decoded_length], 0,
1364 decoder_frame_length_ * decoder->Channels() *
1365 sizeof(decoded_buffer_[0]));
Peter Kastingdce40cf2015-08-24 14:52:23 -07001366 decode_length = rtc::checked_cast<int>(decoder_frame_length_);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +00001367 } else if (!packet->primary) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001368 // This is a redundant payload; call the special decoder method.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001369 decode_length = decoder->DecodeRedundant(
henrik.lundin@webrtc.org1eda4e32015-02-25 10:02:29 +00001370 packet->payload, packet->payload_length, fs_hz_,
minyue@webrtc.org7f7d7e32015-03-16 12:30:37 +00001371 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001372 &decoded_buffer_[*decoded_length], speech_type);
1373 } else {
henrik.lundin@webrtc.org1eda4e32015-02-25 10:02:29 +00001374 decode_length =
minyue@webrtc.org7f7d7e32015-03-16 12:30:37 +00001375 decoder->Decode(
1376 packet->payload, packet->payload_length, fs_hz_,
1377 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1378 &decoded_buffer_[*decoded_length], speech_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001379 }
1380
1381 delete[] packet->payload;
1382 delete packet;
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001383 packet = NULL;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001384 if (decode_length > 0) {
1385 *decoded_length += decode_length;
1386 // Update |decoder_frame_length_| with number of samples per channel.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001387 decoder_frame_length_ =
Peter Kastingdce40cf2015-08-24 14:52:23 -07001388 static_cast<size_t>(decode_length) / decoder->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001389 } else if (decode_length < 0) {
1390 // Error.
Henrik Lundind67a2192015-08-03 12:54:37 +02001391 LOG(LS_WARNING) << "Decode " << decode_length << " " << payload_length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001392 *decoded_length = -1;
1393 PacketBuffer::DeleteAllPackets(packet_list);
1394 break;
1395 }
1396 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1397 // Guard against overflow.
Henrik Lundind67a2192015-08-03 12:54:37 +02001398 LOG(LS_WARNING) << "Decoded too much.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001399 PacketBuffer::DeleteAllPackets(packet_list);
1400 return kDecodedTooMuch;
1401 }
1402 if (!packet_list->empty()) {
1403 packet = packet_list->front();
1404 } else {
1405 packet = NULL;
1406 }
1407 } // End of decode loop.
1408
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001409 // If the list is not empty at this point, either a decoding error terminated
1410 // the while-loop, or list must hold exactly one CNG packet.
1411 assert(packet_list->empty() || *decoded_length < 0 ||
1412 (packet_list->size() == 1 && packet &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001413 decoder_database_->IsComfortNoise(packet->header.payloadType)));
1414 return 0;
1415}
1416
1417void NetEqImpl::DoNormal(const int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001418 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001419 assert(normal_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001420 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001421 normal_->Process(decoded_buffer, decoded_length, last_mode_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001422 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001423 if (decoded_length != 0) {
1424 last_mode_ = kModeNormal;
1425 }
1426
1427 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1428 if ((speech_type == AudioDecoder::kComfortNoise)
1429 || ((last_mode_ == kModeCodecInternalCng)
1430 && (decoded_length == 0))) {
1431 // TODO(hlundin): Remove second part of || statement above.
1432 last_mode_ = kModeCodecInternalCng;
1433 }
1434
1435 if (!play_dtmf) {
1436 dtmf_tone_generator_->Reset();
1437 }
1438}
1439
1440void NetEqImpl::DoMerge(int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001441 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001442 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001443 assert(merge_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001444 size_t new_length = merge_->Process(decoded_buffer, decoded_length,
1445 mute_factor_array_.get(),
1446 algorithm_buffer_.get());
1447 size_t expand_length_correction = new_length -
1448 decoded_length / algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001449
1450 // Update in-call and post-call statistics.
1451 if (expand_->MuteFactor(0) == 0) {
1452 // Expand generates only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001453 stats_.ExpandedNoiseSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001454 } else {
1455 // Expansion generates more than only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001456 stats_.ExpandedVoiceSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001457 }
1458
1459 last_mode_ = kModeMerge;
1460 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1461 if (speech_type == AudioDecoder::kComfortNoise) {
1462 last_mode_ = kModeCodecInternalCng;
1463 }
1464 expand_->Reset();
1465 if (!play_dtmf) {
1466 dtmf_tone_generator_->Reset();
1467 }
1468}
1469
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001470int NetEqImpl::DoExpand(bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001471 while ((sync_buffer_->FutureLength() - expand_->overlap_length()) <
Peter Kastingdce40cf2015-08-24 14:52:23 -07001472 output_size_samples_) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001473 algorithm_buffer_->Clear();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001474 int return_value = expand_->Process(algorithm_buffer_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001475 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001476
1477 // Update in-call and post-call statistics.
1478 if (expand_->MuteFactor(0) == 0) {
1479 // Expand operation generates only noise.
1480 stats_.ExpandedNoiseSamples(length);
1481 } else {
1482 // Expand operation generates more than only noise.
1483 stats_.ExpandedVoiceSamples(length);
1484 }
1485
1486 last_mode_ = kModeExpand;
1487
1488 if (return_value < 0) {
1489 return return_value;
1490 }
1491
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001492 sync_buffer_->PushBack(*algorithm_buffer_);
1493 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001494 }
1495 if (!play_dtmf) {
1496 dtmf_tone_generator_->Reset();
1497 }
1498 return 0;
1499}
1500
Henrik Lundincf808d22015-05-27 14:33:29 +02001501int NetEqImpl::DoAccelerate(int16_t* decoded_buffer,
1502 size_t decoded_length,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001503 AudioDecoder::SpeechType speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +02001504 bool play_dtmf,
1505 bool fast_accelerate) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001506 const size_t required_samples =
1507 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001508 size_t borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001509 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001510 size_t decoded_length_per_channel = decoded_length / num_channels;
1511 if (decoded_length_per_channel < required_samples) {
1512 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001513 borrowed_samples_per_channel = static_cast<int>(required_samples -
1514 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001515 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1516 decoded_buffer,
1517 sizeof(int16_t) * decoded_length);
1518 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1519 decoded_buffer);
1520 decoded_length = required_samples * num_channels;
1521 }
1522
Peter Kastingdce40cf2015-08-24 14:52:23 -07001523 size_t samples_removed;
Henrik Lundincf808d22015-05-27 14:33:29 +02001524 Accelerate::ReturnCodes return_code =
1525 accelerate_->Process(decoded_buffer, decoded_length, fast_accelerate,
1526 algorithm_buffer_.get(), &samples_removed);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001527 stats_.AcceleratedSamples(samples_removed);
1528 switch (return_code) {
1529 case Accelerate::kSuccess:
1530 last_mode_ = kModeAccelerateSuccess;
1531 break;
1532 case Accelerate::kSuccessLowEnergy:
1533 last_mode_ = kModeAccelerateLowEnergy;
1534 break;
1535 case Accelerate::kNoStretch:
1536 last_mode_ = kModeAccelerateFail;
1537 break;
1538 case Accelerate::kError:
1539 // TODO(hlundin): Map to kModeError instead?
1540 last_mode_ = kModeAccelerateFail;
1541 return kAccelerateError;
1542 }
1543
1544 if (borrowed_samples_per_channel > 0) {
1545 // Copy borrowed samples back to the |sync_buffer_|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001546 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001547 if (length < borrowed_samples_per_channel) {
1548 // This destroys the beginning of the buffer, but will not cause any
1549 // problems.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001550 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001551 sync_buffer_->Size() -
1552 borrowed_samples_per_channel);
1553 sync_buffer_->PushFrontZeros(borrowed_samples_per_channel - length);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001554 algorithm_buffer_->PopFront(length);
1555 assert(algorithm_buffer_->Empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001556 } else {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001557 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001558 borrowed_samples_per_channel,
1559 sync_buffer_->Size() -
1560 borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001561 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001562 }
1563 }
1564
1565 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1566 if (speech_type == AudioDecoder::kComfortNoise) {
1567 last_mode_ = kModeCodecInternalCng;
1568 }
1569 if (!play_dtmf) {
1570 dtmf_tone_generator_->Reset();
1571 }
1572 expand_->Reset();
1573 return 0;
1574}
1575
1576int NetEqImpl::DoPreemptiveExpand(int16_t* decoded_buffer,
1577 size_t decoded_length,
1578 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001579 bool play_dtmf) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001580 const size_t required_samples =
1581 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001582 size_t num_channels = algorithm_buffer_->Channels();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001583 size_t borrowed_samples_per_channel = 0;
1584 size_t old_borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001585 size_t decoded_length_per_channel = decoded_length / num_channels;
1586 if (decoded_length_per_channel < required_samples) {
1587 // Must move data from the |sync_buffer_| in order to get 30 ms.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001588 borrowed_samples_per_channel =
1589 required_samples - decoded_length_per_channel;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001590 // Calculate how many of these were already played out.
Peter Kastingf045e4d2015-06-10 21:15:38 -07001591 old_borrowed_samples_per_channel =
Peter Kastingdce40cf2015-08-24 14:52:23 -07001592 (borrowed_samples_per_channel > sync_buffer_->FutureLength()) ?
1593 (borrowed_samples_per_channel - sync_buffer_->FutureLength()) : 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001594 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1595 decoded_buffer,
1596 sizeof(int16_t) * decoded_length);
1597 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1598 decoded_buffer);
1599 decoded_length = required_samples * num_channels;
1600 }
1601
Peter Kastingdce40cf2015-08-24 14:52:23 -07001602 size_t samples_added;
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001603 PreemptiveExpand::ReturnCodes return_code = preemptive_expand_->Process(
Peter Kastingdce40cf2015-08-24 14:52:23 -07001604 decoded_buffer, decoded_length,
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001605 old_borrowed_samples_per_channel,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001606 algorithm_buffer_.get(), &samples_added);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001607 stats_.PreemptiveExpandedSamples(samples_added);
1608 switch (return_code) {
1609 case PreemptiveExpand::kSuccess:
1610 last_mode_ = kModePreemptiveExpandSuccess;
1611 break;
1612 case PreemptiveExpand::kSuccessLowEnergy:
1613 last_mode_ = kModePreemptiveExpandLowEnergy;
1614 break;
1615 case PreemptiveExpand::kNoStretch:
1616 last_mode_ = kModePreemptiveExpandFail;
1617 break;
1618 case PreemptiveExpand::kError:
1619 // TODO(hlundin): Map to kModeError instead?
1620 last_mode_ = kModePreemptiveExpandFail;
1621 return kPreemptiveExpandError;
1622 }
1623
1624 if (borrowed_samples_per_channel > 0) {
1625 // Copy borrowed samples back to the |sync_buffer_|.
1626 sync_buffer_->ReplaceAtIndex(
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001627 *algorithm_buffer_, borrowed_samples_per_channel,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001628 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001629 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001630 }
1631
1632 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1633 if (speech_type == AudioDecoder::kComfortNoise) {
1634 last_mode_ = kModeCodecInternalCng;
1635 }
1636 if (!play_dtmf) {
1637 dtmf_tone_generator_->Reset();
1638 }
1639 expand_->Reset();
1640 return 0;
1641}
1642
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001643int NetEqImpl::DoRfc3389Cng(PacketList* packet_list, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001644 if (!packet_list->empty()) {
1645 // Must have exactly one SID frame at this point.
1646 assert(packet_list->size() == 1);
1647 Packet* packet = packet_list->front();
1648 packet_list->pop_front();
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001649 if (!decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1650#ifdef LEGACY_BITEXACT
1651 // This can happen due to a bug in GetDecision. Change the payload type
1652 // to a CNG type, and move on. Note that this means that we are in fact
1653 // sending a non-CNG payload to the comfort noise decoder for decoding.
1654 // Clearly wrong, but will maintain bit-exactness with legacy.
1655 if (fs_hz_ == 8000) {
1656 packet->header.payloadType =
kwibergee1879c2015-10-29 06:20:28 -07001657 decoder_database_->GetRtpPayloadType(NetEqDecoder::kDecoderCNGnb);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001658 } else if (fs_hz_ == 16000) {
1659 packet->header.payloadType =
kwibergee1879c2015-10-29 06:20:28 -07001660 decoder_database_->GetRtpPayloadType(NetEqDecoder::kDecoderCNGwb);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001661 } else if (fs_hz_ == 32000) {
kwibergee1879c2015-10-29 06:20:28 -07001662 packet->header.payloadType = decoder_database_->GetRtpPayloadType(
1663 NetEqDecoder::kDecoderCNGswb32kHz);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001664 } else if (fs_hz_ == 48000) {
kwibergee1879c2015-10-29 06:20:28 -07001665 packet->header.payloadType = decoder_database_->GetRtpPayloadType(
1666 NetEqDecoder::kDecoderCNGswb48kHz);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001667 }
1668 assert(decoder_database_->IsComfortNoise(packet->header.payloadType));
1669#else
1670 LOG(LS_ERROR) << "Trying to decode non-CNG payload as CNG.";
1671 return kOtherError;
1672#endif
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001673 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001674 // UpdateParameters() deletes |packet|.
1675 if (comfort_noise_->UpdateParameters(packet) ==
1676 ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001677 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001678 return -comfort_noise_->internal_error_code();
1679 }
1680 }
1681 int cn_return = comfort_noise_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001682 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001683 expand_->Reset();
1684 last_mode_ = kModeRfc3389Cng;
1685 if (!play_dtmf) {
1686 dtmf_tone_generator_->Reset();
1687 }
1688 if (cn_return == ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001689 decoder_error_code_ = comfort_noise_->internal_error_code();
1690 return kComfortNoiseErrorCode;
1691 } else if (cn_return == ComfortNoise::kUnknownPayloadType) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001692 return kUnknownRtpPayloadType;
1693 }
1694 return 0;
1695}
1696
minyuel6d92bf52015-09-23 15:20:39 +02001697void NetEqImpl::DoCodecInternalCng(const int16_t* decoded_buffer,
1698 size_t decoded_length) {
1699 RTC_DCHECK(normal_.get());
1700 RTC_DCHECK(mute_factor_array_.get());
1701 normal_->Process(decoded_buffer, decoded_length, last_mode_,
1702 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001703 last_mode_ = kModeCodecInternalCng;
1704 expand_->Reset();
1705}
1706
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001707int NetEqImpl::DoDtmf(const DtmfEvent& dtmf_event, bool* play_dtmf) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001708 // This block of the code and the block further down, handling |dtmf_switch|
1709 // are commented out. Otherwise playing out-of-band DTMF would fail in VoE
1710 // test, DtmfTest.ManualSuccessfullySendsOutOfBandTelephoneEvents. This is
1711 // equivalent to |dtmf_switch| always be false.
1712 //
1713 // See http://webrtc-codereview.appspot.com/1195004/ for discussion
1714 // On this issue. This change might cause some glitches at the point of
1715 // switch from audio to DTMF. Issue 1545 is filed to track this.
1716 //
1717 // bool dtmf_switch = false;
1718 // if ((last_mode_ != kModeDtmf) && dtmf_tone_generator_->initialized()) {
1719 // // Special case; see below.
1720 // // We must catch this before calling Generate, since |initialized| is
1721 // // modified in that call.
1722 // dtmf_switch = true;
1723 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001724
1725 int dtmf_return_value = 0;
1726 if (!dtmf_tone_generator_->initialized()) {
1727 // Initialize if not already done.
1728 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1729 dtmf_event.volume);
1730 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001731
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001732 if (dtmf_return_value == 0) {
1733 // Generate DTMF signal.
1734 dtmf_return_value = dtmf_tone_generator_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001735 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001736 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001737
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001738 if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001739 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001740 return dtmf_return_value;
1741 }
1742
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001743 // if (dtmf_switch) {
1744 // // This is the special case where the previous operation was DTMF
1745 // // overdub, but the current instruction is "regular" DTMF. We must make
1746 // // sure that the DTMF does not have any discontinuities. The first DTMF
1747 // // sample that we generate now must be played out immediately, therefore
1748 // // it must be copied to the speech buffer.
1749 // // TODO(hlundin): This code seems incorrect. (Legacy.) Write test and
1750 // // verify correct operation.
1751 // assert(false);
1752 // // Must generate enough data to replace all of the |sync_buffer_|
1753 // // "future".
1754 // int required_length = sync_buffer_->FutureLength();
1755 // assert(dtmf_tone_generator_->initialized());
1756 // dtmf_return_value = dtmf_tone_generator_->Generate(required_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001757 // algorithm_buffer_);
1758 // assert((size_t) required_length == algorithm_buffer_->Size());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001759 // if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001760 // algorithm_buffer_->Zeros(output_size_samples_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001761 // return dtmf_return_value;
1762 // }
1763 //
1764 // // Overwrite the "future" part of the speech buffer with the new DTMF
1765 // // data.
1766 // // TODO(hlundin): It seems that this overwriting has gone lost.
1767 // // Not adapted for multi-channel yet.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001768 // assert(algorithm_buffer_->Channels() == 1);
1769 // if (algorithm_buffer_->Channels() != 1) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001770 // LOG(LS_WARNING) << "DTMF not supported for more than one channel";
1771 // return kStereoNotSupported;
1772 // }
1773 // // Shuffle the remaining data to the beginning of algorithm buffer.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001774 // algorithm_buffer_->PopFront(sync_buffer_->FutureLength());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001775 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001776
Peter Kastingb7e50542015-06-11 12:55:50 -07001777 sync_buffer_->IncreaseEndTimestamp(
1778 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001779 expand_->Reset();
1780 last_mode_ = kModeDtmf;
1781
1782 // Set to false because the DTMF is already in the algorithm buffer.
1783 *play_dtmf = false;
1784 return 0;
1785}
1786
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001787void NetEqImpl::DoAlternativePlc(bool increase_timestamp) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001788 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001789 size_t length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001790 if (decoder && decoder->HasDecodePlc()) {
1791 // Use the decoder's packet-loss concealment.
1792 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1793 int16_t decoded_buffer[kMaxFrameSize];
1794 length = decoder->DecodePlc(1, decoded_buffer);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001795 if (length > 0)
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001796 algorithm_buffer_->PushBackInterleaved(decoded_buffer, length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001797 } else {
1798 // Do simple zero-stuffing.
1799 length = output_size_samples_;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001800 algorithm_buffer_->Zeros(length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001801 // By not advancing the timestamp, NetEq inserts samples.
1802 stats_.AddZeros(length);
1803 }
1804 if (increase_timestamp) {
Peter Kastingb7e50542015-06-11 12:55:50 -07001805 sync_buffer_->IncreaseEndTimestamp(static_cast<uint32_t>(length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001806 }
1807 expand_->Reset();
1808}
1809
1810int NetEqImpl::DtmfOverdub(const DtmfEvent& dtmf_event, size_t num_channels,
1811 int16_t* output) const {
1812 size_t out_index = 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001813 size_t overdub_length = output_size_samples_; // Default value.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001814
1815 if (sync_buffer_->dtmf_index() > sync_buffer_->next_index()) {
1816 // Special operation for transition from "DTMF only" to "DTMF overdub".
1817 out_index = std::min(
1818 sync_buffer_->dtmf_index() - sync_buffer_->next_index(),
Peter Kastingdce40cf2015-08-24 14:52:23 -07001819 output_size_samples_);
1820 overdub_length = output_size_samples_ - out_index;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001821 }
1822
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001823 AudioMultiVector dtmf_output(num_channels);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001824 int dtmf_return_value = 0;
1825 if (!dtmf_tone_generator_->initialized()) {
1826 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1827 dtmf_event.volume);
1828 }
1829 if (dtmf_return_value == 0) {
1830 dtmf_return_value = dtmf_tone_generator_->Generate(overdub_length,
1831 &dtmf_output);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001832 assert(overdub_length == dtmf_output.Size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001833 }
1834 dtmf_output.ReadInterleaved(overdub_length, &output[out_index]);
1835 return dtmf_return_value < 0 ? dtmf_return_value : 0;
1836}
1837
Peter Kastingdce40cf2015-08-24 14:52:23 -07001838int NetEqImpl::ExtractPackets(size_t required_samples,
1839 PacketList* packet_list) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001840 bool first_packet = true;
1841 uint8_t prev_payload_type = 0;
1842 uint32_t prev_timestamp = 0;
1843 uint16_t prev_sequence_number = 0;
1844 bool next_packet_available = false;
1845
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001846 const RTPHeader* header = packet_buffer_->NextRtpHeader();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001847 assert(header);
1848 if (!header) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001849 LOG(LS_ERROR) << "Packet buffer unexpectedly empty.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001850 return -1;
1851 }
turaj@webrtc.org7df97062013-08-02 18:07:13 +00001852 uint32_t first_timestamp = header->timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001853 int extracted_samples = 0;
1854
1855 // Packet extraction loop.
1856 do {
1857 timestamp_ = header->timestamp;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001858 size_t discard_count = 0;
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001859 Packet* packet = packet_buffer_->GetNextPacket(&discard_count);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001860 // |header| may be invalid after the |packet_buffer_| operation.
1861 header = NULL;
1862 if (!packet) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001863 LOG(LS_ERROR) << "Should always be able to extract a packet here";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001864 assert(false); // Should always be able to extract a packet here.
1865 return -1;
1866 }
1867 stats_.PacketsDiscarded(discard_count);
1868 // Store waiting time in ms; packets->waiting_time is in "output blocks".
1869 stats_.StoreWaitingTime(packet->waiting_time * kOutputSizeMs);
1870 assert(packet->payload_length > 0);
1871 packet_list->push_back(packet); // Store packet in list.
1872
1873 if (first_packet) {
1874 first_packet = false;
henrik.lundin48ed9302015-10-29 05:36:24 -07001875 if (nack_enabled_) {
1876 RTC_DCHECK(nack_);
1877 // TODO(henrik.lundin): Should we update this for all decoded packets?
1878 nack_->UpdateLastDecodedPacket(packet->header.sequenceNumber,
1879 packet->header.timestamp);
1880 }
1881 prev_sequence_number = packet->header.sequenceNumber;
1882 prev_timestamp = packet->header.timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001883 prev_payload_type = packet->header.payloadType;
1884 }
1885
1886 // Store number of extracted samples.
1887 int packet_duration = 0;
1888 AudioDecoder* decoder = decoder_database_->GetDecoder(
1889 packet->header.payloadType);
1890 if (decoder) {
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001891 if (packet->sync_packet) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001892 packet_duration = rtc::checked_cast<int>(decoder_frame_length_);
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001893 } else {
minyue@webrtc.org2c1bcf22015-02-17 10:17:09 +00001894 if (packet->primary) {
1895 packet_duration = decoder->PacketDuration(packet->payload,
1896 packet->payload_length);
1897 } else {
1898 packet_duration = decoder->
1899 PacketDurationRedundant(packet->payload, packet->payload_length);
1900 stats_.SecondaryDecodedSamples(packet_duration);
1901 }
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001902 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001903 } else {
Henrik Lundind67a2192015-08-03 12:54:37 +02001904 LOG(LS_WARNING) << "Unknown payload type "
1905 << static_cast<int>(packet->header.payloadType);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001906 assert(false);
1907 }
1908 if (packet_duration <= 0) {
1909 // Decoder did not return a packet duration. Assume that the packet
1910 // contains the same number of samples as the previous one.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001911 packet_duration = rtc::checked_cast<int>(decoder_frame_length_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001912 }
1913 extracted_samples = packet->header.timestamp - first_timestamp +
1914 packet_duration;
1915
1916 // Check what packet is available next.
1917 header = packet_buffer_->NextRtpHeader();
1918 next_packet_available = false;
1919 if (header && prev_payload_type == header->payloadType) {
1920 int16_t seq_no_diff = header->sequenceNumber - prev_sequence_number;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001921 size_t ts_diff = header->timestamp - prev_timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001922 if (seq_no_diff == 1 ||
1923 (seq_no_diff == 0 && ts_diff == decoder_frame_length_)) {
1924 // The next sequence number is available, or the next part of a packet
1925 // that was split into pieces upon insertion.
1926 next_packet_available = true;
1927 }
1928 prev_sequence_number = header->sequenceNumber;
1929 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07001930 } while (extracted_samples < rtc::checked_cast<int>(required_samples) &&
1931 next_packet_available);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001932
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00001933 if (extracted_samples > 0) {
1934 // Delete old packets only when we are going to decode something. Otherwise,
1935 // we could end up in the situation where we never decode anything, since
1936 // all incoming packets are considered too old but the buffer will also
1937 // never be flooded and flushed.
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001938 packet_buffer_->DiscardAllOldPackets(timestamp_);
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00001939 }
1940
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001941 return extracted_samples;
1942}
1943
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001944void NetEqImpl::UpdatePlcComponents(int fs_hz, size_t channels) {
1945 // Delete objects and create new ones.
1946 expand_.reset(expand_factory_->Create(background_noise_.get(),
1947 sync_buffer_.get(), &random_vector_,
Henrik Lundinbef77e22015-08-18 14:58:09 +02001948 &stats_, fs_hz, channels));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001949 merge_.reset(new Merge(fs_hz, channels, expand_.get(), sync_buffer_.get()));
1950}
1951
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001952void NetEqImpl::SetSampleRateAndChannels(int fs_hz, size_t channels) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001953 LOG(LS_VERBOSE) << "SetSampleRateAndChannels " << fs_hz << " " << channels;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001954 // TODO(hlundin): Change to an enumerator and skip assert.
1955 assert(fs_hz == 8000 || fs_hz == 16000 || fs_hz == 32000 || fs_hz == 48000);
1956 assert(channels > 0);
1957
1958 fs_hz_ = fs_hz;
1959 fs_mult_ = fs_hz / 8000;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001960 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001961 decoder_frame_length_ = 3 * output_size_samples_; // Initialize to 30ms.
1962
1963 last_mode_ = kModeNormal;
1964
1965 // Create a new array of mute factors and set all to 1.
1966 mute_factor_array_.reset(new int16_t[channels]);
1967 for (size_t i = 0; i < channels; ++i) {
1968 mute_factor_array_[i] = 16384; // 1.0 in Q14.
1969 }
1970
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001971 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02001972 if (cng_decoder)
1973 cng_decoder->Reset();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001974
1975 // Reinit post-decode VAD with new sample rate.
1976 assert(vad_.get()); // Cannot be NULL here.
1977 vad_->Init();
1978
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001979 // Delete algorithm buffer and create a new one.
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001980 algorithm_buffer_.reset(new AudioMultiVector(channels));
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001981
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001982 // Delete sync buffer and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001983 sync_buffer_.reset(new SyncBuffer(channels, kSyncBufferSize * fs_mult_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001984
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00001985 // Delete BackgroundNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001986 background_noise_.reset(new BackgroundNoise(channels));
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00001987 background_noise_->set_mode(background_noise_mode_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001988
1989 // Reset random vector.
1990 random_vector_.Reset();
1991
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001992 UpdatePlcComponents(fs_hz, channels);
1993
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001994 // Move index so that we create a small set of future samples (all 0).
1995 sync_buffer_->set_next_index(sync_buffer_->next_index() -
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001996 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001997
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001998 normal_.reset(new Normal(fs_hz, decoder_database_.get(), *background_noise_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001999 expand_.get()));
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +00002000 accelerate_.reset(
2001 accelerate_factory_->Create(fs_hz, channels, *background_noise_));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002002 preemptive_expand_.reset(preemptive_expand_factory_->Create(
Peter Kastingdce40cf2015-08-24 14:52:23 -07002003 fs_hz, channels, *background_noise_, expand_->overlap_length()));
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002004
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002005 // Delete ComfortNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002006 comfort_noise_.reset(new ComfortNoise(fs_hz, decoder_database_.get(),
2007 sync_buffer_.get()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002008
2009 // Verify that |decoded_buffer_| is long enough.
2010 if (decoded_buffer_length_ < kMaxFrameSize * channels) {
2011 // Reallocate to larger size.
2012 decoded_buffer_length_ = kMaxFrameSize * channels;
2013 decoded_buffer_.reset(new int16_t[decoded_buffer_length_]);
2014 }
2015
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002016 // Create DecisionLogic if it is not created yet, then communicate new sample
2017 // rate and output size to DecisionLogic object.
2018 if (!decision_logic_.get()) {
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002019 CreateDecisionLogic();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002020 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002021 decision_logic_->SetSampleRate(fs_hz_, output_size_samples_);
2022}
2023
2024NetEqOutputType NetEqImpl::LastOutputType() {
2025 assert(vad_.get());
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002026 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002027 if (last_mode_ == kModeCodecInternalCng || last_mode_ == kModeRfc3389Cng) {
2028 return kOutputCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002029 } else if (last_mode_ == kModeExpand && expand_->MuteFactor(0) == 0) {
2030 // Expand mode has faded down to background noise only (very long expand).
2031 return kOutputPLCtoCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002032 } else if (last_mode_ == kModeExpand) {
2033 return kOutputPLC;
wu@webrtc.org24301a62013-12-13 19:17:43 +00002034 } else if (vad_->running() && !vad_->active_speech()) {
2035 return kOutputVADPassive;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002036 } else {
2037 return kOutputNormal;
2038 }
2039}
2040
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002041void NetEqImpl::CreateDecisionLogic() {
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002042 decision_logic_.reset(DecisionLogic::Create(fs_hz_, output_size_samples_,
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002043 playout_mode_,
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002044 decoder_database_.get(),
2045 *packet_buffer_.get(),
2046 delay_manager_.get(),
2047 buffer_level_filter_.get()));
2048}
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002049} // namespace webrtc