blob: 85e3690c9d20d366d90c98179a5484a0c00651c8 [file] [log] [blame]
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001/*
2 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "modules/audio_coding/neteq/neteq_impl.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000012
13#include <assert.h>
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000014
15#include <algorithm>
ossu61a208b2016-09-20 01:38:00 -070016#include <utility>
ossu97ba30e2016-04-25 07:55:58 -070017#include <vector>
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000018
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020019#include "api/audio_codecs/audio_decoder.h"
20#include "common_audio/signal_processing/include/signal_processing_library.h"
21#include "modules/audio_coding/neteq/accelerate.h"
22#include "modules/audio_coding/neteq/background_noise.h"
23#include "modules/audio_coding/neteq/buffer_level_filter.h"
24#include "modules/audio_coding/neteq/comfort_noise.h"
25#include "modules/audio_coding/neteq/decision_logic.h"
26#include "modules/audio_coding/neteq/decoder_database.h"
27#include "modules/audio_coding/neteq/defines.h"
28#include "modules/audio_coding/neteq/delay_manager.h"
29#include "modules/audio_coding/neteq/delay_peak_detector.h"
30#include "modules/audio_coding/neteq/dtmf_buffer.h"
31#include "modules/audio_coding/neteq/dtmf_tone_generator.h"
32#include "modules/audio_coding/neteq/expand.h"
33#include "modules/audio_coding/neteq/merge.h"
34#include "modules/audio_coding/neteq/nack_tracker.h"
35#include "modules/audio_coding/neteq/normal.h"
36#include "modules/audio_coding/neteq/packet.h"
37#include "modules/audio_coding/neteq/packet_buffer.h"
38#include "modules/audio_coding/neteq/post_decode_vad.h"
39#include "modules/audio_coding/neteq/preemptive_expand.h"
40#include "modules/audio_coding/neteq/red_payload_splitter.h"
41#include "modules/audio_coding/neteq/sync_buffer.h"
42#include "modules/audio_coding/neteq/tick_timer.h"
43#include "modules/audio_coding/neteq/timestamp_scaler.h"
44#include "modules/include/module_common_types.h"
45#include "rtc_base/checks.h"
46#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010047#include "rtc_base/numerics/safe_conversions.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020048#include "rtc_base/sanitizer.h"
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 Lundin4f2a4a12018-01-26 17:32:56 +0100106 enable_muted_state_(config.enable_muted_state) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100107 RTC_LOG(LS_INFO) << "NetEq config: " << config.ToString();
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +0000108 int fs = config.sample_rate_hz;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000109 if (fs != 8000 && fs != 16000 && fs != 32000 && fs != 48000) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100110 RTC_LOG(LS_ERROR) << "Sample rate " << fs << " Hz not supported. "
111 << "Changing to 8000 Hz.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000112 fs = 8000;
113 }
henrik.lundin1d9061e2016-04-26 12:19:34 -0700114 delay_manager_->SetMaximumDelay(config.max_delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000115 fs_hz_ = fs;
116 fs_mult_ = fs / 8000;
henrik.lundind89814b2015-11-23 06:49:25 -0800117 last_output_sample_rate_hz_ = fs;
Peter Kastingdce40cf2015-08-24 14:52:23 -0700118 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000119 decoder_frame_length_ = 3 * output_size_samples_;
120 WebRtcSpl_Init();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000121 if (create_components) {
122 SetSampleRateAndChannels(fs, 1); // Default is 1 channel.
123 }
henrik.lundin9bc26672015-11-02 03:25:57 -0800124 RTC_DCHECK(!vad_->enabled());
125 if (config.enable_post_decode_vad) {
126 vad_->Enable();
127 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000128}
129
Henrik Lundind67a2192015-08-03 12:54:37 +0200130NetEqImpl::~NetEqImpl() = default;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000131
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200132int NetEqImpl::InsertPacket(const RTPHeader& rtp_header,
kwibergee2bac22015-11-11 10:34:00 -0800133 rtc::ArrayView<const uint8_t> payload,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000134 uint32_t receive_timestamp) {
kwibergac554ee2016-09-02 00:39:33 -0700135 rtc::MsanCheckInitialized(payload);
henrik.lundina689b442015-12-17 03:50:05 -0800136 TRACE_EVENT0("webrtc", "NetEqImpl::InsertPacket");
Tommi9090e0b2016-01-20 13:39:36 +0100137 rtc::CritScope lock(&crit_sect_);
Henrik Lundinc417d9e2017-06-14 12:29:03 +0200138 if (InsertPacketInternal(rtp_header, payload, receive_timestamp) != 0) {
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000139 return kFail;
140 }
141 return kOK;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000142}
143
henrik.lundinb8c55b12017-05-10 07:38:01 -0700144void NetEqImpl::InsertEmptyPacket(const RTPHeader& /*rtp_header*/) {
145 // TODO(henrik.lundin) Handle NACK as well. This will make use of the
146 // rtp_header parameter.
147 // https://bugs.chromium.org/p/webrtc/issues/detail?id=7611
148 rtc::CritScope lock(&crit_sect_);
149 delay_manager_->RegisterEmptyPacket();
150}
151
henrik.lundin500c04b2016-03-08 02:36:04 -0800152namespace {
153void SetAudioFrameActivityAndType(bool vad_enabled,
henrik.lundin55480f52016-03-08 02:37:57 -0800154 NetEqImpl::OutputType type,
henrik.lundin500c04b2016-03-08 02:36:04 -0800155 AudioFrame::VADActivity last_vad_activity,
156 AudioFrame* audio_frame) {
157 switch (type) {
henrik.lundin55480f52016-03-08 02:37:57 -0800158 case NetEqImpl::OutputType::kNormalSpeech: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800159 audio_frame->speech_type_ = AudioFrame::kNormalSpeech;
160 audio_frame->vad_activity_ = AudioFrame::kVadActive;
161 break;
162 }
henrik.lundin55480f52016-03-08 02:37:57 -0800163 case NetEqImpl::OutputType::kVadPassive: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800164 // This should only be reached if the VAD is enabled.
165 RTC_DCHECK(vad_enabled);
166 audio_frame->speech_type_ = AudioFrame::kNormalSpeech;
167 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
168 break;
169 }
henrik.lundin55480f52016-03-08 02:37:57 -0800170 case NetEqImpl::OutputType::kCNG: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800171 audio_frame->speech_type_ = AudioFrame::kCNG;
172 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
173 break;
174 }
henrik.lundin55480f52016-03-08 02:37:57 -0800175 case NetEqImpl::OutputType::kPLC: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800176 audio_frame->speech_type_ = AudioFrame::kPLC;
177 audio_frame->vad_activity_ = last_vad_activity;
178 break;
179 }
henrik.lundin55480f52016-03-08 02:37:57 -0800180 case NetEqImpl::OutputType::kPLCCNG: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800181 audio_frame->speech_type_ = AudioFrame::kPLCCNG;
182 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
183 break;
184 }
185 default:
186 RTC_NOTREACHED();
187 }
188 if (!vad_enabled) {
189 // Always set kVadUnknown when receive VAD is inactive.
190 audio_frame->vad_activity_ = AudioFrame::kVadUnknown;
191 }
192}
henrik.lundinbc89de32016-03-08 05:20:14 -0800193} // namespace
henrik.lundin500c04b2016-03-08 02:36:04 -0800194
henrik.lundin7a926812016-05-12 13:51:28 -0700195int NetEqImpl::GetAudio(AudioFrame* audio_frame, bool* muted) {
henrik.lundine1ca1672016-01-08 03:50:08 -0800196 TRACE_EVENT0("webrtc", "NetEqImpl::GetAudio");
Tommi9090e0b2016-01-20 13:39:36 +0100197 rtc::CritScope lock(&crit_sect_);
Henrik Lundinc417d9e2017-06-14 12:29:03 +0200198 if (GetAudioInternal(audio_frame, muted) != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000199 return kFail;
200 }
henrik.lundin5fac3f02016-08-24 11:18:49 -0700201 RTC_DCHECK_EQ(
202 audio_frame->sample_rate_hz_,
kwibergd3edd772017-03-01 18:52:48 -0800203 rtc::dchecked_cast<int>(audio_frame->samples_per_channel_ * 100));
henrik.lundina4491072017-07-06 05:23:53 -0700204 RTC_DCHECK_EQ(*muted, audio_frame->muted());
henrik.lundin500c04b2016-03-08 02:36:04 -0800205 SetAudioFrameActivityAndType(vad_->enabled(), LastOutputType(),
206 last_vad_activity_, audio_frame);
207 last_vad_activity_ = audio_frame->vad_activity_;
henrik.lundin6d8e0112016-03-04 10:34:21 -0800208 last_output_sample_rate_hz_ = audio_frame->sample_rate_hz_;
henrik.lundind89814b2015-11-23 06:49:25 -0800209 RTC_DCHECK(last_output_sample_rate_hz_ == 8000 ||
210 last_output_sample_rate_hz_ == 16000 ||
211 last_output_sample_rate_hz_ == 32000 ||
212 last_output_sample_rate_hz_ == 48000)
213 << "Unexpected sample rate " << last_output_sample_rate_hz_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000214 return kOK;
215}
216
kwiberg1c07c702017-03-27 07:15:49 -0700217void NetEqImpl::SetCodecs(const std::map<int, SdpAudioFormat>& codecs) {
218 rtc::CritScope lock(&crit_sect_);
219 const std::vector<int> changed_payload_types =
220 decoder_database_->SetCodecs(codecs);
221 for (const int pt : changed_payload_types) {
minyue-webrtcfae474c2017-07-05 11:17:40 +0200222 packet_buffer_->DiscardPacketsWithPayloadType(pt, &stats_);
kwiberg1c07c702017-03-27 07:15:49 -0700223 }
224}
225
kwibergee1879c2015-10-29 06:20:28 -0700226int NetEqImpl::RegisterPayloadType(NetEqDecoder codec,
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800227 const std::string& name,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000228 uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100229 rtc::CritScope lock(&crit_sect_);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100230 RTC_LOG(LS_VERBOSE) << "RegisterPayloadType "
231 << static_cast<int>(rtp_payload_type) << " "
232 << static_cast<int>(codec);
Henrik Lundinc417d9e2017-06-14 12:29:03 +0200233 if (decoder_database_->RegisterPayload(rtp_payload_type, codec, name) !=
234 DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000235 return kFail;
236 }
237 return kOK;
238}
239
240int NetEqImpl::RegisterExternalDecoder(AudioDecoder* decoder,
kwibergee1879c2015-10-29 06:20:28 -0700241 NetEqDecoder codec,
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800242 const std::string& codec_name,
kwiberg342f7402016-06-16 03:18:00 -0700243 uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100244 rtc::CritScope lock(&crit_sect_);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100245 RTC_LOG(LS_VERBOSE) << "RegisterExternalDecoder "
246 << static_cast<int>(rtp_payload_type) << " "
247 << static_cast<int>(codec);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000248 if (!decoder) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100249 RTC_LOG(LS_ERROR) << "Cannot register external decoder with NULL pointer";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000250 assert(false);
251 return kFail;
252 }
Henrik Lundinc417d9e2017-06-14 12:29:03 +0200253 if (decoder_database_->InsertExternal(rtp_payload_type, codec, codec_name,
254 decoder) != DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000255 return kFail;
256 }
257 return kOK;
258}
259
kwiberg5adaf732016-10-04 09:33:27 -0700260bool NetEqImpl::RegisterPayloadType(int rtp_payload_type,
261 const SdpAudioFormat& audio_format) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100262 RTC_LOG(LS_VERBOSE) << "NetEqImpl::RegisterPayloadType: payload type "
263 << rtp_payload_type << ", codec " << audio_format;
kwiberg5adaf732016-10-04 09:33:27 -0700264 rtc::CritScope lock(&crit_sect_);
Henrik Lundinc417d9e2017-06-14 12:29:03 +0200265 return decoder_database_->RegisterPayload(rtp_payload_type, audio_format) ==
266 DecoderDatabase::kOK;
kwiberg5adaf732016-10-04 09:33:27 -0700267}
268
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000269int NetEqImpl::RemovePayloadType(uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100270 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000271 int ret = decoder_database_->Remove(rtp_payload_type);
Henrik Lundinc417d9e2017-06-14 12:29:03 +0200272 if (ret == DecoderDatabase::kOK || ret == DecoderDatabase::kDecoderNotFound) {
minyue-webrtcfae474c2017-07-05 11:17:40 +0200273 packet_buffer_->DiscardPacketsWithPayloadType(rtp_payload_type, &stats_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000274 return kOK;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000275 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000276 return kFail;
277}
278
kwiberg6b19b562016-09-20 04:02:25 -0700279void NetEqImpl::RemoveAllPayloadTypes() {
280 rtc::CritScope lock(&crit_sect_);
281 decoder_database_->RemoveAll();
282}
283
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000284bool NetEqImpl::SetMinimumDelay(int delay_ms) {
Tommi9090e0b2016-01-20 13:39:36 +0100285 rtc::CritScope lock(&crit_sect_);
Gustaf Ullberg48d96c02017-09-15 13:59:52 +0200286 if (delay_ms >= 0 && delay_ms <= 10000) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000287 assert(delay_manager_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000288 return delay_manager_->SetMinimumDelay(delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000289 }
290 return false;
291}
292
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000293bool NetEqImpl::SetMaximumDelay(int delay_ms) {
Tommi9090e0b2016-01-20 13:39:36 +0100294 rtc::CritScope lock(&crit_sect_);
Gustaf Ullberg48d96c02017-09-15 13:59:52 +0200295 if (delay_ms >= 0 && delay_ms <= 10000) {
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000296 assert(delay_manager_.get());
297 return delay_manager_->SetMaximumDelay(delay_ms);
298 }
299 return false;
300}
301
302int NetEqImpl::LeastRequiredDelayMs() const {
Tommi9090e0b2016-01-20 13:39:36 +0100303 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000304 assert(delay_manager_.get());
305 return delay_manager_->least_required_delay_ms();
306}
307
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200308int NetEqImpl::SetTargetDelay() {
309 return kNotImplemented;
310}
311
Henrik Lundinabbff892017-11-29 09:14:04 +0100312int NetEqImpl::TargetDelayMs() const {
henrik.lundin114c1b32017-04-26 07:47:32 -0700313 rtc::CritScope lock(&crit_sect_);
314 RTC_DCHECK(delay_manager_.get());
315 // The value from TargetLevel() is in number of packets, represented in Q8.
316 const size_t target_delay_samples =
317 (delay_manager_->TargetLevel() * decoder_frame_length_) >> 8;
318 return static_cast<int>(target_delay_samples) /
319 rtc::CheckedDivExact(fs_hz_, 1000);
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200320}
321
henrik.lundin9c3efd02015-08-27 13:12:22 -0700322int NetEqImpl::CurrentDelayMs() const {
Tommi9090e0b2016-01-20 13:39:36 +0100323 rtc::CritScope lock(&crit_sect_);
henrik.lundin9c3efd02015-08-27 13:12:22 -0700324 if (fs_hz_ == 0)
325 return 0;
326 // Sum up the samples in the packet buffer with the future length of the sync
327 // buffer, and divide the sum by the sample rate.
328 const size_t delay_samples =
ossu61a208b2016-09-20 01:38:00 -0700329 packet_buffer_->NumSamplesInBuffer(decoder_frame_length_) +
henrik.lundin9c3efd02015-08-27 13:12:22 -0700330 sync_buffer_->FutureLength();
331 // The division below will truncate.
332 const int delay_ms =
333 static_cast<int>(delay_samples) / rtc::CheckedDivExact(fs_hz_, 1000);
334 return delay_ms;
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200335}
336
henrik.lundinb3f1c5d2016-08-22 15:39:53 -0700337int NetEqImpl::FilteredCurrentDelayMs() const {
338 rtc::CritScope lock(&crit_sect_);
339 // Calculate the filtered packet buffer level in samples. The value from
340 // |buffer_level_filter_| is in number of packets, represented in Q8.
341 const size_t packet_buffer_samples =
342 (buffer_level_filter_->filtered_current_level() *
343 decoder_frame_length_) >>
344 8;
345 // Sum up the filtered packet buffer level with the future length of the sync
346 // buffer, and divide the sum by the sample rate.
347 const size_t delay_samples =
348 packet_buffer_samples + sync_buffer_->FutureLength();
349 // The division below will truncate. The return value is in ms.
350 return static_cast<int>(delay_samples) / rtc::CheckedDivExact(fs_hz_, 1000);
351}
352
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000353// Deprecated.
354// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000355void NetEqImpl::SetPlayoutMode(NetEqPlayoutMode mode) {
Tommi9090e0b2016-01-20 13:39:36 +0100356 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000357 if (mode != playout_mode_) {
358 playout_mode_ = mode;
359 CreateDecisionLogic();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000360 }
361}
362
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000363// Deprecated.
364// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000365NetEqPlayoutMode NetEqImpl::PlayoutMode() const {
Tommi9090e0b2016-01-20 13:39:36 +0100366 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000367 return playout_mode_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000368}
369
370int NetEqImpl::NetworkStatistics(NetEqNetworkStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100371 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000372 assert(decoder_database_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700373 const size_t total_samples_in_buffers =
ossu61a208b2016-09-20 01:38:00 -0700374 packet_buffer_->NumSamplesInBuffer(decoder_frame_length_) +
Peter Kastingdce40cf2015-08-24 14:52:23 -0700375 sync_buffer_->FutureLength();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000376 assert(delay_manager_.get());
377 assert(decision_logic_.get());
Henrik Lundindccfc402017-09-25 12:30:58 +0200378 const int ms_per_packet = rtc::dchecked_cast<int>(
379 decision_logic_->packet_length_samples() / (fs_hz_ / 1000));
380 stats_.PopulateDelayManagerStats(ms_per_packet, *delay_manager_.get(), stats);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000381 stats_.GetNetworkStatistics(fs_hz_, total_samples_in_buffers,
Henrik Lundindccfc402017-09-25 12:30:58 +0200382 decoder_frame_length_, stats);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000383 return 0;
384}
385
Steve Anton2dbc69f2017-08-24 17:15:13 -0700386NetEqLifetimeStatistics NetEqImpl::GetLifetimeStatistics() const {
387 rtc::CritScope lock(&crit_sect_);
388 return stats_.GetLifetimeStatistics();
389}
390
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000391void NetEqImpl::GetRtcpStatistics(RtcpStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100392 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000393 if (stats) {
394 rtcp_.GetStatistics(false, stats);
395 }
396}
397
398void NetEqImpl::GetRtcpStatisticsNoReset(RtcpStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100399 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000400 if (stats) {
401 rtcp_.GetStatistics(true, stats);
402 }
403}
404
405void NetEqImpl::EnableVad() {
Tommi9090e0b2016-01-20 13:39:36 +0100406 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000407 assert(vad_.get());
408 vad_->Enable();
409}
410
411void NetEqImpl::DisableVad() {
Tommi9090e0b2016-01-20 13:39:36 +0100412 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000413 assert(vad_.get());
414 vad_->Disable();
415}
416
henrik.lundin15c51e32016-04-06 08:38:56 -0700417rtc::Optional<uint32_t> NetEqImpl::GetPlayoutTimestamp() const {
Tommi9090e0b2016-01-20 13:39:36 +0100418 rtc::CritScope lock(&crit_sect_);
henrik.lundin0d96ab72016-04-06 12:28:26 -0700419 if (first_packet_ || last_mode_ == kModeRfc3389Cng ||
420 last_mode_ == kModeCodecInternalCng) {
wu@webrtc.org94454b72014-06-05 20:34:08 +0000421 // We don't have a valid RTP timestamp until we have decoded our first
henrik.lundin0d96ab72016-04-06 12:28:26 -0700422 // RTP packet. Also, the RTP timestamp is not accurate while playing CNG,
423 // which is indicated by returning an empty value.
Oskar Sundbom12ab00b2017-11-16 15:31:38 +0100424 return rtc::nullopt;
wu@webrtc.org94454b72014-06-05 20:34:08 +0000425 }
Oskar Sundbom12ab00b2017-11-16 15:31:38 +0100426 return timestamp_scaler_->ToExternal(playout_timestamp_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000427}
428
henrik.lundind89814b2015-11-23 06:49:25 -0800429int NetEqImpl::last_output_sample_rate_hz() const {
Tommi9090e0b2016-01-20 13:39:36 +0100430 rtc::CritScope lock(&crit_sect_);
henrik.lundind89814b2015-11-23 06:49:25 -0800431 return last_output_sample_rate_hz_;
432}
433
kwiberg6f0f6162016-09-20 03:07:46 -0700434rtc::Optional<CodecInst> NetEqImpl::GetDecoder(int payload_type) const {
435 rtc::CritScope lock(&crit_sect_);
436 const DecoderDatabase::DecoderInfo* di =
437 decoder_database_->GetDecoderInfo(payload_type);
438 if (!di) {
Oskar Sundbom12ab00b2017-11-16 15:31:38 +0100439 return rtc::nullopt;
kwiberg6f0f6162016-09-20 03:07:46 -0700440 }
441
442 // Create a CodecInst with some fields set. The remaining fields are zeroed,
443 // but we tell MSan to consider them uninitialized.
444 CodecInst ci = {0};
445 rtc::MsanMarkUninitialized(rtc::MakeArrayView(&ci, 1));
446 ci.pltype = payload_type;
kwiberge9413062016-11-03 05:29:05 -0700447 std::strncpy(ci.plname, di->get_name().c_str(), sizeof(ci.plname));
kwiberg6f0f6162016-09-20 03:07:46 -0700448 ci.plname[sizeof(ci.plname) - 1] = '\0';
solenberg2779bab2016-11-17 04:45:19 -0800449 ci.plfreq = di->IsRed() ? 8000 : di->SampleRateHz();
kwiberg6f0f6162016-09-20 03:07:46 -0700450 AudioDecoder* const decoder = di->GetDecoder();
451 ci.channels = decoder ? decoder->Channels() : 1;
Oskar Sundbom12ab00b2017-11-16 15:31:38 +0100452 return ci;
kwiberg6f0f6162016-09-20 03:07:46 -0700453}
454
ossuf1b08da2016-09-23 02:19:43 -0700455rtc::Optional<SdpAudioFormat> NetEqImpl::GetDecoderFormat(
456 int payload_type) const {
kwibergc4ccd4d2016-09-21 10:55:15 -0700457 rtc::CritScope lock(&crit_sect_);
458 const DecoderDatabase::DecoderInfo* const di =
459 decoder_database_->GetDecoderInfo(payload_type);
460 if (!di) {
Oskar Sundbom12ab00b2017-11-16 15:31:38 +0100461 return rtc::nullopt; // Payload type not registered.
kwibergc4ccd4d2016-09-21 10:55:15 -0700462 }
Oskar Sundbom12ab00b2017-11-16 15:31:38 +0100463 return di->GetFormat();
kwibergc4ccd4d2016-09-21 10:55:15 -0700464}
465
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200466int NetEqImpl::SetTargetNumberOfChannels() {
467 return kNotImplemented;
468}
469
470int NetEqImpl::SetTargetSampleRate() {
471 return kNotImplemented;
472}
473
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000474void NetEqImpl::FlushBuffers() {
Tommi9090e0b2016-01-20 13:39:36 +0100475 rtc::CritScope lock(&crit_sect_);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100476 RTC_LOG(LS_VERBOSE) << "FlushBuffers";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000477 packet_buffer_->Flush();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000478 assert(sync_buffer_.get());
479 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000480 sync_buffer_->Flush();
481 sync_buffer_->set_next_index(sync_buffer_->next_index() -
482 expand_->overlap_length());
483 // Set to wait for new codec.
484 first_packet_ = true;
485}
486
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000487void NetEqImpl::PacketBufferStatistics(int* current_num_packets,
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000488 int* max_num_packets) const {
Tommi9090e0b2016-01-20 13:39:36 +0100489 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000490 packet_buffer_->BufferStat(current_num_packets, max_num_packets);
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000491}
492
henrik.lundin48ed9302015-10-29 05:36:24 -0700493void NetEqImpl::EnableNack(size_t max_nack_list_size) {
Tommi9090e0b2016-01-20 13:39:36 +0100494 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700495 if (!nack_enabled_) {
496 const int kNackThresholdPackets = 2;
henrik.lundin91951862016-06-08 06:43:41 -0700497 nack_.reset(NackTracker::Create(kNackThresholdPackets));
henrik.lundin48ed9302015-10-29 05:36:24 -0700498 nack_enabled_ = true;
499 nack_->UpdateSampleRate(fs_hz_);
500 }
501 nack_->SetMaxNackListSize(max_nack_list_size);
502}
503
504void NetEqImpl::DisableNack() {
Tommi9090e0b2016-01-20 13:39:36 +0100505 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700506 nack_.reset();
507 nack_enabled_ = false;
508}
509
510std::vector<uint16_t> NetEqImpl::GetNackList(int64_t round_trip_time_ms) const {
Tommi9090e0b2016-01-20 13:39:36 +0100511 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700512 if (!nack_enabled_) {
513 return std::vector<uint16_t>();
514 }
515 RTC_DCHECK(nack_.get());
516 return nack_->GetNackList(round_trip_time_ms);
minyue@webrtc.orgd7301772013-08-29 00:58:14 +0000517}
518
henrik.lundin114c1b32017-04-26 07:47:32 -0700519std::vector<uint32_t> NetEqImpl::LastDecodedTimestamps() const {
520 rtc::CritScope lock(&crit_sect_);
521 return last_decoded_timestamps_;
522}
523
524int NetEqImpl::SyncBufferSizeMs() const {
525 rtc::CritScope lock(&crit_sect_);
526 return rtc::dchecked_cast<int>(sync_buffer_->FutureLength() /
527 rtc::CheckedDivExact(fs_hz_, 1000));
528}
529
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000530const SyncBuffer* NetEqImpl::sync_buffer_for_test() const {
Tommi9090e0b2016-01-20 13:39:36 +0100531 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000532 return sync_buffer_.get();
533}
534
minyue5bd33972016-05-02 04:46:11 -0700535Operations NetEqImpl::last_operation_for_test() const {
536 rtc::CritScope lock(&crit_sect_);
537 return last_operation_;
538}
539
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000540// Methods below this line are private.
541
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200542int NetEqImpl::InsertPacketInternal(const RTPHeader& rtp_header,
kwibergee2bac22015-11-11 10:34:00 -0800543 rtc::ArrayView<const uint8_t> payload,
ossu17e3fa12016-09-08 04:52:55 -0700544 uint32_t receive_timestamp) {
kwibergee2bac22015-11-11 10:34:00 -0800545 if (payload.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100546 RTC_LOG_F(LS_ERROR) << "payload is empty";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000547 return kInvalidPointer;
548 }
ossu17e3fa12016-09-08 04:52:55 -0700549
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000550 PacketList packet_list;
ossua73f6c92016-10-24 08:25:28 -0700551 // Insert packet in a packet list.
552 packet_list.push_back([&rtp_header, &payload] {
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000553 // Convert to Packet.
ossua73f6c92016-10-24 08:25:28 -0700554 Packet packet;
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200555 packet.payload_type = rtp_header.payloadType;
556 packet.sequence_number = rtp_header.sequenceNumber;
557 packet.timestamp = rtp_header.timestamp;
ossua73f6c92016-10-24 08:25:28 -0700558 packet.payload.SetData(payload.data(), payload.size());
henrik.lundin84f8cd62016-04-26 07:45:16 -0700559 // Waiting time will be set upon inserting the packet in the buffer.
ossua73f6c92016-10-24 08:25:28 -0700560 RTC_DCHECK(!packet.waiting_time);
561 return packet;
562 }());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000563
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200564 bool update_sample_rate_and_channels =
565 first_packet_ || (rtp_header.ssrc != ssrc_);
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700566
567 if (update_sample_rate_and_channels) {
568 // Reset timestamp scaling.
569 timestamp_scaler_->Reset();
570 }
571
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200572 if (!decoder_database_->IsRed(rtp_header.payloadType)) {
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700573 // Scale timestamp to internal domain (only for some codecs).
574 timestamp_scaler_->ToInternal(&packet_list);
575 }
576
577 // Store these for later use, since the first packet may very well disappear
578 // before we need these values.
579 uint32_t main_timestamp = packet_list.front().timestamp;
580 uint8_t main_payload_type = packet_list.front().payload_type;
581 uint16_t main_sequence_number = packet_list.front().sequence_number;
582
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000583 // Reinitialize NetEq if it's needed (changed SSRC or first call).
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700584 if (update_sample_rate_and_channels) {
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000585 // Note: |first_packet_| will be cleared further down in this method, once
586 // the packet has been successfully inserted into the packet buffer.
587
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200588 rtcp_.Init(rtp_header.sequenceNumber);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000589
590 // Flush the packet buffer and DTMF buffer.
591 packet_buffer_->Flush();
592 dtmf_buffer_->Flush();
593
594 // Store new SSRC.
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200595 ssrc_ = rtp_header.ssrc;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000596
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000597 // Update audio buffer timestamp.
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700598 sync_buffer_->IncreaseEndTimestamp(main_timestamp - timestamp_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000599
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000600 // Update codecs.
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700601 timestamp_ = main_timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000602 }
603
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000604 // Update RTCP statistics, only for regular packets.
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200605 rtcp_.Update(rtp_header, receive_timestamp);
ossu7a377612016-10-18 04:06:13 -0700606
607 if (nack_enabled_) {
608 RTC_DCHECK(nack_);
609 if (update_sample_rate_and_channels) {
610 nack_->Reset();
611 }
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200612 nack_->UpdateLastReceivedPacket(rtp_header.sequenceNumber,
613 rtp_header.timestamp);
ossu7a377612016-10-18 04:06:13 -0700614 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000615
616 // Check for RED payload type, and separate payloads into several packets.
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200617 if (decoder_database_->IsRed(rtp_header.payloadType)) {
ossua70695a2016-09-22 02:06:28 -0700618 if (!red_payload_splitter_->SplitRed(&packet_list)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000619 return kRedundancySplitError;
620 }
621 // Only accept a few RED payloads of the same type as the main data,
622 // DTMF events and CNG.
ossua70695a2016-09-22 02:06:28 -0700623 red_payload_splitter_->CheckRedPayloads(&packet_list, *decoder_database_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000624 }
625
626 // Check payload types.
627 if (decoder_database_->CheckPayloadTypes(packet_list) ==
628 DecoderDatabase::kDecoderNotFound) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000629 return kUnknownRtpPayloadType;
630 }
631
ossu7a377612016-10-18 04:06:13 -0700632 RTC_DCHECK(!packet_list.empty());
ossu7a377612016-10-18 04:06:13 -0700633
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700634 // Update main_timestamp, if new packets appear in the list
635 // after RED splitting.
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200636 if (decoder_database_->IsRed(rtp_header.payloadType)) {
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700637 timestamp_scaler_->ToInternal(&packet_list);
638 main_timestamp = packet_list.front().timestamp;
639 main_payload_type = packet_list.front().payload_type;
640 main_sequence_number = packet_list.front().sequence_number;
641 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000642
643 // Process DTMF payloads. Cycle through the list of packets, and pick out any
644 // DTMF payloads found.
645 PacketList::iterator it = packet_list.begin();
646 while (it != packet_list.end()) {
ossua73f6c92016-10-24 08:25:28 -0700647 const Packet& current_packet = (*it);
648 RTC_DCHECK(!current_packet.payload.empty());
649 if (decoder_database_->IsDtmf(current_packet.payload_type)) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000650 DtmfEvent event;
ossua73f6c92016-10-24 08:25:28 -0700651 int ret = DtmfBuffer::ParseEvent(current_packet.timestamp,
652 current_packet.payload.data(),
653 current_packet.payload.size(), &event);
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000654 if (ret != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000655 return kDtmfParsingError;
656 }
657 if (dtmf_buffer_->InsertEvent(event) != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000658 return kDtmfInsertError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000659 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000660 it = packet_list.erase(it);
661 } else {
662 ++it;
663 }
664 }
665
ossu17e3fa12016-09-08 04:52:55 -0700666 // Update bandwidth estimate, if the packet is not comfort noise.
667 if (!packet_list.empty() &&
ossu7a377612016-10-18 04:06:13 -0700668 !decoder_database_->IsComfortNoise(main_payload_type)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000669 // The list can be empty here if we got nothing but DTMF payloads.
ossu7a377612016-10-18 04:06:13 -0700670 AudioDecoder* decoder = decoder_database_->GetDecoder(main_payload_type);
671 RTC_DCHECK(decoder); // Should always get a valid object, since we have
672 // already checked that the payload types are known.
ossua73f6c92016-10-24 08:25:28 -0700673 decoder->IncomingPacket(packet_list.front().payload.data(),
674 packet_list.front().payload.size(),
675 packet_list.front().sequence_number,
676 packet_list.front().timestamp,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000677 receive_timestamp);
678 }
679
ossu61a208b2016-09-20 01:38:00 -0700680 PacketList parsed_packet_list;
681 while (!packet_list.empty()) {
ossua73f6c92016-10-24 08:25:28 -0700682 Packet& packet = packet_list.front();
ossu61a208b2016-09-20 01:38:00 -0700683 const DecoderDatabase::DecoderInfo* info =
ossua73f6c92016-10-24 08:25:28 -0700684 decoder_database_->GetDecoderInfo(packet.payload_type);
ossu61a208b2016-09-20 01:38:00 -0700685 if (!info) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100686 RTC_LOG(LS_WARNING) << "SplitAudio unknown payload type";
ossu61a208b2016-09-20 01:38:00 -0700687 return kUnknownRtpPayloadType;
688 }
689
690 if (info->IsComfortNoise()) {
691 // Carry comfort noise packets along.
ossua73f6c92016-10-24 08:25:28 -0700692 parsed_packet_list.splice(parsed_packet_list.end(), packet_list,
693 packet_list.begin());
ossu61a208b2016-09-20 01:38:00 -0700694 } else {
ossua73f6c92016-10-24 08:25:28 -0700695 const auto sequence_number = packet.sequence_number;
696 const auto payload_type = packet.payload_type;
697 const Packet::Priority original_priority = packet.priority;
698 auto packet_from_result = [&] (AudioDecoder::ParseResult& result) {
699 Packet new_packet;
700 new_packet.sequence_number = sequence_number;
701 new_packet.payload_type = payload_type;
702 new_packet.timestamp = result.timestamp;
703 new_packet.priority.codec_level = result.priority;
704 new_packet.priority.red_level = original_priority.red_level;
705 new_packet.frame = std::move(result.frame);
706 return new_packet;
707 };
708
ossu61a208b2016-09-20 01:38:00 -0700709 std::vector<AudioDecoder::ParseResult> results =
ossua73f6c92016-10-24 08:25:28 -0700710 info->GetDecoder()->ParsePayload(std::move(packet.payload),
711 packet.timestamp);
712 if (results.empty()) {
713 packet_list.pop_front();
714 } else {
715 bool first = true;
716 for (auto& result : results) {
717 RTC_DCHECK(result.frame);
718 RTC_DCHECK_GE(result.priority, 0);
719 if (first) {
720 // Re-use the node and move it to parsed_packet_list.
721 packet_list.front() = packet_from_result(result);
722 parsed_packet_list.splice(parsed_packet_list.end(), packet_list,
723 packet_list.begin());
724 first = false;
725 } else {
726 parsed_packet_list.push_back(packet_from_result(result));
727 }
ossu61a208b2016-09-20 01:38:00 -0700728 }
ossu61a208b2016-09-20 01:38:00 -0700729 }
730 }
731 }
732
Ivo Creusenfd7c0a52017-10-20 12:35:04 +0200733 // Calculate the number of primary (non-FEC/RED) packets.
734 const int number_of_primary_packets = std::count_if(
735 parsed_packet_list.begin(), parsed_packet_list.end(),
736 [](const Packet& in) { return in.priority.codec_level == 0; });
737
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000738 // Insert packets in buffer.
ossua70695a2016-09-22 02:06:28 -0700739 const int ret = packet_buffer_->InsertPacketList(
ossu61a208b2016-09-20 01:38:00 -0700740 &parsed_packet_list, *decoder_database_, &current_rtp_payload_type_,
minyue-webrtc12d30842017-07-19 11:44:06 +0200741 &current_cng_rtp_payload_type_, &stats_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000742 if (ret == PacketBuffer::kFlushed) {
743 // Reset DSP timestamp etc. if packet buffer flushed.
744 new_codec_ = true;
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000745 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000746 } else if (ret != PacketBuffer::kOK) {
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000747 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000748 }
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000749
750 if (first_packet_) {
751 first_packet_ = false;
752 // Update the codec on the next GetAudio call.
753 new_codec_ = true;
754 }
755
henrik.lundinda8bbf62016-08-31 03:14:11 -0700756 if (current_rtp_payload_type_) {
757 RTC_DCHECK(decoder_database_->GetDecoderInfo(*current_rtp_payload_type_))
758 << "Payload type " << static_cast<int>(*current_rtp_payload_type_)
759 << " is unknown where it shouldn't be";
760 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000761
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000762 if (update_sample_rate_and_channels && !packet_buffer_->Empty()) {
763 // We do not use |current_rtp_payload_type_| to |set payload_type|, but
764 // get the next RTP header from |packet_buffer_| to obtain the payload type.
765 // The reason for it is the following corner case. If NetEq receives a
766 // CNG packet with a sample rate different than the current CNG then it
767 // flushes its buffer, assuming send codec must have been changed. However,
768 // payload type of the hypothetically new send codec is not known.
ossu7a377612016-10-18 04:06:13 -0700769 const Packet* next_packet = packet_buffer_->PeekNextPacket();
770 RTC_DCHECK(next_packet);
771 const int payload_type = next_packet->payload_type;
ossu97ba30e2016-04-25 07:55:58 -0700772 size_t channels = 1;
773 if (!decoder_database_->IsComfortNoise(payload_type)) {
774 AudioDecoder* decoder = decoder_database_->GetDecoder(payload_type);
775 assert(decoder); // Payloads are already checked to be valid.
776 channels = decoder->Channels();
777 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000778 const DecoderDatabase::DecoderInfo* decoder_info =
779 decoder_database_->GetDecoderInfo(payload_type);
780 assert(decoder_info);
kwibergc0f2dcf2016-05-31 06:28:03 -0700781 if (decoder_info->SampleRateHz() != fs_hz_ ||
ossu97ba30e2016-04-25 07:55:58 -0700782 channels != algorithm_buffer_->Channels()) {
kwibergc0f2dcf2016-05-31 06:28:03 -0700783 SetSampleRateAndChannels(decoder_info->SampleRateHz(),
784 channels);
henrik.lundin48ed9302015-10-29 05:36:24 -0700785 }
786 if (nack_enabled_) {
787 RTC_DCHECK(nack_);
788 // Update the sample rate even if the rate is not new, because of Reset().
789 nack_->UpdateSampleRate(fs_hz_);
790 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000791 }
792
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000793 // TODO(hlundin): Move this code to DelayManager class.
794 const DecoderDatabase::DecoderInfo* dec_info =
ossu7a377612016-10-18 04:06:13 -0700795 decoder_database_->GetDecoderInfo(main_payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000796 assert(dec_info); // Already checked that the payload type is known.
ossuf1b08da2016-09-23 02:19:43 -0700797 delay_manager_->LastDecodedWasCngOrDtmf(dec_info->IsComfortNoise() ||
798 dec_info->IsDtmf());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000799 if (delay_manager_->last_pack_cng_or_dtmf() == 0) {
800 // Calculate the total speech length carried in each packet.
Ivo Creusenfd7c0a52017-10-20 12:35:04 +0200801 if (number_of_primary_packets > 0) {
henrik.lundin116c84e2015-08-27 13:14:48 -0700802 const size_t packet_length_samples =
Ivo Creusenfd7c0a52017-10-20 12:35:04 +0200803 number_of_primary_packets * decoder_frame_length_;
henrik.lundin116c84e2015-08-27 13:14:48 -0700804 if (packet_length_samples != decision_logic_->packet_length_samples()) {
805 decision_logic_->set_packet_length_samples(packet_length_samples);
806 delay_manager_->SetPacketAudioLength(
kwibergd3edd772017-03-01 18:52:48 -0800807 rtc::dchecked_cast<int>((1000 * packet_length_samples) / fs_hz_));
henrik.lundin116c84e2015-08-27 13:14:48 -0700808 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000809 }
810
811 // Update statistics.
ossu7a377612016-10-18 04:06:13 -0700812 if ((int32_t)(main_timestamp - timestamp_) >= 0 && !new_codec_) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000813 // Only update statistics if incoming packet is not older than last played
814 // out packet, and if new codec flag is not set.
ossu7a377612016-10-18 04:06:13 -0700815 delay_manager_->Update(main_sequence_number, main_timestamp, fs_hz_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000816 }
817 } else if (delay_manager_->last_pack_cng_or_dtmf() == -1) {
818 // This is first "normal" packet after CNG or DTMF.
819 // Reset packet time counter and measure time until next packet,
820 // but don't update statistics.
821 delay_manager_->set_last_pack_cng_or_dtmf(0);
822 delay_manager_->ResetPacketIatCount();
823 }
824 return 0;
825}
826
henrik.lundin7a926812016-05-12 13:51:28 -0700827int NetEqImpl::GetAudioInternal(AudioFrame* audio_frame, bool* muted) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000828 PacketList packet_list;
829 DtmfEvent dtmf_event;
830 Operations operation;
831 bool play_dtmf;
henrik.lundin7a926812016-05-12 13:51:28 -0700832 *muted = false;
henrik.lundin114c1b32017-04-26 07:47:32 -0700833 last_decoded_timestamps_.clear();
henrik.lundined497212016-04-25 10:11:38 -0700834 tick_timer_->Increment();
henrik.lundin60f6ce22016-05-10 03:52:04 -0700835 stats_.IncreaseCounter(output_size_samples_, fs_hz_);
henrik.lundin7a926812016-05-12 13:51:28 -0700836
837 // Check for muted state.
838 if (enable_muted_state_ && expand_->Muted() && packet_buffer_->Empty()) {
839 RTC_DCHECK_EQ(last_mode_, kModeExpand);
henrik.lundina4491072017-07-06 05:23:53 -0700840 audio_frame->Reset();
841 RTC_DCHECK(audio_frame->muted()); // Reset() should mute the frame.
henrik.lundin7a926812016-05-12 13:51:28 -0700842 playout_timestamp_ += static_cast<uint32_t>(output_size_samples_);
843 audio_frame->sample_rate_hz_ = fs_hz_;
844 audio_frame->samples_per_channel_ = output_size_samples_;
845 audio_frame->timestamp_ =
846 first_packet_
847 ? 0
848 : timestamp_scaler_->ToExternal(playout_timestamp_) -
849 static_cast<uint32_t>(audio_frame->samples_per_channel_);
850 audio_frame->num_channels_ = sync_buffer_->Channels();
Gustaf Ullberg9a2e9062017-09-18 09:28:20 +0200851 stats_.ExpandedNoiseSamples(output_size_samples_, false);
henrik.lundin7a926812016-05-12 13:51:28 -0700852 *muted = true;
853 return 0;
854 }
855
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000856 int return_value = GetDecision(&operation, &packet_list, &dtmf_event,
857 &play_dtmf);
858 if (return_value != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000859 last_mode_ = kModeError;
860 return return_value;
861 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000862
863 AudioDecoder::SpeechType speech_type;
864 int length = 0;
Henrik Lundin18036282017-11-02 12:09:06 +0100865 const size_t start_num_packets = packet_list.size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000866 int decode_return_value = Decode(&packet_list, &operation,
867 &length, &speech_type);
868
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000869 assert(vad_.get());
870 bool sid_frame_available =
871 (operation == kRfc3389Cng && !packet_list.empty());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700872 vad_->Update(decoded_buffer_.get(), static_cast<size_t>(length), speech_type,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000873 sid_frame_available, fs_hz_);
874
Henrik Lundin18036282017-11-02 12:09:06 +0100875 // This is the criterion that we did decode some data through the speech
876 // decoder, and the operation resulted in comfort noise.
877 const bool codec_internal_sid_frame =
Henrik Lundin4f2a4a12018-01-26 17:32:56 +0100878 (speech_type == AudioDecoder::kComfortNoise &&
879 start_num_packets > packet_list.size());
Henrik Lundin18036282017-11-02 12:09:06 +0100880
881 if (sid_frame_available || codec_internal_sid_frame) {
henrik.lundinb1fb72b2016-05-03 08:18:47 -0700882 // Start a new stopwatch since we are decoding a new CNG packet.
883 generated_noise_stopwatch_ = tick_timer_->GetNewStopwatch();
884 }
885
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000886 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000887 switch (operation) {
888 case kNormal: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000889 DoNormal(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000890 break;
891 }
892 case kMerge: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000893 DoMerge(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000894 break;
895 }
896 case kExpand: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000897 return_value = DoExpand(play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000898 break;
899 }
Henrik Lundincf808d22015-05-27 14:33:29 +0200900 case kAccelerate:
901 case kFastAccelerate: {
902 const bool fast_accelerate =
903 enable_fast_accelerate_ && (operation == kFastAccelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000904 return_value = DoAccelerate(decoded_buffer_.get(), length, speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +0200905 play_dtmf, fast_accelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000906 break;
907 }
908 case kPreemptiveExpand: {
909 return_value = DoPreemptiveExpand(decoded_buffer_.get(), length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000910 speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000911 break;
912 }
913 case kRfc3389Cng:
914 case kRfc3389CngNoPacket: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000915 return_value = DoRfc3389Cng(&packet_list, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000916 break;
917 }
918 case kCodecInternalCng: {
919 // This handles the case when there is no transmission and the decoder
920 // should produce internal comfort noise.
921 // TODO(hlundin): Write test for codec-internal CNG.
minyuel6d92bf52015-09-23 15:20:39 +0200922 DoCodecInternalCng(decoded_buffer_.get(), length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000923 break;
924 }
925 case kDtmf: {
926 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000927 return_value = DoDtmf(dtmf_event, &play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000928 break;
929 }
930 case kAlternativePlc: {
931 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000932 DoAlternativePlc(false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000933 break;
934 }
935 case kAlternativePlcIncreaseTimestamp: {
936 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000937 DoAlternativePlc(true);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000938 break;
939 }
940 case kAudioRepetitionIncreaseTimestamp: {
941 // TODO(hlundin): Write test for this.
Peter Kastingb7e50542015-06-11 12:55:50 -0700942 sync_buffer_->IncreaseEndTimestamp(
943 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000944 // Skipping break on purpose. Execution should move on into the
945 // next case.
kjellanderbdf30722017-09-08 11:00:21 -0700946 FALLTHROUGH();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000947 }
948 case kAudioRepetition: {
949 // TODO(hlundin): Write test for this.
950 // Copy last |output_size_samples_| from |sync_buffer_| to
951 // |algorithm_buffer|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000952 algorithm_buffer_->PushBackFromIndex(
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000953 *sync_buffer_, sync_buffer_->Size() - output_size_samples_);
954 expand_->Reset();
955 break;
956 }
957 case kUndefined: {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100958 RTC_LOG(LS_ERROR) << "Invalid operation kUndefined.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000959 assert(false); // This should not happen.
960 last_mode_ = kModeError;
961 return kInvalidOperation;
962 }
963 } // End of switch.
minyue5bd33972016-05-02 04:46:11 -0700964 last_operation_ = operation;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000965 if (return_value < 0) {
966 return return_value;
967 }
968
969 if (last_mode_ != kModeRfc3389Cng) {
970 comfort_noise_->Reset();
971 }
972
973 // Copy from |algorithm_buffer| to |sync_buffer_|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000974 sync_buffer_->PushBack(*algorithm_buffer_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000975
976 // Extract data from |sync_buffer_| to |output|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000977 size_t num_output_samples_per_channel = output_size_samples_;
978 size_t num_output_samples = output_size_samples_ * sync_buffer_->Channels();
henrik.lundin6d8e0112016-03-04 10:34:21 -0800979 if (num_output_samples > AudioFrame::kMaxDataSizeSamples) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100980 RTC_LOG(LS_WARNING) << "Output array is too short. "
981 << AudioFrame::kMaxDataSizeSamples << " < "
982 << output_size_samples_ << " * "
983 << sync_buffer_->Channels();
henrik.lundin6d8e0112016-03-04 10:34:21 -0800984 num_output_samples = AudioFrame::kMaxDataSizeSamples;
985 num_output_samples_per_channel =
986 AudioFrame::kMaxDataSizeSamples / sync_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000987 }
henrik.lundin6d8e0112016-03-04 10:34:21 -0800988 sync_buffer_->GetNextAudioInterleaved(num_output_samples_per_channel,
989 audio_frame);
990 audio_frame->sample_rate_hz_ = fs_hz_;
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200991 if (sync_buffer_->FutureLength() < expand_->overlap_length()) {
992 // The sync buffer should always contain |overlap_length| samples, but now
993 // too many samples have been extracted. Reinstall the |overlap_length|
994 // lookahead by moving the index.
995 const size_t missing_lookahead_samples =
996 expand_->overlap_length() - sync_buffer_->FutureLength();
henrikg91d6ede2015-09-17 00:24:34 -0700997 RTC_DCHECK_GE(sync_buffer_->next_index(), missing_lookahead_samples);
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200998 sync_buffer_->set_next_index(sync_buffer_->next_index() -
999 missing_lookahead_samples);
1000 }
henrik.lundin6d8e0112016-03-04 10:34:21 -08001001 if (audio_frame->samples_per_channel_ != output_size_samples_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001002 RTC_LOG(LS_ERROR) << "audio_frame->samples_per_channel_ ("
1003 << audio_frame->samples_per_channel_
1004 << ") != output_size_samples_ (" << output_size_samples_
1005 << ")";
minyue@webrtc.orgdb1cefc2013-08-13 01:39:21 +00001006 // TODO(minyue): treatment of under-run, filling zeros
yujo36b1a5f2017-06-12 12:45:32 -07001007 audio_frame->Mute();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001008 return kSampleUnderrun;
1009 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001010
1011 // Should always have overlap samples left in the |sync_buffer_|.
henrikg91d6ede2015-09-17 00:24:34 -07001012 RTC_DCHECK_GE(sync_buffer_->FutureLength(), expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001013
yujo36b1a5f2017-06-12 12:45:32 -07001014 // TODO(yujo): For muted frames, this can be a copy rather than an addition.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001015 if (play_dtmf) {
yujo36b1a5f2017-06-12 12:45:32 -07001016 return_value = DtmfOverdub(dtmf_event, sync_buffer_->Channels(),
1017 audio_frame->mutable_data());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001018 }
1019
1020 // Update the background noise parameters if last operation wrote data
1021 // straight from the decoder to the |sync_buffer_|. That is, none of the
1022 // operations that modify the signal can be followed by a parameter update.
1023 if ((last_mode_ == kModeNormal) ||
1024 (last_mode_ == kModeAccelerateFail) ||
1025 (last_mode_ == kModePreemptiveExpandFail) ||
1026 (last_mode_ == kModeRfc3389Cng) ||
1027 (last_mode_ == kModeCodecInternalCng)) {
1028 background_noise_->Update(*sync_buffer_, *vad_.get());
1029 }
1030
1031 if (operation == kDtmf) {
1032 // DTMF data was written the end of |sync_buffer_|.
1033 // Update index to end of DTMF data in |sync_buffer_|.
1034 sync_buffer_->set_dtmf_index(sync_buffer_->Size());
1035 }
1036
henrik.lundin@webrtc.orged865b52014-03-06 10:28:07 +00001037 if (last_mode_ != kModeExpand) {
1038 // If last operation was not expand, calculate the |playout_timestamp_| from
1039 // the |sync_buffer_|. However, do not update the |playout_timestamp_| if it
1040 // would be moved "backwards".
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001041 uint32_t temp_timestamp = sync_buffer_->end_timestamp() -
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001042 static_cast<uint32_t>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001043 if (static_cast<int32_t>(temp_timestamp - playout_timestamp_) > 0) {
1044 playout_timestamp_ = temp_timestamp;
1045 }
1046 } else {
1047 // Use dead reckoning to estimate the |playout_timestamp_|.
Peter Kastingb7e50542015-06-11 12:55:50 -07001048 playout_timestamp_ += static_cast<uint32_t>(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001049 }
henrik.lundin15c51e32016-04-06 08:38:56 -07001050 // Set the timestamp in the audio frame to zero before the first packet has
1051 // been inserted. Otherwise, subtract the frame size in samples to get the
1052 // timestamp of the first sample in the frame (playout_timestamp_ is the
1053 // last + 1).
1054 audio_frame->timestamp_ =
1055 first_packet_
1056 ? 0
1057 : timestamp_scaler_->ToExternal(playout_timestamp_) -
1058 static_cast<uint32_t>(audio_frame->samples_per_channel_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001059
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001060 if (!(last_mode_ == kModeRfc3389Cng ||
1061 last_mode_ == kModeCodecInternalCng ||
1062 last_mode_ == kModeExpand)) {
1063 generated_noise_stopwatch_.reset();
1064 }
1065
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001066 if (decode_return_value) return decode_return_value;
1067 return return_value;
1068}
1069
1070int NetEqImpl::GetDecision(Operations* operation,
1071 PacketList* packet_list,
1072 DtmfEvent* dtmf_event,
1073 bool* play_dtmf) {
1074 // Initialize output variables.
1075 *play_dtmf = false;
1076 *operation = kUndefined;
1077
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001078 assert(sync_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001079 uint32_t end_timestamp = sync_buffer_->end_timestamp();
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001080 if (!new_codec_) {
1081 const uint32_t five_seconds_samples = 5 * fs_hz_;
minyue-webrtcfae474c2017-07-05 11:17:40 +02001082 packet_buffer_->DiscardOldPackets(end_timestamp, five_seconds_samples,
1083 &stats_);
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001084 }
ossu7a377612016-10-18 04:06:13 -07001085 const Packet* packet = packet_buffer_->PeekNextPacket();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001086
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001087 RTC_DCHECK(!generated_noise_stopwatch_ ||
1088 generated_noise_stopwatch_->ElapsedTicks() >= 1);
1089 uint64_t generated_noise_samples =
1090 generated_noise_stopwatch_
1091 ? (generated_noise_stopwatch_->ElapsedTicks() - 1) *
1092 output_size_samples_ +
1093 decision_logic_->noise_fast_forward()
1094 : 0;
1095
henrik.lundin@webrtc.orgca8cb952014-03-12 10:26:52 +00001096 if (decision_logic_->CngRfc3389On() || last_mode_ == kModeRfc3389Cng) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001097 // Because of timestamp peculiarities, we have to "manually" disallow using
1098 // a CNG packet with the same timestamp as the one that was last played.
1099 // This can happen when using redundancy and will cause the timing to shift.
ossu7a377612016-10-18 04:06:13 -07001100 while (packet && decoder_database_->IsComfortNoise(packet->payload_type) &&
1101 (end_timestamp >= packet->timestamp ||
1102 end_timestamp + generated_noise_samples > packet->timestamp)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001103 // Don't use this packet, discard it.
minyue-webrtcfae474c2017-07-05 11:17:40 +02001104 if (packet_buffer_->DiscardNextPacket(&stats_) != PacketBuffer::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001105 assert(false); // Must be ok by design.
1106 }
1107 // Check buffer again.
1108 if (!new_codec_) {
minyue-webrtcfae474c2017-07-05 11:17:40 +02001109 packet_buffer_->DiscardOldPackets(end_timestamp, 5 * fs_hz_, &stats_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001110 }
ossu7a377612016-10-18 04:06:13 -07001111 packet = packet_buffer_->PeekNextPacket();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001112 }
1113 }
1114
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001115 assert(expand_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001116 const int samples_left = static_cast<int>(sync_buffer_->FutureLength() -
1117 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001118 if (last_mode_ == kModeAccelerateSuccess ||
1119 last_mode_ == kModeAccelerateLowEnergy ||
1120 last_mode_ == kModePreemptiveExpandSuccess ||
1121 last_mode_ == kModePreemptiveExpandLowEnergy) {
1122 // Subtract (samples_left + output_size_samples_) from sampleMemory.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001123 decision_logic_->AddSampleMemory(
kwibergd3edd772017-03-01 18:52:48 -08001124 -(samples_left + rtc::dchecked_cast<int>(output_size_samples_)));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001125 }
1126
1127 // Check if it is time to play a DTMF event.
Peter Kastingb7e50542015-06-11 12:55:50 -07001128 if (dtmf_buffer_->GetEvent(
1129 static_cast<uint32_t>(
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001130 end_timestamp + generated_noise_samples),
Peter Kastingb7e50542015-06-11 12:55:50 -07001131 dtmf_event)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001132 *play_dtmf = true;
1133 }
1134
1135 // Get instruction.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001136 assert(sync_buffer_.get());
1137 assert(expand_.get());
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001138 generated_noise_samples =
1139 generated_noise_stopwatch_
1140 ? generated_noise_stopwatch_->ElapsedTicks() * output_size_samples_ +
1141 decision_logic_->noise_fast_forward()
1142 : 0;
1143 *operation = decision_logic_->GetDecision(
ossu7a377612016-10-18 04:06:13 -07001144 *sync_buffer_, *expand_, decoder_frame_length_, packet, last_mode_,
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001145 *play_dtmf, generated_noise_samples, &reset_decoder_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001146
1147 // Check if we already have enough samples in the |sync_buffer_|. If so,
1148 // change decision to normal, unless the decision was merge, accelerate, or
1149 // preemptive expand.
kwibergd3edd772017-03-01 18:52:48 -08001150 if (samples_left >= rtc::dchecked_cast<int>(output_size_samples_) &&
1151 *operation != kMerge && *operation != kAccelerate &&
1152 *operation != kFastAccelerate && *operation != kPreemptiveExpand) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001153 *operation = kNormal;
1154 return 0;
1155 }
1156
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001157 decision_logic_->ExpandDecision(*operation);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001158
1159 // Check conditions for reset.
1160 if (new_codec_ || *operation == kUndefined) {
1161 // The only valid reason to get kUndefined is that new_codec_ is set.
1162 assert(new_codec_);
ossu7a377612016-10-18 04:06:13 -07001163 if (*play_dtmf && !packet) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001164 timestamp_ = dtmf_event->timestamp;
1165 } else {
ossu7a377612016-10-18 04:06:13 -07001166 if (!packet) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001167 RTC_LOG(LS_ERROR) << "Packet missing where it shouldn't.";
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001168 return -1;
1169 }
ossu7a377612016-10-18 04:06:13 -07001170 timestamp_ = packet->timestamp;
ossu108ecec2016-07-08 08:45:18 -07001171 if (*operation == kRfc3389CngNoPacket &&
ossu7a377612016-10-18 04:06:13 -07001172 decoder_database_->IsComfortNoise(packet->payload_type)) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001173 // Change decision to CNG packet, since we do have a CNG packet, but it
1174 // was considered too early to use. Now, use it anyway.
1175 *operation = kRfc3389Cng;
1176 } else if (*operation != kRfc3389Cng) {
1177 *operation = kNormal;
1178 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001179 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001180 // Adjust |sync_buffer_| timestamp before setting |end_timestamp| to the
1181 // new value.
1182 sync_buffer_->IncreaseEndTimestamp(timestamp_ - end_timestamp);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001183 end_timestamp = timestamp_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001184 new_codec_ = false;
1185 decision_logic_->SoftReset();
1186 buffer_level_filter_->Reset();
1187 delay_manager_->Reset();
1188 stats_.ResetMcu();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001189 }
1190
Peter Kastingdce40cf2015-08-24 14:52:23 -07001191 size_t required_samples = output_size_samples_;
1192 const size_t samples_10_ms = static_cast<size_t>(80 * fs_mult_);
1193 const size_t samples_20_ms = 2 * samples_10_ms;
1194 const size_t samples_30_ms = 3 * samples_10_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001195
1196 switch (*operation) {
1197 case kExpand: {
1198 timestamp_ = end_timestamp;
1199 return 0;
1200 }
1201 case kRfc3389CngNoPacket:
1202 case kCodecInternalCng: {
1203 return 0;
1204 }
1205 case kDtmf: {
1206 // TODO(hlundin): Write test for this.
1207 // Update timestamp.
1208 timestamp_ = end_timestamp;
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001209 const uint64_t generated_noise_samples =
1210 generated_noise_stopwatch_
1211 ? generated_noise_stopwatch_->ElapsedTicks() *
1212 output_size_samples_ +
1213 decision_logic_->noise_fast_forward()
1214 : 0;
1215 if (generated_noise_samples > 0 && last_mode_ != kModeDtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001216 // Make a jump in timestamp due to the recently played comfort noise.
Peter Kastingb7e50542015-06-11 12:55:50 -07001217 uint32_t timestamp_jump =
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001218 static_cast<uint32_t>(generated_noise_samples);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001219 sync_buffer_->IncreaseEndTimestamp(timestamp_jump);
1220 timestamp_ += timestamp_jump;
1221 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001222 return 0;
1223 }
Henrik Lundincf808d22015-05-27 14:33:29 +02001224 case kAccelerate:
1225 case kFastAccelerate: {
1226 // In order to do an accelerate we need at least 30 ms of audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001227 if (samples_left >= static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001228 // Already have enough data, so we do not need to extract any more.
1229 decision_logic_->set_sample_memory(samples_left);
1230 decision_logic_->set_prev_time_scale(true);
1231 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001232 } else if (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001233 decoder_frame_length_ >= samples_30_ms) {
1234 // Avoid decoding more data as it might overflow the playout buffer.
1235 *operation = kNormal;
1236 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001237 } else if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001238 decoder_frame_length_ < samples_30_ms) {
1239 // Build up decoded data by decoding at least 20 ms of audio data. Do
1240 // not perform accelerate yet, but wait until we only need to do one
1241 // decoding.
1242 required_samples = 2 * output_size_samples_;
1243 *operation = kNormal;
1244 }
1245 // If none of the above is true, we have one of two possible situations:
1246 // (1) 20 ms <= samples_left < 30 ms and decoder_frame_length_ < 30 ms; or
1247 // (2) samples_left < 10 ms and decoder_frame_length_ >= 30 ms.
1248 // In either case, we move on with the accelerate decision, and decode one
1249 // frame now.
1250 break;
1251 }
1252 case kPreemptiveExpand: {
1253 // In order to do a preemptive expand we need at least 30 ms of decoded
1254 // audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001255 if ((samples_left >= static_cast<int>(samples_30_ms)) ||
1256 (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001257 decoder_frame_length_ >= samples_30_ms)) {
1258 // Already have enough data, so we do not need to extract any more.
1259 // Or, avoid decoding more data as it might overflow the playout buffer.
1260 // Still try preemptive expand, though.
1261 decision_logic_->set_sample_memory(samples_left);
1262 decision_logic_->set_prev_time_scale(true);
1263 return 0;
1264 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07001265 if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001266 decoder_frame_length_ < samples_30_ms) {
1267 // Build up decoded data by decoding at least 20 ms of audio data.
1268 // Still try to perform preemptive expand.
1269 required_samples = 2 * output_size_samples_;
1270 }
1271 // Move on with the preemptive expand decision.
1272 break;
1273 }
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001274 case kMerge: {
1275 required_samples =
1276 std::max(merge_->RequiredFutureSamples(), required_samples);
1277 break;
1278 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001279 default: {
1280 // Do nothing.
1281 }
1282 }
1283
1284 // Get packets from buffer.
1285 int extracted_samples = 0;
ossu7a377612016-10-18 04:06:13 -07001286 if (packet && *operation != kAlternativePlc &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001287 *operation != kAlternativePlcIncreaseTimestamp &&
1288 *operation != kAudioRepetition &&
1289 *operation != kAudioRepetitionIncreaseTimestamp) {
ossu7a377612016-10-18 04:06:13 -07001290 sync_buffer_->IncreaseEndTimestamp(packet->timestamp - end_timestamp);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001291 if (decision_logic_->CngOff()) {
1292 // Adjustment of timestamp only corresponds to an actual packet loss
1293 // if comfort noise is not played. If comfort noise was just played,
1294 // this adjustment of timestamp is only done to get back in sync with the
1295 // stream timestamp; no loss to report.
ossu7a377612016-10-18 04:06:13 -07001296 stats_.LostSamples(packet->timestamp - end_timestamp);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001297 }
1298
1299 if (*operation != kRfc3389Cng) {
1300 // We are about to decode and use a non-CNG packet.
1301 decision_logic_->SetCngOff();
1302 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001303
1304 extracted_samples = ExtractPackets(required_samples, packet_list);
1305 if (extracted_samples < 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001306 return kPacketBufferCorruption;
1307 }
1308 }
1309
Henrik Lundincf808d22015-05-27 14:33:29 +02001310 if (*operation == kAccelerate || *operation == kFastAccelerate ||
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001311 *operation == kPreemptiveExpand) {
1312 decision_logic_->set_sample_memory(samples_left + extracted_samples);
1313 decision_logic_->set_prev_time_scale(true);
1314 }
1315
Henrik Lundincf808d22015-05-27 14:33:29 +02001316 if (*operation == kAccelerate || *operation == kFastAccelerate) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001317 // Check that we have enough data (30ms) to do accelerate.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001318 if (extracted_samples + samples_left < static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001319 // TODO(hlundin): Write test for this.
1320 // Not enough, do normal operation instead.
1321 *operation = kNormal;
1322 }
1323 }
1324
1325 timestamp_ = end_timestamp;
1326 return 0;
1327}
1328
1329int NetEqImpl::Decode(PacketList* packet_list, Operations* operation,
1330 int* decoded_length,
1331 AudioDecoder::SpeechType* speech_type) {
1332 *speech_type = AudioDecoder::kSpeech;
minyuel6d92bf52015-09-23 15:20:39 +02001333
1334 // When packet_list is empty, we may be in kCodecInternalCng mode, and for
1335 // that we use current active decoder.
1336 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1337
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001338 if (!packet_list->empty()) {
ossua73f6c92016-10-24 08:25:28 -07001339 const Packet& packet = packet_list->front();
1340 uint8_t payload_type = packet.payload_type;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001341 if (!decoder_database_->IsComfortNoise(payload_type)) {
1342 decoder = decoder_database_->GetDecoder(payload_type);
1343 assert(decoder);
1344 if (!decoder) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001345 RTC_LOG(LS_WARNING)
1346 << "Unknown payload type " << static_cast<int>(payload_type);
ossua73f6c92016-10-24 08:25:28 -07001347 packet_list->clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001348 return kDecoderNotFound;
1349 }
1350 bool decoder_changed;
1351 decoder_database_->SetActiveDecoder(payload_type, &decoder_changed);
1352 if (decoder_changed) {
1353 // We have a new decoder. Re-init some values.
1354 const DecoderDatabase::DecoderInfo* decoder_info = decoder_database_
1355 ->GetDecoderInfo(payload_type);
1356 assert(decoder_info);
1357 if (!decoder_info) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001358 RTC_LOG(LS_WARNING)
1359 << "Unknown payload type " << static_cast<int>(payload_type);
ossua73f6c92016-10-24 08:25:28 -07001360 packet_list->clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001361 return kDecoderNotFound;
1362 }
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001363 // If sampling rate or number of channels has changed, we need to make
1364 // a reset.
kwibergc0f2dcf2016-05-31 06:28:03 -07001365 if (decoder_info->SampleRateHz() != fs_hz_ ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001366 decoder->Channels() != algorithm_buffer_->Channels()) {
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001367 // TODO(tlegrand): Add unittest to cover this event.
kwibergc0f2dcf2016-05-31 06:28:03 -07001368 SetSampleRateAndChannels(decoder_info->SampleRateHz(),
1369 decoder->Channels());
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001370 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001371 sync_buffer_->set_end_timestamp(timestamp_);
1372 playout_timestamp_ = timestamp_;
1373 }
1374 }
1375 }
1376
1377 if (reset_decoder_) {
1378 // TODO(hlundin): Write test for this.
Karl Wiberg43766482015-08-27 15:22:11 +02001379 if (decoder)
1380 decoder->Reset();
1381
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001382 // Reset comfort noise decoder.
ossu97ba30e2016-04-25 07:55:58 -07001383 ComfortNoiseDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02001384 if (cng_decoder)
1385 cng_decoder->Reset();
1386
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001387 reset_decoder_ = false;
1388 }
1389
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001390 *decoded_length = 0;
1391 // Update codec-internal PLC state.
1392 if ((*operation == kMerge) && decoder && decoder->HasDecodePlc()) {
1393 decoder->DecodePlc(1, &decoded_buffer_[*decoded_length]);
1394 }
1395
minyuel6d92bf52015-09-23 15:20:39 +02001396 int return_value;
1397 if (*operation == kCodecInternalCng) {
1398 RTC_DCHECK(packet_list->empty());
1399 return_value = DecodeCng(decoder, decoded_length, speech_type);
1400 } else {
1401 return_value = DecodeLoop(packet_list, *operation, decoder,
1402 decoded_length, speech_type);
1403 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001404
1405 if (*decoded_length < 0) {
1406 // Error returned from the decoder.
1407 *decoded_length = 0;
Peter Kastingb7e50542015-06-11 12:55:50 -07001408 sync_buffer_->IncreaseEndTimestamp(
1409 static_cast<uint32_t>(decoder_frame_length_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001410 int error_code = 0;
1411 if (decoder)
1412 error_code = decoder->ErrorCode();
1413 if (error_code != 0) {
1414 // Got some error code from the decoder.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001415 return_value = kDecoderErrorCode;
Mirko Bonadei675513b2017-11-09 11:09:25 +01001416 RTC_LOG(LS_WARNING) << "Decoder returned error code: " << error_code;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001417 } else {
1418 // Decoder does not implement error codes. Return generic error.
1419 return_value = kOtherDecoderError;
Mirko Bonadei675513b2017-11-09 11:09:25 +01001420 RTC_LOG(LS_WARNING) << "Decoder error (no error code)";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001421 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001422 *operation = kExpand; // Do expansion to get data instead.
1423 }
1424 if (*speech_type != AudioDecoder::kComfortNoise) {
1425 // Don't increment timestamp if codec returned CNG speech type
1426 // since in this case, the we will increment the CNGplayedTS counter.
1427 // Increase with number of samples per channel.
1428 assert(*decoded_length == 0 ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001429 (decoder && decoder->Channels() == sync_buffer_->Channels()));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001430 sync_buffer_->IncreaseEndTimestamp(
1431 *decoded_length / static_cast<int>(sync_buffer_->Channels()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001432 }
1433 return return_value;
1434}
1435
minyuel6d92bf52015-09-23 15:20:39 +02001436int NetEqImpl::DecodeCng(AudioDecoder* decoder, int* decoded_length,
1437 AudioDecoder::SpeechType* speech_type) {
1438 if (!decoder) {
1439 // This happens when active decoder is not defined.
1440 *decoded_length = -1;
1441 return 0;
1442 }
1443
kwibergd3edd772017-03-01 18:52:48 -08001444 while (*decoded_length < rtc::dchecked_cast<int>(output_size_samples_)) {
minyuel6d92bf52015-09-23 15:20:39 +02001445 const int length = decoder->Decode(
1446 nullptr, 0, fs_hz_,
1447 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1448 &decoded_buffer_[*decoded_length], speech_type);
1449 if (length > 0) {
1450 *decoded_length += length;
minyuel6d92bf52015-09-23 15:20:39 +02001451 } else {
1452 // Error.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001453 RTC_LOG(LS_WARNING) << "Failed to decode CNG";
minyuel6d92bf52015-09-23 15:20:39 +02001454 *decoded_length = -1;
1455 break;
1456 }
1457 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1458 // Guard against overflow.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001459 RTC_LOG(LS_WARNING) << "Decoded too much CNG.";
minyuel6d92bf52015-09-23 15:20:39 +02001460 return kDecodedTooMuch;
1461 }
1462 }
1463 return 0;
1464}
1465
1466int NetEqImpl::DecodeLoop(PacketList* packet_list, const Operations& operation,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001467 AudioDecoder* decoder, int* decoded_length,
1468 AudioDecoder::SpeechType* speech_type) {
henrik.lundin114c1b32017-04-26 07:47:32 -07001469 RTC_DCHECK(last_decoded_timestamps_.empty());
1470
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001471 // Do decoding.
ossua73f6c92016-10-24 08:25:28 -07001472 while (
1473 !packet_list->empty() &&
1474 !decoder_database_->IsComfortNoise(packet_list->front().payload_type)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001475 assert(decoder); // At this point, we must have a decoder object.
1476 // The number of channels in the |sync_buffer_| should be the same as the
1477 // number decoder channels.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001478 assert(sync_buffer_->Channels() == decoder->Channels());
1479 assert(decoded_buffer_length_ >= kMaxFrameSize * decoder->Channels());
minyuel6d92bf52015-09-23 15:20:39 +02001480 assert(operation == kNormal || operation == kAccelerate ||
1481 operation == kFastAccelerate || operation == kMerge ||
1482 operation == kPreemptiveExpand);
ossua73f6c92016-10-24 08:25:28 -07001483
1484 auto opt_result = packet_list->front().frame->Decode(
ossu61a208b2016-09-20 01:38:00 -07001485 rtc::ArrayView<int16_t>(&decoded_buffer_[*decoded_length],
1486 decoded_buffer_length_ - *decoded_length));
henrik.lundin114c1b32017-04-26 07:47:32 -07001487 last_decoded_timestamps_.push_back(packet_list->front().timestamp);
ossua73f6c92016-10-24 08:25:28 -07001488 packet_list->pop_front();
ossu61a208b2016-09-20 01:38:00 -07001489 if (opt_result) {
1490 const auto& result = *opt_result;
1491 *speech_type = result.speech_type;
1492 if (result.num_decoded_samples > 0) {
kwibergd3edd772017-03-01 18:52:48 -08001493 *decoded_length += rtc::dchecked_cast<int>(result.num_decoded_samples);
ossu61a208b2016-09-20 01:38:00 -07001494 // Update |decoder_frame_length_| with number of samples per channel.
1495 decoder_frame_length_ =
1496 result.num_decoded_samples / decoder->Channels();
1497 }
1498 } else {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001499 // Error.
ossu61a208b2016-09-20 01:38:00 -07001500 // TODO(ossu): What to put here?
Mirko Bonadei675513b2017-11-09 11:09:25 +01001501 RTC_LOG(LS_WARNING) << "Decode error";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001502 *decoded_length = -1;
ossua73f6c92016-10-24 08:25:28 -07001503 packet_list->clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001504 break;
1505 }
kwibergd3edd772017-03-01 18:52:48 -08001506 if (*decoded_length > rtc::dchecked_cast<int>(decoded_buffer_length_)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001507 // Guard against overflow.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001508 RTC_LOG(LS_WARNING) << "Decoded too much.";
ossua73f6c92016-10-24 08:25:28 -07001509 packet_list->clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001510 return kDecodedTooMuch;
1511 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001512 } // End of decode loop.
1513
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001514 // If the list is not empty at this point, either a decoding error terminated
1515 // the while-loop, or list must hold exactly one CNG packet.
ossua73f6c92016-10-24 08:25:28 -07001516 assert(
1517 packet_list->empty() || *decoded_length < 0 ||
1518 (packet_list->size() == 1 &&
1519 decoder_database_->IsComfortNoise(packet_list->front().payload_type)));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001520 return 0;
1521}
1522
1523void NetEqImpl::DoNormal(const int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001524 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001525 assert(normal_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001526 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001527 normal_->Process(decoded_buffer, decoded_length, last_mode_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001528 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001529 if (decoded_length != 0) {
1530 last_mode_ = kModeNormal;
1531 }
1532
1533 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1534 if ((speech_type == AudioDecoder::kComfortNoise)
1535 || ((last_mode_ == kModeCodecInternalCng)
1536 && (decoded_length == 0))) {
1537 // TODO(hlundin): Remove second part of || statement above.
1538 last_mode_ = kModeCodecInternalCng;
1539 }
1540
1541 if (!play_dtmf) {
1542 dtmf_tone_generator_->Reset();
1543 }
1544}
1545
1546void NetEqImpl::DoMerge(int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001547 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001548 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001549 assert(merge_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001550 size_t new_length = merge_->Process(decoded_buffer, decoded_length,
1551 mute_factor_array_.get(),
1552 algorithm_buffer_.get());
henrik.lundin2979f552017-05-05 05:04:16 -07001553 // Correction can be negative.
1554 int expand_length_correction =
1555 rtc::dchecked_cast<int>(new_length) -
1556 rtc::dchecked_cast<int>(decoded_length / algorithm_buffer_->Channels());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001557
1558 // Update in-call and post-call statistics.
1559 if (expand_->MuteFactor(0) == 0) {
1560 // Expand generates only noise.
henrik.lundin2979f552017-05-05 05:04:16 -07001561 stats_.ExpandedNoiseSamplesCorrection(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001562 } else {
1563 // Expansion generates more than only noise.
henrik.lundin2979f552017-05-05 05:04:16 -07001564 stats_.ExpandedVoiceSamplesCorrection(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001565 }
1566
1567 last_mode_ = kModeMerge;
1568 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1569 if (speech_type == AudioDecoder::kComfortNoise) {
1570 last_mode_ = kModeCodecInternalCng;
1571 }
1572 expand_->Reset();
1573 if (!play_dtmf) {
1574 dtmf_tone_generator_->Reset();
1575 }
1576}
1577
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001578int NetEqImpl::DoExpand(bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001579 while ((sync_buffer_->FutureLength() - expand_->overlap_length()) <
Peter Kastingdce40cf2015-08-24 14:52:23 -07001580 output_size_samples_) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001581 algorithm_buffer_->Clear();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001582 int return_value = expand_->Process(algorithm_buffer_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001583 size_t length = algorithm_buffer_->Size();
Gustaf Ullberg9a2e9062017-09-18 09:28:20 +02001584 bool is_new_concealment_event = (last_mode_ != kModeExpand);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001585
1586 // Update in-call and post-call statistics.
1587 if (expand_->MuteFactor(0) == 0) {
1588 // Expand operation generates only noise.
Gustaf Ullberg9a2e9062017-09-18 09:28:20 +02001589 stats_.ExpandedNoiseSamples(length, is_new_concealment_event);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001590 } else {
1591 // Expand operation generates more than only noise.
Gustaf Ullberg9a2e9062017-09-18 09:28:20 +02001592 stats_.ExpandedVoiceSamples(length, is_new_concealment_event);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001593 }
1594
1595 last_mode_ = kModeExpand;
1596
1597 if (return_value < 0) {
1598 return return_value;
1599 }
1600
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001601 sync_buffer_->PushBack(*algorithm_buffer_);
1602 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001603 }
1604 if (!play_dtmf) {
1605 dtmf_tone_generator_->Reset();
1606 }
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001607
1608 if (!generated_noise_stopwatch_) {
1609 // Start a new stopwatch since we may be covering for a lost CNG packet.
1610 generated_noise_stopwatch_ = tick_timer_->GetNewStopwatch();
1611 }
1612
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001613 return 0;
1614}
1615
Henrik Lundincf808d22015-05-27 14:33:29 +02001616int NetEqImpl::DoAccelerate(int16_t* decoded_buffer,
1617 size_t decoded_length,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001618 AudioDecoder::SpeechType speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +02001619 bool play_dtmf,
1620 bool fast_accelerate) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001621 const size_t required_samples =
1622 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001623 size_t borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001624 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001625 size_t decoded_length_per_channel = decoded_length / num_channels;
1626 if (decoded_length_per_channel < required_samples) {
1627 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001628 borrowed_samples_per_channel = static_cast<int>(required_samples -
1629 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001630 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1631 decoded_buffer,
1632 sizeof(int16_t) * decoded_length);
1633 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1634 decoded_buffer);
1635 decoded_length = required_samples * num_channels;
1636 }
1637
Peter Kastingdce40cf2015-08-24 14:52:23 -07001638 size_t samples_removed;
Henrik Lundincf808d22015-05-27 14:33:29 +02001639 Accelerate::ReturnCodes return_code =
1640 accelerate_->Process(decoded_buffer, decoded_length, fast_accelerate,
1641 algorithm_buffer_.get(), &samples_removed);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001642 stats_.AcceleratedSamples(samples_removed);
1643 switch (return_code) {
1644 case Accelerate::kSuccess:
1645 last_mode_ = kModeAccelerateSuccess;
1646 break;
1647 case Accelerate::kSuccessLowEnergy:
1648 last_mode_ = kModeAccelerateLowEnergy;
1649 break;
1650 case Accelerate::kNoStretch:
1651 last_mode_ = kModeAccelerateFail;
1652 break;
1653 case Accelerate::kError:
1654 // TODO(hlundin): Map to kModeError instead?
1655 last_mode_ = kModeAccelerateFail;
1656 return kAccelerateError;
1657 }
1658
1659 if (borrowed_samples_per_channel > 0) {
1660 // Copy borrowed samples back to the |sync_buffer_|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001661 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001662 if (length < borrowed_samples_per_channel) {
1663 // This destroys the beginning of the buffer, but will not cause any
1664 // problems.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001665 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001666 sync_buffer_->Size() -
1667 borrowed_samples_per_channel);
1668 sync_buffer_->PushFrontZeros(borrowed_samples_per_channel - length);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001669 algorithm_buffer_->PopFront(length);
1670 assert(algorithm_buffer_->Empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001671 } else {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001672 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001673 borrowed_samples_per_channel,
1674 sync_buffer_->Size() -
1675 borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001676 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001677 }
1678 }
1679
1680 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1681 if (speech_type == AudioDecoder::kComfortNoise) {
1682 last_mode_ = kModeCodecInternalCng;
1683 }
1684 if (!play_dtmf) {
1685 dtmf_tone_generator_->Reset();
1686 }
1687 expand_->Reset();
1688 return 0;
1689}
1690
1691int NetEqImpl::DoPreemptiveExpand(int16_t* decoded_buffer,
1692 size_t decoded_length,
1693 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001694 bool play_dtmf) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001695 const size_t required_samples =
1696 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001697 size_t num_channels = algorithm_buffer_->Channels();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001698 size_t borrowed_samples_per_channel = 0;
1699 size_t old_borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001700 size_t decoded_length_per_channel = decoded_length / num_channels;
1701 if (decoded_length_per_channel < required_samples) {
1702 // Must move data from the |sync_buffer_| in order to get 30 ms.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001703 borrowed_samples_per_channel =
1704 required_samples - decoded_length_per_channel;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001705 // Calculate how many of these were already played out.
Peter Kastingf045e4d2015-06-10 21:15:38 -07001706 old_borrowed_samples_per_channel =
Peter Kastingdce40cf2015-08-24 14:52:23 -07001707 (borrowed_samples_per_channel > sync_buffer_->FutureLength()) ?
1708 (borrowed_samples_per_channel - sync_buffer_->FutureLength()) : 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001709 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1710 decoded_buffer,
1711 sizeof(int16_t) * decoded_length);
1712 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1713 decoded_buffer);
1714 decoded_length = required_samples * num_channels;
1715 }
1716
Peter Kastingdce40cf2015-08-24 14:52:23 -07001717 size_t samples_added;
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001718 PreemptiveExpand::ReturnCodes return_code = preemptive_expand_->Process(
Peter Kastingdce40cf2015-08-24 14:52:23 -07001719 decoded_buffer, decoded_length,
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001720 old_borrowed_samples_per_channel,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001721 algorithm_buffer_.get(), &samples_added);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001722 stats_.PreemptiveExpandedSamples(samples_added);
1723 switch (return_code) {
1724 case PreemptiveExpand::kSuccess:
1725 last_mode_ = kModePreemptiveExpandSuccess;
1726 break;
1727 case PreemptiveExpand::kSuccessLowEnergy:
1728 last_mode_ = kModePreemptiveExpandLowEnergy;
1729 break;
1730 case PreemptiveExpand::kNoStretch:
1731 last_mode_ = kModePreemptiveExpandFail;
1732 break;
1733 case PreemptiveExpand::kError:
1734 // TODO(hlundin): Map to kModeError instead?
1735 last_mode_ = kModePreemptiveExpandFail;
1736 return kPreemptiveExpandError;
1737 }
1738
1739 if (borrowed_samples_per_channel > 0) {
1740 // Copy borrowed samples back to the |sync_buffer_|.
1741 sync_buffer_->ReplaceAtIndex(
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001742 *algorithm_buffer_, borrowed_samples_per_channel,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001743 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001744 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001745 }
1746
1747 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1748 if (speech_type == AudioDecoder::kComfortNoise) {
1749 last_mode_ = kModeCodecInternalCng;
1750 }
1751 if (!play_dtmf) {
1752 dtmf_tone_generator_->Reset();
1753 }
1754 expand_->Reset();
1755 return 0;
1756}
1757
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001758int NetEqImpl::DoRfc3389Cng(PacketList* packet_list, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001759 if (!packet_list->empty()) {
1760 // Must have exactly one SID frame at this point.
1761 assert(packet_list->size() == 1);
ossua73f6c92016-10-24 08:25:28 -07001762 const Packet& packet = packet_list->front();
1763 if (!decoder_database_->IsComfortNoise(packet.payload_type)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001764 RTC_LOG(LS_ERROR) << "Trying to decode non-CNG payload as CNG.";
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001765 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001766 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001767 if (comfort_noise_->UpdateParameters(packet) ==
1768 ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001769 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001770 return -comfort_noise_->internal_error_code();
1771 }
1772 }
1773 int cn_return = comfort_noise_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001774 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001775 expand_->Reset();
1776 last_mode_ = kModeRfc3389Cng;
1777 if (!play_dtmf) {
1778 dtmf_tone_generator_->Reset();
1779 }
1780 if (cn_return == ComfortNoise::kInternalError) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001781 RTC_LOG(LS_WARNING) << "Comfort noise generator returned error code: "
1782 << comfort_noise_->internal_error_code();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001783 return kComfortNoiseErrorCode;
1784 } else if (cn_return == ComfortNoise::kUnknownPayloadType) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001785 return kUnknownRtpPayloadType;
1786 }
1787 return 0;
1788}
1789
minyuel6d92bf52015-09-23 15:20:39 +02001790void NetEqImpl::DoCodecInternalCng(const int16_t* decoded_buffer,
1791 size_t decoded_length) {
1792 RTC_DCHECK(normal_.get());
1793 RTC_DCHECK(mute_factor_array_.get());
1794 normal_->Process(decoded_buffer, decoded_length, last_mode_,
1795 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001796 last_mode_ = kModeCodecInternalCng;
1797 expand_->Reset();
1798}
1799
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001800int NetEqImpl::DoDtmf(const DtmfEvent& dtmf_event, bool* play_dtmf) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001801 // This block of the code and the block further down, handling |dtmf_switch|
1802 // are commented out. Otherwise playing out-of-band DTMF would fail in VoE
1803 // test, DtmfTest.ManualSuccessfullySendsOutOfBandTelephoneEvents. This is
1804 // equivalent to |dtmf_switch| always be false.
1805 //
1806 // See http://webrtc-codereview.appspot.com/1195004/ for discussion
1807 // On this issue. This change might cause some glitches at the point of
1808 // switch from audio to DTMF. Issue 1545 is filed to track this.
1809 //
1810 // bool dtmf_switch = false;
1811 // if ((last_mode_ != kModeDtmf) && dtmf_tone_generator_->initialized()) {
1812 // // Special case; see below.
1813 // // We must catch this before calling Generate, since |initialized| is
1814 // // modified in that call.
1815 // dtmf_switch = true;
1816 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001817
1818 int dtmf_return_value = 0;
1819 if (!dtmf_tone_generator_->initialized()) {
1820 // Initialize if not already done.
1821 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1822 dtmf_event.volume);
1823 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001824
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001825 if (dtmf_return_value == 0) {
1826 // Generate DTMF signal.
1827 dtmf_return_value = dtmf_tone_generator_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001828 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001829 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001830
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001831 if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001832 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001833 return dtmf_return_value;
1834 }
1835
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001836 // if (dtmf_switch) {
1837 // // This is the special case where the previous operation was DTMF
1838 // // overdub, but the current instruction is "regular" DTMF. We must make
1839 // // sure that the DTMF does not have any discontinuities. The first DTMF
1840 // // sample that we generate now must be played out immediately, therefore
1841 // // it must be copied to the speech buffer.
1842 // // TODO(hlundin): This code seems incorrect. (Legacy.) Write test and
1843 // // verify correct operation.
1844 // assert(false);
1845 // // Must generate enough data to replace all of the |sync_buffer_|
1846 // // "future".
1847 // int required_length = sync_buffer_->FutureLength();
1848 // assert(dtmf_tone_generator_->initialized());
1849 // dtmf_return_value = dtmf_tone_generator_->Generate(required_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001850 // algorithm_buffer_);
1851 // assert((size_t) required_length == algorithm_buffer_->Size());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001852 // if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001853 // algorithm_buffer_->Zeros(output_size_samples_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001854 // return dtmf_return_value;
1855 // }
1856 //
1857 // // Overwrite the "future" part of the speech buffer with the new DTMF
1858 // // data.
1859 // // TODO(hlundin): It seems that this overwriting has gone lost.
1860 // // Not adapted for multi-channel yet.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001861 // assert(algorithm_buffer_->Channels() == 1);
1862 // if (algorithm_buffer_->Channels() != 1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001863 // RTC_LOG(LS_WARNING) << "DTMF not supported for more than one channel";
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001864 // return kStereoNotSupported;
1865 // }
1866 // // Shuffle the remaining data to the beginning of algorithm buffer.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001867 // algorithm_buffer_->PopFront(sync_buffer_->FutureLength());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001868 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001869
Peter Kastingb7e50542015-06-11 12:55:50 -07001870 sync_buffer_->IncreaseEndTimestamp(
1871 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001872 expand_->Reset();
1873 last_mode_ = kModeDtmf;
1874
1875 // Set to false because the DTMF is already in the algorithm buffer.
1876 *play_dtmf = false;
1877 return 0;
1878}
1879
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001880void NetEqImpl::DoAlternativePlc(bool increase_timestamp) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001881 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001882 size_t length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001883 if (decoder && decoder->HasDecodePlc()) {
1884 // Use the decoder's packet-loss concealment.
1885 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1886 int16_t decoded_buffer[kMaxFrameSize];
1887 length = decoder->DecodePlc(1, decoded_buffer);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001888 if (length > 0)
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001889 algorithm_buffer_->PushBackInterleaved(decoded_buffer, length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001890 } else {
1891 // Do simple zero-stuffing.
1892 length = output_size_samples_;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001893 algorithm_buffer_->Zeros(length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001894 // By not advancing the timestamp, NetEq inserts samples.
1895 stats_.AddZeros(length);
1896 }
1897 if (increase_timestamp) {
Peter Kastingb7e50542015-06-11 12:55:50 -07001898 sync_buffer_->IncreaseEndTimestamp(static_cast<uint32_t>(length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001899 }
1900 expand_->Reset();
1901}
1902
1903int NetEqImpl::DtmfOverdub(const DtmfEvent& dtmf_event, size_t num_channels,
1904 int16_t* output) const {
1905 size_t out_index = 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001906 size_t overdub_length = output_size_samples_; // Default value.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001907
1908 if (sync_buffer_->dtmf_index() > sync_buffer_->next_index()) {
1909 // Special operation for transition from "DTMF only" to "DTMF overdub".
1910 out_index = std::min(
1911 sync_buffer_->dtmf_index() - sync_buffer_->next_index(),
Peter Kastingdce40cf2015-08-24 14:52:23 -07001912 output_size_samples_);
1913 overdub_length = output_size_samples_ - out_index;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001914 }
1915
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001916 AudioMultiVector dtmf_output(num_channels);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001917 int dtmf_return_value = 0;
1918 if (!dtmf_tone_generator_->initialized()) {
1919 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1920 dtmf_event.volume);
1921 }
1922 if (dtmf_return_value == 0) {
1923 dtmf_return_value = dtmf_tone_generator_->Generate(overdub_length,
1924 &dtmf_output);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001925 assert(overdub_length == dtmf_output.Size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001926 }
1927 dtmf_output.ReadInterleaved(overdub_length, &output[out_index]);
1928 return dtmf_return_value < 0 ? dtmf_return_value : 0;
1929}
1930
Peter Kastingdce40cf2015-08-24 14:52:23 -07001931int NetEqImpl::ExtractPackets(size_t required_samples,
1932 PacketList* packet_list) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001933 bool first_packet = true;
1934 uint8_t prev_payload_type = 0;
1935 uint32_t prev_timestamp = 0;
1936 uint16_t prev_sequence_number = 0;
1937 bool next_packet_available = false;
1938
ossu7a377612016-10-18 04:06:13 -07001939 const Packet* next_packet = packet_buffer_->PeekNextPacket();
1940 RTC_DCHECK(next_packet);
1941 if (!next_packet) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001942 RTC_LOG(LS_ERROR) << "Packet buffer unexpectedly empty.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001943 return -1;
1944 }
ossu7a377612016-10-18 04:06:13 -07001945 uint32_t first_timestamp = next_packet->timestamp;
ossu61a208b2016-09-20 01:38:00 -07001946 size_t extracted_samples = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001947
1948 // Packet extraction loop.
1949 do {
ossu7a377612016-10-18 04:06:13 -07001950 timestamp_ = next_packet->timestamp;
ossua73f6c92016-10-24 08:25:28 -07001951 rtc::Optional<Packet> packet = packet_buffer_->GetNextPacket();
ossu7a377612016-10-18 04:06:13 -07001952 // |next_packet| may be invalid after the |packet_buffer_| operation.
ossua73f6c92016-10-24 08:25:28 -07001953 next_packet = nullptr;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001954 if (!packet) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001955 RTC_LOG(LS_ERROR) << "Should always be able to extract a packet here";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001956 assert(false); // Should always be able to extract a packet here.
1957 return -1;
1958 }
Gustaf Ullbergb0a02072017-10-02 12:00:34 +02001959 const uint64_t waiting_time_ms = packet->waiting_time->ElapsedMs();
1960 stats_.StoreWaitingTime(waiting_time_ms);
ossu61a208b2016-09-20 01:38:00 -07001961 RTC_DCHECK(!packet->empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001962
1963 if (first_packet) {
1964 first_packet = false;
henrik.lundin48ed9302015-10-29 05:36:24 -07001965 if (nack_enabled_) {
1966 RTC_DCHECK(nack_);
1967 // TODO(henrik.lundin): Should we update this for all decoded packets?
ossu7a377612016-10-18 04:06:13 -07001968 nack_->UpdateLastDecodedPacket(packet->sequence_number,
1969 packet->timestamp);
henrik.lundin48ed9302015-10-29 05:36:24 -07001970 }
ossu7a377612016-10-18 04:06:13 -07001971 prev_sequence_number = packet->sequence_number;
1972 prev_timestamp = packet->timestamp;
1973 prev_payload_type = packet->payload_type;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001974 }
1975
ossucafb4972017-01-02 07:00:50 -08001976 const bool has_cng_packet =
1977 decoder_database_->IsComfortNoise(packet->payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001978 // Store number of extracted samples.
ossu61a208b2016-09-20 01:38:00 -07001979 size_t packet_duration = 0;
1980 if (packet->frame) {
1981 packet_duration = packet->frame->Duration();
ossua70695a2016-09-22 02:06:28 -07001982 // TODO(ossu): Is this the correct way to track Opus FEC packets?
1983 if (packet->priority.codec_level > 0) {
kwibergd3edd772017-03-01 18:52:48 -08001984 stats_.SecondaryDecodedSamples(
1985 rtc::dchecked_cast<int>(packet_duration));
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001986 }
ossucafb4972017-01-02 07:00:50 -08001987 } else if (!has_cng_packet) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001988 RTC_LOG(LS_WARNING) << "Unknown payload type "
1989 << static_cast<int>(packet->payload_type);
ossu61a208b2016-09-20 01:38:00 -07001990 RTC_NOTREACHED();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001991 }
ossu61a208b2016-09-20 01:38:00 -07001992
1993 if (packet_duration == 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001994 // Decoder did not return a packet duration. Assume that the packet
1995 // contains the same number of samples as the previous one.
ossu61a208b2016-09-20 01:38:00 -07001996 packet_duration = decoder_frame_length_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001997 }
ossu7a377612016-10-18 04:06:13 -07001998 extracted_samples = packet->timestamp - first_timestamp + packet_duration;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001999
Gustaf Ullbergb0a02072017-10-02 12:00:34 +02002000 stats_.JitterBufferDelay(extracted_samples, waiting_time_ms);
2001
ossua73f6c92016-10-24 08:25:28 -07002002 packet_list->push_back(std::move(*packet)); // Store packet in list.
Oskar Sundbom12ab00b2017-11-16 15:31:38 +01002003 packet = rtc::nullopt; // Ensure it's never used after the move.
ossua73f6c92016-10-24 08:25:28 -07002004
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002005 // Check what packet is available next.
ossu7a377612016-10-18 04:06:13 -07002006 next_packet = packet_buffer_->PeekNextPacket();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002007 next_packet_available = false;
ossucafb4972017-01-02 07:00:50 -08002008 if (next_packet && prev_payload_type == next_packet->payload_type &&
2009 !has_cng_packet) {
ossu7a377612016-10-18 04:06:13 -07002010 int16_t seq_no_diff = next_packet->sequence_number - prev_sequence_number;
2011 size_t ts_diff = next_packet->timestamp - prev_timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002012 if (seq_no_diff == 1 ||
2013 (seq_no_diff == 0 && ts_diff == decoder_frame_length_)) {
2014 // The next sequence number is available, or the next part of a packet
2015 // that was split into pieces upon insertion.
2016 next_packet_available = true;
2017 }
ossu7a377612016-10-18 04:06:13 -07002018 prev_sequence_number = next_packet->sequence_number;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002019 }
ossu61a208b2016-09-20 01:38:00 -07002020 } while (extracted_samples < required_samples && next_packet_available);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002021
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00002022 if (extracted_samples > 0) {
2023 // Delete old packets only when we are going to decode something. Otherwise,
2024 // we could end up in the situation where we never decode anything, since
2025 // all incoming packets are considered too old but the buffer will also
2026 // never be flooded and flushed.
minyue-webrtcfae474c2017-07-05 11:17:40 +02002027 packet_buffer_->DiscardAllOldPackets(timestamp_, &stats_);
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00002028 }
2029
kwibergd3edd772017-03-01 18:52:48 -08002030 return rtc::dchecked_cast<int>(extracted_samples);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002031}
2032
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002033void NetEqImpl::UpdatePlcComponents(int fs_hz, size_t channels) {
2034 // Delete objects and create new ones.
2035 expand_.reset(expand_factory_->Create(background_noise_.get(),
2036 sync_buffer_.get(), &random_vector_,
Henrik Lundinbef77e22015-08-18 14:58:09 +02002037 &stats_, fs_hz, channels));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002038 merge_.reset(new Merge(fs_hz, channels, expand_.get(), sync_buffer_.get()));
2039}
2040
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002041void NetEqImpl::SetSampleRateAndChannels(int fs_hz, size_t channels) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002042 RTC_LOG(LS_VERBOSE) << "SetSampleRateAndChannels " << fs_hz << " "
2043 << channels;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002044 // TODO(hlundin): Change to an enumerator and skip assert.
2045 assert(fs_hz == 8000 || fs_hz == 16000 || fs_hz == 32000 || fs_hz == 48000);
2046 assert(channels > 0);
2047
2048 fs_hz_ = fs_hz;
2049 fs_mult_ = fs_hz / 8000;
Peter Kastingdce40cf2015-08-24 14:52:23 -07002050 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002051 decoder_frame_length_ = 3 * output_size_samples_; // Initialize to 30ms.
2052
2053 last_mode_ = kModeNormal;
2054
2055 // Create a new array of mute factors and set all to 1.
2056 mute_factor_array_.reset(new int16_t[channels]);
2057 for (size_t i = 0; i < channels; ++i) {
2058 mute_factor_array_[i] = 16384; // 1.0 in Q14.
2059 }
2060
ossu97ba30e2016-04-25 07:55:58 -07002061 ComfortNoiseDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02002062 if (cng_decoder)
2063 cng_decoder->Reset();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002064
2065 // Reinit post-decode VAD with new sample rate.
2066 assert(vad_.get()); // Cannot be NULL here.
2067 vad_->Init();
2068
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002069 // Delete algorithm buffer and create a new one.
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00002070 algorithm_buffer_.reset(new AudioMultiVector(channels));
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002071
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002072 // Delete sync buffer and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002073 sync_buffer_.reset(new SyncBuffer(channels, kSyncBufferSize * fs_mult_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002074
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00002075 // Delete BackgroundNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002076 background_noise_.reset(new BackgroundNoise(channels));
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00002077 background_noise_->set_mode(background_noise_mode_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002078
2079 // Reset random vector.
2080 random_vector_.Reset();
2081
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002082 UpdatePlcComponents(fs_hz, channels);
2083
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002084 // Move index so that we create a small set of future samples (all 0).
2085 sync_buffer_->set_next_index(sync_buffer_->next_index() -
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002086 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002087
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002088 normal_.reset(new Normal(fs_hz, decoder_database_.get(), *background_noise_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002089 expand_.get()));
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +00002090 accelerate_.reset(
2091 accelerate_factory_->Create(fs_hz, channels, *background_noise_));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002092 preemptive_expand_.reset(preemptive_expand_factory_->Create(
Peter Kastingdce40cf2015-08-24 14:52:23 -07002093 fs_hz, channels, *background_noise_, expand_->overlap_length()));
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002094
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002095 // Delete ComfortNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002096 comfort_noise_.reset(new ComfortNoise(fs_hz, decoder_database_.get(),
2097 sync_buffer_.get()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002098
2099 // Verify that |decoded_buffer_| is long enough.
2100 if (decoded_buffer_length_ < kMaxFrameSize * channels) {
2101 // Reallocate to larger size.
2102 decoded_buffer_length_ = kMaxFrameSize * channels;
2103 decoded_buffer_.reset(new int16_t[decoded_buffer_length_]);
2104 }
2105
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002106 // Create DecisionLogic if it is not created yet, then communicate new sample
2107 // rate and output size to DecisionLogic object.
2108 if (!decision_logic_.get()) {
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002109 CreateDecisionLogic();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002110 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002111 decision_logic_->SetSampleRate(fs_hz_, output_size_samples_);
2112}
2113
henrik.lundin55480f52016-03-08 02:37:57 -08002114NetEqImpl::OutputType NetEqImpl::LastOutputType() {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002115 assert(vad_.get());
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002116 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002117 if (last_mode_ == kModeCodecInternalCng || last_mode_ == kModeRfc3389Cng) {
henrik.lundin55480f52016-03-08 02:37:57 -08002118 return OutputType::kCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002119 } else if (last_mode_ == kModeExpand && expand_->MuteFactor(0) == 0) {
2120 // Expand mode has faded down to background noise only (very long expand).
henrik.lundin55480f52016-03-08 02:37:57 -08002121 return OutputType::kPLCCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002122 } else if (last_mode_ == kModeExpand) {
henrik.lundin55480f52016-03-08 02:37:57 -08002123 return OutputType::kPLC;
wu@webrtc.org24301a62013-12-13 19:17:43 +00002124 } else if (vad_->running() && !vad_->active_speech()) {
henrik.lundin55480f52016-03-08 02:37:57 -08002125 return OutputType::kVadPassive;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002126 } else {
henrik.lundin55480f52016-03-08 02:37:57 -08002127 return OutputType::kNormalSpeech;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002128 }
2129}
2130
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002131void NetEqImpl::CreateDecisionLogic() {
Henrik Lundin47b17dc2016-05-10 10:20:59 +02002132 decision_logic_.reset(DecisionLogic::Create(
2133 fs_hz_, output_size_samples_, playout_mode_, decoder_database_.get(),
2134 *packet_buffer_.get(), delay_manager_.get(), buffer_level_filter_.get(),
2135 tick_timer_.get()));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002136}
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002137} // namespace webrtc