blob: 6b2fa4c9ecdfb880e52c69e37424310176661952 [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>
ossu61a208b2016-09-20 01:38:00 -070017#include <utility>
ossu97ba30e2016-04-25 07:55:58 -070018#include <vector>
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000019
henrik.lundin9c3efd02015-08-27 13:12:22 -070020#include "webrtc/base/checks.h"
Henrik Lundind67a2192015-08-03 12:54:37 +020021#include "webrtc/base/logging.h"
Tommid44c0772016-03-11 17:12:32 -080022#include "webrtc/base/safe_conversions.h"
kwibergac554ee2016-09-02 00:39:33 -070023#include "webrtc/base/sanitizer.h"
henrik.lundina689b442015-12-17 03:50:05 -080024#include "webrtc/base/trace_event.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000025#include "webrtc/common_audio/signal_processing/include/signal_processing_library.h"
kwiberg@webrtc.orge04a93b2014-12-09 10:12:53 +000026#include "webrtc/modules/audio_coding/codecs/audio_decoder.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000027#include "webrtc/modules/audio_coding/neteq/accelerate.h"
28#include "webrtc/modules/audio_coding/neteq/background_noise.h"
29#include "webrtc/modules/audio_coding/neteq/buffer_level_filter.h"
30#include "webrtc/modules/audio_coding/neteq/comfort_noise.h"
31#include "webrtc/modules/audio_coding/neteq/decision_logic.h"
32#include "webrtc/modules/audio_coding/neteq/decoder_database.h"
33#include "webrtc/modules/audio_coding/neteq/defines.h"
34#include "webrtc/modules/audio_coding/neteq/delay_manager.h"
35#include "webrtc/modules/audio_coding/neteq/delay_peak_detector.h"
36#include "webrtc/modules/audio_coding/neteq/dtmf_buffer.h"
37#include "webrtc/modules/audio_coding/neteq/dtmf_tone_generator.h"
38#include "webrtc/modules/audio_coding/neteq/expand.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000039#include "webrtc/modules/audio_coding/neteq/merge.h"
henrik.lundin91951862016-06-08 06:43:41 -070040#include "webrtc/modules/audio_coding/neteq/nack_tracker.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000041#include "webrtc/modules/audio_coding/neteq/normal.h"
42#include "webrtc/modules/audio_coding/neteq/packet_buffer.h"
43#include "webrtc/modules/audio_coding/neteq/packet.h"
ossua70695a2016-09-22 02:06:28 -070044#include "webrtc/modules/audio_coding/neteq/red_payload_splitter.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000045#include "webrtc/modules/audio_coding/neteq/post_decode_vad.h"
46#include "webrtc/modules/audio_coding/neteq/preemptive_expand.h"
47#include "webrtc/modules/audio_coding/neteq/sync_buffer.h"
henrik.lundined497212016-04-25 10:11:38 -070048#include "webrtc/modules/audio_coding/neteq/tick_timer.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000049#include "webrtc/modules/audio_coding/neteq/timestamp_scaler.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010050#include "webrtc/modules/include/module_common_types.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000051
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000052namespace webrtc {
53
ossue3525782016-05-25 07:37:43 -070054NetEqImpl::Dependencies::Dependencies(
55 const NetEq::Config& config,
56 const rtc::scoped_refptr<AudioDecoderFactory>& decoder_factory)
henrik.lundin1d9061e2016-04-26 12:19:34 -070057 : tick_timer(new TickTimer),
58 buffer_level_filter(new BufferLevelFilter),
ossue3525782016-05-25 07:37:43 -070059 decoder_database(new DecoderDatabase(decoder_factory)),
henrik.lundinf3933702016-04-28 01:53:52 -070060 delay_peak_detector(new DelayPeakDetector(tick_timer.get())),
henrik.lundin1d9061e2016-04-26 12:19:34 -070061 delay_manager(new DelayManager(config.max_packets_in_buffer,
henrik.lundin8f8c96d2016-04-28 23:19:20 -070062 delay_peak_detector.get(),
63 tick_timer.get())),
henrik.lundin1d9061e2016-04-26 12:19:34 -070064 dtmf_buffer(new DtmfBuffer(config.sample_rate_hz)),
65 dtmf_tone_generator(new DtmfToneGenerator),
66 packet_buffer(
67 new PacketBuffer(config.max_packets_in_buffer, tick_timer.get())),
ossua70695a2016-09-22 02:06:28 -070068 red_payload_splitter(new RedPayloadSplitter),
henrik.lundin1d9061e2016-04-26 12:19:34 -070069 timestamp_scaler(new TimestampScaler(*decoder_database)),
70 accelerate_factory(new AccelerateFactory),
71 expand_factory(new ExpandFactory),
72 preemptive_expand_factory(new PreemptiveExpandFactory) {}
73
74NetEqImpl::Dependencies::~Dependencies() = default;
75
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +000076NetEqImpl::NetEqImpl(const NetEq::Config& config,
henrik.lundin1d9061e2016-04-26 12:19:34 -070077 Dependencies&& deps,
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +000078 bool create_components)
henrik.lundin1d9061e2016-04-26 12:19:34 -070079 : tick_timer_(std::move(deps.tick_timer)),
80 buffer_level_filter_(std::move(deps.buffer_level_filter)),
81 decoder_database_(std::move(deps.decoder_database)),
82 delay_manager_(std::move(deps.delay_manager)),
83 delay_peak_detector_(std::move(deps.delay_peak_detector)),
84 dtmf_buffer_(std::move(deps.dtmf_buffer)),
85 dtmf_tone_generator_(std::move(deps.dtmf_tone_generator)),
86 packet_buffer_(std::move(deps.packet_buffer)),
ossua70695a2016-09-22 02:06:28 -070087 red_payload_splitter_(std::move(deps.red_payload_splitter)),
henrik.lundin1d9061e2016-04-26 12:19:34 -070088 timestamp_scaler_(std::move(deps.timestamp_scaler)),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000089 vad_(new PostDecodeVad()),
henrik.lundin1d9061e2016-04-26 12:19:34 -070090 expand_factory_(std::move(deps.expand_factory)),
91 accelerate_factory_(std::move(deps.accelerate_factory)),
92 preemptive_expand_factory_(std::move(deps.preemptive_expand_factory)),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000093 last_mode_(kModeNormal),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000094 decoded_buffer_length_(kMaxFrameSize),
95 decoded_buffer_(new int16_t[decoded_buffer_length_]),
96 playout_timestamp_(0),
97 new_codec_(false),
98 timestamp_(0),
99 reset_decoder_(false),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000100 ssrc_(0),
101 first_packet_(true),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000102 error_code_(0),
103 decoder_error_code_(0),
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +0000104 background_noise_mode_(config.background_noise_mode),
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000105 playout_mode_(config.playout_mode),
Henrik Lundincf808d22015-05-27 14:33:29 +0200106 enable_fast_accelerate_(config.enable_fast_accelerate),
henrik.lundin7a926812016-05-12 13:51:28 -0700107 nack_enabled_(false),
108 enable_muted_state_(config.enable_muted_state) {
Henrik Lundin905495c2015-05-25 16:58:41 +0200109 LOG(LS_INFO) << "NetEq config: " << config.ToString();
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +0000110 int fs = config.sample_rate_hz;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000111 if (fs != 8000 && fs != 16000 && fs != 32000 && fs != 48000) {
112 LOG(LS_ERROR) << "Sample rate " << fs << " Hz not supported. " <<
113 "Changing to 8000 Hz.";
114 fs = 8000;
115 }
henrik.lundin1d9061e2016-04-26 12:19:34 -0700116 delay_manager_->SetMaximumDelay(config.max_delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000117 fs_hz_ = fs;
118 fs_mult_ = fs / 8000;
henrik.lundind89814b2015-11-23 06:49:25 -0800119 last_output_sample_rate_hz_ = fs;
Peter Kastingdce40cf2015-08-24 14:52:23 -0700120 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000121 decoder_frame_length_ = 3 * output_size_samples_;
122 WebRtcSpl_Init();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000123 if (create_components) {
124 SetSampleRateAndChannels(fs, 1); // Default is 1 channel.
125 }
henrik.lundin9bc26672015-11-02 03:25:57 -0800126 RTC_DCHECK(!vad_->enabled());
127 if (config.enable_post_decode_vad) {
128 vad_->Enable();
129 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000130}
131
Henrik Lundind67a2192015-08-03 12:54:37 +0200132NetEqImpl::~NetEqImpl() = default;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000133
134int NetEqImpl::InsertPacket(const WebRtcRTPHeader& rtp_header,
kwibergee2bac22015-11-11 10:34:00 -0800135 rtc::ArrayView<const uint8_t> payload,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000136 uint32_t receive_timestamp) {
kwibergac554ee2016-09-02 00:39:33 -0700137 rtc::MsanCheckInitialized(payload);
henrik.lundina689b442015-12-17 03:50:05 -0800138 TRACE_EVENT0("webrtc", "NetEqImpl::InsertPacket");
Tommi9090e0b2016-01-20 13:39:36 +0100139 rtc::CritScope lock(&crit_sect_);
kwibergee2bac22015-11-11 10:34:00 -0800140 int error =
ossu17e3fa12016-09-08 04:52:55 -0700141 InsertPacketInternal(rtp_header, payload, receive_timestamp);
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000142 if (error != 0) {
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000143 error_code_ = error;
144 return kFail;
145 }
146 return kOK;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000147}
148
henrik.lundin500c04b2016-03-08 02:36:04 -0800149namespace {
150void SetAudioFrameActivityAndType(bool vad_enabled,
henrik.lundin55480f52016-03-08 02:37:57 -0800151 NetEqImpl::OutputType type,
henrik.lundin500c04b2016-03-08 02:36:04 -0800152 AudioFrame::VADActivity last_vad_activity,
153 AudioFrame* audio_frame) {
154 switch (type) {
henrik.lundin55480f52016-03-08 02:37:57 -0800155 case NetEqImpl::OutputType::kNormalSpeech: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800156 audio_frame->speech_type_ = AudioFrame::kNormalSpeech;
157 audio_frame->vad_activity_ = AudioFrame::kVadActive;
158 break;
159 }
henrik.lundin55480f52016-03-08 02:37:57 -0800160 case NetEqImpl::OutputType::kVadPassive: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800161 // This should only be reached if the VAD is enabled.
162 RTC_DCHECK(vad_enabled);
163 audio_frame->speech_type_ = AudioFrame::kNormalSpeech;
164 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
165 break;
166 }
henrik.lundin55480f52016-03-08 02:37:57 -0800167 case NetEqImpl::OutputType::kCNG: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800168 audio_frame->speech_type_ = AudioFrame::kCNG;
169 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
170 break;
171 }
henrik.lundin55480f52016-03-08 02:37:57 -0800172 case NetEqImpl::OutputType::kPLC: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800173 audio_frame->speech_type_ = AudioFrame::kPLC;
174 audio_frame->vad_activity_ = last_vad_activity;
175 break;
176 }
henrik.lundin55480f52016-03-08 02:37:57 -0800177 case NetEqImpl::OutputType::kPLCCNG: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800178 audio_frame->speech_type_ = AudioFrame::kPLCCNG;
179 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
180 break;
181 }
182 default:
183 RTC_NOTREACHED();
184 }
185 if (!vad_enabled) {
186 // Always set kVadUnknown when receive VAD is inactive.
187 audio_frame->vad_activity_ = AudioFrame::kVadUnknown;
188 }
189}
henrik.lundinbc89de32016-03-08 05:20:14 -0800190} // namespace
henrik.lundin500c04b2016-03-08 02:36:04 -0800191
henrik.lundin7a926812016-05-12 13:51:28 -0700192int NetEqImpl::GetAudio(AudioFrame* audio_frame, bool* muted) {
henrik.lundine1ca1672016-01-08 03:50:08 -0800193 TRACE_EVENT0("webrtc", "NetEqImpl::GetAudio");
Tommi9090e0b2016-01-20 13:39:36 +0100194 rtc::CritScope lock(&crit_sect_);
henrik.lundin7a926812016-05-12 13:51:28 -0700195 int error = GetAudioInternal(audio_frame, muted);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000196 if (error != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000197 error_code_ = error;
198 return kFail;
199 }
henrik.lundin5fac3f02016-08-24 11:18:49 -0700200 RTC_DCHECK_EQ(
201 audio_frame->sample_rate_hz_,
202 rtc::checked_cast<int>(audio_frame->samples_per_channel_ * 100));
henrik.lundin500c04b2016-03-08 02:36:04 -0800203 SetAudioFrameActivityAndType(vad_->enabled(), LastOutputType(),
204 last_vad_activity_, audio_frame);
205 last_vad_activity_ = audio_frame->vad_activity_;
henrik.lundin6d8e0112016-03-04 10:34:21 -0800206 last_output_sample_rate_hz_ = audio_frame->sample_rate_hz_;
henrik.lundind89814b2015-11-23 06:49:25 -0800207 RTC_DCHECK(last_output_sample_rate_hz_ == 8000 ||
208 last_output_sample_rate_hz_ == 16000 ||
209 last_output_sample_rate_hz_ == 32000 ||
210 last_output_sample_rate_hz_ == 48000)
211 << "Unexpected sample rate " << last_output_sample_rate_hz_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000212 return kOK;
213}
214
kwibergee1879c2015-10-29 06:20:28 -0700215int NetEqImpl::RegisterPayloadType(NetEqDecoder codec,
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800216 const std::string& name,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000217 uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100218 rtc::CritScope lock(&crit_sect_);
Henrik Lundind67a2192015-08-03 12:54:37 +0200219 LOG(LS_VERBOSE) << "RegisterPayloadType "
kwibergee1879c2015-10-29 06:20:28 -0700220 << static_cast<int>(rtp_payload_type) << " "
221 << static_cast<int>(codec);
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800222 int ret = decoder_database_->RegisterPayload(rtp_payload_type, codec, name);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000223 if (ret != DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000224 switch (ret) {
225 case DecoderDatabase::kInvalidRtpPayloadType:
226 error_code_ = kInvalidRtpPayloadType;
227 break;
228 case DecoderDatabase::kCodecNotSupported:
229 error_code_ = kCodecNotSupported;
230 break;
231 case DecoderDatabase::kDecoderExists:
232 error_code_ = kDecoderExists;
233 break;
234 default:
235 error_code_ = kOtherError;
236 }
237 return kFail;
238 }
239 return kOK;
240}
241
242int NetEqImpl::RegisterExternalDecoder(AudioDecoder* decoder,
kwibergee1879c2015-10-29 06:20:28 -0700243 NetEqDecoder codec,
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800244 const std::string& codec_name,
kwiberg342f7402016-06-16 03:18:00 -0700245 uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100246 rtc::CritScope lock(&crit_sect_);
Henrik Lundind67a2192015-08-03 12:54:37 +0200247 LOG(LS_VERBOSE) << "RegisterExternalDecoder "
kwibergee1879c2015-10-29 06:20:28 -0700248 << static_cast<int>(rtp_payload_type) << " "
249 << static_cast<int>(codec);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000250 if (!decoder) {
251 LOG(LS_ERROR) << "Cannot register external decoder with NULL pointer";
252 assert(false);
253 return kFail;
254 }
kwiberg342f7402016-06-16 03:18:00 -0700255 int ret = decoder_database_->InsertExternal(rtp_payload_type, codec,
256 codec_name, decoder);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000257 if (ret != DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000258 switch (ret) {
259 case DecoderDatabase::kInvalidRtpPayloadType:
260 error_code_ = kInvalidRtpPayloadType;
261 break;
262 case DecoderDatabase::kCodecNotSupported:
263 error_code_ = kCodecNotSupported;
264 break;
265 case DecoderDatabase::kDecoderExists:
266 error_code_ = kDecoderExists;
267 break;
268 case DecoderDatabase::kInvalidSampleRate:
269 error_code_ = kInvalidSampleRate;
270 break;
271 case DecoderDatabase::kInvalidPointer:
272 error_code_ = kInvalidPointer;
273 break;
274 default:
275 error_code_ = kOtherError;
276 }
277 return kFail;
278 }
279 return kOK;
280}
281
282int NetEqImpl::RemovePayloadType(uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100283 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000284 int ret = decoder_database_->Remove(rtp_payload_type);
285 if (ret == DecoderDatabase::kOK) {
ossu61a208b2016-09-20 01:38:00 -0700286 packet_buffer_->DiscardPacketsWithPayloadType(rtp_payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000287 return kOK;
288 } else if (ret == DecoderDatabase::kDecoderNotFound) {
289 error_code_ = kDecoderNotFound;
290 } else {
291 error_code_ = kOtherError;
292 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000293 return kFail;
294}
295
kwiberg6b19b562016-09-20 04:02:25 -0700296void NetEqImpl::RemoveAllPayloadTypes() {
297 rtc::CritScope lock(&crit_sect_);
298 decoder_database_->RemoveAll();
299}
300
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000301bool NetEqImpl::SetMinimumDelay(int delay_ms) {
Tommi9090e0b2016-01-20 13:39:36 +0100302 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000303 if (delay_ms >= 0 && delay_ms < 10000) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000304 assert(delay_manager_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000305 return delay_manager_->SetMinimumDelay(delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000306 }
307 return false;
308}
309
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000310bool NetEqImpl::SetMaximumDelay(int delay_ms) {
Tommi9090e0b2016-01-20 13:39:36 +0100311 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000312 if (delay_ms >= 0 && delay_ms < 10000) {
313 assert(delay_manager_.get());
314 return delay_manager_->SetMaximumDelay(delay_ms);
315 }
316 return false;
317}
318
319int NetEqImpl::LeastRequiredDelayMs() const {
Tommi9090e0b2016-01-20 13:39:36 +0100320 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000321 assert(delay_manager_.get());
322 return delay_manager_->least_required_delay_ms();
323}
324
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200325int NetEqImpl::SetTargetDelay() {
326 return kNotImplemented;
327}
328
329int NetEqImpl::TargetDelay() {
330 return kNotImplemented;
331}
332
henrik.lundin9c3efd02015-08-27 13:12:22 -0700333int NetEqImpl::CurrentDelayMs() const {
Tommi9090e0b2016-01-20 13:39:36 +0100334 rtc::CritScope lock(&crit_sect_);
henrik.lundin9c3efd02015-08-27 13:12:22 -0700335 if (fs_hz_ == 0)
336 return 0;
337 // Sum up the samples in the packet buffer with the future length of the sync
338 // buffer, and divide the sum by the sample rate.
339 const size_t delay_samples =
ossu61a208b2016-09-20 01:38:00 -0700340 packet_buffer_->NumSamplesInBuffer(decoder_frame_length_) +
henrik.lundin9c3efd02015-08-27 13:12:22 -0700341 sync_buffer_->FutureLength();
342 // The division below will truncate.
343 const int delay_ms =
344 static_cast<int>(delay_samples) / rtc::CheckedDivExact(fs_hz_, 1000);
345 return delay_ms;
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200346}
347
henrik.lundinb3f1c5d2016-08-22 15:39:53 -0700348int NetEqImpl::FilteredCurrentDelayMs() const {
349 rtc::CritScope lock(&crit_sect_);
350 // Calculate the filtered packet buffer level in samples. The value from
351 // |buffer_level_filter_| is in number of packets, represented in Q8.
352 const size_t packet_buffer_samples =
353 (buffer_level_filter_->filtered_current_level() *
354 decoder_frame_length_) >>
355 8;
356 // Sum up the filtered packet buffer level with the future length of the sync
357 // buffer, and divide the sum by the sample rate.
358 const size_t delay_samples =
359 packet_buffer_samples + sync_buffer_->FutureLength();
360 // The division below will truncate. The return value is in ms.
361 return static_cast<int>(delay_samples) / rtc::CheckedDivExact(fs_hz_, 1000);
362}
363
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000364// Deprecated.
365// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000366void NetEqImpl::SetPlayoutMode(NetEqPlayoutMode mode) {
Tommi9090e0b2016-01-20 13:39:36 +0100367 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000368 if (mode != playout_mode_) {
369 playout_mode_ = mode;
370 CreateDecisionLogic();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000371 }
372}
373
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000374// Deprecated.
375// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000376NetEqPlayoutMode NetEqImpl::PlayoutMode() const {
Tommi9090e0b2016-01-20 13:39:36 +0100377 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000378 return playout_mode_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000379}
380
381int NetEqImpl::NetworkStatistics(NetEqNetworkStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100382 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000383 assert(decoder_database_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700384 const size_t total_samples_in_buffers =
ossu61a208b2016-09-20 01:38:00 -0700385 packet_buffer_->NumSamplesInBuffer(decoder_frame_length_) +
Peter Kastingdce40cf2015-08-24 14:52:23 -0700386 sync_buffer_->FutureLength();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000387 assert(delay_manager_.get());
388 assert(decision_logic_.get());
389 stats_.GetNetworkStatistics(fs_hz_, total_samples_in_buffers,
390 decoder_frame_length_, *delay_manager_.get(),
391 *decision_logic_.get(), stats);
392 return 0;
393}
394
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000395void NetEqImpl::GetRtcpStatistics(RtcpStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100396 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000397 if (stats) {
398 rtcp_.GetStatistics(false, stats);
399 }
400}
401
402void NetEqImpl::GetRtcpStatisticsNoReset(RtcpStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100403 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000404 if (stats) {
405 rtcp_.GetStatistics(true, stats);
406 }
407}
408
409void NetEqImpl::EnableVad() {
Tommi9090e0b2016-01-20 13:39:36 +0100410 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000411 assert(vad_.get());
412 vad_->Enable();
413}
414
415void NetEqImpl::DisableVad() {
Tommi9090e0b2016-01-20 13:39:36 +0100416 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000417 assert(vad_.get());
418 vad_->Disable();
419}
420
henrik.lundin15c51e32016-04-06 08:38:56 -0700421rtc::Optional<uint32_t> NetEqImpl::GetPlayoutTimestamp() const {
Tommi9090e0b2016-01-20 13:39:36 +0100422 rtc::CritScope lock(&crit_sect_);
henrik.lundin0d96ab72016-04-06 12:28:26 -0700423 if (first_packet_ || last_mode_ == kModeRfc3389Cng ||
424 last_mode_ == kModeCodecInternalCng) {
wu@webrtc.org94454b72014-06-05 20:34:08 +0000425 // We don't have a valid RTP timestamp until we have decoded our first
henrik.lundin0d96ab72016-04-06 12:28:26 -0700426 // RTP packet. Also, the RTP timestamp is not accurate while playing CNG,
427 // which is indicated by returning an empty value.
henrik.lundin9a410dd2016-04-06 01:39:22 -0700428 return rtc::Optional<uint32_t>();
wu@webrtc.org94454b72014-06-05 20:34:08 +0000429 }
henrik.lundin9a410dd2016-04-06 01:39:22 -0700430 return rtc::Optional<uint32_t>(
431 timestamp_scaler_->ToExternal(playout_timestamp_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000432}
433
henrik.lundind89814b2015-11-23 06:49:25 -0800434int NetEqImpl::last_output_sample_rate_hz() const {
Tommi9090e0b2016-01-20 13:39:36 +0100435 rtc::CritScope lock(&crit_sect_);
henrik.lundind89814b2015-11-23 06:49:25 -0800436 return last_output_sample_rate_hz_;
437}
438
kwiberg6f0f6162016-09-20 03:07:46 -0700439rtc::Optional<CodecInst> NetEqImpl::GetDecoder(int payload_type) const {
440 rtc::CritScope lock(&crit_sect_);
441 const DecoderDatabase::DecoderInfo* di =
442 decoder_database_->GetDecoderInfo(payload_type);
443 if (!di) {
444 return rtc::Optional<CodecInst>();
445 }
446
447 // Create a CodecInst with some fields set. The remaining fields are zeroed,
448 // but we tell MSan to consider them uninitialized.
449 CodecInst ci = {0};
450 rtc::MsanMarkUninitialized(rtc::MakeArrayView(&ci, 1));
451 ci.pltype = payload_type;
452 std::strncpy(ci.plname, di->name.c_str(), sizeof(ci.plname));
453 ci.plname[sizeof(ci.plname) - 1] = '\0';
454 ci.plfreq = di->IsRed() || di->IsDtmf() ? 8000 : di->SampleRateHz();
455 AudioDecoder* const decoder = di->GetDecoder();
456 ci.channels = decoder ? decoder->Channels() : 1;
457 return rtc::Optional<CodecInst>(ci);
458}
459
kwibergc4ccd4d2016-09-21 10:55:15 -0700460const SdpAudioFormat* NetEqImpl::GetDecoderFormat(int payload_type) const {
461 rtc::CritScope lock(&crit_sect_);
462 const DecoderDatabase::DecoderInfo* const di =
463 decoder_database_->GetDecoderInfo(payload_type);
464 if (!di) {
465 return nullptr; // Payload type not registered.
466 }
467 // This will return null if the payload type was registered without an
468 // SdpAudioFormat.
469 return di->GetFormat();
470}
471
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200472int NetEqImpl::SetTargetNumberOfChannels() {
473 return kNotImplemented;
474}
475
476int NetEqImpl::SetTargetSampleRate() {
477 return kNotImplemented;
478}
479
henrik.lundin@webrtc.orgb0f4b3d2014-11-04 08:53:10 +0000480int NetEqImpl::LastError() const {
Tommi9090e0b2016-01-20 13:39:36 +0100481 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000482 return error_code_;
483}
484
485int NetEqImpl::LastDecoderError() {
Tommi9090e0b2016-01-20 13:39:36 +0100486 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000487 return decoder_error_code_;
488}
489
490void NetEqImpl::FlushBuffers() {
Tommi9090e0b2016-01-20 13:39:36 +0100491 rtc::CritScope lock(&crit_sect_);
Henrik Lundind67a2192015-08-03 12:54:37 +0200492 LOG(LS_VERBOSE) << "FlushBuffers";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000493 packet_buffer_->Flush();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000494 assert(sync_buffer_.get());
495 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000496 sync_buffer_->Flush();
497 sync_buffer_->set_next_index(sync_buffer_->next_index() -
498 expand_->overlap_length());
499 // Set to wait for new codec.
500 first_packet_ = true;
501}
502
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000503void NetEqImpl::PacketBufferStatistics(int* current_num_packets,
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000504 int* max_num_packets) const {
Tommi9090e0b2016-01-20 13:39:36 +0100505 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000506 packet_buffer_->BufferStat(current_num_packets, max_num_packets);
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000507}
508
henrik.lundin48ed9302015-10-29 05:36:24 -0700509void NetEqImpl::EnableNack(size_t max_nack_list_size) {
Tommi9090e0b2016-01-20 13:39:36 +0100510 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700511 if (!nack_enabled_) {
512 const int kNackThresholdPackets = 2;
henrik.lundin91951862016-06-08 06:43:41 -0700513 nack_.reset(NackTracker::Create(kNackThresholdPackets));
henrik.lundin48ed9302015-10-29 05:36:24 -0700514 nack_enabled_ = true;
515 nack_->UpdateSampleRate(fs_hz_);
516 }
517 nack_->SetMaxNackListSize(max_nack_list_size);
518}
519
520void NetEqImpl::DisableNack() {
Tommi9090e0b2016-01-20 13:39:36 +0100521 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700522 nack_.reset();
523 nack_enabled_ = false;
524}
525
526std::vector<uint16_t> NetEqImpl::GetNackList(int64_t round_trip_time_ms) const {
Tommi9090e0b2016-01-20 13:39:36 +0100527 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700528 if (!nack_enabled_) {
529 return std::vector<uint16_t>();
530 }
531 RTC_DCHECK(nack_.get());
532 return nack_->GetNackList(round_trip_time_ms);
minyue@webrtc.orgd7301772013-08-29 00:58:14 +0000533}
534
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000535const SyncBuffer* NetEqImpl::sync_buffer_for_test() const {
Tommi9090e0b2016-01-20 13:39:36 +0100536 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000537 return sync_buffer_.get();
538}
539
minyue5bd33972016-05-02 04:46:11 -0700540Operations NetEqImpl::last_operation_for_test() const {
541 rtc::CritScope lock(&crit_sect_);
542 return last_operation_;
543}
544
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000545// Methods below this line are private.
546
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000547int NetEqImpl::InsertPacketInternal(const WebRtcRTPHeader& rtp_header,
kwibergee2bac22015-11-11 10:34:00 -0800548 rtc::ArrayView<const uint8_t> payload,
ossu17e3fa12016-09-08 04:52:55 -0700549 uint32_t receive_timestamp) {
kwibergee2bac22015-11-11 10:34:00 -0800550 if (payload.empty()) {
551 LOG_F(LS_ERROR) << "payload is empty";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000552 return kInvalidPointer;
553 }
ossu17e3fa12016-09-08 04:52:55 -0700554
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000555 PacketList packet_list;
556 RTPHeader main_header;
557 {
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000558 // Convert to Packet.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000559 // Create |packet| within this separate scope, since it should not be used
560 // directly once it's been inserted in the packet list. This way, |packet|
561 // is not defined outside of this block.
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000562 Packet* packet = new Packet;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000563 packet->header.markerBit = false;
564 packet->header.payloadType = rtp_header.header.payloadType;
565 packet->header.sequenceNumber = rtp_header.header.sequenceNumber;
566 packet->header.timestamp = rtp_header.header.timestamp;
567 packet->header.ssrc = rtp_header.header.ssrc;
568 packet->header.numCSRCs = 0;
ossudc431ce2016-08-31 08:51:13 -0700569 packet->payload.SetData(payload.data(), payload.size());
henrik.lundin84f8cd62016-04-26 07:45:16 -0700570 // Waiting time will be set upon inserting the packet in the buffer.
571 RTC_DCHECK(!packet->waiting_time);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000572 // Insert packet in a packet list.
573 packet_list.push_back(packet);
574 // Save main payloads header for later.
575 memcpy(&main_header, &packet->header, sizeof(main_header));
576 }
577
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000578 bool update_sample_rate_and_channels = false;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000579 // Reinitialize NetEq if it's needed (changed SSRC or first call).
580 if ((main_header.ssrc != ssrc_) || first_packet_) {
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000581 // Note: |first_packet_| will be cleared further down in this method, once
582 // the packet has been successfully inserted into the packet buffer.
583
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000584 rtcp_.Init(main_header.sequenceNumber);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000585
586 // Flush the packet buffer and DTMF buffer.
587 packet_buffer_->Flush();
588 dtmf_buffer_->Flush();
589
590 // Store new SSRC.
591 ssrc_ = main_header.ssrc;
592
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000593 // Update audio buffer timestamp.
594 sync_buffer_->IncreaseEndTimestamp(main_header.timestamp - timestamp_);
595
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000596 // Update codecs.
597 timestamp_ = main_header.timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000598
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000599 // Reset timestamp scaling.
600 timestamp_scaler_->Reset();
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000601
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000602 // Trigger an update of sampling rate and the number of channels.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000603 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000604 }
605
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000606 // Update RTCP statistics, only for regular packets.
ossu17e3fa12016-09-08 04:52:55 -0700607 rtcp_.Update(main_header, receive_timestamp);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000608
609 // Check for RED payload type, and separate payloads into several packets.
610 if (decoder_database_->IsRed(main_header.payloadType)) {
ossua70695a2016-09-22 02:06:28 -0700611 if (!red_payload_splitter_->SplitRed(&packet_list)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000612 PacketBuffer::DeleteAllPackets(&packet_list);
613 return kRedundancySplitError;
614 }
615 // Only accept a few RED payloads of the same type as the main data,
616 // DTMF events and CNG.
ossua70695a2016-09-22 02:06:28 -0700617 red_payload_splitter_->CheckRedPayloads(&packet_list, *decoder_database_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000618 // Update the stored main payload header since the main payload has now
619 // changed.
620 memcpy(&main_header, &packet_list.front()->header, sizeof(main_header));
621 }
622
623 // Check payload types.
624 if (decoder_database_->CheckPayloadTypes(packet_list) ==
625 DecoderDatabase::kDecoderNotFound) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000626 PacketBuffer::DeleteAllPackets(&packet_list);
627 return kUnknownRtpPayloadType;
628 }
629
630 // Scale timestamp to internal domain (only for some codecs).
631 timestamp_scaler_->ToInternal(&packet_list);
632
633 // Process DTMF payloads. Cycle through the list of packets, and pick out any
634 // DTMF payloads found.
635 PacketList::iterator it = packet_list.begin();
636 while (it != packet_list.end()) {
637 Packet* current_packet = (*it);
638 assert(current_packet);
ossudc431ce2016-08-31 08:51:13 -0700639 assert(!current_packet->payload.empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000640 if (decoder_database_->IsDtmf(current_packet->header.payloadType)) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000641 DtmfEvent event;
ossudc431ce2016-08-31 08:51:13 -0700642 int ret = DtmfBuffer::ParseEvent(current_packet->header.timestamp,
643 current_packet->payload.data(),
644 current_packet->payload.size(), &event);
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000645 if (ret != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000646 PacketBuffer::DeleteAllPackets(&packet_list);
647 return kDtmfParsingError;
648 }
649 if (dtmf_buffer_->InsertEvent(event) != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000650 PacketBuffer::DeleteAllPackets(&packet_list);
651 return kDtmfInsertError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000652 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000653 delete current_packet;
654 it = packet_list.erase(it);
655 } else {
656 ++it;
657 }
658 }
659
ossu17e3fa12016-09-08 04:52:55 -0700660 // Update bandwidth estimate, if the packet is not comfort noise.
661 if (!packet_list.empty() &&
ossu97ba30e2016-04-25 07:55:58 -0700662 !decoder_database_->IsComfortNoise(main_header.payloadType)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000663 // The list can be empty here if we got nothing but DTMF payloads.
664 AudioDecoder* decoder =
665 decoder_database_->GetDecoder(main_header.payloadType);
666 assert(decoder); // Should always get a valid object, since we have
ossu97ba30e2016-04-25 07:55:58 -0700667 // already checked that the payload types are known.
ossudc431ce2016-08-31 08:51:13 -0700668 decoder->IncomingPacket(packet_list.front()->payload.data(),
669 packet_list.front()->payload.size(),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000670 packet_list.front()->header.sequenceNumber,
671 packet_list.front()->header.timestamp,
672 receive_timestamp);
673 }
674
ossu61a208b2016-09-20 01:38:00 -0700675 PacketList parsed_packet_list;
676 while (!packet_list.empty()) {
677 std::unique_ptr<Packet> packet(packet_list.front());
678 packet_list.pop_front();
679 const DecoderDatabase::DecoderInfo* info =
680 decoder_database_->GetDecoderInfo(packet->header.payloadType);
681 if (!info) {
682 LOG(LS_WARNING) << "SplitAudio unknown payload type";
683 return kUnknownRtpPayloadType;
684 }
685
686 if (info->IsComfortNoise()) {
687 // Carry comfort noise packets along.
688 parsed_packet_list.push_back(packet.release());
689 } else {
690 std::vector<AudioDecoder::ParseResult> results =
691 info->GetDecoder()->ParsePayload(std::move(packet->payload),
ossua70695a2016-09-22 02:06:28 -0700692 packet->header.timestamp);
ossu61a208b2016-09-20 01:38:00 -0700693 const RTPHeader& original_header = packet->header;
ossua70695a2016-09-22 02:06:28 -0700694 const Packet::Priority original_priority = packet->priority;
ossu61a208b2016-09-20 01:38:00 -0700695 for (auto& result : results) {
696 RTC_DCHECK(result.frame);
ossu0d526d52016-09-21 01:57:31 -0700697 // Reuse the packet if possible.
ossu61a208b2016-09-20 01:38:00 -0700698 if (!packet) {
699 packet.reset(new Packet);
700 packet->header = original_header;
701 }
702 packet->header.timestamp = result.timestamp;
ossua70695a2016-09-22 02:06:28 -0700703 RTC_DCHECK_GE(result.priority, 0);
704 packet->priority.codec_level = result.priority;
705 packet->priority.red_level = original_priority.red_level;
ossu61a208b2016-09-20 01:38:00 -0700706 packet->frame = std::move(result.frame);
707 parsed_packet_list.push_back(packet.release());
708 }
709 }
710 }
711
henrik.lundin48ed9302015-10-29 05:36:24 -0700712 if (nack_enabled_) {
713 RTC_DCHECK(nack_);
714 if (update_sample_rate_and_channels) {
715 nack_->Reset();
716 }
ossu61a208b2016-09-20 01:38:00 -0700717 nack_->UpdateLastReceivedPacket(
718 parsed_packet_list.front()->header.sequenceNumber,
719 parsed_packet_list.front()->header.timestamp);
henrik.lundin48ed9302015-10-29 05:36:24 -0700720 }
721
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000722 // Insert packets in buffer.
henrik.lundin116c84e2015-08-27 13:14:48 -0700723 const size_t buffer_length_before_insert =
724 packet_buffer_->NumPacketsInBuffer();
ossua70695a2016-09-22 02:06:28 -0700725 const int ret = packet_buffer_->InsertPacketList(
ossu61a208b2016-09-20 01:38:00 -0700726 &parsed_packet_list, *decoder_database_, &current_rtp_payload_type_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000727 &current_cng_rtp_payload_type_);
728 if (ret == PacketBuffer::kFlushed) {
729 // Reset DSP timestamp etc. if packet buffer flushed.
730 new_codec_ = true;
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000731 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000732 } else if (ret != PacketBuffer::kOK) {
ossu61a208b2016-09-20 01:38:00 -0700733 PacketBuffer::DeleteAllPackets(&parsed_packet_list);
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000734 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000735 }
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000736
737 if (first_packet_) {
738 first_packet_ = false;
739 // Update the codec on the next GetAudio call.
740 new_codec_ = true;
741 }
742
henrik.lundinda8bbf62016-08-31 03:14:11 -0700743 if (current_rtp_payload_type_) {
744 RTC_DCHECK(decoder_database_->GetDecoderInfo(*current_rtp_payload_type_))
745 << "Payload type " << static_cast<int>(*current_rtp_payload_type_)
746 << " is unknown where it shouldn't be";
747 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000748
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000749 if (update_sample_rate_and_channels && !packet_buffer_->Empty()) {
750 // We do not use |current_rtp_payload_type_| to |set payload_type|, but
751 // get the next RTP header from |packet_buffer_| to obtain the payload type.
752 // The reason for it is the following corner case. If NetEq receives a
753 // CNG packet with a sample rate different than the current CNG then it
754 // flushes its buffer, assuming send codec must have been changed. However,
755 // payload type of the hypothetically new send codec is not known.
756 const RTPHeader* rtp_header = packet_buffer_->NextRtpHeader();
757 assert(rtp_header);
758 int payload_type = rtp_header->payloadType;
ossu97ba30e2016-04-25 07:55:58 -0700759 size_t channels = 1;
760 if (!decoder_database_->IsComfortNoise(payload_type)) {
761 AudioDecoder* decoder = decoder_database_->GetDecoder(payload_type);
762 assert(decoder); // Payloads are already checked to be valid.
763 channels = decoder->Channels();
764 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000765 const DecoderDatabase::DecoderInfo* decoder_info =
766 decoder_database_->GetDecoderInfo(payload_type);
767 assert(decoder_info);
kwibergc0f2dcf2016-05-31 06:28:03 -0700768 if (decoder_info->SampleRateHz() != fs_hz_ ||
ossu97ba30e2016-04-25 07:55:58 -0700769 channels != algorithm_buffer_->Channels()) {
kwibergc0f2dcf2016-05-31 06:28:03 -0700770 SetSampleRateAndChannels(decoder_info->SampleRateHz(),
771 channels);
henrik.lundin48ed9302015-10-29 05:36:24 -0700772 }
773 if (nack_enabled_) {
774 RTC_DCHECK(nack_);
775 // Update the sample rate even if the rate is not new, because of Reset().
776 nack_->UpdateSampleRate(fs_hz_);
777 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000778 }
779
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000780 // TODO(hlundin): Move this code to DelayManager class.
781 const DecoderDatabase::DecoderInfo* dec_info =
782 decoder_database_->GetDecoderInfo(main_header.payloadType);
783 assert(dec_info); // Already checked that the payload type is known.
784 delay_manager_->LastDecoderType(dec_info->codec_type);
785 if (delay_manager_->last_pack_cng_or_dtmf() == 0) {
786 // Calculate the total speech length carried in each packet.
henrik.lundin116c84e2015-08-27 13:14:48 -0700787 const size_t buffer_length_after_insert =
788 packet_buffer_->NumPacketsInBuffer();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000789
henrik.lundin116c84e2015-08-27 13:14:48 -0700790 if (buffer_length_after_insert > buffer_length_before_insert) {
791 const size_t packet_length_samples =
792 (buffer_length_after_insert - buffer_length_before_insert) *
793 decoder_frame_length_;
794 if (packet_length_samples != decision_logic_->packet_length_samples()) {
795 decision_logic_->set_packet_length_samples(packet_length_samples);
796 delay_manager_->SetPacketAudioLength(
797 rtc::checked_cast<int>((1000 * packet_length_samples) / fs_hz_));
798 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000799 }
800
801 // Update statistics.
pbos@webrtc.org0946a562013-04-09 00:28:06 +0000802 if ((int32_t) (main_header.timestamp - timestamp_) >= 0 &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000803 !new_codec_) {
804 // Only update statistics if incoming packet is not older than last played
805 // out packet, and if new codec flag is not set.
806 delay_manager_->Update(main_header.sequenceNumber, main_header.timestamp,
807 fs_hz_);
808 }
809 } else if (delay_manager_->last_pack_cng_or_dtmf() == -1) {
810 // This is first "normal" packet after CNG or DTMF.
811 // Reset packet time counter and measure time until next packet,
812 // but don't update statistics.
813 delay_manager_->set_last_pack_cng_or_dtmf(0);
814 delay_manager_->ResetPacketIatCount();
815 }
816 return 0;
817}
818
henrik.lundin7a926812016-05-12 13:51:28 -0700819int NetEqImpl::GetAudioInternal(AudioFrame* audio_frame, bool* muted) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000820 PacketList packet_list;
821 DtmfEvent dtmf_event;
822 Operations operation;
823 bool play_dtmf;
henrik.lundin7a926812016-05-12 13:51:28 -0700824 *muted = false;
henrik.lundined497212016-04-25 10:11:38 -0700825 tick_timer_->Increment();
henrik.lundin60f6ce22016-05-10 03:52:04 -0700826 stats_.IncreaseCounter(output_size_samples_, fs_hz_);
henrik.lundin7a926812016-05-12 13:51:28 -0700827
828 // Check for muted state.
829 if (enable_muted_state_ && expand_->Muted() && packet_buffer_->Empty()) {
830 RTC_DCHECK_EQ(last_mode_, kModeExpand);
831 playout_timestamp_ += static_cast<uint32_t>(output_size_samples_);
832 audio_frame->sample_rate_hz_ = fs_hz_;
833 audio_frame->samples_per_channel_ = output_size_samples_;
834 audio_frame->timestamp_ =
835 first_packet_
836 ? 0
837 : timestamp_scaler_->ToExternal(playout_timestamp_) -
838 static_cast<uint32_t>(audio_frame->samples_per_channel_);
839 audio_frame->num_channels_ = sync_buffer_->Channels();
henrik.lundin612c25e2016-05-25 08:21:04 -0700840 stats_.ExpandedNoiseSamples(output_size_samples_);
henrik.lundin7a926812016-05-12 13:51:28 -0700841 *muted = true;
842 return 0;
843 }
844
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000845 int return_value = GetDecision(&operation, &packet_list, &dtmf_event,
846 &play_dtmf);
847 if (return_value != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000848 last_mode_ = kModeError;
849 return return_value;
850 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000851
852 AudioDecoder::SpeechType speech_type;
853 int length = 0;
854 int decode_return_value = Decode(&packet_list, &operation,
855 &length, &speech_type);
856
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000857 assert(vad_.get());
858 bool sid_frame_available =
859 (operation == kRfc3389Cng && !packet_list.empty());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700860 vad_->Update(decoded_buffer_.get(), static_cast<size_t>(length), speech_type,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000861 sid_frame_available, fs_hz_);
862
henrik.lundinb1fb72b2016-05-03 08:18:47 -0700863 if (sid_frame_available || speech_type == AudioDecoder::kComfortNoise) {
864 // Start a new stopwatch since we are decoding a new CNG packet.
865 generated_noise_stopwatch_ = tick_timer_->GetNewStopwatch();
866 }
867
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000868 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000869 switch (operation) {
870 case kNormal: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000871 DoNormal(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000872 break;
873 }
874 case kMerge: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000875 DoMerge(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000876 break;
877 }
878 case kExpand: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000879 return_value = DoExpand(play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000880 break;
881 }
Henrik Lundincf808d22015-05-27 14:33:29 +0200882 case kAccelerate:
883 case kFastAccelerate: {
884 const bool fast_accelerate =
885 enable_fast_accelerate_ && (operation == kFastAccelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000886 return_value = DoAccelerate(decoded_buffer_.get(), length, speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +0200887 play_dtmf, fast_accelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000888 break;
889 }
890 case kPreemptiveExpand: {
891 return_value = DoPreemptiveExpand(decoded_buffer_.get(), length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000892 speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000893 break;
894 }
895 case kRfc3389Cng:
896 case kRfc3389CngNoPacket: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000897 return_value = DoRfc3389Cng(&packet_list, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000898 break;
899 }
900 case kCodecInternalCng: {
901 // This handles the case when there is no transmission and the decoder
902 // should produce internal comfort noise.
903 // TODO(hlundin): Write test for codec-internal CNG.
minyuel6d92bf52015-09-23 15:20:39 +0200904 DoCodecInternalCng(decoded_buffer_.get(), length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000905 break;
906 }
907 case kDtmf: {
908 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000909 return_value = DoDtmf(dtmf_event, &play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000910 break;
911 }
912 case kAlternativePlc: {
913 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000914 DoAlternativePlc(false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000915 break;
916 }
917 case kAlternativePlcIncreaseTimestamp: {
918 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000919 DoAlternativePlc(true);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000920 break;
921 }
922 case kAudioRepetitionIncreaseTimestamp: {
923 // TODO(hlundin): Write test for this.
Peter Kastingb7e50542015-06-11 12:55:50 -0700924 sync_buffer_->IncreaseEndTimestamp(
925 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000926 // Skipping break on purpose. Execution should move on into the
927 // next case.
kjellander@webrtc.org7d2b6a92015-01-28 18:37:58 +0000928 FALLTHROUGH();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000929 }
930 case kAudioRepetition: {
931 // TODO(hlundin): Write test for this.
932 // Copy last |output_size_samples_| from |sync_buffer_| to
933 // |algorithm_buffer|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000934 algorithm_buffer_->PushBackFromIndex(
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000935 *sync_buffer_, sync_buffer_->Size() - output_size_samples_);
936 expand_->Reset();
937 break;
938 }
939 case kUndefined: {
Henrik Lundind67a2192015-08-03 12:54:37 +0200940 LOG(LS_ERROR) << "Invalid operation kUndefined.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000941 assert(false); // This should not happen.
942 last_mode_ = kModeError;
943 return kInvalidOperation;
944 }
945 } // End of switch.
minyue5bd33972016-05-02 04:46:11 -0700946 last_operation_ = operation;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000947 if (return_value < 0) {
948 return return_value;
949 }
950
951 if (last_mode_ != kModeRfc3389Cng) {
952 comfort_noise_->Reset();
953 }
954
955 // Copy from |algorithm_buffer| to |sync_buffer_|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000956 sync_buffer_->PushBack(*algorithm_buffer_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000957
958 // Extract data from |sync_buffer_| to |output|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000959 size_t num_output_samples_per_channel = output_size_samples_;
960 size_t num_output_samples = output_size_samples_ * sync_buffer_->Channels();
henrik.lundin6d8e0112016-03-04 10:34:21 -0800961 if (num_output_samples > AudioFrame::kMaxDataSizeSamples) {
962 LOG(LS_WARNING) << "Output array is too short. "
963 << AudioFrame::kMaxDataSizeSamples << " < "
964 << output_size_samples_ << " * "
965 << sync_buffer_->Channels();
966 num_output_samples = AudioFrame::kMaxDataSizeSamples;
967 num_output_samples_per_channel =
968 AudioFrame::kMaxDataSizeSamples / sync_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000969 }
henrik.lundin6d8e0112016-03-04 10:34:21 -0800970 sync_buffer_->GetNextAudioInterleaved(num_output_samples_per_channel,
971 audio_frame);
972 audio_frame->sample_rate_hz_ = fs_hz_;
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200973 if (sync_buffer_->FutureLength() < expand_->overlap_length()) {
974 // The sync buffer should always contain |overlap_length| samples, but now
975 // too many samples have been extracted. Reinstall the |overlap_length|
976 // lookahead by moving the index.
977 const size_t missing_lookahead_samples =
978 expand_->overlap_length() - sync_buffer_->FutureLength();
henrikg91d6ede2015-09-17 00:24:34 -0700979 RTC_DCHECK_GE(sync_buffer_->next_index(), missing_lookahead_samples);
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200980 sync_buffer_->set_next_index(sync_buffer_->next_index() -
981 missing_lookahead_samples);
982 }
henrik.lundin6d8e0112016-03-04 10:34:21 -0800983 if (audio_frame->samples_per_channel_ != output_size_samples_) {
984 LOG(LS_ERROR) << "audio_frame->samples_per_channel_ ("
985 << audio_frame->samples_per_channel_
Henrik Lundind67a2192015-08-03 12:54:37 +0200986 << ") != output_size_samples_ (" << output_size_samples_
987 << ")";
minyue@webrtc.orgdb1cefc2013-08-13 01:39:21 +0000988 // TODO(minyue): treatment of under-run, filling zeros
henrik.lundin6d8e0112016-03-04 10:34:21 -0800989 memset(audio_frame->data_, 0, num_output_samples * sizeof(int16_t));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000990 return kSampleUnderrun;
991 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000992
993 // Should always have overlap samples left in the |sync_buffer_|.
henrikg91d6ede2015-09-17 00:24:34 -0700994 RTC_DCHECK_GE(sync_buffer_->FutureLength(), expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000995
996 if (play_dtmf) {
henrik.lundin6d8e0112016-03-04 10:34:21 -0800997 return_value =
998 DtmfOverdub(dtmf_event, sync_buffer_->Channels(), audio_frame->data_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000999 }
1000
1001 // Update the background noise parameters if last operation wrote data
1002 // straight from the decoder to the |sync_buffer_|. That is, none of the
1003 // operations that modify the signal can be followed by a parameter update.
1004 if ((last_mode_ == kModeNormal) ||
1005 (last_mode_ == kModeAccelerateFail) ||
1006 (last_mode_ == kModePreemptiveExpandFail) ||
1007 (last_mode_ == kModeRfc3389Cng) ||
1008 (last_mode_ == kModeCodecInternalCng)) {
1009 background_noise_->Update(*sync_buffer_, *vad_.get());
1010 }
1011
1012 if (operation == kDtmf) {
1013 // DTMF data was written the end of |sync_buffer_|.
1014 // Update index to end of DTMF data in |sync_buffer_|.
1015 sync_buffer_->set_dtmf_index(sync_buffer_->Size());
1016 }
1017
henrik.lundin@webrtc.orged865b52014-03-06 10:28:07 +00001018 if (last_mode_ != kModeExpand) {
1019 // If last operation was not expand, calculate the |playout_timestamp_| from
1020 // the |sync_buffer_|. However, do not update the |playout_timestamp_| if it
1021 // would be moved "backwards".
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001022 uint32_t temp_timestamp = sync_buffer_->end_timestamp() -
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001023 static_cast<uint32_t>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001024 if (static_cast<int32_t>(temp_timestamp - playout_timestamp_) > 0) {
1025 playout_timestamp_ = temp_timestamp;
1026 }
1027 } else {
1028 // Use dead reckoning to estimate the |playout_timestamp_|.
Peter Kastingb7e50542015-06-11 12:55:50 -07001029 playout_timestamp_ += static_cast<uint32_t>(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001030 }
henrik.lundin15c51e32016-04-06 08:38:56 -07001031 // Set the timestamp in the audio frame to zero before the first packet has
1032 // been inserted. Otherwise, subtract the frame size in samples to get the
1033 // timestamp of the first sample in the frame (playout_timestamp_ is the
1034 // last + 1).
1035 audio_frame->timestamp_ =
1036 first_packet_
1037 ? 0
1038 : timestamp_scaler_->ToExternal(playout_timestamp_) -
1039 static_cast<uint32_t>(audio_frame->samples_per_channel_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001040
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001041 if (!(last_mode_ == kModeRfc3389Cng ||
1042 last_mode_ == kModeCodecInternalCng ||
1043 last_mode_ == kModeExpand)) {
1044 generated_noise_stopwatch_.reset();
1045 }
1046
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001047 if (decode_return_value) return decode_return_value;
1048 return return_value;
1049}
1050
1051int NetEqImpl::GetDecision(Operations* operation,
1052 PacketList* packet_list,
1053 DtmfEvent* dtmf_event,
1054 bool* play_dtmf) {
1055 // Initialize output variables.
1056 *play_dtmf = false;
1057 *operation = kUndefined;
1058
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001059 assert(sync_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001060 uint32_t end_timestamp = sync_buffer_->end_timestamp();
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001061 if (!new_codec_) {
1062 const uint32_t five_seconds_samples = 5 * fs_hz_;
1063 packet_buffer_->DiscardOldPackets(end_timestamp, five_seconds_samples);
1064 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001065 const RTPHeader* header = packet_buffer_->NextRtpHeader();
1066
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001067 RTC_DCHECK(!generated_noise_stopwatch_ ||
1068 generated_noise_stopwatch_->ElapsedTicks() >= 1);
1069 uint64_t generated_noise_samples =
1070 generated_noise_stopwatch_
1071 ? (generated_noise_stopwatch_->ElapsedTicks() - 1) *
1072 output_size_samples_ +
1073 decision_logic_->noise_fast_forward()
1074 : 0;
1075
henrik.lundin@webrtc.orgca8cb952014-03-12 10:26:52 +00001076 if (decision_logic_->CngRfc3389On() || last_mode_ == kModeRfc3389Cng) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001077 // Because of timestamp peculiarities, we have to "manually" disallow using
1078 // a CNG packet with the same timestamp as the one that was last played.
1079 // This can happen when using redundancy and will cause the timing to shift.
henrik.lundin@webrtc.org24779fe2014-03-14 12:40:05 +00001080 while (header && decoder_database_->IsComfortNoise(header->payloadType) &&
1081 (end_timestamp >= header->timestamp ||
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001082 end_timestamp + generated_noise_samples > header->timestamp)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001083 // Don't use this packet, discard it.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001084 if (packet_buffer_->DiscardNextPacket() != PacketBuffer::kOK) {
1085 assert(false); // Must be ok by design.
1086 }
1087 // Check buffer again.
1088 if (!new_codec_) {
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001089 packet_buffer_->DiscardOldPackets(end_timestamp, 5 * fs_hz_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001090 }
1091 header = packet_buffer_->NextRtpHeader();
1092 }
1093 }
1094
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001095 assert(expand_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001096 const int samples_left = static_cast<int>(sync_buffer_->FutureLength() -
1097 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001098 if (last_mode_ == kModeAccelerateSuccess ||
1099 last_mode_ == kModeAccelerateLowEnergy ||
1100 last_mode_ == kModePreemptiveExpandSuccess ||
1101 last_mode_ == kModePreemptiveExpandLowEnergy) {
1102 // Subtract (samples_left + output_size_samples_) from sampleMemory.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001103 decision_logic_->AddSampleMemory(
1104 -(samples_left + rtc::checked_cast<int>(output_size_samples_)));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001105 }
1106
1107 // Check if it is time to play a DTMF event.
Peter Kastingb7e50542015-06-11 12:55:50 -07001108 if (dtmf_buffer_->GetEvent(
1109 static_cast<uint32_t>(
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001110 end_timestamp + generated_noise_samples),
Peter Kastingb7e50542015-06-11 12:55:50 -07001111 dtmf_event)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001112 *play_dtmf = true;
1113 }
1114
1115 // Get instruction.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001116 assert(sync_buffer_.get());
1117 assert(expand_.get());
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001118 generated_noise_samples =
1119 generated_noise_stopwatch_
1120 ? generated_noise_stopwatch_->ElapsedTicks() * output_size_samples_ +
1121 decision_logic_->noise_fast_forward()
1122 : 0;
1123 *operation = decision_logic_->GetDecision(
1124 *sync_buffer_, *expand_, decoder_frame_length_, header, last_mode_,
1125 *play_dtmf, generated_noise_samples, &reset_decoder_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001126
1127 // Check if we already have enough samples in the |sync_buffer_|. If so,
1128 // change decision to normal, unless the decision was merge, accelerate, or
1129 // preemptive expand.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001130 if (samples_left >= rtc::checked_cast<int>(output_size_samples_) &&
1131 *operation != kMerge &&
1132 *operation != kAccelerate &&
1133 *operation != kFastAccelerate &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001134 *operation != kPreemptiveExpand) {
1135 *operation = kNormal;
1136 return 0;
1137 }
1138
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001139 decision_logic_->ExpandDecision(*operation);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001140
1141 // Check conditions for reset.
1142 if (new_codec_ || *operation == kUndefined) {
1143 // The only valid reason to get kUndefined is that new_codec_ is set.
1144 assert(new_codec_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001145 if (*play_dtmf && !header) {
1146 timestamp_ = dtmf_event->timestamp;
1147 } else {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001148 if (!header) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001149 LOG(LS_ERROR) << "Packet missing where it shouldn't.";
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001150 return -1;
1151 }
1152 timestamp_ = header->timestamp;
ossu108ecec2016-07-08 08:45:18 -07001153 if (*operation == kRfc3389CngNoPacket &&
1154 decoder_database_->IsComfortNoise(header->payloadType)) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001155 // Change decision to CNG packet, since we do have a CNG packet, but it
1156 // was considered too early to use. Now, use it anyway.
1157 *operation = kRfc3389Cng;
1158 } else if (*operation != kRfc3389Cng) {
1159 *operation = kNormal;
1160 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001161 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001162 // Adjust |sync_buffer_| timestamp before setting |end_timestamp| to the
1163 // new value.
1164 sync_buffer_->IncreaseEndTimestamp(timestamp_ - end_timestamp);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001165 end_timestamp = timestamp_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001166 new_codec_ = false;
1167 decision_logic_->SoftReset();
1168 buffer_level_filter_->Reset();
1169 delay_manager_->Reset();
1170 stats_.ResetMcu();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001171 }
1172
Peter Kastingdce40cf2015-08-24 14:52:23 -07001173 size_t required_samples = output_size_samples_;
1174 const size_t samples_10_ms = static_cast<size_t>(80 * fs_mult_);
1175 const size_t samples_20_ms = 2 * samples_10_ms;
1176 const size_t samples_30_ms = 3 * samples_10_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001177
1178 switch (*operation) {
1179 case kExpand: {
1180 timestamp_ = end_timestamp;
1181 return 0;
1182 }
1183 case kRfc3389CngNoPacket:
1184 case kCodecInternalCng: {
1185 return 0;
1186 }
1187 case kDtmf: {
1188 // TODO(hlundin): Write test for this.
1189 // Update timestamp.
1190 timestamp_ = end_timestamp;
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001191 const uint64_t generated_noise_samples =
1192 generated_noise_stopwatch_
1193 ? generated_noise_stopwatch_->ElapsedTicks() *
1194 output_size_samples_ +
1195 decision_logic_->noise_fast_forward()
1196 : 0;
1197 if (generated_noise_samples > 0 && last_mode_ != kModeDtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001198 // Make a jump in timestamp due to the recently played comfort noise.
Peter Kastingb7e50542015-06-11 12:55:50 -07001199 uint32_t timestamp_jump =
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001200 static_cast<uint32_t>(generated_noise_samples);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001201 sync_buffer_->IncreaseEndTimestamp(timestamp_jump);
1202 timestamp_ += timestamp_jump;
1203 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001204 return 0;
1205 }
Henrik Lundincf808d22015-05-27 14:33:29 +02001206 case kAccelerate:
1207 case kFastAccelerate: {
1208 // In order to do an accelerate we need at least 30 ms of audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001209 if (samples_left >= static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001210 // Already have enough data, so we do not need to extract any more.
1211 decision_logic_->set_sample_memory(samples_left);
1212 decision_logic_->set_prev_time_scale(true);
1213 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001214 } else if (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001215 decoder_frame_length_ >= samples_30_ms) {
1216 // Avoid decoding more data as it might overflow the playout buffer.
1217 *operation = kNormal;
1218 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001219 } else if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001220 decoder_frame_length_ < samples_30_ms) {
1221 // Build up decoded data by decoding at least 20 ms of audio data. Do
1222 // not perform accelerate yet, but wait until we only need to do one
1223 // decoding.
1224 required_samples = 2 * output_size_samples_;
1225 *operation = kNormal;
1226 }
1227 // If none of the above is true, we have one of two possible situations:
1228 // (1) 20 ms <= samples_left < 30 ms and decoder_frame_length_ < 30 ms; or
1229 // (2) samples_left < 10 ms and decoder_frame_length_ >= 30 ms.
1230 // In either case, we move on with the accelerate decision, and decode one
1231 // frame now.
1232 break;
1233 }
1234 case kPreemptiveExpand: {
1235 // In order to do a preemptive expand we need at least 30 ms of decoded
1236 // audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001237 if ((samples_left >= static_cast<int>(samples_30_ms)) ||
1238 (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001239 decoder_frame_length_ >= samples_30_ms)) {
1240 // Already have enough data, so we do not need to extract any more.
1241 // Or, avoid decoding more data as it might overflow the playout buffer.
1242 // Still try preemptive expand, though.
1243 decision_logic_->set_sample_memory(samples_left);
1244 decision_logic_->set_prev_time_scale(true);
1245 return 0;
1246 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07001247 if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001248 decoder_frame_length_ < samples_30_ms) {
1249 // Build up decoded data by decoding at least 20 ms of audio data.
1250 // Still try to perform preemptive expand.
1251 required_samples = 2 * output_size_samples_;
1252 }
1253 // Move on with the preemptive expand decision.
1254 break;
1255 }
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001256 case kMerge: {
1257 required_samples =
1258 std::max(merge_->RequiredFutureSamples(), required_samples);
1259 break;
1260 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001261 default: {
1262 // Do nothing.
1263 }
1264 }
1265
1266 // Get packets from buffer.
1267 int extracted_samples = 0;
1268 if (header &&
1269 *operation != kAlternativePlc &&
1270 *operation != kAlternativePlcIncreaseTimestamp &&
1271 *operation != kAudioRepetition &&
1272 *operation != kAudioRepetitionIncreaseTimestamp) {
1273 sync_buffer_->IncreaseEndTimestamp(header->timestamp - end_timestamp);
1274 if (decision_logic_->CngOff()) {
1275 // Adjustment of timestamp only corresponds to an actual packet loss
1276 // if comfort noise is not played. If comfort noise was just played,
1277 // this adjustment of timestamp is only done to get back in sync with the
1278 // stream timestamp; no loss to report.
1279 stats_.LostSamples(header->timestamp - end_timestamp);
1280 }
1281
1282 if (*operation != kRfc3389Cng) {
1283 // We are about to decode and use a non-CNG packet.
1284 decision_logic_->SetCngOff();
1285 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001286
1287 extracted_samples = ExtractPackets(required_samples, packet_list);
1288 if (extracted_samples < 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001289 return kPacketBufferCorruption;
1290 }
1291 }
1292
Henrik Lundincf808d22015-05-27 14:33:29 +02001293 if (*operation == kAccelerate || *operation == kFastAccelerate ||
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001294 *operation == kPreemptiveExpand) {
1295 decision_logic_->set_sample_memory(samples_left + extracted_samples);
1296 decision_logic_->set_prev_time_scale(true);
1297 }
1298
Henrik Lundincf808d22015-05-27 14:33:29 +02001299 if (*operation == kAccelerate || *operation == kFastAccelerate) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001300 // Check that we have enough data (30ms) to do accelerate.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001301 if (extracted_samples + samples_left < static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001302 // TODO(hlundin): Write test for this.
1303 // Not enough, do normal operation instead.
1304 *operation = kNormal;
1305 }
1306 }
1307
1308 timestamp_ = end_timestamp;
1309 return 0;
1310}
1311
1312int NetEqImpl::Decode(PacketList* packet_list, Operations* operation,
1313 int* decoded_length,
1314 AudioDecoder::SpeechType* speech_type) {
1315 *speech_type = AudioDecoder::kSpeech;
minyuel6d92bf52015-09-23 15:20:39 +02001316
1317 // When packet_list is empty, we may be in kCodecInternalCng mode, and for
1318 // that we use current active decoder.
1319 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1320
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001321 if (!packet_list->empty()) {
1322 const Packet* packet = packet_list->front();
pkasting@chromium.org0e81fdf2015-02-02 23:54:03 +00001323 uint8_t payload_type = packet->header.payloadType;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001324 if (!decoder_database_->IsComfortNoise(payload_type)) {
1325 decoder = decoder_database_->GetDecoder(payload_type);
1326 assert(decoder);
1327 if (!decoder) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001328 LOG(LS_WARNING) << "Unknown payload type "
1329 << static_cast<int>(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001330 PacketBuffer::DeleteAllPackets(packet_list);
1331 return kDecoderNotFound;
1332 }
1333 bool decoder_changed;
1334 decoder_database_->SetActiveDecoder(payload_type, &decoder_changed);
1335 if (decoder_changed) {
1336 // We have a new decoder. Re-init some values.
1337 const DecoderDatabase::DecoderInfo* decoder_info = decoder_database_
1338 ->GetDecoderInfo(payload_type);
1339 assert(decoder_info);
1340 if (!decoder_info) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001341 LOG(LS_WARNING) << "Unknown payload type "
1342 << static_cast<int>(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001343 PacketBuffer::DeleteAllPackets(packet_list);
1344 return kDecoderNotFound;
1345 }
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001346 // If sampling rate or number of channels has changed, we need to make
1347 // a reset.
kwibergc0f2dcf2016-05-31 06:28:03 -07001348 if (decoder_info->SampleRateHz() != fs_hz_ ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001349 decoder->Channels() != algorithm_buffer_->Channels()) {
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001350 // TODO(tlegrand): Add unittest to cover this event.
kwibergc0f2dcf2016-05-31 06:28:03 -07001351 SetSampleRateAndChannels(decoder_info->SampleRateHz(),
1352 decoder->Channels());
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001353 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001354 sync_buffer_->set_end_timestamp(timestamp_);
1355 playout_timestamp_ = timestamp_;
1356 }
1357 }
1358 }
1359
1360 if (reset_decoder_) {
1361 // TODO(hlundin): Write test for this.
Karl Wiberg43766482015-08-27 15:22:11 +02001362 if (decoder)
1363 decoder->Reset();
1364
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001365 // Reset comfort noise decoder.
ossu97ba30e2016-04-25 07:55:58 -07001366 ComfortNoiseDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02001367 if (cng_decoder)
1368 cng_decoder->Reset();
1369
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001370 reset_decoder_ = false;
1371 }
1372
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001373 *decoded_length = 0;
1374 // Update codec-internal PLC state.
1375 if ((*operation == kMerge) && decoder && decoder->HasDecodePlc()) {
1376 decoder->DecodePlc(1, &decoded_buffer_[*decoded_length]);
1377 }
1378
minyuel6d92bf52015-09-23 15:20:39 +02001379 int return_value;
1380 if (*operation == kCodecInternalCng) {
1381 RTC_DCHECK(packet_list->empty());
1382 return_value = DecodeCng(decoder, decoded_length, speech_type);
1383 } else {
1384 return_value = DecodeLoop(packet_list, *operation, decoder,
1385 decoded_length, speech_type);
1386 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001387
1388 if (*decoded_length < 0) {
1389 // Error returned from the decoder.
1390 *decoded_length = 0;
Peter Kastingb7e50542015-06-11 12:55:50 -07001391 sync_buffer_->IncreaseEndTimestamp(
1392 static_cast<uint32_t>(decoder_frame_length_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001393 int error_code = 0;
1394 if (decoder)
1395 error_code = decoder->ErrorCode();
1396 if (error_code != 0) {
1397 // Got some error code from the decoder.
1398 decoder_error_code_ = error_code;
1399 return_value = kDecoderErrorCode;
Henrik Lundind67a2192015-08-03 12:54:37 +02001400 LOG(LS_WARNING) << "Decoder returned error code: " << error_code;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001401 } else {
1402 // Decoder does not implement error codes. Return generic error.
1403 return_value = kOtherDecoderError;
Henrik Lundind67a2192015-08-03 12:54:37 +02001404 LOG(LS_WARNING) << "Decoder error (no error code)";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001405 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001406 *operation = kExpand; // Do expansion to get data instead.
1407 }
1408 if (*speech_type != AudioDecoder::kComfortNoise) {
1409 // Don't increment timestamp if codec returned CNG speech type
1410 // since in this case, the we will increment the CNGplayedTS counter.
1411 // Increase with number of samples per channel.
1412 assert(*decoded_length == 0 ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001413 (decoder && decoder->Channels() == sync_buffer_->Channels()));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001414 sync_buffer_->IncreaseEndTimestamp(
1415 *decoded_length / static_cast<int>(sync_buffer_->Channels()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001416 }
1417 return return_value;
1418}
1419
minyuel6d92bf52015-09-23 15:20:39 +02001420int NetEqImpl::DecodeCng(AudioDecoder* decoder, int* decoded_length,
1421 AudioDecoder::SpeechType* speech_type) {
1422 if (!decoder) {
1423 // This happens when active decoder is not defined.
1424 *decoded_length = -1;
1425 return 0;
1426 }
1427
1428 while (*decoded_length < rtc::checked_cast<int>(output_size_samples_)) {
1429 const int length = decoder->Decode(
1430 nullptr, 0, fs_hz_,
1431 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1432 &decoded_buffer_[*decoded_length], speech_type);
1433 if (length > 0) {
1434 *decoded_length += length;
minyuel6d92bf52015-09-23 15:20:39 +02001435 } else {
1436 // Error.
1437 LOG(LS_WARNING) << "Failed to decode CNG";
1438 *decoded_length = -1;
1439 break;
1440 }
1441 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1442 // Guard against overflow.
1443 LOG(LS_WARNING) << "Decoded too much CNG.";
1444 return kDecodedTooMuch;
1445 }
1446 }
1447 return 0;
1448}
1449
1450int NetEqImpl::DecodeLoop(PacketList* packet_list, const Operations& operation,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001451 AudioDecoder* decoder, int* decoded_length,
1452 AudioDecoder::SpeechType* speech_type) {
1453 Packet* packet = NULL;
1454 if (!packet_list->empty()) {
1455 packet = packet_list->front();
1456 }
minyuel6d92bf52015-09-23 15:20:39 +02001457
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001458 // Do decoding.
1459 while (packet &&
1460 !decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1461 assert(decoder); // At this point, we must have a decoder object.
1462 // The number of channels in the |sync_buffer_| should be the same as the
1463 // number decoder channels.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001464 assert(sync_buffer_->Channels() == decoder->Channels());
1465 assert(decoded_buffer_length_ >= kMaxFrameSize * decoder->Channels());
minyuel6d92bf52015-09-23 15:20:39 +02001466 assert(operation == kNormal || operation == kAccelerate ||
1467 operation == kFastAccelerate || operation == kMerge ||
1468 operation == kPreemptiveExpand);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001469 packet_list->pop_front();
ossu61a208b2016-09-20 01:38:00 -07001470 auto opt_result = packet->frame->Decode(
1471 rtc::ArrayView<int16_t>(&decoded_buffer_[*decoded_length],
1472 decoded_buffer_length_ - *decoded_length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001473 delete packet;
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001474 packet = NULL;
ossu61a208b2016-09-20 01:38:00 -07001475 if (opt_result) {
1476 const auto& result = *opt_result;
1477 *speech_type = result.speech_type;
1478 if (result.num_decoded_samples > 0) {
1479 *decoded_length += rtc::checked_cast<int>(result.num_decoded_samples);
1480 // Update |decoder_frame_length_| with number of samples per channel.
1481 decoder_frame_length_ =
1482 result.num_decoded_samples / decoder->Channels();
1483 }
1484 } else {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001485 // Error.
ossu61a208b2016-09-20 01:38:00 -07001486 // TODO(ossu): What to put here?
1487 LOG(LS_WARNING) << "Decode error";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001488 *decoded_length = -1;
1489 PacketBuffer::DeleteAllPackets(packet_list);
1490 break;
1491 }
ossu61a208b2016-09-20 01:38:00 -07001492 if (*decoded_length > rtc::checked_cast<int>(decoded_buffer_length_)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001493 // Guard against overflow.
Henrik Lundind67a2192015-08-03 12:54:37 +02001494 LOG(LS_WARNING) << "Decoded too much.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001495 PacketBuffer::DeleteAllPackets(packet_list);
1496 return kDecodedTooMuch;
1497 }
1498 if (!packet_list->empty()) {
1499 packet = packet_list->front();
1500 } else {
1501 packet = NULL;
1502 }
1503 } // End of decode loop.
1504
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001505 // If the list is not empty at this point, either a decoding error terminated
1506 // the while-loop, or list must hold exactly one CNG packet.
1507 assert(packet_list->empty() || *decoded_length < 0 ||
1508 (packet_list->size() == 1 && packet &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001509 decoder_database_->IsComfortNoise(packet->header.payloadType)));
1510 return 0;
1511}
1512
1513void NetEqImpl::DoNormal(const int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001514 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001515 assert(normal_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001516 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001517 normal_->Process(decoded_buffer, decoded_length, last_mode_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001518 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001519 if (decoded_length != 0) {
1520 last_mode_ = kModeNormal;
1521 }
1522
1523 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1524 if ((speech_type == AudioDecoder::kComfortNoise)
1525 || ((last_mode_ == kModeCodecInternalCng)
1526 && (decoded_length == 0))) {
1527 // TODO(hlundin): Remove second part of || statement above.
1528 last_mode_ = kModeCodecInternalCng;
1529 }
1530
1531 if (!play_dtmf) {
1532 dtmf_tone_generator_->Reset();
1533 }
1534}
1535
1536void NetEqImpl::DoMerge(int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001537 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001538 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001539 assert(merge_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001540 size_t new_length = merge_->Process(decoded_buffer, decoded_length,
1541 mute_factor_array_.get(),
1542 algorithm_buffer_.get());
1543 size_t expand_length_correction = new_length -
1544 decoded_length / algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001545
1546 // Update in-call and post-call statistics.
1547 if (expand_->MuteFactor(0) == 0) {
1548 // Expand generates only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001549 stats_.ExpandedNoiseSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001550 } else {
1551 // Expansion generates more than only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001552 stats_.ExpandedVoiceSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001553 }
1554
1555 last_mode_ = kModeMerge;
1556 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1557 if (speech_type == AudioDecoder::kComfortNoise) {
1558 last_mode_ = kModeCodecInternalCng;
1559 }
1560 expand_->Reset();
1561 if (!play_dtmf) {
1562 dtmf_tone_generator_->Reset();
1563 }
1564}
1565
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001566int NetEqImpl::DoExpand(bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001567 while ((sync_buffer_->FutureLength() - expand_->overlap_length()) <
Peter Kastingdce40cf2015-08-24 14:52:23 -07001568 output_size_samples_) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001569 algorithm_buffer_->Clear();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001570 int return_value = expand_->Process(algorithm_buffer_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001571 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001572
1573 // Update in-call and post-call statistics.
1574 if (expand_->MuteFactor(0) == 0) {
1575 // Expand operation generates only noise.
1576 stats_.ExpandedNoiseSamples(length);
1577 } else {
1578 // Expand operation generates more than only noise.
1579 stats_.ExpandedVoiceSamples(length);
1580 }
1581
1582 last_mode_ = kModeExpand;
1583
1584 if (return_value < 0) {
1585 return return_value;
1586 }
1587
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001588 sync_buffer_->PushBack(*algorithm_buffer_);
1589 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001590 }
1591 if (!play_dtmf) {
1592 dtmf_tone_generator_->Reset();
1593 }
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001594
1595 if (!generated_noise_stopwatch_) {
1596 // Start a new stopwatch since we may be covering for a lost CNG packet.
1597 generated_noise_stopwatch_ = tick_timer_->GetNewStopwatch();
1598 }
1599
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001600 return 0;
1601}
1602
Henrik Lundincf808d22015-05-27 14:33:29 +02001603int NetEqImpl::DoAccelerate(int16_t* decoded_buffer,
1604 size_t decoded_length,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001605 AudioDecoder::SpeechType speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +02001606 bool play_dtmf,
1607 bool fast_accelerate) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001608 const size_t required_samples =
1609 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001610 size_t borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001611 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001612 size_t decoded_length_per_channel = decoded_length / num_channels;
1613 if (decoded_length_per_channel < required_samples) {
1614 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001615 borrowed_samples_per_channel = static_cast<int>(required_samples -
1616 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001617 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1618 decoded_buffer,
1619 sizeof(int16_t) * decoded_length);
1620 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1621 decoded_buffer);
1622 decoded_length = required_samples * num_channels;
1623 }
1624
Peter Kastingdce40cf2015-08-24 14:52:23 -07001625 size_t samples_removed;
Henrik Lundincf808d22015-05-27 14:33:29 +02001626 Accelerate::ReturnCodes return_code =
1627 accelerate_->Process(decoded_buffer, decoded_length, fast_accelerate,
1628 algorithm_buffer_.get(), &samples_removed);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001629 stats_.AcceleratedSamples(samples_removed);
1630 switch (return_code) {
1631 case Accelerate::kSuccess:
1632 last_mode_ = kModeAccelerateSuccess;
1633 break;
1634 case Accelerate::kSuccessLowEnergy:
1635 last_mode_ = kModeAccelerateLowEnergy;
1636 break;
1637 case Accelerate::kNoStretch:
1638 last_mode_ = kModeAccelerateFail;
1639 break;
1640 case Accelerate::kError:
1641 // TODO(hlundin): Map to kModeError instead?
1642 last_mode_ = kModeAccelerateFail;
1643 return kAccelerateError;
1644 }
1645
1646 if (borrowed_samples_per_channel > 0) {
1647 // Copy borrowed samples back to the |sync_buffer_|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001648 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001649 if (length < borrowed_samples_per_channel) {
1650 // This destroys the beginning of the buffer, but will not cause any
1651 // problems.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001652 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001653 sync_buffer_->Size() -
1654 borrowed_samples_per_channel);
1655 sync_buffer_->PushFrontZeros(borrowed_samples_per_channel - length);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001656 algorithm_buffer_->PopFront(length);
1657 assert(algorithm_buffer_->Empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001658 } else {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001659 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001660 borrowed_samples_per_channel,
1661 sync_buffer_->Size() -
1662 borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001663 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001664 }
1665 }
1666
1667 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1668 if (speech_type == AudioDecoder::kComfortNoise) {
1669 last_mode_ = kModeCodecInternalCng;
1670 }
1671 if (!play_dtmf) {
1672 dtmf_tone_generator_->Reset();
1673 }
1674 expand_->Reset();
1675 return 0;
1676}
1677
1678int NetEqImpl::DoPreemptiveExpand(int16_t* decoded_buffer,
1679 size_t decoded_length,
1680 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001681 bool play_dtmf) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001682 const size_t required_samples =
1683 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001684 size_t num_channels = algorithm_buffer_->Channels();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001685 size_t borrowed_samples_per_channel = 0;
1686 size_t old_borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001687 size_t decoded_length_per_channel = decoded_length / num_channels;
1688 if (decoded_length_per_channel < required_samples) {
1689 // Must move data from the |sync_buffer_| in order to get 30 ms.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001690 borrowed_samples_per_channel =
1691 required_samples - decoded_length_per_channel;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001692 // Calculate how many of these were already played out.
Peter Kastingf045e4d2015-06-10 21:15:38 -07001693 old_borrowed_samples_per_channel =
Peter Kastingdce40cf2015-08-24 14:52:23 -07001694 (borrowed_samples_per_channel > sync_buffer_->FutureLength()) ?
1695 (borrowed_samples_per_channel - sync_buffer_->FutureLength()) : 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001696 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1697 decoded_buffer,
1698 sizeof(int16_t) * decoded_length);
1699 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1700 decoded_buffer);
1701 decoded_length = required_samples * num_channels;
1702 }
1703
Peter Kastingdce40cf2015-08-24 14:52:23 -07001704 size_t samples_added;
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001705 PreemptiveExpand::ReturnCodes return_code = preemptive_expand_->Process(
Peter Kastingdce40cf2015-08-24 14:52:23 -07001706 decoded_buffer, decoded_length,
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001707 old_borrowed_samples_per_channel,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001708 algorithm_buffer_.get(), &samples_added);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001709 stats_.PreemptiveExpandedSamples(samples_added);
1710 switch (return_code) {
1711 case PreemptiveExpand::kSuccess:
1712 last_mode_ = kModePreemptiveExpandSuccess;
1713 break;
1714 case PreemptiveExpand::kSuccessLowEnergy:
1715 last_mode_ = kModePreemptiveExpandLowEnergy;
1716 break;
1717 case PreemptiveExpand::kNoStretch:
1718 last_mode_ = kModePreemptiveExpandFail;
1719 break;
1720 case PreemptiveExpand::kError:
1721 // TODO(hlundin): Map to kModeError instead?
1722 last_mode_ = kModePreemptiveExpandFail;
1723 return kPreemptiveExpandError;
1724 }
1725
1726 if (borrowed_samples_per_channel > 0) {
1727 // Copy borrowed samples back to the |sync_buffer_|.
1728 sync_buffer_->ReplaceAtIndex(
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001729 *algorithm_buffer_, borrowed_samples_per_channel,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001730 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001731 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001732 }
1733
1734 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1735 if (speech_type == AudioDecoder::kComfortNoise) {
1736 last_mode_ = kModeCodecInternalCng;
1737 }
1738 if (!play_dtmf) {
1739 dtmf_tone_generator_->Reset();
1740 }
1741 expand_->Reset();
1742 return 0;
1743}
1744
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001745int NetEqImpl::DoRfc3389Cng(PacketList* packet_list, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001746 if (!packet_list->empty()) {
1747 // Must have exactly one SID frame at this point.
1748 assert(packet_list->size() == 1);
1749 Packet* packet = packet_list->front();
1750 packet_list->pop_front();
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001751 if (!decoder_database_->IsComfortNoise(packet->header.payloadType)) {
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001752 LOG(LS_ERROR) << "Trying to decode non-CNG payload as CNG.";
1753 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001754 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001755 // UpdateParameters() deletes |packet|.
1756 if (comfort_noise_->UpdateParameters(packet) ==
1757 ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001758 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001759 return -comfort_noise_->internal_error_code();
1760 }
1761 }
1762 int cn_return = comfort_noise_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001763 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001764 expand_->Reset();
1765 last_mode_ = kModeRfc3389Cng;
1766 if (!play_dtmf) {
1767 dtmf_tone_generator_->Reset();
1768 }
1769 if (cn_return == ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001770 decoder_error_code_ = comfort_noise_->internal_error_code();
1771 return kComfortNoiseErrorCode;
1772 } else if (cn_return == ComfortNoise::kUnknownPayloadType) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001773 return kUnknownRtpPayloadType;
1774 }
1775 return 0;
1776}
1777
minyuel6d92bf52015-09-23 15:20:39 +02001778void NetEqImpl::DoCodecInternalCng(const int16_t* decoded_buffer,
1779 size_t decoded_length) {
1780 RTC_DCHECK(normal_.get());
1781 RTC_DCHECK(mute_factor_array_.get());
1782 normal_->Process(decoded_buffer, decoded_length, last_mode_,
1783 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001784 last_mode_ = kModeCodecInternalCng;
1785 expand_->Reset();
1786}
1787
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001788int NetEqImpl::DoDtmf(const DtmfEvent& dtmf_event, bool* play_dtmf) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001789 // This block of the code and the block further down, handling |dtmf_switch|
1790 // are commented out. Otherwise playing out-of-band DTMF would fail in VoE
1791 // test, DtmfTest.ManualSuccessfullySendsOutOfBandTelephoneEvents. This is
1792 // equivalent to |dtmf_switch| always be false.
1793 //
1794 // See http://webrtc-codereview.appspot.com/1195004/ for discussion
1795 // On this issue. This change might cause some glitches at the point of
1796 // switch from audio to DTMF. Issue 1545 is filed to track this.
1797 //
1798 // bool dtmf_switch = false;
1799 // if ((last_mode_ != kModeDtmf) && dtmf_tone_generator_->initialized()) {
1800 // // Special case; see below.
1801 // // We must catch this before calling Generate, since |initialized| is
1802 // // modified in that call.
1803 // dtmf_switch = true;
1804 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001805
1806 int dtmf_return_value = 0;
1807 if (!dtmf_tone_generator_->initialized()) {
1808 // Initialize if not already done.
1809 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1810 dtmf_event.volume);
1811 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001812
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001813 if (dtmf_return_value == 0) {
1814 // Generate DTMF signal.
1815 dtmf_return_value = dtmf_tone_generator_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001816 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001817 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001818
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001819 if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001820 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001821 return dtmf_return_value;
1822 }
1823
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001824 // if (dtmf_switch) {
1825 // // This is the special case where the previous operation was DTMF
1826 // // overdub, but the current instruction is "regular" DTMF. We must make
1827 // // sure that the DTMF does not have any discontinuities. The first DTMF
1828 // // sample that we generate now must be played out immediately, therefore
1829 // // it must be copied to the speech buffer.
1830 // // TODO(hlundin): This code seems incorrect. (Legacy.) Write test and
1831 // // verify correct operation.
1832 // assert(false);
1833 // // Must generate enough data to replace all of the |sync_buffer_|
1834 // // "future".
1835 // int required_length = sync_buffer_->FutureLength();
1836 // assert(dtmf_tone_generator_->initialized());
1837 // dtmf_return_value = dtmf_tone_generator_->Generate(required_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001838 // algorithm_buffer_);
1839 // assert((size_t) required_length == algorithm_buffer_->Size());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001840 // if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001841 // algorithm_buffer_->Zeros(output_size_samples_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001842 // return dtmf_return_value;
1843 // }
1844 //
1845 // // Overwrite the "future" part of the speech buffer with the new DTMF
1846 // // data.
1847 // // TODO(hlundin): It seems that this overwriting has gone lost.
1848 // // Not adapted for multi-channel yet.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001849 // assert(algorithm_buffer_->Channels() == 1);
1850 // if (algorithm_buffer_->Channels() != 1) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001851 // LOG(LS_WARNING) << "DTMF not supported for more than one channel";
1852 // return kStereoNotSupported;
1853 // }
1854 // // Shuffle the remaining data to the beginning of algorithm buffer.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001855 // algorithm_buffer_->PopFront(sync_buffer_->FutureLength());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001856 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001857
Peter Kastingb7e50542015-06-11 12:55:50 -07001858 sync_buffer_->IncreaseEndTimestamp(
1859 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001860 expand_->Reset();
1861 last_mode_ = kModeDtmf;
1862
1863 // Set to false because the DTMF is already in the algorithm buffer.
1864 *play_dtmf = false;
1865 return 0;
1866}
1867
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001868void NetEqImpl::DoAlternativePlc(bool increase_timestamp) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001869 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001870 size_t length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001871 if (decoder && decoder->HasDecodePlc()) {
1872 // Use the decoder's packet-loss concealment.
1873 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1874 int16_t decoded_buffer[kMaxFrameSize];
1875 length = decoder->DecodePlc(1, decoded_buffer);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001876 if (length > 0)
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001877 algorithm_buffer_->PushBackInterleaved(decoded_buffer, length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001878 } else {
1879 // Do simple zero-stuffing.
1880 length = output_size_samples_;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001881 algorithm_buffer_->Zeros(length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001882 // By not advancing the timestamp, NetEq inserts samples.
1883 stats_.AddZeros(length);
1884 }
1885 if (increase_timestamp) {
Peter Kastingb7e50542015-06-11 12:55:50 -07001886 sync_buffer_->IncreaseEndTimestamp(static_cast<uint32_t>(length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001887 }
1888 expand_->Reset();
1889}
1890
1891int NetEqImpl::DtmfOverdub(const DtmfEvent& dtmf_event, size_t num_channels,
1892 int16_t* output) const {
1893 size_t out_index = 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001894 size_t overdub_length = output_size_samples_; // Default value.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001895
1896 if (sync_buffer_->dtmf_index() > sync_buffer_->next_index()) {
1897 // Special operation for transition from "DTMF only" to "DTMF overdub".
1898 out_index = std::min(
1899 sync_buffer_->dtmf_index() - sync_buffer_->next_index(),
Peter Kastingdce40cf2015-08-24 14:52:23 -07001900 output_size_samples_);
1901 overdub_length = output_size_samples_ - out_index;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001902 }
1903
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001904 AudioMultiVector dtmf_output(num_channels);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001905 int dtmf_return_value = 0;
1906 if (!dtmf_tone_generator_->initialized()) {
1907 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1908 dtmf_event.volume);
1909 }
1910 if (dtmf_return_value == 0) {
1911 dtmf_return_value = dtmf_tone_generator_->Generate(overdub_length,
1912 &dtmf_output);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001913 assert(overdub_length == dtmf_output.Size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001914 }
1915 dtmf_output.ReadInterleaved(overdub_length, &output[out_index]);
1916 return dtmf_return_value < 0 ? dtmf_return_value : 0;
1917}
1918
Peter Kastingdce40cf2015-08-24 14:52:23 -07001919int NetEqImpl::ExtractPackets(size_t required_samples,
1920 PacketList* packet_list) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001921 bool first_packet = true;
1922 uint8_t prev_payload_type = 0;
1923 uint32_t prev_timestamp = 0;
1924 uint16_t prev_sequence_number = 0;
1925 bool next_packet_available = false;
1926
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001927 const RTPHeader* header = packet_buffer_->NextRtpHeader();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001928 assert(header);
1929 if (!header) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001930 LOG(LS_ERROR) << "Packet buffer unexpectedly empty.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001931 return -1;
1932 }
turaj@webrtc.org7df97062013-08-02 18:07:13 +00001933 uint32_t first_timestamp = header->timestamp;
ossu61a208b2016-09-20 01:38:00 -07001934 size_t extracted_samples = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001935
1936 // Packet extraction loop.
1937 do {
1938 timestamp_ = header->timestamp;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001939 size_t discard_count = 0;
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001940 Packet* packet = packet_buffer_->GetNextPacket(&discard_count);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001941 // |header| may be invalid after the |packet_buffer_| operation.
1942 header = NULL;
1943 if (!packet) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001944 LOG(LS_ERROR) << "Should always be able to extract a packet here";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001945 assert(false); // Should always be able to extract a packet here.
1946 return -1;
1947 }
1948 stats_.PacketsDiscarded(discard_count);
henrik.lundin84f8cd62016-04-26 07:45:16 -07001949 stats_.StoreWaitingTime(packet->waiting_time->ElapsedMs());
ossu61a208b2016-09-20 01:38:00 -07001950 RTC_DCHECK(!packet->empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001951 packet_list->push_back(packet); // Store packet in list.
1952
1953 if (first_packet) {
1954 first_packet = false;
henrik.lundin48ed9302015-10-29 05:36:24 -07001955 if (nack_enabled_) {
1956 RTC_DCHECK(nack_);
1957 // TODO(henrik.lundin): Should we update this for all decoded packets?
1958 nack_->UpdateLastDecodedPacket(packet->header.sequenceNumber,
1959 packet->header.timestamp);
1960 }
1961 prev_sequence_number = packet->header.sequenceNumber;
1962 prev_timestamp = packet->header.timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001963 prev_payload_type = packet->header.payloadType;
1964 }
1965
1966 // Store number of extracted samples.
ossu61a208b2016-09-20 01:38:00 -07001967 size_t packet_duration = 0;
1968 if (packet->frame) {
1969 packet_duration = packet->frame->Duration();
ossua70695a2016-09-22 02:06:28 -07001970 // TODO(ossu): Is this the correct way to track Opus FEC packets?
1971 if (packet->priority.codec_level > 0) {
ossu61a208b2016-09-20 01:38:00 -07001972 stats_.SecondaryDecodedSamples(rtc::checked_cast<int>(packet_duration));
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001973 }
ossu97ba30e2016-04-25 07:55:58 -07001974 } else if (!decoder_database_->IsComfortNoise(packet->header.payloadType)) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001975 LOG(LS_WARNING) << "Unknown payload type "
1976 << static_cast<int>(packet->header.payloadType);
ossu61a208b2016-09-20 01:38:00 -07001977 RTC_NOTREACHED();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001978 }
ossu61a208b2016-09-20 01:38:00 -07001979
1980 if (packet_duration == 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001981 // Decoder did not return a packet duration. Assume that the packet
1982 // contains the same number of samples as the previous one.
ossu61a208b2016-09-20 01:38:00 -07001983 packet_duration = decoder_frame_length_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001984 }
1985 extracted_samples = packet->header.timestamp - first_timestamp +
1986 packet_duration;
1987
1988 // Check what packet is available next.
1989 header = packet_buffer_->NextRtpHeader();
1990 next_packet_available = false;
1991 if (header && prev_payload_type == header->payloadType) {
1992 int16_t seq_no_diff = header->sequenceNumber - prev_sequence_number;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001993 size_t ts_diff = header->timestamp - prev_timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001994 if (seq_no_diff == 1 ||
1995 (seq_no_diff == 0 && ts_diff == decoder_frame_length_)) {
1996 // The next sequence number is available, or the next part of a packet
1997 // that was split into pieces upon insertion.
1998 next_packet_available = true;
1999 }
2000 prev_sequence_number = header->sequenceNumber;
2001 }
ossu61a208b2016-09-20 01:38:00 -07002002 } while (extracted_samples < required_samples && next_packet_available);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002003
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00002004 if (extracted_samples > 0) {
2005 // Delete old packets only when we are going to decode something. Otherwise,
2006 // we could end up in the situation where we never decode anything, since
2007 // all incoming packets are considered too old but the buffer will also
2008 // never be flooded and flushed.
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00002009 packet_buffer_->DiscardAllOldPackets(timestamp_);
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00002010 }
2011
ossu61a208b2016-09-20 01:38:00 -07002012 return rtc::checked_cast<int>(extracted_samples);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002013}
2014
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002015void NetEqImpl::UpdatePlcComponents(int fs_hz, size_t channels) {
2016 // Delete objects and create new ones.
2017 expand_.reset(expand_factory_->Create(background_noise_.get(),
2018 sync_buffer_.get(), &random_vector_,
Henrik Lundinbef77e22015-08-18 14:58:09 +02002019 &stats_, fs_hz, channels));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002020 merge_.reset(new Merge(fs_hz, channels, expand_.get(), sync_buffer_.get()));
2021}
2022
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002023void NetEqImpl::SetSampleRateAndChannels(int fs_hz, size_t channels) {
Henrik Lundind67a2192015-08-03 12:54:37 +02002024 LOG(LS_VERBOSE) << "SetSampleRateAndChannels " << fs_hz << " " << channels;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002025 // TODO(hlundin): Change to an enumerator and skip assert.
2026 assert(fs_hz == 8000 || fs_hz == 16000 || fs_hz == 32000 || fs_hz == 48000);
2027 assert(channels > 0);
2028
2029 fs_hz_ = fs_hz;
2030 fs_mult_ = fs_hz / 8000;
Peter Kastingdce40cf2015-08-24 14:52:23 -07002031 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002032 decoder_frame_length_ = 3 * output_size_samples_; // Initialize to 30ms.
2033
2034 last_mode_ = kModeNormal;
2035
2036 // Create a new array of mute factors and set all to 1.
2037 mute_factor_array_.reset(new int16_t[channels]);
2038 for (size_t i = 0; i < channels; ++i) {
2039 mute_factor_array_[i] = 16384; // 1.0 in Q14.
2040 }
2041
ossu97ba30e2016-04-25 07:55:58 -07002042 ComfortNoiseDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02002043 if (cng_decoder)
2044 cng_decoder->Reset();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002045
2046 // Reinit post-decode VAD with new sample rate.
2047 assert(vad_.get()); // Cannot be NULL here.
2048 vad_->Init();
2049
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002050 // Delete algorithm buffer and create a new one.
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00002051 algorithm_buffer_.reset(new AudioMultiVector(channels));
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002052
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002053 // Delete sync buffer and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002054 sync_buffer_.reset(new SyncBuffer(channels, kSyncBufferSize * fs_mult_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002055
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00002056 // Delete BackgroundNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002057 background_noise_.reset(new BackgroundNoise(channels));
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00002058 background_noise_->set_mode(background_noise_mode_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002059
2060 // Reset random vector.
2061 random_vector_.Reset();
2062
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002063 UpdatePlcComponents(fs_hz, channels);
2064
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002065 // Move index so that we create a small set of future samples (all 0).
2066 sync_buffer_->set_next_index(sync_buffer_->next_index() -
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002067 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002068
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002069 normal_.reset(new Normal(fs_hz, decoder_database_.get(), *background_noise_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002070 expand_.get()));
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +00002071 accelerate_.reset(
2072 accelerate_factory_->Create(fs_hz, channels, *background_noise_));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002073 preemptive_expand_.reset(preemptive_expand_factory_->Create(
Peter Kastingdce40cf2015-08-24 14:52:23 -07002074 fs_hz, channels, *background_noise_, expand_->overlap_length()));
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002075
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002076 // Delete ComfortNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002077 comfort_noise_.reset(new ComfortNoise(fs_hz, decoder_database_.get(),
2078 sync_buffer_.get()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002079
2080 // Verify that |decoded_buffer_| is long enough.
2081 if (decoded_buffer_length_ < kMaxFrameSize * channels) {
2082 // Reallocate to larger size.
2083 decoded_buffer_length_ = kMaxFrameSize * channels;
2084 decoded_buffer_.reset(new int16_t[decoded_buffer_length_]);
2085 }
2086
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002087 // Create DecisionLogic if it is not created yet, then communicate new sample
2088 // rate and output size to DecisionLogic object.
2089 if (!decision_logic_.get()) {
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002090 CreateDecisionLogic();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002091 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002092 decision_logic_->SetSampleRate(fs_hz_, output_size_samples_);
2093}
2094
henrik.lundin55480f52016-03-08 02:37:57 -08002095NetEqImpl::OutputType NetEqImpl::LastOutputType() {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002096 assert(vad_.get());
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002097 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002098 if (last_mode_ == kModeCodecInternalCng || last_mode_ == kModeRfc3389Cng) {
henrik.lundin55480f52016-03-08 02:37:57 -08002099 return OutputType::kCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002100 } else if (last_mode_ == kModeExpand && expand_->MuteFactor(0) == 0) {
2101 // Expand mode has faded down to background noise only (very long expand).
henrik.lundin55480f52016-03-08 02:37:57 -08002102 return OutputType::kPLCCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002103 } else if (last_mode_ == kModeExpand) {
henrik.lundin55480f52016-03-08 02:37:57 -08002104 return OutputType::kPLC;
wu@webrtc.org24301a62013-12-13 19:17:43 +00002105 } else if (vad_->running() && !vad_->active_speech()) {
henrik.lundin55480f52016-03-08 02:37:57 -08002106 return OutputType::kVadPassive;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002107 } else {
henrik.lundin55480f52016-03-08 02:37:57 -08002108 return OutputType::kNormalSpeech;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002109 }
2110}
2111
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002112void NetEqImpl::CreateDecisionLogic() {
Henrik Lundin47b17dc2016-05-10 10:20:59 +02002113 decision_logic_.reset(DecisionLogic::Create(
2114 fs_hz_, output_size_samples_, playout_mode_, decoder_database_.get(),
2115 *packet_buffer_.get(), delay_manager_.get(), buffer_level_filter_.get(),
2116 tick_timer_.get()));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002117}
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002118} // namespace webrtc