blob: 78015d95be159b6dc01c44dbedb2ba429c94e40b [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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "modules/audio_coding/neteq/neteq_impl.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000012
13#include <assert.h>
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000014
15#include <algorithm>
ossu61a208b2016-09-20 01:38:00 -070016#include <utility>
ossu97ba30e2016-04-25 07:55:58 -070017#include <vector>
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000018
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020019#include "api/audio_codecs/audio_decoder.h"
20#include "common_audio/signal_processing/include/signal_processing_library.h"
21#include "modules/audio_coding/neteq/accelerate.h"
22#include "modules/audio_coding/neteq/background_noise.h"
23#include "modules/audio_coding/neteq/buffer_level_filter.h"
24#include "modules/audio_coding/neteq/comfort_noise.h"
25#include "modules/audio_coding/neteq/decision_logic.h"
26#include "modules/audio_coding/neteq/decoder_database.h"
27#include "modules/audio_coding/neteq/defines.h"
28#include "modules/audio_coding/neteq/delay_manager.h"
29#include "modules/audio_coding/neteq/delay_peak_detector.h"
30#include "modules/audio_coding/neteq/dtmf_buffer.h"
31#include "modules/audio_coding/neteq/dtmf_tone_generator.h"
32#include "modules/audio_coding/neteq/expand.h"
33#include "modules/audio_coding/neteq/merge.h"
34#include "modules/audio_coding/neteq/nack_tracker.h"
35#include "modules/audio_coding/neteq/normal.h"
36#include "modules/audio_coding/neteq/packet.h"
37#include "modules/audio_coding/neteq/packet_buffer.h"
38#include "modules/audio_coding/neteq/post_decode_vad.h"
39#include "modules/audio_coding/neteq/preemptive_expand.h"
40#include "modules/audio_coding/neteq/red_payload_splitter.h"
41#include "modules/audio_coding/neteq/sync_buffer.h"
42#include "modules/audio_coding/neteq/tick_timer.h"
43#include "modules/audio_coding/neteq/timestamp_scaler.h"
44#include "modules/include/module_common_types.h"
45#include "rtc_base/checks.h"
46#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010047#include "rtc_base/numerics/safe_conversions.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020048#include "rtc_base/sanitizer.h"
Karl Wiberg80ba3332018-02-05 10:33:35 +010049#include "rtc_base/system/fallthrough.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020050#include "rtc_base/trace_event.h"
Henrik Lundin18036282017-11-02 12:09:06 +010051#include "system_wrappers/include/field_trial.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000052
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000053namespace webrtc {
54
ossue3525782016-05-25 07:37:43 -070055NetEqImpl::Dependencies::Dependencies(
56 const NetEq::Config& config,
57 const rtc::scoped_refptr<AudioDecoderFactory>& decoder_factory)
henrik.lundin1d9061e2016-04-26 12:19:34 -070058 : tick_timer(new TickTimer),
59 buffer_level_filter(new BufferLevelFilter),
Karl Wiberg08126342018-03-20 19:18:55 +010060 decoder_database(
61 new DecoderDatabase(decoder_factory, config.codec_pair_id)),
henrik.lundinf3933702016-04-28 01:53:52 -070062 delay_peak_detector(new DelayPeakDetector(tick_timer.get())),
henrik.lundin1d9061e2016-04-26 12:19:34 -070063 delay_manager(new DelayManager(config.max_packets_in_buffer,
henrik.lundin8f8c96d2016-04-28 23:19:20 -070064 delay_peak_detector.get(),
65 tick_timer.get())),
henrik.lundin1d9061e2016-04-26 12:19:34 -070066 dtmf_buffer(new DtmfBuffer(config.sample_rate_hz)),
67 dtmf_tone_generator(new DtmfToneGenerator),
68 packet_buffer(
69 new PacketBuffer(config.max_packets_in_buffer, tick_timer.get())),
ossua70695a2016-09-22 02:06:28 -070070 red_payload_splitter(new RedPayloadSplitter),
henrik.lundin1d9061e2016-04-26 12:19:34 -070071 timestamp_scaler(new TimestampScaler(*decoder_database)),
72 accelerate_factory(new AccelerateFactory),
73 expand_factory(new ExpandFactory),
74 preemptive_expand_factory(new PreemptiveExpandFactory) {}
75
76NetEqImpl::Dependencies::~Dependencies() = default;
77
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +000078NetEqImpl::NetEqImpl(const NetEq::Config& config,
henrik.lundin1d9061e2016-04-26 12:19:34 -070079 Dependencies&& deps,
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +000080 bool create_components)
henrik.lundin1d9061e2016-04-26 12:19:34 -070081 : tick_timer_(std::move(deps.tick_timer)),
82 buffer_level_filter_(std::move(deps.buffer_level_filter)),
83 decoder_database_(std::move(deps.decoder_database)),
84 delay_manager_(std::move(deps.delay_manager)),
85 delay_peak_detector_(std::move(deps.delay_peak_detector)),
86 dtmf_buffer_(std::move(deps.dtmf_buffer)),
87 dtmf_tone_generator_(std::move(deps.dtmf_tone_generator)),
88 packet_buffer_(std::move(deps.packet_buffer)),
ossua70695a2016-09-22 02:06:28 -070089 red_payload_splitter_(std::move(deps.red_payload_splitter)),
henrik.lundin1d9061e2016-04-26 12:19:34 -070090 timestamp_scaler_(std::move(deps.timestamp_scaler)),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000091 vad_(new PostDecodeVad()),
henrik.lundin1d9061e2016-04-26 12:19:34 -070092 expand_factory_(std::move(deps.expand_factory)),
93 accelerate_factory_(std::move(deps.accelerate_factory)),
94 preemptive_expand_factory_(std::move(deps.preemptive_expand_factory)),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000095 last_mode_(kModeNormal),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000096 decoded_buffer_length_(kMaxFrameSize),
97 decoded_buffer_(new int16_t[decoded_buffer_length_]),
98 playout_timestamp_(0),
99 new_codec_(false),
100 timestamp_(0),
101 reset_decoder_(false),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000102 ssrc_(0),
103 first_packet_(true),
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),
Henrik Lundin4f2a4a12018-01-26 17:32:56 +0100108 enable_muted_state_(config.enable_muted_state) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100109 RTC_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) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100112 RTC_LOG(LS_ERROR) << "Sample rate " << fs << " Hz not supported. "
113 << "Changing to 8000 Hz.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000114 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
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200134int NetEqImpl::InsertPacket(const RTPHeader& 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_);
Henrik Lundinc417d9e2017-06-14 12:29:03 +0200140 if (InsertPacketInternal(rtp_header, payload, receive_timestamp) != 0) {
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000141 return kFail;
142 }
143 return kOK;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000144}
145
henrik.lundinb8c55b12017-05-10 07:38:01 -0700146void NetEqImpl::InsertEmptyPacket(const RTPHeader& /*rtp_header*/) {
147 // TODO(henrik.lundin) Handle NACK as well. This will make use of the
148 // rtp_header parameter.
149 // https://bugs.chromium.org/p/webrtc/issues/detail?id=7611
150 rtc::CritScope lock(&crit_sect_);
151 delay_manager_->RegisterEmptyPacket();
152}
153
henrik.lundin500c04b2016-03-08 02:36:04 -0800154namespace {
155void SetAudioFrameActivityAndType(bool vad_enabled,
henrik.lundin55480f52016-03-08 02:37:57 -0800156 NetEqImpl::OutputType type,
henrik.lundin500c04b2016-03-08 02:36:04 -0800157 AudioFrame::VADActivity last_vad_activity,
158 AudioFrame* audio_frame) {
159 switch (type) {
henrik.lundin55480f52016-03-08 02:37:57 -0800160 case NetEqImpl::OutputType::kNormalSpeech: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800161 audio_frame->speech_type_ = AudioFrame::kNormalSpeech;
162 audio_frame->vad_activity_ = AudioFrame::kVadActive;
163 break;
164 }
henrik.lundin55480f52016-03-08 02:37:57 -0800165 case NetEqImpl::OutputType::kVadPassive: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800166 // This should only be reached if the VAD is enabled.
167 RTC_DCHECK(vad_enabled);
168 audio_frame->speech_type_ = AudioFrame::kNormalSpeech;
169 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
170 break;
171 }
henrik.lundin55480f52016-03-08 02:37:57 -0800172 case NetEqImpl::OutputType::kCNG: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800173 audio_frame->speech_type_ = AudioFrame::kCNG;
174 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
175 break;
176 }
henrik.lundin55480f52016-03-08 02:37:57 -0800177 case NetEqImpl::OutputType::kPLC: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800178 audio_frame->speech_type_ = AudioFrame::kPLC;
179 audio_frame->vad_activity_ = last_vad_activity;
180 break;
181 }
henrik.lundin55480f52016-03-08 02:37:57 -0800182 case NetEqImpl::OutputType::kPLCCNG: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800183 audio_frame->speech_type_ = AudioFrame::kPLCCNG;
184 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
185 break;
186 }
187 default:
188 RTC_NOTREACHED();
189 }
190 if (!vad_enabled) {
191 // Always set kVadUnknown when receive VAD is inactive.
192 audio_frame->vad_activity_ = AudioFrame::kVadUnknown;
193 }
194}
henrik.lundinbc89de32016-03-08 05:20:14 -0800195} // namespace
henrik.lundin500c04b2016-03-08 02:36:04 -0800196
henrik.lundin7a926812016-05-12 13:51:28 -0700197int NetEqImpl::GetAudio(AudioFrame* audio_frame, bool* muted) {
henrik.lundine1ca1672016-01-08 03:50:08 -0800198 TRACE_EVENT0("webrtc", "NetEqImpl::GetAudio");
Tommi9090e0b2016-01-20 13:39:36 +0100199 rtc::CritScope lock(&crit_sect_);
Henrik Lundinc417d9e2017-06-14 12:29:03 +0200200 if (GetAudioInternal(audio_frame, muted) != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000201 return kFail;
202 }
henrik.lundin5fac3f02016-08-24 11:18:49 -0700203 RTC_DCHECK_EQ(
204 audio_frame->sample_rate_hz_,
kwibergd3edd772017-03-01 18:52:48 -0800205 rtc::dchecked_cast<int>(audio_frame->samples_per_channel_ * 100));
henrik.lundina4491072017-07-06 05:23:53 -0700206 RTC_DCHECK_EQ(*muted, audio_frame->muted());
henrik.lundin500c04b2016-03-08 02:36:04 -0800207 SetAudioFrameActivityAndType(vad_->enabled(), LastOutputType(),
208 last_vad_activity_, audio_frame);
209 last_vad_activity_ = audio_frame->vad_activity_;
henrik.lundin6d8e0112016-03-04 10:34:21 -0800210 last_output_sample_rate_hz_ = audio_frame->sample_rate_hz_;
henrik.lundind89814b2015-11-23 06:49:25 -0800211 RTC_DCHECK(last_output_sample_rate_hz_ == 8000 ||
212 last_output_sample_rate_hz_ == 16000 ||
213 last_output_sample_rate_hz_ == 32000 ||
214 last_output_sample_rate_hz_ == 48000)
215 << "Unexpected sample rate " << last_output_sample_rate_hz_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000216 return kOK;
217}
218
kwiberg1c07c702017-03-27 07:15:49 -0700219void NetEqImpl::SetCodecs(const std::map<int, SdpAudioFormat>& codecs) {
220 rtc::CritScope lock(&crit_sect_);
221 const std::vector<int> changed_payload_types =
222 decoder_database_->SetCodecs(codecs);
223 for (const int pt : changed_payload_types) {
minyue-webrtcfae474c2017-07-05 11:17:40 +0200224 packet_buffer_->DiscardPacketsWithPayloadType(pt, &stats_);
kwiberg1c07c702017-03-27 07:15:49 -0700225 }
226}
227
kwibergee1879c2015-10-29 06:20:28 -0700228int NetEqImpl::RegisterPayloadType(NetEqDecoder codec,
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800229 const std::string& name,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000230 uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100231 rtc::CritScope lock(&crit_sect_);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100232 RTC_LOG(LS_VERBOSE) << "RegisterPayloadType "
233 << static_cast<int>(rtp_payload_type) << " "
234 << static_cast<int>(codec);
Henrik Lundinc417d9e2017-06-14 12:29:03 +0200235 if (decoder_database_->RegisterPayload(rtp_payload_type, codec, name) !=
236 DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000237 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_);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100247 RTC_LOG(LS_VERBOSE) << "RegisterExternalDecoder "
248 << static_cast<int>(rtp_payload_type) << " "
249 << static_cast<int>(codec);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000250 if (!decoder) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100251 RTC_LOG(LS_ERROR) << "Cannot register external decoder with NULL pointer";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000252 assert(false);
253 return kFail;
254 }
Henrik Lundinc417d9e2017-06-14 12:29:03 +0200255 if (decoder_database_->InsertExternal(rtp_payload_type, codec, codec_name,
256 decoder) != DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000257 return kFail;
258 }
259 return kOK;
260}
261
kwiberg5adaf732016-10-04 09:33:27 -0700262bool NetEqImpl::RegisterPayloadType(int rtp_payload_type,
263 const SdpAudioFormat& audio_format) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100264 RTC_LOG(LS_VERBOSE) << "NetEqImpl::RegisterPayloadType: payload type "
265 << rtp_payload_type << ", codec " << audio_format;
kwiberg5adaf732016-10-04 09:33:27 -0700266 rtc::CritScope lock(&crit_sect_);
Henrik Lundinc417d9e2017-06-14 12:29:03 +0200267 return decoder_database_->RegisterPayload(rtp_payload_type, audio_format) ==
268 DecoderDatabase::kOK;
kwiberg5adaf732016-10-04 09:33:27 -0700269}
270
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000271int NetEqImpl::RemovePayloadType(uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100272 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000273 int ret = decoder_database_->Remove(rtp_payload_type);
Henrik Lundinc417d9e2017-06-14 12:29:03 +0200274 if (ret == DecoderDatabase::kOK || ret == DecoderDatabase::kDecoderNotFound) {
minyue-webrtcfae474c2017-07-05 11:17:40 +0200275 packet_buffer_->DiscardPacketsWithPayloadType(rtp_payload_type, &stats_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000276 return kOK;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000277 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000278 return kFail;
279}
280
kwiberg6b19b562016-09-20 04:02:25 -0700281void NetEqImpl::RemoveAllPayloadTypes() {
282 rtc::CritScope lock(&crit_sect_);
283 decoder_database_->RemoveAll();
284}
285
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000286bool NetEqImpl::SetMinimumDelay(int delay_ms) {
Tommi9090e0b2016-01-20 13:39:36 +0100287 rtc::CritScope lock(&crit_sect_);
Gustaf Ullberg48d96c02017-09-15 13:59:52 +0200288 if (delay_ms >= 0 && delay_ms <= 10000) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000289 assert(delay_manager_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000290 return delay_manager_->SetMinimumDelay(delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000291 }
292 return false;
293}
294
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000295bool NetEqImpl::SetMaximumDelay(int delay_ms) {
Tommi9090e0b2016-01-20 13:39:36 +0100296 rtc::CritScope lock(&crit_sect_);
Gustaf Ullberg48d96c02017-09-15 13:59:52 +0200297 if (delay_ms >= 0 && delay_ms <= 10000) {
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000298 assert(delay_manager_.get());
299 return delay_manager_->SetMaximumDelay(delay_ms);
300 }
301 return false;
302}
303
304int NetEqImpl::LeastRequiredDelayMs() const {
Tommi9090e0b2016-01-20 13:39:36 +0100305 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000306 assert(delay_manager_.get());
307 return delay_manager_->least_required_delay_ms();
308}
309
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200310int NetEqImpl::SetTargetDelay() {
311 return kNotImplemented;
312}
313
Henrik Lundinabbff892017-11-29 09:14:04 +0100314int NetEqImpl::TargetDelayMs() const {
henrik.lundin114c1b32017-04-26 07:47:32 -0700315 rtc::CritScope lock(&crit_sect_);
316 RTC_DCHECK(delay_manager_.get());
317 // The value from TargetLevel() is in number of packets, represented in Q8.
318 const size_t target_delay_samples =
319 (delay_manager_->TargetLevel() * decoder_frame_length_) >> 8;
320 return static_cast<int>(target_delay_samples) /
321 rtc::CheckedDivExact(fs_hz_, 1000);
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200322}
323
henrik.lundin9c3efd02015-08-27 13:12:22 -0700324int NetEqImpl::CurrentDelayMs() const {
Tommi9090e0b2016-01-20 13:39:36 +0100325 rtc::CritScope lock(&crit_sect_);
henrik.lundin9c3efd02015-08-27 13:12:22 -0700326 if (fs_hz_ == 0)
327 return 0;
328 // Sum up the samples in the packet buffer with the future length of the sync
329 // buffer, and divide the sum by the sample rate.
330 const size_t delay_samples =
ossu61a208b2016-09-20 01:38:00 -0700331 packet_buffer_->NumSamplesInBuffer(decoder_frame_length_) +
henrik.lundin9c3efd02015-08-27 13:12:22 -0700332 sync_buffer_->FutureLength();
333 // The division below will truncate.
334 const int delay_ms =
335 static_cast<int>(delay_samples) / rtc::CheckedDivExact(fs_hz_, 1000);
336 return delay_ms;
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200337}
338
henrik.lundinb3f1c5d2016-08-22 15:39:53 -0700339int NetEqImpl::FilteredCurrentDelayMs() const {
340 rtc::CritScope lock(&crit_sect_);
341 // Calculate the filtered packet buffer level in samples. The value from
342 // |buffer_level_filter_| is in number of packets, represented in Q8.
343 const size_t packet_buffer_samples =
344 (buffer_level_filter_->filtered_current_level() *
345 decoder_frame_length_) >>
346 8;
347 // Sum up the filtered packet buffer level with the future length of the sync
348 // buffer, and divide the sum by the sample rate.
349 const size_t delay_samples =
350 packet_buffer_samples + sync_buffer_->FutureLength();
351 // The division below will truncate. The return value is in ms.
352 return static_cast<int>(delay_samples) / rtc::CheckedDivExact(fs_hz_, 1000);
353}
354
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000355// Deprecated.
356// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000357void NetEqImpl::SetPlayoutMode(NetEqPlayoutMode mode) {
Tommi9090e0b2016-01-20 13:39:36 +0100358 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000359 if (mode != playout_mode_) {
360 playout_mode_ = mode;
361 CreateDecisionLogic();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000362 }
363}
364
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000365// Deprecated.
366// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000367NetEqPlayoutMode NetEqImpl::PlayoutMode() const {
Tommi9090e0b2016-01-20 13:39:36 +0100368 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000369 return playout_mode_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000370}
371
372int NetEqImpl::NetworkStatistics(NetEqNetworkStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100373 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000374 assert(decoder_database_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700375 const size_t total_samples_in_buffers =
ossu61a208b2016-09-20 01:38:00 -0700376 packet_buffer_->NumSamplesInBuffer(decoder_frame_length_) +
Peter Kastingdce40cf2015-08-24 14:52:23 -0700377 sync_buffer_->FutureLength();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000378 assert(delay_manager_.get());
379 assert(decision_logic_.get());
Henrik Lundindccfc402017-09-25 12:30:58 +0200380 const int ms_per_packet = rtc::dchecked_cast<int>(
381 decision_logic_->packet_length_samples() / (fs_hz_ / 1000));
382 stats_.PopulateDelayManagerStats(ms_per_packet, *delay_manager_.get(), stats);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000383 stats_.GetNetworkStatistics(fs_hz_, total_samples_in_buffers,
Henrik Lundindccfc402017-09-25 12:30:58 +0200384 decoder_frame_length_, stats);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000385 return 0;
386}
387
Steve Anton2dbc69f2017-08-24 17:15:13 -0700388NetEqLifetimeStatistics NetEqImpl::GetLifetimeStatistics() const {
389 rtc::CritScope lock(&crit_sect_);
390 return stats_.GetLifetimeStatistics();
391}
392
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000393void NetEqImpl::GetRtcpStatistics(RtcpStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100394 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000395 if (stats) {
396 rtcp_.GetStatistics(false, stats);
397 }
398}
399
400void NetEqImpl::GetRtcpStatisticsNoReset(RtcpStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100401 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000402 if (stats) {
403 rtcp_.GetStatistics(true, stats);
404 }
405}
406
407void NetEqImpl::EnableVad() {
Tommi9090e0b2016-01-20 13:39:36 +0100408 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000409 assert(vad_.get());
410 vad_->Enable();
411}
412
413void NetEqImpl::DisableVad() {
Tommi9090e0b2016-01-20 13:39:36 +0100414 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000415 assert(vad_.get());
416 vad_->Disable();
417}
418
henrik.lundin15c51e32016-04-06 08:38:56 -0700419rtc::Optional<uint32_t> NetEqImpl::GetPlayoutTimestamp() const {
Tommi9090e0b2016-01-20 13:39:36 +0100420 rtc::CritScope lock(&crit_sect_);
henrik.lundin0d96ab72016-04-06 12:28:26 -0700421 if (first_packet_ || last_mode_ == kModeRfc3389Cng ||
422 last_mode_ == kModeCodecInternalCng) {
wu@webrtc.org94454b72014-06-05 20:34:08 +0000423 // We don't have a valid RTP timestamp until we have decoded our first
henrik.lundin0d96ab72016-04-06 12:28:26 -0700424 // RTP packet. Also, the RTP timestamp is not accurate while playing CNG,
425 // which is indicated by returning an empty value.
Oskar Sundbom12ab00b2017-11-16 15:31:38 +0100426 return rtc::nullopt;
wu@webrtc.org94454b72014-06-05 20:34:08 +0000427 }
Oskar Sundbom12ab00b2017-11-16 15:31:38 +0100428 return timestamp_scaler_->ToExternal(playout_timestamp_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000429}
430
henrik.lundind89814b2015-11-23 06:49:25 -0800431int NetEqImpl::last_output_sample_rate_hz() const {
Tommi9090e0b2016-01-20 13:39:36 +0100432 rtc::CritScope lock(&crit_sect_);
henrik.lundind89814b2015-11-23 06:49:25 -0800433 return last_output_sample_rate_hz_;
434}
435
kwiberg6f0f6162016-09-20 03:07:46 -0700436rtc::Optional<CodecInst> NetEqImpl::GetDecoder(int payload_type) const {
437 rtc::CritScope lock(&crit_sect_);
438 const DecoderDatabase::DecoderInfo* di =
439 decoder_database_->GetDecoderInfo(payload_type);
440 if (!di) {
Oskar Sundbom12ab00b2017-11-16 15:31:38 +0100441 return rtc::nullopt;
kwiberg6f0f6162016-09-20 03:07:46 -0700442 }
443
444 // Create a CodecInst with some fields set. The remaining fields are zeroed,
445 // but we tell MSan to consider them uninitialized.
446 CodecInst ci = {0};
447 rtc::MsanMarkUninitialized(rtc::MakeArrayView(&ci, 1));
448 ci.pltype = payload_type;
kwiberge9413062016-11-03 05:29:05 -0700449 std::strncpy(ci.plname, di->get_name().c_str(), sizeof(ci.plname));
kwiberg6f0f6162016-09-20 03:07:46 -0700450 ci.plname[sizeof(ci.plname) - 1] = '\0';
solenberg2779bab2016-11-17 04:45:19 -0800451 ci.plfreq = di->IsRed() ? 8000 : di->SampleRateHz();
kwiberg6f0f6162016-09-20 03:07:46 -0700452 AudioDecoder* const decoder = di->GetDecoder();
453 ci.channels = decoder ? decoder->Channels() : 1;
Oskar Sundbom12ab00b2017-11-16 15:31:38 +0100454 return ci;
kwiberg6f0f6162016-09-20 03:07:46 -0700455}
456
ossuf1b08da2016-09-23 02:19:43 -0700457rtc::Optional<SdpAudioFormat> NetEqImpl::GetDecoderFormat(
458 int payload_type) const {
kwibergc4ccd4d2016-09-21 10:55:15 -0700459 rtc::CritScope lock(&crit_sect_);
460 const DecoderDatabase::DecoderInfo* const di =
461 decoder_database_->GetDecoderInfo(payload_type);
462 if (!di) {
Oskar Sundbom12ab00b2017-11-16 15:31:38 +0100463 return rtc::nullopt; // Payload type not registered.
kwibergc4ccd4d2016-09-21 10:55:15 -0700464 }
Oskar Sundbom12ab00b2017-11-16 15:31:38 +0100465 return di->GetFormat();
kwibergc4ccd4d2016-09-21 10:55:15 -0700466}
467
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200468int NetEqImpl::SetTargetNumberOfChannels() {
469 return kNotImplemented;
470}
471
472int NetEqImpl::SetTargetSampleRate() {
473 return kNotImplemented;
474}
475
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000476void NetEqImpl::FlushBuffers() {
Tommi9090e0b2016-01-20 13:39:36 +0100477 rtc::CritScope lock(&crit_sect_);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100478 RTC_LOG(LS_VERBOSE) << "FlushBuffers";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000479 packet_buffer_->Flush();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000480 assert(sync_buffer_.get());
481 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000482 sync_buffer_->Flush();
483 sync_buffer_->set_next_index(sync_buffer_->next_index() -
484 expand_->overlap_length());
485 // Set to wait for new codec.
486 first_packet_ = true;
487}
488
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000489void NetEqImpl::PacketBufferStatistics(int* current_num_packets,
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000490 int* max_num_packets) const {
Tommi9090e0b2016-01-20 13:39:36 +0100491 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000492 packet_buffer_->BufferStat(current_num_packets, max_num_packets);
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000493}
494
henrik.lundin48ed9302015-10-29 05:36:24 -0700495void NetEqImpl::EnableNack(size_t max_nack_list_size) {
Tommi9090e0b2016-01-20 13:39:36 +0100496 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700497 if (!nack_enabled_) {
498 const int kNackThresholdPackets = 2;
henrik.lundin91951862016-06-08 06:43:41 -0700499 nack_.reset(NackTracker::Create(kNackThresholdPackets));
henrik.lundin48ed9302015-10-29 05:36:24 -0700500 nack_enabled_ = true;
501 nack_->UpdateSampleRate(fs_hz_);
502 }
503 nack_->SetMaxNackListSize(max_nack_list_size);
504}
505
506void NetEqImpl::DisableNack() {
Tommi9090e0b2016-01-20 13:39:36 +0100507 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700508 nack_.reset();
509 nack_enabled_ = false;
510}
511
512std::vector<uint16_t> NetEqImpl::GetNackList(int64_t round_trip_time_ms) const {
Tommi9090e0b2016-01-20 13:39:36 +0100513 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700514 if (!nack_enabled_) {
515 return std::vector<uint16_t>();
516 }
517 RTC_DCHECK(nack_.get());
518 return nack_->GetNackList(round_trip_time_ms);
minyue@webrtc.orgd7301772013-08-29 00:58:14 +0000519}
520
henrik.lundin114c1b32017-04-26 07:47:32 -0700521std::vector<uint32_t> NetEqImpl::LastDecodedTimestamps() const {
522 rtc::CritScope lock(&crit_sect_);
523 return last_decoded_timestamps_;
524}
525
526int NetEqImpl::SyncBufferSizeMs() const {
527 rtc::CritScope lock(&crit_sect_);
528 return rtc::dchecked_cast<int>(sync_buffer_->FutureLength() /
529 rtc::CheckedDivExact(fs_hz_, 1000));
530}
531
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000532const SyncBuffer* NetEqImpl::sync_buffer_for_test() const {
Tommi9090e0b2016-01-20 13:39:36 +0100533 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000534 return sync_buffer_.get();
535}
536
minyue5bd33972016-05-02 04:46:11 -0700537Operations NetEqImpl::last_operation_for_test() const {
538 rtc::CritScope lock(&crit_sect_);
539 return last_operation_;
540}
541
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000542// Methods below this line are private.
543
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200544int NetEqImpl::InsertPacketInternal(const RTPHeader& rtp_header,
kwibergee2bac22015-11-11 10:34:00 -0800545 rtc::ArrayView<const uint8_t> payload,
ossu17e3fa12016-09-08 04:52:55 -0700546 uint32_t receive_timestamp) {
kwibergee2bac22015-11-11 10:34:00 -0800547 if (payload.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100548 RTC_LOG_F(LS_ERROR) << "payload is empty";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000549 return kInvalidPointer;
550 }
ossu17e3fa12016-09-08 04:52:55 -0700551
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000552 PacketList packet_list;
ossua73f6c92016-10-24 08:25:28 -0700553 // Insert packet in a packet list.
554 packet_list.push_back([&rtp_header, &payload] {
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000555 // Convert to Packet.
ossua73f6c92016-10-24 08:25:28 -0700556 Packet packet;
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200557 packet.payload_type = rtp_header.payloadType;
558 packet.sequence_number = rtp_header.sequenceNumber;
559 packet.timestamp = rtp_header.timestamp;
ossua73f6c92016-10-24 08:25:28 -0700560 packet.payload.SetData(payload.data(), payload.size());
henrik.lundin84f8cd62016-04-26 07:45:16 -0700561 // Waiting time will be set upon inserting the packet in the buffer.
ossua73f6c92016-10-24 08:25:28 -0700562 RTC_DCHECK(!packet.waiting_time);
563 return packet;
564 }());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000565
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200566 bool update_sample_rate_and_channels =
567 first_packet_ || (rtp_header.ssrc != ssrc_);
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700568
569 if (update_sample_rate_and_channels) {
570 // Reset timestamp scaling.
571 timestamp_scaler_->Reset();
572 }
573
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200574 if (!decoder_database_->IsRed(rtp_header.payloadType)) {
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700575 // Scale timestamp to internal domain (only for some codecs).
576 timestamp_scaler_->ToInternal(&packet_list);
577 }
578
579 // Store these for later use, since the first packet may very well disappear
580 // before we need these values.
581 uint32_t main_timestamp = packet_list.front().timestamp;
582 uint8_t main_payload_type = packet_list.front().payload_type;
583 uint16_t main_sequence_number = packet_list.front().sequence_number;
584
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000585 // Reinitialize NetEq if it's needed (changed SSRC or first call).
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700586 if (update_sample_rate_and_channels) {
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000587 // Note: |first_packet_| will be cleared further down in this method, once
588 // the packet has been successfully inserted into the packet buffer.
589
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200590 rtcp_.Init(rtp_header.sequenceNumber);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000591
592 // Flush the packet buffer and DTMF buffer.
593 packet_buffer_->Flush();
594 dtmf_buffer_->Flush();
595
596 // Store new SSRC.
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200597 ssrc_ = rtp_header.ssrc;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000598
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000599 // Update audio buffer timestamp.
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700600 sync_buffer_->IncreaseEndTimestamp(main_timestamp - timestamp_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000601
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000602 // Update codecs.
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700603 timestamp_ = main_timestamp;
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.
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200607 rtcp_.Update(rtp_header, receive_timestamp);
ossu7a377612016-10-18 04:06:13 -0700608
609 if (nack_enabled_) {
610 RTC_DCHECK(nack_);
611 if (update_sample_rate_and_channels) {
612 nack_->Reset();
613 }
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200614 nack_->UpdateLastReceivedPacket(rtp_header.sequenceNumber,
615 rtp_header.timestamp);
ossu7a377612016-10-18 04:06:13 -0700616 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000617
618 // Check for RED payload type, and separate payloads into several packets.
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200619 if (decoder_database_->IsRed(rtp_header.payloadType)) {
ossua70695a2016-09-22 02:06:28 -0700620 if (!red_payload_splitter_->SplitRed(&packet_list)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000621 return kRedundancySplitError;
622 }
623 // Only accept a few RED payloads of the same type as the main data,
624 // DTMF events and CNG.
ossua70695a2016-09-22 02:06:28 -0700625 red_payload_splitter_->CheckRedPayloads(&packet_list, *decoder_database_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000626 }
627
628 // Check payload types.
629 if (decoder_database_->CheckPayloadTypes(packet_list) ==
630 DecoderDatabase::kDecoderNotFound) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000631 return kUnknownRtpPayloadType;
632 }
633
ossu7a377612016-10-18 04:06:13 -0700634 RTC_DCHECK(!packet_list.empty());
ossu7a377612016-10-18 04:06:13 -0700635
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700636 // Update main_timestamp, if new packets appear in the list
637 // after RED splitting.
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200638 if (decoder_database_->IsRed(rtp_header.payloadType)) {
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700639 timestamp_scaler_->ToInternal(&packet_list);
640 main_timestamp = packet_list.front().timestamp;
641 main_payload_type = packet_list.front().payload_type;
642 main_sequence_number = packet_list.front().sequence_number;
643 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000644
645 // Process DTMF payloads. Cycle through the list of packets, and pick out any
646 // DTMF payloads found.
647 PacketList::iterator it = packet_list.begin();
648 while (it != packet_list.end()) {
ossua73f6c92016-10-24 08:25:28 -0700649 const Packet& current_packet = (*it);
650 RTC_DCHECK(!current_packet.payload.empty());
651 if (decoder_database_->IsDtmf(current_packet.payload_type)) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000652 DtmfEvent event;
ossua73f6c92016-10-24 08:25:28 -0700653 int ret = DtmfBuffer::ParseEvent(current_packet.timestamp,
654 current_packet.payload.data(),
655 current_packet.payload.size(), &event);
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000656 if (ret != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000657 return kDtmfParsingError;
658 }
659 if (dtmf_buffer_->InsertEvent(event) != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000660 return kDtmfInsertError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000661 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000662 it = packet_list.erase(it);
663 } else {
664 ++it;
665 }
666 }
667
ossu17e3fa12016-09-08 04:52:55 -0700668 // Update bandwidth estimate, if the packet is not comfort noise.
669 if (!packet_list.empty() &&
ossu7a377612016-10-18 04:06:13 -0700670 !decoder_database_->IsComfortNoise(main_payload_type)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000671 // The list can be empty here if we got nothing but DTMF payloads.
ossu7a377612016-10-18 04:06:13 -0700672 AudioDecoder* decoder = decoder_database_->GetDecoder(main_payload_type);
673 RTC_DCHECK(decoder); // Should always get a valid object, since we have
674 // already checked that the payload types are known.
ossua73f6c92016-10-24 08:25:28 -0700675 decoder->IncomingPacket(packet_list.front().payload.data(),
676 packet_list.front().payload.size(),
677 packet_list.front().sequence_number,
678 packet_list.front().timestamp,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000679 receive_timestamp);
680 }
681
ossu61a208b2016-09-20 01:38:00 -0700682 PacketList parsed_packet_list;
683 while (!packet_list.empty()) {
ossua73f6c92016-10-24 08:25:28 -0700684 Packet& packet = packet_list.front();
ossu61a208b2016-09-20 01:38:00 -0700685 const DecoderDatabase::DecoderInfo* info =
ossua73f6c92016-10-24 08:25:28 -0700686 decoder_database_->GetDecoderInfo(packet.payload_type);
ossu61a208b2016-09-20 01:38:00 -0700687 if (!info) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100688 RTC_LOG(LS_WARNING) << "SplitAudio unknown payload type";
ossu61a208b2016-09-20 01:38:00 -0700689 return kUnknownRtpPayloadType;
690 }
691
692 if (info->IsComfortNoise()) {
693 // Carry comfort noise packets along.
ossua73f6c92016-10-24 08:25:28 -0700694 parsed_packet_list.splice(parsed_packet_list.end(), packet_list,
695 packet_list.begin());
ossu61a208b2016-09-20 01:38:00 -0700696 } else {
ossua73f6c92016-10-24 08:25:28 -0700697 const auto sequence_number = packet.sequence_number;
698 const auto payload_type = packet.payload_type;
699 const Packet::Priority original_priority = packet.priority;
700 auto packet_from_result = [&] (AudioDecoder::ParseResult& result) {
701 Packet new_packet;
702 new_packet.sequence_number = sequence_number;
703 new_packet.payload_type = payload_type;
704 new_packet.timestamp = result.timestamp;
705 new_packet.priority.codec_level = result.priority;
706 new_packet.priority.red_level = original_priority.red_level;
707 new_packet.frame = std::move(result.frame);
708 return new_packet;
709 };
710
ossu61a208b2016-09-20 01:38:00 -0700711 std::vector<AudioDecoder::ParseResult> results =
ossua73f6c92016-10-24 08:25:28 -0700712 info->GetDecoder()->ParsePayload(std::move(packet.payload),
713 packet.timestamp);
714 if (results.empty()) {
715 packet_list.pop_front();
716 } else {
717 bool first = true;
718 for (auto& result : results) {
719 RTC_DCHECK(result.frame);
720 RTC_DCHECK_GE(result.priority, 0);
721 if (first) {
722 // Re-use the node and move it to parsed_packet_list.
723 packet_list.front() = packet_from_result(result);
724 parsed_packet_list.splice(parsed_packet_list.end(), packet_list,
725 packet_list.begin());
726 first = false;
727 } else {
728 parsed_packet_list.push_back(packet_from_result(result));
729 }
ossu61a208b2016-09-20 01:38:00 -0700730 }
ossu61a208b2016-09-20 01:38:00 -0700731 }
732 }
733 }
734
Ivo Creusenfd7c0a52017-10-20 12:35:04 +0200735 // Calculate the number of primary (non-FEC/RED) packets.
736 const int number_of_primary_packets = std::count_if(
737 parsed_packet_list.begin(), parsed_packet_list.end(),
738 [](const Packet& in) { return in.priority.codec_level == 0; });
739
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000740 // Insert packets in buffer.
ossua70695a2016-09-22 02:06:28 -0700741 const int ret = packet_buffer_->InsertPacketList(
ossu61a208b2016-09-20 01:38:00 -0700742 &parsed_packet_list, *decoder_database_, &current_rtp_payload_type_,
minyue-webrtc12d30842017-07-19 11:44:06 +0200743 &current_cng_rtp_payload_type_, &stats_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000744 if (ret == PacketBuffer::kFlushed) {
745 // Reset DSP timestamp etc. if packet buffer flushed.
746 new_codec_ = true;
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000747 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000748 } else if (ret != PacketBuffer::kOK) {
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000749 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000750 }
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000751
752 if (first_packet_) {
753 first_packet_ = false;
754 // Update the codec on the next GetAudio call.
755 new_codec_ = true;
756 }
757
henrik.lundinda8bbf62016-08-31 03:14:11 -0700758 if (current_rtp_payload_type_) {
759 RTC_DCHECK(decoder_database_->GetDecoderInfo(*current_rtp_payload_type_))
760 << "Payload type " << static_cast<int>(*current_rtp_payload_type_)
761 << " is unknown where it shouldn't be";
762 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000763
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000764 if (update_sample_rate_and_channels && !packet_buffer_->Empty()) {
765 // We do not use |current_rtp_payload_type_| to |set payload_type|, but
766 // get the next RTP header from |packet_buffer_| to obtain the payload type.
767 // The reason for it is the following corner case. If NetEq receives a
768 // CNG packet with a sample rate different than the current CNG then it
769 // flushes its buffer, assuming send codec must have been changed. However,
770 // payload type of the hypothetically new send codec is not known.
ossu7a377612016-10-18 04:06:13 -0700771 const Packet* next_packet = packet_buffer_->PeekNextPacket();
772 RTC_DCHECK(next_packet);
773 const int payload_type = next_packet->payload_type;
ossu97ba30e2016-04-25 07:55:58 -0700774 size_t channels = 1;
775 if (!decoder_database_->IsComfortNoise(payload_type)) {
776 AudioDecoder* decoder = decoder_database_->GetDecoder(payload_type);
777 assert(decoder); // Payloads are already checked to be valid.
778 channels = decoder->Channels();
779 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000780 const DecoderDatabase::DecoderInfo* decoder_info =
781 decoder_database_->GetDecoderInfo(payload_type);
782 assert(decoder_info);
kwibergc0f2dcf2016-05-31 06:28:03 -0700783 if (decoder_info->SampleRateHz() != fs_hz_ ||
ossu97ba30e2016-04-25 07:55:58 -0700784 channels != algorithm_buffer_->Channels()) {
kwibergc0f2dcf2016-05-31 06:28:03 -0700785 SetSampleRateAndChannels(decoder_info->SampleRateHz(),
786 channels);
henrik.lundin48ed9302015-10-29 05:36:24 -0700787 }
788 if (nack_enabled_) {
789 RTC_DCHECK(nack_);
790 // Update the sample rate even if the rate is not new, because of Reset().
791 nack_->UpdateSampleRate(fs_hz_);
792 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000793 }
794
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000795 // TODO(hlundin): Move this code to DelayManager class.
796 const DecoderDatabase::DecoderInfo* dec_info =
ossu7a377612016-10-18 04:06:13 -0700797 decoder_database_->GetDecoderInfo(main_payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000798 assert(dec_info); // Already checked that the payload type is known.
ossuf1b08da2016-09-23 02:19:43 -0700799 delay_manager_->LastDecodedWasCngOrDtmf(dec_info->IsComfortNoise() ||
800 dec_info->IsDtmf());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000801 if (delay_manager_->last_pack_cng_or_dtmf() == 0) {
802 // Calculate the total speech length carried in each packet.
Ivo Creusenfd7c0a52017-10-20 12:35:04 +0200803 if (number_of_primary_packets > 0) {
henrik.lundin116c84e2015-08-27 13:14:48 -0700804 const size_t packet_length_samples =
Ivo Creusenfd7c0a52017-10-20 12:35:04 +0200805 number_of_primary_packets * decoder_frame_length_;
henrik.lundin116c84e2015-08-27 13:14:48 -0700806 if (packet_length_samples != decision_logic_->packet_length_samples()) {
807 decision_logic_->set_packet_length_samples(packet_length_samples);
808 delay_manager_->SetPacketAudioLength(
kwibergd3edd772017-03-01 18:52:48 -0800809 rtc::dchecked_cast<int>((1000 * packet_length_samples) / fs_hz_));
henrik.lundin116c84e2015-08-27 13:14:48 -0700810 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000811 }
812
813 // Update statistics.
ossu7a377612016-10-18 04:06:13 -0700814 if ((int32_t)(main_timestamp - timestamp_) >= 0 && !new_codec_) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000815 // Only update statistics if incoming packet is not older than last played
816 // out packet, and if new codec flag is not set.
ossu7a377612016-10-18 04:06:13 -0700817 delay_manager_->Update(main_sequence_number, main_timestamp, fs_hz_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000818 }
819 } else if (delay_manager_->last_pack_cng_or_dtmf() == -1) {
820 // This is first "normal" packet after CNG or DTMF.
821 // Reset packet time counter and measure time until next packet,
822 // but don't update statistics.
823 delay_manager_->set_last_pack_cng_or_dtmf(0);
824 delay_manager_->ResetPacketIatCount();
825 }
826 return 0;
827}
828
henrik.lundin7a926812016-05-12 13:51:28 -0700829int NetEqImpl::GetAudioInternal(AudioFrame* audio_frame, bool* muted) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000830 PacketList packet_list;
831 DtmfEvent dtmf_event;
832 Operations operation;
833 bool play_dtmf;
henrik.lundin7a926812016-05-12 13:51:28 -0700834 *muted = false;
henrik.lundin114c1b32017-04-26 07:47:32 -0700835 last_decoded_timestamps_.clear();
henrik.lundined497212016-04-25 10:11:38 -0700836 tick_timer_->Increment();
henrik.lundin60f6ce22016-05-10 03:52:04 -0700837 stats_.IncreaseCounter(output_size_samples_, fs_hz_);
henrik.lundin7a926812016-05-12 13:51:28 -0700838
839 // Check for muted state.
840 if (enable_muted_state_ && expand_->Muted() && packet_buffer_->Empty()) {
841 RTC_DCHECK_EQ(last_mode_, kModeExpand);
henrik.lundina4491072017-07-06 05:23:53 -0700842 audio_frame->Reset();
843 RTC_DCHECK(audio_frame->muted()); // Reset() should mute the frame.
henrik.lundin7a926812016-05-12 13:51:28 -0700844 playout_timestamp_ += static_cast<uint32_t>(output_size_samples_);
845 audio_frame->sample_rate_hz_ = fs_hz_;
846 audio_frame->samples_per_channel_ = output_size_samples_;
847 audio_frame->timestamp_ =
848 first_packet_
849 ? 0
850 : timestamp_scaler_->ToExternal(playout_timestamp_) -
851 static_cast<uint32_t>(audio_frame->samples_per_channel_);
852 audio_frame->num_channels_ = sync_buffer_->Channels();
Gustaf Ullberg9a2e9062017-09-18 09:28:20 +0200853 stats_.ExpandedNoiseSamples(output_size_samples_, false);
henrik.lundin7a926812016-05-12 13:51:28 -0700854 *muted = true;
855 return 0;
856 }
857
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000858 int return_value = GetDecision(&operation, &packet_list, &dtmf_event,
859 &play_dtmf);
860 if (return_value != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000861 last_mode_ = kModeError;
862 return return_value;
863 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000864
865 AudioDecoder::SpeechType speech_type;
866 int length = 0;
Henrik Lundin18036282017-11-02 12:09:06 +0100867 const size_t start_num_packets = packet_list.size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000868 int decode_return_value = Decode(&packet_list, &operation,
869 &length, &speech_type);
870
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000871 assert(vad_.get());
872 bool sid_frame_available =
873 (operation == kRfc3389Cng && !packet_list.empty());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700874 vad_->Update(decoded_buffer_.get(), static_cast<size_t>(length), speech_type,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000875 sid_frame_available, fs_hz_);
876
Henrik Lundin18036282017-11-02 12:09:06 +0100877 // This is the criterion that we did decode some data through the speech
878 // decoder, and the operation resulted in comfort noise.
879 const bool codec_internal_sid_frame =
Henrik Lundin4f2a4a12018-01-26 17:32:56 +0100880 (speech_type == AudioDecoder::kComfortNoise &&
881 start_num_packets > packet_list.size());
Henrik Lundin18036282017-11-02 12:09:06 +0100882
883 if (sid_frame_available || codec_internal_sid_frame) {
henrik.lundinb1fb72b2016-05-03 08:18:47 -0700884 // Start a new stopwatch since we are decoding a new CNG packet.
885 generated_noise_stopwatch_ = tick_timer_->GetNewStopwatch();
886 }
887
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000888 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000889 switch (operation) {
890 case kNormal: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000891 DoNormal(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000892 break;
893 }
894 case kMerge: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000895 DoMerge(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000896 break;
897 }
898 case kExpand: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000899 return_value = DoExpand(play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000900 break;
901 }
Henrik Lundincf808d22015-05-27 14:33:29 +0200902 case kAccelerate:
903 case kFastAccelerate: {
904 const bool fast_accelerate =
905 enable_fast_accelerate_ && (operation == kFastAccelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000906 return_value = DoAccelerate(decoded_buffer_.get(), length, speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +0200907 play_dtmf, fast_accelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000908 break;
909 }
910 case kPreemptiveExpand: {
911 return_value = DoPreemptiveExpand(decoded_buffer_.get(), length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000912 speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000913 break;
914 }
915 case kRfc3389Cng:
916 case kRfc3389CngNoPacket: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000917 return_value = DoRfc3389Cng(&packet_list, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000918 break;
919 }
920 case kCodecInternalCng: {
921 // This handles the case when there is no transmission and the decoder
922 // should produce internal comfort noise.
923 // TODO(hlundin): Write test for codec-internal CNG.
minyuel6d92bf52015-09-23 15:20:39 +0200924 DoCodecInternalCng(decoded_buffer_.get(), length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000925 break;
926 }
927 case kDtmf: {
928 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000929 return_value = DoDtmf(dtmf_event, &play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000930 break;
931 }
932 case kAlternativePlc: {
933 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000934 DoAlternativePlc(false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000935 break;
936 }
937 case kAlternativePlcIncreaseTimestamp: {
938 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000939 DoAlternativePlc(true);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000940 break;
941 }
942 case kAudioRepetitionIncreaseTimestamp: {
943 // TODO(hlundin): Write test for this.
Peter Kastingb7e50542015-06-11 12:55:50 -0700944 sync_buffer_->IncreaseEndTimestamp(
945 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000946 // Skipping break on purpose. Execution should move on into the
947 // next case.
Karl Wiberg80ba3332018-02-05 10:33:35 +0100948 RTC_FALLTHROUGH();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000949 }
950 case kAudioRepetition: {
951 // TODO(hlundin): Write test for this.
952 // Copy last |output_size_samples_| from |sync_buffer_| to
953 // |algorithm_buffer|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000954 algorithm_buffer_->PushBackFromIndex(
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000955 *sync_buffer_, sync_buffer_->Size() - output_size_samples_);
956 expand_->Reset();
957 break;
958 }
959 case kUndefined: {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100960 RTC_LOG(LS_ERROR) << "Invalid operation kUndefined.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000961 assert(false); // This should not happen.
962 last_mode_ = kModeError;
963 return kInvalidOperation;
964 }
965 } // End of switch.
minyue5bd33972016-05-02 04:46:11 -0700966 last_operation_ = operation;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000967 if (return_value < 0) {
968 return return_value;
969 }
970
971 if (last_mode_ != kModeRfc3389Cng) {
972 comfort_noise_->Reset();
973 }
974
975 // Copy from |algorithm_buffer| to |sync_buffer_|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000976 sync_buffer_->PushBack(*algorithm_buffer_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000977
978 // Extract data from |sync_buffer_| to |output|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000979 size_t num_output_samples_per_channel = output_size_samples_;
980 size_t num_output_samples = output_size_samples_ * sync_buffer_->Channels();
henrik.lundin6d8e0112016-03-04 10:34:21 -0800981 if (num_output_samples > AudioFrame::kMaxDataSizeSamples) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100982 RTC_LOG(LS_WARNING) << "Output array is too short. "
983 << AudioFrame::kMaxDataSizeSamples << " < "
984 << output_size_samples_ << " * "
985 << sync_buffer_->Channels();
henrik.lundin6d8e0112016-03-04 10:34:21 -0800986 num_output_samples = AudioFrame::kMaxDataSizeSamples;
987 num_output_samples_per_channel =
988 AudioFrame::kMaxDataSizeSamples / sync_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000989 }
henrik.lundin6d8e0112016-03-04 10:34:21 -0800990 sync_buffer_->GetNextAudioInterleaved(num_output_samples_per_channel,
991 audio_frame);
992 audio_frame->sample_rate_hz_ = fs_hz_;
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200993 if (sync_buffer_->FutureLength() < expand_->overlap_length()) {
994 // The sync buffer should always contain |overlap_length| samples, but now
995 // too many samples have been extracted. Reinstall the |overlap_length|
996 // lookahead by moving the index.
997 const size_t missing_lookahead_samples =
998 expand_->overlap_length() - sync_buffer_->FutureLength();
henrikg91d6ede2015-09-17 00:24:34 -0700999 RTC_DCHECK_GE(sync_buffer_->next_index(), missing_lookahead_samples);
Henrik Lundin05f71fc2015-09-01 11:51:58 +02001000 sync_buffer_->set_next_index(sync_buffer_->next_index() -
1001 missing_lookahead_samples);
1002 }
henrik.lundin6d8e0112016-03-04 10:34:21 -08001003 if (audio_frame->samples_per_channel_ != output_size_samples_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001004 RTC_LOG(LS_ERROR) << "audio_frame->samples_per_channel_ ("
1005 << audio_frame->samples_per_channel_
1006 << ") != output_size_samples_ (" << output_size_samples_
1007 << ")";
minyue@webrtc.orgdb1cefc2013-08-13 01:39:21 +00001008 // TODO(minyue): treatment of under-run, filling zeros
yujo36b1a5f2017-06-12 12:45:32 -07001009 audio_frame->Mute();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001010 return kSampleUnderrun;
1011 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001012
1013 // Should always have overlap samples left in the |sync_buffer_|.
henrikg91d6ede2015-09-17 00:24:34 -07001014 RTC_DCHECK_GE(sync_buffer_->FutureLength(), expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001015
yujo36b1a5f2017-06-12 12:45:32 -07001016 // TODO(yujo): For muted frames, this can be a copy rather than an addition.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001017 if (play_dtmf) {
yujo36b1a5f2017-06-12 12:45:32 -07001018 return_value = DtmfOverdub(dtmf_event, sync_buffer_->Channels(),
1019 audio_frame->mutable_data());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001020 }
1021
1022 // Update the background noise parameters if last operation wrote data
1023 // straight from the decoder to the |sync_buffer_|. That is, none of the
1024 // operations that modify the signal can be followed by a parameter update.
1025 if ((last_mode_ == kModeNormal) ||
1026 (last_mode_ == kModeAccelerateFail) ||
1027 (last_mode_ == kModePreemptiveExpandFail) ||
1028 (last_mode_ == kModeRfc3389Cng) ||
1029 (last_mode_ == kModeCodecInternalCng)) {
1030 background_noise_->Update(*sync_buffer_, *vad_.get());
1031 }
1032
1033 if (operation == kDtmf) {
1034 // DTMF data was written the end of |sync_buffer_|.
1035 // Update index to end of DTMF data in |sync_buffer_|.
1036 sync_buffer_->set_dtmf_index(sync_buffer_->Size());
1037 }
1038
henrik.lundin@webrtc.orged865b52014-03-06 10:28:07 +00001039 if (last_mode_ != kModeExpand) {
1040 // If last operation was not expand, calculate the |playout_timestamp_| from
1041 // the |sync_buffer_|. However, do not update the |playout_timestamp_| if it
1042 // would be moved "backwards".
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001043 uint32_t temp_timestamp = sync_buffer_->end_timestamp() -
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001044 static_cast<uint32_t>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001045 if (static_cast<int32_t>(temp_timestamp - playout_timestamp_) > 0) {
1046 playout_timestamp_ = temp_timestamp;
1047 }
1048 } else {
1049 // Use dead reckoning to estimate the |playout_timestamp_|.
Peter Kastingb7e50542015-06-11 12:55:50 -07001050 playout_timestamp_ += static_cast<uint32_t>(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001051 }
henrik.lundin15c51e32016-04-06 08:38:56 -07001052 // Set the timestamp in the audio frame to zero before the first packet has
1053 // been inserted. Otherwise, subtract the frame size in samples to get the
1054 // timestamp of the first sample in the frame (playout_timestamp_ is the
1055 // last + 1).
1056 audio_frame->timestamp_ =
1057 first_packet_
1058 ? 0
1059 : timestamp_scaler_->ToExternal(playout_timestamp_) -
1060 static_cast<uint32_t>(audio_frame->samples_per_channel_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001061
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001062 if (!(last_mode_ == kModeRfc3389Cng ||
1063 last_mode_ == kModeCodecInternalCng ||
1064 last_mode_ == kModeExpand)) {
1065 generated_noise_stopwatch_.reset();
1066 }
1067
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001068 if (decode_return_value) return decode_return_value;
1069 return return_value;
1070}
1071
1072int NetEqImpl::GetDecision(Operations* operation,
1073 PacketList* packet_list,
1074 DtmfEvent* dtmf_event,
1075 bool* play_dtmf) {
1076 // Initialize output variables.
1077 *play_dtmf = false;
1078 *operation = kUndefined;
1079
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001080 assert(sync_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001081 uint32_t end_timestamp = sync_buffer_->end_timestamp();
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001082 if (!new_codec_) {
1083 const uint32_t five_seconds_samples = 5 * fs_hz_;
minyue-webrtcfae474c2017-07-05 11:17:40 +02001084 packet_buffer_->DiscardOldPackets(end_timestamp, five_seconds_samples,
1085 &stats_);
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001086 }
ossu7a377612016-10-18 04:06:13 -07001087 const Packet* packet = packet_buffer_->PeekNextPacket();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001088
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001089 RTC_DCHECK(!generated_noise_stopwatch_ ||
1090 generated_noise_stopwatch_->ElapsedTicks() >= 1);
1091 uint64_t generated_noise_samples =
1092 generated_noise_stopwatch_
1093 ? (generated_noise_stopwatch_->ElapsedTicks() - 1) *
1094 output_size_samples_ +
1095 decision_logic_->noise_fast_forward()
1096 : 0;
1097
henrik.lundin@webrtc.orgca8cb952014-03-12 10:26:52 +00001098 if (decision_logic_->CngRfc3389On() || last_mode_ == kModeRfc3389Cng) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001099 // Because of timestamp peculiarities, we have to "manually" disallow using
1100 // a CNG packet with the same timestamp as the one that was last played.
1101 // This can happen when using redundancy and will cause the timing to shift.
ossu7a377612016-10-18 04:06:13 -07001102 while (packet && decoder_database_->IsComfortNoise(packet->payload_type) &&
1103 (end_timestamp >= packet->timestamp ||
1104 end_timestamp + generated_noise_samples > packet->timestamp)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001105 // Don't use this packet, discard it.
minyue-webrtcfae474c2017-07-05 11:17:40 +02001106 if (packet_buffer_->DiscardNextPacket(&stats_) != PacketBuffer::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001107 assert(false); // Must be ok by design.
1108 }
1109 // Check buffer again.
1110 if (!new_codec_) {
minyue-webrtcfae474c2017-07-05 11:17:40 +02001111 packet_buffer_->DiscardOldPackets(end_timestamp, 5 * fs_hz_, &stats_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001112 }
ossu7a377612016-10-18 04:06:13 -07001113 packet = packet_buffer_->PeekNextPacket();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001114 }
1115 }
1116
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001117 assert(expand_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001118 const int samples_left = static_cast<int>(sync_buffer_->FutureLength() -
1119 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001120 if (last_mode_ == kModeAccelerateSuccess ||
1121 last_mode_ == kModeAccelerateLowEnergy ||
1122 last_mode_ == kModePreemptiveExpandSuccess ||
1123 last_mode_ == kModePreemptiveExpandLowEnergy) {
1124 // Subtract (samples_left + output_size_samples_) from sampleMemory.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001125 decision_logic_->AddSampleMemory(
kwibergd3edd772017-03-01 18:52:48 -08001126 -(samples_left + rtc::dchecked_cast<int>(output_size_samples_)));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001127 }
1128
1129 // Check if it is time to play a DTMF event.
Peter Kastingb7e50542015-06-11 12:55:50 -07001130 if (dtmf_buffer_->GetEvent(
1131 static_cast<uint32_t>(
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001132 end_timestamp + generated_noise_samples),
Peter Kastingb7e50542015-06-11 12:55:50 -07001133 dtmf_event)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001134 *play_dtmf = true;
1135 }
1136
1137 // Get instruction.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001138 assert(sync_buffer_.get());
1139 assert(expand_.get());
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001140 generated_noise_samples =
1141 generated_noise_stopwatch_
1142 ? generated_noise_stopwatch_->ElapsedTicks() * output_size_samples_ +
1143 decision_logic_->noise_fast_forward()
1144 : 0;
1145 *operation = decision_logic_->GetDecision(
ossu7a377612016-10-18 04:06:13 -07001146 *sync_buffer_, *expand_, decoder_frame_length_, packet, last_mode_,
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001147 *play_dtmf, generated_noise_samples, &reset_decoder_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001148
1149 // Check if we already have enough samples in the |sync_buffer_|. If so,
1150 // change decision to normal, unless the decision was merge, accelerate, or
1151 // preemptive expand.
kwibergd3edd772017-03-01 18:52:48 -08001152 if (samples_left >= rtc::dchecked_cast<int>(output_size_samples_) &&
1153 *operation != kMerge && *operation != kAccelerate &&
1154 *operation != kFastAccelerate && *operation != kPreemptiveExpand) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001155 *operation = kNormal;
1156 return 0;
1157 }
1158
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001159 decision_logic_->ExpandDecision(*operation);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001160
1161 // Check conditions for reset.
1162 if (new_codec_ || *operation == kUndefined) {
1163 // The only valid reason to get kUndefined is that new_codec_ is set.
1164 assert(new_codec_);
ossu7a377612016-10-18 04:06:13 -07001165 if (*play_dtmf && !packet) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001166 timestamp_ = dtmf_event->timestamp;
1167 } else {
ossu7a377612016-10-18 04:06:13 -07001168 if (!packet) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001169 RTC_LOG(LS_ERROR) << "Packet missing where it shouldn't.";
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001170 return -1;
1171 }
ossu7a377612016-10-18 04:06:13 -07001172 timestamp_ = packet->timestamp;
ossu108ecec2016-07-08 08:45:18 -07001173 if (*operation == kRfc3389CngNoPacket &&
ossu7a377612016-10-18 04:06:13 -07001174 decoder_database_->IsComfortNoise(packet->payload_type)) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001175 // Change decision to CNG packet, since we do have a CNG packet, but it
1176 // was considered too early to use. Now, use it anyway.
1177 *operation = kRfc3389Cng;
1178 } else if (*operation != kRfc3389Cng) {
1179 *operation = kNormal;
1180 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001181 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001182 // Adjust |sync_buffer_| timestamp before setting |end_timestamp| to the
1183 // new value.
1184 sync_buffer_->IncreaseEndTimestamp(timestamp_ - end_timestamp);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001185 end_timestamp = timestamp_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001186 new_codec_ = false;
1187 decision_logic_->SoftReset();
1188 buffer_level_filter_->Reset();
1189 delay_manager_->Reset();
1190 stats_.ResetMcu();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001191 }
1192
Peter Kastingdce40cf2015-08-24 14:52:23 -07001193 size_t required_samples = output_size_samples_;
1194 const size_t samples_10_ms = static_cast<size_t>(80 * fs_mult_);
1195 const size_t samples_20_ms = 2 * samples_10_ms;
1196 const size_t samples_30_ms = 3 * samples_10_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001197
1198 switch (*operation) {
1199 case kExpand: {
1200 timestamp_ = end_timestamp;
1201 return 0;
1202 }
1203 case kRfc3389CngNoPacket:
1204 case kCodecInternalCng: {
1205 return 0;
1206 }
1207 case kDtmf: {
1208 // TODO(hlundin): Write test for this.
1209 // Update timestamp.
1210 timestamp_ = end_timestamp;
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001211 const uint64_t generated_noise_samples =
1212 generated_noise_stopwatch_
1213 ? generated_noise_stopwatch_->ElapsedTicks() *
1214 output_size_samples_ +
1215 decision_logic_->noise_fast_forward()
1216 : 0;
1217 if (generated_noise_samples > 0 && last_mode_ != kModeDtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001218 // Make a jump in timestamp due to the recently played comfort noise.
Peter Kastingb7e50542015-06-11 12:55:50 -07001219 uint32_t timestamp_jump =
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001220 static_cast<uint32_t>(generated_noise_samples);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001221 sync_buffer_->IncreaseEndTimestamp(timestamp_jump);
1222 timestamp_ += timestamp_jump;
1223 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001224 return 0;
1225 }
Henrik Lundincf808d22015-05-27 14:33:29 +02001226 case kAccelerate:
1227 case kFastAccelerate: {
1228 // In order to do an accelerate we need at least 30 ms of audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001229 if (samples_left >= static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001230 // Already have enough data, so we do not need to extract any more.
1231 decision_logic_->set_sample_memory(samples_left);
1232 decision_logic_->set_prev_time_scale(true);
1233 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001234 } else if (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001235 decoder_frame_length_ >= samples_30_ms) {
1236 // Avoid decoding more data as it might overflow the playout buffer.
1237 *operation = kNormal;
1238 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001239 } else if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001240 decoder_frame_length_ < samples_30_ms) {
1241 // Build up decoded data by decoding at least 20 ms of audio data. Do
1242 // not perform accelerate yet, but wait until we only need to do one
1243 // decoding.
1244 required_samples = 2 * output_size_samples_;
1245 *operation = kNormal;
1246 }
1247 // If none of the above is true, we have one of two possible situations:
1248 // (1) 20 ms <= samples_left < 30 ms and decoder_frame_length_ < 30 ms; or
1249 // (2) samples_left < 10 ms and decoder_frame_length_ >= 30 ms.
1250 // In either case, we move on with the accelerate decision, and decode one
1251 // frame now.
1252 break;
1253 }
1254 case kPreemptiveExpand: {
1255 // In order to do a preemptive expand we need at least 30 ms of decoded
1256 // audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001257 if ((samples_left >= static_cast<int>(samples_30_ms)) ||
1258 (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001259 decoder_frame_length_ >= samples_30_ms)) {
1260 // Already have enough data, so we do not need to extract any more.
1261 // Or, avoid decoding more data as it might overflow the playout buffer.
1262 // Still try preemptive expand, though.
1263 decision_logic_->set_sample_memory(samples_left);
1264 decision_logic_->set_prev_time_scale(true);
1265 return 0;
1266 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07001267 if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001268 decoder_frame_length_ < samples_30_ms) {
1269 // Build up decoded data by decoding at least 20 ms of audio data.
1270 // Still try to perform preemptive expand.
1271 required_samples = 2 * output_size_samples_;
1272 }
1273 // Move on with the preemptive expand decision.
1274 break;
1275 }
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001276 case kMerge: {
1277 required_samples =
1278 std::max(merge_->RequiredFutureSamples(), required_samples);
1279 break;
1280 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001281 default: {
1282 // Do nothing.
1283 }
1284 }
1285
1286 // Get packets from buffer.
1287 int extracted_samples = 0;
ossu7a377612016-10-18 04:06:13 -07001288 if (packet && *operation != kAlternativePlc &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001289 *operation != kAlternativePlcIncreaseTimestamp &&
1290 *operation != kAudioRepetition &&
1291 *operation != kAudioRepetitionIncreaseTimestamp) {
ossu7a377612016-10-18 04:06:13 -07001292 sync_buffer_->IncreaseEndTimestamp(packet->timestamp - end_timestamp);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001293 if (decision_logic_->CngOff()) {
1294 // Adjustment of timestamp only corresponds to an actual packet loss
1295 // if comfort noise is not played. If comfort noise was just played,
1296 // this adjustment of timestamp is only done to get back in sync with the
1297 // stream timestamp; no loss to report.
ossu7a377612016-10-18 04:06:13 -07001298 stats_.LostSamples(packet->timestamp - end_timestamp);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001299 }
1300
1301 if (*operation != kRfc3389Cng) {
1302 // We are about to decode and use a non-CNG packet.
1303 decision_logic_->SetCngOff();
1304 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001305
1306 extracted_samples = ExtractPackets(required_samples, packet_list);
1307 if (extracted_samples < 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001308 return kPacketBufferCorruption;
1309 }
1310 }
1311
Henrik Lundincf808d22015-05-27 14:33:29 +02001312 if (*operation == kAccelerate || *operation == kFastAccelerate ||
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001313 *operation == kPreemptiveExpand) {
1314 decision_logic_->set_sample_memory(samples_left + extracted_samples);
1315 decision_logic_->set_prev_time_scale(true);
1316 }
1317
Henrik Lundincf808d22015-05-27 14:33:29 +02001318 if (*operation == kAccelerate || *operation == kFastAccelerate) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001319 // Check that we have enough data (30ms) to do accelerate.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001320 if (extracted_samples + samples_left < static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001321 // TODO(hlundin): Write test for this.
1322 // Not enough, do normal operation instead.
1323 *operation = kNormal;
1324 }
1325 }
1326
1327 timestamp_ = end_timestamp;
1328 return 0;
1329}
1330
1331int NetEqImpl::Decode(PacketList* packet_list, Operations* operation,
1332 int* decoded_length,
1333 AudioDecoder::SpeechType* speech_type) {
1334 *speech_type = AudioDecoder::kSpeech;
minyuel6d92bf52015-09-23 15:20:39 +02001335
1336 // When packet_list is empty, we may be in kCodecInternalCng mode, and for
1337 // that we use current active decoder.
1338 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1339
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001340 if (!packet_list->empty()) {
ossua73f6c92016-10-24 08:25:28 -07001341 const Packet& packet = packet_list->front();
1342 uint8_t payload_type = packet.payload_type;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001343 if (!decoder_database_->IsComfortNoise(payload_type)) {
1344 decoder = decoder_database_->GetDecoder(payload_type);
1345 assert(decoder);
1346 if (!decoder) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001347 RTC_LOG(LS_WARNING)
1348 << "Unknown payload type " << static_cast<int>(payload_type);
ossua73f6c92016-10-24 08:25:28 -07001349 packet_list->clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001350 return kDecoderNotFound;
1351 }
1352 bool decoder_changed;
1353 decoder_database_->SetActiveDecoder(payload_type, &decoder_changed);
1354 if (decoder_changed) {
1355 // We have a new decoder. Re-init some values.
1356 const DecoderDatabase::DecoderInfo* decoder_info = decoder_database_
1357 ->GetDecoderInfo(payload_type);
1358 assert(decoder_info);
1359 if (!decoder_info) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001360 RTC_LOG(LS_WARNING)
1361 << "Unknown payload type " << static_cast<int>(payload_type);
ossua73f6c92016-10-24 08:25:28 -07001362 packet_list->clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001363 return kDecoderNotFound;
1364 }
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001365 // If sampling rate or number of channels has changed, we need to make
1366 // a reset.
kwibergc0f2dcf2016-05-31 06:28:03 -07001367 if (decoder_info->SampleRateHz() != fs_hz_ ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001368 decoder->Channels() != algorithm_buffer_->Channels()) {
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001369 // TODO(tlegrand): Add unittest to cover this event.
kwibergc0f2dcf2016-05-31 06:28:03 -07001370 SetSampleRateAndChannels(decoder_info->SampleRateHz(),
1371 decoder->Channels());
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001372 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001373 sync_buffer_->set_end_timestamp(timestamp_);
1374 playout_timestamp_ = timestamp_;
1375 }
1376 }
1377 }
1378
1379 if (reset_decoder_) {
1380 // TODO(hlundin): Write test for this.
Karl Wiberg43766482015-08-27 15:22:11 +02001381 if (decoder)
1382 decoder->Reset();
1383
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001384 // Reset comfort noise decoder.
ossu97ba30e2016-04-25 07:55:58 -07001385 ComfortNoiseDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02001386 if (cng_decoder)
1387 cng_decoder->Reset();
1388
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001389 reset_decoder_ = false;
1390 }
1391
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001392 *decoded_length = 0;
1393 // Update codec-internal PLC state.
1394 if ((*operation == kMerge) && decoder && decoder->HasDecodePlc()) {
1395 decoder->DecodePlc(1, &decoded_buffer_[*decoded_length]);
1396 }
1397
minyuel6d92bf52015-09-23 15:20:39 +02001398 int return_value;
1399 if (*operation == kCodecInternalCng) {
1400 RTC_DCHECK(packet_list->empty());
1401 return_value = DecodeCng(decoder, decoded_length, speech_type);
1402 } else {
1403 return_value = DecodeLoop(packet_list, *operation, decoder,
1404 decoded_length, speech_type);
1405 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001406
1407 if (*decoded_length < 0) {
1408 // Error returned from the decoder.
1409 *decoded_length = 0;
Peter Kastingb7e50542015-06-11 12:55:50 -07001410 sync_buffer_->IncreaseEndTimestamp(
1411 static_cast<uint32_t>(decoder_frame_length_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001412 int error_code = 0;
1413 if (decoder)
1414 error_code = decoder->ErrorCode();
1415 if (error_code != 0) {
1416 // Got some error code from the decoder.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001417 return_value = kDecoderErrorCode;
Mirko Bonadei675513b2017-11-09 11:09:25 +01001418 RTC_LOG(LS_WARNING) << "Decoder returned error code: " << error_code;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001419 } else {
1420 // Decoder does not implement error codes. Return generic error.
1421 return_value = kOtherDecoderError;
Mirko Bonadei675513b2017-11-09 11:09:25 +01001422 RTC_LOG(LS_WARNING) << "Decoder error (no error code)";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001423 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001424 *operation = kExpand; // Do expansion to get data instead.
1425 }
1426 if (*speech_type != AudioDecoder::kComfortNoise) {
1427 // Don't increment timestamp if codec returned CNG speech type
1428 // since in this case, the we will increment the CNGplayedTS counter.
1429 // Increase with number of samples per channel.
1430 assert(*decoded_length == 0 ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001431 (decoder && decoder->Channels() == sync_buffer_->Channels()));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001432 sync_buffer_->IncreaseEndTimestamp(
1433 *decoded_length / static_cast<int>(sync_buffer_->Channels()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001434 }
1435 return return_value;
1436}
1437
minyuel6d92bf52015-09-23 15:20:39 +02001438int NetEqImpl::DecodeCng(AudioDecoder* decoder, int* decoded_length,
1439 AudioDecoder::SpeechType* speech_type) {
1440 if (!decoder) {
1441 // This happens when active decoder is not defined.
1442 *decoded_length = -1;
1443 return 0;
1444 }
1445
kwibergd3edd772017-03-01 18:52:48 -08001446 while (*decoded_length < rtc::dchecked_cast<int>(output_size_samples_)) {
minyuel6d92bf52015-09-23 15:20:39 +02001447 const int length = decoder->Decode(
1448 nullptr, 0, fs_hz_,
1449 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1450 &decoded_buffer_[*decoded_length], speech_type);
1451 if (length > 0) {
1452 *decoded_length += length;
minyuel6d92bf52015-09-23 15:20:39 +02001453 } else {
1454 // Error.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001455 RTC_LOG(LS_WARNING) << "Failed to decode CNG";
minyuel6d92bf52015-09-23 15:20:39 +02001456 *decoded_length = -1;
1457 break;
1458 }
1459 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1460 // Guard against overflow.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001461 RTC_LOG(LS_WARNING) << "Decoded too much CNG.";
minyuel6d92bf52015-09-23 15:20:39 +02001462 return kDecodedTooMuch;
1463 }
1464 }
1465 return 0;
1466}
1467
1468int NetEqImpl::DecodeLoop(PacketList* packet_list, const Operations& operation,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001469 AudioDecoder* decoder, int* decoded_length,
1470 AudioDecoder::SpeechType* speech_type) {
henrik.lundin114c1b32017-04-26 07:47:32 -07001471 RTC_DCHECK(last_decoded_timestamps_.empty());
1472
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001473 // Do decoding.
ossua73f6c92016-10-24 08:25:28 -07001474 while (
1475 !packet_list->empty() &&
1476 !decoder_database_->IsComfortNoise(packet_list->front().payload_type)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001477 assert(decoder); // At this point, we must have a decoder object.
1478 // The number of channels in the |sync_buffer_| should be the same as the
1479 // number decoder channels.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001480 assert(sync_buffer_->Channels() == decoder->Channels());
1481 assert(decoded_buffer_length_ >= kMaxFrameSize * decoder->Channels());
minyuel6d92bf52015-09-23 15:20:39 +02001482 assert(operation == kNormal || operation == kAccelerate ||
1483 operation == kFastAccelerate || operation == kMerge ||
1484 operation == kPreemptiveExpand);
ossua73f6c92016-10-24 08:25:28 -07001485
1486 auto opt_result = packet_list->front().frame->Decode(
ossu61a208b2016-09-20 01:38:00 -07001487 rtc::ArrayView<int16_t>(&decoded_buffer_[*decoded_length],
1488 decoded_buffer_length_ - *decoded_length));
henrik.lundin114c1b32017-04-26 07:47:32 -07001489 last_decoded_timestamps_.push_back(packet_list->front().timestamp);
ossua73f6c92016-10-24 08:25:28 -07001490 packet_list->pop_front();
ossu61a208b2016-09-20 01:38:00 -07001491 if (opt_result) {
1492 const auto& result = *opt_result;
1493 *speech_type = result.speech_type;
1494 if (result.num_decoded_samples > 0) {
kwibergd3edd772017-03-01 18:52:48 -08001495 *decoded_length += rtc::dchecked_cast<int>(result.num_decoded_samples);
ossu61a208b2016-09-20 01:38:00 -07001496 // Update |decoder_frame_length_| with number of samples per channel.
1497 decoder_frame_length_ =
1498 result.num_decoded_samples / decoder->Channels();
1499 }
1500 } else {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001501 // Error.
ossu61a208b2016-09-20 01:38:00 -07001502 // TODO(ossu): What to put here?
Mirko Bonadei675513b2017-11-09 11:09:25 +01001503 RTC_LOG(LS_WARNING) << "Decode error";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001504 *decoded_length = -1;
ossua73f6c92016-10-24 08:25:28 -07001505 packet_list->clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001506 break;
1507 }
kwibergd3edd772017-03-01 18:52:48 -08001508 if (*decoded_length > rtc::dchecked_cast<int>(decoded_buffer_length_)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001509 // Guard against overflow.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001510 RTC_LOG(LS_WARNING) << "Decoded too much.";
ossua73f6c92016-10-24 08:25:28 -07001511 packet_list->clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001512 return kDecodedTooMuch;
1513 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001514 } // End of decode loop.
1515
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001516 // If the list is not empty at this point, either a decoding error terminated
1517 // the while-loop, or list must hold exactly one CNG packet.
ossua73f6c92016-10-24 08:25:28 -07001518 assert(
1519 packet_list->empty() || *decoded_length < 0 ||
1520 (packet_list->size() == 1 &&
1521 decoder_database_->IsComfortNoise(packet_list->front().payload_type)));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001522 return 0;
1523}
1524
1525void NetEqImpl::DoNormal(const int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001526 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001527 assert(normal_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001528 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001529 normal_->Process(decoded_buffer, decoded_length, last_mode_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001530 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001531 if (decoded_length != 0) {
1532 last_mode_ = kModeNormal;
1533 }
1534
1535 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1536 if ((speech_type == AudioDecoder::kComfortNoise)
1537 || ((last_mode_ == kModeCodecInternalCng)
1538 && (decoded_length == 0))) {
1539 // TODO(hlundin): Remove second part of || statement above.
1540 last_mode_ = kModeCodecInternalCng;
1541 }
1542
1543 if (!play_dtmf) {
1544 dtmf_tone_generator_->Reset();
1545 }
1546}
1547
1548void NetEqImpl::DoMerge(int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001549 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001550 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001551 assert(merge_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001552 size_t new_length = merge_->Process(decoded_buffer, decoded_length,
1553 mute_factor_array_.get(),
1554 algorithm_buffer_.get());
henrik.lundin2979f552017-05-05 05:04:16 -07001555 // Correction can be negative.
1556 int expand_length_correction =
1557 rtc::dchecked_cast<int>(new_length) -
1558 rtc::dchecked_cast<int>(decoded_length / algorithm_buffer_->Channels());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001559
1560 // Update in-call and post-call statistics.
1561 if (expand_->MuteFactor(0) == 0) {
1562 // Expand generates only noise.
henrik.lundin2979f552017-05-05 05:04:16 -07001563 stats_.ExpandedNoiseSamplesCorrection(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001564 } else {
1565 // Expansion generates more than only noise.
henrik.lundin2979f552017-05-05 05:04:16 -07001566 stats_.ExpandedVoiceSamplesCorrection(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001567 }
1568
1569 last_mode_ = kModeMerge;
1570 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1571 if (speech_type == AudioDecoder::kComfortNoise) {
1572 last_mode_ = kModeCodecInternalCng;
1573 }
1574 expand_->Reset();
1575 if (!play_dtmf) {
1576 dtmf_tone_generator_->Reset();
1577 }
1578}
1579
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001580int NetEqImpl::DoExpand(bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001581 while ((sync_buffer_->FutureLength() - expand_->overlap_length()) <
Peter Kastingdce40cf2015-08-24 14:52:23 -07001582 output_size_samples_) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001583 algorithm_buffer_->Clear();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001584 int return_value = expand_->Process(algorithm_buffer_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001585 size_t length = algorithm_buffer_->Size();
Gustaf Ullberg9a2e9062017-09-18 09:28:20 +02001586 bool is_new_concealment_event = (last_mode_ != kModeExpand);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001587
1588 // Update in-call and post-call statistics.
1589 if (expand_->MuteFactor(0) == 0) {
1590 // Expand operation generates only noise.
Gustaf Ullberg9a2e9062017-09-18 09:28:20 +02001591 stats_.ExpandedNoiseSamples(length, is_new_concealment_event);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001592 } else {
1593 // Expand operation generates more than only noise.
Gustaf Ullberg9a2e9062017-09-18 09:28:20 +02001594 stats_.ExpandedVoiceSamples(length, is_new_concealment_event);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001595 }
1596
1597 last_mode_ = kModeExpand;
1598
1599 if (return_value < 0) {
1600 return return_value;
1601 }
1602
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001603 sync_buffer_->PushBack(*algorithm_buffer_);
1604 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001605 }
1606 if (!play_dtmf) {
1607 dtmf_tone_generator_->Reset();
1608 }
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001609
1610 if (!generated_noise_stopwatch_) {
1611 // Start a new stopwatch since we may be covering for a lost CNG packet.
1612 generated_noise_stopwatch_ = tick_timer_->GetNewStopwatch();
1613 }
1614
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001615 return 0;
1616}
1617
Henrik Lundincf808d22015-05-27 14:33:29 +02001618int NetEqImpl::DoAccelerate(int16_t* decoded_buffer,
1619 size_t decoded_length,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001620 AudioDecoder::SpeechType speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +02001621 bool play_dtmf,
1622 bool fast_accelerate) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001623 const size_t required_samples =
1624 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001625 size_t borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001626 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001627 size_t decoded_length_per_channel = decoded_length / num_channels;
1628 if (decoded_length_per_channel < required_samples) {
1629 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001630 borrowed_samples_per_channel = static_cast<int>(required_samples -
1631 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001632 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1633 decoded_buffer,
1634 sizeof(int16_t) * decoded_length);
1635 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1636 decoded_buffer);
1637 decoded_length = required_samples * num_channels;
1638 }
1639
Peter Kastingdce40cf2015-08-24 14:52:23 -07001640 size_t samples_removed;
Henrik Lundincf808d22015-05-27 14:33:29 +02001641 Accelerate::ReturnCodes return_code =
1642 accelerate_->Process(decoded_buffer, decoded_length, fast_accelerate,
1643 algorithm_buffer_.get(), &samples_removed);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001644 stats_.AcceleratedSamples(samples_removed);
1645 switch (return_code) {
1646 case Accelerate::kSuccess:
1647 last_mode_ = kModeAccelerateSuccess;
1648 break;
1649 case Accelerate::kSuccessLowEnergy:
1650 last_mode_ = kModeAccelerateLowEnergy;
1651 break;
1652 case Accelerate::kNoStretch:
1653 last_mode_ = kModeAccelerateFail;
1654 break;
1655 case Accelerate::kError:
1656 // TODO(hlundin): Map to kModeError instead?
1657 last_mode_ = kModeAccelerateFail;
1658 return kAccelerateError;
1659 }
1660
1661 if (borrowed_samples_per_channel > 0) {
1662 // Copy borrowed samples back to the |sync_buffer_|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001663 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001664 if (length < borrowed_samples_per_channel) {
1665 // This destroys the beginning of the buffer, but will not cause any
1666 // problems.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001667 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001668 sync_buffer_->Size() -
1669 borrowed_samples_per_channel);
1670 sync_buffer_->PushFrontZeros(borrowed_samples_per_channel - length);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001671 algorithm_buffer_->PopFront(length);
1672 assert(algorithm_buffer_->Empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001673 } else {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001674 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001675 borrowed_samples_per_channel,
1676 sync_buffer_->Size() -
1677 borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001678 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001679 }
1680 }
1681
1682 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1683 if (speech_type == AudioDecoder::kComfortNoise) {
1684 last_mode_ = kModeCodecInternalCng;
1685 }
1686 if (!play_dtmf) {
1687 dtmf_tone_generator_->Reset();
1688 }
1689 expand_->Reset();
1690 return 0;
1691}
1692
1693int NetEqImpl::DoPreemptiveExpand(int16_t* decoded_buffer,
1694 size_t decoded_length,
1695 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001696 bool play_dtmf) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001697 const size_t required_samples =
1698 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001699 size_t num_channels = algorithm_buffer_->Channels();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001700 size_t borrowed_samples_per_channel = 0;
1701 size_t old_borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001702 size_t decoded_length_per_channel = decoded_length / num_channels;
1703 if (decoded_length_per_channel < required_samples) {
1704 // Must move data from the |sync_buffer_| in order to get 30 ms.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001705 borrowed_samples_per_channel =
1706 required_samples - decoded_length_per_channel;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001707 // Calculate how many of these were already played out.
Peter Kastingf045e4d2015-06-10 21:15:38 -07001708 old_borrowed_samples_per_channel =
Peter Kastingdce40cf2015-08-24 14:52:23 -07001709 (borrowed_samples_per_channel > sync_buffer_->FutureLength()) ?
1710 (borrowed_samples_per_channel - sync_buffer_->FutureLength()) : 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001711 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1712 decoded_buffer,
1713 sizeof(int16_t) * decoded_length);
1714 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1715 decoded_buffer);
1716 decoded_length = required_samples * num_channels;
1717 }
1718
Peter Kastingdce40cf2015-08-24 14:52:23 -07001719 size_t samples_added;
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001720 PreemptiveExpand::ReturnCodes return_code = preemptive_expand_->Process(
Peter Kastingdce40cf2015-08-24 14:52:23 -07001721 decoded_buffer, decoded_length,
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001722 old_borrowed_samples_per_channel,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001723 algorithm_buffer_.get(), &samples_added);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001724 stats_.PreemptiveExpandedSamples(samples_added);
1725 switch (return_code) {
1726 case PreemptiveExpand::kSuccess:
1727 last_mode_ = kModePreemptiveExpandSuccess;
1728 break;
1729 case PreemptiveExpand::kSuccessLowEnergy:
1730 last_mode_ = kModePreemptiveExpandLowEnergy;
1731 break;
1732 case PreemptiveExpand::kNoStretch:
1733 last_mode_ = kModePreemptiveExpandFail;
1734 break;
1735 case PreemptiveExpand::kError:
1736 // TODO(hlundin): Map to kModeError instead?
1737 last_mode_ = kModePreemptiveExpandFail;
1738 return kPreemptiveExpandError;
1739 }
1740
1741 if (borrowed_samples_per_channel > 0) {
1742 // Copy borrowed samples back to the |sync_buffer_|.
1743 sync_buffer_->ReplaceAtIndex(
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001744 *algorithm_buffer_, borrowed_samples_per_channel,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001745 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001746 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001747 }
1748
1749 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1750 if (speech_type == AudioDecoder::kComfortNoise) {
1751 last_mode_ = kModeCodecInternalCng;
1752 }
1753 if (!play_dtmf) {
1754 dtmf_tone_generator_->Reset();
1755 }
1756 expand_->Reset();
1757 return 0;
1758}
1759
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001760int NetEqImpl::DoRfc3389Cng(PacketList* packet_list, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001761 if (!packet_list->empty()) {
1762 // Must have exactly one SID frame at this point.
1763 assert(packet_list->size() == 1);
ossua73f6c92016-10-24 08:25:28 -07001764 const Packet& packet = packet_list->front();
1765 if (!decoder_database_->IsComfortNoise(packet.payload_type)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001766 RTC_LOG(LS_ERROR) << "Trying to decode non-CNG payload as CNG.";
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001767 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001768 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001769 if (comfort_noise_->UpdateParameters(packet) ==
1770 ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001771 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001772 return -comfort_noise_->internal_error_code();
1773 }
1774 }
1775 int cn_return = comfort_noise_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001776 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001777 expand_->Reset();
1778 last_mode_ = kModeRfc3389Cng;
1779 if (!play_dtmf) {
1780 dtmf_tone_generator_->Reset();
1781 }
1782 if (cn_return == ComfortNoise::kInternalError) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001783 RTC_LOG(LS_WARNING) << "Comfort noise generator returned error code: "
1784 << comfort_noise_->internal_error_code();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001785 return kComfortNoiseErrorCode;
1786 } else if (cn_return == ComfortNoise::kUnknownPayloadType) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001787 return kUnknownRtpPayloadType;
1788 }
1789 return 0;
1790}
1791
minyuel6d92bf52015-09-23 15:20:39 +02001792void NetEqImpl::DoCodecInternalCng(const int16_t* decoded_buffer,
1793 size_t decoded_length) {
1794 RTC_DCHECK(normal_.get());
1795 RTC_DCHECK(mute_factor_array_.get());
1796 normal_->Process(decoded_buffer, decoded_length, last_mode_,
1797 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001798 last_mode_ = kModeCodecInternalCng;
1799 expand_->Reset();
1800}
1801
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001802int NetEqImpl::DoDtmf(const DtmfEvent& dtmf_event, bool* play_dtmf) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001803 // This block of the code and the block further down, handling |dtmf_switch|
1804 // are commented out. Otherwise playing out-of-band DTMF would fail in VoE
1805 // test, DtmfTest.ManualSuccessfullySendsOutOfBandTelephoneEvents. This is
1806 // equivalent to |dtmf_switch| always be false.
1807 //
1808 // See http://webrtc-codereview.appspot.com/1195004/ for discussion
1809 // On this issue. This change might cause some glitches at the point of
1810 // switch from audio to DTMF. Issue 1545 is filed to track this.
1811 //
1812 // bool dtmf_switch = false;
1813 // if ((last_mode_ != kModeDtmf) && dtmf_tone_generator_->initialized()) {
1814 // // Special case; see below.
1815 // // We must catch this before calling Generate, since |initialized| is
1816 // // modified in that call.
1817 // dtmf_switch = true;
1818 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001819
1820 int dtmf_return_value = 0;
1821 if (!dtmf_tone_generator_->initialized()) {
1822 // Initialize if not already done.
1823 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1824 dtmf_event.volume);
1825 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001826
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001827 if (dtmf_return_value == 0) {
1828 // Generate DTMF signal.
1829 dtmf_return_value = dtmf_tone_generator_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001830 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001831 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001832
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001833 if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001834 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001835 return dtmf_return_value;
1836 }
1837
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001838 // if (dtmf_switch) {
1839 // // This is the special case where the previous operation was DTMF
1840 // // overdub, but the current instruction is "regular" DTMF. We must make
1841 // // sure that the DTMF does not have any discontinuities. The first DTMF
1842 // // sample that we generate now must be played out immediately, therefore
1843 // // it must be copied to the speech buffer.
1844 // // TODO(hlundin): This code seems incorrect. (Legacy.) Write test and
1845 // // verify correct operation.
1846 // assert(false);
1847 // // Must generate enough data to replace all of the |sync_buffer_|
1848 // // "future".
1849 // int required_length = sync_buffer_->FutureLength();
1850 // assert(dtmf_tone_generator_->initialized());
1851 // dtmf_return_value = dtmf_tone_generator_->Generate(required_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001852 // algorithm_buffer_);
1853 // assert((size_t) required_length == algorithm_buffer_->Size());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001854 // if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001855 // algorithm_buffer_->Zeros(output_size_samples_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001856 // return dtmf_return_value;
1857 // }
1858 //
1859 // // Overwrite the "future" part of the speech buffer with the new DTMF
1860 // // data.
1861 // // TODO(hlundin): It seems that this overwriting has gone lost.
1862 // // Not adapted for multi-channel yet.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001863 // assert(algorithm_buffer_->Channels() == 1);
1864 // if (algorithm_buffer_->Channels() != 1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001865 // RTC_LOG(LS_WARNING) << "DTMF not supported for more than one channel";
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001866 // return kStereoNotSupported;
1867 // }
1868 // // Shuffle the remaining data to the beginning of algorithm buffer.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001869 // algorithm_buffer_->PopFront(sync_buffer_->FutureLength());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001870 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001871
Peter Kastingb7e50542015-06-11 12:55:50 -07001872 sync_buffer_->IncreaseEndTimestamp(
1873 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001874 expand_->Reset();
1875 last_mode_ = kModeDtmf;
1876
1877 // Set to false because the DTMF is already in the algorithm buffer.
1878 *play_dtmf = false;
1879 return 0;
1880}
1881
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001882void NetEqImpl::DoAlternativePlc(bool increase_timestamp) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001883 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001884 size_t length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001885 if (decoder && decoder->HasDecodePlc()) {
1886 // Use the decoder's packet-loss concealment.
1887 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1888 int16_t decoded_buffer[kMaxFrameSize];
1889 length = decoder->DecodePlc(1, decoded_buffer);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001890 if (length > 0)
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001891 algorithm_buffer_->PushBackInterleaved(decoded_buffer, length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001892 } else {
1893 // Do simple zero-stuffing.
1894 length = output_size_samples_;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001895 algorithm_buffer_->Zeros(length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001896 // By not advancing the timestamp, NetEq inserts samples.
1897 stats_.AddZeros(length);
1898 }
1899 if (increase_timestamp) {
Peter Kastingb7e50542015-06-11 12:55:50 -07001900 sync_buffer_->IncreaseEndTimestamp(static_cast<uint32_t>(length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001901 }
1902 expand_->Reset();
1903}
1904
1905int NetEqImpl::DtmfOverdub(const DtmfEvent& dtmf_event, size_t num_channels,
1906 int16_t* output) const {
1907 size_t out_index = 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001908 size_t overdub_length = output_size_samples_; // Default value.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001909
1910 if (sync_buffer_->dtmf_index() > sync_buffer_->next_index()) {
1911 // Special operation for transition from "DTMF only" to "DTMF overdub".
1912 out_index = std::min(
1913 sync_buffer_->dtmf_index() - sync_buffer_->next_index(),
Peter Kastingdce40cf2015-08-24 14:52:23 -07001914 output_size_samples_);
1915 overdub_length = output_size_samples_ - out_index;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001916 }
1917
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001918 AudioMultiVector dtmf_output(num_channels);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001919 int dtmf_return_value = 0;
1920 if (!dtmf_tone_generator_->initialized()) {
1921 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1922 dtmf_event.volume);
1923 }
1924 if (dtmf_return_value == 0) {
1925 dtmf_return_value = dtmf_tone_generator_->Generate(overdub_length,
1926 &dtmf_output);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001927 assert(overdub_length == dtmf_output.Size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001928 }
1929 dtmf_output.ReadInterleaved(overdub_length, &output[out_index]);
1930 return dtmf_return_value < 0 ? dtmf_return_value : 0;
1931}
1932
Peter Kastingdce40cf2015-08-24 14:52:23 -07001933int NetEqImpl::ExtractPackets(size_t required_samples,
1934 PacketList* packet_list) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001935 bool first_packet = true;
1936 uint8_t prev_payload_type = 0;
1937 uint32_t prev_timestamp = 0;
1938 uint16_t prev_sequence_number = 0;
1939 bool next_packet_available = false;
1940
ossu7a377612016-10-18 04:06:13 -07001941 const Packet* next_packet = packet_buffer_->PeekNextPacket();
1942 RTC_DCHECK(next_packet);
1943 if (!next_packet) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001944 RTC_LOG(LS_ERROR) << "Packet buffer unexpectedly empty.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001945 return -1;
1946 }
ossu7a377612016-10-18 04:06:13 -07001947 uint32_t first_timestamp = next_packet->timestamp;
ossu61a208b2016-09-20 01:38:00 -07001948 size_t extracted_samples = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001949
1950 // Packet extraction loop.
1951 do {
ossu7a377612016-10-18 04:06:13 -07001952 timestamp_ = next_packet->timestamp;
ossua73f6c92016-10-24 08:25:28 -07001953 rtc::Optional<Packet> packet = packet_buffer_->GetNextPacket();
ossu7a377612016-10-18 04:06:13 -07001954 // |next_packet| may be invalid after the |packet_buffer_| operation.
ossua73f6c92016-10-24 08:25:28 -07001955 next_packet = nullptr;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001956 if (!packet) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001957 RTC_LOG(LS_ERROR) << "Should always be able to extract a packet here";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001958 assert(false); // Should always be able to extract a packet here.
1959 return -1;
1960 }
Gustaf Ullbergb0a02072017-10-02 12:00:34 +02001961 const uint64_t waiting_time_ms = packet->waiting_time->ElapsedMs();
1962 stats_.StoreWaitingTime(waiting_time_ms);
ossu61a208b2016-09-20 01:38:00 -07001963 RTC_DCHECK(!packet->empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001964
1965 if (first_packet) {
1966 first_packet = false;
henrik.lundin48ed9302015-10-29 05:36:24 -07001967 if (nack_enabled_) {
1968 RTC_DCHECK(nack_);
1969 // TODO(henrik.lundin): Should we update this for all decoded packets?
ossu7a377612016-10-18 04:06:13 -07001970 nack_->UpdateLastDecodedPacket(packet->sequence_number,
1971 packet->timestamp);
henrik.lundin48ed9302015-10-29 05:36:24 -07001972 }
ossu7a377612016-10-18 04:06:13 -07001973 prev_sequence_number = packet->sequence_number;
1974 prev_timestamp = packet->timestamp;
1975 prev_payload_type = packet->payload_type;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001976 }
1977
ossucafb4972017-01-02 07:00:50 -08001978 const bool has_cng_packet =
1979 decoder_database_->IsComfortNoise(packet->payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001980 // Store number of extracted samples.
ossu61a208b2016-09-20 01:38:00 -07001981 size_t packet_duration = 0;
1982 if (packet->frame) {
1983 packet_duration = packet->frame->Duration();
ossua70695a2016-09-22 02:06:28 -07001984 // TODO(ossu): Is this the correct way to track Opus FEC packets?
1985 if (packet->priority.codec_level > 0) {
kwibergd3edd772017-03-01 18:52:48 -08001986 stats_.SecondaryDecodedSamples(
1987 rtc::dchecked_cast<int>(packet_duration));
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001988 }
ossucafb4972017-01-02 07:00:50 -08001989 } else if (!has_cng_packet) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001990 RTC_LOG(LS_WARNING) << "Unknown payload type "
1991 << static_cast<int>(packet->payload_type);
ossu61a208b2016-09-20 01:38:00 -07001992 RTC_NOTREACHED();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001993 }
ossu61a208b2016-09-20 01:38:00 -07001994
1995 if (packet_duration == 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001996 // Decoder did not return a packet duration. Assume that the packet
1997 // contains the same number of samples as the previous one.
ossu61a208b2016-09-20 01:38:00 -07001998 packet_duration = decoder_frame_length_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001999 }
ossu7a377612016-10-18 04:06:13 -07002000 extracted_samples = packet->timestamp - first_timestamp + packet_duration;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002001
Gustaf Ullbergb0a02072017-10-02 12:00:34 +02002002 stats_.JitterBufferDelay(extracted_samples, waiting_time_ms);
2003
ossua73f6c92016-10-24 08:25:28 -07002004 packet_list->push_back(std::move(*packet)); // Store packet in list.
Oskar Sundbom12ab00b2017-11-16 15:31:38 +01002005 packet = rtc::nullopt; // Ensure it's never used after the move.
ossua73f6c92016-10-24 08:25:28 -07002006
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002007 // Check what packet is available next.
ossu7a377612016-10-18 04:06:13 -07002008 next_packet = packet_buffer_->PeekNextPacket();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002009 next_packet_available = false;
ossucafb4972017-01-02 07:00:50 -08002010 if (next_packet && prev_payload_type == next_packet->payload_type &&
2011 !has_cng_packet) {
ossu7a377612016-10-18 04:06:13 -07002012 int16_t seq_no_diff = next_packet->sequence_number - prev_sequence_number;
2013 size_t ts_diff = next_packet->timestamp - prev_timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002014 if (seq_no_diff == 1 ||
2015 (seq_no_diff == 0 && ts_diff == decoder_frame_length_)) {
2016 // The next sequence number is available, or the next part of a packet
2017 // that was split into pieces upon insertion.
2018 next_packet_available = true;
2019 }
ossu7a377612016-10-18 04:06:13 -07002020 prev_sequence_number = next_packet->sequence_number;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002021 }
ossu61a208b2016-09-20 01:38:00 -07002022 } while (extracted_samples < required_samples && next_packet_available);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002023
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00002024 if (extracted_samples > 0) {
2025 // Delete old packets only when we are going to decode something. Otherwise,
2026 // we could end up in the situation where we never decode anything, since
2027 // all incoming packets are considered too old but the buffer will also
2028 // never be flooded and flushed.
minyue-webrtcfae474c2017-07-05 11:17:40 +02002029 packet_buffer_->DiscardAllOldPackets(timestamp_, &stats_);
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00002030 }
2031
kwibergd3edd772017-03-01 18:52:48 -08002032 return rtc::dchecked_cast<int>(extracted_samples);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002033}
2034
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002035void NetEqImpl::UpdatePlcComponents(int fs_hz, size_t channels) {
2036 // Delete objects and create new ones.
2037 expand_.reset(expand_factory_->Create(background_noise_.get(),
2038 sync_buffer_.get(), &random_vector_,
Henrik Lundinbef77e22015-08-18 14:58:09 +02002039 &stats_, fs_hz, channels));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002040 merge_.reset(new Merge(fs_hz, channels, expand_.get(), sync_buffer_.get()));
2041}
2042
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002043void NetEqImpl::SetSampleRateAndChannels(int fs_hz, size_t channels) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002044 RTC_LOG(LS_VERBOSE) << "SetSampleRateAndChannels " << fs_hz << " "
2045 << channels;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002046 // TODO(hlundin): Change to an enumerator and skip assert.
2047 assert(fs_hz == 8000 || fs_hz == 16000 || fs_hz == 32000 || fs_hz == 48000);
2048 assert(channels > 0);
2049
2050 fs_hz_ = fs_hz;
2051 fs_mult_ = fs_hz / 8000;
Peter Kastingdce40cf2015-08-24 14:52:23 -07002052 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002053 decoder_frame_length_ = 3 * output_size_samples_; // Initialize to 30ms.
2054
2055 last_mode_ = kModeNormal;
2056
2057 // Create a new array of mute factors and set all to 1.
2058 mute_factor_array_.reset(new int16_t[channels]);
2059 for (size_t i = 0; i < channels; ++i) {
2060 mute_factor_array_[i] = 16384; // 1.0 in Q14.
2061 }
2062
ossu97ba30e2016-04-25 07:55:58 -07002063 ComfortNoiseDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02002064 if (cng_decoder)
2065 cng_decoder->Reset();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002066
2067 // Reinit post-decode VAD with new sample rate.
2068 assert(vad_.get()); // Cannot be NULL here.
2069 vad_->Init();
2070
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002071 // Delete algorithm buffer and create a new one.
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00002072 algorithm_buffer_.reset(new AudioMultiVector(channels));
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002073
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002074 // Delete sync buffer and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002075 sync_buffer_.reset(new SyncBuffer(channels, kSyncBufferSize * fs_mult_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002076
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00002077 // Delete BackgroundNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002078 background_noise_.reset(new BackgroundNoise(channels));
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00002079 background_noise_->set_mode(background_noise_mode_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002080
2081 // Reset random vector.
2082 random_vector_.Reset();
2083
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002084 UpdatePlcComponents(fs_hz, channels);
2085
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002086 // Move index so that we create a small set of future samples (all 0).
2087 sync_buffer_->set_next_index(sync_buffer_->next_index() -
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002088 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002089
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002090 normal_.reset(new Normal(fs_hz, decoder_database_.get(), *background_noise_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002091 expand_.get()));
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +00002092 accelerate_.reset(
2093 accelerate_factory_->Create(fs_hz, channels, *background_noise_));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002094 preemptive_expand_.reset(preemptive_expand_factory_->Create(
Peter Kastingdce40cf2015-08-24 14:52:23 -07002095 fs_hz, channels, *background_noise_, expand_->overlap_length()));
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002096
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002097 // Delete ComfortNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002098 comfort_noise_.reset(new ComfortNoise(fs_hz, decoder_database_.get(),
2099 sync_buffer_.get()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002100
2101 // Verify that |decoded_buffer_| is long enough.
2102 if (decoded_buffer_length_ < kMaxFrameSize * channels) {
2103 // Reallocate to larger size.
2104 decoded_buffer_length_ = kMaxFrameSize * channels;
2105 decoded_buffer_.reset(new int16_t[decoded_buffer_length_]);
2106 }
2107
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002108 // Create DecisionLogic if it is not created yet, then communicate new sample
2109 // rate and output size to DecisionLogic object.
2110 if (!decision_logic_.get()) {
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002111 CreateDecisionLogic();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002112 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002113 decision_logic_->SetSampleRate(fs_hz_, output_size_samples_);
2114}
2115
henrik.lundin55480f52016-03-08 02:37:57 -08002116NetEqImpl::OutputType NetEqImpl::LastOutputType() {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002117 assert(vad_.get());
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002118 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002119 if (last_mode_ == kModeCodecInternalCng || last_mode_ == kModeRfc3389Cng) {
henrik.lundin55480f52016-03-08 02:37:57 -08002120 return OutputType::kCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002121 } else if (last_mode_ == kModeExpand && expand_->MuteFactor(0) == 0) {
2122 // Expand mode has faded down to background noise only (very long expand).
henrik.lundin55480f52016-03-08 02:37:57 -08002123 return OutputType::kPLCCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002124 } else if (last_mode_ == kModeExpand) {
henrik.lundin55480f52016-03-08 02:37:57 -08002125 return OutputType::kPLC;
wu@webrtc.org24301a62013-12-13 19:17:43 +00002126 } else if (vad_->running() && !vad_->active_speech()) {
henrik.lundin55480f52016-03-08 02:37:57 -08002127 return OutputType::kVadPassive;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002128 } else {
henrik.lundin55480f52016-03-08 02:37:57 -08002129 return OutputType::kNormalSpeech;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002130 }
2131}
2132
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002133void NetEqImpl::CreateDecisionLogic() {
Henrik Lundin47b17dc2016-05-10 10:20:59 +02002134 decision_logic_.reset(DecisionLogic::Create(
2135 fs_hz_, output_size_samples_, playout_mode_, decoder_database_.get(),
2136 *packet_buffer_.get(), delay_manager_.get(), buffer_level_filter_.get(),
2137 tick_timer_.get()));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002138}
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002139} // namespace webrtc