blob: 93699821cfbc430cc6b9fa8daa7cbb2326e8ee64 [file] [log] [blame]
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001/*
2 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000011#include "webrtc/modules/audio_coding/neteq/neteq_impl.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000012
13#include <assert.h>
14#include <memory.h> // memset
15
16#include <algorithm>
17
henrik.lundin9c3efd02015-08-27 13:12:22 -070018#include "webrtc/base/checks.h"
Henrik Lundind67a2192015-08-03 12:54:37 +020019#include "webrtc/base/logging.h"
Peter Kastingdce40cf2015-08-24 14:52:23 -070020#include "webrtc/base/safe_conversions.h"
henrik.lundina689b442015-12-17 03:50:05 -080021#include "webrtc/base/trace_event.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000022#include "webrtc/common_audio/signal_processing/include/signal_processing_library.h"
kwiberg@webrtc.orge04a93b2014-12-09 10:12:53 +000023#include "webrtc/modules/audio_coding/codecs/audio_decoder.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000024#include "webrtc/modules/audio_coding/neteq/accelerate.h"
25#include "webrtc/modules/audio_coding/neteq/background_noise.h"
26#include "webrtc/modules/audio_coding/neteq/buffer_level_filter.h"
27#include "webrtc/modules/audio_coding/neteq/comfort_noise.h"
28#include "webrtc/modules/audio_coding/neteq/decision_logic.h"
29#include "webrtc/modules/audio_coding/neteq/decoder_database.h"
30#include "webrtc/modules/audio_coding/neteq/defines.h"
31#include "webrtc/modules/audio_coding/neteq/delay_manager.h"
32#include "webrtc/modules/audio_coding/neteq/delay_peak_detector.h"
33#include "webrtc/modules/audio_coding/neteq/dtmf_buffer.h"
34#include "webrtc/modules/audio_coding/neteq/dtmf_tone_generator.h"
35#include "webrtc/modules/audio_coding/neteq/expand.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000036#include "webrtc/modules/audio_coding/neteq/merge.h"
henrik.lundin48ed9302015-10-29 05:36:24 -070037#include "webrtc/modules/audio_coding/neteq/nack.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000038#include "webrtc/modules/audio_coding/neteq/normal.h"
39#include "webrtc/modules/audio_coding/neteq/packet_buffer.h"
40#include "webrtc/modules/audio_coding/neteq/packet.h"
41#include "webrtc/modules/audio_coding/neteq/payload_splitter.h"
42#include "webrtc/modules/audio_coding/neteq/post_decode_vad.h"
43#include "webrtc/modules/audio_coding/neteq/preemptive_expand.h"
44#include "webrtc/modules/audio_coding/neteq/sync_buffer.h"
45#include "webrtc/modules/audio_coding/neteq/timestamp_scaler.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010046#include "webrtc/modules/include/module_common_types.h"
henrik.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)
Tommi9090e0b2016-01-20 13:39:36 +010069 : buffer_level_filter_(buffer_level_filter),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000070 decoder_database_(decoder_database),
71 delay_manager_(delay_manager),
72 delay_peak_detector_(delay_peak_detector),
73 dtmf_buffer_(dtmf_buffer),
74 dtmf_tone_generator_(dtmf_tone_generator),
75 packet_buffer_(packet_buffer),
76 payload_splitter_(payload_splitter),
77 timestamp_scaler_(timestamp_scaler),
78 vad_(new PostDecodeVad()),
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +000079 expand_factory_(expand_factory),
80 accelerate_factory_(accelerate_factory),
81 preemptive_expand_factory_(preemptive_expand_factory),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000082 last_mode_(kModeNormal),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000083 decoded_buffer_length_(kMaxFrameSize),
84 decoded_buffer_(new int16_t[decoded_buffer_length_]),
85 playout_timestamp_(0),
86 new_codec_(false),
87 timestamp_(0),
88 reset_decoder_(false),
henrik.lundin48ed9302015-10-29 05:36:24 -070089 current_rtp_payload_type_(0xFF), // Invalid RTP payload type.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000090 current_cng_rtp_payload_type_(0xFF), // Invalid RTP payload type.
91 ssrc_(0),
92 first_packet_(true),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000093 error_code_(0),
94 decoder_error_code_(0),
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +000095 background_noise_mode_(config.background_noise_mode),
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +000096 playout_mode_(config.playout_mode),
Henrik Lundincf808d22015-05-27 14:33:29 +020097 enable_fast_accelerate_(config.enable_fast_accelerate),
henrik.lundin48ed9302015-10-29 05:36:24 -070098 nack_enabled_(false) {
Henrik Lundin905495c2015-05-25 16:58:41 +020099 LOG(LS_INFO) << "NetEq config: " << config.ToString();
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +0000100 int fs = config.sample_rate_hz;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000101 if (fs != 8000 && fs != 16000 && fs != 32000 && fs != 48000) {
102 LOG(LS_ERROR) << "Sample rate " << fs << " Hz not supported. " <<
103 "Changing to 8000 Hz.";
104 fs = 8000;
105 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000106 fs_hz_ = fs;
107 fs_mult_ = fs / 8000;
henrik.lundind89814b2015-11-23 06:49:25 -0800108 last_output_sample_rate_hz_ = fs;
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.lundina689b442015-12-17 03:50:05 -0800126 TRACE_EVENT0("webrtc", "NetEqImpl::InsertPacket");
Tommi9090e0b2016-01-20 13:39:36 +0100127 rtc::CritScope lock(&crit_sect_);
kwibergee2bac22015-11-11 10:34:00 -0800128 int error =
129 InsertPacketInternal(rtp_header, payload, receive_timestamp, false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000130 if (error != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000131 error_code_ = error;
132 return kFail;
133 }
134 return kOK;
135}
136
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000137int NetEqImpl::InsertSyncPacket(const WebRtcRTPHeader& rtp_header,
138 uint32_t receive_timestamp) {
Tommi9090e0b2016-01-20 13:39:36 +0100139 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000140 const uint8_t kSyncPayload[] = { 's', 'y', 'n', 'c' };
kwibergee2bac22015-11-11 10:34:00 -0800141 int error =
142 InsertPacketInternal(rtp_header, kSyncPayload, receive_timestamp, true);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000143
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000144 if (error != 0) {
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000145 error_code_ = error;
146 return kFail;
147 }
148 return kOK;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000149}
150
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000151int NetEqImpl::GetAudio(size_t max_length, int16_t* output_audio,
Peter Kasting69558702016-01-12 16:26:35 -0800152 size_t* samples_per_channel, size_t* num_channels,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000153 NetEqOutputType* type) {
henrik.lundine1ca1672016-01-08 03:50:08 -0800154 TRACE_EVENT0("webrtc", "NetEqImpl::GetAudio");
Tommi9090e0b2016-01-20 13:39:36 +0100155 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000156 int error = GetAudioInternal(max_length, output_audio, samples_per_channel,
157 num_channels);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000158 if (error != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000159 error_code_ = error;
160 return kFail;
161 }
162 if (type) {
163 *type = LastOutputType();
164 }
henrik.lundind89814b2015-11-23 06:49:25 -0800165 last_output_sample_rate_hz_ =
166 rtc::checked_cast<int>(*samples_per_channel * 100);
167 RTC_DCHECK(last_output_sample_rate_hz_ == 8000 ||
168 last_output_sample_rate_hz_ == 16000 ||
169 last_output_sample_rate_hz_ == 32000 ||
170 last_output_sample_rate_hz_ == 48000)
171 << "Unexpected sample rate " << last_output_sample_rate_hz_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000172 return kOK;
173}
174
kwibergee1879c2015-10-29 06:20:28 -0700175int NetEqImpl::RegisterPayloadType(NetEqDecoder codec,
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800176 const std::string& name,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000177 uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100178 rtc::CritScope lock(&crit_sect_);
Henrik Lundind67a2192015-08-03 12:54:37 +0200179 LOG(LS_VERBOSE) << "RegisterPayloadType "
kwibergee1879c2015-10-29 06:20:28 -0700180 << static_cast<int>(rtp_payload_type) << " "
181 << static_cast<int>(codec);
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800182 int ret = decoder_database_->RegisterPayload(rtp_payload_type, codec, name);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000183 if (ret != DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000184 switch (ret) {
185 case DecoderDatabase::kInvalidRtpPayloadType:
186 error_code_ = kInvalidRtpPayloadType;
187 break;
188 case DecoderDatabase::kCodecNotSupported:
189 error_code_ = kCodecNotSupported;
190 break;
191 case DecoderDatabase::kDecoderExists:
192 error_code_ = kDecoderExists;
193 break;
194 default:
195 error_code_ = kOtherError;
196 }
197 return kFail;
198 }
199 return kOK;
200}
201
202int NetEqImpl::RegisterExternalDecoder(AudioDecoder* decoder,
kwibergee1879c2015-10-29 06:20:28 -0700203 NetEqDecoder codec,
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800204 const std::string& codec_name,
Karl Wibergd8399e62015-05-25 14:39:56 +0200205 uint8_t rtp_payload_type,
206 int sample_rate_hz) {
Tommi9090e0b2016-01-20 13:39:36 +0100207 rtc::CritScope lock(&crit_sect_);
Henrik Lundind67a2192015-08-03 12:54:37 +0200208 LOG(LS_VERBOSE) << "RegisterExternalDecoder "
kwibergee1879c2015-10-29 06:20:28 -0700209 << static_cast<int>(rtp_payload_type) << " "
210 << static_cast<int>(codec);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000211 if (!decoder) {
212 LOG(LS_ERROR) << "Cannot register external decoder with NULL pointer";
213 assert(false);
214 return kFail;
215 }
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800216 int ret = decoder_database_->InsertExternal(
217 rtp_payload_type, codec, codec_name, sample_rate_hz, decoder);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000218 if (ret != DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000219 switch (ret) {
220 case DecoderDatabase::kInvalidRtpPayloadType:
221 error_code_ = kInvalidRtpPayloadType;
222 break;
223 case DecoderDatabase::kCodecNotSupported:
224 error_code_ = kCodecNotSupported;
225 break;
226 case DecoderDatabase::kDecoderExists:
227 error_code_ = kDecoderExists;
228 break;
229 case DecoderDatabase::kInvalidSampleRate:
230 error_code_ = kInvalidSampleRate;
231 break;
232 case DecoderDatabase::kInvalidPointer:
233 error_code_ = kInvalidPointer;
234 break;
235 default:
236 error_code_ = kOtherError;
237 }
238 return kFail;
239 }
240 return kOK;
241}
242
243int NetEqImpl::RemovePayloadType(uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100244 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000245 int ret = decoder_database_->Remove(rtp_payload_type);
246 if (ret == DecoderDatabase::kOK) {
247 return kOK;
248 } else if (ret == DecoderDatabase::kDecoderNotFound) {
249 error_code_ = kDecoderNotFound;
250 } else {
251 error_code_ = kOtherError;
252 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000253 return kFail;
254}
255
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000256bool NetEqImpl::SetMinimumDelay(int delay_ms) {
Tommi9090e0b2016-01-20 13:39:36 +0100257 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000258 if (delay_ms >= 0 && delay_ms < 10000) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000259 assert(delay_manager_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000260 return delay_manager_->SetMinimumDelay(delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000261 }
262 return false;
263}
264
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000265bool NetEqImpl::SetMaximumDelay(int delay_ms) {
Tommi9090e0b2016-01-20 13:39:36 +0100266 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000267 if (delay_ms >= 0 && delay_ms < 10000) {
268 assert(delay_manager_.get());
269 return delay_manager_->SetMaximumDelay(delay_ms);
270 }
271 return false;
272}
273
274int NetEqImpl::LeastRequiredDelayMs() const {
Tommi9090e0b2016-01-20 13:39:36 +0100275 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000276 assert(delay_manager_.get());
277 return delay_manager_->least_required_delay_ms();
278}
279
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200280int NetEqImpl::SetTargetDelay() {
281 return kNotImplemented;
282}
283
284int NetEqImpl::TargetDelay() {
285 return kNotImplemented;
286}
287
henrik.lundin9c3efd02015-08-27 13:12:22 -0700288int NetEqImpl::CurrentDelayMs() const {
Tommi9090e0b2016-01-20 13:39:36 +0100289 rtc::CritScope lock(&crit_sect_);
henrik.lundin9c3efd02015-08-27 13:12:22 -0700290 if (fs_hz_ == 0)
291 return 0;
292 // Sum up the samples in the packet buffer with the future length of the sync
293 // buffer, and divide the sum by the sample rate.
294 const size_t delay_samples =
295 packet_buffer_->NumSamplesInBuffer(decoder_database_.get(),
296 decoder_frame_length_) +
297 sync_buffer_->FutureLength();
298 // The division below will truncate.
299 const int delay_ms =
300 static_cast<int>(delay_samples) / rtc::CheckedDivExact(fs_hz_, 1000);
301 return delay_ms;
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200302}
303
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000304// Deprecated.
305// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000306void NetEqImpl::SetPlayoutMode(NetEqPlayoutMode mode) {
Tommi9090e0b2016-01-20 13:39:36 +0100307 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000308 if (mode != playout_mode_) {
309 playout_mode_ = mode;
310 CreateDecisionLogic();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000311 }
312}
313
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000314// Deprecated.
315// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000316NetEqPlayoutMode NetEqImpl::PlayoutMode() const {
Tommi9090e0b2016-01-20 13:39:36 +0100317 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000318 return playout_mode_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000319}
320
321int NetEqImpl::NetworkStatistics(NetEqNetworkStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100322 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000323 assert(decoder_database_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700324 const size_t total_samples_in_buffers =
Peter Kasting728d9032015-06-11 14:31:38 -0700325 packet_buffer_->NumSamplesInBuffer(decoder_database_.get(),
326 decoder_frame_length_) +
Peter Kastingdce40cf2015-08-24 14:52:23 -0700327 sync_buffer_->FutureLength();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000328 assert(delay_manager_.get());
329 assert(decision_logic_.get());
330 stats_.GetNetworkStatistics(fs_hz_, total_samples_in_buffers,
331 decoder_frame_length_, *delay_manager_.get(),
332 *decision_logic_.get(), stats);
333 return 0;
334}
335
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000336void NetEqImpl::GetRtcpStatistics(RtcpStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100337 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000338 if (stats) {
339 rtcp_.GetStatistics(false, stats);
340 }
341}
342
343void NetEqImpl::GetRtcpStatisticsNoReset(RtcpStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100344 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000345 if (stats) {
346 rtcp_.GetStatistics(true, stats);
347 }
348}
349
350void NetEqImpl::EnableVad() {
Tommi9090e0b2016-01-20 13:39:36 +0100351 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000352 assert(vad_.get());
353 vad_->Enable();
354}
355
356void NetEqImpl::DisableVad() {
Tommi9090e0b2016-01-20 13:39:36 +0100357 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000358 assert(vad_.get());
359 vad_->Disable();
360}
361
wu@webrtc.org94454b72014-06-05 20:34:08 +0000362bool NetEqImpl::GetPlayoutTimestamp(uint32_t* timestamp) {
Tommi9090e0b2016-01-20 13:39:36 +0100363 rtc::CritScope lock(&crit_sect_);
wu@webrtc.org94454b72014-06-05 20:34:08 +0000364 if (first_packet_) {
365 // We don't have a valid RTP timestamp until we have decoded our first
366 // RTP packet.
367 return false;
368 }
369 *timestamp = timestamp_scaler_->ToExternal(playout_timestamp_);
370 return true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000371}
372
henrik.lundind89814b2015-11-23 06:49:25 -0800373int NetEqImpl::last_output_sample_rate_hz() const {
Tommi9090e0b2016-01-20 13:39:36 +0100374 rtc::CritScope lock(&crit_sect_);
henrik.lundind89814b2015-11-23 06:49:25 -0800375 return last_output_sample_rate_hz_;
376}
377
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200378int NetEqImpl::SetTargetNumberOfChannels() {
379 return kNotImplemented;
380}
381
382int NetEqImpl::SetTargetSampleRate() {
383 return kNotImplemented;
384}
385
henrik.lundin@webrtc.orgb0f4b3d2014-11-04 08:53:10 +0000386int NetEqImpl::LastError() const {
Tommi9090e0b2016-01-20 13:39:36 +0100387 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000388 return error_code_;
389}
390
391int NetEqImpl::LastDecoderError() {
Tommi9090e0b2016-01-20 13:39:36 +0100392 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000393 return decoder_error_code_;
394}
395
396void NetEqImpl::FlushBuffers() {
Tommi9090e0b2016-01-20 13:39:36 +0100397 rtc::CritScope lock(&crit_sect_);
Henrik Lundind67a2192015-08-03 12:54:37 +0200398 LOG(LS_VERBOSE) << "FlushBuffers";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000399 packet_buffer_->Flush();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000400 assert(sync_buffer_.get());
401 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000402 sync_buffer_->Flush();
403 sync_buffer_->set_next_index(sync_buffer_->next_index() -
404 expand_->overlap_length());
405 // Set to wait for new codec.
406 first_packet_ = true;
407}
408
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000409void NetEqImpl::PacketBufferStatistics(int* current_num_packets,
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000410 int* max_num_packets) const {
Tommi9090e0b2016-01-20 13:39:36 +0100411 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000412 packet_buffer_->BufferStat(current_num_packets, max_num_packets);
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000413}
414
henrik.lundin48ed9302015-10-29 05:36:24 -0700415void NetEqImpl::EnableNack(size_t max_nack_list_size) {
Tommi9090e0b2016-01-20 13:39:36 +0100416 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700417 if (!nack_enabled_) {
418 const int kNackThresholdPackets = 2;
419 nack_.reset(Nack::Create(kNackThresholdPackets));
420 nack_enabled_ = true;
421 nack_->UpdateSampleRate(fs_hz_);
422 }
423 nack_->SetMaxNackListSize(max_nack_list_size);
424}
425
426void NetEqImpl::DisableNack() {
Tommi9090e0b2016-01-20 13:39:36 +0100427 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700428 nack_.reset();
429 nack_enabled_ = false;
430}
431
432std::vector<uint16_t> NetEqImpl::GetNackList(int64_t round_trip_time_ms) const {
Tommi9090e0b2016-01-20 13:39:36 +0100433 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700434 if (!nack_enabled_) {
435 return std::vector<uint16_t>();
436 }
437 RTC_DCHECK(nack_.get());
438 return nack_->GetNackList(round_trip_time_ms);
minyue@webrtc.orgd7301772013-08-29 00:58:14 +0000439}
440
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000441const SyncBuffer* NetEqImpl::sync_buffer_for_test() const {
Tommi9090e0b2016-01-20 13:39:36 +0100442 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000443 return sync_buffer_.get();
444}
445
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000446// Methods below this line are private.
447
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000448int NetEqImpl::InsertPacketInternal(const WebRtcRTPHeader& rtp_header,
kwibergee2bac22015-11-11 10:34:00 -0800449 rtc::ArrayView<const uint8_t> payload,
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000450 uint32_t receive_timestamp,
451 bool is_sync_packet) {
kwibergee2bac22015-11-11 10:34:00 -0800452 if (payload.empty()) {
453 LOG_F(LS_ERROR) << "payload is empty";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000454 return kInvalidPointer;
455 }
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000456 // Sanity checks for sync-packets.
457 if (is_sync_packet) {
458 if (decoder_database_->IsDtmf(rtp_header.header.payloadType) ||
459 decoder_database_->IsRed(rtp_header.header.payloadType) ||
460 decoder_database_->IsComfortNoise(rtp_header.header.payloadType)) {
461 LOG_F(LS_ERROR) << "Sync-packet with an unacceptable payload type "
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000462 << static_cast<int>(rtp_header.header.payloadType);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000463 return kSyncPacketNotAccepted;
464 }
465 if (first_packet_ ||
466 rtp_header.header.payloadType != current_rtp_payload_type_ ||
467 rtp_header.header.ssrc != ssrc_) {
468 // Even if |current_rtp_payload_type_| is 0xFF, sync-packet isn't
469 // accepted.
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000470 LOG_F(LS_ERROR)
471 << "Changing codec, SSRC or first packet with sync-packet.";
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000472 return kSyncPacketNotAccepted;
473 }
474 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000475 PacketList packet_list;
476 RTPHeader main_header;
477 {
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000478 // Convert to Packet.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000479 // Create |packet| within this separate scope, since it should not be used
480 // directly once it's been inserted in the packet list. This way, |packet|
481 // is not defined outside of this block.
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000482 Packet* packet = new Packet;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000483 packet->header.markerBit = false;
484 packet->header.payloadType = rtp_header.header.payloadType;
485 packet->header.sequenceNumber = rtp_header.header.sequenceNumber;
486 packet->header.timestamp = rtp_header.header.timestamp;
487 packet->header.ssrc = rtp_header.header.ssrc;
488 packet->header.numCSRCs = 0;
kwibergee2bac22015-11-11 10:34:00 -0800489 packet->payload_length = payload.size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000490 packet->primary = true;
491 packet->waiting_time = 0;
492 packet->payload = new uint8_t[packet->payload_length];
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000493 packet->sync_packet = is_sync_packet;
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +0000494 if (!packet->payload) {
495 LOG_F(LS_ERROR) << "Payload pointer is NULL.";
496 }
kwibergee2bac22015-11-11 10:34:00 -0800497 assert(!payload.empty()); // Already checked above.
498 memcpy(packet->payload, payload.data(), packet->payload_length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000499 // Insert packet in a packet list.
500 packet_list.push_back(packet);
501 // Save main payloads header for later.
502 memcpy(&main_header, &packet->header, sizeof(main_header));
503 }
504
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000505 bool update_sample_rate_and_channels = false;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000506 // Reinitialize NetEq if it's needed (changed SSRC or first call).
507 if ((main_header.ssrc != ssrc_) || first_packet_) {
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000508 // Note: |first_packet_| will be cleared further down in this method, once
509 // the packet has been successfully inserted into the packet buffer.
510
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000511 rtcp_.Init(main_header.sequenceNumber);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000512
513 // Flush the packet buffer and DTMF buffer.
514 packet_buffer_->Flush();
515 dtmf_buffer_->Flush();
516
517 // Store new SSRC.
518 ssrc_ = main_header.ssrc;
519
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000520 // Update audio buffer timestamp.
521 sync_buffer_->IncreaseEndTimestamp(main_header.timestamp - timestamp_);
522
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000523 // Update codecs.
524 timestamp_ = main_header.timestamp;
525 current_rtp_payload_type_ = main_header.payloadType;
526
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000527 // Reset timestamp scaling.
528 timestamp_scaler_->Reset();
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000529
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000530 // Trigger an update of sampling rate and the number of channels.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000531 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000532 }
533
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000534 // Update RTCP statistics, only for regular packets.
535 if (!is_sync_packet)
536 rtcp_.Update(main_header, receive_timestamp);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000537
538 // Check for RED payload type, and separate payloads into several packets.
539 if (decoder_database_->IsRed(main_header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000540 assert(!is_sync_packet); // We had a sanity check for this.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000541 if (payload_splitter_->SplitRed(&packet_list) != PayloadSplitter::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000542 PacketBuffer::DeleteAllPackets(&packet_list);
543 return kRedundancySplitError;
544 }
545 // Only accept a few RED payloads of the same type as the main data,
546 // DTMF events and CNG.
547 payload_splitter_->CheckRedPayloads(&packet_list, *decoder_database_);
548 // Update the stored main payload header since the main payload has now
549 // changed.
550 memcpy(&main_header, &packet_list.front()->header, sizeof(main_header));
551 }
552
553 // Check payload types.
554 if (decoder_database_->CheckPayloadTypes(packet_list) ==
555 DecoderDatabase::kDecoderNotFound) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000556 PacketBuffer::DeleteAllPackets(&packet_list);
557 return kUnknownRtpPayloadType;
558 }
559
560 // Scale timestamp to internal domain (only for some codecs).
561 timestamp_scaler_->ToInternal(&packet_list);
562
563 // Process DTMF payloads. Cycle through the list of packets, and pick out any
564 // DTMF payloads found.
565 PacketList::iterator it = packet_list.begin();
566 while (it != packet_list.end()) {
567 Packet* current_packet = (*it);
568 assert(current_packet);
569 assert(current_packet->payload);
570 if (decoder_database_->IsDtmf(current_packet->header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000571 assert(!current_packet->sync_packet); // We had a sanity check for this.
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000572 DtmfEvent event;
573 int ret = DtmfBuffer::ParseEvent(
574 current_packet->header.timestamp,
575 current_packet->payload,
576 current_packet->payload_length,
577 &event);
578 if (ret != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000579 PacketBuffer::DeleteAllPackets(&packet_list);
580 return kDtmfParsingError;
581 }
582 if (dtmf_buffer_->InsertEvent(event) != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000583 PacketBuffer::DeleteAllPackets(&packet_list);
584 return kDtmfInsertError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000585 }
586 // TODO(hlundin): Let the destructor of Packet handle the payload.
587 delete [] current_packet->payload;
588 delete current_packet;
589 it = packet_list.erase(it);
590 } else {
591 ++it;
592 }
593 }
594
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000595 // Check for FEC in packets, and separate payloads into several packets.
596 int ret = payload_splitter_->SplitFec(&packet_list, decoder_database_.get());
597 if (ret != PayloadSplitter::kOK) {
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000598 PacketBuffer::DeleteAllPackets(&packet_list);
599 switch (ret) {
600 case PayloadSplitter::kUnknownPayloadType:
601 return kUnknownRtpPayloadType;
602 default:
603 return kOtherError;
604 }
605 }
606
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000607 // Split payloads into smaller chunks. This also verifies that all payloads
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000608 // are of a known payload type. SplitAudio() method is protected against
609 // sync-packets.
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +0000610 ret = payload_splitter_->SplitAudio(&packet_list, *decoder_database_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000611 if (ret != PayloadSplitter::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000612 PacketBuffer::DeleteAllPackets(&packet_list);
613 switch (ret) {
614 case PayloadSplitter::kUnknownPayloadType:
615 return kUnknownRtpPayloadType;
616 case PayloadSplitter::kFrameSplitError:
617 return kFrameSplitError;
618 default:
619 return kOtherError;
620 }
621 }
622
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000623 // Update bandwidth estimate, if the packet is not sync-packet.
624 if (!packet_list.empty() && !packet_list.front()->sync_packet) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000625 // The list can be empty here if we got nothing but DTMF payloads.
626 AudioDecoder* decoder =
627 decoder_database_->GetDecoder(main_header.payloadType);
628 assert(decoder); // Should always get a valid object, since we have
629 // already checked that the payload types are known.
630 decoder->IncomingPacket(packet_list.front()->payload,
631 packet_list.front()->payload_length,
632 packet_list.front()->header.sequenceNumber,
633 packet_list.front()->header.timestamp,
634 receive_timestamp);
635 }
636
henrik.lundin48ed9302015-10-29 05:36:24 -0700637 if (nack_enabled_) {
638 RTC_DCHECK(nack_);
639 if (update_sample_rate_and_channels) {
640 nack_->Reset();
641 }
642 nack_->UpdateLastReceivedPacket(packet_list.front()->header.sequenceNumber,
643 packet_list.front()->header.timestamp);
644 }
645
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000646 // Insert packets in buffer.
henrik.lundin116c84e2015-08-27 13:14:48 -0700647 const size_t buffer_length_before_insert =
648 packet_buffer_->NumPacketsInBuffer();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000649 ret = packet_buffer_->InsertPacketList(
650 &packet_list,
651 *decoder_database_,
652 &current_rtp_payload_type_,
653 &current_cng_rtp_payload_type_);
654 if (ret == PacketBuffer::kFlushed) {
655 // Reset DSP timestamp etc. if packet buffer flushed.
656 new_codec_ = true;
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000657 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000658 } else if (ret != PacketBuffer::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000659 PacketBuffer::DeleteAllPackets(&packet_list);
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000660 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000661 }
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000662
663 if (first_packet_) {
664 first_packet_ = false;
665 // Update the codec on the next GetAudio call.
666 new_codec_ = true;
667 }
668
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000669 if (current_rtp_payload_type_ != 0xFF) {
670 const DecoderDatabase::DecoderInfo* dec_info =
671 decoder_database_->GetDecoderInfo(current_rtp_payload_type_);
672 if (!dec_info) {
673 assert(false); // Already checked that the payload type is known.
674 }
675 }
676
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000677 if (update_sample_rate_and_channels && !packet_buffer_->Empty()) {
678 // We do not use |current_rtp_payload_type_| to |set payload_type|, but
679 // get the next RTP header from |packet_buffer_| to obtain the payload type.
680 // The reason for it is the following corner case. If NetEq receives a
681 // CNG packet with a sample rate different than the current CNG then it
682 // flushes its buffer, assuming send codec must have been changed. However,
683 // payload type of the hypothetically new send codec is not known.
684 const RTPHeader* rtp_header = packet_buffer_->NextRtpHeader();
685 assert(rtp_header);
686 int payload_type = rtp_header->payloadType;
687 AudioDecoder* decoder = decoder_database_->GetDecoder(payload_type);
688 assert(decoder); // Payloads are already checked to be valid.
689 const DecoderDatabase::DecoderInfo* decoder_info =
690 decoder_database_->GetDecoderInfo(payload_type);
691 assert(decoder_info);
692 if (decoder_info->fs_hz != fs_hz_ ||
henrik.lundin48ed9302015-10-29 05:36:24 -0700693 decoder->Channels() != algorithm_buffer_->Channels()) {
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +0000694 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->Channels());
henrik.lundin48ed9302015-10-29 05:36:24 -0700695 }
696 if (nack_enabled_) {
697 RTC_DCHECK(nack_);
698 // Update the sample rate even if the rate is not new, because of Reset().
699 nack_->UpdateSampleRate(fs_hz_);
700 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000701 }
702
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000703 // TODO(hlundin): Move this code to DelayManager class.
704 const DecoderDatabase::DecoderInfo* dec_info =
705 decoder_database_->GetDecoderInfo(main_header.payloadType);
706 assert(dec_info); // Already checked that the payload type is known.
707 delay_manager_->LastDecoderType(dec_info->codec_type);
708 if (delay_manager_->last_pack_cng_or_dtmf() == 0) {
709 // Calculate the total speech length carried in each packet.
henrik.lundin116c84e2015-08-27 13:14:48 -0700710 const size_t buffer_length_after_insert =
711 packet_buffer_->NumPacketsInBuffer();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000712
henrik.lundin116c84e2015-08-27 13:14:48 -0700713 if (buffer_length_after_insert > buffer_length_before_insert) {
714 const size_t packet_length_samples =
715 (buffer_length_after_insert - buffer_length_before_insert) *
716 decoder_frame_length_;
717 if (packet_length_samples != decision_logic_->packet_length_samples()) {
718 decision_logic_->set_packet_length_samples(packet_length_samples);
719 delay_manager_->SetPacketAudioLength(
720 rtc::checked_cast<int>((1000 * packet_length_samples) / fs_hz_));
721 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000722 }
723
724 // Update statistics.
pbos@webrtc.org0946a562013-04-09 00:28:06 +0000725 if ((int32_t) (main_header.timestamp - timestamp_) >= 0 &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000726 !new_codec_) {
727 // Only update statistics if incoming packet is not older than last played
728 // out packet, and if new codec flag is not set.
729 delay_manager_->Update(main_header.sequenceNumber, main_header.timestamp,
730 fs_hz_);
731 }
732 } else if (delay_manager_->last_pack_cng_or_dtmf() == -1) {
733 // This is first "normal" packet after CNG or DTMF.
734 // Reset packet time counter and measure time until next packet,
735 // but don't update statistics.
736 delay_manager_->set_last_pack_cng_or_dtmf(0);
737 delay_manager_->ResetPacketIatCount();
738 }
739 return 0;
740}
741
Peter Kasting728d9032015-06-11 14:31:38 -0700742int NetEqImpl::GetAudioInternal(size_t max_length,
743 int16_t* output,
Peter Kastingdce40cf2015-08-24 14:52:23 -0700744 size_t* samples_per_channel,
Peter Kasting69558702016-01-12 16:26:35 -0800745 size_t* num_channels) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000746 PacketList packet_list;
747 DtmfEvent dtmf_event;
748 Operations operation;
749 bool play_dtmf;
750 int return_value = GetDecision(&operation, &packet_list, &dtmf_event,
751 &play_dtmf);
752 if (return_value != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000753 last_mode_ = kModeError;
754 return return_value;
755 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000756
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);
Peter Kasting69558702016-01-12 16:26:35 -0800869 *num_channels = sync_buffer_->Channels();
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200870 if (sync_buffer_->FutureLength() < expand_->overlap_length()) {
871 // The sync buffer should always contain |overlap_length| samples, but now
872 // too many samples have been extracted. Reinstall the |overlap_length|
873 // lookahead by moving the index.
874 const size_t missing_lookahead_samples =
875 expand_->overlap_length() - sync_buffer_->FutureLength();
henrikg91d6ede2015-09-17 00:24:34 -0700876 RTC_DCHECK_GE(sync_buffer_->next_index(), missing_lookahead_samples);
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200877 sync_buffer_->set_next_index(sync_buffer_->next_index() -
878 missing_lookahead_samples);
879 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000880 if (samples_from_sync != output_size_samples_) {
Henrik Lundind67a2192015-08-03 12:54:37 +0200881 LOG(LS_ERROR) << "samples_from_sync (" << samples_from_sync
882 << ") != output_size_samples_ (" << output_size_samples_
883 << ")";
minyue@webrtc.orgdb1cefc2013-08-13 01:39:21 +0000884 // TODO(minyue): treatment of under-run, filling zeros
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000885 memset(output, 0, num_output_samples * sizeof(int16_t));
886 *samples_per_channel = output_size_samples_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000887 return kSampleUnderrun;
888 }
889 *samples_per_channel = output_size_samples_;
890
891 // Should always have overlap samples left in the |sync_buffer_|.
henrikg91d6ede2015-09-17 00:24:34 -0700892 RTC_DCHECK_GE(sync_buffer_->FutureLength(), expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000893
894 if (play_dtmf) {
895 return_value = DtmfOverdub(dtmf_event, sync_buffer_->Channels(), output);
896 }
897
898 // Update the background noise parameters if last operation wrote data
899 // straight from the decoder to the |sync_buffer_|. That is, none of the
900 // operations that modify the signal can be followed by a parameter update.
901 if ((last_mode_ == kModeNormal) ||
902 (last_mode_ == kModeAccelerateFail) ||
903 (last_mode_ == kModePreemptiveExpandFail) ||
904 (last_mode_ == kModeRfc3389Cng) ||
905 (last_mode_ == kModeCodecInternalCng)) {
906 background_noise_->Update(*sync_buffer_, *vad_.get());
907 }
908
909 if (operation == kDtmf) {
910 // DTMF data was written the end of |sync_buffer_|.
911 // Update index to end of DTMF data in |sync_buffer_|.
912 sync_buffer_->set_dtmf_index(sync_buffer_->Size());
913 }
914
henrik.lundin@webrtc.orged865b52014-03-06 10:28:07 +0000915 if (last_mode_ != kModeExpand) {
916 // If last operation was not expand, calculate the |playout_timestamp_| from
917 // the |sync_buffer_|. However, do not update the |playout_timestamp_| if it
918 // would be moved "backwards".
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000919 uint32_t temp_timestamp = sync_buffer_->end_timestamp() -
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000920 static_cast<uint32_t>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000921 if (static_cast<int32_t>(temp_timestamp - playout_timestamp_) > 0) {
922 playout_timestamp_ = temp_timestamp;
923 }
924 } else {
925 // Use dead reckoning to estimate the |playout_timestamp_|.
Peter Kastingb7e50542015-06-11 12:55:50 -0700926 playout_timestamp_ += static_cast<uint32_t>(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000927 }
928
929 if (decode_return_value) return decode_return_value;
930 return return_value;
931}
932
933int NetEqImpl::GetDecision(Operations* operation,
934 PacketList* packet_list,
935 DtmfEvent* dtmf_event,
936 bool* play_dtmf) {
937 // Initialize output variables.
938 *play_dtmf = false;
939 *operation = kUndefined;
940
941 // Increment time counters.
942 packet_buffer_->IncrementWaitingTimes();
943 stats_.IncreaseCounter(output_size_samples_, fs_hz_);
944
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000945 assert(sync_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000946 uint32_t end_timestamp = sync_buffer_->end_timestamp();
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +0000947 if (!new_codec_) {
948 const uint32_t five_seconds_samples = 5 * fs_hz_;
949 packet_buffer_->DiscardOldPackets(end_timestamp, five_seconds_samples);
950 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000951 const RTPHeader* header = packet_buffer_->NextRtpHeader();
952
henrik.lundin@webrtc.orgca8cb952014-03-12 10:26:52 +0000953 if (decision_logic_->CngRfc3389On() || last_mode_ == kModeRfc3389Cng) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000954 // Because of timestamp peculiarities, we have to "manually" disallow using
955 // a CNG packet with the same timestamp as the one that was last played.
956 // This can happen when using redundancy and will cause the timing to shift.
henrik.lundin@webrtc.org24779fe2014-03-14 12:40:05 +0000957 while (header && decoder_database_->IsComfortNoise(header->payloadType) &&
958 (end_timestamp >= header->timestamp ||
959 end_timestamp + decision_logic_->generated_noise_samples() >
960 header->timestamp)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000961 // Don't use this packet, discard it.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000962 if (packet_buffer_->DiscardNextPacket() != PacketBuffer::kOK) {
963 assert(false); // Must be ok by design.
964 }
965 // Check buffer again.
966 if (!new_codec_) {
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +0000967 packet_buffer_->DiscardOldPackets(end_timestamp, 5 * fs_hz_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000968 }
969 header = packet_buffer_->NextRtpHeader();
970 }
971 }
972
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000973 assert(expand_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000974 const int samples_left = static_cast<int>(sync_buffer_->FutureLength() -
975 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000976 if (last_mode_ == kModeAccelerateSuccess ||
977 last_mode_ == kModeAccelerateLowEnergy ||
978 last_mode_ == kModePreemptiveExpandSuccess ||
979 last_mode_ == kModePreemptiveExpandLowEnergy) {
980 // Subtract (samples_left + output_size_samples_) from sampleMemory.
Peter Kastingdce40cf2015-08-24 14:52:23 -0700981 decision_logic_->AddSampleMemory(
982 -(samples_left + rtc::checked_cast<int>(output_size_samples_)));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000983 }
984
985 // Check if it is time to play a DTMF event.
Peter Kastingb7e50542015-06-11 12:55:50 -0700986 if (dtmf_buffer_->GetEvent(
987 static_cast<uint32_t>(
988 end_timestamp + decision_logic_->generated_noise_samples()),
989 dtmf_event)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000990 *play_dtmf = true;
991 }
992
993 // Get instruction.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000994 assert(sync_buffer_.get());
995 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000996 *operation = decision_logic_->GetDecision(*sync_buffer_,
997 *expand_,
998 decoder_frame_length_,
999 header,
1000 last_mode_,
1001 *play_dtmf,
1002 &reset_decoder_);
1003
1004 // Check if we already have enough samples in the |sync_buffer_|. If so,
1005 // change decision to normal, unless the decision was merge, accelerate, or
1006 // preemptive expand.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001007 if (samples_left >= rtc::checked_cast<int>(output_size_samples_) &&
1008 *operation != kMerge &&
1009 *operation != kAccelerate &&
1010 *operation != kFastAccelerate &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001011 *operation != kPreemptiveExpand) {
1012 *operation = kNormal;
1013 return 0;
1014 }
1015
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001016 decision_logic_->ExpandDecision(*operation);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001017
1018 // Check conditions for reset.
1019 if (new_codec_ || *operation == kUndefined) {
1020 // The only valid reason to get kUndefined is that new_codec_ is set.
1021 assert(new_codec_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001022 if (*play_dtmf && !header) {
1023 timestamp_ = dtmf_event->timestamp;
1024 } else {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001025 if (!header) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001026 LOG(LS_ERROR) << "Packet missing where it shouldn't.";
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001027 return -1;
1028 }
1029 timestamp_ = header->timestamp;
1030 if (*operation == kRfc3389CngNoPacket
1031#ifndef LEGACY_BITEXACT
1032 // Without this check, it can happen that a non-CNG packet is sent to
1033 // the CNG decoder as if it was a SID frame. This is clearly a bug,
1034 // but is kept for now to maintain bit-exactness with the test
1035 // vectors.
1036 && decoder_database_->IsComfortNoise(header->payloadType)
1037#endif
1038 ) {
1039 // Change decision to CNG packet, since we do have a CNG packet, but it
1040 // was considered too early to use. Now, use it anyway.
1041 *operation = kRfc3389Cng;
1042 } else if (*operation != kRfc3389Cng) {
1043 *operation = kNormal;
1044 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001045 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001046 // Adjust |sync_buffer_| timestamp before setting |end_timestamp| to the
1047 // new value.
1048 sync_buffer_->IncreaseEndTimestamp(timestamp_ - end_timestamp);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001049 end_timestamp = timestamp_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001050 new_codec_ = false;
1051 decision_logic_->SoftReset();
1052 buffer_level_filter_->Reset();
1053 delay_manager_->Reset();
1054 stats_.ResetMcu();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001055 }
1056
Peter Kastingdce40cf2015-08-24 14:52:23 -07001057 size_t required_samples = output_size_samples_;
1058 const size_t samples_10_ms = static_cast<size_t>(80 * fs_mult_);
1059 const size_t samples_20_ms = 2 * samples_10_ms;
1060 const size_t samples_30_ms = 3 * samples_10_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001061
1062 switch (*operation) {
1063 case kExpand: {
1064 timestamp_ = end_timestamp;
1065 return 0;
1066 }
1067 case kRfc3389CngNoPacket:
1068 case kCodecInternalCng: {
1069 return 0;
1070 }
1071 case kDtmf: {
1072 // TODO(hlundin): Write test for this.
1073 // Update timestamp.
1074 timestamp_ = end_timestamp;
1075 if (decision_logic_->generated_noise_samples() > 0 &&
1076 last_mode_ != kModeDtmf) {
1077 // Make a jump in timestamp due to the recently played comfort noise.
Peter Kastingb7e50542015-06-11 12:55:50 -07001078 uint32_t timestamp_jump =
1079 static_cast<uint32_t>(decision_logic_->generated_noise_samples());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001080 sync_buffer_->IncreaseEndTimestamp(timestamp_jump);
1081 timestamp_ += timestamp_jump;
1082 }
1083 decision_logic_->set_generated_noise_samples(0);
1084 return 0;
1085 }
Henrik Lundincf808d22015-05-27 14:33:29 +02001086 case kAccelerate:
1087 case kFastAccelerate: {
1088 // In order to do an accelerate we need at least 30 ms of audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001089 if (samples_left >= static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001090 // Already have enough data, so we do not need to extract any more.
1091 decision_logic_->set_sample_memory(samples_left);
1092 decision_logic_->set_prev_time_scale(true);
1093 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001094 } else if (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001095 decoder_frame_length_ >= samples_30_ms) {
1096 // Avoid decoding more data as it might overflow the playout buffer.
1097 *operation = kNormal;
1098 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001099 } else if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001100 decoder_frame_length_ < samples_30_ms) {
1101 // Build up decoded data by decoding at least 20 ms of audio data. Do
1102 // not perform accelerate yet, but wait until we only need to do one
1103 // decoding.
1104 required_samples = 2 * output_size_samples_;
1105 *operation = kNormal;
1106 }
1107 // If none of the above is true, we have one of two possible situations:
1108 // (1) 20 ms <= samples_left < 30 ms and decoder_frame_length_ < 30 ms; or
1109 // (2) samples_left < 10 ms and decoder_frame_length_ >= 30 ms.
1110 // In either case, we move on with the accelerate decision, and decode one
1111 // frame now.
1112 break;
1113 }
1114 case kPreemptiveExpand: {
1115 // In order to do a preemptive expand we need at least 30 ms of decoded
1116 // audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001117 if ((samples_left >= static_cast<int>(samples_30_ms)) ||
1118 (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001119 decoder_frame_length_ >= samples_30_ms)) {
1120 // Already have enough data, so we do not need to extract any more.
1121 // Or, avoid decoding more data as it might overflow the playout buffer.
1122 // Still try preemptive expand, though.
1123 decision_logic_->set_sample_memory(samples_left);
1124 decision_logic_->set_prev_time_scale(true);
1125 return 0;
1126 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07001127 if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001128 decoder_frame_length_ < samples_30_ms) {
1129 // Build up decoded data by decoding at least 20 ms of audio data.
1130 // Still try to perform preemptive expand.
1131 required_samples = 2 * output_size_samples_;
1132 }
1133 // Move on with the preemptive expand decision.
1134 break;
1135 }
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001136 case kMerge: {
1137 required_samples =
1138 std::max(merge_->RequiredFutureSamples(), required_samples);
1139 break;
1140 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001141 default: {
1142 // Do nothing.
1143 }
1144 }
1145
1146 // Get packets from buffer.
1147 int extracted_samples = 0;
1148 if (header &&
1149 *operation != kAlternativePlc &&
1150 *operation != kAlternativePlcIncreaseTimestamp &&
1151 *operation != kAudioRepetition &&
1152 *operation != kAudioRepetitionIncreaseTimestamp) {
1153 sync_buffer_->IncreaseEndTimestamp(header->timestamp - end_timestamp);
1154 if (decision_logic_->CngOff()) {
1155 // Adjustment of timestamp only corresponds to an actual packet loss
1156 // if comfort noise is not played. If comfort noise was just played,
1157 // this adjustment of timestamp is only done to get back in sync with the
1158 // stream timestamp; no loss to report.
1159 stats_.LostSamples(header->timestamp - end_timestamp);
1160 }
1161
1162 if (*operation != kRfc3389Cng) {
1163 // We are about to decode and use a non-CNG packet.
1164 decision_logic_->SetCngOff();
1165 }
1166 // Reset CNG timestamp as a new packet will be delivered.
1167 // (Also if this is a CNG packet, since playedOutTS is updated.)
1168 decision_logic_->set_generated_noise_samples(0);
1169
1170 extracted_samples = ExtractPackets(required_samples, packet_list);
1171 if (extracted_samples < 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001172 return kPacketBufferCorruption;
1173 }
1174 }
1175
Henrik Lundincf808d22015-05-27 14:33:29 +02001176 if (*operation == kAccelerate || *operation == kFastAccelerate ||
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001177 *operation == kPreemptiveExpand) {
1178 decision_logic_->set_sample_memory(samples_left + extracted_samples);
1179 decision_logic_->set_prev_time_scale(true);
1180 }
1181
Henrik Lundincf808d22015-05-27 14:33:29 +02001182 if (*operation == kAccelerate || *operation == kFastAccelerate) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001183 // Check that we have enough data (30ms) to do accelerate.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001184 if (extracted_samples + samples_left < static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001185 // TODO(hlundin): Write test for this.
1186 // Not enough, do normal operation instead.
1187 *operation = kNormal;
1188 }
1189 }
1190
1191 timestamp_ = end_timestamp;
1192 return 0;
1193}
1194
1195int NetEqImpl::Decode(PacketList* packet_list, Operations* operation,
1196 int* decoded_length,
1197 AudioDecoder::SpeechType* speech_type) {
1198 *speech_type = AudioDecoder::kSpeech;
minyuel6d92bf52015-09-23 15:20:39 +02001199
1200 // When packet_list is empty, we may be in kCodecInternalCng mode, and for
1201 // that we use current active decoder.
1202 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1203
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001204 if (!packet_list->empty()) {
1205 const Packet* packet = packet_list->front();
pkasting@chromium.org0e81fdf2015-02-02 23:54:03 +00001206 uint8_t payload_type = packet->header.payloadType;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001207 if (!decoder_database_->IsComfortNoise(payload_type)) {
1208 decoder = decoder_database_->GetDecoder(payload_type);
1209 assert(decoder);
1210 if (!decoder) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001211 LOG(LS_WARNING) << "Unknown payload type "
1212 << static_cast<int>(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001213 PacketBuffer::DeleteAllPackets(packet_list);
1214 return kDecoderNotFound;
1215 }
1216 bool decoder_changed;
1217 decoder_database_->SetActiveDecoder(payload_type, &decoder_changed);
1218 if (decoder_changed) {
1219 // We have a new decoder. Re-init some values.
1220 const DecoderDatabase::DecoderInfo* decoder_info = decoder_database_
1221 ->GetDecoderInfo(payload_type);
1222 assert(decoder_info);
1223 if (!decoder_info) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001224 LOG(LS_WARNING) << "Unknown payload type "
1225 << static_cast<int>(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001226 PacketBuffer::DeleteAllPackets(packet_list);
1227 return kDecoderNotFound;
1228 }
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001229 // If sampling rate or number of channels has changed, we need to make
1230 // a reset.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001231 if (decoder_info->fs_hz != fs_hz_ ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001232 decoder->Channels() != algorithm_buffer_->Channels()) {
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001233 // TODO(tlegrand): Add unittest to cover this event.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001234 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->Channels());
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001235 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001236 sync_buffer_->set_end_timestamp(timestamp_);
1237 playout_timestamp_ = timestamp_;
1238 }
1239 }
1240 }
1241
1242 if (reset_decoder_) {
1243 // TODO(hlundin): Write test for this.
Karl Wiberg43766482015-08-27 15:22:11 +02001244 if (decoder)
1245 decoder->Reset();
1246
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001247 // Reset comfort noise decoder.
1248 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02001249 if (cng_decoder)
1250 cng_decoder->Reset();
1251
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001252 reset_decoder_ = false;
1253 }
1254
1255#ifdef LEGACY_BITEXACT
1256 // Due to a bug in old SignalMCU, it could happen that CNG operation was
1257 // decided, but a speech packet was provided. The speech packet will be used
1258 // to update the comfort noise decoder, as if it was a SID frame, which is
1259 // clearly wrong.
1260 if (*operation == kRfc3389Cng) {
1261 return 0;
1262 }
1263#endif
1264
1265 *decoded_length = 0;
1266 // Update codec-internal PLC state.
1267 if ((*operation == kMerge) && decoder && decoder->HasDecodePlc()) {
1268 decoder->DecodePlc(1, &decoded_buffer_[*decoded_length]);
1269 }
1270
minyuel6d92bf52015-09-23 15:20:39 +02001271 int return_value;
1272 if (*operation == kCodecInternalCng) {
1273 RTC_DCHECK(packet_list->empty());
1274 return_value = DecodeCng(decoder, decoded_length, speech_type);
1275 } else {
1276 return_value = DecodeLoop(packet_list, *operation, decoder,
1277 decoded_length, speech_type);
1278 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001279
1280 if (*decoded_length < 0) {
1281 // Error returned from the decoder.
1282 *decoded_length = 0;
Peter Kastingb7e50542015-06-11 12:55:50 -07001283 sync_buffer_->IncreaseEndTimestamp(
1284 static_cast<uint32_t>(decoder_frame_length_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001285 int error_code = 0;
1286 if (decoder)
1287 error_code = decoder->ErrorCode();
1288 if (error_code != 0) {
1289 // Got some error code from the decoder.
1290 decoder_error_code_ = error_code;
1291 return_value = kDecoderErrorCode;
Henrik Lundind67a2192015-08-03 12:54:37 +02001292 LOG(LS_WARNING) << "Decoder returned error code: " << error_code;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001293 } else {
1294 // Decoder does not implement error codes. Return generic error.
1295 return_value = kOtherDecoderError;
Henrik Lundind67a2192015-08-03 12:54:37 +02001296 LOG(LS_WARNING) << "Decoder error (no error code)";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001297 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001298 *operation = kExpand; // Do expansion to get data instead.
1299 }
1300 if (*speech_type != AudioDecoder::kComfortNoise) {
1301 // Don't increment timestamp if codec returned CNG speech type
1302 // since in this case, the we will increment the CNGplayedTS counter.
1303 // Increase with number of samples per channel.
1304 assert(*decoded_length == 0 ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001305 (decoder && decoder->Channels() == sync_buffer_->Channels()));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001306 sync_buffer_->IncreaseEndTimestamp(
1307 *decoded_length / static_cast<int>(sync_buffer_->Channels()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001308 }
1309 return return_value;
1310}
1311
minyuel6d92bf52015-09-23 15:20:39 +02001312int NetEqImpl::DecodeCng(AudioDecoder* decoder, int* decoded_length,
1313 AudioDecoder::SpeechType* speech_type) {
1314 if (!decoder) {
1315 // This happens when active decoder is not defined.
1316 *decoded_length = -1;
1317 return 0;
1318 }
1319
1320 while (*decoded_length < rtc::checked_cast<int>(output_size_samples_)) {
1321 const int length = decoder->Decode(
1322 nullptr, 0, fs_hz_,
1323 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1324 &decoded_buffer_[*decoded_length], speech_type);
1325 if (length > 0) {
1326 *decoded_length += length;
minyuel6d92bf52015-09-23 15:20:39 +02001327 } else {
1328 // Error.
1329 LOG(LS_WARNING) << "Failed to decode CNG";
1330 *decoded_length = -1;
1331 break;
1332 }
1333 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1334 // Guard against overflow.
1335 LOG(LS_WARNING) << "Decoded too much CNG.";
1336 return kDecodedTooMuch;
1337 }
1338 }
1339 return 0;
1340}
1341
1342int NetEqImpl::DecodeLoop(PacketList* packet_list, const Operations& operation,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001343 AudioDecoder* decoder, int* decoded_length,
1344 AudioDecoder::SpeechType* speech_type) {
1345 Packet* packet = NULL;
1346 if (!packet_list->empty()) {
1347 packet = packet_list->front();
1348 }
minyuel6d92bf52015-09-23 15:20:39 +02001349
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001350 // Do decoding.
1351 while (packet &&
1352 !decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1353 assert(decoder); // At this point, we must have a decoder object.
1354 // The number of channels in the |sync_buffer_| should be the same as the
1355 // number decoder channels.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001356 assert(sync_buffer_->Channels() == decoder->Channels());
1357 assert(decoded_buffer_length_ >= kMaxFrameSize * decoder->Channels());
minyuel6d92bf52015-09-23 15:20:39 +02001358 assert(operation == kNormal || operation == kAccelerate ||
1359 operation == kFastAccelerate || operation == kMerge ||
1360 operation == kPreemptiveExpand);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001361 packet_list->pop_front();
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001362 size_t payload_length = packet->payload_length;
Peter Kasting36b7cc32015-06-11 19:57:18 -07001363 int decode_length;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +00001364 if (packet->sync_packet) {
1365 // Decode to silence with the same frame size as the last decode.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001366 memset(&decoded_buffer_[*decoded_length], 0,
1367 decoder_frame_length_ * decoder->Channels() *
1368 sizeof(decoded_buffer_[0]));
Peter Kastingdce40cf2015-08-24 14:52:23 -07001369 decode_length = rtc::checked_cast<int>(decoder_frame_length_);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +00001370 } else if (!packet->primary) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001371 // This is a redundant payload; call the special decoder method.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001372 decode_length = decoder->DecodeRedundant(
henrik.lundin@webrtc.org1eda4e32015-02-25 10:02:29 +00001373 packet->payload, packet->payload_length, fs_hz_,
minyue@webrtc.org7f7d7e32015-03-16 12:30:37 +00001374 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001375 &decoded_buffer_[*decoded_length], speech_type);
1376 } else {
henrik.lundin@webrtc.org1eda4e32015-02-25 10:02:29 +00001377 decode_length =
minyue@webrtc.org7f7d7e32015-03-16 12:30:37 +00001378 decoder->Decode(
1379 packet->payload, packet->payload_length, fs_hz_,
1380 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1381 &decoded_buffer_[*decoded_length], speech_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001382 }
1383
1384 delete[] packet->payload;
1385 delete packet;
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001386 packet = NULL;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001387 if (decode_length > 0) {
1388 *decoded_length += decode_length;
1389 // Update |decoder_frame_length_| with number of samples per channel.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001390 decoder_frame_length_ =
Peter Kastingdce40cf2015-08-24 14:52:23 -07001391 static_cast<size_t>(decode_length) / decoder->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001392 } else if (decode_length < 0) {
1393 // Error.
Henrik Lundind67a2192015-08-03 12:54:37 +02001394 LOG(LS_WARNING) << "Decode " << decode_length << " " << payload_length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001395 *decoded_length = -1;
1396 PacketBuffer::DeleteAllPackets(packet_list);
1397 break;
1398 }
1399 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1400 // Guard against overflow.
Henrik Lundind67a2192015-08-03 12:54:37 +02001401 LOG(LS_WARNING) << "Decoded too much.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001402 PacketBuffer::DeleteAllPackets(packet_list);
1403 return kDecodedTooMuch;
1404 }
1405 if (!packet_list->empty()) {
1406 packet = packet_list->front();
1407 } else {
1408 packet = NULL;
1409 }
1410 } // End of decode loop.
1411
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001412 // If the list is not empty at this point, either a decoding error terminated
1413 // the while-loop, or list must hold exactly one CNG packet.
1414 assert(packet_list->empty() || *decoded_length < 0 ||
1415 (packet_list->size() == 1 && packet &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001416 decoder_database_->IsComfortNoise(packet->header.payloadType)));
1417 return 0;
1418}
1419
1420void NetEqImpl::DoNormal(const int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001421 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001422 assert(normal_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001423 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001424 normal_->Process(decoded_buffer, decoded_length, last_mode_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001425 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001426 if (decoded_length != 0) {
1427 last_mode_ = kModeNormal;
1428 }
1429
1430 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1431 if ((speech_type == AudioDecoder::kComfortNoise)
1432 || ((last_mode_ == kModeCodecInternalCng)
1433 && (decoded_length == 0))) {
1434 // TODO(hlundin): Remove second part of || statement above.
1435 last_mode_ = kModeCodecInternalCng;
1436 }
1437
1438 if (!play_dtmf) {
1439 dtmf_tone_generator_->Reset();
1440 }
1441}
1442
1443void NetEqImpl::DoMerge(int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001444 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001445 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001446 assert(merge_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001447 size_t new_length = merge_->Process(decoded_buffer, decoded_length,
1448 mute_factor_array_.get(),
1449 algorithm_buffer_.get());
1450 size_t expand_length_correction = new_length -
1451 decoded_length / algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001452
1453 // Update in-call and post-call statistics.
1454 if (expand_->MuteFactor(0) == 0) {
1455 // Expand generates only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001456 stats_.ExpandedNoiseSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001457 } else {
1458 // Expansion generates more than only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001459 stats_.ExpandedVoiceSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001460 }
1461
1462 last_mode_ = kModeMerge;
1463 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1464 if (speech_type == AudioDecoder::kComfortNoise) {
1465 last_mode_ = kModeCodecInternalCng;
1466 }
1467 expand_->Reset();
1468 if (!play_dtmf) {
1469 dtmf_tone_generator_->Reset();
1470 }
1471}
1472
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001473int NetEqImpl::DoExpand(bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001474 while ((sync_buffer_->FutureLength() - expand_->overlap_length()) <
Peter Kastingdce40cf2015-08-24 14:52:23 -07001475 output_size_samples_) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001476 algorithm_buffer_->Clear();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001477 int return_value = expand_->Process(algorithm_buffer_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001478 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001479
1480 // Update in-call and post-call statistics.
1481 if (expand_->MuteFactor(0) == 0) {
1482 // Expand operation generates only noise.
1483 stats_.ExpandedNoiseSamples(length);
1484 } else {
1485 // Expand operation generates more than only noise.
1486 stats_.ExpandedVoiceSamples(length);
1487 }
1488
1489 last_mode_ = kModeExpand;
1490
1491 if (return_value < 0) {
1492 return return_value;
1493 }
1494
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001495 sync_buffer_->PushBack(*algorithm_buffer_);
1496 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001497 }
1498 if (!play_dtmf) {
1499 dtmf_tone_generator_->Reset();
1500 }
1501 return 0;
1502}
1503
Henrik Lundincf808d22015-05-27 14:33:29 +02001504int NetEqImpl::DoAccelerate(int16_t* decoded_buffer,
1505 size_t decoded_length,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001506 AudioDecoder::SpeechType speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +02001507 bool play_dtmf,
1508 bool fast_accelerate) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001509 const size_t required_samples =
1510 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001511 size_t borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001512 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001513 size_t decoded_length_per_channel = decoded_length / num_channels;
1514 if (decoded_length_per_channel < required_samples) {
1515 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001516 borrowed_samples_per_channel = static_cast<int>(required_samples -
1517 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001518 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1519 decoded_buffer,
1520 sizeof(int16_t) * decoded_length);
1521 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1522 decoded_buffer);
1523 decoded_length = required_samples * num_channels;
1524 }
1525
Peter Kastingdce40cf2015-08-24 14:52:23 -07001526 size_t samples_removed;
Henrik Lundincf808d22015-05-27 14:33:29 +02001527 Accelerate::ReturnCodes return_code =
1528 accelerate_->Process(decoded_buffer, decoded_length, fast_accelerate,
1529 algorithm_buffer_.get(), &samples_removed);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001530 stats_.AcceleratedSamples(samples_removed);
1531 switch (return_code) {
1532 case Accelerate::kSuccess:
1533 last_mode_ = kModeAccelerateSuccess;
1534 break;
1535 case Accelerate::kSuccessLowEnergy:
1536 last_mode_ = kModeAccelerateLowEnergy;
1537 break;
1538 case Accelerate::kNoStretch:
1539 last_mode_ = kModeAccelerateFail;
1540 break;
1541 case Accelerate::kError:
1542 // TODO(hlundin): Map to kModeError instead?
1543 last_mode_ = kModeAccelerateFail;
1544 return kAccelerateError;
1545 }
1546
1547 if (borrowed_samples_per_channel > 0) {
1548 // Copy borrowed samples back to the |sync_buffer_|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001549 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001550 if (length < borrowed_samples_per_channel) {
1551 // This destroys the beginning of the buffer, but will not cause any
1552 // problems.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001553 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001554 sync_buffer_->Size() -
1555 borrowed_samples_per_channel);
1556 sync_buffer_->PushFrontZeros(borrowed_samples_per_channel - length);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001557 algorithm_buffer_->PopFront(length);
1558 assert(algorithm_buffer_->Empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001559 } else {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001560 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001561 borrowed_samples_per_channel,
1562 sync_buffer_->Size() -
1563 borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001564 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001565 }
1566 }
1567
1568 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1569 if (speech_type == AudioDecoder::kComfortNoise) {
1570 last_mode_ = kModeCodecInternalCng;
1571 }
1572 if (!play_dtmf) {
1573 dtmf_tone_generator_->Reset();
1574 }
1575 expand_->Reset();
1576 return 0;
1577}
1578
1579int NetEqImpl::DoPreemptiveExpand(int16_t* decoded_buffer,
1580 size_t decoded_length,
1581 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001582 bool play_dtmf) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001583 const size_t required_samples =
1584 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001585 size_t num_channels = algorithm_buffer_->Channels();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001586 size_t borrowed_samples_per_channel = 0;
1587 size_t old_borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001588 size_t decoded_length_per_channel = decoded_length / num_channels;
1589 if (decoded_length_per_channel < required_samples) {
1590 // Must move data from the |sync_buffer_| in order to get 30 ms.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001591 borrowed_samples_per_channel =
1592 required_samples - decoded_length_per_channel;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001593 // Calculate how many of these were already played out.
Peter Kastingf045e4d2015-06-10 21:15:38 -07001594 old_borrowed_samples_per_channel =
Peter Kastingdce40cf2015-08-24 14:52:23 -07001595 (borrowed_samples_per_channel > sync_buffer_->FutureLength()) ?
1596 (borrowed_samples_per_channel - sync_buffer_->FutureLength()) : 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001597 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1598 decoded_buffer,
1599 sizeof(int16_t) * decoded_length);
1600 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1601 decoded_buffer);
1602 decoded_length = required_samples * num_channels;
1603 }
1604
Peter Kastingdce40cf2015-08-24 14:52:23 -07001605 size_t samples_added;
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001606 PreemptiveExpand::ReturnCodes return_code = preemptive_expand_->Process(
Peter Kastingdce40cf2015-08-24 14:52:23 -07001607 decoded_buffer, decoded_length,
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001608 old_borrowed_samples_per_channel,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001609 algorithm_buffer_.get(), &samples_added);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001610 stats_.PreemptiveExpandedSamples(samples_added);
1611 switch (return_code) {
1612 case PreemptiveExpand::kSuccess:
1613 last_mode_ = kModePreemptiveExpandSuccess;
1614 break;
1615 case PreemptiveExpand::kSuccessLowEnergy:
1616 last_mode_ = kModePreemptiveExpandLowEnergy;
1617 break;
1618 case PreemptiveExpand::kNoStretch:
1619 last_mode_ = kModePreemptiveExpandFail;
1620 break;
1621 case PreemptiveExpand::kError:
1622 // TODO(hlundin): Map to kModeError instead?
1623 last_mode_ = kModePreemptiveExpandFail;
1624 return kPreemptiveExpandError;
1625 }
1626
1627 if (borrowed_samples_per_channel > 0) {
1628 // Copy borrowed samples back to the |sync_buffer_|.
1629 sync_buffer_->ReplaceAtIndex(
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001630 *algorithm_buffer_, borrowed_samples_per_channel,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001631 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001632 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001633 }
1634
1635 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1636 if (speech_type == AudioDecoder::kComfortNoise) {
1637 last_mode_ = kModeCodecInternalCng;
1638 }
1639 if (!play_dtmf) {
1640 dtmf_tone_generator_->Reset();
1641 }
1642 expand_->Reset();
1643 return 0;
1644}
1645
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001646int NetEqImpl::DoRfc3389Cng(PacketList* packet_list, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001647 if (!packet_list->empty()) {
1648 // Must have exactly one SID frame at this point.
1649 assert(packet_list->size() == 1);
1650 Packet* packet = packet_list->front();
1651 packet_list->pop_front();
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001652 if (!decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1653#ifdef LEGACY_BITEXACT
1654 // This can happen due to a bug in GetDecision. Change the payload type
1655 // to a CNG type, and move on. Note that this means that we are in fact
1656 // sending a non-CNG payload to the comfort noise decoder for decoding.
1657 // Clearly wrong, but will maintain bit-exactness with legacy.
1658 if (fs_hz_ == 8000) {
1659 packet->header.payloadType =
kwibergee1879c2015-10-29 06:20:28 -07001660 decoder_database_->GetRtpPayloadType(NetEqDecoder::kDecoderCNGnb);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001661 } else if (fs_hz_ == 16000) {
1662 packet->header.payloadType =
kwibergee1879c2015-10-29 06:20:28 -07001663 decoder_database_->GetRtpPayloadType(NetEqDecoder::kDecoderCNGwb);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001664 } else if (fs_hz_ == 32000) {
kwibergee1879c2015-10-29 06:20:28 -07001665 packet->header.payloadType = decoder_database_->GetRtpPayloadType(
1666 NetEqDecoder::kDecoderCNGswb32kHz);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001667 } else if (fs_hz_ == 48000) {
kwibergee1879c2015-10-29 06:20:28 -07001668 packet->header.payloadType = decoder_database_->GetRtpPayloadType(
1669 NetEqDecoder::kDecoderCNGswb48kHz);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001670 }
1671 assert(decoder_database_->IsComfortNoise(packet->header.payloadType));
1672#else
1673 LOG(LS_ERROR) << "Trying to decode non-CNG payload as CNG.";
1674 return kOtherError;
1675#endif
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001676 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001677 // UpdateParameters() deletes |packet|.
1678 if (comfort_noise_->UpdateParameters(packet) ==
1679 ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001680 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001681 return -comfort_noise_->internal_error_code();
1682 }
1683 }
1684 int cn_return = comfort_noise_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001685 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001686 expand_->Reset();
1687 last_mode_ = kModeRfc3389Cng;
1688 if (!play_dtmf) {
1689 dtmf_tone_generator_->Reset();
1690 }
1691 if (cn_return == ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001692 decoder_error_code_ = comfort_noise_->internal_error_code();
1693 return kComfortNoiseErrorCode;
1694 } else if (cn_return == ComfortNoise::kUnknownPayloadType) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001695 return kUnknownRtpPayloadType;
1696 }
1697 return 0;
1698}
1699
minyuel6d92bf52015-09-23 15:20:39 +02001700void NetEqImpl::DoCodecInternalCng(const int16_t* decoded_buffer,
1701 size_t decoded_length) {
1702 RTC_DCHECK(normal_.get());
1703 RTC_DCHECK(mute_factor_array_.get());
1704 normal_->Process(decoded_buffer, decoded_length, last_mode_,
1705 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001706 last_mode_ = kModeCodecInternalCng;
1707 expand_->Reset();
1708}
1709
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001710int NetEqImpl::DoDtmf(const DtmfEvent& dtmf_event, bool* play_dtmf) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001711 // This block of the code and the block further down, handling |dtmf_switch|
1712 // are commented out. Otherwise playing out-of-band DTMF would fail in VoE
1713 // test, DtmfTest.ManualSuccessfullySendsOutOfBandTelephoneEvents. This is
1714 // equivalent to |dtmf_switch| always be false.
1715 //
1716 // See http://webrtc-codereview.appspot.com/1195004/ for discussion
1717 // On this issue. This change might cause some glitches at the point of
1718 // switch from audio to DTMF. Issue 1545 is filed to track this.
1719 //
1720 // bool dtmf_switch = false;
1721 // if ((last_mode_ != kModeDtmf) && dtmf_tone_generator_->initialized()) {
1722 // // Special case; see below.
1723 // // We must catch this before calling Generate, since |initialized| is
1724 // // modified in that call.
1725 // dtmf_switch = true;
1726 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001727
1728 int dtmf_return_value = 0;
1729 if (!dtmf_tone_generator_->initialized()) {
1730 // Initialize if not already done.
1731 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1732 dtmf_event.volume);
1733 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001734
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001735 if (dtmf_return_value == 0) {
1736 // Generate DTMF signal.
1737 dtmf_return_value = dtmf_tone_generator_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001738 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001739 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001740
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001741 if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001742 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001743 return dtmf_return_value;
1744 }
1745
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001746 // if (dtmf_switch) {
1747 // // This is the special case where the previous operation was DTMF
1748 // // overdub, but the current instruction is "regular" DTMF. We must make
1749 // // sure that the DTMF does not have any discontinuities. The first DTMF
1750 // // sample that we generate now must be played out immediately, therefore
1751 // // it must be copied to the speech buffer.
1752 // // TODO(hlundin): This code seems incorrect. (Legacy.) Write test and
1753 // // verify correct operation.
1754 // assert(false);
1755 // // Must generate enough data to replace all of the |sync_buffer_|
1756 // // "future".
1757 // int required_length = sync_buffer_->FutureLength();
1758 // assert(dtmf_tone_generator_->initialized());
1759 // dtmf_return_value = dtmf_tone_generator_->Generate(required_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001760 // algorithm_buffer_);
1761 // assert((size_t) required_length == algorithm_buffer_->Size());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001762 // if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001763 // algorithm_buffer_->Zeros(output_size_samples_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001764 // return dtmf_return_value;
1765 // }
1766 //
1767 // // Overwrite the "future" part of the speech buffer with the new DTMF
1768 // // data.
1769 // // TODO(hlundin): It seems that this overwriting has gone lost.
1770 // // Not adapted for multi-channel yet.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001771 // assert(algorithm_buffer_->Channels() == 1);
1772 // if (algorithm_buffer_->Channels() != 1) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001773 // LOG(LS_WARNING) << "DTMF not supported for more than one channel";
1774 // return kStereoNotSupported;
1775 // }
1776 // // Shuffle the remaining data to the beginning of algorithm buffer.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001777 // algorithm_buffer_->PopFront(sync_buffer_->FutureLength());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001778 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001779
Peter Kastingb7e50542015-06-11 12:55:50 -07001780 sync_buffer_->IncreaseEndTimestamp(
1781 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001782 expand_->Reset();
1783 last_mode_ = kModeDtmf;
1784
1785 // Set to false because the DTMF is already in the algorithm buffer.
1786 *play_dtmf = false;
1787 return 0;
1788}
1789
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001790void NetEqImpl::DoAlternativePlc(bool increase_timestamp) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001791 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001792 size_t length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001793 if (decoder && decoder->HasDecodePlc()) {
1794 // Use the decoder's packet-loss concealment.
1795 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1796 int16_t decoded_buffer[kMaxFrameSize];
1797 length = decoder->DecodePlc(1, decoded_buffer);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001798 if (length > 0)
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001799 algorithm_buffer_->PushBackInterleaved(decoded_buffer, length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001800 } else {
1801 // Do simple zero-stuffing.
1802 length = output_size_samples_;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001803 algorithm_buffer_->Zeros(length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001804 // By not advancing the timestamp, NetEq inserts samples.
1805 stats_.AddZeros(length);
1806 }
1807 if (increase_timestamp) {
Peter Kastingb7e50542015-06-11 12:55:50 -07001808 sync_buffer_->IncreaseEndTimestamp(static_cast<uint32_t>(length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001809 }
1810 expand_->Reset();
1811}
1812
1813int NetEqImpl::DtmfOverdub(const DtmfEvent& dtmf_event, size_t num_channels,
1814 int16_t* output) const {
1815 size_t out_index = 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001816 size_t overdub_length = output_size_samples_; // Default value.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001817
1818 if (sync_buffer_->dtmf_index() > sync_buffer_->next_index()) {
1819 // Special operation for transition from "DTMF only" to "DTMF overdub".
1820 out_index = std::min(
1821 sync_buffer_->dtmf_index() - sync_buffer_->next_index(),
Peter Kastingdce40cf2015-08-24 14:52:23 -07001822 output_size_samples_);
1823 overdub_length = output_size_samples_ - out_index;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001824 }
1825
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001826 AudioMultiVector dtmf_output(num_channels);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001827 int dtmf_return_value = 0;
1828 if (!dtmf_tone_generator_->initialized()) {
1829 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1830 dtmf_event.volume);
1831 }
1832 if (dtmf_return_value == 0) {
1833 dtmf_return_value = dtmf_tone_generator_->Generate(overdub_length,
1834 &dtmf_output);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001835 assert(overdub_length == dtmf_output.Size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001836 }
1837 dtmf_output.ReadInterleaved(overdub_length, &output[out_index]);
1838 return dtmf_return_value < 0 ? dtmf_return_value : 0;
1839}
1840
Peter Kastingdce40cf2015-08-24 14:52:23 -07001841int NetEqImpl::ExtractPackets(size_t required_samples,
1842 PacketList* packet_list) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001843 bool first_packet = true;
1844 uint8_t prev_payload_type = 0;
1845 uint32_t prev_timestamp = 0;
1846 uint16_t prev_sequence_number = 0;
1847 bool next_packet_available = false;
1848
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001849 const RTPHeader* header = packet_buffer_->NextRtpHeader();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001850 assert(header);
1851 if (!header) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001852 LOG(LS_ERROR) << "Packet buffer unexpectedly empty.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001853 return -1;
1854 }
turaj@webrtc.org7df97062013-08-02 18:07:13 +00001855 uint32_t first_timestamp = header->timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001856 int extracted_samples = 0;
1857
1858 // Packet extraction loop.
1859 do {
1860 timestamp_ = header->timestamp;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001861 size_t discard_count = 0;
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001862 Packet* packet = packet_buffer_->GetNextPacket(&discard_count);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001863 // |header| may be invalid after the |packet_buffer_| operation.
1864 header = NULL;
1865 if (!packet) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001866 LOG(LS_ERROR) << "Should always be able to extract a packet here";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001867 assert(false); // Should always be able to extract a packet here.
1868 return -1;
1869 }
1870 stats_.PacketsDiscarded(discard_count);
1871 // Store waiting time in ms; packets->waiting_time is in "output blocks".
1872 stats_.StoreWaitingTime(packet->waiting_time * kOutputSizeMs);
1873 assert(packet->payload_length > 0);
1874 packet_list->push_back(packet); // Store packet in list.
1875
1876 if (first_packet) {
1877 first_packet = false;
henrik.lundin48ed9302015-10-29 05:36:24 -07001878 if (nack_enabled_) {
1879 RTC_DCHECK(nack_);
1880 // TODO(henrik.lundin): Should we update this for all decoded packets?
1881 nack_->UpdateLastDecodedPacket(packet->header.sequenceNumber,
1882 packet->header.timestamp);
1883 }
1884 prev_sequence_number = packet->header.sequenceNumber;
1885 prev_timestamp = packet->header.timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001886 prev_payload_type = packet->header.payloadType;
1887 }
1888
1889 // Store number of extracted samples.
1890 int packet_duration = 0;
1891 AudioDecoder* decoder = decoder_database_->GetDecoder(
1892 packet->header.payloadType);
1893 if (decoder) {
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001894 if (packet->sync_packet) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001895 packet_duration = rtc::checked_cast<int>(decoder_frame_length_);
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001896 } else {
minyue@webrtc.org2c1bcf22015-02-17 10:17:09 +00001897 if (packet->primary) {
1898 packet_duration = decoder->PacketDuration(packet->payload,
1899 packet->payload_length);
1900 } else {
1901 packet_duration = decoder->
1902 PacketDurationRedundant(packet->payload, packet->payload_length);
1903 stats_.SecondaryDecodedSamples(packet_duration);
1904 }
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001905 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001906 } else {
Henrik Lundind67a2192015-08-03 12:54:37 +02001907 LOG(LS_WARNING) << "Unknown payload type "
1908 << static_cast<int>(packet->header.payloadType);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001909 assert(false);
1910 }
1911 if (packet_duration <= 0) {
1912 // Decoder did not return a packet duration. Assume that the packet
1913 // contains the same number of samples as the previous one.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001914 packet_duration = rtc::checked_cast<int>(decoder_frame_length_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001915 }
1916 extracted_samples = packet->header.timestamp - first_timestamp +
1917 packet_duration;
1918
1919 // Check what packet is available next.
1920 header = packet_buffer_->NextRtpHeader();
1921 next_packet_available = false;
1922 if (header && prev_payload_type == header->payloadType) {
1923 int16_t seq_no_diff = header->sequenceNumber - prev_sequence_number;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001924 size_t ts_diff = header->timestamp - prev_timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001925 if (seq_no_diff == 1 ||
1926 (seq_no_diff == 0 && ts_diff == decoder_frame_length_)) {
1927 // The next sequence number is available, or the next part of a packet
1928 // that was split into pieces upon insertion.
1929 next_packet_available = true;
1930 }
1931 prev_sequence_number = header->sequenceNumber;
1932 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07001933 } while (extracted_samples < rtc::checked_cast<int>(required_samples) &&
1934 next_packet_available);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001935
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00001936 if (extracted_samples > 0) {
1937 // Delete old packets only when we are going to decode something. Otherwise,
1938 // we could end up in the situation where we never decode anything, since
1939 // all incoming packets are considered too old but the buffer will also
1940 // never be flooded and flushed.
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001941 packet_buffer_->DiscardAllOldPackets(timestamp_);
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00001942 }
1943
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001944 return extracted_samples;
1945}
1946
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001947void NetEqImpl::UpdatePlcComponents(int fs_hz, size_t channels) {
1948 // Delete objects and create new ones.
1949 expand_.reset(expand_factory_->Create(background_noise_.get(),
1950 sync_buffer_.get(), &random_vector_,
Henrik Lundinbef77e22015-08-18 14:58:09 +02001951 &stats_, fs_hz, channels));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001952 merge_.reset(new Merge(fs_hz, channels, expand_.get(), sync_buffer_.get()));
1953}
1954
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001955void NetEqImpl::SetSampleRateAndChannels(int fs_hz, size_t channels) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001956 LOG(LS_VERBOSE) << "SetSampleRateAndChannels " << fs_hz << " " << channels;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001957 // TODO(hlundin): Change to an enumerator and skip assert.
1958 assert(fs_hz == 8000 || fs_hz == 16000 || fs_hz == 32000 || fs_hz == 48000);
1959 assert(channels > 0);
1960
1961 fs_hz_ = fs_hz;
1962 fs_mult_ = fs_hz / 8000;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001963 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001964 decoder_frame_length_ = 3 * output_size_samples_; // Initialize to 30ms.
1965
1966 last_mode_ = kModeNormal;
1967
1968 // Create a new array of mute factors and set all to 1.
1969 mute_factor_array_.reset(new int16_t[channels]);
1970 for (size_t i = 0; i < channels; ++i) {
1971 mute_factor_array_[i] = 16384; // 1.0 in Q14.
1972 }
1973
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001974 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02001975 if (cng_decoder)
1976 cng_decoder->Reset();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001977
1978 // Reinit post-decode VAD with new sample rate.
1979 assert(vad_.get()); // Cannot be NULL here.
1980 vad_->Init();
1981
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001982 // Delete algorithm buffer and create a new one.
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001983 algorithm_buffer_.reset(new AudioMultiVector(channels));
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001984
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001985 // Delete sync buffer and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001986 sync_buffer_.reset(new SyncBuffer(channels, kSyncBufferSize * fs_mult_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001987
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00001988 // Delete BackgroundNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001989 background_noise_.reset(new BackgroundNoise(channels));
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00001990 background_noise_->set_mode(background_noise_mode_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001991
1992 // Reset random vector.
1993 random_vector_.Reset();
1994
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001995 UpdatePlcComponents(fs_hz, channels);
1996
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001997 // Move index so that we create a small set of future samples (all 0).
1998 sync_buffer_->set_next_index(sync_buffer_->next_index() -
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001999 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002000
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002001 normal_.reset(new Normal(fs_hz, decoder_database_.get(), *background_noise_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002002 expand_.get()));
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +00002003 accelerate_.reset(
2004 accelerate_factory_->Create(fs_hz, channels, *background_noise_));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002005 preemptive_expand_.reset(preemptive_expand_factory_->Create(
Peter Kastingdce40cf2015-08-24 14:52:23 -07002006 fs_hz, channels, *background_noise_, expand_->overlap_length()));
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002007
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002008 // Delete ComfortNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002009 comfort_noise_.reset(new ComfortNoise(fs_hz, decoder_database_.get(),
2010 sync_buffer_.get()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002011
2012 // Verify that |decoded_buffer_| is long enough.
2013 if (decoded_buffer_length_ < kMaxFrameSize * channels) {
2014 // Reallocate to larger size.
2015 decoded_buffer_length_ = kMaxFrameSize * channels;
2016 decoded_buffer_.reset(new int16_t[decoded_buffer_length_]);
2017 }
2018
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002019 // Create DecisionLogic if it is not created yet, then communicate new sample
2020 // rate and output size to DecisionLogic object.
2021 if (!decision_logic_.get()) {
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002022 CreateDecisionLogic();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002023 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002024 decision_logic_->SetSampleRate(fs_hz_, output_size_samples_);
2025}
2026
2027NetEqOutputType NetEqImpl::LastOutputType() {
2028 assert(vad_.get());
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002029 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002030 if (last_mode_ == kModeCodecInternalCng || last_mode_ == kModeRfc3389Cng) {
2031 return kOutputCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002032 } else if (last_mode_ == kModeExpand && expand_->MuteFactor(0) == 0) {
2033 // Expand mode has faded down to background noise only (very long expand).
2034 return kOutputPLCtoCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002035 } else if (last_mode_ == kModeExpand) {
2036 return kOutputPLC;
wu@webrtc.org24301a62013-12-13 19:17:43 +00002037 } else if (vad_->running() && !vad_->active_speech()) {
2038 return kOutputVADPassive;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002039 } else {
2040 return kOutputNormal;
2041 }
2042}
2043
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002044void NetEqImpl::CreateDecisionLogic() {
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002045 decision_logic_.reset(DecisionLogic::Create(fs_hz_, output_size_samples_,
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002046 playout_mode_,
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002047 decoder_database_.get(),
2048 *packet_buffer_.get(),
2049 delay_manager_.get(),
2050 buffer_level_filter_.get()));
2051}
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002052} // namespace webrtc