blob: f899d072176dd16e4b10d93447ffae2df44e6d72 [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.lundin6d8e0112016-03-04 10:34:21 -0800151int NetEqImpl::GetAudio(AudioFrame* audio_frame, NetEqOutputType* type) {
henrik.lundine1ca1672016-01-08 03:50:08 -0800152 TRACE_EVENT0("webrtc", "NetEqImpl::GetAudio");
Tommi9090e0b2016-01-20 13:39:36 +0100153 rtc::CritScope lock(&crit_sect_);
henrik.lundin6d8e0112016-03-04 10:34:21 -0800154 int error = GetAudioInternal(audio_frame);
155 RTC_DCHECK_EQ(
156 audio_frame->sample_rate_hz_,
157 rtc::checked_cast<int>(audio_frame->samples_per_channel_ * 100));
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.lundin6d8e0112016-03-04 10:34:21 -0800165 last_output_sample_rate_hz_ = audio_frame->sample_rate_hz_;
henrik.lundind89814b2015-11-23 06:49:25 -0800166 RTC_DCHECK(last_output_sample_rate_hz_ == 8000 ||
167 last_output_sample_rate_hz_ == 16000 ||
168 last_output_sample_rate_hz_ == 32000 ||
169 last_output_sample_rate_hz_ == 48000)
170 << "Unexpected sample rate " << last_output_sample_rate_hz_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000171 return kOK;
172}
173
kwibergee1879c2015-10-29 06:20:28 -0700174int NetEqImpl::RegisterPayloadType(NetEqDecoder codec,
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800175 const std::string& name,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000176 uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100177 rtc::CritScope lock(&crit_sect_);
Henrik Lundind67a2192015-08-03 12:54:37 +0200178 LOG(LS_VERBOSE) << "RegisterPayloadType "
kwibergee1879c2015-10-29 06:20:28 -0700179 << static_cast<int>(rtp_payload_type) << " "
180 << static_cast<int>(codec);
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800181 int ret = decoder_database_->RegisterPayload(rtp_payload_type, codec, name);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000182 if (ret != DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000183 switch (ret) {
184 case DecoderDatabase::kInvalidRtpPayloadType:
185 error_code_ = kInvalidRtpPayloadType;
186 break;
187 case DecoderDatabase::kCodecNotSupported:
188 error_code_ = kCodecNotSupported;
189 break;
190 case DecoderDatabase::kDecoderExists:
191 error_code_ = kDecoderExists;
192 break;
193 default:
194 error_code_ = kOtherError;
195 }
196 return kFail;
197 }
198 return kOK;
199}
200
201int NetEqImpl::RegisterExternalDecoder(AudioDecoder* decoder,
kwibergee1879c2015-10-29 06:20:28 -0700202 NetEqDecoder codec,
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800203 const std::string& codec_name,
Karl Wibergd8399e62015-05-25 14:39:56 +0200204 uint8_t rtp_payload_type,
205 int sample_rate_hz) {
Tommi9090e0b2016-01-20 13:39:36 +0100206 rtc::CritScope lock(&crit_sect_);
Henrik Lundind67a2192015-08-03 12:54:37 +0200207 LOG(LS_VERBOSE) << "RegisterExternalDecoder "
kwibergee1879c2015-10-29 06:20:28 -0700208 << static_cast<int>(rtp_payload_type) << " "
209 << static_cast<int>(codec);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000210 if (!decoder) {
211 LOG(LS_ERROR) << "Cannot register external decoder with NULL pointer";
212 assert(false);
213 return kFail;
214 }
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800215 int ret = decoder_database_->InsertExternal(
216 rtp_payload_type, codec, codec_name, sample_rate_hz, decoder);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000217 if (ret != DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000218 switch (ret) {
219 case DecoderDatabase::kInvalidRtpPayloadType:
220 error_code_ = kInvalidRtpPayloadType;
221 break;
222 case DecoderDatabase::kCodecNotSupported:
223 error_code_ = kCodecNotSupported;
224 break;
225 case DecoderDatabase::kDecoderExists:
226 error_code_ = kDecoderExists;
227 break;
228 case DecoderDatabase::kInvalidSampleRate:
229 error_code_ = kInvalidSampleRate;
230 break;
231 case DecoderDatabase::kInvalidPointer:
232 error_code_ = kInvalidPointer;
233 break;
234 default:
235 error_code_ = kOtherError;
236 }
237 return kFail;
238 }
239 return kOK;
240}
241
242int NetEqImpl::RemovePayloadType(uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100243 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000244 int ret = decoder_database_->Remove(rtp_payload_type);
245 if (ret == DecoderDatabase::kOK) {
246 return kOK;
247 } else if (ret == DecoderDatabase::kDecoderNotFound) {
248 error_code_ = kDecoderNotFound;
249 } else {
250 error_code_ = kOtherError;
251 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000252 return kFail;
253}
254
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000255bool NetEqImpl::SetMinimumDelay(int delay_ms) {
Tommi9090e0b2016-01-20 13:39:36 +0100256 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000257 if (delay_ms >= 0 && delay_ms < 10000) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000258 assert(delay_manager_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000259 return delay_manager_->SetMinimumDelay(delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000260 }
261 return false;
262}
263
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000264bool NetEqImpl::SetMaximumDelay(int delay_ms) {
Tommi9090e0b2016-01-20 13:39:36 +0100265 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000266 if (delay_ms >= 0 && delay_ms < 10000) {
267 assert(delay_manager_.get());
268 return delay_manager_->SetMaximumDelay(delay_ms);
269 }
270 return false;
271}
272
273int NetEqImpl::LeastRequiredDelayMs() const {
Tommi9090e0b2016-01-20 13:39:36 +0100274 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000275 assert(delay_manager_.get());
276 return delay_manager_->least_required_delay_ms();
277}
278
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200279int NetEqImpl::SetTargetDelay() {
280 return kNotImplemented;
281}
282
283int NetEqImpl::TargetDelay() {
284 return kNotImplemented;
285}
286
henrik.lundin9c3efd02015-08-27 13:12:22 -0700287int NetEqImpl::CurrentDelayMs() const {
Tommi9090e0b2016-01-20 13:39:36 +0100288 rtc::CritScope lock(&crit_sect_);
henrik.lundin9c3efd02015-08-27 13:12:22 -0700289 if (fs_hz_ == 0)
290 return 0;
291 // Sum up the samples in the packet buffer with the future length of the sync
292 // buffer, and divide the sum by the sample rate.
293 const size_t delay_samples =
294 packet_buffer_->NumSamplesInBuffer(decoder_database_.get(),
295 decoder_frame_length_) +
296 sync_buffer_->FutureLength();
297 // The division below will truncate.
298 const int delay_ms =
299 static_cast<int>(delay_samples) / rtc::CheckedDivExact(fs_hz_, 1000);
300 return delay_ms;
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200301}
302
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000303// Deprecated.
304// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000305void NetEqImpl::SetPlayoutMode(NetEqPlayoutMode mode) {
Tommi9090e0b2016-01-20 13:39:36 +0100306 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000307 if (mode != playout_mode_) {
308 playout_mode_ = mode;
309 CreateDecisionLogic();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000310 }
311}
312
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000313// Deprecated.
314// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000315NetEqPlayoutMode NetEqImpl::PlayoutMode() const {
Tommi9090e0b2016-01-20 13:39:36 +0100316 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000317 return playout_mode_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000318}
319
320int NetEqImpl::NetworkStatistics(NetEqNetworkStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100321 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000322 assert(decoder_database_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700323 const size_t total_samples_in_buffers =
Peter Kasting728d9032015-06-11 14:31:38 -0700324 packet_buffer_->NumSamplesInBuffer(decoder_database_.get(),
325 decoder_frame_length_) +
Peter Kastingdce40cf2015-08-24 14:52:23 -0700326 sync_buffer_->FutureLength();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000327 assert(delay_manager_.get());
328 assert(decision_logic_.get());
329 stats_.GetNetworkStatistics(fs_hz_, total_samples_in_buffers,
330 decoder_frame_length_, *delay_manager_.get(),
331 *decision_logic_.get(), stats);
332 return 0;
333}
334
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000335void NetEqImpl::GetRtcpStatistics(RtcpStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100336 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000337 if (stats) {
338 rtcp_.GetStatistics(false, stats);
339 }
340}
341
342void NetEqImpl::GetRtcpStatisticsNoReset(RtcpStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100343 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000344 if (stats) {
345 rtcp_.GetStatistics(true, stats);
346 }
347}
348
349void NetEqImpl::EnableVad() {
Tommi9090e0b2016-01-20 13:39:36 +0100350 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000351 assert(vad_.get());
352 vad_->Enable();
353}
354
355void NetEqImpl::DisableVad() {
Tommi9090e0b2016-01-20 13:39:36 +0100356 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000357 assert(vad_.get());
358 vad_->Disable();
359}
360
wu@webrtc.org94454b72014-06-05 20:34:08 +0000361bool NetEqImpl::GetPlayoutTimestamp(uint32_t* timestamp) {
Tommi9090e0b2016-01-20 13:39:36 +0100362 rtc::CritScope lock(&crit_sect_);
wu@webrtc.org94454b72014-06-05 20:34:08 +0000363 if (first_packet_) {
364 // We don't have a valid RTP timestamp until we have decoded our first
365 // RTP packet.
366 return false;
367 }
368 *timestamp = timestamp_scaler_->ToExternal(playout_timestamp_);
369 return true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000370}
371
henrik.lundind89814b2015-11-23 06:49:25 -0800372int NetEqImpl::last_output_sample_rate_hz() const {
Tommi9090e0b2016-01-20 13:39:36 +0100373 rtc::CritScope lock(&crit_sect_);
henrik.lundind89814b2015-11-23 06:49:25 -0800374 return last_output_sample_rate_hz_;
375}
376
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200377int NetEqImpl::SetTargetNumberOfChannels() {
378 return kNotImplemented;
379}
380
381int NetEqImpl::SetTargetSampleRate() {
382 return kNotImplemented;
383}
384
henrik.lundin@webrtc.orgb0f4b3d2014-11-04 08:53:10 +0000385int NetEqImpl::LastError() const {
Tommi9090e0b2016-01-20 13:39:36 +0100386 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000387 return error_code_;
388}
389
390int NetEqImpl::LastDecoderError() {
Tommi9090e0b2016-01-20 13:39:36 +0100391 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000392 return decoder_error_code_;
393}
394
395void NetEqImpl::FlushBuffers() {
Tommi9090e0b2016-01-20 13:39:36 +0100396 rtc::CritScope lock(&crit_sect_);
Henrik Lundind67a2192015-08-03 12:54:37 +0200397 LOG(LS_VERBOSE) << "FlushBuffers";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000398 packet_buffer_->Flush();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000399 assert(sync_buffer_.get());
400 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000401 sync_buffer_->Flush();
402 sync_buffer_->set_next_index(sync_buffer_->next_index() -
403 expand_->overlap_length());
404 // Set to wait for new codec.
405 first_packet_ = true;
406}
407
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000408void NetEqImpl::PacketBufferStatistics(int* current_num_packets,
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000409 int* max_num_packets) const {
Tommi9090e0b2016-01-20 13:39:36 +0100410 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000411 packet_buffer_->BufferStat(current_num_packets, max_num_packets);
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000412}
413
henrik.lundin48ed9302015-10-29 05:36:24 -0700414void NetEqImpl::EnableNack(size_t max_nack_list_size) {
Tommi9090e0b2016-01-20 13:39:36 +0100415 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700416 if (!nack_enabled_) {
417 const int kNackThresholdPackets = 2;
418 nack_.reset(Nack::Create(kNackThresholdPackets));
419 nack_enabled_ = true;
420 nack_->UpdateSampleRate(fs_hz_);
421 }
422 nack_->SetMaxNackListSize(max_nack_list_size);
423}
424
425void NetEqImpl::DisableNack() {
Tommi9090e0b2016-01-20 13:39:36 +0100426 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700427 nack_.reset();
428 nack_enabled_ = false;
429}
430
431std::vector<uint16_t> NetEqImpl::GetNackList(int64_t round_trip_time_ms) const {
Tommi9090e0b2016-01-20 13:39:36 +0100432 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700433 if (!nack_enabled_) {
434 return std::vector<uint16_t>();
435 }
436 RTC_DCHECK(nack_.get());
437 return nack_->GetNackList(round_trip_time_ms);
minyue@webrtc.orgd7301772013-08-29 00:58:14 +0000438}
439
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000440const SyncBuffer* NetEqImpl::sync_buffer_for_test() const {
Tommi9090e0b2016-01-20 13:39:36 +0100441 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000442 return sync_buffer_.get();
443}
444
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000445// Methods below this line are private.
446
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000447int NetEqImpl::InsertPacketInternal(const WebRtcRTPHeader& rtp_header,
kwibergee2bac22015-11-11 10:34:00 -0800448 rtc::ArrayView<const uint8_t> payload,
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000449 uint32_t receive_timestamp,
450 bool is_sync_packet) {
kwibergee2bac22015-11-11 10:34:00 -0800451 if (payload.empty()) {
452 LOG_F(LS_ERROR) << "payload is empty";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000453 return kInvalidPointer;
454 }
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000455 // Sanity checks for sync-packets.
456 if (is_sync_packet) {
457 if (decoder_database_->IsDtmf(rtp_header.header.payloadType) ||
458 decoder_database_->IsRed(rtp_header.header.payloadType) ||
459 decoder_database_->IsComfortNoise(rtp_header.header.payloadType)) {
460 LOG_F(LS_ERROR) << "Sync-packet with an unacceptable payload type "
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000461 << static_cast<int>(rtp_header.header.payloadType);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000462 return kSyncPacketNotAccepted;
463 }
464 if (first_packet_ ||
465 rtp_header.header.payloadType != current_rtp_payload_type_ ||
466 rtp_header.header.ssrc != ssrc_) {
467 // Even if |current_rtp_payload_type_| is 0xFF, sync-packet isn't
468 // accepted.
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000469 LOG_F(LS_ERROR)
470 << "Changing codec, SSRC or first packet with sync-packet.";
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000471 return kSyncPacketNotAccepted;
472 }
473 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000474 PacketList packet_list;
475 RTPHeader main_header;
476 {
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000477 // Convert to Packet.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000478 // Create |packet| within this separate scope, since it should not be used
479 // directly once it's been inserted in the packet list. This way, |packet|
480 // is not defined outside of this block.
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000481 Packet* packet = new Packet;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000482 packet->header.markerBit = false;
483 packet->header.payloadType = rtp_header.header.payloadType;
484 packet->header.sequenceNumber = rtp_header.header.sequenceNumber;
485 packet->header.timestamp = rtp_header.header.timestamp;
486 packet->header.ssrc = rtp_header.header.ssrc;
487 packet->header.numCSRCs = 0;
kwibergee2bac22015-11-11 10:34:00 -0800488 packet->payload_length = payload.size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000489 packet->primary = true;
490 packet->waiting_time = 0;
491 packet->payload = new uint8_t[packet->payload_length];
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000492 packet->sync_packet = is_sync_packet;
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +0000493 if (!packet->payload) {
494 LOG_F(LS_ERROR) << "Payload pointer is NULL.";
495 }
kwibergee2bac22015-11-11 10:34:00 -0800496 assert(!payload.empty()); // Already checked above.
497 memcpy(packet->payload, payload.data(), packet->payload_length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000498 // Insert packet in a packet list.
499 packet_list.push_back(packet);
500 // Save main payloads header for later.
501 memcpy(&main_header, &packet->header, sizeof(main_header));
502 }
503
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000504 bool update_sample_rate_and_channels = false;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000505 // Reinitialize NetEq if it's needed (changed SSRC or first call).
506 if ((main_header.ssrc != ssrc_) || first_packet_) {
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000507 // Note: |first_packet_| will be cleared further down in this method, once
508 // the packet has been successfully inserted into the packet buffer.
509
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000510 rtcp_.Init(main_header.sequenceNumber);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000511
512 // Flush the packet buffer and DTMF buffer.
513 packet_buffer_->Flush();
514 dtmf_buffer_->Flush();
515
516 // Store new SSRC.
517 ssrc_ = main_header.ssrc;
518
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000519 // Update audio buffer timestamp.
520 sync_buffer_->IncreaseEndTimestamp(main_header.timestamp - timestamp_);
521
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000522 // Update codecs.
523 timestamp_ = main_header.timestamp;
524 current_rtp_payload_type_ = main_header.payloadType;
525
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000526 // Reset timestamp scaling.
527 timestamp_scaler_->Reset();
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000528
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000529 // Trigger an update of sampling rate and the number of channels.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000530 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000531 }
532
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000533 // Update RTCP statistics, only for regular packets.
534 if (!is_sync_packet)
535 rtcp_.Update(main_header, receive_timestamp);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000536
537 // Check for RED payload type, and separate payloads into several packets.
538 if (decoder_database_->IsRed(main_header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000539 assert(!is_sync_packet); // We had a sanity check for this.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000540 if (payload_splitter_->SplitRed(&packet_list) != PayloadSplitter::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000541 PacketBuffer::DeleteAllPackets(&packet_list);
542 return kRedundancySplitError;
543 }
544 // Only accept a few RED payloads of the same type as the main data,
545 // DTMF events and CNG.
546 payload_splitter_->CheckRedPayloads(&packet_list, *decoder_database_);
547 // Update the stored main payload header since the main payload has now
548 // changed.
549 memcpy(&main_header, &packet_list.front()->header, sizeof(main_header));
550 }
551
552 // Check payload types.
553 if (decoder_database_->CheckPayloadTypes(packet_list) ==
554 DecoderDatabase::kDecoderNotFound) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000555 PacketBuffer::DeleteAllPackets(&packet_list);
556 return kUnknownRtpPayloadType;
557 }
558
559 // Scale timestamp to internal domain (only for some codecs).
560 timestamp_scaler_->ToInternal(&packet_list);
561
562 // Process DTMF payloads. Cycle through the list of packets, and pick out any
563 // DTMF payloads found.
564 PacketList::iterator it = packet_list.begin();
565 while (it != packet_list.end()) {
566 Packet* current_packet = (*it);
567 assert(current_packet);
568 assert(current_packet->payload);
569 if (decoder_database_->IsDtmf(current_packet->header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000570 assert(!current_packet->sync_packet); // We had a sanity check for this.
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000571 DtmfEvent event;
572 int ret = DtmfBuffer::ParseEvent(
573 current_packet->header.timestamp,
574 current_packet->payload,
575 current_packet->payload_length,
576 &event);
577 if (ret != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000578 PacketBuffer::DeleteAllPackets(&packet_list);
579 return kDtmfParsingError;
580 }
581 if (dtmf_buffer_->InsertEvent(event) != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000582 PacketBuffer::DeleteAllPackets(&packet_list);
583 return kDtmfInsertError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000584 }
585 // TODO(hlundin): Let the destructor of Packet handle the payload.
586 delete [] current_packet->payload;
587 delete current_packet;
588 it = packet_list.erase(it);
589 } else {
590 ++it;
591 }
592 }
593
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000594 // Check for FEC in packets, and separate payloads into several packets.
595 int ret = payload_splitter_->SplitFec(&packet_list, decoder_database_.get());
596 if (ret != PayloadSplitter::kOK) {
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000597 PacketBuffer::DeleteAllPackets(&packet_list);
598 switch (ret) {
599 case PayloadSplitter::kUnknownPayloadType:
600 return kUnknownRtpPayloadType;
601 default:
602 return kOtherError;
603 }
604 }
605
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000606 // Split payloads into smaller chunks. This also verifies that all payloads
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000607 // are of a known payload type. SplitAudio() method is protected against
608 // sync-packets.
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +0000609 ret = payload_splitter_->SplitAudio(&packet_list, *decoder_database_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000610 if (ret != PayloadSplitter::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000611 PacketBuffer::DeleteAllPackets(&packet_list);
612 switch (ret) {
613 case PayloadSplitter::kUnknownPayloadType:
614 return kUnknownRtpPayloadType;
615 case PayloadSplitter::kFrameSplitError:
616 return kFrameSplitError;
617 default:
618 return kOtherError;
619 }
620 }
621
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000622 // Update bandwidth estimate, if the packet is not sync-packet.
623 if (!packet_list.empty() && !packet_list.front()->sync_packet) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000624 // The list can be empty here if we got nothing but DTMF payloads.
625 AudioDecoder* decoder =
626 decoder_database_->GetDecoder(main_header.payloadType);
627 assert(decoder); // Should always get a valid object, since we have
628 // already checked that the payload types are known.
629 decoder->IncomingPacket(packet_list.front()->payload,
630 packet_list.front()->payload_length,
631 packet_list.front()->header.sequenceNumber,
632 packet_list.front()->header.timestamp,
633 receive_timestamp);
634 }
635
henrik.lundin48ed9302015-10-29 05:36:24 -0700636 if (nack_enabled_) {
637 RTC_DCHECK(nack_);
638 if (update_sample_rate_and_channels) {
639 nack_->Reset();
640 }
641 nack_->UpdateLastReceivedPacket(packet_list.front()->header.sequenceNumber,
642 packet_list.front()->header.timestamp);
643 }
644
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000645 // Insert packets in buffer.
henrik.lundin116c84e2015-08-27 13:14:48 -0700646 const size_t buffer_length_before_insert =
647 packet_buffer_->NumPacketsInBuffer();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000648 ret = packet_buffer_->InsertPacketList(
649 &packet_list,
650 *decoder_database_,
651 &current_rtp_payload_type_,
652 &current_cng_rtp_payload_type_);
653 if (ret == PacketBuffer::kFlushed) {
654 // Reset DSP timestamp etc. if packet buffer flushed.
655 new_codec_ = true;
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000656 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000657 } else if (ret != PacketBuffer::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000658 PacketBuffer::DeleteAllPackets(&packet_list);
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000659 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000660 }
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000661
662 if (first_packet_) {
663 first_packet_ = false;
664 // Update the codec on the next GetAudio call.
665 new_codec_ = true;
666 }
667
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000668 if (current_rtp_payload_type_ != 0xFF) {
669 const DecoderDatabase::DecoderInfo* dec_info =
670 decoder_database_->GetDecoderInfo(current_rtp_payload_type_);
671 if (!dec_info) {
672 assert(false); // Already checked that the payload type is known.
673 }
674 }
675
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000676 if (update_sample_rate_and_channels && !packet_buffer_->Empty()) {
677 // We do not use |current_rtp_payload_type_| to |set payload_type|, but
678 // get the next RTP header from |packet_buffer_| to obtain the payload type.
679 // The reason for it is the following corner case. If NetEq receives a
680 // CNG packet with a sample rate different than the current CNG then it
681 // flushes its buffer, assuming send codec must have been changed. However,
682 // payload type of the hypothetically new send codec is not known.
683 const RTPHeader* rtp_header = packet_buffer_->NextRtpHeader();
684 assert(rtp_header);
685 int payload_type = rtp_header->payloadType;
686 AudioDecoder* decoder = decoder_database_->GetDecoder(payload_type);
687 assert(decoder); // Payloads are already checked to be valid.
688 const DecoderDatabase::DecoderInfo* decoder_info =
689 decoder_database_->GetDecoderInfo(payload_type);
690 assert(decoder_info);
691 if (decoder_info->fs_hz != fs_hz_ ||
henrik.lundin48ed9302015-10-29 05:36:24 -0700692 decoder->Channels() != algorithm_buffer_->Channels()) {
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +0000693 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->Channels());
henrik.lundin48ed9302015-10-29 05:36:24 -0700694 }
695 if (nack_enabled_) {
696 RTC_DCHECK(nack_);
697 // Update the sample rate even if the rate is not new, because of Reset().
698 nack_->UpdateSampleRate(fs_hz_);
699 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000700 }
701
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000702 // TODO(hlundin): Move this code to DelayManager class.
703 const DecoderDatabase::DecoderInfo* dec_info =
704 decoder_database_->GetDecoderInfo(main_header.payloadType);
705 assert(dec_info); // Already checked that the payload type is known.
706 delay_manager_->LastDecoderType(dec_info->codec_type);
707 if (delay_manager_->last_pack_cng_or_dtmf() == 0) {
708 // Calculate the total speech length carried in each packet.
henrik.lundin116c84e2015-08-27 13:14:48 -0700709 const size_t buffer_length_after_insert =
710 packet_buffer_->NumPacketsInBuffer();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000711
henrik.lundin116c84e2015-08-27 13:14:48 -0700712 if (buffer_length_after_insert > buffer_length_before_insert) {
713 const size_t packet_length_samples =
714 (buffer_length_after_insert - buffer_length_before_insert) *
715 decoder_frame_length_;
716 if (packet_length_samples != decision_logic_->packet_length_samples()) {
717 decision_logic_->set_packet_length_samples(packet_length_samples);
718 delay_manager_->SetPacketAudioLength(
719 rtc::checked_cast<int>((1000 * packet_length_samples) / fs_hz_));
720 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000721 }
722
723 // Update statistics.
pbos@webrtc.org0946a562013-04-09 00:28:06 +0000724 if ((int32_t) (main_header.timestamp - timestamp_) >= 0 &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000725 !new_codec_) {
726 // Only update statistics if incoming packet is not older than last played
727 // out packet, and if new codec flag is not set.
728 delay_manager_->Update(main_header.sequenceNumber, main_header.timestamp,
729 fs_hz_);
730 }
731 } else if (delay_manager_->last_pack_cng_or_dtmf() == -1) {
732 // This is first "normal" packet after CNG or DTMF.
733 // Reset packet time counter and measure time until next packet,
734 // but don't update statistics.
735 delay_manager_->set_last_pack_cng_or_dtmf(0);
736 delay_manager_->ResetPacketIatCount();
737 }
738 return 0;
739}
740
henrik.lundin6d8e0112016-03-04 10:34:21 -0800741int NetEqImpl::GetAudioInternal(AudioFrame* audio_frame) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000742 PacketList packet_list;
743 DtmfEvent dtmf_event;
744 Operations operation;
745 bool play_dtmf;
746 int return_value = GetDecision(&operation, &packet_list, &dtmf_event,
747 &play_dtmf);
748 if (return_value != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000749 last_mode_ = kModeError;
750 return return_value;
751 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000752
753 AudioDecoder::SpeechType speech_type;
754 int length = 0;
755 int decode_return_value = Decode(&packet_list, &operation,
756 &length, &speech_type);
757
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000758 assert(vad_.get());
759 bool sid_frame_available =
760 (operation == kRfc3389Cng && !packet_list.empty());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700761 vad_->Update(decoded_buffer_.get(), static_cast<size_t>(length), speech_type,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000762 sid_frame_available, fs_hz_);
763
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000764 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000765 switch (operation) {
766 case kNormal: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000767 DoNormal(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000768 break;
769 }
770 case kMerge: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000771 DoMerge(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000772 break;
773 }
774 case kExpand: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000775 return_value = DoExpand(play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000776 break;
777 }
Henrik Lundincf808d22015-05-27 14:33:29 +0200778 case kAccelerate:
779 case kFastAccelerate: {
780 const bool fast_accelerate =
781 enable_fast_accelerate_ && (operation == kFastAccelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000782 return_value = DoAccelerate(decoded_buffer_.get(), length, speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +0200783 play_dtmf, fast_accelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000784 break;
785 }
786 case kPreemptiveExpand: {
787 return_value = DoPreemptiveExpand(decoded_buffer_.get(), length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000788 speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000789 break;
790 }
791 case kRfc3389Cng:
792 case kRfc3389CngNoPacket: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000793 return_value = DoRfc3389Cng(&packet_list, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000794 break;
795 }
796 case kCodecInternalCng: {
797 // This handles the case when there is no transmission and the decoder
798 // should produce internal comfort noise.
799 // TODO(hlundin): Write test for codec-internal CNG.
minyuel6d92bf52015-09-23 15:20:39 +0200800 DoCodecInternalCng(decoded_buffer_.get(), length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000801 break;
802 }
803 case kDtmf: {
804 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000805 return_value = DoDtmf(dtmf_event, &play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000806 break;
807 }
808 case kAlternativePlc: {
809 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000810 DoAlternativePlc(false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000811 break;
812 }
813 case kAlternativePlcIncreaseTimestamp: {
814 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000815 DoAlternativePlc(true);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000816 break;
817 }
818 case kAudioRepetitionIncreaseTimestamp: {
819 // TODO(hlundin): Write test for this.
Peter Kastingb7e50542015-06-11 12:55:50 -0700820 sync_buffer_->IncreaseEndTimestamp(
821 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000822 // Skipping break on purpose. Execution should move on into the
823 // next case.
kjellander@webrtc.org7d2b6a92015-01-28 18:37:58 +0000824 FALLTHROUGH();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000825 }
826 case kAudioRepetition: {
827 // TODO(hlundin): Write test for this.
828 // Copy last |output_size_samples_| from |sync_buffer_| to
829 // |algorithm_buffer|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000830 algorithm_buffer_->PushBackFromIndex(
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000831 *sync_buffer_, sync_buffer_->Size() - output_size_samples_);
832 expand_->Reset();
833 break;
834 }
835 case kUndefined: {
Henrik Lundind67a2192015-08-03 12:54:37 +0200836 LOG(LS_ERROR) << "Invalid operation kUndefined.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000837 assert(false); // This should not happen.
838 last_mode_ = kModeError;
839 return kInvalidOperation;
840 }
841 } // End of switch.
842 if (return_value < 0) {
843 return return_value;
844 }
845
846 if (last_mode_ != kModeRfc3389Cng) {
847 comfort_noise_->Reset();
848 }
849
850 // Copy from |algorithm_buffer| to |sync_buffer_|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000851 sync_buffer_->PushBack(*algorithm_buffer_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000852
853 // Extract data from |sync_buffer_| to |output|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000854 size_t num_output_samples_per_channel = output_size_samples_;
855 size_t num_output_samples = output_size_samples_ * sync_buffer_->Channels();
henrik.lundin6d8e0112016-03-04 10:34:21 -0800856 if (num_output_samples > AudioFrame::kMaxDataSizeSamples) {
857 LOG(LS_WARNING) << "Output array is too short. "
858 << AudioFrame::kMaxDataSizeSamples << " < "
859 << output_size_samples_ << " * "
860 << sync_buffer_->Channels();
861 num_output_samples = AudioFrame::kMaxDataSizeSamples;
862 num_output_samples_per_channel =
863 AudioFrame::kMaxDataSizeSamples / sync_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000864 }
henrik.lundin6d8e0112016-03-04 10:34:21 -0800865 sync_buffer_->GetNextAudioInterleaved(num_output_samples_per_channel,
866 audio_frame);
867 audio_frame->sample_rate_hz_ = fs_hz_;
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200868 if (sync_buffer_->FutureLength() < expand_->overlap_length()) {
869 // The sync buffer should always contain |overlap_length| samples, but now
870 // too many samples have been extracted. Reinstall the |overlap_length|
871 // lookahead by moving the index.
872 const size_t missing_lookahead_samples =
873 expand_->overlap_length() - sync_buffer_->FutureLength();
henrikg91d6ede2015-09-17 00:24:34 -0700874 RTC_DCHECK_GE(sync_buffer_->next_index(), missing_lookahead_samples);
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200875 sync_buffer_->set_next_index(sync_buffer_->next_index() -
876 missing_lookahead_samples);
877 }
henrik.lundin6d8e0112016-03-04 10:34:21 -0800878 if (audio_frame->samples_per_channel_ != output_size_samples_) {
879 LOG(LS_ERROR) << "audio_frame->samples_per_channel_ ("
880 << audio_frame->samples_per_channel_
Henrik Lundind67a2192015-08-03 12:54:37 +0200881 << ") != output_size_samples_ (" << output_size_samples_
882 << ")";
minyue@webrtc.orgdb1cefc2013-08-13 01:39:21 +0000883 // TODO(minyue): treatment of under-run, filling zeros
henrik.lundin6d8e0112016-03-04 10:34:21 -0800884 memset(audio_frame->data_, 0, num_output_samples * sizeof(int16_t));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000885 return kSampleUnderrun;
886 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000887
888 // Should always have overlap samples left in the |sync_buffer_|.
henrikg91d6ede2015-09-17 00:24:34 -0700889 RTC_DCHECK_GE(sync_buffer_->FutureLength(), expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000890
891 if (play_dtmf) {
henrik.lundin6d8e0112016-03-04 10:34:21 -0800892 return_value =
893 DtmfOverdub(dtmf_event, sync_buffer_->Channels(), audio_frame->data_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000894 }
895
896 // Update the background noise parameters if last operation wrote data
897 // straight from the decoder to the |sync_buffer_|. That is, none of the
898 // operations that modify the signal can be followed by a parameter update.
899 if ((last_mode_ == kModeNormal) ||
900 (last_mode_ == kModeAccelerateFail) ||
901 (last_mode_ == kModePreemptiveExpandFail) ||
902 (last_mode_ == kModeRfc3389Cng) ||
903 (last_mode_ == kModeCodecInternalCng)) {
904 background_noise_->Update(*sync_buffer_, *vad_.get());
905 }
906
907 if (operation == kDtmf) {
908 // DTMF data was written the end of |sync_buffer_|.
909 // Update index to end of DTMF data in |sync_buffer_|.
910 sync_buffer_->set_dtmf_index(sync_buffer_->Size());
911 }
912
henrik.lundin@webrtc.orged865b52014-03-06 10:28:07 +0000913 if (last_mode_ != kModeExpand) {
914 // If last operation was not expand, calculate the |playout_timestamp_| from
915 // the |sync_buffer_|. However, do not update the |playout_timestamp_| if it
916 // would be moved "backwards".
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000917 uint32_t temp_timestamp = sync_buffer_->end_timestamp() -
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000918 static_cast<uint32_t>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000919 if (static_cast<int32_t>(temp_timestamp - playout_timestamp_) > 0) {
920 playout_timestamp_ = temp_timestamp;
921 }
922 } else {
923 // Use dead reckoning to estimate the |playout_timestamp_|.
Peter Kastingb7e50542015-06-11 12:55:50 -0700924 playout_timestamp_ += static_cast<uint32_t>(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000925 }
926
927 if (decode_return_value) return decode_return_value;
928 return return_value;
929}
930
931int NetEqImpl::GetDecision(Operations* operation,
932 PacketList* packet_list,
933 DtmfEvent* dtmf_event,
934 bool* play_dtmf) {
935 // Initialize output variables.
936 *play_dtmf = false;
937 *operation = kUndefined;
938
939 // Increment time counters.
940 packet_buffer_->IncrementWaitingTimes();
941 stats_.IncreaseCounter(output_size_samples_, fs_hz_);
942
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000943 assert(sync_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000944 uint32_t end_timestamp = sync_buffer_->end_timestamp();
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +0000945 if (!new_codec_) {
946 const uint32_t five_seconds_samples = 5 * fs_hz_;
947 packet_buffer_->DiscardOldPackets(end_timestamp, five_seconds_samples);
948 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000949 const RTPHeader* header = packet_buffer_->NextRtpHeader();
950
henrik.lundin@webrtc.orgca8cb952014-03-12 10:26:52 +0000951 if (decision_logic_->CngRfc3389On() || last_mode_ == kModeRfc3389Cng) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000952 // Because of timestamp peculiarities, we have to "manually" disallow using
953 // a CNG packet with the same timestamp as the one that was last played.
954 // This can happen when using redundancy and will cause the timing to shift.
henrik.lundin@webrtc.org24779fe2014-03-14 12:40:05 +0000955 while (header && decoder_database_->IsComfortNoise(header->payloadType) &&
956 (end_timestamp >= header->timestamp ||
957 end_timestamp + decision_logic_->generated_noise_samples() >
958 header->timestamp)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000959 // Don't use this packet, discard it.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000960 if (packet_buffer_->DiscardNextPacket() != PacketBuffer::kOK) {
961 assert(false); // Must be ok by design.
962 }
963 // Check buffer again.
964 if (!new_codec_) {
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +0000965 packet_buffer_->DiscardOldPackets(end_timestamp, 5 * fs_hz_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000966 }
967 header = packet_buffer_->NextRtpHeader();
968 }
969 }
970
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000971 assert(expand_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000972 const int samples_left = static_cast<int>(sync_buffer_->FutureLength() -
973 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000974 if (last_mode_ == kModeAccelerateSuccess ||
975 last_mode_ == kModeAccelerateLowEnergy ||
976 last_mode_ == kModePreemptiveExpandSuccess ||
977 last_mode_ == kModePreemptiveExpandLowEnergy) {
978 // Subtract (samples_left + output_size_samples_) from sampleMemory.
Peter Kastingdce40cf2015-08-24 14:52:23 -0700979 decision_logic_->AddSampleMemory(
980 -(samples_left + rtc::checked_cast<int>(output_size_samples_)));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000981 }
982
983 // Check if it is time to play a DTMF event.
Peter Kastingb7e50542015-06-11 12:55:50 -0700984 if (dtmf_buffer_->GetEvent(
985 static_cast<uint32_t>(
986 end_timestamp + decision_logic_->generated_noise_samples()),
987 dtmf_event)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000988 *play_dtmf = true;
989 }
990
991 // Get instruction.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000992 assert(sync_buffer_.get());
993 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000994 *operation = decision_logic_->GetDecision(*sync_buffer_,
995 *expand_,
996 decoder_frame_length_,
997 header,
998 last_mode_,
999 *play_dtmf,
1000 &reset_decoder_);
1001
1002 // Check if we already have enough samples in the |sync_buffer_|. If so,
1003 // change decision to normal, unless the decision was merge, accelerate, or
1004 // preemptive expand.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001005 if (samples_left >= rtc::checked_cast<int>(output_size_samples_) &&
1006 *operation != kMerge &&
1007 *operation != kAccelerate &&
1008 *operation != kFastAccelerate &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001009 *operation != kPreemptiveExpand) {
1010 *operation = kNormal;
1011 return 0;
1012 }
1013
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001014 decision_logic_->ExpandDecision(*operation);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001015
1016 // Check conditions for reset.
1017 if (new_codec_ || *operation == kUndefined) {
1018 // The only valid reason to get kUndefined is that new_codec_ is set.
1019 assert(new_codec_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001020 if (*play_dtmf && !header) {
1021 timestamp_ = dtmf_event->timestamp;
1022 } else {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001023 if (!header) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001024 LOG(LS_ERROR) << "Packet missing where it shouldn't.";
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001025 return -1;
1026 }
1027 timestamp_ = header->timestamp;
1028 if (*operation == kRfc3389CngNoPacket
1029#ifndef LEGACY_BITEXACT
1030 // Without this check, it can happen that a non-CNG packet is sent to
1031 // the CNG decoder as if it was a SID frame. This is clearly a bug,
1032 // but is kept for now to maintain bit-exactness with the test
1033 // vectors.
1034 && decoder_database_->IsComfortNoise(header->payloadType)
1035#endif
1036 ) {
1037 // Change decision to CNG packet, since we do have a CNG packet, but it
1038 // was considered too early to use. Now, use it anyway.
1039 *operation = kRfc3389Cng;
1040 } else if (*operation != kRfc3389Cng) {
1041 *operation = kNormal;
1042 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001043 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001044 // Adjust |sync_buffer_| timestamp before setting |end_timestamp| to the
1045 // new value.
1046 sync_buffer_->IncreaseEndTimestamp(timestamp_ - end_timestamp);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001047 end_timestamp = timestamp_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001048 new_codec_ = false;
1049 decision_logic_->SoftReset();
1050 buffer_level_filter_->Reset();
1051 delay_manager_->Reset();
1052 stats_.ResetMcu();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001053 }
1054
Peter Kastingdce40cf2015-08-24 14:52:23 -07001055 size_t required_samples = output_size_samples_;
1056 const size_t samples_10_ms = static_cast<size_t>(80 * fs_mult_);
1057 const size_t samples_20_ms = 2 * samples_10_ms;
1058 const size_t samples_30_ms = 3 * samples_10_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001059
1060 switch (*operation) {
1061 case kExpand: {
1062 timestamp_ = end_timestamp;
1063 return 0;
1064 }
1065 case kRfc3389CngNoPacket:
1066 case kCodecInternalCng: {
1067 return 0;
1068 }
1069 case kDtmf: {
1070 // TODO(hlundin): Write test for this.
1071 // Update timestamp.
1072 timestamp_ = end_timestamp;
1073 if (decision_logic_->generated_noise_samples() > 0 &&
1074 last_mode_ != kModeDtmf) {
1075 // Make a jump in timestamp due to the recently played comfort noise.
Peter Kastingb7e50542015-06-11 12:55:50 -07001076 uint32_t timestamp_jump =
1077 static_cast<uint32_t>(decision_logic_->generated_noise_samples());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001078 sync_buffer_->IncreaseEndTimestamp(timestamp_jump);
1079 timestamp_ += timestamp_jump;
1080 }
1081 decision_logic_->set_generated_noise_samples(0);
1082 return 0;
1083 }
Henrik Lundincf808d22015-05-27 14:33:29 +02001084 case kAccelerate:
1085 case kFastAccelerate: {
1086 // In order to do an accelerate we need at least 30 ms of audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001087 if (samples_left >= static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001088 // Already have enough data, so we do not need to extract any more.
1089 decision_logic_->set_sample_memory(samples_left);
1090 decision_logic_->set_prev_time_scale(true);
1091 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001092 } else if (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001093 decoder_frame_length_ >= samples_30_ms) {
1094 // Avoid decoding more data as it might overflow the playout buffer.
1095 *operation = kNormal;
1096 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001097 } else if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001098 decoder_frame_length_ < samples_30_ms) {
1099 // Build up decoded data by decoding at least 20 ms of audio data. Do
1100 // not perform accelerate yet, but wait until we only need to do one
1101 // decoding.
1102 required_samples = 2 * output_size_samples_;
1103 *operation = kNormal;
1104 }
1105 // If none of the above is true, we have one of two possible situations:
1106 // (1) 20 ms <= samples_left < 30 ms and decoder_frame_length_ < 30 ms; or
1107 // (2) samples_left < 10 ms and decoder_frame_length_ >= 30 ms.
1108 // In either case, we move on with the accelerate decision, and decode one
1109 // frame now.
1110 break;
1111 }
1112 case kPreemptiveExpand: {
1113 // In order to do a preemptive expand we need at least 30 ms of decoded
1114 // audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001115 if ((samples_left >= static_cast<int>(samples_30_ms)) ||
1116 (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001117 decoder_frame_length_ >= samples_30_ms)) {
1118 // Already have enough data, so we do not need to extract any more.
1119 // Or, avoid decoding more data as it might overflow the playout buffer.
1120 // Still try preemptive expand, though.
1121 decision_logic_->set_sample_memory(samples_left);
1122 decision_logic_->set_prev_time_scale(true);
1123 return 0;
1124 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07001125 if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001126 decoder_frame_length_ < samples_30_ms) {
1127 // Build up decoded data by decoding at least 20 ms of audio data.
1128 // Still try to perform preemptive expand.
1129 required_samples = 2 * output_size_samples_;
1130 }
1131 // Move on with the preemptive expand decision.
1132 break;
1133 }
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001134 case kMerge: {
1135 required_samples =
1136 std::max(merge_->RequiredFutureSamples(), required_samples);
1137 break;
1138 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001139 default: {
1140 // Do nothing.
1141 }
1142 }
1143
1144 // Get packets from buffer.
1145 int extracted_samples = 0;
1146 if (header &&
1147 *operation != kAlternativePlc &&
1148 *operation != kAlternativePlcIncreaseTimestamp &&
1149 *operation != kAudioRepetition &&
1150 *operation != kAudioRepetitionIncreaseTimestamp) {
1151 sync_buffer_->IncreaseEndTimestamp(header->timestamp - end_timestamp);
1152 if (decision_logic_->CngOff()) {
1153 // Adjustment of timestamp only corresponds to an actual packet loss
1154 // if comfort noise is not played. If comfort noise was just played,
1155 // this adjustment of timestamp is only done to get back in sync with the
1156 // stream timestamp; no loss to report.
1157 stats_.LostSamples(header->timestamp - end_timestamp);
1158 }
1159
1160 if (*operation != kRfc3389Cng) {
1161 // We are about to decode and use a non-CNG packet.
1162 decision_logic_->SetCngOff();
1163 }
1164 // Reset CNG timestamp as a new packet will be delivered.
1165 // (Also if this is a CNG packet, since playedOutTS is updated.)
1166 decision_logic_->set_generated_noise_samples(0);
1167
1168 extracted_samples = ExtractPackets(required_samples, packet_list);
1169 if (extracted_samples < 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001170 return kPacketBufferCorruption;
1171 }
1172 }
1173
Henrik Lundincf808d22015-05-27 14:33:29 +02001174 if (*operation == kAccelerate || *operation == kFastAccelerate ||
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001175 *operation == kPreemptiveExpand) {
1176 decision_logic_->set_sample_memory(samples_left + extracted_samples);
1177 decision_logic_->set_prev_time_scale(true);
1178 }
1179
Henrik Lundincf808d22015-05-27 14:33:29 +02001180 if (*operation == kAccelerate || *operation == kFastAccelerate) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001181 // Check that we have enough data (30ms) to do accelerate.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001182 if (extracted_samples + samples_left < static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001183 // TODO(hlundin): Write test for this.
1184 // Not enough, do normal operation instead.
1185 *operation = kNormal;
1186 }
1187 }
1188
1189 timestamp_ = end_timestamp;
1190 return 0;
1191}
1192
1193int NetEqImpl::Decode(PacketList* packet_list, Operations* operation,
1194 int* decoded_length,
1195 AudioDecoder::SpeechType* speech_type) {
1196 *speech_type = AudioDecoder::kSpeech;
minyuel6d92bf52015-09-23 15:20:39 +02001197
1198 // When packet_list is empty, we may be in kCodecInternalCng mode, and for
1199 // that we use current active decoder.
1200 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1201
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001202 if (!packet_list->empty()) {
1203 const Packet* packet = packet_list->front();
pkasting@chromium.org0e81fdf2015-02-02 23:54:03 +00001204 uint8_t payload_type = packet->header.payloadType;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001205 if (!decoder_database_->IsComfortNoise(payload_type)) {
1206 decoder = decoder_database_->GetDecoder(payload_type);
1207 assert(decoder);
1208 if (!decoder) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001209 LOG(LS_WARNING) << "Unknown payload type "
1210 << static_cast<int>(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001211 PacketBuffer::DeleteAllPackets(packet_list);
1212 return kDecoderNotFound;
1213 }
1214 bool decoder_changed;
1215 decoder_database_->SetActiveDecoder(payload_type, &decoder_changed);
1216 if (decoder_changed) {
1217 // We have a new decoder. Re-init some values.
1218 const DecoderDatabase::DecoderInfo* decoder_info = decoder_database_
1219 ->GetDecoderInfo(payload_type);
1220 assert(decoder_info);
1221 if (!decoder_info) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001222 LOG(LS_WARNING) << "Unknown payload type "
1223 << static_cast<int>(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001224 PacketBuffer::DeleteAllPackets(packet_list);
1225 return kDecoderNotFound;
1226 }
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001227 // If sampling rate or number of channels has changed, we need to make
1228 // a reset.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001229 if (decoder_info->fs_hz != fs_hz_ ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001230 decoder->Channels() != algorithm_buffer_->Channels()) {
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001231 // TODO(tlegrand): Add unittest to cover this event.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001232 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->Channels());
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001233 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001234 sync_buffer_->set_end_timestamp(timestamp_);
1235 playout_timestamp_ = timestamp_;
1236 }
1237 }
1238 }
1239
1240 if (reset_decoder_) {
1241 // TODO(hlundin): Write test for this.
Karl Wiberg43766482015-08-27 15:22:11 +02001242 if (decoder)
1243 decoder->Reset();
1244
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001245 // Reset comfort noise decoder.
1246 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02001247 if (cng_decoder)
1248 cng_decoder->Reset();
1249
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001250 reset_decoder_ = false;
1251 }
1252
1253#ifdef LEGACY_BITEXACT
1254 // Due to a bug in old SignalMCU, it could happen that CNG operation was
1255 // decided, but a speech packet was provided. The speech packet will be used
1256 // to update the comfort noise decoder, as if it was a SID frame, which is
1257 // clearly wrong.
1258 if (*operation == kRfc3389Cng) {
1259 return 0;
1260 }
1261#endif
1262
1263 *decoded_length = 0;
1264 // Update codec-internal PLC state.
1265 if ((*operation == kMerge) && decoder && decoder->HasDecodePlc()) {
1266 decoder->DecodePlc(1, &decoded_buffer_[*decoded_length]);
1267 }
1268
minyuel6d92bf52015-09-23 15:20:39 +02001269 int return_value;
1270 if (*operation == kCodecInternalCng) {
1271 RTC_DCHECK(packet_list->empty());
1272 return_value = DecodeCng(decoder, decoded_length, speech_type);
1273 } else {
1274 return_value = DecodeLoop(packet_list, *operation, decoder,
1275 decoded_length, speech_type);
1276 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001277
1278 if (*decoded_length < 0) {
1279 // Error returned from the decoder.
1280 *decoded_length = 0;
Peter Kastingb7e50542015-06-11 12:55:50 -07001281 sync_buffer_->IncreaseEndTimestamp(
1282 static_cast<uint32_t>(decoder_frame_length_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001283 int error_code = 0;
1284 if (decoder)
1285 error_code = decoder->ErrorCode();
1286 if (error_code != 0) {
1287 // Got some error code from the decoder.
1288 decoder_error_code_ = error_code;
1289 return_value = kDecoderErrorCode;
Henrik Lundind67a2192015-08-03 12:54:37 +02001290 LOG(LS_WARNING) << "Decoder returned error code: " << error_code;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001291 } else {
1292 // Decoder does not implement error codes. Return generic error.
1293 return_value = kOtherDecoderError;
Henrik Lundind67a2192015-08-03 12:54:37 +02001294 LOG(LS_WARNING) << "Decoder error (no error code)";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001295 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001296 *operation = kExpand; // Do expansion to get data instead.
1297 }
1298 if (*speech_type != AudioDecoder::kComfortNoise) {
1299 // Don't increment timestamp if codec returned CNG speech type
1300 // since in this case, the we will increment the CNGplayedTS counter.
1301 // Increase with number of samples per channel.
1302 assert(*decoded_length == 0 ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001303 (decoder && decoder->Channels() == sync_buffer_->Channels()));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001304 sync_buffer_->IncreaseEndTimestamp(
1305 *decoded_length / static_cast<int>(sync_buffer_->Channels()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001306 }
1307 return return_value;
1308}
1309
minyuel6d92bf52015-09-23 15:20:39 +02001310int NetEqImpl::DecodeCng(AudioDecoder* decoder, int* decoded_length,
1311 AudioDecoder::SpeechType* speech_type) {
1312 if (!decoder) {
1313 // This happens when active decoder is not defined.
1314 *decoded_length = -1;
1315 return 0;
1316 }
1317
1318 while (*decoded_length < rtc::checked_cast<int>(output_size_samples_)) {
1319 const int length = decoder->Decode(
1320 nullptr, 0, fs_hz_,
1321 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1322 &decoded_buffer_[*decoded_length], speech_type);
1323 if (length > 0) {
1324 *decoded_length += length;
minyuel6d92bf52015-09-23 15:20:39 +02001325 } else {
1326 // Error.
1327 LOG(LS_WARNING) << "Failed to decode CNG";
1328 *decoded_length = -1;
1329 break;
1330 }
1331 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1332 // Guard against overflow.
1333 LOG(LS_WARNING) << "Decoded too much CNG.";
1334 return kDecodedTooMuch;
1335 }
1336 }
1337 return 0;
1338}
1339
1340int NetEqImpl::DecodeLoop(PacketList* packet_list, const Operations& operation,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001341 AudioDecoder* decoder, int* decoded_length,
1342 AudioDecoder::SpeechType* speech_type) {
1343 Packet* packet = NULL;
1344 if (!packet_list->empty()) {
1345 packet = packet_list->front();
1346 }
minyuel6d92bf52015-09-23 15:20:39 +02001347
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001348 // Do decoding.
1349 while (packet &&
1350 !decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1351 assert(decoder); // At this point, we must have a decoder object.
1352 // The number of channels in the |sync_buffer_| should be the same as the
1353 // number decoder channels.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001354 assert(sync_buffer_->Channels() == decoder->Channels());
1355 assert(decoded_buffer_length_ >= kMaxFrameSize * decoder->Channels());
minyuel6d92bf52015-09-23 15:20:39 +02001356 assert(operation == kNormal || operation == kAccelerate ||
1357 operation == kFastAccelerate || operation == kMerge ||
1358 operation == kPreemptiveExpand);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001359 packet_list->pop_front();
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001360 size_t payload_length = packet->payload_length;
Peter Kasting36b7cc32015-06-11 19:57:18 -07001361 int decode_length;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +00001362 if (packet->sync_packet) {
1363 // Decode to silence with the same frame size as the last decode.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001364 memset(&decoded_buffer_[*decoded_length], 0,
1365 decoder_frame_length_ * decoder->Channels() *
1366 sizeof(decoded_buffer_[0]));
Peter Kastingdce40cf2015-08-24 14:52:23 -07001367 decode_length = rtc::checked_cast<int>(decoder_frame_length_);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +00001368 } else if (!packet->primary) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001369 // This is a redundant payload; call the special decoder method.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001370 decode_length = decoder->DecodeRedundant(
henrik.lundin@webrtc.org1eda4e32015-02-25 10:02:29 +00001371 packet->payload, packet->payload_length, fs_hz_,
minyue@webrtc.org7f7d7e32015-03-16 12:30:37 +00001372 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001373 &decoded_buffer_[*decoded_length], speech_type);
1374 } else {
henrik.lundin@webrtc.org1eda4e32015-02-25 10:02:29 +00001375 decode_length =
minyue@webrtc.org7f7d7e32015-03-16 12:30:37 +00001376 decoder->Decode(
1377 packet->payload, packet->payload_length, fs_hz_,
1378 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1379 &decoded_buffer_[*decoded_length], speech_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001380 }
1381
1382 delete[] packet->payload;
1383 delete packet;
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001384 packet = NULL;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001385 if (decode_length > 0) {
1386 *decoded_length += decode_length;
1387 // Update |decoder_frame_length_| with number of samples per channel.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001388 decoder_frame_length_ =
Peter Kastingdce40cf2015-08-24 14:52:23 -07001389 static_cast<size_t>(decode_length) / decoder->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001390 } else if (decode_length < 0) {
1391 // Error.
Henrik Lundind67a2192015-08-03 12:54:37 +02001392 LOG(LS_WARNING) << "Decode " << decode_length << " " << payload_length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001393 *decoded_length = -1;
1394 PacketBuffer::DeleteAllPackets(packet_list);
1395 break;
1396 }
1397 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1398 // Guard against overflow.
Henrik Lundind67a2192015-08-03 12:54:37 +02001399 LOG(LS_WARNING) << "Decoded too much.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001400 PacketBuffer::DeleteAllPackets(packet_list);
1401 return kDecodedTooMuch;
1402 }
1403 if (!packet_list->empty()) {
1404 packet = packet_list->front();
1405 } else {
1406 packet = NULL;
1407 }
1408 } // End of decode loop.
1409
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001410 // If the list is not empty at this point, either a decoding error terminated
1411 // the while-loop, or list must hold exactly one CNG packet.
1412 assert(packet_list->empty() || *decoded_length < 0 ||
1413 (packet_list->size() == 1 && packet &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001414 decoder_database_->IsComfortNoise(packet->header.payloadType)));
1415 return 0;
1416}
1417
1418void NetEqImpl::DoNormal(const int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001419 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001420 assert(normal_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001421 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001422 normal_->Process(decoded_buffer, decoded_length, last_mode_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001423 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001424 if (decoded_length != 0) {
1425 last_mode_ = kModeNormal;
1426 }
1427
1428 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1429 if ((speech_type == AudioDecoder::kComfortNoise)
1430 || ((last_mode_ == kModeCodecInternalCng)
1431 && (decoded_length == 0))) {
1432 // TODO(hlundin): Remove second part of || statement above.
1433 last_mode_ = kModeCodecInternalCng;
1434 }
1435
1436 if (!play_dtmf) {
1437 dtmf_tone_generator_->Reset();
1438 }
1439}
1440
1441void NetEqImpl::DoMerge(int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001442 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001443 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001444 assert(merge_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001445 size_t new_length = merge_->Process(decoded_buffer, decoded_length,
1446 mute_factor_array_.get(),
1447 algorithm_buffer_.get());
1448 size_t expand_length_correction = new_length -
1449 decoded_length / algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001450
1451 // Update in-call and post-call statistics.
1452 if (expand_->MuteFactor(0) == 0) {
1453 // Expand generates only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001454 stats_.ExpandedNoiseSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001455 } else {
1456 // Expansion generates more than only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001457 stats_.ExpandedVoiceSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001458 }
1459
1460 last_mode_ = kModeMerge;
1461 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1462 if (speech_type == AudioDecoder::kComfortNoise) {
1463 last_mode_ = kModeCodecInternalCng;
1464 }
1465 expand_->Reset();
1466 if (!play_dtmf) {
1467 dtmf_tone_generator_->Reset();
1468 }
1469}
1470
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001471int NetEqImpl::DoExpand(bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001472 while ((sync_buffer_->FutureLength() - expand_->overlap_length()) <
Peter Kastingdce40cf2015-08-24 14:52:23 -07001473 output_size_samples_) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001474 algorithm_buffer_->Clear();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001475 int return_value = expand_->Process(algorithm_buffer_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001476 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001477
1478 // Update in-call and post-call statistics.
1479 if (expand_->MuteFactor(0) == 0) {
1480 // Expand operation generates only noise.
1481 stats_.ExpandedNoiseSamples(length);
1482 } else {
1483 // Expand operation generates more than only noise.
1484 stats_.ExpandedVoiceSamples(length);
1485 }
1486
1487 last_mode_ = kModeExpand;
1488
1489 if (return_value < 0) {
1490 return return_value;
1491 }
1492
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001493 sync_buffer_->PushBack(*algorithm_buffer_);
1494 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001495 }
1496 if (!play_dtmf) {
1497 dtmf_tone_generator_->Reset();
1498 }
1499 return 0;
1500}
1501
Henrik Lundincf808d22015-05-27 14:33:29 +02001502int NetEqImpl::DoAccelerate(int16_t* decoded_buffer,
1503 size_t decoded_length,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001504 AudioDecoder::SpeechType speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +02001505 bool play_dtmf,
1506 bool fast_accelerate) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001507 const size_t required_samples =
1508 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001509 size_t borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001510 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001511 size_t decoded_length_per_channel = decoded_length / num_channels;
1512 if (decoded_length_per_channel < required_samples) {
1513 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001514 borrowed_samples_per_channel = static_cast<int>(required_samples -
1515 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001516 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1517 decoded_buffer,
1518 sizeof(int16_t) * decoded_length);
1519 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1520 decoded_buffer);
1521 decoded_length = required_samples * num_channels;
1522 }
1523
Peter Kastingdce40cf2015-08-24 14:52:23 -07001524 size_t samples_removed;
Henrik Lundincf808d22015-05-27 14:33:29 +02001525 Accelerate::ReturnCodes return_code =
1526 accelerate_->Process(decoded_buffer, decoded_length, fast_accelerate,
1527 algorithm_buffer_.get(), &samples_removed);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001528 stats_.AcceleratedSamples(samples_removed);
1529 switch (return_code) {
1530 case Accelerate::kSuccess:
1531 last_mode_ = kModeAccelerateSuccess;
1532 break;
1533 case Accelerate::kSuccessLowEnergy:
1534 last_mode_ = kModeAccelerateLowEnergy;
1535 break;
1536 case Accelerate::kNoStretch:
1537 last_mode_ = kModeAccelerateFail;
1538 break;
1539 case Accelerate::kError:
1540 // TODO(hlundin): Map to kModeError instead?
1541 last_mode_ = kModeAccelerateFail;
1542 return kAccelerateError;
1543 }
1544
1545 if (borrowed_samples_per_channel > 0) {
1546 // Copy borrowed samples back to the |sync_buffer_|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001547 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001548 if (length < borrowed_samples_per_channel) {
1549 // This destroys the beginning of the buffer, but will not cause any
1550 // problems.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001551 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001552 sync_buffer_->Size() -
1553 borrowed_samples_per_channel);
1554 sync_buffer_->PushFrontZeros(borrowed_samples_per_channel - length);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001555 algorithm_buffer_->PopFront(length);
1556 assert(algorithm_buffer_->Empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001557 } else {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001558 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001559 borrowed_samples_per_channel,
1560 sync_buffer_->Size() -
1561 borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001562 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001563 }
1564 }
1565
1566 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1567 if (speech_type == AudioDecoder::kComfortNoise) {
1568 last_mode_ = kModeCodecInternalCng;
1569 }
1570 if (!play_dtmf) {
1571 dtmf_tone_generator_->Reset();
1572 }
1573 expand_->Reset();
1574 return 0;
1575}
1576
1577int NetEqImpl::DoPreemptiveExpand(int16_t* decoded_buffer,
1578 size_t decoded_length,
1579 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001580 bool play_dtmf) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001581 const size_t required_samples =
1582 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001583 size_t num_channels = algorithm_buffer_->Channels();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001584 size_t borrowed_samples_per_channel = 0;
1585 size_t old_borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001586 size_t decoded_length_per_channel = decoded_length / num_channels;
1587 if (decoded_length_per_channel < required_samples) {
1588 // Must move data from the |sync_buffer_| in order to get 30 ms.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001589 borrowed_samples_per_channel =
1590 required_samples - decoded_length_per_channel;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001591 // Calculate how many of these were already played out.
Peter Kastingf045e4d2015-06-10 21:15:38 -07001592 old_borrowed_samples_per_channel =
Peter Kastingdce40cf2015-08-24 14:52:23 -07001593 (borrowed_samples_per_channel > sync_buffer_->FutureLength()) ?
1594 (borrowed_samples_per_channel - sync_buffer_->FutureLength()) : 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001595 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1596 decoded_buffer,
1597 sizeof(int16_t) * decoded_length);
1598 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1599 decoded_buffer);
1600 decoded_length = required_samples * num_channels;
1601 }
1602
Peter Kastingdce40cf2015-08-24 14:52:23 -07001603 size_t samples_added;
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001604 PreemptiveExpand::ReturnCodes return_code = preemptive_expand_->Process(
Peter Kastingdce40cf2015-08-24 14:52:23 -07001605 decoded_buffer, decoded_length,
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001606 old_borrowed_samples_per_channel,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001607 algorithm_buffer_.get(), &samples_added);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001608 stats_.PreemptiveExpandedSamples(samples_added);
1609 switch (return_code) {
1610 case PreemptiveExpand::kSuccess:
1611 last_mode_ = kModePreemptiveExpandSuccess;
1612 break;
1613 case PreemptiveExpand::kSuccessLowEnergy:
1614 last_mode_ = kModePreemptiveExpandLowEnergy;
1615 break;
1616 case PreemptiveExpand::kNoStretch:
1617 last_mode_ = kModePreemptiveExpandFail;
1618 break;
1619 case PreemptiveExpand::kError:
1620 // TODO(hlundin): Map to kModeError instead?
1621 last_mode_ = kModePreemptiveExpandFail;
1622 return kPreemptiveExpandError;
1623 }
1624
1625 if (borrowed_samples_per_channel > 0) {
1626 // Copy borrowed samples back to the |sync_buffer_|.
1627 sync_buffer_->ReplaceAtIndex(
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001628 *algorithm_buffer_, borrowed_samples_per_channel,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001629 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001630 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001631 }
1632
1633 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1634 if (speech_type == AudioDecoder::kComfortNoise) {
1635 last_mode_ = kModeCodecInternalCng;
1636 }
1637 if (!play_dtmf) {
1638 dtmf_tone_generator_->Reset();
1639 }
1640 expand_->Reset();
1641 return 0;
1642}
1643
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001644int NetEqImpl::DoRfc3389Cng(PacketList* packet_list, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001645 if (!packet_list->empty()) {
1646 // Must have exactly one SID frame at this point.
1647 assert(packet_list->size() == 1);
1648 Packet* packet = packet_list->front();
1649 packet_list->pop_front();
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001650 if (!decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1651#ifdef LEGACY_BITEXACT
1652 // This can happen due to a bug in GetDecision. Change the payload type
1653 // to a CNG type, and move on. Note that this means that we are in fact
1654 // sending a non-CNG payload to the comfort noise decoder for decoding.
1655 // Clearly wrong, but will maintain bit-exactness with legacy.
1656 if (fs_hz_ == 8000) {
1657 packet->header.payloadType =
kwibergee1879c2015-10-29 06:20:28 -07001658 decoder_database_->GetRtpPayloadType(NetEqDecoder::kDecoderCNGnb);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001659 } else if (fs_hz_ == 16000) {
1660 packet->header.payloadType =
kwibergee1879c2015-10-29 06:20:28 -07001661 decoder_database_->GetRtpPayloadType(NetEqDecoder::kDecoderCNGwb);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001662 } else if (fs_hz_ == 32000) {
kwibergee1879c2015-10-29 06:20:28 -07001663 packet->header.payloadType = decoder_database_->GetRtpPayloadType(
1664 NetEqDecoder::kDecoderCNGswb32kHz);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001665 } else if (fs_hz_ == 48000) {
kwibergee1879c2015-10-29 06:20:28 -07001666 packet->header.payloadType = decoder_database_->GetRtpPayloadType(
1667 NetEqDecoder::kDecoderCNGswb48kHz);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001668 }
1669 assert(decoder_database_->IsComfortNoise(packet->header.payloadType));
1670#else
1671 LOG(LS_ERROR) << "Trying to decode non-CNG payload as CNG.";
1672 return kOtherError;
1673#endif
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001674 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001675 // UpdateParameters() deletes |packet|.
1676 if (comfort_noise_->UpdateParameters(packet) ==
1677 ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001678 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001679 return -comfort_noise_->internal_error_code();
1680 }
1681 }
1682 int cn_return = comfort_noise_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001683 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001684 expand_->Reset();
1685 last_mode_ = kModeRfc3389Cng;
1686 if (!play_dtmf) {
1687 dtmf_tone_generator_->Reset();
1688 }
1689 if (cn_return == ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001690 decoder_error_code_ = comfort_noise_->internal_error_code();
1691 return kComfortNoiseErrorCode;
1692 } else if (cn_return == ComfortNoise::kUnknownPayloadType) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001693 return kUnknownRtpPayloadType;
1694 }
1695 return 0;
1696}
1697
minyuel6d92bf52015-09-23 15:20:39 +02001698void NetEqImpl::DoCodecInternalCng(const int16_t* decoded_buffer,
1699 size_t decoded_length) {
1700 RTC_DCHECK(normal_.get());
1701 RTC_DCHECK(mute_factor_array_.get());
1702 normal_->Process(decoded_buffer, decoded_length, last_mode_,
1703 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001704 last_mode_ = kModeCodecInternalCng;
1705 expand_->Reset();
1706}
1707
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001708int NetEqImpl::DoDtmf(const DtmfEvent& dtmf_event, bool* play_dtmf) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001709 // This block of the code and the block further down, handling |dtmf_switch|
1710 // are commented out. Otherwise playing out-of-band DTMF would fail in VoE
1711 // test, DtmfTest.ManualSuccessfullySendsOutOfBandTelephoneEvents. This is
1712 // equivalent to |dtmf_switch| always be false.
1713 //
1714 // See http://webrtc-codereview.appspot.com/1195004/ for discussion
1715 // On this issue. This change might cause some glitches at the point of
1716 // switch from audio to DTMF. Issue 1545 is filed to track this.
1717 //
1718 // bool dtmf_switch = false;
1719 // if ((last_mode_ != kModeDtmf) && dtmf_tone_generator_->initialized()) {
1720 // // Special case; see below.
1721 // // We must catch this before calling Generate, since |initialized| is
1722 // // modified in that call.
1723 // dtmf_switch = true;
1724 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001725
1726 int dtmf_return_value = 0;
1727 if (!dtmf_tone_generator_->initialized()) {
1728 // Initialize if not already done.
1729 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1730 dtmf_event.volume);
1731 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001732
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001733 if (dtmf_return_value == 0) {
1734 // Generate DTMF signal.
1735 dtmf_return_value = dtmf_tone_generator_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001736 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001737 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001738
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001739 if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001740 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001741 return dtmf_return_value;
1742 }
1743
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001744 // if (dtmf_switch) {
1745 // // This is the special case where the previous operation was DTMF
1746 // // overdub, but the current instruction is "regular" DTMF. We must make
1747 // // sure that the DTMF does not have any discontinuities. The first DTMF
1748 // // sample that we generate now must be played out immediately, therefore
1749 // // it must be copied to the speech buffer.
1750 // // TODO(hlundin): This code seems incorrect. (Legacy.) Write test and
1751 // // verify correct operation.
1752 // assert(false);
1753 // // Must generate enough data to replace all of the |sync_buffer_|
1754 // // "future".
1755 // int required_length = sync_buffer_->FutureLength();
1756 // assert(dtmf_tone_generator_->initialized());
1757 // dtmf_return_value = dtmf_tone_generator_->Generate(required_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001758 // algorithm_buffer_);
1759 // assert((size_t) required_length == algorithm_buffer_->Size());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001760 // if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001761 // algorithm_buffer_->Zeros(output_size_samples_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001762 // return dtmf_return_value;
1763 // }
1764 //
1765 // // Overwrite the "future" part of the speech buffer with the new DTMF
1766 // // data.
1767 // // TODO(hlundin): It seems that this overwriting has gone lost.
1768 // // Not adapted for multi-channel yet.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001769 // assert(algorithm_buffer_->Channels() == 1);
1770 // if (algorithm_buffer_->Channels() != 1) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001771 // LOG(LS_WARNING) << "DTMF not supported for more than one channel";
1772 // return kStereoNotSupported;
1773 // }
1774 // // Shuffle the remaining data to the beginning of algorithm buffer.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001775 // algorithm_buffer_->PopFront(sync_buffer_->FutureLength());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001776 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001777
Peter Kastingb7e50542015-06-11 12:55:50 -07001778 sync_buffer_->IncreaseEndTimestamp(
1779 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001780 expand_->Reset();
1781 last_mode_ = kModeDtmf;
1782
1783 // Set to false because the DTMF is already in the algorithm buffer.
1784 *play_dtmf = false;
1785 return 0;
1786}
1787
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001788void NetEqImpl::DoAlternativePlc(bool increase_timestamp) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001789 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001790 size_t length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001791 if (decoder && decoder->HasDecodePlc()) {
1792 // Use the decoder's packet-loss concealment.
1793 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1794 int16_t decoded_buffer[kMaxFrameSize];
1795 length = decoder->DecodePlc(1, decoded_buffer);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001796 if (length > 0)
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001797 algorithm_buffer_->PushBackInterleaved(decoded_buffer, length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001798 } else {
1799 // Do simple zero-stuffing.
1800 length = output_size_samples_;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001801 algorithm_buffer_->Zeros(length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001802 // By not advancing the timestamp, NetEq inserts samples.
1803 stats_.AddZeros(length);
1804 }
1805 if (increase_timestamp) {
Peter Kastingb7e50542015-06-11 12:55:50 -07001806 sync_buffer_->IncreaseEndTimestamp(static_cast<uint32_t>(length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001807 }
1808 expand_->Reset();
1809}
1810
1811int NetEqImpl::DtmfOverdub(const DtmfEvent& dtmf_event, size_t num_channels,
1812 int16_t* output) const {
1813 size_t out_index = 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001814 size_t overdub_length = output_size_samples_; // Default value.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001815
1816 if (sync_buffer_->dtmf_index() > sync_buffer_->next_index()) {
1817 // Special operation for transition from "DTMF only" to "DTMF overdub".
1818 out_index = std::min(
1819 sync_buffer_->dtmf_index() - sync_buffer_->next_index(),
Peter Kastingdce40cf2015-08-24 14:52:23 -07001820 output_size_samples_);
1821 overdub_length = output_size_samples_ - out_index;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001822 }
1823
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001824 AudioMultiVector dtmf_output(num_channels);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001825 int dtmf_return_value = 0;
1826 if (!dtmf_tone_generator_->initialized()) {
1827 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1828 dtmf_event.volume);
1829 }
1830 if (dtmf_return_value == 0) {
1831 dtmf_return_value = dtmf_tone_generator_->Generate(overdub_length,
1832 &dtmf_output);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001833 assert(overdub_length == dtmf_output.Size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001834 }
1835 dtmf_output.ReadInterleaved(overdub_length, &output[out_index]);
1836 return dtmf_return_value < 0 ? dtmf_return_value : 0;
1837}
1838
Peter Kastingdce40cf2015-08-24 14:52:23 -07001839int NetEqImpl::ExtractPackets(size_t required_samples,
1840 PacketList* packet_list) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001841 bool first_packet = true;
1842 uint8_t prev_payload_type = 0;
1843 uint32_t prev_timestamp = 0;
1844 uint16_t prev_sequence_number = 0;
1845 bool next_packet_available = false;
1846
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001847 const RTPHeader* header = packet_buffer_->NextRtpHeader();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001848 assert(header);
1849 if (!header) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001850 LOG(LS_ERROR) << "Packet buffer unexpectedly empty.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001851 return -1;
1852 }
turaj@webrtc.org7df97062013-08-02 18:07:13 +00001853 uint32_t first_timestamp = header->timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001854 int extracted_samples = 0;
1855
1856 // Packet extraction loop.
1857 do {
1858 timestamp_ = header->timestamp;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001859 size_t discard_count = 0;
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001860 Packet* packet = packet_buffer_->GetNextPacket(&discard_count);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001861 // |header| may be invalid after the |packet_buffer_| operation.
1862 header = NULL;
1863 if (!packet) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001864 LOG(LS_ERROR) << "Should always be able to extract a packet here";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001865 assert(false); // Should always be able to extract a packet here.
1866 return -1;
1867 }
1868 stats_.PacketsDiscarded(discard_count);
1869 // Store waiting time in ms; packets->waiting_time is in "output blocks".
1870 stats_.StoreWaitingTime(packet->waiting_time * kOutputSizeMs);
1871 assert(packet->payload_length > 0);
1872 packet_list->push_back(packet); // Store packet in list.
1873
1874 if (first_packet) {
1875 first_packet = false;
henrik.lundin48ed9302015-10-29 05:36:24 -07001876 if (nack_enabled_) {
1877 RTC_DCHECK(nack_);
1878 // TODO(henrik.lundin): Should we update this for all decoded packets?
1879 nack_->UpdateLastDecodedPacket(packet->header.sequenceNumber,
1880 packet->header.timestamp);
1881 }
1882 prev_sequence_number = packet->header.sequenceNumber;
1883 prev_timestamp = packet->header.timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001884 prev_payload_type = packet->header.payloadType;
1885 }
1886
1887 // Store number of extracted samples.
1888 int packet_duration = 0;
1889 AudioDecoder* decoder = decoder_database_->GetDecoder(
1890 packet->header.payloadType);
1891 if (decoder) {
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001892 if (packet->sync_packet) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001893 packet_duration = rtc::checked_cast<int>(decoder_frame_length_);
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001894 } else {
minyue@webrtc.org2c1bcf22015-02-17 10:17:09 +00001895 if (packet->primary) {
1896 packet_duration = decoder->PacketDuration(packet->payload,
1897 packet->payload_length);
1898 } else {
1899 packet_duration = decoder->
1900 PacketDurationRedundant(packet->payload, packet->payload_length);
1901 stats_.SecondaryDecodedSamples(packet_duration);
1902 }
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001903 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001904 } else {
Henrik Lundind67a2192015-08-03 12:54:37 +02001905 LOG(LS_WARNING) << "Unknown payload type "
1906 << static_cast<int>(packet->header.payloadType);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001907 assert(false);
1908 }
1909 if (packet_duration <= 0) {
1910 // Decoder did not return a packet duration. Assume that the packet
1911 // contains the same number of samples as the previous one.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001912 packet_duration = rtc::checked_cast<int>(decoder_frame_length_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001913 }
1914 extracted_samples = packet->header.timestamp - first_timestamp +
1915 packet_duration;
1916
1917 // Check what packet is available next.
1918 header = packet_buffer_->NextRtpHeader();
1919 next_packet_available = false;
1920 if (header && prev_payload_type == header->payloadType) {
1921 int16_t seq_no_diff = header->sequenceNumber - prev_sequence_number;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001922 size_t ts_diff = header->timestamp - prev_timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001923 if (seq_no_diff == 1 ||
1924 (seq_no_diff == 0 && ts_diff == decoder_frame_length_)) {
1925 // The next sequence number is available, or the next part of a packet
1926 // that was split into pieces upon insertion.
1927 next_packet_available = true;
1928 }
1929 prev_sequence_number = header->sequenceNumber;
1930 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07001931 } while (extracted_samples < rtc::checked_cast<int>(required_samples) &&
1932 next_packet_available);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001933
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00001934 if (extracted_samples > 0) {
1935 // Delete old packets only when we are going to decode something. Otherwise,
1936 // we could end up in the situation where we never decode anything, since
1937 // all incoming packets are considered too old but the buffer will also
1938 // never be flooded and flushed.
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001939 packet_buffer_->DiscardAllOldPackets(timestamp_);
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00001940 }
1941
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001942 return extracted_samples;
1943}
1944
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001945void NetEqImpl::UpdatePlcComponents(int fs_hz, size_t channels) {
1946 // Delete objects and create new ones.
1947 expand_.reset(expand_factory_->Create(background_noise_.get(),
1948 sync_buffer_.get(), &random_vector_,
Henrik Lundinbef77e22015-08-18 14:58:09 +02001949 &stats_, fs_hz, channels));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001950 merge_.reset(new Merge(fs_hz, channels, expand_.get(), sync_buffer_.get()));
1951}
1952
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001953void NetEqImpl::SetSampleRateAndChannels(int fs_hz, size_t channels) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001954 LOG(LS_VERBOSE) << "SetSampleRateAndChannels " << fs_hz << " " << channels;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001955 // TODO(hlundin): Change to an enumerator and skip assert.
1956 assert(fs_hz == 8000 || fs_hz == 16000 || fs_hz == 32000 || fs_hz == 48000);
1957 assert(channels > 0);
1958
1959 fs_hz_ = fs_hz;
1960 fs_mult_ = fs_hz / 8000;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001961 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001962 decoder_frame_length_ = 3 * output_size_samples_; // Initialize to 30ms.
1963
1964 last_mode_ = kModeNormal;
1965
1966 // Create a new array of mute factors and set all to 1.
1967 mute_factor_array_.reset(new int16_t[channels]);
1968 for (size_t i = 0; i < channels; ++i) {
1969 mute_factor_array_[i] = 16384; // 1.0 in Q14.
1970 }
1971
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001972 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02001973 if (cng_decoder)
1974 cng_decoder->Reset();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001975
1976 // Reinit post-decode VAD with new sample rate.
1977 assert(vad_.get()); // Cannot be NULL here.
1978 vad_->Init();
1979
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001980 // Delete algorithm buffer and create a new one.
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001981 algorithm_buffer_.reset(new AudioMultiVector(channels));
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001982
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001983 // Delete sync buffer and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001984 sync_buffer_.reset(new SyncBuffer(channels, kSyncBufferSize * fs_mult_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001985
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00001986 // Delete BackgroundNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001987 background_noise_.reset(new BackgroundNoise(channels));
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00001988 background_noise_->set_mode(background_noise_mode_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001989
1990 // Reset random vector.
1991 random_vector_.Reset();
1992
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001993 UpdatePlcComponents(fs_hz, channels);
1994
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001995 // Move index so that we create a small set of future samples (all 0).
1996 sync_buffer_->set_next_index(sync_buffer_->next_index() -
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001997 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001998
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001999 normal_.reset(new Normal(fs_hz, decoder_database_.get(), *background_noise_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002000 expand_.get()));
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +00002001 accelerate_.reset(
2002 accelerate_factory_->Create(fs_hz, channels, *background_noise_));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002003 preemptive_expand_.reset(preemptive_expand_factory_->Create(
Peter Kastingdce40cf2015-08-24 14:52:23 -07002004 fs_hz, channels, *background_noise_, expand_->overlap_length()));
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002005
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002006 // Delete ComfortNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002007 comfort_noise_.reset(new ComfortNoise(fs_hz, decoder_database_.get(),
2008 sync_buffer_.get()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002009
2010 // Verify that |decoded_buffer_| is long enough.
2011 if (decoded_buffer_length_ < kMaxFrameSize * channels) {
2012 // Reallocate to larger size.
2013 decoded_buffer_length_ = kMaxFrameSize * channels;
2014 decoded_buffer_.reset(new int16_t[decoded_buffer_length_]);
2015 }
2016
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002017 // Create DecisionLogic if it is not created yet, then communicate new sample
2018 // rate and output size to DecisionLogic object.
2019 if (!decision_logic_.get()) {
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002020 CreateDecisionLogic();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002021 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002022 decision_logic_->SetSampleRate(fs_hz_, output_size_samples_);
2023}
2024
2025NetEqOutputType NetEqImpl::LastOutputType() {
2026 assert(vad_.get());
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002027 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002028 if (last_mode_ == kModeCodecInternalCng || last_mode_ == kModeRfc3389Cng) {
2029 return kOutputCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002030 } else if (last_mode_ == kModeExpand && expand_->MuteFactor(0) == 0) {
2031 // Expand mode has faded down to background noise only (very long expand).
2032 return kOutputPLCtoCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002033 } else if (last_mode_ == kModeExpand) {
2034 return kOutputPLC;
wu@webrtc.org24301a62013-12-13 19:17:43 +00002035 } else if (vad_->running() && !vad_->active_speech()) {
2036 return kOutputVADPassive;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002037 } else {
2038 return kOutputNormal;
2039 }
2040}
2041
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002042void NetEqImpl::CreateDecisionLogic() {
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002043 decision_logic_.reset(DecisionLogic::Create(fs_hz_, output_size_samples_,
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002044 playout_mode_,
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002045 decoder_database_.get(),
2046 *packet_buffer_.get(),
2047 delay_manager_.get(),
2048 buffer_level_filter_.get()));
2049}
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002050} // namespace webrtc