blob: bbd3220c00b20f33523b68d31508bcdfc03f6d51 [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;
Peter Kastingdce40cf2015-08-24 14:52:23 -0700109 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000110 decoder_frame_length_ = 3 * output_size_samples_;
111 WebRtcSpl_Init();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000112 if (create_components) {
113 SetSampleRateAndChannels(fs, 1); // Default is 1 channel.
114 }
henrik.lundin9bc26672015-11-02 03:25:57 -0800115 RTC_DCHECK(!vad_->enabled());
116 if (config.enable_post_decode_vad) {
117 vad_->Enable();
118 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000119}
120
Henrik Lundind67a2192015-08-03 12:54:37 +0200121NetEqImpl::~NetEqImpl() = default;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000122
123int NetEqImpl::InsertPacket(const WebRtcRTPHeader& rtp_header,
kwibergee2bac22015-11-11 10:34:00 -0800124 rtc::ArrayView<const uint8_t> payload,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000125 uint32_t receive_timestamp) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000126 CriticalSectionScoped lock(crit_sect_.get());
kwibergee2bac22015-11-11 10:34:00 -0800127 LOG(LS_VERBOSE) << "InsertPacket: ts=" << rtp_header.header.timestamp
128 << ", sn=" << rtp_header.header.sequenceNumber
129 << ", pt=" << static_cast<int>(rtp_header.header.payloadType)
130 << ", ssrc=" << rtp_header.header.ssrc
131 << ", len=" << payload.size();
132 int error =
133 InsertPacketInternal(rtp_header, payload, receive_timestamp, false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000134 if (error != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000135 error_code_ = error;
136 return kFail;
137 }
138 return kOK;
139}
140
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000141int NetEqImpl::InsertSyncPacket(const WebRtcRTPHeader& rtp_header,
142 uint32_t receive_timestamp) {
143 CriticalSectionScoped lock(crit_sect_.get());
144 LOG(LS_VERBOSE) << "InsertPacket-Sync: ts="
145 << rtp_header.header.timestamp <<
146 ", sn=" << rtp_header.header.sequenceNumber <<
147 ", pt=" << static_cast<int>(rtp_header.header.payloadType) <<
148 ", ssrc=" << rtp_header.header.ssrc;
149
150 const uint8_t kSyncPayload[] = { 's', 'y', 'n', 'c' };
kwibergee2bac22015-11-11 10:34:00 -0800151 int error =
152 InsertPacketInternal(rtp_header, kSyncPayload, receive_timestamp, true);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000153
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000154 if (error != 0) {
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000155 error_code_ = error;
156 return kFail;
157 }
158 return kOK;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000159}
160
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000161int NetEqImpl::GetAudio(size_t max_length, int16_t* output_audio,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700162 size_t* samples_per_channel, int* num_channels,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000163 NetEqOutputType* type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000164 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000165 LOG(LS_VERBOSE) << "GetAudio";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000166 int error = GetAudioInternal(max_length, output_audio, samples_per_channel,
167 num_channels);
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000168 LOG(LS_VERBOSE) << "Produced " << *samples_per_channel <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000169 " samples/channel for " << *num_channels << " channel(s)";
170 if (error != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000171 error_code_ = error;
172 return kFail;
173 }
174 if (type) {
175 *type = LastOutputType();
176 }
177 return kOK;
178}
179
kwibergee1879c2015-10-29 06:20:28 -0700180int NetEqImpl::RegisterPayloadType(NetEqDecoder codec,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000181 uint8_t rtp_payload_type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000182 CriticalSectionScoped lock(crit_sect_.get());
Henrik Lundind67a2192015-08-03 12:54:37 +0200183 LOG(LS_VERBOSE) << "RegisterPayloadType "
kwibergee1879c2015-10-29 06:20:28 -0700184 << static_cast<int>(rtp_payload_type) << " "
185 << static_cast<int>(codec);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000186 int ret = decoder_database_->RegisterPayload(rtp_payload_type, codec);
187 if (ret != DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000188 switch (ret) {
189 case DecoderDatabase::kInvalidRtpPayloadType:
190 error_code_ = kInvalidRtpPayloadType;
191 break;
192 case DecoderDatabase::kCodecNotSupported:
193 error_code_ = kCodecNotSupported;
194 break;
195 case DecoderDatabase::kDecoderExists:
196 error_code_ = kDecoderExists;
197 break;
198 default:
199 error_code_ = kOtherError;
200 }
201 return kFail;
202 }
203 return kOK;
204}
205
206int NetEqImpl::RegisterExternalDecoder(AudioDecoder* decoder,
kwibergee1879c2015-10-29 06:20:28 -0700207 NetEqDecoder codec,
Karl Wibergd8399e62015-05-25 14:39:56 +0200208 uint8_t rtp_payload_type,
209 int sample_rate_hz) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000210 CriticalSectionScoped lock(crit_sect_.get());
Henrik Lundind67a2192015-08-03 12:54:37 +0200211 LOG(LS_VERBOSE) << "RegisterExternalDecoder "
kwibergee1879c2015-10-29 06:20:28 -0700212 << static_cast<int>(rtp_payload_type) << " "
213 << static_cast<int>(codec);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000214 if (!decoder) {
215 LOG(LS_ERROR) << "Cannot register external decoder with NULL pointer";
216 assert(false);
217 return kFail;
218 }
219 int ret = decoder_database_->InsertExternal(rtp_payload_type, codec,
220 sample_rate_hz, decoder);
221 if (ret != DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000222 switch (ret) {
223 case DecoderDatabase::kInvalidRtpPayloadType:
224 error_code_ = kInvalidRtpPayloadType;
225 break;
226 case DecoderDatabase::kCodecNotSupported:
227 error_code_ = kCodecNotSupported;
228 break;
229 case DecoderDatabase::kDecoderExists:
230 error_code_ = kDecoderExists;
231 break;
232 case DecoderDatabase::kInvalidSampleRate:
233 error_code_ = kInvalidSampleRate;
234 break;
235 case DecoderDatabase::kInvalidPointer:
236 error_code_ = kInvalidPointer;
237 break;
238 default:
239 error_code_ = kOtherError;
240 }
241 return kFail;
242 }
243 return kOK;
244}
245
246int NetEqImpl::RemovePayloadType(uint8_t rtp_payload_type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000247 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000248 int ret = decoder_database_->Remove(rtp_payload_type);
249 if (ret == DecoderDatabase::kOK) {
250 return kOK;
251 } else if (ret == DecoderDatabase::kDecoderNotFound) {
252 error_code_ = kDecoderNotFound;
253 } else {
254 error_code_ = kOtherError;
255 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000256 return kFail;
257}
258
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000259bool NetEqImpl::SetMinimumDelay(int delay_ms) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000260 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000261 if (delay_ms >= 0 && delay_ms < 10000) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000262 assert(delay_manager_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000263 return delay_manager_->SetMinimumDelay(delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000264 }
265 return false;
266}
267
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000268bool NetEqImpl::SetMaximumDelay(int delay_ms) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000269 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000270 if (delay_ms >= 0 && delay_ms < 10000) {
271 assert(delay_manager_.get());
272 return delay_manager_->SetMaximumDelay(delay_ms);
273 }
274 return false;
275}
276
277int NetEqImpl::LeastRequiredDelayMs() const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000278 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000279 assert(delay_manager_.get());
280 return delay_manager_->least_required_delay_ms();
281}
282
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200283int NetEqImpl::SetTargetDelay() {
284 return kNotImplemented;
285}
286
287int NetEqImpl::TargetDelay() {
288 return kNotImplemented;
289}
290
henrik.lundin9c3efd02015-08-27 13:12:22 -0700291int NetEqImpl::CurrentDelayMs() const {
292 CriticalSectionScoped lock(crit_sect_.get());
293 if (fs_hz_ == 0)
294 return 0;
295 // Sum up the samples in the packet buffer with the future length of the sync
296 // buffer, and divide the sum by the sample rate.
297 const size_t delay_samples =
298 packet_buffer_->NumSamplesInBuffer(decoder_database_.get(),
299 decoder_frame_length_) +
300 sync_buffer_->FutureLength();
301 // The division below will truncate.
302 const int delay_ms =
303 static_cast<int>(delay_samples) / rtc::CheckedDivExact(fs_hz_, 1000);
304 return delay_ms;
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200305}
306
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000307// Deprecated.
308// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000309void NetEqImpl::SetPlayoutMode(NetEqPlayoutMode mode) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000310 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000311 if (mode != playout_mode_) {
312 playout_mode_ = mode;
313 CreateDecisionLogic();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000314 }
315}
316
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000317// Deprecated.
318// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000319NetEqPlayoutMode NetEqImpl::PlayoutMode() const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000320 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000321 return playout_mode_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000322}
323
324int NetEqImpl::NetworkStatistics(NetEqNetworkStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000325 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000326 assert(decoder_database_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700327 const size_t total_samples_in_buffers =
Peter Kasting728d9032015-06-11 14:31:38 -0700328 packet_buffer_->NumSamplesInBuffer(decoder_database_.get(),
329 decoder_frame_length_) +
Peter Kastingdce40cf2015-08-24 14:52:23 -0700330 sync_buffer_->FutureLength();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000331 assert(delay_manager_.get());
332 assert(decision_logic_.get());
333 stats_.GetNetworkStatistics(fs_hz_, total_samples_in_buffers,
334 decoder_frame_length_, *delay_manager_.get(),
335 *decision_logic_.get(), stats);
336 return 0;
337}
338
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000339void NetEqImpl::GetRtcpStatistics(RtcpStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000340 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000341 if (stats) {
342 rtcp_.GetStatistics(false, stats);
343 }
344}
345
346void NetEqImpl::GetRtcpStatisticsNoReset(RtcpStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000347 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000348 if (stats) {
349 rtcp_.GetStatistics(true, stats);
350 }
351}
352
353void NetEqImpl::EnableVad() {
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_->Enable();
357}
358
359void NetEqImpl::DisableVad() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000360 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000361 assert(vad_.get());
362 vad_->Disable();
363}
364
wu@webrtc.org94454b72014-06-05 20:34:08 +0000365bool NetEqImpl::GetPlayoutTimestamp(uint32_t* timestamp) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000366 CriticalSectionScoped lock(crit_sect_.get());
wu@webrtc.org94454b72014-06-05 20:34:08 +0000367 if (first_packet_) {
368 // We don't have a valid RTP timestamp until we have decoded our first
369 // RTP packet.
370 return false;
371 }
372 *timestamp = timestamp_scaler_->ToExternal(playout_timestamp_);
373 return true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000374}
375
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200376int NetEqImpl::SetTargetNumberOfChannels() {
377 return kNotImplemented;
378}
379
380int NetEqImpl::SetTargetSampleRate() {
381 return kNotImplemented;
382}
383
henrik.lundin@webrtc.orgb0f4b3d2014-11-04 08:53:10 +0000384int NetEqImpl::LastError() const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000385 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000386 return error_code_;
387}
388
389int NetEqImpl::LastDecoderError() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000390 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000391 return decoder_error_code_;
392}
393
394void NetEqImpl::FlushBuffers() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000395 CriticalSectionScoped lock(crit_sect_.get());
Henrik Lundind67a2192015-08-03 12:54:37 +0200396 LOG(LS_VERBOSE) << "FlushBuffers";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000397 packet_buffer_->Flush();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000398 assert(sync_buffer_.get());
399 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000400 sync_buffer_->Flush();
401 sync_buffer_->set_next_index(sync_buffer_->next_index() -
402 expand_->overlap_length());
403 // Set to wait for new codec.
404 first_packet_ = true;
405}
406
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000407void NetEqImpl::PacketBufferStatistics(int* current_num_packets,
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000408 int* max_num_packets) const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000409 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000410 packet_buffer_->BufferStat(current_num_packets, max_num_packets);
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000411}
412
henrik.lundin48ed9302015-10-29 05:36:24 -0700413void NetEqImpl::EnableNack(size_t max_nack_list_size) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000414 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin48ed9302015-10-29 05:36:24 -0700415 if (!nack_enabled_) {
416 const int kNackThresholdPackets = 2;
417 nack_.reset(Nack::Create(kNackThresholdPackets));
418 nack_enabled_ = true;
419 nack_->UpdateSampleRate(fs_hz_);
420 }
421 nack_->SetMaxNackListSize(max_nack_list_size);
422}
423
424void NetEqImpl::DisableNack() {
425 CriticalSectionScoped lock(crit_sect_.get());
426 nack_.reset();
427 nack_enabled_ = false;
428}
429
430std::vector<uint16_t> NetEqImpl::GetNackList(int64_t round_trip_time_ms) const {
431 CriticalSectionScoped lock(crit_sect_.get());
432 if (!nack_enabled_) {
433 return std::vector<uint16_t>();
434 }
435 RTC_DCHECK(nack_.get());
436 return nack_->GetNackList(round_trip_time_ms);
minyue@webrtc.orgd7301772013-08-29 00:58:14 +0000437}
438
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000439const SyncBuffer* NetEqImpl::sync_buffer_for_test() const {
440 CriticalSectionScoped lock(crit_sect_.get());
441 return sync_buffer_.get();
442}
443
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000444// Methods below this line are private.
445
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000446int NetEqImpl::InsertPacketInternal(const WebRtcRTPHeader& rtp_header,
kwibergee2bac22015-11-11 10:34:00 -0800447 rtc::ArrayView<const uint8_t> payload,
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000448 uint32_t receive_timestamp,
449 bool is_sync_packet) {
kwibergee2bac22015-11-11 10:34:00 -0800450 if (payload.empty()) {
451 LOG_F(LS_ERROR) << "payload is empty";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000452 return kInvalidPointer;
453 }
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000454 // Sanity checks for sync-packets.
455 if (is_sync_packet) {
456 if (decoder_database_->IsDtmf(rtp_header.header.payloadType) ||
457 decoder_database_->IsRed(rtp_header.header.payloadType) ||
458 decoder_database_->IsComfortNoise(rtp_header.header.payloadType)) {
459 LOG_F(LS_ERROR) << "Sync-packet with an unacceptable payload type "
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000460 << static_cast<int>(rtp_header.header.payloadType);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000461 return kSyncPacketNotAccepted;
462 }
463 if (first_packet_ ||
464 rtp_header.header.payloadType != current_rtp_payload_type_ ||
465 rtp_header.header.ssrc != ssrc_) {
466 // Even if |current_rtp_payload_type_| is 0xFF, sync-packet isn't
467 // accepted.
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000468 LOG_F(LS_ERROR)
469 << "Changing codec, SSRC or first packet with sync-packet.";
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000470 return kSyncPacketNotAccepted;
471 }
472 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000473 PacketList packet_list;
474 RTPHeader main_header;
475 {
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000476 // Convert to Packet.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000477 // Create |packet| within this separate scope, since it should not be used
478 // directly once it's been inserted in the packet list. This way, |packet|
479 // is not defined outside of this block.
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000480 Packet* packet = new Packet;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000481 packet->header.markerBit = false;
482 packet->header.payloadType = rtp_header.header.payloadType;
483 packet->header.sequenceNumber = rtp_header.header.sequenceNumber;
484 packet->header.timestamp = rtp_header.header.timestamp;
485 packet->header.ssrc = rtp_header.header.ssrc;
486 packet->header.numCSRCs = 0;
kwibergee2bac22015-11-11 10:34:00 -0800487 packet->payload_length = payload.size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000488 packet->primary = true;
489 packet->waiting_time = 0;
490 packet->payload = new uint8_t[packet->payload_length];
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000491 packet->sync_packet = is_sync_packet;
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +0000492 if (!packet->payload) {
493 LOG_F(LS_ERROR) << "Payload pointer is NULL.";
494 }
kwibergee2bac22015-11-11 10:34:00 -0800495 assert(!payload.empty()); // Already checked above.
496 memcpy(packet->payload, payload.data(), packet->payload_length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000497 // Insert packet in a packet list.
498 packet_list.push_back(packet);
499 // Save main payloads header for later.
500 memcpy(&main_header, &packet->header, sizeof(main_header));
501 }
502
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000503 bool update_sample_rate_and_channels = false;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000504 // Reinitialize NetEq if it's needed (changed SSRC or first call).
505 if ((main_header.ssrc != ssrc_) || first_packet_) {
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000506 // Note: |first_packet_| will be cleared further down in this method, once
507 // the packet has been successfully inserted into the packet buffer.
508
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000509 rtcp_.Init(main_header.sequenceNumber);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000510
511 // Flush the packet buffer and DTMF buffer.
512 packet_buffer_->Flush();
513 dtmf_buffer_->Flush();
514
515 // Store new SSRC.
516 ssrc_ = main_header.ssrc;
517
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000518 // Update audio buffer timestamp.
519 sync_buffer_->IncreaseEndTimestamp(main_header.timestamp - timestamp_);
520
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000521 // Update codecs.
522 timestamp_ = main_header.timestamp;
523 current_rtp_payload_type_ = main_header.payloadType;
524
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000525 // Reset timestamp scaling.
526 timestamp_scaler_->Reset();
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000527
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000528 // Trigger an update of sampling rate and the number of channels.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000529 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000530 }
531
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000532 // Update RTCP statistics, only for regular packets.
533 if (!is_sync_packet)
534 rtcp_.Update(main_header, receive_timestamp);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000535
536 // Check for RED payload type, and separate payloads into several packets.
537 if (decoder_database_->IsRed(main_header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000538 assert(!is_sync_packet); // We had a sanity check for this.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000539 if (payload_splitter_->SplitRed(&packet_list) != PayloadSplitter::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000540 PacketBuffer::DeleteAllPackets(&packet_list);
541 return kRedundancySplitError;
542 }
543 // Only accept a few RED payloads of the same type as the main data,
544 // DTMF events and CNG.
545 payload_splitter_->CheckRedPayloads(&packet_list, *decoder_database_);
546 // Update the stored main payload header since the main payload has now
547 // changed.
548 memcpy(&main_header, &packet_list.front()->header, sizeof(main_header));
549 }
550
551 // Check payload types.
552 if (decoder_database_->CheckPayloadTypes(packet_list) ==
553 DecoderDatabase::kDecoderNotFound) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000554 PacketBuffer::DeleteAllPackets(&packet_list);
555 return kUnknownRtpPayloadType;
556 }
557
558 // Scale timestamp to internal domain (only for some codecs).
559 timestamp_scaler_->ToInternal(&packet_list);
560
561 // Process DTMF payloads. Cycle through the list of packets, and pick out any
562 // DTMF payloads found.
563 PacketList::iterator it = packet_list.begin();
564 while (it != packet_list.end()) {
565 Packet* current_packet = (*it);
566 assert(current_packet);
567 assert(current_packet->payload);
568 if (decoder_database_->IsDtmf(current_packet->header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000569 assert(!current_packet->sync_packet); // We had a sanity check for this.
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000570 DtmfEvent event;
571 int ret = DtmfBuffer::ParseEvent(
572 current_packet->header.timestamp,
573 current_packet->payload,
574 current_packet->payload_length,
575 &event);
576 if (ret != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000577 PacketBuffer::DeleteAllPackets(&packet_list);
578 return kDtmfParsingError;
579 }
580 if (dtmf_buffer_->InsertEvent(event) != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000581 PacketBuffer::DeleteAllPackets(&packet_list);
582 return kDtmfInsertError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000583 }
584 // TODO(hlundin): Let the destructor of Packet handle the payload.
585 delete [] current_packet->payload;
586 delete current_packet;
587 it = packet_list.erase(it);
588 } else {
589 ++it;
590 }
591 }
592
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000593 // Check for FEC in packets, and separate payloads into several packets.
594 int ret = payload_splitter_->SplitFec(&packet_list, decoder_database_.get());
595 if (ret != PayloadSplitter::kOK) {
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000596 PacketBuffer::DeleteAllPackets(&packet_list);
597 switch (ret) {
598 case PayloadSplitter::kUnknownPayloadType:
599 return kUnknownRtpPayloadType;
600 default:
601 return kOtherError;
602 }
603 }
604
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000605 // Split payloads into smaller chunks. This also verifies that all payloads
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000606 // are of a known payload type. SplitAudio() method is protected against
607 // sync-packets.
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +0000608 ret = payload_splitter_->SplitAudio(&packet_list, *decoder_database_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000609 if (ret != PayloadSplitter::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000610 PacketBuffer::DeleteAllPackets(&packet_list);
611 switch (ret) {
612 case PayloadSplitter::kUnknownPayloadType:
613 return kUnknownRtpPayloadType;
614 case PayloadSplitter::kFrameSplitError:
615 return kFrameSplitError;
616 default:
617 return kOtherError;
618 }
619 }
620
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000621 // Update bandwidth estimate, if the packet is not sync-packet.
622 if (!packet_list.empty() && !packet_list.front()->sync_packet) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000623 // The list can be empty here if we got nothing but DTMF payloads.
624 AudioDecoder* decoder =
625 decoder_database_->GetDecoder(main_header.payloadType);
626 assert(decoder); // Should always get a valid object, since we have
627 // already checked that the payload types are known.
628 decoder->IncomingPacket(packet_list.front()->payload,
629 packet_list.front()->payload_length,
630 packet_list.front()->header.sequenceNumber,
631 packet_list.front()->header.timestamp,
632 receive_timestamp);
633 }
634
henrik.lundin48ed9302015-10-29 05:36:24 -0700635 if (nack_enabled_) {
636 RTC_DCHECK(nack_);
637 if (update_sample_rate_and_channels) {
638 nack_->Reset();
639 }
640 nack_->UpdateLastReceivedPacket(packet_list.front()->header.sequenceNumber,
641 packet_list.front()->header.timestamp);
642 }
643
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000644 // Insert packets in buffer.
henrik.lundin116c84e2015-08-27 13:14:48 -0700645 const size_t buffer_length_before_insert =
646 packet_buffer_->NumPacketsInBuffer();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000647 ret = packet_buffer_->InsertPacketList(
648 &packet_list,
649 *decoder_database_,
650 &current_rtp_payload_type_,
651 &current_cng_rtp_payload_type_);
652 if (ret == PacketBuffer::kFlushed) {
653 // Reset DSP timestamp etc. if packet buffer flushed.
654 new_codec_ = true;
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000655 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000656 } else if (ret != PacketBuffer::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000657 PacketBuffer::DeleteAllPackets(&packet_list);
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000658 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000659 }
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000660
661 if (first_packet_) {
662 first_packet_ = false;
663 // Update the codec on the next GetAudio call.
664 new_codec_ = true;
665 }
666
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000667 if (current_rtp_payload_type_ != 0xFF) {
668 const DecoderDatabase::DecoderInfo* dec_info =
669 decoder_database_->GetDecoderInfo(current_rtp_payload_type_);
670 if (!dec_info) {
671 assert(false); // Already checked that the payload type is known.
672 }
673 }
674
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000675 if (update_sample_rate_and_channels && !packet_buffer_->Empty()) {
676 // We do not use |current_rtp_payload_type_| to |set payload_type|, but
677 // get the next RTP header from |packet_buffer_| to obtain the payload type.
678 // The reason for it is the following corner case. If NetEq receives a
679 // CNG packet with a sample rate different than the current CNG then it
680 // flushes its buffer, assuming send codec must have been changed. However,
681 // payload type of the hypothetically new send codec is not known.
682 const RTPHeader* rtp_header = packet_buffer_->NextRtpHeader();
683 assert(rtp_header);
684 int payload_type = rtp_header->payloadType;
685 AudioDecoder* decoder = decoder_database_->GetDecoder(payload_type);
686 assert(decoder); // Payloads are already checked to be valid.
687 const DecoderDatabase::DecoderInfo* decoder_info =
688 decoder_database_->GetDecoderInfo(payload_type);
689 assert(decoder_info);
690 if (decoder_info->fs_hz != fs_hz_ ||
henrik.lundin48ed9302015-10-29 05:36:24 -0700691 decoder->Channels() != algorithm_buffer_->Channels()) {
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +0000692 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->Channels());
henrik.lundin48ed9302015-10-29 05:36:24 -0700693 }
694 if (nack_enabled_) {
695 RTC_DCHECK(nack_);
696 // Update the sample rate even if the rate is not new, because of Reset().
697 nack_->UpdateSampleRate(fs_hz_);
698 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000699 }
700
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000701 // TODO(hlundin): Move this code to DelayManager class.
702 const DecoderDatabase::DecoderInfo* dec_info =
703 decoder_database_->GetDecoderInfo(main_header.payloadType);
704 assert(dec_info); // Already checked that the payload type is known.
705 delay_manager_->LastDecoderType(dec_info->codec_type);
706 if (delay_manager_->last_pack_cng_or_dtmf() == 0) {
707 // Calculate the total speech length carried in each packet.
henrik.lundin116c84e2015-08-27 13:14:48 -0700708 const size_t buffer_length_after_insert =
709 packet_buffer_->NumPacketsInBuffer();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000710
henrik.lundin116c84e2015-08-27 13:14:48 -0700711 if (buffer_length_after_insert > buffer_length_before_insert) {
712 const size_t packet_length_samples =
713 (buffer_length_after_insert - buffer_length_before_insert) *
714 decoder_frame_length_;
715 if (packet_length_samples != decision_logic_->packet_length_samples()) {
716 decision_logic_->set_packet_length_samples(packet_length_samples);
717 delay_manager_->SetPacketAudioLength(
718 rtc::checked_cast<int>((1000 * packet_length_samples) / fs_hz_));
719 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000720 }
721
722 // Update statistics.
pbos@webrtc.org0946a562013-04-09 00:28:06 +0000723 if ((int32_t) (main_header.timestamp - timestamp_) >= 0 &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000724 !new_codec_) {
725 // Only update statistics if incoming packet is not older than last played
726 // out packet, and if new codec flag is not set.
727 delay_manager_->Update(main_header.sequenceNumber, main_header.timestamp,
728 fs_hz_);
729 }
730 } else if (delay_manager_->last_pack_cng_or_dtmf() == -1) {
731 // This is first "normal" packet after CNG or DTMF.
732 // Reset packet time counter and measure time until next packet,
733 // but don't update statistics.
734 delay_manager_->set_last_pack_cng_or_dtmf(0);
735 delay_manager_->ResetPacketIatCount();
736 }
737 return 0;
738}
739
Peter Kasting728d9032015-06-11 14:31:38 -0700740int NetEqImpl::GetAudioInternal(size_t max_length,
741 int16_t* output,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700742 size_t* samples_per_channel,
Peter Kasting728d9032015-06-11 14:31:38 -0700743 int* num_channels) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000744 PacketList packet_list;
745 DtmfEvent dtmf_event;
746 Operations operation;
747 bool play_dtmf;
748 int return_value = GetDecision(&operation, &packet_list, &dtmf_event,
749 &play_dtmf);
750 if (return_value != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000751 last_mode_ = kModeError;
752 return return_value;
753 }
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000754 LOG(LS_VERBOSE) << "GetDecision returned operation=" << operation <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000755 " and " << packet_list.size() << " packet(s)";
756
757 AudioDecoder::SpeechType speech_type;
758 int length = 0;
759 int decode_return_value = Decode(&packet_list, &operation,
760 &length, &speech_type);
761
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000762 assert(vad_.get());
763 bool sid_frame_available =
764 (operation == kRfc3389Cng && !packet_list.empty());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700765 vad_->Update(decoded_buffer_.get(), static_cast<size_t>(length), speech_type,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000766 sid_frame_available, fs_hz_);
767
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000768 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000769 switch (operation) {
770 case kNormal: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000771 DoNormal(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000772 break;
773 }
774 case kMerge: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000775 DoMerge(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000776 break;
777 }
778 case kExpand: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000779 return_value = DoExpand(play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000780 break;
781 }
Henrik Lundincf808d22015-05-27 14:33:29 +0200782 case kAccelerate:
783 case kFastAccelerate: {
784 const bool fast_accelerate =
785 enable_fast_accelerate_ && (operation == kFastAccelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000786 return_value = DoAccelerate(decoded_buffer_.get(), length, speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +0200787 play_dtmf, fast_accelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000788 break;
789 }
790 case kPreemptiveExpand: {
791 return_value = DoPreemptiveExpand(decoded_buffer_.get(), length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000792 speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000793 break;
794 }
795 case kRfc3389Cng:
796 case kRfc3389CngNoPacket: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000797 return_value = DoRfc3389Cng(&packet_list, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000798 break;
799 }
800 case kCodecInternalCng: {
801 // This handles the case when there is no transmission and the decoder
802 // should produce internal comfort noise.
803 // TODO(hlundin): Write test for codec-internal CNG.
minyuel6d92bf52015-09-23 15:20:39 +0200804 DoCodecInternalCng(decoded_buffer_.get(), length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000805 break;
806 }
807 case kDtmf: {
808 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000809 return_value = DoDtmf(dtmf_event, &play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000810 break;
811 }
812 case kAlternativePlc: {
813 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000814 DoAlternativePlc(false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000815 break;
816 }
817 case kAlternativePlcIncreaseTimestamp: {
818 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000819 DoAlternativePlc(true);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000820 break;
821 }
822 case kAudioRepetitionIncreaseTimestamp: {
823 // TODO(hlundin): Write test for this.
Peter Kastingb7e50542015-06-11 12:55:50 -0700824 sync_buffer_->IncreaseEndTimestamp(
825 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000826 // Skipping break on purpose. Execution should move on into the
827 // next case.
kjellander@webrtc.org7d2b6a92015-01-28 18:37:58 +0000828 FALLTHROUGH();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000829 }
830 case kAudioRepetition: {
831 // TODO(hlundin): Write test for this.
832 // Copy last |output_size_samples_| from |sync_buffer_| to
833 // |algorithm_buffer|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000834 algorithm_buffer_->PushBackFromIndex(
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000835 *sync_buffer_, sync_buffer_->Size() - output_size_samples_);
836 expand_->Reset();
837 break;
838 }
839 case kUndefined: {
Henrik Lundind67a2192015-08-03 12:54:37 +0200840 LOG(LS_ERROR) << "Invalid operation kUndefined.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000841 assert(false); // This should not happen.
842 last_mode_ = kModeError;
843 return kInvalidOperation;
844 }
845 } // End of switch.
846 if (return_value < 0) {
847 return return_value;
848 }
849
850 if (last_mode_ != kModeRfc3389Cng) {
851 comfort_noise_->Reset();
852 }
853
854 // Copy from |algorithm_buffer| to |sync_buffer_|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000855 sync_buffer_->PushBack(*algorithm_buffer_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000856
857 // Extract data from |sync_buffer_| to |output|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000858 size_t num_output_samples_per_channel = output_size_samples_;
859 size_t num_output_samples = output_size_samples_ * sync_buffer_->Channels();
860 if (num_output_samples > max_length) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000861 LOG(LS_WARNING) << "Output array is too short. " << max_length << " < " <<
862 output_size_samples_ << " * " << sync_buffer_->Channels();
863 num_output_samples = max_length;
Peter Kastingdce40cf2015-08-24 14:52:23 -0700864 num_output_samples_per_channel = max_length / sync_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000865 }
Peter Kastingdce40cf2015-08-24 14:52:23 -0700866 const size_t samples_from_sync =
867 sync_buffer_->GetNextAudioInterleaved(num_output_samples_per_channel,
868 output);
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000869 *num_channels = static_cast<int>(sync_buffer_->Channels());
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000870 LOG(LS_VERBOSE) << "Sync buffer (" << *num_channels << " channel(s)):" <<
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000871 " insert " << algorithm_buffer_->Size() << " samples, extract " <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000872 samples_from_sync << " samples";
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200873 if (sync_buffer_->FutureLength() < expand_->overlap_length()) {
874 // The sync buffer should always contain |overlap_length| samples, but now
875 // too many samples have been extracted. Reinstall the |overlap_length|
876 // lookahead by moving the index.
877 const size_t missing_lookahead_samples =
878 expand_->overlap_length() - sync_buffer_->FutureLength();
henrikg91d6ede2015-09-17 00:24:34 -0700879 RTC_DCHECK_GE(sync_buffer_->next_index(), missing_lookahead_samples);
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200880 sync_buffer_->set_next_index(sync_buffer_->next_index() -
881 missing_lookahead_samples);
882 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000883 if (samples_from_sync != output_size_samples_) {
Henrik Lundind67a2192015-08-03 12:54:37 +0200884 LOG(LS_ERROR) << "samples_from_sync (" << samples_from_sync
885 << ") != output_size_samples_ (" << output_size_samples_
886 << ")";
minyue@webrtc.orgdb1cefc2013-08-13 01:39:21 +0000887 // TODO(minyue): treatment of under-run, filling zeros
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000888 memset(output, 0, num_output_samples * sizeof(int16_t));
889 *samples_per_channel = output_size_samples_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000890 return kSampleUnderrun;
891 }
892 *samples_per_channel = output_size_samples_;
893
894 // Should always have overlap samples left in the |sync_buffer_|.
henrikg91d6ede2015-09-17 00:24:34 -0700895 RTC_DCHECK_GE(sync_buffer_->FutureLength(), expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000896
897 if (play_dtmf) {
898 return_value = DtmfOverdub(dtmf_event, sync_buffer_->Channels(), output);
899 }
900
901 // Update the background noise parameters if last operation wrote data
902 // straight from the decoder to the |sync_buffer_|. That is, none of the
903 // operations that modify the signal can be followed by a parameter update.
904 if ((last_mode_ == kModeNormal) ||
905 (last_mode_ == kModeAccelerateFail) ||
906 (last_mode_ == kModePreemptiveExpandFail) ||
907 (last_mode_ == kModeRfc3389Cng) ||
908 (last_mode_ == kModeCodecInternalCng)) {
909 background_noise_->Update(*sync_buffer_, *vad_.get());
910 }
911
912 if (operation == kDtmf) {
913 // DTMF data was written the end of |sync_buffer_|.
914 // Update index to end of DTMF data in |sync_buffer_|.
915 sync_buffer_->set_dtmf_index(sync_buffer_->Size());
916 }
917
henrik.lundin@webrtc.orged865b52014-03-06 10:28:07 +0000918 if (last_mode_ != kModeExpand) {
919 // If last operation was not expand, calculate the |playout_timestamp_| from
920 // the |sync_buffer_|. However, do not update the |playout_timestamp_| if it
921 // would be moved "backwards".
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000922 uint32_t temp_timestamp = sync_buffer_->end_timestamp() -
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000923 static_cast<uint32_t>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000924 if (static_cast<int32_t>(temp_timestamp - playout_timestamp_) > 0) {
925 playout_timestamp_ = temp_timestamp;
926 }
927 } else {
928 // Use dead reckoning to estimate the |playout_timestamp_|.
Peter Kastingb7e50542015-06-11 12:55:50 -0700929 playout_timestamp_ += static_cast<uint32_t>(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000930 }
931
932 if (decode_return_value) return decode_return_value;
933 return return_value;
934}
935
936int NetEqImpl::GetDecision(Operations* operation,
937 PacketList* packet_list,
938 DtmfEvent* dtmf_event,
939 bool* play_dtmf) {
940 // Initialize output variables.
941 *play_dtmf = false;
942 *operation = kUndefined;
943
944 // Increment time counters.
945 packet_buffer_->IncrementWaitingTimes();
946 stats_.IncreaseCounter(output_size_samples_, fs_hz_);
947
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000948 assert(sync_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000949 uint32_t end_timestamp = sync_buffer_->end_timestamp();
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +0000950 if (!new_codec_) {
951 const uint32_t five_seconds_samples = 5 * fs_hz_;
952 packet_buffer_->DiscardOldPackets(end_timestamp, five_seconds_samples);
953 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000954 const RTPHeader* header = packet_buffer_->NextRtpHeader();
955
henrik.lundin@webrtc.orgca8cb952014-03-12 10:26:52 +0000956 if (decision_logic_->CngRfc3389On() || last_mode_ == kModeRfc3389Cng) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000957 // Because of timestamp peculiarities, we have to "manually" disallow using
958 // a CNG packet with the same timestamp as the one that was last played.
959 // This can happen when using redundancy and will cause the timing to shift.
henrik.lundin@webrtc.org24779fe2014-03-14 12:40:05 +0000960 while (header && decoder_database_->IsComfortNoise(header->payloadType) &&
961 (end_timestamp >= header->timestamp ||
962 end_timestamp + decision_logic_->generated_noise_samples() >
963 header->timestamp)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000964 // Don't use this packet, discard it.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000965 if (packet_buffer_->DiscardNextPacket() != PacketBuffer::kOK) {
966 assert(false); // Must be ok by design.
967 }
968 // Check buffer again.
969 if (!new_codec_) {
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +0000970 packet_buffer_->DiscardOldPackets(end_timestamp, 5 * fs_hz_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000971 }
972 header = packet_buffer_->NextRtpHeader();
973 }
974 }
975
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000976 assert(expand_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000977 const int samples_left = static_cast<int>(sync_buffer_->FutureLength() -
978 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000979 if (last_mode_ == kModeAccelerateSuccess ||
980 last_mode_ == kModeAccelerateLowEnergy ||
981 last_mode_ == kModePreemptiveExpandSuccess ||
982 last_mode_ == kModePreemptiveExpandLowEnergy) {
983 // Subtract (samples_left + output_size_samples_) from sampleMemory.
Peter Kastingdce40cf2015-08-24 14:52:23 -0700984 decision_logic_->AddSampleMemory(
985 -(samples_left + rtc::checked_cast<int>(output_size_samples_)));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000986 }
987
988 // Check if it is time to play a DTMF event.
Peter Kastingb7e50542015-06-11 12:55:50 -0700989 if (dtmf_buffer_->GetEvent(
990 static_cast<uint32_t>(
991 end_timestamp + decision_logic_->generated_noise_samples()),
992 dtmf_event)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000993 *play_dtmf = true;
994 }
995
996 // Get instruction.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000997 assert(sync_buffer_.get());
998 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000999 *operation = decision_logic_->GetDecision(*sync_buffer_,
1000 *expand_,
1001 decoder_frame_length_,
1002 header,
1003 last_mode_,
1004 *play_dtmf,
1005 &reset_decoder_);
1006
1007 // Check if we already have enough samples in the |sync_buffer_|. If so,
1008 // change decision to normal, unless the decision was merge, accelerate, or
1009 // preemptive expand.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001010 if (samples_left >= rtc::checked_cast<int>(output_size_samples_) &&
1011 *operation != kMerge &&
1012 *operation != kAccelerate &&
1013 *operation != kFastAccelerate &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001014 *operation != kPreemptiveExpand) {
1015 *operation = kNormal;
1016 return 0;
1017 }
1018
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001019 decision_logic_->ExpandDecision(*operation);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001020
1021 // Check conditions for reset.
1022 if (new_codec_ || *operation == kUndefined) {
1023 // The only valid reason to get kUndefined is that new_codec_ is set.
1024 assert(new_codec_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001025 if (*play_dtmf && !header) {
1026 timestamp_ = dtmf_event->timestamp;
1027 } else {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001028 if (!header) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001029 LOG(LS_ERROR) << "Packet missing where it shouldn't.";
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001030 return -1;
1031 }
1032 timestamp_ = header->timestamp;
1033 if (*operation == kRfc3389CngNoPacket
1034#ifndef LEGACY_BITEXACT
1035 // Without this check, it can happen that a non-CNG packet is sent to
1036 // the CNG decoder as if it was a SID frame. This is clearly a bug,
1037 // but is kept for now to maintain bit-exactness with the test
1038 // vectors.
1039 && decoder_database_->IsComfortNoise(header->payloadType)
1040#endif
1041 ) {
1042 // Change decision to CNG packet, since we do have a CNG packet, but it
1043 // was considered too early to use. Now, use it anyway.
1044 *operation = kRfc3389Cng;
1045 } else if (*operation != kRfc3389Cng) {
1046 *operation = kNormal;
1047 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001048 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001049 // Adjust |sync_buffer_| timestamp before setting |end_timestamp| to the
1050 // new value.
1051 sync_buffer_->IncreaseEndTimestamp(timestamp_ - end_timestamp);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001052 end_timestamp = timestamp_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001053 new_codec_ = false;
1054 decision_logic_->SoftReset();
1055 buffer_level_filter_->Reset();
1056 delay_manager_->Reset();
1057 stats_.ResetMcu();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001058 }
1059
Peter Kastingdce40cf2015-08-24 14:52:23 -07001060 size_t required_samples = output_size_samples_;
1061 const size_t samples_10_ms = static_cast<size_t>(80 * fs_mult_);
1062 const size_t samples_20_ms = 2 * samples_10_ms;
1063 const size_t samples_30_ms = 3 * samples_10_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001064
1065 switch (*operation) {
1066 case kExpand: {
1067 timestamp_ = end_timestamp;
1068 return 0;
1069 }
1070 case kRfc3389CngNoPacket:
1071 case kCodecInternalCng: {
1072 return 0;
1073 }
1074 case kDtmf: {
1075 // TODO(hlundin): Write test for this.
1076 // Update timestamp.
1077 timestamp_ = end_timestamp;
1078 if (decision_logic_->generated_noise_samples() > 0 &&
1079 last_mode_ != kModeDtmf) {
1080 // Make a jump in timestamp due to the recently played comfort noise.
Peter Kastingb7e50542015-06-11 12:55:50 -07001081 uint32_t timestamp_jump =
1082 static_cast<uint32_t>(decision_logic_->generated_noise_samples());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001083 sync_buffer_->IncreaseEndTimestamp(timestamp_jump);
1084 timestamp_ += timestamp_jump;
1085 }
1086 decision_logic_->set_generated_noise_samples(0);
1087 return 0;
1088 }
Henrik Lundincf808d22015-05-27 14:33:29 +02001089 case kAccelerate:
1090 case kFastAccelerate: {
1091 // In order to do an accelerate we need at least 30 ms of audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001092 if (samples_left >= static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001093 // Already have enough data, so we do not need to extract any more.
1094 decision_logic_->set_sample_memory(samples_left);
1095 decision_logic_->set_prev_time_scale(true);
1096 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001097 } else if (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001098 decoder_frame_length_ >= samples_30_ms) {
1099 // Avoid decoding more data as it might overflow the playout buffer.
1100 *operation = kNormal;
1101 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001102 } else if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001103 decoder_frame_length_ < samples_30_ms) {
1104 // Build up decoded data by decoding at least 20 ms of audio data. Do
1105 // not perform accelerate yet, but wait until we only need to do one
1106 // decoding.
1107 required_samples = 2 * output_size_samples_;
1108 *operation = kNormal;
1109 }
1110 // If none of the above is true, we have one of two possible situations:
1111 // (1) 20 ms <= samples_left < 30 ms and decoder_frame_length_ < 30 ms; or
1112 // (2) samples_left < 10 ms and decoder_frame_length_ >= 30 ms.
1113 // In either case, we move on with the accelerate decision, and decode one
1114 // frame now.
1115 break;
1116 }
1117 case kPreemptiveExpand: {
1118 // In order to do a preemptive expand we need at least 30 ms of decoded
1119 // audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001120 if ((samples_left >= static_cast<int>(samples_30_ms)) ||
1121 (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001122 decoder_frame_length_ >= samples_30_ms)) {
1123 // Already have enough data, so we do not need to extract any more.
1124 // Or, avoid decoding more data as it might overflow the playout buffer.
1125 // Still try preemptive expand, though.
1126 decision_logic_->set_sample_memory(samples_left);
1127 decision_logic_->set_prev_time_scale(true);
1128 return 0;
1129 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07001130 if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001131 decoder_frame_length_ < samples_30_ms) {
1132 // Build up decoded data by decoding at least 20 ms of audio data.
1133 // Still try to perform preemptive expand.
1134 required_samples = 2 * output_size_samples_;
1135 }
1136 // Move on with the preemptive expand decision.
1137 break;
1138 }
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001139 case kMerge: {
1140 required_samples =
1141 std::max(merge_->RequiredFutureSamples(), required_samples);
1142 break;
1143 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001144 default: {
1145 // Do nothing.
1146 }
1147 }
1148
1149 // Get packets from buffer.
1150 int extracted_samples = 0;
1151 if (header &&
1152 *operation != kAlternativePlc &&
1153 *operation != kAlternativePlcIncreaseTimestamp &&
1154 *operation != kAudioRepetition &&
1155 *operation != kAudioRepetitionIncreaseTimestamp) {
1156 sync_buffer_->IncreaseEndTimestamp(header->timestamp - end_timestamp);
1157 if (decision_logic_->CngOff()) {
1158 // Adjustment of timestamp only corresponds to an actual packet loss
1159 // if comfort noise is not played. If comfort noise was just played,
1160 // this adjustment of timestamp is only done to get back in sync with the
1161 // stream timestamp; no loss to report.
1162 stats_.LostSamples(header->timestamp - end_timestamp);
1163 }
1164
1165 if (*operation != kRfc3389Cng) {
1166 // We are about to decode and use a non-CNG packet.
1167 decision_logic_->SetCngOff();
1168 }
1169 // Reset CNG timestamp as a new packet will be delivered.
1170 // (Also if this is a CNG packet, since playedOutTS is updated.)
1171 decision_logic_->set_generated_noise_samples(0);
1172
1173 extracted_samples = ExtractPackets(required_samples, packet_list);
1174 if (extracted_samples < 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001175 return kPacketBufferCorruption;
1176 }
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 *operation == kPreemptiveExpand) {
1181 decision_logic_->set_sample_memory(samples_left + extracted_samples);
1182 decision_logic_->set_prev_time_scale(true);
1183 }
1184
Henrik Lundincf808d22015-05-27 14:33:29 +02001185 if (*operation == kAccelerate || *operation == kFastAccelerate) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001186 // Check that we have enough data (30ms) to do accelerate.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001187 if (extracted_samples + samples_left < static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001188 // TODO(hlundin): Write test for this.
1189 // Not enough, do normal operation instead.
1190 *operation = kNormal;
1191 }
1192 }
1193
1194 timestamp_ = end_timestamp;
1195 return 0;
1196}
1197
1198int NetEqImpl::Decode(PacketList* packet_list, Operations* operation,
1199 int* decoded_length,
1200 AudioDecoder::SpeechType* speech_type) {
1201 *speech_type = AudioDecoder::kSpeech;
minyuel6d92bf52015-09-23 15:20:39 +02001202
1203 // When packet_list is empty, we may be in kCodecInternalCng mode, and for
1204 // that we use current active decoder.
1205 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1206
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001207 if (!packet_list->empty()) {
1208 const Packet* packet = packet_list->front();
pkasting@chromium.org0e81fdf2015-02-02 23:54:03 +00001209 uint8_t payload_type = packet->header.payloadType;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001210 if (!decoder_database_->IsComfortNoise(payload_type)) {
1211 decoder = decoder_database_->GetDecoder(payload_type);
1212 assert(decoder);
1213 if (!decoder) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001214 LOG(LS_WARNING) << "Unknown payload type "
1215 << static_cast<int>(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001216 PacketBuffer::DeleteAllPackets(packet_list);
1217 return kDecoderNotFound;
1218 }
1219 bool decoder_changed;
1220 decoder_database_->SetActiveDecoder(payload_type, &decoder_changed);
1221 if (decoder_changed) {
1222 // We have a new decoder. Re-init some values.
1223 const DecoderDatabase::DecoderInfo* decoder_info = decoder_database_
1224 ->GetDecoderInfo(payload_type);
1225 assert(decoder_info);
1226 if (!decoder_info) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001227 LOG(LS_WARNING) << "Unknown payload type "
1228 << static_cast<int>(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001229 PacketBuffer::DeleteAllPackets(packet_list);
1230 return kDecoderNotFound;
1231 }
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001232 // If sampling rate or number of channels has changed, we need to make
1233 // a reset.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001234 if (decoder_info->fs_hz != fs_hz_ ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001235 decoder->Channels() != algorithm_buffer_->Channels()) {
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001236 // TODO(tlegrand): Add unittest to cover this event.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001237 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->Channels());
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001238 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001239 sync_buffer_->set_end_timestamp(timestamp_);
1240 playout_timestamp_ = timestamp_;
1241 }
1242 }
1243 }
1244
1245 if (reset_decoder_) {
1246 // TODO(hlundin): Write test for this.
Karl Wiberg43766482015-08-27 15:22:11 +02001247 if (decoder)
1248 decoder->Reset();
1249
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001250 // Reset comfort noise decoder.
1251 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02001252 if (cng_decoder)
1253 cng_decoder->Reset();
1254
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001255 reset_decoder_ = false;
1256 }
1257
1258#ifdef LEGACY_BITEXACT
1259 // Due to a bug in old SignalMCU, it could happen that CNG operation was
1260 // decided, but a speech packet was provided. The speech packet will be used
1261 // to update the comfort noise decoder, as if it was a SID frame, which is
1262 // clearly wrong.
1263 if (*operation == kRfc3389Cng) {
1264 return 0;
1265 }
1266#endif
1267
1268 *decoded_length = 0;
1269 // Update codec-internal PLC state.
1270 if ((*operation == kMerge) && decoder && decoder->HasDecodePlc()) {
1271 decoder->DecodePlc(1, &decoded_buffer_[*decoded_length]);
1272 }
1273
minyuel6d92bf52015-09-23 15:20:39 +02001274 int return_value;
1275 if (*operation == kCodecInternalCng) {
1276 RTC_DCHECK(packet_list->empty());
1277 return_value = DecodeCng(decoder, decoded_length, speech_type);
1278 } else {
1279 return_value = DecodeLoop(packet_list, *operation, decoder,
1280 decoded_length, speech_type);
1281 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001282
1283 if (*decoded_length < 0) {
1284 // Error returned from the decoder.
1285 *decoded_length = 0;
Peter Kastingb7e50542015-06-11 12:55:50 -07001286 sync_buffer_->IncreaseEndTimestamp(
1287 static_cast<uint32_t>(decoder_frame_length_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001288 int error_code = 0;
1289 if (decoder)
1290 error_code = decoder->ErrorCode();
1291 if (error_code != 0) {
1292 // Got some error code from the decoder.
1293 decoder_error_code_ = error_code;
1294 return_value = kDecoderErrorCode;
Henrik Lundind67a2192015-08-03 12:54:37 +02001295 LOG(LS_WARNING) << "Decoder returned error code: " << error_code;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001296 } else {
1297 // Decoder does not implement error codes. Return generic error.
1298 return_value = kOtherDecoderError;
Henrik Lundind67a2192015-08-03 12:54:37 +02001299 LOG(LS_WARNING) << "Decoder error (no error code)";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001300 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001301 *operation = kExpand; // Do expansion to get data instead.
1302 }
1303 if (*speech_type != AudioDecoder::kComfortNoise) {
1304 // Don't increment timestamp if codec returned CNG speech type
1305 // since in this case, the we will increment the CNGplayedTS counter.
1306 // Increase with number of samples per channel.
1307 assert(*decoded_length == 0 ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001308 (decoder && decoder->Channels() == sync_buffer_->Channels()));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001309 sync_buffer_->IncreaseEndTimestamp(
1310 *decoded_length / static_cast<int>(sync_buffer_->Channels()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001311 }
1312 return return_value;
1313}
1314
minyuel6d92bf52015-09-23 15:20:39 +02001315int NetEqImpl::DecodeCng(AudioDecoder* decoder, int* decoded_length,
1316 AudioDecoder::SpeechType* speech_type) {
1317 if (!decoder) {
1318 // This happens when active decoder is not defined.
1319 *decoded_length = -1;
1320 return 0;
1321 }
1322
1323 while (*decoded_length < rtc::checked_cast<int>(output_size_samples_)) {
1324 const int length = decoder->Decode(
1325 nullptr, 0, fs_hz_,
1326 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1327 &decoded_buffer_[*decoded_length], speech_type);
1328 if (length > 0) {
1329 *decoded_length += length;
1330 LOG(LS_VERBOSE) << "Decoded " << length << " CNG samples";
1331 } else {
1332 // Error.
1333 LOG(LS_WARNING) << "Failed to decode CNG";
1334 *decoded_length = -1;
1335 break;
1336 }
1337 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1338 // Guard against overflow.
1339 LOG(LS_WARNING) << "Decoded too much CNG.";
1340 return kDecodedTooMuch;
1341 }
1342 }
1343 return 0;
1344}
1345
1346int NetEqImpl::DecodeLoop(PacketList* packet_list, const Operations& operation,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001347 AudioDecoder* decoder, int* decoded_length,
1348 AudioDecoder::SpeechType* speech_type) {
1349 Packet* packet = NULL;
1350 if (!packet_list->empty()) {
1351 packet = packet_list->front();
1352 }
minyuel6d92bf52015-09-23 15:20:39 +02001353
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001354 // Do decoding.
1355 while (packet &&
1356 !decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1357 assert(decoder); // At this point, we must have a decoder object.
1358 // The number of channels in the |sync_buffer_| should be the same as the
1359 // number decoder channels.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001360 assert(sync_buffer_->Channels() == decoder->Channels());
1361 assert(decoded_buffer_length_ >= kMaxFrameSize * decoder->Channels());
minyuel6d92bf52015-09-23 15:20:39 +02001362 assert(operation == kNormal || operation == kAccelerate ||
1363 operation == kFastAccelerate || operation == kMerge ||
1364 operation == kPreemptiveExpand);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001365 packet_list->pop_front();
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001366 size_t payload_length = packet->payload_length;
Peter Kasting36b7cc32015-06-11 19:57:18 -07001367 int decode_length;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +00001368 if (packet->sync_packet) {
1369 // Decode to silence with the same frame size as the last decode.
1370 LOG(LS_VERBOSE) << "Decoding sync-packet: " <<
1371 " ts=" << packet->header.timestamp <<
1372 ", sn=" << packet->header.sequenceNumber <<
1373 ", pt=" << static_cast<int>(packet->header.payloadType) <<
1374 ", ssrc=" << packet->header.ssrc <<
1375 ", len=" << packet->payload_length;
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001376 memset(&decoded_buffer_[*decoded_length], 0,
1377 decoder_frame_length_ * decoder->Channels() *
1378 sizeof(decoded_buffer_[0]));
Peter Kastingdce40cf2015-08-24 14:52:23 -07001379 decode_length = rtc::checked_cast<int>(decoder_frame_length_);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +00001380 } else if (!packet->primary) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001381 // This is a redundant payload; call the special decoder method.
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +00001382 LOG(LS_VERBOSE) << "Decoding packet (redundant):" <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001383 " ts=" << packet->header.timestamp <<
1384 ", sn=" << packet->header.sequenceNumber <<
1385 ", pt=" << static_cast<int>(packet->header.payloadType) <<
1386 ", ssrc=" << packet->header.ssrc <<
1387 ", len=" << packet->payload_length;
1388 decode_length = decoder->DecodeRedundant(
henrik.lundin@webrtc.org1eda4e32015-02-25 10:02:29 +00001389 packet->payload, packet->payload_length, fs_hz_,
minyue@webrtc.org7f7d7e32015-03-16 12:30:37 +00001390 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001391 &decoded_buffer_[*decoded_length], speech_type);
1392 } else {
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +00001393 LOG(LS_VERBOSE) << "Decoding packet: ts=" << packet->header.timestamp <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001394 ", sn=" << packet->header.sequenceNumber <<
1395 ", pt=" << static_cast<int>(packet->header.payloadType) <<
1396 ", ssrc=" << packet->header.ssrc <<
1397 ", len=" << packet->payload_length;
henrik.lundin@webrtc.org1eda4e32015-02-25 10:02:29 +00001398 decode_length =
minyue@webrtc.org7f7d7e32015-03-16 12:30:37 +00001399 decoder->Decode(
1400 packet->payload, packet->payload_length, fs_hz_,
1401 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1402 &decoded_buffer_[*decoded_length], speech_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001403 }
1404
1405 delete[] packet->payload;
1406 delete packet;
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001407 packet = NULL;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001408 if (decode_length > 0) {
1409 *decoded_length += decode_length;
1410 // Update |decoder_frame_length_| with number of samples per channel.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001411 decoder_frame_length_ =
Peter Kastingdce40cf2015-08-24 14:52:23 -07001412 static_cast<size_t>(decode_length) / decoder->Channels();
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001413 LOG(LS_VERBOSE) << "Decoded " << decode_length << " samples ("
1414 << decoder->Channels() << " channel(s) -> "
1415 << decoder_frame_length_ << " samples per channel)";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001416 } else if (decode_length < 0) {
1417 // Error.
Henrik Lundind67a2192015-08-03 12:54:37 +02001418 LOG(LS_WARNING) << "Decode " << decode_length << " " << payload_length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001419 *decoded_length = -1;
1420 PacketBuffer::DeleteAllPackets(packet_list);
1421 break;
1422 }
1423 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1424 // Guard against overflow.
Henrik Lundind67a2192015-08-03 12:54:37 +02001425 LOG(LS_WARNING) << "Decoded too much.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001426 PacketBuffer::DeleteAllPackets(packet_list);
1427 return kDecodedTooMuch;
1428 }
1429 if (!packet_list->empty()) {
1430 packet = packet_list->front();
1431 } else {
1432 packet = NULL;
1433 }
1434 } // End of decode loop.
1435
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001436 // If the list is not empty at this point, either a decoding error terminated
1437 // the while-loop, or list must hold exactly one CNG packet.
1438 assert(packet_list->empty() || *decoded_length < 0 ||
1439 (packet_list->size() == 1 && packet &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001440 decoder_database_->IsComfortNoise(packet->header.payloadType)));
1441 return 0;
1442}
1443
1444void NetEqImpl::DoNormal(const int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001445 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001446 assert(normal_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001447 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001448 normal_->Process(decoded_buffer, decoded_length, last_mode_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001449 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001450 if (decoded_length != 0) {
1451 last_mode_ = kModeNormal;
1452 }
1453
1454 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1455 if ((speech_type == AudioDecoder::kComfortNoise)
1456 || ((last_mode_ == kModeCodecInternalCng)
1457 && (decoded_length == 0))) {
1458 // TODO(hlundin): Remove second part of || statement above.
1459 last_mode_ = kModeCodecInternalCng;
1460 }
1461
1462 if (!play_dtmf) {
1463 dtmf_tone_generator_->Reset();
1464 }
1465}
1466
1467void NetEqImpl::DoMerge(int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001468 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001469 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001470 assert(merge_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001471 size_t new_length = merge_->Process(decoded_buffer, decoded_length,
1472 mute_factor_array_.get(),
1473 algorithm_buffer_.get());
1474 size_t expand_length_correction = new_length -
1475 decoded_length / algorithm_buffer_->Channels();
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 generates only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001480 stats_.ExpandedNoiseSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001481 } else {
1482 // Expansion generates more than only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001483 stats_.ExpandedVoiceSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001484 }
1485
1486 last_mode_ = kModeMerge;
1487 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1488 if (speech_type == AudioDecoder::kComfortNoise) {
1489 last_mode_ = kModeCodecInternalCng;
1490 }
1491 expand_->Reset();
1492 if (!play_dtmf) {
1493 dtmf_tone_generator_->Reset();
1494 }
1495}
1496
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001497int NetEqImpl::DoExpand(bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001498 while ((sync_buffer_->FutureLength() - expand_->overlap_length()) <
Peter Kastingdce40cf2015-08-24 14:52:23 -07001499 output_size_samples_) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001500 algorithm_buffer_->Clear();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001501 int return_value = expand_->Process(algorithm_buffer_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001502 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001503
1504 // Update in-call and post-call statistics.
1505 if (expand_->MuteFactor(0) == 0) {
1506 // Expand operation generates only noise.
1507 stats_.ExpandedNoiseSamples(length);
1508 } else {
1509 // Expand operation generates more than only noise.
1510 stats_.ExpandedVoiceSamples(length);
1511 }
1512
1513 last_mode_ = kModeExpand;
1514
1515 if (return_value < 0) {
1516 return return_value;
1517 }
1518
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001519 sync_buffer_->PushBack(*algorithm_buffer_);
1520 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001521 }
1522 if (!play_dtmf) {
1523 dtmf_tone_generator_->Reset();
1524 }
1525 return 0;
1526}
1527
Henrik Lundincf808d22015-05-27 14:33:29 +02001528int NetEqImpl::DoAccelerate(int16_t* decoded_buffer,
1529 size_t decoded_length,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001530 AudioDecoder::SpeechType speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +02001531 bool play_dtmf,
1532 bool fast_accelerate) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001533 const size_t required_samples =
1534 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001535 size_t borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001536 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001537 size_t decoded_length_per_channel = decoded_length / num_channels;
1538 if (decoded_length_per_channel < required_samples) {
1539 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001540 borrowed_samples_per_channel = static_cast<int>(required_samples -
1541 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001542 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1543 decoded_buffer,
1544 sizeof(int16_t) * decoded_length);
1545 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1546 decoded_buffer);
1547 decoded_length = required_samples * num_channels;
1548 }
1549
Peter Kastingdce40cf2015-08-24 14:52:23 -07001550 size_t samples_removed;
Henrik Lundincf808d22015-05-27 14:33:29 +02001551 Accelerate::ReturnCodes return_code =
1552 accelerate_->Process(decoded_buffer, decoded_length, fast_accelerate,
1553 algorithm_buffer_.get(), &samples_removed);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001554 stats_.AcceleratedSamples(samples_removed);
1555 switch (return_code) {
1556 case Accelerate::kSuccess:
1557 last_mode_ = kModeAccelerateSuccess;
1558 break;
1559 case Accelerate::kSuccessLowEnergy:
1560 last_mode_ = kModeAccelerateLowEnergy;
1561 break;
1562 case Accelerate::kNoStretch:
1563 last_mode_ = kModeAccelerateFail;
1564 break;
1565 case Accelerate::kError:
1566 // TODO(hlundin): Map to kModeError instead?
1567 last_mode_ = kModeAccelerateFail;
1568 return kAccelerateError;
1569 }
1570
1571 if (borrowed_samples_per_channel > 0) {
1572 // Copy borrowed samples back to the |sync_buffer_|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001573 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001574 if (length < borrowed_samples_per_channel) {
1575 // This destroys the beginning of the buffer, but will not cause any
1576 // problems.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001577 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001578 sync_buffer_->Size() -
1579 borrowed_samples_per_channel);
1580 sync_buffer_->PushFrontZeros(borrowed_samples_per_channel - length);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001581 algorithm_buffer_->PopFront(length);
1582 assert(algorithm_buffer_->Empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001583 } else {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001584 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001585 borrowed_samples_per_channel,
1586 sync_buffer_->Size() -
1587 borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001588 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001589 }
1590 }
1591
1592 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1593 if (speech_type == AudioDecoder::kComfortNoise) {
1594 last_mode_ = kModeCodecInternalCng;
1595 }
1596 if (!play_dtmf) {
1597 dtmf_tone_generator_->Reset();
1598 }
1599 expand_->Reset();
1600 return 0;
1601}
1602
1603int NetEqImpl::DoPreemptiveExpand(int16_t* decoded_buffer,
1604 size_t decoded_length,
1605 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001606 bool play_dtmf) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001607 const size_t required_samples =
1608 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001609 size_t num_channels = algorithm_buffer_->Channels();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001610 size_t borrowed_samples_per_channel = 0;
1611 size_t old_borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001612 size_t decoded_length_per_channel = decoded_length / num_channels;
1613 if (decoded_length_per_channel < required_samples) {
1614 // Must move data from the |sync_buffer_| in order to get 30 ms.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001615 borrowed_samples_per_channel =
1616 required_samples - decoded_length_per_channel;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001617 // Calculate how many of these were already played out.
Peter Kastingf045e4d2015-06-10 21:15:38 -07001618 old_borrowed_samples_per_channel =
Peter Kastingdce40cf2015-08-24 14:52:23 -07001619 (borrowed_samples_per_channel > sync_buffer_->FutureLength()) ?
1620 (borrowed_samples_per_channel - sync_buffer_->FutureLength()) : 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001621 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1622 decoded_buffer,
1623 sizeof(int16_t) * decoded_length);
1624 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1625 decoded_buffer);
1626 decoded_length = required_samples * num_channels;
1627 }
1628
Peter Kastingdce40cf2015-08-24 14:52:23 -07001629 size_t samples_added;
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001630 PreemptiveExpand::ReturnCodes return_code = preemptive_expand_->Process(
Peter Kastingdce40cf2015-08-24 14:52:23 -07001631 decoded_buffer, decoded_length,
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001632 old_borrowed_samples_per_channel,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001633 algorithm_buffer_.get(), &samples_added);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001634 stats_.PreemptiveExpandedSamples(samples_added);
1635 switch (return_code) {
1636 case PreemptiveExpand::kSuccess:
1637 last_mode_ = kModePreemptiveExpandSuccess;
1638 break;
1639 case PreemptiveExpand::kSuccessLowEnergy:
1640 last_mode_ = kModePreemptiveExpandLowEnergy;
1641 break;
1642 case PreemptiveExpand::kNoStretch:
1643 last_mode_ = kModePreemptiveExpandFail;
1644 break;
1645 case PreemptiveExpand::kError:
1646 // TODO(hlundin): Map to kModeError instead?
1647 last_mode_ = kModePreemptiveExpandFail;
1648 return kPreemptiveExpandError;
1649 }
1650
1651 if (borrowed_samples_per_channel > 0) {
1652 // Copy borrowed samples back to the |sync_buffer_|.
1653 sync_buffer_->ReplaceAtIndex(
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001654 *algorithm_buffer_, borrowed_samples_per_channel,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001655 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001656 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001657 }
1658
1659 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1660 if (speech_type == AudioDecoder::kComfortNoise) {
1661 last_mode_ = kModeCodecInternalCng;
1662 }
1663 if (!play_dtmf) {
1664 dtmf_tone_generator_->Reset();
1665 }
1666 expand_->Reset();
1667 return 0;
1668}
1669
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001670int NetEqImpl::DoRfc3389Cng(PacketList* packet_list, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001671 if (!packet_list->empty()) {
1672 // Must have exactly one SID frame at this point.
1673 assert(packet_list->size() == 1);
1674 Packet* packet = packet_list->front();
1675 packet_list->pop_front();
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001676 if (!decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1677#ifdef LEGACY_BITEXACT
1678 // This can happen due to a bug in GetDecision. Change the payload type
1679 // to a CNG type, and move on. Note that this means that we are in fact
1680 // sending a non-CNG payload to the comfort noise decoder for decoding.
1681 // Clearly wrong, but will maintain bit-exactness with legacy.
1682 if (fs_hz_ == 8000) {
1683 packet->header.payloadType =
kwibergee1879c2015-10-29 06:20:28 -07001684 decoder_database_->GetRtpPayloadType(NetEqDecoder::kDecoderCNGnb);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001685 } else if (fs_hz_ == 16000) {
1686 packet->header.payloadType =
kwibergee1879c2015-10-29 06:20:28 -07001687 decoder_database_->GetRtpPayloadType(NetEqDecoder::kDecoderCNGwb);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001688 } else if (fs_hz_ == 32000) {
kwibergee1879c2015-10-29 06:20:28 -07001689 packet->header.payloadType = decoder_database_->GetRtpPayloadType(
1690 NetEqDecoder::kDecoderCNGswb32kHz);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001691 } else if (fs_hz_ == 48000) {
kwibergee1879c2015-10-29 06:20:28 -07001692 packet->header.payloadType = decoder_database_->GetRtpPayloadType(
1693 NetEqDecoder::kDecoderCNGswb48kHz);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001694 }
1695 assert(decoder_database_->IsComfortNoise(packet->header.payloadType));
1696#else
1697 LOG(LS_ERROR) << "Trying to decode non-CNG payload as CNG.";
1698 return kOtherError;
1699#endif
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001700 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001701 // UpdateParameters() deletes |packet|.
1702 if (comfort_noise_->UpdateParameters(packet) ==
1703 ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001704 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001705 return -comfort_noise_->internal_error_code();
1706 }
1707 }
1708 int cn_return = comfort_noise_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001709 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001710 expand_->Reset();
1711 last_mode_ = kModeRfc3389Cng;
1712 if (!play_dtmf) {
1713 dtmf_tone_generator_->Reset();
1714 }
1715 if (cn_return == ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001716 decoder_error_code_ = comfort_noise_->internal_error_code();
1717 return kComfortNoiseErrorCode;
1718 } else if (cn_return == ComfortNoise::kUnknownPayloadType) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001719 return kUnknownRtpPayloadType;
1720 }
1721 return 0;
1722}
1723
minyuel6d92bf52015-09-23 15:20:39 +02001724void NetEqImpl::DoCodecInternalCng(const int16_t* decoded_buffer,
1725 size_t decoded_length) {
1726 RTC_DCHECK(normal_.get());
1727 RTC_DCHECK(mute_factor_array_.get());
1728 normal_->Process(decoded_buffer, decoded_length, last_mode_,
1729 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001730 last_mode_ = kModeCodecInternalCng;
1731 expand_->Reset();
1732}
1733
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001734int NetEqImpl::DoDtmf(const DtmfEvent& dtmf_event, bool* play_dtmf) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001735 // This block of the code and the block further down, handling |dtmf_switch|
1736 // are commented out. Otherwise playing out-of-band DTMF would fail in VoE
1737 // test, DtmfTest.ManualSuccessfullySendsOutOfBandTelephoneEvents. This is
1738 // equivalent to |dtmf_switch| always be false.
1739 //
1740 // See http://webrtc-codereview.appspot.com/1195004/ for discussion
1741 // On this issue. This change might cause some glitches at the point of
1742 // switch from audio to DTMF. Issue 1545 is filed to track this.
1743 //
1744 // bool dtmf_switch = false;
1745 // if ((last_mode_ != kModeDtmf) && dtmf_tone_generator_->initialized()) {
1746 // // Special case; see below.
1747 // // We must catch this before calling Generate, since |initialized| is
1748 // // modified in that call.
1749 // dtmf_switch = true;
1750 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001751
1752 int dtmf_return_value = 0;
1753 if (!dtmf_tone_generator_->initialized()) {
1754 // Initialize if not already done.
1755 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1756 dtmf_event.volume);
1757 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001758
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001759 if (dtmf_return_value == 0) {
1760 // Generate DTMF signal.
1761 dtmf_return_value = dtmf_tone_generator_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001762 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001763 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001764
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001765 if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001766 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001767 return dtmf_return_value;
1768 }
1769
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001770 // if (dtmf_switch) {
1771 // // This is the special case where the previous operation was DTMF
1772 // // overdub, but the current instruction is "regular" DTMF. We must make
1773 // // sure that the DTMF does not have any discontinuities. The first DTMF
1774 // // sample that we generate now must be played out immediately, therefore
1775 // // it must be copied to the speech buffer.
1776 // // TODO(hlundin): This code seems incorrect. (Legacy.) Write test and
1777 // // verify correct operation.
1778 // assert(false);
1779 // // Must generate enough data to replace all of the |sync_buffer_|
1780 // // "future".
1781 // int required_length = sync_buffer_->FutureLength();
1782 // assert(dtmf_tone_generator_->initialized());
1783 // dtmf_return_value = dtmf_tone_generator_->Generate(required_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001784 // algorithm_buffer_);
1785 // assert((size_t) required_length == algorithm_buffer_->Size());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001786 // if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001787 // algorithm_buffer_->Zeros(output_size_samples_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001788 // return dtmf_return_value;
1789 // }
1790 //
1791 // // Overwrite the "future" part of the speech buffer with the new DTMF
1792 // // data.
1793 // // TODO(hlundin): It seems that this overwriting has gone lost.
1794 // // Not adapted for multi-channel yet.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001795 // assert(algorithm_buffer_->Channels() == 1);
1796 // if (algorithm_buffer_->Channels() != 1) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001797 // LOG(LS_WARNING) << "DTMF not supported for more than one channel";
1798 // return kStereoNotSupported;
1799 // }
1800 // // Shuffle the remaining data to the beginning of algorithm buffer.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001801 // algorithm_buffer_->PopFront(sync_buffer_->FutureLength());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001802 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001803
Peter Kastingb7e50542015-06-11 12:55:50 -07001804 sync_buffer_->IncreaseEndTimestamp(
1805 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001806 expand_->Reset();
1807 last_mode_ = kModeDtmf;
1808
1809 // Set to false because the DTMF is already in the algorithm buffer.
1810 *play_dtmf = false;
1811 return 0;
1812}
1813
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001814void NetEqImpl::DoAlternativePlc(bool increase_timestamp) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001815 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001816 size_t length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001817 if (decoder && decoder->HasDecodePlc()) {
1818 // Use the decoder's packet-loss concealment.
1819 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1820 int16_t decoded_buffer[kMaxFrameSize];
1821 length = decoder->DecodePlc(1, decoded_buffer);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001822 if (length > 0)
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001823 algorithm_buffer_->PushBackInterleaved(decoded_buffer, length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001824 } else {
1825 // Do simple zero-stuffing.
1826 length = output_size_samples_;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001827 algorithm_buffer_->Zeros(length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001828 // By not advancing the timestamp, NetEq inserts samples.
1829 stats_.AddZeros(length);
1830 }
1831 if (increase_timestamp) {
Peter Kastingb7e50542015-06-11 12:55:50 -07001832 sync_buffer_->IncreaseEndTimestamp(static_cast<uint32_t>(length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001833 }
1834 expand_->Reset();
1835}
1836
1837int NetEqImpl::DtmfOverdub(const DtmfEvent& dtmf_event, size_t num_channels,
1838 int16_t* output) const {
1839 size_t out_index = 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001840 size_t overdub_length = output_size_samples_; // Default value.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001841
1842 if (sync_buffer_->dtmf_index() > sync_buffer_->next_index()) {
1843 // Special operation for transition from "DTMF only" to "DTMF overdub".
1844 out_index = std::min(
1845 sync_buffer_->dtmf_index() - sync_buffer_->next_index(),
Peter Kastingdce40cf2015-08-24 14:52:23 -07001846 output_size_samples_);
1847 overdub_length = output_size_samples_ - out_index;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001848 }
1849
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001850 AudioMultiVector dtmf_output(num_channels);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001851 int dtmf_return_value = 0;
1852 if (!dtmf_tone_generator_->initialized()) {
1853 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1854 dtmf_event.volume);
1855 }
1856 if (dtmf_return_value == 0) {
1857 dtmf_return_value = dtmf_tone_generator_->Generate(overdub_length,
1858 &dtmf_output);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001859 assert(overdub_length == dtmf_output.Size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001860 }
1861 dtmf_output.ReadInterleaved(overdub_length, &output[out_index]);
1862 return dtmf_return_value < 0 ? dtmf_return_value : 0;
1863}
1864
Peter Kastingdce40cf2015-08-24 14:52:23 -07001865int NetEqImpl::ExtractPackets(size_t required_samples,
1866 PacketList* packet_list) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001867 bool first_packet = true;
1868 uint8_t prev_payload_type = 0;
1869 uint32_t prev_timestamp = 0;
1870 uint16_t prev_sequence_number = 0;
1871 bool next_packet_available = false;
1872
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001873 const RTPHeader* header = packet_buffer_->NextRtpHeader();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001874 assert(header);
1875 if (!header) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001876 LOG(LS_ERROR) << "Packet buffer unexpectedly empty.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001877 return -1;
1878 }
turaj@webrtc.org7df97062013-08-02 18:07:13 +00001879 uint32_t first_timestamp = header->timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001880 int extracted_samples = 0;
1881
1882 // Packet extraction loop.
1883 do {
1884 timestamp_ = header->timestamp;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001885 size_t discard_count = 0;
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001886 Packet* packet = packet_buffer_->GetNextPacket(&discard_count);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001887 // |header| may be invalid after the |packet_buffer_| operation.
1888 header = NULL;
1889 if (!packet) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001890 LOG(LS_ERROR) << "Should always be able to extract a packet here";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001891 assert(false); // Should always be able to extract a packet here.
1892 return -1;
1893 }
1894 stats_.PacketsDiscarded(discard_count);
1895 // Store waiting time in ms; packets->waiting_time is in "output blocks".
1896 stats_.StoreWaitingTime(packet->waiting_time * kOutputSizeMs);
1897 assert(packet->payload_length > 0);
1898 packet_list->push_back(packet); // Store packet in list.
1899
1900 if (first_packet) {
1901 first_packet = false;
henrik.lundin48ed9302015-10-29 05:36:24 -07001902 if (nack_enabled_) {
1903 RTC_DCHECK(nack_);
1904 // TODO(henrik.lundin): Should we update this for all decoded packets?
1905 nack_->UpdateLastDecodedPacket(packet->header.sequenceNumber,
1906 packet->header.timestamp);
1907 }
1908 prev_sequence_number = packet->header.sequenceNumber;
1909 prev_timestamp = packet->header.timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001910 prev_payload_type = packet->header.payloadType;
1911 }
1912
1913 // Store number of extracted samples.
1914 int packet_duration = 0;
1915 AudioDecoder* decoder = decoder_database_->GetDecoder(
1916 packet->header.payloadType);
1917 if (decoder) {
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001918 if (packet->sync_packet) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001919 packet_duration = rtc::checked_cast<int>(decoder_frame_length_);
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001920 } else {
minyue@webrtc.org2c1bcf22015-02-17 10:17:09 +00001921 if (packet->primary) {
1922 packet_duration = decoder->PacketDuration(packet->payload,
1923 packet->payload_length);
1924 } else {
1925 packet_duration = decoder->
1926 PacketDurationRedundant(packet->payload, packet->payload_length);
1927 stats_.SecondaryDecodedSamples(packet_duration);
1928 }
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001929 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001930 } else {
Henrik Lundind67a2192015-08-03 12:54:37 +02001931 LOG(LS_WARNING) << "Unknown payload type "
1932 << static_cast<int>(packet->header.payloadType);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001933 assert(false);
1934 }
1935 if (packet_duration <= 0) {
1936 // Decoder did not return a packet duration. Assume that the packet
1937 // contains the same number of samples as the previous one.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001938 packet_duration = rtc::checked_cast<int>(decoder_frame_length_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001939 }
1940 extracted_samples = packet->header.timestamp - first_timestamp +
1941 packet_duration;
1942
1943 // Check what packet is available next.
1944 header = packet_buffer_->NextRtpHeader();
1945 next_packet_available = false;
1946 if (header && prev_payload_type == header->payloadType) {
1947 int16_t seq_no_diff = header->sequenceNumber - prev_sequence_number;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001948 size_t ts_diff = header->timestamp - prev_timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001949 if (seq_no_diff == 1 ||
1950 (seq_no_diff == 0 && ts_diff == decoder_frame_length_)) {
1951 // The next sequence number is available, or the next part of a packet
1952 // that was split into pieces upon insertion.
1953 next_packet_available = true;
1954 }
1955 prev_sequence_number = header->sequenceNumber;
1956 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07001957 } while (extracted_samples < rtc::checked_cast<int>(required_samples) &&
1958 next_packet_available);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001959
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00001960 if (extracted_samples > 0) {
1961 // Delete old packets only when we are going to decode something. Otherwise,
1962 // we could end up in the situation where we never decode anything, since
1963 // all incoming packets are considered too old but the buffer will also
1964 // never be flooded and flushed.
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001965 packet_buffer_->DiscardAllOldPackets(timestamp_);
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00001966 }
1967
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001968 return extracted_samples;
1969}
1970
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001971void NetEqImpl::UpdatePlcComponents(int fs_hz, size_t channels) {
1972 // Delete objects and create new ones.
1973 expand_.reset(expand_factory_->Create(background_noise_.get(),
1974 sync_buffer_.get(), &random_vector_,
Henrik Lundinbef77e22015-08-18 14:58:09 +02001975 &stats_, fs_hz, channels));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001976 merge_.reset(new Merge(fs_hz, channels, expand_.get(), sync_buffer_.get()));
1977}
1978
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001979void NetEqImpl::SetSampleRateAndChannels(int fs_hz, size_t channels) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001980 LOG(LS_VERBOSE) << "SetSampleRateAndChannels " << fs_hz << " " << channels;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001981 // TODO(hlundin): Change to an enumerator and skip assert.
1982 assert(fs_hz == 8000 || fs_hz == 16000 || fs_hz == 32000 || fs_hz == 48000);
1983 assert(channels > 0);
1984
1985 fs_hz_ = fs_hz;
1986 fs_mult_ = fs_hz / 8000;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001987 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001988 decoder_frame_length_ = 3 * output_size_samples_; // Initialize to 30ms.
1989
1990 last_mode_ = kModeNormal;
1991
1992 // Create a new array of mute factors and set all to 1.
1993 mute_factor_array_.reset(new int16_t[channels]);
1994 for (size_t i = 0; i < channels; ++i) {
1995 mute_factor_array_[i] = 16384; // 1.0 in Q14.
1996 }
1997
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001998 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02001999 if (cng_decoder)
2000 cng_decoder->Reset();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002001
2002 // Reinit post-decode VAD with new sample rate.
2003 assert(vad_.get()); // Cannot be NULL here.
2004 vad_->Init();
2005
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002006 // Delete algorithm buffer and create a new one.
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00002007 algorithm_buffer_.reset(new AudioMultiVector(channels));
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002008
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002009 // Delete sync buffer and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002010 sync_buffer_.reset(new SyncBuffer(channels, kSyncBufferSize * fs_mult_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002011
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00002012 // Delete BackgroundNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002013 background_noise_.reset(new BackgroundNoise(channels));
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00002014 background_noise_->set_mode(background_noise_mode_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002015
2016 // Reset random vector.
2017 random_vector_.Reset();
2018
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002019 UpdatePlcComponents(fs_hz, channels);
2020
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002021 // Move index so that we create a small set of future samples (all 0).
2022 sync_buffer_->set_next_index(sync_buffer_->next_index() -
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002023 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002024
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002025 normal_.reset(new Normal(fs_hz, decoder_database_.get(), *background_noise_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002026 expand_.get()));
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +00002027 accelerate_.reset(
2028 accelerate_factory_->Create(fs_hz, channels, *background_noise_));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002029 preemptive_expand_.reset(preemptive_expand_factory_->Create(
Peter Kastingdce40cf2015-08-24 14:52:23 -07002030 fs_hz, channels, *background_noise_, expand_->overlap_length()));
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002031
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002032 // Delete ComfortNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002033 comfort_noise_.reset(new ComfortNoise(fs_hz, decoder_database_.get(),
2034 sync_buffer_.get()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002035
2036 // Verify that |decoded_buffer_| is long enough.
2037 if (decoded_buffer_length_ < kMaxFrameSize * channels) {
2038 // Reallocate to larger size.
2039 decoded_buffer_length_ = kMaxFrameSize * channels;
2040 decoded_buffer_.reset(new int16_t[decoded_buffer_length_]);
2041 }
2042
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002043 // Create DecisionLogic if it is not created yet, then communicate new sample
2044 // rate and output size to DecisionLogic object.
2045 if (!decision_logic_.get()) {
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002046 CreateDecisionLogic();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002047 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002048 decision_logic_->SetSampleRate(fs_hz_, output_size_samples_);
2049}
2050
2051NetEqOutputType NetEqImpl::LastOutputType() {
2052 assert(vad_.get());
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002053 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002054 if (last_mode_ == kModeCodecInternalCng || last_mode_ == kModeRfc3389Cng) {
2055 return kOutputCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002056 } else if (last_mode_ == kModeExpand && expand_->MuteFactor(0) == 0) {
2057 // Expand mode has faded down to background noise only (very long expand).
2058 return kOutputPLCtoCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002059 } else if (last_mode_ == kModeExpand) {
2060 return kOutputPLC;
wu@webrtc.org24301a62013-12-13 19:17:43 +00002061 } else if (vad_->running() && !vad_->active_speech()) {
2062 return kOutputVADPassive;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002063 } else {
2064 return kOutputNormal;
2065 }
2066}
2067
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002068void NetEqImpl::CreateDecisionLogic() {
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002069 decision_logic_.reset(DecisionLogic::Create(fs_hz_, output_size_samples_,
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002070 playout_mode_,
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002071 decoder_database_.get(),
2072 *packet_buffer_.get(),
2073 delay_manager_.get(),
2074 buffer_level_filter_.get()));
2075}
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002076} // namespace webrtc