blob: 14f2fc7aaac19303ba2d19ff81498789db3d028e [file] [log] [blame]
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001/*
2 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "modules/audio_coding/neteq/neteq_impl.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000012
13#include <assert.h>
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000014
15#include <algorithm>
ossu61a208b2016-09-20 01:38:00 -070016#include <utility>
ossu97ba30e2016-04-25 07:55:58 -070017#include <vector>
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000018
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020019#include "api/audio_codecs/audio_decoder.h"
20#include "common_audio/signal_processing/include/signal_processing_library.h"
21#include "modules/audio_coding/neteq/accelerate.h"
22#include "modules/audio_coding/neteq/background_noise.h"
23#include "modules/audio_coding/neteq/buffer_level_filter.h"
24#include "modules/audio_coding/neteq/comfort_noise.h"
25#include "modules/audio_coding/neteq/decision_logic.h"
26#include "modules/audio_coding/neteq/decoder_database.h"
27#include "modules/audio_coding/neteq/defines.h"
28#include "modules/audio_coding/neteq/delay_manager.h"
29#include "modules/audio_coding/neteq/delay_peak_detector.h"
30#include "modules/audio_coding/neteq/dtmf_buffer.h"
31#include "modules/audio_coding/neteq/dtmf_tone_generator.h"
32#include "modules/audio_coding/neteq/expand.h"
33#include "modules/audio_coding/neteq/merge.h"
34#include "modules/audio_coding/neteq/nack_tracker.h"
35#include "modules/audio_coding/neteq/normal.h"
36#include "modules/audio_coding/neteq/packet.h"
37#include "modules/audio_coding/neteq/packet_buffer.h"
38#include "modules/audio_coding/neteq/post_decode_vad.h"
39#include "modules/audio_coding/neteq/preemptive_expand.h"
40#include "modules/audio_coding/neteq/red_payload_splitter.h"
41#include "modules/audio_coding/neteq/sync_buffer.h"
42#include "modules/audio_coding/neteq/tick_timer.h"
43#include "modules/audio_coding/neteq/timestamp_scaler.h"
44#include "modules/include/module_common_types.h"
45#include "rtc_base/checks.h"
46#include "rtc_base/logging.h"
47#include "rtc_base/safe_conversions.h"
48#include "rtc_base/sanitizer.h"
49#include "rtc_base/trace_event.h"
Henrik Lundin18036282017-11-02 12:09:06 +010050#include "system_wrappers/include/field_trial.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000051
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000052namespace webrtc {
53
ossue3525782016-05-25 07:37:43 -070054NetEqImpl::Dependencies::Dependencies(
55 const NetEq::Config& config,
56 const rtc::scoped_refptr<AudioDecoderFactory>& decoder_factory)
henrik.lundin1d9061e2016-04-26 12:19:34 -070057 : tick_timer(new TickTimer),
58 buffer_level_filter(new BufferLevelFilter),
ossue3525782016-05-25 07:37:43 -070059 decoder_database(new DecoderDatabase(decoder_factory)),
henrik.lundinf3933702016-04-28 01:53:52 -070060 delay_peak_detector(new DelayPeakDetector(tick_timer.get())),
henrik.lundin1d9061e2016-04-26 12:19:34 -070061 delay_manager(new DelayManager(config.max_packets_in_buffer,
henrik.lundin8f8c96d2016-04-28 23:19:20 -070062 delay_peak_detector.get(),
63 tick_timer.get())),
henrik.lundin1d9061e2016-04-26 12:19:34 -070064 dtmf_buffer(new DtmfBuffer(config.sample_rate_hz)),
65 dtmf_tone_generator(new DtmfToneGenerator),
66 packet_buffer(
67 new PacketBuffer(config.max_packets_in_buffer, tick_timer.get())),
ossua70695a2016-09-22 02:06:28 -070068 red_payload_splitter(new RedPayloadSplitter),
henrik.lundin1d9061e2016-04-26 12:19:34 -070069 timestamp_scaler(new TimestampScaler(*decoder_database)),
70 accelerate_factory(new AccelerateFactory),
71 expand_factory(new ExpandFactory),
72 preemptive_expand_factory(new PreemptiveExpandFactory) {}
73
74NetEqImpl::Dependencies::~Dependencies() = default;
75
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +000076NetEqImpl::NetEqImpl(const NetEq::Config& config,
henrik.lundin1d9061e2016-04-26 12:19:34 -070077 Dependencies&& deps,
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +000078 bool create_components)
henrik.lundin1d9061e2016-04-26 12:19:34 -070079 : tick_timer_(std::move(deps.tick_timer)),
80 buffer_level_filter_(std::move(deps.buffer_level_filter)),
81 decoder_database_(std::move(deps.decoder_database)),
82 delay_manager_(std::move(deps.delay_manager)),
83 delay_peak_detector_(std::move(deps.delay_peak_detector)),
84 dtmf_buffer_(std::move(deps.dtmf_buffer)),
85 dtmf_tone_generator_(std::move(deps.dtmf_tone_generator)),
86 packet_buffer_(std::move(deps.packet_buffer)),
ossua70695a2016-09-22 02:06:28 -070087 red_payload_splitter_(std::move(deps.red_payload_splitter)),
henrik.lundin1d9061e2016-04-26 12:19:34 -070088 timestamp_scaler_(std::move(deps.timestamp_scaler)),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000089 vad_(new PostDecodeVad()),
henrik.lundin1d9061e2016-04-26 12:19:34 -070090 expand_factory_(std::move(deps.expand_factory)),
91 accelerate_factory_(std::move(deps.accelerate_factory)),
92 preemptive_expand_factory_(std::move(deps.preemptive_expand_factory)),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000093 last_mode_(kModeNormal),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000094 decoded_buffer_length_(kMaxFrameSize),
95 decoded_buffer_(new int16_t[decoded_buffer_length_]),
96 playout_timestamp_(0),
97 new_codec_(false),
98 timestamp_(0),
99 reset_decoder_(false),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000100 ssrc_(0),
101 first_packet_(true),
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +0000102 background_noise_mode_(config.background_noise_mode),
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000103 playout_mode_(config.playout_mode),
Henrik Lundincf808d22015-05-27 14:33:29 +0200104 enable_fast_accelerate_(config.enable_fast_accelerate),
henrik.lundin7a926812016-05-12 13:51:28 -0700105 nack_enabled_(false),
Henrik Lundin18036282017-11-02 12:09:06 +0100106 enable_muted_state_(config.enable_muted_state),
107 use_dtx_delay_fix_(
108 field_trial::IsEnabled("WebRTC-NetEqOpusDtxDelayFix")) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100109 RTC_LOG(LS_INFO) << "NetEq config: " << config.ToString();
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +0000110 int fs = config.sample_rate_hz;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000111 if (fs != 8000 && fs != 16000 && fs != 32000 && fs != 48000) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100112 RTC_LOG(LS_ERROR) << "Sample rate " << fs << " Hz not supported. "
113 << "Changing to 8000 Hz.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000114 fs = 8000;
115 }
henrik.lundin1d9061e2016-04-26 12:19:34 -0700116 delay_manager_->SetMaximumDelay(config.max_delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000117 fs_hz_ = fs;
118 fs_mult_ = fs / 8000;
henrik.lundind89814b2015-11-23 06:49:25 -0800119 last_output_sample_rate_hz_ = fs;
Peter Kastingdce40cf2015-08-24 14:52:23 -0700120 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000121 decoder_frame_length_ = 3 * output_size_samples_;
122 WebRtcSpl_Init();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000123 if (create_components) {
124 SetSampleRateAndChannels(fs, 1); // Default is 1 channel.
125 }
henrik.lundin9bc26672015-11-02 03:25:57 -0800126 RTC_DCHECK(!vad_->enabled());
127 if (config.enable_post_decode_vad) {
128 vad_->Enable();
129 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000130}
131
Henrik Lundind67a2192015-08-03 12:54:37 +0200132NetEqImpl::~NetEqImpl() = default;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000133
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200134int NetEqImpl::InsertPacket(const RTPHeader& rtp_header,
kwibergee2bac22015-11-11 10:34:00 -0800135 rtc::ArrayView<const uint8_t> payload,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000136 uint32_t receive_timestamp) {
kwibergac554ee2016-09-02 00:39:33 -0700137 rtc::MsanCheckInitialized(payload);
henrik.lundina689b442015-12-17 03:50:05 -0800138 TRACE_EVENT0("webrtc", "NetEqImpl::InsertPacket");
Tommi9090e0b2016-01-20 13:39:36 +0100139 rtc::CritScope lock(&crit_sect_);
Henrik Lundinc417d9e2017-06-14 12:29:03 +0200140 if (InsertPacketInternal(rtp_header, payload, receive_timestamp) != 0) {
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000141 return kFail;
142 }
143 return kOK;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000144}
145
henrik.lundinb8c55b12017-05-10 07:38:01 -0700146void NetEqImpl::InsertEmptyPacket(const RTPHeader& /*rtp_header*/) {
147 // TODO(henrik.lundin) Handle NACK as well. This will make use of the
148 // rtp_header parameter.
149 // https://bugs.chromium.org/p/webrtc/issues/detail?id=7611
150 rtc::CritScope lock(&crit_sect_);
151 delay_manager_->RegisterEmptyPacket();
152}
153
henrik.lundin500c04b2016-03-08 02:36:04 -0800154namespace {
155void SetAudioFrameActivityAndType(bool vad_enabled,
henrik.lundin55480f52016-03-08 02:37:57 -0800156 NetEqImpl::OutputType type,
henrik.lundin500c04b2016-03-08 02:36:04 -0800157 AudioFrame::VADActivity last_vad_activity,
158 AudioFrame* audio_frame) {
159 switch (type) {
henrik.lundin55480f52016-03-08 02:37:57 -0800160 case NetEqImpl::OutputType::kNormalSpeech: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800161 audio_frame->speech_type_ = AudioFrame::kNormalSpeech;
162 audio_frame->vad_activity_ = AudioFrame::kVadActive;
163 break;
164 }
henrik.lundin55480f52016-03-08 02:37:57 -0800165 case NetEqImpl::OutputType::kVadPassive: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800166 // This should only be reached if the VAD is enabled.
167 RTC_DCHECK(vad_enabled);
168 audio_frame->speech_type_ = AudioFrame::kNormalSpeech;
169 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
170 break;
171 }
henrik.lundin55480f52016-03-08 02:37:57 -0800172 case NetEqImpl::OutputType::kCNG: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800173 audio_frame->speech_type_ = AudioFrame::kCNG;
174 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
175 break;
176 }
henrik.lundin55480f52016-03-08 02:37:57 -0800177 case NetEqImpl::OutputType::kPLC: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800178 audio_frame->speech_type_ = AudioFrame::kPLC;
179 audio_frame->vad_activity_ = last_vad_activity;
180 break;
181 }
henrik.lundin55480f52016-03-08 02:37:57 -0800182 case NetEqImpl::OutputType::kPLCCNG: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800183 audio_frame->speech_type_ = AudioFrame::kPLCCNG;
184 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
185 break;
186 }
187 default:
188 RTC_NOTREACHED();
189 }
190 if (!vad_enabled) {
191 // Always set kVadUnknown when receive VAD is inactive.
192 audio_frame->vad_activity_ = AudioFrame::kVadUnknown;
193 }
194}
henrik.lundinbc89de32016-03-08 05:20:14 -0800195} // namespace
henrik.lundin500c04b2016-03-08 02:36:04 -0800196
henrik.lundin7a926812016-05-12 13:51:28 -0700197int NetEqImpl::GetAudio(AudioFrame* audio_frame, bool* muted) {
henrik.lundine1ca1672016-01-08 03:50:08 -0800198 TRACE_EVENT0("webrtc", "NetEqImpl::GetAudio");
Tommi9090e0b2016-01-20 13:39:36 +0100199 rtc::CritScope lock(&crit_sect_);
Henrik Lundinc417d9e2017-06-14 12:29:03 +0200200 if (GetAudioInternal(audio_frame, muted) != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000201 return kFail;
202 }
henrik.lundin5fac3f02016-08-24 11:18:49 -0700203 RTC_DCHECK_EQ(
204 audio_frame->sample_rate_hz_,
kwibergd3edd772017-03-01 18:52:48 -0800205 rtc::dchecked_cast<int>(audio_frame->samples_per_channel_ * 100));
henrik.lundina4491072017-07-06 05:23:53 -0700206 RTC_DCHECK_EQ(*muted, audio_frame->muted());
henrik.lundin500c04b2016-03-08 02:36:04 -0800207 SetAudioFrameActivityAndType(vad_->enabled(), LastOutputType(),
208 last_vad_activity_, audio_frame);
209 last_vad_activity_ = audio_frame->vad_activity_;
henrik.lundin6d8e0112016-03-04 10:34:21 -0800210 last_output_sample_rate_hz_ = audio_frame->sample_rate_hz_;
henrik.lundind89814b2015-11-23 06:49:25 -0800211 RTC_DCHECK(last_output_sample_rate_hz_ == 8000 ||
212 last_output_sample_rate_hz_ == 16000 ||
213 last_output_sample_rate_hz_ == 32000 ||
214 last_output_sample_rate_hz_ == 48000)
215 << "Unexpected sample rate " << last_output_sample_rate_hz_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000216 return kOK;
217}
218
kwiberg1c07c702017-03-27 07:15:49 -0700219void NetEqImpl::SetCodecs(const std::map<int, SdpAudioFormat>& codecs) {
220 rtc::CritScope lock(&crit_sect_);
221 const std::vector<int> changed_payload_types =
222 decoder_database_->SetCodecs(codecs);
223 for (const int pt : changed_payload_types) {
minyue-webrtcfae474c2017-07-05 11:17:40 +0200224 packet_buffer_->DiscardPacketsWithPayloadType(pt, &stats_);
kwiberg1c07c702017-03-27 07:15:49 -0700225 }
226}
227
kwibergee1879c2015-10-29 06:20:28 -0700228int NetEqImpl::RegisterPayloadType(NetEqDecoder codec,
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800229 const std::string& name,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000230 uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100231 rtc::CritScope lock(&crit_sect_);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100232 RTC_LOG(LS_VERBOSE) << "RegisterPayloadType "
233 << static_cast<int>(rtp_payload_type) << " "
234 << static_cast<int>(codec);
Henrik Lundinc417d9e2017-06-14 12:29:03 +0200235 if (decoder_database_->RegisterPayload(rtp_payload_type, codec, name) !=
236 DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000237 return kFail;
238 }
239 return kOK;
240}
241
242int NetEqImpl::RegisterExternalDecoder(AudioDecoder* decoder,
kwibergee1879c2015-10-29 06:20:28 -0700243 NetEqDecoder codec,
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800244 const std::string& codec_name,
kwiberg342f7402016-06-16 03:18:00 -0700245 uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100246 rtc::CritScope lock(&crit_sect_);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100247 RTC_LOG(LS_VERBOSE) << "RegisterExternalDecoder "
248 << static_cast<int>(rtp_payload_type) << " "
249 << static_cast<int>(codec);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000250 if (!decoder) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100251 RTC_LOG(LS_ERROR) << "Cannot register external decoder with NULL pointer";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000252 assert(false);
253 return kFail;
254 }
Henrik Lundinc417d9e2017-06-14 12:29:03 +0200255 if (decoder_database_->InsertExternal(rtp_payload_type, codec, codec_name,
256 decoder) != DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000257 return kFail;
258 }
259 return kOK;
260}
261
kwiberg5adaf732016-10-04 09:33:27 -0700262bool NetEqImpl::RegisterPayloadType(int rtp_payload_type,
263 const SdpAudioFormat& audio_format) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100264 RTC_LOG(LS_VERBOSE) << "NetEqImpl::RegisterPayloadType: payload type "
265 << rtp_payload_type << ", codec " << audio_format;
kwiberg5adaf732016-10-04 09:33:27 -0700266 rtc::CritScope lock(&crit_sect_);
Henrik Lundinc417d9e2017-06-14 12:29:03 +0200267 return decoder_database_->RegisterPayload(rtp_payload_type, audio_format) ==
268 DecoderDatabase::kOK;
kwiberg5adaf732016-10-04 09:33:27 -0700269}
270
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000271int NetEqImpl::RemovePayloadType(uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100272 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000273 int ret = decoder_database_->Remove(rtp_payload_type);
Henrik Lundinc417d9e2017-06-14 12:29:03 +0200274 if (ret == DecoderDatabase::kOK || ret == DecoderDatabase::kDecoderNotFound) {
minyue-webrtcfae474c2017-07-05 11:17:40 +0200275 packet_buffer_->DiscardPacketsWithPayloadType(rtp_payload_type, &stats_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000276 return kOK;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000277 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000278 return kFail;
279}
280
kwiberg6b19b562016-09-20 04:02:25 -0700281void NetEqImpl::RemoveAllPayloadTypes() {
282 rtc::CritScope lock(&crit_sect_);
283 decoder_database_->RemoveAll();
284}
285
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000286bool NetEqImpl::SetMinimumDelay(int delay_ms) {
Tommi9090e0b2016-01-20 13:39:36 +0100287 rtc::CritScope lock(&crit_sect_);
Gustaf Ullberg48d96c02017-09-15 13:59:52 +0200288 if (delay_ms >= 0 && delay_ms <= 10000) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000289 assert(delay_manager_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000290 return delay_manager_->SetMinimumDelay(delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000291 }
292 return false;
293}
294
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000295bool NetEqImpl::SetMaximumDelay(int delay_ms) {
Tommi9090e0b2016-01-20 13:39:36 +0100296 rtc::CritScope lock(&crit_sect_);
Gustaf Ullberg48d96c02017-09-15 13:59:52 +0200297 if (delay_ms >= 0 && delay_ms <= 10000) {
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000298 assert(delay_manager_.get());
299 return delay_manager_->SetMaximumDelay(delay_ms);
300 }
301 return false;
302}
303
304int NetEqImpl::LeastRequiredDelayMs() const {
Tommi9090e0b2016-01-20 13:39:36 +0100305 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000306 assert(delay_manager_.get());
307 return delay_manager_->least_required_delay_ms();
308}
309
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200310int NetEqImpl::SetTargetDelay() {
311 return kNotImplemented;
312}
313
henrik.lundin114c1b32017-04-26 07:47:32 -0700314int NetEqImpl::TargetDelayMs() {
315 rtc::CritScope lock(&crit_sect_);
316 RTC_DCHECK(delay_manager_.get());
317 // The value from TargetLevel() is in number of packets, represented in Q8.
318 const size_t target_delay_samples =
319 (delay_manager_->TargetLevel() * decoder_frame_length_) >> 8;
320 return static_cast<int>(target_delay_samples) /
321 rtc::CheckedDivExact(fs_hz_, 1000);
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200322}
323
henrik.lundin9c3efd02015-08-27 13:12:22 -0700324int NetEqImpl::CurrentDelayMs() const {
Tommi9090e0b2016-01-20 13:39:36 +0100325 rtc::CritScope lock(&crit_sect_);
henrik.lundin9c3efd02015-08-27 13:12:22 -0700326 if (fs_hz_ == 0)
327 return 0;
328 // Sum up the samples in the packet buffer with the future length of the sync
329 // buffer, and divide the sum by the sample rate.
330 const size_t delay_samples =
ossu61a208b2016-09-20 01:38:00 -0700331 packet_buffer_->NumSamplesInBuffer(decoder_frame_length_) +
henrik.lundin9c3efd02015-08-27 13:12:22 -0700332 sync_buffer_->FutureLength();
333 // The division below will truncate.
334 const int delay_ms =
335 static_cast<int>(delay_samples) / rtc::CheckedDivExact(fs_hz_, 1000);
336 return delay_ms;
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200337}
338
henrik.lundinb3f1c5d2016-08-22 15:39:53 -0700339int NetEqImpl::FilteredCurrentDelayMs() const {
340 rtc::CritScope lock(&crit_sect_);
341 // Calculate the filtered packet buffer level in samples. The value from
342 // |buffer_level_filter_| is in number of packets, represented in Q8.
343 const size_t packet_buffer_samples =
344 (buffer_level_filter_->filtered_current_level() *
345 decoder_frame_length_) >>
346 8;
347 // Sum up the filtered packet buffer level with the future length of the sync
348 // buffer, and divide the sum by the sample rate.
349 const size_t delay_samples =
350 packet_buffer_samples + sync_buffer_->FutureLength();
351 // The division below will truncate. The return value is in ms.
352 return static_cast<int>(delay_samples) / rtc::CheckedDivExact(fs_hz_, 1000);
353}
354
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000355// Deprecated.
356// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000357void NetEqImpl::SetPlayoutMode(NetEqPlayoutMode mode) {
Tommi9090e0b2016-01-20 13:39:36 +0100358 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000359 if (mode != playout_mode_) {
360 playout_mode_ = mode;
361 CreateDecisionLogic();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000362 }
363}
364
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000365// Deprecated.
366// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000367NetEqPlayoutMode NetEqImpl::PlayoutMode() const {
Tommi9090e0b2016-01-20 13:39:36 +0100368 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000369 return playout_mode_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000370}
371
372int NetEqImpl::NetworkStatistics(NetEqNetworkStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100373 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000374 assert(decoder_database_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700375 const size_t total_samples_in_buffers =
ossu61a208b2016-09-20 01:38:00 -0700376 packet_buffer_->NumSamplesInBuffer(decoder_frame_length_) +
Peter Kastingdce40cf2015-08-24 14:52:23 -0700377 sync_buffer_->FutureLength();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000378 assert(delay_manager_.get());
379 assert(decision_logic_.get());
Henrik Lundindccfc402017-09-25 12:30:58 +0200380 const int ms_per_packet = rtc::dchecked_cast<int>(
381 decision_logic_->packet_length_samples() / (fs_hz_ / 1000));
382 stats_.PopulateDelayManagerStats(ms_per_packet, *delay_manager_.get(), stats);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000383 stats_.GetNetworkStatistics(fs_hz_, total_samples_in_buffers,
Henrik Lundindccfc402017-09-25 12:30:58 +0200384 decoder_frame_length_, stats);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000385 return 0;
386}
387
Steve Anton2dbc69f2017-08-24 17:15:13 -0700388NetEqLifetimeStatistics NetEqImpl::GetLifetimeStatistics() const {
389 rtc::CritScope lock(&crit_sect_);
390 return stats_.GetLifetimeStatistics();
391}
392
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000393void NetEqImpl::GetRtcpStatistics(RtcpStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100394 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000395 if (stats) {
396 rtcp_.GetStatistics(false, stats);
397 }
398}
399
400void NetEqImpl::GetRtcpStatisticsNoReset(RtcpStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100401 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000402 if (stats) {
403 rtcp_.GetStatistics(true, stats);
404 }
405}
406
407void NetEqImpl::EnableVad() {
Tommi9090e0b2016-01-20 13:39:36 +0100408 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000409 assert(vad_.get());
410 vad_->Enable();
411}
412
413void NetEqImpl::DisableVad() {
Tommi9090e0b2016-01-20 13:39:36 +0100414 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000415 assert(vad_.get());
416 vad_->Disable();
417}
418
henrik.lundin15c51e32016-04-06 08:38:56 -0700419rtc::Optional<uint32_t> NetEqImpl::GetPlayoutTimestamp() const {
Tommi9090e0b2016-01-20 13:39:36 +0100420 rtc::CritScope lock(&crit_sect_);
henrik.lundin0d96ab72016-04-06 12:28:26 -0700421 if (first_packet_ || last_mode_ == kModeRfc3389Cng ||
422 last_mode_ == kModeCodecInternalCng) {
wu@webrtc.org94454b72014-06-05 20:34:08 +0000423 // We don't have a valid RTP timestamp until we have decoded our first
henrik.lundin0d96ab72016-04-06 12:28:26 -0700424 // RTP packet. Also, the RTP timestamp is not accurate while playing CNG,
425 // which is indicated by returning an empty value.
Oskar Sundbom12ab00b2017-11-16 15:31:38 +0100426 return rtc::nullopt;
wu@webrtc.org94454b72014-06-05 20:34:08 +0000427 }
Oskar Sundbom12ab00b2017-11-16 15:31:38 +0100428 return timestamp_scaler_->ToExternal(playout_timestamp_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000429}
430
henrik.lundind89814b2015-11-23 06:49:25 -0800431int NetEqImpl::last_output_sample_rate_hz() const {
Tommi9090e0b2016-01-20 13:39:36 +0100432 rtc::CritScope lock(&crit_sect_);
henrik.lundind89814b2015-11-23 06:49:25 -0800433 return last_output_sample_rate_hz_;
434}
435
kwiberg6f0f6162016-09-20 03:07:46 -0700436rtc::Optional<CodecInst> NetEqImpl::GetDecoder(int payload_type) const {
437 rtc::CritScope lock(&crit_sect_);
438 const DecoderDatabase::DecoderInfo* di =
439 decoder_database_->GetDecoderInfo(payload_type);
440 if (!di) {
Oskar Sundbom12ab00b2017-11-16 15:31:38 +0100441 return rtc::nullopt;
kwiberg6f0f6162016-09-20 03:07:46 -0700442 }
443
444 // Create a CodecInst with some fields set. The remaining fields are zeroed,
445 // but we tell MSan to consider them uninitialized.
446 CodecInst ci = {0};
447 rtc::MsanMarkUninitialized(rtc::MakeArrayView(&ci, 1));
448 ci.pltype = payload_type;
kwiberge9413062016-11-03 05:29:05 -0700449 std::strncpy(ci.plname, di->get_name().c_str(), sizeof(ci.plname));
kwiberg6f0f6162016-09-20 03:07:46 -0700450 ci.plname[sizeof(ci.plname) - 1] = '\0';
solenberg2779bab2016-11-17 04:45:19 -0800451 ci.plfreq = di->IsRed() ? 8000 : di->SampleRateHz();
kwiberg6f0f6162016-09-20 03:07:46 -0700452 AudioDecoder* const decoder = di->GetDecoder();
453 ci.channels = decoder ? decoder->Channels() : 1;
Oskar Sundbom12ab00b2017-11-16 15:31:38 +0100454 return ci;
kwiberg6f0f6162016-09-20 03:07:46 -0700455}
456
ossuf1b08da2016-09-23 02:19:43 -0700457rtc::Optional<SdpAudioFormat> NetEqImpl::GetDecoderFormat(
458 int payload_type) const {
kwibergc4ccd4d2016-09-21 10:55:15 -0700459 rtc::CritScope lock(&crit_sect_);
460 const DecoderDatabase::DecoderInfo* const di =
461 decoder_database_->GetDecoderInfo(payload_type);
462 if (!di) {
Oskar Sundbom12ab00b2017-11-16 15:31:38 +0100463 return rtc::nullopt; // Payload type not registered.
kwibergc4ccd4d2016-09-21 10:55:15 -0700464 }
Oskar Sundbom12ab00b2017-11-16 15:31:38 +0100465 return di->GetFormat();
kwibergc4ccd4d2016-09-21 10:55:15 -0700466}
467
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200468int NetEqImpl::SetTargetNumberOfChannels() {
469 return kNotImplemented;
470}
471
472int NetEqImpl::SetTargetSampleRate() {
473 return kNotImplemented;
474}
475
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000476void NetEqImpl::FlushBuffers() {
Tommi9090e0b2016-01-20 13:39:36 +0100477 rtc::CritScope lock(&crit_sect_);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100478 RTC_LOG(LS_VERBOSE) << "FlushBuffers";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000479 packet_buffer_->Flush();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000480 assert(sync_buffer_.get());
481 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000482 sync_buffer_->Flush();
483 sync_buffer_->set_next_index(sync_buffer_->next_index() -
484 expand_->overlap_length());
485 // Set to wait for new codec.
486 first_packet_ = true;
487}
488
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000489void NetEqImpl::PacketBufferStatistics(int* current_num_packets,
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000490 int* max_num_packets) const {
Tommi9090e0b2016-01-20 13:39:36 +0100491 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000492 packet_buffer_->BufferStat(current_num_packets, max_num_packets);
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000493}
494
henrik.lundin48ed9302015-10-29 05:36:24 -0700495void NetEqImpl::EnableNack(size_t max_nack_list_size) {
Tommi9090e0b2016-01-20 13:39:36 +0100496 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700497 if (!nack_enabled_) {
498 const int kNackThresholdPackets = 2;
henrik.lundin91951862016-06-08 06:43:41 -0700499 nack_.reset(NackTracker::Create(kNackThresholdPackets));
henrik.lundin48ed9302015-10-29 05:36:24 -0700500 nack_enabled_ = true;
501 nack_->UpdateSampleRate(fs_hz_);
502 }
503 nack_->SetMaxNackListSize(max_nack_list_size);
504}
505
506void NetEqImpl::DisableNack() {
Tommi9090e0b2016-01-20 13:39:36 +0100507 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700508 nack_.reset();
509 nack_enabled_ = false;
510}
511
512std::vector<uint16_t> NetEqImpl::GetNackList(int64_t round_trip_time_ms) const {
Tommi9090e0b2016-01-20 13:39:36 +0100513 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700514 if (!nack_enabled_) {
515 return std::vector<uint16_t>();
516 }
517 RTC_DCHECK(nack_.get());
518 return nack_->GetNackList(round_trip_time_ms);
minyue@webrtc.orgd7301772013-08-29 00:58:14 +0000519}
520
henrik.lundin114c1b32017-04-26 07:47:32 -0700521std::vector<uint32_t> NetEqImpl::LastDecodedTimestamps() const {
522 rtc::CritScope lock(&crit_sect_);
523 return last_decoded_timestamps_;
524}
525
526int NetEqImpl::SyncBufferSizeMs() const {
527 rtc::CritScope lock(&crit_sect_);
528 return rtc::dchecked_cast<int>(sync_buffer_->FutureLength() /
529 rtc::CheckedDivExact(fs_hz_, 1000));
530}
531
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000532const SyncBuffer* NetEqImpl::sync_buffer_for_test() const {
Tommi9090e0b2016-01-20 13:39:36 +0100533 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000534 return sync_buffer_.get();
535}
536
minyue5bd33972016-05-02 04:46:11 -0700537Operations NetEqImpl::last_operation_for_test() const {
538 rtc::CritScope lock(&crit_sect_);
539 return last_operation_;
540}
541
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000542// Methods below this line are private.
543
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200544int NetEqImpl::InsertPacketInternal(const RTPHeader& rtp_header,
kwibergee2bac22015-11-11 10:34:00 -0800545 rtc::ArrayView<const uint8_t> payload,
ossu17e3fa12016-09-08 04:52:55 -0700546 uint32_t receive_timestamp) {
kwibergee2bac22015-11-11 10:34:00 -0800547 if (payload.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100548 RTC_LOG_F(LS_ERROR) << "payload is empty";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000549 return kInvalidPointer;
550 }
ossu17e3fa12016-09-08 04:52:55 -0700551
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000552 PacketList packet_list;
ossua73f6c92016-10-24 08:25:28 -0700553 // Insert packet in a packet list.
554 packet_list.push_back([&rtp_header, &payload] {
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000555 // Convert to Packet.
ossua73f6c92016-10-24 08:25:28 -0700556 Packet packet;
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200557 packet.payload_type = rtp_header.payloadType;
558 packet.sequence_number = rtp_header.sequenceNumber;
559 packet.timestamp = rtp_header.timestamp;
ossua73f6c92016-10-24 08:25:28 -0700560 packet.payload.SetData(payload.data(), payload.size());
henrik.lundin84f8cd62016-04-26 07:45:16 -0700561 // Waiting time will be set upon inserting the packet in the buffer.
ossua73f6c92016-10-24 08:25:28 -0700562 RTC_DCHECK(!packet.waiting_time);
563 return packet;
564 }());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000565
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200566 bool update_sample_rate_and_channels =
567 first_packet_ || (rtp_header.ssrc != ssrc_);
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700568
569 if (update_sample_rate_and_channels) {
570 // Reset timestamp scaling.
571 timestamp_scaler_->Reset();
572 }
573
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200574 if (!decoder_database_->IsRed(rtp_header.payloadType)) {
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700575 // Scale timestamp to internal domain (only for some codecs).
576 timestamp_scaler_->ToInternal(&packet_list);
577 }
578
579 // Store these for later use, since the first packet may very well disappear
580 // before we need these values.
581 uint32_t main_timestamp = packet_list.front().timestamp;
582 uint8_t main_payload_type = packet_list.front().payload_type;
583 uint16_t main_sequence_number = packet_list.front().sequence_number;
584
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000585 // Reinitialize NetEq if it's needed (changed SSRC or first call).
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700586 if (update_sample_rate_and_channels) {
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000587 // Note: |first_packet_| will be cleared further down in this method, once
588 // the packet has been successfully inserted into the packet buffer.
589
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200590 rtcp_.Init(rtp_header.sequenceNumber);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000591
592 // Flush the packet buffer and DTMF buffer.
593 packet_buffer_->Flush();
594 dtmf_buffer_->Flush();
595
596 // Store new SSRC.
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200597 ssrc_ = rtp_header.ssrc;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000598
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000599 // Update audio buffer timestamp.
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700600 sync_buffer_->IncreaseEndTimestamp(main_timestamp - timestamp_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000601
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000602 // Update codecs.
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700603 timestamp_ = main_timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000604 }
605
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000606 // Update RTCP statistics, only for regular packets.
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200607 rtcp_.Update(rtp_header, receive_timestamp);
ossu7a377612016-10-18 04:06:13 -0700608
609 if (nack_enabled_) {
610 RTC_DCHECK(nack_);
611 if (update_sample_rate_and_channels) {
612 nack_->Reset();
613 }
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200614 nack_->UpdateLastReceivedPacket(rtp_header.sequenceNumber,
615 rtp_header.timestamp);
ossu7a377612016-10-18 04:06:13 -0700616 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000617
618 // Check for RED payload type, and separate payloads into several packets.
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200619 if (decoder_database_->IsRed(rtp_header.payloadType)) {
ossua70695a2016-09-22 02:06:28 -0700620 if (!red_payload_splitter_->SplitRed(&packet_list)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000621 return kRedundancySplitError;
622 }
623 // Only accept a few RED payloads of the same type as the main data,
624 // DTMF events and CNG.
ossua70695a2016-09-22 02:06:28 -0700625 red_payload_splitter_->CheckRedPayloads(&packet_list, *decoder_database_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000626 }
627
628 // Check payload types.
629 if (decoder_database_->CheckPayloadTypes(packet_list) ==
630 DecoderDatabase::kDecoderNotFound) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000631 return kUnknownRtpPayloadType;
632 }
633
ossu7a377612016-10-18 04:06:13 -0700634 RTC_DCHECK(!packet_list.empty());
ossu7a377612016-10-18 04:06:13 -0700635
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700636 // Update main_timestamp, if new packets appear in the list
637 // after RED splitting.
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200638 if (decoder_database_->IsRed(rtp_header.payloadType)) {
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700639 timestamp_scaler_->ToInternal(&packet_list);
640 main_timestamp = packet_list.front().timestamp;
641 main_payload_type = packet_list.front().payload_type;
642 main_sequence_number = packet_list.front().sequence_number;
643 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000644
645 // Process DTMF payloads. Cycle through the list of packets, and pick out any
646 // DTMF payloads found.
647 PacketList::iterator it = packet_list.begin();
648 while (it != packet_list.end()) {
ossua73f6c92016-10-24 08:25:28 -0700649 const Packet& current_packet = (*it);
650 RTC_DCHECK(!current_packet.payload.empty());
651 if (decoder_database_->IsDtmf(current_packet.payload_type)) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000652 DtmfEvent event;
ossua73f6c92016-10-24 08:25:28 -0700653 int ret = DtmfBuffer::ParseEvent(current_packet.timestamp,
654 current_packet.payload.data(),
655 current_packet.payload.size(), &event);
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000656 if (ret != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000657 return kDtmfParsingError;
658 }
659 if (dtmf_buffer_->InsertEvent(event) != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000660 return kDtmfInsertError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000661 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000662 it = packet_list.erase(it);
663 } else {
664 ++it;
665 }
666 }
667
ossu17e3fa12016-09-08 04:52:55 -0700668 // Update bandwidth estimate, if the packet is not comfort noise.
669 if (!packet_list.empty() &&
ossu7a377612016-10-18 04:06:13 -0700670 !decoder_database_->IsComfortNoise(main_payload_type)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000671 // The list can be empty here if we got nothing but DTMF payloads.
ossu7a377612016-10-18 04:06:13 -0700672 AudioDecoder* decoder = decoder_database_->GetDecoder(main_payload_type);
673 RTC_DCHECK(decoder); // Should always get a valid object, since we have
674 // already checked that the payload types are known.
ossua73f6c92016-10-24 08:25:28 -0700675 decoder->IncomingPacket(packet_list.front().payload.data(),
676 packet_list.front().payload.size(),
677 packet_list.front().sequence_number,
678 packet_list.front().timestamp,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000679 receive_timestamp);
680 }
681
ossu61a208b2016-09-20 01:38:00 -0700682 PacketList parsed_packet_list;
683 while (!packet_list.empty()) {
ossua73f6c92016-10-24 08:25:28 -0700684 Packet& packet = packet_list.front();
ossu61a208b2016-09-20 01:38:00 -0700685 const DecoderDatabase::DecoderInfo* info =
ossua73f6c92016-10-24 08:25:28 -0700686 decoder_database_->GetDecoderInfo(packet.payload_type);
ossu61a208b2016-09-20 01:38:00 -0700687 if (!info) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100688 RTC_LOG(LS_WARNING) << "SplitAudio unknown payload type";
ossu61a208b2016-09-20 01:38:00 -0700689 return kUnknownRtpPayloadType;
690 }
691
692 if (info->IsComfortNoise()) {
693 // Carry comfort noise packets along.
ossua73f6c92016-10-24 08:25:28 -0700694 parsed_packet_list.splice(parsed_packet_list.end(), packet_list,
695 packet_list.begin());
ossu61a208b2016-09-20 01:38:00 -0700696 } else {
ossua73f6c92016-10-24 08:25:28 -0700697 const auto sequence_number = packet.sequence_number;
698 const auto payload_type = packet.payload_type;
699 const Packet::Priority original_priority = packet.priority;
700 auto packet_from_result = [&] (AudioDecoder::ParseResult& result) {
701 Packet new_packet;
702 new_packet.sequence_number = sequence_number;
703 new_packet.payload_type = payload_type;
704 new_packet.timestamp = result.timestamp;
705 new_packet.priority.codec_level = result.priority;
706 new_packet.priority.red_level = original_priority.red_level;
707 new_packet.frame = std::move(result.frame);
708 return new_packet;
709 };
710
ossu61a208b2016-09-20 01:38:00 -0700711 std::vector<AudioDecoder::ParseResult> results =
ossua73f6c92016-10-24 08:25:28 -0700712 info->GetDecoder()->ParsePayload(std::move(packet.payload),
713 packet.timestamp);
714 if (results.empty()) {
715 packet_list.pop_front();
716 } else {
717 bool first = true;
718 for (auto& result : results) {
719 RTC_DCHECK(result.frame);
720 RTC_DCHECK_GE(result.priority, 0);
721 if (first) {
722 // Re-use the node and move it to parsed_packet_list.
723 packet_list.front() = packet_from_result(result);
724 parsed_packet_list.splice(parsed_packet_list.end(), packet_list,
725 packet_list.begin());
726 first = false;
727 } else {
728 parsed_packet_list.push_back(packet_from_result(result));
729 }
ossu61a208b2016-09-20 01:38:00 -0700730 }
ossu61a208b2016-09-20 01:38:00 -0700731 }
732 }
733 }
734
Ivo Creusenfd7c0a52017-10-20 12:35:04 +0200735 // Calculate the number of primary (non-FEC/RED) packets.
736 const int number_of_primary_packets = std::count_if(
737 parsed_packet_list.begin(), parsed_packet_list.end(),
738 [](const Packet& in) { return in.priority.codec_level == 0; });
739
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000740 // Insert packets in buffer.
ossua70695a2016-09-22 02:06:28 -0700741 const int ret = packet_buffer_->InsertPacketList(
ossu61a208b2016-09-20 01:38:00 -0700742 &parsed_packet_list, *decoder_database_, &current_rtp_payload_type_,
minyue-webrtc12d30842017-07-19 11:44:06 +0200743 &current_cng_rtp_payload_type_, &stats_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000744 if (ret == PacketBuffer::kFlushed) {
745 // Reset DSP timestamp etc. if packet buffer flushed.
746 new_codec_ = true;
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000747 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000748 } else if (ret != PacketBuffer::kOK) {
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000749 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000750 }
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000751
752 if (first_packet_) {
753 first_packet_ = false;
754 // Update the codec on the next GetAudio call.
755 new_codec_ = true;
756 }
757
henrik.lundinda8bbf62016-08-31 03:14:11 -0700758 if (current_rtp_payload_type_) {
759 RTC_DCHECK(decoder_database_->GetDecoderInfo(*current_rtp_payload_type_))
760 << "Payload type " << static_cast<int>(*current_rtp_payload_type_)
761 << " is unknown where it shouldn't be";
762 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000763
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000764 if (update_sample_rate_and_channels && !packet_buffer_->Empty()) {
765 // We do not use |current_rtp_payload_type_| to |set payload_type|, but
766 // get the next RTP header from |packet_buffer_| to obtain the payload type.
767 // The reason for it is the following corner case. If NetEq receives a
768 // CNG packet with a sample rate different than the current CNG then it
769 // flushes its buffer, assuming send codec must have been changed. However,
770 // payload type of the hypothetically new send codec is not known.
ossu7a377612016-10-18 04:06:13 -0700771 const Packet* next_packet = packet_buffer_->PeekNextPacket();
772 RTC_DCHECK(next_packet);
773 const int payload_type = next_packet->payload_type;
ossu97ba30e2016-04-25 07:55:58 -0700774 size_t channels = 1;
775 if (!decoder_database_->IsComfortNoise(payload_type)) {
776 AudioDecoder* decoder = decoder_database_->GetDecoder(payload_type);
777 assert(decoder); // Payloads are already checked to be valid.
778 channels = decoder->Channels();
779 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000780 const DecoderDatabase::DecoderInfo* decoder_info =
781 decoder_database_->GetDecoderInfo(payload_type);
782 assert(decoder_info);
kwibergc0f2dcf2016-05-31 06:28:03 -0700783 if (decoder_info->SampleRateHz() != fs_hz_ ||
ossu97ba30e2016-04-25 07:55:58 -0700784 channels != algorithm_buffer_->Channels()) {
kwibergc0f2dcf2016-05-31 06:28:03 -0700785 SetSampleRateAndChannels(decoder_info->SampleRateHz(),
786 channels);
henrik.lundin48ed9302015-10-29 05:36:24 -0700787 }
788 if (nack_enabled_) {
789 RTC_DCHECK(nack_);
790 // Update the sample rate even if the rate is not new, because of Reset().
791 nack_->UpdateSampleRate(fs_hz_);
792 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000793 }
794
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000795 // TODO(hlundin): Move this code to DelayManager class.
796 const DecoderDatabase::DecoderInfo* dec_info =
ossu7a377612016-10-18 04:06:13 -0700797 decoder_database_->GetDecoderInfo(main_payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000798 assert(dec_info); // Already checked that the payload type is known.
ossuf1b08da2016-09-23 02:19:43 -0700799 delay_manager_->LastDecodedWasCngOrDtmf(dec_info->IsComfortNoise() ||
800 dec_info->IsDtmf());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000801 if (delay_manager_->last_pack_cng_or_dtmf() == 0) {
802 // Calculate the total speech length carried in each packet.
Ivo Creusenfd7c0a52017-10-20 12:35:04 +0200803 if (number_of_primary_packets > 0) {
henrik.lundin116c84e2015-08-27 13:14:48 -0700804 const size_t packet_length_samples =
Ivo Creusenfd7c0a52017-10-20 12:35:04 +0200805 number_of_primary_packets * decoder_frame_length_;
henrik.lundin116c84e2015-08-27 13:14:48 -0700806 if (packet_length_samples != decision_logic_->packet_length_samples()) {
807 decision_logic_->set_packet_length_samples(packet_length_samples);
808 delay_manager_->SetPacketAudioLength(
kwibergd3edd772017-03-01 18:52:48 -0800809 rtc::dchecked_cast<int>((1000 * packet_length_samples) / fs_hz_));
henrik.lundin116c84e2015-08-27 13:14:48 -0700810 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000811 }
812
813 // Update statistics.
ossu7a377612016-10-18 04:06:13 -0700814 if ((int32_t)(main_timestamp - timestamp_) >= 0 && !new_codec_) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000815 // Only update statistics if incoming packet is not older than last played
816 // out packet, and if new codec flag is not set.
ossu7a377612016-10-18 04:06:13 -0700817 delay_manager_->Update(main_sequence_number, main_timestamp, fs_hz_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000818 }
819 } else if (delay_manager_->last_pack_cng_or_dtmf() == -1) {
820 // This is first "normal" packet after CNG or DTMF.
821 // Reset packet time counter and measure time until next packet,
822 // but don't update statistics.
823 delay_manager_->set_last_pack_cng_or_dtmf(0);
824 delay_manager_->ResetPacketIatCount();
825 }
826 return 0;
827}
828
henrik.lundin7a926812016-05-12 13:51:28 -0700829int NetEqImpl::GetAudioInternal(AudioFrame* audio_frame, bool* muted) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000830 PacketList packet_list;
831 DtmfEvent dtmf_event;
832 Operations operation;
833 bool play_dtmf;
henrik.lundin7a926812016-05-12 13:51:28 -0700834 *muted = false;
henrik.lundin114c1b32017-04-26 07:47:32 -0700835 last_decoded_timestamps_.clear();
henrik.lundined497212016-04-25 10:11:38 -0700836 tick_timer_->Increment();
henrik.lundin60f6ce22016-05-10 03:52:04 -0700837 stats_.IncreaseCounter(output_size_samples_, fs_hz_);
henrik.lundin7a926812016-05-12 13:51:28 -0700838
839 // Check for muted state.
840 if (enable_muted_state_ && expand_->Muted() && packet_buffer_->Empty()) {
841 RTC_DCHECK_EQ(last_mode_, kModeExpand);
henrik.lundina4491072017-07-06 05:23:53 -0700842 audio_frame->Reset();
843 RTC_DCHECK(audio_frame->muted()); // Reset() should mute the frame.
henrik.lundin7a926812016-05-12 13:51:28 -0700844 playout_timestamp_ += static_cast<uint32_t>(output_size_samples_);
845 audio_frame->sample_rate_hz_ = fs_hz_;
846 audio_frame->samples_per_channel_ = output_size_samples_;
847 audio_frame->timestamp_ =
848 first_packet_
849 ? 0
850 : timestamp_scaler_->ToExternal(playout_timestamp_) -
851 static_cast<uint32_t>(audio_frame->samples_per_channel_);
852 audio_frame->num_channels_ = sync_buffer_->Channels();
Gustaf Ullberg9a2e9062017-09-18 09:28:20 +0200853 stats_.ExpandedNoiseSamples(output_size_samples_, false);
henrik.lundin7a926812016-05-12 13:51:28 -0700854 *muted = true;
855 return 0;
856 }
857
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000858 int return_value = GetDecision(&operation, &packet_list, &dtmf_event,
859 &play_dtmf);
860 if (return_value != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000861 last_mode_ = kModeError;
862 return return_value;
863 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000864
865 AudioDecoder::SpeechType speech_type;
866 int length = 0;
Henrik Lundin18036282017-11-02 12:09:06 +0100867 const size_t start_num_packets = packet_list.size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000868 int decode_return_value = Decode(&packet_list, &operation,
869 &length, &speech_type);
870
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000871 assert(vad_.get());
872 bool sid_frame_available =
873 (operation == kRfc3389Cng && !packet_list.empty());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700874 vad_->Update(decoded_buffer_.get(), static_cast<size_t>(length), speech_type,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000875 sid_frame_available, fs_hz_);
876
Henrik Lundin18036282017-11-02 12:09:06 +0100877 // This is the criterion that we did decode some data through the speech
878 // decoder, and the operation resulted in comfort noise.
879 const bool codec_internal_sid_frame =
880 use_dtx_delay_fix_ ? (speech_type == AudioDecoder::kComfortNoise &&
881 start_num_packets > packet_list.size())
882 : (speech_type == AudioDecoder::kComfortNoise);
883
884 if (sid_frame_available || codec_internal_sid_frame) {
henrik.lundinb1fb72b2016-05-03 08:18:47 -0700885 // Start a new stopwatch since we are decoding a new CNG packet.
886 generated_noise_stopwatch_ = tick_timer_->GetNewStopwatch();
887 }
888
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000889 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000890 switch (operation) {
891 case kNormal: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000892 DoNormal(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000893 break;
894 }
895 case kMerge: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000896 DoMerge(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000897 break;
898 }
899 case kExpand: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000900 return_value = DoExpand(play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000901 break;
902 }
Henrik Lundincf808d22015-05-27 14:33:29 +0200903 case kAccelerate:
904 case kFastAccelerate: {
905 const bool fast_accelerate =
906 enable_fast_accelerate_ && (operation == kFastAccelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000907 return_value = DoAccelerate(decoded_buffer_.get(), length, speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +0200908 play_dtmf, fast_accelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000909 break;
910 }
911 case kPreemptiveExpand: {
912 return_value = DoPreemptiveExpand(decoded_buffer_.get(), length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000913 speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000914 break;
915 }
916 case kRfc3389Cng:
917 case kRfc3389CngNoPacket: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000918 return_value = DoRfc3389Cng(&packet_list, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000919 break;
920 }
921 case kCodecInternalCng: {
922 // This handles the case when there is no transmission and the decoder
923 // should produce internal comfort noise.
924 // TODO(hlundin): Write test for codec-internal CNG.
minyuel6d92bf52015-09-23 15:20:39 +0200925 DoCodecInternalCng(decoded_buffer_.get(), length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000926 break;
927 }
928 case kDtmf: {
929 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000930 return_value = DoDtmf(dtmf_event, &play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000931 break;
932 }
933 case kAlternativePlc: {
934 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000935 DoAlternativePlc(false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000936 break;
937 }
938 case kAlternativePlcIncreaseTimestamp: {
939 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000940 DoAlternativePlc(true);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000941 break;
942 }
943 case kAudioRepetitionIncreaseTimestamp: {
944 // TODO(hlundin): Write test for this.
Peter Kastingb7e50542015-06-11 12:55:50 -0700945 sync_buffer_->IncreaseEndTimestamp(
946 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000947 // Skipping break on purpose. Execution should move on into the
948 // next case.
kjellanderbdf30722017-09-08 11:00:21 -0700949 FALLTHROUGH();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000950 }
951 case kAudioRepetition: {
952 // TODO(hlundin): Write test for this.
953 // Copy last |output_size_samples_| from |sync_buffer_| to
954 // |algorithm_buffer|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000955 algorithm_buffer_->PushBackFromIndex(
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000956 *sync_buffer_, sync_buffer_->Size() - output_size_samples_);
957 expand_->Reset();
958 break;
959 }
960 case kUndefined: {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100961 RTC_LOG(LS_ERROR) << "Invalid operation kUndefined.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000962 assert(false); // This should not happen.
963 last_mode_ = kModeError;
964 return kInvalidOperation;
965 }
966 } // End of switch.
minyue5bd33972016-05-02 04:46:11 -0700967 last_operation_ = operation;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000968 if (return_value < 0) {
969 return return_value;
970 }
971
972 if (last_mode_ != kModeRfc3389Cng) {
973 comfort_noise_->Reset();
974 }
975
976 // Copy from |algorithm_buffer| to |sync_buffer_|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000977 sync_buffer_->PushBack(*algorithm_buffer_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000978
979 // Extract data from |sync_buffer_| to |output|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000980 size_t num_output_samples_per_channel = output_size_samples_;
981 size_t num_output_samples = output_size_samples_ * sync_buffer_->Channels();
henrik.lundin6d8e0112016-03-04 10:34:21 -0800982 if (num_output_samples > AudioFrame::kMaxDataSizeSamples) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100983 RTC_LOG(LS_WARNING) << "Output array is too short. "
984 << AudioFrame::kMaxDataSizeSamples << " < "
985 << output_size_samples_ << " * "
986 << sync_buffer_->Channels();
henrik.lundin6d8e0112016-03-04 10:34:21 -0800987 num_output_samples = AudioFrame::kMaxDataSizeSamples;
988 num_output_samples_per_channel =
989 AudioFrame::kMaxDataSizeSamples / sync_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000990 }
henrik.lundin6d8e0112016-03-04 10:34:21 -0800991 sync_buffer_->GetNextAudioInterleaved(num_output_samples_per_channel,
992 audio_frame);
993 audio_frame->sample_rate_hz_ = fs_hz_;
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200994 if (sync_buffer_->FutureLength() < expand_->overlap_length()) {
995 // The sync buffer should always contain |overlap_length| samples, but now
996 // too many samples have been extracted. Reinstall the |overlap_length|
997 // lookahead by moving the index.
998 const size_t missing_lookahead_samples =
999 expand_->overlap_length() - sync_buffer_->FutureLength();
henrikg91d6ede2015-09-17 00:24:34 -07001000 RTC_DCHECK_GE(sync_buffer_->next_index(), missing_lookahead_samples);
Henrik Lundin05f71fc2015-09-01 11:51:58 +02001001 sync_buffer_->set_next_index(sync_buffer_->next_index() -
1002 missing_lookahead_samples);
1003 }
henrik.lundin6d8e0112016-03-04 10:34:21 -08001004 if (audio_frame->samples_per_channel_ != output_size_samples_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001005 RTC_LOG(LS_ERROR) << "audio_frame->samples_per_channel_ ("
1006 << audio_frame->samples_per_channel_
1007 << ") != output_size_samples_ (" << output_size_samples_
1008 << ")";
minyue@webrtc.orgdb1cefc2013-08-13 01:39:21 +00001009 // TODO(minyue): treatment of under-run, filling zeros
yujo36b1a5f2017-06-12 12:45:32 -07001010 audio_frame->Mute();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001011 return kSampleUnderrun;
1012 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001013
1014 // Should always have overlap samples left in the |sync_buffer_|.
henrikg91d6ede2015-09-17 00:24:34 -07001015 RTC_DCHECK_GE(sync_buffer_->FutureLength(), expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001016
yujo36b1a5f2017-06-12 12:45:32 -07001017 // TODO(yujo): For muted frames, this can be a copy rather than an addition.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001018 if (play_dtmf) {
yujo36b1a5f2017-06-12 12:45:32 -07001019 return_value = DtmfOverdub(dtmf_event, sync_buffer_->Channels(),
1020 audio_frame->mutable_data());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001021 }
1022
1023 // Update the background noise parameters if last operation wrote data
1024 // straight from the decoder to the |sync_buffer_|. That is, none of the
1025 // operations that modify the signal can be followed by a parameter update.
1026 if ((last_mode_ == kModeNormal) ||
1027 (last_mode_ == kModeAccelerateFail) ||
1028 (last_mode_ == kModePreemptiveExpandFail) ||
1029 (last_mode_ == kModeRfc3389Cng) ||
1030 (last_mode_ == kModeCodecInternalCng)) {
1031 background_noise_->Update(*sync_buffer_, *vad_.get());
1032 }
1033
1034 if (operation == kDtmf) {
1035 // DTMF data was written the end of |sync_buffer_|.
1036 // Update index to end of DTMF data in |sync_buffer_|.
1037 sync_buffer_->set_dtmf_index(sync_buffer_->Size());
1038 }
1039
henrik.lundin@webrtc.orged865b52014-03-06 10:28:07 +00001040 if (last_mode_ != kModeExpand) {
1041 // If last operation was not expand, calculate the |playout_timestamp_| from
1042 // the |sync_buffer_|. However, do not update the |playout_timestamp_| if it
1043 // would be moved "backwards".
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001044 uint32_t temp_timestamp = sync_buffer_->end_timestamp() -
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001045 static_cast<uint32_t>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001046 if (static_cast<int32_t>(temp_timestamp - playout_timestamp_) > 0) {
1047 playout_timestamp_ = temp_timestamp;
1048 }
1049 } else {
1050 // Use dead reckoning to estimate the |playout_timestamp_|.
Peter Kastingb7e50542015-06-11 12:55:50 -07001051 playout_timestamp_ += static_cast<uint32_t>(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001052 }
henrik.lundin15c51e32016-04-06 08:38:56 -07001053 // Set the timestamp in the audio frame to zero before the first packet has
1054 // been inserted. Otherwise, subtract the frame size in samples to get the
1055 // timestamp of the first sample in the frame (playout_timestamp_ is the
1056 // last + 1).
1057 audio_frame->timestamp_ =
1058 first_packet_
1059 ? 0
1060 : timestamp_scaler_->ToExternal(playout_timestamp_) -
1061 static_cast<uint32_t>(audio_frame->samples_per_channel_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001062
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001063 if (!(last_mode_ == kModeRfc3389Cng ||
1064 last_mode_ == kModeCodecInternalCng ||
1065 last_mode_ == kModeExpand)) {
1066 generated_noise_stopwatch_.reset();
1067 }
1068
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001069 if (decode_return_value) return decode_return_value;
1070 return return_value;
1071}
1072
1073int NetEqImpl::GetDecision(Operations* operation,
1074 PacketList* packet_list,
1075 DtmfEvent* dtmf_event,
1076 bool* play_dtmf) {
1077 // Initialize output variables.
1078 *play_dtmf = false;
1079 *operation = kUndefined;
1080
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001081 assert(sync_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001082 uint32_t end_timestamp = sync_buffer_->end_timestamp();
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001083 if (!new_codec_) {
1084 const uint32_t five_seconds_samples = 5 * fs_hz_;
minyue-webrtcfae474c2017-07-05 11:17:40 +02001085 packet_buffer_->DiscardOldPackets(end_timestamp, five_seconds_samples,
1086 &stats_);
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001087 }
ossu7a377612016-10-18 04:06:13 -07001088 const Packet* packet = packet_buffer_->PeekNextPacket();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001089
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001090 RTC_DCHECK(!generated_noise_stopwatch_ ||
1091 generated_noise_stopwatch_->ElapsedTicks() >= 1);
1092 uint64_t generated_noise_samples =
1093 generated_noise_stopwatch_
1094 ? (generated_noise_stopwatch_->ElapsedTicks() - 1) *
1095 output_size_samples_ +
1096 decision_logic_->noise_fast_forward()
1097 : 0;
1098
henrik.lundin@webrtc.orgca8cb952014-03-12 10:26:52 +00001099 if (decision_logic_->CngRfc3389On() || last_mode_ == kModeRfc3389Cng) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001100 // Because of timestamp peculiarities, we have to "manually" disallow using
1101 // a CNG packet with the same timestamp as the one that was last played.
1102 // This can happen when using redundancy and will cause the timing to shift.
ossu7a377612016-10-18 04:06:13 -07001103 while (packet && decoder_database_->IsComfortNoise(packet->payload_type) &&
1104 (end_timestamp >= packet->timestamp ||
1105 end_timestamp + generated_noise_samples > packet->timestamp)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001106 // Don't use this packet, discard it.
minyue-webrtcfae474c2017-07-05 11:17:40 +02001107 if (packet_buffer_->DiscardNextPacket(&stats_) != PacketBuffer::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001108 assert(false); // Must be ok by design.
1109 }
1110 // Check buffer again.
1111 if (!new_codec_) {
minyue-webrtcfae474c2017-07-05 11:17:40 +02001112 packet_buffer_->DiscardOldPackets(end_timestamp, 5 * fs_hz_, &stats_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001113 }
ossu7a377612016-10-18 04:06:13 -07001114 packet = packet_buffer_->PeekNextPacket();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001115 }
1116 }
1117
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001118 assert(expand_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001119 const int samples_left = static_cast<int>(sync_buffer_->FutureLength() -
1120 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001121 if (last_mode_ == kModeAccelerateSuccess ||
1122 last_mode_ == kModeAccelerateLowEnergy ||
1123 last_mode_ == kModePreemptiveExpandSuccess ||
1124 last_mode_ == kModePreemptiveExpandLowEnergy) {
1125 // Subtract (samples_left + output_size_samples_) from sampleMemory.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001126 decision_logic_->AddSampleMemory(
kwibergd3edd772017-03-01 18:52:48 -08001127 -(samples_left + rtc::dchecked_cast<int>(output_size_samples_)));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001128 }
1129
1130 // Check if it is time to play a DTMF event.
Peter Kastingb7e50542015-06-11 12:55:50 -07001131 if (dtmf_buffer_->GetEvent(
1132 static_cast<uint32_t>(
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001133 end_timestamp + generated_noise_samples),
Peter Kastingb7e50542015-06-11 12:55:50 -07001134 dtmf_event)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001135 *play_dtmf = true;
1136 }
1137
1138 // Get instruction.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001139 assert(sync_buffer_.get());
1140 assert(expand_.get());
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001141 generated_noise_samples =
1142 generated_noise_stopwatch_
1143 ? generated_noise_stopwatch_->ElapsedTicks() * output_size_samples_ +
1144 decision_logic_->noise_fast_forward()
1145 : 0;
1146 *operation = decision_logic_->GetDecision(
ossu7a377612016-10-18 04:06:13 -07001147 *sync_buffer_, *expand_, decoder_frame_length_, packet, last_mode_,
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001148 *play_dtmf, generated_noise_samples, &reset_decoder_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001149
1150 // Check if we already have enough samples in the |sync_buffer_|. If so,
1151 // change decision to normal, unless the decision was merge, accelerate, or
1152 // preemptive expand.
kwibergd3edd772017-03-01 18:52:48 -08001153 if (samples_left >= rtc::dchecked_cast<int>(output_size_samples_) &&
1154 *operation != kMerge && *operation != kAccelerate &&
1155 *operation != kFastAccelerate && *operation != kPreemptiveExpand) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001156 *operation = kNormal;
1157 return 0;
1158 }
1159
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001160 decision_logic_->ExpandDecision(*operation);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001161
1162 // Check conditions for reset.
1163 if (new_codec_ || *operation == kUndefined) {
1164 // The only valid reason to get kUndefined is that new_codec_ is set.
1165 assert(new_codec_);
ossu7a377612016-10-18 04:06:13 -07001166 if (*play_dtmf && !packet) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001167 timestamp_ = dtmf_event->timestamp;
1168 } else {
ossu7a377612016-10-18 04:06:13 -07001169 if (!packet) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001170 RTC_LOG(LS_ERROR) << "Packet missing where it shouldn't.";
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001171 return -1;
1172 }
ossu7a377612016-10-18 04:06:13 -07001173 timestamp_ = packet->timestamp;
ossu108ecec2016-07-08 08:45:18 -07001174 if (*operation == kRfc3389CngNoPacket &&
ossu7a377612016-10-18 04:06:13 -07001175 decoder_database_->IsComfortNoise(packet->payload_type)) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001176 // Change decision to CNG packet, since we do have a CNG packet, but it
1177 // was considered too early to use. Now, use it anyway.
1178 *operation = kRfc3389Cng;
1179 } else if (*operation != kRfc3389Cng) {
1180 *operation = kNormal;
1181 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001182 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001183 // Adjust |sync_buffer_| timestamp before setting |end_timestamp| to the
1184 // new value.
1185 sync_buffer_->IncreaseEndTimestamp(timestamp_ - end_timestamp);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001186 end_timestamp = timestamp_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001187 new_codec_ = false;
1188 decision_logic_->SoftReset();
1189 buffer_level_filter_->Reset();
1190 delay_manager_->Reset();
1191 stats_.ResetMcu();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001192 }
1193
Peter Kastingdce40cf2015-08-24 14:52:23 -07001194 size_t required_samples = output_size_samples_;
1195 const size_t samples_10_ms = static_cast<size_t>(80 * fs_mult_);
1196 const size_t samples_20_ms = 2 * samples_10_ms;
1197 const size_t samples_30_ms = 3 * samples_10_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001198
1199 switch (*operation) {
1200 case kExpand: {
1201 timestamp_ = end_timestamp;
1202 return 0;
1203 }
1204 case kRfc3389CngNoPacket:
1205 case kCodecInternalCng: {
1206 return 0;
1207 }
1208 case kDtmf: {
1209 // TODO(hlundin): Write test for this.
1210 // Update timestamp.
1211 timestamp_ = end_timestamp;
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001212 const uint64_t generated_noise_samples =
1213 generated_noise_stopwatch_
1214 ? generated_noise_stopwatch_->ElapsedTicks() *
1215 output_size_samples_ +
1216 decision_logic_->noise_fast_forward()
1217 : 0;
1218 if (generated_noise_samples > 0 && last_mode_ != kModeDtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001219 // Make a jump in timestamp due to the recently played comfort noise.
Peter Kastingb7e50542015-06-11 12:55:50 -07001220 uint32_t timestamp_jump =
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001221 static_cast<uint32_t>(generated_noise_samples);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001222 sync_buffer_->IncreaseEndTimestamp(timestamp_jump);
1223 timestamp_ += timestamp_jump;
1224 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001225 return 0;
1226 }
Henrik Lundincf808d22015-05-27 14:33:29 +02001227 case kAccelerate:
1228 case kFastAccelerate: {
1229 // In order to do an accelerate we need at least 30 ms of audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001230 if (samples_left >= static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001231 // Already have enough data, so we do not need to extract any more.
1232 decision_logic_->set_sample_memory(samples_left);
1233 decision_logic_->set_prev_time_scale(true);
1234 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001235 } else if (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001236 decoder_frame_length_ >= samples_30_ms) {
1237 // Avoid decoding more data as it might overflow the playout buffer.
1238 *operation = kNormal;
1239 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001240 } else if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001241 decoder_frame_length_ < samples_30_ms) {
1242 // Build up decoded data by decoding at least 20 ms of audio data. Do
1243 // not perform accelerate yet, but wait until we only need to do one
1244 // decoding.
1245 required_samples = 2 * output_size_samples_;
1246 *operation = kNormal;
1247 }
1248 // If none of the above is true, we have one of two possible situations:
1249 // (1) 20 ms <= samples_left < 30 ms and decoder_frame_length_ < 30 ms; or
1250 // (2) samples_left < 10 ms and decoder_frame_length_ >= 30 ms.
1251 // In either case, we move on with the accelerate decision, and decode one
1252 // frame now.
1253 break;
1254 }
1255 case kPreemptiveExpand: {
1256 // In order to do a preemptive expand we need at least 30 ms of decoded
1257 // audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001258 if ((samples_left >= static_cast<int>(samples_30_ms)) ||
1259 (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001260 decoder_frame_length_ >= samples_30_ms)) {
1261 // Already have enough data, so we do not need to extract any more.
1262 // Or, avoid decoding more data as it might overflow the playout buffer.
1263 // Still try preemptive expand, though.
1264 decision_logic_->set_sample_memory(samples_left);
1265 decision_logic_->set_prev_time_scale(true);
1266 return 0;
1267 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07001268 if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001269 decoder_frame_length_ < samples_30_ms) {
1270 // Build up decoded data by decoding at least 20 ms of audio data.
1271 // Still try to perform preemptive expand.
1272 required_samples = 2 * output_size_samples_;
1273 }
1274 // Move on with the preemptive expand decision.
1275 break;
1276 }
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001277 case kMerge: {
1278 required_samples =
1279 std::max(merge_->RequiredFutureSamples(), required_samples);
1280 break;
1281 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001282 default: {
1283 // Do nothing.
1284 }
1285 }
1286
1287 // Get packets from buffer.
1288 int extracted_samples = 0;
ossu7a377612016-10-18 04:06:13 -07001289 if (packet && *operation != kAlternativePlc &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001290 *operation != kAlternativePlcIncreaseTimestamp &&
1291 *operation != kAudioRepetition &&
1292 *operation != kAudioRepetitionIncreaseTimestamp) {
ossu7a377612016-10-18 04:06:13 -07001293 sync_buffer_->IncreaseEndTimestamp(packet->timestamp - end_timestamp);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001294 if (decision_logic_->CngOff()) {
1295 // Adjustment of timestamp only corresponds to an actual packet loss
1296 // if comfort noise is not played. If comfort noise was just played,
1297 // this adjustment of timestamp is only done to get back in sync with the
1298 // stream timestamp; no loss to report.
ossu7a377612016-10-18 04:06:13 -07001299 stats_.LostSamples(packet->timestamp - end_timestamp);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001300 }
1301
1302 if (*operation != kRfc3389Cng) {
1303 // We are about to decode and use a non-CNG packet.
1304 decision_logic_->SetCngOff();
1305 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001306
1307 extracted_samples = ExtractPackets(required_samples, packet_list);
1308 if (extracted_samples < 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001309 return kPacketBufferCorruption;
1310 }
1311 }
1312
Henrik Lundincf808d22015-05-27 14:33:29 +02001313 if (*operation == kAccelerate || *operation == kFastAccelerate ||
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001314 *operation == kPreemptiveExpand) {
1315 decision_logic_->set_sample_memory(samples_left + extracted_samples);
1316 decision_logic_->set_prev_time_scale(true);
1317 }
1318
Henrik Lundincf808d22015-05-27 14:33:29 +02001319 if (*operation == kAccelerate || *operation == kFastAccelerate) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001320 // Check that we have enough data (30ms) to do accelerate.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001321 if (extracted_samples + samples_left < static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001322 // TODO(hlundin): Write test for this.
1323 // Not enough, do normal operation instead.
1324 *operation = kNormal;
1325 }
1326 }
1327
1328 timestamp_ = end_timestamp;
1329 return 0;
1330}
1331
1332int NetEqImpl::Decode(PacketList* packet_list, Operations* operation,
1333 int* decoded_length,
1334 AudioDecoder::SpeechType* speech_type) {
1335 *speech_type = AudioDecoder::kSpeech;
minyuel6d92bf52015-09-23 15:20:39 +02001336
1337 // When packet_list is empty, we may be in kCodecInternalCng mode, and for
1338 // that we use current active decoder.
1339 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1340
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001341 if (!packet_list->empty()) {
ossua73f6c92016-10-24 08:25:28 -07001342 const Packet& packet = packet_list->front();
1343 uint8_t payload_type = packet.payload_type;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001344 if (!decoder_database_->IsComfortNoise(payload_type)) {
1345 decoder = decoder_database_->GetDecoder(payload_type);
1346 assert(decoder);
1347 if (!decoder) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001348 RTC_LOG(LS_WARNING)
1349 << "Unknown payload type " << static_cast<int>(payload_type);
ossua73f6c92016-10-24 08:25:28 -07001350 packet_list->clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001351 return kDecoderNotFound;
1352 }
1353 bool decoder_changed;
1354 decoder_database_->SetActiveDecoder(payload_type, &decoder_changed);
1355 if (decoder_changed) {
1356 // We have a new decoder. Re-init some values.
1357 const DecoderDatabase::DecoderInfo* decoder_info = decoder_database_
1358 ->GetDecoderInfo(payload_type);
1359 assert(decoder_info);
1360 if (!decoder_info) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001361 RTC_LOG(LS_WARNING)
1362 << "Unknown payload type " << static_cast<int>(payload_type);
ossua73f6c92016-10-24 08:25:28 -07001363 packet_list->clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001364 return kDecoderNotFound;
1365 }
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001366 // If sampling rate or number of channels has changed, we need to make
1367 // a reset.
kwibergc0f2dcf2016-05-31 06:28:03 -07001368 if (decoder_info->SampleRateHz() != fs_hz_ ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001369 decoder->Channels() != algorithm_buffer_->Channels()) {
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001370 // TODO(tlegrand): Add unittest to cover this event.
kwibergc0f2dcf2016-05-31 06:28:03 -07001371 SetSampleRateAndChannels(decoder_info->SampleRateHz(),
1372 decoder->Channels());
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001373 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001374 sync_buffer_->set_end_timestamp(timestamp_);
1375 playout_timestamp_ = timestamp_;
1376 }
1377 }
1378 }
1379
1380 if (reset_decoder_) {
1381 // TODO(hlundin): Write test for this.
Karl Wiberg43766482015-08-27 15:22:11 +02001382 if (decoder)
1383 decoder->Reset();
1384
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001385 // Reset comfort noise decoder.
ossu97ba30e2016-04-25 07:55:58 -07001386 ComfortNoiseDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02001387 if (cng_decoder)
1388 cng_decoder->Reset();
1389
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001390 reset_decoder_ = false;
1391 }
1392
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001393 *decoded_length = 0;
1394 // Update codec-internal PLC state.
1395 if ((*operation == kMerge) && decoder && decoder->HasDecodePlc()) {
1396 decoder->DecodePlc(1, &decoded_buffer_[*decoded_length]);
1397 }
1398
minyuel6d92bf52015-09-23 15:20:39 +02001399 int return_value;
1400 if (*operation == kCodecInternalCng) {
1401 RTC_DCHECK(packet_list->empty());
1402 return_value = DecodeCng(decoder, decoded_length, speech_type);
1403 } else {
1404 return_value = DecodeLoop(packet_list, *operation, decoder,
1405 decoded_length, speech_type);
1406 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001407
1408 if (*decoded_length < 0) {
1409 // Error returned from the decoder.
1410 *decoded_length = 0;
Peter Kastingb7e50542015-06-11 12:55:50 -07001411 sync_buffer_->IncreaseEndTimestamp(
1412 static_cast<uint32_t>(decoder_frame_length_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001413 int error_code = 0;
1414 if (decoder)
1415 error_code = decoder->ErrorCode();
1416 if (error_code != 0) {
1417 // Got some error code from the decoder.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001418 return_value = kDecoderErrorCode;
Mirko Bonadei675513b2017-11-09 11:09:25 +01001419 RTC_LOG(LS_WARNING) << "Decoder returned error code: " << error_code;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001420 } else {
1421 // Decoder does not implement error codes. Return generic error.
1422 return_value = kOtherDecoderError;
Mirko Bonadei675513b2017-11-09 11:09:25 +01001423 RTC_LOG(LS_WARNING) << "Decoder error (no error code)";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001424 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001425 *operation = kExpand; // Do expansion to get data instead.
1426 }
1427 if (*speech_type != AudioDecoder::kComfortNoise) {
1428 // Don't increment timestamp if codec returned CNG speech type
1429 // since in this case, the we will increment the CNGplayedTS counter.
1430 // Increase with number of samples per channel.
1431 assert(*decoded_length == 0 ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001432 (decoder && decoder->Channels() == sync_buffer_->Channels()));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001433 sync_buffer_->IncreaseEndTimestamp(
1434 *decoded_length / static_cast<int>(sync_buffer_->Channels()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001435 }
1436 return return_value;
1437}
1438
minyuel6d92bf52015-09-23 15:20:39 +02001439int NetEqImpl::DecodeCng(AudioDecoder* decoder, int* decoded_length,
1440 AudioDecoder::SpeechType* speech_type) {
1441 if (!decoder) {
1442 // This happens when active decoder is not defined.
1443 *decoded_length = -1;
1444 return 0;
1445 }
1446
kwibergd3edd772017-03-01 18:52:48 -08001447 while (*decoded_length < rtc::dchecked_cast<int>(output_size_samples_)) {
minyuel6d92bf52015-09-23 15:20:39 +02001448 const int length = decoder->Decode(
1449 nullptr, 0, fs_hz_,
1450 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1451 &decoded_buffer_[*decoded_length], speech_type);
1452 if (length > 0) {
1453 *decoded_length += length;
minyuel6d92bf52015-09-23 15:20:39 +02001454 } else {
1455 // Error.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001456 RTC_LOG(LS_WARNING) << "Failed to decode CNG";
minyuel6d92bf52015-09-23 15:20:39 +02001457 *decoded_length = -1;
1458 break;
1459 }
1460 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1461 // Guard against overflow.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001462 RTC_LOG(LS_WARNING) << "Decoded too much CNG.";
minyuel6d92bf52015-09-23 15:20:39 +02001463 return kDecodedTooMuch;
1464 }
1465 }
1466 return 0;
1467}
1468
1469int NetEqImpl::DecodeLoop(PacketList* packet_list, const Operations& operation,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001470 AudioDecoder* decoder, int* decoded_length,
1471 AudioDecoder::SpeechType* speech_type) {
henrik.lundin114c1b32017-04-26 07:47:32 -07001472 RTC_DCHECK(last_decoded_timestamps_.empty());
1473
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001474 // Do decoding.
ossua73f6c92016-10-24 08:25:28 -07001475 while (
1476 !packet_list->empty() &&
1477 !decoder_database_->IsComfortNoise(packet_list->front().payload_type)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001478 assert(decoder); // At this point, we must have a decoder object.
1479 // The number of channels in the |sync_buffer_| should be the same as the
1480 // number decoder channels.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001481 assert(sync_buffer_->Channels() == decoder->Channels());
1482 assert(decoded_buffer_length_ >= kMaxFrameSize * decoder->Channels());
minyuel6d92bf52015-09-23 15:20:39 +02001483 assert(operation == kNormal || operation == kAccelerate ||
1484 operation == kFastAccelerate || operation == kMerge ||
1485 operation == kPreemptiveExpand);
ossua73f6c92016-10-24 08:25:28 -07001486
1487 auto opt_result = packet_list->front().frame->Decode(
ossu61a208b2016-09-20 01:38:00 -07001488 rtc::ArrayView<int16_t>(&decoded_buffer_[*decoded_length],
1489 decoded_buffer_length_ - *decoded_length));
henrik.lundin114c1b32017-04-26 07:47:32 -07001490 last_decoded_timestamps_.push_back(packet_list->front().timestamp);
ossua73f6c92016-10-24 08:25:28 -07001491 packet_list->pop_front();
ossu61a208b2016-09-20 01:38:00 -07001492 if (opt_result) {
1493 const auto& result = *opt_result;
1494 *speech_type = result.speech_type;
1495 if (result.num_decoded_samples > 0) {
kwibergd3edd772017-03-01 18:52:48 -08001496 *decoded_length += rtc::dchecked_cast<int>(result.num_decoded_samples);
ossu61a208b2016-09-20 01:38:00 -07001497 // Update |decoder_frame_length_| with number of samples per channel.
1498 decoder_frame_length_ =
1499 result.num_decoded_samples / decoder->Channels();
1500 }
1501 } else {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001502 // Error.
ossu61a208b2016-09-20 01:38:00 -07001503 // TODO(ossu): What to put here?
Mirko Bonadei675513b2017-11-09 11:09:25 +01001504 RTC_LOG(LS_WARNING) << "Decode error";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001505 *decoded_length = -1;
ossua73f6c92016-10-24 08:25:28 -07001506 packet_list->clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001507 break;
1508 }
kwibergd3edd772017-03-01 18:52:48 -08001509 if (*decoded_length > rtc::dchecked_cast<int>(decoded_buffer_length_)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001510 // Guard against overflow.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001511 RTC_LOG(LS_WARNING) << "Decoded too much.";
ossua73f6c92016-10-24 08:25:28 -07001512 packet_list->clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001513 return kDecodedTooMuch;
1514 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001515 } // End of decode loop.
1516
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001517 // If the list is not empty at this point, either a decoding error terminated
1518 // the while-loop, or list must hold exactly one CNG packet.
ossua73f6c92016-10-24 08:25:28 -07001519 assert(
1520 packet_list->empty() || *decoded_length < 0 ||
1521 (packet_list->size() == 1 &&
1522 decoder_database_->IsComfortNoise(packet_list->front().payload_type)));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001523 return 0;
1524}
1525
1526void NetEqImpl::DoNormal(const int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001527 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001528 assert(normal_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001529 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001530 normal_->Process(decoded_buffer, decoded_length, last_mode_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001531 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001532 if (decoded_length != 0) {
1533 last_mode_ = kModeNormal;
1534 }
1535
1536 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1537 if ((speech_type == AudioDecoder::kComfortNoise)
1538 || ((last_mode_ == kModeCodecInternalCng)
1539 && (decoded_length == 0))) {
1540 // TODO(hlundin): Remove second part of || statement above.
1541 last_mode_ = kModeCodecInternalCng;
1542 }
1543
1544 if (!play_dtmf) {
1545 dtmf_tone_generator_->Reset();
1546 }
1547}
1548
1549void NetEqImpl::DoMerge(int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001550 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001551 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001552 assert(merge_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001553 size_t new_length = merge_->Process(decoded_buffer, decoded_length,
1554 mute_factor_array_.get(),
1555 algorithm_buffer_.get());
henrik.lundin2979f552017-05-05 05:04:16 -07001556 // Correction can be negative.
1557 int expand_length_correction =
1558 rtc::dchecked_cast<int>(new_length) -
1559 rtc::dchecked_cast<int>(decoded_length / algorithm_buffer_->Channels());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001560
1561 // Update in-call and post-call statistics.
1562 if (expand_->MuteFactor(0) == 0) {
1563 // Expand generates only noise.
henrik.lundin2979f552017-05-05 05:04:16 -07001564 stats_.ExpandedNoiseSamplesCorrection(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001565 } else {
1566 // Expansion generates more than only noise.
henrik.lundin2979f552017-05-05 05:04:16 -07001567 stats_.ExpandedVoiceSamplesCorrection(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001568 }
1569
1570 last_mode_ = kModeMerge;
1571 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1572 if (speech_type == AudioDecoder::kComfortNoise) {
1573 last_mode_ = kModeCodecInternalCng;
1574 }
1575 expand_->Reset();
1576 if (!play_dtmf) {
1577 dtmf_tone_generator_->Reset();
1578 }
1579}
1580
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001581int NetEqImpl::DoExpand(bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001582 while ((sync_buffer_->FutureLength() - expand_->overlap_length()) <
Peter Kastingdce40cf2015-08-24 14:52:23 -07001583 output_size_samples_) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001584 algorithm_buffer_->Clear();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001585 int return_value = expand_->Process(algorithm_buffer_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001586 size_t length = algorithm_buffer_->Size();
Gustaf Ullberg9a2e9062017-09-18 09:28:20 +02001587 bool is_new_concealment_event = (last_mode_ != kModeExpand);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001588
1589 // Update in-call and post-call statistics.
1590 if (expand_->MuteFactor(0) == 0) {
1591 // Expand operation generates only noise.
Gustaf Ullberg9a2e9062017-09-18 09:28:20 +02001592 stats_.ExpandedNoiseSamples(length, is_new_concealment_event);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001593 } else {
1594 // Expand operation generates more than only noise.
Gustaf Ullberg9a2e9062017-09-18 09:28:20 +02001595 stats_.ExpandedVoiceSamples(length, is_new_concealment_event);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001596 }
1597
1598 last_mode_ = kModeExpand;
1599
1600 if (return_value < 0) {
1601 return return_value;
1602 }
1603
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001604 sync_buffer_->PushBack(*algorithm_buffer_);
1605 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001606 }
1607 if (!play_dtmf) {
1608 dtmf_tone_generator_->Reset();
1609 }
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001610
1611 if (!generated_noise_stopwatch_) {
1612 // Start a new stopwatch since we may be covering for a lost CNG packet.
1613 generated_noise_stopwatch_ = tick_timer_->GetNewStopwatch();
1614 }
1615
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001616 return 0;
1617}
1618
Henrik Lundincf808d22015-05-27 14:33:29 +02001619int NetEqImpl::DoAccelerate(int16_t* decoded_buffer,
1620 size_t decoded_length,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001621 AudioDecoder::SpeechType speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +02001622 bool play_dtmf,
1623 bool fast_accelerate) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001624 const size_t required_samples =
1625 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001626 size_t borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001627 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001628 size_t decoded_length_per_channel = decoded_length / num_channels;
1629 if (decoded_length_per_channel < required_samples) {
1630 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001631 borrowed_samples_per_channel = static_cast<int>(required_samples -
1632 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001633 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1634 decoded_buffer,
1635 sizeof(int16_t) * decoded_length);
1636 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1637 decoded_buffer);
1638 decoded_length = required_samples * num_channels;
1639 }
1640
Peter Kastingdce40cf2015-08-24 14:52:23 -07001641 size_t samples_removed;
Henrik Lundincf808d22015-05-27 14:33:29 +02001642 Accelerate::ReturnCodes return_code =
1643 accelerate_->Process(decoded_buffer, decoded_length, fast_accelerate,
1644 algorithm_buffer_.get(), &samples_removed);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001645 stats_.AcceleratedSamples(samples_removed);
1646 switch (return_code) {
1647 case Accelerate::kSuccess:
1648 last_mode_ = kModeAccelerateSuccess;
1649 break;
1650 case Accelerate::kSuccessLowEnergy:
1651 last_mode_ = kModeAccelerateLowEnergy;
1652 break;
1653 case Accelerate::kNoStretch:
1654 last_mode_ = kModeAccelerateFail;
1655 break;
1656 case Accelerate::kError:
1657 // TODO(hlundin): Map to kModeError instead?
1658 last_mode_ = kModeAccelerateFail;
1659 return kAccelerateError;
1660 }
1661
1662 if (borrowed_samples_per_channel > 0) {
1663 // Copy borrowed samples back to the |sync_buffer_|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001664 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001665 if (length < borrowed_samples_per_channel) {
1666 // This destroys the beginning of the buffer, but will not cause any
1667 // problems.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001668 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001669 sync_buffer_->Size() -
1670 borrowed_samples_per_channel);
1671 sync_buffer_->PushFrontZeros(borrowed_samples_per_channel - length);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001672 algorithm_buffer_->PopFront(length);
1673 assert(algorithm_buffer_->Empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001674 } else {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001675 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001676 borrowed_samples_per_channel,
1677 sync_buffer_->Size() -
1678 borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001679 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001680 }
1681 }
1682
1683 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1684 if (speech_type == AudioDecoder::kComfortNoise) {
1685 last_mode_ = kModeCodecInternalCng;
1686 }
1687 if (!play_dtmf) {
1688 dtmf_tone_generator_->Reset();
1689 }
1690 expand_->Reset();
1691 return 0;
1692}
1693
1694int NetEqImpl::DoPreemptiveExpand(int16_t* decoded_buffer,
1695 size_t decoded_length,
1696 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001697 bool play_dtmf) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001698 const size_t required_samples =
1699 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001700 size_t num_channels = algorithm_buffer_->Channels();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001701 size_t borrowed_samples_per_channel = 0;
1702 size_t old_borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001703 size_t decoded_length_per_channel = decoded_length / num_channels;
1704 if (decoded_length_per_channel < required_samples) {
1705 // Must move data from the |sync_buffer_| in order to get 30 ms.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001706 borrowed_samples_per_channel =
1707 required_samples - decoded_length_per_channel;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001708 // Calculate how many of these were already played out.
Peter Kastingf045e4d2015-06-10 21:15:38 -07001709 old_borrowed_samples_per_channel =
Peter Kastingdce40cf2015-08-24 14:52:23 -07001710 (borrowed_samples_per_channel > sync_buffer_->FutureLength()) ?
1711 (borrowed_samples_per_channel - sync_buffer_->FutureLength()) : 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001712 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1713 decoded_buffer,
1714 sizeof(int16_t) * decoded_length);
1715 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1716 decoded_buffer);
1717 decoded_length = required_samples * num_channels;
1718 }
1719
Peter Kastingdce40cf2015-08-24 14:52:23 -07001720 size_t samples_added;
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001721 PreemptiveExpand::ReturnCodes return_code = preemptive_expand_->Process(
Peter Kastingdce40cf2015-08-24 14:52:23 -07001722 decoded_buffer, decoded_length,
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001723 old_borrowed_samples_per_channel,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001724 algorithm_buffer_.get(), &samples_added);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001725 stats_.PreemptiveExpandedSamples(samples_added);
1726 switch (return_code) {
1727 case PreemptiveExpand::kSuccess:
1728 last_mode_ = kModePreemptiveExpandSuccess;
1729 break;
1730 case PreemptiveExpand::kSuccessLowEnergy:
1731 last_mode_ = kModePreemptiveExpandLowEnergy;
1732 break;
1733 case PreemptiveExpand::kNoStretch:
1734 last_mode_ = kModePreemptiveExpandFail;
1735 break;
1736 case PreemptiveExpand::kError:
1737 // TODO(hlundin): Map to kModeError instead?
1738 last_mode_ = kModePreemptiveExpandFail;
1739 return kPreemptiveExpandError;
1740 }
1741
1742 if (borrowed_samples_per_channel > 0) {
1743 // Copy borrowed samples back to the |sync_buffer_|.
1744 sync_buffer_->ReplaceAtIndex(
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001745 *algorithm_buffer_, borrowed_samples_per_channel,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001746 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001747 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001748 }
1749
1750 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1751 if (speech_type == AudioDecoder::kComfortNoise) {
1752 last_mode_ = kModeCodecInternalCng;
1753 }
1754 if (!play_dtmf) {
1755 dtmf_tone_generator_->Reset();
1756 }
1757 expand_->Reset();
1758 return 0;
1759}
1760
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001761int NetEqImpl::DoRfc3389Cng(PacketList* packet_list, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001762 if (!packet_list->empty()) {
1763 // Must have exactly one SID frame at this point.
1764 assert(packet_list->size() == 1);
ossua73f6c92016-10-24 08:25:28 -07001765 const Packet& packet = packet_list->front();
1766 if (!decoder_database_->IsComfortNoise(packet.payload_type)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001767 RTC_LOG(LS_ERROR) << "Trying to decode non-CNG payload as CNG.";
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001768 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001769 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001770 if (comfort_noise_->UpdateParameters(packet) ==
1771 ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001772 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001773 return -comfort_noise_->internal_error_code();
1774 }
1775 }
1776 int cn_return = comfort_noise_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001777 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001778 expand_->Reset();
1779 last_mode_ = kModeRfc3389Cng;
1780 if (!play_dtmf) {
1781 dtmf_tone_generator_->Reset();
1782 }
1783 if (cn_return == ComfortNoise::kInternalError) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001784 RTC_LOG(LS_WARNING) << "Comfort noise generator returned error code: "
1785 << comfort_noise_->internal_error_code();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001786 return kComfortNoiseErrorCode;
1787 } else if (cn_return == ComfortNoise::kUnknownPayloadType) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001788 return kUnknownRtpPayloadType;
1789 }
1790 return 0;
1791}
1792
minyuel6d92bf52015-09-23 15:20:39 +02001793void NetEqImpl::DoCodecInternalCng(const int16_t* decoded_buffer,
1794 size_t decoded_length) {
1795 RTC_DCHECK(normal_.get());
1796 RTC_DCHECK(mute_factor_array_.get());
1797 normal_->Process(decoded_buffer, decoded_length, last_mode_,
1798 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001799 last_mode_ = kModeCodecInternalCng;
1800 expand_->Reset();
1801}
1802
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001803int NetEqImpl::DoDtmf(const DtmfEvent& dtmf_event, bool* play_dtmf) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001804 // This block of the code and the block further down, handling |dtmf_switch|
1805 // are commented out. Otherwise playing out-of-band DTMF would fail in VoE
1806 // test, DtmfTest.ManualSuccessfullySendsOutOfBandTelephoneEvents. This is
1807 // equivalent to |dtmf_switch| always be false.
1808 //
1809 // See http://webrtc-codereview.appspot.com/1195004/ for discussion
1810 // On this issue. This change might cause some glitches at the point of
1811 // switch from audio to DTMF. Issue 1545 is filed to track this.
1812 //
1813 // bool dtmf_switch = false;
1814 // if ((last_mode_ != kModeDtmf) && dtmf_tone_generator_->initialized()) {
1815 // // Special case; see below.
1816 // // We must catch this before calling Generate, since |initialized| is
1817 // // modified in that call.
1818 // dtmf_switch = true;
1819 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001820
1821 int dtmf_return_value = 0;
1822 if (!dtmf_tone_generator_->initialized()) {
1823 // Initialize if not already done.
1824 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1825 dtmf_event.volume);
1826 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001827
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001828 if (dtmf_return_value == 0) {
1829 // Generate DTMF signal.
1830 dtmf_return_value = dtmf_tone_generator_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001831 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001832 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001833
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001834 if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001835 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001836 return dtmf_return_value;
1837 }
1838
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001839 // if (dtmf_switch) {
1840 // // This is the special case where the previous operation was DTMF
1841 // // overdub, but the current instruction is "regular" DTMF. We must make
1842 // // sure that the DTMF does not have any discontinuities. The first DTMF
1843 // // sample that we generate now must be played out immediately, therefore
1844 // // it must be copied to the speech buffer.
1845 // // TODO(hlundin): This code seems incorrect. (Legacy.) Write test and
1846 // // verify correct operation.
1847 // assert(false);
1848 // // Must generate enough data to replace all of the |sync_buffer_|
1849 // // "future".
1850 // int required_length = sync_buffer_->FutureLength();
1851 // assert(dtmf_tone_generator_->initialized());
1852 // dtmf_return_value = dtmf_tone_generator_->Generate(required_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001853 // algorithm_buffer_);
1854 // assert((size_t) required_length == algorithm_buffer_->Size());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001855 // if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001856 // algorithm_buffer_->Zeros(output_size_samples_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001857 // return dtmf_return_value;
1858 // }
1859 //
1860 // // Overwrite the "future" part of the speech buffer with the new DTMF
1861 // // data.
1862 // // TODO(hlundin): It seems that this overwriting has gone lost.
1863 // // Not adapted for multi-channel yet.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001864 // assert(algorithm_buffer_->Channels() == 1);
1865 // if (algorithm_buffer_->Channels() != 1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001866 // RTC_LOG(LS_WARNING) << "DTMF not supported for more than one channel";
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001867 // return kStereoNotSupported;
1868 // }
1869 // // Shuffle the remaining data to the beginning of algorithm buffer.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001870 // algorithm_buffer_->PopFront(sync_buffer_->FutureLength());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001871 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001872
Peter Kastingb7e50542015-06-11 12:55:50 -07001873 sync_buffer_->IncreaseEndTimestamp(
1874 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001875 expand_->Reset();
1876 last_mode_ = kModeDtmf;
1877
1878 // Set to false because the DTMF is already in the algorithm buffer.
1879 *play_dtmf = false;
1880 return 0;
1881}
1882
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001883void NetEqImpl::DoAlternativePlc(bool increase_timestamp) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001884 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001885 size_t length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001886 if (decoder && decoder->HasDecodePlc()) {
1887 // Use the decoder's packet-loss concealment.
1888 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1889 int16_t decoded_buffer[kMaxFrameSize];
1890 length = decoder->DecodePlc(1, decoded_buffer);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001891 if (length > 0)
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001892 algorithm_buffer_->PushBackInterleaved(decoded_buffer, length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001893 } else {
1894 // Do simple zero-stuffing.
1895 length = output_size_samples_;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001896 algorithm_buffer_->Zeros(length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001897 // By not advancing the timestamp, NetEq inserts samples.
1898 stats_.AddZeros(length);
1899 }
1900 if (increase_timestamp) {
Peter Kastingb7e50542015-06-11 12:55:50 -07001901 sync_buffer_->IncreaseEndTimestamp(static_cast<uint32_t>(length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001902 }
1903 expand_->Reset();
1904}
1905
1906int NetEqImpl::DtmfOverdub(const DtmfEvent& dtmf_event, size_t num_channels,
1907 int16_t* output) const {
1908 size_t out_index = 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001909 size_t overdub_length = output_size_samples_; // Default value.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001910
1911 if (sync_buffer_->dtmf_index() > sync_buffer_->next_index()) {
1912 // Special operation for transition from "DTMF only" to "DTMF overdub".
1913 out_index = std::min(
1914 sync_buffer_->dtmf_index() - sync_buffer_->next_index(),
Peter Kastingdce40cf2015-08-24 14:52:23 -07001915 output_size_samples_);
1916 overdub_length = output_size_samples_ - out_index;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001917 }
1918
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001919 AudioMultiVector dtmf_output(num_channels);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001920 int dtmf_return_value = 0;
1921 if (!dtmf_tone_generator_->initialized()) {
1922 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1923 dtmf_event.volume);
1924 }
1925 if (dtmf_return_value == 0) {
1926 dtmf_return_value = dtmf_tone_generator_->Generate(overdub_length,
1927 &dtmf_output);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001928 assert(overdub_length == dtmf_output.Size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001929 }
1930 dtmf_output.ReadInterleaved(overdub_length, &output[out_index]);
1931 return dtmf_return_value < 0 ? dtmf_return_value : 0;
1932}
1933
Peter Kastingdce40cf2015-08-24 14:52:23 -07001934int NetEqImpl::ExtractPackets(size_t required_samples,
1935 PacketList* packet_list) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001936 bool first_packet = true;
1937 uint8_t prev_payload_type = 0;
1938 uint32_t prev_timestamp = 0;
1939 uint16_t prev_sequence_number = 0;
1940 bool next_packet_available = false;
1941
ossu7a377612016-10-18 04:06:13 -07001942 const Packet* next_packet = packet_buffer_->PeekNextPacket();
1943 RTC_DCHECK(next_packet);
1944 if (!next_packet) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001945 RTC_LOG(LS_ERROR) << "Packet buffer unexpectedly empty.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001946 return -1;
1947 }
ossu7a377612016-10-18 04:06:13 -07001948 uint32_t first_timestamp = next_packet->timestamp;
ossu61a208b2016-09-20 01:38:00 -07001949 size_t extracted_samples = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001950
1951 // Packet extraction loop.
1952 do {
ossu7a377612016-10-18 04:06:13 -07001953 timestamp_ = next_packet->timestamp;
ossua73f6c92016-10-24 08:25:28 -07001954 rtc::Optional<Packet> packet = packet_buffer_->GetNextPacket();
ossu7a377612016-10-18 04:06:13 -07001955 // |next_packet| may be invalid after the |packet_buffer_| operation.
ossua73f6c92016-10-24 08:25:28 -07001956 next_packet = nullptr;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001957 if (!packet) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001958 RTC_LOG(LS_ERROR) << "Should always be able to extract a packet here";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001959 assert(false); // Should always be able to extract a packet here.
1960 return -1;
1961 }
Gustaf Ullbergb0a02072017-10-02 12:00:34 +02001962 const uint64_t waiting_time_ms = packet->waiting_time->ElapsedMs();
1963 stats_.StoreWaitingTime(waiting_time_ms);
ossu61a208b2016-09-20 01:38:00 -07001964 RTC_DCHECK(!packet->empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001965
1966 if (first_packet) {
1967 first_packet = false;
henrik.lundin48ed9302015-10-29 05:36:24 -07001968 if (nack_enabled_) {
1969 RTC_DCHECK(nack_);
1970 // TODO(henrik.lundin): Should we update this for all decoded packets?
ossu7a377612016-10-18 04:06:13 -07001971 nack_->UpdateLastDecodedPacket(packet->sequence_number,
1972 packet->timestamp);
henrik.lundin48ed9302015-10-29 05:36:24 -07001973 }
ossu7a377612016-10-18 04:06:13 -07001974 prev_sequence_number = packet->sequence_number;
1975 prev_timestamp = packet->timestamp;
1976 prev_payload_type = packet->payload_type;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001977 }
1978
ossucafb4972017-01-02 07:00:50 -08001979 const bool has_cng_packet =
1980 decoder_database_->IsComfortNoise(packet->payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001981 // Store number of extracted samples.
ossu61a208b2016-09-20 01:38:00 -07001982 size_t packet_duration = 0;
1983 if (packet->frame) {
1984 packet_duration = packet->frame->Duration();
ossua70695a2016-09-22 02:06:28 -07001985 // TODO(ossu): Is this the correct way to track Opus FEC packets?
1986 if (packet->priority.codec_level > 0) {
kwibergd3edd772017-03-01 18:52:48 -08001987 stats_.SecondaryDecodedSamples(
1988 rtc::dchecked_cast<int>(packet_duration));
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001989 }
ossucafb4972017-01-02 07:00:50 -08001990 } else if (!has_cng_packet) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001991 RTC_LOG(LS_WARNING) << "Unknown payload type "
1992 << static_cast<int>(packet->payload_type);
ossu61a208b2016-09-20 01:38:00 -07001993 RTC_NOTREACHED();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001994 }
ossu61a208b2016-09-20 01:38:00 -07001995
1996 if (packet_duration == 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001997 // Decoder did not return a packet duration. Assume that the packet
1998 // contains the same number of samples as the previous one.
ossu61a208b2016-09-20 01:38:00 -07001999 packet_duration = decoder_frame_length_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002000 }
ossu7a377612016-10-18 04:06:13 -07002001 extracted_samples = packet->timestamp - first_timestamp + packet_duration;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002002
Gustaf Ullbergb0a02072017-10-02 12:00:34 +02002003 stats_.JitterBufferDelay(extracted_samples, waiting_time_ms);
2004
ossua73f6c92016-10-24 08:25:28 -07002005 packet_list->push_back(std::move(*packet)); // Store packet in list.
Oskar Sundbom12ab00b2017-11-16 15:31:38 +01002006 packet = rtc::nullopt; // Ensure it's never used after the move.
ossua73f6c92016-10-24 08:25:28 -07002007
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002008 // Check what packet is available next.
ossu7a377612016-10-18 04:06:13 -07002009 next_packet = packet_buffer_->PeekNextPacket();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002010 next_packet_available = false;
ossucafb4972017-01-02 07:00:50 -08002011 if (next_packet && prev_payload_type == next_packet->payload_type &&
2012 !has_cng_packet) {
ossu7a377612016-10-18 04:06:13 -07002013 int16_t seq_no_diff = next_packet->sequence_number - prev_sequence_number;
2014 size_t ts_diff = next_packet->timestamp - prev_timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002015 if (seq_no_diff == 1 ||
2016 (seq_no_diff == 0 && ts_diff == decoder_frame_length_)) {
2017 // The next sequence number is available, or the next part of a packet
2018 // that was split into pieces upon insertion.
2019 next_packet_available = true;
2020 }
ossu7a377612016-10-18 04:06:13 -07002021 prev_sequence_number = next_packet->sequence_number;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002022 }
ossu61a208b2016-09-20 01:38:00 -07002023 } while (extracted_samples < required_samples && next_packet_available);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002024
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00002025 if (extracted_samples > 0) {
2026 // Delete old packets only when we are going to decode something. Otherwise,
2027 // we could end up in the situation where we never decode anything, since
2028 // all incoming packets are considered too old but the buffer will also
2029 // never be flooded and flushed.
minyue-webrtcfae474c2017-07-05 11:17:40 +02002030 packet_buffer_->DiscardAllOldPackets(timestamp_, &stats_);
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00002031 }
2032
kwibergd3edd772017-03-01 18:52:48 -08002033 return rtc::dchecked_cast<int>(extracted_samples);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002034}
2035
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002036void NetEqImpl::UpdatePlcComponents(int fs_hz, size_t channels) {
2037 // Delete objects and create new ones.
2038 expand_.reset(expand_factory_->Create(background_noise_.get(),
2039 sync_buffer_.get(), &random_vector_,
Henrik Lundinbef77e22015-08-18 14:58:09 +02002040 &stats_, fs_hz, channels));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002041 merge_.reset(new Merge(fs_hz, channels, expand_.get(), sync_buffer_.get()));
2042}
2043
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002044void NetEqImpl::SetSampleRateAndChannels(int fs_hz, size_t channels) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002045 RTC_LOG(LS_VERBOSE) << "SetSampleRateAndChannels " << fs_hz << " "
2046 << channels;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002047 // TODO(hlundin): Change to an enumerator and skip assert.
2048 assert(fs_hz == 8000 || fs_hz == 16000 || fs_hz == 32000 || fs_hz == 48000);
2049 assert(channels > 0);
2050
2051 fs_hz_ = fs_hz;
2052 fs_mult_ = fs_hz / 8000;
Peter Kastingdce40cf2015-08-24 14:52:23 -07002053 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002054 decoder_frame_length_ = 3 * output_size_samples_; // Initialize to 30ms.
2055
2056 last_mode_ = kModeNormal;
2057
2058 // Create a new array of mute factors and set all to 1.
2059 mute_factor_array_.reset(new int16_t[channels]);
2060 for (size_t i = 0; i < channels; ++i) {
2061 mute_factor_array_[i] = 16384; // 1.0 in Q14.
2062 }
2063
ossu97ba30e2016-04-25 07:55:58 -07002064 ComfortNoiseDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02002065 if (cng_decoder)
2066 cng_decoder->Reset();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002067
2068 // Reinit post-decode VAD with new sample rate.
2069 assert(vad_.get()); // Cannot be NULL here.
2070 vad_->Init();
2071
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002072 // Delete algorithm buffer and create a new one.
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00002073 algorithm_buffer_.reset(new AudioMultiVector(channels));
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002074
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002075 // Delete sync buffer and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002076 sync_buffer_.reset(new SyncBuffer(channels, kSyncBufferSize * fs_mult_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002077
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00002078 // Delete BackgroundNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002079 background_noise_.reset(new BackgroundNoise(channels));
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00002080 background_noise_->set_mode(background_noise_mode_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002081
2082 // Reset random vector.
2083 random_vector_.Reset();
2084
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002085 UpdatePlcComponents(fs_hz, channels);
2086
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002087 // Move index so that we create a small set of future samples (all 0).
2088 sync_buffer_->set_next_index(sync_buffer_->next_index() -
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002089 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002090
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002091 normal_.reset(new Normal(fs_hz, decoder_database_.get(), *background_noise_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002092 expand_.get()));
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +00002093 accelerate_.reset(
2094 accelerate_factory_->Create(fs_hz, channels, *background_noise_));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002095 preemptive_expand_.reset(preemptive_expand_factory_->Create(
Peter Kastingdce40cf2015-08-24 14:52:23 -07002096 fs_hz, channels, *background_noise_, expand_->overlap_length()));
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002097
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002098 // Delete ComfortNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002099 comfort_noise_.reset(new ComfortNoise(fs_hz, decoder_database_.get(),
2100 sync_buffer_.get()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002101
2102 // Verify that |decoded_buffer_| is long enough.
2103 if (decoded_buffer_length_ < kMaxFrameSize * channels) {
2104 // Reallocate to larger size.
2105 decoded_buffer_length_ = kMaxFrameSize * channels;
2106 decoded_buffer_.reset(new int16_t[decoded_buffer_length_]);
2107 }
2108
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002109 // Create DecisionLogic if it is not created yet, then communicate new sample
2110 // rate and output size to DecisionLogic object.
2111 if (!decision_logic_.get()) {
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002112 CreateDecisionLogic();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002113 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002114 decision_logic_->SetSampleRate(fs_hz_, output_size_samples_);
2115}
2116
henrik.lundin55480f52016-03-08 02:37:57 -08002117NetEqImpl::OutputType NetEqImpl::LastOutputType() {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002118 assert(vad_.get());
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002119 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002120 if (last_mode_ == kModeCodecInternalCng || last_mode_ == kModeRfc3389Cng) {
henrik.lundin55480f52016-03-08 02:37:57 -08002121 return OutputType::kCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002122 } else if (last_mode_ == kModeExpand && expand_->MuteFactor(0) == 0) {
2123 // Expand mode has faded down to background noise only (very long expand).
henrik.lundin55480f52016-03-08 02:37:57 -08002124 return OutputType::kPLCCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002125 } else if (last_mode_ == kModeExpand) {
henrik.lundin55480f52016-03-08 02:37:57 -08002126 return OutputType::kPLC;
wu@webrtc.org24301a62013-12-13 19:17:43 +00002127 } else if (vad_->running() && !vad_->active_speech()) {
henrik.lundin55480f52016-03-08 02:37:57 -08002128 return OutputType::kVadPassive;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002129 } else {
henrik.lundin55480f52016-03-08 02:37:57 -08002130 return OutputType::kNormalSpeech;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002131 }
2132}
2133
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002134void NetEqImpl::CreateDecisionLogic() {
Henrik Lundin47b17dc2016-05-10 10:20:59 +02002135 decision_logic_.reset(DecisionLogic::Create(
2136 fs_hz_, output_size_samples_, playout_mode_, decoder_database_.get(),
2137 *packet_buffer_.get(), delay_manager_.get(), buffer_level_filter_.get(),
2138 tick_timer_.get()));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002139}
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002140} // namespace webrtc