blob: 265043acb4909cbf99fa9712c3127a8cbca16348 [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.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000054
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000055namespace webrtc {
Ivo Creusen53a31f72019-10-24 15:20:39 +020056namespace {
57
58std::unique_ptr<NetEqController> CreateNetEqController(
Ivo Creusen3ce44a32019-10-31 14:38:11 +010059 const NetEqControllerFactory& controller_factory,
Ivo Creusen53a31f72019-10-24 15:20:39 +020060 int base_min_delay,
61 int max_packets_in_buffer,
62 bool enable_rtx_handling,
63 bool allow_time_stretching,
Ivo Creusen88636c62020-01-24 11:04:56 +010064 TickTimer* tick_timer,
65 webrtc::Clock* clock) {
Ivo Creusen53a31f72019-10-24 15:20:39 +020066 NetEqController::Config config;
67 config.base_min_delay_ms = base_min_delay;
68 config.max_packets_in_buffer = max_packets_in_buffer;
69 config.enable_rtx_handling = enable_rtx_handling;
70 config.allow_time_stretching = allow_time_stretching;
71 config.tick_timer = tick_timer;
Ivo Creusen88636c62020-01-24 11:04:56 +010072 config.clock = clock;
Ivo Creusen3ce44a32019-10-31 14:38:11 +010073 return controller_factory.CreateNetEqController(config);
Ivo Creusen53a31f72019-10-24 15:20:39 +020074}
75
76} // namespace
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000077
ossue3525782016-05-25 07:37:43 -070078NetEqImpl::Dependencies::Dependencies(
79 const NetEq::Config& config,
Alessio Bazzica8f319a32019-07-24 16:47:02 +000080 Clock* clock,
Ivo Creusen3ce44a32019-10-31 14:38:11 +010081 const rtc::scoped_refptr<AudioDecoderFactory>& decoder_factory,
82 const NetEqControllerFactory& controller_factory)
Alessio Bazzica8f319a32019-07-24 16:47:02 +000083 : clock(clock),
84 tick_timer(new TickTimer),
Jakob Ivarsson44507082019-03-05 16:59:03 +010085 stats(new StatisticsCalculator),
Karl Wiberg08126342018-03-20 19:18:55 +010086 decoder_database(
87 new DecoderDatabase(decoder_factory, config.codec_pair_id)),
henrik.lundin1d9061e2016-04-26 12:19:34 -070088 dtmf_buffer(new DtmfBuffer(config.sample_rate_hz)),
89 dtmf_tone_generator(new DtmfToneGenerator),
90 packet_buffer(
91 new PacketBuffer(config.max_packets_in_buffer, tick_timer.get())),
Ivo Creusen53a31f72019-10-24 15:20:39 +020092 neteq_controller(
Ivo Creusen3ce44a32019-10-31 14:38:11 +010093 CreateNetEqController(controller_factory,
94 config.min_delay_ms,
Ivo Creusen53a31f72019-10-24 15:20:39 +020095 config.max_packets_in_buffer,
96 config.enable_rtx_handling,
97 !config.for_test_no_time_stretching,
Ivo Creusen88636c62020-01-24 11:04:56 +010098 tick_timer.get(),
99 clock)),
ossua70695a2016-09-22 02:06:28 -0700100 red_payload_splitter(new RedPayloadSplitter),
henrik.lundin1d9061e2016-04-26 12:19:34 -0700101 timestamp_scaler(new TimestampScaler(*decoder_database)),
102 accelerate_factory(new AccelerateFactory),
103 expand_factory(new ExpandFactory),
104 preemptive_expand_factory(new PreemptiveExpandFactory) {}
105
106NetEqImpl::Dependencies::~Dependencies() = default;
107
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +0000108NetEqImpl::NetEqImpl(const NetEq::Config& config,
henrik.lundin1d9061e2016-04-26 12:19:34 -0700109 Dependencies&& deps,
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000110 bool create_components)
Alessio Bazzica8f319a32019-07-24 16:47:02 +0000111 : clock_(deps.clock),
112 tick_timer_(std::move(deps.tick_timer)),
henrik.lundin1d9061e2016-04-26 12:19:34 -0700113 decoder_database_(std::move(deps.decoder_database)),
henrik.lundin1d9061e2016-04-26 12:19:34 -0700114 dtmf_buffer_(std::move(deps.dtmf_buffer)),
115 dtmf_tone_generator_(std::move(deps.dtmf_tone_generator)),
116 packet_buffer_(std::move(deps.packet_buffer)),
ossua70695a2016-09-22 02:06:28 -0700117 red_payload_splitter_(std::move(deps.red_payload_splitter)),
henrik.lundin1d9061e2016-04-26 12:19:34 -0700118 timestamp_scaler_(std::move(deps.timestamp_scaler)),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000119 vad_(new PostDecodeVad()),
henrik.lundin1d9061e2016-04-26 12:19:34 -0700120 expand_factory_(std::move(deps.expand_factory)),
121 accelerate_factory_(std::move(deps.accelerate_factory)),
122 preemptive_expand_factory_(std::move(deps.preemptive_expand_factory)),
Jakob Ivarsson44507082019-03-05 16:59:03 +0100123 stats_(std::move(deps.stats)),
Ivo Creusen53a31f72019-10-24 15:20:39 +0200124 controller_(std::move(deps.neteq_controller)),
Ivo Creusen3ce44a32019-10-31 14:38:11 +0100125 last_mode_(Mode::kNormal),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000126 decoded_buffer_length_(kMaxFrameSize),
127 decoded_buffer_(new int16_t[decoded_buffer_length_]),
128 playout_timestamp_(0),
129 new_codec_(false),
130 timestamp_(0),
131 reset_decoder_(false),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000132 first_packet_(true),
Henrik Lundincf808d22015-05-27 14:33:29 +0200133 enable_fast_accelerate_(config.enable_fast_accelerate),
henrik.lundin7a926812016-05-12 13:51:28 -0700134 nack_enabled_(false),
Henrik Lundin3ef3bfc2018-04-10 15:10:26 +0200135 enable_muted_state_(config.enable_muted_state),
136 expand_uma_logger_("WebRTC.Audio.ExpandRatePercent",
137 10, // Report once every 10 s.
138 tick_timer_.get()),
139 speech_expand_uma_logger_("WebRTC.Audio.SpeechExpandRatePercent",
140 10, // Report once every 10 s.
Henrik Lundin7687ad52018-07-02 10:14:46 +0200141 tick_timer_.get()),
Jakob Ivarsson39b934b2019-01-10 10:28:23 +0100142 no_time_stretching_(config.for_test_no_time_stretching),
143 enable_rtx_handling_(config.enable_rtx_handling) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100144 RTC_LOG(LS_INFO) << "NetEq config: " << config.ToString();
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +0000145 int fs = config.sample_rate_hz;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000146 if (fs != 8000 && fs != 16000 && fs != 32000 && fs != 48000) {
Jonas Olssonb2b20312020-01-14 12:11:31 +0100147 RTC_LOG(LS_ERROR) << "Sample rate " << fs
148 << " Hz not supported. "
149 "Changing to 8000 Hz.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000150 fs = 8000;
151 }
Ivo Creusen53a31f72019-10-24 15:20:39 +0200152 controller_->SetMaximumDelay(config.max_delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000153 fs_hz_ = fs;
154 fs_mult_ = fs / 8000;
henrik.lundind89814b2015-11-23 06:49:25 -0800155 last_output_sample_rate_hz_ = fs;
Peter Kastingdce40cf2015-08-24 14:52:23 -0700156 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
Ivo Creusen53a31f72019-10-24 15:20:39 +0200157 controller_->SetSampleRate(fs_hz_, output_size_samples_);
Alessio Bazzica2d02c942019-11-29 13:32:12 +0100158 decoder_frame_length_ = 2 * output_size_samples_; // 20 ms.
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000159 if (create_components) {
160 SetSampleRateAndChannels(fs, 1); // Default is 1 channel.
161 }
henrik.lundin9bc26672015-11-02 03:25:57 -0800162 RTC_DCHECK(!vad_->enabled());
163 if (config.enable_post_decode_vad) {
164 vad_->Enable();
165 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000166}
167
Henrik Lundind67a2192015-08-03 12:54:37 +0200168NetEqImpl::~NetEqImpl() = default;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000169
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200170int NetEqImpl::InsertPacket(const RTPHeader& rtp_header,
Karl Wiberg45eb1352019-10-10 14:23:00 +0200171 rtc::ArrayView<const uint8_t> payload) {
kwibergac554ee2016-09-02 00:39:33 -0700172 rtc::MsanCheckInitialized(payload);
henrik.lundina689b442015-12-17 03:50:05 -0800173 TRACE_EVENT0("webrtc", "NetEqImpl::InsertPacket");
Tommi9090e0b2016-01-20 13:39:36 +0100174 rtc::CritScope lock(&crit_sect_);
Karl Wiberg45eb1352019-10-10 14:23:00 +0200175 if (InsertPacketInternal(rtp_header, payload) != 0) {
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000176 return kFail;
177 }
178 return kOK;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000179}
180
henrik.lundinb8c55b12017-05-10 07:38:01 -0700181void NetEqImpl::InsertEmptyPacket(const RTPHeader& /*rtp_header*/) {
182 // TODO(henrik.lundin) Handle NACK as well. This will make use of the
183 // rtp_header parameter.
184 // https://bugs.chromium.org/p/webrtc/issues/detail?id=7611
185 rtc::CritScope lock(&crit_sect_);
Ivo Creusen53a31f72019-10-24 15:20:39 +0200186 controller_->RegisterEmptyPacket();
henrik.lundinb8c55b12017-05-10 07:38:01 -0700187}
188
henrik.lundin500c04b2016-03-08 02:36:04 -0800189namespace {
190void SetAudioFrameActivityAndType(bool vad_enabled,
henrik.lundin55480f52016-03-08 02:37:57 -0800191 NetEqImpl::OutputType type,
henrik.lundin500c04b2016-03-08 02:36:04 -0800192 AudioFrame::VADActivity last_vad_activity,
193 AudioFrame* audio_frame) {
194 switch (type) {
henrik.lundin55480f52016-03-08 02:37:57 -0800195 case NetEqImpl::OutputType::kNormalSpeech: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800196 audio_frame->speech_type_ = AudioFrame::kNormalSpeech;
197 audio_frame->vad_activity_ = AudioFrame::kVadActive;
198 break;
199 }
henrik.lundin55480f52016-03-08 02:37:57 -0800200 case NetEqImpl::OutputType::kVadPassive: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800201 // This should only be reached if the VAD is enabled.
202 RTC_DCHECK(vad_enabled);
203 audio_frame->speech_type_ = AudioFrame::kNormalSpeech;
204 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
205 break;
206 }
henrik.lundin55480f52016-03-08 02:37:57 -0800207 case NetEqImpl::OutputType::kCNG: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800208 audio_frame->speech_type_ = AudioFrame::kCNG;
209 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
210 break;
211 }
henrik.lundin55480f52016-03-08 02:37:57 -0800212 case NetEqImpl::OutputType::kPLC: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800213 audio_frame->speech_type_ = AudioFrame::kPLC;
214 audio_frame->vad_activity_ = last_vad_activity;
215 break;
216 }
henrik.lundin55480f52016-03-08 02:37:57 -0800217 case NetEqImpl::OutputType::kPLCCNG: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800218 audio_frame->speech_type_ = AudioFrame::kPLCCNG;
219 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
220 break;
221 }
Alex Narest5b5d97c2019-08-07 18:15:08 +0200222 case NetEqImpl::OutputType::kCodecPLC: {
223 audio_frame->speech_type_ = AudioFrame::kCodecPLC;
224 audio_frame->vad_activity_ = last_vad_activity;
225 break;
226 }
henrik.lundin500c04b2016-03-08 02:36:04 -0800227 default:
228 RTC_NOTREACHED();
229 }
230 if (!vad_enabled) {
231 // Always set kVadUnknown when receive VAD is inactive.
232 audio_frame->vad_activity_ = AudioFrame::kVadUnknown;
233 }
234}
henrik.lundinbc89de32016-03-08 05:20:14 -0800235} // namespace
henrik.lundin500c04b2016-03-08 02:36:04 -0800236
Ivo Creusen55de08e2018-09-03 11:49:27 +0200237int NetEqImpl::GetAudio(AudioFrame* audio_frame,
238 bool* muted,
Ivo Creusen3ce44a32019-10-31 14:38:11 +0100239 absl::optional<Operation> action_override) {
henrik.lundine1ca1672016-01-08 03:50:08 -0800240 TRACE_EVENT0("webrtc", "NetEqImpl::GetAudio");
Tommi9090e0b2016-01-20 13:39:36 +0100241 rtc::CritScope lock(&crit_sect_);
Ivo Creusen55de08e2018-09-03 11:49:27 +0200242 if (GetAudioInternal(audio_frame, muted, action_override) != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000243 return kFail;
244 }
henrik.lundin5fac3f02016-08-24 11:18:49 -0700245 RTC_DCHECK_EQ(
246 audio_frame->sample_rate_hz_,
kwibergd3edd772017-03-01 18:52:48 -0800247 rtc::dchecked_cast<int>(audio_frame->samples_per_channel_ * 100));
henrik.lundina4491072017-07-06 05:23:53 -0700248 RTC_DCHECK_EQ(*muted, audio_frame->muted());
henrik.lundin500c04b2016-03-08 02:36:04 -0800249 SetAudioFrameActivityAndType(vad_->enabled(), LastOutputType(),
250 last_vad_activity_, audio_frame);
251 last_vad_activity_ = audio_frame->vad_activity_;
henrik.lundin6d8e0112016-03-04 10:34:21 -0800252 last_output_sample_rate_hz_ = audio_frame->sample_rate_hz_;
henrik.lundind89814b2015-11-23 06:49:25 -0800253 RTC_DCHECK(last_output_sample_rate_hz_ == 8000 ||
254 last_output_sample_rate_hz_ == 16000 ||
255 last_output_sample_rate_hz_ == 32000 ||
256 last_output_sample_rate_hz_ == 48000)
257 << "Unexpected sample rate " << last_output_sample_rate_hz_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000258 return kOK;
259}
260
kwiberg1c07c702017-03-27 07:15:49 -0700261void NetEqImpl::SetCodecs(const std::map<int, SdpAudioFormat>& codecs) {
262 rtc::CritScope lock(&crit_sect_);
263 const std::vector<int> changed_payload_types =
264 decoder_database_->SetCodecs(codecs);
265 for (const int pt : changed_payload_types) {
Jakob Ivarsson44507082019-03-05 16:59:03 +0100266 packet_buffer_->DiscardPacketsWithPayloadType(pt, stats_.get());
kwiberg1c07c702017-03-27 07:15:49 -0700267 }
268}
269
kwiberg5adaf732016-10-04 09:33:27 -0700270bool NetEqImpl::RegisterPayloadType(int rtp_payload_type,
271 const SdpAudioFormat& audio_format) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100272 RTC_LOG(LS_VERBOSE) << "NetEqImpl::RegisterPayloadType: payload type "
Jonas Olssonabbe8412018-04-03 13:40:05 +0200273 << rtp_payload_type << ", codec "
274 << rtc::ToString(audio_format);
kwiberg5adaf732016-10-04 09:33:27 -0700275 rtc::CritScope lock(&crit_sect_);
Henrik Lundinc417d9e2017-06-14 12:29:03 +0200276 return decoder_database_->RegisterPayload(rtp_payload_type, audio_format) ==
277 DecoderDatabase::kOK;
kwiberg5adaf732016-10-04 09:33:27 -0700278}
279
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000280int NetEqImpl::RemovePayloadType(uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100281 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000282 int ret = decoder_database_->Remove(rtp_payload_type);
Henrik Lundinc417d9e2017-06-14 12:29:03 +0200283 if (ret == DecoderDatabase::kOK || ret == DecoderDatabase::kDecoderNotFound) {
Jakob Ivarsson44507082019-03-05 16:59:03 +0100284 packet_buffer_->DiscardPacketsWithPayloadType(rtp_payload_type,
285 stats_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000286 return kOK;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000287 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000288 return kFail;
289}
290
kwiberg6b19b562016-09-20 04:02:25 -0700291void NetEqImpl::RemoveAllPayloadTypes() {
292 rtc::CritScope lock(&crit_sect_);
293 decoder_database_->RemoveAll();
294}
295
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000296bool NetEqImpl::SetMinimumDelay(int delay_ms) {
Tommi9090e0b2016-01-20 13:39:36 +0100297 rtc::CritScope lock(&crit_sect_);
Gustaf Ullberg48d96c02017-09-15 13:59:52 +0200298 if (delay_ms >= 0 && delay_ms <= 10000) {
Ivo Creusen53a31f72019-10-24 15:20:39 +0200299 assert(controller_.get());
300 return controller_->SetMinimumDelay(delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000301 }
302 return false;
303}
304
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000305bool NetEqImpl::SetMaximumDelay(int delay_ms) {
Tommi9090e0b2016-01-20 13:39:36 +0100306 rtc::CritScope lock(&crit_sect_);
Gustaf Ullberg48d96c02017-09-15 13:59:52 +0200307 if (delay_ms >= 0 && delay_ms <= 10000) {
Ivo Creusen53a31f72019-10-24 15:20:39 +0200308 assert(controller_.get());
309 return controller_->SetMaximumDelay(delay_ms);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000310 }
311 return false;
312}
313
Ruslan Burakov9bee67c2019-02-05 13:49:26 +0100314bool NetEqImpl::SetBaseMinimumDelayMs(int delay_ms) {
315 rtc::CritScope lock(&crit_sect_);
316 if (delay_ms >= 0 && delay_ms <= 10000) {
Ivo Creusen53a31f72019-10-24 15:20:39 +0200317 return controller_->SetBaseMinimumDelay(delay_ms);
Ruslan Burakov9bee67c2019-02-05 13:49:26 +0100318 }
319 return false;
320}
321
322int NetEqImpl::GetBaseMinimumDelayMs() const {
323 rtc::CritScope lock(&crit_sect_);
Ivo Creusen53a31f72019-10-24 15:20:39 +0200324 return controller_->GetBaseMinimumDelay();
Ruslan Burakov9bee67c2019-02-05 13:49:26 +0100325}
326
Henrik Lundinabbff892017-11-29 09:14:04 +0100327int NetEqImpl::TargetDelayMs() const {
henrik.lundin114c1b32017-04-26 07:47:32 -0700328 rtc::CritScope lock(&crit_sect_);
Ivo Creusen53a31f72019-10-24 15:20:39 +0200329 RTC_DCHECK(controller_.get());
330 return controller_->TargetLevelMs();
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200331}
332
henrik.lundinb3f1c5d2016-08-22 15:39:53 -0700333int NetEqImpl::FilteredCurrentDelayMs() const {
334 rtc::CritScope lock(&crit_sect_);
Jakob Ivarssond487a552019-06-20 12:09:11 +0000335 // Sum up the filtered packet buffer level with the future length of the sync
Jakob Ivarssona36c5912019-06-27 10:12:02 +0200336 // buffer.
Ivo Creusen53a31f72019-10-24 15:20:39 +0200337 const int delay_samples =
338 controller_->GetFilteredBufferLevel() + sync_buffer_->FutureLength();
henrik.lundinb3f1c5d2016-08-22 15:39:53 -0700339 // The division below will truncate. The return value is in ms.
Jakob Ivarssona36c5912019-06-27 10:12:02 +0200340 return delay_samples / rtc::CheckedDivExact(fs_hz_, 1000);
henrik.lundinb3f1c5d2016-08-22 15:39:53 -0700341}
342
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000343int NetEqImpl::NetworkStatistics(NetEqNetworkStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100344 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000345 assert(decoder_database_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700346 const size_t total_samples_in_buffers =
ossu61a208b2016-09-20 01:38:00 -0700347 packet_buffer_->NumSamplesInBuffer(decoder_frame_length_) +
Peter Kastingdce40cf2015-08-24 14:52:23 -0700348 sync_buffer_->FutureLength();
Ivo Creusen53a31f72019-10-24 15:20:39 +0200349 assert(controller_.get());
350 stats->preferred_buffer_size_ms = controller_->TargetLevelMs();
351 stats->jitter_peaks_found = controller_->PeakFound();
Jakob Ivarsson44507082019-03-05 16:59:03 +0100352 stats_->GetNetworkStatistics(fs_hz_, total_samples_in_buffers,
353 decoder_frame_length_, stats);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000354 return 0;
355}
356
Steve Anton2dbc69f2017-08-24 17:15:13 -0700357NetEqLifetimeStatistics NetEqImpl::GetLifetimeStatistics() const {
358 rtc::CritScope lock(&crit_sect_);
Jakob Ivarsson44507082019-03-05 16:59:03 +0100359 return stats_->GetLifetimeStatistics();
Steve Anton2dbc69f2017-08-24 17:15:13 -0700360}
361
Ivo Creusend1c2f782018-09-13 14:39:55 +0200362NetEqOperationsAndState NetEqImpl::GetOperationsAndState() const {
363 rtc::CritScope lock(&crit_sect_);
Jakob Ivarsson44507082019-03-05 16:59:03 +0100364 auto result = stats_->GetOperationsAndState();
Ivo Creusend1c2f782018-09-13 14:39:55 +0200365 result.current_buffer_size_ms =
366 (packet_buffer_->NumSamplesInBuffer(decoder_frame_length_) +
367 sync_buffer_->FutureLength()) *
368 1000 / fs_hz_;
Ivo Creusendc6d5532018-09-27 11:43:42 +0200369 result.current_frame_size_ms = decoder_frame_length_ * 1000 / fs_hz_;
370 result.next_packet_available = packet_buffer_->PeekNextPacket() &&
371 packet_buffer_->PeekNextPacket()->timestamp ==
372 sync_buffer_->end_timestamp();
Ivo Creusend1c2f782018-09-13 14:39:55 +0200373 return result;
374}
375
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000376void NetEqImpl::EnableVad() {
Tommi9090e0b2016-01-20 13:39:36 +0100377 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000378 assert(vad_.get());
379 vad_->Enable();
380}
381
382void NetEqImpl::DisableVad() {
Tommi9090e0b2016-01-20 13:39:36 +0100383 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000384 assert(vad_.get());
385 vad_->Disable();
386}
387
Danil Chapovalovb6021232018-06-19 13:26:36 +0200388absl::optional<uint32_t> NetEqImpl::GetPlayoutTimestamp() const {
Tommi9090e0b2016-01-20 13:39:36 +0100389 rtc::CritScope lock(&crit_sect_);
Ivo Creusen3ce44a32019-10-31 14:38:11 +0100390 if (first_packet_ || last_mode_ == Mode::kRfc3389Cng ||
391 last_mode_ == Mode::kCodecInternalCng) {
wu@webrtc.org94454b72014-06-05 20:34:08 +0000392 // We don't have a valid RTP timestamp until we have decoded our first
henrik.lundin0d96ab72016-04-06 12:28:26 -0700393 // RTP packet. Also, the RTP timestamp is not accurate while playing CNG,
394 // which is indicated by returning an empty value.
Danil Chapovalovb6021232018-06-19 13:26:36 +0200395 return absl::nullopt;
wu@webrtc.org94454b72014-06-05 20:34:08 +0000396 }
Oskar Sundbom12ab00b2017-11-16 15:31:38 +0100397 return timestamp_scaler_->ToExternal(playout_timestamp_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000398}
399
henrik.lundind89814b2015-11-23 06:49:25 -0800400int NetEqImpl::last_output_sample_rate_hz() const {
Tommi9090e0b2016-01-20 13:39:36 +0100401 rtc::CritScope lock(&crit_sect_);
henrik.lundind89814b2015-11-23 06:49:25 -0800402 return last_output_sample_rate_hz_;
403}
404
Karl Wiberg4b644112019-10-11 09:37:42 +0200405absl::optional<NetEq::DecoderFormat> NetEqImpl::GetDecoderFormat(
ossuf1b08da2016-09-23 02:19:43 -0700406 int payload_type) const {
kwibergc4ccd4d2016-09-21 10:55:15 -0700407 rtc::CritScope lock(&crit_sect_);
408 const DecoderDatabase::DecoderInfo* const di =
409 decoder_database_->GetDecoderInfo(payload_type);
Karl Wiberg4b644112019-10-11 09:37:42 +0200410 if (di) {
411 const AudioDecoder* const decoder = di->GetDecoder();
412 // TODO(kwiberg): Why the special case for RED?
413 return DecoderFormat{
414 /*sample_rate_hz=*/di->IsRed() ? 8000 : di->SampleRateHz(),
415 /*num_channels=*/
416 decoder ? rtc::dchecked_cast<int>(decoder->Channels()) : 1,
417 /*sdp_format=*/di->GetFormat()};
418 } else {
419 // Payload type not registered.
420 return absl::nullopt;
kwibergc4ccd4d2016-09-21 10:55:15 -0700421 }
kwibergc4ccd4d2016-09-21 10:55:15 -0700422}
423
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000424void NetEqImpl::FlushBuffers() {
Tommi9090e0b2016-01-20 13:39:36 +0100425 rtc::CritScope lock(&crit_sect_);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100426 RTC_LOG(LS_VERBOSE) << "FlushBuffers";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000427 packet_buffer_->Flush();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000428 assert(sync_buffer_.get());
429 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000430 sync_buffer_->Flush();
431 sync_buffer_->set_next_index(sync_buffer_->next_index() -
432 expand_->overlap_length());
433 // Set to wait for new codec.
434 first_packet_ = true;
435}
436
henrik.lundin48ed9302015-10-29 05:36:24 -0700437void NetEqImpl::EnableNack(size_t max_nack_list_size) {
Tommi9090e0b2016-01-20 13:39:36 +0100438 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700439 if (!nack_enabled_) {
440 const int kNackThresholdPackets = 2;
henrik.lundin91951862016-06-08 06:43:41 -0700441 nack_.reset(NackTracker::Create(kNackThresholdPackets));
henrik.lundin48ed9302015-10-29 05:36:24 -0700442 nack_enabled_ = true;
443 nack_->UpdateSampleRate(fs_hz_);
444 }
445 nack_->SetMaxNackListSize(max_nack_list_size);
446}
447
448void NetEqImpl::DisableNack() {
Tommi9090e0b2016-01-20 13:39:36 +0100449 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700450 nack_.reset();
451 nack_enabled_ = false;
452}
453
454std::vector<uint16_t> NetEqImpl::GetNackList(int64_t round_trip_time_ms) const {
Tommi9090e0b2016-01-20 13:39:36 +0100455 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700456 if (!nack_enabled_) {
457 return std::vector<uint16_t>();
458 }
459 RTC_DCHECK(nack_.get());
460 return nack_->GetNackList(round_trip_time_ms);
minyue@webrtc.orgd7301772013-08-29 00:58:14 +0000461}
462
henrik.lundin114c1b32017-04-26 07:47:32 -0700463std::vector<uint32_t> NetEqImpl::LastDecodedTimestamps() const {
464 rtc::CritScope lock(&crit_sect_);
465 return last_decoded_timestamps_;
466}
467
468int NetEqImpl::SyncBufferSizeMs() const {
469 rtc::CritScope lock(&crit_sect_);
470 return rtc::dchecked_cast<int>(sync_buffer_->FutureLength() /
471 rtc::CheckedDivExact(fs_hz_, 1000));
472}
473
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000474const SyncBuffer* NetEqImpl::sync_buffer_for_test() const {
Tommi9090e0b2016-01-20 13:39:36 +0100475 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000476 return sync_buffer_.get();
477}
478
Ivo Creusen3ce44a32019-10-31 14:38:11 +0100479NetEq::Operation NetEqImpl::last_operation_for_test() const {
minyue5bd33972016-05-02 04:46:11 -0700480 rtc::CritScope lock(&crit_sect_);
481 return last_operation_;
482}
483
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000484// Methods below this line are private.
485
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200486int NetEqImpl::InsertPacketInternal(const RTPHeader& rtp_header,
Karl Wiberg45eb1352019-10-10 14:23:00 +0200487 rtc::ArrayView<const uint8_t> payload) {
kwibergee2bac22015-11-11 10:34:00 -0800488 if (payload.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100489 RTC_LOG_F(LS_ERROR) << "payload is empty";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000490 return kInvalidPointer;
491 }
Alessio Bazzica8f319a32019-07-24 16:47:02 +0000492
493 int64_t receive_time_ms = clock_->TimeInMilliseconds();
Jakob Ivarsson44507082019-03-05 16:59:03 +0100494 stats_->ReceivedPacket();
ossu17e3fa12016-09-08 04:52:55 -0700495
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000496 PacketList packet_list;
ossua73f6c92016-10-24 08:25:28 -0700497 // Insert packet in a packet list.
Alessio Bazzica8f319a32019-07-24 16:47:02 +0000498 packet_list.push_back([&rtp_header, &payload, &receive_time_ms] {
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000499 // Convert to Packet.
ossua73f6c92016-10-24 08:25:28 -0700500 Packet packet;
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200501 packet.payload_type = rtp_header.payloadType;
502 packet.sequence_number = rtp_header.sequenceNumber;
503 packet.timestamp = rtp_header.timestamp;
ossua73f6c92016-10-24 08:25:28 -0700504 packet.payload.SetData(payload.data(), payload.size());
Alessio Bazzica8f319a32019-07-24 16:47:02 +0000505 packet.packet_info = RtpPacketInfo(rtp_header, receive_time_ms);
henrik.lundin84f8cd62016-04-26 07:45:16 -0700506 // Waiting time will be set upon inserting the packet in the buffer.
ossua73f6c92016-10-24 08:25:28 -0700507 RTC_DCHECK(!packet.waiting_time);
508 return packet;
509 }());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000510
Niels Möllerbb9f4c12018-11-21 16:07:10 +0100511 bool update_sample_rate_and_channels = first_packet_;
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700512
513 if (update_sample_rate_and_channels) {
514 // Reset timestamp scaling.
515 timestamp_scaler_->Reset();
516 }
517
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200518 if (!decoder_database_->IsRed(rtp_header.payloadType)) {
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700519 // Scale timestamp to internal domain (only for some codecs).
520 timestamp_scaler_->ToInternal(&packet_list);
521 }
522
523 // Store these for later use, since the first packet may very well disappear
524 // before we need these values.
525 uint32_t main_timestamp = packet_list.front().timestamp;
526 uint8_t main_payload_type = packet_list.front().payload_type;
527 uint16_t main_sequence_number = packet_list.front().sequence_number;
528
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000529 // Reinitialize NetEq if it's needed (changed SSRC or first call).
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700530 if (update_sample_rate_and_channels) {
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000531 // Note: |first_packet_| will be cleared further down in this method, once
532 // the packet has been successfully inserted into the packet buffer.
533
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000534 // Flush the packet buffer and DTMF buffer.
535 packet_buffer_->Flush();
536 dtmf_buffer_->Flush();
537
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000538 // Update audio buffer timestamp.
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700539 sync_buffer_->IncreaseEndTimestamp(main_timestamp - timestamp_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000540
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000541 // Update codecs.
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700542 timestamp_ = main_timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000543 }
544
ossu7a377612016-10-18 04:06:13 -0700545 if (nack_enabled_) {
546 RTC_DCHECK(nack_);
547 if (update_sample_rate_and_channels) {
548 nack_->Reset();
549 }
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200550 nack_->UpdateLastReceivedPacket(rtp_header.sequenceNumber,
551 rtp_header.timestamp);
ossu7a377612016-10-18 04:06:13 -0700552 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000553
554 // Check for RED payload type, and separate payloads into several packets.
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200555 if (decoder_database_->IsRed(rtp_header.payloadType)) {
ossua70695a2016-09-22 02:06:28 -0700556 if (!red_payload_splitter_->SplitRed(&packet_list)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000557 return kRedundancySplitError;
558 }
559 // Only accept a few RED payloads of the same type as the main data,
560 // DTMF events and CNG.
ossua70695a2016-09-22 02:06:28 -0700561 red_payload_splitter_->CheckRedPayloads(&packet_list, *decoder_database_);
Henrik Lundindefa7a82018-07-03 13:07:30 +0200562 if (packet_list.empty()) {
563 return kRedundancySplitError;
564 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000565 }
566
567 // Check payload types.
568 if (decoder_database_->CheckPayloadTypes(packet_list) ==
569 DecoderDatabase::kDecoderNotFound) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000570 return kUnknownRtpPayloadType;
571 }
572
ossu7a377612016-10-18 04:06:13 -0700573 RTC_DCHECK(!packet_list.empty());
ossu7a377612016-10-18 04:06:13 -0700574
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700575 // Update main_timestamp, if new packets appear in the list
576 // after RED splitting.
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200577 if (decoder_database_->IsRed(rtp_header.payloadType)) {
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700578 timestamp_scaler_->ToInternal(&packet_list);
579 main_timestamp = packet_list.front().timestamp;
580 main_payload_type = packet_list.front().payload_type;
581 main_sequence_number = packet_list.front().sequence_number;
582 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000583
584 // Process DTMF payloads. Cycle through the list of packets, and pick out any
585 // DTMF payloads found.
586 PacketList::iterator it = packet_list.begin();
587 while (it != packet_list.end()) {
ossua73f6c92016-10-24 08:25:28 -0700588 const Packet& current_packet = (*it);
589 RTC_DCHECK(!current_packet.payload.empty());
590 if (decoder_database_->IsDtmf(current_packet.payload_type)) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000591 DtmfEvent event;
ossua73f6c92016-10-24 08:25:28 -0700592 int ret = DtmfBuffer::ParseEvent(current_packet.timestamp,
593 current_packet.payload.data(),
594 current_packet.payload.size(), &event);
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000595 if (ret != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000596 return kDtmfParsingError;
597 }
598 if (dtmf_buffer_->InsertEvent(event) != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000599 return kDtmfInsertError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000600 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000601 it = packet_list.erase(it);
602 } else {
603 ++it;
604 }
605 }
606
ossu61a208b2016-09-20 01:38:00 -0700607 PacketList parsed_packet_list;
608 while (!packet_list.empty()) {
ossua73f6c92016-10-24 08:25:28 -0700609 Packet& packet = packet_list.front();
ossu61a208b2016-09-20 01:38:00 -0700610 const DecoderDatabase::DecoderInfo* info =
ossua73f6c92016-10-24 08:25:28 -0700611 decoder_database_->GetDecoderInfo(packet.payload_type);
ossu61a208b2016-09-20 01:38:00 -0700612 if (!info) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100613 RTC_LOG(LS_WARNING) << "SplitAudio unknown payload type";
ossu61a208b2016-09-20 01:38:00 -0700614 return kUnknownRtpPayloadType;
615 }
616
617 if (info->IsComfortNoise()) {
618 // Carry comfort noise packets along.
ossua73f6c92016-10-24 08:25:28 -0700619 parsed_packet_list.splice(parsed_packet_list.end(), packet_list,
620 packet_list.begin());
ossu61a208b2016-09-20 01:38:00 -0700621 } else {
ossua73f6c92016-10-24 08:25:28 -0700622 const auto sequence_number = packet.sequence_number;
623 const auto payload_type = packet.payload_type;
624 const Packet::Priority original_priority = packet.priority;
Alessio Bazzica8f319a32019-07-24 16:47:02 +0000625 const auto& packet_info = packet.packet_info;
Yves Gerey665174f2018-06-19 15:03:05 +0200626 auto packet_from_result = [&](AudioDecoder::ParseResult& result) {
ossua73f6c92016-10-24 08:25:28 -0700627 Packet new_packet;
628 new_packet.sequence_number = sequence_number;
629 new_packet.payload_type = payload_type;
630 new_packet.timestamp = result.timestamp;
631 new_packet.priority.codec_level = result.priority;
632 new_packet.priority.red_level = original_priority.red_level;
Alessio Bazzica8f319a32019-07-24 16:47:02 +0000633 new_packet.packet_info = packet_info;
ossua73f6c92016-10-24 08:25:28 -0700634 new_packet.frame = std::move(result.frame);
635 return new_packet;
636 };
637
ossu61a208b2016-09-20 01:38:00 -0700638 std::vector<AudioDecoder::ParseResult> results =
ossua73f6c92016-10-24 08:25:28 -0700639 info->GetDecoder()->ParsePayload(std::move(packet.payload),
640 packet.timestamp);
641 if (results.empty()) {
642 packet_list.pop_front();
643 } else {
644 bool first = true;
645 for (auto& result : results) {
646 RTC_DCHECK(result.frame);
647 RTC_DCHECK_GE(result.priority, 0);
648 if (first) {
649 // Re-use the node and move it to parsed_packet_list.
650 packet_list.front() = packet_from_result(result);
651 parsed_packet_list.splice(parsed_packet_list.end(), packet_list,
652 packet_list.begin());
653 first = false;
654 } else {
655 parsed_packet_list.push_back(packet_from_result(result));
656 }
ossu61a208b2016-09-20 01:38:00 -0700657 }
ossu61a208b2016-09-20 01:38:00 -0700658 }
659 }
660 }
661
Ivo Creusenfd7c0a52017-10-20 12:35:04 +0200662 // Calculate the number of primary (non-FEC/RED) packets.
Ivo Creusenbf4a2212019-04-24 14:06:24 +0200663 const size_t number_of_primary_packets = std::count_if(
Ivo Creusenfd7c0a52017-10-20 12:35:04 +0200664 parsed_packet_list.begin(), parsed_packet_list.end(),
665 [](const Packet& in) { return in.priority.codec_level == 0; });
Ivo Creusenbf4a2212019-04-24 14:06:24 +0200666 if (number_of_primary_packets < parsed_packet_list.size()) {
667 stats_->SecondaryPacketsReceived(parsed_packet_list.size() -
668 number_of_primary_packets);
669 }
Ivo Creusenfd7c0a52017-10-20 12:35:04 +0200670
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000671 // Insert packets in buffer.
ossua70695a2016-09-22 02:06:28 -0700672 const int ret = packet_buffer_->InsertPacketList(
ossu61a208b2016-09-20 01:38:00 -0700673 &parsed_packet_list, *decoder_database_, &current_rtp_payload_type_,
Jakob Ivarsson44507082019-03-05 16:59:03 +0100674 &current_cng_rtp_payload_type_, stats_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000675 if (ret == PacketBuffer::kFlushed) {
676 // Reset DSP timestamp etc. if packet buffer flushed.
677 new_codec_ = true;
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000678 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000679 } else if (ret != PacketBuffer::kOK) {
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000680 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000681 }
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000682
683 if (first_packet_) {
684 first_packet_ = false;
685 // Update the codec on the next GetAudio call.
686 new_codec_ = true;
687 }
688
henrik.lundinda8bbf62016-08-31 03:14:11 -0700689 if (current_rtp_payload_type_) {
690 RTC_DCHECK(decoder_database_->GetDecoderInfo(*current_rtp_payload_type_))
691 << "Payload type " << static_cast<int>(*current_rtp_payload_type_)
692 << " is unknown where it shouldn't be";
693 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000694
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000695 if (update_sample_rate_and_channels && !packet_buffer_->Empty()) {
696 // We do not use |current_rtp_payload_type_| to |set payload_type|, but
697 // get the next RTP header from |packet_buffer_| to obtain the payload type.
698 // The reason for it is the following corner case. If NetEq receives a
699 // CNG packet with a sample rate different than the current CNG then it
700 // flushes its buffer, assuming send codec must have been changed. However,
701 // payload type of the hypothetically new send codec is not known.
ossu7a377612016-10-18 04:06:13 -0700702 const Packet* next_packet = packet_buffer_->PeekNextPacket();
703 RTC_DCHECK(next_packet);
704 const int payload_type = next_packet->payload_type;
ossu97ba30e2016-04-25 07:55:58 -0700705 size_t channels = 1;
706 if (!decoder_database_->IsComfortNoise(payload_type)) {
707 AudioDecoder* decoder = decoder_database_->GetDecoder(payload_type);
708 assert(decoder); // Payloads are already checked to be valid.
709 channels = decoder->Channels();
710 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000711 const DecoderDatabase::DecoderInfo* decoder_info =
712 decoder_database_->GetDecoderInfo(payload_type);
713 assert(decoder_info);
kwibergc0f2dcf2016-05-31 06:28:03 -0700714 if (decoder_info->SampleRateHz() != fs_hz_ ||
ossu97ba30e2016-04-25 07:55:58 -0700715 channels != algorithm_buffer_->Channels()) {
Yves Gerey665174f2018-06-19 15:03:05 +0200716 SetSampleRateAndChannels(decoder_info->SampleRateHz(), channels);
henrik.lundin48ed9302015-10-29 05:36:24 -0700717 }
718 if (nack_enabled_) {
719 RTC_DCHECK(nack_);
720 // Update the sample rate even if the rate is not new, because of Reset().
721 nack_->UpdateSampleRate(fs_hz_);
722 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000723 }
724
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000725 const DecoderDatabase::DecoderInfo* dec_info =
ossu7a377612016-10-18 04:06:13 -0700726 decoder_database_->GetDecoderInfo(main_payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000727 assert(dec_info); // Already checked that the payload type is known.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000728
Ivo Creusen53a31f72019-10-24 15:20:39 +0200729 const bool last_cng_or_dtmf =
730 dec_info->IsComfortNoise() || dec_info->IsDtmf();
731 const size_t packet_length_samples =
732 number_of_primary_packets * decoder_frame_length_;
733 // Only update statistics if incoming packet is not older than last played
734 // out packet or RTX handling is enabled, and if new codec flag is not
735 // set.
736 const bool should_update_stats =
737 (enable_rtx_handling_ ||
738 static_cast<int32_t>(main_timestamp - timestamp_) >= 0) &&
739 !new_codec_;
740
741 auto relative_delay = controller_->PacketArrived(
742 last_cng_or_dtmf, packet_length_samples, should_update_stats,
743 main_sequence_number, main_timestamp, fs_hz_);
744 if (relative_delay) {
745 stats_->RelativePacketArrivalDelay(relative_delay.value());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000746 }
747 return 0;
748}
749
Ivo Creusen55de08e2018-09-03 11:49:27 +0200750int NetEqImpl::GetAudioInternal(AudioFrame* audio_frame,
751 bool* muted,
Ivo Creusen3ce44a32019-10-31 14:38:11 +0100752 absl::optional<Operation> action_override) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000753 PacketList packet_list;
754 DtmfEvent dtmf_event;
Ivo Creusen3ce44a32019-10-31 14:38:11 +0100755 Operation operation;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000756 bool play_dtmf;
henrik.lundin7a926812016-05-12 13:51:28 -0700757 *muted = false;
henrik.lundin114c1b32017-04-26 07:47:32 -0700758 last_decoded_timestamps_.clear();
Alessio Bazzica8f319a32019-07-24 16:47:02 +0000759 last_decoded_packet_infos_.clear();
henrik.lundined497212016-04-25 10:11:38 -0700760 tick_timer_->Increment();
Jakob Ivarsson44507082019-03-05 16:59:03 +0100761 stats_->IncreaseCounter(output_size_samples_, fs_hz_);
762 const auto lifetime_stats = stats_->GetLifetimeStatistics();
Henrik Lundin3ef3bfc2018-04-10 15:10:26 +0200763 expand_uma_logger_.UpdateSampleCounter(lifetime_stats.concealed_samples,
764 fs_hz_);
765 speech_expand_uma_logger_.UpdateSampleCounter(
Ivo Creusenbf4a2212019-04-24 14:06:24 +0200766 lifetime_stats.concealed_samples -
767 lifetime_stats.silent_concealed_samples,
768 fs_hz_);
henrik.lundin7a926812016-05-12 13:51:28 -0700769
770 // Check for muted state.
771 if (enable_muted_state_ && expand_->Muted() && packet_buffer_->Empty()) {
Ivo Creusen3ce44a32019-10-31 14:38:11 +0100772 RTC_DCHECK_EQ(last_mode_, Mode::kExpand);
henrik.lundina4491072017-07-06 05:23:53 -0700773 audio_frame->Reset();
774 RTC_DCHECK(audio_frame->muted()); // Reset() should mute the frame.
henrik.lundin7a926812016-05-12 13:51:28 -0700775 playout_timestamp_ += static_cast<uint32_t>(output_size_samples_);
776 audio_frame->sample_rate_hz_ = fs_hz_;
777 audio_frame->samples_per_channel_ = output_size_samples_;
778 audio_frame->timestamp_ =
779 first_packet_
780 ? 0
781 : timestamp_scaler_->ToExternal(playout_timestamp_) -
782 static_cast<uint32_t>(audio_frame->samples_per_channel_);
783 audio_frame->num_channels_ = sync_buffer_->Channels();
Jakob Ivarsson44507082019-03-05 16:59:03 +0100784 stats_->ExpandedNoiseSamples(output_size_samples_, false);
henrik.lundin7a926812016-05-12 13:51:28 -0700785 *muted = true;
786 return 0;
787 }
Ivo Creusen55de08e2018-09-03 11:49:27 +0200788 int return_value = GetDecision(&operation, &packet_list, &dtmf_event,
789 &play_dtmf, action_override);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000790 if (return_value != 0) {
Ivo Creusen3ce44a32019-10-31 14:38:11 +0100791 last_mode_ = Mode::kError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000792 return return_value;
793 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000794
795 AudioDecoder::SpeechType speech_type;
796 int length = 0;
Henrik Lundin18036282017-11-02 12:09:06 +0100797 const size_t start_num_packets = packet_list.size();
Yves Gerey665174f2018-06-19 15:03:05 +0200798 int decode_return_value =
799 Decode(&packet_list, &operation, &length, &speech_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000800
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000801 assert(vad_.get());
Ivo Creusen3ce44a32019-10-31 14:38:11 +0100802 bool sid_frame_available =
803 (operation == Operation::kRfc3389Cng && !packet_list.empty());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700804 vad_->Update(decoded_buffer_.get(), static_cast<size_t>(length), speech_type,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000805 sid_frame_available, fs_hz_);
806
Henrik Lundin18036282017-11-02 12:09:06 +0100807 // This is the criterion that we did decode some data through the speech
808 // decoder, and the operation resulted in comfort noise.
809 const bool codec_internal_sid_frame =
Henrik Lundin4f2a4a12018-01-26 17:32:56 +0100810 (speech_type == AudioDecoder::kComfortNoise &&
811 start_num_packets > packet_list.size());
Henrik Lundin18036282017-11-02 12:09:06 +0100812
813 if (sid_frame_available || codec_internal_sid_frame) {
henrik.lundinb1fb72b2016-05-03 08:18:47 -0700814 // Start a new stopwatch since we are decoding a new CNG packet.
815 generated_noise_stopwatch_ = tick_timer_->GetNewStopwatch();
816 }
817
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000818 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000819 switch (operation) {
Ivo Creusen3ce44a32019-10-31 14:38:11 +0100820 case Operation::kNormal: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000821 DoNormal(decoded_buffer_.get(), length, speech_type, play_dtmf);
Henrik Lundin2a8bd092019-04-26 09:47:07 +0200822 if (length > 0) {
823 stats_->DecodedOutputPlayed();
824 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000825 break;
826 }
Ivo Creusen3ce44a32019-10-31 14:38:11 +0100827 case Operation::kMerge: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000828 DoMerge(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000829 break;
830 }
Ivo Creusen3ce44a32019-10-31 14:38:11 +0100831 case Operation::kExpand: {
Henrik Lundin00eb12a2018-09-05 18:14:52 +0200832 RTC_DCHECK_EQ(return_value, 0);
833 if (!current_rtp_payload_type_ || !DoCodecPlc()) {
834 return_value = DoExpand(play_dtmf);
835 }
836 RTC_DCHECK_GE(sync_buffer_->FutureLength() - expand_->overlap_length(),
837 output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000838 break;
839 }
Ivo Creusen3ce44a32019-10-31 14:38:11 +0100840 case Operation::kAccelerate:
841 case Operation::kFastAccelerate: {
Henrik Lundincf808d22015-05-27 14:33:29 +0200842 const bool fast_accelerate =
Ivo Creusen3ce44a32019-10-31 14:38:11 +0100843 enable_fast_accelerate_ && (operation == Operation::kFastAccelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000844 return_value = DoAccelerate(decoded_buffer_.get(), length, speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +0200845 play_dtmf, fast_accelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000846 break;
847 }
Ivo Creusen3ce44a32019-10-31 14:38:11 +0100848 case Operation::kPreemptiveExpand: {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000849 return_value = DoPreemptiveExpand(decoded_buffer_.get(), length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000850 speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000851 break;
852 }
Ivo Creusen3ce44a32019-10-31 14:38:11 +0100853 case Operation::kRfc3389Cng:
854 case Operation::kRfc3389CngNoPacket: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000855 return_value = DoRfc3389Cng(&packet_list, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000856 break;
857 }
Ivo Creusen3ce44a32019-10-31 14:38:11 +0100858 case Operation::kCodecInternalCng: {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000859 // This handles the case when there is no transmission and the decoder
860 // should produce internal comfort noise.
861 // TODO(hlundin): Write test for codec-internal CNG.
minyuel6d92bf52015-09-23 15:20:39 +0200862 DoCodecInternalCng(decoded_buffer_.get(), length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000863 break;
864 }
Ivo Creusen3ce44a32019-10-31 14:38:11 +0100865 case Operation::kDtmf: {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000866 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000867 return_value = DoDtmf(dtmf_event, &play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000868 break;
869 }
Ivo Creusen3ce44a32019-10-31 14:38:11 +0100870 case Operation::kUndefined: {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100871 RTC_LOG(LS_ERROR) << "Invalid operation kUndefined.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000872 assert(false); // This should not happen.
Ivo Creusen3ce44a32019-10-31 14:38:11 +0100873 last_mode_ = Mode::kError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000874 return kInvalidOperation;
875 }
876 } // End of switch.
minyue5bd33972016-05-02 04:46:11 -0700877 last_operation_ = operation;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000878 if (return_value < 0) {
879 return return_value;
880 }
881
Ivo Creusen3ce44a32019-10-31 14:38:11 +0100882 if (last_mode_ != Mode::kRfc3389Cng) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000883 comfort_noise_->Reset();
884 }
885
Alessio Bazzica8f319a32019-07-24 16:47:02 +0000886 // We treat it as if all packets referenced to by |last_decoded_packet_infos_|
887 // were mashed together when creating the samples in |algorithm_buffer_|.
Minyue Lic759f832019-08-09 13:20:03 +0200888 RtpPacketInfos packet_infos(last_decoded_packet_infos_);
Alessio Bazzica8f319a32019-07-24 16:47:02 +0000889
890 // Copy samples from |algorithm_buffer_| to |sync_buffer_|.
891 //
892 // TODO(bugs.webrtc.org/10757):
893 // We would in the future also like to pass |packet_infos| so that we can do
894 // sample-perfect tracking of that information across |sync_buffer_|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000895 sync_buffer_->PushBack(*algorithm_buffer_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000896
897 // Extract data from |sync_buffer_| to |output|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000898 size_t num_output_samples_per_channel = output_size_samples_;
899 size_t num_output_samples = output_size_samples_ * sync_buffer_->Channels();
henrik.lundin6d8e0112016-03-04 10:34:21 -0800900 if (num_output_samples > AudioFrame::kMaxDataSizeSamples) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100901 RTC_LOG(LS_WARNING) << "Output array is too short. "
902 << AudioFrame::kMaxDataSizeSamples << " < "
903 << output_size_samples_ << " * "
904 << sync_buffer_->Channels();
henrik.lundin6d8e0112016-03-04 10:34:21 -0800905 num_output_samples = AudioFrame::kMaxDataSizeSamples;
906 num_output_samples_per_channel =
907 AudioFrame::kMaxDataSizeSamples / sync_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000908 }
henrik.lundin6d8e0112016-03-04 10:34:21 -0800909 sync_buffer_->GetNextAudioInterleaved(num_output_samples_per_channel,
910 audio_frame);
911 audio_frame->sample_rate_hz_ = fs_hz_;
Alessio Bazzica8f319a32019-07-24 16:47:02 +0000912 // TODO(bugs.webrtc.org/10757):
913 // We don't have the ability to properly track individual packets once their
914 // audio samples have entered |sync_buffer_|. So for now, treat it as if
915 // |packet_infos| from packets decoded by the current |GetAudioInternal()|
916 // call were all consumed assembling the current audio frame and the current
917 // audio frame only.
918 audio_frame->packet_infos_ = std::move(packet_infos);
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200919 if (sync_buffer_->FutureLength() < expand_->overlap_length()) {
920 // The sync buffer should always contain |overlap_length| samples, but now
921 // too many samples have been extracted. Reinstall the |overlap_length|
922 // lookahead by moving the index.
923 const size_t missing_lookahead_samples =
924 expand_->overlap_length() - sync_buffer_->FutureLength();
henrikg91d6ede2015-09-17 00:24:34 -0700925 RTC_DCHECK_GE(sync_buffer_->next_index(), missing_lookahead_samples);
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200926 sync_buffer_->set_next_index(sync_buffer_->next_index() -
927 missing_lookahead_samples);
928 }
henrik.lundin6d8e0112016-03-04 10:34:21 -0800929 if (audio_frame->samples_per_channel_ != output_size_samples_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100930 RTC_LOG(LS_ERROR) << "audio_frame->samples_per_channel_ ("
931 << audio_frame->samples_per_channel_
932 << ") != output_size_samples_ (" << output_size_samples_
933 << ")";
minyue@webrtc.orgdb1cefc2013-08-13 01:39:21 +0000934 // TODO(minyue): treatment of under-run, filling zeros
yujo36b1a5f2017-06-12 12:45:32 -0700935 audio_frame->Mute();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000936 return kSampleUnderrun;
937 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000938
939 // Should always have overlap samples left in the |sync_buffer_|.
henrikg91d6ede2015-09-17 00:24:34 -0700940 RTC_DCHECK_GE(sync_buffer_->FutureLength(), expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000941
yujo36b1a5f2017-06-12 12:45:32 -0700942 // TODO(yujo): For muted frames, this can be a copy rather than an addition.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000943 if (play_dtmf) {
yujo36b1a5f2017-06-12 12:45:32 -0700944 return_value = DtmfOverdub(dtmf_event, sync_buffer_->Channels(),
945 audio_frame->mutable_data());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000946 }
947
948 // Update the background noise parameters if last operation wrote data
949 // straight from the decoder to the |sync_buffer_|. That is, none of the
950 // operations that modify the signal can be followed by a parameter update.
Ivo Creusen3ce44a32019-10-31 14:38:11 +0100951 if ((last_mode_ == Mode::kNormal) || (last_mode_ == Mode::kAccelerateFail) ||
952 (last_mode_ == Mode::kPreemptiveExpandFail) ||
953 (last_mode_ == Mode::kRfc3389Cng) ||
954 (last_mode_ == Mode::kCodecInternalCng)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000955 background_noise_->Update(*sync_buffer_, *vad_.get());
956 }
957
Ivo Creusen3ce44a32019-10-31 14:38:11 +0100958 if (operation == Operation::kDtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000959 // DTMF data was written the end of |sync_buffer_|.
960 // Update index to end of DTMF data in |sync_buffer_|.
961 sync_buffer_->set_dtmf_index(sync_buffer_->Size());
962 }
963
Ivo Creusen3ce44a32019-10-31 14:38:11 +0100964 if (last_mode_ != Mode::kExpand && last_mode_ != Mode::kCodecPlc) {
henrik.lundin@webrtc.orged865b52014-03-06 10:28:07 +0000965 // If last operation was not expand, calculate the |playout_timestamp_| from
966 // the |sync_buffer_|. However, do not update the |playout_timestamp_| if it
967 // would be moved "backwards".
Yves Gerey665174f2018-06-19 15:03:05 +0200968 uint32_t temp_timestamp =
969 sync_buffer_->end_timestamp() -
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000970 static_cast<uint32_t>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000971 if (static_cast<int32_t>(temp_timestamp - playout_timestamp_) > 0) {
972 playout_timestamp_ = temp_timestamp;
973 }
974 } else {
975 // Use dead reckoning to estimate the |playout_timestamp_|.
Peter Kastingb7e50542015-06-11 12:55:50 -0700976 playout_timestamp_ += static_cast<uint32_t>(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000977 }
henrik.lundin15c51e32016-04-06 08:38:56 -0700978 // Set the timestamp in the audio frame to zero before the first packet has
979 // been inserted. Otherwise, subtract the frame size in samples to get the
980 // timestamp of the first sample in the frame (playout_timestamp_ is the
981 // last + 1).
982 audio_frame->timestamp_ =
983 first_packet_
984 ? 0
985 : timestamp_scaler_->ToExternal(playout_timestamp_) -
986 static_cast<uint32_t>(audio_frame->samples_per_channel_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000987
Ivo Creusen3ce44a32019-10-31 14:38:11 +0100988 if (!(last_mode_ == Mode::kRfc3389Cng ||
989 last_mode_ == Mode::kCodecInternalCng || last_mode_ == Mode::kExpand ||
990 last_mode_ == Mode::kCodecPlc)) {
henrik.lundinb1fb72b2016-05-03 08:18:47 -0700991 generated_noise_stopwatch_.reset();
992 }
993
Yves Gerey665174f2018-06-19 15:03:05 +0200994 if (decode_return_value)
995 return decode_return_value;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000996 return return_value;
997}
998
Ivo Creusen3ce44a32019-10-31 14:38:11 +0100999int NetEqImpl::GetDecision(Operation* operation,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001000 PacketList* packet_list,
1001 DtmfEvent* dtmf_event,
Ivo Creusen55de08e2018-09-03 11:49:27 +02001002 bool* play_dtmf,
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001003 absl::optional<Operation> action_override) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001004 // Initialize output variables.
1005 *play_dtmf = false;
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001006 *operation = Operation::kUndefined;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001007
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001008 assert(sync_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001009 uint32_t end_timestamp = sync_buffer_->end_timestamp();
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001010 if (!new_codec_) {
1011 const uint32_t five_seconds_samples = 5 * fs_hz_;
minyue-webrtcfae474c2017-07-05 11:17:40 +02001012 packet_buffer_->DiscardOldPackets(end_timestamp, five_seconds_samples,
Jakob Ivarsson44507082019-03-05 16:59:03 +01001013 stats_.get());
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001014 }
ossu7a377612016-10-18 04:06:13 -07001015 const Packet* packet = packet_buffer_->PeekNextPacket();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001016
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001017 RTC_DCHECK(!generated_noise_stopwatch_ ||
1018 generated_noise_stopwatch_->ElapsedTicks() >= 1);
1019 uint64_t generated_noise_samples =
Yves Gerey665174f2018-06-19 15:03:05 +02001020 generated_noise_stopwatch_ ? (generated_noise_stopwatch_->ElapsedTicks() -
1021 1) * output_size_samples_ +
Ivo Creusen53a31f72019-10-24 15:20:39 +02001022 controller_->noise_fast_forward()
Yves Gerey665174f2018-06-19 15:03:05 +02001023 : 0;
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001024
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001025 if (controller_->CngRfc3389On() || last_mode_ == Mode::kRfc3389Cng) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001026 // Because of timestamp peculiarities, we have to "manually" disallow using
1027 // a CNG packet with the same timestamp as the one that was last played.
1028 // This can happen when using redundancy and will cause the timing to shift.
ossu7a377612016-10-18 04:06:13 -07001029 while (packet && decoder_database_->IsComfortNoise(packet->payload_type) &&
1030 (end_timestamp >= packet->timestamp ||
1031 end_timestamp + generated_noise_samples > packet->timestamp)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001032 // Don't use this packet, discard it.
Jakob Ivarsson44507082019-03-05 16:59:03 +01001033 if (packet_buffer_->DiscardNextPacket(stats_.get()) !=
1034 PacketBuffer::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001035 assert(false); // Must be ok by design.
1036 }
1037 // Check buffer again.
1038 if (!new_codec_) {
Jakob Ivarsson44507082019-03-05 16:59:03 +01001039 packet_buffer_->DiscardOldPackets(end_timestamp, 5 * fs_hz_,
1040 stats_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001041 }
ossu7a377612016-10-18 04:06:13 -07001042 packet = packet_buffer_->PeekNextPacket();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001043 }
1044 }
1045
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001046 assert(expand_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001047 const int samples_left = static_cast<int>(sync_buffer_->FutureLength() -
Yves Gerey665174f2018-06-19 15:03:05 +02001048 expand_->overlap_length());
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001049 if (last_mode_ == Mode::kAccelerateSuccess ||
1050 last_mode_ == Mode::kAccelerateLowEnergy ||
1051 last_mode_ == Mode::kPreemptiveExpandSuccess ||
1052 last_mode_ == Mode::kPreemptiveExpandLowEnergy) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001053 // Subtract (samples_left + output_size_samples_) from sampleMemory.
Ivo Creusen53a31f72019-10-24 15:20:39 +02001054 controller_->AddSampleMemory(
kwibergd3edd772017-03-01 18:52:48 -08001055 -(samples_left + rtc::dchecked_cast<int>(output_size_samples_)));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001056 }
1057
1058 // Check if it is time to play a DTMF event.
Peter Kastingb7e50542015-06-11 12:55:50 -07001059 if (dtmf_buffer_->GetEvent(
Yves Gerey665174f2018-06-19 15:03:05 +02001060 static_cast<uint32_t>(end_timestamp + generated_noise_samples),
1061 dtmf_event)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001062 *play_dtmf = true;
1063 }
1064
1065 // Get instruction.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001066 assert(sync_buffer_.get());
1067 assert(expand_.get());
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001068 generated_noise_samples =
1069 generated_noise_stopwatch_
1070 ? generated_noise_stopwatch_->ElapsedTicks() * output_size_samples_ +
Ivo Creusen53a31f72019-10-24 15:20:39 +02001071 controller_->noise_fast_forward()
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001072 : 0;
Ivo Creusen53a31f72019-10-24 15:20:39 +02001073 NetEqController::NetEqStatus status;
1074 status.packet_buffer_info.dtx_or_cng =
1075 packet_buffer_->ContainsDtxOrCngPacket(decoder_database_.get());
1076 status.packet_buffer_info.num_samples =
1077 packet_buffer_->NumSamplesInBuffer(decoder_frame_length_);
1078 status.packet_buffer_info.span_samples = packet_buffer_->GetSpanSamples(
1079 decoder_frame_length_, last_output_sample_rate_hz_, true);
1080 status.packet_buffer_info.span_samples_no_dtx =
1081 packet_buffer_->GetSpanSamples(decoder_frame_length_,
1082 last_output_sample_rate_hz_, false);
1083 status.packet_buffer_info.num_packets = packet_buffer_->NumPacketsInBuffer();
1084 status.target_timestamp = sync_buffer_->end_timestamp();
1085 status.expand_mutefactor = expand_->MuteFactor(0);
1086 status.last_packet_samples = decoder_frame_length_;
1087 status.last_mode = last_mode_;
1088 status.play_dtmf = *play_dtmf;
1089 status.generated_noise_samples = generated_noise_samples;
Ivo Creusen88636c62020-01-24 11:04:56 +01001090 status.sync_buffer_samples = sync_buffer_->FutureLength();
Ivo Creusen53a31f72019-10-24 15:20:39 +02001091 if (packet) {
1092 status.next_packet = {
1093 packet->timestamp, packet->frame && packet->frame->IsDtxPacket(),
1094 decoder_database_->IsComfortNoise(packet->payload_type)};
1095 }
1096 *operation = controller_->GetDecision(status, &reset_decoder_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001097
Minyue Li54c66402019-04-15 14:29:27 +02001098 // Disallow time stretching if this packet is DTX, because such a decision may
1099 // be based on earlier buffer level estimate, as we do not update buffer level
1100 // during DTX. When we have a better way to update buffer level during DTX,
1101 // this can be discarded.
1102 if (packet && packet->frame && packet->frame->IsDtxPacket() &&
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001103 (*operation == Operation::kMerge ||
1104 *operation == Operation::kAccelerate ||
1105 *operation == Operation::kFastAccelerate ||
1106 *operation == Operation::kPreemptiveExpand)) {
1107 *operation = Operation::kNormal;
Minyue Li54c66402019-04-15 14:29:27 +02001108 }
1109
Ivo Creusen55de08e2018-09-03 11:49:27 +02001110 if (action_override) {
1111 // Use the provided action instead of the decision NetEq decided on.
1112 *operation = *action_override;
1113 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001114 // Check if we already have enough samples in the |sync_buffer_|. If so,
1115 // change decision to normal, unless the decision was merge, accelerate, or
1116 // preemptive expand.
kwibergd3edd772017-03-01 18:52:48 -08001117 if (samples_left >= rtc::dchecked_cast<int>(output_size_samples_) &&
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001118 *operation != Operation::kMerge && *operation != Operation::kAccelerate &&
1119 *operation != Operation::kFastAccelerate &&
1120 *operation != Operation::kPreemptiveExpand) {
1121 *operation = Operation::kNormal;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001122 return 0;
1123 }
1124
Ivo Creusen53a31f72019-10-24 15:20:39 +02001125 controller_->ExpandDecision(*operation);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001126
1127 // Check conditions for reset.
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001128 if (new_codec_ || *operation == Operation::kUndefined) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001129 // The only valid reason to get kUndefined is that new_codec_ is set.
1130 assert(new_codec_);
ossu7a377612016-10-18 04:06:13 -07001131 if (*play_dtmf && !packet) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001132 timestamp_ = dtmf_event->timestamp;
1133 } else {
ossu7a377612016-10-18 04:06:13 -07001134 if (!packet) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001135 RTC_LOG(LS_ERROR) << "Packet missing where it shouldn't.";
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001136 return -1;
1137 }
ossu7a377612016-10-18 04:06:13 -07001138 timestamp_ = packet->timestamp;
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001139 if (*operation == Operation::kRfc3389CngNoPacket &&
ossu7a377612016-10-18 04:06:13 -07001140 decoder_database_->IsComfortNoise(packet->payload_type)) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001141 // Change decision to CNG packet, since we do have a CNG packet, but it
1142 // was considered too early to use. Now, use it anyway.
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001143 *operation = Operation::kRfc3389Cng;
1144 } else if (*operation != Operation::kRfc3389Cng) {
1145 *operation = Operation::kNormal;
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001146 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001147 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001148 // Adjust |sync_buffer_| timestamp before setting |end_timestamp| to the
1149 // new value.
1150 sync_buffer_->IncreaseEndTimestamp(timestamp_ - end_timestamp);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001151 end_timestamp = timestamp_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001152 new_codec_ = false;
Ivo Creusen53a31f72019-10-24 15:20:39 +02001153 controller_->SoftReset();
Jakob Ivarsson44507082019-03-05 16:59:03 +01001154 stats_->ResetMcu();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001155 }
1156
Peter Kastingdce40cf2015-08-24 14:52:23 -07001157 size_t required_samples = output_size_samples_;
1158 const size_t samples_10_ms = static_cast<size_t>(80 * fs_mult_);
1159 const size_t samples_20_ms = 2 * samples_10_ms;
1160 const size_t samples_30_ms = 3 * samples_10_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001161
1162 switch (*operation) {
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001163 case Operation::kExpand: {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001164 timestamp_ = end_timestamp;
1165 return 0;
1166 }
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001167 case Operation::kRfc3389CngNoPacket:
1168 case Operation::kCodecInternalCng: {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001169 return 0;
1170 }
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001171 case Operation::kDtmf: {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001172 // TODO(hlundin): Write test for this.
1173 // Update timestamp.
1174 timestamp_ = end_timestamp;
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001175 const uint64_t generated_noise_samples =
1176 generated_noise_stopwatch_
1177 ? generated_noise_stopwatch_->ElapsedTicks() *
1178 output_size_samples_ +
Ivo Creusen53a31f72019-10-24 15:20:39 +02001179 controller_->noise_fast_forward()
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001180 : 0;
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001181 if (generated_noise_samples > 0 && last_mode_ != Mode::kDtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001182 // Make a jump in timestamp due to the recently played comfort noise.
Peter Kastingb7e50542015-06-11 12:55:50 -07001183 uint32_t timestamp_jump =
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001184 static_cast<uint32_t>(generated_noise_samples);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001185 sync_buffer_->IncreaseEndTimestamp(timestamp_jump);
1186 timestamp_ += timestamp_jump;
1187 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001188 return 0;
1189 }
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001190 case Operation::kAccelerate:
1191 case Operation::kFastAccelerate: {
Henrik Lundincf808d22015-05-27 14:33:29 +02001192 // In order to do an accelerate we need at least 30 ms of audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001193 if (samples_left >= static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001194 // Already have enough data, so we do not need to extract any more.
Ivo Creusen53a31f72019-10-24 15:20:39 +02001195 controller_->set_sample_memory(samples_left);
1196 controller_->set_prev_time_scale(true);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001197 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001198 } else if (samples_left >= static_cast<int>(samples_10_ms) &&
Yves Gerey665174f2018-06-19 15:03:05 +02001199 decoder_frame_length_ >= samples_30_ms) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001200 // Avoid decoding more data as it might overflow the playout buffer.
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001201 *operation = Operation::kNormal;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001202 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001203 } else if (samples_left < static_cast<int>(samples_20_ms) &&
Yves Gerey665174f2018-06-19 15:03:05 +02001204 decoder_frame_length_ < samples_30_ms) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001205 // Build up decoded data by decoding at least 20 ms of audio data. Do
1206 // not perform accelerate yet, but wait until we only need to do one
1207 // decoding.
1208 required_samples = 2 * output_size_samples_;
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001209 *operation = Operation::kNormal;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001210 }
1211 // If none of the above is true, we have one of two possible situations:
1212 // (1) 20 ms <= samples_left < 30 ms and decoder_frame_length_ < 30 ms; or
1213 // (2) samples_left < 10 ms and decoder_frame_length_ >= 30 ms.
1214 // In either case, we move on with the accelerate decision, and decode one
1215 // frame now.
1216 break;
1217 }
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001218 case Operation::kPreemptiveExpand: {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001219 // In order to do a preemptive expand we need at least 30 ms of decoded
1220 // audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001221 if ((samples_left >= static_cast<int>(samples_30_ms)) ||
1222 (samples_left >= static_cast<int>(samples_10_ms) &&
Yves Gerey665174f2018-06-19 15:03:05 +02001223 decoder_frame_length_ >= samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001224 // Already have enough data, so we do not need to extract any more.
1225 // Or, avoid decoding more data as it might overflow the playout buffer.
1226 // Still try preemptive expand, though.
Ivo Creusen53a31f72019-10-24 15:20:39 +02001227 controller_->set_sample_memory(samples_left);
1228 controller_->set_prev_time_scale(true);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001229 return 0;
1230 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07001231 if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001232 decoder_frame_length_ < samples_30_ms) {
1233 // Build up decoded data by decoding at least 20 ms of audio data.
1234 // Still try to perform preemptive expand.
1235 required_samples = 2 * output_size_samples_;
1236 }
1237 // Move on with the preemptive expand decision.
1238 break;
1239 }
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001240 case Operation::kMerge: {
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001241 required_samples =
1242 std::max(merge_->RequiredFutureSamples(), required_samples);
1243 break;
1244 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001245 default: {
1246 // Do nothing.
1247 }
1248 }
1249
1250 // Get packets from buffer.
1251 int extracted_samples = 0;
Henrik Lundin7687ad52018-07-02 10:14:46 +02001252 if (packet) {
ossu7a377612016-10-18 04:06:13 -07001253 sync_buffer_->IncreaseEndTimestamp(packet->timestamp - end_timestamp);
Ivo Creusen53a31f72019-10-24 15:20:39 +02001254 if (controller_->CngOff()) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001255 // Adjustment of timestamp only corresponds to an actual packet loss
1256 // if comfort noise is not played. If comfort noise was just played,
1257 // this adjustment of timestamp is only done to get back in sync with the
1258 // stream timestamp; no loss to report.
Jakob Ivarsson44507082019-03-05 16:59:03 +01001259 stats_->LostSamples(packet->timestamp - end_timestamp);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001260 }
1261
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001262 if (*operation != Operation::kRfc3389Cng) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001263 // We are about to decode and use a non-CNG packet.
Ivo Creusen53a31f72019-10-24 15:20:39 +02001264 controller_->SetCngOff();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001265 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001266
1267 extracted_samples = ExtractPackets(required_samples, packet_list);
1268 if (extracted_samples < 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001269 return kPacketBufferCorruption;
1270 }
1271 }
1272
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001273 if (*operation == Operation::kAccelerate ||
1274 *operation == Operation::kFastAccelerate ||
1275 *operation == Operation::kPreemptiveExpand) {
Ivo Creusen53a31f72019-10-24 15:20:39 +02001276 controller_->set_sample_memory(samples_left + extracted_samples);
1277 controller_->set_prev_time_scale(true);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001278 }
1279
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001280 if (*operation == Operation::kAccelerate ||
1281 *operation == Operation::kFastAccelerate) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001282 // Check that we have enough data (30ms) to do accelerate.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001283 if (extracted_samples + samples_left < static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001284 // TODO(hlundin): Write test for this.
1285 // Not enough, do normal operation instead.
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001286 *operation = Operation::kNormal;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001287 }
1288 }
1289
1290 timestamp_ = end_timestamp;
1291 return 0;
1292}
1293
Yves Gerey665174f2018-06-19 15:03:05 +02001294int NetEqImpl::Decode(PacketList* packet_list,
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001295 Operation* operation,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001296 int* decoded_length,
1297 AudioDecoder::SpeechType* speech_type) {
1298 *speech_type = AudioDecoder::kSpeech;
minyuel6d92bf52015-09-23 15:20:39 +02001299
1300 // When packet_list is empty, we may be in kCodecInternalCng mode, and for
1301 // that we use current active decoder.
1302 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1303
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001304 if (!packet_list->empty()) {
ossua73f6c92016-10-24 08:25:28 -07001305 const Packet& packet = packet_list->front();
1306 uint8_t payload_type = packet.payload_type;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001307 if (!decoder_database_->IsComfortNoise(payload_type)) {
1308 decoder = decoder_database_->GetDecoder(payload_type);
1309 assert(decoder);
1310 if (!decoder) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001311 RTC_LOG(LS_WARNING)
1312 << "Unknown payload type " << static_cast<int>(payload_type);
ossua73f6c92016-10-24 08:25:28 -07001313 packet_list->clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001314 return kDecoderNotFound;
1315 }
1316 bool decoder_changed;
1317 decoder_database_->SetActiveDecoder(payload_type, &decoder_changed);
1318 if (decoder_changed) {
1319 // We have a new decoder. Re-init some values.
Yves Gerey665174f2018-06-19 15:03:05 +02001320 const DecoderDatabase::DecoderInfo* decoder_info =
1321 decoder_database_->GetDecoderInfo(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001322 assert(decoder_info);
1323 if (!decoder_info) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001324 RTC_LOG(LS_WARNING)
1325 << "Unknown payload type " << static_cast<int>(payload_type);
ossua73f6c92016-10-24 08:25:28 -07001326 packet_list->clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001327 return kDecoderNotFound;
1328 }
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001329 // If sampling rate or number of channels has changed, we need to make
1330 // a reset.
kwibergc0f2dcf2016-05-31 06:28:03 -07001331 if (decoder_info->SampleRateHz() != fs_hz_ ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001332 decoder->Channels() != algorithm_buffer_->Channels()) {
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001333 // TODO(tlegrand): Add unittest to cover this event.
kwibergc0f2dcf2016-05-31 06:28:03 -07001334 SetSampleRateAndChannels(decoder_info->SampleRateHz(),
1335 decoder->Channels());
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001336 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001337 sync_buffer_->set_end_timestamp(timestamp_);
1338 playout_timestamp_ = timestamp_;
1339 }
1340 }
1341 }
1342
1343 if (reset_decoder_) {
1344 // TODO(hlundin): Write test for this.
Karl Wiberg43766482015-08-27 15:22:11 +02001345 if (decoder)
1346 decoder->Reset();
1347
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001348 // Reset comfort noise decoder.
ossu97ba30e2016-04-25 07:55:58 -07001349 ComfortNoiseDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02001350 if (cng_decoder)
1351 cng_decoder->Reset();
1352
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001353 reset_decoder_ = false;
1354 }
1355
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001356 *decoded_length = 0;
1357 // Update codec-internal PLC state.
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001358 if ((*operation == Operation::kMerge) && decoder && decoder->HasDecodePlc()) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001359 decoder->DecodePlc(1, &decoded_buffer_[*decoded_length]);
1360 }
1361
minyuel6d92bf52015-09-23 15:20:39 +02001362 int return_value;
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001363 if (*operation == Operation::kCodecInternalCng) {
minyuel6d92bf52015-09-23 15:20:39 +02001364 RTC_DCHECK(packet_list->empty());
1365 return_value = DecodeCng(decoder, decoded_length, speech_type);
1366 } else {
Yves Gerey665174f2018-06-19 15:03:05 +02001367 return_value = DecodeLoop(packet_list, *operation, decoder, decoded_length,
1368 speech_type);
minyuel6d92bf52015-09-23 15:20:39 +02001369 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001370
1371 if (*decoded_length < 0) {
1372 // Error returned from the decoder.
1373 *decoded_length = 0;
Peter Kastingb7e50542015-06-11 12:55:50 -07001374 sync_buffer_->IncreaseEndTimestamp(
1375 static_cast<uint32_t>(decoder_frame_length_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001376 int error_code = 0;
1377 if (decoder)
1378 error_code = decoder->ErrorCode();
1379 if (error_code != 0) {
1380 // Got some error code from the decoder.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001381 return_value = kDecoderErrorCode;
Mirko Bonadei675513b2017-11-09 11:09:25 +01001382 RTC_LOG(LS_WARNING) << "Decoder returned error code: " << error_code;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001383 } else {
1384 // Decoder does not implement error codes. Return generic error.
1385 return_value = kOtherDecoderError;
Mirko Bonadei675513b2017-11-09 11:09:25 +01001386 RTC_LOG(LS_WARNING) << "Decoder error (no error code)";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001387 }
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001388 *operation = Operation::kExpand; // Do expansion to get data instead.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001389 }
1390 if (*speech_type != AudioDecoder::kComfortNoise) {
1391 // Don't increment timestamp if codec returned CNG speech type
1392 // since in this case, the we will increment the CNGplayedTS counter.
1393 // Increase with number of samples per channel.
1394 assert(*decoded_length == 0 ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001395 (decoder && decoder->Channels() == sync_buffer_->Channels()));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001396 sync_buffer_->IncreaseEndTimestamp(
1397 *decoded_length / static_cast<int>(sync_buffer_->Channels()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001398 }
1399 return return_value;
1400}
1401
Yves Gerey665174f2018-06-19 15:03:05 +02001402int NetEqImpl::DecodeCng(AudioDecoder* decoder,
1403 int* decoded_length,
minyuel6d92bf52015-09-23 15:20:39 +02001404 AudioDecoder::SpeechType* speech_type) {
1405 if (!decoder) {
1406 // This happens when active decoder is not defined.
1407 *decoded_length = -1;
1408 return 0;
1409 }
1410
kwibergd3edd772017-03-01 18:52:48 -08001411 while (*decoded_length < rtc::dchecked_cast<int>(output_size_samples_)) {
minyuel6d92bf52015-09-23 15:20:39 +02001412 const int length = decoder->Decode(
Yves Gerey665174f2018-06-19 15:03:05 +02001413 nullptr, 0, fs_hz_,
1414 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1415 &decoded_buffer_[*decoded_length], speech_type);
minyuel6d92bf52015-09-23 15:20:39 +02001416 if (length > 0) {
1417 *decoded_length += length;
minyuel6d92bf52015-09-23 15:20:39 +02001418 } else {
1419 // Error.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001420 RTC_LOG(LS_WARNING) << "Failed to decode CNG";
minyuel6d92bf52015-09-23 15:20:39 +02001421 *decoded_length = -1;
1422 break;
1423 }
1424 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1425 // Guard against overflow.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001426 RTC_LOG(LS_WARNING) << "Decoded too much CNG.";
minyuel6d92bf52015-09-23 15:20:39 +02001427 return kDecodedTooMuch;
1428 }
1429 }
1430 return 0;
1431}
1432
Yves Gerey665174f2018-06-19 15:03:05 +02001433int NetEqImpl::DecodeLoop(PacketList* packet_list,
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001434 const Operation& operation,
Yves Gerey665174f2018-06-19 15:03:05 +02001435 AudioDecoder* decoder,
1436 int* decoded_length,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001437 AudioDecoder::SpeechType* speech_type) {
henrik.lundin114c1b32017-04-26 07:47:32 -07001438 RTC_DCHECK(last_decoded_timestamps_.empty());
Alessio Bazzica8f319a32019-07-24 16:47:02 +00001439 RTC_DCHECK(last_decoded_packet_infos_.empty());
henrik.lundin114c1b32017-04-26 07:47:32 -07001440
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001441 // Do decoding.
Yves Gerey665174f2018-06-19 15:03:05 +02001442 while (!packet_list->empty() && !decoder_database_->IsComfortNoise(
1443 packet_list->front().payload_type)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001444 assert(decoder); // At this point, we must have a decoder object.
1445 // The number of channels in the |sync_buffer_| should be the same as the
1446 // number decoder channels.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001447 assert(sync_buffer_->Channels() == decoder->Channels());
1448 assert(decoded_buffer_length_ >= kMaxFrameSize * decoder->Channels());
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001449 assert(operation == Operation::kNormal ||
1450 operation == Operation::kAccelerate ||
1451 operation == Operation::kFastAccelerate ||
1452 operation == Operation::kMerge ||
1453 operation == Operation::kPreemptiveExpand);
ossua73f6c92016-10-24 08:25:28 -07001454
1455 auto opt_result = packet_list->front().frame->Decode(
ossu61a208b2016-09-20 01:38:00 -07001456 rtc::ArrayView<int16_t>(&decoded_buffer_[*decoded_length],
1457 decoded_buffer_length_ - *decoded_length));
henrik.lundin114c1b32017-04-26 07:47:32 -07001458 last_decoded_timestamps_.push_back(packet_list->front().timestamp);
Alessio Bazzica8f319a32019-07-24 16:47:02 +00001459 last_decoded_packet_infos_.push_back(
1460 std::move(packet_list->front().packet_info));
ossua73f6c92016-10-24 08:25:28 -07001461 packet_list->pop_front();
ossu61a208b2016-09-20 01:38:00 -07001462 if (opt_result) {
1463 const auto& result = *opt_result;
1464 *speech_type = result.speech_type;
1465 if (result.num_decoded_samples > 0) {
kwibergd3edd772017-03-01 18:52:48 -08001466 *decoded_length += rtc::dchecked_cast<int>(result.num_decoded_samples);
ossu61a208b2016-09-20 01:38:00 -07001467 // Update |decoder_frame_length_| with number of samples per channel.
1468 decoder_frame_length_ =
1469 result.num_decoded_samples / decoder->Channels();
1470 }
1471 } else {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001472 // Error.
ossu61a208b2016-09-20 01:38:00 -07001473 // TODO(ossu): What to put here?
Mirko Bonadei675513b2017-11-09 11:09:25 +01001474 RTC_LOG(LS_WARNING) << "Decode error";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001475 *decoded_length = -1;
Alessio Bazzica8f319a32019-07-24 16:47:02 +00001476 last_decoded_packet_infos_.clear();
ossua73f6c92016-10-24 08:25:28 -07001477 packet_list->clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001478 break;
1479 }
kwibergd3edd772017-03-01 18:52:48 -08001480 if (*decoded_length > rtc::dchecked_cast<int>(decoded_buffer_length_)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001481 // Guard against overflow.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001482 RTC_LOG(LS_WARNING) << "Decoded too much.";
ossua73f6c92016-10-24 08:25:28 -07001483 packet_list->clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001484 return kDecodedTooMuch;
1485 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001486 } // End of decode loop.
1487
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001488 // If the list is not empty at this point, either a decoding error terminated
1489 // the while-loop, or list must hold exactly one CNG packet.
Yves Gerey665174f2018-06-19 15:03:05 +02001490 assert(packet_list->empty() || *decoded_length < 0 ||
1491 (packet_list->size() == 1 && decoder_database_->IsComfortNoise(
1492 packet_list->front().payload_type)));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001493 return 0;
1494}
1495
Yves Gerey665174f2018-06-19 15:03:05 +02001496void NetEqImpl::DoNormal(const int16_t* decoded_buffer,
1497 size_t decoded_length,
1498 AudioDecoder::SpeechType speech_type,
1499 bool play_dtmf) {
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001500 assert(normal_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001501 normal_->Process(decoded_buffer, decoded_length, last_mode_,
Henrik Lundin6dc82e82018-05-22 10:40:23 +02001502 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001503 if (decoded_length != 0) {
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001504 last_mode_ = Mode::kNormal;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001505 }
1506
1507 // If last packet was decoded as an inband CNG, set mode to CNG instead.
Yves Gerey665174f2018-06-19 15:03:05 +02001508 if ((speech_type == AudioDecoder::kComfortNoise) ||
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001509 ((last_mode_ == Mode::kCodecInternalCng) && (decoded_length == 0))) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001510 // TODO(hlundin): Remove second part of || statement above.
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001511 last_mode_ = Mode::kCodecInternalCng;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001512 }
1513
1514 if (!play_dtmf) {
1515 dtmf_tone_generator_->Reset();
1516 }
1517}
1518
Yves Gerey665174f2018-06-19 15:03:05 +02001519void NetEqImpl::DoMerge(int16_t* decoded_buffer,
1520 size_t decoded_length,
1521 AudioDecoder::SpeechType speech_type,
1522 bool play_dtmf) {
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001523 assert(merge_.get());
Yves Gerey665174f2018-06-19 15:03:05 +02001524 size_t new_length =
1525 merge_->Process(decoded_buffer, decoded_length, algorithm_buffer_.get());
henrik.lundin2979f552017-05-05 05:04:16 -07001526 // Correction can be negative.
1527 int expand_length_correction =
1528 rtc::dchecked_cast<int>(new_length) -
1529 rtc::dchecked_cast<int>(decoded_length / algorithm_buffer_->Channels());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001530
1531 // Update in-call and post-call statistics.
1532 if (expand_->MuteFactor(0) == 0) {
1533 // Expand generates only noise.
Jakob Ivarsson44507082019-03-05 16:59:03 +01001534 stats_->ExpandedNoiseSamplesCorrection(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001535 } else {
1536 // Expansion generates more than only noise.
Jakob Ivarsson44507082019-03-05 16:59:03 +01001537 stats_->ExpandedVoiceSamplesCorrection(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001538 }
1539
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001540 last_mode_ = Mode::kMerge;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001541 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1542 if (speech_type == AudioDecoder::kComfortNoise) {
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001543 last_mode_ = Mode::kCodecInternalCng;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001544 }
1545 expand_->Reset();
1546 if (!play_dtmf) {
1547 dtmf_tone_generator_->Reset();
1548 }
1549}
1550
Henrik Lundin00eb12a2018-09-05 18:14:52 +02001551bool NetEqImpl::DoCodecPlc() {
1552 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1553 if (!decoder) {
1554 return false;
1555 }
1556 const size_t channels = algorithm_buffer_->Channels();
1557 const size_t requested_samples_per_channel =
1558 output_size_samples_ -
1559 (sync_buffer_->FutureLength() - expand_->overlap_length());
1560 concealment_audio_.Clear();
1561 decoder->GeneratePlc(requested_samples_per_channel, &concealment_audio_);
1562 if (concealment_audio_.empty()) {
1563 // Nothing produced. Resort to regular expand.
1564 return false;
1565 }
1566 RTC_CHECK_GE(concealment_audio_.size(),
1567 requested_samples_per_channel * channels);
1568 sync_buffer_->PushBackInterleaved(concealment_audio_);
1569 RTC_DCHECK_NE(algorithm_buffer_->Channels(), 0);
1570 const size_t concealed_samples_per_channel =
1571 concealment_audio_.size() / channels;
1572
1573 // Update in-call and post-call statistics.
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001574 const bool is_new_concealment_event = (last_mode_ != Mode::kCodecPlc);
Henrik Lundin00eb12a2018-09-05 18:14:52 +02001575 if (std::all_of(concealment_audio_.cbegin(), concealment_audio_.cend(),
1576 [](int16_t i) { return i == 0; })) {
1577 // Expand operation generates only noise.
Jakob Ivarsson44507082019-03-05 16:59:03 +01001578 stats_->ExpandedNoiseSamples(concealed_samples_per_channel,
1579 is_new_concealment_event);
Henrik Lundin00eb12a2018-09-05 18:14:52 +02001580 } else {
1581 // Expand operation generates more than only noise.
Jakob Ivarsson44507082019-03-05 16:59:03 +01001582 stats_->ExpandedVoiceSamples(concealed_samples_per_channel,
1583 is_new_concealment_event);
Henrik Lundin00eb12a2018-09-05 18:14:52 +02001584 }
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001585 last_mode_ = Mode::kCodecPlc;
Henrik Lundin00eb12a2018-09-05 18:14:52 +02001586 if (!generated_noise_stopwatch_) {
1587 // Start a new stopwatch since we may be covering for a lost CNG packet.
1588 generated_noise_stopwatch_ = tick_timer_->GetNewStopwatch();
1589 }
1590 return true;
1591}
1592
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001593int NetEqImpl::DoExpand(bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001594 while ((sync_buffer_->FutureLength() - expand_->overlap_length()) <
Yves Gerey665174f2018-06-19 15:03:05 +02001595 output_size_samples_) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001596 algorithm_buffer_->Clear();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001597 int return_value = expand_->Process(algorithm_buffer_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001598 size_t length = algorithm_buffer_->Size();
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001599 bool is_new_concealment_event = (last_mode_ != Mode::kExpand);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001600
1601 // Update in-call and post-call statistics.
1602 if (expand_->MuteFactor(0) == 0) {
1603 // Expand operation generates only noise.
Jakob Ivarsson44507082019-03-05 16:59:03 +01001604 stats_->ExpandedNoiseSamples(length, is_new_concealment_event);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001605 } else {
1606 // Expand operation generates more than only noise.
Jakob Ivarsson44507082019-03-05 16:59:03 +01001607 stats_->ExpandedVoiceSamples(length, is_new_concealment_event);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001608 }
1609
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001610 last_mode_ = Mode::kExpand;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001611
1612 if (return_value < 0) {
1613 return return_value;
1614 }
1615
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001616 sync_buffer_->PushBack(*algorithm_buffer_);
1617 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001618 }
1619 if (!play_dtmf) {
1620 dtmf_tone_generator_->Reset();
1621 }
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001622
1623 if (!generated_noise_stopwatch_) {
1624 // Start a new stopwatch since we may be covering for a lost CNG packet.
1625 generated_noise_stopwatch_ = tick_timer_->GetNewStopwatch();
1626 }
1627
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001628 return 0;
1629}
1630
Henrik Lundincf808d22015-05-27 14:33:29 +02001631int NetEqImpl::DoAccelerate(int16_t* decoded_buffer,
1632 size_t decoded_length,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001633 AudioDecoder::SpeechType speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +02001634 bool play_dtmf,
1635 bool fast_accelerate) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001636 const size_t required_samples =
1637 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001638 size_t borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001639 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001640 size_t decoded_length_per_channel = decoded_length / num_channels;
1641 if (decoded_length_per_channel < required_samples) {
1642 // Must move data from the |sync_buffer_| in order to get 30 ms.
Yves Gerey665174f2018-06-19 15:03:05 +02001643 borrowed_samples_per_channel =
1644 static_cast<int>(required_samples - decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001645 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
Yves Gerey665174f2018-06-19 15:03:05 +02001646 decoded_buffer, sizeof(int16_t) * decoded_length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001647 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1648 decoded_buffer);
1649 decoded_length = required_samples * num_channels;
1650 }
1651
Peter Kastingdce40cf2015-08-24 14:52:23 -07001652 size_t samples_removed;
Henrik Lundincf808d22015-05-27 14:33:29 +02001653 Accelerate::ReturnCodes return_code =
1654 accelerate_->Process(decoded_buffer, decoded_length, fast_accelerate,
1655 algorithm_buffer_.get(), &samples_removed);
Jakob Ivarsson44507082019-03-05 16:59:03 +01001656 stats_->AcceleratedSamples(samples_removed);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001657 switch (return_code) {
1658 case Accelerate::kSuccess:
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001659 last_mode_ = Mode::kAccelerateSuccess;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001660 break;
1661 case Accelerate::kSuccessLowEnergy:
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001662 last_mode_ = Mode::kAccelerateLowEnergy;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001663 break;
1664 case Accelerate::kNoStretch:
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001665 last_mode_ = Mode::kAccelerateFail;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001666 break;
1667 case Accelerate::kError:
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001668 // TODO(hlundin): Map to Modes::kError instead?
1669 last_mode_ = Mode::kAccelerateFail;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001670 return kAccelerateError;
1671 }
1672
1673 if (borrowed_samples_per_channel > 0) {
1674 // Copy borrowed samples back to the |sync_buffer_|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001675 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001676 if (length < borrowed_samples_per_channel) {
1677 // This destroys the beginning of the buffer, but will not cause any
1678 // problems.
Yves Gerey665174f2018-06-19 15:03:05 +02001679 sync_buffer_->ReplaceAtIndex(
1680 *algorithm_buffer_,
1681 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001682 sync_buffer_->PushFrontZeros(borrowed_samples_per_channel - length);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001683 algorithm_buffer_->PopFront(length);
1684 assert(algorithm_buffer_->Empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001685 } else {
Yves Gerey665174f2018-06-19 15:03:05 +02001686 sync_buffer_->ReplaceAtIndex(
1687 *algorithm_buffer_, borrowed_samples_per_channel,
1688 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001689 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001690 }
1691 }
1692
1693 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1694 if (speech_type == AudioDecoder::kComfortNoise) {
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001695 last_mode_ = Mode::kCodecInternalCng;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001696 }
1697 if (!play_dtmf) {
1698 dtmf_tone_generator_->Reset();
1699 }
1700 expand_->Reset();
1701 return 0;
1702}
1703
1704int NetEqImpl::DoPreemptiveExpand(int16_t* decoded_buffer,
1705 size_t decoded_length,
1706 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001707 bool play_dtmf) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001708 const size_t required_samples =
1709 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001710 size_t num_channels = algorithm_buffer_->Channels();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001711 size_t borrowed_samples_per_channel = 0;
1712 size_t old_borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001713 size_t decoded_length_per_channel = decoded_length / num_channels;
1714 if (decoded_length_per_channel < required_samples) {
1715 // Must move data from the |sync_buffer_| in order to get 30 ms.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001716 borrowed_samples_per_channel =
1717 required_samples - decoded_length_per_channel;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001718 // Calculate how many of these were already played out.
Peter Kastingf045e4d2015-06-10 21:15:38 -07001719 old_borrowed_samples_per_channel =
Yves Gerey665174f2018-06-19 15:03:05 +02001720 (borrowed_samples_per_channel > sync_buffer_->FutureLength())
1721 ? (borrowed_samples_per_channel - sync_buffer_->FutureLength())
1722 : 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001723 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
Yves Gerey665174f2018-06-19 15:03:05 +02001724 decoded_buffer, sizeof(int16_t) * decoded_length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001725 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1726 decoded_buffer);
1727 decoded_length = required_samples * num_channels;
1728 }
1729
Peter Kastingdce40cf2015-08-24 14:52:23 -07001730 size_t samples_added;
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001731 PreemptiveExpand::ReturnCodes return_code = preemptive_expand_->Process(
Yves Gerey665174f2018-06-19 15:03:05 +02001732 decoded_buffer, decoded_length, old_borrowed_samples_per_channel,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001733 algorithm_buffer_.get(), &samples_added);
Jakob Ivarsson44507082019-03-05 16:59:03 +01001734 stats_->PreemptiveExpandedSamples(samples_added);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001735 switch (return_code) {
1736 case PreemptiveExpand::kSuccess:
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001737 last_mode_ = Mode::kPreemptiveExpandSuccess;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001738 break;
1739 case PreemptiveExpand::kSuccessLowEnergy:
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001740 last_mode_ = Mode::kPreemptiveExpandLowEnergy;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001741 break;
1742 case PreemptiveExpand::kNoStretch:
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001743 last_mode_ = Mode::kPreemptiveExpandFail;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001744 break;
1745 case PreemptiveExpand::kError:
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001746 // TODO(hlundin): Map to Modes::kError instead?
1747 last_mode_ = Mode::kPreemptiveExpandFail;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001748 return kPreemptiveExpandError;
1749 }
1750
1751 if (borrowed_samples_per_channel > 0) {
1752 // Copy borrowed samples back to the |sync_buffer_|.
1753 sync_buffer_->ReplaceAtIndex(
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001754 *algorithm_buffer_, borrowed_samples_per_channel,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001755 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001756 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001757 }
1758
1759 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1760 if (speech_type == AudioDecoder::kComfortNoise) {
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001761 last_mode_ = Mode::kCodecInternalCng;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001762 }
1763 if (!play_dtmf) {
1764 dtmf_tone_generator_->Reset();
1765 }
1766 expand_->Reset();
1767 return 0;
1768}
1769
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001770int NetEqImpl::DoRfc3389Cng(PacketList* packet_list, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001771 if (!packet_list->empty()) {
1772 // Must have exactly one SID frame at this point.
1773 assert(packet_list->size() == 1);
ossua73f6c92016-10-24 08:25:28 -07001774 const Packet& packet = packet_list->front();
1775 if (!decoder_database_->IsComfortNoise(packet.payload_type)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001776 RTC_LOG(LS_ERROR) << "Trying to decode non-CNG payload as CNG.";
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001777 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001778 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001779 if (comfort_noise_->UpdateParameters(packet) ==
1780 ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001781 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001782 return -comfort_noise_->internal_error_code();
1783 }
1784 }
Yves Gerey665174f2018-06-19 15:03:05 +02001785 int cn_return =
1786 comfort_noise_->Generate(output_size_samples_, algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001787 expand_->Reset();
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001788 last_mode_ = Mode::kRfc3389Cng;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001789 if (!play_dtmf) {
1790 dtmf_tone_generator_->Reset();
1791 }
1792 if (cn_return == ComfortNoise::kInternalError) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001793 RTC_LOG(LS_WARNING) << "Comfort noise generator returned error code: "
1794 << comfort_noise_->internal_error_code();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001795 return kComfortNoiseErrorCode;
1796 } else if (cn_return == ComfortNoise::kUnknownPayloadType) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001797 return kUnknownRtpPayloadType;
1798 }
1799 return 0;
1800}
1801
minyuel6d92bf52015-09-23 15:20:39 +02001802void NetEqImpl::DoCodecInternalCng(const int16_t* decoded_buffer,
1803 size_t decoded_length) {
1804 RTC_DCHECK(normal_.get());
minyuel6d92bf52015-09-23 15:20:39 +02001805 normal_->Process(decoded_buffer, decoded_length, last_mode_,
Henrik Lundin6dc82e82018-05-22 10:40:23 +02001806 algorithm_buffer_.get());
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001807 last_mode_ = Mode::kCodecInternalCng;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001808 expand_->Reset();
1809}
1810
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001811int NetEqImpl::DoDtmf(const DtmfEvent& dtmf_event, bool* play_dtmf) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001812 // This block of the code and the block further down, handling |dtmf_switch|
1813 // are commented out. Otherwise playing out-of-band DTMF would fail in VoE
1814 // test, DtmfTest.ManualSuccessfullySendsOutOfBandTelephoneEvents. This is
1815 // equivalent to |dtmf_switch| always be false.
1816 //
1817 // See http://webrtc-codereview.appspot.com/1195004/ for discussion
1818 // On this issue. This change might cause some glitches at the point of
1819 // switch from audio to DTMF. Issue 1545 is filed to track this.
1820 //
1821 // bool dtmf_switch = false;
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001822 // if ((last_mode_ != Modes::kDtmf) &&
1823 // dtmf_tone_generator_->initialized()) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001824 // // Special case; see below.
1825 // // We must catch this before calling Generate, since |initialized| is
1826 // // modified in that call.
1827 // dtmf_switch = true;
1828 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001829
1830 int dtmf_return_value = 0;
1831 if (!dtmf_tone_generator_->initialized()) {
1832 // Initialize if not already done.
1833 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1834 dtmf_event.volume);
1835 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001836
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001837 if (dtmf_return_value == 0) {
1838 // Generate DTMF signal.
1839 dtmf_return_value = dtmf_tone_generator_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001840 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001841 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001842
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001843 if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001844 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001845 return dtmf_return_value;
1846 }
1847
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001848 // if (dtmf_switch) {
1849 // // This is the special case where the previous operation was DTMF
1850 // // overdub, but the current instruction is "regular" DTMF. We must make
1851 // // sure that the DTMF does not have any discontinuities. The first DTMF
1852 // // sample that we generate now must be played out immediately, therefore
1853 // // it must be copied to the speech buffer.
1854 // // TODO(hlundin): This code seems incorrect. (Legacy.) Write test and
1855 // // verify correct operation.
1856 // assert(false);
1857 // // Must generate enough data to replace all of the |sync_buffer_|
1858 // // "future".
1859 // int required_length = sync_buffer_->FutureLength();
1860 // assert(dtmf_tone_generator_->initialized());
1861 // dtmf_return_value = dtmf_tone_generator_->Generate(required_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001862 // algorithm_buffer_);
1863 // assert((size_t) required_length == algorithm_buffer_->Size());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001864 // if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001865 // algorithm_buffer_->Zeros(output_size_samples_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001866 // return dtmf_return_value;
1867 // }
1868 //
1869 // // Overwrite the "future" part of the speech buffer with the new DTMF
1870 // // data.
1871 // // TODO(hlundin): It seems that this overwriting has gone lost.
1872 // // Not adapted for multi-channel yet.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001873 // assert(algorithm_buffer_->Channels() == 1);
1874 // if (algorithm_buffer_->Channels() != 1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001875 // RTC_LOG(LS_WARNING) << "DTMF not supported for more than one channel";
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001876 // return kStereoNotSupported;
1877 // }
1878 // // Shuffle the remaining data to the beginning of algorithm buffer.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001879 // algorithm_buffer_->PopFront(sync_buffer_->FutureLength());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001880 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001881
Peter Kastingb7e50542015-06-11 12:55:50 -07001882 sync_buffer_->IncreaseEndTimestamp(
1883 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001884 expand_->Reset();
Ivo Creusen3ce44a32019-10-31 14:38:11 +01001885 last_mode_ = Mode::kDtmf;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001886
1887 // Set to false because the DTMF is already in the algorithm buffer.
1888 *play_dtmf = false;
1889 return 0;
1890}
1891
Yves Gerey665174f2018-06-19 15:03:05 +02001892int NetEqImpl::DtmfOverdub(const DtmfEvent& dtmf_event,
1893 size_t num_channels,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001894 int16_t* output) const {
1895 size_t out_index = 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001896 size_t overdub_length = output_size_samples_; // Default value.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001897
1898 if (sync_buffer_->dtmf_index() > sync_buffer_->next_index()) {
1899 // Special operation for transition from "DTMF only" to "DTMF overdub".
Yves Gerey665174f2018-06-19 15:03:05 +02001900 out_index =
1901 std::min(sync_buffer_->dtmf_index() - sync_buffer_->next_index(),
1902 output_size_samples_);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001903 overdub_length = output_size_samples_ - out_index;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001904 }
1905
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001906 AudioMultiVector dtmf_output(num_channels);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001907 int dtmf_return_value = 0;
1908 if (!dtmf_tone_generator_->initialized()) {
1909 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1910 dtmf_event.volume);
1911 }
1912 if (dtmf_return_value == 0) {
Yves Gerey665174f2018-06-19 15:03:05 +02001913 dtmf_return_value =
1914 dtmf_tone_generator_->Generate(overdub_length, &dtmf_output);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001915 assert(overdub_length == dtmf_output.Size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001916 }
1917 dtmf_output.ReadInterleaved(overdub_length, &output[out_index]);
1918 return dtmf_return_value < 0 ? dtmf_return_value : 0;
1919}
1920
Peter Kastingdce40cf2015-08-24 14:52:23 -07001921int NetEqImpl::ExtractPackets(size_t required_samples,
1922 PacketList* packet_list) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001923 bool first_packet = true;
1924 uint8_t prev_payload_type = 0;
1925 uint32_t prev_timestamp = 0;
1926 uint16_t prev_sequence_number = 0;
1927 bool next_packet_available = false;
1928
ossu7a377612016-10-18 04:06:13 -07001929 const Packet* next_packet = packet_buffer_->PeekNextPacket();
1930 RTC_DCHECK(next_packet);
1931 if (!next_packet) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001932 RTC_LOG(LS_ERROR) << "Packet buffer unexpectedly empty.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001933 return -1;
1934 }
ossu7a377612016-10-18 04:06:13 -07001935 uint32_t first_timestamp = next_packet->timestamp;
ossu61a208b2016-09-20 01:38:00 -07001936 size_t extracted_samples = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001937
1938 // Packet extraction loop.
1939 do {
ossu7a377612016-10-18 04:06:13 -07001940 timestamp_ = next_packet->timestamp;
Danil Chapovalovb6021232018-06-19 13:26:36 +02001941 absl::optional<Packet> packet = packet_buffer_->GetNextPacket();
ossu7a377612016-10-18 04:06:13 -07001942 // |next_packet| may be invalid after the |packet_buffer_| operation.
ossua73f6c92016-10-24 08:25:28 -07001943 next_packet = nullptr;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001944 if (!packet) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001945 RTC_LOG(LS_ERROR) << "Should always be able to extract a packet here";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001946 assert(false); // Should always be able to extract a packet here.
1947 return -1;
1948 }
Gustaf Ullbergb0a02072017-10-02 12:00:34 +02001949 const uint64_t waiting_time_ms = packet->waiting_time->ElapsedMs();
Jakob Ivarsson44507082019-03-05 16:59:03 +01001950 stats_->StoreWaitingTime(waiting_time_ms);
ossu61a208b2016-09-20 01:38:00 -07001951 RTC_DCHECK(!packet->empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001952
1953 if (first_packet) {
1954 first_packet = false;
henrik.lundin48ed9302015-10-29 05:36:24 -07001955 if (nack_enabled_) {
1956 RTC_DCHECK(nack_);
1957 // TODO(henrik.lundin): Should we update this for all decoded packets?
ossu7a377612016-10-18 04:06:13 -07001958 nack_->UpdateLastDecodedPacket(packet->sequence_number,
1959 packet->timestamp);
henrik.lundin48ed9302015-10-29 05:36:24 -07001960 }
ossu7a377612016-10-18 04:06:13 -07001961 prev_sequence_number = packet->sequence_number;
1962 prev_timestamp = packet->timestamp;
1963 prev_payload_type = packet->payload_type;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001964 }
1965
ossucafb4972017-01-02 07:00:50 -08001966 const bool has_cng_packet =
1967 decoder_database_->IsComfortNoise(packet->payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001968 // Store number of extracted samples.
ossu61a208b2016-09-20 01:38:00 -07001969 size_t packet_duration = 0;
1970 if (packet->frame) {
1971 packet_duration = packet->frame->Duration();
ossua70695a2016-09-22 02:06:28 -07001972 // TODO(ossu): Is this the correct way to track Opus FEC packets?
1973 if (packet->priority.codec_level > 0) {
Jakob Ivarsson44507082019-03-05 16:59:03 +01001974 stats_->SecondaryDecodedSamples(
kwibergd3edd772017-03-01 18:52:48 -08001975 rtc::dchecked_cast<int>(packet_duration));
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001976 }
ossucafb4972017-01-02 07:00:50 -08001977 } else if (!has_cng_packet) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001978 RTC_LOG(LS_WARNING) << "Unknown payload type "
1979 << static_cast<int>(packet->payload_type);
ossu61a208b2016-09-20 01:38:00 -07001980 RTC_NOTREACHED();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001981 }
ossu61a208b2016-09-20 01:38:00 -07001982
1983 if (packet_duration == 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001984 // Decoder did not return a packet duration. Assume that the packet
1985 // contains the same number of samples as the previous one.
ossu61a208b2016-09-20 01:38:00 -07001986 packet_duration = decoder_frame_length_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001987 }
ossu7a377612016-10-18 04:06:13 -07001988 extracted_samples = packet->timestamp - first_timestamp + packet_duration;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001989
Jakob Ivarsson44507082019-03-05 16:59:03 +01001990 stats_->JitterBufferDelay(packet_duration, waiting_time_ms);
Gustaf Ullbergb0a02072017-10-02 12:00:34 +02001991
ossua73f6c92016-10-24 08:25:28 -07001992 packet_list->push_back(std::move(*packet)); // Store packet in list.
Danil Chapovalovb6021232018-06-19 13:26:36 +02001993 packet = absl::nullopt; // Ensure it's never used after the move.
ossua73f6c92016-10-24 08:25:28 -07001994
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001995 // Check what packet is available next.
ossu7a377612016-10-18 04:06:13 -07001996 next_packet = packet_buffer_->PeekNextPacket();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001997 next_packet_available = false;
ossucafb4972017-01-02 07:00:50 -08001998 if (next_packet && prev_payload_type == next_packet->payload_type &&
1999 !has_cng_packet) {
ossu7a377612016-10-18 04:06:13 -07002000 int16_t seq_no_diff = next_packet->sequence_number - prev_sequence_number;
2001 size_t ts_diff = next_packet->timestamp - prev_timestamp;
Jakob Ivarsson00a6ab52019-01-09 16:35:07 +01002002 if ((seq_no_diff == 1 || seq_no_diff == 0) &&
2003 ts_diff <= packet_duration) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002004 // The next sequence number is available, or the next part of a packet
2005 // that was split into pieces upon insertion.
2006 next_packet_available = true;
2007 }
ossu7a377612016-10-18 04:06:13 -07002008 prev_sequence_number = next_packet->sequence_number;
Jakob Ivarsson00a6ab52019-01-09 16:35:07 +01002009 prev_timestamp = next_packet->timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002010 }
ossu61a208b2016-09-20 01:38:00 -07002011 } while (extracted_samples < required_samples && next_packet_available);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002012
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00002013 if (extracted_samples > 0) {
2014 // Delete old packets only when we are going to decode something. Otherwise,
2015 // we could end up in the situation where we never decode anything, since
2016 // all incoming packets are considered too old but the buffer will also
2017 // never be flooded and flushed.
Jakob Ivarsson44507082019-03-05 16:59:03 +01002018 packet_buffer_->DiscardAllOldPackets(timestamp_, stats_.get());
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00002019 }
2020
kwibergd3edd772017-03-01 18:52:48 -08002021 return rtc::dchecked_cast<int>(extracted_samples);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002022}
2023
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002024void NetEqImpl::UpdatePlcComponents(int fs_hz, size_t channels) {
2025 // Delete objects and create new ones.
2026 expand_.reset(expand_factory_->Create(background_noise_.get(),
2027 sync_buffer_.get(), &random_vector_,
Jakob Ivarsson44507082019-03-05 16:59:03 +01002028 stats_.get(), fs_hz, channels));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002029 merge_.reset(new Merge(fs_hz, channels, expand_.get(), sync_buffer_.get()));
2030}
2031
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002032void NetEqImpl::SetSampleRateAndChannels(int fs_hz, size_t channels) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002033 RTC_LOG(LS_VERBOSE) << "SetSampleRateAndChannels " << fs_hz << " "
2034 << channels;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002035 // TODO(hlundin): Change to an enumerator and skip assert.
Yves Gerey665174f2018-06-19 15:03:05 +02002036 assert(fs_hz == 8000 || fs_hz == 16000 || fs_hz == 32000 || fs_hz == 48000);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002037 assert(channels > 0);
2038
Henrik Lundinfe047752019-11-19 12:58:11 +01002039 // Before changing the sample rate, end and report any ongoing expand event.
2040 stats_->EndExpandEvent(fs_hz_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002041 fs_hz_ = fs_hz;
2042 fs_mult_ = fs_hz / 8000;
Peter Kastingdce40cf2015-08-24 14:52:23 -07002043 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002044 decoder_frame_length_ = 3 * output_size_samples_; // Initialize to 30ms.
2045
Ivo Creusen3ce44a32019-10-31 14:38:11 +01002046 last_mode_ = Mode::kNormal;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002047
ossu97ba30e2016-04-25 07:55:58 -07002048 ComfortNoiseDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02002049 if (cng_decoder)
2050 cng_decoder->Reset();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002051
2052 // Reinit post-decode VAD with new sample rate.
2053 assert(vad_.get()); // Cannot be NULL here.
2054 vad_->Init();
2055
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002056 // Delete algorithm buffer and create a new one.
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00002057 algorithm_buffer_.reset(new AudioMultiVector(channels));
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002058
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002059 // Delete sync buffer and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002060 sync_buffer_.reset(new SyncBuffer(channels, kSyncBufferSize * fs_mult_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002061
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00002062 // Delete BackgroundNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002063 background_noise_.reset(new BackgroundNoise(channels));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002064
2065 // Reset random vector.
2066 random_vector_.Reset();
2067
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002068 UpdatePlcComponents(fs_hz, channels);
2069
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002070 // Move index so that we create a small set of future samples (all 0).
2071 sync_buffer_->set_next_index(sync_buffer_->next_index() -
Yves Gerey665174f2018-06-19 15:03:05 +02002072 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002073
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002074 normal_.reset(new Normal(fs_hz, decoder_database_.get(), *background_noise_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002075 expand_.get()));
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +00002076 accelerate_.reset(
2077 accelerate_factory_->Create(fs_hz, channels, *background_noise_));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002078 preemptive_expand_.reset(preemptive_expand_factory_->Create(
Peter Kastingdce40cf2015-08-24 14:52:23 -07002079 fs_hz, channels, *background_noise_, expand_->overlap_length()));
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002080
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002081 // Delete ComfortNoise object and create a new one.
Yves Gerey665174f2018-06-19 15:03:05 +02002082 comfort_noise_.reset(
2083 new ComfortNoise(fs_hz, decoder_database_.get(), sync_buffer_.get()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002084
2085 // Verify that |decoded_buffer_| is long enough.
2086 if (decoded_buffer_length_ < kMaxFrameSize * channels) {
2087 // Reallocate to larger size.
2088 decoded_buffer_length_ = kMaxFrameSize * channels;
2089 decoded_buffer_.reset(new int16_t[decoded_buffer_length_]);
2090 }
Ivo Creusen53a31f72019-10-24 15:20:39 +02002091 RTC_CHECK(controller_) << "Unexpectedly found no NetEqController";
2092 controller_->SetSampleRate(fs_hz_, output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002093}
2094
henrik.lundin55480f52016-03-08 02:37:57 -08002095NetEqImpl::OutputType NetEqImpl::LastOutputType() {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002096 assert(vad_.get());
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002097 assert(expand_.get());
Ivo Creusen3ce44a32019-10-31 14:38:11 +01002098 if (last_mode_ == Mode::kCodecInternalCng ||
2099 last_mode_ == Mode::kRfc3389Cng) {
henrik.lundin55480f52016-03-08 02:37:57 -08002100 return OutputType::kCNG;
Ivo Creusen3ce44a32019-10-31 14:38:11 +01002101 } else if (last_mode_ == Mode::kExpand && expand_->MuteFactor(0) == 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002102 // Expand mode has faded down to background noise only (very long expand).
henrik.lundin55480f52016-03-08 02:37:57 -08002103 return OutputType::kPLCCNG;
Ivo Creusen3ce44a32019-10-31 14:38:11 +01002104 } else if (last_mode_ == Mode::kExpand) {
henrik.lundin55480f52016-03-08 02:37:57 -08002105 return OutputType::kPLC;
wu@webrtc.org24301a62013-12-13 19:17:43 +00002106 } else if (vad_->running() && !vad_->active_speech()) {
henrik.lundin55480f52016-03-08 02:37:57 -08002107 return OutputType::kVadPassive;
Ivo Creusen3ce44a32019-10-31 14:38:11 +01002108 } else if (last_mode_ == Mode::kCodecPlc) {
Alex Narest5b5d97c2019-08-07 18:15:08 +02002109 return OutputType::kCodecPLC;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002110 } else {
henrik.lundin55480f52016-03-08 02:37:57 -08002111 return OutputType::kNormalSpeech;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002112 }
2113}
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002114} // namespace webrtc