blob: 643fb1e2dd859c00a3ecb8ba9931228bca721d29 [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>
Jonas Olssona4d87372019-07-05 19:08:33 +020014
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000015#include <algorithm>
Yves Gerey988cc082018-10-23 12:03:01 +020016#include <cstdint>
17#include <cstring>
18#include <list>
Alessio Bazzica8f319a32019-07-24 16:47:02 +000019#include <map>
ossu61a208b2016-09-20 01:38:00 -070020#include <utility>
ossu97ba30e2016-04-25 07:55:58 -070021#include <vector>
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000022
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020023#include "api/audio_codecs/audio_decoder.h"
Ivo Creusen3ce44a32019-10-31 14:38:11 +010024#include "api/neteq/tick_timer.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020025#include "common_audio/signal_processing/include/signal_processing_library.h"
Yves Gerey988cc082018-10-23 12:03:01 +020026#include "modules/audio_coding/codecs/cng/webrtc_cng.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020027#include "modules/audio_coding/neteq/accelerate.h"
28#include "modules/audio_coding/neteq/background_noise.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020029#include "modules/audio_coding/neteq/comfort_noise.h"
30#include "modules/audio_coding/neteq/decision_logic.h"
31#include "modules/audio_coding/neteq/decoder_database.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020032#include "modules/audio_coding/neteq/dtmf_buffer.h"
33#include "modules/audio_coding/neteq/dtmf_tone_generator.h"
34#include "modules/audio_coding/neteq/expand.h"
35#include "modules/audio_coding/neteq/merge.h"
36#include "modules/audio_coding/neteq/nack_tracker.h"
37#include "modules/audio_coding/neteq/normal.h"
38#include "modules/audio_coding/neteq/packet.h"
39#include "modules/audio_coding/neteq/packet_buffer.h"
40#include "modules/audio_coding/neteq/post_decode_vad.h"
41#include "modules/audio_coding/neteq/preemptive_expand.h"
42#include "modules/audio_coding/neteq/red_payload_splitter.h"
Jakob Ivarsson44507082019-03-05 16:59:03 +010043#include "modules/audio_coding/neteq/statistics_calculator.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020044#include "modules/audio_coding/neteq/sync_buffer.h"
Yves Gerey988cc082018-10-23 12:03:01 +020045#include "modules/audio_coding/neteq/time_stretch.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020046#include "modules/audio_coding/neteq/timestamp_scaler.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020047#include "rtc_base/checks.h"
48#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010049#include "rtc_base/numerics/safe_conversions.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020050#include "rtc_base/sanitizer.h"
Jonas Olssonabbe8412018-04-03 13:40:05 +020051#include "rtc_base/strings/audio_format_to_string.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020052#include "rtc_base/trace_event.h"
Alessio Bazzica8f319a32019-07-24 16:47:02 +000053#include "system_wrappers/include/clock.h"
Henrik Lundinf7cba9f2020-06-10 18:19:27 +020054#include "system_wrappers/include/field_trial.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000055
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000056namespace webrtc {
Ivo Creusen53a31f72019-10-24 15:20:39 +020057namespace {
58
59std::unique_ptr<NetEqController> CreateNetEqController(
Ivo Creusen3ce44a32019-10-31 14:38:11 +010060 const NetEqControllerFactory& controller_factory,
Ivo Creusen53a31f72019-10-24 15:20:39 +020061 int base_min_delay,
62 int max_packets_in_buffer,
63 bool enable_rtx_handling,
64 bool allow_time_stretching,
Ivo Creusen88636c62020-01-24 11:04:56 +010065 TickTimer* tick_timer,
66 webrtc::Clock* clock) {
Ivo Creusen53a31f72019-10-24 15:20:39 +020067 NetEqController::Config config;
68 config.base_min_delay_ms = base_min_delay;
69 config.max_packets_in_buffer = max_packets_in_buffer;
70 config.enable_rtx_handling = enable_rtx_handling;
71 config.allow_time_stretching = allow_time_stretching;
72 config.tick_timer = tick_timer;
Ivo Creusen88636c62020-01-24 11:04:56 +010073 config.clock = clock;
Ivo Creusen3ce44a32019-10-31 14:38:11 +010074 return controller_factory.CreateNetEqController(config);
Ivo Creusen53a31f72019-10-24 15:20:39 +020075}
76
Henrik Lundinf7cba9f2020-06-10 18:19:27 +020077int GetDelayChainLengthMs(int config_extra_delay_ms) {
78 constexpr char kExtraDelayFieldTrial[] = "WebRTC-Audio-NetEqExtraDelay";
79 if (webrtc::field_trial::IsEnabled(kExtraDelayFieldTrial)) {
80 const auto field_trial_string =
81 webrtc::field_trial::FindFullName(kExtraDelayFieldTrial);
82 int extra_delay_ms = -1;
83 if (sscanf(field_trial_string.c_str(), "Enabled-%d", &extra_delay_ms) ==
84 1 &&
85 extra_delay_ms >= 0 && extra_delay_ms <= 2000) {
86 RTC_LOG(LS_INFO) << "Delay chain length set to " << extra_delay_ms
87 << " ms in field trial";
88 return (extra_delay_ms / 10) * 10; // Rounding down to multiple of 10.
89 }
90 }
91 // Field trial not set, or invalid value read. Use value from config.
92 return config_extra_delay_ms;
93}
94
Ivo Creusen53a31f72019-10-24 15:20:39 +020095} // namespace
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000096
ossue3525782016-05-25 07:37:43 -070097NetEqImpl::Dependencies::Dependencies(
98 const NetEq::Config& config,
Alessio Bazzica8f319a32019-07-24 16:47:02 +000099 Clock* clock,
Ivo Creusen3ce44a32019-10-31 14:38:11 +0100100 const rtc::scoped_refptr<AudioDecoderFactory>& decoder_factory,
101 const NetEqControllerFactory& controller_factory)
Alessio Bazzica8f319a32019-07-24 16:47:02 +0000102 : clock(clock),
103 tick_timer(new TickTimer),
Jakob Ivarsson44507082019-03-05 16:59:03 +0100104 stats(new StatisticsCalculator),
Karl Wiberg08126342018-03-20 19:18:55 +0100105 decoder_database(
106 new DecoderDatabase(decoder_factory, config.codec_pair_id)),
henrik.lundin1d9061e2016-04-26 12:19:34 -0700107 dtmf_buffer(new DtmfBuffer(config.sample_rate_hz)),
108 dtmf_tone_generator(new DtmfToneGenerator),
109 packet_buffer(
110 new PacketBuffer(config.max_packets_in_buffer, tick_timer.get())),
Ivo Creusen53a31f72019-10-24 15:20:39 +0200111 neteq_controller(
Ivo Creusen3ce44a32019-10-31 14:38:11 +0100112 CreateNetEqController(controller_factory,
113 config.min_delay_ms,
Ivo Creusen53a31f72019-10-24 15:20:39 +0200114 config.max_packets_in_buffer,
115 config.enable_rtx_handling,
116 !config.for_test_no_time_stretching,
Ivo Creusen88636c62020-01-24 11:04:56 +0100117 tick_timer.get(),
118 clock)),
ossua70695a2016-09-22 02:06:28 -0700119 red_payload_splitter(new RedPayloadSplitter),
henrik.lundin1d9061e2016-04-26 12:19:34 -0700120 timestamp_scaler(new TimestampScaler(*decoder_database)),
121 accelerate_factory(new AccelerateFactory),
122 expand_factory(new ExpandFactory),
123 preemptive_expand_factory(new PreemptiveExpandFactory) {}
124
125NetEqImpl::Dependencies::~Dependencies() = default;
126
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +0000127NetEqImpl::NetEqImpl(const NetEq::Config& config,
henrik.lundin1d9061e2016-04-26 12:19:34 -0700128 Dependencies&& deps,
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000129 bool create_components)
Alessio Bazzica8f319a32019-07-24 16:47:02 +0000130 : clock_(deps.clock),
131 tick_timer_(std::move(deps.tick_timer)),
henrik.lundin1d9061e2016-04-26 12:19:34 -0700132 decoder_database_(std::move(deps.decoder_database)),
henrik.lundin1d9061e2016-04-26 12:19:34 -0700133 dtmf_buffer_(std::move(deps.dtmf_buffer)),
134 dtmf_tone_generator_(std::move(deps.dtmf_tone_generator)),
135 packet_buffer_(std::move(deps.packet_buffer)),
ossua70695a2016-09-22 02:06:28 -0700136 red_payload_splitter_(std::move(deps.red_payload_splitter)),
henrik.lundin1d9061e2016-04-26 12:19:34 -0700137 timestamp_scaler_(std::move(deps.timestamp_scaler)),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000138 vad_(new PostDecodeVad()),
henrik.lundin1d9061e2016-04-26 12:19:34 -0700139 expand_factory_(std::move(deps.expand_factory)),
140 accelerate_factory_(std::move(deps.accelerate_factory)),
141 preemptive_expand_factory_(std::move(deps.preemptive_expand_factory)),
Jakob Ivarsson44507082019-03-05 16:59:03 +0100142 stats_(std::move(deps.stats)),
Ivo Creusen53a31f72019-10-24 15:20:39 +0200143 controller_(std::move(deps.neteq_controller)),
Ivo Creusen3ce44a32019-10-31 14:38:11 +0100144 last_mode_(Mode::kNormal),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000145 decoded_buffer_length_(kMaxFrameSize),
146 decoded_buffer_(new int16_t[decoded_buffer_length_]),
147 playout_timestamp_(0),
148 new_codec_(false),
149 timestamp_(0),
150 reset_decoder_(false),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000151 first_packet_(true),
Henrik Lundincf808d22015-05-27 14:33:29 +0200152 enable_fast_accelerate_(config.enable_fast_accelerate),
henrik.lundin7a926812016-05-12 13:51:28 -0700153 nack_enabled_(false),
Henrik Lundin3ef3bfc2018-04-10 15:10:26 +0200154 enable_muted_state_(config.enable_muted_state),
155 expand_uma_logger_("WebRTC.Audio.ExpandRatePercent",
156 10, // Report once every 10 s.
157 tick_timer_.get()),
158 speech_expand_uma_logger_("WebRTC.Audio.SpeechExpandRatePercent",
159 10, // Report once every 10 s.
Henrik Lundin7687ad52018-07-02 10:14:46 +0200160 tick_timer_.get()),
Jakob Ivarsson39b934b2019-01-10 10:28:23 +0100161 no_time_stretching_(config.for_test_no_time_stretching),
Henrik Lundinc49e9c22020-05-25 11:26:15 +0200162 enable_rtx_handling_(config.enable_rtx_handling),
Henrik Lundinf7cba9f2020-06-10 18:19:27 +0200163 output_delay_chain_ms_(
164 GetDelayChainLengthMs(config.extra_output_delay_ms)),
165 output_delay_chain_(rtc::CheckedDivExact(output_delay_chain_ms_, 10)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100166 RTC_LOG(LS_INFO) << "NetEq config: " << config.ToString();
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +0000167 int fs = config.sample_rate_hz;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000168 if (fs != 8000 && fs != 16000 && fs != 32000 && fs != 48000) {
Jonas Olssonb2b20312020-01-14 12:11:31 +0100169 RTC_LOG(LS_ERROR) << "Sample rate " << fs
170 << " Hz not supported. "
171 "Changing to 8000 Hz.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000172 fs = 8000;
173 }
Ivo Creusen53a31f72019-10-24 15:20:39 +0200174 controller_->SetMaximumDelay(config.max_delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000175 fs_hz_ = fs;
176 fs_mult_ = fs / 8000;
henrik.lundind89814b2015-11-23 06:49:25 -0800177 last_output_sample_rate_hz_ = fs;
Peter Kastingdce40cf2015-08-24 14:52:23 -0700178 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
Ivo Creusen53a31f72019-10-24 15:20:39 +0200179 controller_->SetSampleRate(fs_hz_, output_size_samples_);
Alessio Bazzica2d02c942019-11-29 13:32:12 +0100180 decoder_frame_length_ = 2 * output_size_samples_; // 20 ms.
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000181 if (create_components) {
182 SetSampleRateAndChannels(fs, 1); // Default is 1 channel.
183 }
henrik.lundin9bc26672015-11-02 03:25:57 -0800184 RTC_DCHECK(!vad_->enabled());
185 if (config.enable_post_decode_vad) {
186 vad_->Enable();
187 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000188}
189
Henrik Lundind67a2192015-08-03 12:54:37 +0200190NetEqImpl::~NetEqImpl() = default;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000191
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200192int NetEqImpl::InsertPacket(const RTPHeader& rtp_header,
Karl Wiberg45eb1352019-10-10 14:23:00 +0200193 rtc::ArrayView<const uint8_t> payload) {
kwibergac554ee2016-09-02 00:39:33 -0700194 rtc::MsanCheckInitialized(payload);
henrik.lundina689b442015-12-17 03:50:05 -0800195 TRACE_EVENT0("webrtc", "NetEqImpl::InsertPacket");
Markus Handell0df0fae2020-07-07 15:53:34 +0200196 MutexLock lock(&mutex_);
Karl Wiberg45eb1352019-10-10 14:23:00 +0200197 if (InsertPacketInternal(rtp_header, payload) != 0) {
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000198 return kFail;
199 }
200 return kOK;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000201}
202
henrik.lundinb8c55b12017-05-10 07:38:01 -0700203void NetEqImpl::InsertEmptyPacket(const RTPHeader& /*rtp_header*/) {
204 // TODO(henrik.lundin) Handle NACK as well. This will make use of the
205 // rtp_header parameter.
206 // https://bugs.chromium.org/p/webrtc/issues/detail?id=7611
Markus Handell0df0fae2020-07-07 15:53:34 +0200207 MutexLock lock(&mutex_);
Ivo Creusen53a31f72019-10-24 15:20:39 +0200208 controller_->RegisterEmptyPacket();
henrik.lundinb8c55b12017-05-10 07:38:01 -0700209}
210
henrik.lundin500c04b2016-03-08 02:36:04 -0800211namespace {
212void SetAudioFrameActivityAndType(bool vad_enabled,
henrik.lundin55480f52016-03-08 02:37:57 -0800213 NetEqImpl::OutputType type,
henrik.lundin500c04b2016-03-08 02:36:04 -0800214 AudioFrame::VADActivity last_vad_activity,
215 AudioFrame* audio_frame) {
216 switch (type) {
henrik.lundin55480f52016-03-08 02:37:57 -0800217 case NetEqImpl::OutputType::kNormalSpeech: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800218 audio_frame->speech_type_ = AudioFrame::kNormalSpeech;
219 audio_frame->vad_activity_ = AudioFrame::kVadActive;
220 break;
221 }
henrik.lundin55480f52016-03-08 02:37:57 -0800222 case NetEqImpl::OutputType::kVadPassive: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800223 // This should only be reached if the VAD is enabled.
224 RTC_DCHECK(vad_enabled);
225 audio_frame->speech_type_ = AudioFrame::kNormalSpeech;
226 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
227 break;
228 }
henrik.lundin55480f52016-03-08 02:37:57 -0800229 case NetEqImpl::OutputType::kCNG: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800230 audio_frame->speech_type_ = AudioFrame::kCNG;
231 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
232 break;
233 }
henrik.lundin55480f52016-03-08 02:37:57 -0800234 case NetEqImpl::OutputType::kPLC: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800235 audio_frame->speech_type_ = AudioFrame::kPLC;
236 audio_frame->vad_activity_ = last_vad_activity;
237 break;
238 }
henrik.lundin55480f52016-03-08 02:37:57 -0800239 case NetEqImpl::OutputType::kPLCCNG: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800240 audio_frame->speech_type_ = AudioFrame::kPLCCNG;
241 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
242 break;
243 }
Alex Narest5b5d97c2019-08-07 18:15:08 +0200244 case NetEqImpl::OutputType::kCodecPLC: {
245 audio_frame->speech_type_ = AudioFrame::kCodecPLC;
246 audio_frame->vad_activity_ = last_vad_activity;
247 break;
248 }
henrik.lundin500c04b2016-03-08 02:36:04 -0800249 default:
250 RTC_NOTREACHED();
251 }
252 if (!vad_enabled) {
253 // Always set kVadUnknown when receive VAD is inactive.
254 audio_frame->vad_activity_ = AudioFrame::kVadUnknown;
255 }
256}
henrik.lundinbc89de32016-03-08 05:20:14 -0800257} // namespace
henrik.lundin500c04b2016-03-08 02:36:04 -0800258
Ivo Creusen55de08e2018-09-03 11:49:27 +0200259int NetEqImpl::GetAudio(AudioFrame* audio_frame,
260 bool* muted,
Ivo Creusen3ce44a32019-10-31 14:38:11 +0100261 absl::optional<Operation> action_override) {
henrik.lundine1ca1672016-01-08 03:50:08 -0800262 TRACE_EVENT0("webrtc", "NetEqImpl::GetAudio");
Markus Handell0df0fae2020-07-07 15:53:34 +0200263 MutexLock lock(&mutex_);
Ivo Creusen55de08e2018-09-03 11:49:27 +0200264 if (GetAudioInternal(audio_frame, muted, action_override) != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000265 return kFail;
266 }
henrik.lundin5fac3f02016-08-24 11:18:49 -0700267 RTC_DCHECK_EQ(
268 audio_frame->sample_rate_hz_,
kwibergd3edd772017-03-01 18:52:48 -0800269 rtc::dchecked_cast<int>(audio_frame->samples_per_channel_ * 100));
henrik.lundina4491072017-07-06 05:23:53 -0700270 RTC_DCHECK_EQ(*muted, audio_frame->muted());
henrik.lundin500c04b2016-03-08 02:36:04 -0800271 SetAudioFrameActivityAndType(vad_->enabled(), LastOutputType(),
272 last_vad_activity_, audio_frame);
273 last_vad_activity_ = audio_frame->vad_activity_;
henrik.lundin6d8e0112016-03-04 10:34:21 -0800274 last_output_sample_rate_hz_ = audio_frame->sample_rate_hz_;
henrik.lundind89814b2015-11-23 06:49:25 -0800275 RTC_DCHECK(last_output_sample_rate_hz_ == 8000 ||
276 last_output_sample_rate_hz_ == 16000 ||
277 last_output_sample_rate_hz_ == 32000 ||
278 last_output_sample_rate_hz_ == 48000)
279 << "Unexpected sample rate " << last_output_sample_rate_hz_;
Henrik Lundinc49e9c22020-05-25 11:26:15 +0200280
281 if (!output_delay_chain_.empty()) {
282 if (output_delay_chain_empty_) {
283 for (auto& f : output_delay_chain_) {
284 f.CopyFrom(*audio_frame);
285 }
286 output_delay_chain_empty_ = false;
287 delayed_last_output_sample_rate_hz_ = last_output_sample_rate_hz_;
288 } else {
289 RTC_DCHECK_GE(output_delay_chain_ix_, 0);
290 RTC_DCHECK_LT(output_delay_chain_ix_, output_delay_chain_.size());
291 swap(output_delay_chain_[output_delay_chain_ix_], *audio_frame);
292 *muted = audio_frame->muted();
293 output_delay_chain_ix_ =
294 (output_delay_chain_ix_ + 1) % output_delay_chain_.size();
295 delayed_last_output_sample_rate_hz_ = audio_frame->sample_rate_hz();
296 }
297 }
298
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000299 return kOK;
300}
301
kwiberg1c07c702017-03-27 07:15:49 -0700302void NetEqImpl::SetCodecs(const std::map<int, SdpAudioFormat>& codecs) {
Markus Handell0df0fae2020-07-07 15:53:34 +0200303 MutexLock lock(&mutex_);
kwiberg1c07c702017-03-27 07:15:49 -0700304 const std::vector<int> changed_payload_types =
305 decoder_database_->SetCodecs(codecs);
306 for (const int pt : changed_payload_types) {
Jakob Ivarsson44507082019-03-05 16:59:03 +0100307 packet_buffer_->DiscardPacketsWithPayloadType(pt, stats_.get());
kwiberg1c07c702017-03-27 07:15:49 -0700308 }
309}
310
kwiberg5adaf732016-10-04 09:33:27 -0700311bool NetEqImpl::RegisterPayloadType(int rtp_payload_type,
312 const SdpAudioFormat& audio_format) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100313 RTC_LOG(LS_VERBOSE) << "NetEqImpl::RegisterPayloadType: payload type "
Jonas Olssonabbe8412018-04-03 13:40:05 +0200314 << rtp_payload_type << ", codec "
315 << rtc::ToString(audio_format);
Markus Handell0df0fae2020-07-07 15:53:34 +0200316 MutexLock lock(&mutex_);
Henrik Lundinc417d9e2017-06-14 12:29:03 +0200317 return decoder_database_->RegisterPayload(rtp_payload_type, audio_format) ==
318 DecoderDatabase::kOK;
kwiberg5adaf732016-10-04 09:33:27 -0700319}
320
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000321int NetEqImpl::RemovePayloadType(uint8_t rtp_payload_type) {
Markus Handell0df0fae2020-07-07 15:53:34 +0200322 MutexLock lock(&mutex_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000323 int ret = decoder_database_->Remove(rtp_payload_type);
Henrik Lundinc417d9e2017-06-14 12:29:03 +0200324 if (ret == DecoderDatabase::kOK || ret == DecoderDatabase::kDecoderNotFound) {
Jakob Ivarsson44507082019-03-05 16:59:03 +0100325 packet_buffer_->DiscardPacketsWithPayloadType(rtp_payload_type,
326 stats_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000327 return kOK;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000328 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000329 return kFail;
330}
331
kwiberg6b19b562016-09-20 04:02:25 -0700332void NetEqImpl::RemoveAllPayloadTypes() {
Markus Handell0df0fae2020-07-07 15:53:34 +0200333 MutexLock lock(&mutex_);
kwiberg6b19b562016-09-20 04:02:25 -0700334 decoder_database_->RemoveAll();
335}
336
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000337bool NetEqImpl::SetMinimumDelay(int delay_ms) {
Markus Handell0df0fae2020-07-07 15:53:34 +0200338 MutexLock lock(&mutex_);
Gustaf Ullberg48d96c02017-09-15 13:59:52 +0200339 if (delay_ms >= 0 && delay_ms <= 10000) {
Ivo Creusen53a31f72019-10-24 15:20:39 +0200340 assert(controller_.get());
Henrik Lundinc49e9c22020-05-25 11:26:15 +0200341 return controller_->SetMinimumDelay(
342 std::max(delay_ms - output_delay_chain_ms_, 0));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000343 }
344 return false;
345}
346
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000347bool NetEqImpl::SetMaximumDelay(int delay_ms) {
Markus Handell0df0fae2020-07-07 15:53:34 +0200348 MutexLock lock(&mutex_);
Gustaf Ullberg48d96c02017-09-15 13:59:52 +0200349 if (delay_ms >= 0 && delay_ms <= 10000) {
Ivo Creusen53a31f72019-10-24 15:20:39 +0200350 assert(controller_.get());
Henrik Lundinc49e9c22020-05-25 11:26:15 +0200351 return controller_->SetMaximumDelay(
352 std::max(delay_ms - output_delay_chain_ms_, 0));
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000353 }
354 return false;
355}
356
Ruslan Burakov9bee67c2019-02-05 13:49:26 +0100357bool NetEqImpl::SetBaseMinimumDelayMs(int delay_ms) {
Markus Handell0df0fae2020-07-07 15:53:34 +0200358 MutexLock lock(&mutex_);
Ruslan Burakov9bee67c2019-02-05 13:49:26 +0100359 if (delay_ms >= 0 && delay_ms <= 10000) {
Ivo Creusen53a31f72019-10-24 15:20:39 +0200360 return controller_->SetBaseMinimumDelay(delay_ms);
Ruslan Burakov9bee67c2019-02-05 13:49:26 +0100361 }
362 return false;
363}
364
365int NetEqImpl::GetBaseMinimumDelayMs() const {
Markus Handell0df0fae2020-07-07 15:53:34 +0200366 MutexLock lock(&mutex_);
Ivo Creusen53a31f72019-10-24 15:20:39 +0200367 return controller_->GetBaseMinimumDelay();
Ruslan Burakov9bee67c2019-02-05 13:49:26 +0100368}
369
Henrik Lundinabbff892017-11-29 09:14:04 +0100370int NetEqImpl::TargetDelayMs() const {
Markus Handell0df0fae2020-07-07 15:53:34 +0200371 MutexLock lock(&mutex_);
Ivo Creusen53a31f72019-10-24 15:20:39 +0200372 RTC_DCHECK(controller_.get());
Henrik Lundinc49e9c22020-05-25 11:26:15 +0200373 return controller_->TargetLevelMs() + output_delay_chain_ms_;
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200374}
375
henrik.lundinb3f1c5d2016-08-22 15:39:53 -0700376int NetEqImpl::FilteredCurrentDelayMs() const {
Markus Handell0df0fae2020-07-07 15:53:34 +0200377 MutexLock lock(&mutex_);
Jakob Ivarssond487a552019-06-20 12:09:11 +0000378 // Sum up the filtered packet buffer level with the future length of the sync
Jakob Ivarssona36c5912019-06-27 10:12:02 +0200379 // buffer.
Ivo Creusen53a31f72019-10-24 15:20:39 +0200380 const int delay_samples =
381 controller_->GetFilteredBufferLevel() + sync_buffer_->FutureLength();
henrik.lundinb3f1c5d2016-08-22 15:39:53 -0700382 // The division below will truncate. The return value is in ms.
Henrik Lundinc49e9c22020-05-25 11:26:15 +0200383 return delay_samples / rtc::CheckedDivExact(fs_hz_, 1000) +
384 output_delay_chain_ms_;
henrik.lundinb3f1c5d2016-08-22 15:39:53 -0700385}
386
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000387int NetEqImpl::NetworkStatistics(NetEqNetworkStatistics* stats) {
Markus Handell0df0fae2020-07-07 15:53:34 +0200388 MutexLock lock(&mutex_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000389 assert(decoder_database_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700390 const size_t total_samples_in_buffers =
ossu61a208b2016-09-20 01:38:00 -0700391 packet_buffer_->NumSamplesInBuffer(decoder_frame_length_) +
Peter Kastingdce40cf2015-08-24 14:52:23 -0700392 sync_buffer_->FutureLength();
Ivo Creusen53a31f72019-10-24 15:20:39 +0200393 assert(controller_.get());
394 stats->preferred_buffer_size_ms = controller_->TargetLevelMs();
395 stats->jitter_peaks_found = controller_->PeakFound();
Jakob Ivarsson44507082019-03-05 16:59:03 +0100396 stats_->GetNetworkStatistics(fs_hz_, total_samples_in_buffers,
397 decoder_frame_length_, stats);
Henrik Lundinc49e9c22020-05-25 11:26:15 +0200398 // Compensate for output delay chain.
399 stats->current_buffer_size_ms += output_delay_chain_ms_;
400 stats->preferred_buffer_size_ms += output_delay_chain_ms_;
401 stats->mean_waiting_time_ms += output_delay_chain_ms_;
402 stats->median_waiting_time_ms += output_delay_chain_ms_;
403 stats->min_waiting_time_ms += output_delay_chain_ms_;
404 stats->max_waiting_time_ms += output_delay_chain_ms_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000405 return 0;
406}
407
Steve Anton2dbc69f2017-08-24 17:15:13 -0700408NetEqLifetimeStatistics NetEqImpl::GetLifetimeStatistics() const {
Markus Handell0df0fae2020-07-07 15:53:34 +0200409 MutexLock lock(&mutex_);
Jakob Ivarsson44507082019-03-05 16:59:03 +0100410 return stats_->GetLifetimeStatistics();
Steve Anton2dbc69f2017-08-24 17:15:13 -0700411}
412
Ivo Creusend1c2f782018-09-13 14:39:55 +0200413NetEqOperationsAndState NetEqImpl::GetOperationsAndState() const {
Markus Handell0df0fae2020-07-07 15:53:34 +0200414 MutexLock lock(&mutex_);
Jakob Ivarsson44507082019-03-05 16:59:03 +0100415 auto result = stats_->GetOperationsAndState();
Ivo Creusend1c2f782018-09-13 14:39:55 +0200416 result.current_buffer_size_ms =
417 (packet_buffer_->NumSamplesInBuffer(decoder_frame_length_) +
418 sync_buffer_->FutureLength()) *
419 1000 / fs_hz_;
Ivo Creusendc6d5532018-09-27 11:43:42 +0200420 result.current_frame_size_ms = decoder_frame_length_ * 1000 / fs_hz_;
421 result.next_packet_available = packet_buffer_->PeekNextPacket() &&
422 packet_buffer_->PeekNextPacket()->timestamp ==
423 sync_buffer_->end_timestamp();
Ivo Creusend1c2f782018-09-13 14:39:55 +0200424 return result;
425}
426
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000427void NetEqImpl::EnableVad() {
Markus Handell0df0fae2020-07-07 15:53:34 +0200428 MutexLock lock(&mutex_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000429 assert(vad_.get());
430 vad_->Enable();
431}
432
433void NetEqImpl::DisableVad() {
Markus Handell0df0fae2020-07-07 15:53:34 +0200434 MutexLock lock(&mutex_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000435 assert(vad_.get());
436 vad_->Disable();
437}
438
Danil Chapovalovb6021232018-06-19 13:26:36 +0200439absl::optional<uint32_t> NetEqImpl::GetPlayoutTimestamp() const {
Markus Handell0df0fae2020-07-07 15:53:34 +0200440 MutexLock lock(&mutex_);
Ivo Creusen3ce44a32019-10-31 14:38:11 +0100441 if (first_packet_ || last_mode_ == Mode::kRfc3389Cng ||
442 last_mode_ == Mode::kCodecInternalCng) {
wu@webrtc.org94454b72014-06-05 20:34:08 +0000443 // We don't have a valid RTP timestamp until we have decoded our first
henrik.lundin0d96ab72016-04-06 12:28:26 -0700444 // RTP packet. Also, the RTP timestamp is not accurate while playing CNG,
445 // which is indicated by returning an empty value.
Danil Chapovalovb6021232018-06-19 13:26:36 +0200446 return absl::nullopt;
wu@webrtc.org94454b72014-06-05 20:34:08 +0000447 }
Henrik Lundinc49e9c22020-05-25 11:26:15 +0200448 size_t sum_samples_in_output_delay_chain = 0;
449 for (const auto& audio_frame : output_delay_chain_) {
450 sum_samples_in_output_delay_chain += audio_frame.samples_per_channel();
451 }
452 return timestamp_scaler_->ToExternal(
453 playout_timestamp_ -
454 static_cast<uint32_t>(sum_samples_in_output_delay_chain));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000455}
456
henrik.lundind89814b2015-11-23 06:49:25 -0800457int NetEqImpl::last_output_sample_rate_hz() const {
Markus Handell0df0fae2020-07-07 15:53:34 +0200458 MutexLock lock(&mutex_);
Henrik Lundinc49e9c22020-05-25 11:26:15 +0200459 return delayed_last_output_sample_rate_hz_.value_or(
460 last_output_sample_rate_hz_);
henrik.lundind89814b2015-11-23 06:49:25 -0800461}
462
Karl Wiberg4b644112019-10-11 09:37:42 +0200463absl::optional<NetEq::DecoderFormat> NetEqImpl::GetDecoderFormat(
ossuf1b08da2016-09-23 02:19:43 -0700464 int payload_type) const {
Markus Handell0df0fae2020-07-07 15:53:34 +0200465 MutexLock lock(&mutex_);
kwibergc4ccd4d2016-09-21 10:55:15 -0700466 const DecoderDatabase::DecoderInfo* const di =
467 decoder_database_->GetDecoderInfo(payload_type);
Karl Wiberg4b644112019-10-11 09:37:42 +0200468 if (di) {
469 const AudioDecoder* const decoder = di->GetDecoder();
470 // TODO(kwiberg): Why the special case for RED?
471 return DecoderFormat{
472 /*sample_rate_hz=*/di->IsRed() ? 8000 : di->SampleRateHz(),
473 /*num_channels=*/
474 decoder ? rtc::dchecked_cast<int>(decoder->Channels()) : 1,
475 /*sdp_format=*/di->GetFormat()};
476 } else {
477 // Payload type not registered.
478 return absl::nullopt;
kwibergc4ccd4d2016-09-21 10:55:15 -0700479 }
kwibergc4ccd4d2016-09-21 10:55:15 -0700480}
481
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000482void NetEqImpl::FlushBuffers() {
Markus Handell0df0fae2020-07-07 15:53:34 +0200483 MutexLock lock(&mutex_);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100484 RTC_LOG(LS_VERBOSE) << "FlushBuffers";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000485 packet_buffer_->Flush();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000486 assert(sync_buffer_.get());
487 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000488 sync_buffer_->Flush();
489 sync_buffer_->set_next_index(sync_buffer_->next_index() -
490 expand_->overlap_length());
491 // Set to wait for new codec.
492 first_packet_ = true;
493}
494
henrik.lundin48ed9302015-10-29 05:36:24 -0700495void NetEqImpl::EnableNack(size_t max_nack_list_size) {
Markus Handell0df0fae2020-07-07 15:53:34 +0200496 MutexLock lock(&mutex_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700497 if (!nack_enabled_) {
498 const int kNackThresholdPackets = 2;
henrik.lundin91951862016-06-08 06:43:41 -0700499 nack_.reset(NackTracker::Create(kNackThresholdPackets));
henrik.lundin48ed9302015-10-29 05:36:24 -0700500 nack_enabled_ = true;
501 nack_->UpdateSampleRate(fs_hz_);
502 }
503 nack_->SetMaxNackListSize(max_nack_list_size);
504}
505
506void NetEqImpl::DisableNack() {
Markus Handell0df0fae2020-07-07 15:53:34 +0200507 MutexLock lock(&mutex_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700508 nack_.reset();
509 nack_enabled_ = false;
510}
511
512std::vector<uint16_t> NetEqImpl::GetNackList(int64_t round_trip_time_ms) const {
Markus Handell0df0fae2020-07-07 15:53:34 +0200513 MutexLock lock(&mutex_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700514 if (!nack_enabled_) {
515 return std::vector<uint16_t>();
516 }
517 RTC_DCHECK(nack_.get());
518 return nack_->GetNackList(round_trip_time_ms);
minyue@webrtc.orgd7301772013-08-29 00:58:14 +0000519}
520
henrik.lundin114c1b32017-04-26 07:47:32 -0700521std::vector<uint32_t> NetEqImpl::LastDecodedTimestamps() const {
Markus Handell0df0fae2020-07-07 15:53:34 +0200522 MutexLock lock(&mutex_);
henrik.lundin114c1b32017-04-26 07:47:32 -0700523 return last_decoded_timestamps_;
524}
525
526int NetEqImpl::SyncBufferSizeMs() const {
Markus Handell0df0fae2020-07-07 15:53:34 +0200527 MutexLock lock(&mutex_);
henrik.lundin114c1b32017-04-26 07:47:32 -0700528 return rtc::dchecked_cast<int>(sync_buffer_->FutureLength() /
529 rtc::CheckedDivExact(fs_hz_, 1000));
530}
531
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000532const SyncBuffer* NetEqImpl::sync_buffer_for_test() const {
Markus Handell0df0fae2020-07-07 15:53:34 +0200533 MutexLock lock(&mutex_);
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000534 return sync_buffer_.get();
535}
536
Ivo Creusen3ce44a32019-10-31 14:38:11 +0100537NetEq::Operation NetEqImpl::last_operation_for_test() const {
Markus Handell0df0fae2020-07-07 15:53:34 +0200538 MutexLock lock(&mutex_);
minyue5bd33972016-05-02 04:46:11 -0700539 return last_operation_;
540}
541
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000542// Methods below this line are private.
543
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200544int NetEqImpl::InsertPacketInternal(const RTPHeader& rtp_header,
Karl Wiberg45eb1352019-10-10 14:23:00 +0200545 rtc::ArrayView<const uint8_t> payload) {
kwibergee2bac22015-11-11 10:34:00 -0800546 if (payload.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100547 RTC_LOG_F(LS_ERROR) << "payload is empty";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000548 return kInvalidPointer;
549 }
Alessio Bazzica8f319a32019-07-24 16:47:02 +0000550
551 int64_t receive_time_ms = clock_->TimeInMilliseconds();
Jakob Ivarsson44507082019-03-05 16:59:03 +0100552 stats_->ReceivedPacket();
ossu17e3fa12016-09-08 04:52:55 -0700553
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000554 PacketList packet_list;
ossua73f6c92016-10-24 08:25:28 -0700555 // Insert packet in a packet list.
Alessio Bazzica8f319a32019-07-24 16:47:02 +0000556 packet_list.push_back([&rtp_header, &payload, &receive_time_ms] {
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000557 // Convert to Packet.
ossua73f6c92016-10-24 08:25:28 -0700558 Packet packet;
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200559 packet.payload_type = rtp_header.payloadType;
560 packet.sequence_number = rtp_header.sequenceNumber;
561 packet.timestamp = rtp_header.timestamp;
ossua73f6c92016-10-24 08:25:28 -0700562 packet.payload.SetData(payload.data(), payload.size());
Alessio Bazzica8f319a32019-07-24 16:47:02 +0000563 packet.packet_info = RtpPacketInfo(rtp_header, receive_time_ms);
henrik.lundin84f8cd62016-04-26 07:45:16 -0700564 // Waiting time will be set upon inserting the packet in the buffer.
ossua73f6c92016-10-24 08:25:28 -0700565 RTC_DCHECK(!packet.waiting_time);
566 return packet;
567 }());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000568
Niels Möllerbb9f4c12018-11-21 16:07:10 +0100569 bool update_sample_rate_and_channels = first_packet_;
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700570
571 if (update_sample_rate_and_channels) {
572 // Reset timestamp scaling.
573 timestamp_scaler_->Reset();
574 }
575
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200576 if (!decoder_database_->IsRed(rtp_header.payloadType)) {
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700577 // Scale timestamp to internal domain (only for some codecs).
578 timestamp_scaler_->ToInternal(&packet_list);
579 }
580
581 // Store these for later use, since the first packet may very well disappear
582 // before we need these values.
583 uint32_t main_timestamp = packet_list.front().timestamp;
584 uint8_t main_payload_type = packet_list.front().payload_type;
585 uint16_t main_sequence_number = packet_list.front().sequence_number;
586
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000587 // Reinitialize NetEq if it's needed (changed SSRC or first call).
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700588 if (update_sample_rate_and_channels) {
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000589 // Note: |first_packet_| will be cleared further down in this method, once
590 // the packet has been successfully inserted into the packet buffer.
591
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000592 // Flush the packet buffer and DTMF buffer.
593 packet_buffer_->Flush();
594 dtmf_buffer_->Flush();
595
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000596 // Update audio buffer timestamp.
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700597 sync_buffer_->IncreaseEndTimestamp(main_timestamp - timestamp_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000598
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000599 // Update codecs.
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700600 timestamp_ = main_timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000601 }
602
ossu7a377612016-10-18 04:06:13 -0700603 if (nack_enabled_) {
604 RTC_DCHECK(nack_);
605 if (update_sample_rate_and_channels) {
606 nack_->Reset();
607 }
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200608 nack_->UpdateLastReceivedPacket(rtp_header.sequenceNumber,
609 rtp_header.timestamp);
ossu7a377612016-10-18 04:06:13 -0700610 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000611
612 // Check for RED payload type, and separate payloads into several packets.
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200613 if (decoder_database_->IsRed(rtp_header.payloadType)) {
ossua70695a2016-09-22 02:06:28 -0700614 if (!red_payload_splitter_->SplitRed(&packet_list)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000615 return kRedundancySplitError;
616 }
617 // Only accept a few RED payloads of the same type as the main data,
618 // DTMF events and CNG.
ossua70695a2016-09-22 02:06:28 -0700619 red_payload_splitter_->CheckRedPayloads(&packet_list, *decoder_database_);
Henrik Lundindefa7a82018-07-03 13:07:30 +0200620 if (packet_list.empty()) {
621 return kRedundancySplitError;
622 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000623 }
624
625 // Check payload types.
626 if (decoder_database_->CheckPayloadTypes(packet_list) ==
627 DecoderDatabase::kDecoderNotFound) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000628 return kUnknownRtpPayloadType;
629 }
630
ossu7a377612016-10-18 04:06:13 -0700631 RTC_DCHECK(!packet_list.empty());
ossu7a377612016-10-18 04:06:13 -0700632
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700633 // Update main_timestamp, if new packets appear in the list
634 // after RED splitting.
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200635 if (decoder_database_->IsRed(rtp_header.payloadType)) {
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700636 timestamp_scaler_->ToInternal(&packet_list);
637 main_timestamp = packet_list.front().timestamp;
638 main_payload_type = packet_list.front().payload_type;
639 main_sequence_number = packet_list.front().sequence_number;
640 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000641
642 // Process DTMF payloads. Cycle through the list of packets, and pick out any
643 // DTMF payloads found.
644 PacketList::iterator it = packet_list.begin();
645 while (it != packet_list.end()) {
ossua73f6c92016-10-24 08:25:28 -0700646 const Packet& current_packet = (*it);
647 RTC_DCHECK(!current_packet.payload.empty());
648 if (decoder_database_->IsDtmf(current_packet.payload_type)) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000649 DtmfEvent event;
ossua73f6c92016-10-24 08:25:28 -0700650 int ret = DtmfBuffer::ParseEvent(current_packet.timestamp,
651 current_packet.payload.data(),
652 current_packet.payload.size(), &event);
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000653 if (ret != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000654 return kDtmfParsingError;
655 }
656 if (dtmf_buffer_->InsertEvent(event) != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000657 return kDtmfInsertError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000658 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000659 it = packet_list.erase(it);
660 } else {
661 ++it;
662 }
663 }
664
ossu61a208b2016-09-20 01:38:00 -0700665 PacketList parsed_packet_list;
666 while (!packet_list.empty()) {
ossua73f6c92016-10-24 08:25:28 -0700667 Packet& packet = packet_list.front();
ossu61a208b2016-09-20 01:38:00 -0700668 const DecoderDatabase::DecoderInfo* info =
ossua73f6c92016-10-24 08:25:28 -0700669 decoder_database_->GetDecoderInfo(packet.payload_type);
ossu61a208b2016-09-20 01:38:00 -0700670 if (!info) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100671 RTC_LOG(LS_WARNING) << "SplitAudio unknown payload type";
ossu61a208b2016-09-20 01:38:00 -0700672 return kUnknownRtpPayloadType;
673 }
674
675 if (info->IsComfortNoise()) {
676 // Carry comfort noise packets along.
ossua73f6c92016-10-24 08:25:28 -0700677 parsed_packet_list.splice(parsed_packet_list.end(), packet_list,
678 packet_list.begin());
ossu61a208b2016-09-20 01:38:00 -0700679 } else {
ossua73f6c92016-10-24 08:25:28 -0700680 const auto sequence_number = packet.sequence_number;
681 const auto payload_type = packet.payload_type;
682 const Packet::Priority original_priority = packet.priority;
Alessio Bazzica8f319a32019-07-24 16:47:02 +0000683 const auto& packet_info = packet.packet_info;
Yves Gerey665174f2018-06-19 15:03:05 +0200684 auto packet_from_result = [&](AudioDecoder::ParseResult& result) {
ossua73f6c92016-10-24 08:25:28 -0700685 Packet new_packet;
686 new_packet.sequence_number = sequence_number;
687 new_packet.payload_type = payload_type;
688 new_packet.timestamp = result.timestamp;
689 new_packet.priority.codec_level = result.priority;
690 new_packet.priority.red_level = original_priority.red_level;
Alessio Bazzica8f319a32019-07-24 16:47:02 +0000691 new_packet.packet_info = packet_info;
ossua73f6c92016-10-24 08:25:28 -0700692 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.
Ivo Creusenbf4a2212019-04-24 14:06:24 +0200721 const size_t number_of_primary_packets = std::count_if(
Ivo Creusenfd7c0a52017-10-20 12:35:04 +0200722 parsed_packet_list.begin(), parsed_packet_list.end(),
723 [](const Packet& in) { return in.priority.codec_level == 0; });
Ivo Creusenbf4a2212019-04-24 14:06:24 +0200724 if (number_of_primary_packets < parsed_packet_list.size()) {
725 stats_->SecondaryPacketsReceived(parsed_packet_list.size() -
726 number_of_primary_packets);
727 }
Ivo Creusenfd7c0a52017-10-20 12:35:04 +0200728
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000729 // Insert packets in buffer.
ossua70695a2016-09-22 02:06:28 -0700730 const int ret = packet_buffer_->InsertPacketList(
ossu61a208b2016-09-20 01:38:00 -0700731 &parsed_packet_list, *decoder_database_, &current_rtp_payload_type_,
Jakob Ivarsson44507082019-03-05 16:59:03 +0100732 &current_cng_rtp_payload_type_, stats_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000733 if (ret == PacketBuffer::kFlushed) {
734 // Reset DSP timestamp etc. if packet buffer flushed.
735 new_codec_ = true;
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000736 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000737 } else if (ret != PacketBuffer::kOK) {
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000738 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000739 }
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000740
741 if (first_packet_) {
742 first_packet_ = false;
743 // Update the codec on the next GetAudio call.
744 new_codec_ = true;
745 }
746
henrik.lundinda8bbf62016-08-31 03:14:11 -0700747 if (current_rtp_payload_type_) {
748 RTC_DCHECK(decoder_database_->GetDecoderInfo(*current_rtp_payload_type_))
749 << "Payload type " << static_cast<int>(*current_rtp_payload_type_)
750 << " is unknown where it shouldn't be";
751 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000752
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000753 if (update_sample_rate_and_channels && !packet_buffer_->Empty()) {
754 // We do not use |current_rtp_payload_type_| to |set payload_type|, but
755 // get the next RTP header from |packet_buffer_| to obtain the payload type.
756 // The reason for it is the following corner case. If NetEq receives a
757 // CNG packet with a sample rate different than the current CNG then it
758 // flushes its buffer, assuming send codec must have been changed. However,
759 // payload type of the hypothetically new send codec is not known.
ossu7a377612016-10-18 04:06:13 -0700760 const Packet* next_packet = packet_buffer_->PeekNextPacket();
761 RTC_DCHECK(next_packet);
762 const int payload_type = next_packet->payload_type;
ossu97ba30e2016-04-25 07:55:58 -0700763 size_t channels = 1;
764 if (!decoder_database_->IsComfortNoise(payload_type)) {
765 AudioDecoder* decoder = decoder_database_->GetDecoder(payload_type);
766 assert(decoder); // Payloads are already checked to be valid.
767 channels = decoder->Channels();
768 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000769 const DecoderDatabase::DecoderInfo* decoder_info =
770 decoder_database_->GetDecoderInfo(payload_type);
771 assert(decoder_info);
kwibergc0f2dcf2016-05-31 06:28:03 -0700772 if (decoder_info->SampleRateHz() != fs_hz_ ||
ossu97ba30e2016-04-25 07:55:58 -0700773 channels != algorithm_buffer_->Channels()) {
Yves Gerey665174f2018-06-19 15:03:05 +0200774 SetSampleRateAndChannels(decoder_info->SampleRateHz(), channels);
henrik.lundin48ed9302015-10-29 05:36:24 -0700775 }
776 if (nack_enabled_) {
777 RTC_DCHECK(nack_);
778 // Update the sample rate even if the rate is not new, because of Reset().
779 nack_->UpdateSampleRate(fs_hz_);
780 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000781 }
782
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000783 const DecoderDatabase::DecoderInfo* dec_info =
ossu7a377612016-10-18 04:06:13 -0700784 decoder_database_->GetDecoderInfo(main_payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000785 assert(dec_info); // Already checked that the payload type is known.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000786
Ivo Creusen53a31f72019-10-24 15:20:39 +0200787 const bool last_cng_or_dtmf =
788 dec_info->IsComfortNoise() || dec_info->IsDtmf();
789 const size_t packet_length_samples =
790 number_of_primary_packets * decoder_frame_length_;
791 // Only update statistics if incoming packet is not older than last played
792 // out packet or RTX handling is enabled, and if new codec flag is not
793 // set.
794 const bool should_update_stats =
795 (enable_rtx_handling_ ||
796 static_cast<int32_t>(main_timestamp - timestamp_) >= 0) &&
797 !new_codec_;
798
799 auto relative_delay = controller_->PacketArrived(
800 last_cng_or_dtmf, packet_length_samples, should_update_stats,
801 main_sequence_number, main_timestamp, fs_hz_);
802 if (relative_delay) {
803 stats_->RelativePacketArrivalDelay(relative_delay.value());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000804 }
805 return 0;
806}
807
Ivo Creusen55de08e2018-09-03 11:49:27 +0200808int NetEqImpl::GetAudioInternal(AudioFrame* audio_frame,
809 bool* muted,
Ivo Creusen3ce44a32019-10-31 14:38:11 +0100810 absl::optional<Operation> action_override) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000811 PacketList packet_list;
812 DtmfEvent dtmf_event;
Ivo Creusen3ce44a32019-10-31 14:38:11 +0100813 Operation operation;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000814 bool play_dtmf;
henrik.lundin7a926812016-05-12 13:51:28 -0700815 *muted = false;
henrik.lundin114c1b32017-04-26 07:47:32 -0700816 last_decoded_timestamps_.clear();
Alessio Bazzica8f319a32019-07-24 16:47:02 +0000817 last_decoded_packet_infos_.clear();
henrik.lundined497212016-04-25 10:11:38 -0700818 tick_timer_->Increment();
Jakob Ivarsson44507082019-03-05 16:59:03 +0100819 stats_->IncreaseCounter(output_size_samples_, fs_hz_);
820 const auto lifetime_stats = stats_->GetLifetimeStatistics();
Henrik Lundin3ef3bfc2018-04-10 15:10:26 +0200821 expand_uma_logger_.UpdateSampleCounter(lifetime_stats.concealed_samples,
822 fs_hz_);
823 speech_expand_uma_logger_.UpdateSampleCounter(
Ivo Creusenbf4a2212019-04-24 14:06:24 +0200824 lifetime_stats.concealed_samples -
825 lifetime_stats.silent_concealed_samples,
826 fs_hz_);
henrik.lundin7a926812016-05-12 13:51:28 -0700827
828 // Check for muted state.
829 if (enable_muted_state_ && expand_->Muted() && packet_buffer_->Empty()) {
Ivo Creusen3ce44a32019-10-31 14:38:11 +0100830 RTC_DCHECK_EQ(last_mode_, Mode::kExpand);
henrik.lundina4491072017-07-06 05:23:53 -0700831 audio_frame->Reset();
832 RTC_DCHECK(audio_frame->muted()); // Reset() should mute the frame.
henrik.lundin7a926812016-05-12 13:51:28 -0700833 playout_timestamp_ += static_cast<uint32_t>(output_size_samples_);
834 audio_frame->sample_rate_hz_ = fs_hz_;
835 audio_frame->samples_per_channel_ = output_size_samples_;
836 audio_frame->timestamp_ =
837 first_packet_
838 ? 0
839 : timestamp_scaler_->ToExternal(playout_timestamp_) -
840 static_cast<uint32_t>(audio_frame->samples_per_channel_);
841 audio_frame->num_channels_ = sync_buffer_->Channels();
Jakob Ivarsson44507082019-03-05 16:59:03 +0100842 stats_->ExpandedNoiseSamples(output_size_samples_, false);
henrik.lundin7a926812016-05-12 13:51:28 -0700843 *muted = true;
844 return 0;
845 }
Ivo Creusen55de08e2018-09-03 11:49:27 +0200846 int return_value = GetDecision(&operation, &packet_list, &dtmf_event,
847 &play_dtmf, action_override);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000848 if (return_value != 0) {
Ivo Creusen3ce44a32019-10-31 14:38:11 +0100849 last_mode_ = Mode::kError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000850 return return_value;
851 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000852
853 AudioDecoder::SpeechType speech_type;
854 int length = 0;
Henrik Lundin18036282017-11-02 12:09:06 +0100855 const size_t start_num_packets = packet_list.size();
Yves Gerey665174f2018-06-19 15:03:05 +0200856 int decode_return_value =
857 Decode(&packet_list, &operation, &length, &speech_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000858
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000859 assert(vad_.get());
Ivo Creusen3ce44a32019-10-31 14:38:11 +0100860 bool sid_frame_available =
861 (operation == Operation::kRfc3389Cng && !packet_list.empty());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700862 vad_->Update(decoded_buffer_.get(), static_cast<size_t>(length), speech_type,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000863 sid_frame_available, fs_hz_);
864
Henrik Lundin18036282017-11-02 12:09:06 +0100865 // This is the criterion that we did decode some data through the speech
866 // decoder, and the operation resulted in comfort noise.
867 const bool codec_internal_sid_frame =
Henrik Lundin4f2a4a12018-01-26 17:32:56 +0100868 (speech_type == AudioDecoder::kComfortNoise &&
869 start_num_packets > packet_list.size());
Henrik Lundin18036282017-11-02 12:09:06 +0100870
871 if (sid_frame_available || codec_internal_sid_frame) {
henrik.lundinb1fb72b2016-05-03 08:18:47 -0700872 // Start a new stopwatch since we are decoding a new CNG packet.
873 generated_noise_stopwatch_ = tick_timer_->GetNewStopwatch();
874 }
875
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000876 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000877 switch (operation) {
Ivo Creusen3ce44a32019-10-31 14:38:11 +0100878 case Operation::kNormal: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000879 DoNormal(decoded_buffer_.get(), length, speech_type, play_dtmf);
Henrik Lundin2a8bd092019-04-26 09:47:07 +0200880 if (length > 0) {
881 stats_->DecodedOutputPlayed();
882 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000883 break;
884 }
Ivo Creusen3ce44a32019-10-31 14:38:11 +0100885 case Operation::kMerge: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000886 DoMerge(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000887 break;
888 }
Ivo Creusen3ce44a32019-10-31 14:38:11 +0100889 case Operation::kExpand: {
Henrik Lundin00eb12a2018-09-05 18:14:52 +0200890 RTC_DCHECK_EQ(return_value, 0);
891 if (!current_rtp_payload_type_ || !DoCodecPlc()) {
892 return_value = DoExpand(play_dtmf);
893 }
894 RTC_DCHECK_GE(sync_buffer_->FutureLength() - expand_->overlap_length(),
895 output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000896 break;
897 }
Ivo Creusen3ce44a32019-10-31 14:38:11 +0100898 case Operation::kAccelerate:
899 case Operation::kFastAccelerate: {
Henrik Lundincf808d22015-05-27 14:33:29 +0200900 const bool fast_accelerate =
Ivo Creusen3ce44a32019-10-31 14:38:11 +0100901 enable_fast_accelerate_ && (operation == Operation::kFastAccelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000902 return_value = DoAccelerate(decoded_buffer_.get(), length, speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +0200903 play_dtmf, fast_accelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000904 break;
905 }
Ivo Creusen3ce44a32019-10-31 14:38:11 +0100906 case Operation::kPreemptiveExpand: {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000907 return_value = DoPreemptiveExpand(decoded_buffer_.get(), length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000908 speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000909 break;
910 }
Ivo Creusen3ce44a32019-10-31 14:38:11 +0100911 case Operation::kRfc3389Cng:
912 case Operation::kRfc3389CngNoPacket: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000913 return_value = DoRfc3389Cng(&packet_list, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000914 break;
915 }
Ivo Creusen3ce44a32019-10-31 14:38:11 +0100916 case Operation::kCodecInternalCng: {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000917 // This handles the case when there is no transmission and the decoder
918 // should produce internal comfort noise.
919 // TODO(hlundin): Write test for codec-internal CNG.
minyuel6d92bf52015-09-23 15:20:39 +0200920 DoCodecInternalCng(decoded_buffer_.get(), length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000921 break;
922 }
Ivo Creusen3ce44a32019-10-31 14:38:11 +0100923 case Operation::kDtmf: {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000924 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000925 return_value = DoDtmf(dtmf_event, &play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000926 break;
927 }
Ivo Creusen3ce44a32019-10-31 14:38:11 +0100928 case Operation::kUndefined: {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100929 RTC_LOG(LS_ERROR) << "Invalid operation kUndefined.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000930 assert(false); // This should not happen.
Ivo Creusen3ce44a32019-10-31 14:38:11 +0100931 last_mode_ = Mode::kError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000932 return kInvalidOperation;
933 }
934 } // End of switch.
minyue5bd33972016-05-02 04:46:11 -0700935 last_operation_ = operation;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000936 if (return_value < 0) {
937 return return_value;
938 }
939
Ivo Creusen3ce44a32019-10-31 14:38:11 +0100940 if (last_mode_ != Mode::kRfc3389Cng) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000941 comfort_noise_->Reset();
942 }
943
Alessio Bazzica8f319a32019-07-24 16:47:02 +0000944 // We treat it as if all packets referenced to by |last_decoded_packet_infos_|
945 // were mashed together when creating the samples in |algorithm_buffer_|.
Minyue Lic759f832019-08-09 13:20:03 +0200946 RtpPacketInfos packet_infos(last_decoded_packet_infos_);
Alessio Bazzica8f319a32019-07-24 16:47:02 +0000947
948 // Copy samples from |algorithm_buffer_| to |sync_buffer_|.
949 //
950 // TODO(bugs.webrtc.org/10757):
951 // We would in the future also like to pass |packet_infos| so that we can do
952 // sample-perfect tracking of that information across |sync_buffer_|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000953 sync_buffer_->PushBack(*algorithm_buffer_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000954
955 // Extract data from |sync_buffer_| to |output|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000956 size_t num_output_samples_per_channel = output_size_samples_;
957 size_t num_output_samples = output_size_samples_ * sync_buffer_->Channels();
henrik.lundin6d8e0112016-03-04 10:34:21 -0800958 if (num_output_samples > AudioFrame::kMaxDataSizeSamples) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100959 RTC_LOG(LS_WARNING) << "Output array is too short. "
960 << AudioFrame::kMaxDataSizeSamples << " < "
961 << output_size_samples_ << " * "
962 << sync_buffer_->Channels();
henrik.lundin6d8e0112016-03-04 10:34:21 -0800963 num_output_samples = AudioFrame::kMaxDataSizeSamples;
964 num_output_samples_per_channel =
965 AudioFrame::kMaxDataSizeSamples / sync_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000966 }
henrik.lundin6d8e0112016-03-04 10:34:21 -0800967 sync_buffer_->GetNextAudioInterleaved(num_output_samples_per_channel,
968 audio_frame);
969 audio_frame->sample_rate_hz_ = fs_hz_;
Alessio Bazzica8f319a32019-07-24 16:47:02 +0000970 // TODO(bugs.webrtc.org/10757):
971 // We don't have the ability to properly track individual packets once their
972 // audio samples have entered |sync_buffer_|. So for now, treat it as if
973 // |packet_infos| from packets decoded by the current |GetAudioInternal()|
974 // call were all consumed assembling the current audio frame and the current
975 // audio frame only.
976 audio_frame->packet_infos_ = std::move(packet_infos);
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200977 if (sync_buffer_->FutureLength() < expand_->overlap_length()) {
978 // The sync buffer should always contain |overlap_length| samples, but now
979 // too many samples have been extracted. Reinstall the |overlap_length|
980 // lookahead by moving the index.
981 const size_t missing_lookahead_samples =
982 expand_->overlap_length() - sync_buffer_->FutureLength();
henrikg91d6ede2015-09-17 00:24:34 -0700983 RTC_DCHECK_GE(sync_buffer_->next_index(), missing_lookahead_samples);
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200984 sync_buffer_->set_next_index(sync_buffer_->next_index() -
985 missing_lookahead_samples);
986 }
henrik.lundin6d8e0112016-03-04 10:34:21 -0800987 if (audio_frame->samples_per_channel_ != output_size_samples_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100988 RTC_LOG(LS_ERROR) << "audio_frame->samples_per_channel_ ("
989 << audio_frame->samples_per_channel_
990 << ") != output_size_samples_ (" << output_size_samples_
991 << ")";
minyue@webrtc.orgdb1cefc2013-08-13 01:39:21 +0000992 // TODO(minyue): treatment of under-run, filling zeros
yujo36b1a5f2017-06-12 12:45:32 -0700993 audio_frame->Mute();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000994 return kSampleUnderrun;
995 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000996
997 // Should always have overlap samples left in the |sync_buffer_|.
henrikg91d6ede2015-09-17 00:24:34 -0700998 RTC_DCHECK_GE(sync_buffer_->FutureLength(), expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000999
yujo36b1a5f2017-06-12 12:45:32 -07001000 // TODO(yujo): For muted frames, this can be a copy rather than an addition.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001001 if (play_dtmf) {
yujo36b1a5f2017-06-12 12:45:32 -07001002 return_value = DtmfOverdub(dtmf_event, sync_buffer_->Channels(),
1003 audio_frame->mutable_data());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001004 }
1005
1006 // Update the background noise parameters if last operation wrote data
1007 // straight from the decoder to the |sync_buffer_|. That is, none of the
1008 // operations that modify the signal can be followed by a parameter update.
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001009 if ((last_mode_ == Mode::kNormal) || (last_mode_ == Mode::kAccelerateFail) ||
1010 (last_mode_ == Mode::kPreemptiveExpandFail) ||
1011 (last_mode_ == Mode::kRfc3389Cng) ||
1012 (last_mode_ == Mode::kCodecInternalCng)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001013 background_noise_->Update(*sync_buffer_, *vad_.get());
1014 }
1015
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001016 if (operation == Operation::kDtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001017 // DTMF data was written the end of |sync_buffer_|.
1018 // Update index to end of DTMF data in |sync_buffer_|.
1019 sync_buffer_->set_dtmf_index(sync_buffer_->Size());
1020 }
1021
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001022 if (last_mode_ != Mode::kExpand && last_mode_ != Mode::kCodecPlc) {
henrik.lundin@webrtc.orged865b52014-03-06 10:28:07 +00001023 // If last operation was not expand, calculate the |playout_timestamp_| from
1024 // the |sync_buffer_|. However, do not update the |playout_timestamp_| if it
1025 // would be moved "backwards".
Yves Gerey665174f2018-06-19 15:03:05 +02001026 uint32_t temp_timestamp =
1027 sync_buffer_->end_timestamp() -
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001028 static_cast<uint32_t>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001029 if (static_cast<int32_t>(temp_timestamp - playout_timestamp_) > 0) {
1030 playout_timestamp_ = temp_timestamp;
1031 }
1032 } else {
1033 // Use dead reckoning to estimate the |playout_timestamp_|.
Peter Kastingb7e50542015-06-11 12:55:50 -07001034 playout_timestamp_ += static_cast<uint32_t>(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001035 }
henrik.lundin15c51e32016-04-06 08:38:56 -07001036 // Set the timestamp in the audio frame to zero before the first packet has
1037 // been inserted. Otherwise, subtract the frame size in samples to get the
1038 // timestamp of the first sample in the frame (playout_timestamp_ is the
1039 // last + 1).
1040 audio_frame->timestamp_ =
1041 first_packet_
1042 ? 0
1043 : timestamp_scaler_->ToExternal(playout_timestamp_) -
1044 static_cast<uint32_t>(audio_frame->samples_per_channel_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001045
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001046 if (!(last_mode_ == Mode::kRfc3389Cng ||
1047 last_mode_ == Mode::kCodecInternalCng || last_mode_ == Mode::kExpand ||
1048 last_mode_ == Mode::kCodecPlc)) {
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001049 generated_noise_stopwatch_.reset();
1050 }
1051
Yves Gerey665174f2018-06-19 15:03:05 +02001052 if (decode_return_value)
1053 return decode_return_value;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001054 return return_value;
1055}
1056
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001057int NetEqImpl::GetDecision(Operation* operation,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001058 PacketList* packet_list,
1059 DtmfEvent* dtmf_event,
Ivo Creusen55de08e2018-09-03 11:49:27 +02001060 bool* play_dtmf,
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001061 absl::optional<Operation> action_override) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001062 // Initialize output variables.
1063 *play_dtmf = false;
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001064 *operation = Operation::kUndefined;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001065
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001066 assert(sync_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001067 uint32_t end_timestamp = sync_buffer_->end_timestamp();
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001068 if (!new_codec_) {
1069 const uint32_t five_seconds_samples = 5 * fs_hz_;
minyue-webrtcfae474c2017-07-05 11:17:40 +02001070 packet_buffer_->DiscardOldPackets(end_timestamp, five_seconds_samples,
Jakob Ivarsson44507082019-03-05 16:59:03 +01001071 stats_.get());
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001072 }
ossu7a377612016-10-18 04:06:13 -07001073 const Packet* packet = packet_buffer_->PeekNextPacket();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001074
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001075 RTC_DCHECK(!generated_noise_stopwatch_ ||
1076 generated_noise_stopwatch_->ElapsedTicks() >= 1);
1077 uint64_t generated_noise_samples =
Yves Gerey665174f2018-06-19 15:03:05 +02001078 generated_noise_stopwatch_ ? (generated_noise_stopwatch_->ElapsedTicks() -
1079 1) * output_size_samples_ +
Ivo Creusen53a31f72019-10-24 15:20:39 +02001080 controller_->noise_fast_forward()
Yves Gerey665174f2018-06-19 15:03:05 +02001081 : 0;
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001082
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001083 if (controller_->CngRfc3389On() || last_mode_ == Mode::kRfc3389Cng) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001084 // Because of timestamp peculiarities, we have to "manually" disallow using
1085 // a CNG packet with the same timestamp as the one that was last played.
1086 // This can happen when using redundancy and will cause the timing to shift.
ossu7a377612016-10-18 04:06:13 -07001087 while (packet && decoder_database_->IsComfortNoise(packet->payload_type) &&
1088 (end_timestamp >= packet->timestamp ||
1089 end_timestamp + generated_noise_samples > packet->timestamp)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001090 // Don't use this packet, discard it.
Jakob Ivarsson44507082019-03-05 16:59:03 +01001091 if (packet_buffer_->DiscardNextPacket(stats_.get()) !=
1092 PacketBuffer::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001093 assert(false); // Must be ok by design.
1094 }
1095 // Check buffer again.
1096 if (!new_codec_) {
Jakob Ivarsson44507082019-03-05 16:59:03 +01001097 packet_buffer_->DiscardOldPackets(end_timestamp, 5 * fs_hz_,
1098 stats_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001099 }
ossu7a377612016-10-18 04:06:13 -07001100 packet = packet_buffer_->PeekNextPacket();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001101 }
1102 }
1103
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001104 assert(expand_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001105 const int samples_left = static_cast<int>(sync_buffer_->FutureLength() -
Yves Gerey665174f2018-06-19 15:03:05 +02001106 expand_->overlap_length());
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001107 if (last_mode_ == Mode::kAccelerateSuccess ||
1108 last_mode_ == Mode::kAccelerateLowEnergy ||
1109 last_mode_ == Mode::kPreemptiveExpandSuccess ||
1110 last_mode_ == Mode::kPreemptiveExpandLowEnergy) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001111 // Subtract (samples_left + output_size_samples_) from sampleMemory.
Ivo Creusen53a31f72019-10-24 15:20:39 +02001112 controller_->AddSampleMemory(
kwibergd3edd772017-03-01 18:52:48 -08001113 -(samples_left + rtc::dchecked_cast<int>(output_size_samples_)));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001114 }
1115
1116 // Check if it is time to play a DTMF event.
Peter Kastingb7e50542015-06-11 12:55:50 -07001117 if (dtmf_buffer_->GetEvent(
Yves Gerey665174f2018-06-19 15:03:05 +02001118 static_cast<uint32_t>(end_timestamp + generated_noise_samples),
1119 dtmf_event)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001120 *play_dtmf = true;
1121 }
1122
1123 // Get instruction.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001124 assert(sync_buffer_.get());
1125 assert(expand_.get());
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001126 generated_noise_samples =
1127 generated_noise_stopwatch_
1128 ? generated_noise_stopwatch_->ElapsedTicks() * output_size_samples_ +
Ivo Creusen53a31f72019-10-24 15:20:39 +02001129 controller_->noise_fast_forward()
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001130 : 0;
Ivo Creusen53a31f72019-10-24 15:20:39 +02001131 NetEqController::NetEqStatus status;
1132 status.packet_buffer_info.dtx_or_cng =
1133 packet_buffer_->ContainsDtxOrCngPacket(decoder_database_.get());
1134 status.packet_buffer_info.num_samples =
1135 packet_buffer_->NumSamplesInBuffer(decoder_frame_length_);
1136 status.packet_buffer_info.span_samples = packet_buffer_->GetSpanSamples(
1137 decoder_frame_length_, last_output_sample_rate_hz_, true);
1138 status.packet_buffer_info.span_samples_no_dtx =
1139 packet_buffer_->GetSpanSamples(decoder_frame_length_,
1140 last_output_sample_rate_hz_, false);
1141 status.packet_buffer_info.num_packets = packet_buffer_->NumPacketsInBuffer();
1142 status.target_timestamp = sync_buffer_->end_timestamp();
1143 status.expand_mutefactor = expand_->MuteFactor(0);
1144 status.last_packet_samples = decoder_frame_length_;
1145 status.last_mode = last_mode_;
1146 status.play_dtmf = *play_dtmf;
1147 status.generated_noise_samples = generated_noise_samples;
Ivo Creusen88636c62020-01-24 11:04:56 +01001148 status.sync_buffer_samples = sync_buffer_->FutureLength();
Ivo Creusen53a31f72019-10-24 15:20:39 +02001149 if (packet) {
1150 status.next_packet = {
1151 packet->timestamp, packet->frame && packet->frame->IsDtxPacket(),
1152 decoder_database_->IsComfortNoise(packet->payload_type)};
1153 }
1154 *operation = controller_->GetDecision(status, &reset_decoder_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001155
Minyue Li54c66402019-04-15 14:29:27 +02001156 // Disallow time stretching if this packet is DTX, because such a decision may
1157 // be based on earlier buffer level estimate, as we do not update buffer level
1158 // during DTX. When we have a better way to update buffer level during DTX,
1159 // this can be discarded.
1160 if (packet && packet->frame && packet->frame->IsDtxPacket() &&
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001161 (*operation == Operation::kMerge ||
1162 *operation == Operation::kAccelerate ||
1163 *operation == Operation::kFastAccelerate ||
1164 *operation == Operation::kPreemptiveExpand)) {
1165 *operation = Operation::kNormal;
Minyue Li54c66402019-04-15 14:29:27 +02001166 }
1167
Ivo Creusen55de08e2018-09-03 11:49:27 +02001168 if (action_override) {
1169 // Use the provided action instead of the decision NetEq decided on.
1170 *operation = *action_override;
1171 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001172 // Check if we already have enough samples in the |sync_buffer_|. If so,
1173 // change decision to normal, unless the decision was merge, accelerate, or
1174 // preemptive expand.
kwibergd3edd772017-03-01 18:52:48 -08001175 if (samples_left >= rtc::dchecked_cast<int>(output_size_samples_) &&
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001176 *operation != Operation::kMerge && *operation != Operation::kAccelerate &&
1177 *operation != Operation::kFastAccelerate &&
1178 *operation != Operation::kPreemptiveExpand) {
1179 *operation = Operation::kNormal;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001180 return 0;
1181 }
1182
Ivo Creusen53a31f72019-10-24 15:20:39 +02001183 controller_->ExpandDecision(*operation);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001184
1185 // Check conditions for reset.
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001186 if (new_codec_ || *operation == Operation::kUndefined) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001187 // The only valid reason to get kUndefined is that new_codec_ is set.
1188 assert(new_codec_);
ossu7a377612016-10-18 04:06:13 -07001189 if (*play_dtmf && !packet) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001190 timestamp_ = dtmf_event->timestamp;
1191 } else {
ossu7a377612016-10-18 04:06:13 -07001192 if (!packet) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001193 RTC_LOG(LS_ERROR) << "Packet missing where it shouldn't.";
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001194 return -1;
1195 }
ossu7a377612016-10-18 04:06:13 -07001196 timestamp_ = packet->timestamp;
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001197 if (*operation == Operation::kRfc3389CngNoPacket &&
ossu7a377612016-10-18 04:06:13 -07001198 decoder_database_->IsComfortNoise(packet->payload_type)) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001199 // Change decision to CNG packet, since we do have a CNG packet, but it
1200 // was considered too early to use. Now, use it anyway.
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001201 *operation = Operation::kRfc3389Cng;
1202 } else if (*operation != Operation::kRfc3389Cng) {
1203 *operation = Operation::kNormal;
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001204 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001205 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001206 // Adjust |sync_buffer_| timestamp before setting |end_timestamp| to the
1207 // new value.
1208 sync_buffer_->IncreaseEndTimestamp(timestamp_ - end_timestamp);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001209 end_timestamp = timestamp_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001210 new_codec_ = false;
Ivo Creusen53a31f72019-10-24 15:20:39 +02001211 controller_->SoftReset();
Jakob Ivarsson44507082019-03-05 16:59:03 +01001212 stats_->ResetMcu();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001213 }
1214
Peter Kastingdce40cf2015-08-24 14:52:23 -07001215 size_t required_samples = output_size_samples_;
1216 const size_t samples_10_ms = static_cast<size_t>(80 * fs_mult_);
1217 const size_t samples_20_ms = 2 * samples_10_ms;
1218 const size_t samples_30_ms = 3 * samples_10_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001219
1220 switch (*operation) {
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001221 case Operation::kExpand: {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001222 timestamp_ = end_timestamp;
1223 return 0;
1224 }
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001225 case Operation::kRfc3389CngNoPacket:
1226 case Operation::kCodecInternalCng: {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001227 return 0;
1228 }
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001229 case Operation::kDtmf: {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001230 // TODO(hlundin): Write test for this.
1231 // Update timestamp.
1232 timestamp_ = end_timestamp;
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001233 const uint64_t generated_noise_samples =
1234 generated_noise_stopwatch_
1235 ? generated_noise_stopwatch_->ElapsedTicks() *
1236 output_size_samples_ +
Ivo Creusen53a31f72019-10-24 15:20:39 +02001237 controller_->noise_fast_forward()
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001238 : 0;
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001239 if (generated_noise_samples > 0 && last_mode_ != Mode::kDtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001240 // Make a jump in timestamp due to the recently played comfort noise.
Peter Kastingb7e50542015-06-11 12:55:50 -07001241 uint32_t timestamp_jump =
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001242 static_cast<uint32_t>(generated_noise_samples);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001243 sync_buffer_->IncreaseEndTimestamp(timestamp_jump);
1244 timestamp_ += timestamp_jump;
1245 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001246 return 0;
1247 }
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001248 case Operation::kAccelerate:
1249 case Operation::kFastAccelerate: {
Henrik Lundincf808d22015-05-27 14:33:29 +02001250 // In order to do an accelerate we need at least 30 ms of audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001251 if (samples_left >= static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001252 // Already have enough data, so we do not need to extract any more.
Ivo Creusen53a31f72019-10-24 15:20:39 +02001253 controller_->set_sample_memory(samples_left);
1254 controller_->set_prev_time_scale(true);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001255 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001256 } else if (samples_left >= static_cast<int>(samples_10_ms) &&
Yves Gerey665174f2018-06-19 15:03:05 +02001257 decoder_frame_length_ >= samples_30_ms) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001258 // Avoid decoding more data as it might overflow the playout buffer.
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001259 *operation = Operation::kNormal;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001260 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001261 } else if (samples_left < static_cast<int>(samples_20_ms) &&
Yves Gerey665174f2018-06-19 15:03:05 +02001262 decoder_frame_length_ < samples_30_ms) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001263 // Build up decoded data by decoding at least 20 ms of audio data. Do
1264 // not perform accelerate yet, but wait until we only need to do one
1265 // decoding.
1266 required_samples = 2 * output_size_samples_;
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001267 *operation = Operation::kNormal;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001268 }
1269 // If none of the above is true, we have one of two possible situations:
1270 // (1) 20 ms <= samples_left < 30 ms and decoder_frame_length_ < 30 ms; or
1271 // (2) samples_left < 10 ms and decoder_frame_length_ >= 30 ms.
1272 // In either case, we move on with the accelerate decision, and decode one
1273 // frame now.
1274 break;
1275 }
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001276 case Operation::kPreemptiveExpand: {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001277 // In order to do a preemptive expand we need at least 30 ms of decoded
1278 // audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001279 if ((samples_left >= static_cast<int>(samples_30_ms)) ||
1280 (samples_left >= static_cast<int>(samples_10_ms) &&
Yves Gerey665174f2018-06-19 15:03:05 +02001281 decoder_frame_length_ >= samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001282 // Already have enough data, so we do not need to extract any more.
1283 // Or, avoid decoding more data as it might overflow the playout buffer.
1284 // Still try preemptive expand, though.
Ivo Creusen53a31f72019-10-24 15:20:39 +02001285 controller_->set_sample_memory(samples_left);
1286 controller_->set_prev_time_scale(true);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001287 return 0;
1288 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07001289 if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001290 decoder_frame_length_ < samples_30_ms) {
1291 // Build up decoded data by decoding at least 20 ms of audio data.
1292 // Still try to perform preemptive expand.
1293 required_samples = 2 * output_size_samples_;
1294 }
1295 // Move on with the preemptive expand decision.
1296 break;
1297 }
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001298 case Operation::kMerge: {
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001299 required_samples =
1300 std::max(merge_->RequiredFutureSamples(), required_samples);
1301 break;
1302 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001303 default: {
1304 // Do nothing.
1305 }
1306 }
1307
1308 // Get packets from buffer.
1309 int extracted_samples = 0;
Henrik Lundin7687ad52018-07-02 10:14:46 +02001310 if (packet) {
ossu7a377612016-10-18 04:06:13 -07001311 sync_buffer_->IncreaseEndTimestamp(packet->timestamp - end_timestamp);
Ivo Creusen53a31f72019-10-24 15:20:39 +02001312 if (controller_->CngOff()) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001313 // Adjustment of timestamp only corresponds to an actual packet loss
1314 // if comfort noise is not played. If comfort noise was just played,
1315 // this adjustment of timestamp is only done to get back in sync with the
1316 // stream timestamp; no loss to report.
Jakob Ivarsson44507082019-03-05 16:59:03 +01001317 stats_->LostSamples(packet->timestamp - end_timestamp);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001318 }
1319
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001320 if (*operation != Operation::kRfc3389Cng) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001321 // We are about to decode and use a non-CNG packet.
Ivo Creusen53a31f72019-10-24 15:20:39 +02001322 controller_->SetCngOff();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001323 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001324
1325 extracted_samples = ExtractPackets(required_samples, packet_list);
1326 if (extracted_samples < 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001327 return kPacketBufferCorruption;
1328 }
1329 }
1330
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001331 if (*operation == Operation::kAccelerate ||
1332 *operation == Operation::kFastAccelerate ||
1333 *operation == Operation::kPreemptiveExpand) {
Ivo Creusen53a31f72019-10-24 15:20:39 +02001334 controller_->set_sample_memory(samples_left + extracted_samples);
1335 controller_->set_prev_time_scale(true);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001336 }
1337
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001338 if (*operation == Operation::kAccelerate ||
1339 *operation == Operation::kFastAccelerate) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001340 // Check that we have enough data (30ms) to do accelerate.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001341 if (extracted_samples + samples_left < static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001342 // TODO(hlundin): Write test for this.
1343 // Not enough, do normal operation instead.
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001344 *operation = Operation::kNormal;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001345 }
1346 }
1347
1348 timestamp_ = end_timestamp;
1349 return 0;
1350}
1351
Yves Gerey665174f2018-06-19 15:03:05 +02001352int NetEqImpl::Decode(PacketList* packet_list,
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001353 Operation* operation,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001354 int* decoded_length,
1355 AudioDecoder::SpeechType* speech_type) {
1356 *speech_type = AudioDecoder::kSpeech;
minyuel6d92bf52015-09-23 15:20:39 +02001357
1358 // When packet_list is empty, we may be in kCodecInternalCng mode, and for
1359 // that we use current active decoder.
1360 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1361
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001362 if (!packet_list->empty()) {
ossua73f6c92016-10-24 08:25:28 -07001363 const Packet& packet = packet_list->front();
1364 uint8_t payload_type = packet.payload_type;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001365 if (!decoder_database_->IsComfortNoise(payload_type)) {
1366 decoder = decoder_database_->GetDecoder(payload_type);
1367 assert(decoder);
1368 if (!decoder) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001369 RTC_LOG(LS_WARNING)
1370 << "Unknown payload type " << static_cast<int>(payload_type);
ossua73f6c92016-10-24 08:25:28 -07001371 packet_list->clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001372 return kDecoderNotFound;
1373 }
1374 bool decoder_changed;
1375 decoder_database_->SetActiveDecoder(payload_type, &decoder_changed);
1376 if (decoder_changed) {
1377 // We have a new decoder. Re-init some values.
Yves Gerey665174f2018-06-19 15:03:05 +02001378 const DecoderDatabase::DecoderInfo* decoder_info =
1379 decoder_database_->GetDecoderInfo(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001380 assert(decoder_info);
1381 if (!decoder_info) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001382 RTC_LOG(LS_WARNING)
1383 << "Unknown payload type " << static_cast<int>(payload_type);
ossua73f6c92016-10-24 08:25:28 -07001384 packet_list->clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001385 return kDecoderNotFound;
1386 }
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001387 // If sampling rate or number of channels has changed, we need to make
1388 // a reset.
kwibergc0f2dcf2016-05-31 06:28:03 -07001389 if (decoder_info->SampleRateHz() != fs_hz_ ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001390 decoder->Channels() != algorithm_buffer_->Channels()) {
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001391 // TODO(tlegrand): Add unittest to cover this event.
kwibergc0f2dcf2016-05-31 06:28:03 -07001392 SetSampleRateAndChannels(decoder_info->SampleRateHz(),
1393 decoder->Channels());
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001394 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001395 sync_buffer_->set_end_timestamp(timestamp_);
1396 playout_timestamp_ = timestamp_;
1397 }
1398 }
1399 }
1400
1401 if (reset_decoder_) {
1402 // TODO(hlundin): Write test for this.
Karl Wiberg43766482015-08-27 15:22:11 +02001403 if (decoder)
1404 decoder->Reset();
1405
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001406 // Reset comfort noise decoder.
ossu97ba30e2016-04-25 07:55:58 -07001407 ComfortNoiseDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02001408 if (cng_decoder)
1409 cng_decoder->Reset();
1410
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001411 reset_decoder_ = false;
1412 }
1413
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001414 *decoded_length = 0;
1415 // Update codec-internal PLC state.
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001416 if ((*operation == Operation::kMerge) && decoder && decoder->HasDecodePlc()) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001417 decoder->DecodePlc(1, &decoded_buffer_[*decoded_length]);
1418 }
1419
minyuel6d92bf52015-09-23 15:20:39 +02001420 int return_value;
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001421 if (*operation == Operation::kCodecInternalCng) {
minyuel6d92bf52015-09-23 15:20:39 +02001422 RTC_DCHECK(packet_list->empty());
1423 return_value = DecodeCng(decoder, decoded_length, speech_type);
1424 } else {
Yves Gerey665174f2018-06-19 15:03:05 +02001425 return_value = DecodeLoop(packet_list, *operation, decoder, decoded_length,
1426 speech_type);
minyuel6d92bf52015-09-23 15:20:39 +02001427 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001428
1429 if (*decoded_length < 0) {
1430 // Error returned from the decoder.
1431 *decoded_length = 0;
Peter Kastingb7e50542015-06-11 12:55:50 -07001432 sync_buffer_->IncreaseEndTimestamp(
1433 static_cast<uint32_t>(decoder_frame_length_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001434 int error_code = 0;
1435 if (decoder)
1436 error_code = decoder->ErrorCode();
1437 if (error_code != 0) {
1438 // Got some error code from the decoder.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001439 return_value = kDecoderErrorCode;
Mirko Bonadei675513b2017-11-09 11:09:25 +01001440 RTC_LOG(LS_WARNING) << "Decoder returned error code: " << error_code;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001441 } else {
1442 // Decoder does not implement error codes. Return generic error.
1443 return_value = kOtherDecoderError;
Mirko Bonadei675513b2017-11-09 11:09:25 +01001444 RTC_LOG(LS_WARNING) << "Decoder error (no error code)";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001445 }
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001446 *operation = Operation::kExpand; // Do expansion to get data instead.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001447 }
1448 if (*speech_type != AudioDecoder::kComfortNoise) {
1449 // Don't increment timestamp if codec returned CNG speech type
1450 // since in this case, the we will increment the CNGplayedTS counter.
1451 // Increase with number of samples per channel.
1452 assert(*decoded_length == 0 ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001453 (decoder && decoder->Channels() == sync_buffer_->Channels()));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001454 sync_buffer_->IncreaseEndTimestamp(
1455 *decoded_length / static_cast<int>(sync_buffer_->Channels()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001456 }
1457 return return_value;
1458}
1459
Yves Gerey665174f2018-06-19 15:03:05 +02001460int NetEqImpl::DecodeCng(AudioDecoder* decoder,
1461 int* decoded_length,
minyuel6d92bf52015-09-23 15:20:39 +02001462 AudioDecoder::SpeechType* speech_type) {
1463 if (!decoder) {
1464 // This happens when active decoder is not defined.
1465 *decoded_length = -1;
1466 return 0;
1467 }
1468
kwibergd3edd772017-03-01 18:52:48 -08001469 while (*decoded_length < rtc::dchecked_cast<int>(output_size_samples_)) {
minyuel6d92bf52015-09-23 15:20:39 +02001470 const int length = decoder->Decode(
Yves Gerey665174f2018-06-19 15:03:05 +02001471 nullptr, 0, fs_hz_,
1472 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1473 &decoded_buffer_[*decoded_length], speech_type);
minyuel6d92bf52015-09-23 15:20:39 +02001474 if (length > 0) {
1475 *decoded_length += length;
minyuel6d92bf52015-09-23 15:20:39 +02001476 } else {
1477 // Error.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001478 RTC_LOG(LS_WARNING) << "Failed to decode CNG";
minyuel6d92bf52015-09-23 15:20:39 +02001479 *decoded_length = -1;
1480 break;
1481 }
1482 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1483 // Guard against overflow.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001484 RTC_LOG(LS_WARNING) << "Decoded too much CNG.";
minyuel6d92bf52015-09-23 15:20:39 +02001485 return kDecodedTooMuch;
1486 }
1487 }
1488 return 0;
1489}
1490
Yves Gerey665174f2018-06-19 15:03:05 +02001491int NetEqImpl::DecodeLoop(PacketList* packet_list,
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001492 const Operation& operation,
Yves Gerey665174f2018-06-19 15:03:05 +02001493 AudioDecoder* decoder,
1494 int* decoded_length,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001495 AudioDecoder::SpeechType* speech_type) {
henrik.lundin114c1b32017-04-26 07:47:32 -07001496 RTC_DCHECK(last_decoded_timestamps_.empty());
Alessio Bazzica8f319a32019-07-24 16:47:02 +00001497 RTC_DCHECK(last_decoded_packet_infos_.empty());
henrik.lundin114c1b32017-04-26 07:47:32 -07001498
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001499 // Do decoding.
Yves Gerey665174f2018-06-19 15:03:05 +02001500 while (!packet_list->empty() && !decoder_database_->IsComfortNoise(
1501 packet_list->front().payload_type)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001502 assert(decoder); // At this point, we must have a decoder object.
1503 // The number of channels in the |sync_buffer_| should be the same as the
1504 // number decoder channels.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001505 assert(sync_buffer_->Channels() == decoder->Channels());
1506 assert(decoded_buffer_length_ >= kMaxFrameSize * decoder->Channels());
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001507 assert(operation == Operation::kNormal ||
1508 operation == Operation::kAccelerate ||
1509 operation == Operation::kFastAccelerate ||
1510 operation == Operation::kMerge ||
1511 operation == Operation::kPreemptiveExpand);
ossua73f6c92016-10-24 08:25:28 -07001512
1513 auto opt_result = packet_list->front().frame->Decode(
ossu61a208b2016-09-20 01:38:00 -07001514 rtc::ArrayView<int16_t>(&decoded_buffer_[*decoded_length],
1515 decoded_buffer_length_ - *decoded_length));
henrik.lundin114c1b32017-04-26 07:47:32 -07001516 last_decoded_timestamps_.push_back(packet_list->front().timestamp);
Alessio Bazzica8f319a32019-07-24 16:47:02 +00001517 last_decoded_packet_infos_.push_back(
1518 std::move(packet_list->front().packet_info));
ossua73f6c92016-10-24 08:25:28 -07001519 packet_list->pop_front();
ossu61a208b2016-09-20 01:38:00 -07001520 if (opt_result) {
1521 const auto& result = *opt_result;
1522 *speech_type = result.speech_type;
1523 if (result.num_decoded_samples > 0) {
kwibergd3edd772017-03-01 18:52:48 -08001524 *decoded_length += rtc::dchecked_cast<int>(result.num_decoded_samples);
ossu61a208b2016-09-20 01:38:00 -07001525 // Update |decoder_frame_length_| with number of samples per channel.
1526 decoder_frame_length_ =
1527 result.num_decoded_samples / decoder->Channels();
1528 }
1529 } else {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001530 // Error.
ossu61a208b2016-09-20 01:38:00 -07001531 // TODO(ossu): What to put here?
Mirko Bonadei675513b2017-11-09 11:09:25 +01001532 RTC_LOG(LS_WARNING) << "Decode error";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001533 *decoded_length = -1;
Alessio Bazzica8f319a32019-07-24 16:47:02 +00001534 last_decoded_packet_infos_.clear();
ossua73f6c92016-10-24 08:25:28 -07001535 packet_list->clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001536 break;
1537 }
kwibergd3edd772017-03-01 18:52:48 -08001538 if (*decoded_length > rtc::dchecked_cast<int>(decoded_buffer_length_)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001539 // Guard against overflow.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001540 RTC_LOG(LS_WARNING) << "Decoded too much.";
ossua73f6c92016-10-24 08:25:28 -07001541 packet_list->clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001542 return kDecodedTooMuch;
1543 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001544 } // End of decode loop.
1545
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001546 // If the list is not empty at this point, either a decoding error terminated
1547 // the while-loop, or list must hold exactly one CNG packet.
Yves Gerey665174f2018-06-19 15:03:05 +02001548 assert(packet_list->empty() || *decoded_length < 0 ||
1549 (packet_list->size() == 1 && decoder_database_->IsComfortNoise(
1550 packet_list->front().payload_type)));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001551 return 0;
1552}
1553
Yves Gerey665174f2018-06-19 15:03:05 +02001554void NetEqImpl::DoNormal(const int16_t* decoded_buffer,
1555 size_t decoded_length,
1556 AudioDecoder::SpeechType speech_type,
1557 bool play_dtmf) {
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001558 assert(normal_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001559 normal_->Process(decoded_buffer, decoded_length, last_mode_,
Henrik Lundin6dc82e82018-05-22 10:40:23 +02001560 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001561 if (decoded_length != 0) {
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001562 last_mode_ = Mode::kNormal;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001563 }
1564
1565 // If last packet was decoded as an inband CNG, set mode to CNG instead.
Yves Gerey665174f2018-06-19 15:03:05 +02001566 if ((speech_type == AudioDecoder::kComfortNoise) ||
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001567 ((last_mode_ == Mode::kCodecInternalCng) && (decoded_length == 0))) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001568 // TODO(hlundin): Remove second part of || statement above.
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001569 last_mode_ = Mode::kCodecInternalCng;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001570 }
1571
1572 if (!play_dtmf) {
1573 dtmf_tone_generator_->Reset();
1574 }
1575}
1576
Yves Gerey665174f2018-06-19 15:03:05 +02001577void NetEqImpl::DoMerge(int16_t* decoded_buffer,
1578 size_t decoded_length,
1579 AudioDecoder::SpeechType speech_type,
1580 bool play_dtmf) {
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001581 assert(merge_.get());
Yves Gerey665174f2018-06-19 15:03:05 +02001582 size_t new_length =
1583 merge_->Process(decoded_buffer, decoded_length, algorithm_buffer_.get());
henrik.lundin2979f552017-05-05 05:04:16 -07001584 // Correction can be negative.
1585 int expand_length_correction =
1586 rtc::dchecked_cast<int>(new_length) -
1587 rtc::dchecked_cast<int>(decoded_length / algorithm_buffer_->Channels());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001588
1589 // Update in-call and post-call statistics.
1590 if (expand_->MuteFactor(0) == 0) {
1591 // Expand generates only noise.
Jakob Ivarsson44507082019-03-05 16:59:03 +01001592 stats_->ExpandedNoiseSamplesCorrection(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001593 } else {
1594 // Expansion generates more than only noise.
Jakob Ivarsson44507082019-03-05 16:59:03 +01001595 stats_->ExpandedVoiceSamplesCorrection(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001596 }
1597
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001598 last_mode_ = Mode::kMerge;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001599 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1600 if (speech_type == AudioDecoder::kComfortNoise) {
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001601 last_mode_ = Mode::kCodecInternalCng;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001602 }
1603 expand_->Reset();
1604 if (!play_dtmf) {
1605 dtmf_tone_generator_->Reset();
1606 }
1607}
1608
Henrik Lundin00eb12a2018-09-05 18:14:52 +02001609bool NetEqImpl::DoCodecPlc() {
1610 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1611 if (!decoder) {
1612 return false;
1613 }
1614 const size_t channels = algorithm_buffer_->Channels();
1615 const size_t requested_samples_per_channel =
1616 output_size_samples_ -
1617 (sync_buffer_->FutureLength() - expand_->overlap_length());
1618 concealment_audio_.Clear();
1619 decoder->GeneratePlc(requested_samples_per_channel, &concealment_audio_);
1620 if (concealment_audio_.empty()) {
1621 // Nothing produced. Resort to regular expand.
1622 return false;
1623 }
1624 RTC_CHECK_GE(concealment_audio_.size(),
1625 requested_samples_per_channel * channels);
1626 sync_buffer_->PushBackInterleaved(concealment_audio_);
1627 RTC_DCHECK_NE(algorithm_buffer_->Channels(), 0);
1628 const size_t concealed_samples_per_channel =
1629 concealment_audio_.size() / channels;
1630
1631 // Update in-call and post-call statistics.
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001632 const bool is_new_concealment_event = (last_mode_ != Mode::kCodecPlc);
Henrik Lundin00eb12a2018-09-05 18:14:52 +02001633 if (std::all_of(concealment_audio_.cbegin(), concealment_audio_.cend(),
1634 [](int16_t i) { return i == 0; })) {
1635 // Expand operation generates only noise.
Jakob Ivarsson44507082019-03-05 16:59:03 +01001636 stats_->ExpandedNoiseSamples(concealed_samples_per_channel,
1637 is_new_concealment_event);
Henrik Lundin00eb12a2018-09-05 18:14:52 +02001638 } else {
1639 // Expand operation generates more than only noise.
Jakob Ivarsson44507082019-03-05 16:59:03 +01001640 stats_->ExpandedVoiceSamples(concealed_samples_per_channel,
1641 is_new_concealment_event);
Henrik Lundin00eb12a2018-09-05 18:14:52 +02001642 }
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001643 last_mode_ = Mode::kCodecPlc;
Henrik Lundin00eb12a2018-09-05 18:14:52 +02001644 if (!generated_noise_stopwatch_) {
1645 // Start a new stopwatch since we may be covering for a lost CNG packet.
1646 generated_noise_stopwatch_ = tick_timer_->GetNewStopwatch();
1647 }
1648 return true;
1649}
1650
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001651int NetEqImpl::DoExpand(bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001652 while ((sync_buffer_->FutureLength() - expand_->overlap_length()) <
Yves Gerey665174f2018-06-19 15:03:05 +02001653 output_size_samples_) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001654 algorithm_buffer_->Clear();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001655 int return_value = expand_->Process(algorithm_buffer_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001656 size_t length = algorithm_buffer_->Size();
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001657 bool is_new_concealment_event = (last_mode_ != Mode::kExpand);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001658
1659 // Update in-call and post-call statistics.
1660 if (expand_->MuteFactor(0) == 0) {
1661 // Expand operation generates only noise.
Jakob Ivarsson44507082019-03-05 16:59:03 +01001662 stats_->ExpandedNoiseSamples(length, is_new_concealment_event);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001663 } else {
1664 // Expand operation generates more than only noise.
Jakob Ivarsson44507082019-03-05 16:59:03 +01001665 stats_->ExpandedVoiceSamples(length, is_new_concealment_event);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001666 }
1667
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001668 last_mode_ = Mode::kExpand;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001669
1670 if (return_value < 0) {
1671 return return_value;
1672 }
1673
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001674 sync_buffer_->PushBack(*algorithm_buffer_);
1675 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001676 }
1677 if (!play_dtmf) {
1678 dtmf_tone_generator_->Reset();
1679 }
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001680
1681 if (!generated_noise_stopwatch_) {
1682 // Start a new stopwatch since we may be covering for a lost CNG packet.
1683 generated_noise_stopwatch_ = tick_timer_->GetNewStopwatch();
1684 }
1685
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001686 return 0;
1687}
1688
Henrik Lundincf808d22015-05-27 14:33:29 +02001689int NetEqImpl::DoAccelerate(int16_t* decoded_buffer,
1690 size_t decoded_length,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001691 AudioDecoder::SpeechType speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +02001692 bool play_dtmf,
1693 bool fast_accelerate) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001694 const size_t required_samples =
1695 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001696 size_t borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001697 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001698 size_t decoded_length_per_channel = decoded_length / num_channels;
1699 if (decoded_length_per_channel < required_samples) {
1700 // Must move data from the |sync_buffer_| in order to get 30 ms.
Yves Gerey665174f2018-06-19 15:03:05 +02001701 borrowed_samples_per_channel =
1702 static_cast<int>(required_samples - decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001703 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
Yves Gerey665174f2018-06-19 15:03:05 +02001704 decoded_buffer, sizeof(int16_t) * decoded_length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001705 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1706 decoded_buffer);
1707 decoded_length = required_samples * num_channels;
1708 }
1709
Peter Kastingdce40cf2015-08-24 14:52:23 -07001710 size_t samples_removed;
Henrik Lundincf808d22015-05-27 14:33:29 +02001711 Accelerate::ReturnCodes return_code =
1712 accelerate_->Process(decoded_buffer, decoded_length, fast_accelerate,
1713 algorithm_buffer_.get(), &samples_removed);
Jakob Ivarsson44507082019-03-05 16:59:03 +01001714 stats_->AcceleratedSamples(samples_removed);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001715 switch (return_code) {
1716 case Accelerate::kSuccess:
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001717 last_mode_ = Mode::kAccelerateSuccess;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001718 break;
1719 case Accelerate::kSuccessLowEnergy:
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001720 last_mode_ = Mode::kAccelerateLowEnergy;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001721 break;
1722 case Accelerate::kNoStretch:
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001723 last_mode_ = Mode::kAccelerateFail;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001724 break;
1725 case Accelerate::kError:
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001726 // TODO(hlundin): Map to Modes::kError instead?
1727 last_mode_ = Mode::kAccelerateFail;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001728 return kAccelerateError;
1729 }
1730
1731 if (borrowed_samples_per_channel > 0) {
1732 // Copy borrowed samples back to the |sync_buffer_|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001733 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001734 if (length < borrowed_samples_per_channel) {
1735 // This destroys the beginning of the buffer, but will not cause any
1736 // problems.
Yves Gerey665174f2018-06-19 15:03:05 +02001737 sync_buffer_->ReplaceAtIndex(
1738 *algorithm_buffer_,
1739 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001740 sync_buffer_->PushFrontZeros(borrowed_samples_per_channel - length);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001741 algorithm_buffer_->PopFront(length);
1742 assert(algorithm_buffer_->Empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001743 } else {
Yves Gerey665174f2018-06-19 15:03:05 +02001744 sync_buffer_->ReplaceAtIndex(
1745 *algorithm_buffer_, borrowed_samples_per_channel,
1746 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001747 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001748 }
1749 }
1750
1751 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1752 if (speech_type == AudioDecoder::kComfortNoise) {
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001753 last_mode_ = Mode::kCodecInternalCng;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001754 }
1755 if (!play_dtmf) {
1756 dtmf_tone_generator_->Reset();
1757 }
1758 expand_->Reset();
1759 return 0;
1760}
1761
1762int NetEqImpl::DoPreemptiveExpand(int16_t* decoded_buffer,
1763 size_t decoded_length,
1764 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001765 bool play_dtmf) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001766 const size_t required_samples =
1767 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001768 size_t num_channels = algorithm_buffer_->Channels();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001769 size_t borrowed_samples_per_channel = 0;
1770 size_t old_borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001771 size_t decoded_length_per_channel = decoded_length / num_channels;
1772 if (decoded_length_per_channel < required_samples) {
1773 // Must move data from the |sync_buffer_| in order to get 30 ms.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001774 borrowed_samples_per_channel =
1775 required_samples - decoded_length_per_channel;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001776 // Calculate how many of these were already played out.
Peter Kastingf045e4d2015-06-10 21:15:38 -07001777 old_borrowed_samples_per_channel =
Yves Gerey665174f2018-06-19 15:03:05 +02001778 (borrowed_samples_per_channel > sync_buffer_->FutureLength())
1779 ? (borrowed_samples_per_channel - sync_buffer_->FutureLength())
1780 : 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001781 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
Yves Gerey665174f2018-06-19 15:03:05 +02001782 decoded_buffer, sizeof(int16_t) * decoded_length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001783 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1784 decoded_buffer);
1785 decoded_length = required_samples * num_channels;
1786 }
1787
Peter Kastingdce40cf2015-08-24 14:52:23 -07001788 size_t samples_added;
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001789 PreemptiveExpand::ReturnCodes return_code = preemptive_expand_->Process(
Yves Gerey665174f2018-06-19 15:03:05 +02001790 decoded_buffer, decoded_length, old_borrowed_samples_per_channel,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001791 algorithm_buffer_.get(), &samples_added);
Jakob Ivarsson44507082019-03-05 16:59:03 +01001792 stats_->PreemptiveExpandedSamples(samples_added);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001793 switch (return_code) {
1794 case PreemptiveExpand::kSuccess:
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001795 last_mode_ = Mode::kPreemptiveExpandSuccess;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001796 break;
1797 case PreemptiveExpand::kSuccessLowEnergy:
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001798 last_mode_ = Mode::kPreemptiveExpandLowEnergy;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001799 break;
1800 case PreemptiveExpand::kNoStretch:
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001801 last_mode_ = Mode::kPreemptiveExpandFail;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001802 break;
1803 case PreemptiveExpand::kError:
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001804 // TODO(hlundin): Map to Modes::kError instead?
1805 last_mode_ = Mode::kPreemptiveExpandFail;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001806 return kPreemptiveExpandError;
1807 }
1808
1809 if (borrowed_samples_per_channel > 0) {
1810 // Copy borrowed samples back to the |sync_buffer_|.
1811 sync_buffer_->ReplaceAtIndex(
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001812 *algorithm_buffer_, borrowed_samples_per_channel,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001813 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001814 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001815 }
1816
1817 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1818 if (speech_type == AudioDecoder::kComfortNoise) {
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001819 last_mode_ = Mode::kCodecInternalCng;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001820 }
1821 if (!play_dtmf) {
1822 dtmf_tone_generator_->Reset();
1823 }
1824 expand_->Reset();
1825 return 0;
1826}
1827
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001828int NetEqImpl::DoRfc3389Cng(PacketList* packet_list, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001829 if (!packet_list->empty()) {
1830 // Must have exactly one SID frame at this point.
1831 assert(packet_list->size() == 1);
ossua73f6c92016-10-24 08:25:28 -07001832 const Packet& packet = packet_list->front();
1833 if (!decoder_database_->IsComfortNoise(packet.payload_type)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001834 RTC_LOG(LS_ERROR) << "Trying to decode non-CNG payload as CNG.";
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001835 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001836 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001837 if (comfort_noise_->UpdateParameters(packet) ==
1838 ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001839 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001840 return -comfort_noise_->internal_error_code();
1841 }
1842 }
Yves Gerey665174f2018-06-19 15:03:05 +02001843 int cn_return =
1844 comfort_noise_->Generate(output_size_samples_, algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001845 expand_->Reset();
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001846 last_mode_ = Mode::kRfc3389Cng;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001847 if (!play_dtmf) {
1848 dtmf_tone_generator_->Reset();
1849 }
1850 if (cn_return == ComfortNoise::kInternalError) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001851 RTC_LOG(LS_WARNING) << "Comfort noise generator returned error code: "
1852 << comfort_noise_->internal_error_code();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001853 return kComfortNoiseErrorCode;
1854 } else if (cn_return == ComfortNoise::kUnknownPayloadType) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001855 return kUnknownRtpPayloadType;
1856 }
1857 return 0;
1858}
1859
minyuel6d92bf52015-09-23 15:20:39 +02001860void NetEqImpl::DoCodecInternalCng(const int16_t* decoded_buffer,
1861 size_t decoded_length) {
1862 RTC_DCHECK(normal_.get());
minyuel6d92bf52015-09-23 15:20:39 +02001863 normal_->Process(decoded_buffer, decoded_length, last_mode_,
Henrik Lundin6dc82e82018-05-22 10:40:23 +02001864 algorithm_buffer_.get());
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001865 last_mode_ = Mode::kCodecInternalCng;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001866 expand_->Reset();
1867}
1868
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001869int NetEqImpl::DoDtmf(const DtmfEvent& dtmf_event, bool* play_dtmf) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001870 // This block of the code and the block further down, handling |dtmf_switch|
1871 // are commented out. Otherwise playing out-of-band DTMF would fail in VoE
1872 // test, DtmfTest.ManualSuccessfullySendsOutOfBandTelephoneEvents. This is
1873 // equivalent to |dtmf_switch| always be false.
1874 //
1875 // See http://webrtc-codereview.appspot.com/1195004/ for discussion
1876 // On this issue. This change might cause some glitches at the point of
1877 // switch from audio to DTMF. Issue 1545 is filed to track this.
1878 //
1879 // bool dtmf_switch = false;
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001880 // if ((last_mode_ != Modes::kDtmf) &&
1881 // dtmf_tone_generator_->initialized()) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001882 // // Special case; see below.
1883 // // We must catch this before calling Generate, since |initialized| is
1884 // // modified in that call.
1885 // dtmf_switch = true;
1886 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001887
1888 int dtmf_return_value = 0;
1889 if (!dtmf_tone_generator_->initialized()) {
1890 // Initialize if not already done.
1891 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1892 dtmf_event.volume);
1893 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001894
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001895 if (dtmf_return_value == 0) {
1896 // Generate DTMF signal.
1897 dtmf_return_value = dtmf_tone_generator_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001898 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001899 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001900
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001901 if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001902 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001903 return dtmf_return_value;
1904 }
1905
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001906 // if (dtmf_switch) {
1907 // // This is the special case where the previous operation was DTMF
1908 // // overdub, but the current instruction is "regular" DTMF. We must make
1909 // // sure that the DTMF does not have any discontinuities. The first DTMF
1910 // // sample that we generate now must be played out immediately, therefore
1911 // // it must be copied to the speech buffer.
1912 // // TODO(hlundin): This code seems incorrect. (Legacy.) Write test and
1913 // // verify correct operation.
1914 // assert(false);
1915 // // Must generate enough data to replace all of the |sync_buffer_|
1916 // // "future".
1917 // int required_length = sync_buffer_->FutureLength();
1918 // assert(dtmf_tone_generator_->initialized());
1919 // dtmf_return_value = dtmf_tone_generator_->Generate(required_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001920 // algorithm_buffer_);
1921 // assert((size_t) required_length == algorithm_buffer_->Size());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001922 // if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001923 // algorithm_buffer_->Zeros(output_size_samples_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001924 // return dtmf_return_value;
1925 // }
1926 //
1927 // // Overwrite the "future" part of the speech buffer with the new DTMF
1928 // // data.
1929 // // TODO(hlundin): It seems that this overwriting has gone lost.
1930 // // Not adapted for multi-channel yet.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001931 // assert(algorithm_buffer_->Channels() == 1);
1932 // if (algorithm_buffer_->Channels() != 1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001933 // RTC_LOG(LS_WARNING) << "DTMF not supported for more than one channel";
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001934 // return kStereoNotSupported;
1935 // }
1936 // // Shuffle the remaining data to the beginning of algorithm buffer.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001937 // algorithm_buffer_->PopFront(sync_buffer_->FutureLength());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001938 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001939
Peter Kastingb7e50542015-06-11 12:55:50 -07001940 sync_buffer_->IncreaseEndTimestamp(
1941 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001942 expand_->Reset();
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001943 last_mode_ = Mode::kDtmf;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001944
1945 // Set to false because the DTMF is already in the algorithm buffer.
1946 *play_dtmf = false;
1947 return 0;
1948}
1949
Yves Gerey665174f2018-06-19 15:03:05 +02001950int NetEqImpl::DtmfOverdub(const DtmfEvent& dtmf_event,
1951 size_t num_channels,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001952 int16_t* output) const {
1953 size_t out_index = 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001954 size_t overdub_length = output_size_samples_; // Default value.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001955
1956 if (sync_buffer_->dtmf_index() > sync_buffer_->next_index()) {
1957 // Special operation for transition from "DTMF only" to "DTMF overdub".
Yves Gerey665174f2018-06-19 15:03:05 +02001958 out_index =
1959 std::min(sync_buffer_->dtmf_index() - sync_buffer_->next_index(),
1960 output_size_samples_);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001961 overdub_length = output_size_samples_ - out_index;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001962 }
1963
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001964 AudioMultiVector dtmf_output(num_channels);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001965 int dtmf_return_value = 0;
1966 if (!dtmf_tone_generator_->initialized()) {
1967 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1968 dtmf_event.volume);
1969 }
1970 if (dtmf_return_value == 0) {
Yves Gerey665174f2018-06-19 15:03:05 +02001971 dtmf_return_value =
1972 dtmf_tone_generator_->Generate(overdub_length, &dtmf_output);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001973 assert(overdub_length == dtmf_output.Size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001974 }
1975 dtmf_output.ReadInterleaved(overdub_length, &output[out_index]);
1976 return dtmf_return_value < 0 ? dtmf_return_value : 0;
1977}
1978
Peter Kastingdce40cf2015-08-24 14:52:23 -07001979int NetEqImpl::ExtractPackets(size_t required_samples,
1980 PacketList* packet_list) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001981 bool first_packet = true;
1982 uint8_t prev_payload_type = 0;
1983 uint32_t prev_timestamp = 0;
1984 uint16_t prev_sequence_number = 0;
1985 bool next_packet_available = false;
1986
ossu7a377612016-10-18 04:06:13 -07001987 const Packet* next_packet = packet_buffer_->PeekNextPacket();
1988 RTC_DCHECK(next_packet);
1989 if (!next_packet) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001990 RTC_LOG(LS_ERROR) << "Packet buffer unexpectedly empty.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001991 return -1;
1992 }
ossu7a377612016-10-18 04:06:13 -07001993 uint32_t first_timestamp = next_packet->timestamp;
ossu61a208b2016-09-20 01:38:00 -07001994 size_t extracted_samples = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001995
1996 // Packet extraction loop.
1997 do {
ossu7a377612016-10-18 04:06:13 -07001998 timestamp_ = next_packet->timestamp;
Danil Chapovalovb6021232018-06-19 13:26:36 +02001999 absl::optional<Packet> packet = packet_buffer_->GetNextPacket();
ossu7a377612016-10-18 04:06:13 -07002000 // |next_packet| may be invalid after the |packet_buffer_| operation.
ossua73f6c92016-10-24 08:25:28 -07002001 next_packet = nullptr;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002002 if (!packet) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002003 RTC_LOG(LS_ERROR) << "Should always be able to extract a packet here";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002004 assert(false); // Should always be able to extract a packet here.
2005 return -1;
2006 }
Gustaf Ullbergb0a02072017-10-02 12:00:34 +02002007 const uint64_t waiting_time_ms = packet->waiting_time->ElapsedMs();
Jakob Ivarsson44507082019-03-05 16:59:03 +01002008 stats_->StoreWaitingTime(waiting_time_ms);
ossu61a208b2016-09-20 01:38:00 -07002009 RTC_DCHECK(!packet->empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002010
2011 if (first_packet) {
2012 first_packet = false;
henrik.lundin48ed9302015-10-29 05:36:24 -07002013 if (nack_enabled_) {
2014 RTC_DCHECK(nack_);
2015 // TODO(henrik.lundin): Should we update this for all decoded packets?
ossu7a377612016-10-18 04:06:13 -07002016 nack_->UpdateLastDecodedPacket(packet->sequence_number,
2017 packet->timestamp);
henrik.lundin48ed9302015-10-29 05:36:24 -07002018 }
ossu7a377612016-10-18 04:06:13 -07002019 prev_sequence_number = packet->sequence_number;
2020 prev_timestamp = packet->timestamp;
2021 prev_payload_type = packet->payload_type;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002022 }
2023
ossucafb4972017-01-02 07:00:50 -08002024 const bool has_cng_packet =
2025 decoder_database_->IsComfortNoise(packet->payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002026 // Store number of extracted samples.
ossu61a208b2016-09-20 01:38:00 -07002027 size_t packet_duration = 0;
2028 if (packet->frame) {
2029 packet_duration = packet->frame->Duration();
ossua70695a2016-09-22 02:06:28 -07002030 // TODO(ossu): Is this the correct way to track Opus FEC packets?
2031 if (packet->priority.codec_level > 0) {
Jakob Ivarsson44507082019-03-05 16:59:03 +01002032 stats_->SecondaryDecodedSamples(
kwibergd3edd772017-03-01 18:52:48 -08002033 rtc::dchecked_cast<int>(packet_duration));
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00002034 }
ossucafb4972017-01-02 07:00:50 -08002035 } else if (!has_cng_packet) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002036 RTC_LOG(LS_WARNING) << "Unknown payload type "
2037 << static_cast<int>(packet->payload_type);
ossu61a208b2016-09-20 01:38:00 -07002038 RTC_NOTREACHED();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002039 }
ossu61a208b2016-09-20 01:38:00 -07002040
2041 if (packet_duration == 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002042 // Decoder did not return a packet duration. Assume that the packet
2043 // contains the same number of samples as the previous one.
ossu61a208b2016-09-20 01:38:00 -07002044 packet_duration = decoder_frame_length_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002045 }
ossu7a377612016-10-18 04:06:13 -07002046 extracted_samples = packet->timestamp - first_timestamp + packet_duration;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002047
Artem Titove618cc92020-03-11 11:18:54 +01002048 RTC_DCHECK(controller_);
Henrik Lundinc49e9c22020-05-25 11:26:15 +02002049 stats_->JitterBufferDelay(
2050 packet_duration, waiting_time_ms + output_delay_chain_ms_,
2051 controller_->TargetLevelMs() + output_delay_chain_ms_);
Gustaf Ullbergb0a02072017-10-02 12:00:34 +02002052
ossua73f6c92016-10-24 08:25:28 -07002053 packet_list->push_back(std::move(*packet)); // Store packet in list.
Danil Chapovalovb6021232018-06-19 13:26:36 +02002054 packet = absl::nullopt; // Ensure it's never used after the move.
ossua73f6c92016-10-24 08:25:28 -07002055
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002056 // Check what packet is available next.
ossu7a377612016-10-18 04:06:13 -07002057 next_packet = packet_buffer_->PeekNextPacket();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002058 next_packet_available = false;
ossucafb4972017-01-02 07:00:50 -08002059 if (next_packet && prev_payload_type == next_packet->payload_type &&
2060 !has_cng_packet) {
ossu7a377612016-10-18 04:06:13 -07002061 int16_t seq_no_diff = next_packet->sequence_number - prev_sequence_number;
2062 size_t ts_diff = next_packet->timestamp - prev_timestamp;
Jakob Ivarsson00a6ab52019-01-09 16:35:07 +01002063 if ((seq_no_diff == 1 || seq_no_diff == 0) &&
2064 ts_diff <= packet_duration) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002065 // The next sequence number is available, or the next part of a packet
2066 // that was split into pieces upon insertion.
2067 next_packet_available = true;
2068 }
ossu7a377612016-10-18 04:06:13 -07002069 prev_sequence_number = next_packet->sequence_number;
Jakob Ivarsson00a6ab52019-01-09 16:35:07 +01002070 prev_timestamp = next_packet->timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002071 }
ossu61a208b2016-09-20 01:38:00 -07002072 } while (extracted_samples < required_samples && next_packet_available);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002073
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00002074 if (extracted_samples > 0) {
2075 // Delete old packets only when we are going to decode something. Otherwise,
2076 // we could end up in the situation where we never decode anything, since
2077 // all incoming packets are considered too old but the buffer will also
2078 // never be flooded and flushed.
Jakob Ivarsson44507082019-03-05 16:59:03 +01002079 packet_buffer_->DiscardAllOldPackets(timestamp_, stats_.get());
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00002080 }
2081
kwibergd3edd772017-03-01 18:52:48 -08002082 return rtc::dchecked_cast<int>(extracted_samples);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002083}
2084
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002085void NetEqImpl::UpdatePlcComponents(int fs_hz, size_t channels) {
2086 // Delete objects and create new ones.
2087 expand_.reset(expand_factory_->Create(background_noise_.get(),
2088 sync_buffer_.get(), &random_vector_,
Jakob Ivarsson44507082019-03-05 16:59:03 +01002089 stats_.get(), fs_hz, channels));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002090 merge_.reset(new Merge(fs_hz, channels, expand_.get(), sync_buffer_.get()));
2091}
2092
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002093void NetEqImpl::SetSampleRateAndChannels(int fs_hz, size_t channels) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002094 RTC_LOG(LS_VERBOSE) << "SetSampleRateAndChannels " << fs_hz << " "
2095 << channels;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002096 // TODO(hlundin): Change to an enumerator and skip assert.
Yves Gerey665174f2018-06-19 15:03:05 +02002097 assert(fs_hz == 8000 || fs_hz == 16000 || fs_hz == 32000 || fs_hz == 48000);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002098 assert(channels > 0);
2099
Henrik Lundinfe047752019-11-19 12:58:11 +01002100 // Before changing the sample rate, end and report any ongoing expand event.
2101 stats_->EndExpandEvent(fs_hz_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002102 fs_hz_ = fs_hz;
2103 fs_mult_ = fs_hz / 8000;
Peter Kastingdce40cf2015-08-24 14:52:23 -07002104 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002105 decoder_frame_length_ = 3 * output_size_samples_; // Initialize to 30ms.
2106
Ivo Creusen3ce44a32019-10-31 14:38:11 +01002107 last_mode_ = Mode::kNormal;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002108
ossu97ba30e2016-04-25 07:55:58 -07002109 ComfortNoiseDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02002110 if (cng_decoder)
2111 cng_decoder->Reset();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002112
2113 // Reinit post-decode VAD with new sample rate.
2114 assert(vad_.get()); // Cannot be NULL here.
2115 vad_->Init();
2116
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002117 // Delete algorithm buffer and create a new one.
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00002118 algorithm_buffer_.reset(new AudioMultiVector(channels));
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002119
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002120 // Delete sync buffer and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002121 sync_buffer_.reset(new SyncBuffer(channels, kSyncBufferSize * fs_mult_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002122
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00002123 // Delete BackgroundNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002124 background_noise_.reset(new BackgroundNoise(channels));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002125
2126 // Reset random vector.
2127 random_vector_.Reset();
2128
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002129 UpdatePlcComponents(fs_hz, channels);
2130
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002131 // Move index so that we create a small set of future samples (all 0).
2132 sync_buffer_->set_next_index(sync_buffer_->next_index() -
Yves Gerey665174f2018-06-19 15:03:05 +02002133 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002134
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002135 normal_.reset(new Normal(fs_hz, decoder_database_.get(), *background_noise_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002136 expand_.get()));
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +00002137 accelerate_.reset(
2138 accelerate_factory_->Create(fs_hz, channels, *background_noise_));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002139 preemptive_expand_.reset(preemptive_expand_factory_->Create(
Peter Kastingdce40cf2015-08-24 14:52:23 -07002140 fs_hz, channels, *background_noise_, expand_->overlap_length()));
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002141
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002142 // Delete ComfortNoise object and create a new one.
Yves Gerey665174f2018-06-19 15:03:05 +02002143 comfort_noise_.reset(
2144 new ComfortNoise(fs_hz, decoder_database_.get(), sync_buffer_.get()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002145
2146 // Verify that |decoded_buffer_| is long enough.
2147 if (decoded_buffer_length_ < kMaxFrameSize * channels) {
2148 // Reallocate to larger size.
2149 decoded_buffer_length_ = kMaxFrameSize * channels;
2150 decoded_buffer_.reset(new int16_t[decoded_buffer_length_]);
2151 }
Ivo Creusen53a31f72019-10-24 15:20:39 +02002152 RTC_CHECK(controller_) << "Unexpectedly found no NetEqController";
2153 controller_->SetSampleRate(fs_hz_, output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002154}
2155
henrik.lundin55480f52016-03-08 02:37:57 -08002156NetEqImpl::OutputType NetEqImpl::LastOutputType() {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002157 assert(vad_.get());
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002158 assert(expand_.get());
Ivo Creusen3ce44a32019-10-31 14:38:11 +01002159 if (last_mode_ == Mode::kCodecInternalCng ||
2160 last_mode_ == Mode::kRfc3389Cng) {
henrik.lundin55480f52016-03-08 02:37:57 -08002161 return OutputType::kCNG;
Ivo Creusen3ce44a32019-10-31 14:38:11 +01002162 } else if (last_mode_ == Mode::kExpand && expand_->MuteFactor(0) == 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002163 // Expand mode has faded down to background noise only (very long expand).
henrik.lundin55480f52016-03-08 02:37:57 -08002164 return OutputType::kPLCCNG;
Ivo Creusen3ce44a32019-10-31 14:38:11 +01002165 } else if (last_mode_ == Mode::kExpand) {
henrik.lundin55480f52016-03-08 02:37:57 -08002166 return OutputType::kPLC;
wu@webrtc.org24301a62013-12-13 19:17:43 +00002167 } else if (vad_->running() && !vad_->active_speech()) {
henrik.lundin55480f52016-03-08 02:37:57 -08002168 return OutputType::kVadPassive;
Ivo Creusen3ce44a32019-10-31 14:38:11 +01002169 } else if (last_mode_ == Mode::kCodecPlc) {
Alex Narest5b5d97c2019-08-07 18:15:08 +02002170 return OutputType::kCodecPLC;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002171 } else {
henrik.lundin55480f52016-03-08 02:37:57 -08002172 return OutputType::kNormalSpeech;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002173 }
2174}
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002175} // namespace webrtc