blob: 089f6caf9c85c266c893ebb8f93fa18e4cb95c38 [file] [log] [blame]
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001/*
2 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "modules/audio_coding/neteq/neteq_impl.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000012
13#include <assert.h>
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000014
15#include <algorithm>
ossu61a208b2016-09-20 01:38:00 -070016#include <utility>
ossu97ba30e2016-04-25 07:55:58 -070017#include <vector>
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000018
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020019#include "api/audio_codecs/audio_decoder.h"
20#include "common_audio/signal_processing/include/signal_processing_library.h"
21#include "modules/audio_coding/neteq/accelerate.h"
22#include "modules/audio_coding/neteq/background_noise.h"
23#include "modules/audio_coding/neteq/buffer_level_filter.h"
24#include "modules/audio_coding/neteq/comfort_noise.h"
25#include "modules/audio_coding/neteq/decision_logic.h"
26#include "modules/audio_coding/neteq/decoder_database.h"
27#include "modules/audio_coding/neteq/defines.h"
28#include "modules/audio_coding/neteq/delay_manager.h"
29#include "modules/audio_coding/neteq/delay_peak_detector.h"
30#include "modules/audio_coding/neteq/dtmf_buffer.h"
31#include "modules/audio_coding/neteq/dtmf_tone_generator.h"
32#include "modules/audio_coding/neteq/expand.h"
33#include "modules/audio_coding/neteq/merge.h"
34#include "modules/audio_coding/neteq/nack_tracker.h"
35#include "modules/audio_coding/neteq/normal.h"
36#include "modules/audio_coding/neteq/packet.h"
37#include "modules/audio_coding/neteq/packet_buffer.h"
38#include "modules/audio_coding/neteq/post_decode_vad.h"
39#include "modules/audio_coding/neteq/preemptive_expand.h"
40#include "modules/audio_coding/neteq/red_payload_splitter.h"
41#include "modules/audio_coding/neteq/sync_buffer.h"
42#include "modules/audio_coding/neteq/tick_timer.h"
43#include "modules/audio_coding/neteq/timestamp_scaler.h"
44#include "modules/include/module_common_types.h"
45#include "rtc_base/checks.h"
46#include "rtc_base/logging.h"
47#include "rtc_base/safe_conversions.h"
48#include "rtc_base/sanitizer.h"
49#include "rtc_base/trace_event.h"
Henrik Lundin18036282017-11-02 12:09:06 +010050#include "system_wrappers/include/field_trial.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000051
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000052namespace webrtc {
53
ossue3525782016-05-25 07:37:43 -070054NetEqImpl::Dependencies::Dependencies(
55 const NetEq::Config& config,
56 const rtc::scoped_refptr<AudioDecoderFactory>& decoder_factory)
henrik.lundin1d9061e2016-04-26 12:19:34 -070057 : tick_timer(new TickTimer),
58 buffer_level_filter(new BufferLevelFilter),
ossue3525782016-05-25 07:37:43 -070059 decoder_database(new DecoderDatabase(decoder_factory)),
henrik.lundinf3933702016-04-28 01:53:52 -070060 delay_peak_detector(new DelayPeakDetector(tick_timer.get())),
henrik.lundin1d9061e2016-04-26 12:19:34 -070061 delay_manager(new DelayManager(config.max_packets_in_buffer,
henrik.lundin8f8c96d2016-04-28 23:19:20 -070062 delay_peak_detector.get(),
63 tick_timer.get())),
henrik.lundin1d9061e2016-04-26 12:19:34 -070064 dtmf_buffer(new DtmfBuffer(config.sample_rate_hz)),
65 dtmf_tone_generator(new DtmfToneGenerator),
66 packet_buffer(
67 new PacketBuffer(config.max_packets_in_buffer, tick_timer.get())),
ossua70695a2016-09-22 02:06:28 -070068 red_payload_splitter(new RedPayloadSplitter),
henrik.lundin1d9061e2016-04-26 12:19:34 -070069 timestamp_scaler(new TimestampScaler(*decoder_database)),
70 accelerate_factory(new AccelerateFactory),
71 expand_factory(new ExpandFactory),
72 preemptive_expand_factory(new PreemptiveExpandFactory) {}
73
74NetEqImpl::Dependencies::~Dependencies() = default;
75
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +000076NetEqImpl::NetEqImpl(const NetEq::Config& config,
henrik.lundin1d9061e2016-04-26 12:19:34 -070077 Dependencies&& deps,
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +000078 bool create_components)
henrik.lundin1d9061e2016-04-26 12:19:34 -070079 : tick_timer_(std::move(deps.tick_timer)),
80 buffer_level_filter_(std::move(deps.buffer_level_filter)),
81 decoder_database_(std::move(deps.decoder_database)),
82 delay_manager_(std::move(deps.delay_manager)),
83 delay_peak_detector_(std::move(deps.delay_peak_detector)),
84 dtmf_buffer_(std::move(deps.dtmf_buffer)),
85 dtmf_tone_generator_(std::move(deps.dtmf_tone_generator)),
86 packet_buffer_(std::move(deps.packet_buffer)),
ossua70695a2016-09-22 02:06:28 -070087 red_payload_splitter_(std::move(deps.red_payload_splitter)),
henrik.lundin1d9061e2016-04-26 12:19:34 -070088 timestamp_scaler_(std::move(deps.timestamp_scaler)),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000089 vad_(new PostDecodeVad()),
henrik.lundin1d9061e2016-04-26 12:19:34 -070090 expand_factory_(std::move(deps.expand_factory)),
91 accelerate_factory_(std::move(deps.accelerate_factory)),
92 preemptive_expand_factory_(std::move(deps.preemptive_expand_factory)),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000093 last_mode_(kModeNormal),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000094 decoded_buffer_length_(kMaxFrameSize),
95 decoded_buffer_(new int16_t[decoded_buffer_length_]),
96 playout_timestamp_(0),
97 new_codec_(false),
98 timestamp_(0),
99 reset_decoder_(false),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000100 ssrc_(0),
101 first_packet_(true),
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +0000102 background_noise_mode_(config.background_noise_mode),
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000103 playout_mode_(config.playout_mode),
Henrik Lundincf808d22015-05-27 14:33:29 +0200104 enable_fast_accelerate_(config.enable_fast_accelerate),
henrik.lundin7a926812016-05-12 13:51:28 -0700105 nack_enabled_(false),
Henrik Lundin18036282017-11-02 12:09:06 +0100106 enable_muted_state_(config.enable_muted_state),
107 use_dtx_delay_fix_(
108 field_trial::IsEnabled("WebRTC-NetEqOpusDtxDelayFix")) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100109 RTC_LOG(LS_INFO) << "NetEq config: " << config.ToString();
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +0000110 int fs = config.sample_rate_hz;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000111 if (fs != 8000 && fs != 16000 && fs != 32000 && fs != 48000) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100112 RTC_LOG(LS_ERROR) << "Sample rate " << fs << " Hz not supported. "
113 << "Changing to 8000 Hz.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000114 fs = 8000;
115 }
henrik.lundin1d9061e2016-04-26 12:19:34 -0700116 delay_manager_->SetMaximumDelay(config.max_delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000117 fs_hz_ = fs;
118 fs_mult_ = fs / 8000;
henrik.lundind89814b2015-11-23 06:49:25 -0800119 last_output_sample_rate_hz_ = fs;
Peter Kastingdce40cf2015-08-24 14:52:23 -0700120 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000121 decoder_frame_length_ = 3 * output_size_samples_;
122 WebRtcSpl_Init();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000123 if (create_components) {
124 SetSampleRateAndChannels(fs, 1); // Default is 1 channel.
125 }
henrik.lundin9bc26672015-11-02 03:25:57 -0800126 RTC_DCHECK(!vad_->enabled());
127 if (config.enable_post_decode_vad) {
128 vad_->Enable();
129 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000130}
131
Henrik Lundind67a2192015-08-03 12:54:37 +0200132NetEqImpl::~NetEqImpl() = default;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000133
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200134int NetEqImpl::InsertPacket(const RTPHeader& rtp_header,
kwibergee2bac22015-11-11 10:34:00 -0800135 rtc::ArrayView<const uint8_t> payload,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000136 uint32_t receive_timestamp) {
kwibergac554ee2016-09-02 00:39:33 -0700137 rtc::MsanCheckInitialized(payload);
henrik.lundina689b442015-12-17 03:50:05 -0800138 TRACE_EVENT0("webrtc", "NetEqImpl::InsertPacket");
Tommi9090e0b2016-01-20 13:39:36 +0100139 rtc::CritScope lock(&crit_sect_);
Henrik Lundinc417d9e2017-06-14 12:29:03 +0200140 if (InsertPacketInternal(rtp_header, payload, receive_timestamp) != 0) {
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000141 return kFail;
142 }
143 return kOK;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000144}
145
henrik.lundinb8c55b12017-05-10 07:38:01 -0700146void NetEqImpl::InsertEmptyPacket(const RTPHeader& /*rtp_header*/) {
147 // TODO(henrik.lundin) Handle NACK as well. This will make use of the
148 // rtp_header parameter.
149 // https://bugs.chromium.org/p/webrtc/issues/detail?id=7611
150 rtc::CritScope lock(&crit_sect_);
151 delay_manager_->RegisterEmptyPacket();
152}
153
henrik.lundin500c04b2016-03-08 02:36:04 -0800154namespace {
155void SetAudioFrameActivityAndType(bool vad_enabled,
henrik.lundin55480f52016-03-08 02:37:57 -0800156 NetEqImpl::OutputType type,
henrik.lundin500c04b2016-03-08 02:36:04 -0800157 AudioFrame::VADActivity last_vad_activity,
158 AudioFrame* audio_frame) {
159 switch (type) {
henrik.lundin55480f52016-03-08 02:37:57 -0800160 case NetEqImpl::OutputType::kNormalSpeech: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800161 audio_frame->speech_type_ = AudioFrame::kNormalSpeech;
162 audio_frame->vad_activity_ = AudioFrame::kVadActive;
163 break;
164 }
henrik.lundin55480f52016-03-08 02:37:57 -0800165 case NetEqImpl::OutputType::kVadPassive: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800166 // This should only be reached if the VAD is enabled.
167 RTC_DCHECK(vad_enabled);
168 audio_frame->speech_type_ = AudioFrame::kNormalSpeech;
169 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
170 break;
171 }
henrik.lundin55480f52016-03-08 02:37:57 -0800172 case NetEqImpl::OutputType::kCNG: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800173 audio_frame->speech_type_ = AudioFrame::kCNG;
174 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
175 break;
176 }
henrik.lundin55480f52016-03-08 02:37:57 -0800177 case NetEqImpl::OutputType::kPLC: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800178 audio_frame->speech_type_ = AudioFrame::kPLC;
179 audio_frame->vad_activity_ = last_vad_activity;
180 break;
181 }
henrik.lundin55480f52016-03-08 02:37:57 -0800182 case NetEqImpl::OutputType::kPLCCNG: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800183 audio_frame->speech_type_ = AudioFrame::kPLCCNG;
184 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
185 break;
186 }
187 default:
188 RTC_NOTREACHED();
189 }
190 if (!vad_enabled) {
191 // Always set kVadUnknown when receive VAD is inactive.
192 audio_frame->vad_activity_ = AudioFrame::kVadUnknown;
193 }
194}
henrik.lundinbc89de32016-03-08 05:20:14 -0800195} // namespace
henrik.lundin500c04b2016-03-08 02:36:04 -0800196
henrik.lundin7a926812016-05-12 13:51:28 -0700197int NetEqImpl::GetAudio(AudioFrame* audio_frame, bool* muted) {
henrik.lundine1ca1672016-01-08 03:50:08 -0800198 TRACE_EVENT0("webrtc", "NetEqImpl::GetAudio");
Tommi9090e0b2016-01-20 13:39:36 +0100199 rtc::CritScope lock(&crit_sect_);
Henrik Lundinc417d9e2017-06-14 12:29:03 +0200200 if (GetAudioInternal(audio_frame, muted) != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000201 return kFail;
202 }
henrik.lundin5fac3f02016-08-24 11:18:49 -0700203 RTC_DCHECK_EQ(
204 audio_frame->sample_rate_hz_,
kwibergd3edd772017-03-01 18:52:48 -0800205 rtc::dchecked_cast<int>(audio_frame->samples_per_channel_ * 100));
henrik.lundina4491072017-07-06 05:23:53 -0700206 RTC_DCHECK_EQ(*muted, audio_frame->muted());
henrik.lundin500c04b2016-03-08 02:36:04 -0800207 SetAudioFrameActivityAndType(vad_->enabled(), LastOutputType(),
208 last_vad_activity_, audio_frame);
209 last_vad_activity_ = audio_frame->vad_activity_;
henrik.lundin6d8e0112016-03-04 10:34:21 -0800210 last_output_sample_rate_hz_ = audio_frame->sample_rate_hz_;
henrik.lundind89814b2015-11-23 06:49:25 -0800211 RTC_DCHECK(last_output_sample_rate_hz_ == 8000 ||
212 last_output_sample_rate_hz_ == 16000 ||
213 last_output_sample_rate_hz_ == 32000 ||
214 last_output_sample_rate_hz_ == 48000)
215 << "Unexpected sample rate " << last_output_sample_rate_hz_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000216 return kOK;
217}
218
kwiberg1c07c702017-03-27 07:15:49 -0700219void NetEqImpl::SetCodecs(const std::map<int, SdpAudioFormat>& codecs) {
220 rtc::CritScope lock(&crit_sect_);
221 const std::vector<int> changed_payload_types =
222 decoder_database_->SetCodecs(codecs);
223 for (const int pt : changed_payload_types) {
minyue-webrtcfae474c2017-07-05 11:17:40 +0200224 packet_buffer_->DiscardPacketsWithPayloadType(pt, &stats_);
kwiberg1c07c702017-03-27 07:15:49 -0700225 }
226}
227
kwibergee1879c2015-10-29 06:20:28 -0700228int NetEqImpl::RegisterPayloadType(NetEqDecoder codec,
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800229 const std::string& name,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000230 uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100231 rtc::CritScope lock(&crit_sect_);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100232 RTC_LOG(LS_VERBOSE) << "RegisterPayloadType "
233 << static_cast<int>(rtp_payload_type) << " "
234 << static_cast<int>(codec);
Henrik Lundinc417d9e2017-06-14 12:29:03 +0200235 if (decoder_database_->RegisterPayload(rtp_payload_type, codec, name) !=
236 DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000237 return kFail;
238 }
239 return kOK;
240}
241
242int NetEqImpl::RegisterExternalDecoder(AudioDecoder* decoder,
kwibergee1879c2015-10-29 06:20:28 -0700243 NetEqDecoder codec,
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800244 const std::string& codec_name,
kwiberg342f7402016-06-16 03:18:00 -0700245 uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100246 rtc::CritScope lock(&crit_sect_);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100247 RTC_LOG(LS_VERBOSE) << "RegisterExternalDecoder "
248 << static_cast<int>(rtp_payload_type) << " "
249 << static_cast<int>(codec);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000250 if (!decoder) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100251 RTC_LOG(LS_ERROR) << "Cannot register external decoder with NULL pointer";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000252 assert(false);
253 return kFail;
254 }
Henrik Lundinc417d9e2017-06-14 12:29:03 +0200255 if (decoder_database_->InsertExternal(rtp_payload_type, codec, codec_name,
256 decoder) != DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000257 return kFail;
258 }
259 return kOK;
260}
261
kwiberg5adaf732016-10-04 09:33:27 -0700262bool NetEqImpl::RegisterPayloadType(int rtp_payload_type,
263 const SdpAudioFormat& audio_format) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100264 RTC_LOG(LS_VERBOSE) << "NetEqImpl::RegisterPayloadType: payload type "
265 << rtp_payload_type << ", codec " << audio_format;
kwiberg5adaf732016-10-04 09:33:27 -0700266 rtc::CritScope lock(&crit_sect_);
Henrik Lundinc417d9e2017-06-14 12:29:03 +0200267 return decoder_database_->RegisterPayload(rtp_payload_type, audio_format) ==
268 DecoderDatabase::kOK;
kwiberg5adaf732016-10-04 09:33:27 -0700269}
270
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000271int NetEqImpl::RemovePayloadType(uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100272 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000273 int ret = decoder_database_->Remove(rtp_payload_type);
Henrik Lundinc417d9e2017-06-14 12:29:03 +0200274 if (ret == DecoderDatabase::kOK || ret == DecoderDatabase::kDecoderNotFound) {
minyue-webrtcfae474c2017-07-05 11:17:40 +0200275 packet_buffer_->DiscardPacketsWithPayloadType(rtp_payload_type, &stats_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000276 return kOK;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000277 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000278 return kFail;
279}
280
kwiberg6b19b562016-09-20 04:02:25 -0700281void NetEqImpl::RemoveAllPayloadTypes() {
282 rtc::CritScope lock(&crit_sect_);
283 decoder_database_->RemoveAll();
284}
285
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000286bool NetEqImpl::SetMinimumDelay(int delay_ms) {
Tommi9090e0b2016-01-20 13:39:36 +0100287 rtc::CritScope lock(&crit_sect_);
Gustaf Ullberg48d96c02017-09-15 13:59:52 +0200288 if (delay_ms >= 0 && delay_ms <= 10000) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000289 assert(delay_manager_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000290 return delay_manager_->SetMinimumDelay(delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000291 }
292 return false;
293}
294
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000295bool NetEqImpl::SetMaximumDelay(int delay_ms) {
Tommi9090e0b2016-01-20 13:39:36 +0100296 rtc::CritScope lock(&crit_sect_);
Gustaf Ullberg48d96c02017-09-15 13:59:52 +0200297 if (delay_ms >= 0 && delay_ms <= 10000) {
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000298 assert(delay_manager_.get());
299 return delay_manager_->SetMaximumDelay(delay_ms);
300 }
301 return false;
302}
303
304int NetEqImpl::LeastRequiredDelayMs() const {
Tommi9090e0b2016-01-20 13:39:36 +0100305 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000306 assert(delay_manager_.get());
307 return delay_manager_->least_required_delay_ms();
308}
309
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200310int NetEqImpl::SetTargetDelay() {
311 return kNotImplemented;
312}
313
henrik.lundin114c1b32017-04-26 07:47:32 -0700314int NetEqImpl::TargetDelayMs() {
315 rtc::CritScope lock(&crit_sect_);
316 RTC_DCHECK(delay_manager_.get());
317 // The value from TargetLevel() is in number of packets, represented in Q8.
318 const size_t target_delay_samples =
319 (delay_manager_->TargetLevel() * decoder_frame_length_) >> 8;
320 return static_cast<int>(target_delay_samples) /
321 rtc::CheckedDivExact(fs_hz_, 1000);
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200322}
323
henrik.lundin9c3efd02015-08-27 13:12:22 -0700324int NetEqImpl::CurrentDelayMs() const {
Tommi9090e0b2016-01-20 13:39:36 +0100325 rtc::CritScope lock(&crit_sect_);
henrik.lundin9c3efd02015-08-27 13:12:22 -0700326 if (fs_hz_ == 0)
327 return 0;
328 // Sum up the samples in the packet buffer with the future length of the sync
329 // buffer, and divide the sum by the sample rate.
330 const size_t delay_samples =
ossu61a208b2016-09-20 01:38:00 -0700331 packet_buffer_->NumSamplesInBuffer(decoder_frame_length_) +
henrik.lundin9c3efd02015-08-27 13:12:22 -0700332 sync_buffer_->FutureLength();
333 // The division below will truncate.
334 const int delay_ms =
335 static_cast<int>(delay_samples) / rtc::CheckedDivExact(fs_hz_, 1000);
336 return delay_ms;
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200337}
338
henrik.lundinb3f1c5d2016-08-22 15:39:53 -0700339int NetEqImpl::FilteredCurrentDelayMs() const {
340 rtc::CritScope lock(&crit_sect_);
341 // Calculate the filtered packet buffer level in samples. The value from
342 // |buffer_level_filter_| is in number of packets, represented in Q8.
343 const size_t packet_buffer_samples =
344 (buffer_level_filter_->filtered_current_level() *
345 decoder_frame_length_) >>
346 8;
347 // Sum up the filtered packet buffer level with the future length of the sync
348 // buffer, and divide the sum by the sample rate.
349 const size_t delay_samples =
350 packet_buffer_samples + sync_buffer_->FutureLength();
351 // The division below will truncate. The return value is in ms.
352 return static_cast<int>(delay_samples) / rtc::CheckedDivExact(fs_hz_, 1000);
353}
354
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000355// Deprecated.
356// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000357void NetEqImpl::SetPlayoutMode(NetEqPlayoutMode mode) {
Tommi9090e0b2016-01-20 13:39:36 +0100358 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000359 if (mode != playout_mode_) {
360 playout_mode_ = mode;
361 CreateDecisionLogic();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000362 }
363}
364
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000365// Deprecated.
366// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000367NetEqPlayoutMode NetEqImpl::PlayoutMode() const {
Tommi9090e0b2016-01-20 13:39:36 +0100368 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000369 return playout_mode_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000370}
371
372int NetEqImpl::NetworkStatistics(NetEqNetworkStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100373 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000374 assert(decoder_database_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700375 const size_t total_samples_in_buffers =
ossu61a208b2016-09-20 01:38:00 -0700376 packet_buffer_->NumSamplesInBuffer(decoder_frame_length_) +
Peter Kastingdce40cf2015-08-24 14:52:23 -0700377 sync_buffer_->FutureLength();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000378 assert(delay_manager_.get());
379 assert(decision_logic_.get());
Henrik Lundindccfc402017-09-25 12:30:58 +0200380 const int ms_per_packet = rtc::dchecked_cast<int>(
381 decision_logic_->packet_length_samples() / (fs_hz_ / 1000));
382 stats_.PopulateDelayManagerStats(ms_per_packet, *delay_manager_.get(), stats);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000383 stats_.GetNetworkStatistics(fs_hz_, total_samples_in_buffers,
Henrik Lundindccfc402017-09-25 12:30:58 +0200384 decoder_frame_length_, stats);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000385 return 0;
386}
387
Steve Anton2dbc69f2017-08-24 17:15:13 -0700388NetEqLifetimeStatistics NetEqImpl::GetLifetimeStatistics() const {
389 rtc::CritScope lock(&crit_sect_);
390 return stats_.GetLifetimeStatistics();
391}
392
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000393void NetEqImpl::GetRtcpStatistics(RtcpStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100394 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000395 if (stats) {
396 rtcp_.GetStatistics(false, stats);
397 }
398}
399
400void NetEqImpl::GetRtcpStatisticsNoReset(RtcpStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100401 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000402 if (stats) {
403 rtcp_.GetStatistics(true, stats);
404 }
405}
406
407void NetEqImpl::EnableVad() {
Tommi9090e0b2016-01-20 13:39:36 +0100408 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000409 assert(vad_.get());
410 vad_->Enable();
411}
412
413void NetEqImpl::DisableVad() {
Tommi9090e0b2016-01-20 13:39:36 +0100414 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000415 assert(vad_.get());
416 vad_->Disable();
417}
418
henrik.lundin15c51e32016-04-06 08:38:56 -0700419rtc::Optional<uint32_t> NetEqImpl::GetPlayoutTimestamp() const {
Tommi9090e0b2016-01-20 13:39:36 +0100420 rtc::CritScope lock(&crit_sect_);
henrik.lundin0d96ab72016-04-06 12:28:26 -0700421 if (first_packet_ || last_mode_ == kModeRfc3389Cng ||
422 last_mode_ == kModeCodecInternalCng) {
wu@webrtc.org94454b72014-06-05 20:34:08 +0000423 // We don't have a valid RTP timestamp until we have decoded our first
henrik.lundin0d96ab72016-04-06 12:28:26 -0700424 // RTP packet. Also, the RTP timestamp is not accurate while playing CNG,
425 // which is indicated by returning an empty value.
henrik.lundin9a410dd2016-04-06 01:39:22 -0700426 return rtc::Optional<uint32_t>();
wu@webrtc.org94454b72014-06-05 20:34:08 +0000427 }
henrik.lundin9a410dd2016-04-06 01:39:22 -0700428 return rtc::Optional<uint32_t>(
429 timestamp_scaler_->ToExternal(playout_timestamp_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000430}
431
henrik.lundind89814b2015-11-23 06:49:25 -0800432int NetEqImpl::last_output_sample_rate_hz() const {
Tommi9090e0b2016-01-20 13:39:36 +0100433 rtc::CritScope lock(&crit_sect_);
henrik.lundind89814b2015-11-23 06:49:25 -0800434 return last_output_sample_rate_hz_;
435}
436
kwiberg6f0f6162016-09-20 03:07:46 -0700437rtc::Optional<CodecInst> NetEqImpl::GetDecoder(int payload_type) const {
438 rtc::CritScope lock(&crit_sect_);
439 const DecoderDatabase::DecoderInfo* di =
440 decoder_database_->GetDecoderInfo(payload_type);
441 if (!di) {
442 return rtc::Optional<CodecInst>();
443 }
444
445 // Create a CodecInst with some fields set. The remaining fields are zeroed,
446 // but we tell MSan to consider them uninitialized.
447 CodecInst ci = {0};
448 rtc::MsanMarkUninitialized(rtc::MakeArrayView(&ci, 1));
449 ci.pltype = payload_type;
kwiberge9413062016-11-03 05:29:05 -0700450 std::strncpy(ci.plname, di->get_name().c_str(), sizeof(ci.plname));
kwiberg6f0f6162016-09-20 03:07:46 -0700451 ci.plname[sizeof(ci.plname) - 1] = '\0';
solenberg2779bab2016-11-17 04:45:19 -0800452 ci.plfreq = di->IsRed() ? 8000 : di->SampleRateHz();
kwiberg6f0f6162016-09-20 03:07:46 -0700453 AudioDecoder* const decoder = di->GetDecoder();
454 ci.channels = decoder ? decoder->Channels() : 1;
455 return rtc::Optional<CodecInst>(ci);
456}
457
ossuf1b08da2016-09-23 02:19:43 -0700458rtc::Optional<SdpAudioFormat> NetEqImpl::GetDecoderFormat(
459 int payload_type) const {
kwibergc4ccd4d2016-09-21 10:55:15 -0700460 rtc::CritScope lock(&crit_sect_);
461 const DecoderDatabase::DecoderInfo* const di =
462 decoder_database_->GetDecoderInfo(payload_type);
463 if (!di) {
ossuf1b08da2016-09-23 02:19:43 -0700464 return rtc::Optional<SdpAudioFormat>(); // Payload type not registered.
kwibergc4ccd4d2016-09-21 10:55:15 -0700465 }
ossuf1b08da2016-09-23 02:19:43 -0700466 return rtc::Optional<SdpAudioFormat>(di->GetFormat());
kwibergc4ccd4d2016-09-21 10:55:15 -0700467}
468
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200469int NetEqImpl::SetTargetNumberOfChannels() {
470 return kNotImplemented;
471}
472
473int NetEqImpl::SetTargetSampleRate() {
474 return kNotImplemented;
475}
476
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000477void NetEqImpl::FlushBuffers() {
Tommi9090e0b2016-01-20 13:39:36 +0100478 rtc::CritScope lock(&crit_sect_);
Mirko Bonadei675513b2017-11-09 11:09:25 +0100479 RTC_LOG(LS_VERBOSE) << "FlushBuffers";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000480 packet_buffer_->Flush();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000481 assert(sync_buffer_.get());
482 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000483 sync_buffer_->Flush();
484 sync_buffer_->set_next_index(sync_buffer_->next_index() -
485 expand_->overlap_length());
486 // Set to wait for new codec.
487 first_packet_ = true;
488}
489
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000490void NetEqImpl::PacketBufferStatistics(int* current_num_packets,
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000491 int* max_num_packets) const {
Tommi9090e0b2016-01-20 13:39:36 +0100492 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000493 packet_buffer_->BufferStat(current_num_packets, max_num_packets);
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000494}
495
henrik.lundin48ed9302015-10-29 05:36:24 -0700496void NetEqImpl::EnableNack(size_t max_nack_list_size) {
Tommi9090e0b2016-01-20 13:39:36 +0100497 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700498 if (!nack_enabled_) {
499 const int kNackThresholdPackets = 2;
henrik.lundin91951862016-06-08 06:43:41 -0700500 nack_.reset(NackTracker::Create(kNackThresholdPackets));
henrik.lundin48ed9302015-10-29 05:36:24 -0700501 nack_enabled_ = true;
502 nack_->UpdateSampleRate(fs_hz_);
503 }
504 nack_->SetMaxNackListSize(max_nack_list_size);
505}
506
507void NetEqImpl::DisableNack() {
Tommi9090e0b2016-01-20 13:39:36 +0100508 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700509 nack_.reset();
510 nack_enabled_ = false;
511}
512
513std::vector<uint16_t> NetEqImpl::GetNackList(int64_t round_trip_time_ms) const {
Tommi9090e0b2016-01-20 13:39:36 +0100514 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700515 if (!nack_enabled_) {
516 return std::vector<uint16_t>();
517 }
518 RTC_DCHECK(nack_.get());
519 return nack_->GetNackList(round_trip_time_ms);
minyue@webrtc.orgd7301772013-08-29 00:58:14 +0000520}
521
henrik.lundin114c1b32017-04-26 07:47:32 -0700522std::vector<uint32_t> NetEqImpl::LastDecodedTimestamps() const {
523 rtc::CritScope lock(&crit_sect_);
524 return last_decoded_timestamps_;
525}
526
527int NetEqImpl::SyncBufferSizeMs() const {
528 rtc::CritScope lock(&crit_sect_);
529 return rtc::dchecked_cast<int>(sync_buffer_->FutureLength() /
530 rtc::CheckedDivExact(fs_hz_, 1000));
531}
532
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000533const SyncBuffer* NetEqImpl::sync_buffer_for_test() const {
Tommi9090e0b2016-01-20 13:39:36 +0100534 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000535 return sync_buffer_.get();
536}
537
minyue5bd33972016-05-02 04:46:11 -0700538Operations NetEqImpl::last_operation_for_test() const {
539 rtc::CritScope lock(&crit_sect_);
540 return last_operation_;
541}
542
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000543// Methods below this line are private.
544
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200545int NetEqImpl::InsertPacketInternal(const RTPHeader& rtp_header,
kwibergee2bac22015-11-11 10:34:00 -0800546 rtc::ArrayView<const uint8_t> payload,
ossu17e3fa12016-09-08 04:52:55 -0700547 uint32_t receive_timestamp) {
kwibergee2bac22015-11-11 10:34:00 -0800548 if (payload.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100549 RTC_LOG_F(LS_ERROR) << "payload is empty";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000550 return kInvalidPointer;
551 }
ossu17e3fa12016-09-08 04:52:55 -0700552
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000553 PacketList packet_list;
ossua73f6c92016-10-24 08:25:28 -0700554 // Insert packet in a packet list.
555 packet_list.push_back([&rtp_header, &payload] {
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000556 // Convert to Packet.
ossua73f6c92016-10-24 08:25:28 -0700557 Packet packet;
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200558 packet.payload_type = rtp_header.payloadType;
559 packet.sequence_number = rtp_header.sequenceNumber;
560 packet.timestamp = rtp_header.timestamp;
ossua73f6c92016-10-24 08:25:28 -0700561 packet.payload.SetData(payload.data(), payload.size());
henrik.lundin84f8cd62016-04-26 07:45:16 -0700562 // Waiting time will be set upon inserting the packet in the buffer.
ossua73f6c92016-10-24 08:25:28 -0700563 RTC_DCHECK(!packet.waiting_time);
564 return packet;
565 }());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000566
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200567 bool update_sample_rate_and_channels =
568 first_packet_ || (rtp_header.ssrc != ssrc_);
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700569
570 if (update_sample_rate_and_channels) {
571 // Reset timestamp scaling.
572 timestamp_scaler_->Reset();
573 }
574
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200575 if (!decoder_database_->IsRed(rtp_header.payloadType)) {
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700576 // Scale timestamp to internal domain (only for some codecs).
577 timestamp_scaler_->ToInternal(&packet_list);
578 }
579
580 // Store these for later use, since the first packet may very well disappear
581 // before we need these values.
582 uint32_t main_timestamp = packet_list.front().timestamp;
583 uint8_t main_payload_type = packet_list.front().payload_type;
584 uint16_t main_sequence_number = packet_list.front().sequence_number;
585
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000586 // Reinitialize NetEq if it's needed (changed SSRC or first call).
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700587 if (update_sample_rate_and_channels) {
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000588 // Note: |first_packet_| will be cleared further down in this method, once
589 // the packet has been successfully inserted into the packet buffer.
590
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200591 rtcp_.Init(rtp_header.sequenceNumber);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000592
593 // Flush the packet buffer and DTMF buffer.
594 packet_buffer_->Flush();
595 dtmf_buffer_->Flush();
596
597 // Store new SSRC.
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200598 ssrc_ = rtp_header.ssrc;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000599
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000600 // Update audio buffer timestamp.
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700601 sync_buffer_->IncreaseEndTimestamp(main_timestamp - timestamp_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000602
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000603 // Update codecs.
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700604 timestamp_ = main_timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000605 }
606
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000607 // Update RTCP statistics, only for regular packets.
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200608 rtcp_.Update(rtp_header, receive_timestamp);
ossu7a377612016-10-18 04:06:13 -0700609
610 if (nack_enabled_) {
611 RTC_DCHECK(nack_);
612 if (update_sample_rate_and_channels) {
613 nack_->Reset();
614 }
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200615 nack_->UpdateLastReceivedPacket(rtp_header.sequenceNumber,
616 rtp_header.timestamp);
ossu7a377612016-10-18 04:06:13 -0700617 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000618
619 // Check for RED payload type, and separate payloads into several packets.
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200620 if (decoder_database_->IsRed(rtp_header.payloadType)) {
ossua70695a2016-09-22 02:06:28 -0700621 if (!red_payload_splitter_->SplitRed(&packet_list)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000622 return kRedundancySplitError;
623 }
624 // Only accept a few RED payloads of the same type as the main data,
625 // DTMF events and CNG.
ossua70695a2016-09-22 02:06:28 -0700626 red_payload_splitter_->CheckRedPayloads(&packet_list, *decoder_database_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000627 }
628
629 // Check payload types.
630 if (decoder_database_->CheckPayloadTypes(packet_list) ==
631 DecoderDatabase::kDecoderNotFound) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000632 return kUnknownRtpPayloadType;
633 }
634
ossu7a377612016-10-18 04:06:13 -0700635 RTC_DCHECK(!packet_list.empty());
ossu7a377612016-10-18 04:06:13 -0700636
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700637 // Update main_timestamp, if new packets appear in the list
638 // after RED splitting.
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200639 if (decoder_database_->IsRed(rtp_header.payloadType)) {
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700640 timestamp_scaler_->ToInternal(&packet_list);
641 main_timestamp = packet_list.front().timestamp;
642 main_payload_type = packet_list.front().payload_type;
643 main_sequence_number = packet_list.front().sequence_number;
644 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000645
646 // Process DTMF payloads. Cycle through the list of packets, and pick out any
647 // DTMF payloads found.
648 PacketList::iterator it = packet_list.begin();
649 while (it != packet_list.end()) {
ossua73f6c92016-10-24 08:25:28 -0700650 const Packet& current_packet = (*it);
651 RTC_DCHECK(!current_packet.payload.empty());
652 if (decoder_database_->IsDtmf(current_packet.payload_type)) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000653 DtmfEvent event;
ossua73f6c92016-10-24 08:25:28 -0700654 int ret = DtmfBuffer::ParseEvent(current_packet.timestamp,
655 current_packet.payload.data(),
656 current_packet.payload.size(), &event);
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000657 if (ret != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000658 return kDtmfParsingError;
659 }
660 if (dtmf_buffer_->InsertEvent(event) != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000661 return kDtmfInsertError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000662 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000663 it = packet_list.erase(it);
664 } else {
665 ++it;
666 }
667 }
668
ossu17e3fa12016-09-08 04:52:55 -0700669 // Update bandwidth estimate, if the packet is not comfort noise.
670 if (!packet_list.empty() &&
ossu7a377612016-10-18 04:06:13 -0700671 !decoder_database_->IsComfortNoise(main_payload_type)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000672 // The list can be empty here if we got nothing but DTMF payloads.
ossu7a377612016-10-18 04:06:13 -0700673 AudioDecoder* decoder = decoder_database_->GetDecoder(main_payload_type);
674 RTC_DCHECK(decoder); // Should always get a valid object, since we have
675 // already checked that the payload types are known.
ossua73f6c92016-10-24 08:25:28 -0700676 decoder->IncomingPacket(packet_list.front().payload.data(),
677 packet_list.front().payload.size(),
678 packet_list.front().sequence_number,
679 packet_list.front().timestamp,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000680 receive_timestamp);
681 }
682
ossu61a208b2016-09-20 01:38:00 -0700683 PacketList parsed_packet_list;
684 while (!packet_list.empty()) {
ossua73f6c92016-10-24 08:25:28 -0700685 Packet& packet = packet_list.front();
ossu61a208b2016-09-20 01:38:00 -0700686 const DecoderDatabase::DecoderInfo* info =
ossua73f6c92016-10-24 08:25:28 -0700687 decoder_database_->GetDecoderInfo(packet.payload_type);
ossu61a208b2016-09-20 01:38:00 -0700688 if (!info) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100689 RTC_LOG(LS_WARNING) << "SplitAudio unknown payload type";
ossu61a208b2016-09-20 01:38:00 -0700690 return kUnknownRtpPayloadType;
691 }
692
693 if (info->IsComfortNoise()) {
694 // Carry comfort noise packets along.
ossua73f6c92016-10-24 08:25:28 -0700695 parsed_packet_list.splice(parsed_packet_list.end(), packet_list,
696 packet_list.begin());
ossu61a208b2016-09-20 01:38:00 -0700697 } else {
ossua73f6c92016-10-24 08:25:28 -0700698 const auto sequence_number = packet.sequence_number;
699 const auto payload_type = packet.payload_type;
700 const Packet::Priority original_priority = packet.priority;
701 auto packet_from_result = [&] (AudioDecoder::ParseResult& result) {
702 Packet new_packet;
703 new_packet.sequence_number = sequence_number;
704 new_packet.payload_type = payload_type;
705 new_packet.timestamp = result.timestamp;
706 new_packet.priority.codec_level = result.priority;
707 new_packet.priority.red_level = original_priority.red_level;
708 new_packet.frame = std::move(result.frame);
709 return new_packet;
710 };
711
ossu61a208b2016-09-20 01:38:00 -0700712 std::vector<AudioDecoder::ParseResult> results =
ossua73f6c92016-10-24 08:25:28 -0700713 info->GetDecoder()->ParsePayload(std::move(packet.payload),
714 packet.timestamp);
715 if (results.empty()) {
716 packet_list.pop_front();
717 } else {
718 bool first = true;
719 for (auto& result : results) {
720 RTC_DCHECK(result.frame);
721 RTC_DCHECK_GE(result.priority, 0);
722 if (first) {
723 // Re-use the node and move it to parsed_packet_list.
724 packet_list.front() = packet_from_result(result);
725 parsed_packet_list.splice(parsed_packet_list.end(), packet_list,
726 packet_list.begin());
727 first = false;
728 } else {
729 parsed_packet_list.push_back(packet_from_result(result));
730 }
ossu61a208b2016-09-20 01:38:00 -0700731 }
ossu61a208b2016-09-20 01:38:00 -0700732 }
733 }
734 }
735
Ivo Creusenfd7c0a52017-10-20 12:35:04 +0200736 // Calculate the number of primary (non-FEC/RED) packets.
737 const int number_of_primary_packets = std::count_if(
738 parsed_packet_list.begin(), parsed_packet_list.end(),
739 [](const Packet& in) { return in.priority.codec_level == 0; });
740
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000741 // Insert packets in buffer.
ossua70695a2016-09-22 02:06:28 -0700742 const int ret = packet_buffer_->InsertPacketList(
ossu61a208b2016-09-20 01:38:00 -0700743 &parsed_packet_list, *decoder_database_, &current_rtp_payload_type_,
minyue-webrtc12d30842017-07-19 11:44:06 +0200744 &current_cng_rtp_payload_type_, &stats_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000745 if (ret == PacketBuffer::kFlushed) {
746 // Reset DSP timestamp etc. if packet buffer flushed.
747 new_codec_ = true;
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000748 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000749 } else if (ret != PacketBuffer::kOK) {
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000750 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000751 }
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000752
753 if (first_packet_) {
754 first_packet_ = false;
755 // Update the codec on the next GetAudio call.
756 new_codec_ = true;
757 }
758
henrik.lundinda8bbf62016-08-31 03:14:11 -0700759 if (current_rtp_payload_type_) {
760 RTC_DCHECK(decoder_database_->GetDecoderInfo(*current_rtp_payload_type_))
761 << "Payload type " << static_cast<int>(*current_rtp_payload_type_)
762 << " is unknown where it shouldn't be";
763 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000764
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000765 if (update_sample_rate_and_channels && !packet_buffer_->Empty()) {
766 // We do not use |current_rtp_payload_type_| to |set payload_type|, but
767 // get the next RTP header from |packet_buffer_| to obtain the payload type.
768 // The reason for it is the following corner case. If NetEq receives a
769 // CNG packet with a sample rate different than the current CNG then it
770 // flushes its buffer, assuming send codec must have been changed. However,
771 // payload type of the hypothetically new send codec is not known.
ossu7a377612016-10-18 04:06:13 -0700772 const Packet* next_packet = packet_buffer_->PeekNextPacket();
773 RTC_DCHECK(next_packet);
774 const int payload_type = next_packet->payload_type;
ossu97ba30e2016-04-25 07:55:58 -0700775 size_t channels = 1;
776 if (!decoder_database_->IsComfortNoise(payload_type)) {
777 AudioDecoder* decoder = decoder_database_->GetDecoder(payload_type);
778 assert(decoder); // Payloads are already checked to be valid.
779 channels = decoder->Channels();
780 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000781 const DecoderDatabase::DecoderInfo* decoder_info =
782 decoder_database_->GetDecoderInfo(payload_type);
783 assert(decoder_info);
kwibergc0f2dcf2016-05-31 06:28:03 -0700784 if (decoder_info->SampleRateHz() != fs_hz_ ||
ossu97ba30e2016-04-25 07:55:58 -0700785 channels != algorithm_buffer_->Channels()) {
kwibergc0f2dcf2016-05-31 06:28:03 -0700786 SetSampleRateAndChannels(decoder_info->SampleRateHz(),
787 channels);
henrik.lundin48ed9302015-10-29 05:36:24 -0700788 }
789 if (nack_enabled_) {
790 RTC_DCHECK(nack_);
791 // Update the sample rate even if the rate is not new, because of Reset().
792 nack_->UpdateSampleRate(fs_hz_);
793 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000794 }
795
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000796 // TODO(hlundin): Move this code to DelayManager class.
797 const DecoderDatabase::DecoderInfo* dec_info =
ossu7a377612016-10-18 04:06:13 -0700798 decoder_database_->GetDecoderInfo(main_payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000799 assert(dec_info); // Already checked that the payload type is known.
ossuf1b08da2016-09-23 02:19:43 -0700800 delay_manager_->LastDecodedWasCngOrDtmf(dec_info->IsComfortNoise() ||
801 dec_info->IsDtmf());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000802 if (delay_manager_->last_pack_cng_or_dtmf() == 0) {
803 // Calculate the total speech length carried in each packet.
Ivo Creusenfd7c0a52017-10-20 12:35:04 +0200804 if (number_of_primary_packets > 0) {
henrik.lundin116c84e2015-08-27 13:14:48 -0700805 const size_t packet_length_samples =
Ivo Creusenfd7c0a52017-10-20 12:35:04 +0200806 number_of_primary_packets * decoder_frame_length_;
henrik.lundin116c84e2015-08-27 13:14:48 -0700807 if (packet_length_samples != decision_logic_->packet_length_samples()) {
808 decision_logic_->set_packet_length_samples(packet_length_samples);
809 delay_manager_->SetPacketAudioLength(
kwibergd3edd772017-03-01 18:52:48 -0800810 rtc::dchecked_cast<int>((1000 * packet_length_samples) / fs_hz_));
henrik.lundin116c84e2015-08-27 13:14:48 -0700811 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000812 }
813
814 // Update statistics.
ossu7a377612016-10-18 04:06:13 -0700815 if ((int32_t)(main_timestamp - timestamp_) >= 0 && !new_codec_) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000816 // Only update statistics if incoming packet is not older than last played
817 // out packet, and if new codec flag is not set.
ossu7a377612016-10-18 04:06:13 -0700818 delay_manager_->Update(main_sequence_number, main_timestamp, fs_hz_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000819 }
820 } else if (delay_manager_->last_pack_cng_or_dtmf() == -1) {
821 // This is first "normal" packet after CNG or DTMF.
822 // Reset packet time counter and measure time until next packet,
823 // but don't update statistics.
824 delay_manager_->set_last_pack_cng_or_dtmf(0);
825 delay_manager_->ResetPacketIatCount();
826 }
827 return 0;
828}
829
henrik.lundin7a926812016-05-12 13:51:28 -0700830int NetEqImpl::GetAudioInternal(AudioFrame* audio_frame, bool* muted) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000831 PacketList packet_list;
832 DtmfEvent dtmf_event;
833 Operations operation;
834 bool play_dtmf;
henrik.lundin7a926812016-05-12 13:51:28 -0700835 *muted = false;
henrik.lundin114c1b32017-04-26 07:47:32 -0700836 last_decoded_timestamps_.clear();
henrik.lundined497212016-04-25 10:11:38 -0700837 tick_timer_->Increment();
henrik.lundin60f6ce22016-05-10 03:52:04 -0700838 stats_.IncreaseCounter(output_size_samples_, fs_hz_);
henrik.lundin7a926812016-05-12 13:51:28 -0700839
840 // Check for muted state.
841 if (enable_muted_state_ && expand_->Muted() && packet_buffer_->Empty()) {
842 RTC_DCHECK_EQ(last_mode_, kModeExpand);
henrik.lundina4491072017-07-06 05:23:53 -0700843 audio_frame->Reset();
844 RTC_DCHECK(audio_frame->muted()); // Reset() should mute the frame.
henrik.lundin7a926812016-05-12 13:51:28 -0700845 playout_timestamp_ += static_cast<uint32_t>(output_size_samples_);
846 audio_frame->sample_rate_hz_ = fs_hz_;
847 audio_frame->samples_per_channel_ = output_size_samples_;
848 audio_frame->timestamp_ =
849 first_packet_
850 ? 0
851 : timestamp_scaler_->ToExternal(playout_timestamp_) -
852 static_cast<uint32_t>(audio_frame->samples_per_channel_);
853 audio_frame->num_channels_ = sync_buffer_->Channels();
Gustaf Ullberg9a2e9062017-09-18 09:28:20 +0200854 stats_.ExpandedNoiseSamples(output_size_samples_, false);
henrik.lundin7a926812016-05-12 13:51:28 -0700855 *muted = true;
856 return 0;
857 }
858
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000859 int return_value = GetDecision(&operation, &packet_list, &dtmf_event,
860 &play_dtmf);
861 if (return_value != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000862 last_mode_ = kModeError;
863 return return_value;
864 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000865
866 AudioDecoder::SpeechType speech_type;
867 int length = 0;
Henrik Lundin18036282017-11-02 12:09:06 +0100868 const size_t start_num_packets = packet_list.size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000869 int decode_return_value = Decode(&packet_list, &operation,
870 &length, &speech_type);
871
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000872 assert(vad_.get());
873 bool sid_frame_available =
874 (operation == kRfc3389Cng && !packet_list.empty());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700875 vad_->Update(decoded_buffer_.get(), static_cast<size_t>(length), speech_type,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000876 sid_frame_available, fs_hz_);
877
Henrik Lundin18036282017-11-02 12:09:06 +0100878 // This is the criterion that we did decode some data through the speech
879 // decoder, and the operation resulted in comfort noise.
880 const bool codec_internal_sid_frame =
881 use_dtx_delay_fix_ ? (speech_type == AudioDecoder::kComfortNoise &&
882 start_num_packets > packet_list.size())
883 : (speech_type == AudioDecoder::kComfortNoise);
884
885 if (sid_frame_available || codec_internal_sid_frame) {
henrik.lundinb1fb72b2016-05-03 08:18:47 -0700886 // Start a new stopwatch since we are decoding a new CNG packet.
887 generated_noise_stopwatch_ = tick_timer_->GetNewStopwatch();
888 }
889
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000890 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000891 switch (operation) {
892 case kNormal: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000893 DoNormal(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000894 break;
895 }
896 case kMerge: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000897 DoMerge(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000898 break;
899 }
900 case kExpand: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000901 return_value = DoExpand(play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000902 break;
903 }
Henrik Lundincf808d22015-05-27 14:33:29 +0200904 case kAccelerate:
905 case kFastAccelerate: {
906 const bool fast_accelerate =
907 enable_fast_accelerate_ && (operation == kFastAccelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000908 return_value = DoAccelerate(decoded_buffer_.get(), length, speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +0200909 play_dtmf, fast_accelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000910 break;
911 }
912 case kPreemptiveExpand: {
913 return_value = DoPreemptiveExpand(decoded_buffer_.get(), length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000914 speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000915 break;
916 }
917 case kRfc3389Cng:
918 case kRfc3389CngNoPacket: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000919 return_value = DoRfc3389Cng(&packet_list, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000920 break;
921 }
922 case kCodecInternalCng: {
923 // This handles the case when there is no transmission and the decoder
924 // should produce internal comfort noise.
925 // TODO(hlundin): Write test for codec-internal CNG.
minyuel6d92bf52015-09-23 15:20:39 +0200926 DoCodecInternalCng(decoded_buffer_.get(), length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000927 break;
928 }
929 case kDtmf: {
930 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000931 return_value = DoDtmf(dtmf_event, &play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000932 break;
933 }
934 case kAlternativePlc: {
935 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000936 DoAlternativePlc(false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000937 break;
938 }
939 case kAlternativePlcIncreaseTimestamp: {
940 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000941 DoAlternativePlc(true);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000942 break;
943 }
944 case kAudioRepetitionIncreaseTimestamp: {
945 // TODO(hlundin): Write test for this.
Peter Kastingb7e50542015-06-11 12:55:50 -0700946 sync_buffer_->IncreaseEndTimestamp(
947 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000948 // Skipping break on purpose. Execution should move on into the
949 // next case.
kjellanderbdf30722017-09-08 11:00:21 -0700950 FALLTHROUGH();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000951 }
952 case kAudioRepetition: {
953 // TODO(hlundin): Write test for this.
954 // Copy last |output_size_samples_| from |sync_buffer_| to
955 // |algorithm_buffer|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000956 algorithm_buffer_->PushBackFromIndex(
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000957 *sync_buffer_, sync_buffer_->Size() - output_size_samples_);
958 expand_->Reset();
959 break;
960 }
961 case kUndefined: {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100962 RTC_LOG(LS_ERROR) << "Invalid operation kUndefined.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000963 assert(false); // This should not happen.
964 last_mode_ = kModeError;
965 return kInvalidOperation;
966 }
967 } // End of switch.
minyue5bd33972016-05-02 04:46:11 -0700968 last_operation_ = operation;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000969 if (return_value < 0) {
970 return return_value;
971 }
972
973 if (last_mode_ != kModeRfc3389Cng) {
974 comfort_noise_->Reset();
975 }
976
977 // Copy from |algorithm_buffer| to |sync_buffer_|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000978 sync_buffer_->PushBack(*algorithm_buffer_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000979
980 // Extract data from |sync_buffer_| to |output|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000981 size_t num_output_samples_per_channel = output_size_samples_;
982 size_t num_output_samples = output_size_samples_ * sync_buffer_->Channels();
henrik.lundin6d8e0112016-03-04 10:34:21 -0800983 if (num_output_samples > AudioFrame::kMaxDataSizeSamples) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100984 RTC_LOG(LS_WARNING) << "Output array is too short. "
985 << AudioFrame::kMaxDataSizeSamples << " < "
986 << output_size_samples_ << " * "
987 << sync_buffer_->Channels();
henrik.lundin6d8e0112016-03-04 10:34:21 -0800988 num_output_samples = AudioFrame::kMaxDataSizeSamples;
989 num_output_samples_per_channel =
990 AudioFrame::kMaxDataSizeSamples / sync_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000991 }
henrik.lundin6d8e0112016-03-04 10:34:21 -0800992 sync_buffer_->GetNextAudioInterleaved(num_output_samples_per_channel,
993 audio_frame);
994 audio_frame->sample_rate_hz_ = fs_hz_;
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200995 if (sync_buffer_->FutureLength() < expand_->overlap_length()) {
996 // The sync buffer should always contain |overlap_length| samples, but now
997 // too many samples have been extracted. Reinstall the |overlap_length|
998 // lookahead by moving the index.
999 const size_t missing_lookahead_samples =
1000 expand_->overlap_length() - sync_buffer_->FutureLength();
henrikg91d6ede2015-09-17 00:24:34 -07001001 RTC_DCHECK_GE(sync_buffer_->next_index(), missing_lookahead_samples);
Henrik Lundin05f71fc2015-09-01 11:51:58 +02001002 sync_buffer_->set_next_index(sync_buffer_->next_index() -
1003 missing_lookahead_samples);
1004 }
henrik.lundin6d8e0112016-03-04 10:34:21 -08001005 if (audio_frame->samples_per_channel_ != output_size_samples_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001006 RTC_LOG(LS_ERROR) << "audio_frame->samples_per_channel_ ("
1007 << audio_frame->samples_per_channel_
1008 << ") != output_size_samples_ (" << output_size_samples_
1009 << ")";
minyue@webrtc.orgdb1cefc2013-08-13 01:39:21 +00001010 // TODO(minyue): treatment of under-run, filling zeros
yujo36b1a5f2017-06-12 12:45:32 -07001011 audio_frame->Mute();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001012 return kSampleUnderrun;
1013 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001014
1015 // Should always have overlap samples left in the |sync_buffer_|.
henrikg91d6ede2015-09-17 00:24:34 -07001016 RTC_DCHECK_GE(sync_buffer_->FutureLength(), expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001017
yujo36b1a5f2017-06-12 12:45:32 -07001018 // TODO(yujo): For muted frames, this can be a copy rather than an addition.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001019 if (play_dtmf) {
yujo36b1a5f2017-06-12 12:45:32 -07001020 return_value = DtmfOverdub(dtmf_event, sync_buffer_->Channels(),
1021 audio_frame->mutable_data());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001022 }
1023
1024 // Update the background noise parameters if last operation wrote data
1025 // straight from the decoder to the |sync_buffer_|. That is, none of the
1026 // operations that modify the signal can be followed by a parameter update.
1027 if ((last_mode_ == kModeNormal) ||
1028 (last_mode_ == kModeAccelerateFail) ||
1029 (last_mode_ == kModePreemptiveExpandFail) ||
1030 (last_mode_ == kModeRfc3389Cng) ||
1031 (last_mode_ == kModeCodecInternalCng)) {
1032 background_noise_->Update(*sync_buffer_, *vad_.get());
1033 }
1034
1035 if (operation == kDtmf) {
1036 // DTMF data was written the end of |sync_buffer_|.
1037 // Update index to end of DTMF data in |sync_buffer_|.
1038 sync_buffer_->set_dtmf_index(sync_buffer_->Size());
1039 }
1040
henrik.lundin@webrtc.orged865b52014-03-06 10:28:07 +00001041 if (last_mode_ != kModeExpand) {
1042 // If last operation was not expand, calculate the |playout_timestamp_| from
1043 // the |sync_buffer_|. However, do not update the |playout_timestamp_| if it
1044 // would be moved "backwards".
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001045 uint32_t temp_timestamp = sync_buffer_->end_timestamp() -
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001046 static_cast<uint32_t>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001047 if (static_cast<int32_t>(temp_timestamp - playout_timestamp_) > 0) {
1048 playout_timestamp_ = temp_timestamp;
1049 }
1050 } else {
1051 // Use dead reckoning to estimate the |playout_timestamp_|.
Peter Kastingb7e50542015-06-11 12:55:50 -07001052 playout_timestamp_ += static_cast<uint32_t>(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001053 }
henrik.lundin15c51e32016-04-06 08:38:56 -07001054 // Set the timestamp in the audio frame to zero before the first packet has
1055 // been inserted. Otherwise, subtract the frame size in samples to get the
1056 // timestamp of the first sample in the frame (playout_timestamp_ is the
1057 // last + 1).
1058 audio_frame->timestamp_ =
1059 first_packet_
1060 ? 0
1061 : timestamp_scaler_->ToExternal(playout_timestamp_) -
1062 static_cast<uint32_t>(audio_frame->samples_per_channel_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001063
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001064 if (!(last_mode_ == kModeRfc3389Cng ||
1065 last_mode_ == kModeCodecInternalCng ||
1066 last_mode_ == kModeExpand)) {
1067 generated_noise_stopwatch_.reset();
1068 }
1069
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001070 if (decode_return_value) return decode_return_value;
1071 return return_value;
1072}
1073
1074int NetEqImpl::GetDecision(Operations* operation,
1075 PacketList* packet_list,
1076 DtmfEvent* dtmf_event,
1077 bool* play_dtmf) {
1078 // Initialize output variables.
1079 *play_dtmf = false;
1080 *operation = kUndefined;
1081
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001082 assert(sync_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001083 uint32_t end_timestamp = sync_buffer_->end_timestamp();
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001084 if (!new_codec_) {
1085 const uint32_t five_seconds_samples = 5 * fs_hz_;
minyue-webrtcfae474c2017-07-05 11:17:40 +02001086 packet_buffer_->DiscardOldPackets(end_timestamp, five_seconds_samples,
1087 &stats_);
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001088 }
ossu7a377612016-10-18 04:06:13 -07001089 const Packet* packet = packet_buffer_->PeekNextPacket();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001090
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001091 RTC_DCHECK(!generated_noise_stopwatch_ ||
1092 generated_noise_stopwatch_->ElapsedTicks() >= 1);
1093 uint64_t generated_noise_samples =
1094 generated_noise_stopwatch_
1095 ? (generated_noise_stopwatch_->ElapsedTicks() - 1) *
1096 output_size_samples_ +
1097 decision_logic_->noise_fast_forward()
1098 : 0;
1099
henrik.lundin@webrtc.orgca8cb952014-03-12 10:26:52 +00001100 if (decision_logic_->CngRfc3389On() || last_mode_ == kModeRfc3389Cng) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001101 // Because of timestamp peculiarities, we have to "manually" disallow using
1102 // a CNG packet with the same timestamp as the one that was last played.
1103 // This can happen when using redundancy and will cause the timing to shift.
ossu7a377612016-10-18 04:06:13 -07001104 while (packet && decoder_database_->IsComfortNoise(packet->payload_type) &&
1105 (end_timestamp >= packet->timestamp ||
1106 end_timestamp + generated_noise_samples > packet->timestamp)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001107 // Don't use this packet, discard it.
minyue-webrtcfae474c2017-07-05 11:17:40 +02001108 if (packet_buffer_->DiscardNextPacket(&stats_) != PacketBuffer::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001109 assert(false); // Must be ok by design.
1110 }
1111 // Check buffer again.
1112 if (!new_codec_) {
minyue-webrtcfae474c2017-07-05 11:17:40 +02001113 packet_buffer_->DiscardOldPackets(end_timestamp, 5 * fs_hz_, &stats_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001114 }
ossu7a377612016-10-18 04:06:13 -07001115 packet = packet_buffer_->PeekNextPacket();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001116 }
1117 }
1118
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001119 assert(expand_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001120 const int samples_left = static_cast<int>(sync_buffer_->FutureLength() -
1121 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001122 if (last_mode_ == kModeAccelerateSuccess ||
1123 last_mode_ == kModeAccelerateLowEnergy ||
1124 last_mode_ == kModePreemptiveExpandSuccess ||
1125 last_mode_ == kModePreemptiveExpandLowEnergy) {
1126 // Subtract (samples_left + output_size_samples_) from sampleMemory.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001127 decision_logic_->AddSampleMemory(
kwibergd3edd772017-03-01 18:52:48 -08001128 -(samples_left + rtc::dchecked_cast<int>(output_size_samples_)));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001129 }
1130
1131 // Check if it is time to play a DTMF event.
Peter Kastingb7e50542015-06-11 12:55:50 -07001132 if (dtmf_buffer_->GetEvent(
1133 static_cast<uint32_t>(
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001134 end_timestamp + generated_noise_samples),
Peter Kastingb7e50542015-06-11 12:55:50 -07001135 dtmf_event)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001136 *play_dtmf = true;
1137 }
1138
1139 // Get instruction.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001140 assert(sync_buffer_.get());
1141 assert(expand_.get());
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001142 generated_noise_samples =
1143 generated_noise_stopwatch_
1144 ? generated_noise_stopwatch_->ElapsedTicks() * output_size_samples_ +
1145 decision_logic_->noise_fast_forward()
1146 : 0;
1147 *operation = decision_logic_->GetDecision(
ossu7a377612016-10-18 04:06:13 -07001148 *sync_buffer_, *expand_, decoder_frame_length_, packet, last_mode_,
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001149 *play_dtmf, generated_noise_samples, &reset_decoder_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001150
1151 // Check if we already have enough samples in the |sync_buffer_|. If so,
1152 // change decision to normal, unless the decision was merge, accelerate, or
1153 // preemptive expand.
kwibergd3edd772017-03-01 18:52:48 -08001154 if (samples_left >= rtc::dchecked_cast<int>(output_size_samples_) &&
1155 *operation != kMerge && *operation != kAccelerate &&
1156 *operation != kFastAccelerate && *operation != kPreemptiveExpand) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001157 *operation = kNormal;
1158 return 0;
1159 }
1160
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001161 decision_logic_->ExpandDecision(*operation);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001162
1163 // Check conditions for reset.
1164 if (new_codec_ || *operation == kUndefined) {
1165 // The only valid reason to get kUndefined is that new_codec_ is set.
1166 assert(new_codec_);
ossu7a377612016-10-18 04:06:13 -07001167 if (*play_dtmf && !packet) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001168 timestamp_ = dtmf_event->timestamp;
1169 } else {
ossu7a377612016-10-18 04:06:13 -07001170 if (!packet) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001171 RTC_LOG(LS_ERROR) << "Packet missing where it shouldn't.";
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001172 return -1;
1173 }
ossu7a377612016-10-18 04:06:13 -07001174 timestamp_ = packet->timestamp;
ossu108ecec2016-07-08 08:45:18 -07001175 if (*operation == kRfc3389CngNoPacket &&
ossu7a377612016-10-18 04:06:13 -07001176 decoder_database_->IsComfortNoise(packet->payload_type)) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001177 // Change decision to CNG packet, since we do have a CNG packet, but it
1178 // was considered too early to use. Now, use it anyway.
1179 *operation = kRfc3389Cng;
1180 } else if (*operation != kRfc3389Cng) {
1181 *operation = kNormal;
1182 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001183 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001184 // Adjust |sync_buffer_| timestamp before setting |end_timestamp| to the
1185 // new value.
1186 sync_buffer_->IncreaseEndTimestamp(timestamp_ - end_timestamp);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001187 end_timestamp = timestamp_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001188 new_codec_ = false;
1189 decision_logic_->SoftReset();
1190 buffer_level_filter_->Reset();
1191 delay_manager_->Reset();
1192 stats_.ResetMcu();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001193 }
1194
Peter Kastingdce40cf2015-08-24 14:52:23 -07001195 size_t required_samples = output_size_samples_;
1196 const size_t samples_10_ms = static_cast<size_t>(80 * fs_mult_);
1197 const size_t samples_20_ms = 2 * samples_10_ms;
1198 const size_t samples_30_ms = 3 * samples_10_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001199
1200 switch (*operation) {
1201 case kExpand: {
1202 timestamp_ = end_timestamp;
1203 return 0;
1204 }
1205 case kRfc3389CngNoPacket:
1206 case kCodecInternalCng: {
1207 return 0;
1208 }
1209 case kDtmf: {
1210 // TODO(hlundin): Write test for this.
1211 // Update timestamp.
1212 timestamp_ = end_timestamp;
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001213 const uint64_t generated_noise_samples =
1214 generated_noise_stopwatch_
1215 ? generated_noise_stopwatch_->ElapsedTicks() *
1216 output_size_samples_ +
1217 decision_logic_->noise_fast_forward()
1218 : 0;
1219 if (generated_noise_samples > 0 && last_mode_ != kModeDtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001220 // Make a jump in timestamp due to the recently played comfort noise.
Peter Kastingb7e50542015-06-11 12:55:50 -07001221 uint32_t timestamp_jump =
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001222 static_cast<uint32_t>(generated_noise_samples);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001223 sync_buffer_->IncreaseEndTimestamp(timestamp_jump);
1224 timestamp_ += timestamp_jump;
1225 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001226 return 0;
1227 }
Henrik Lundincf808d22015-05-27 14:33:29 +02001228 case kAccelerate:
1229 case kFastAccelerate: {
1230 // In order to do an accelerate we need at least 30 ms of audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001231 if (samples_left >= static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001232 // Already have enough data, so we do not need to extract any more.
1233 decision_logic_->set_sample_memory(samples_left);
1234 decision_logic_->set_prev_time_scale(true);
1235 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001236 } else if (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001237 decoder_frame_length_ >= samples_30_ms) {
1238 // Avoid decoding more data as it might overflow the playout buffer.
1239 *operation = kNormal;
1240 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001241 } else if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001242 decoder_frame_length_ < samples_30_ms) {
1243 // Build up decoded data by decoding at least 20 ms of audio data. Do
1244 // not perform accelerate yet, but wait until we only need to do one
1245 // decoding.
1246 required_samples = 2 * output_size_samples_;
1247 *operation = kNormal;
1248 }
1249 // If none of the above is true, we have one of two possible situations:
1250 // (1) 20 ms <= samples_left < 30 ms and decoder_frame_length_ < 30 ms; or
1251 // (2) samples_left < 10 ms and decoder_frame_length_ >= 30 ms.
1252 // In either case, we move on with the accelerate decision, and decode one
1253 // frame now.
1254 break;
1255 }
1256 case kPreemptiveExpand: {
1257 // In order to do a preemptive expand we need at least 30 ms of decoded
1258 // audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001259 if ((samples_left >= static_cast<int>(samples_30_ms)) ||
1260 (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001261 decoder_frame_length_ >= samples_30_ms)) {
1262 // Already have enough data, so we do not need to extract any more.
1263 // Or, avoid decoding more data as it might overflow the playout buffer.
1264 // Still try preemptive expand, though.
1265 decision_logic_->set_sample_memory(samples_left);
1266 decision_logic_->set_prev_time_scale(true);
1267 return 0;
1268 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07001269 if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001270 decoder_frame_length_ < samples_30_ms) {
1271 // Build up decoded data by decoding at least 20 ms of audio data.
1272 // Still try to perform preemptive expand.
1273 required_samples = 2 * output_size_samples_;
1274 }
1275 // Move on with the preemptive expand decision.
1276 break;
1277 }
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001278 case kMerge: {
1279 required_samples =
1280 std::max(merge_->RequiredFutureSamples(), required_samples);
1281 break;
1282 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001283 default: {
1284 // Do nothing.
1285 }
1286 }
1287
1288 // Get packets from buffer.
1289 int extracted_samples = 0;
ossu7a377612016-10-18 04:06:13 -07001290 if (packet && *operation != kAlternativePlc &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001291 *operation != kAlternativePlcIncreaseTimestamp &&
1292 *operation != kAudioRepetition &&
1293 *operation != kAudioRepetitionIncreaseTimestamp) {
ossu7a377612016-10-18 04:06:13 -07001294 sync_buffer_->IncreaseEndTimestamp(packet->timestamp - end_timestamp);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001295 if (decision_logic_->CngOff()) {
1296 // Adjustment of timestamp only corresponds to an actual packet loss
1297 // if comfort noise is not played. If comfort noise was just played,
1298 // this adjustment of timestamp is only done to get back in sync with the
1299 // stream timestamp; no loss to report.
ossu7a377612016-10-18 04:06:13 -07001300 stats_.LostSamples(packet->timestamp - end_timestamp);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001301 }
1302
1303 if (*operation != kRfc3389Cng) {
1304 // We are about to decode and use a non-CNG packet.
1305 decision_logic_->SetCngOff();
1306 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001307
1308 extracted_samples = ExtractPackets(required_samples, packet_list);
1309 if (extracted_samples < 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001310 return kPacketBufferCorruption;
1311 }
1312 }
1313
Henrik Lundincf808d22015-05-27 14:33:29 +02001314 if (*operation == kAccelerate || *operation == kFastAccelerate ||
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001315 *operation == kPreemptiveExpand) {
1316 decision_logic_->set_sample_memory(samples_left + extracted_samples);
1317 decision_logic_->set_prev_time_scale(true);
1318 }
1319
Henrik Lundincf808d22015-05-27 14:33:29 +02001320 if (*operation == kAccelerate || *operation == kFastAccelerate) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001321 // Check that we have enough data (30ms) to do accelerate.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001322 if (extracted_samples + samples_left < static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001323 // TODO(hlundin): Write test for this.
1324 // Not enough, do normal operation instead.
1325 *operation = kNormal;
1326 }
1327 }
1328
1329 timestamp_ = end_timestamp;
1330 return 0;
1331}
1332
1333int NetEqImpl::Decode(PacketList* packet_list, Operations* operation,
1334 int* decoded_length,
1335 AudioDecoder::SpeechType* speech_type) {
1336 *speech_type = AudioDecoder::kSpeech;
minyuel6d92bf52015-09-23 15:20:39 +02001337
1338 // When packet_list is empty, we may be in kCodecInternalCng mode, and for
1339 // that we use current active decoder.
1340 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1341
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001342 if (!packet_list->empty()) {
ossua73f6c92016-10-24 08:25:28 -07001343 const Packet& packet = packet_list->front();
1344 uint8_t payload_type = packet.payload_type;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001345 if (!decoder_database_->IsComfortNoise(payload_type)) {
1346 decoder = decoder_database_->GetDecoder(payload_type);
1347 assert(decoder);
1348 if (!decoder) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001349 RTC_LOG(LS_WARNING)
1350 << "Unknown payload type " << static_cast<int>(payload_type);
ossua73f6c92016-10-24 08:25:28 -07001351 packet_list->clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001352 return kDecoderNotFound;
1353 }
1354 bool decoder_changed;
1355 decoder_database_->SetActiveDecoder(payload_type, &decoder_changed);
1356 if (decoder_changed) {
1357 // We have a new decoder. Re-init some values.
1358 const DecoderDatabase::DecoderInfo* decoder_info = decoder_database_
1359 ->GetDecoderInfo(payload_type);
1360 assert(decoder_info);
1361 if (!decoder_info) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001362 RTC_LOG(LS_WARNING)
1363 << "Unknown payload type " << static_cast<int>(payload_type);
ossua73f6c92016-10-24 08:25:28 -07001364 packet_list->clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001365 return kDecoderNotFound;
1366 }
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001367 // If sampling rate or number of channels has changed, we need to make
1368 // a reset.
kwibergc0f2dcf2016-05-31 06:28:03 -07001369 if (decoder_info->SampleRateHz() != fs_hz_ ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001370 decoder->Channels() != algorithm_buffer_->Channels()) {
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001371 // TODO(tlegrand): Add unittest to cover this event.
kwibergc0f2dcf2016-05-31 06:28:03 -07001372 SetSampleRateAndChannels(decoder_info->SampleRateHz(),
1373 decoder->Channels());
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001374 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001375 sync_buffer_->set_end_timestamp(timestamp_);
1376 playout_timestamp_ = timestamp_;
1377 }
1378 }
1379 }
1380
1381 if (reset_decoder_) {
1382 // TODO(hlundin): Write test for this.
Karl Wiberg43766482015-08-27 15:22:11 +02001383 if (decoder)
1384 decoder->Reset();
1385
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001386 // Reset comfort noise decoder.
ossu97ba30e2016-04-25 07:55:58 -07001387 ComfortNoiseDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02001388 if (cng_decoder)
1389 cng_decoder->Reset();
1390
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001391 reset_decoder_ = false;
1392 }
1393
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001394 *decoded_length = 0;
1395 // Update codec-internal PLC state.
1396 if ((*operation == kMerge) && decoder && decoder->HasDecodePlc()) {
1397 decoder->DecodePlc(1, &decoded_buffer_[*decoded_length]);
1398 }
1399
minyuel6d92bf52015-09-23 15:20:39 +02001400 int return_value;
1401 if (*operation == kCodecInternalCng) {
1402 RTC_DCHECK(packet_list->empty());
1403 return_value = DecodeCng(decoder, decoded_length, speech_type);
1404 } else {
1405 return_value = DecodeLoop(packet_list, *operation, decoder,
1406 decoded_length, speech_type);
1407 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001408
1409 if (*decoded_length < 0) {
1410 // Error returned from the decoder.
1411 *decoded_length = 0;
Peter Kastingb7e50542015-06-11 12:55:50 -07001412 sync_buffer_->IncreaseEndTimestamp(
1413 static_cast<uint32_t>(decoder_frame_length_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001414 int error_code = 0;
1415 if (decoder)
1416 error_code = decoder->ErrorCode();
1417 if (error_code != 0) {
1418 // Got some error code from the decoder.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001419 return_value = kDecoderErrorCode;
Mirko Bonadei675513b2017-11-09 11:09:25 +01001420 RTC_LOG(LS_WARNING) << "Decoder returned error code: " << error_code;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001421 } else {
1422 // Decoder does not implement error codes. Return generic error.
1423 return_value = kOtherDecoderError;
Mirko Bonadei675513b2017-11-09 11:09:25 +01001424 RTC_LOG(LS_WARNING) << "Decoder error (no error code)";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001425 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001426 *operation = kExpand; // Do expansion to get data instead.
1427 }
1428 if (*speech_type != AudioDecoder::kComfortNoise) {
1429 // Don't increment timestamp if codec returned CNG speech type
1430 // since in this case, the we will increment the CNGplayedTS counter.
1431 // Increase with number of samples per channel.
1432 assert(*decoded_length == 0 ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001433 (decoder && decoder->Channels() == sync_buffer_->Channels()));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001434 sync_buffer_->IncreaseEndTimestamp(
1435 *decoded_length / static_cast<int>(sync_buffer_->Channels()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001436 }
1437 return return_value;
1438}
1439
minyuel6d92bf52015-09-23 15:20:39 +02001440int NetEqImpl::DecodeCng(AudioDecoder* decoder, int* decoded_length,
1441 AudioDecoder::SpeechType* speech_type) {
1442 if (!decoder) {
1443 // This happens when active decoder is not defined.
1444 *decoded_length = -1;
1445 return 0;
1446 }
1447
kwibergd3edd772017-03-01 18:52:48 -08001448 while (*decoded_length < rtc::dchecked_cast<int>(output_size_samples_)) {
minyuel6d92bf52015-09-23 15:20:39 +02001449 const int length = decoder->Decode(
1450 nullptr, 0, fs_hz_,
1451 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1452 &decoded_buffer_[*decoded_length], speech_type);
1453 if (length > 0) {
1454 *decoded_length += length;
minyuel6d92bf52015-09-23 15:20:39 +02001455 } else {
1456 // Error.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001457 RTC_LOG(LS_WARNING) << "Failed to decode CNG";
minyuel6d92bf52015-09-23 15:20:39 +02001458 *decoded_length = -1;
1459 break;
1460 }
1461 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1462 // Guard against overflow.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001463 RTC_LOG(LS_WARNING) << "Decoded too much CNG.";
minyuel6d92bf52015-09-23 15:20:39 +02001464 return kDecodedTooMuch;
1465 }
1466 }
1467 return 0;
1468}
1469
1470int NetEqImpl::DecodeLoop(PacketList* packet_list, const Operations& operation,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001471 AudioDecoder* decoder, int* decoded_length,
1472 AudioDecoder::SpeechType* speech_type) {
henrik.lundin114c1b32017-04-26 07:47:32 -07001473 RTC_DCHECK(last_decoded_timestamps_.empty());
1474
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001475 // Do decoding.
ossua73f6c92016-10-24 08:25:28 -07001476 while (
1477 !packet_list->empty() &&
1478 !decoder_database_->IsComfortNoise(packet_list->front().payload_type)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001479 assert(decoder); // At this point, we must have a decoder object.
1480 // The number of channels in the |sync_buffer_| should be the same as the
1481 // number decoder channels.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001482 assert(sync_buffer_->Channels() == decoder->Channels());
1483 assert(decoded_buffer_length_ >= kMaxFrameSize * decoder->Channels());
minyuel6d92bf52015-09-23 15:20:39 +02001484 assert(operation == kNormal || operation == kAccelerate ||
1485 operation == kFastAccelerate || operation == kMerge ||
1486 operation == kPreemptiveExpand);
ossua73f6c92016-10-24 08:25:28 -07001487
1488 auto opt_result = packet_list->front().frame->Decode(
ossu61a208b2016-09-20 01:38:00 -07001489 rtc::ArrayView<int16_t>(&decoded_buffer_[*decoded_length],
1490 decoded_buffer_length_ - *decoded_length));
henrik.lundin114c1b32017-04-26 07:47:32 -07001491 last_decoded_timestamps_.push_back(packet_list->front().timestamp);
ossua73f6c92016-10-24 08:25:28 -07001492 packet_list->pop_front();
ossu61a208b2016-09-20 01:38:00 -07001493 if (opt_result) {
1494 const auto& result = *opt_result;
1495 *speech_type = result.speech_type;
1496 if (result.num_decoded_samples > 0) {
kwibergd3edd772017-03-01 18:52:48 -08001497 *decoded_length += rtc::dchecked_cast<int>(result.num_decoded_samples);
ossu61a208b2016-09-20 01:38:00 -07001498 // Update |decoder_frame_length_| with number of samples per channel.
1499 decoder_frame_length_ =
1500 result.num_decoded_samples / decoder->Channels();
1501 }
1502 } else {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001503 // Error.
ossu61a208b2016-09-20 01:38:00 -07001504 // TODO(ossu): What to put here?
Mirko Bonadei675513b2017-11-09 11:09:25 +01001505 RTC_LOG(LS_WARNING) << "Decode error";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001506 *decoded_length = -1;
ossua73f6c92016-10-24 08:25:28 -07001507 packet_list->clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001508 break;
1509 }
kwibergd3edd772017-03-01 18:52:48 -08001510 if (*decoded_length > rtc::dchecked_cast<int>(decoded_buffer_length_)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001511 // Guard against overflow.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001512 RTC_LOG(LS_WARNING) << "Decoded too much.";
ossua73f6c92016-10-24 08:25:28 -07001513 packet_list->clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001514 return kDecodedTooMuch;
1515 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001516 } // End of decode loop.
1517
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001518 // If the list is not empty at this point, either a decoding error terminated
1519 // the while-loop, or list must hold exactly one CNG packet.
ossua73f6c92016-10-24 08:25:28 -07001520 assert(
1521 packet_list->empty() || *decoded_length < 0 ||
1522 (packet_list->size() == 1 &&
1523 decoder_database_->IsComfortNoise(packet_list->front().payload_type)));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001524 return 0;
1525}
1526
1527void NetEqImpl::DoNormal(const int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001528 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001529 assert(normal_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001530 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001531 normal_->Process(decoded_buffer, decoded_length, last_mode_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001532 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001533 if (decoded_length != 0) {
1534 last_mode_ = kModeNormal;
1535 }
1536
1537 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1538 if ((speech_type == AudioDecoder::kComfortNoise)
1539 || ((last_mode_ == kModeCodecInternalCng)
1540 && (decoded_length == 0))) {
1541 // TODO(hlundin): Remove second part of || statement above.
1542 last_mode_ = kModeCodecInternalCng;
1543 }
1544
1545 if (!play_dtmf) {
1546 dtmf_tone_generator_->Reset();
1547 }
1548}
1549
1550void NetEqImpl::DoMerge(int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001551 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001552 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001553 assert(merge_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001554 size_t new_length = merge_->Process(decoded_buffer, decoded_length,
1555 mute_factor_array_.get(),
1556 algorithm_buffer_.get());
henrik.lundin2979f552017-05-05 05:04:16 -07001557 // Correction can be negative.
1558 int expand_length_correction =
1559 rtc::dchecked_cast<int>(new_length) -
1560 rtc::dchecked_cast<int>(decoded_length / algorithm_buffer_->Channels());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001561
1562 // Update in-call and post-call statistics.
1563 if (expand_->MuteFactor(0) == 0) {
1564 // Expand generates only noise.
henrik.lundin2979f552017-05-05 05:04:16 -07001565 stats_.ExpandedNoiseSamplesCorrection(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001566 } else {
1567 // Expansion generates more than only noise.
henrik.lundin2979f552017-05-05 05:04:16 -07001568 stats_.ExpandedVoiceSamplesCorrection(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001569 }
1570
1571 last_mode_ = kModeMerge;
1572 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1573 if (speech_type == AudioDecoder::kComfortNoise) {
1574 last_mode_ = kModeCodecInternalCng;
1575 }
1576 expand_->Reset();
1577 if (!play_dtmf) {
1578 dtmf_tone_generator_->Reset();
1579 }
1580}
1581
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001582int NetEqImpl::DoExpand(bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001583 while ((sync_buffer_->FutureLength() - expand_->overlap_length()) <
Peter Kastingdce40cf2015-08-24 14:52:23 -07001584 output_size_samples_) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001585 algorithm_buffer_->Clear();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001586 int return_value = expand_->Process(algorithm_buffer_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001587 size_t length = algorithm_buffer_->Size();
Gustaf Ullberg9a2e9062017-09-18 09:28:20 +02001588 bool is_new_concealment_event = (last_mode_ != kModeExpand);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001589
1590 // Update in-call and post-call statistics.
1591 if (expand_->MuteFactor(0) == 0) {
1592 // Expand operation generates only noise.
Gustaf Ullberg9a2e9062017-09-18 09:28:20 +02001593 stats_.ExpandedNoiseSamples(length, is_new_concealment_event);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001594 } else {
1595 // Expand operation generates more than only noise.
Gustaf Ullberg9a2e9062017-09-18 09:28:20 +02001596 stats_.ExpandedVoiceSamples(length, is_new_concealment_event);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001597 }
1598
1599 last_mode_ = kModeExpand;
1600
1601 if (return_value < 0) {
1602 return return_value;
1603 }
1604
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001605 sync_buffer_->PushBack(*algorithm_buffer_);
1606 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001607 }
1608 if (!play_dtmf) {
1609 dtmf_tone_generator_->Reset();
1610 }
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001611
1612 if (!generated_noise_stopwatch_) {
1613 // Start a new stopwatch since we may be covering for a lost CNG packet.
1614 generated_noise_stopwatch_ = tick_timer_->GetNewStopwatch();
1615 }
1616
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001617 return 0;
1618}
1619
Henrik Lundincf808d22015-05-27 14:33:29 +02001620int NetEqImpl::DoAccelerate(int16_t* decoded_buffer,
1621 size_t decoded_length,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001622 AudioDecoder::SpeechType speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +02001623 bool play_dtmf,
1624 bool fast_accelerate) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001625 const size_t required_samples =
1626 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001627 size_t borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001628 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001629 size_t decoded_length_per_channel = decoded_length / num_channels;
1630 if (decoded_length_per_channel < required_samples) {
1631 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001632 borrowed_samples_per_channel = static_cast<int>(required_samples -
1633 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001634 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1635 decoded_buffer,
1636 sizeof(int16_t) * decoded_length);
1637 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1638 decoded_buffer);
1639 decoded_length = required_samples * num_channels;
1640 }
1641
Peter Kastingdce40cf2015-08-24 14:52:23 -07001642 size_t samples_removed;
Henrik Lundincf808d22015-05-27 14:33:29 +02001643 Accelerate::ReturnCodes return_code =
1644 accelerate_->Process(decoded_buffer, decoded_length, fast_accelerate,
1645 algorithm_buffer_.get(), &samples_removed);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001646 stats_.AcceleratedSamples(samples_removed);
1647 switch (return_code) {
1648 case Accelerate::kSuccess:
1649 last_mode_ = kModeAccelerateSuccess;
1650 break;
1651 case Accelerate::kSuccessLowEnergy:
1652 last_mode_ = kModeAccelerateLowEnergy;
1653 break;
1654 case Accelerate::kNoStretch:
1655 last_mode_ = kModeAccelerateFail;
1656 break;
1657 case Accelerate::kError:
1658 // TODO(hlundin): Map to kModeError instead?
1659 last_mode_ = kModeAccelerateFail;
1660 return kAccelerateError;
1661 }
1662
1663 if (borrowed_samples_per_channel > 0) {
1664 // Copy borrowed samples back to the |sync_buffer_|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001665 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001666 if (length < borrowed_samples_per_channel) {
1667 // This destroys the beginning of the buffer, but will not cause any
1668 // problems.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001669 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001670 sync_buffer_->Size() -
1671 borrowed_samples_per_channel);
1672 sync_buffer_->PushFrontZeros(borrowed_samples_per_channel - length);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001673 algorithm_buffer_->PopFront(length);
1674 assert(algorithm_buffer_->Empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001675 } else {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001676 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001677 borrowed_samples_per_channel,
1678 sync_buffer_->Size() -
1679 borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001680 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001681 }
1682 }
1683
1684 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1685 if (speech_type == AudioDecoder::kComfortNoise) {
1686 last_mode_ = kModeCodecInternalCng;
1687 }
1688 if (!play_dtmf) {
1689 dtmf_tone_generator_->Reset();
1690 }
1691 expand_->Reset();
1692 return 0;
1693}
1694
1695int NetEqImpl::DoPreemptiveExpand(int16_t* decoded_buffer,
1696 size_t decoded_length,
1697 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001698 bool play_dtmf) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001699 const size_t required_samples =
1700 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001701 size_t num_channels = algorithm_buffer_->Channels();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001702 size_t borrowed_samples_per_channel = 0;
1703 size_t old_borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001704 size_t decoded_length_per_channel = decoded_length / num_channels;
1705 if (decoded_length_per_channel < required_samples) {
1706 // Must move data from the |sync_buffer_| in order to get 30 ms.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001707 borrowed_samples_per_channel =
1708 required_samples - decoded_length_per_channel;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001709 // Calculate how many of these were already played out.
Peter Kastingf045e4d2015-06-10 21:15:38 -07001710 old_borrowed_samples_per_channel =
Peter Kastingdce40cf2015-08-24 14:52:23 -07001711 (borrowed_samples_per_channel > sync_buffer_->FutureLength()) ?
1712 (borrowed_samples_per_channel - sync_buffer_->FutureLength()) : 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001713 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1714 decoded_buffer,
1715 sizeof(int16_t) * decoded_length);
1716 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1717 decoded_buffer);
1718 decoded_length = required_samples * num_channels;
1719 }
1720
Peter Kastingdce40cf2015-08-24 14:52:23 -07001721 size_t samples_added;
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001722 PreemptiveExpand::ReturnCodes return_code = preemptive_expand_->Process(
Peter Kastingdce40cf2015-08-24 14:52:23 -07001723 decoded_buffer, decoded_length,
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001724 old_borrowed_samples_per_channel,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001725 algorithm_buffer_.get(), &samples_added);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001726 stats_.PreemptiveExpandedSamples(samples_added);
1727 switch (return_code) {
1728 case PreemptiveExpand::kSuccess:
1729 last_mode_ = kModePreemptiveExpandSuccess;
1730 break;
1731 case PreemptiveExpand::kSuccessLowEnergy:
1732 last_mode_ = kModePreemptiveExpandLowEnergy;
1733 break;
1734 case PreemptiveExpand::kNoStretch:
1735 last_mode_ = kModePreemptiveExpandFail;
1736 break;
1737 case PreemptiveExpand::kError:
1738 // TODO(hlundin): Map to kModeError instead?
1739 last_mode_ = kModePreemptiveExpandFail;
1740 return kPreemptiveExpandError;
1741 }
1742
1743 if (borrowed_samples_per_channel > 0) {
1744 // Copy borrowed samples back to the |sync_buffer_|.
1745 sync_buffer_->ReplaceAtIndex(
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001746 *algorithm_buffer_, borrowed_samples_per_channel,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001747 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001748 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001749 }
1750
1751 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1752 if (speech_type == AudioDecoder::kComfortNoise) {
1753 last_mode_ = kModeCodecInternalCng;
1754 }
1755 if (!play_dtmf) {
1756 dtmf_tone_generator_->Reset();
1757 }
1758 expand_->Reset();
1759 return 0;
1760}
1761
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001762int NetEqImpl::DoRfc3389Cng(PacketList* packet_list, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001763 if (!packet_list->empty()) {
1764 // Must have exactly one SID frame at this point.
1765 assert(packet_list->size() == 1);
ossua73f6c92016-10-24 08:25:28 -07001766 const Packet& packet = packet_list->front();
1767 if (!decoder_database_->IsComfortNoise(packet.payload_type)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001768 RTC_LOG(LS_ERROR) << "Trying to decode non-CNG payload as CNG.";
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001769 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001770 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001771 if (comfort_noise_->UpdateParameters(packet) ==
1772 ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001773 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001774 return -comfort_noise_->internal_error_code();
1775 }
1776 }
1777 int cn_return = comfort_noise_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001778 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001779 expand_->Reset();
1780 last_mode_ = kModeRfc3389Cng;
1781 if (!play_dtmf) {
1782 dtmf_tone_generator_->Reset();
1783 }
1784 if (cn_return == ComfortNoise::kInternalError) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001785 RTC_LOG(LS_WARNING) << "Comfort noise generator returned error code: "
1786 << comfort_noise_->internal_error_code();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001787 return kComfortNoiseErrorCode;
1788 } else if (cn_return == ComfortNoise::kUnknownPayloadType) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001789 return kUnknownRtpPayloadType;
1790 }
1791 return 0;
1792}
1793
minyuel6d92bf52015-09-23 15:20:39 +02001794void NetEqImpl::DoCodecInternalCng(const int16_t* decoded_buffer,
1795 size_t decoded_length) {
1796 RTC_DCHECK(normal_.get());
1797 RTC_DCHECK(mute_factor_array_.get());
1798 normal_->Process(decoded_buffer, decoded_length, last_mode_,
1799 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001800 last_mode_ = kModeCodecInternalCng;
1801 expand_->Reset();
1802}
1803
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001804int NetEqImpl::DoDtmf(const DtmfEvent& dtmf_event, bool* play_dtmf) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001805 // This block of the code and the block further down, handling |dtmf_switch|
1806 // are commented out. Otherwise playing out-of-band DTMF would fail in VoE
1807 // test, DtmfTest.ManualSuccessfullySendsOutOfBandTelephoneEvents. This is
1808 // equivalent to |dtmf_switch| always be false.
1809 //
1810 // See http://webrtc-codereview.appspot.com/1195004/ for discussion
1811 // On this issue. This change might cause some glitches at the point of
1812 // switch from audio to DTMF. Issue 1545 is filed to track this.
1813 //
1814 // bool dtmf_switch = false;
1815 // if ((last_mode_ != kModeDtmf) && dtmf_tone_generator_->initialized()) {
1816 // // Special case; see below.
1817 // // We must catch this before calling Generate, since |initialized| is
1818 // // modified in that call.
1819 // dtmf_switch = true;
1820 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001821
1822 int dtmf_return_value = 0;
1823 if (!dtmf_tone_generator_->initialized()) {
1824 // Initialize if not already done.
1825 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1826 dtmf_event.volume);
1827 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001828
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001829 if (dtmf_return_value == 0) {
1830 // Generate DTMF signal.
1831 dtmf_return_value = dtmf_tone_generator_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001832 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001833 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001834
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001835 if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001836 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001837 return dtmf_return_value;
1838 }
1839
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001840 // if (dtmf_switch) {
1841 // // This is the special case where the previous operation was DTMF
1842 // // overdub, but the current instruction is "regular" DTMF. We must make
1843 // // sure that the DTMF does not have any discontinuities. The first DTMF
1844 // // sample that we generate now must be played out immediately, therefore
1845 // // it must be copied to the speech buffer.
1846 // // TODO(hlundin): This code seems incorrect. (Legacy.) Write test and
1847 // // verify correct operation.
1848 // assert(false);
1849 // // Must generate enough data to replace all of the |sync_buffer_|
1850 // // "future".
1851 // int required_length = sync_buffer_->FutureLength();
1852 // assert(dtmf_tone_generator_->initialized());
1853 // dtmf_return_value = dtmf_tone_generator_->Generate(required_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001854 // algorithm_buffer_);
1855 // assert((size_t) required_length == algorithm_buffer_->Size());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001856 // if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001857 // algorithm_buffer_->Zeros(output_size_samples_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001858 // return dtmf_return_value;
1859 // }
1860 //
1861 // // Overwrite the "future" part of the speech buffer with the new DTMF
1862 // // data.
1863 // // TODO(hlundin): It seems that this overwriting has gone lost.
1864 // // Not adapted for multi-channel yet.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001865 // assert(algorithm_buffer_->Channels() == 1);
1866 // if (algorithm_buffer_->Channels() != 1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001867 // RTC_LOG(LS_WARNING) << "DTMF not supported for more than one channel";
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001868 // return kStereoNotSupported;
1869 // }
1870 // // Shuffle the remaining data to the beginning of algorithm buffer.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001871 // algorithm_buffer_->PopFront(sync_buffer_->FutureLength());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001872 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001873
Peter Kastingb7e50542015-06-11 12:55:50 -07001874 sync_buffer_->IncreaseEndTimestamp(
1875 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001876 expand_->Reset();
1877 last_mode_ = kModeDtmf;
1878
1879 // Set to false because the DTMF is already in the algorithm buffer.
1880 *play_dtmf = false;
1881 return 0;
1882}
1883
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001884void NetEqImpl::DoAlternativePlc(bool increase_timestamp) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001885 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001886 size_t length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001887 if (decoder && decoder->HasDecodePlc()) {
1888 // Use the decoder's packet-loss concealment.
1889 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1890 int16_t decoded_buffer[kMaxFrameSize];
1891 length = decoder->DecodePlc(1, decoded_buffer);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001892 if (length > 0)
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001893 algorithm_buffer_->PushBackInterleaved(decoded_buffer, length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001894 } else {
1895 // Do simple zero-stuffing.
1896 length = output_size_samples_;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001897 algorithm_buffer_->Zeros(length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001898 // By not advancing the timestamp, NetEq inserts samples.
1899 stats_.AddZeros(length);
1900 }
1901 if (increase_timestamp) {
Peter Kastingb7e50542015-06-11 12:55:50 -07001902 sync_buffer_->IncreaseEndTimestamp(static_cast<uint32_t>(length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001903 }
1904 expand_->Reset();
1905}
1906
1907int NetEqImpl::DtmfOverdub(const DtmfEvent& dtmf_event, size_t num_channels,
1908 int16_t* output) const {
1909 size_t out_index = 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001910 size_t overdub_length = output_size_samples_; // Default value.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001911
1912 if (sync_buffer_->dtmf_index() > sync_buffer_->next_index()) {
1913 // Special operation for transition from "DTMF only" to "DTMF overdub".
1914 out_index = std::min(
1915 sync_buffer_->dtmf_index() - sync_buffer_->next_index(),
Peter Kastingdce40cf2015-08-24 14:52:23 -07001916 output_size_samples_);
1917 overdub_length = output_size_samples_ - out_index;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001918 }
1919
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001920 AudioMultiVector dtmf_output(num_channels);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001921 int dtmf_return_value = 0;
1922 if (!dtmf_tone_generator_->initialized()) {
1923 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1924 dtmf_event.volume);
1925 }
1926 if (dtmf_return_value == 0) {
1927 dtmf_return_value = dtmf_tone_generator_->Generate(overdub_length,
1928 &dtmf_output);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001929 assert(overdub_length == dtmf_output.Size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001930 }
1931 dtmf_output.ReadInterleaved(overdub_length, &output[out_index]);
1932 return dtmf_return_value < 0 ? dtmf_return_value : 0;
1933}
1934
Peter Kastingdce40cf2015-08-24 14:52:23 -07001935int NetEqImpl::ExtractPackets(size_t required_samples,
1936 PacketList* packet_list) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001937 bool first_packet = true;
1938 uint8_t prev_payload_type = 0;
1939 uint32_t prev_timestamp = 0;
1940 uint16_t prev_sequence_number = 0;
1941 bool next_packet_available = false;
1942
ossu7a377612016-10-18 04:06:13 -07001943 const Packet* next_packet = packet_buffer_->PeekNextPacket();
1944 RTC_DCHECK(next_packet);
1945 if (!next_packet) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001946 RTC_LOG(LS_ERROR) << "Packet buffer unexpectedly empty.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001947 return -1;
1948 }
ossu7a377612016-10-18 04:06:13 -07001949 uint32_t first_timestamp = next_packet->timestamp;
ossu61a208b2016-09-20 01:38:00 -07001950 size_t extracted_samples = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001951
1952 // Packet extraction loop.
1953 do {
ossu7a377612016-10-18 04:06:13 -07001954 timestamp_ = next_packet->timestamp;
ossua73f6c92016-10-24 08:25:28 -07001955 rtc::Optional<Packet> packet = packet_buffer_->GetNextPacket();
ossu7a377612016-10-18 04:06:13 -07001956 // |next_packet| may be invalid after the |packet_buffer_| operation.
ossua73f6c92016-10-24 08:25:28 -07001957 next_packet = nullptr;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001958 if (!packet) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001959 RTC_LOG(LS_ERROR) << "Should always be able to extract a packet here";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001960 assert(false); // Should always be able to extract a packet here.
1961 return -1;
1962 }
Gustaf Ullbergb0a02072017-10-02 12:00:34 +02001963 const uint64_t waiting_time_ms = packet->waiting_time->ElapsedMs();
1964 stats_.StoreWaitingTime(waiting_time_ms);
ossu61a208b2016-09-20 01:38:00 -07001965 RTC_DCHECK(!packet->empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001966
1967 if (first_packet) {
1968 first_packet = false;
henrik.lundin48ed9302015-10-29 05:36:24 -07001969 if (nack_enabled_) {
1970 RTC_DCHECK(nack_);
1971 // TODO(henrik.lundin): Should we update this for all decoded packets?
ossu7a377612016-10-18 04:06:13 -07001972 nack_->UpdateLastDecodedPacket(packet->sequence_number,
1973 packet->timestamp);
henrik.lundin48ed9302015-10-29 05:36:24 -07001974 }
ossu7a377612016-10-18 04:06:13 -07001975 prev_sequence_number = packet->sequence_number;
1976 prev_timestamp = packet->timestamp;
1977 prev_payload_type = packet->payload_type;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001978 }
1979
ossucafb4972017-01-02 07:00:50 -08001980 const bool has_cng_packet =
1981 decoder_database_->IsComfortNoise(packet->payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001982 // Store number of extracted samples.
ossu61a208b2016-09-20 01:38:00 -07001983 size_t packet_duration = 0;
1984 if (packet->frame) {
1985 packet_duration = packet->frame->Duration();
ossua70695a2016-09-22 02:06:28 -07001986 // TODO(ossu): Is this the correct way to track Opus FEC packets?
1987 if (packet->priority.codec_level > 0) {
kwibergd3edd772017-03-01 18:52:48 -08001988 stats_.SecondaryDecodedSamples(
1989 rtc::dchecked_cast<int>(packet_duration));
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001990 }
ossucafb4972017-01-02 07:00:50 -08001991 } else if (!has_cng_packet) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001992 RTC_LOG(LS_WARNING) << "Unknown payload type "
1993 << static_cast<int>(packet->payload_type);
ossu61a208b2016-09-20 01:38:00 -07001994 RTC_NOTREACHED();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001995 }
ossu61a208b2016-09-20 01:38:00 -07001996
1997 if (packet_duration == 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001998 // Decoder did not return a packet duration. Assume that the packet
1999 // contains the same number of samples as the previous one.
ossu61a208b2016-09-20 01:38:00 -07002000 packet_duration = decoder_frame_length_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002001 }
ossu7a377612016-10-18 04:06:13 -07002002 extracted_samples = packet->timestamp - first_timestamp + packet_duration;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002003
Gustaf Ullbergb0a02072017-10-02 12:00:34 +02002004 stats_.JitterBufferDelay(extracted_samples, waiting_time_ms);
2005
ossua73f6c92016-10-24 08:25:28 -07002006 packet_list->push_back(std::move(*packet)); // Store packet in list.
2007 packet = rtc::Optional<Packet>(); // Ensure it's never used after the move.
2008
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002009 // Check what packet is available next.
ossu7a377612016-10-18 04:06:13 -07002010 next_packet = packet_buffer_->PeekNextPacket();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002011 next_packet_available = false;
ossucafb4972017-01-02 07:00:50 -08002012 if (next_packet && prev_payload_type == next_packet->payload_type &&
2013 !has_cng_packet) {
ossu7a377612016-10-18 04:06:13 -07002014 int16_t seq_no_diff = next_packet->sequence_number - prev_sequence_number;
2015 size_t ts_diff = next_packet->timestamp - prev_timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002016 if (seq_no_diff == 1 ||
2017 (seq_no_diff == 0 && ts_diff == decoder_frame_length_)) {
2018 // The next sequence number is available, or the next part of a packet
2019 // that was split into pieces upon insertion.
2020 next_packet_available = true;
2021 }
ossu7a377612016-10-18 04:06:13 -07002022 prev_sequence_number = next_packet->sequence_number;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002023 }
ossu61a208b2016-09-20 01:38:00 -07002024 } while (extracted_samples < required_samples && next_packet_available);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002025
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00002026 if (extracted_samples > 0) {
2027 // Delete old packets only when we are going to decode something. Otherwise,
2028 // we could end up in the situation where we never decode anything, since
2029 // all incoming packets are considered too old but the buffer will also
2030 // never be flooded and flushed.
minyue-webrtcfae474c2017-07-05 11:17:40 +02002031 packet_buffer_->DiscardAllOldPackets(timestamp_, &stats_);
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00002032 }
2033
kwibergd3edd772017-03-01 18:52:48 -08002034 return rtc::dchecked_cast<int>(extracted_samples);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002035}
2036
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002037void NetEqImpl::UpdatePlcComponents(int fs_hz, size_t channels) {
2038 // Delete objects and create new ones.
2039 expand_.reset(expand_factory_->Create(background_noise_.get(),
2040 sync_buffer_.get(), &random_vector_,
Henrik Lundinbef77e22015-08-18 14:58:09 +02002041 &stats_, fs_hz, channels));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002042 merge_.reset(new Merge(fs_hz, channels, expand_.get(), sync_buffer_.get()));
2043}
2044
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002045void NetEqImpl::SetSampleRateAndChannels(int fs_hz, size_t channels) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002046 RTC_LOG(LS_VERBOSE) << "SetSampleRateAndChannels " << fs_hz << " "
2047 << channels;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002048 // TODO(hlundin): Change to an enumerator and skip assert.
2049 assert(fs_hz == 8000 || fs_hz == 16000 || fs_hz == 32000 || fs_hz == 48000);
2050 assert(channels > 0);
2051
2052 fs_hz_ = fs_hz;
2053 fs_mult_ = fs_hz / 8000;
Peter Kastingdce40cf2015-08-24 14:52:23 -07002054 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002055 decoder_frame_length_ = 3 * output_size_samples_; // Initialize to 30ms.
2056
2057 last_mode_ = kModeNormal;
2058
2059 // Create a new array of mute factors and set all to 1.
2060 mute_factor_array_.reset(new int16_t[channels]);
2061 for (size_t i = 0; i < channels; ++i) {
2062 mute_factor_array_[i] = 16384; // 1.0 in Q14.
2063 }
2064
ossu97ba30e2016-04-25 07:55:58 -07002065 ComfortNoiseDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02002066 if (cng_decoder)
2067 cng_decoder->Reset();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002068
2069 // Reinit post-decode VAD with new sample rate.
2070 assert(vad_.get()); // Cannot be NULL here.
2071 vad_->Init();
2072
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002073 // Delete algorithm buffer and create a new one.
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00002074 algorithm_buffer_.reset(new AudioMultiVector(channels));
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002075
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002076 // Delete sync buffer and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002077 sync_buffer_.reset(new SyncBuffer(channels, kSyncBufferSize * fs_mult_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002078
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00002079 // Delete BackgroundNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002080 background_noise_.reset(new BackgroundNoise(channels));
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00002081 background_noise_->set_mode(background_noise_mode_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002082
2083 // Reset random vector.
2084 random_vector_.Reset();
2085
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002086 UpdatePlcComponents(fs_hz, channels);
2087
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002088 // Move index so that we create a small set of future samples (all 0).
2089 sync_buffer_->set_next_index(sync_buffer_->next_index() -
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002090 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002091
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002092 normal_.reset(new Normal(fs_hz, decoder_database_.get(), *background_noise_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002093 expand_.get()));
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +00002094 accelerate_.reset(
2095 accelerate_factory_->Create(fs_hz, channels, *background_noise_));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002096 preemptive_expand_.reset(preemptive_expand_factory_->Create(
Peter Kastingdce40cf2015-08-24 14:52:23 -07002097 fs_hz, channels, *background_noise_, expand_->overlap_length()));
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002098
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002099 // Delete ComfortNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002100 comfort_noise_.reset(new ComfortNoise(fs_hz, decoder_database_.get(),
2101 sync_buffer_.get()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002102
2103 // Verify that |decoded_buffer_| is long enough.
2104 if (decoded_buffer_length_ < kMaxFrameSize * channels) {
2105 // Reallocate to larger size.
2106 decoded_buffer_length_ = kMaxFrameSize * channels;
2107 decoded_buffer_.reset(new int16_t[decoded_buffer_length_]);
2108 }
2109
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002110 // Create DecisionLogic if it is not created yet, then communicate new sample
2111 // rate and output size to DecisionLogic object.
2112 if (!decision_logic_.get()) {
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002113 CreateDecisionLogic();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002114 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002115 decision_logic_->SetSampleRate(fs_hz_, output_size_samples_);
2116}
2117
henrik.lundin55480f52016-03-08 02:37:57 -08002118NetEqImpl::OutputType NetEqImpl::LastOutputType() {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002119 assert(vad_.get());
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002120 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002121 if (last_mode_ == kModeCodecInternalCng || last_mode_ == kModeRfc3389Cng) {
henrik.lundin55480f52016-03-08 02:37:57 -08002122 return OutputType::kCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002123 } else if (last_mode_ == kModeExpand && expand_->MuteFactor(0) == 0) {
2124 // Expand mode has faded down to background noise only (very long expand).
henrik.lundin55480f52016-03-08 02:37:57 -08002125 return OutputType::kPLCCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002126 } else if (last_mode_ == kModeExpand) {
henrik.lundin55480f52016-03-08 02:37:57 -08002127 return OutputType::kPLC;
wu@webrtc.org24301a62013-12-13 19:17:43 +00002128 } else if (vad_->running() && !vad_->active_speech()) {
henrik.lundin55480f52016-03-08 02:37:57 -08002129 return OutputType::kVadPassive;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002130 } else {
henrik.lundin55480f52016-03-08 02:37:57 -08002131 return OutputType::kNormalSpeech;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002132 }
2133}
2134
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002135void NetEqImpl::CreateDecisionLogic() {
Henrik Lundin47b17dc2016-05-10 10:20:59 +02002136 decision_logic_.reset(DecisionLogic::Create(
2137 fs_hz_, output_size_samples_, playout_mode_, decoder_database_.get(),
2138 *packet_buffer_.get(), delay_manager_.get(), buffer_level_filter_.get(),
2139 tick_timer_.get()));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002140}
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002141} // namespace webrtc