blob: 4e780c3f2fce303de0feddf70ecedf503e7ac723 [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"
Jonas Olssonabbe8412018-04-03 13:40:05 +020049#include "rtc_base/strings/audio_format_to_string.h"
Karl Wiberg80ba3332018-02-05 10:33:35 +010050#include "rtc_base/system/fallthrough.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020051#include "rtc_base/trace_event.h"
Henrik Lundin18036282017-11-02 12:09:06 +010052#include "system_wrappers/include/field_trial.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000053
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000054namespace webrtc {
55
ossue3525782016-05-25 07:37:43 -070056NetEqImpl::Dependencies::Dependencies(
57 const NetEq::Config& config,
58 const rtc::scoped_refptr<AudioDecoderFactory>& decoder_factory)
henrik.lundin1d9061e2016-04-26 12:19:34 -070059 : tick_timer(new TickTimer),
60 buffer_level_filter(new BufferLevelFilter),
Karl Wiberg08126342018-03-20 19:18:55 +010061 decoder_database(
62 new DecoderDatabase(decoder_factory, config.codec_pair_id)),
henrik.lundinf3933702016-04-28 01:53:52 -070063 delay_peak_detector(new DelayPeakDetector(tick_timer.get())),
henrik.lundin1d9061e2016-04-26 12:19:34 -070064 delay_manager(new DelayManager(config.max_packets_in_buffer,
henrik.lundin8f8c96d2016-04-28 23:19:20 -070065 delay_peak_detector.get(),
66 tick_timer.get())),
henrik.lundin1d9061e2016-04-26 12:19:34 -070067 dtmf_buffer(new DtmfBuffer(config.sample_rate_hz)),
68 dtmf_tone_generator(new DtmfToneGenerator),
69 packet_buffer(
70 new PacketBuffer(config.max_packets_in_buffer, tick_timer.get())),
ossua70695a2016-09-22 02:06:28 -070071 red_payload_splitter(new RedPayloadSplitter),
henrik.lundin1d9061e2016-04-26 12:19:34 -070072 timestamp_scaler(new TimestampScaler(*decoder_database)),
73 accelerate_factory(new AccelerateFactory),
74 expand_factory(new ExpandFactory),
75 preemptive_expand_factory(new PreemptiveExpandFactory) {}
76
77NetEqImpl::Dependencies::~Dependencies() = default;
78
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +000079NetEqImpl::NetEqImpl(const NetEq::Config& config,
henrik.lundin1d9061e2016-04-26 12:19:34 -070080 Dependencies&& deps,
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +000081 bool create_components)
henrik.lundin1d9061e2016-04-26 12:19:34 -070082 : tick_timer_(std::move(deps.tick_timer)),
83 buffer_level_filter_(std::move(deps.buffer_level_filter)),
84 decoder_database_(std::move(deps.decoder_database)),
85 delay_manager_(std::move(deps.delay_manager)),
86 delay_peak_detector_(std::move(deps.delay_peak_detector)),
87 dtmf_buffer_(std::move(deps.dtmf_buffer)),
88 dtmf_tone_generator_(std::move(deps.dtmf_tone_generator)),
89 packet_buffer_(std::move(deps.packet_buffer)),
ossua70695a2016-09-22 02:06:28 -070090 red_payload_splitter_(std::move(deps.red_payload_splitter)),
henrik.lundin1d9061e2016-04-26 12:19:34 -070091 timestamp_scaler_(std::move(deps.timestamp_scaler)),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000092 vad_(new PostDecodeVad()),
henrik.lundin1d9061e2016-04-26 12:19:34 -070093 expand_factory_(std::move(deps.expand_factory)),
94 accelerate_factory_(std::move(deps.accelerate_factory)),
95 preemptive_expand_factory_(std::move(deps.preemptive_expand_factory)),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000096 last_mode_(kModeNormal),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000097 decoded_buffer_length_(kMaxFrameSize),
98 decoded_buffer_(new int16_t[decoded_buffer_length_]),
99 playout_timestamp_(0),
100 new_codec_(false),
101 timestamp_(0),
102 reset_decoder_(false),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000103 ssrc_(0),
104 first_packet_(true),
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +0000105 background_noise_mode_(config.background_noise_mode),
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000106 playout_mode_(config.playout_mode),
Henrik Lundincf808d22015-05-27 14:33:29 +0200107 enable_fast_accelerate_(config.enable_fast_accelerate),
henrik.lundin7a926812016-05-12 13:51:28 -0700108 nack_enabled_(false),
Henrik Lundin4f2a4a12018-01-26 17:32:56 +0100109 enable_muted_state_(config.enable_muted_state) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100110 RTC_LOG(LS_INFO) << "NetEq config: " << config.ToString();
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +0000111 int fs = config.sample_rate_hz;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000112 if (fs != 8000 && fs != 16000 && fs != 32000 && fs != 48000) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100113 RTC_LOG(LS_ERROR) << "Sample rate " << fs << " Hz not supported. "
114 << "Changing to 8000 Hz.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000115 fs = 8000;
116 }
henrik.lundin1d9061e2016-04-26 12:19:34 -0700117 delay_manager_->SetMaximumDelay(config.max_delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000118 fs_hz_ = fs;
119 fs_mult_ = fs / 8000;
henrik.lundind89814b2015-11-23 06:49:25 -0800120 last_output_sample_rate_hz_ = fs;
Peter Kastingdce40cf2015-08-24 14:52:23 -0700121 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000122 decoder_frame_length_ = 3 * output_size_samples_;
123 WebRtcSpl_Init();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000124 if (create_components) {
125 SetSampleRateAndChannels(fs, 1); // Default is 1 channel.
126 }
henrik.lundin9bc26672015-11-02 03:25:57 -0800127 RTC_DCHECK(!vad_->enabled());
128 if (config.enable_post_decode_vad) {
129 vad_->Enable();
130 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000131}
132
Henrik Lundind67a2192015-08-03 12:54:37 +0200133NetEqImpl::~NetEqImpl() = default;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000134
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200135int NetEqImpl::InsertPacket(const RTPHeader& rtp_header,
kwibergee2bac22015-11-11 10:34:00 -0800136 rtc::ArrayView<const uint8_t> payload,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000137 uint32_t receive_timestamp) {
kwibergac554ee2016-09-02 00:39:33 -0700138 rtc::MsanCheckInitialized(payload);
henrik.lundina689b442015-12-17 03:50:05 -0800139 TRACE_EVENT0("webrtc", "NetEqImpl::InsertPacket");
Tommi9090e0b2016-01-20 13:39:36 +0100140 rtc::CritScope lock(&crit_sect_);
Henrik Lundinc417d9e2017-06-14 12:29:03 +0200141 if (InsertPacketInternal(rtp_header, payload, receive_timestamp) != 0) {
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000142 return kFail;
143 }
144 return kOK;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000145}
146
henrik.lundinb8c55b12017-05-10 07:38:01 -0700147void NetEqImpl::InsertEmptyPacket(const RTPHeader& /*rtp_header*/) {
148 // TODO(henrik.lundin) Handle NACK as well. This will make use of the
149 // rtp_header parameter.
150 // https://bugs.chromium.org/p/webrtc/issues/detail?id=7611
151 rtc::CritScope lock(&crit_sect_);
152 delay_manager_->RegisterEmptyPacket();
153}
154
henrik.lundin500c04b2016-03-08 02:36:04 -0800155namespace {
156void SetAudioFrameActivityAndType(bool vad_enabled,
henrik.lundin55480f52016-03-08 02:37:57 -0800157 NetEqImpl::OutputType type,
henrik.lundin500c04b2016-03-08 02:36:04 -0800158 AudioFrame::VADActivity last_vad_activity,
159 AudioFrame* audio_frame) {
160 switch (type) {
henrik.lundin55480f52016-03-08 02:37:57 -0800161 case NetEqImpl::OutputType::kNormalSpeech: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800162 audio_frame->speech_type_ = AudioFrame::kNormalSpeech;
163 audio_frame->vad_activity_ = AudioFrame::kVadActive;
164 break;
165 }
henrik.lundin55480f52016-03-08 02:37:57 -0800166 case NetEqImpl::OutputType::kVadPassive: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800167 // This should only be reached if the VAD is enabled.
168 RTC_DCHECK(vad_enabled);
169 audio_frame->speech_type_ = AudioFrame::kNormalSpeech;
170 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
171 break;
172 }
henrik.lundin55480f52016-03-08 02:37:57 -0800173 case NetEqImpl::OutputType::kCNG: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800174 audio_frame->speech_type_ = AudioFrame::kCNG;
175 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
176 break;
177 }
henrik.lundin55480f52016-03-08 02:37:57 -0800178 case NetEqImpl::OutputType::kPLC: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800179 audio_frame->speech_type_ = AudioFrame::kPLC;
180 audio_frame->vad_activity_ = last_vad_activity;
181 break;
182 }
henrik.lundin55480f52016-03-08 02:37:57 -0800183 case NetEqImpl::OutputType::kPLCCNG: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800184 audio_frame->speech_type_ = AudioFrame::kPLCCNG;
185 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
186 break;
187 }
188 default:
189 RTC_NOTREACHED();
190 }
191 if (!vad_enabled) {
192 // Always set kVadUnknown when receive VAD is inactive.
193 audio_frame->vad_activity_ = AudioFrame::kVadUnknown;
194 }
195}
henrik.lundinbc89de32016-03-08 05:20:14 -0800196} // namespace
henrik.lundin500c04b2016-03-08 02:36:04 -0800197
henrik.lundin7a926812016-05-12 13:51:28 -0700198int NetEqImpl::GetAudio(AudioFrame* audio_frame, bool* muted) {
henrik.lundine1ca1672016-01-08 03:50:08 -0800199 TRACE_EVENT0("webrtc", "NetEqImpl::GetAudio");
Tommi9090e0b2016-01-20 13:39:36 +0100200 rtc::CritScope lock(&crit_sect_);
Henrik Lundinc417d9e2017-06-14 12:29:03 +0200201 if (GetAudioInternal(audio_frame, muted) != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000202 return kFail;
203 }
henrik.lundin5fac3f02016-08-24 11:18:49 -0700204 RTC_DCHECK_EQ(
205 audio_frame->sample_rate_hz_,
kwibergd3edd772017-03-01 18:52:48 -0800206 rtc::dchecked_cast<int>(audio_frame->samples_per_channel_ * 100));
henrik.lundina4491072017-07-06 05:23:53 -0700207 RTC_DCHECK_EQ(*muted, audio_frame->muted());
henrik.lundin500c04b2016-03-08 02:36:04 -0800208 SetAudioFrameActivityAndType(vad_->enabled(), LastOutputType(),
209 last_vad_activity_, audio_frame);
210 last_vad_activity_ = audio_frame->vad_activity_;
henrik.lundin6d8e0112016-03-04 10:34:21 -0800211 last_output_sample_rate_hz_ = audio_frame->sample_rate_hz_;
henrik.lundind89814b2015-11-23 06:49:25 -0800212 RTC_DCHECK(last_output_sample_rate_hz_ == 8000 ||
213 last_output_sample_rate_hz_ == 16000 ||
214 last_output_sample_rate_hz_ == 32000 ||
215 last_output_sample_rate_hz_ == 48000)
216 << "Unexpected sample rate " << last_output_sample_rate_hz_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000217 return kOK;
218}
219
kwiberg1c07c702017-03-27 07:15:49 -0700220void NetEqImpl::SetCodecs(const std::map<int, SdpAudioFormat>& codecs) {
221 rtc::CritScope lock(&crit_sect_);
222 const std::vector<int> changed_payload_types =
223 decoder_database_->SetCodecs(codecs);
224 for (const int pt : changed_payload_types) {
minyue-webrtcfae474c2017-07-05 11:17:40 +0200225 packet_buffer_->DiscardPacketsWithPayloadType(pt, &stats_);
kwiberg1c07c702017-03-27 07:15:49 -0700226 }
227}
228
kwibergee1879c2015-10-29 06:20:28 -0700229int NetEqImpl::RegisterPayloadType(NetEqDecoder codec,
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800230 const std::string& name,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000231 uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100232 rtc::CritScope lock(&crit_sect_);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100233 RTC_LOG(LS_VERBOSE) << "RegisterPayloadType "
234 << static_cast<int>(rtp_payload_type) << " "
235 << static_cast<int>(codec);
Henrik Lundinc417d9e2017-06-14 12:29:03 +0200236 if (decoder_database_->RegisterPayload(rtp_payload_type, codec, name) !=
237 DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000238 return kFail;
239 }
240 return kOK;
241}
242
243int NetEqImpl::RegisterExternalDecoder(AudioDecoder* decoder,
kwibergee1879c2015-10-29 06:20:28 -0700244 NetEqDecoder codec,
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800245 const std::string& codec_name,
kwiberg342f7402016-06-16 03:18:00 -0700246 uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100247 rtc::CritScope lock(&crit_sect_);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100248 RTC_LOG(LS_VERBOSE) << "RegisterExternalDecoder "
249 << static_cast<int>(rtp_payload_type) << " "
250 << static_cast<int>(codec);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000251 if (!decoder) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100252 RTC_LOG(LS_ERROR) << "Cannot register external decoder with NULL pointer";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000253 assert(false);
254 return kFail;
255 }
Henrik Lundinc417d9e2017-06-14 12:29:03 +0200256 if (decoder_database_->InsertExternal(rtp_payload_type, codec, codec_name,
257 decoder) != DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000258 return kFail;
259 }
260 return kOK;
261}
262
kwiberg5adaf732016-10-04 09:33:27 -0700263bool NetEqImpl::RegisterPayloadType(int rtp_payload_type,
264 const SdpAudioFormat& audio_format) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100265 RTC_LOG(LS_VERBOSE) << "NetEqImpl::RegisterPayloadType: payload type "
Jonas Olssonabbe8412018-04-03 13:40:05 +0200266 << rtp_payload_type << ", codec "
267 << rtc::ToString(audio_format);
kwiberg5adaf732016-10-04 09:33:27 -0700268 rtc::CritScope lock(&crit_sect_);
Henrik Lundinc417d9e2017-06-14 12:29:03 +0200269 return decoder_database_->RegisterPayload(rtp_payload_type, audio_format) ==
270 DecoderDatabase::kOK;
kwiberg5adaf732016-10-04 09:33:27 -0700271}
272
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000273int NetEqImpl::RemovePayloadType(uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100274 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000275 int ret = decoder_database_->Remove(rtp_payload_type);
Henrik Lundinc417d9e2017-06-14 12:29:03 +0200276 if (ret == DecoderDatabase::kOK || ret == DecoderDatabase::kDecoderNotFound) {
minyue-webrtcfae474c2017-07-05 11:17:40 +0200277 packet_buffer_->DiscardPacketsWithPayloadType(rtp_payload_type, &stats_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000278 return kOK;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000279 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000280 return kFail;
281}
282
kwiberg6b19b562016-09-20 04:02:25 -0700283void NetEqImpl::RemoveAllPayloadTypes() {
284 rtc::CritScope lock(&crit_sect_);
285 decoder_database_->RemoveAll();
286}
287
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000288bool NetEqImpl::SetMinimumDelay(int delay_ms) {
Tommi9090e0b2016-01-20 13:39:36 +0100289 rtc::CritScope lock(&crit_sect_);
Gustaf Ullberg48d96c02017-09-15 13:59:52 +0200290 if (delay_ms >= 0 && delay_ms <= 10000) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000291 assert(delay_manager_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000292 return delay_manager_->SetMinimumDelay(delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000293 }
294 return false;
295}
296
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000297bool NetEqImpl::SetMaximumDelay(int delay_ms) {
Tommi9090e0b2016-01-20 13:39:36 +0100298 rtc::CritScope lock(&crit_sect_);
Gustaf Ullberg48d96c02017-09-15 13:59:52 +0200299 if (delay_ms >= 0 && delay_ms <= 10000) {
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000300 assert(delay_manager_.get());
301 return delay_manager_->SetMaximumDelay(delay_ms);
302 }
303 return false;
304}
305
306int NetEqImpl::LeastRequiredDelayMs() const {
Tommi9090e0b2016-01-20 13:39:36 +0100307 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000308 assert(delay_manager_.get());
309 return delay_manager_->least_required_delay_ms();
310}
311
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200312int NetEqImpl::SetTargetDelay() {
313 return kNotImplemented;
314}
315
Henrik Lundinabbff892017-11-29 09:14:04 +0100316int NetEqImpl::TargetDelayMs() const {
henrik.lundin114c1b32017-04-26 07:47:32 -0700317 rtc::CritScope lock(&crit_sect_);
318 RTC_DCHECK(delay_manager_.get());
319 // The value from TargetLevel() is in number of packets, represented in Q8.
320 const size_t target_delay_samples =
321 (delay_manager_->TargetLevel() * decoder_frame_length_) >> 8;
322 return static_cast<int>(target_delay_samples) /
323 rtc::CheckedDivExact(fs_hz_, 1000);
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200324}
325
henrik.lundin9c3efd02015-08-27 13:12:22 -0700326int NetEqImpl::CurrentDelayMs() const {
Tommi9090e0b2016-01-20 13:39:36 +0100327 rtc::CritScope lock(&crit_sect_);
henrik.lundin9c3efd02015-08-27 13:12:22 -0700328 if (fs_hz_ == 0)
329 return 0;
330 // Sum up the samples in the packet buffer with the future length of the sync
331 // buffer, and divide the sum by the sample rate.
332 const size_t delay_samples =
ossu61a208b2016-09-20 01:38:00 -0700333 packet_buffer_->NumSamplesInBuffer(decoder_frame_length_) +
henrik.lundin9c3efd02015-08-27 13:12:22 -0700334 sync_buffer_->FutureLength();
335 // The division below will truncate.
336 const int delay_ms =
337 static_cast<int>(delay_samples) / rtc::CheckedDivExact(fs_hz_, 1000);
338 return delay_ms;
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200339}
340
henrik.lundinb3f1c5d2016-08-22 15:39:53 -0700341int NetEqImpl::FilteredCurrentDelayMs() const {
342 rtc::CritScope lock(&crit_sect_);
343 // Calculate the filtered packet buffer level in samples. The value from
344 // |buffer_level_filter_| is in number of packets, represented in Q8.
345 const size_t packet_buffer_samples =
346 (buffer_level_filter_->filtered_current_level() *
347 decoder_frame_length_) >>
348 8;
349 // Sum up the filtered packet buffer level with the future length of the sync
350 // buffer, and divide the sum by the sample rate.
351 const size_t delay_samples =
352 packet_buffer_samples + sync_buffer_->FutureLength();
353 // The division below will truncate. The return value is in ms.
354 return static_cast<int>(delay_samples) / rtc::CheckedDivExact(fs_hz_, 1000);
355}
356
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000357// Deprecated.
358// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000359void NetEqImpl::SetPlayoutMode(NetEqPlayoutMode mode) {
Tommi9090e0b2016-01-20 13:39:36 +0100360 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000361 if (mode != playout_mode_) {
362 playout_mode_ = mode;
363 CreateDecisionLogic();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000364 }
365}
366
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000367// Deprecated.
368// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000369NetEqPlayoutMode NetEqImpl::PlayoutMode() const {
Tommi9090e0b2016-01-20 13:39:36 +0100370 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000371 return playout_mode_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000372}
373
374int NetEqImpl::NetworkStatistics(NetEqNetworkStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100375 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000376 assert(decoder_database_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700377 const size_t total_samples_in_buffers =
ossu61a208b2016-09-20 01:38:00 -0700378 packet_buffer_->NumSamplesInBuffer(decoder_frame_length_) +
Peter Kastingdce40cf2015-08-24 14:52:23 -0700379 sync_buffer_->FutureLength();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000380 assert(delay_manager_.get());
381 assert(decision_logic_.get());
Henrik Lundindccfc402017-09-25 12:30:58 +0200382 const int ms_per_packet = rtc::dchecked_cast<int>(
383 decision_logic_->packet_length_samples() / (fs_hz_ / 1000));
384 stats_.PopulateDelayManagerStats(ms_per_packet, *delay_manager_.get(), stats);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000385 stats_.GetNetworkStatistics(fs_hz_, total_samples_in_buffers,
Henrik Lundindccfc402017-09-25 12:30:58 +0200386 decoder_frame_length_, stats);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000387 return 0;
388}
389
Steve Anton2dbc69f2017-08-24 17:15:13 -0700390NetEqLifetimeStatistics NetEqImpl::GetLifetimeStatistics() const {
391 rtc::CritScope lock(&crit_sect_);
392 return stats_.GetLifetimeStatistics();
393}
394
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000395void NetEqImpl::GetRtcpStatistics(RtcpStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100396 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000397 if (stats) {
398 rtcp_.GetStatistics(false, stats);
399 }
400}
401
402void NetEqImpl::GetRtcpStatisticsNoReset(RtcpStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100403 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000404 if (stats) {
405 rtcp_.GetStatistics(true, stats);
406 }
407}
408
409void NetEqImpl::EnableVad() {
Tommi9090e0b2016-01-20 13:39:36 +0100410 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000411 assert(vad_.get());
412 vad_->Enable();
413}
414
415void NetEqImpl::DisableVad() {
Tommi9090e0b2016-01-20 13:39:36 +0100416 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000417 assert(vad_.get());
418 vad_->Disable();
419}
420
henrik.lundin15c51e32016-04-06 08:38:56 -0700421rtc::Optional<uint32_t> NetEqImpl::GetPlayoutTimestamp() const {
Tommi9090e0b2016-01-20 13:39:36 +0100422 rtc::CritScope lock(&crit_sect_);
henrik.lundin0d96ab72016-04-06 12:28:26 -0700423 if (first_packet_ || last_mode_ == kModeRfc3389Cng ||
424 last_mode_ == kModeCodecInternalCng) {
wu@webrtc.org94454b72014-06-05 20:34:08 +0000425 // We don't have a valid RTP timestamp until we have decoded our first
henrik.lundin0d96ab72016-04-06 12:28:26 -0700426 // RTP packet. Also, the RTP timestamp is not accurate while playing CNG,
427 // which is indicated by returning an empty value.
Oskar Sundbom12ab00b2017-11-16 15:31:38 +0100428 return rtc::nullopt;
wu@webrtc.org94454b72014-06-05 20:34:08 +0000429 }
Oskar Sundbom12ab00b2017-11-16 15:31:38 +0100430 return timestamp_scaler_->ToExternal(playout_timestamp_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000431}
432
henrik.lundind89814b2015-11-23 06:49:25 -0800433int NetEqImpl::last_output_sample_rate_hz() const {
Tommi9090e0b2016-01-20 13:39:36 +0100434 rtc::CritScope lock(&crit_sect_);
henrik.lundind89814b2015-11-23 06:49:25 -0800435 return last_output_sample_rate_hz_;
436}
437
kwiberg6f0f6162016-09-20 03:07:46 -0700438rtc::Optional<CodecInst> NetEqImpl::GetDecoder(int payload_type) const {
439 rtc::CritScope lock(&crit_sect_);
440 const DecoderDatabase::DecoderInfo* di =
441 decoder_database_->GetDecoderInfo(payload_type);
442 if (!di) {
Oskar Sundbom12ab00b2017-11-16 15:31:38 +0100443 return rtc::nullopt;
kwiberg6f0f6162016-09-20 03:07:46 -0700444 }
445
446 // Create a CodecInst with some fields set. The remaining fields are zeroed,
447 // but we tell MSan to consider them uninitialized.
448 CodecInst ci = {0};
449 rtc::MsanMarkUninitialized(rtc::MakeArrayView(&ci, 1));
450 ci.pltype = payload_type;
kwiberge9413062016-11-03 05:29:05 -0700451 std::strncpy(ci.plname, di->get_name().c_str(), sizeof(ci.plname));
kwiberg6f0f6162016-09-20 03:07:46 -0700452 ci.plname[sizeof(ci.plname) - 1] = '\0';
solenberg2779bab2016-11-17 04:45:19 -0800453 ci.plfreq = di->IsRed() ? 8000 : di->SampleRateHz();
kwiberg6f0f6162016-09-20 03:07:46 -0700454 AudioDecoder* const decoder = di->GetDecoder();
455 ci.channels = decoder ? decoder->Channels() : 1;
Oskar Sundbom12ab00b2017-11-16 15:31:38 +0100456 return ci;
kwiberg6f0f6162016-09-20 03:07:46 -0700457}
458
ossuf1b08da2016-09-23 02:19:43 -0700459rtc::Optional<SdpAudioFormat> NetEqImpl::GetDecoderFormat(
460 int payload_type) const {
kwibergc4ccd4d2016-09-21 10:55:15 -0700461 rtc::CritScope lock(&crit_sect_);
462 const DecoderDatabase::DecoderInfo* const di =
463 decoder_database_->GetDecoderInfo(payload_type);
464 if (!di) {
Oskar Sundbom12ab00b2017-11-16 15:31:38 +0100465 return rtc::nullopt; // Payload type not registered.
kwibergc4ccd4d2016-09-21 10:55:15 -0700466 }
Oskar Sundbom12ab00b2017-11-16 15:31:38 +0100467 return di->GetFormat();
kwibergc4ccd4d2016-09-21 10:55:15 -0700468}
469
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200470int NetEqImpl::SetTargetNumberOfChannels() {
471 return kNotImplemented;
472}
473
474int NetEqImpl::SetTargetSampleRate() {
475 return kNotImplemented;
476}
477
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000478void NetEqImpl::FlushBuffers() {
Tommi9090e0b2016-01-20 13:39:36 +0100479 rtc::CritScope lock(&crit_sect_);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100480 RTC_LOG(LS_VERBOSE) << "FlushBuffers";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000481 packet_buffer_->Flush();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000482 assert(sync_buffer_.get());
483 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000484 sync_buffer_->Flush();
485 sync_buffer_->set_next_index(sync_buffer_->next_index() -
486 expand_->overlap_length());
487 // Set to wait for new codec.
488 first_packet_ = true;
489}
490
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000491void NetEqImpl::PacketBufferStatistics(int* current_num_packets,
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000492 int* max_num_packets) const {
Tommi9090e0b2016-01-20 13:39:36 +0100493 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000494 packet_buffer_->BufferStat(current_num_packets, max_num_packets);
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000495}
496
henrik.lundin48ed9302015-10-29 05:36:24 -0700497void NetEqImpl::EnableNack(size_t max_nack_list_size) {
Tommi9090e0b2016-01-20 13:39:36 +0100498 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700499 if (!nack_enabled_) {
500 const int kNackThresholdPackets = 2;
henrik.lundin91951862016-06-08 06:43:41 -0700501 nack_.reset(NackTracker::Create(kNackThresholdPackets));
henrik.lundin48ed9302015-10-29 05:36:24 -0700502 nack_enabled_ = true;
503 nack_->UpdateSampleRate(fs_hz_);
504 }
505 nack_->SetMaxNackListSize(max_nack_list_size);
506}
507
508void NetEqImpl::DisableNack() {
Tommi9090e0b2016-01-20 13:39:36 +0100509 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700510 nack_.reset();
511 nack_enabled_ = false;
512}
513
514std::vector<uint16_t> NetEqImpl::GetNackList(int64_t round_trip_time_ms) const {
Tommi9090e0b2016-01-20 13:39:36 +0100515 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700516 if (!nack_enabled_) {
517 return std::vector<uint16_t>();
518 }
519 RTC_DCHECK(nack_.get());
520 return nack_->GetNackList(round_trip_time_ms);
minyue@webrtc.orgd7301772013-08-29 00:58:14 +0000521}
522
henrik.lundin114c1b32017-04-26 07:47:32 -0700523std::vector<uint32_t> NetEqImpl::LastDecodedTimestamps() const {
524 rtc::CritScope lock(&crit_sect_);
525 return last_decoded_timestamps_;
526}
527
528int NetEqImpl::SyncBufferSizeMs() const {
529 rtc::CritScope lock(&crit_sect_);
530 return rtc::dchecked_cast<int>(sync_buffer_->FutureLength() /
531 rtc::CheckedDivExact(fs_hz_, 1000));
532}
533
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000534const SyncBuffer* NetEqImpl::sync_buffer_for_test() const {
Tommi9090e0b2016-01-20 13:39:36 +0100535 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000536 return sync_buffer_.get();
537}
538
minyue5bd33972016-05-02 04:46:11 -0700539Operations NetEqImpl::last_operation_for_test() const {
540 rtc::CritScope lock(&crit_sect_);
541 return last_operation_;
542}
543
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000544// Methods below this line are private.
545
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200546int NetEqImpl::InsertPacketInternal(const RTPHeader& rtp_header,
kwibergee2bac22015-11-11 10:34:00 -0800547 rtc::ArrayView<const uint8_t> payload,
ossu17e3fa12016-09-08 04:52:55 -0700548 uint32_t receive_timestamp) {
kwibergee2bac22015-11-11 10:34:00 -0800549 if (payload.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100550 RTC_LOG_F(LS_ERROR) << "payload is empty";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000551 return kInvalidPointer;
552 }
ossu17e3fa12016-09-08 04:52:55 -0700553
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000554 PacketList packet_list;
ossua73f6c92016-10-24 08:25:28 -0700555 // Insert packet in a packet list.
556 packet_list.push_back([&rtp_header, &payload] {
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000557 // Convert to Packet.
ossua73f6c92016-10-24 08:25:28 -0700558 Packet packet;
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200559 packet.payload_type = rtp_header.payloadType;
560 packet.sequence_number = rtp_header.sequenceNumber;
561 packet.timestamp = rtp_header.timestamp;
ossua73f6c92016-10-24 08:25:28 -0700562 packet.payload.SetData(payload.data(), payload.size());
henrik.lundin84f8cd62016-04-26 07:45:16 -0700563 // Waiting time will be set upon inserting the packet in the buffer.
ossua73f6c92016-10-24 08:25:28 -0700564 RTC_DCHECK(!packet.waiting_time);
565 return packet;
566 }());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000567
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200568 bool update_sample_rate_and_channels =
569 first_packet_ || (rtp_header.ssrc != ssrc_);
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700570
571 if (update_sample_rate_and_channels) {
572 // Reset timestamp scaling.
573 timestamp_scaler_->Reset();
574 }
575
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200576 if (!decoder_database_->IsRed(rtp_header.payloadType)) {
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700577 // Scale timestamp to internal domain (only for some codecs).
578 timestamp_scaler_->ToInternal(&packet_list);
579 }
580
581 // Store these for later use, since the first packet may very well disappear
582 // before we need these values.
583 uint32_t main_timestamp = packet_list.front().timestamp;
584 uint8_t main_payload_type = packet_list.front().payload_type;
585 uint16_t main_sequence_number = packet_list.front().sequence_number;
586
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000587 // Reinitialize NetEq if it's needed (changed SSRC or first call).
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700588 if (update_sample_rate_and_channels) {
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000589 // Note: |first_packet_| will be cleared further down in this method, once
590 // the packet has been successfully inserted into the packet buffer.
591
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200592 rtcp_.Init(rtp_header.sequenceNumber);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000593
594 // Flush the packet buffer and DTMF buffer.
595 packet_buffer_->Flush();
596 dtmf_buffer_->Flush();
597
598 // Store new SSRC.
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200599 ssrc_ = rtp_header.ssrc;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000600
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000601 // Update audio buffer timestamp.
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700602 sync_buffer_->IncreaseEndTimestamp(main_timestamp - timestamp_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000603
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000604 // Update codecs.
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700605 timestamp_ = main_timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000606 }
607
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000608 // Update RTCP statistics, only for regular packets.
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200609 rtcp_.Update(rtp_header, receive_timestamp);
ossu7a377612016-10-18 04:06:13 -0700610
611 if (nack_enabled_) {
612 RTC_DCHECK(nack_);
613 if (update_sample_rate_and_channels) {
614 nack_->Reset();
615 }
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200616 nack_->UpdateLastReceivedPacket(rtp_header.sequenceNumber,
617 rtp_header.timestamp);
ossu7a377612016-10-18 04:06:13 -0700618 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000619
620 // Check for RED payload type, and separate payloads into several packets.
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200621 if (decoder_database_->IsRed(rtp_header.payloadType)) {
ossua70695a2016-09-22 02:06:28 -0700622 if (!red_payload_splitter_->SplitRed(&packet_list)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000623 return kRedundancySplitError;
624 }
625 // Only accept a few RED payloads of the same type as the main data,
626 // DTMF events and CNG.
ossua70695a2016-09-22 02:06:28 -0700627 red_payload_splitter_->CheckRedPayloads(&packet_list, *decoder_database_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000628 }
629
630 // Check payload types.
631 if (decoder_database_->CheckPayloadTypes(packet_list) ==
632 DecoderDatabase::kDecoderNotFound) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000633 return kUnknownRtpPayloadType;
634 }
635
ossu7a377612016-10-18 04:06:13 -0700636 RTC_DCHECK(!packet_list.empty());
ossu7a377612016-10-18 04:06:13 -0700637
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700638 // Update main_timestamp, if new packets appear in the list
639 // after RED splitting.
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200640 if (decoder_database_->IsRed(rtp_header.payloadType)) {
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700641 timestamp_scaler_->ToInternal(&packet_list);
642 main_timestamp = packet_list.front().timestamp;
643 main_payload_type = packet_list.front().payload_type;
644 main_sequence_number = packet_list.front().sequence_number;
645 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000646
647 // Process DTMF payloads. Cycle through the list of packets, and pick out any
648 // DTMF payloads found.
649 PacketList::iterator it = packet_list.begin();
650 while (it != packet_list.end()) {
ossua73f6c92016-10-24 08:25:28 -0700651 const Packet& current_packet = (*it);
652 RTC_DCHECK(!current_packet.payload.empty());
653 if (decoder_database_->IsDtmf(current_packet.payload_type)) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000654 DtmfEvent event;
ossua73f6c92016-10-24 08:25:28 -0700655 int ret = DtmfBuffer::ParseEvent(current_packet.timestamp,
656 current_packet.payload.data(),
657 current_packet.payload.size(), &event);
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000658 if (ret != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000659 return kDtmfParsingError;
660 }
661 if (dtmf_buffer_->InsertEvent(event) != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000662 return kDtmfInsertError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000663 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000664 it = packet_list.erase(it);
665 } else {
666 ++it;
667 }
668 }
669
ossu17e3fa12016-09-08 04:52:55 -0700670 // Update bandwidth estimate, if the packet is not comfort noise.
671 if (!packet_list.empty() &&
ossu7a377612016-10-18 04:06:13 -0700672 !decoder_database_->IsComfortNoise(main_payload_type)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000673 // The list can be empty here if we got nothing but DTMF payloads.
ossu7a377612016-10-18 04:06:13 -0700674 AudioDecoder* decoder = decoder_database_->GetDecoder(main_payload_type);
675 RTC_DCHECK(decoder); // Should always get a valid object, since we have
676 // already checked that the payload types are known.
ossua73f6c92016-10-24 08:25:28 -0700677 decoder->IncomingPacket(packet_list.front().payload.data(),
678 packet_list.front().payload.size(),
679 packet_list.front().sequence_number,
680 packet_list.front().timestamp,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000681 receive_timestamp);
682 }
683
ossu61a208b2016-09-20 01:38:00 -0700684 PacketList parsed_packet_list;
685 while (!packet_list.empty()) {
ossua73f6c92016-10-24 08:25:28 -0700686 Packet& packet = packet_list.front();
ossu61a208b2016-09-20 01:38:00 -0700687 const DecoderDatabase::DecoderInfo* info =
ossua73f6c92016-10-24 08:25:28 -0700688 decoder_database_->GetDecoderInfo(packet.payload_type);
ossu61a208b2016-09-20 01:38:00 -0700689 if (!info) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100690 RTC_LOG(LS_WARNING) << "SplitAudio unknown payload type";
ossu61a208b2016-09-20 01:38:00 -0700691 return kUnknownRtpPayloadType;
692 }
693
694 if (info->IsComfortNoise()) {
695 // Carry comfort noise packets along.
ossua73f6c92016-10-24 08:25:28 -0700696 parsed_packet_list.splice(parsed_packet_list.end(), packet_list,
697 packet_list.begin());
ossu61a208b2016-09-20 01:38:00 -0700698 } else {
ossua73f6c92016-10-24 08:25:28 -0700699 const auto sequence_number = packet.sequence_number;
700 const auto payload_type = packet.payload_type;
701 const Packet::Priority original_priority = packet.priority;
702 auto packet_from_result = [&] (AudioDecoder::ParseResult& result) {
703 Packet new_packet;
704 new_packet.sequence_number = sequence_number;
705 new_packet.payload_type = payload_type;
706 new_packet.timestamp = result.timestamp;
707 new_packet.priority.codec_level = result.priority;
708 new_packet.priority.red_level = original_priority.red_level;
709 new_packet.frame = std::move(result.frame);
710 return new_packet;
711 };
712
ossu61a208b2016-09-20 01:38:00 -0700713 std::vector<AudioDecoder::ParseResult> results =
ossua73f6c92016-10-24 08:25:28 -0700714 info->GetDecoder()->ParsePayload(std::move(packet.payload),
715 packet.timestamp);
716 if (results.empty()) {
717 packet_list.pop_front();
718 } else {
719 bool first = true;
720 for (auto& result : results) {
721 RTC_DCHECK(result.frame);
722 RTC_DCHECK_GE(result.priority, 0);
723 if (first) {
724 // Re-use the node and move it to parsed_packet_list.
725 packet_list.front() = packet_from_result(result);
726 parsed_packet_list.splice(parsed_packet_list.end(), packet_list,
727 packet_list.begin());
728 first = false;
729 } else {
730 parsed_packet_list.push_back(packet_from_result(result));
731 }
ossu61a208b2016-09-20 01:38:00 -0700732 }
ossu61a208b2016-09-20 01:38:00 -0700733 }
734 }
735 }
736
Ivo Creusenfd7c0a52017-10-20 12:35:04 +0200737 // Calculate the number of primary (non-FEC/RED) packets.
738 const int number_of_primary_packets = std::count_if(
739 parsed_packet_list.begin(), parsed_packet_list.end(),
740 [](const Packet& in) { return in.priority.codec_level == 0; });
741
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000742 // Insert packets in buffer.
ossua70695a2016-09-22 02:06:28 -0700743 const int ret = packet_buffer_->InsertPacketList(
ossu61a208b2016-09-20 01:38:00 -0700744 &parsed_packet_list, *decoder_database_, &current_rtp_payload_type_,
minyue-webrtc12d30842017-07-19 11:44:06 +0200745 &current_cng_rtp_payload_type_, &stats_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000746 if (ret == PacketBuffer::kFlushed) {
747 // Reset DSP timestamp etc. if packet buffer flushed.
748 new_codec_ = true;
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000749 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000750 } else if (ret != PacketBuffer::kOK) {
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000751 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000752 }
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000753
754 if (first_packet_) {
755 first_packet_ = false;
756 // Update the codec on the next GetAudio call.
757 new_codec_ = true;
758 }
759
henrik.lundinda8bbf62016-08-31 03:14:11 -0700760 if (current_rtp_payload_type_) {
761 RTC_DCHECK(decoder_database_->GetDecoderInfo(*current_rtp_payload_type_))
762 << "Payload type " << static_cast<int>(*current_rtp_payload_type_)
763 << " is unknown where it shouldn't be";
764 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000765
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000766 if (update_sample_rate_and_channels && !packet_buffer_->Empty()) {
767 // We do not use |current_rtp_payload_type_| to |set payload_type|, but
768 // get the next RTP header from |packet_buffer_| to obtain the payload type.
769 // The reason for it is the following corner case. If NetEq receives a
770 // CNG packet with a sample rate different than the current CNG then it
771 // flushes its buffer, assuming send codec must have been changed. However,
772 // payload type of the hypothetically new send codec is not known.
ossu7a377612016-10-18 04:06:13 -0700773 const Packet* next_packet = packet_buffer_->PeekNextPacket();
774 RTC_DCHECK(next_packet);
775 const int payload_type = next_packet->payload_type;
ossu97ba30e2016-04-25 07:55:58 -0700776 size_t channels = 1;
777 if (!decoder_database_->IsComfortNoise(payload_type)) {
778 AudioDecoder* decoder = decoder_database_->GetDecoder(payload_type);
779 assert(decoder); // Payloads are already checked to be valid.
780 channels = decoder->Channels();
781 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000782 const DecoderDatabase::DecoderInfo* decoder_info =
783 decoder_database_->GetDecoderInfo(payload_type);
784 assert(decoder_info);
kwibergc0f2dcf2016-05-31 06:28:03 -0700785 if (decoder_info->SampleRateHz() != fs_hz_ ||
ossu97ba30e2016-04-25 07:55:58 -0700786 channels != algorithm_buffer_->Channels()) {
kwibergc0f2dcf2016-05-31 06:28:03 -0700787 SetSampleRateAndChannels(decoder_info->SampleRateHz(),
788 channels);
henrik.lundin48ed9302015-10-29 05:36:24 -0700789 }
790 if (nack_enabled_) {
791 RTC_DCHECK(nack_);
792 // Update the sample rate even if the rate is not new, because of Reset().
793 nack_->UpdateSampleRate(fs_hz_);
794 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000795 }
796
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000797 // TODO(hlundin): Move this code to DelayManager class.
798 const DecoderDatabase::DecoderInfo* dec_info =
ossu7a377612016-10-18 04:06:13 -0700799 decoder_database_->GetDecoderInfo(main_payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000800 assert(dec_info); // Already checked that the payload type is known.
ossuf1b08da2016-09-23 02:19:43 -0700801 delay_manager_->LastDecodedWasCngOrDtmf(dec_info->IsComfortNoise() ||
802 dec_info->IsDtmf());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000803 if (delay_manager_->last_pack_cng_or_dtmf() == 0) {
804 // Calculate the total speech length carried in each packet.
Ivo Creusenfd7c0a52017-10-20 12:35:04 +0200805 if (number_of_primary_packets > 0) {
henrik.lundin116c84e2015-08-27 13:14:48 -0700806 const size_t packet_length_samples =
Ivo Creusenfd7c0a52017-10-20 12:35:04 +0200807 number_of_primary_packets * decoder_frame_length_;
henrik.lundin116c84e2015-08-27 13:14:48 -0700808 if (packet_length_samples != decision_logic_->packet_length_samples()) {
809 decision_logic_->set_packet_length_samples(packet_length_samples);
810 delay_manager_->SetPacketAudioLength(
kwibergd3edd772017-03-01 18:52:48 -0800811 rtc::dchecked_cast<int>((1000 * packet_length_samples) / fs_hz_));
henrik.lundin116c84e2015-08-27 13:14:48 -0700812 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000813 }
814
815 // Update statistics.
ossu7a377612016-10-18 04:06:13 -0700816 if ((int32_t)(main_timestamp - timestamp_) >= 0 && !new_codec_) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000817 // Only update statistics if incoming packet is not older than last played
818 // out packet, and if new codec flag is not set.
ossu7a377612016-10-18 04:06:13 -0700819 delay_manager_->Update(main_sequence_number, main_timestamp, fs_hz_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000820 }
821 } else if (delay_manager_->last_pack_cng_or_dtmf() == -1) {
822 // This is first "normal" packet after CNG or DTMF.
823 // Reset packet time counter and measure time until next packet,
824 // but don't update statistics.
825 delay_manager_->set_last_pack_cng_or_dtmf(0);
826 delay_manager_->ResetPacketIatCount();
827 }
828 return 0;
829}
830
henrik.lundin7a926812016-05-12 13:51:28 -0700831int NetEqImpl::GetAudioInternal(AudioFrame* audio_frame, bool* muted) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000832 PacketList packet_list;
833 DtmfEvent dtmf_event;
834 Operations operation;
835 bool play_dtmf;
henrik.lundin7a926812016-05-12 13:51:28 -0700836 *muted = false;
henrik.lundin114c1b32017-04-26 07:47:32 -0700837 last_decoded_timestamps_.clear();
henrik.lundined497212016-04-25 10:11:38 -0700838 tick_timer_->Increment();
henrik.lundin60f6ce22016-05-10 03:52:04 -0700839 stats_.IncreaseCounter(output_size_samples_, fs_hz_);
henrik.lundin7a926812016-05-12 13:51:28 -0700840
841 // Check for muted state.
842 if (enable_muted_state_ && expand_->Muted() && packet_buffer_->Empty()) {
843 RTC_DCHECK_EQ(last_mode_, kModeExpand);
henrik.lundina4491072017-07-06 05:23:53 -0700844 audio_frame->Reset();
845 RTC_DCHECK(audio_frame->muted()); // Reset() should mute the frame.
henrik.lundin7a926812016-05-12 13:51:28 -0700846 playout_timestamp_ += static_cast<uint32_t>(output_size_samples_);
847 audio_frame->sample_rate_hz_ = fs_hz_;
848 audio_frame->samples_per_channel_ = output_size_samples_;
849 audio_frame->timestamp_ =
850 first_packet_
851 ? 0
852 : timestamp_scaler_->ToExternal(playout_timestamp_) -
853 static_cast<uint32_t>(audio_frame->samples_per_channel_);
854 audio_frame->num_channels_ = sync_buffer_->Channels();
Gustaf Ullberg9a2e9062017-09-18 09:28:20 +0200855 stats_.ExpandedNoiseSamples(output_size_samples_, false);
henrik.lundin7a926812016-05-12 13:51:28 -0700856 *muted = true;
857 return 0;
858 }
859
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000860 int return_value = GetDecision(&operation, &packet_list, &dtmf_event,
861 &play_dtmf);
862 if (return_value != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000863 last_mode_ = kModeError;
864 return return_value;
865 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000866
867 AudioDecoder::SpeechType speech_type;
868 int length = 0;
Henrik Lundin18036282017-11-02 12:09:06 +0100869 const size_t start_num_packets = packet_list.size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000870 int decode_return_value = Decode(&packet_list, &operation,
871 &length, &speech_type);
872
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000873 assert(vad_.get());
874 bool sid_frame_available =
875 (operation == kRfc3389Cng && !packet_list.empty());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700876 vad_->Update(decoded_buffer_.get(), static_cast<size_t>(length), speech_type,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000877 sid_frame_available, fs_hz_);
878
Henrik Lundin18036282017-11-02 12:09:06 +0100879 // This is the criterion that we did decode some data through the speech
880 // decoder, and the operation resulted in comfort noise.
881 const bool codec_internal_sid_frame =
Henrik Lundin4f2a4a12018-01-26 17:32:56 +0100882 (speech_type == AudioDecoder::kComfortNoise &&
883 start_num_packets > packet_list.size());
Henrik Lundin18036282017-11-02 12:09:06 +0100884
885 if (sid_frame_available || codec_internal_sid_frame) {
henrik.lundinb1fb72b2016-05-03 08:18:47 -0700886 // Start a new stopwatch since we are decoding a new CNG packet.
887 generated_noise_stopwatch_ = tick_timer_->GetNewStopwatch();
888 }
889
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000890 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000891 switch (operation) {
892 case kNormal: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000893 DoNormal(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000894 break;
895 }
896 case kMerge: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000897 DoMerge(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000898 break;
899 }
900 case kExpand: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000901 return_value = DoExpand(play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000902 break;
903 }
Henrik Lundincf808d22015-05-27 14:33:29 +0200904 case kAccelerate:
905 case kFastAccelerate: {
906 const bool fast_accelerate =
907 enable_fast_accelerate_ && (operation == kFastAccelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000908 return_value = DoAccelerate(decoded_buffer_.get(), length, speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +0200909 play_dtmf, fast_accelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000910 break;
911 }
912 case kPreemptiveExpand: {
913 return_value = DoPreemptiveExpand(decoded_buffer_.get(), length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000914 speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000915 break;
916 }
917 case kRfc3389Cng:
918 case kRfc3389CngNoPacket: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000919 return_value = DoRfc3389Cng(&packet_list, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000920 break;
921 }
922 case kCodecInternalCng: {
923 // This handles the case when there is no transmission and the decoder
924 // should produce internal comfort noise.
925 // TODO(hlundin): Write test for codec-internal CNG.
minyuel6d92bf52015-09-23 15:20:39 +0200926 DoCodecInternalCng(decoded_buffer_.get(), length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000927 break;
928 }
929 case kDtmf: {
930 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000931 return_value = DoDtmf(dtmf_event, &play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000932 break;
933 }
934 case kAlternativePlc: {
935 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000936 DoAlternativePlc(false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000937 break;
938 }
939 case kAlternativePlcIncreaseTimestamp: {
940 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000941 DoAlternativePlc(true);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000942 break;
943 }
944 case kAudioRepetitionIncreaseTimestamp: {
945 // TODO(hlundin): Write test for this.
Peter Kastingb7e50542015-06-11 12:55:50 -0700946 sync_buffer_->IncreaseEndTimestamp(
947 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000948 // Skipping break on purpose. Execution should move on into the
949 // next case.
Karl Wiberg80ba3332018-02-05 10:33:35 +0100950 RTC_FALLTHROUGH();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000951 }
952 case kAudioRepetition: {
953 // TODO(hlundin): Write test for this.
954 // Copy last |output_size_samples_| from |sync_buffer_| to
955 // |algorithm_buffer|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000956 algorithm_buffer_->PushBackFromIndex(
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000957 *sync_buffer_, sync_buffer_->Size() - output_size_samples_);
958 expand_->Reset();
959 break;
960 }
961 case kUndefined: {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100962 RTC_LOG(LS_ERROR) << "Invalid operation kUndefined.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000963 assert(false); // This should not happen.
964 last_mode_ = kModeError;
965 return kInvalidOperation;
966 }
967 } // End of switch.
minyue5bd33972016-05-02 04:46:11 -0700968 last_operation_ = operation;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000969 if (return_value < 0) {
970 return return_value;
971 }
972
973 if (last_mode_ != kModeRfc3389Cng) {
974 comfort_noise_->Reset();
975 }
976
977 // Copy from |algorithm_buffer| to |sync_buffer_|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000978 sync_buffer_->PushBack(*algorithm_buffer_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000979
980 // Extract data from |sync_buffer_| to |output|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000981 size_t num_output_samples_per_channel = output_size_samples_;
982 size_t num_output_samples = output_size_samples_ * sync_buffer_->Channels();
henrik.lundin6d8e0112016-03-04 10:34:21 -0800983 if (num_output_samples > AudioFrame::kMaxDataSizeSamples) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100984 RTC_LOG(LS_WARNING) << "Output array is too short. "
985 << AudioFrame::kMaxDataSizeSamples << " < "
986 << output_size_samples_ << " * "
987 << sync_buffer_->Channels();
henrik.lundin6d8e0112016-03-04 10:34:21 -0800988 num_output_samples = AudioFrame::kMaxDataSizeSamples;
989 num_output_samples_per_channel =
990 AudioFrame::kMaxDataSizeSamples / sync_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000991 }
henrik.lundin6d8e0112016-03-04 10:34:21 -0800992 sync_buffer_->GetNextAudioInterleaved(num_output_samples_per_channel,
993 audio_frame);
994 audio_frame->sample_rate_hz_ = fs_hz_;
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200995 if (sync_buffer_->FutureLength() < expand_->overlap_length()) {
996 // The sync buffer should always contain |overlap_length| samples, but now
997 // too many samples have been extracted. Reinstall the |overlap_length|
998 // lookahead by moving the index.
999 const size_t missing_lookahead_samples =
1000 expand_->overlap_length() - sync_buffer_->FutureLength();
henrikg91d6ede2015-09-17 00:24:34 -07001001 RTC_DCHECK_GE(sync_buffer_->next_index(), missing_lookahead_samples);
Henrik Lundin05f71fc2015-09-01 11:51:58 +02001002 sync_buffer_->set_next_index(sync_buffer_->next_index() -
1003 missing_lookahead_samples);
1004 }
henrik.lundin6d8e0112016-03-04 10:34:21 -08001005 if (audio_frame->samples_per_channel_ != output_size_samples_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001006 RTC_LOG(LS_ERROR) << "audio_frame->samples_per_channel_ ("
1007 << audio_frame->samples_per_channel_
1008 << ") != output_size_samples_ (" << output_size_samples_
1009 << ")";
minyue@webrtc.orgdb1cefc2013-08-13 01:39:21 +00001010 // TODO(minyue): treatment of under-run, filling zeros
yujo36b1a5f2017-06-12 12:45:32 -07001011 audio_frame->Mute();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001012 return kSampleUnderrun;
1013 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001014
1015 // Should always have overlap samples left in the |sync_buffer_|.
henrikg91d6ede2015-09-17 00:24:34 -07001016 RTC_DCHECK_GE(sync_buffer_->FutureLength(), expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001017
yujo36b1a5f2017-06-12 12:45:32 -07001018 // TODO(yujo): For muted frames, this can be a copy rather than an addition.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001019 if (play_dtmf) {
yujo36b1a5f2017-06-12 12:45:32 -07001020 return_value = DtmfOverdub(dtmf_event, sync_buffer_->Channels(),
1021 audio_frame->mutable_data());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001022 }
1023
1024 // Update the background noise parameters if last operation wrote data
1025 // straight from the decoder to the |sync_buffer_|. That is, none of the
1026 // operations that modify the signal can be followed by a parameter update.
1027 if ((last_mode_ == kModeNormal) ||
1028 (last_mode_ == kModeAccelerateFail) ||
1029 (last_mode_ == kModePreemptiveExpandFail) ||
1030 (last_mode_ == kModeRfc3389Cng) ||
1031 (last_mode_ == kModeCodecInternalCng)) {
1032 background_noise_->Update(*sync_buffer_, *vad_.get());
1033 }
1034
1035 if (operation == kDtmf) {
1036 // DTMF data was written the end of |sync_buffer_|.
1037 // Update index to end of DTMF data in |sync_buffer_|.
1038 sync_buffer_->set_dtmf_index(sync_buffer_->Size());
1039 }
1040
henrik.lundin@webrtc.orged865b52014-03-06 10:28:07 +00001041 if (last_mode_ != kModeExpand) {
1042 // If last operation was not expand, calculate the |playout_timestamp_| from
1043 // the |sync_buffer_|. However, do not update the |playout_timestamp_| if it
1044 // would be moved "backwards".
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001045 uint32_t temp_timestamp = sync_buffer_->end_timestamp() -
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001046 static_cast<uint32_t>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001047 if (static_cast<int32_t>(temp_timestamp - playout_timestamp_) > 0) {
1048 playout_timestamp_ = temp_timestamp;
1049 }
1050 } else {
1051 // Use dead reckoning to estimate the |playout_timestamp_|.
Peter Kastingb7e50542015-06-11 12:55:50 -07001052 playout_timestamp_ += static_cast<uint32_t>(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001053 }
henrik.lundin15c51e32016-04-06 08:38:56 -07001054 // Set the timestamp in the audio frame to zero before the first packet has
1055 // been inserted. Otherwise, subtract the frame size in samples to get the
1056 // timestamp of the first sample in the frame (playout_timestamp_ is the
1057 // last + 1).
1058 audio_frame->timestamp_ =
1059 first_packet_
1060 ? 0
1061 : timestamp_scaler_->ToExternal(playout_timestamp_) -
1062 static_cast<uint32_t>(audio_frame->samples_per_channel_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001063
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001064 if (!(last_mode_ == kModeRfc3389Cng ||
1065 last_mode_ == kModeCodecInternalCng ||
1066 last_mode_ == kModeExpand)) {
1067 generated_noise_stopwatch_.reset();
1068 }
1069
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001070 if (decode_return_value) return decode_return_value;
1071 return return_value;
1072}
1073
1074int NetEqImpl::GetDecision(Operations* operation,
1075 PacketList* packet_list,
1076 DtmfEvent* dtmf_event,
1077 bool* play_dtmf) {
1078 // Initialize output variables.
1079 *play_dtmf = false;
1080 *operation = kUndefined;
1081
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001082 assert(sync_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001083 uint32_t end_timestamp = sync_buffer_->end_timestamp();
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001084 if (!new_codec_) {
1085 const uint32_t five_seconds_samples = 5 * fs_hz_;
minyue-webrtcfae474c2017-07-05 11:17:40 +02001086 packet_buffer_->DiscardOldPackets(end_timestamp, five_seconds_samples,
1087 &stats_);
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001088 }
ossu7a377612016-10-18 04:06:13 -07001089 const Packet* packet = packet_buffer_->PeekNextPacket();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001090
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001091 RTC_DCHECK(!generated_noise_stopwatch_ ||
1092 generated_noise_stopwatch_->ElapsedTicks() >= 1);
1093 uint64_t generated_noise_samples =
1094 generated_noise_stopwatch_
1095 ? (generated_noise_stopwatch_->ElapsedTicks() - 1) *
1096 output_size_samples_ +
1097 decision_logic_->noise_fast_forward()
1098 : 0;
1099
henrik.lundin@webrtc.orgca8cb952014-03-12 10:26:52 +00001100 if (decision_logic_->CngRfc3389On() || last_mode_ == kModeRfc3389Cng) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001101 // Because of timestamp peculiarities, we have to "manually" disallow using
1102 // a CNG packet with the same timestamp as the one that was last played.
1103 // This can happen when using redundancy and will cause the timing to shift.
ossu7a377612016-10-18 04:06:13 -07001104 while (packet && decoder_database_->IsComfortNoise(packet->payload_type) &&
1105 (end_timestamp >= packet->timestamp ||
1106 end_timestamp + generated_noise_samples > packet->timestamp)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001107 // Don't use this packet, discard it.
minyue-webrtcfae474c2017-07-05 11:17:40 +02001108 if (packet_buffer_->DiscardNextPacket(&stats_) != PacketBuffer::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001109 assert(false); // Must be ok by design.
1110 }
1111 // Check buffer again.
1112 if (!new_codec_) {
minyue-webrtcfae474c2017-07-05 11:17:40 +02001113 packet_buffer_->DiscardOldPackets(end_timestamp, 5 * fs_hz_, &stats_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001114 }
ossu7a377612016-10-18 04:06:13 -07001115 packet = packet_buffer_->PeekNextPacket();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001116 }
1117 }
1118
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001119 assert(expand_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001120 const int samples_left = static_cast<int>(sync_buffer_->FutureLength() -
1121 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001122 if (last_mode_ == kModeAccelerateSuccess ||
1123 last_mode_ == kModeAccelerateLowEnergy ||
1124 last_mode_ == kModePreemptiveExpandSuccess ||
1125 last_mode_ == kModePreemptiveExpandLowEnergy) {
1126 // Subtract (samples_left + output_size_samples_) from sampleMemory.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001127 decision_logic_->AddSampleMemory(
kwibergd3edd772017-03-01 18:52:48 -08001128 -(samples_left + rtc::dchecked_cast<int>(output_size_samples_)));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001129 }
1130
1131 // Check if it is time to play a DTMF event.
Peter Kastingb7e50542015-06-11 12:55:50 -07001132 if (dtmf_buffer_->GetEvent(
1133 static_cast<uint32_t>(
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001134 end_timestamp + generated_noise_samples),
Peter Kastingb7e50542015-06-11 12:55:50 -07001135 dtmf_event)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001136 *play_dtmf = true;
1137 }
1138
1139 // Get instruction.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001140 assert(sync_buffer_.get());
1141 assert(expand_.get());
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001142 generated_noise_samples =
1143 generated_noise_stopwatch_
1144 ? generated_noise_stopwatch_->ElapsedTicks() * output_size_samples_ +
1145 decision_logic_->noise_fast_forward()
1146 : 0;
1147 *operation = decision_logic_->GetDecision(
ossu7a377612016-10-18 04:06:13 -07001148 *sync_buffer_, *expand_, decoder_frame_length_, packet, last_mode_,
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001149 *play_dtmf, generated_noise_samples, &reset_decoder_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001150
1151 // Check if we already have enough samples in the |sync_buffer_|. If so,
1152 // change decision to normal, unless the decision was merge, accelerate, or
1153 // preemptive expand.
kwibergd3edd772017-03-01 18:52:48 -08001154 if (samples_left >= rtc::dchecked_cast<int>(output_size_samples_) &&
1155 *operation != kMerge && *operation != kAccelerate &&
1156 *operation != kFastAccelerate && *operation != kPreemptiveExpand) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001157 *operation = kNormal;
1158 return 0;
1159 }
1160
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001161 decision_logic_->ExpandDecision(*operation);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001162
1163 // Check conditions for reset.
1164 if (new_codec_ || *operation == kUndefined) {
1165 // The only valid reason to get kUndefined is that new_codec_ is set.
1166 assert(new_codec_);
ossu7a377612016-10-18 04:06:13 -07001167 if (*play_dtmf && !packet) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001168 timestamp_ = dtmf_event->timestamp;
1169 } else {
ossu7a377612016-10-18 04:06:13 -07001170 if (!packet) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001171 RTC_LOG(LS_ERROR) << "Packet missing where it shouldn't.";
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001172 return -1;
1173 }
ossu7a377612016-10-18 04:06:13 -07001174 timestamp_ = packet->timestamp;
ossu108ecec2016-07-08 08:45:18 -07001175 if (*operation == kRfc3389CngNoPacket &&
ossu7a377612016-10-18 04:06:13 -07001176 decoder_database_->IsComfortNoise(packet->payload_type)) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001177 // Change decision to CNG packet, since we do have a CNG packet, but it
1178 // was considered too early to use. Now, use it anyway.
1179 *operation = kRfc3389Cng;
1180 } else if (*operation != kRfc3389Cng) {
1181 *operation = kNormal;
1182 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001183 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001184 // Adjust |sync_buffer_| timestamp before setting |end_timestamp| to the
1185 // new value.
1186 sync_buffer_->IncreaseEndTimestamp(timestamp_ - end_timestamp);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001187 end_timestamp = timestamp_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001188 new_codec_ = false;
1189 decision_logic_->SoftReset();
1190 buffer_level_filter_->Reset();
1191 delay_manager_->Reset();
1192 stats_.ResetMcu();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001193 }
1194
Peter Kastingdce40cf2015-08-24 14:52:23 -07001195 size_t required_samples = output_size_samples_;
1196 const size_t samples_10_ms = static_cast<size_t>(80 * fs_mult_);
1197 const size_t samples_20_ms = 2 * samples_10_ms;
1198 const size_t samples_30_ms = 3 * samples_10_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001199
1200 switch (*operation) {
1201 case kExpand: {
1202 timestamp_ = end_timestamp;
1203 return 0;
1204 }
1205 case kRfc3389CngNoPacket:
1206 case kCodecInternalCng: {
1207 return 0;
1208 }
1209 case kDtmf: {
1210 // TODO(hlundin): Write test for this.
1211 // Update timestamp.
1212 timestamp_ = end_timestamp;
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001213 const uint64_t generated_noise_samples =
1214 generated_noise_stopwatch_
1215 ? generated_noise_stopwatch_->ElapsedTicks() *
1216 output_size_samples_ +
1217 decision_logic_->noise_fast_forward()
1218 : 0;
1219 if (generated_noise_samples > 0 && last_mode_ != kModeDtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001220 // Make a jump in timestamp due to the recently played comfort noise.
Peter Kastingb7e50542015-06-11 12:55:50 -07001221 uint32_t timestamp_jump =
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001222 static_cast<uint32_t>(generated_noise_samples);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001223 sync_buffer_->IncreaseEndTimestamp(timestamp_jump);
1224 timestamp_ += timestamp_jump;
1225 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001226 return 0;
1227 }
Henrik Lundincf808d22015-05-27 14:33:29 +02001228 case kAccelerate:
1229 case kFastAccelerate: {
1230 // In order to do an accelerate we need at least 30 ms of audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001231 if (samples_left >= static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001232 // Already have enough data, so we do not need to extract any more.
1233 decision_logic_->set_sample_memory(samples_left);
1234 decision_logic_->set_prev_time_scale(true);
1235 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001236 } else if (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001237 decoder_frame_length_ >= samples_30_ms) {
1238 // Avoid decoding more data as it might overflow the playout buffer.
1239 *operation = kNormal;
1240 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001241 } else if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001242 decoder_frame_length_ < samples_30_ms) {
1243 // Build up decoded data by decoding at least 20 ms of audio data. Do
1244 // not perform accelerate yet, but wait until we only need to do one
1245 // decoding.
1246 required_samples = 2 * output_size_samples_;
1247 *operation = kNormal;
1248 }
1249 // If none of the above is true, we have one of two possible situations:
1250 // (1) 20 ms <= samples_left < 30 ms and decoder_frame_length_ < 30 ms; or
1251 // (2) samples_left < 10 ms and decoder_frame_length_ >= 30 ms.
1252 // In either case, we move on with the accelerate decision, and decode one
1253 // frame now.
1254 break;
1255 }
1256 case kPreemptiveExpand: {
1257 // In order to do a preemptive expand we need at least 30 ms of decoded
1258 // audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001259 if ((samples_left >= static_cast<int>(samples_30_ms)) ||
1260 (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001261 decoder_frame_length_ >= samples_30_ms)) {
1262 // Already have enough data, so we do not need to extract any more.
1263 // Or, avoid decoding more data as it might overflow the playout buffer.
1264 // Still try preemptive expand, though.
1265 decision_logic_->set_sample_memory(samples_left);
1266 decision_logic_->set_prev_time_scale(true);
1267 return 0;
1268 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07001269 if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001270 decoder_frame_length_ < samples_30_ms) {
1271 // Build up decoded data by decoding at least 20 ms of audio data.
1272 // Still try to perform preemptive expand.
1273 required_samples = 2 * output_size_samples_;
1274 }
1275 // Move on with the preemptive expand decision.
1276 break;
1277 }
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001278 case kMerge: {
1279 required_samples =
1280 std::max(merge_->RequiredFutureSamples(), required_samples);
1281 break;
1282 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001283 default: {
1284 // Do nothing.
1285 }
1286 }
1287
1288 // Get packets from buffer.
1289 int extracted_samples = 0;
ossu7a377612016-10-18 04:06:13 -07001290 if (packet && *operation != kAlternativePlc &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001291 *operation != kAlternativePlcIncreaseTimestamp &&
1292 *operation != kAudioRepetition &&
1293 *operation != kAudioRepetitionIncreaseTimestamp) {
ossu7a377612016-10-18 04:06:13 -07001294 sync_buffer_->IncreaseEndTimestamp(packet->timestamp - end_timestamp);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001295 if (decision_logic_->CngOff()) {
1296 // Adjustment of timestamp only corresponds to an actual packet loss
1297 // if comfort noise is not played. If comfort noise was just played,
1298 // this adjustment of timestamp is only done to get back in sync with the
1299 // stream timestamp; no loss to report.
ossu7a377612016-10-18 04:06:13 -07001300 stats_.LostSamples(packet->timestamp - end_timestamp);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001301 }
1302
1303 if (*operation != kRfc3389Cng) {
1304 // We are about to decode and use a non-CNG packet.
1305 decision_logic_->SetCngOff();
1306 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001307
1308 extracted_samples = ExtractPackets(required_samples, packet_list);
1309 if (extracted_samples < 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001310 return kPacketBufferCorruption;
1311 }
1312 }
1313
Henrik Lundincf808d22015-05-27 14:33:29 +02001314 if (*operation == kAccelerate || *operation == kFastAccelerate ||
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001315 *operation == kPreemptiveExpand) {
1316 decision_logic_->set_sample_memory(samples_left + extracted_samples);
1317 decision_logic_->set_prev_time_scale(true);
1318 }
1319
Henrik Lundincf808d22015-05-27 14:33:29 +02001320 if (*operation == kAccelerate || *operation == kFastAccelerate) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001321 // Check that we have enough data (30ms) to do accelerate.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001322 if (extracted_samples + samples_left < static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001323 // TODO(hlundin): Write test for this.
1324 // Not enough, do normal operation instead.
1325 *operation = kNormal;
1326 }
1327 }
1328
1329 timestamp_ = end_timestamp;
1330 return 0;
1331}
1332
1333int NetEqImpl::Decode(PacketList* packet_list, Operations* operation,
1334 int* decoded_length,
1335 AudioDecoder::SpeechType* speech_type) {
1336 *speech_type = AudioDecoder::kSpeech;
minyuel6d92bf52015-09-23 15:20:39 +02001337
1338 // When packet_list is empty, we may be in kCodecInternalCng mode, and for
1339 // that we use current active decoder.
1340 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1341
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001342 if (!packet_list->empty()) {
ossua73f6c92016-10-24 08:25:28 -07001343 const Packet& packet = packet_list->front();
1344 uint8_t payload_type = packet.payload_type;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001345 if (!decoder_database_->IsComfortNoise(payload_type)) {
1346 decoder = decoder_database_->GetDecoder(payload_type);
1347 assert(decoder);
1348 if (!decoder) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001349 RTC_LOG(LS_WARNING)
1350 << "Unknown payload type " << static_cast<int>(payload_type);
ossua73f6c92016-10-24 08:25:28 -07001351 packet_list->clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001352 return kDecoderNotFound;
1353 }
1354 bool decoder_changed;
1355 decoder_database_->SetActiveDecoder(payload_type, &decoder_changed);
1356 if (decoder_changed) {
1357 // We have a new decoder. Re-init some values.
1358 const DecoderDatabase::DecoderInfo* decoder_info = decoder_database_
1359 ->GetDecoderInfo(payload_type);
1360 assert(decoder_info);
1361 if (!decoder_info) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001362 RTC_LOG(LS_WARNING)
1363 << "Unknown payload type " << static_cast<int>(payload_type);
ossua73f6c92016-10-24 08:25:28 -07001364 packet_list->clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001365 return kDecoderNotFound;
1366 }
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001367 // If sampling rate or number of channels has changed, we need to make
1368 // a reset.
kwibergc0f2dcf2016-05-31 06:28:03 -07001369 if (decoder_info->SampleRateHz() != fs_hz_ ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001370 decoder->Channels() != algorithm_buffer_->Channels()) {
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001371 // TODO(tlegrand): Add unittest to cover this event.
kwibergc0f2dcf2016-05-31 06:28:03 -07001372 SetSampleRateAndChannels(decoder_info->SampleRateHz(),
1373 decoder->Channels());
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001374 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001375 sync_buffer_->set_end_timestamp(timestamp_);
1376 playout_timestamp_ = timestamp_;
1377 }
1378 }
1379 }
1380
1381 if (reset_decoder_) {
1382 // TODO(hlundin): Write test for this.
Karl Wiberg43766482015-08-27 15:22:11 +02001383 if (decoder)
1384 decoder->Reset();
1385
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001386 // Reset comfort noise decoder.
ossu97ba30e2016-04-25 07:55:58 -07001387 ComfortNoiseDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02001388 if (cng_decoder)
1389 cng_decoder->Reset();
1390
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001391 reset_decoder_ = false;
1392 }
1393
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001394 *decoded_length = 0;
1395 // Update codec-internal PLC state.
1396 if ((*operation == kMerge) && decoder && decoder->HasDecodePlc()) {
1397 decoder->DecodePlc(1, &decoded_buffer_[*decoded_length]);
1398 }
1399
minyuel6d92bf52015-09-23 15:20:39 +02001400 int return_value;
1401 if (*operation == kCodecInternalCng) {
1402 RTC_DCHECK(packet_list->empty());
1403 return_value = DecodeCng(decoder, decoded_length, speech_type);
1404 } else {
1405 return_value = DecodeLoop(packet_list, *operation, decoder,
1406 decoded_length, speech_type);
1407 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001408
1409 if (*decoded_length < 0) {
1410 // Error returned from the decoder.
1411 *decoded_length = 0;
Peter Kastingb7e50542015-06-11 12:55:50 -07001412 sync_buffer_->IncreaseEndTimestamp(
1413 static_cast<uint32_t>(decoder_frame_length_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001414 int error_code = 0;
1415 if (decoder)
1416 error_code = decoder->ErrorCode();
1417 if (error_code != 0) {
1418 // Got some error code from the decoder.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001419 return_value = kDecoderErrorCode;
Mirko Bonadei675513b2017-11-09 11:09:25 +01001420 RTC_LOG(LS_WARNING) << "Decoder returned error code: " << error_code;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001421 } else {
1422 // Decoder does not implement error codes. Return generic error.
1423 return_value = kOtherDecoderError;
Mirko Bonadei675513b2017-11-09 11:09:25 +01001424 RTC_LOG(LS_WARNING) << "Decoder error (no error code)";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001425 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001426 *operation = kExpand; // Do expansion to get data instead.
1427 }
1428 if (*speech_type != AudioDecoder::kComfortNoise) {
1429 // Don't increment timestamp if codec returned CNG speech type
1430 // since in this case, the we will increment the CNGplayedTS counter.
1431 // Increase with number of samples per channel.
1432 assert(*decoded_length == 0 ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001433 (decoder && decoder->Channels() == sync_buffer_->Channels()));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001434 sync_buffer_->IncreaseEndTimestamp(
1435 *decoded_length / static_cast<int>(sync_buffer_->Channels()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001436 }
1437 return return_value;
1438}
1439
minyuel6d92bf52015-09-23 15:20:39 +02001440int NetEqImpl::DecodeCng(AudioDecoder* decoder, int* decoded_length,
1441 AudioDecoder::SpeechType* speech_type) {
1442 if (!decoder) {
1443 // This happens when active decoder is not defined.
1444 *decoded_length = -1;
1445 return 0;
1446 }
1447
kwibergd3edd772017-03-01 18:52:48 -08001448 while (*decoded_length < rtc::dchecked_cast<int>(output_size_samples_)) {
minyuel6d92bf52015-09-23 15:20:39 +02001449 const int length = decoder->Decode(
1450 nullptr, 0, fs_hz_,
1451 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1452 &decoded_buffer_[*decoded_length], speech_type);
1453 if (length > 0) {
1454 *decoded_length += length;
minyuel6d92bf52015-09-23 15:20:39 +02001455 } else {
1456 // Error.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001457 RTC_LOG(LS_WARNING) << "Failed to decode CNG";
minyuel6d92bf52015-09-23 15:20:39 +02001458 *decoded_length = -1;
1459 break;
1460 }
1461 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1462 // Guard against overflow.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001463 RTC_LOG(LS_WARNING) << "Decoded too much CNG.";
minyuel6d92bf52015-09-23 15:20:39 +02001464 return kDecodedTooMuch;
1465 }
1466 }
1467 return 0;
1468}
1469
1470int NetEqImpl::DecodeLoop(PacketList* packet_list, const Operations& operation,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001471 AudioDecoder* decoder, int* decoded_length,
1472 AudioDecoder::SpeechType* speech_type) {
henrik.lundin114c1b32017-04-26 07:47:32 -07001473 RTC_DCHECK(last_decoded_timestamps_.empty());
1474
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001475 // Do decoding.
ossua73f6c92016-10-24 08:25:28 -07001476 while (
1477 !packet_list->empty() &&
1478 !decoder_database_->IsComfortNoise(packet_list->front().payload_type)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001479 assert(decoder); // At this point, we must have a decoder object.
1480 // The number of channels in the |sync_buffer_| should be the same as the
1481 // number decoder channels.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001482 assert(sync_buffer_->Channels() == decoder->Channels());
1483 assert(decoded_buffer_length_ >= kMaxFrameSize * decoder->Channels());
minyuel6d92bf52015-09-23 15:20:39 +02001484 assert(operation == kNormal || operation == kAccelerate ||
1485 operation == kFastAccelerate || operation == kMerge ||
1486 operation == kPreemptiveExpand);
ossua73f6c92016-10-24 08:25:28 -07001487
1488 auto opt_result = packet_list->front().frame->Decode(
ossu61a208b2016-09-20 01:38:00 -07001489 rtc::ArrayView<int16_t>(&decoded_buffer_[*decoded_length],
1490 decoded_buffer_length_ - *decoded_length));
henrik.lundin114c1b32017-04-26 07:47:32 -07001491 last_decoded_timestamps_.push_back(packet_list->front().timestamp);
ossua73f6c92016-10-24 08:25:28 -07001492 packet_list->pop_front();
ossu61a208b2016-09-20 01:38:00 -07001493 if (opt_result) {
1494 const auto& result = *opt_result;
1495 *speech_type = result.speech_type;
1496 if (result.num_decoded_samples > 0) {
kwibergd3edd772017-03-01 18:52:48 -08001497 *decoded_length += rtc::dchecked_cast<int>(result.num_decoded_samples);
ossu61a208b2016-09-20 01:38:00 -07001498 // Update |decoder_frame_length_| with number of samples per channel.
1499 decoder_frame_length_ =
1500 result.num_decoded_samples / decoder->Channels();
1501 }
1502 } else {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001503 // Error.
ossu61a208b2016-09-20 01:38:00 -07001504 // TODO(ossu): What to put here?
Mirko Bonadei675513b2017-11-09 11:09:25 +01001505 RTC_LOG(LS_WARNING) << "Decode error";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001506 *decoded_length = -1;
ossua73f6c92016-10-24 08:25:28 -07001507 packet_list->clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001508 break;
1509 }
kwibergd3edd772017-03-01 18:52:48 -08001510 if (*decoded_length > rtc::dchecked_cast<int>(decoded_buffer_length_)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001511 // Guard against overflow.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001512 RTC_LOG(LS_WARNING) << "Decoded too much.";
ossua73f6c92016-10-24 08:25:28 -07001513 packet_list->clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001514 return kDecodedTooMuch;
1515 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001516 } // End of decode loop.
1517
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001518 // If the list is not empty at this point, either a decoding error terminated
1519 // the while-loop, or list must hold exactly one CNG packet.
ossua73f6c92016-10-24 08:25:28 -07001520 assert(
1521 packet_list->empty() || *decoded_length < 0 ||
1522 (packet_list->size() == 1 &&
1523 decoder_database_->IsComfortNoise(packet_list->front().payload_type)));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001524 return 0;
1525}
1526
1527void NetEqImpl::DoNormal(const int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001528 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001529 assert(normal_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001530 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001531 normal_->Process(decoded_buffer, decoded_length, last_mode_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001532 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001533 if (decoded_length != 0) {
1534 last_mode_ = kModeNormal;
1535 }
1536
1537 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1538 if ((speech_type == AudioDecoder::kComfortNoise)
1539 || ((last_mode_ == kModeCodecInternalCng)
1540 && (decoded_length == 0))) {
1541 // TODO(hlundin): Remove second part of || statement above.
1542 last_mode_ = kModeCodecInternalCng;
1543 }
1544
1545 if (!play_dtmf) {
1546 dtmf_tone_generator_->Reset();
1547 }
1548}
1549
1550void NetEqImpl::DoMerge(int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001551 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001552 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001553 assert(merge_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001554 size_t new_length = merge_->Process(decoded_buffer, decoded_length,
1555 mute_factor_array_.get(),
1556 algorithm_buffer_.get());
henrik.lundin2979f552017-05-05 05:04:16 -07001557 // Correction can be negative.
1558 int expand_length_correction =
1559 rtc::dchecked_cast<int>(new_length) -
1560 rtc::dchecked_cast<int>(decoded_length / algorithm_buffer_->Channels());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001561
1562 // Update in-call and post-call statistics.
1563 if (expand_->MuteFactor(0) == 0) {
1564 // Expand generates only noise.
henrik.lundin2979f552017-05-05 05:04:16 -07001565 stats_.ExpandedNoiseSamplesCorrection(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001566 } else {
1567 // Expansion generates more than only noise.
henrik.lundin2979f552017-05-05 05:04:16 -07001568 stats_.ExpandedVoiceSamplesCorrection(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001569 }
1570
1571 last_mode_ = kModeMerge;
1572 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1573 if (speech_type == AudioDecoder::kComfortNoise) {
1574 last_mode_ = kModeCodecInternalCng;
1575 }
1576 expand_->Reset();
1577 if (!play_dtmf) {
1578 dtmf_tone_generator_->Reset();
1579 }
1580}
1581
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001582int NetEqImpl::DoExpand(bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001583 while ((sync_buffer_->FutureLength() - expand_->overlap_length()) <
Peter Kastingdce40cf2015-08-24 14:52:23 -07001584 output_size_samples_) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001585 algorithm_buffer_->Clear();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001586 int return_value = expand_->Process(algorithm_buffer_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001587 size_t length = algorithm_buffer_->Size();
Gustaf Ullberg9a2e9062017-09-18 09:28:20 +02001588 bool is_new_concealment_event = (last_mode_ != kModeExpand);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001589
1590 // Update in-call and post-call statistics.
1591 if (expand_->MuteFactor(0) == 0) {
1592 // Expand operation generates only noise.
Gustaf Ullberg9a2e9062017-09-18 09:28:20 +02001593 stats_.ExpandedNoiseSamples(length, is_new_concealment_event);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001594 } else {
1595 // Expand operation generates more than only noise.
Gustaf Ullberg9a2e9062017-09-18 09:28:20 +02001596 stats_.ExpandedVoiceSamples(length, is_new_concealment_event);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001597 }
1598
1599 last_mode_ = kModeExpand;
1600
1601 if (return_value < 0) {
1602 return return_value;
1603 }
1604
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001605 sync_buffer_->PushBack(*algorithm_buffer_);
1606 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001607 }
1608 if (!play_dtmf) {
1609 dtmf_tone_generator_->Reset();
1610 }
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001611
1612 if (!generated_noise_stopwatch_) {
1613 // Start a new stopwatch since we may be covering for a lost CNG packet.
1614 generated_noise_stopwatch_ = tick_timer_->GetNewStopwatch();
1615 }
1616
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001617 return 0;
1618}
1619
Henrik Lundincf808d22015-05-27 14:33:29 +02001620int NetEqImpl::DoAccelerate(int16_t* decoded_buffer,
1621 size_t decoded_length,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001622 AudioDecoder::SpeechType speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +02001623 bool play_dtmf,
1624 bool fast_accelerate) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001625 const size_t required_samples =
1626 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001627 size_t borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001628 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001629 size_t decoded_length_per_channel = decoded_length / num_channels;
1630 if (decoded_length_per_channel < required_samples) {
1631 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001632 borrowed_samples_per_channel = static_cast<int>(required_samples -
1633 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001634 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1635 decoded_buffer,
1636 sizeof(int16_t) * decoded_length);
1637 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1638 decoded_buffer);
1639 decoded_length = required_samples * num_channels;
1640 }
1641
Peter Kastingdce40cf2015-08-24 14:52:23 -07001642 size_t samples_removed;
Henrik Lundincf808d22015-05-27 14:33:29 +02001643 Accelerate::ReturnCodes return_code =
1644 accelerate_->Process(decoded_buffer, decoded_length, fast_accelerate,
1645 algorithm_buffer_.get(), &samples_removed);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001646 stats_.AcceleratedSamples(samples_removed);
1647 switch (return_code) {
1648 case Accelerate::kSuccess:
1649 last_mode_ = kModeAccelerateSuccess;
1650 break;
1651 case Accelerate::kSuccessLowEnergy:
1652 last_mode_ = kModeAccelerateLowEnergy;
1653 break;
1654 case Accelerate::kNoStretch:
1655 last_mode_ = kModeAccelerateFail;
1656 break;
1657 case Accelerate::kError:
1658 // TODO(hlundin): Map to kModeError instead?
1659 last_mode_ = kModeAccelerateFail;
1660 return kAccelerateError;
1661 }
1662
1663 if (borrowed_samples_per_channel > 0) {
1664 // Copy borrowed samples back to the |sync_buffer_|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001665 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001666 if (length < borrowed_samples_per_channel) {
1667 // This destroys the beginning of the buffer, but will not cause any
1668 // problems.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001669 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001670 sync_buffer_->Size() -
1671 borrowed_samples_per_channel);
1672 sync_buffer_->PushFrontZeros(borrowed_samples_per_channel - length);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001673 algorithm_buffer_->PopFront(length);
1674 assert(algorithm_buffer_->Empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001675 } else {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001676 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001677 borrowed_samples_per_channel,
1678 sync_buffer_->Size() -
1679 borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001680 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001681 }
1682 }
1683
1684 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1685 if (speech_type == AudioDecoder::kComfortNoise) {
1686 last_mode_ = kModeCodecInternalCng;
1687 }
1688 if (!play_dtmf) {
1689 dtmf_tone_generator_->Reset();
1690 }
1691 expand_->Reset();
1692 return 0;
1693}
1694
1695int NetEqImpl::DoPreemptiveExpand(int16_t* decoded_buffer,
1696 size_t decoded_length,
1697 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001698 bool play_dtmf) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001699 const size_t required_samples =
1700 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001701 size_t num_channels = algorithm_buffer_->Channels();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001702 size_t borrowed_samples_per_channel = 0;
1703 size_t old_borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001704 size_t decoded_length_per_channel = decoded_length / num_channels;
1705 if (decoded_length_per_channel < required_samples) {
1706 // Must move data from the |sync_buffer_| in order to get 30 ms.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001707 borrowed_samples_per_channel =
1708 required_samples - decoded_length_per_channel;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001709 // Calculate how many of these were already played out.
Peter Kastingf045e4d2015-06-10 21:15:38 -07001710 old_borrowed_samples_per_channel =
Peter Kastingdce40cf2015-08-24 14:52:23 -07001711 (borrowed_samples_per_channel > sync_buffer_->FutureLength()) ?
1712 (borrowed_samples_per_channel - sync_buffer_->FutureLength()) : 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001713 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1714 decoded_buffer,
1715 sizeof(int16_t) * decoded_length);
1716 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1717 decoded_buffer);
1718 decoded_length = required_samples * num_channels;
1719 }
1720
Peter Kastingdce40cf2015-08-24 14:52:23 -07001721 size_t samples_added;
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001722 PreemptiveExpand::ReturnCodes return_code = preemptive_expand_->Process(
Peter Kastingdce40cf2015-08-24 14:52:23 -07001723 decoded_buffer, decoded_length,
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001724 old_borrowed_samples_per_channel,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001725 algorithm_buffer_.get(), &samples_added);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001726 stats_.PreemptiveExpandedSamples(samples_added);
1727 switch (return_code) {
1728 case PreemptiveExpand::kSuccess:
1729 last_mode_ = kModePreemptiveExpandSuccess;
1730 break;
1731 case PreemptiveExpand::kSuccessLowEnergy:
1732 last_mode_ = kModePreemptiveExpandLowEnergy;
1733 break;
1734 case PreemptiveExpand::kNoStretch:
1735 last_mode_ = kModePreemptiveExpandFail;
1736 break;
1737 case PreemptiveExpand::kError:
1738 // TODO(hlundin): Map to kModeError instead?
1739 last_mode_ = kModePreemptiveExpandFail;
1740 return kPreemptiveExpandError;
1741 }
1742
1743 if (borrowed_samples_per_channel > 0) {
1744 // Copy borrowed samples back to the |sync_buffer_|.
1745 sync_buffer_->ReplaceAtIndex(
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001746 *algorithm_buffer_, borrowed_samples_per_channel,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001747 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001748 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001749 }
1750
1751 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1752 if (speech_type == AudioDecoder::kComfortNoise) {
1753 last_mode_ = kModeCodecInternalCng;
1754 }
1755 if (!play_dtmf) {
1756 dtmf_tone_generator_->Reset();
1757 }
1758 expand_->Reset();
1759 return 0;
1760}
1761
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001762int NetEqImpl::DoRfc3389Cng(PacketList* packet_list, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001763 if (!packet_list->empty()) {
1764 // Must have exactly one SID frame at this point.
1765 assert(packet_list->size() == 1);
ossua73f6c92016-10-24 08:25:28 -07001766 const Packet& packet = packet_list->front();
1767 if (!decoder_database_->IsComfortNoise(packet.payload_type)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001768 RTC_LOG(LS_ERROR) << "Trying to decode non-CNG payload as CNG.";
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001769 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001770 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001771 if (comfort_noise_->UpdateParameters(packet) ==
1772 ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001773 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001774 return -comfort_noise_->internal_error_code();
1775 }
1776 }
1777 int cn_return = comfort_noise_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001778 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001779 expand_->Reset();
1780 last_mode_ = kModeRfc3389Cng;
1781 if (!play_dtmf) {
1782 dtmf_tone_generator_->Reset();
1783 }
1784 if (cn_return == ComfortNoise::kInternalError) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001785 RTC_LOG(LS_WARNING) << "Comfort noise generator returned error code: "
1786 << comfort_noise_->internal_error_code();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001787 return kComfortNoiseErrorCode;
1788 } else if (cn_return == ComfortNoise::kUnknownPayloadType) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001789 return kUnknownRtpPayloadType;
1790 }
1791 return 0;
1792}
1793
minyuel6d92bf52015-09-23 15:20:39 +02001794void NetEqImpl::DoCodecInternalCng(const int16_t* decoded_buffer,
1795 size_t decoded_length) {
1796 RTC_DCHECK(normal_.get());
1797 RTC_DCHECK(mute_factor_array_.get());
1798 normal_->Process(decoded_buffer, decoded_length, last_mode_,
1799 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001800 last_mode_ = kModeCodecInternalCng;
1801 expand_->Reset();
1802}
1803
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001804int NetEqImpl::DoDtmf(const DtmfEvent& dtmf_event, bool* play_dtmf) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001805 // This block of the code and the block further down, handling |dtmf_switch|
1806 // are commented out. Otherwise playing out-of-band DTMF would fail in VoE
1807 // test, DtmfTest.ManualSuccessfullySendsOutOfBandTelephoneEvents. This is
1808 // equivalent to |dtmf_switch| always be false.
1809 //
1810 // See http://webrtc-codereview.appspot.com/1195004/ for discussion
1811 // On this issue. This change might cause some glitches at the point of
1812 // switch from audio to DTMF. Issue 1545 is filed to track this.
1813 //
1814 // bool dtmf_switch = false;
1815 // if ((last_mode_ != kModeDtmf) && dtmf_tone_generator_->initialized()) {
1816 // // Special case; see below.
1817 // // We must catch this before calling Generate, since |initialized| is
1818 // // modified in that call.
1819 // dtmf_switch = true;
1820 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001821
1822 int dtmf_return_value = 0;
1823 if (!dtmf_tone_generator_->initialized()) {
1824 // Initialize if not already done.
1825 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1826 dtmf_event.volume);
1827 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001828
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001829 if (dtmf_return_value == 0) {
1830 // Generate DTMF signal.
1831 dtmf_return_value = dtmf_tone_generator_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001832 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001833 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001834
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001835 if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001836 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001837 return dtmf_return_value;
1838 }
1839
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001840 // if (dtmf_switch) {
1841 // // This is the special case where the previous operation was DTMF
1842 // // overdub, but the current instruction is "regular" DTMF. We must make
1843 // // sure that the DTMF does not have any discontinuities. The first DTMF
1844 // // sample that we generate now must be played out immediately, therefore
1845 // // it must be copied to the speech buffer.
1846 // // TODO(hlundin): This code seems incorrect. (Legacy.) Write test and
1847 // // verify correct operation.
1848 // assert(false);
1849 // // Must generate enough data to replace all of the |sync_buffer_|
1850 // // "future".
1851 // int required_length = sync_buffer_->FutureLength();
1852 // assert(dtmf_tone_generator_->initialized());
1853 // dtmf_return_value = dtmf_tone_generator_->Generate(required_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001854 // algorithm_buffer_);
1855 // assert((size_t) required_length == algorithm_buffer_->Size());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001856 // if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001857 // algorithm_buffer_->Zeros(output_size_samples_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001858 // return dtmf_return_value;
1859 // }
1860 //
1861 // // Overwrite the "future" part of the speech buffer with the new DTMF
1862 // // data.
1863 // // TODO(hlundin): It seems that this overwriting has gone lost.
1864 // // Not adapted for multi-channel yet.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001865 // assert(algorithm_buffer_->Channels() == 1);
1866 // if (algorithm_buffer_->Channels() != 1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001867 // RTC_LOG(LS_WARNING) << "DTMF not supported for more than one channel";
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001868 // return kStereoNotSupported;
1869 // }
1870 // // Shuffle the remaining data to the beginning of algorithm buffer.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001871 // algorithm_buffer_->PopFront(sync_buffer_->FutureLength());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001872 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001873
Peter Kastingb7e50542015-06-11 12:55:50 -07001874 sync_buffer_->IncreaseEndTimestamp(
1875 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001876 expand_->Reset();
1877 last_mode_ = kModeDtmf;
1878
1879 // Set to false because the DTMF is already in the algorithm buffer.
1880 *play_dtmf = false;
1881 return 0;
1882}
1883
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001884void NetEqImpl::DoAlternativePlc(bool increase_timestamp) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001885 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001886 size_t length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001887 if (decoder && decoder->HasDecodePlc()) {
1888 // Use the decoder's packet-loss concealment.
1889 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1890 int16_t decoded_buffer[kMaxFrameSize];
1891 length = decoder->DecodePlc(1, decoded_buffer);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001892 if (length > 0)
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001893 algorithm_buffer_->PushBackInterleaved(decoded_buffer, length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001894 } else {
1895 // Do simple zero-stuffing.
1896 length = output_size_samples_;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001897 algorithm_buffer_->Zeros(length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001898 // By not advancing the timestamp, NetEq inserts samples.
1899 stats_.AddZeros(length);
1900 }
1901 if (increase_timestamp) {
Peter Kastingb7e50542015-06-11 12:55:50 -07001902 sync_buffer_->IncreaseEndTimestamp(static_cast<uint32_t>(length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001903 }
1904 expand_->Reset();
1905}
1906
1907int NetEqImpl::DtmfOverdub(const DtmfEvent& dtmf_event, size_t num_channels,
1908 int16_t* output) const {
1909 size_t out_index = 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001910 size_t overdub_length = output_size_samples_; // Default value.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001911
1912 if (sync_buffer_->dtmf_index() > sync_buffer_->next_index()) {
1913 // Special operation for transition from "DTMF only" to "DTMF overdub".
1914 out_index = std::min(
1915 sync_buffer_->dtmf_index() - sync_buffer_->next_index(),
Peter Kastingdce40cf2015-08-24 14:52:23 -07001916 output_size_samples_);
1917 overdub_length = output_size_samples_ - out_index;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001918 }
1919
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001920 AudioMultiVector dtmf_output(num_channels);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001921 int dtmf_return_value = 0;
1922 if (!dtmf_tone_generator_->initialized()) {
1923 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1924 dtmf_event.volume);
1925 }
1926 if (dtmf_return_value == 0) {
1927 dtmf_return_value = dtmf_tone_generator_->Generate(overdub_length,
1928 &dtmf_output);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001929 assert(overdub_length == dtmf_output.Size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001930 }
1931 dtmf_output.ReadInterleaved(overdub_length, &output[out_index]);
1932 return dtmf_return_value < 0 ? dtmf_return_value : 0;
1933}
1934
Peter Kastingdce40cf2015-08-24 14:52:23 -07001935int NetEqImpl::ExtractPackets(size_t required_samples,
1936 PacketList* packet_list) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001937 bool first_packet = true;
1938 uint8_t prev_payload_type = 0;
1939 uint32_t prev_timestamp = 0;
1940 uint16_t prev_sequence_number = 0;
1941 bool next_packet_available = false;
1942
ossu7a377612016-10-18 04:06:13 -07001943 const Packet* next_packet = packet_buffer_->PeekNextPacket();
1944 RTC_DCHECK(next_packet);
1945 if (!next_packet) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001946 RTC_LOG(LS_ERROR) << "Packet buffer unexpectedly empty.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001947 return -1;
1948 }
ossu7a377612016-10-18 04:06:13 -07001949 uint32_t first_timestamp = next_packet->timestamp;
ossu61a208b2016-09-20 01:38:00 -07001950 size_t extracted_samples = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001951
1952 // Packet extraction loop.
1953 do {
ossu7a377612016-10-18 04:06:13 -07001954 timestamp_ = next_packet->timestamp;
ossua73f6c92016-10-24 08:25:28 -07001955 rtc::Optional<Packet> packet = packet_buffer_->GetNextPacket();
ossu7a377612016-10-18 04:06:13 -07001956 // |next_packet| may be invalid after the |packet_buffer_| operation.
ossua73f6c92016-10-24 08:25:28 -07001957 next_packet = nullptr;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001958 if (!packet) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001959 RTC_LOG(LS_ERROR) << "Should always be able to extract a packet here";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001960 assert(false); // Should always be able to extract a packet here.
1961 return -1;
1962 }
Gustaf Ullbergb0a02072017-10-02 12:00:34 +02001963 const uint64_t waiting_time_ms = packet->waiting_time->ElapsedMs();
1964 stats_.StoreWaitingTime(waiting_time_ms);
ossu61a208b2016-09-20 01:38:00 -07001965 RTC_DCHECK(!packet->empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001966
1967 if (first_packet) {
1968 first_packet = false;
henrik.lundin48ed9302015-10-29 05:36:24 -07001969 if (nack_enabled_) {
1970 RTC_DCHECK(nack_);
1971 // TODO(henrik.lundin): Should we update this for all decoded packets?
ossu7a377612016-10-18 04:06:13 -07001972 nack_->UpdateLastDecodedPacket(packet->sequence_number,
1973 packet->timestamp);
henrik.lundin48ed9302015-10-29 05:36:24 -07001974 }
ossu7a377612016-10-18 04:06:13 -07001975 prev_sequence_number = packet->sequence_number;
1976 prev_timestamp = packet->timestamp;
1977 prev_payload_type = packet->payload_type;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001978 }
1979
ossucafb4972017-01-02 07:00:50 -08001980 const bool has_cng_packet =
1981 decoder_database_->IsComfortNoise(packet->payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001982 // Store number of extracted samples.
ossu61a208b2016-09-20 01:38:00 -07001983 size_t packet_duration = 0;
1984 if (packet->frame) {
1985 packet_duration = packet->frame->Duration();
ossua70695a2016-09-22 02:06:28 -07001986 // TODO(ossu): Is this the correct way to track Opus FEC packets?
1987 if (packet->priority.codec_level > 0) {
kwibergd3edd772017-03-01 18:52:48 -08001988 stats_.SecondaryDecodedSamples(
1989 rtc::dchecked_cast<int>(packet_duration));
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001990 }
ossucafb4972017-01-02 07:00:50 -08001991 } else if (!has_cng_packet) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001992 RTC_LOG(LS_WARNING) << "Unknown payload type "
1993 << static_cast<int>(packet->payload_type);
ossu61a208b2016-09-20 01:38:00 -07001994 RTC_NOTREACHED();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001995 }
ossu61a208b2016-09-20 01:38:00 -07001996
1997 if (packet_duration == 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001998 // Decoder did not return a packet duration. Assume that the packet
1999 // contains the same number of samples as the previous one.
ossu61a208b2016-09-20 01:38:00 -07002000 packet_duration = decoder_frame_length_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002001 }
ossu7a377612016-10-18 04:06:13 -07002002 extracted_samples = packet->timestamp - first_timestamp + packet_duration;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002003
Gustaf Ullbergb0a02072017-10-02 12:00:34 +02002004 stats_.JitterBufferDelay(extracted_samples, waiting_time_ms);
2005
ossua73f6c92016-10-24 08:25:28 -07002006 packet_list->push_back(std::move(*packet)); // Store packet in list.
Oskar Sundbom12ab00b2017-11-16 15:31:38 +01002007 packet = rtc::nullopt; // Ensure it's never used after the move.
ossua73f6c92016-10-24 08:25:28 -07002008
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002009 // Check what packet is available next.
ossu7a377612016-10-18 04:06:13 -07002010 next_packet = packet_buffer_->PeekNextPacket();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002011 next_packet_available = false;
ossucafb4972017-01-02 07:00:50 -08002012 if (next_packet && prev_payload_type == next_packet->payload_type &&
2013 !has_cng_packet) {
ossu7a377612016-10-18 04:06:13 -07002014 int16_t seq_no_diff = next_packet->sequence_number - prev_sequence_number;
2015 size_t ts_diff = next_packet->timestamp - prev_timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002016 if (seq_no_diff == 1 ||
2017 (seq_no_diff == 0 && ts_diff == decoder_frame_length_)) {
2018 // The next sequence number is available, or the next part of a packet
2019 // that was split into pieces upon insertion.
2020 next_packet_available = true;
2021 }
ossu7a377612016-10-18 04:06:13 -07002022 prev_sequence_number = next_packet->sequence_number;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002023 }
ossu61a208b2016-09-20 01:38:00 -07002024 } while (extracted_samples < required_samples && next_packet_available);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002025
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00002026 if (extracted_samples > 0) {
2027 // Delete old packets only when we are going to decode something. Otherwise,
2028 // we could end up in the situation where we never decode anything, since
2029 // all incoming packets are considered too old but the buffer will also
2030 // never be flooded and flushed.
minyue-webrtcfae474c2017-07-05 11:17:40 +02002031 packet_buffer_->DiscardAllOldPackets(timestamp_, &stats_);
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00002032 }
2033
kwibergd3edd772017-03-01 18:52:48 -08002034 return rtc::dchecked_cast<int>(extracted_samples);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002035}
2036
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002037void NetEqImpl::UpdatePlcComponents(int fs_hz, size_t channels) {
2038 // Delete objects and create new ones.
2039 expand_.reset(expand_factory_->Create(background_noise_.get(),
2040 sync_buffer_.get(), &random_vector_,
Henrik Lundinbef77e22015-08-18 14:58:09 +02002041 &stats_, fs_hz, channels));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002042 merge_.reset(new Merge(fs_hz, channels, expand_.get(), sync_buffer_.get()));
2043}
2044
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002045void NetEqImpl::SetSampleRateAndChannels(int fs_hz, size_t channels) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002046 RTC_LOG(LS_VERBOSE) << "SetSampleRateAndChannels " << fs_hz << " "
2047 << channels;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002048 // TODO(hlundin): Change to an enumerator and skip assert.
2049 assert(fs_hz == 8000 || fs_hz == 16000 || fs_hz == 32000 || fs_hz == 48000);
2050 assert(channels > 0);
2051
2052 fs_hz_ = fs_hz;
2053 fs_mult_ = fs_hz / 8000;
Peter Kastingdce40cf2015-08-24 14:52:23 -07002054 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002055 decoder_frame_length_ = 3 * output_size_samples_; // Initialize to 30ms.
2056
2057 last_mode_ = kModeNormal;
2058
2059 // Create a new array of mute factors and set all to 1.
2060 mute_factor_array_.reset(new int16_t[channels]);
2061 for (size_t i = 0; i < channels; ++i) {
2062 mute_factor_array_[i] = 16384; // 1.0 in Q14.
2063 }
2064
ossu97ba30e2016-04-25 07:55:58 -07002065 ComfortNoiseDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02002066 if (cng_decoder)
2067 cng_decoder->Reset();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002068
2069 // Reinit post-decode VAD with new sample rate.
2070 assert(vad_.get()); // Cannot be NULL here.
2071 vad_->Init();
2072
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002073 // Delete algorithm buffer and create a new one.
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00002074 algorithm_buffer_.reset(new AudioMultiVector(channels));
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002075
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002076 // Delete sync buffer and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002077 sync_buffer_.reset(new SyncBuffer(channels, kSyncBufferSize * fs_mult_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002078
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00002079 // Delete BackgroundNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002080 background_noise_.reset(new BackgroundNoise(channels));
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00002081 background_noise_->set_mode(background_noise_mode_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002082
2083 // Reset random vector.
2084 random_vector_.Reset();
2085
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002086 UpdatePlcComponents(fs_hz, channels);
2087
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002088 // Move index so that we create a small set of future samples (all 0).
2089 sync_buffer_->set_next_index(sync_buffer_->next_index() -
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002090 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002091
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002092 normal_.reset(new Normal(fs_hz, decoder_database_.get(), *background_noise_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002093 expand_.get()));
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +00002094 accelerate_.reset(
2095 accelerate_factory_->Create(fs_hz, channels, *background_noise_));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002096 preemptive_expand_.reset(preemptive_expand_factory_->Create(
Peter Kastingdce40cf2015-08-24 14:52:23 -07002097 fs_hz, channels, *background_noise_, expand_->overlap_length()));
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002098
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002099 // Delete ComfortNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002100 comfort_noise_.reset(new ComfortNoise(fs_hz, decoder_database_.get(),
2101 sync_buffer_.get()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002102
2103 // Verify that |decoded_buffer_| is long enough.
2104 if (decoded_buffer_length_ < kMaxFrameSize * channels) {
2105 // Reallocate to larger size.
2106 decoded_buffer_length_ = kMaxFrameSize * channels;
2107 decoded_buffer_.reset(new int16_t[decoded_buffer_length_]);
2108 }
2109
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002110 // Create DecisionLogic if it is not created yet, then communicate new sample
2111 // rate and output size to DecisionLogic object.
2112 if (!decision_logic_.get()) {
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002113 CreateDecisionLogic();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002114 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002115 decision_logic_->SetSampleRate(fs_hz_, output_size_samples_);
2116}
2117
henrik.lundin55480f52016-03-08 02:37:57 -08002118NetEqImpl::OutputType NetEqImpl::LastOutputType() {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002119 assert(vad_.get());
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002120 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002121 if (last_mode_ == kModeCodecInternalCng || last_mode_ == kModeRfc3389Cng) {
henrik.lundin55480f52016-03-08 02:37:57 -08002122 return OutputType::kCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002123 } else if (last_mode_ == kModeExpand && expand_->MuteFactor(0) == 0) {
2124 // Expand mode has faded down to background noise only (very long expand).
henrik.lundin55480f52016-03-08 02:37:57 -08002125 return OutputType::kPLCCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002126 } else if (last_mode_ == kModeExpand) {
henrik.lundin55480f52016-03-08 02:37:57 -08002127 return OutputType::kPLC;
wu@webrtc.org24301a62013-12-13 19:17:43 +00002128 } else if (vad_->running() && !vad_->active_speech()) {
henrik.lundin55480f52016-03-08 02:37:57 -08002129 return OutputType::kVadPassive;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002130 } else {
henrik.lundin55480f52016-03-08 02:37:57 -08002131 return OutputType::kNormalSpeech;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002132 }
2133}
2134
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002135void NetEqImpl::CreateDecisionLogic() {
Henrik Lundin47b17dc2016-05-10 10:20:59 +02002136 decision_logic_.reset(DecisionLogic::Create(
2137 fs_hz_, output_size_samples_, playout_mode_, decoder_database_.get(),
2138 *packet_buffer_.get(), delay_manager_.get(), buffer_level_filter_.get(),
2139 tick_timer_.get()));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002140}
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002141} // namespace webrtc