blob: 857a4d7724e03c41b29df3d72ffe8a824342bdc3 [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"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020044#include "rtc_base/checks.h"
45#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010046#include "rtc_base/numerics/safe_conversions.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020047#include "rtc_base/sanitizer.h"
Jonas Olssonabbe8412018-04-03 13:40:05 +020048#include "rtc_base/strings/audio_format_to_string.h"
Karl Wiberg80ba3332018-02-05 10:33:35 +010049#include "rtc_base/system/fallthrough.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020050#include "rtc_base/trace_event.h"
Henrik Lundin18036282017-11-02 12:09:06 +010051#include "system_wrappers/include/field_trial.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000052
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000053namespace webrtc {
54
ossue3525782016-05-25 07:37:43 -070055NetEqImpl::Dependencies::Dependencies(
56 const NetEq::Config& config,
57 const rtc::scoped_refptr<AudioDecoderFactory>& decoder_factory)
henrik.lundin1d9061e2016-04-26 12:19:34 -070058 : tick_timer(new TickTimer),
59 buffer_level_filter(new BufferLevelFilter),
Karl Wiberg08126342018-03-20 19:18:55 +010060 decoder_database(
61 new DecoderDatabase(decoder_factory, config.codec_pair_id)),
henrik.lundinf3933702016-04-28 01:53:52 -070062 delay_peak_detector(new DelayPeakDetector(tick_timer.get())),
henrik.lundin1d9061e2016-04-26 12:19:34 -070063 delay_manager(new DelayManager(config.max_packets_in_buffer,
henrik.lundin8f8c96d2016-04-28 23:19:20 -070064 delay_peak_detector.get(),
65 tick_timer.get())),
henrik.lundin1d9061e2016-04-26 12:19:34 -070066 dtmf_buffer(new DtmfBuffer(config.sample_rate_hz)),
67 dtmf_tone_generator(new DtmfToneGenerator),
68 packet_buffer(
69 new PacketBuffer(config.max_packets_in_buffer, tick_timer.get())),
ossua70695a2016-09-22 02:06:28 -070070 red_payload_splitter(new RedPayloadSplitter),
henrik.lundin1d9061e2016-04-26 12:19:34 -070071 timestamp_scaler(new TimestampScaler(*decoder_database)),
72 accelerate_factory(new AccelerateFactory),
73 expand_factory(new ExpandFactory),
74 preemptive_expand_factory(new PreemptiveExpandFactory) {}
75
76NetEqImpl::Dependencies::~Dependencies() = default;
77
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +000078NetEqImpl::NetEqImpl(const NetEq::Config& config,
henrik.lundin1d9061e2016-04-26 12:19:34 -070079 Dependencies&& deps,
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +000080 bool create_components)
henrik.lundin1d9061e2016-04-26 12:19:34 -070081 : tick_timer_(std::move(deps.tick_timer)),
82 buffer_level_filter_(std::move(deps.buffer_level_filter)),
83 decoder_database_(std::move(deps.decoder_database)),
84 delay_manager_(std::move(deps.delay_manager)),
85 delay_peak_detector_(std::move(deps.delay_peak_detector)),
86 dtmf_buffer_(std::move(deps.dtmf_buffer)),
87 dtmf_tone_generator_(std::move(deps.dtmf_tone_generator)),
88 packet_buffer_(std::move(deps.packet_buffer)),
ossua70695a2016-09-22 02:06:28 -070089 red_payload_splitter_(std::move(deps.red_payload_splitter)),
henrik.lundin1d9061e2016-04-26 12:19:34 -070090 timestamp_scaler_(std::move(deps.timestamp_scaler)),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000091 vad_(new PostDecodeVad()),
henrik.lundin1d9061e2016-04-26 12:19:34 -070092 expand_factory_(std::move(deps.expand_factory)),
93 accelerate_factory_(std::move(deps.accelerate_factory)),
94 preemptive_expand_factory_(std::move(deps.preemptive_expand_factory)),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000095 last_mode_(kModeNormal),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000096 decoded_buffer_length_(kMaxFrameSize),
97 decoded_buffer_(new int16_t[decoded_buffer_length_]),
98 playout_timestamp_(0),
99 new_codec_(false),
100 timestamp_(0),
101 reset_decoder_(false),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000102 ssrc_(0),
103 first_packet_(true),
Henrik Lundincf808d22015-05-27 14:33:29 +0200104 enable_fast_accelerate_(config.enable_fast_accelerate),
henrik.lundin7a926812016-05-12 13:51:28 -0700105 nack_enabled_(false),
Henrik Lundin3ef3bfc2018-04-10 15:10:26 +0200106 enable_muted_state_(config.enable_muted_state),
107 expand_uma_logger_("WebRTC.Audio.ExpandRatePercent",
108 10, // Report once every 10 s.
109 tick_timer_.get()),
110 speech_expand_uma_logger_("WebRTC.Audio.SpeechExpandRatePercent",
111 10, // Report once every 10 s.
Henrik Lundin7687ad52018-07-02 10:14:46 +0200112 tick_timer_.get()),
113 no_time_stretching_(config.for_test_no_time_stretching) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100114 RTC_LOG(LS_INFO) << "NetEq config: " << config.ToString();
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +0000115 int fs = config.sample_rate_hz;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000116 if (fs != 8000 && fs != 16000 && fs != 32000 && fs != 48000) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100117 RTC_LOG(LS_ERROR) << "Sample rate " << fs << " Hz not supported. "
118 << "Changing to 8000 Hz.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000119 fs = 8000;
120 }
henrik.lundin1d9061e2016-04-26 12:19:34 -0700121 delay_manager_->SetMaximumDelay(config.max_delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000122 fs_hz_ = fs;
123 fs_mult_ = fs / 8000;
henrik.lundind89814b2015-11-23 06:49:25 -0800124 last_output_sample_rate_hz_ = fs;
Peter Kastingdce40cf2015-08-24 14:52:23 -0700125 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000126 decoder_frame_length_ = 3 * output_size_samples_;
127 WebRtcSpl_Init();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000128 if (create_components) {
129 SetSampleRateAndChannels(fs, 1); // Default is 1 channel.
130 }
henrik.lundin9bc26672015-11-02 03:25:57 -0800131 RTC_DCHECK(!vad_->enabled());
132 if (config.enable_post_decode_vad) {
133 vad_->Enable();
134 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000135}
136
Henrik Lundind67a2192015-08-03 12:54:37 +0200137NetEqImpl::~NetEqImpl() = default;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000138
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200139int NetEqImpl::InsertPacket(const RTPHeader& rtp_header,
kwibergee2bac22015-11-11 10:34:00 -0800140 rtc::ArrayView<const uint8_t> payload,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000141 uint32_t receive_timestamp) {
kwibergac554ee2016-09-02 00:39:33 -0700142 rtc::MsanCheckInitialized(payload);
henrik.lundina689b442015-12-17 03:50:05 -0800143 TRACE_EVENT0("webrtc", "NetEqImpl::InsertPacket");
Tommi9090e0b2016-01-20 13:39:36 +0100144 rtc::CritScope lock(&crit_sect_);
Henrik Lundinc417d9e2017-06-14 12:29:03 +0200145 if (InsertPacketInternal(rtp_header, payload, receive_timestamp) != 0) {
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000146 return kFail;
147 }
148 return kOK;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000149}
150
henrik.lundinb8c55b12017-05-10 07:38:01 -0700151void NetEqImpl::InsertEmptyPacket(const RTPHeader& /*rtp_header*/) {
152 // TODO(henrik.lundin) Handle NACK as well. This will make use of the
153 // rtp_header parameter.
154 // https://bugs.chromium.org/p/webrtc/issues/detail?id=7611
155 rtc::CritScope lock(&crit_sect_);
156 delay_manager_->RegisterEmptyPacket();
157}
158
henrik.lundin500c04b2016-03-08 02:36:04 -0800159namespace {
160void SetAudioFrameActivityAndType(bool vad_enabled,
henrik.lundin55480f52016-03-08 02:37:57 -0800161 NetEqImpl::OutputType type,
henrik.lundin500c04b2016-03-08 02:36:04 -0800162 AudioFrame::VADActivity last_vad_activity,
163 AudioFrame* audio_frame) {
164 switch (type) {
henrik.lundin55480f52016-03-08 02:37:57 -0800165 case NetEqImpl::OutputType::kNormalSpeech: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800166 audio_frame->speech_type_ = AudioFrame::kNormalSpeech;
167 audio_frame->vad_activity_ = AudioFrame::kVadActive;
168 break;
169 }
henrik.lundin55480f52016-03-08 02:37:57 -0800170 case NetEqImpl::OutputType::kVadPassive: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800171 // This should only be reached if the VAD is enabled.
172 RTC_DCHECK(vad_enabled);
173 audio_frame->speech_type_ = AudioFrame::kNormalSpeech;
174 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
175 break;
176 }
henrik.lundin55480f52016-03-08 02:37:57 -0800177 case NetEqImpl::OutputType::kCNG: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800178 audio_frame->speech_type_ = AudioFrame::kCNG;
179 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
180 break;
181 }
henrik.lundin55480f52016-03-08 02:37:57 -0800182 case NetEqImpl::OutputType::kPLC: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800183 audio_frame->speech_type_ = AudioFrame::kPLC;
184 audio_frame->vad_activity_ = last_vad_activity;
185 break;
186 }
henrik.lundin55480f52016-03-08 02:37:57 -0800187 case NetEqImpl::OutputType::kPLCCNG: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800188 audio_frame->speech_type_ = AudioFrame::kPLCCNG;
189 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
190 break;
191 }
192 default:
193 RTC_NOTREACHED();
194 }
195 if (!vad_enabled) {
196 // Always set kVadUnknown when receive VAD is inactive.
197 audio_frame->vad_activity_ = AudioFrame::kVadUnknown;
198 }
199}
henrik.lundinbc89de32016-03-08 05:20:14 -0800200} // namespace
henrik.lundin500c04b2016-03-08 02:36:04 -0800201
Ivo Creusen55de08e2018-09-03 11:49:27 +0200202int NetEqImpl::GetAudio(AudioFrame* audio_frame,
203 bool* muted,
204 absl::optional<Operations> action_override) {
henrik.lundine1ca1672016-01-08 03:50:08 -0800205 TRACE_EVENT0("webrtc", "NetEqImpl::GetAudio");
Tommi9090e0b2016-01-20 13:39:36 +0100206 rtc::CritScope lock(&crit_sect_);
Ivo Creusen55de08e2018-09-03 11:49:27 +0200207 if (GetAudioInternal(audio_frame, muted, action_override) != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000208 return kFail;
209 }
henrik.lundin5fac3f02016-08-24 11:18:49 -0700210 RTC_DCHECK_EQ(
211 audio_frame->sample_rate_hz_,
kwibergd3edd772017-03-01 18:52:48 -0800212 rtc::dchecked_cast<int>(audio_frame->samples_per_channel_ * 100));
henrik.lundina4491072017-07-06 05:23:53 -0700213 RTC_DCHECK_EQ(*muted, audio_frame->muted());
henrik.lundin500c04b2016-03-08 02:36:04 -0800214 SetAudioFrameActivityAndType(vad_->enabled(), LastOutputType(),
215 last_vad_activity_, audio_frame);
216 last_vad_activity_ = audio_frame->vad_activity_;
henrik.lundin6d8e0112016-03-04 10:34:21 -0800217 last_output_sample_rate_hz_ = audio_frame->sample_rate_hz_;
henrik.lundind89814b2015-11-23 06:49:25 -0800218 RTC_DCHECK(last_output_sample_rate_hz_ == 8000 ||
219 last_output_sample_rate_hz_ == 16000 ||
220 last_output_sample_rate_hz_ == 32000 ||
221 last_output_sample_rate_hz_ == 48000)
222 << "Unexpected sample rate " << last_output_sample_rate_hz_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000223 return kOK;
224}
225
kwiberg1c07c702017-03-27 07:15:49 -0700226void NetEqImpl::SetCodecs(const std::map<int, SdpAudioFormat>& codecs) {
227 rtc::CritScope lock(&crit_sect_);
228 const std::vector<int> changed_payload_types =
229 decoder_database_->SetCodecs(codecs);
230 for (const int pt : changed_payload_types) {
minyue-webrtcfae474c2017-07-05 11:17:40 +0200231 packet_buffer_->DiscardPacketsWithPayloadType(pt, &stats_);
kwiberg1c07c702017-03-27 07:15:49 -0700232 }
233}
234
kwibergee1879c2015-10-29 06:20:28 -0700235int NetEqImpl::RegisterPayloadType(NetEqDecoder codec,
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800236 const std::string& name,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000237 uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100238 rtc::CritScope lock(&crit_sect_);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100239 RTC_LOG(LS_VERBOSE) << "RegisterPayloadType "
240 << static_cast<int>(rtp_payload_type) << " "
241 << static_cast<int>(codec);
Henrik Lundinc417d9e2017-06-14 12:29:03 +0200242 if (decoder_database_->RegisterPayload(rtp_payload_type, codec, name) !=
243 DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000244 return kFail;
245 }
246 return kOK;
247}
248
249int NetEqImpl::RegisterExternalDecoder(AudioDecoder* decoder,
kwibergee1879c2015-10-29 06:20:28 -0700250 NetEqDecoder codec,
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800251 const std::string& codec_name,
kwiberg342f7402016-06-16 03:18:00 -0700252 uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100253 rtc::CritScope lock(&crit_sect_);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100254 RTC_LOG(LS_VERBOSE) << "RegisterExternalDecoder "
255 << static_cast<int>(rtp_payload_type) << " "
256 << static_cast<int>(codec);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000257 if (!decoder) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100258 RTC_LOG(LS_ERROR) << "Cannot register external decoder with NULL pointer";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000259 assert(false);
260 return kFail;
261 }
Henrik Lundinc417d9e2017-06-14 12:29:03 +0200262 if (decoder_database_->InsertExternal(rtp_payload_type, codec, codec_name,
263 decoder) != DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000264 return kFail;
265 }
266 return kOK;
267}
268
kwiberg5adaf732016-10-04 09:33:27 -0700269bool NetEqImpl::RegisterPayloadType(int rtp_payload_type,
270 const SdpAudioFormat& audio_format) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100271 RTC_LOG(LS_VERBOSE) << "NetEqImpl::RegisterPayloadType: payload type "
Jonas Olssonabbe8412018-04-03 13:40:05 +0200272 << rtp_payload_type << ", codec "
273 << rtc::ToString(audio_format);
kwiberg5adaf732016-10-04 09:33:27 -0700274 rtc::CritScope lock(&crit_sect_);
Henrik Lundinc417d9e2017-06-14 12:29:03 +0200275 return decoder_database_->RegisterPayload(rtp_payload_type, audio_format) ==
276 DecoderDatabase::kOK;
kwiberg5adaf732016-10-04 09:33:27 -0700277}
278
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000279int NetEqImpl::RemovePayloadType(uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100280 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000281 int ret = decoder_database_->Remove(rtp_payload_type);
Henrik Lundinc417d9e2017-06-14 12:29:03 +0200282 if (ret == DecoderDatabase::kOK || ret == DecoderDatabase::kDecoderNotFound) {
minyue-webrtcfae474c2017-07-05 11:17:40 +0200283 packet_buffer_->DiscardPacketsWithPayloadType(rtp_payload_type, &stats_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000284 return kOK;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000285 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000286 return kFail;
287}
288
kwiberg6b19b562016-09-20 04:02:25 -0700289void NetEqImpl::RemoveAllPayloadTypes() {
290 rtc::CritScope lock(&crit_sect_);
291 decoder_database_->RemoveAll();
292}
293
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000294bool NetEqImpl::SetMinimumDelay(int delay_ms) {
Tommi9090e0b2016-01-20 13:39:36 +0100295 rtc::CritScope lock(&crit_sect_);
Gustaf Ullberg48d96c02017-09-15 13:59:52 +0200296 if (delay_ms >= 0 && delay_ms <= 10000) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000297 assert(delay_manager_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000298 return delay_manager_->SetMinimumDelay(delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000299 }
300 return false;
301}
302
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000303bool NetEqImpl::SetMaximumDelay(int delay_ms) {
Tommi9090e0b2016-01-20 13:39:36 +0100304 rtc::CritScope lock(&crit_sect_);
Gustaf Ullberg48d96c02017-09-15 13:59:52 +0200305 if (delay_ms >= 0 && delay_ms <= 10000) {
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000306 assert(delay_manager_.get());
307 return delay_manager_->SetMaximumDelay(delay_ms);
308 }
309 return false;
310}
311
Henrik Lundinabbff892017-11-29 09:14:04 +0100312int NetEqImpl::TargetDelayMs() const {
henrik.lundin114c1b32017-04-26 07:47:32 -0700313 rtc::CritScope lock(&crit_sect_);
314 RTC_DCHECK(delay_manager_.get());
315 // The value from TargetLevel() is in number of packets, represented in Q8.
316 const size_t target_delay_samples =
317 (delay_manager_->TargetLevel() * decoder_frame_length_) >> 8;
318 return static_cast<int>(target_delay_samples) /
319 rtc::CheckedDivExact(fs_hz_, 1000);
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200320}
321
henrik.lundin9c3efd02015-08-27 13:12:22 -0700322int NetEqImpl::CurrentDelayMs() const {
Tommi9090e0b2016-01-20 13:39:36 +0100323 rtc::CritScope lock(&crit_sect_);
henrik.lundin9c3efd02015-08-27 13:12:22 -0700324 if (fs_hz_ == 0)
325 return 0;
326 // Sum up the samples in the packet buffer with the future length of the sync
327 // buffer, and divide the sum by the sample rate.
328 const size_t delay_samples =
ossu61a208b2016-09-20 01:38:00 -0700329 packet_buffer_->NumSamplesInBuffer(decoder_frame_length_) +
henrik.lundin9c3efd02015-08-27 13:12:22 -0700330 sync_buffer_->FutureLength();
331 // The division below will truncate.
332 const int delay_ms =
333 static_cast<int>(delay_samples) / rtc::CheckedDivExact(fs_hz_, 1000);
334 return delay_ms;
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200335}
336
henrik.lundinb3f1c5d2016-08-22 15:39:53 -0700337int NetEqImpl::FilteredCurrentDelayMs() const {
338 rtc::CritScope lock(&crit_sect_);
339 // Calculate the filtered packet buffer level in samples. The value from
340 // |buffer_level_filter_| is in number of packets, represented in Q8.
341 const size_t packet_buffer_samples =
342 (buffer_level_filter_->filtered_current_level() *
343 decoder_frame_length_) >>
344 8;
345 // Sum up the filtered packet buffer level with the future length of the sync
346 // buffer, and divide the sum by the sample rate.
347 const size_t delay_samples =
348 packet_buffer_samples + sync_buffer_->FutureLength();
349 // The division below will truncate. The return value is in ms.
350 return static_cast<int>(delay_samples) / rtc::CheckedDivExact(fs_hz_, 1000);
351}
352
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000353int NetEqImpl::NetworkStatistics(NetEqNetworkStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100354 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000355 assert(decoder_database_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700356 const size_t total_samples_in_buffers =
ossu61a208b2016-09-20 01:38:00 -0700357 packet_buffer_->NumSamplesInBuffer(decoder_frame_length_) +
Peter Kastingdce40cf2015-08-24 14:52:23 -0700358 sync_buffer_->FutureLength();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000359 assert(delay_manager_.get());
360 assert(decision_logic_.get());
Henrik Lundindccfc402017-09-25 12:30:58 +0200361 const int ms_per_packet = rtc::dchecked_cast<int>(
362 decision_logic_->packet_length_samples() / (fs_hz_ / 1000));
363 stats_.PopulateDelayManagerStats(ms_per_packet, *delay_manager_.get(), stats);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000364 stats_.GetNetworkStatistics(fs_hz_, total_samples_in_buffers,
Henrik Lundindccfc402017-09-25 12:30:58 +0200365 decoder_frame_length_, stats);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000366 return 0;
367}
368
Steve Anton2dbc69f2017-08-24 17:15:13 -0700369NetEqLifetimeStatistics NetEqImpl::GetLifetimeStatistics() const {
370 rtc::CritScope lock(&crit_sect_);
371 return stats_.GetLifetimeStatistics();
372}
373
Ivo Creusend1c2f782018-09-13 14:39:55 +0200374NetEqOperationsAndState NetEqImpl::GetOperationsAndState() const {
375 rtc::CritScope lock(&crit_sect_);
376 auto result = stats_.GetOperationsAndState();
377 result.current_buffer_size_ms =
378 (packet_buffer_->NumSamplesInBuffer(decoder_frame_length_) +
379 sync_buffer_->FutureLength()) *
380 1000 / fs_hz_;
381 return result;
382}
383
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000384void NetEqImpl::GetRtcpStatistics(RtcpStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100385 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000386 if (stats) {
387 rtcp_.GetStatistics(false, stats);
388 }
389}
390
391void NetEqImpl::GetRtcpStatisticsNoReset(RtcpStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100392 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000393 if (stats) {
394 rtcp_.GetStatistics(true, stats);
395 }
396}
397
398void NetEqImpl::EnableVad() {
Tommi9090e0b2016-01-20 13:39:36 +0100399 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000400 assert(vad_.get());
401 vad_->Enable();
402}
403
404void NetEqImpl::DisableVad() {
Tommi9090e0b2016-01-20 13:39:36 +0100405 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000406 assert(vad_.get());
407 vad_->Disable();
408}
409
Danil Chapovalovb6021232018-06-19 13:26:36 +0200410absl::optional<uint32_t> NetEqImpl::GetPlayoutTimestamp() const {
Tommi9090e0b2016-01-20 13:39:36 +0100411 rtc::CritScope lock(&crit_sect_);
henrik.lundin0d96ab72016-04-06 12:28:26 -0700412 if (first_packet_ || last_mode_ == kModeRfc3389Cng ||
413 last_mode_ == kModeCodecInternalCng) {
wu@webrtc.org94454b72014-06-05 20:34:08 +0000414 // We don't have a valid RTP timestamp until we have decoded our first
henrik.lundin0d96ab72016-04-06 12:28:26 -0700415 // RTP packet. Also, the RTP timestamp is not accurate while playing CNG,
416 // which is indicated by returning an empty value.
Danil Chapovalovb6021232018-06-19 13:26:36 +0200417 return absl::nullopt;
wu@webrtc.org94454b72014-06-05 20:34:08 +0000418 }
Oskar Sundbom12ab00b2017-11-16 15:31:38 +0100419 return timestamp_scaler_->ToExternal(playout_timestamp_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000420}
421
henrik.lundind89814b2015-11-23 06:49:25 -0800422int NetEqImpl::last_output_sample_rate_hz() const {
Tommi9090e0b2016-01-20 13:39:36 +0100423 rtc::CritScope lock(&crit_sect_);
henrik.lundind89814b2015-11-23 06:49:25 -0800424 return last_output_sample_rate_hz_;
425}
426
Danil Chapovalovb6021232018-06-19 13:26:36 +0200427absl::optional<CodecInst> NetEqImpl::GetDecoder(int payload_type) const {
kwiberg6f0f6162016-09-20 03:07:46 -0700428 rtc::CritScope lock(&crit_sect_);
429 const DecoderDatabase::DecoderInfo* di =
430 decoder_database_->GetDecoderInfo(payload_type);
431 if (!di) {
Danil Chapovalovb6021232018-06-19 13:26:36 +0200432 return absl::nullopt;
kwiberg6f0f6162016-09-20 03:07:46 -0700433 }
434
435 // Create a CodecInst with some fields set. The remaining fields are zeroed,
436 // but we tell MSan to consider them uninitialized.
437 CodecInst ci = {0};
438 rtc::MsanMarkUninitialized(rtc::MakeArrayView(&ci, 1));
439 ci.pltype = payload_type;
kwiberge9413062016-11-03 05:29:05 -0700440 std::strncpy(ci.plname, di->get_name().c_str(), sizeof(ci.plname));
kwiberg6f0f6162016-09-20 03:07:46 -0700441 ci.plname[sizeof(ci.plname) - 1] = '\0';
solenberg2779bab2016-11-17 04:45:19 -0800442 ci.plfreq = di->IsRed() ? 8000 : di->SampleRateHz();
kwiberg6f0f6162016-09-20 03:07:46 -0700443 AudioDecoder* const decoder = di->GetDecoder();
444 ci.channels = decoder ? decoder->Channels() : 1;
Oskar Sundbom12ab00b2017-11-16 15:31:38 +0100445 return ci;
kwiberg6f0f6162016-09-20 03:07:46 -0700446}
447
Danil Chapovalovb6021232018-06-19 13:26:36 +0200448absl::optional<SdpAudioFormat> NetEqImpl::GetDecoderFormat(
ossuf1b08da2016-09-23 02:19:43 -0700449 int payload_type) const {
kwibergc4ccd4d2016-09-21 10:55:15 -0700450 rtc::CritScope lock(&crit_sect_);
451 const DecoderDatabase::DecoderInfo* const di =
452 decoder_database_->GetDecoderInfo(payload_type);
453 if (!di) {
Danil Chapovalovb6021232018-06-19 13:26:36 +0200454 return absl::nullopt; // Payload type not registered.
kwibergc4ccd4d2016-09-21 10:55:15 -0700455 }
Oskar Sundbom12ab00b2017-11-16 15:31:38 +0100456 return di->GetFormat();
kwibergc4ccd4d2016-09-21 10:55:15 -0700457}
458
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000459void NetEqImpl::FlushBuffers() {
Tommi9090e0b2016-01-20 13:39:36 +0100460 rtc::CritScope lock(&crit_sect_);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100461 RTC_LOG(LS_VERBOSE) << "FlushBuffers";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000462 packet_buffer_->Flush();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000463 assert(sync_buffer_.get());
464 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000465 sync_buffer_->Flush();
466 sync_buffer_->set_next_index(sync_buffer_->next_index() -
467 expand_->overlap_length());
468 // Set to wait for new codec.
469 first_packet_ = true;
470}
471
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000472void NetEqImpl::PacketBufferStatistics(int* current_num_packets,
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000473 int* max_num_packets) const {
Tommi9090e0b2016-01-20 13:39:36 +0100474 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000475 packet_buffer_->BufferStat(current_num_packets, max_num_packets);
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000476}
477
henrik.lundin48ed9302015-10-29 05:36:24 -0700478void NetEqImpl::EnableNack(size_t max_nack_list_size) {
Tommi9090e0b2016-01-20 13:39:36 +0100479 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700480 if (!nack_enabled_) {
481 const int kNackThresholdPackets = 2;
henrik.lundin91951862016-06-08 06:43:41 -0700482 nack_.reset(NackTracker::Create(kNackThresholdPackets));
henrik.lundin48ed9302015-10-29 05:36:24 -0700483 nack_enabled_ = true;
484 nack_->UpdateSampleRate(fs_hz_);
485 }
486 nack_->SetMaxNackListSize(max_nack_list_size);
487}
488
489void NetEqImpl::DisableNack() {
Tommi9090e0b2016-01-20 13:39:36 +0100490 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700491 nack_.reset();
492 nack_enabled_ = false;
493}
494
495std::vector<uint16_t> NetEqImpl::GetNackList(int64_t round_trip_time_ms) const {
Tommi9090e0b2016-01-20 13:39:36 +0100496 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700497 if (!nack_enabled_) {
498 return std::vector<uint16_t>();
499 }
500 RTC_DCHECK(nack_.get());
501 return nack_->GetNackList(round_trip_time_ms);
minyue@webrtc.orgd7301772013-08-29 00:58:14 +0000502}
503
henrik.lundin114c1b32017-04-26 07:47:32 -0700504std::vector<uint32_t> NetEqImpl::LastDecodedTimestamps() const {
505 rtc::CritScope lock(&crit_sect_);
506 return last_decoded_timestamps_;
507}
508
509int NetEqImpl::SyncBufferSizeMs() const {
510 rtc::CritScope lock(&crit_sect_);
511 return rtc::dchecked_cast<int>(sync_buffer_->FutureLength() /
512 rtc::CheckedDivExact(fs_hz_, 1000));
513}
514
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000515const SyncBuffer* NetEqImpl::sync_buffer_for_test() const {
Tommi9090e0b2016-01-20 13:39:36 +0100516 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000517 return sync_buffer_.get();
518}
519
minyue5bd33972016-05-02 04:46:11 -0700520Operations NetEqImpl::last_operation_for_test() const {
521 rtc::CritScope lock(&crit_sect_);
522 return last_operation_;
523}
524
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000525// Methods below this line are private.
526
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200527int NetEqImpl::InsertPacketInternal(const RTPHeader& rtp_header,
kwibergee2bac22015-11-11 10:34:00 -0800528 rtc::ArrayView<const uint8_t> payload,
ossu17e3fa12016-09-08 04:52:55 -0700529 uint32_t receive_timestamp) {
kwibergee2bac22015-11-11 10:34:00 -0800530 if (payload.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100531 RTC_LOG_F(LS_ERROR) << "payload is empty";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000532 return kInvalidPointer;
533 }
ossu17e3fa12016-09-08 04:52:55 -0700534
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000535 PacketList packet_list;
ossua73f6c92016-10-24 08:25:28 -0700536 // Insert packet in a packet list.
537 packet_list.push_back([&rtp_header, &payload] {
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000538 // Convert to Packet.
ossua73f6c92016-10-24 08:25:28 -0700539 Packet packet;
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200540 packet.payload_type = rtp_header.payloadType;
541 packet.sequence_number = rtp_header.sequenceNumber;
542 packet.timestamp = rtp_header.timestamp;
ossua73f6c92016-10-24 08:25:28 -0700543 packet.payload.SetData(payload.data(), payload.size());
henrik.lundin84f8cd62016-04-26 07:45:16 -0700544 // Waiting time will be set upon inserting the packet in the buffer.
ossua73f6c92016-10-24 08:25:28 -0700545 RTC_DCHECK(!packet.waiting_time);
546 return packet;
547 }());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000548
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200549 bool update_sample_rate_and_channels =
550 first_packet_ || (rtp_header.ssrc != ssrc_);
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700551
552 if (update_sample_rate_and_channels) {
553 // Reset timestamp scaling.
554 timestamp_scaler_->Reset();
555 }
556
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200557 if (!decoder_database_->IsRed(rtp_header.payloadType)) {
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700558 // Scale timestamp to internal domain (only for some codecs).
559 timestamp_scaler_->ToInternal(&packet_list);
560 }
561
562 // Store these for later use, since the first packet may very well disappear
563 // before we need these values.
564 uint32_t main_timestamp = packet_list.front().timestamp;
565 uint8_t main_payload_type = packet_list.front().payload_type;
566 uint16_t main_sequence_number = packet_list.front().sequence_number;
567
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000568 // Reinitialize NetEq if it's needed (changed SSRC or first call).
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700569 if (update_sample_rate_and_channels) {
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000570 // Note: |first_packet_| will be cleared further down in this method, once
571 // the packet has been successfully inserted into the packet buffer.
572
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200573 rtcp_.Init(rtp_header.sequenceNumber);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000574
575 // Flush the packet buffer and DTMF buffer.
576 packet_buffer_->Flush();
577 dtmf_buffer_->Flush();
578
579 // Store new SSRC.
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200580 ssrc_ = rtp_header.ssrc;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000581
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000582 // Update audio buffer timestamp.
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700583 sync_buffer_->IncreaseEndTimestamp(main_timestamp - timestamp_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000584
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000585 // Update codecs.
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700586 timestamp_ = main_timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000587 }
588
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000589 // Update RTCP statistics, only for regular packets.
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200590 rtcp_.Update(rtp_header, receive_timestamp);
ossu7a377612016-10-18 04:06:13 -0700591
592 if (nack_enabled_) {
593 RTC_DCHECK(nack_);
594 if (update_sample_rate_and_channels) {
595 nack_->Reset();
596 }
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200597 nack_->UpdateLastReceivedPacket(rtp_header.sequenceNumber,
598 rtp_header.timestamp);
ossu7a377612016-10-18 04:06:13 -0700599 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000600
601 // Check for RED payload type, and separate payloads into several packets.
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200602 if (decoder_database_->IsRed(rtp_header.payloadType)) {
ossua70695a2016-09-22 02:06:28 -0700603 if (!red_payload_splitter_->SplitRed(&packet_list)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000604 return kRedundancySplitError;
605 }
606 // Only accept a few RED payloads of the same type as the main data,
607 // DTMF events and CNG.
ossua70695a2016-09-22 02:06:28 -0700608 red_payload_splitter_->CheckRedPayloads(&packet_list, *decoder_database_);
Henrik Lundindefa7a82018-07-03 13:07:30 +0200609 if (packet_list.empty()) {
610 return kRedundancySplitError;
611 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000612 }
613
614 // Check payload types.
615 if (decoder_database_->CheckPayloadTypes(packet_list) ==
616 DecoderDatabase::kDecoderNotFound) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000617 return kUnknownRtpPayloadType;
618 }
619
ossu7a377612016-10-18 04:06:13 -0700620 RTC_DCHECK(!packet_list.empty());
ossu7a377612016-10-18 04:06:13 -0700621
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700622 // Update main_timestamp, if new packets appear in the list
623 // after RED splitting.
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200624 if (decoder_database_->IsRed(rtp_header.payloadType)) {
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700625 timestamp_scaler_->ToInternal(&packet_list);
626 main_timestamp = packet_list.front().timestamp;
627 main_payload_type = packet_list.front().payload_type;
628 main_sequence_number = packet_list.front().sequence_number;
629 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000630
631 // Process DTMF payloads. Cycle through the list of packets, and pick out any
632 // DTMF payloads found.
633 PacketList::iterator it = packet_list.begin();
634 while (it != packet_list.end()) {
ossua73f6c92016-10-24 08:25:28 -0700635 const Packet& current_packet = (*it);
636 RTC_DCHECK(!current_packet.payload.empty());
637 if (decoder_database_->IsDtmf(current_packet.payload_type)) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000638 DtmfEvent event;
ossua73f6c92016-10-24 08:25:28 -0700639 int ret = DtmfBuffer::ParseEvent(current_packet.timestamp,
640 current_packet.payload.data(),
641 current_packet.payload.size(), &event);
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000642 if (ret != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000643 return kDtmfParsingError;
644 }
645 if (dtmf_buffer_->InsertEvent(event) != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000646 return kDtmfInsertError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000647 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000648 it = packet_list.erase(it);
649 } else {
650 ++it;
651 }
652 }
653
ossu17e3fa12016-09-08 04:52:55 -0700654 // Update bandwidth estimate, if the packet is not comfort noise.
655 if (!packet_list.empty() &&
ossu7a377612016-10-18 04:06:13 -0700656 !decoder_database_->IsComfortNoise(main_payload_type)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000657 // The list can be empty here if we got nothing but DTMF payloads.
ossu7a377612016-10-18 04:06:13 -0700658 AudioDecoder* decoder = decoder_database_->GetDecoder(main_payload_type);
659 RTC_DCHECK(decoder); // Should always get a valid object, since we have
660 // already checked that the payload types are known.
ossua73f6c92016-10-24 08:25:28 -0700661 decoder->IncomingPacket(packet_list.front().payload.data(),
662 packet_list.front().payload.size(),
663 packet_list.front().sequence_number,
Yves Gerey665174f2018-06-19 15:03:05 +0200664 packet_list.front().timestamp, receive_timestamp);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000665 }
666
ossu61a208b2016-09-20 01:38:00 -0700667 PacketList parsed_packet_list;
668 while (!packet_list.empty()) {
ossua73f6c92016-10-24 08:25:28 -0700669 Packet& packet = packet_list.front();
ossu61a208b2016-09-20 01:38:00 -0700670 const DecoderDatabase::DecoderInfo* info =
ossua73f6c92016-10-24 08:25:28 -0700671 decoder_database_->GetDecoderInfo(packet.payload_type);
ossu61a208b2016-09-20 01:38:00 -0700672 if (!info) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100673 RTC_LOG(LS_WARNING) << "SplitAudio unknown payload type";
ossu61a208b2016-09-20 01:38:00 -0700674 return kUnknownRtpPayloadType;
675 }
676
677 if (info->IsComfortNoise()) {
678 // Carry comfort noise packets along.
ossua73f6c92016-10-24 08:25:28 -0700679 parsed_packet_list.splice(parsed_packet_list.end(), packet_list,
680 packet_list.begin());
ossu61a208b2016-09-20 01:38:00 -0700681 } else {
ossua73f6c92016-10-24 08:25:28 -0700682 const auto sequence_number = packet.sequence_number;
683 const auto payload_type = packet.payload_type;
684 const Packet::Priority original_priority = packet.priority;
Yves Gerey665174f2018-06-19 15:03:05 +0200685 auto packet_from_result = [&](AudioDecoder::ParseResult& result) {
ossua73f6c92016-10-24 08:25:28 -0700686 Packet new_packet;
687 new_packet.sequence_number = sequence_number;
688 new_packet.payload_type = payload_type;
689 new_packet.timestamp = result.timestamp;
690 new_packet.priority.codec_level = result.priority;
691 new_packet.priority.red_level = original_priority.red_level;
692 new_packet.frame = std::move(result.frame);
693 return new_packet;
694 };
695
ossu61a208b2016-09-20 01:38:00 -0700696 std::vector<AudioDecoder::ParseResult> results =
ossua73f6c92016-10-24 08:25:28 -0700697 info->GetDecoder()->ParsePayload(std::move(packet.payload),
698 packet.timestamp);
699 if (results.empty()) {
700 packet_list.pop_front();
701 } else {
702 bool first = true;
703 for (auto& result : results) {
704 RTC_DCHECK(result.frame);
705 RTC_DCHECK_GE(result.priority, 0);
706 if (first) {
707 // Re-use the node and move it to parsed_packet_list.
708 packet_list.front() = packet_from_result(result);
709 parsed_packet_list.splice(parsed_packet_list.end(), packet_list,
710 packet_list.begin());
711 first = false;
712 } else {
713 parsed_packet_list.push_back(packet_from_result(result));
714 }
ossu61a208b2016-09-20 01:38:00 -0700715 }
ossu61a208b2016-09-20 01:38:00 -0700716 }
717 }
718 }
719
Ivo Creusenfd7c0a52017-10-20 12:35:04 +0200720 // Calculate the number of primary (non-FEC/RED) packets.
721 const int number_of_primary_packets = std::count_if(
722 parsed_packet_list.begin(), parsed_packet_list.end(),
723 [](const Packet& in) { return in.priority.codec_level == 0; });
724
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000725 // Insert packets in buffer.
ossua70695a2016-09-22 02:06:28 -0700726 const int ret = packet_buffer_->InsertPacketList(
ossu61a208b2016-09-20 01:38:00 -0700727 &parsed_packet_list, *decoder_database_, &current_rtp_payload_type_,
minyue-webrtc12d30842017-07-19 11:44:06 +0200728 &current_cng_rtp_payload_type_, &stats_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000729 if (ret == PacketBuffer::kFlushed) {
730 // Reset DSP timestamp etc. if packet buffer flushed.
731 new_codec_ = true;
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000732 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000733 } else if (ret != PacketBuffer::kOK) {
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000734 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000735 }
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000736
737 if (first_packet_) {
738 first_packet_ = false;
739 // Update the codec on the next GetAudio call.
740 new_codec_ = true;
741 }
742
henrik.lundinda8bbf62016-08-31 03:14:11 -0700743 if (current_rtp_payload_type_) {
744 RTC_DCHECK(decoder_database_->GetDecoderInfo(*current_rtp_payload_type_))
745 << "Payload type " << static_cast<int>(*current_rtp_payload_type_)
746 << " is unknown where it shouldn't be";
747 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000748
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000749 if (update_sample_rate_and_channels && !packet_buffer_->Empty()) {
750 // We do not use |current_rtp_payload_type_| to |set payload_type|, but
751 // get the next RTP header from |packet_buffer_| to obtain the payload type.
752 // The reason for it is the following corner case. If NetEq receives a
753 // CNG packet with a sample rate different than the current CNG then it
754 // flushes its buffer, assuming send codec must have been changed. However,
755 // payload type of the hypothetically new send codec is not known.
ossu7a377612016-10-18 04:06:13 -0700756 const Packet* next_packet = packet_buffer_->PeekNextPacket();
757 RTC_DCHECK(next_packet);
758 const int payload_type = next_packet->payload_type;
ossu97ba30e2016-04-25 07:55:58 -0700759 size_t channels = 1;
760 if (!decoder_database_->IsComfortNoise(payload_type)) {
761 AudioDecoder* decoder = decoder_database_->GetDecoder(payload_type);
762 assert(decoder); // Payloads are already checked to be valid.
763 channels = decoder->Channels();
764 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000765 const DecoderDatabase::DecoderInfo* decoder_info =
766 decoder_database_->GetDecoderInfo(payload_type);
767 assert(decoder_info);
kwibergc0f2dcf2016-05-31 06:28:03 -0700768 if (decoder_info->SampleRateHz() != fs_hz_ ||
ossu97ba30e2016-04-25 07:55:58 -0700769 channels != algorithm_buffer_->Channels()) {
Yves Gerey665174f2018-06-19 15:03:05 +0200770 SetSampleRateAndChannels(decoder_info->SampleRateHz(), channels);
henrik.lundin48ed9302015-10-29 05:36:24 -0700771 }
772 if (nack_enabled_) {
773 RTC_DCHECK(nack_);
774 // Update the sample rate even if the rate is not new, because of Reset().
775 nack_->UpdateSampleRate(fs_hz_);
776 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000777 }
778
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000779 // TODO(hlundin): Move this code to DelayManager class.
780 const DecoderDatabase::DecoderInfo* dec_info =
ossu7a377612016-10-18 04:06:13 -0700781 decoder_database_->GetDecoderInfo(main_payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000782 assert(dec_info); // Already checked that the payload type is known.
ossuf1b08da2016-09-23 02:19:43 -0700783 delay_manager_->LastDecodedWasCngOrDtmf(dec_info->IsComfortNoise() ||
784 dec_info->IsDtmf());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000785 if (delay_manager_->last_pack_cng_or_dtmf() == 0) {
786 // Calculate the total speech length carried in each packet.
Ivo Creusenfd7c0a52017-10-20 12:35:04 +0200787 if (number_of_primary_packets > 0) {
henrik.lundin116c84e2015-08-27 13:14:48 -0700788 const size_t packet_length_samples =
Ivo Creusenfd7c0a52017-10-20 12:35:04 +0200789 number_of_primary_packets * decoder_frame_length_;
henrik.lundin116c84e2015-08-27 13:14:48 -0700790 if (packet_length_samples != decision_logic_->packet_length_samples()) {
791 decision_logic_->set_packet_length_samples(packet_length_samples);
792 delay_manager_->SetPacketAudioLength(
kwibergd3edd772017-03-01 18:52:48 -0800793 rtc::dchecked_cast<int>((1000 * packet_length_samples) / fs_hz_));
henrik.lundin116c84e2015-08-27 13:14:48 -0700794 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000795 }
796
797 // Update statistics.
ossu7a377612016-10-18 04:06:13 -0700798 if ((int32_t)(main_timestamp - timestamp_) >= 0 && !new_codec_) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000799 // Only update statistics if incoming packet is not older than last played
800 // out packet, and if new codec flag is not set.
ossu7a377612016-10-18 04:06:13 -0700801 delay_manager_->Update(main_sequence_number, main_timestamp, fs_hz_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000802 }
803 } else if (delay_manager_->last_pack_cng_or_dtmf() == -1) {
804 // This is first "normal" packet after CNG or DTMF.
805 // Reset packet time counter and measure time until next packet,
806 // but don't update statistics.
807 delay_manager_->set_last_pack_cng_or_dtmf(0);
808 delay_manager_->ResetPacketIatCount();
809 }
810 return 0;
811}
812
Ivo Creusen55de08e2018-09-03 11:49:27 +0200813int NetEqImpl::GetAudioInternal(AudioFrame* audio_frame,
814 bool* muted,
815 absl::optional<Operations> action_override) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000816 PacketList packet_list;
817 DtmfEvent dtmf_event;
818 Operations operation;
819 bool play_dtmf;
henrik.lundin7a926812016-05-12 13:51:28 -0700820 *muted = false;
henrik.lundin114c1b32017-04-26 07:47:32 -0700821 last_decoded_timestamps_.clear();
henrik.lundined497212016-04-25 10:11:38 -0700822 tick_timer_->Increment();
henrik.lundin60f6ce22016-05-10 03:52:04 -0700823 stats_.IncreaseCounter(output_size_samples_, fs_hz_);
Henrik Lundin3ef3bfc2018-04-10 15:10:26 +0200824 const auto lifetime_stats = stats_.GetLifetimeStatistics();
825 expand_uma_logger_.UpdateSampleCounter(lifetime_stats.concealed_samples,
826 fs_hz_);
827 speech_expand_uma_logger_.UpdateSampleCounter(
828 lifetime_stats.voice_concealed_samples, fs_hz_);
henrik.lundin7a926812016-05-12 13:51:28 -0700829
830 // Check for muted state.
831 if (enable_muted_state_ && expand_->Muted() && packet_buffer_->Empty()) {
832 RTC_DCHECK_EQ(last_mode_, kModeExpand);
henrik.lundina4491072017-07-06 05:23:53 -0700833 audio_frame->Reset();
834 RTC_DCHECK(audio_frame->muted()); // Reset() should mute the frame.
henrik.lundin7a926812016-05-12 13:51:28 -0700835 playout_timestamp_ += static_cast<uint32_t>(output_size_samples_);
836 audio_frame->sample_rate_hz_ = fs_hz_;
837 audio_frame->samples_per_channel_ = output_size_samples_;
838 audio_frame->timestamp_ =
839 first_packet_
840 ? 0
841 : timestamp_scaler_->ToExternal(playout_timestamp_) -
842 static_cast<uint32_t>(audio_frame->samples_per_channel_);
843 audio_frame->num_channels_ = sync_buffer_->Channels();
Gustaf Ullberg9a2e9062017-09-18 09:28:20 +0200844 stats_.ExpandedNoiseSamples(output_size_samples_, false);
henrik.lundin7a926812016-05-12 13:51:28 -0700845 *muted = true;
846 return 0;
847 }
Ivo Creusen55de08e2018-09-03 11:49:27 +0200848 int return_value = GetDecision(&operation, &packet_list, &dtmf_event,
849 &play_dtmf, action_override);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000850 if (return_value != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000851 last_mode_ = kModeError;
852 return return_value;
853 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000854
855 AudioDecoder::SpeechType speech_type;
856 int length = 0;
Henrik Lundin18036282017-11-02 12:09:06 +0100857 const size_t start_num_packets = packet_list.size();
Yves Gerey665174f2018-06-19 15:03:05 +0200858 int decode_return_value =
859 Decode(&packet_list, &operation, &length, &speech_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000860
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000861 assert(vad_.get());
Yves Gerey665174f2018-06-19 15:03:05 +0200862 bool sid_frame_available = (operation == kRfc3389Cng && !packet_list.empty());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700863 vad_->Update(decoded_buffer_.get(), static_cast<size_t>(length), speech_type,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000864 sid_frame_available, fs_hz_);
865
Henrik Lundin18036282017-11-02 12:09:06 +0100866 // This is the criterion that we did decode some data through the speech
867 // decoder, and the operation resulted in comfort noise.
868 const bool codec_internal_sid_frame =
Henrik Lundin4f2a4a12018-01-26 17:32:56 +0100869 (speech_type == AudioDecoder::kComfortNoise &&
870 start_num_packets > packet_list.size());
Henrik Lundin18036282017-11-02 12:09:06 +0100871
872 if (sid_frame_available || codec_internal_sid_frame) {
henrik.lundinb1fb72b2016-05-03 08:18:47 -0700873 // Start a new stopwatch since we are decoding a new CNG packet.
874 generated_noise_stopwatch_ = tick_timer_->GetNewStopwatch();
875 }
876
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000877 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000878 switch (operation) {
879 case kNormal: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000880 DoNormal(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000881 break;
882 }
883 case kMerge: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000884 DoMerge(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000885 break;
886 }
887 case kExpand: {
Henrik Lundin00eb12a2018-09-05 18:14:52 +0200888 RTC_DCHECK_EQ(return_value, 0);
889 if (!current_rtp_payload_type_ || !DoCodecPlc()) {
890 return_value = DoExpand(play_dtmf);
891 }
892 RTC_DCHECK_GE(sync_buffer_->FutureLength() - expand_->overlap_length(),
893 output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000894 break;
895 }
Henrik Lundincf808d22015-05-27 14:33:29 +0200896 case kAccelerate:
897 case kFastAccelerate: {
898 const bool fast_accelerate =
899 enable_fast_accelerate_ && (operation == kFastAccelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000900 return_value = DoAccelerate(decoded_buffer_.get(), length, speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +0200901 play_dtmf, fast_accelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000902 break;
903 }
904 case kPreemptiveExpand: {
905 return_value = DoPreemptiveExpand(decoded_buffer_.get(), length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000906 speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000907 break;
908 }
909 case kRfc3389Cng:
910 case kRfc3389CngNoPacket: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000911 return_value = DoRfc3389Cng(&packet_list, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000912 break;
913 }
914 case kCodecInternalCng: {
915 // This handles the case when there is no transmission and the decoder
916 // should produce internal comfort noise.
917 // TODO(hlundin): Write test for codec-internal CNG.
minyuel6d92bf52015-09-23 15:20:39 +0200918 DoCodecInternalCng(decoded_buffer_.get(), length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000919 break;
920 }
921 case kDtmf: {
922 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000923 return_value = DoDtmf(dtmf_event, &play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000924 break;
925 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000926 case kUndefined: {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100927 RTC_LOG(LS_ERROR) << "Invalid operation kUndefined.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000928 assert(false); // This should not happen.
929 last_mode_ = kModeError;
930 return kInvalidOperation;
931 }
932 } // End of switch.
minyue5bd33972016-05-02 04:46:11 -0700933 last_operation_ = operation;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000934 if (return_value < 0) {
935 return return_value;
936 }
937
938 if (last_mode_ != kModeRfc3389Cng) {
939 comfort_noise_->Reset();
940 }
941
942 // Copy from |algorithm_buffer| to |sync_buffer_|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000943 sync_buffer_->PushBack(*algorithm_buffer_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000944
945 // Extract data from |sync_buffer_| to |output|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000946 size_t num_output_samples_per_channel = output_size_samples_;
947 size_t num_output_samples = output_size_samples_ * sync_buffer_->Channels();
henrik.lundin6d8e0112016-03-04 10:34:21 -0800948 if (num_output_samples > AudioFrame::kMaxDataSizeSamples) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100949 RTC_LOG(LS_WARNING) << "Output array is too short. "
950 << AudioFrame::kMaxDataSizeSamples << " < "
951 << output_size_samples_ << " * "
952 << sync_buffer_->Channels();
henrik.lundin6d8e0112016-03-04 10:34:21 -0800953 num_output_samples = AudioFrame::kMaxDataSizeSamples;
954 num_output_samples_per_channel =
955 AudioFrame::kMaxDataSizeSamples / sync_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000956 }
henrik.lundin6d8e0112016-03-04 10:34:21 -0800957 sync_buffer_->GetNextAudioInterleaved(num_output_samples_per_channel,
958 audio_frame);
959 audio_frame->sample_rate_hz_ = fs_hz_;
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200960 if (sync_buffer_->FutureLength() < expand_->overlap_length()) {
961 // The sync buffer should always contain |overlap_length| samples, but now
962 // too many samples have been extracted. Reinstall the |overlap_length|
963 // lookahead by moving the index.
964 const size_t missing_lookahead_samples =
965 expand_->overlap_length() - sync_buffer_->FutureLength();
henrikg91d6ede2015-09-17 00:24:34 -0700966 RTC_DCHECK_GE(sync_buffer_->next_index(), missing_lookahead_samples);
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200967 sync_buffer_->set_next_index(sync_buffer_->next_index() -
968 missing_lookahead_samples);
969 }
henrik.lundin6d8e0112016-03-04 10:34:21 -0800970 if (audio_frame->samples_per_channel_ != output_size_samples_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100971 RTC_LOG(LS_ERROR) << "audio_frame->samples_per_channel_ ("
972 << audio_frame->samples_per_channel_
973 << ") != output_size_samples_ (" << output_size_samples_
974 << ")";
minyue@webrtc.orgdb1cefc2013-08-13 01:39:21 +0000975 // TODO(minyue): treatment of under-run, filling zeros
yujo36b1a5f2017-06-12 12:45:32 -0700976 audio_frame->Mute();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000977 return kSampleUnderrun;
978 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000979
980 // Should always have overlap samples left in the |sync_buffer_|.
henrikg91d6ede2015-09-17 00:24:34 -0700981 RTC_DCHECK_GE(sync_buffer_->FutureLength(), expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000982
yujo36b1a5f2017-06-12 12:45:32 -0700983 // TODO(yujo): For muted frames, this can be a copy rather than an addition.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000984 if (play_dtmf) {
yujo36b1a5f2017-06-12 12:45:32 -0700985 return_value = DtmfOverdub(dtmf_event, sync_buffer_->Channels(),
986 audio_frame->mutable_data());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000987 }
988
989 // Update the background noise parameters if last operation wrote data
990 // straight from the decoder to the |sync_buffer_|. That is, none of the
991 // operations that modify the signal can be followed by a parameter update.
Yves Gerey665174f2018-06-19 15:03:05 +0200992 if ((last_mode_ == kModeNormal) || (last_mode_ == kModeAccelerateFail) ||
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000993 (last_mode_ == kModePreemptiveExpandFail) ||
994 (last_mode_ == kModeRfc3389Cng) ||
995 (last_mode_ == kModeCodecInternalCng)) {
996 background_noise_->Update(*sync_buffer_, *vad_.get());
997 }
998
999 if (operation == kDtmf) {
1000 // DTMF data was written the end of |sync_buffer_|.
1001 // Update index to end of DTMF data in |sync_buffer_|.
1002 sync_buffer_->set_dtmf_index(sync_buffer_->Size());
1003 }
1004
Henrik Lundin00eb12a2018-09-05 18:14:52 +02001005 if (last_mode_ != kModeExpand && last_mode_ != kModeCodecPlc) {
henrik.lundin@webrtc.orged865b52014-03-06 10:28:07 +00001006 // If last operation was not expand, calculate the |playout_timestamp_| from
1007 // the |sync_buffer_|. However, do not update the |playout_timestamp_| if it
1008 // would be moved "backwards".
Yves Gerey665174f2018-06-19 15:03:05 +02001009 uint32_t temp_timestamp =
1010 sync_buffer_->end_timestamp() -
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001011 static_cast<uint32_t>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001012 if (static_cast<int32_t>(temp_timestamp - playout_timestamp_) > 0) {
1013 playout_timestamp_ = temp_timestamp;
1014 }
1015 } else {
1016 // Use dead reckoning to estimate the |playout_timestamp_|.
Peter Kastingb7e50542015-06-11 12:55:50 -07001017 playout_timestamp_ += static_cast<uint32_t>(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001018 }
henrik.lundin15c51e32016-04-06 08:38:56 -07001019 // Set the timestamp in the audio frame to zero before the first packet has
1020 // been inserted. Otherwise, subtract the frame size in samples to get the
1021 // timestamp of the first sample in the frame (playout_timestamp_ is the
1022 // last + 1).
1023 audio_frame->timestamp_ =
1024 first_packet_
1025 ? 0
1026 : timestamp_scaler_->ToExternal(playout_timestamp_) -
1027 static_cast<uint32_t>(audio_frame->samples_per_channel_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001028
Yves Gerey665174f2018-06-19 15:03:05 +02001029 if (!(last_mode_ == kModeRfc3389Cng || last_mode_ == kModeCodecInternalCng ||
Henrik Lundin00eb12a2018-09-05 18:14:52 +02001030 last_mode_ == kModeExpand || last_mode_ == kModeCodecPlc)) {
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001031 generated_noise_stopwatch_.reset();
1032 }
1033
Yves Gerey665174f2018-06-19 15:03:05 +02001034 if (decode_return_value)
1035 return decode_return_value;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001036 return return_value;
1037}
1038
1039int NetEqImpl::GetDecision(Operations* operation,
1040 PacketList* packet_list,
1041 DtmfEvent* dtmf_event,
Ivo Creusen55de08e2018-09-03 11:49:27 +02001042 bool* play_dtmf,
1043 absl::optional<Operations> action_override) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001044 // Initialize output variables.
1045 *play_dtmf = false;
1046 *operation = kUndefined;
1047
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001048 assert(sync_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001049 uint32_t end_timestamp = sync_buffer_->end_timestamp();
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001050 if (!new_codec_) {
1051 const uint32_t five_seconds_samples = 5 * fs_hz_;
minyue-webrtcfae474c2017-07-05 11:17:40 +02001052 packet_buffer_->DiscardOldPackets(end_timestamp, five_seconds_samples,
1053 &stats_);
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001054 }
ossu7a377612016-10-18 04:06:13 -07001055 const Packet* packet = packet_buffer_->PeekNextPacket();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001056
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001057 RTC_DCHECK(!generated_noise_stopwatch_ ||
1058 generated_noise_stopwatch_->ElapsedTicks() >= 1);
1059 uint64_t generated_noise_samples =
Yves Gerey665174f2018-06-19 15:03:05 +02001060 generated_noise_stopwatch_ ? (generated_noise_stopwatch_->ElapsedTicks() -
1061 1) * output_size_samples_ +
1062 decision_logic_->noise_fast_forward()
1063 : 0;
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001064
henrik.lundin@webrtc.orgca8cb952014-03-12 10:26:52 +00001065 if (decision_logic_->CngRfc3389On() || last_mode_ == kModeRfc3389Cng) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001066 // Because of timestamp peculiarities, we have to "manually" disallow using
1067 // a CNG packet with the same timestamp as the one that was last played.
1068 // This can happen when using redundancy and will cause the timing to shift.
ossu7a377612016-10-18 04:06:13 -07001069 while (packet && decoder_database_->IsComfortNoise(packet->payload_type) &&
1070 (end_timestamp >= packet->timestamp ||
1071 end_timestamp + generated_noise_samples > packet->timestamp)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001072 // Don't use this packet, discard it.
minyue-webrtcfae474c2017-07-05 11:17:40 +02001073 if (packet_buffer_->DiscardNextPacket(&stats_) != PacketBuffer::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001074 assert(false); // Must be ok by design.
1075 }
1076 // Check buffer again.
1077 if (!new_codec_) {
minyue-webrtcfae474c2017-07-05 11:17:40 +02001078 packet_buffer_->DiscardOldPackets(end_timestamp, 5 * fs_hz_, &stats_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001079 }
ossu7a377612016-10-18 04:06:13 -07001080 packet = packet_buffer_->PeekNextPacket();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001081 }
1082 }
1083
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001084 assert(expand_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001085 const int samples_left = static_cast<int>(sync_buffer_->FutureLength() -
Yves Gerey665174f2018-06-19 15:03:05 +02001086 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001087 if (last_mode_ == kModeAccelerateSuccess ||
1088 last_mode_ == kModeAccelerateLowEnergy ||
1089 last_mode_ == kModePreemptiveExpandSuccess ||
1090 last_mode_ == kModePreemptiveExpandLowEnergy) {
1091 // Subtract (samples_left + output_size_samples_) from sampleMemory.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001092 decision_logic_->AddSampleMemory(
kwibergd3edd772017-03-01 18:52:48 -08001093 -(samples_left + rtc::dchecked_cast<int>(output_size_samples_)));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001094 }
1095
1096 // Check if it is time to play a DTMF event.
Peter Kastingb7e50542015-06-11 12:55:50 -07001097 if (dtmf_buffer_->GetEvent(
Yves Gerey665174f2018-06-19 15:03:05 +02001098 static_cast<uint32_t>(end_timestamp + generated_noise_samples),
1099 dtmf_event)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001100 *play_dtmf = true;
1101 }
1102
1103 // Get instruction.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001104 assert(sync_buffer_.get());
1105 assert(expand_.get());
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001106 generated_noise_samples =
1107 generated_noise_stopwatch_
1108 ? generated_noise_stopwatch_->ElapsedTicks() * output_size_samples_ +
1109 decision_logic_->noise_fast_forward()
1110 : 0;
1111 *operation = decision_logic_->GetDecision(
ossu7a377612016-10-18 04:06:13 -07001112 *sync_buffer_, *expand_, decoder_frame_length_, packet, last_mode_,
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001113 *play_dtmf, generated_noise_samples, &reset_decoder_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001114
Ivo Creusen55de08e2018-09-03 11:49:27 +02001115 if (action_override) {
1116 // Use the provided action instead of the decision NetEq decided on.
1117 *operation = *action_override;
1118 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001119 // Check if we already have enough samples in the |sync_buffer_|. If so,
1120 // change decision to normal, unless the decision was merge, accelerate, or
1121 // preemptive expand.
kwibergd3edd772017-03-01 18:52:48 -08001122 if (samples_left >= rtc::dchecked_cast<int>(output_size_samples_) &&
1123 *operation != kMerge && *operation != kAccelerate &&
1124 *operation != kFastAccelerate && *operation != kPreemptiveExpand) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001125 *operation = kNormal;
1126 return 0;
1127 }
1128
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001129 decision_logic_->ExpandDecision(*operation);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001130
1131 // Check conditions for reset.
1132 if (new_codec_ || *operation == kUndefined) {
1133 // The only valid reason to get kUndefined is that new_codec_ is set.
1134 assert(new_codec_);
ossu7a377612016-10-18 04:06:13 -07001135 if (*play_dtmf && !packet) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001136 timestamp_ = dtmf_event->timestamp;
1137 } else {
ossu7a377612016-10-18 04:06:13 -07001138 if (!packet) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001139 RTC_LOG(LS_ERROR) << "Packet missing where it shouldn't.";
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001140 return -1;
1141 }
ossu7a377612016-10-18 04:06:13 -07001142 timestamp_ = packet->timestamp;
ossu108ecec2016-07-08 08:45:18 -07001143 if (*operation == kRfc3389CngNoPacket &&
ossu7a377612016-10-18 04:06:13 -07001144 decoder_database_->IsComfortNoise(packet->payload_type)) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001145 // Change decision to CNG packet, since we do have a CNG packet, but it
1146 // was considered too early to use. Now, use it anyway.
1147 *operation = kRfc3389Cng;
1148 } else if (*operation != kRfc3389Cng) {
1149 *operation = kNormal;
1150 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001151 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001152 // Adjust |sync_buffer_| timestamp before setting |end_timestamp| to the
1153 // new value.
1154 sync_buffer_->IncreaseEndTimestamp(timestamp_ - end_timestamp);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001155 end_timestamp = timestamp_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001156 new_codec_ = false;
1157 decision_logic_->SoftReset();
1158 buffer_level_filter_->Reset();
1159 delay_manager_->Reset();
1160 stats_.ResetMcu();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001161 }
1162
Peter Kastingdce40cf2015-08-24 14:52:23 -07001163 size_t required_samples = output_size_samples_;
1164 const size_t samples_10_ms = static_cast<size_t>(80 * fs_mult_);
1165 const size_t samples_20_ms = 2 * samples_10_ms;
1166 const size_t samples_30_ms = 3 * samples_10_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001167
1168 switch (*operation) {
1169 case kExpand: {
1170 timestamp_ = end_timestamp;
1171 return 0;
1172 }
1173 case kRfc3389CngNoPacket:
1174 case kCodecInternalCng: {
1175 return 0;
1176 }
1177 case kDtmf: {
1178 // TODO(hlundin): Write test for this.
1179 // Update timestamp.
1180 timestamp_ = end_timestamp;
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001181 const uint64_t generated_noise_samples =
1182 generated_noise_stopwatch_
1183 ? generated_noise_stopwatch_->ElapsedTicks() *
1184 output_size_samples_ +
1185 decision_logic_->noise_fast_forward()
1186 : 0;
1187 if (generated_noise_samples > 0 && last_mode_ != kModeDtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001188 // Make a jump in timestamp due to the recently played comfort noise.
Peter Kastingb7e50542015-06-11 12:55:50 -07001189 uint32_t timestamp_jump =
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001190 static_cast<uint32_t>(generated_noise_samples);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001191 sync_buffer_->IncreaseEndTimestamp(timestamp_jump);
1192 timestamp_ += timestamp_jump;
1193 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001194 return 0;
1195 }
Henrik Lundincf808d22015-05-27 14:33:29 +02001196 case kAccelerate:
1197 case kFastAccelerate: {
1198 // In order to do an accelerate we need at least 30 ms of audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001199 if (samples_left >= static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001200 // Already have enough data, so we do not need to extract any more.
1201 decision_logic_->set_sample_memory(samples_left);
1202 decision_logic_->set_prev_time_scale(true);
1203 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001204 } else if (samples_left >= static_cast<int>(samples_10_ms) &&
Yves Gerey665174f2018-06-19 15:03:05 +02001205 decoder_frame_length_ >= samples_30_ms) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001206 // Avoid decoding more data as it might overflow the playout buffer.
1207 *operation = kNormal;
1208 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001209 } else if (samples_left < static_cast<int>(samples_20_ms) &&
Yves Gerey665174f2018-06-19 15:03:05 +02001210 decoder_frame_length_ < samples_30_ms) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001211 // Build up decoded data by decoding at least 20 ms of audio data. Do
1212 // not perform accelerate yet, but wait until we only need to do one
1213 // decoding.
1214 required_samples = 2 * output_size_samples_;
1215 *operation = kNormal;
1216 }
1217 // If none of the above is true, we have one of two possible situations:
1218 // (1) 20 ms <= samples_left < 30 ms and decoder_frame_length_ < 30 ms; or
1219 // (2) samples_left < 10 ms and decoder_frame_length_ >= 30 ms.
1220 // In either case, we move on with the accelerate decision, and decode one
1221 // frame now.
1222 break;
1223 }
1224 case kPreemptiveExpand: {
1225 // In order to do a preemptive expand we need at least 30 ms of decoded
1226 // audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001227 if ((samples_left >= static_cast<int>(samples_30_ms)) ||
1228 (samples_left >= static_cast<int>(samples_10_ms) &&
Yves Gerey665174f2018-06-19 15:03:05 +02001229 decoder_frame_length_ >= samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001230 // Already have enough data, so we do not need to extract any more.
1231 // Or, avoid decoding more data as it might overflow the playout buffer.
1232 // Still try preemptive expand, though.
1233 decision_logic_->set_sample_memory(samples_left);
1234 decision_logic_->set_prev_time_scale(true);
1235 return 0;
1236 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07001237 if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001238 decoder_frame_length_ < samples_30_ms) {
1239 // Build up decoded data by decoding at least 20 ms of audio data.
1240 // Still try to perform preemptive expand.
1241 required_samples = 2 * output_size_samples_;
1242 }
1243 // Move on with the preemptive expand decision.
1244 break;
1245 }
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001246 case kMerge: {
1247 required_samples =
1248 std::max(merge_->RequiredFutureSamples(), required_samples);
1249 break;
1250 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001251 default: {
1252 // Do nothing.
1253 }
1254 }
1255
1256 // Get packets from buffer.
1257 int extracted_samples = 0;
Henrik Lundin7687ad52018-07-02 10:14:46 +02001258 if (packet) {
ossu7a377612016-10-18 04:06:13 -07001259 sync_buffer_->IncreaseEndTimestamp(packet->timestamp - end_timestamp);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001260 if (decision_logic_->CngOff()) {
1261 // Adjustment of timestamp only corresponds to an actual packet loss
1262 // if comfort noise is not played. If comfort noise was just played,
1263 // this adjustment of timestamp is only done to get back in sync with the
1264 // stream timestamp; no loss to report.
ossu7a377612016-10-18 04:06:13 -07001265 stats_.LostSamples(packet->timestamp - end_timestamp);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001266 }
1267
1268 if (*operation != kRfc3389Cng) {
1269 // We are about to decode and use a non-CNG packet.
1270 decision_logic_->SetCngOff();
1271 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001272
1273 extracted_samples = ExtractPackets(required_samples, packet_list);
1274 if (extracted_samples < 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001275 return kPacketBufferCorruption;
1276 }
1277 }
1278
Henrik Lundincf808d22015-05-27 14:33:29 +02001279 if (*operation == kAccelerate || *operation == kFastAccelerate ||
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001280 *operation == kPreemptiveExpand) {
1281 decision_logic_->set_sample_memory(samples_left + extracted_samples);
1282 decision_logic_->set_prev_time_scale(true);
1283 }
1284
Henrik Lundincf808d22015-05-27 14:33:29 +02001285 if (*operation == kAccelerate || *operation == kFastAccelerate) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001286 // Check that we have enough data (30ms) to do accelerate.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001287 if (extracted_samples + samples_left < static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001288 // TODO(hlundin): Write test for this.
1289 // Not enough, do normal operation instead.
1290 *operation = kNormal;
1291 }
1292 }
1293
1294 timestamp_ = end_timestamp;
1295 return 0;
1296}
1297
Yves Gerey665174f2018-06-19 15:03:05 +02001298int NetEqImpl::Decode(PacketList* packet_list,
1299 Operations* operation,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001300 int* decoded_length,
1301 AudioDecoder::SpeechType* speech_type) {
1302 *speech_type = AudioDecoder::kSpeech;
minyuel6d92bf52015-09-23 15:20:39 +02001303
1304 // When packet_list is empty, we may be in kCodecInternalCng mode, and for
1305 // that we use current active decoder.
1306 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1307
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001308 if (!packet_list->empty()) {
ossua73f6c92016-10-24 08:25:28 -07001309 const Packet& packet = packet_list->front();
1310 uint8_t payload_type = packet.payload_type;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001311 if (!decoder_database_->IsComfortNoise(payload_type)) {
1312 decoder = decoder_database_->GetDecoder(payload_type);
1313 assert(decoder);
1314 if (!decoder) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001315 RTC_LOG(LS_WARNING)
1316 << "Unknown payload type " << static_cast<int>(payload_type);
ossua73f6c92016-10-24 08:25:28 -07001317 packet_list->clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001318 return kDecoderNotFound;
1319 }
1320 bool decoder_changed;
1321 decoder_database_->SetActiveDecoder(payload_type, &decoder_changed);
1322 if (decoder_changed) {
1323 // We have a new decoder. Re-init some values.
Yves Gerey665174f2018-06-19 15:03:05 +02001324 const DecoderDatabase::DecoderInfo* decoder_info =
1325 decoder_database_->GetDecoderInfo(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001326 assert(decoder_info);
1327 if (!decoder_info) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001328 RTC_LOG(LS_WARNING)
1329 << "Unknown payload type " << static_cast<int>(payload_type);
ossua73f6c92016-10-24 08:25:28 -07001330 packet_list->clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001331 return kDecoderNotFound;
1332 }
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001333 // If sampling rate or number of channels has changed, we need to make
1334 // a reset.
kwibergc0f2dcf2016-05-31 06:28:03 -07001335 if (decoder_info->SampleRateHz() != fs_hz_ ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001336 decoder->Channels() != algorithm_buffer_->Channels()) {
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001337 // TODO(tlegrand): Add unittest to cover this event.
kwibergc0f2dcf2016-05-31 06:28:03 -07001338 SetSampleRateAndChannels(decoder_info->SampleRateHz(),
1339 decoder->Channels());
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001340 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001341 sync_buffer_->set_end_timestamp(timestamp_);
1342 playout_timestamp_ = timestamp_;
1343 }
1344 }
1345 }
1346
1347 if (reset_decoder_) {
1348 // TODO(hlundin): Write test for this.
Karl Wiberg43766482015-08-27 15:22:11 +02001349 if (decoder)
1350 decoder->Reset();
1351
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001352 // Reset comfort noise decoder.
ossu97ba30e2016-04-25 07:55:58 -07001353 ComfortNoiseDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02001354 if (cng_decoder)
1355 cng_decoder->Reset();
1356
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001357 reset_decoder_ = false;
1358 }
1359
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001360 *decoded_length = 0;
1361 // Update codec-internal PLC state.
1362 if ((*operation == kMerge) && decoder && decoder->HasDecodePlc()) {
1363 decoder->DecodePlc(1, &decoded_buffer_[*decoded_length]);
1364 }
1365
minyuel6d92bf52015-09-23 15:20:39 +02001366 int return_value;
1367 if (*operation == kCodecInternalCng) {
1368 RTC_DCHECK(packet_list->empty());
1369 return_value = DecodeCng(decoder, decoded_length, speech_type);
1370 } else {
Yves Gerey665174f2018-06-19 15:03:05 +02001371 return_value = DecodeLoop(packet_list, *operation, decoder, decoded_length,
1372 speech_type);
minyuel6d92bf52015-09-23 15:20:39 +02001373 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001374
1375 if (*decoded_length < 0) {
1376 // Error returned from the decoder.
1377 *decoded_length = 0;
Peter Kastingb7e50542015-06-11 12:55:50 -07001378 sync_buffer_->IncreaseEndTimestamp(
1379 static_cast<uint32_t>(decoder_frame_length_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001380 int error_code = 0;
1381 if (decoder)
1382 error_code = decoder->ErrorCode();
1383 if (error_code != 0) {
1384 // Got some error code from the decoder.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001385 return_value = kDecoderErrorCode;
Mirko Bonadei675513b2017-11-09 11:09:25 +01001386 RTC_LOG(LS_WARNING) << "Decoder returned error code: " << error_code;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001387 } else {
1388 // Decoder does not implement error codes. Return generic error.
1389 return_value = kOtherDecoderError;
Mirko Bonadei675513b2017-11-09 11:09:25 +01001390 RTC_LOG(LS_WARNING) << "Decoder error (no error code)";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001391 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001392 *operation = kExpand; // Do expansion to get data instead.
1393 }
1394 if (*speech_type != AudioDecoder::kComfortNoise) {
1395 // Don't increment timestamp if codec returned CNG speech type
1396 // since in this case, the we will increment the CNGplayedTS counter.
1397 // Increase with number of samples per channel.
1398 assert(*decoded_length == 0 ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001399 (decoder && decoder->Channels() == sync_buffer_->Channels()));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001400 sync_buffer_->IncreaseEndTimestamp(
1401 *decoded_length / static_cast<int>(sync_buffer_->Channels()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001402 }
1403 return return_value;
1404}
1405
Yves Gerey665174f2018-06-19 15:03:05 +02001406int NetEqImpl::DecodeCng(AudioDecoder* decoder,
1407 int* decoded_length,
minyuel6d92bf52015-09-23 15:20:39 +02001408 AudioDecoder::SpeechType* speech_type) {
1409 if (!decoder) {
1410 // This happens when active decoder is not defined.
1411 *decoded_length = -1;
1412 return 0;
1413 }
1414
kwibergd3edd772017-03-01 18:52:48 -08001415 while (*decoded_length < rtc::dchecked_cast<int>(output_size_samples_)) {
minyuel6d92bf52015-09-23 15:20:39 +02001416 const int length = decoder->Decode(
Yves Gerey665174f2018-06-19 15:03:05 +02001417 nullptr, 0, fs_hz_,
1418 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1419 &decoded_buffer_[*decoded_length], speech_type);
minyuel6d92bf52015-09-23 15:20:39 +02001420 if (length > 0) {
1421 *decoded_length += length;
minyuel6d92bf52015-09-23 15:20:39 +02001422 } else {
1423 // Error.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001424 RTC_LOG(LS_WARNING) << "Failed to decode CNG";
minyuel6d92bf52015-09-23 15:20:39 +02001425 *decoded_length = -1;
1426 break;
1427 }
1428 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1429 // Guard against overflow.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001430 RTC_LOG(LS_WARNING) << "Decoded too much CNG.";
minyuel6d92bf52015-09-23 15:20:39 +02001431 return kDecodedTooMuch;
1432 }
1433 }
1434 return 0;
1435}
1436
Yves Gerey665174f2018-06-19 15:03:05 +02001437int NetEqImpl::DecodeLoop(PacketList* packet_list,
1438 const Operations& operation,
1439 AudioDecoder* decoder,
1440 int* decoded_length,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001441 AudioDecoder::SpeechType* speech_type) {
henrik.lundin114c1b32017-04-26 07:47:32 -07001442 RTC_DCHECK(last_decoded_timestamps_.empty());
1443
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001444 // Do decoding.
Yves Gerey665174f2018-06-19 15:03:05 +02001445 while (!packet_list->empty() && !decoder_database_->IsComfortNoise(
1446 packet_list->front().payload_type)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001447 assert(decoder); // At this point, we must have a decoder object.
1448 // The number of channels in the |sync_buffer_| should be the same as the
1449 // number decoder channels.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001450 assert(sync_buffer_->Channels() == decoder->Channels());
1451 assert(decoded_buffer_length_ >= kMaxFrameSize * decoder->Channels());
minyuel6d92bf52015-09-23 15:20:39 +02001452 assert(operation == kNormal || operation == kAccelerate ||
1453 operation == kFastAccelerate || operation == kMerge ||
1454 operation == kPreemptiveExpand);
ossua73f6c92016-10-24 08:25:28 -07001455
1456 auto opt_result = packet_list->front().frame->Decode(
ossu61a208b2016-09-20 01:38:00 -07001457 rtc::ArrayView<int16_t>(&decoded_buffer_[*decoded_length],
1458 decoded_buffer_length_ - *decoded_length));
henrik.lundin114c1b32017-04-26 07:47:32 -07001459 last_decoded_timestamps_.push_back(packet_list->front().timestamp);
ossua73f6c92016-10-24 08:25:28 -07001460 packet_list->pop_front();
ossu61a208b2016-09-20 01:38:00 -07001461 if (opt_result) {
1462 const auto& result = *opt_result;
1463 *speech_type = result.speech_type;
1464 if (result.num_decoded_samples > 0) {
kwibergd3edd772017-03-01 18:52:48 -08001465 *decoded_length += rtc::dchecked_cast<int>(result.num_decoded_samples);
ossu61a208b2016-09-20 01:38:00 -07001466 // Update |decoder_frame_length_| with number of samples per channel.
1467 decoder_frame_length_ =
1468 result.num_decoded_samples / decoder->Channels();
1469 }
1470 } else {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001471 // Error.
ossu61a208b2016-09-20 01:38:00 -07001472 // TODO(ossu): What to put here?
Mirko Bonadei675513b2017-11-09 11:09:25 +01001473 RTC_LOG(LS_WARNING) << "Decode error";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001474 *decoded_length = -1;
ossua73f6c92016-10-24 08:25:28 -07001475 packet_list->clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001476 break;
1477 }
kwibergd3edd772017-03-01 18:52:48 -08001478 if (*decoded_length > rtc::dchecked_cast<int>(decoded_buffer_length_)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001479 // Guard against overflow.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001480 RTC_LOG(LS_WARNING) << "Decoded too much.";
ossua73f6c92016-10-24 08:25:28 -07001481 packet_list->clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001482 return kDecodedTooMuch;
1483 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001484 } // End of decode loop.
1485
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001486 // If the list is not empty at this point, either a decoding error terminated
1487 // the while-loop, or list must hold exactly one CNG packet.
Yves Gerey665174f2018-06-19 15:03:05 +02001488 assert(packet_list->empty() || *decoded_length < 0 ||
1489 (packet_list->size() == 1 && decoder_database_->IsComfortNoise(
1490 packet_list->front().payload_type)));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001491 return 0;
1492}
1493
Yves Gerey665174f2018-06-19 15:03:05 +02001494void NetEqImpl::DoNormal(const int16_t* decoded_buffer,
1495 size_t decoded_length,
1496 AudioDecoder::SpeechType speech_type,
1497 bool play_dtmf) {
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001498 assert(normal_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001499 normal_->Process(decoded_buffer, decoded_length, last_mode_,
Henrik Lundin6dc82e82018-05-22 10:40:23 +02001500 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001501 if (decoded_length != 0) {
1502 last_mode_ = kModeNormal;
1503 }
1504
1505 // If last packet was decoded as an inband CNG, set mode to CNG instead.
Yves Gerey665174f2018-06-19 15:03:05 +02001506 if ((speech_type == AudioDecoder::kComfortNoise) ||
1507 ((last_mode_ == kModeCodecInternalCng) && (decoded_length == 0))) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001508 // TODO(hlundin): Remove second part of || statement above.
1509 last_mode_ = kModeCodecInternalCng;
1510 }
1511
1512 if (!play_dtmf) {
1513 dtmf_tone_generator_->Reset();
1514 }
1515}
1516
Yves Gerey665174f2018-06-19 15:03:05 +02001517void NetEqImpl::DoMerge(int16_t* decoded_buffer,
1518 size_t decoded_length,
1519 AudioDecoder::SpeechType speech_type,
1520 bool play_dtmf) {
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001521 assert(merge_.get());
Yves Gerey665174f2018-06-19 15:03:05 +02001522 size_t new_length =
1523 merge_->Process(decoded_buffer, decoded_length, algorithm_buffer_.get());
henrik.lundin2979f552017-05-05 05:04:16 -07001524 // Correction can be negative.
1525 int expand_length_correction =
1526 rtc::dchecked_cast<int>(new_length) -
1527 rtc::dchecked_cast<int>(decoded_length / algorithm_buffer_->Channels());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001528
1529 // Update in-call and post-call statistics.
1530 if (expand_->MuteFactor(0) == 0) {
1531 // Expand generates only noise.
henrik.lundin2979f552017-05-05 05:04:16 -07001532 stats_.ExpandedNoiseSamplesCorrection(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001533 } else {
1534 // Expansion generates more than only noise.
henrik.lundin2979f552017-05-05 05:04:16 -07001535 stats_.ExpandedVoiceSamplesCorrection(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001536 }
1537
1538 last_mode_ = kModeMerge;
1539 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1540 if (speech_type == AudioDecoder::kComfortNoise) {
1541 last_mode_ = kModeCodecInternalCng;
1542 }
1543 expand_->Reset();
1544 if (!play_dtmf) {
1545 dtmf_tone_generator_->Reset();
1546 }
1547}
1548
Henrik Lundin00eb12a2018-09-05 18:14:52 +02001549bool NetEqImpl::DoCodecPlc() {
1550 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1551 if (!decoder) {
1552 return false;
1553 }
1554 const size_t channels = algorithm_buffer_->Channels();
1555 const size_t requested_samples_per_channel =
1556 output_size_samples_ -
1557 (sync_buffer_->FutureLength() - expand_->overlap_length());
1558 concealment_audio_.Clear();
1559 decoder->GeneratePlc(requested_samples_per_channel, &concealment_audio_);
1560 if (concealment_audio_.empty()) {
1561 // Nothing produced. Resort to regular expand.
1562 return false;
1563 }
1564 RTC_CHECK_GE(concealment_audio_.size(),
1565 requested_samples_per_channel * channels);
1566 sync_buffer_->PushBackInterleaved(concealment_audio_);
1567 RTC_DCHECK_NE(algorithm_buffer_->Channels(), 0);
1568 const size_t concealed_samples_per_channel =
1569 concealment_audio_.size() / channels;
1570
1571 // Update in-call and post-call statistics.
1572 const bool is_new_concealment_event = (last_mode_ != kModeCodecPlc);
1573 if (std::all_of(concealment_audio_.cbegin(), concealment_audio_.cend(),
1574 [](int16_t i) { return i == 0; })) {
1575 // Expand operation generates only noise.
1576 stats_.ExpandedNoiseSamples(concealed_samples_per_channel,
1577 is_new_concealment_event);
1578 } else {
1579 // Expand operation generates more than only noise.
1580 stats_.ExpandedVoiceSamples(concealed_samples_per_channel,
1581 is_new_concealment_event);
1582 }
1583 last_mode_ = kModeCodecPlc;
1584 if (!generated_noise_stopwatch_) {
1585 // Start a new stopwatch since we may be covering for a lost CNG packet.
1586 generated_noise_stopwatch_ = tick_timer_->GetNewStopwatch();
1587 }
1588 return true;
1589}
1590
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001591int NetEqImpl::DoExpand(bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001592 while ((sync_buffer_->FutureLength() - expand_->overlap_length()) <
Yves Gerey665174f2018-06-19 15:03:05 +02001593 output_size_samples_) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001594 algorithm_buffer_->Clear();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001595 int return_value = expand_->Process(algorithm_buffer_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001596 size_t length = algorithm_buffer_->Size();
Gustaf Ullberg9a2e9062017-09-18 09:28:20 +02001597 bool is_new_concealment_event = (last_mode_ != kModeExpand);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001598
1599 // Update in-call and post-call statistics.
1600 if (expand_->MuteFactor(0) == 0) {
1601 // Expand operation generates only noise.
Gustaf Ullberg9a2e9062017-09-18 09:28:20 +02001602 stats_.ExpandedNoiseSamples(length, is_new_concealment_event);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001603 } else {
1604 // Expand operation generates more than only noise.
Gustaf Ullberg9a2e9062017-09-18 09:28:20 +02001605 stats_.ExpandedVoiceSamples(length, is_new_concealment_event);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001606 }
1607
1608 last_mode_ = kModeExpand;
1609
1610 if (return_value < 0) {
1611 return return_value;
1612 }
1613
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001614 sync_buffer_->PushBack(*algorithm_buffer_);
1615 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001616 }
1617 if (!play_dtmf) {
1618 dtmf_tone_generator_->Reset();
1619 }
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001620
1621 if (!generated_noise_stopwatch_) {
1622 // Start a new stopwatch since we may be covering for a lost CNG packet.
1623 generated_noise_stopwatch_ = tick_timer_->GetNewStopwatch();
1624 }
1625
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001626 return 0;
1627}
1628
Henrik Lundincf808d22015-05-27 14:33:29 +02001629int NetEqImpl::DoAccelerate(int16_t* decoded_buffer,
1630 size_t decoded_length,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001631 AudioDecoder::SpeechType speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +02001632 bool play_dtmf,
1633 bool fast_accelerate) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001634 const size_t required_samples =
1635 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001636 size_t borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001637 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001638 size_t decoded_length_per_channel = decoded_length / num_channels;
1639 if (decoded_length_per_channel < required_samples) {
1640 // Must move data from the |sync_buffer_| in order to get 30 ms.
Yves Gerey665174f2018-06-19 15:03:05 +02001641 borrowed_samples_per_channel =
1642 static_cast<int>(required_samples - decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001643 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
Yves Gerey665174f2018-06-19 15:03:05 +02001644 decoded_buffer, sizeof(int16_t) * decoded_length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001645 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1646 decoded_buffer);
1647 decoded_length = required_samples * num_channels;
1648 }
1649
Peter Kastingdce40cf2015-08-24 14:52:23 -07001650 size_t samples_removed;
Henrik Lundincf808d22015-05-27 14:33:29 +02001651 Accelerate::ReturnCodes return_code =
1652 accelerate_->Process(decoded_buffer, decoded_length, fast_accelerate,
1653 algorithm_buffer_.get(), &samples_removed);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001654 stats_.AcceleratedSamples(samples_removed);
1655 switch (return_code) {
1656 case Accelerate::kSuccess:
1657 last_mode_ = kModeAccelerateSuccess;
1658 break;
1659 case Accelerate::kSuccessLowEnergy:
1660 last_mode_ = kModeAccelerateLowEnergy;
1661 break;
1662 case Accelerate::kNoStretch:
1663 last_mode_ = kModeAccelerateFail;
1664 break;
1665 case Accelerate::kError:
1666 // TODO(hlundin): Map to kModeError instead?
1667 last_mode_ = kModeAccelerateFail;
1668 return kAccelerateError;
1669 }
1670
1671 if (borrowed_samples_per_channel > 0) {
1672 // Copy borrowed samples back to the |sync_buffer_|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001673 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001674 if (length < borrowed_samples_per_channel) {
1675 // This destroys the beginning of the buffer, but will not cause any
1676 // problems.
Yves Gerey665174f2018-06-19 15:03:05 +02001677 sync_buffer_->ReplaceAtIndex(
1678 *algorithm_buffer_,
1679 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001680 sync_buffer_->PushFrontZeros(borrowed_samples_per_channel - length);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001681 algorithm_buffer_->PopFront(length);
1682 assert(algorithm_buffer_->Empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001683 } else {
Yves Gerey665174f2018-06-19 15:03:05 +02001684 sync_buffer_->ReplaceAtIndex(
1685 *algorithm_buffer_, borrowed_samples_per_channel,
1686 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001687 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001688 }
1689 }
1690
1691 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1692 if (speech_type == AudioDecoder::kComfortNoise) {
1693 last_mode_ = kModeCodecInternalCng;
1694 }
1695 if (!play_dtmf) {
1696 dtmf_tone_generator_->Reset();
1697 }
1698 expand_->Reset();
1699 return 0;
1700}
1701
1702int NetEqImpl::DoPreemptiveExpand(int16_t* decoded_buffer,
1703 size_t decoded_length,
1704 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001705 bool play_dtmf) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001706 const size_t required_samples =
1707 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001708 size_t num_channels = algorithm_buffer_->Channels();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001709 size_t borrowed_samples_per_channel = 0;
1710 size_t old_borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001711 size_t decoded_length_per_channel = decoded_length / num_channels;
1712 if (decoded_length_per_channel < required_samples) {
1713 // Must move data from the |sync_buffer_| in order to get 30 ms.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001714 borrowed_samples_per_channel =
1715 required_samples - decoded_length_per_channel;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001716 // Calculate how many of these were already played out.
Peter Kastingf045e4d2015-06-10 21:15:38 -07001717 old_borrowed_samples_per_channel =
Yves Gerey665174f2018-06-19 15:03:05 +02001718 (borrowed_samples_per_channel > sync_buffer_->FutureLength())
1719 ? (borrowed_samples_per_channel - sync_buffer_->FutureLength())
1720 : 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001721 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
Yves Gerey665174f2018-06-19 15:03:05 +02001722 decoded_buffer, sizeof(int16_t) * decoded_length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001723 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1724 decoded_buffer);
1725 decoded_length = required_samples * num_channels;
1726 }
1727
Peter Kastingdce40cf2015-08-24 14:52:23 -07001728 size_t samples_added;
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001729 PreemptiveExpand::ReturnCodes return_code = preemptive_expand_->Process(
Yves Gerey665174f2018-06-19 15:03:05 +02001730 decoded_buffer, decoded_length, old_borrowed_samples_per_channel,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001731 algorithm_buffer_.get(), &samples_added);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001732 stats_.PreemptiveExpandedSamples(samples_added);
1733 switch (return_code) {
1734 case PreemptiveExpand::kSuccess:
1735 last_mode_ = kModePreemptiveExpandSuccess;
1736 break;
1737 case PreemptiveExpand::kSuccessLowEnergy:
1738 last_mode_ = kModePreemptiveExpandLowEnergy;
1739 break;
1740 case PreemptiveExpand::kNoStretch:
1741 last_mode_ = kModePreemptiveExpandFail;
1742 break;
1743 case PreemptiveExpand::kError:
1744 // TODO(hlundin): Map to kModeError instead?
1745 last_mode_ = kModePreemptiveExpandFail;
1746 return kPreemptiveExpandError;
1747 }
1748
1749 if (borrowed_samples_per_channel > 0) {
1750 // Copy borrowed samples back to the |sync_buffer_|.
1751 sync_buffer_->ReplaceAtIndex(
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001752 *algorithm_buffer_, borrowed_samples_per_channel,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001753 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001754 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001755 }
1756
1757 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1758 if (speech_type == AudioDecoder::kComfortNoise) {
1759 last_mode_ = kModeCodecInternalCng;
1760 }
1761 if (!play_dtmf) {
1762 dtmf_tone_generator_->Reset();
1763 }
1764 expand_->Reset();
1765 return 0;
1766}
1767
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001768int NetEqImpl::DoRfc3389Cng(PacketList* packet_list, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001769 if (!packet_list->empty()) {
1770 // Must have exactly one SID frame at this point.
1771 assert(packet_list->size() == 1);
ossua73f6c92016-10-24 08:25:28 -07001772 const Packet& packet = packet_list->front();
1773 if (!decoder_database_->IsComfortNoise(packet.payload_type)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001774 RTC_LOG(LS_ERROR) << "Trying to decode non-CNG payload as CNG.";
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001775 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001776 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001777 if (comfort_noise_->UpdateParameters(packet) ==
1778 ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001779 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001780 return -comfort_noise_->internal_error_code();
1781 }
1782 }
Yves Gerey665174f2018-06-19 15:03:05 +02001783 int cn_return =
1784 comfort_noise_->Generate(output_size_samples_, algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001785 expand_->Reset();
1786 last_mode_ = kModeRfc3389Cng;
1787 if (!play_dtmf) {
1788 dtmf_tone_generator_->Reset();
1789 }
1790 if (cn_return == ComfortNoise::kInternalError) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001791 RTC_LOG(LS_WARNING) << "Comfort noise generator returned error code: "
1792 << comfort_noise_->internal_error_code();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001793 return kComfortNoiseErrorCode;
1794 } else if (cn_return == ComfortNoise::kUnknownPayloadType) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001795 return kUnknownRtpPayloadType;
1796 }
1797 return 0;
1798}
1799
minyuel6d92bf52015-09-23 15:20:39 +02001800void NetEqImpl::DoCodecInternalCng(const int16_t* decoded_buffer,
1801 size_t decoded_length) {
1802 RTC_DCHECK(normal_.get());
minyuel6d92bf52015-09-23 15:20:39 +02001803 normal_->Process(decoded_buffer, decoded_length, last_mode_,
Henrik Lundin6dc82e82018-05-22 10:40:23 +02001804 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001805 last_mode_ = kModeCodecInternalCng;
1806 expand_->Reset();
1807}
1808
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001809int NetEqImpl::DoDtmf(const DtmfEvent& dtmf_event, bool* play_dtmf) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001810 // This block of the code and the block further down, handling |dtmf_switch|
1811 // are commented out. Otherwise playing out-of-band DTMF would fail in VoE
1812 // test, DtmfTest.ManualSuccessfullySendsOutOfBandTelephoneEvents. This is
1813 // equivalent to |dtmf_switch| always be false.
1814 //
1815 // See http://webrtc-codereview.appspot.com/1195004/ for discussion
1816 // On this issue. This change might cause some glitches at the point of
1817 // switch from audio to DTMF. Issue 1545 is filed to track this.
1818 //
1819 // bool dtmf_switch = false;
1820 // if ((last_mode_ != kModeDtmf) && dtmf_tone_generator_->initialized()) {
1821 // // Special case; see below.
1822 // // We must catch this before calling Generate, since |initialized| is
1823 // // modified in that call.
1824 // dtmf_switch = true;
1825 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001826
1827 int dtmf_return_value = 0;
1828 if (!dtmf_tone_generator_->initialized()) {
1829 // Initialize if not already done.
1830 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1831 dtmf_event.volume);
1832 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001833
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001834 if (dtmf_return_value == 0) {
1835 // Generate DTMF signal.
1836 dtmf_return_value = dtmf_tone_generator_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001837 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001838 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001839
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001840 if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001841 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001842 return dtmf_return_value;
1843 }
1844
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001845 // if (dtmf_switch) {
1846 // // This is the special case where the previous operation was DTMF
1847 // // overdub, but the current instruction is "regular" DTMF. We must make
1848 // // sure that the DTMF does not have any discontinuities. The first DTMF
1849 // // sample that we generate now must be played out immediately, therefore
1850 // // it must be copied to the speech buffer.
1851 // // TODO(hlundin): This code seems incorrect. (Legacy.) Write test and
1852 // // verify correct operation.
1853 // assert(false);
1854 // // Must generate enough data to replace all of the |sync_buffer_|
1855 // // "future".
1856 // int required_length = sync_buffer_->FutureLength();
1857 // assert(dtmf_tone_generator_->initialized());
1858 // dtmf_return_value = dtmf_tone_generator_->Generate(required_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001859 // algorithm_buffer_);
1860 // assert((size_t) required_length == algorithm_buffer_->Size());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001861 // if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001862 // algorithm_buffer_->Zeros(output_size_samples_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001863 // return dtmf_return_value;
1864 // }
1865 //
1866 // // Overwrite the "future" part of the speech buffer with the new DTMF
1867 // // data.
1868 // // TODO(hlundin): It seems that this overwriting has gone lost.
1869 // // Not adapted for multi-channel yet.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001870 // assert(algorithm_buffer_->Channels() == 1);
1871 // if (algorithm_buffer_->Channels() != 1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001872 // RTC_LOG(LS_WARNING) << "DTMF not supported for more than one channel";
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001873 // return kStereoNotSupported;
1874 // }
1875 // // Shuffle the remaining data to the beginning of algorithm buffer.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001876 // algorithm_buffer_->PopFront(sync_buffer_->FutureLength());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001877 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001878
Peter Kastingb7e50542015-06-11 12:55:50 -07001879 sync_buffer_->IncreaseEndTimestamp(
1880 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001881 expand_->Reset();
1882 last_mode_ = kModeDtmf;
1883
1884 // Set to false because the DTMF is already in the algorithm buffer.
1885 *play_dtmf = false;
1886 return 0;
1887}
1888
Yves Gerey665174f2018-06-19 15:03:05 +02001889int NetEqImpl::DtmfOverdub(const DtmfEvent& dtmf_event,
1890 size_t num_channels,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001891 int16_t* output) const {
1892 size_t out_index = 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001893 size_t overdub_length = output_size_samples_; // Default value.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001894
1895 if (sync_buffer_->dtmf_index() > sync_buffer_->next_index()) {
1896 // Special operation for transition from "DTMF only" to "DTMF overdub".
Yves Gerey665174f2018-06-19 15:03:05 +02001897 out_index =
1898 std::min(sync_buffer_->dtmf_index() - sync_buffer_->next_index(),
1899 output_size_samples_);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001900 overdub_length = output_size_samples_ - out_index;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001901 }
1902
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001903 AudioMultiVector dtmf_output(num_channels);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001904 int dtmf_return_value = 0;
1905 if (!dtmf_tone_generator_->initialized()) {
1906 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1907 dtmf_event.volume);
1908 }
1909 if (dtmf_return_value == 0) {
Yves Gerey665174f2018-06-19 15:03:05 +02001910 dtmf_return_value =
1911 dtmf_tone_generator_->Generate(overdub_length, &dtmf_output);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001912 assert(overdub_length == dtmf_output.Size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001913 }
1914 dtmf_output.ReadInterleaved(overdub_length, &output[out_index]);
1915 return dtmf_return_value < 0 ? dtmf_return_value : 0;
1916}
1917
Peter Kastingdce40cf2015-08-24 14:52:23 -07001918int NetEqImpl::ExtractPackets(size_t required_samples,
1919 PacketList* packet_list) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001920 bool first_packet = true;
1921 uint8_t prev_payload_type = 0;
1922 uint32_t prev_timestamp = 0;
1923 uint16_t prev_sequence_number = 0;
1924 bool next_packet_available = false;
1925
ossu7a377612016-10-18 04:06:13 -07001926 const Packet* next_packet = packet_buffer_->PeekNextPacket();
1927 RTC_DCHECK(next_packet);
1928 if (!next_packet) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001929 RTC_LOG(LS_ERROR) << "Packet buffer unexpectedly empty.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001930 return -1;
1931 }
ossu7a377612016-10-18 04:06:13 -07001932 uint32_t first_timestamp = next_packet->timestamp;
ossu61a208b2016-09-20 01:38:00 -07001933 size_t extracted_samples = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001934
1935 // Packet extraction loop.
1936 do {
ossu7a377612016-10-18 04:06:13 -07001937 timestamp_ = next_packet->timestamp;
Danil Chapovalovb6021232018-06-19 13:26:36 +02001938 absl::optional<Packet> packet = packet_buffer_->GetNextPacket();
ossu7a377612016-10-18 04:06:13 -07001939 // |next_packet| may be invalid after the |packet_buffer_| operation.
ossua73f6c92016-10-24 08:25:28 -07001940 next_packet = nullptr;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001941 if (!packet) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001942 RTC_LOG(LS_ERROR) << "Should always be able to extract a packet here";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001943 assert(false); // Should always be able to extract a packet here.
1944 return -1;
1945 }
Gustaf Ullbergb0a02072017-10-02 12:00:34 +02001946 const uint64_t waiting_time_ms = packet->waiting_time->ElapsedMs();
1947 stats_.StoreWaitingTime(waiting_time_ms);
ossu61a208b2016-09-20 01:38:00 -07001948 RTC_DCHECK(!packet->empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001949
1950 if (first_packet) {
1951 first_packet = false;
henrik.lundin48ed9302015-10-29 05:36:24 -07001952 if (nack_enabled_) {
1953 RTC_DCHECK(nack_);
1954 // TODO(henrik.lundin): Should we update this for all decoded packets?
ossu7a377612016-10-18 04:06:13 -07001955 nack_->UpdateLastDecodedPacket(packet->sequence_number,
1956 packet->timestamp);
henrik.lundin48ed9302015-10-29 05:36:24 -07001957 }
ossu7a377612016-10-18 04:06:13 -07001958 prev_sequence_number = packet->sequence_number;
1959 prev_timestamp = packet->timestamp;
1960 prev_payload_type = packet->payload_type;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001961 }
1962
ossucafb4972017-01-02 07:00:50 -08001963 const bool has_cng_packet =
1964 decoder_database_->IsComfortNoise(packet->payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001965 // Store number of extracted samples.
ossu61a208b2016-09-20 01:38:00 -07001966 size_t packet_duration = 0;
1967 if (packet->frame) {
1968 packet_duration = packet->frame->Duration();
ossua70695a2016-09-22 02:06:28 -07001969 // TODO(ossu): Is this the correct way to track Opus FEC packets?
1970 if (packet->priority.codec_level > 0) {
kwibergd3edd772017-03-01 18:52:48 -08001971 stats_.SecondaryDecodedSamples(
1972 rtc::dchecked_cast<int>(packet_duration));
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001973 }
ossucafb4972017-01-02 07:00:50 -08001974 } else if (!has_cng_packet) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001975 RTC_LOG(LS_WARNING) << "Unknown payload type "
1976 << static_cast<int>(packet->payload_type);
ossu61a208b2016-09-20 01:38:00 -07001977 RTC_NOTREACHED();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001978 }
ossu61a208b2016-09-20 01:38:00 -07001979
1980 if (packet_duration == 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001981 // Decoder did not return a packet duration. Assume that the packet
1982 // contains the same number of samples as the previous one.
ossu61a208b2016-09-20 01:38:00 -07001983 packet_duration = decoder_frame_length_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001984 }
ossu7a377612016-10-18 04:06:13 -07001985 extracted_samples = packet->timestamp - first_timestamp + packet_duration;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001986
Gustaf Ullbergb0a02072017-10-02 12:00:34 +02001987 stats_.JitterBufferDelay(extracted_samples, waiting_time_ms);
1988
ossua73f6c92016-10-24 08:25:28 -07001989 packet_list->push_back(std::move(*packet)); // Store packet in list.
Danil Chapovalovb6021232018-06-19 13:26:36 +02001990 packet = absl::nullopt; // Ensure it's never used after the move.
ossua73f6c92016-10-24 08:25:28 -07001991
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001992 // Check what packet is available next.
ossu7a377612016-10-18 04:06:13 -07001993 next_packet = packet_buffer_->PeekNextPacket();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001994 next_packet_available = false;
ossucafb4972017-01-02 07:00:50 -08001995 if (next_packet && prev_payload_type == next_packet->payload_type &&
1996 !has_cng_packet) {
ossu7a377612016-10-18 04:06:13 -07001997 int16_t seq_no_diff = next_packet->sequence_number - prev_sequence_number;
1998 size_t ts_diff = next_packet->timestamp - prev_timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001999 if (seq_no_diff == 1 ||
2000 (seq_no_diff == 0 && ts_diff == decoder_frame_length_)) {
2001 // The next sequence number is available, or the next part of a packet
2002 // that was split into pieces upon insertion.
2003 next_packet_available = true;
2004 }
ossu7a377612016-10-18 04:06:13 -07002005 prev_sequence_number = next_packet->sequence_number;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002006 }
ossu61a208b2016-09-20 01:38:00 -07002007 } while (extracted_samples < required_samples && next_packet_available);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002008
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00002009 if (extracted_samples > 0) {
2010 // Delete old packets only when we are going to decode something. Otherwise,
2011 // we could end up in the situation where we never decode anything, since
2012 // all incoming packets are considered too old but the buffer will also
2013 // never be flooded and flushed.
minyue-webrtcfae474c2017-07-05 11:17:40 +02002014 packet_buffer_->DiscardAllOldPackets(timestamp_, &stats_);
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00002015 }
2016
kwibergd3edd772017-03-01 18:52:48 -08002017 return rtc::dchecked_cast<int>(extracted_samples);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002018}
2019
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002020void NetEqImpl::UpdatePlcComponents(int fs_hz, size_t channels) {
2021 // Delete objects and create new ones.
2022 expand_.reset(expand_factory_->Create(background_noise_.get(),
2023 sync_buffer_.get(), &random_vector_,
Henrik Lundinbef77e22015-08-18 14:58:09 +02002024 &stats_, fs_hz, channels));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002025 merge_.reset(new Merge(fs_hz, channels, expand_.get(), sync_buffer_.get()));
2026}
2027
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002028void NetEqImpl::SetSampleRateAndChannels(int fs_hz, size_t channels) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002029 RTC_LOG(LS_VERBOSE) << "SetSampleRateAndChannels " << fs_hz << " "
2030 << channels;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002031 // TODO(hlundin): Change to an enumerator and skip assert.
Yves Gerey665174f2018-06-19 15:03:05 +02002032 assert(fs_hz == 8000 || fs_hz == 16000 || fs_hz == 32000 || fs_hz == 48000);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002033 assert(channels > 0);
2034
2035 fs_hz_ = fs_hz;
2036 fs_mult_ = fs_hz / 8000;
Peter Kastingdce40cf2015-08-24 14:52:23 -07002037 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002038 decoder_frame_length_ = 3 * output_size_samples_; // Initialize to 30ms.
2039
2040 last_mode_ = kModeNormal;
2041
ossu97ba30e2016-04-25 07:55:58 -07002042 ComfortNoiseDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02002043 if (cng_decoder)
2044 cng_decoder->Reset();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002045
2046 // Reinit post-decode VAD with new sample rate.
2047 assert(vad_.get()); // Cannot be NULL here.
2048 vad_->Init();
2049
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002050 // Delete algorithm buffer and create a new one.
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00002051 algorithm_buffer_.reset(new AudioMultiVector(channels));
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002052
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002053 // Delete sync buffer and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002054 sync_buffer_.reset(new SyncBuffer(channels, kSyncBufferSize * fs_mult_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002055
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00002056 // Delete BackgroundNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002057 background_noise_.reset(new BackgroundNoise(channels));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002058
2059 // Reset random vector.
2060 random_vector_.Reset();
2061
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002062 UpdatePlcComponents(fs_hz, channels);
2063
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002064 // Move index so that we create a small set of future samples (all 0).
2065 sync_buffer_->set_next_index(sync_buffer_->next_index() -
Yves Gerey665174f2018-06-19 15:03:05 +02002066 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002067
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002068 normal_.reset(new Normal(fs_hz, decoder_database_.get(), *background_noise_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002069 expand_.get()));
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +00002070 accelerate_.reset(
2071 accelerate_factory_->Create(fs_hz, channels, *background_noise_));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002072 preemptive_expand_.reset(preemptive_expand_factory_->Create(
Peter Kastingdce40cf2015-08-24 14:52:23 -07002073 fs_hz, channels, *background_noise_, expand_->overlap_length()));
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002074
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002075 // Delete ComfortNoise object and create a new one.
Yves Gerey665174f2018-06-19 15:03:05 +02002076 comfort_noise_.reset(
2077 new ComfortNoise(fs_hz, decoder_database_.get(), sync_buffer_.get()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002078
2079 // Verify that |decoded_buffer_| is long enough.
2080 if (decoded_buffer_length_ < kMaxFrameSize * channels) {
2081 // Reallocate to larger size.
2082 decoded_buffer_length_ = kMaxFrameSize * channels;
2083 decoded_buffer_.reset(new int16_t[decoded_buffer_length_]);
2084 }
2085
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002086 // Create DecisionLogic if it is not created yet, then communicate new sample
2087 // rate and output size to DecisionLogic object.
2088 if (!decision_logic_.get()) {
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002089 CreateDecisionLogic();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002090 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002091 decision_logic_->SetSampleRate(fs_hz_, output_size_samples_);
2092}
2093
henrik.lundin55480f52016-03-08 02:37:57 -08002094NetEqImpl::OutputType NetEqImpl::LastOutputType() {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002095 assert(vad_.get());
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002096 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002097 if (last_mode_ == kModeCodecInternalCng || last_mode_ == kModeRfc3389Cng) {
henrik.lundin55480f52016-03-08 02:37:57 -08002098 return OutputType::kCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002099 } else if (last_mode_ == kModeExpand && expand_->MuteFactor(0) == 0) {
2100 // Expand mode has faded down to background noise only (very long expand).
henrik.lundin55480f52016-03-08 02:37:57 -08002101 return OutputType::kPLCCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002102 } else if (last_mode_ == kModeExpand) {
henrik.lundin55480f52016-03-08 02:37:57 -08002103 return OutputType::kPLC;
wu@webrtc.org24301a62013-12-13 19:17:43 +00002104 } else if (vad_->running() && !vad_->active_speech()) {
henrik.lundin55480f52016-03-08 02:37:57 -08002105 return OutputType::kVadPassive;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002106 } else {
henrik.lundin55480f52016-03-08 02:37:57 -08002107 return OutputType::kNormalSpeech;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002108 }
2109}
2110
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002111void NetEqImpl::CreateDecisionLogic() {
Henrik Lundin47b17dc2016-05-10 10:20:59 +02002112 decision_logic_.reset(DecisionLogic::Create(
Henrik Lundin7687ad52018-07-02 10:14:46 +02002113 fs_hz_, output_size_samples_, no_time_stretching_,
2114 decoder_database_.get(), *packet_buffer_.get(), delay_manager_.get(),
2115 buffer_level_filter_.get(), tick_timer_.get()));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002116}
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002117} // namespace webrtc