blob: f512d75a561edf6bc9f222855f44cd8e64b31755 [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
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000011#include "webrtc/modules/audio_coding/neteq/neteq_impl.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000012
13#include <assert.h>
14#include <memory.h> // memset
15
16#include <algorithm>
ossu61a208b2016-09-20 01:38:00 -070017#include <utility>
ossu97ba30e2016-04-25 07:55:58 -070018#include <vector>
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000019
kwiberg087bd342017-02-10 08:15:44 -080020#include "webrtc/api/audio_codecs/audio_decoder.h"
henrik.lundin9c3efd02015-08-27 13:12:22 -070021#include "webrtc/base/checks.h"
Henrik Lundind67a2192015-08-03 12:54:37 +020022#include "webrtc/base/logging.h"
Tommid44c0772016-03-11 17:12:32 -080023#include "webrtc/base/safe_conversions.h"
kwibergac554ee2016-09-02 00:39:33 -070024#include "webrtc/base/sanitizer.h"
henrik.lundina689b442015-12-17 03:50:05 -080025#include "webrtc/base/trace_event.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000026#include "webrtc/common_audio/signal_processing/include/signal_processing_library.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000027#include "webrtc/modules/audio_coding/neteq/accelerate.h"
28#include "webrtc/modules/audio_coding/neteq/background_noise.h"
29#include "webrtc/modules/audio_coding/neteq/buffer_level_filter.h"
30#include "webrtc/modules/audio_coding/neteq/comfort_noise.h"
31#include "webrtc/modules/audio_coding/neteq/decision_logic.h"
32#include "webrtc/modules/audio_coding/neteq/decoder_database.h"
33#include "webrtc/modules/audio_coding/neteq/defines.h"
34#include "webrtc/modules/audio_coding/neteq/delay_manager.h"
35#include "webrtc/modules/audio_coding/neteq/delay_peak_detector.h"
36#include "webrtc/modules/audio_coding/neteq/dtmf_buffer.h"
37#include "webrtc/modules/audio_coding/neteq/dtmf_tone_generator.h"
38#include "webrtc/modules/audio_coding/neteq/expand.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000039#include "webrtc/modules/audio_coding/neteq/merge.h"
henrik.lundin91951862016-06-08 06:43:41 -070040#include "webrtc/modules/audio_coding/neteq/nack_tracker.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000041#include "webrtc/modules/audio_coding/neteq/normal.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000042#include "webrtc/modules/audio_coding/neteq/packet.h"
kwiberg087bd342017-02-10 08:15:44 -080043#include "webrtc/modules/audio_coding/neteq/packet_buffer.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000044#include "webrtc/modules/audio_coding/neteq/post_decode_vad.h"
45#include "webrtc/modules/audio_coding/neteq/preemptive_expand.h"
kwiberg087bd342017-02-10 08:15:44 -080046#include "webrtc/modules/audio_coding/neteq/red_payload_splitter.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000047#include "webrtc/modules/audio_coding/neteq/sync_buffer.h"
henrik.lundined497212016-04-25 10:11:38 -070048#include "webrtc/modules/audio_coding/neteq/tick_timer.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000049#include "webrtc/modules/audio_coding/neteq/timestamp_scaler.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010050#include "webrtc/modules/include/module_common_types.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.orgd94659d2013-01-29 12:09:21 +0000102 error_code_(0),
103 decoder_error_code_(0),
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +0000104 background_noise_mode_(config.background_noise_mode),
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000105 playout_mode_(config.playout_mode),
Henrik Lundincf808d22015-05-27 14:33:29 +0200106 enable_fast_accelerate_(config.enable_fast_accelerate),
henrik.lundin7a926812016-05-12 13:51:28 -0700107 nack_enabled_(false),
108 enable_muted_state_(config.enable_muted_state) {
Henrik Lundin905495c2015-05-25 16:58:41 +0200109 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) {
112 LOG(LS_ERROR) << "Sample rate " << fs << " Hz not supported. " <<
113 "Changing to 8000 Hz.";
114 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_);
kwibergee2bac22015-11-11 10:34:00 -0800140 int error =
ossu17e3fa12016-09-08 04:52:55 -0700141 InsertPacketInternal(rtp_header, payload, receive_timestamp);
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000142 if (error != 0) {
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000143 error_code_ = error;
144 return kFail;
145 }
146 return kOK;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000147}
148
henrik.lundinb8c55b12017-05-10 07:38:01 -0700149void NetEqImpl::InsertEmptyPacket(const RTPHeader& /*rtp_header*/) {
150 // TODO(henrik.lundin) Handle NACK as well. This will make use of the
151 // rtp_header parameter.
152 // https://bugs.chromium.org/p/webrtc/issues/detail?id=7611
153 rtc::CritScope lock(&crit_sect_);
154 delay_manager_->RegisterEmptyPacket();
155}
156
henrik.lundin500c04b2016-03-08 02:36:04 -0800157namespace {
158void SetAudioFrameActivityAndType(bool vad_enabled,
henrik.lundin55480f52016-03-08 02:37:57 -0800159 NetEqImpl::OutputType type,
henrik.lundin500c04b2016-03-08 02:36:04 -0800160 AudioFrame::VADActivity last_vad_activity,
161 AudioFrame* audio_frame) {
162 switch (type) {
henrik.lundin55480f52016-03-08 02:37:57 -0800163 case NetEqImpl::OutputType::kNormalSpeech: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800164 audio_frame->speech_type_ = AudioFrame::kNormalSpeech;
165 audio_frame->vad_activity_ = AudioFrame::kVadActive;
166 break;
167 }
henrik.lundin55480f52016-03-08 02:37:57 -0800168 case NetEqImpl::OutputType::kVadPassive: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800169 // This should only be reached if the VAD is enabled.
170 RTC_DCHECK(vad_enabled);
171 audio_frame->speech_type_ = AudioFrame::kNormalSpeech;
172 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
173 break;
174 }
henrik.lundin55480f52016-03-08 02:37:57 -0800175 case NetEqImpl::OutputType::kCNG: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800176 audio_frame->speech_type_ = AudioFrame::kCNG;
177 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
178 break;
179 }
henrik.lundin55480f52016-03-08 02:37:57 -0800180 case NetEqImpl::OutputType::kPLC: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800181 audio_frame->speech_type_ = AudioFrame::kPLC;
182 audio_frame->vad_activity_ = last_vad_activity;
183 break;
184 }
henrik.lundin55480f52016-03-08 02:37:57 -0800185 case NetEqImpl::OutputType::kPLCCNG: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800186 audio_frame->speech_type_ = AudioFrame::kPLCCNG;
187 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
188 break;
189 }
190 default:
191 RTC_NOTREACHED();
192 }
193 if (!vad_enabled) {
194 // Always set kVadUnknown when receive VAD is inactive.
195 audio_frame->vad_activity_ = AudioFrame::kVadUnknown;
196 }
197}
henrik.lundinbc89de32016-03-08 05:20:14 -0800198} // namespace
henrik.lundin500c04b2016-03-08 02:36:04 -0800199
henrik.lundin7a926812016-05-12 13:51:28 -0700200int NetEqImpl::GetAudio(AudioFrame* audio_frame, bool* muted) {
henrik.lundine1ca1672016-01-08 03:50:08 -0800201 TRACE_EVENT0("webrtc", "NetEqImpl::GetAudio");
Tommi9090e0b2016-01-20 13:39:36 +0100202 rtc::CritScope lock(&crit_sect_);
henrik.lundin7a926812016-05-12 13:51:28 -0700203 int error = GetAudioInternal(audio_frame, muted);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000204 if (error != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000205 error_code_ = error;
206 return kFail;
207 }
henrik.lundin5fac3f02016-08-24 11:18:49 -0700208 RTC_DCHECK_EQ(
209 audio_frame->sample_rate_hz_,
kwibergd3edd772017-03-01 18:52:48 -0800210 rtc::dchecked_cast<int>(audio_frame->samples_per_channel_ * 100));
henrik.lundin500c04b2016-03-08 02:36:04 -0800211 SetAudioFrameActivityAndType(vad_->enabled(), LastOutputType(),
212 last_vad_activity_, audio_frame);
213 last_vad_activity_ = audio_frame->vad_activity_;
henrik.lundin6d8e0112016-03-04 10:34:21 -0800214 last_output_sample_rate_hz_ = audio_frame->sample_rate_hz_;
henrik.lundind89814b2015-11-23 06:49:25 -0800215 RTC_DCHECK(last_output_sample_rate_hz_ == 8000 ||
216 last_output_sample_rate_hz_ == 16000 ||
217 last_output_sample_rate_hz_ == 32000 ||
218 last_output_sample_rate_hz_ == 48000)
219 << "Unexpected sample rate " << last_output_sample_rate_hz_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000220 return kOK;
221}
222
kwiberg1c07c702017-03-27 07:15:49 -0700223void NetEqImpl::SetCodecs(const std::map<int, SdpAudioFormat>& codecs) {
224 rtc::CritScope lock(&crit_sect_);
225 const std::vector<int> changed_payload_types =
226 decoder_database_->SetCodecs(codecs);
227 for (const int pt : changed_payload_types) {
228 packet_buffer_->DiscardPacketsWithPayloadType(pt);
229 }
230}
231
kwibergee1879c2015-10-29 06:20:28 -0700232int NetEqImpl::RegisterPayloadType(NetEqDecoder codec,
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800233 const std::string& name,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000234 uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100235 rtc::CritScope lock(&crit_sect_);
Henrik Lundind67a2192015-08-03 12:54:37 +0200236 LOG(LS_VERBOSE) << "RegisterPayloadType "
kwibergee1879c2015-10-29 06:20:28 -0700237 << static_cast<int>(rtp_payload_type) << " "
238 << static_cast<int>(codec);
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800239 int ret = decoder_database_->RegisterPayload(rtp_payload_type, codec, name);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000240 if (ret != DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000241 switch (ret) {
242 case DecoderDatabase::kInvalidRtpPayloadType:
243 error_code_ = kInvalidRtpPayloadType;
244 break;
245 case DecoderDatabase::kCodecNotSupported:
246 error_code_ = kCodecNotSupported;
247 break;
248 case DecoderDatabase::kDecoderExists:
249 error_code_ = kDecoderExists;
250 break;
251 default:
252 error_code_ = kOtherError;
253 }
254 return kFail;
255 }
256 return kOK;
257}
258
259int NetEqImpl::RegisterExternalDecoder(AudioDecoder* decoder,
kwibergee1879c2015-10-29 06:20:28 -0700260 NetEqDecoder codec,
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800261 const std::string& codec_name,
kwiberg342f7402016-06-16 03:18:00 -0700262 uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100263 rtc::CritScope lock(&crit_sect_);
Henrik Lundind67a2192015-08-03 12:54:37 +0200264 LOG(LS_VERBOSE) << "RegisterExternalDecoder "
kwibergee1879c2015-10-29 06:20:28 -0700265 << static_cast<int>(rtp_payload_type) << " "
266 << static_cast<int>(codec);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000267 if (!decoder) {
268 LOG(LS_ERROR) << "Cannot register external decoder with NULL pointer";
269 assert(false);
270 return kFail;
271 }
kwiberg342f7402016-06-16 03:18:00 -0700272 int ret = decoder_database_->InsertExternal(rtp_payload_type, codec,
273 codec_name, decoder);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000274 if (ret != DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000275 switch (ret) {
276 case DecoderDatabase::kInvalidRtpPayloadType:
277 error_code_ = kInvalidRtpPayloadType;
278 break;
279 case DecoderDatabase::kCodecNotSupported:
280 error_code_ = kCodecNotSupported;
281 break;
282 case DecoderDatabase::kDecoderExists:
283 error_code_ = kDecoderExists;
284 break;
285 case DecoderDatabase::kInvalidSampleRate:
286 error_code_ = kInvalidSampleRate;
287 break;
288 case DecoderDatabase::kInvalidPointer:
289 error_code_ = kInvalidPointer;
290 break;
291 default:
292 error_code_ = kOtherError;
293 }
294 return kFail;
295 }
296 return kOK;
297}
298
kwiberg5adaf732016-10-04 09:33:27 -0700299bool NetEqImpl::RegisterPayloadType(int rtp_payload_type,
300 const SdpAudioFormat& audio_format) {
301 LOG(LS_VERBOSE) << "NetEqImpl::RegisterPayloadType: payload type "
302 << rtp_payload_type << ", codec " << audio_format;
303 rtc::CritScope lock(&crit_sect_);
304 switch (decoder_database_->RegisterPayload(rtp_payload_type, audio_format)) {
305 case DecoderDatabase::kOK:
306 return true;
307 case DecoderDatabase::kInvalidRtpPayloadType:
308 error_code_ = kInvalidRtpPayloadType;
309 return false;
310 case DecoderDatabase::kCodecNotSupported:
311 error_code_ = kCodecNotSupported;
312 return false;
313 case DecoderDatabase::kDecoderExists:
314 error_code_ = kDecoderExists;
315 return false;
316 case DecoderDatabase::kInvalidSampleRate:
317 error_code_ = kInvalidSampleRate;
318 return false;
319 case DecoderDatabase::kInvalidPointer:
320 error_code_ = kInvalidPointer;
321 return false;
322 default:
323 error_code_ = kOtherError;
324 return false;
325 }
326}
327
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000328int NetEqImpl::RemovePayloadType(uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100329 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000330 int ret = decoder_database_->Remove(rtp_payload_type);
331 if (ret == DecoderDatabase::kOK) {
ossu61a208b2016-09-20 01:38:00 -0700332 packet_buffer_->DiscardPacketsWithPayloadType(rtp_payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000333 return kOK;
334 } else if (ret == DecoderDatabase::kDecoderNotFound) {
335 error_code_ = kDecoderNotFound;
336 } else {
337 error_code_ = kOtherError;
338 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000339 return kFail;
340}
341
kwiberg6b19b562016-09-20 04:02:25 -0700342void NetEqImpl::RemoveAllPayloadTypes() {
343 rtc::CritScope lock(&crit_sect_);
344 decoder_database_->RemoveAll();
345}
346
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000347bool NetEqImpl::SetMinimumDelay(int delay_ms) {
Tommi9090e0b2016-01-20 13:39:36 +0100348 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000349 if (delay_ms >= 0 && delay_ms < 10000) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000350 assert(delay_manager_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000351 return delay_manager_->SetMinimumDelay(delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000352 }
353 return false;
354}
355
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000356bool NetEqImpl::SetMaximumDelay(int delay_ms) {
Tommi9090e0b2016-01-20 13:39:36 +0100357 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000358 if (delay_ms >= 0 && delay_ms < 10000) {
359 assert(delay_manager_.get());
360 return delay_manager_->SetMaximumDelay(delay_ms);
361 }
362 return false;
363}
364
365int NetEqImpl::LeastRequiredDelayMs() const {
Tommi9090e0b2016-01-20 13:39:36 +0100366 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000367 assert(delay_manager_.get());
368 return delay_manager_->least_required_delay_ms();
369}
370
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200371int NetEqImpl::SetTargetDelay() {
372 return kNotImplemented;
373}
374
henrik.lundin114c1b32017-04-26 07:47:32 -0700375int NetEqImpl::TargetDelayMs() {
376 rtc::CritScope lock(&crit_sect_);
377 RTC_DCHECK(delay_manager_.get());
378 // The value from TargetLevel() is in number of packets, represented in Q8.
379 const size_t target_delay_samples =
380 (delay_manager_->TargetLevel() * decoder_frame_length_) >> 8;
381 return static_cast<int>(target_delay_samples) /
382 rtc::CheckedDivExact(fs_hz_, 1000);
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200383}
384
henrik.lundin9c3efd02015-08-27 13:12:22 -0700385int NetEqImpl::CurrentDelayMs() const {
Tommi9090e0b2016-01-20 13:39:36 +0100386 rtc::CritScope lock(&crit_sect_);
henrik.lundin9c3efd02015-08-27 13:12:22 -0700387 if (fs_hz_ == 0)
388 return 0;
389 // Sum up the samples in the packet buffer with the future length of the sync
390 // buffer, and divide the sum by the sample rate.
391 const size_t delay_samples =
ossu61a208b2016-09-20 01:38:00 -0700392 packet_buffer_->NumSamplesInBuffer(decoder_frame_length_) +
henrik.lundin9c3efd02015-08-27 13:12:22 -0700393 sync_buffer_->FutureLength();
394 // The division below will truncate.
395 const int delay_ms =
396 static_cast<int>(delay_samples) / rtc::CheckedDivExact(fs_hz_, 1000);
397 return delay_ms;
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200398}
399
henrik.lundinb3f1c5d2016-08-22 15:39:53 -0700400int NetEqImpl::FilteredCurrentDelayMs() const {
401 rtc::CritScope lock(&crit_sect_);
402 // Calculate the filtered packet buffer level in samples. The value from
403 // |buffer_level_filter_| is in number of packets, represented in Q8.
404 const size_t packet_buffer_samples =
405 (buffer_level_filter_->filtered_current_level() *
406 decoder_frame_length_) >>
407 8;
408 // Sum up the filtered packet buffer level with the future length of the sync
409 // buffer, and divide the sum by the sample rate.
410 const size_t delay_samples =
411 packet_buffer_samples + sync_buffer_->FutureLength();
412 // The division below will truncate. The return value is in ms.
413 return static_cast<int>(delay_samples) / rtc::CheckedDivExact(fs_hz_, 1000);
414}
415
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000416// Deprecated.
417// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000418void NetEqImpl::SetPlayoutMode(NetEqPlayoutMode mode) {
Tommi9090e0b2016-01-20 13:39:36 +0100419 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000420 if (mode != playout_mode_) {
421 playout_mode_ = mode;
422 CreateDecisionLogic();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000423 }
424}
425
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000426// Deprecated.
427// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000428NetEqPlayoutMode NetEqImpl::PlayoutMode() const {
Tommi9090e0b2016-01-20 13:39:36 +0100429 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000430 return playout_mode_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000431}
432
433int NetEqImpl::NetworkStatistics(NetEqNetworkStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100434 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000435 assert(decoder_database_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700436 const size_t total_samples_in_buffers =
ossu61a208b2016-09-20 01:38:00 -0700437 packet_buffer_->NumSamplesInBuffer(decoder_frame_length_) +
Peter Kastingdce40cf2015-08-24 14:52:23 -0700438 sync_buffer_->FutureLength();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000439 assert(delay_manager_.get());
440 assert(decision_logic_.get());
441 stats_.GetNetworkStatistics(fs_hz_, total_samples_in_buffers,
442 decoder_frame_length_, *delay_manager_.get(),
443 *decision_logic_.get(), stats);
444 return 0;
445}
446
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000447void NetEqImpl::GetRtcpStatistics(RtcpStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100448 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000449 if (stats) {
450 rtcp_.GetStatistics(false, stats);
451 }
452}
453
454void NetEqImpl::GetRtcpStatisticsNoReset(RtcpStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100455 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000456 if (stats) {
457 rtcp_.GetStatistics(true, stats);
458 }
459}
460
461void NetEqImpl::EnableVad() {
Tommi9090e0b2016-01-20 13:39:36 +0100462 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000463 assert(vad_.get());
464 vad_->Enable();
465}
466
467void NetEqImpl::DisableVad() {
Tommi9090e0b2016-01-20 13:39:36 +0100468 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000469 assert(vad_.get());
470 vad_->Disable();
471}
472
henrik.lundin15c51e32016-04-06 08:38:56 -0700473rtc::Optional<uint32_t> NetEqImpl::GetPlayoutTimestamp() const {
Tommi9090e0b2016-01-20 13:39:36 +0100474 rtc::CritScope lock(&crit_sect_);
henrik.lundin0d96ab72016-04-06 12:28:26 -0700475 if (first_packet_ || last_mode_ == kModeRfc3389Cng ||
476 last_mode_ == kModeCodecInternalCng) {
wu@webrtc.org94454b72014-06-05 20:34:08 +0000477 // We don't have a valid RTP timestamp until we have decoded our first
henrik.lundin0d96ab72016-04-06 12:28:26 -0700478 // RTP packet. Also, the RTP timestamp is not accurate while playing CNG,
479 // which is indicated by returning an empty value.
henrik.lundin9a410dd2016-04-06 01:39:22 -0700480 return rtc::Optional<uint32_t>();
wu@webrtc.org94454b72014-06-05 20:34:08 +0000481 }
henrik.lundin9a410dd2016-04-06 01:39:22 -0700482 return rtc::Optional<uint32_t>(
483 timestamp_scaler_->ToExternal(playout_timestamp_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000484}
485
henrik.lundind89814b2015-11-23 06:49:25 -0800486int NetEqImpl::last_output_sample_rate_hz() const {
Tommi9090e0b2016-01-20 13:39:36 +0100487 rtc::CritScope lock(&crit_sect_);
henrik.lundind89814b2015-11-23 06:49:25 -0800488 return last_output_sample_rate_hz_;
489}
490
kwiberg6f0f6162016-09-20 03:07:46 -0700491rtc::Optional<CodecInst> NetEqImpl::GetDecoder(int payload_type) const {
492 rtc::CritScope lock(&crit_sect_);
493 const DecoderDatabase::DecoderInfo* di =
494 decoder_database_->GetDecoderInfo(payload_type);
495 if (!di) {
496 return rtc::Optional<CodecInst>();
497 }
498
499 // Create a CodecInst with some fields set. The remaining fields are zeroed,
500 // but we tell MSan to consider them uninitialized.
501 CodecInst ci = {0};
502 rtc::MsanMarkUninitialized(rtc::MakeArrayView(&ci, 1));
503 ci.pltype = payload_type;
kwiberge9413062016-11-03 05:29:05 -0700504 std::strncpy(ci.plname, di->get_name().c_str(), sizeof(ci.plname));
kwiberg6f0f6162016-09-20 03:07:46 -0700505 ci.plname[sizeof(ci.plname) - 1] = '\0';
solenberg2779bab2016-11-17 04:45:19 -0800506 ci.plfreq = di->IsRed() ? 8000 : di->SampleRateHz();
kwiberg6f0f6162016-09-20 03:07:46 -0700507 AudioDecoder* const decoder = di->GetDecoder();
508 ci.channels = decoder ? decoder->Channels() : 1;
509 return rtc::Optional<CodecInst>(ci);
510}
511
ossuf1b08da2016-09-23 02:19:43 -0700512rtc::Optional<SdpAudioFormat> NetEqImpl::GetDecoderFormat(
513 int payload_type) const {
kwibergc4ccd4d2016-09-21 10:55:15 -0700514 rtc::CritScope lock(&crit_sect_);
515 const DecoderDatabase::DecoderInfo* const di =
516 decoder_database_->GetDecoderInfo(payload_type);
517 if (!di) {
ossuf1b08da2016-09-23 02:19:43 -0700518 return rtc::Optional<SdpAudioFormat>(); // Payload type not registered.
kwibergc4ccd4d2016-09-21 10:55:15 -0700519 }
ossuf1b08da2016-09-23 02:19:43 -0700520 return rtc::Optional<SdpAudioFormat>(di->GetFormat());
kwibergc4ccd4d2016-09-21 10:55:15 -0700521}
522
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200523int NetEqImpl::SetTargetNumberOfChannels() {
524 return kNotImplemented;
525}
526
527int NetEqImpl::SetTargetSampleRate() {
528 return kNotImplemented;
529}
530
henrik.lundin@webrtc.orgb0f4b3d2014-11-04 08:53:10 +0000531int NetEqImpl::LastError() const {
Tommi9090e0b2016-01-20 13:39:36 +0100532 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000533 return error_code_;
534}
535
536int NetEqImpl::LastDecoderError() {
Tommi9090e0b2016-01-20 13:39:36 +0100537 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000538 return decoder_error_code_;
539}
540
541void NetEqImpl::FlushBuffers() {
Tommi9090e0b2016-01-20 13:39:36 +0100542 rtc::CritScope lock(&crit_sect_);
Henrik Lundind67a2192015-08-03 12:54:37 +0200543 LOG(LS_VERBOSE) << "FlushBuffers";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000544 packet_buffer_->Flush();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000545 assert(sync_buffer_.get());
546 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000547 sync_buffer_->Flush();
548 sync_buffer_->set_next_index(sync_buffer_->next_index() -
549 expand_->overlap_length());
550 // Set to wait for new codec.
551 first_packet_ = true;
552}
553
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000554void NetEqImpl::PacketBufferStatistics(int* current_num_packets,
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000555 int* max_num_packets) const {
Tommi9090e0b2016-01-20 13:39:36 +0100556 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000557 packet_buffer_->BufferStat(current_num_packets, max_num_packets);
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000558}
559
henrik.lundin48ed9302015-10-29 05:36:24 -0700560void NetEqImpl::EnableNack(size_t max_nack_list_size) {
Tommi9090e0b2016-01-20 13:39:36 +0100561 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700562 if (!nack_enabled_) {
563 const int kNackThresholdPackets = 2;
henrik.lundin91951862016-06-08 06:43:41 -0700564 nack_.reset(NackTracker::Create(kNackThresholdPackets));
henrik.lundin48ed9302015-10-29 05:36:24 -0700565 nack_enabled_ = true;
566 nack_->UpdateSampleRate(fs_hz_);
567 }
568 nack_->SetMaxNackListSize(max_nack_list_size);
569}
570
571void NetEqImpl::DisableNack() {
Tommi9090e0b2016-01-20 13:39:36 +0100572 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700573 nack_.reset();
574 nack_enabled_ = false;
575}
576
577std::vector<uint16_t> NetEqImpl::GetNackList(int64_t round_trip_time_ms) const {
Tommi9090e0b2016-01-20 13:39:36 +0100578 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700579 if (!nack_enabled_) {
580 return std::vector<uint16_t>();
581 }
582 RTC_DCHECK(nack_.get());
583 return nack_->GetNackList(round_trip_time_ms);
minyue@webrtc.orgd7301772013-08-29 00:58:14 +0000584}
585
henrik.lundin114c1b32017-04-26 07:47:32 -0700586std::vector<uint32_t> NetEqImpl::LastDecodedTimestamps() const {
587 rtc::CritScope lock(&crit_sect_);
588 return last_decoded_timestamps_;
589}
590
591int NetEqImpl::SyncBufferSizeMs() const {
592 rtc::CritScope lock(&crit_sect_);
593 return rtc::dchecked_cast<int>(sync_buffer_->FutureLength() /
594 rtc::CheckedDivExact(fs_hz_, 1000));
595}
596
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000597const SyncBuffer* NetEqImpl::sync_buffer_for_test() const {
Tommi9090e0b2016-01-20 13:39:36 +0100598 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000599 return sync_buffer_.get();
600}
601
minyue5bd33972016-05-02 04:46:11 -0700602Operations NetEqImpl::last_operation_for_test() const {
603 rtc::CritScope lock(&crit_sect_);
604 return last_operation_;
605}
606
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000607// Methods below this line are private.
608
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200609int NetEqImpl::InsertPacketInternal(const RTPHeader& rtp_header,
kwibergee2bac22015-11-11 10:34:00 -0800610 rtc::ArrayView<const uint8_t> payload,
ossu17e3fa12016-09-08 04:52:55 -0700611 uint32_t receive_timestamp) {
kwibergee2bac22015-11-11 10:34:00 -0800612 if (payload.empty()) {
613 LOG_F(LS_ERROR) << "payload is empty";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000614 return kInvalidPointer;
615 }
ossu17e3fa12016-09-08 04:52:55 -0700616
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000617 PacketList packet_list;
ossua73f6c92016-10-24 08:25:28 -0700618 // Insert packet in a packet list.
619 packet_list.push_back([&rtp_header, &payload] {
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000620 // Convert to Packet.
ossua73f6c92016-10-24 08:25:28 -0700621 Packet packet;
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200622 packet.payload_type = rtp_header.payloadType;
623 packet.sequence_number = rtp_header.sequenceNumber;
624 packet.timestamp = rtp_header.timestamp;
ossua73f6c92016-10-24 08:25:28 -0700625 packet.payload.SetData(payload.data(), payload.size());
henrik.lundin84f8cd62016-04-26 07:45:16 -0700626 // Waiting time will be set upon inserting the packet in the buffer.
ossua73f6c92016-10-24 08:25:28 -0700627 RTC_DCHECK(!packet.waiting_time);
628 return packet;
629 }());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000630
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200631 bool update_sample_rate_and_channels =
632 first_packet_ || (rtp_header.ssrc != ssrc_);
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700633
634 if (update_sample_rate_and_channels) {
635 // Reset timestamp scaling.
636 timestamp_scaler_->Reset();
637 }
638
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200639 if (!decoder_database_->IsRed(rtp_header.payloadType)) {
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700640 // Scale timestamp to internal domain (only for some codecs).
641 timestamp_scaler_->ToInternal(&packet_list);
642 }
643
644 // Store these for later use, since the first packet may very well disappear
645 // before we need these values.
646 uint32_t main_timestamp = packet_list.front().timestamp;
647 uint8_t main_payload_type = packet_list.front().payload_type;
648 uint16_t main_sequence_number = packet_list.front().sequence_number;
649
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000650 // Reinitialize NetEq if it's needed (changed SSRC or first call).
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700651 if (update_sample_rate_and_channels) {
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000652 // Note: |first_packet_| will be cleared further down in this method, once
653 // the packet has been successfully inserted into the packet buffer.
654
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200655 rtcp_.Init(rtp_header.sequenceNumber);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000656
657 // Flush the packet buffer and DTMF buffer.
658 packet_buffer_->Flush();
659 dtmf_buffer_->Flush();
660
661 // Store new SSRC.
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200662 ssrc_ = rtp_header.ssrc;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000663
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000664 // Update audio buffer timestamp.
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700665 sync_buffer_->IncreaseEndTimestamp(main_timestamp - timestamp_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000666
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000667 // Update codecs.
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700668 timestamp_ = main_timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000669 }
670
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000671 // Update RTCP statistics, only for regular packets.
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200672 rtcp_.Update(rtp_header, receive_timestamp);
ossu7a377612016-10-18 04:06:13 -0700673
674 if (nack_enabled_) {
675 RTC_DCHECK(nack_);
676 if (update_sample_rate_and_channels) {
677 nack_->Reset();
678 }
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200679 nack_->UpdateLastReceivedPacket(rtp_header.sequenceNumber,
680 rtp_header.timestamp);
ossu7a377612016-10-18 04:06:13 -0700681 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000682
683 // Check for RED payload type, and separate payloads into several packets.
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200684 if (decoder_database_->IsRed(rtp_header.payloadType)) {
ossua70695a2016-09-22 02:06:28 -0700685 if (!red_payload_splitter_->SplitRed(&packet_list)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000686 return kRedundancySplitError;
687 }
688 // Only accept a few RED payloads of the same type as the main data,
689 // DTMF events and CNG.
ossua70695a2016-09-22 02:06:28 -0700690 red_payload_splitter_->CheckRedPayloads(&packet_list, *decoder_database_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000691 }
692
693 // Check payload types.
694 if (decoder_database_->CheckPayloadTypes(packet_list) ==
695 DecoderDatabase::kDecoderNotFound) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000696 return kUnknownRtpPayloadType;
697 }
698
ossu7a377612016-10-18 04:06:13 -0700699 RTC_DCHECK(!packet_list.empty());
ossu7a377612016-10-18 04:06:13 -0700700
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700701 // Update main_timestamp, if new packets appear in the list
702 // after RED splitting.
Henrik Lundin70c09bd2017-04-24 15:56:56 +0200703 if (decoder_database_->IsRed(rtp_header.payloadType)) {
dkirovbroadsofte851a9a2017-03-14 10:00:27 -0700704 timestamp_scaler_->ToInternal(&packet_list);
705 main_timestamp = packet_list.front().timestamp;
706 main_payload_type = packet_list.front().payload_type;
707 main_sequence_number = packet_list.front().sequence_number;
708 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000709
710 // Process DTMF payloads. Cycle through the list of packets, and pick out any
711 // DTMF payloads found.
712 PacketList::iterator it = packet_list.begin();
713 while (it != packet_list.end()) {
ossua73f6c92016-10-24 08:25:28 -0700714 const Packet& current_packet = (*it);
715 RTC_DCHECK(!current_packet.payload.empty());
716 if (decoder_database_->IsDtmf(current_packet.payload_type)) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000717 DtmfEvent event;
ossua73f6c92016-10-24 08:25:28 -0700718 int ret = DtmfBuffer::ParseEvent(current_packet.timestamp,
719 current_packet.payload.data(),
720 current_packet.payload.size(), &event);
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000721 if (ret != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000722 return kDtmfParsingError;
723 }
724 if (dtmf_buffer_->InsertEvent(event) != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000725 return kDtmfInsertError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000726 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000727 it = packet_list.erase(it);
728 } else {
729 ++it;
730 }
731 }
732
ossu17e3fa12016-09-08 04:52:55 -0700733 // Update bandwidth estimate, if the packet is not comfort noise.
734 if (!packet_list.empty() &&
ossu7a377612016-10-18 04:06:13 -0700735 !decoder_database_->IsComfortNoise(main_payload_type)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000736 // The list can be empty here if we got nothing but DTMF payloads.
ossu7a377612016-10-18 04:06:13 -0700737 AudioDecoder* decoder = decoder_database_->GetDecoder(main_payload_type);
738 RTC_DCHECK(decoder); // Should always get a valid object, since we have
739 // already checked that the payload types are known.
ossua73f6c92016-10-24 08:25:28 -0700740 decoder->IncomingPacket(packet_list.front().payload.data(),
741 packet_list.front().payload.size(),
742 packet_list.front().sequence_number,
743 packet_list.front().timestamp,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000744 receive_timestamp);
745 }
746
ossu61a208b2016-09-20 01:38:00 -0700747 PacketList parsed_packet_list;
748 while (!packet_list.empty()) {
ossua73f6c92016-10-24 08:25:28 -0700749 Packet& packet = packet_list.front();
ossu61a208b2016-09-20 01:38:00 -0700750 const DecoderDatabase::DecoderInfo* info =
ossua73f6c92016-10-24 08:25:28 -0700751 decoder_database_->GetDecoderInfo(packet.payload_type);
ossu61a208b2016-09-20 01:38:00 -0700752 if (!info) {
753 LOG(LS_WARNING) << "SplitAudio unknown payload type";
754 return kUnknownRtpPayloadType;
755 }
756
757 if (info->IsComfortNoise()) {
758 // Carry comfort noise packets along.
ossua73f6c92016-10-24 08:25:28 -0700759 parsed_packet_list.splice(parsed_packet_list.end(), packet_list,
760 packet_list.begin());
ossu61a208b2016-09-20 01:38:00 -0700761 } else {
ossua73f6c92016-10-24 08:25:28 -0700762 const auto sequence_number = packet.sequence_number;
763 const auto payload_type = packet.payload_type;
764 const Packet::Priority original_priority = packet.priority;
765 auto packet_from_result = [&] (AudioDecoder::ParseResult& result) {
766 Packet new_packet;
767 new_packet.sequence_number = sequence_number;
768 new_packet.payload_type = payload_type;
769 new_packet.timestamp = result.timestamp;
770 new_packet.priority.codec_level = result.priority;
771 new_packet.priority.red_level = original_priority.red_level;
772 new_packet.frame = std::move(result.frame);
773 return new_packet;
774 };
775
ossu61a208b2016-09-20 01:38:00 -0700776 std::vector<AudioDecoder::ParseResult> results =
ossua73f6c92016-10-24 08:25:28 -0700777 info->GetDecoder()->ParsePayload(std::move(packet.payload),
778 packet.timestamp);
779 if (results.empty()) {
780 packet_list.pop_front();
781 } else {
782 bool first = true;
783 for (auto& result : results) {
784 RTC_DCHECK(result.frame);
785 RTC_DCHECK_GE(result.priority, 0);
786 if (first) {
787 // Re-use the node and move it to parsed_packet_list.
788 packet_list.front() = packet_from_result(result);
789 parsed_packet_list.splice(parsed_packet_list.end(), packet_list,
790 packet_list.begin());
791 first = false;
792 } else {
793 parsed_packet_list.push_back(packet_from_result(result));
794 }
ossu61a208b2016-09-20 01:38:00 -0700795 }
ossu61a208b2016-09-20 01:38:00 -0700796 }
797 }
798 }
799
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000800 // Insert packets in buffer.
henrik.lundin116c84e2015-08-27 13:14:48 -0700801 const size_t buffer_length_before_insert =
802 packet_buffer_->NumPacketsInBuffer();
ossua70695a2016-09-22 02:06:28 -0700803 const int ret = packet_buffer_->InsertPacketList(
ossu61a208b2016-09-20 01:38:00 -0700804 &parsed_packet_list, *decoder_database_, &current_rtp_payload_type_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000805 &current_cng_rtp_payload_type_);
806 if (ret == PacketBuffer::kFlushed) {
807 // Reset DSP timestamp etc. if packet buffer flushed.
808 new_codec_ = true;
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000809 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000810 } else if (ret != PacketBuffer::kOK) {
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000811 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000812 }
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000813
814 if (first_packet_) {
815 first_packet_ = false;
816 // Update the codec on the next GetAudio call.
817 new_codec_ = true;
818 }
819
henrik.lundinda8bbf62016-08-31 03:14:11 -0700820 if (current_rtp_payload_type_) {
821 RTC_DCHECK(decoder_database_->GetDecoderInfo(*current_rtp_payload_type_))
822 << "Payload type " << static_cast<int>(*current_rtp_payload_type_)
823 << " is unknown where it shouldn't be";
824 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000825
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000826 if (update_sample_rate_and_channels && !packet_buffer_->Empty()) {
827 // We do not use |current_rtp_payload_type_| to |set payload_type|, but
828 // get the next RTP header from |packet_buffer_| to obtain the payload type.
829 // The reason for it is the following corner case. If NetEq receives a
830 // CNG packet with a sample rate different than the current CNG then it
831 // flushes its buffer, assuming send codec must have been changed. However,
832 // payload type of the hypothetically new send codec is not known.
ossu7a377612016-10-18 04:06:13 -0700833 const Packet* next_packet = packet_buffer_->PeekNextPacket();
834 RTC_DCHECK(next_packet);
835 const int payload_type = next_packet->payload_type;
ossu97ba30e2016-04-25 07:55:58 -0700836 size_t channels = 1;
837 if (!decoder_database_->IsComfortNoise(payload_type)) {
838 AudioDecoder* decoder = decoder_database_->GetDecoder(payload_type);
839 assert(decoder); // Payloads are already checked to be valid.
840 channels = decoder->Channels();
841 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000842 const DecoderDatabase::DecoderInfo* decoder_info =
843 decoder_database_->GetDecoderInfo(payload_type);
844 assert(decoder_info);
kwibergc0f2dcf2016-05-31 06:28:03 -0700845 if (decoder_info->SampleRateHz() != fs_hz_ ||
ossu97ba30e2016-04-25 07:55:58 -0700846 channels != algorithm_buffer_->Channels()) {
kwibergc0f2dcf2016-05-31 06:28:03 -0700847 SetSampleRateAndChannels(decoder_info->SampleRateHz(),
848 channels);
henrik.lundin48ed9302015-10-29 05:36:24 -0700849 }
850 if (nack_enabled_) {
851 RTC_DCHECK(nack_);
852 // Update the sample rate even if the rate is not new, because of Reset().
853 nack_->UpdateSampleRate(fs_hz_);
854 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000855 }
856
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000857 // TODO(hlundin): Move this code to DelayManager class.
858 const DecoderDatabase::DecoderInfo* dec_info =
ossu7a377612016-10-18 04:06:13 -0700859 decoder_database_->GetDecoderInfo(main_payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000860 assert(dec_info); // Already checked that the payload type is known.
ossuf1b08da2016-09-23 02:19:43 -0700861 delay_manager_->LastDecodedWasCngOrDtmf(dec_info->IsComfortNoise() ||
862 dec_info->IsDtmf());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000863 if (delay_manager_->last_pack_cng_or_dtmf() == 0) {
864 // Calculate the total speech length carried in each packet.
henrik.lundin116c84e2015-08-27 13:14:48 -0700865 const size_t buffer_length_after_insert =
866 packet_buffer_->NumPacketsInBuffer();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000867
henrik.lundin116c84e2015-08-27 13:14:48 -0700868 if (buffer_length_after_insert > buffer_length_before_insert) {
869 const size_t packet_length_samples =
870 (buffer_length_after_insert - buffer_length_before_insert) *
871 decoder_frame_length_;
872 if (packet_length_samples != decision_logic_->packet_length_samples()) {
873 decision_logic_->set_packet_length_samples(packet_length_samples);
874 delay_manager_->SetPacketAudioLength(
kwibergd3edd772017-03-01 18:52:48 -0800875 rtc::dchecked_cast<int>((1000 * packet_length_samples) / fs_hz_));
henrik.lundin116c84e2015-08-27 13:14:48 -0700876 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000877 }
878
879 // Update statistics.
ossu7a377612016-10-18 04:06:13 -0700880 if ((int32_t)(main_timestamp - timestamp_) >= 0 && !new_codec_) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000881 // Only update statistics if incoming packet is not older than last played
882 // out packet, and if new codec flag is not set.
ossu7a377612016-10-18 04:06:13 -0700883 delay_manager_->Update(main_sequence_number, main_timestamp, fs_hz_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000884 }
885 } else if (delay_manager_->last_pack_cng_or_dtmf() == -1) {
886 // This is first "normal" packet after CNG or DTMF.
887 // Reset packet time counter and measure time until next packet,
888 // but don't update statistics.
889 delay_manager_->set_last_pack_cng_or_dtmf(0);
890 delay_manager_->ResetPacketIatCount();
891 }
892 return 0;
893}
894
henrik.lundin7a926812016-05-12 13:51:28 -0700895int NetEqImpl::GetAudioInternal(AudioFrame* audio_frame, bool* muted) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000896 PacketList packet_list;
897 DtmfEvent dtmf_event;
898 Operations operation;
899 bool play_dtmf;
henrik.lundin7a926812016-05-12 13:51:28 -0700900 *muted = false;
henrik.lundin114c1b32017-04-26 07:47:32 -0700901 last_decoded_timestamps_.clear();
henrik.lundined497212016-04-25 10:11:38 -0700902 tick_timer_->Increment();
henrik.lundin60f6ce22016-05-10 03:52:04 -0700903 stats_.IncreaseCounter(output_size_samples_, fs_hz_);
henrik.lundin7a926812016-05-12 13:51:28 -0700904
905 // Check for muted state.
906 if (enable_muted_state_ && expand_->Muted() && packet_buffer_->Empty()) {
907 RTC_DCHECK_EQ(last_mode_, kModeExpand);
908 playout_timestamp_ += static_cast<uint32_t>(output_size_samples_);
909 audio_frame->sample_rate_hz_ = fs_hz_;
910 audio_frame->samples_per_channel_ = output_size_samples_;
911 audio_frame->timestamp_ =
912 first_packet_
913 ? 0
914 : timestamp_scaler_->ToExternal(playout_timestamp_) -
915 static_cast<uint32_t>(audio_frame->samples_per_channel_);
916 audio_frame->num_channels_ = sync_buffer_->Channels();
henrik.lundin612c25e2016-05-25 08:21:04 -0700917 stats_.ExpandedNoiseSamples(output_size_samples_);
henrik.lundin7a926812016-05-12 13:51:28 -0700918 *muted = true;
919 return 0;
920 }
921
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000922 int return_value = GetDecision(&operation, &packet_list, &dtmf_event,
923 &play_dtmf);
924 if (return_value != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000925 last_mode_ = kModeError;
926 return return_value;
927 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000928
929 AudioDecoder::SpeechType speech_type;
930 int length = 0;
931 int decode_return_value = Decode(&packet_list, &operation,
932 &length, &speech_type);
933
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000934 assert(vad_.get());
935 bool sid_frame_available =
936 (operation == kRfc3389Cng && !packet_list.empty());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700937 vad_->Update(decoded_buffer_.get(), static_cast<size_t>(length), speech_type,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000938 sid_frame_available, fs_hz_);
939
henrik.lundinb1fb72b2016-05-03 08:18:47 -0700940 if (sid_frame_available || speech_type == AudioDecoder::kComfortNoise) {
941 // Start a new stopwatch since we are decoding a new CNG packet.
942 generated_noise_stopwatch_ = tick_timer_->GetNewStopwatch();
943 }
944
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000945 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000946 switch (operation) {
947 case kNormal: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000948 DoNormal(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000949 break;
950 }
951 case kMerge: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000952 DoMerge(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000953 break;
954 }
955 case kExpand: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000956 return_value = DoExpand(play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000957 break;
958 }
Henrik Lundincf808d22015-05-27 14:33:29 +0200959 case kAccelerate:
960 case kFastAccelerate: {
961 const bool fast_accelerate =
962 enable_fast_accelerate_ && (operation == kFastAccelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000963 return_value = DoAccelerate(decoded_buffer_.get(), length, speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +0200964 play_dtmf, fast_accelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000965 break;
966 }
967 case kPreemptiveExpand: {
968 return_value = DoPreemptiveExpand(decoded_buffer_.get(), length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000969 speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000970 break;
971 }
972 case kRfc3389Cng:
973 case kRfc3389CngNoPacket: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000974 return_value = DoRfc3389Cng(&packet_list, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000975 break;
976 }
977 case kCodecInternalCng: {
978 // This handles the case when there is no transmission and the decoder
979 // should produce internal comfort noise.
980 // TODO(hlundin): Write test for codec-internal CNG.
minyuel6d92bf52015-09-23 15:20:39 +0200981 DoCodecInternalCng(decoded_buffer_.get(), length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000982 break;
983 }
984 case kDtmf: {
985 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000986 return_value = DoDtmf(dtmf_event, &play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000987 break;
988 }
989 case kAlternativePlc: {
990 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000991 DoAlternativePlc(false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000992 break;
993 }
994 case kAlternativePlcIncreaseTimestamp: {
995 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000996 DoAlternativePlc(true);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000997 break;
998 }
999 case kAudioRepetitionIncreaseTimestamp: {
1000 // TODO(hlundin): Write test for this.
Peter Kastingb7e50542015-06-11 12:55:50 -07001001 sync_buffer_->IncreaseEndTimestamp(
1002 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001003 // Skipping break on purpose. Execution should move on into the
1004 // next case.
kjellander@webrtc.org7d2b6a92015-01-28 18:37:58 +00001005 FALLTHROUGH();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001006 }
1007 case kAudioRepetition: {
1008 // TODO(hlundin): Write test for this.
1009 // Copy last |output_size_samples_| from |sync_buffer_| to
1010 // |algorithm_buffer|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001011 algorithm_buffer_->PushBackFromIndex(
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001012 *sync_buffer_, sync_buffer_->Size() - output_size_samples_);
1013 expand_->Reset();
1014 break;
1015 }
1016 case kUndefined: {
Henrik Lundind67a2192015-08-03 12:54:37 +02001017 LOG(LS_ERROR) << "Invalid operation kUndefined.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001018 assert(false); // This should not happen.
1019 last_mode_ = kModeError;
1020 return kInvalidOperation;
1021 }
1022 } // End of switch.
minyue5bd33972016-05-02 04:46:11 -07001023 last_operation_ = operation;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001024 if (return_value < 0) {
1025 return return_value;
1026 }
1027
1028 if (last_mode_ != kModeRfc3389Cng) {
1029 comfort_noise_->Reset();
1030 }
1031
1032 // Copy from |algorithm_buffer| to |sync_buffer_|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001033 sync_buffer_->PushBack(*algorithm_buffer_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001034
1035 // Extract data from |sync_buffer_| to |output|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001036 size_t num_output_samples_per_channel = output_size_samples_;
1037 size_t num_output_samples = output_size_samples_ * sync_buffer_->Channels();
henrik.lundin6d8e0112016-03-04 10:34:21 -08001038 if (num_output_samples > AudioFrame::kMaxDataSizeSamples) {
1039 LOG(LS_WARNING) << "Output array is too short. "
1040 << AudioFrame::kMaxDataSizeSamples << " < "
1041 << output_size_samples_ << " * "
1042 << sync_buffer_->Channels();
1043 num_output_samples = AudioFrame::kMaxDataSizeSamples;
1044 num_output_samples_per_channel =
1045 AudioFrame::kMaxDataSizeSamples / sync_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001046 }
henrik.lundin6d8e0112016-03-04 10:34:21 -08001047 sync_buffer_->GetNextAudioInterleaved(num_output_samples_per_channel,
1048 audio_frame);
1049 audio_frame->sample_rate_hz_ = fs_hz_;
Henrik Lundin05f71fc2015-09-01 11:51:58 +02001050 if (sync_buffer_->FutureLength() < expand_->overlap_length()) {
1051 // The sync buffer should always contain |overlap_length| samples, but now
1052 // too many samples have been extracted. Reinstall the |overlap_length|
1053 // lookahead by moving the index.
1054 const size_t missing_lookahead_samples =
1055 expand_->overlap_length() - sync_buffer_->FutureLength();
henrikg91d6ede2015-09-17 00:24:34 -07001056 RTC_DCHECK_GE(sync_buffer_->next_index(), missing_lookahead_samples);
Henrik Lundin05f71fc2015-09-01 11:51:58 +02001057 sync_buffer_->set_next_index(sync_buffer_->next_index() -
1058 missing_lookahead_samples);
1059 }
henrik.lundin6d8e0112016-03-04 10:34:21 -08001060 if (audio_frame->samples_per_channel_ != output_size_samples_) {
1061 LOG(LS_ERROR) << "audio_frame->samples_per_channel_ ("
1062 << audio_frame->samples_per_channel_
Henrik Lundind67a2192015-08-03 12:54:37 +02001063 << ") != output_size_samples_ (" << output_size_samples_
1064 << ")";
minyue@webrtc.orgdb1cefc2013-08-13 01:39:21 +00001065 // TODO(minyue): treatment of under-run, filling zeros
henrik.lundin6d8e0112016-03-04 10:34:21 -08001066 memset(audio_frame->data_, 0, num_output_samples * sizeof(int16_t));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001067 return kSampleUnderrun;
1068 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001069
1070 // Should always have overlap samples left in the |sync_buffer_|.
henrikg91d6ede2015-09-17 00:24:34 -07001071 RTC_DCHECK_GE(sync_buffer_->FutureLength(), expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001072
1073 if (play_dtmf) {
henrik.lundin6d8e0112016-03-04 10:34:21 -08001074 return_value =
1075 DtmfOverdub(dtmf_event, sync_buffer_->Channels(), audio_frame->data_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001076 }
1077
1078 // Update the background noise parameters if last operation wrote data
1079 // straight from the decoder to the |sync_buffer_|. That is, none of the
1080 // operations that modify the signal can be followed by a parameter update.
1081 if ((last_mode_ == kModeNormal) ||
1082 (last_mode_ == kModeAccelerateFail) ||
1083 (last_mode_ == kModePreemptiveExpandFail) ||
1084 (last_mode_ == kModeRfc3389Cng) ||
1085 (last_mode_ == kModeCodecInternalCng)) {
1086 background_noise_->Update(*sync_buffer_, *vad_.get());
1087 }
1088
1089 if (operation == kDtmf) {
1090 // DTMF data was written the end of |sync_buffer_|.
1091 // Update index to end of DTMF data in |sync_buffer_|.
1092 sync_buffer_->set_dtmf_index(sync_buffer_->Size());
1093 }
1094
henrik.lundin@webrtc.orged865b52014-03-06 10:28:07 +00001095 if (last_mode_ != kModeExpand) {
1096 // If last operation was not expand, calculate the |playout_timestamp_| from
1097 // the |sync_buffer_|. However, do not update the |playout_timestamp_| if it
1098 // would be moved "backwards".
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001099 uint32_t temp_timestamp = sync_buffer_->end_timestamp() -
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001100 static_cast<uint32_t>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001101 if (static_cast<int32_t>(temp_timestamp - playout_timestamp_) > 0) {
1102 playout_timestamp_ = temp_timestamp;
1103 }
1104 } else {
1105 // Use dead reckoning to estimate the |playout_timestamp_|.
Peter Kastingb7e50542015-06-11 12:55:50 -07001106 playout_timestamp_ += static_cast<uint32_t>(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001107 }
henrik.lundin15c51e32016-04-06 08:38:56 -07001108 // Set the timestamp in the audio frame to zero before the first packet has
1109 // been inserted. Otherwise, subtract the frame size in samples to get the
1110 // timestamp of the first sample in the frame (playout_timestamp_ is the
1111 // last + 1).
1112 audio_frame->timestamp_ =
1113 first_packet_
1114 ? 0
1115 : timestamp_scaler_->ToExternal(playout_timestamp_) -
1116 static_cast<uint32_t>(audio_frame->samples_per_channel_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001117
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001118 if (!(last_mode_ == kModeRfc3389Cng ||
1119 last_mode_ == kModeCodecInternalCng ||
1120 last_mode_ == kModeExpand)) {
1121 generated_noise_stopwatch_.reset();
1122 }
1123
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001124 if (decode_return_value) return decode_return_value;
1125 return return_value;
1126}
1127
1128int NetEqImpl::GetDecision(Operations* operation,
1129 PacketList* packet_list,
1130 DtmfEvent* dtmf_event,
1131 bool* play_dtmf) {
1132 // Initialize output variables.
1133 *play_dtmf = false;
1134 *operation = kUndefined;
1135
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001136 assert(sync_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001137 uint32_t end_timestamp = sync_buffer_->end_timestamp();
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001138 if (!new_codec_) {
1139 const uint32_t five_seconds_samples = 5 * fs_hz_;
1140 packet_buffer_->DiscardOldPackets(end_timestamp, five_seconds_samples);
1141 }
ossu7a377612016-10-18 04:06:13 -07001142 const Packet* packet = packet_buffer_->PeekNextPacket();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001143
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001144 RTC_DCHECK(!generated_noise_stopwatch_ ||
1145 generated_noise_stopwatch_->ElapsedTicks() >= 1);
1146 uint64_t generated_noise_samples =
1147 generated_noise_stopwatch_
1148 ? (generated_noise_stopwatch_->ElapsedTicks() - 1) *
1149 output_size_samples_ +
1150 decision_logic_->noise_fast_forward()
1151 : 0;
1152
henrik.lundin@webrtc.orgca8cb952014-03-12 10:26:52 +00001153 if (decision_logic_->CngRfc3389On() || last_mode_ == kModeRfc3389Cng) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001154 // Because of timestamp peculiarities, we have to "manually" disallow using
1155 // a CNG packet with the same timestamp as the one that was last played.
1156 // This can happen when using redundancy and will cause the timing to shift.
ossu7a377612016-10-18 04:06:13 -07001157 while (packet && decoder_database_->IsComfortNoise(packet->payload_type) &&
1158 (end_timestamp >= packet->timestamp ||
1159 end_timestamp + generated_noise_samples > packet->timestamp)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001160 // Don't use this packet, discard it.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001161 if (packet_buffer_->DiscardNextPacket() != PacketBuffer::kOK) {
1162 assert(false); // Must be ok by design.
1163 }
1164 // Check buffer again.
1165 if (!new_codec_) {
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001166 packet_buffer_->DiscardOldPackets(end_timestamp, 5 * fs_hz_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001167 }
ossu7a377612016-10-18 04:06:13 -07001168 packet = packet_buffer_->PeekNextPacket();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001169 }
1170 }
1171
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001172 assert(expand_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001173 const int samples_left = static_cast<int>(sync_buffer_->FutureLength() -
1174 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001175 if (last_mode_ == kModeAccelerateSuccess ||
1176 last_mode_ == kModeAccelerateLowEnergy ||
1177 last_mode_ == kModePreemptiveExpandSuccess ||
1178 last_mode_ == kModePreemptiveExpandLowEnergy) {
1179 // Subtract (samples_left + output_size_samples_) from sampleMemory.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001180 decision_logic_->AddSampleMemory(
kwibergd3edd772017-03-01 18:52:48 -08001181 -(samples_left + rtc::dchecked_cast<int>(output_size_samples_)));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001182 }
1183
1184 // Check if it is time to play a DTMF event.
Peter Kastingb7e50542015-06-11 12:55:50 -07001185 if (dtmf_buffer_->GetEvent(
1186 static_cast<uint32_t>(
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001187 end_timestamp + generated_noise_samples),
Peter Kastingb7e50542015-06-11 12:55:50 -07001188 dtmf_event)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001189 *play_dtmf = true;
1190 }
1191
1192 // Get instruction.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001193 assert(sync_buffer_.get());
1194 assert(expand_.get());
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001195 generated_noise_samples =
1196 generated_noise_stopwatch_
1197 ? generated_noise_stopwatch_->ElapsedTicks() * output_size_samples_ +
1198 decision_logic_->noise_fast_forward()
1199 : 0;
1200 *operation = decision_logic_->GetDecision(
ossu7a377612016-10-18 04:06:13 -07001201 *sync_buffer_, *expand_, decoder_frame_length_, packet, last_mode_,
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001202 *play_dtmf, generated_noise_samples, &reset_decoder_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001203
1204 // Check if we already have enough samples in the |sync_buffer_|. If so,
1205 // change decision to normal, unless the decision was merge, accelerate, or
1206 // preemptive expand.
kwibergd3edd772017-03-01 18:52:48 -08001207 if (samples_left >= rtc::dchecked_cast<int>(output_size_samples_) &&
1208 *operation != kMerge && *operation != kAccelerate &&
1209 *operation != kFastAccelerate && *operation != kPreemptiveExpand) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001210 *operation = kNormal;
1211 return 0;
1212 }
1213
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001214 decision_logic_->ExpandDecision(*operation);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001215
1216 // Check conditions for reset.
1217 if (new_codec_ || *operation == kUndefined) {
1218 // The only valid reason to get kUndefined is that new_codec_ is set.
1219 assert(new_codec_);
ossu7a377612016-10-18 04:06:13 -07001220 if (*play_dtmf && !packet) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001221 timestamp_ = dtmf_event->timestamp;
1222 } else {
ossu7a377612016-10-18 04:06:13 -07001223 if (!packet) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001224 LOG(LS_ERROR) << "Packet missing where it shouldn't.";
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001225 return -1;
1226 }
ossu7a377612016-10-18 04:06:13 -07001227 timestamp_ = packet->timestamp;
ossu108ecec2016-07-08 08:45:18 -07001228 if (*operation == kRfc3389CngNoPacket &&
ossu7a377612016-10-18 04:06:13 -07001229 decoder_database_->IsComfortNoise(packet->payload_type)) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001230 // Change decision to CNG packet, since we do have a CNG packet, but it
1231 // was considered too early to use. Now, use it anyway.
1232 *operation = kRfc3389Cng;
1233 } else if (*operation != kRfc3389Cng) {
1234 *operation = kNormal;
1235 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001236 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001237 // Adjust |sync_buffer_| timestamp before setting |end_timestamp| to the
1238 // new value.
1239 sync_buffer_->IncreaseEndTimestamp(timestamp_ - end_timestamp);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001240 end_timestamp = timestamp_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001241 new_codec_ = false;
1242 decision_logic_->SoftReset();
1243 buffer_level_filter_->Reset();
1244 delay_manager_->Reset();
1245 stats_.ResetMcu();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001246 }
1247
Peter Kastingdce40cf2015-08-24 14:52:23 -07001248 size_t required_samples = output_size_samples_;
1249 const size_t samples_10_ms = static_cast<size_t>(80 * fs_mult_);
1250 const size_t samples_20_ms = 2 * samples_10_ms;
1251 const size_t samples_30_ms = 3 * samples_10_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001252
1253 switch (*operation) {
1254 case kExpand: {
1255 timestamp_ = end_timestamp;
1256 return 0;
1257 }
1258 case kRfc3389CngNoPacket:
1259 case kCodecInternalCng: {
1260 return 0;
1261 }
1262 case kDtmf: {
1263 // TODO(hlundin): Write test for this.
1264 // Update timestamp.
1265 timestamp_ = end_timestamp;
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001266 const uint64_t generated_noise_samples =
1267 generated_noise_stopwatch_
1268 ? generated_noise_stopwatch_->ElapsedTicks() *
1269 output_size_samples_ +
1270 decision_logic_->noise_fast_forward()
1271 : 0;
1272 if (generated_noise_samples > 0 && last_mode_ != kModeDtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001273 // Make a jump in timestamp due to the recently played comfort noise.
Peter Kastingb7e50542015-06-11 12:55:50 -07001274 uint32_t timestamp_jump =
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001275 static_cast<uint32_t>(generated_noise_samples);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001276 sync_buffer_->IncreaseEndTimestamp(timestamp_jump);
1277 timestamp_ += timestamp_jump;
1278 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001279 return 0;
1280 }
Henrik Lundincf808d22015-05-27 14:33:29 +02001281 case kAccelerate:
1282 case kFastAccelerate: {
1283 // In order to do an accelerate we need at least 30 ms of audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001284 if (samples_left >= static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001285 // Already have enough data, so we do not need to extract any more.
1286 decision_logic_->set_sample_memory(samples_left);
1287 decision_logic_->set_prev_time_scale(true);
1288 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001289 } else if (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001290 decoder_frame_length_ >= samples_30_ms) {
1291 // Avoid decoding more data as it might overflow the playout buffer.
1292 *operation = kNormal;
1293 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001294 } else if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001295 decoder_frame_length_ < samples_30_ms) {
1296 // Build up decoded data by decoding at least 20 ms of audio data. Do
1297 // not perform accelerate yet, but wait until we only need to do one
1298 // decoding.
1299 required_samples = 2 * output_size_samples_;
1300 *operation = kNormal;
1301 }
1302 // If none of the above is true, we have one of two possible situations:
1303 // (1) 20 ms <= samples_left < 30 ms and decoder_frame_length_ < 30 ms; or
1304 // (2) samples_left < 10 ms and decoder_frame_length_ >= 30 ms.
1305 // In either case, we move on with the accelerate decision, and decode one
1306 // frame now.
1307 break;
1308 }
1309 case kPreemptiveExpand: {
1310 // In order to do a preemptive expand we need at least 30 ms of decoded
1311 // audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001312 if ((samples_left >= static_cast<int>(samples_30_ms)) ||
1313 (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001314 decoder_frame_length_ >= samples_30_ms)) {
1315 // Already have enough data, so we do not need to extract any more.
1316 // Or, avoid decoding more data as it might overflow the playout buffer.
1317 // Still try preemptive expand, though.
1318 decision_logic_->set_sample_memory(samples_left);
1319 decision_logic_->set_prev_time_scale(true);
1320 return 0;
1321 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07001322 if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001323 decoder_frame_length_ < samples_30_ms) {
1324 // Build up decoded data by decoding at least 20 ms of audio data.
1325 // Still try to perform preemptive expand.
1326 required_samples = 2 * output_size_samples_;
1327 }
1328 // Move on with the preemptive expand decision.
1329 break;
1330 }
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001331 case kMerge: {
1332 required_samples =
1333 std::max(merge_->RequiredFutureSamples(), required_samples);
1334 break;
1335 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001336 default: {
1337 // Do nothing.
1338 }
1339 }
1340
1341 // Get packets from buffer.
1342 int extracted_samples = 0;
ossu7a377612016-10-18 04:06:13 -07001343 if (packet && *operation != kAlternativePlc &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001344 *operation != kAlternativePlcIncreaseTimestamp &&
1345 *operation != kAudioRepetition &&
1346 *operation != kAudioRepetitionIncreaseTimestamp) {
ossu7a377612016-10-18 04:06:13 -07001347 sync_buffer_->IncreaseEndTimestamp(packet->timestamp - end_timestamp);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001348 if (decision_logic_->CngOff()) {
1349 // Adjustment of timestamp only corresponds to an actual packet loss
1350 // if comfort noise is not played. If comfort noise was just played,
1351 // this adjustment of timestamp is only done to get back in sync with the
1352 // stream timestamp; no loss to report.
ossu7a377612016-10-18 04:06:13 -07001353 stats_.LostSamples(packet->timestamp - end_timestamp);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001354 }
1355
1356 if (*operation != kRfc3389Cng) {
1357 // We are about to decode and use a non-CNG packet.
1358 decision_logic_->SetCngOff();
1359 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001360
1361 extracted_samples = ExtractPackets(required_samples, packet_list);
1362 if (extracted_samples < 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001363 return kPacketBufferCorruption;
1364 }
1365 }
1366
Henrik Lundincf808d22015-05-27 14:33:29 +02001367 if (*operation == kAccelerate || *operation == kFastAccelerate ||
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001368 *operation == kPreemptiveExpand) {
1369 decision_logic_->set_sample_memory(samples_left + extracted_samples);
1370 decision_logic_->set_prev_time_scale(true);
1371 }
1372
Henrik Lundincf808d22015-05-27 14:33:29 +02001373 if (*operation == kAccelerate || *operation == kFastAccelerate) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001374 // Check that we have enough data (30ms) to do accelerate.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001375 if (extracted_samples + samples_left < static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001376 // TODO(hlundin): Write test for this.
1377 // Not enough, do normal operation instead.
1378 *operation = kNormal;
1379 }
1380 }
1381
1382 timestamp_ = end_timestamp;
1383 return 0;
1384}
1385
1386int NetEqImpl::Decode(PacketList* packet_list, Operations* operation,
1387 int* decoded_length,
1388 AudioDecoder::SpeechType* speech_type) {
1389 *speech_type = AudioDecoder::kSpeech;
minyuel6d92bf52015-09-23 15:20:39 +02001390
1391 // When packet_list is empty, we may be in kCodecInternalCng mode, and for
1392 // that we use current active decoder.
1393 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1394
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001395 if (!packet_list->empty()) {
ossua73f6c92016-10-24 08:25:28 -07001396 const Packet& packet = packet_list->front();
1397 uint8_t payload_type = packet.payload_type;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001398 if (!decoder_database_->IsComfortNoise(payload_type)) {
1399 decoder = decoder_database_->GetDecoder(payload_type);
1400 assert(decoder);
1401 if (!decoder) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001402 LOG(LS_WARNING) << "Unknown payload type "
1403 << static_cast<int>(payload_type);
ossua73f6c92016-10-24 08:25:28 -07001404 packet_list->clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001405 return kDecoderNotFound;
1406 }
1407 bool decoder_changed;
1408 decoder_database_->SetActiveDecoder(payload_type, &decoder_changed);
1409 if (decoder_changed) {
1410 // We have a new decoder. Re-init some values.
1411 const DecoderDatabase::DecoderInfo* decoder_info = decoder_database_
1412 ->GetDecoderInfo(payload_type);
1413 assert(decoder_info);
1414 if (!decoder_info) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001415 LOG(LS_WARNING) << "Unknown payload type "
1416 << static_cast<int>(payload_type);
ossua73f6c92016-10-24 08:25:28 -07001417 packet_list->clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001418 return kDecoderNotFound;
1419 }
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001420 // If sampling rate or number of channels has changed, we need to make
1421 // a reset.
kwibergc0f2dcf2016-05-31 06:28:03 -07001422 if (decoder_info->SampleRateHz() != fs_hz_ ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001423 decoder->Channels() != algorithm_buffer_->Channels()) {
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001424 // TODO(tlegrand): Add unittest to cover this event.
kwibergc0f2dcf2016-05-31 06:28:03 -07001425 SetSampleRateAndChannels(decoder_info->SampleRateHz(),
1426 decoder->Channels());
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001427 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001428 sync_buffer_->set_end_timestamp(timestamp_);
1429 playout_timestamp_ = timestamp_;
1430 }
1431 }
1432 }
1433
1434 if (reset_decoder_) {
1435 // TODO(hlundin): Write test for this.
Karl Wiberg43766482015-08-27 15:22:11 +02001436 if (decoder)
1437 decoder->Reset();
1438
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001439 // Reset comfort noise decoder.
ossu97ba30e2016-04-25 07:55:58 -07001440 ComfortNoiseDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02001441 if (cng_decoder)
1442 cng_decoder->Reset();
1443
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001444 reset_decoder_ = false;
1445 }
1446
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001447 *decoded_length = 0;
1448 // Update codec-internal PLC state.
1449 if ((*operation == kMerge) && decoder && decoder->HasDecodePlc()) {
1450 decoder->DecodePlc(1, &decoded_buffer_[*decoded_length]);
1451 }
1452
minyuel6d92bf52015-09-23 15:20:39 +02001453 int return_value;
1454 if (*operation == kCodecInternalCng) {
1455 RTC_DCHECK(packet_list->empty());
1456 return_value = DecodeCng(decoder, decoded_length, speech_type);
1457 } else {
1458 return_value = DecodeLoop(packet_list, *operation, decoder,
1459 decoded_length, speech_type);
1460 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001461
1462 if (*decoded_length < 0) {
1463 // Error returned from the decoder.
1464 *decoded_length = 0;
Peter Kastingb7e50542015-06-11 12:55:50 -07001465 sync_buffer_->IncreaseEndTimestamp(
1466 static_cast<uint32_t>(decoder_frame_length_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001467 int error_code = 0;
1468 if (decoder)
1469 error_code = decoder->ErrorCode();
1470 if (error_code != 0) {
1471 // Got some error code from the decoder.
1472 decoder_error_code_ = error_code;
1473 return_value = kDecoderErrorCode;
Henrik Lundind67a2192015-08-03 12:54:37 +02001474 LOG(LS_WARNING) << "Decoder returned error code: " << error_code;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001475 } else {
1476 // Decoder does not implement error codes. Return generic error.
1477 return_value = kOtherDecoderError;
Henrik Lundind67a2192015-08-03 12:54:37 +02001478 LOG(LS_WARNING) << "Decoder error (no error code)";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001479 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001480 *operation = kExpand; // Do expansion to get data instead.
1481 }
1482 if (*speech_type != AudioDecoder::kComfortNoise) {
1483 // Don't increment timestamp if codec returned CNG speech type
1484 // since in this case, the we will increment the CNGplayedTS counter.
1485 // Increase with number of samples per channel.
1486 assert(*decoded_length == 0 ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001487 (decoder && decoder->Channels() == sync_buffer_->Channels()));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001488 sync_buffer_->IncreaseEndTimestamp(
1489 *decoded_length / static_cast<int>(sync_buffer_->Channels()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001490 }
1491 return return_value;
1492}
1493
minyuel6d92bf52015-09-23 15:20:39 +02001494int NetEqImpl::DecodeCng(AudioDecoder* decoder, int* decoded_length,
1495 AudioDecoder::SpeechType* speech_type) {
1496 if (!decoder) {
1497 // This happens when active decoder is not defined.
1498 *decoded_length = -1;
1499 return 0;
1500 }
1501
kwibergd3edd772017-03-01 18:52:48 -08001502 while (*decoded_length < rtc::dchecked_cast<int>(output_size_samples_)) {
minyuel6d92bf52015-09-23 15:20:39 +02001503 const int length = decoder->Decode(
1504 nullptr, 0, fs_hz_,
1505 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1506 &decoded_buffer_[*decoded_length], speech_type);
1507 if (length > 0) {
1508 *decoded_length += length;
minyuel6d92bf52015-09-23 15:20:39 +02001509 } else {
1510 // Error.
1511 LOG(LS_WARNING) << "Failed to decode CNG";
1512 *decoded_length = -1;
1513 break;
1514 }
1515 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1516 // Guard against overflow.
1517 LOG(LS_WARNING) << "Decoded too much CNG.";
1518 return kDecodedTooMuch;
1519 }
1520 }
1521 return 0;
1522}
1523
1524int NetEqImpl::DecodeLoop(PacketList* packet_list, const Operations& operation,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001525 AudioDecoder* decoder, int* decoded_length,
1526 AudioDecoder::SpeechType* speech_type) {
henrik.lundin114c1b32017-04-26 07:47:32 -07001527 RTC_DCHECK(last_decoded_timestamps_.empty());
1528
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001529 // Do decoding.
ossua73f6c92016-10-24 08:25:28 -07001530 while (
1531 !packet_list->empty() &&
1532 !decoder_database_->IsComfortNoise(packet_list->front().payload_type)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001533 assert(decoder); // At this point, we must have a decoder object.
1534 // The number of channels in the |sync_buffer_| should be the same as the
1535 // number decoder channels.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001536 assert(sync_buffer_->Channels() == decoder->Channels());
1537 assert(decoded_buffer_length_ >= kMaxFrameSize * decoder->Channels());
minyuel6d92bf52015-09-23 15:20:39 +02001538 assert(operation == kNormal || operation == kAccelerate ||
1539 operation == kFastAccelerate || operation == kMerge ||
1540 operation == kPreemptiveExpand);
ossua73f6c92016-10-24 08:25:28 -07001541
1542 auto opt_result = packet_list->front().frame->Decode(
ossu61a208b2016-09-20 01:38:00 -07001543 rtc::ArrayView<int16_t>(&decoded_buffer_[*decoded_length],
1544 decoded_buffer_length_ - *decoded_length));
henrik.lundin114c1b32017-04-26 07:47:32 -07001545 last_decoded_timestamps_.push_back(packet_list->front().timestamp);
ossua73f6c92016-10-24 08:25:28 -07001546 packet_list->pop_front();
ossu61a208b2016-09-20 01:38:00 -07001547 if (opt_result) {
1548 const auto& result = *opt_result;
1549 *speech_type = result.speech_type;
1550 if (result.num_decoded_samples > 0) {
kwibergd3edd772017-03-01 18:52:48 -08001551 *decoded_length += rtc::dchecked_cast<int>(result.num_decoded_samples);
ossu61a208b2016-09-20 01:38:00 -07001552 // Update |decoder_frame_length_| with number of samples per channel.
1553 decoder_frame_length_ =
1554 result.num_decoded_samples / decoder->Channels();
1555 }
1556 } else {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001557 // Error.
ossu61a208b2016-09-20 01:38:00 -07001558 // TODO(ossu): What to put here?
1559 LOG(LS_WARNING) << "Decode error";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001560 *decoded_length = -1;
ossua73f6c92016-10-24 08:25:28 -07001561 packet_list->clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001562 break;
1563 }
kwibergd3edd772017-03-01 18:52:48 -08001564 if (*decoded_length > rtc::dchecked_cast<int>(decoded_buffer_length_)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001565 // Guard against overflow.
Henrik Lundind67a2192015-08-03 12:54:37 +02001566 LOG(LS_WARNING) << "Decoded too much.";
ossua73f6c92016-10-24 08:25:28 -07001567 packet_list->clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001568 return kDecodedTooMuch;
1569 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001570 } // End of decode loop.
1571
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001572 // If the list is not empty at this point, either a decoding error terminated
1573 // the while-loop, or list must hold exactly one CNG packet.
ossua73f6c92016-10-24 08:25:28 -07001574 assert(
1575 packet_list->empty() || *decoded_length < 0 ||
1576 (packet_list->size() == 1 &&
1577 decoder_database_->IsComfortNoise(packet_list->front().payload_type)));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001578 return 0;
1579}
1580
1581void NetEqImpl::DoNormal(const int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001582 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001583 assert(normal_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001584 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001585 normal_->Process(decoded_buffer, decoded_length, last_mode_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001586 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001587 if (decoded_length != 0) {
1588 last_mode_ = kModeNormal;
1589 }
1590
1591 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1592 if ((speech_type == AudioDecoder::kComfortNoise)
1593 || ((last_mode_ == kModeCodecInternalCng)
1594 && (decoded_length == 0))) {
1595 // TODO(hlundin): Remove second part of || statement above.
1596 last_mode_ = kModeCodecInternalCng;
1597 }
1598
1599 if (!play_dtmf) {
1600 dtmf_tone_generator_->Reset();
1601 }
1602}
1603
1604void NetEqImpl::DoMerge(int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001605 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001606 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001607 assert(merge_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001608 size_t new_length = merge_->Process(decoded_buffer, decoded_length,
1609 mute_factor_array_.get(),
1610 algorithm_buffer_.get());
henrik.lundin2979f552017-05-05 05:04:16 -07001611 // Correction can be negative.
1612 int expand_length_correction =
1613 rtc::dchecked_cast<int>(new_length) -
1614 rtc::dchecked_cast<int>(decoded_length / algorithm_buffer_->Channels());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001615
1616 // Update in-call and post-call statistics.
1617 if (expand_->MuteFactor(0) == 0) {
1618 // Expand generates only noise.
henrik.lundin2979f552017-05-05 05:04:16 -07001619 stats_.ExpandedNoiseSamplesCorrection(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001620 } else {
1621 // Expansion generates more than only noise.
henrik.lundin2979f552017-05-05 05:04:16 -07001622 stats_.ExpandedVoiceSamplesCorrection(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001623 }
1624
1625 last_mode_ = kModeMerge;
1626 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1627 if (speech_type == AudioDecoder::kComfortNoise) {
1628 last_mode_ = kModeCodecInternalCng;
1629 }
1630 expand_->Reset();
1631 if (!play_dtmf) {
1632 dtmf_tone_generator_->Reset();
1633 }
1634}
1635
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001636int NetEqImpl::DoExpand(bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001637 while ((sync_buffer_->FutureLength() - expand_->overlap_length()) <
Peter Kastingdce40cf2015-08-24 14:52:23 -07001638 output_size_samples_) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001639 algorithm_buffer_->Clear();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001640 int return_value = expand_->Process(algorithm_buffer_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001641 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001642
1643 // Update in-call and post-call statistics.
1644 if (expand_->MuteFactor(0) == 0) {
1645 // Expand operation generates only noise.
1646 stats_.ExpandedNoiseSamples(length);
1647 } else {
1648 // Expand operation generates more than only noise.
1649 stats_.ExpandedVoiceSamples(length);
1650 }
1651
1652 last_mode_ = kModeExpand;
1653
1654 if (return_value < 0) {
1655 return return_value;
1656 }
1657
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001658 sync_buffer_->PushBack(*algorithm_buffer_);
1659 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001660 }
1661 if (!play_dtmf) {
1662 dtmf_tone_generator_->Reset();
1663 }
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001664
1665 if (!generated_noise_stopwatch_) {
1666 // Start a new stopwatch since we may be covering for a lost CNG packet.
1667 generated_noise_stopwatch_ = tick_timer_->GetNewStopwatch();
1668 }
1669
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001670 return 0;
1671}
1672
Henrik Lundincf808d22015-05-27 14:33:29 +02001673int NetEqImpl::DoAccelerate(int16_t* decoded_buffer,
1674 size_t decoded_length,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001675 AudioDecoder::SpeechType speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +02001676 bool play_dtmf,
1677 bool fast_accelerate) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001678 const size_t required_samples =
1679 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001680 size_t borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001681 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001682 size_t decoded_length_per_channel = decoded_length / num_channels;
1683 if (decoded_length_per_channel < required_samples) {
1684 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001685 borrowed_samples_per_channel = static_cast<int>(required_samples -
1686 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001687 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1688 decoded_buffer,
1689 sizeof(int16_t) * decoded_length);
1690 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1691 decoded_buffer);
1692 decoded_length = required_samples * num_channels;
1693 }
1694
Peter Kastingdce40cf2015-08-24 14:52:23 -07001695 size_t samples_removed;
Henrik Lundincf808d22015-05-27 14:33:29 +02001696 Accelerate::ReturnCodes return_code =
1697 accelerate_->Process(decoded_buffer, decoded_length, fast_accelerate,
1698 algorithm_buffer_.get(), &samples_removed);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001699 stats_.AcceleratedSamples(samples_removed);
1700 switch (return_code) {
1701 case Accelerate::kSuccess:
1702 last_mode_ = kModeAccelerateSuccess;
1703 break;
1704 case Accelerate::kSuccessLowEnergy:
1705 last_mode_ = kModeAccelerateLowEnergy;
1706 break;
1707 case Accelerate::kNoStretch:
1708 last_mode_ = kModeAccelerateFail;
1709 break;
1710 case Accelerate::kError:
1711 // TODO(hlundin): Map to kModeError instead?
1712 last_mode_ = kModeAccelerateFail;
1713 return kAccelerateError;
1714 }
1715
1716 if (borrowed_samples_per_channel > 0) {
1717 // Copy borrowed samples back to the |sync_buffer_|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001718 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001719 if (length < borrowed_samples_per_channel) {
1720 // This destroys the beginning of the buffer, but will not cause any
1721 // problems.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001722 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001723 sync_buffer_->Size() -
1724 borrowed_samples_per_channel);
1725 sync_buffer_->PushFrontZeros(borrowed_samples_per_channel - length);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001726 algorithm_buffer_->PopFront(length);
1727 assert(algorithm_buffer_->Empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001728 } else {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001729 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001730 borrowed_samples_per_channel,
1731 sync_buffer_->Size() -
1732 borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001733 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001734 }
1735 }
1736
1737 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1738 if (speech_type == AudioDecoder::kComfortNoise) {
1739 last_mode_ = kModeCodecInternalCng;
1740 }
1741 if (!play_dtmf) {
1742 dtmf_tone_generator_->Reset();
1743 }
1744 expand_->Reset();
1745 return 0;
1746}
1747
1748int NetEqImpl::DoPreemptiveExpand(int16_t* decoded_buffer,
1749 size_t decoded_length,
1750 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001751 bool play_dtmf) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001752 const size_t required_samples =
1753 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001754 size_t num_channels = algorithm_buffer_->Channels();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001755 size_t borrowed_samples_per_channel = 0;
1756 size_t old_borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001757 size_t decoded_length_per_channel = decoded_length / num_channels;
1758 if (decoded_length_per_channel < required_samples) {
1759 // Must move data from the |sync_buffer_| in order to get 30 ms.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001760 borrowed_samples_per_channel =
1761 required_samples - decoded_length_per_channel;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001762 // Calculate how many of these were already played out.
Peter Kastingf045e4d2015-06-10 21:15:38 -07001763 old_borrowed_samples_per_channel =
Peter Kastingdce40cf2015-08-24 14:52:23 -07001764 (borrowed_samples_per_channel > sync_buffer_->FutureLength()) ?
1765 (borrowed_samples_per_channel - sync_buffer_->FutureLength()) : 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001766 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1767 decoded_buffer,
1768 sizeof(int16_t) * decoded_length);
1769 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1770 decoded_buffer);
1771 decoded_length = required_samples * num_channels;
1772 }
1773
Peter Kastingdce40cf2015-08-24 14:52:23 -07001774 size_t samples_added;
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001775 PreemptiveExpand::ReturnCodes return_code = preemptive_expand_->Process(
Peter Kastingdce40cf2015-08-24 14:52:23 -07001776 decoded_buffer, decoded_length,
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001777 old_borrowed_samples_per_channel,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001778 algorithm_buffer_.get(), &samples_added);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001779 stats_.PreemptiveExpandedSamples(samples_added);
1780 switch (return_code) {
1781 case PreemptiveExpand::kSuccess:
1782 last_mode_ = kModePreemptiveExpandSuccess;
1783 break;
1784 case PreemptiveExpand::kSuccessLowEnergy:
1785 last_mode_ = kModePreemptiveExpandLowEnergy;
1786 break;
1787 case PreemptiveExpand::kNoStretch:
1788 last_mode_ = kModePreemptiveExpandFail;
1789 break;
1790 case PreemptiveExpand::kError:
1791 // TODO(hlundin): Map to kModeError instead?
1792 last_mode_ = kModePreemptiveExpandFail;
1793 return kPreemptiveExpandError;
1794 }
1795
1796 if (borrowed_samples_per_channel > 0) {
1797 // Copy borrowed samples back to the |sync_buffer_|.
1798 sync_buffer_->ReplaceAtIndex(
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001799 *algorithm_buffer_, borrowed_samples_per_channel,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001800 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001801 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001802 }
1803
1804 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1805 if (speech_type == AudioDecoder::kComfortNoise) {
1806 last_mode_ = kModeCodecInternalCng;
1807 }
1808 if (!play_dtmf) {
1809 dtmf_tone_generator_->Reset();
1810 }
1811 expand_->Reset();
1812 return 0;
1813}
1814
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001815int NetEqImpl::DoRfc3389Cng(PacketList* packet_list, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001816 if (!packet_list->empty()) {
1817 // Must have exactly one SID frame at this point.
1818 assert(packet_list->size() == 1);
ossua73f6c92016-10-24 08:25:28 -07001819 const Packet& packet = packet_list->front();
1820 if (!decoder_database_->IsComfortNoise(packet.payload_type)) {
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001821 LOG(LS_ERROR) << "Trying to decode non-CNG payload as CNG.";
1822 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001823 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001824 if (comfort_noise_->UpdateParameters(packet) ==
1825 ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001826 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001827 return -comfort_noise_->internal_error_code();
1828 }
1829 }
1830 int cn_return = comfort_noise_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001831 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001832 expand_->Reset();
1833 last_mode_ = kModeRfc3389Cng;
1834 if (!play_dtmf) {
1835 dtmf_tone_generator_->Reset();
1836 }
1837 if (cn_return == ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001838 decoder_error_code_ = comfort_noise_->internal_error_code();
1839 return kComfortNoiseErrorCode;
1840 } else if (cn_return == ComfortNoise::kUnknownPayloadType) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001841 return kUnknownRtpPayloadType;
1842 }
1843 return 0;
1844}
1845
minyuel6d92bf52015-09-23 15:20:39 +02001846void NetEqImpl::DoCodecInternalCng(const int16_t* decoded_buffer,
1847 size_t decoded_length) {
1848 RTC_DCHECK(normal_.get());
1849 RTC_DCHECK(mute_factor_array_.get());
1850 normal_->Process(decoded_buffer, decoded_length, last_mode_,
1851 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001852 last_mode_ = kModeCodecInternalCng;
1853 expand_->Reset();
1854}
1855
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001856int NetEqImpl::DoDtmf(const DtmfEvent& dtmf_event, bool* play_dtmf) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001857 // This block of the code and the block further down, handling |dtmf_switch|
1858 // are commented out. Otherwise playing out-of-band DTMF would fail in VoE
1859 // test, DtmfTest.ManualSuccessfullySendsOutOfBandTelephoneEvents. This is
1860 // equivalent to |dtmf_switch| always be false.
1861 //
1862 // See http://webrtc-codereview.appspot.com/1195004/ for discussion
1863 // On this issue. This change might cause some glitches at the point of
1864 // switch from audio to DTMF. Issue 1545 is filed to track this.
1865 //
1866 // bool dtmf_switch = false;
1867 // if ((last_mode_ != kModeDtmf) && dtmf_tone_generator_->initialized()) {
1868 // // Special case; see below.
1869 // // We must catch this before calling Generate, since |initialized| is
1870 // // modified in that call.
1871 // dtmf_switch = true;
1872 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001873
1874 int dtmf_return_value = 0;
1875 if (!dtmf_tone_generator_->initialized()) {
1876 // Initialize if not already done.
1877 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1878 dtmf_event.volume);
1879 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001880
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001881 if (dtmf_return_value == 0) {
1882 // Generate DTMF signal.
1883 dtmf_return_value = dtmf_tone_generator_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001884 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001885 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001886
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001887 if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001888 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001889 return dtmf_return_value;
1890 }
1891
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001892 // if (dtmf_switch) {
1893 // // This is the special case where the previous operation was DTMF
1894 // // overdub, but the current instruction is "regular" DTMF. We must make
1895 // // sure that the DTMF does not have any discontinuities. The first DTMF
1896 // // sample that we generate now must be played out immediately, therefore
1897 // // it must be copied to the speech buffer.
1898 // // TODO(hlundin): This code seems incorrect. (Legacy.) Write test and
1899 // // verify correct operation.
1900 // assert(false);
1901 // // Must generate enough data to replace all of the |sync_buffer_|
1902 // // "future".
1903 // int required_length = sync_buffer_->FutureLength();
1904 // assert(dtmf_tone_generator_->initialized());
1905 // dtmf_return_value = dtmf_tone_generator_->Generate(required_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001906 // algorithm_buffer_);
1907 // assert((size_t) required_length == algorithm_buffer_->Size());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001908 // if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001909 // algorithm_buffer_->Zeros(output_size_samples_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001910 // return dtmf_return_value;
1911 // }
1912 //
1913 // // Overwrite the "future" part of the speech buffer with the new DTMF
1914 // // data.
1915 // // TODO(hlundin): It seems that this overwriting has gone lost.
1916 // // Not adapted for multi-channel yet.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001917 // assert(algorithm_buffer_->Channels() == 1);
1918 // if (algorithm_buffer_->Channels() != 1) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001919 // LOG(LS_WARNING) << "DTMF not supported for more than one channel";
1920 // return kStereoNotSupported;
1921 // }
1922 // // Shuffle the remaining data to the beginning of algorithm buffer.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001923 // algorithm_buffer_->PopFront(sync_buffer_->FutureLength());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001924 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001925
Peter Kastingb7e50542015-06-11 12:55:50 -07001926 sync_buffer_->IncreaseEndTimestamp(
1927 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001928 expand_->Reset();
1929 last_mode_ = kModeDtmf;
1930
1931 // Set to false because the DTMF is already in the algorithm buffer.
1932 *play_dtmf = false;
1933 return 0;
1934}
1935
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001936void NetEqImpl::DoAlternativePlc(bool increase_timestamp) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001937 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001938 size_t length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001939 if (decoder && decoder->HasDecodePlc()) {
1940 // Use the decoder's packet-loss concealment.
1941 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1942 int16_t decoded_buffer[kMaxFrameSize];
1943 length = decoder->DecodePlc(1, decoded_buffer);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001944 if (length > 0)
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001945 algorithm_buffer_->PushBackInterleaved(decoded_buffer, length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001946 } else {
1947 // Do simple zero-stuffing.
1948 length = output_size_samples_;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001949 algorithm_buffer_->Zeros(length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001950 // By not advancing the timestamp, NetEq inserts samples.
1951 stats_.AddZeros(length);
1952 }
1953 if (increase_timestamp) {
Peter Kastingb7e50542015-06-11 12:55:50 -07001954 sync_buffer_->IncreaseEndTimestamp(static_cast<uint32_t>(length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001955 }
1956 expand_->Reset();
1957}
1958
1959int NetEqImpl::DtmfOverdub(const DtmfEvent& dtmf_event, size_t num_channels,
1960 int16_t* output) const {
1961 size_t out_index = 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001962 size_t overdub_length = output_size_samples_; // Default value.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001963
1964 if (sync_buffer_->dtmf_index() > sync_buffer_->next_index()) {
1965 // Special operation for transition from "DTMF only" to "DTMF overdub".
1966 out_index = std::min(
1967 sync_buffer_->dtmf_index() - sync_buffer_->next_index(),
Peter Kastingdce40cf2015-08-24 14:52:23 -07001968 output_size_samples_);
1969 overdub_length = output_size_samples_ - out_index;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001970 }
1971
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001972 AudioMultiVector dtmf_output(num_channels);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001973 int dtmf_return_value = 0;
1974 if (!dtmf_tone_generator_->initialized()) {
1975 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1976 dtmf_event.volume);
1977 }
1978 if (dtmf_return_value == 0) {
1979 dtmf_return_value = dtmf_tone_generator_->Generate(overdub_length,
1980 &dtmf_output);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001981 assert(overdub_length == dtmf_output.Size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001982 }
1983 dtmf_output.ReadInterleaved(overdub_length, &output[out_index]);
1984 return dtmf_return_value < 0 ? dtmf_return_value : 0;
1985}
1986
Peter Kastingdce40cf2015-08-24 14:52:23 -07001987int NetEqImpl::ExtractPackets(size_t required_samples,
1988 PacketList* packet_list) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001989 bool first_packet = true;
1990 uint8_t prev_payload_type = 0;
1991 uint32_t prev_timestamp = 0;
1992 uint16_t prev_sequence_number = 0;
1993 bool next_packet_available = false;
1994
ossu7a377612016-10-18 04:06:13 -07001995 const Packet* next_packet = packet_buffer_->PeekNextPacket();
1996 RTC_DCHECK(next_packet);
1997 if (!next_packet) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001998 LOG(LS_ERROR) << "Packet buffer unexpectedly empty.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001999 return -1;
2000 }
ossu7a377612016-10-18 04:06:13 -07002001 uint32_t first_timestamp = next_packet->timestamp;
ossu61a208b2016-09-20 01:38:00 -07002002 size_t extracted_samples = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002003
2004 // Packet extraction loop.
2005 do {
ossu7a377612016-10-18 04:06:13 -07002006 timestamp_ = next_packet->timestamp;
ossua73f6c92016-10-24 08:25:28 -07002007 rtc::Optional<Packet> packet = packet_buffer_->GetNextPacket();
ossu7a377612016-10-18 04:06:13 -07002008 // |next_packet| may be invalid after the |packet_buffer_| operation.
ossua73f6c92016-10-24 08:25:28 -07002009 next_packet = nullptr;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002010 if (!packet) {
Henrik Lundind67a2192015-08-03 12:54:37 +02002011 LOG(LS_ERROR) << "Should always be able to extract a packet here";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002012 assert(false); // Should always be able to extract a packet here.
2013 return -1;
2014 }
henrik.lundin84f8cd62016-04-26 07:45:16 -07002015 stats_.StoreWaitingTime(packet->waiting_time->ElapsedMs());
ossu61a208b2016-09-20 01:38:00 -07002016 RTC_DCHECK(!packet->empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002017
2018 if (first_packet) {
2019 first_packet = false;
henrik.lundin48ed9302015-10-29 05:36:24 -07002020 if (nack_enabled_) {
2021 RTC_DCHECK(nack_);
2022 // TODO(henrik.lundin): Should we update this for all decoded packets?
ossu7a377612016-10-18 04:06:13 -07002023 nack_->UpdateLastDecodedPacket(packet->sequence_number,
2024 packet->timestamp);
henrik.lundin48ed9302015-10-29 05:36:24 -07002025 }
ossu7a377612016-10-18 04:06:13 -07002026 prev_sequence_number = packet->sequence_number;
2027 prev_timestamp = packet->timestamp;
2028 prev_payload_type = packet->payload_type;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002029 }
2030
ossucafb4972017-01-02 07:00:50 -08002031 const bool has_cng_packet =
2032 decoder_database_->IsComfortNoise(packet->payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002033 // Store number of extracted samples.
ossu61a208b2016-09-20 01:38:00 -07002034 size_t packet_duration = 0;
2035 if (packet->frame) {
2036 packet_duration = packet->frame->Duration();
ossua70695a2016-09-22 02:06:28 -07002037 // TODO(ossu): Is this the correct way to track Opus FEC packets?
2038 if (packet->priority.codec_level > 0) {
kwibergd3edd772017-03-01 18:52:48 -08002039 stats_.SecondaryDecodedSamples(
2040 rtc::dchecked_cast<int>(packet_duration));
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00002041 }
ossucafb4972017-01-02 07:00:50 -08002042 } else if (!has_cng_packet) {
Henrik Lundind67a2192015-08-03 12:54:37 +02002043 LOG(LS_WARNING) << "Unknown payload type "
ossu7a377612016-10-18 04:06:13 -07002044 << static_cast<int>(packet->payload_type);
ossu61a208b2016-09-20 01:38:00 -07002045 RTC_NOTREACHED();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002046 }
ossu61a208b2016-09-20 01:38:00 -07002047
2048 if (packet_duration == 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002049 // Decoder did not return a packet duration. Assume that the packet
2050 // contains the same number of samples as the previous one.
ossu61a208b2016-09-20 01:38:00 -07002051 packet_duration = decoder_frame_length_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002052 }
ossu7a377612016-10-18 04:06:13 -07002053 extracted_samples = packet->timestamp - first_timestamp + packet_duration;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002054
ossua73f6c92016-10-24 08:25:28 -07002055 packet_list->push_back(std::move(*packet)); // Store packet in list.
2056 packet = rtc::Optional<Packet>(); // Ensure it's never used after the move.
2057
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002058 // Check what packet is available next.
ossu7a377612016-10-18 04:06:13 -07002059 next_packet = packet_buffer_->PeekNextPacket();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002060 next_packet_available = false;
ossucafb4972017-01-02 07:00:50 -08002061 if (next_packet && prev_payload_type == next_packet->payload_type &&
2062 !has_cng_packet) {
ossu7a377612016-10-18 04:06:13 -07002063 int16_t seq_no_diff = next_packet->sequence_number - prev_sequence_number;
2064 size_t ts_diff = next_packet->timestamp - prev_timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002065 if (seq_no_diff == 1 ||
2066 (seq_no_diff == 0 && ts_diff == decoder_frame_length_)) {
2067 // The next sequence number is available, or the next part of a packet
2068 // that was split into pieces upon insertion.
2069 next_packet_available = true;
2070 }
ossu7a377612016-10-18 04:06:13 -07002071 prev_sequence_number = next_packet->sequence_number;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002072 }
ossu61a208b2016-09-20 01:38:00 -07002073 } while (extracted_samples < required_samples && next_packet_available);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002074
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00002075 if (extracted_samples > 0) {
2076 // Delete old packets only when we are going to decode something. Otherwise,
2077 // we could end up in the situation where we never decode anything, since
2078 // all incoming packets are considered too old but the buffer will also
2079 // never be flooded and flushed.
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00002080 packet_buffer_->DiscardAllOldPackets(timestamp_);
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00002081 }
2082
kwibergd3edd772017-03-01 18:52:48 -08002083 return rtc::dchecked_cast<int>(extracted_samples);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002084}
2085
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002086void NetEqImpl::UpdatePlcComponents(int fs_hz, size_t channels) {
2087 // Delete objects and create new ones.
2088 expand_.reset(expand_factory_->Create(background_noise_.get(),
2089 sync_buffer_.get(), &random_vector_,
Henrik Lundinbef77e22015-08-18 14:58:09 +02002090 &stats_, fs_hz, channels));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002091 merge_.reset(new Merge(fs_hz, channels, expand_.get(), sync_buffer_.get()));
2092}
2093
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002094void NetEqImpl::SetSampleRateAndChannels(int fs_hz, size_t channels) {
Henrik Lundind67a2192015-08-03 12:54:37 +02002095 LOG(LS_VERBOSE) << "SetSampleRateAndChannels " << fs_hz << " " << channels;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002096 // TODO(hlundin): Change to an enumerator and skip assert.
2097 assert(fs_hz == 8000 || fs_hz == 16000 || fs_hz == 32000 || fs_hz == 48000);
2098 assert(channels > 0);
2099
2100 fs_hz_ = fs_hz;
2101 fs_mult_ = fs_hz / 8000;
Peter Kastingdce40cf2015-08-24 14:52:23 -07002102 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002103 decoder_frame_length_ = 3 * output_size_samples_; // Initialize to 30ms.
2104
2105 last_mode_ = kModeNormal;
2106
2107 // Create a new array of mute factors and set all to 1.
2108 mute_factor_array_.reset(new int16_t[channels]);
2109 for (size_t i = 0; i < channels; ++i) {
2110 mute_factor_array_[i] = 16384; // 1.0 in Q14.
2111 }
2112
ossu97ba30e2016-04-25 07:55:58 -07002113 ComfortNoiseDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02002114 if (cng_decoder)
2115 cng_decoder->Reset();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002116
2117 // Reinit post-decode VAD with new sample rate.
2118 assert(vad_.get()); // Cannot be NULL here.
2119 vad_->Init();
2120
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002121 // Delete algorithm buffer and create a new one.
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00002122 algorithm_buffer_.reset(new AudioMultiVector(channels));
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002123
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002124 // Delete sync buffer and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002125 sync_buffer_.reset(new SyncBuffer(channels, kSyncBufferSize * fs_mult_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002126
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00002127 // Delete BackgroundNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002128 background_noise_.reset(new BackgroundNoise(channels));
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00002129 background_noise_->set_mode(background_noise_mode_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002130
2131 // Reset random vector.
2132 random_vector_.Reset();
2133
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002134 UpdatePlcComponents(fs_hz, channels);
2135
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002136 // Move index so that we create a small set of future samples (all 0).
2137 sync_buffer_->set_next_index(sync_buffer_->next_index() -
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002138 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002139
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002140 normal_.reset(new Normal(fs_hz, decoder_database_.get(), *background_noise_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002141 expand_.get()));
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +00002142 accelerate_.reset(
2143 accelerate_factory_->Create(fs_hz, channels, *background_noise_));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002144 preemptive_expand_.reset(preemptive_expand_factory_->Create(
Peter Kastingdce40cf2015-08-24 14:52:23 -07002145 fs_hz, channels, *background_noise_, expand_->overlap_length()));
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002146
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002147 // Delete ComfortNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002148 comfort_noise_.reset(new ComfortNoise(fs_hz, decoder_database_.get(),
2149 sync_buffer_.get()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002150
2151 // Verify that |decoded_buffer_| is long enough.
2152 if (decoded_buffer_length_ < kMaxFrameSize * channels) {
2153 // Reallocate to larger size.
2154 decoded_buffer_length_ = kMaxFrameSize * channels;
2155 decoded_buffer_.reset(new int16_t[decoded_buffer_length_]);
2156 }
2157
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002158 // Create DecisionLogic if it is not created yet, then communicate new sample
2159 // rate and output size to DecisionLogic object.
2160 if (!decision_logic_.get()) {
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002161 CreateDecisionLogic();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002162 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002163 decision_logic_->SetSampleRate(fs_hz_, output_size_samples_);
2164}
2165
henrik.lundin55480f52016-03-08 02:37:57 -08002166NetEqImpl::OutputType NetEqImpl::LastOutputType() {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002167 assert(vad_.get());
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002168 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002169 if (last_mode_ == kModeCodecInternalCng || last_mode_ == kModeRfc3389Cng) {
henrik.lundin55480f52016-03-08 02:37:57 -08002170 return OutputType::kCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002171 } else if (last_mode_ == kModeExpand && expand_->MuteFactor(0) == 0) {
2172 // Expand mode has faded down to background noise only (very long expand).
henrik.lundin55480f52016-03-08 02:37:57 -08002173 return OutputType::kPLCCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002174 } else if (last_mode_ == kModeExpand) {
henrik.lundin55480f52016-03-08 02:37:57 -08002175 return OutputType::kPLC;
wu@webrtc.org24301a62013-12-13 19:17:43 +00002176 } else if (vad_->running() && !vad_->active_speech()) {
henrik.lundin55480f52016-03-08 02:37:57 -08002177 return OutputType::kVadPassive;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002178 } else {
henrik.lundin55480f52016-03-08 02:37:57 -08002179 return OutputType::kNormalSpeech;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002180 }
2181}
2182
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002183void NetEqImpl::CreateDecisionLogic() {
Henrik Lundin47b17dc2016-05-10 10:20:59 +02002184 decision_logic_.reset(DecisionLogic::Create(
2185 fs_hz_, output_size_samples_, playout_mode_, decoder_database_.get(),
2186 *packet_buffer_.get(), delay_manager_.get(), buffer_level_filter_.get(),
2187 tick_timer_.get()));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002188}
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002189} // namespace webrtc