blob: ca20e5ba6d15e56ade17f584ce4e107406cfe127 [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
henrik.lundin9c3efd02015-08-27 13:12:22 -070020#include "webrtc/base/checks.h"
Henrik Lundind67a2192015-08-03 12:54:37 +020021#include "webrtc/base/logging.h"
Tommid44c0772016-03-11 17:12:32 -080022#include "webrtc/base/safe_conversions.h"
kwibergac554ee2016-09-02 00:39:33 -070023#include "webrtc/base/sanitizer.h"
henrik.lundina689b442015-12-17 03:50:05 -080024#include "webrtc/base/trace_event.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000025#include "webrtc/common_audio/signal_processing/include/signal_processing_library.h"
kwiberg@webrtc.orge04a93b2014-12-09 10:12:53 +000026#include "webrtc/modules/audio_coding/codecs/audio_decoder.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"
42#include "webrtc/modules/audio_coding/neteq/packet_buffer.h"
43#include "webrtc/modules/audio_coding/neteq/packet.h"
44#include "webrtc/modules/audio_coding/neteq/payload_splitter.h"
45#include "webrtc/modules/audio_coding/neteq/post_decode_vad.h"
46#include "webrtc/modules/audio_coding/neteq/preemptive_expand.h"
47#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())),
68 payload_splitter(new PayloadSplitter),
69 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)),
87 payload_splitter_(std::move(deps.payload_splitter)),
88 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
134int NetEqImpl::InsertPacket(const WebRtcRTPHeader& 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.lundin500c04b2016-03-08 02:36:04 -0800149namespace {
150void SetAudioFrameActivityAndType(bool vad_enabled,
henrik.lundin55480f52016-03-08 02:37:57 -0800151 NetEqImpl::OutputType type,
henrik.lundin500c04b2016-03-08 02:36:04 -0800152 AudioFrame::VADActivity last_vad_activity,
153 AudioFrame* audio_frame) {
154 switch (type) {
henrik.lundin55480f52016-03-08 02:37:57 -0800155 case NetEqImpl::OutputType::kNormalSpeech: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800156 audio_frame->speech_type_ = AudioFrame::kNormalSpeech;
157 audio_frame->vad_activity_ = AudioFrame::kVadActive;
158 break;
159 }
henrik.lundin55480f52016-03-08 02:37:57 -0800160 case NetEqImpl::OutputType::kVadPassive: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800161 // This should only be reached if the VAD is enabled.
162 RTC_DCHECK(vad_enabled);
163 audio_frame->speech_type_ = AudioFrame::kNormalSpeech;
164 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
165 break;
166 }
henrik.lundin55480f52016-03-08 02:37:57 -0800167 case NetEqImpl::OutputType::kCNG: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800168 audio_frame->speech_type_ = AudioFrame::kCNG;
169 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
170 break;
171 }
henrik.lundin55480f52016-03-08 02:37:57 -0800172 case NetEqImpl::OutputType::kPLC: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800173 audio_frame->speech_type_ = AudioFrame::kPLC;
174 audio_frame->vad_activity_ = last_vad_activity;
175 break;
176 }
henrik.lundin55480f52016-03-08 02:37:57 -0800177 case NetEqImpl::OutputType::kPLCCNG: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800178 audio_frame->speech_type_ = AudioFrame::kPLCCNG;
179 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
180 break;
181 }
182 default:
183 RTC_NOTREACHED();
184 }
185 if (!vad_enabled) {
186 // Always set kVadUnknown when receive VAD is inactive.
187 audio_frame->vad_activity_ = AudioFrame::kVadUnknown;
188 }
189}
henrik.lundinbc89de32016-03-08 05:20:14 -0800190} // namespace
henrik.lundin500c04b2016-03-08 02:36:04 -0800191
henrik.lundin7a926812016-05-12 13:51:28 -0700192int NetEqImpl::GetAudio(AudioFrame* audio_frame, bool* muted) {
henrik.lundine1ca1672016-01-08 03:50:08 -0800193 TRACE_EVENT0("webrtc", "NetEqImpl::GetAudio");
Tommi9090e0b2016-01-20 13:39:36 +0100194 rtc::CritScope lock(&crit_sect_);
henrik.lundin7a926812016-05-12 13:51:28 -0700195 int error = GetAudioInternal(audio_frame, muted);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000196 if (error != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000197 error_code_ = error;
198 return kFail;
199 }
henrik.lundin5fac3f02016-08-24 11:18:49 -0700200 RTC_DCHECK_EQ(
201 audio_frame->sample_rate_hz_,
202 rtc::checked_cast<int>(audio_frame->samples_per_channel_ * 100));
henrik.lundin500c04b2016-03-08 02:36:04 -0800203 SetAudioFrameActivityAndType(vad_->enabled(), LastOutputType(),
204 last_vad_activity_, audio_frame);
205 last_vad_activity_ = audio_frame->vad_activity_;
henrik.lundin6d8e0112016-03-04 10:34:21 -0800206 last_output_sample_rate_hz_ = audio_frame->sample_rate_hz_;
henrik.lundind89814b2015-11-23 06:49:25 -0800207 RTC_DCHECK(last_output_sample_rate_hz_ == 8000 ||
208 last_output_sample_rate_hz_ == 16000 ||
209 last_output_sample_rate_hz_ == 32000 ||
210 last_output_sample_rate_hz_ == 48000)
211 << "Unexpected sample rate " << last_output_sample_rate_hz_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000212 return kOK;
213}
214
kwibergee1879c2015-10-29 06:20:28 -0700215int NetEqImpl::RegisterPayloadType(NetEqDecoder codec,
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800216 const std::string& name,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000217 uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100218 rtc::CritScope lock(&crit_sect_);
Henrik Lundind67a2192015-08-03 12:54:37 +0200219 LOG(LS_VERBOSE) << "RegisterPayloadType "
kwibergee1879c2015-10-29 06:20:28 -0700220 << static_cast<int>(rtp_payload_type) << " "
221 << static_cast<int>(codec);
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800222 int ret = decoder_database_->RegisterPayload(rtp_payload_type, codec, name);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000223 if (ret != DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000224 switch (ret) {
225 case DecoderDatabase::kInvalidRtpPayloadType:
226 error_code_ = kInvalidRtpPayloadType;
227 break;
228 case DecoderDatabase::kCodecNotSupported:
229 error_code_ = kCodecNotSupported;
230 break;
231 case DecoderDatabase::kDecoderExists:
232 error_code_ = kDecoderExists;
233 break;
234 default:
235 error_code_ = kOtherError;
236 }
237 return kFail;
238 }
239 return kOK;
240}
241
242int NetEqImpl::RegisterExternalDecoder(AudioDecoder* decoder,
kwibergee1879c2015-10-29 06:20:28 -0700243 NetEqDecoder codec,
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800244 const std::string& codec_name,
kwiberg342f7402016-06-16 03:18:00 -0700245 uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100246 rtc::CritScope lock(&crit_sect_);
Henrik Lundind67a2192015-08-03 12:54:37 +0200247 LOG(LS_VERBOSE) << "RegisterExternalDecoder "
kwibergee1879c2015-10-29 06:20:28 -0700248 << static_cast<int>(rtp_payload_type) << " "
249 << static_cast<int>(codec);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000250 if (!decoder) {
251 LOG(LS_ERROR) << "Cannot register external decoder with NULL pointer";
252 assert(false);
253 return kFail;
254 }
kwiberg342f7402016-06-16 03:18:00 -0700255 int ret = decoder_database_->InsertExternal(rtp_payload_type, codec,
256 codec_name, decoder);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000257 if (ret != DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000258 switch (ret) {
259 case DecoderDatabase::kInvalidRtpPayloadType:
260 error_code_ = kInvalidRtpPayloadType;
261 break;
262 case DecoderDatabase::kCodecNotSupported:
263 error_code_ = kCodecNotSupported;
264 break;
265 case DecoderDatabase::kDecoderExists:
266 error_code_ = kDecoderExists;
267 break;
268 case DecoderDatabase::kInvalidSampleRate:
269 error_code_ = kInvalidSampleRate;
270 break;
271 case DecoderDatabase::kInvalidPointer:
272 error_code_ = kInvalidPointer;
273 break;
274 default:
275 error_code_ = kOtherError;
276 }
277 return kFail;
278 }
279 return kOK;
280}
281
282int NetEqImpl::RemovePayloadType(uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100283 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000284 int ret = decoder_database_->Remove(rtp_payload_type);
285 if (ret == DecoderDatabase::kOK) {
ossu61a208b2016-09-20 01:38:00 -0700286 packet_buffer_->DiscardPacketsWithPayloadType(rtp_payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000287 return kOK;
288 } else if (ret == DecoderDatabase::kDecoderNotFound) {
289 error_code_ = kDecoderNotFound;
290 } else {
291 error_code_ = kOtherError;
292 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000293 return kFail;
294}
295
kwiberg6b19b562016-09-20 04:02:25 -0700296void NetEqImpl::RemoveAllPayloadTypes() {
297 rtc::CritScope lock(&crit_sect_);
298 decoder_database_->RemoveAll();
299}
300
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000301bool NetEqImpl::SetMinimumDelay(int delay_ms) {
Tommi9090e0b2016-01-20 13:39:36 +0100302 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000303 if (delay_ms >= 0 && delay_ms < 10000) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000304 assert(delay_manager_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000305 return delay_manager_->SetMinimumDelay(delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000306 }
307 return false;
308}
309
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000310bool NetEqImpl::SetMaximumDelay(int delay_ms) {
Tommi9090e0b2016-01-20 13:39:36 +0100311 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000312 if (delay_ms >= 0 && delay_ms < 10000) {
313 assert(delay_manager_.get());
314 return delay_manager_->SetMaximumDelay(delay_ms);
315 }
316 return false;
317}
318
319int NetEqImpl::LeastRequiredDelayMs() const {
Tommi9090e0b2016-01-20 13:39:36 +0100320 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000321 assert(delay_manager_.get());
322 return delay_manager_->least_required_delay_ms();
323}
324
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200325int NetEqImpl::SetTargetDelay() {
326 return kNotImplemented;
327}
328
329int NetEqImpl::TargetDelay() {
330 return kNotImplemented;
331}
332
henrik.lundin9c3efd02015-08-27 13:12:22 -0700333int NetEqImpl::CurrentDelayMs() const {
Tommi9090e0b2016-01-20 13:39:36 +0100334 rtc::CritScope lock(&crit_sect_);
henrik.lundin9c3efd02015-08-27 13:12:22 -0700335 if (fs_hz_ == 0)
336 return 0;
337 // Sum up the samples in the packet buffer with the future length of the sync
338 // buffer, and divide the sum by the sample rate.
339 const size_t delay_samples =
ossu61a208b2016-09-20 01:38:00 -0700340 packet_buffer_->NumSamplesInBuffer(decoder_frame_length_) +
henrik.lundin9c3efd02015-08-27 13:12:22 -0700341 sync_buffer_->FutureLength();
342 // The division below will truncate.
343 const int delay_ms =
344 static_cast<int>(delay_samples) / rtc::CheckedDivExact(fs_hz_, 1000);
345 return delay_ms;
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200346}
347
henrik.lundinb3f1c5d2016-08-22 15:39:53 -0700348int NetEqImpl::FilteredCurrentDelayMs() const {
349 rtc::CritScope lock(&crit_sect_);
350 // Calculate the filtered packet buffer level in samples. The value from
351 // |buffer_level_filter_| is in number of packets, represented in Q8.
352 const size_t packet_buffer_samples =
353 (buffer_level_filter_->filtered_current_level() *
354 decoder_frame_length_) >>
355 8;
356 // Sum up the filtered packet buffer level with the future length of the sync
357 // buffer, and divide the sum by the sample rate.
358 const size_t delay_samples =
359 packet_buffer_samples + sync_buffer_->FutureLength();
360 // The division below will truncate. The return value is in ms.
361 return static_cast<int>(delay_samples) / rtc::CheckedDivExact(fs_hz_, 1000);
362}
363
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000364// Deprecated.
365// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000366void NetEqImpl::SetPlayoutMode(NetEqPlayoutMode mode) {
Tommi9090e0b2016-01-20 13:39:36 +0100367 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000368 if (mode != playout_mode_) {
369 playout_mode_ = mode;
370 CreateDecisionLogic();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000371 }
372}
373
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000374// Deprecated.
375// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000376NetEqPlayoutMode NetEqImpl::PlayoutMode() const {
Tommi9090e0b2016-01-20 13:39:36 +0100377 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000378 return playout_mode_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000379}
380
381int NetEqImpl::NetworkStatistics(NetEqNetworkStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100382 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000383 assert(decoder_database_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700384 const size_t total_samples_in_buffers =
ossu61a208b2016-09-20 01:38:00 -0700385 packet_buffer_->NumSamplesInBuffer(decoder_frame_length_) +
Peter Kastingdce40cf2015-08-24 14:52:23 -0700386 sync_buffer_->FutureLength();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000387 assert(delay_manager_.get());
388 assert(decision_logic_.get());
389 stats_.GetNetworkStatistics(fs_hz_, total_samples_in_buffers,
390 decoder_frame_length_, *delay_manager_.get(),
391 *decision_logic_.get(), stats);
392 return 0;
393}
394
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000395void NetEqImpl::GetRtcpStatistics(RtcpStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100396 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000397 if (stats) {
398 rtcp_.GetStatistics(false, stats);
399 }
400}
401
402void NetEqImpl::GetRtcpStatisticsNoReset(RtcpStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100403 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000404 if (stats) {
405 rtcp_.GetStatistics(true, stats);
406 }
407}
408
409void NetEqImpl::EnableVad() {
Tommi9090e0b2016-01-20 13:39:36 +0100410 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000411 assert(vad_.get());
412 vad_->Enable();
413}
414
415void NetEqImpl::DisableVad() {
Tommi9090e0b2016-01-20 13:39:36 +0100416 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000417 assert(vad_.get());
418 vad_->Disable();
419}
420
henrik.lundin15c51e32016-04-06 08:38:56 -0700421rtc::Optional<uint32_t> NetEqImpl::GetPlayoutTimestamp() const {
Tommi9090e0b2016-01-20 13:39:36 +0100422 rtc::CritScope lock(&crit_sect_);
henrik.lundin0d96ab72016-04-06 12:28:26 -0700423 if (first_packet_ || last_mode_ == kModeRfc3389Cng ||
424 last_mode_ == kModeCodecInternalCng) {
wu@webrtc.org94454b72014-06-05 20:34:08 +0000425 // We don't have a valid RTP timestamp until we have decoded our first
henrik.lundin0d96ab72016-04-06 12:28:26 -0700426 // RTP packet. Also, the RTP timestamp is not accurate while playing CNG,
427 // which is indicated by returning an empty value.
henrik.lundin9a410dd2016-04-06 01:39:22 -0700428 return rtc::Optional<uint32_t>();
wu@webrtc.org94454b72014-06-05 20:34:08 +0000429 }
henrik.lundin9a410dd2016-04-06 01:39:22 -0700430 return rtc::Optional<uint32_t>(
431 timestamp_scaler_->ToExternal(playout_timestamp_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000432}
433
henrik.lundind89814b2015-11-23 06:49:25 -0800434int NetEqImpl::last_output_sample_rate_hz() const {
Tommi9090e0b2016-01-20 13:39:36 +0100435 rtc::CritScope lock(&crit_sect_);
henrik.lundind89814b2015-11-23 06:49:25 -0800436 return last_output_sample_rate_hz_;
437}
438
kwiberg6f0f6162016-09-20 03:07:46 -0700439rtc::Optional<CodecInst> NetEqImpl::GetDecoder(int payload_type) const {
440 rtc::CritScope lock(&crit_sect_);
441 const DecoderDatabase::DecoderInfo* di =
442 decoder_database_->GetDecoderInfo(payload_type);
443 if (!di) {
444 return rtc::Optional<CodecInst>();
445 }
446
447 // Create a CodecInst with some fields set. The remaining fields are zeroed,
448 // but we tell MSan to consider them uninitialized.
449 CodecInst ci = {0};
450 rtc::MsanMarkUninitialized(rtc::MakeArrayView(&ci, 1));
451 ci.pltype = payload_type;
452 std::strncpy(ci.plname, di->name.c_str(), sizeof(ci.plname));
453 ci.plname[sizeof(ci.plname) - 1] = '\0';
454 ci.plfreq = di->IsRed() || di->IsDtmf() ? 8000 : di->SampleRateHz();
455 AudioDecoder* const decoder = di->GetDecoder();
456 ci.channels = decoder ? decoder->Channels() : 1;
457 return rtc::Optional<CodecInst>(ci);
458}
459
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200460int NetEqImpl::SetTargetNumberOfChannels() {
461 return kNotImplemented;
462}
463
464int NetEqImpl::SetTargetSampleRate() {
465 return kNotImplemented;
466}
467
henrik.lundin@webrtc.orgb0f4b3d2014-11-04 08:53:10 +0000468int NetEqImpl::LastError() const {
Tommi9090e0b2016-01-20 13:39:36 +0100469 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000470 return error_code_;
471}
472
473int NetEqImpl::LastDecoderError() {
Tommi9090e0b2016-01-20 13:39:36 +0100474 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000475 return decoder_error_code_;
476}
477
478void NetEqImpl::FlushBuffers() {
Tommi9090e0b2016-01-20 13:39:36 +0100479 rtc::CritScope lock(&crit_sect_);
Henrik Lundind67a2192015-08-03 12:54:37 +0200480 LOG(LS_VERBOSE) << "FlushBuffers";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000481 packet_buffer_->Flush();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000482 assert(sync_buffer_.get());
483 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000484 sync_buffer_->Flush();
485 sync_buffer_->set_next_index(sync_buffer_->next_index() -
486 expand_->overlap_length());
487 // Set to wait for new codec.
488 first_packet_ = true;
489}
490
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000491void NetEqImpl::PacketBufferStatistics(int* current_num_packets,
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000492 int* max_num_packets) const {
Tommi9090e0b2016-01-20 13:39:36 +0100493 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000494 packet_buffer_->BufferStat(current_num_packets, max_num_packets);
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000495}
496
henrik.lundin48ed9302015-10-29 05:36:24 -0700497void NetEqImpl::EnableNack(size_t max_nack_list_size) {
Tommi9090e0b2016-01-20 13:39:36 +0100498 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700499 if (!nack_enabled_) {
500 const int kNackThresholdPackets = 2;
henrik.lundin91951862016-06-08 06:43:41 -0700501 nack_.reset(NackTracker::Create(kNackThresholdPackets));
henrik.lundin48ed9302015-10-29 05:36:24 -0700502 nack_enabled_ = true;
503 nack_->UpdateSampleRate(fs_hz_);
504 }
505 nack_->SetMaxNackListSize(max_nack_list_size);
506}
507
508void NetEqImpl::DisableNack() {
Tommi9090e0b2016-01-20 13:39:36 +0100509 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700510 nack_.reset();
511 nack_enabled_ = false;
512}
513
514std::vector<uint16_t> NetEqImpl::GetNackList(int64_t round_trip_time_ms) const {
Tommi9090e0b2016-01-20 13:39:36 +0100515 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700516 if (!nack_enabled_) {
517 return std::vector<uint16_t>();
518 }
519 RTC_DCHECK(nack_.get());
520 return nack_->GetNackList(round_trip_time_ms);
minyue@webrtc.orgd7301772013-08-29 00:58:14 +0000521}
522
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000523const SyncBuffer* NetEqImpl::sync_buffer_for_test() const {
Tommi9090e0b2016-01-20 13:39:36 +0100524 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000525 return sync_buffer_.get();
526}
527
minyue5bd33972016-05-02 04:46:11 -0700528Operations NetEqImpl::last_operation_for_test() const {
529 rtc::CritScope lock(&crit_sect_);
530 return last_operation_;
531}
532
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000533// Methods below this line are private.
534
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000535int NetEqImpl::InsertPacketInternal(const WebRtcRTPHeader& rtp_header,
kwibergee2bac22015-11-11 10:34:00 -0800536 rtc::ArrayView<const uint8_t> payload,
ossu17e3fa12016-09-08 04:52:55 -0700537 uint32_t receive_timestamp) {
kwibergee2bac22015-11-11 10:34:00 -0800538 if (payload.empty()) {
539 LOG_F(LS_ERROR) << "payload is empty";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000540 return kInvalidPointer;
541 }
ossu17e3fa12016-09-08 04:52:55 -0700542
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000543 PacketList packet_list;
544 RTPHeader main_header;
545 {
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000546 // Convert to Packet.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000547 // Create |packet| within this separate scope, since it should not be used
548 // directly once it's been inserted in the packet list. This way, |packet|
549 // is not defined outside of this block.
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000550 Packet* packet = new Packet;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000551 packet->header.markerBit = false;
552 packet->header.payloadType = rtp_header.header.payloadType;
553 packet->header.sequenceNumber = rtp_header.header.sequenceNumber;
554 packet->header.timestamp = rtp_header.header.timestamp;
555 packet->header.ssrc = rtp_header.header.ssrc;
556 packet->header.numCSRCs = 0;
ossudc431ce2016-08-31 08:51:13 -0700557 packet->payload.SetData(payload.data(), payload.size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000558 packet->primary = true;
henrik.lundin84f8cd62016-04-26 07:45:16 -0700559 // Waiting time will be set upon inserting the packet in the buffer.
560 RTC_DCHECK(!packet->waiting_time);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000561 // Insert packet in a packet list.
562 packet_list.push_back(packet);
563 // Save main payloads header for later.
564 memcpy(&main_header, &packet->header, sizeof(main_header));
565 }
566
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000567 bool update_sample_rate_and_channels = false;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000568 // Reinitialize NetEq if it's needed (changed SSRC or first call).
569 if ((main_header.ssrc != ssrc_) || first_packet_) {
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000570 // Note: |first_packet_| will be cleared further down in this method, once
571 // the packet has been successfully inserted into the packet buffer.
572
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000573 rtcp_.Init(main_header.sequenceNumber);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000574
575 // Flush the packet buffer and DTMF buffer.
576 packet_buffer_->Flush();
577 dtmf_buffer_->Flush();
578
579 // Store new SSRC.
580 ssrc_ = main_header.ssrc;
581
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000582 // Update audio buffer timestamp.
583 sync_buffer_->IncreaseEndTimestamp(main_header.timestamp - timestamp_);
584
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000585 // Update codecs.
586 timestamp_ = main_header.timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000587
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000588 // Reset timestamp scaling.
589 timestamp_scaler_->Reset();
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000590
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000591 // Trigger an update of sampling rate and the number of channels.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000592 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000593 }
594
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000595 // Update RTCP statistics, only for regular packets.
ossu17e3fa12016-09-08 04:52:55 -0700596 rtcp_.Update(main_header, receive_timestamp);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000597
598 // Check for RED payload type, and separate payloads into several packets.
599 if (decoder_database_->IsRed(main_header.payloadType)) {
600 if (payload_splitter_->SplitRed(&packet_list) != PayloadSplitter::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000601 PacketBuffer::DeleteAllPackets(&packet_list);
602 return kRedundancySplitError;
603 }
604 // Only accept a few RED payloads of the same type as the main data,
605 // DTMF events and CNG.
606 payload_splitter_->CheckRedPayloads(&packet_list, *decoder_database_);
607 // Update the stored main payload header since the main payload has now
608 // changed.
609 memcpy(&main_header, &packet_list.front()->header, sizeof(main_header));
610 }
611
612 // Check payload types.
613 if (decoder_database_->CheckPayloadTypes(packet_list) ==
614 DecoderDatabase::kDecoderNotFound) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000615 PacketBuffer::DeleteAllPackets(&packet_list);
616 return kUnknownRtpPayloadType;
617 }
618
619 // Scale timestamp to internal domain (only for some codecs).
620 timestamp_scaler_->ToInternal(&packet_list);
621
622 // Process DTMF payloads. Cycle through the list of packets, and pick out any
623 // DTMF payloads found.
624 PacketList::iterator it = packet_list.begin();
625 while (it != packet_list.end()) {
626 Packet* current_packet = (*it);
627 assert(current_packet);
ossudc431ce2016-08-31 08:51:13 -0700628 assert(!current_packet->payload.empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000629 if (decoder_database_->IsDtmf(current_packet->header.payloadType)) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000630 DtmfEvent event;
ossudc431ce2016-08-31 08:51:13 -0700631 int ret = DtmfBuffer::ParseEvent(current_packet->header.timestamp,
632 current_packet->payload.data(),
633 current_packet->payload.size(), &event);
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000634 if (ret != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000635 PacketBuffer::DeleteAllPackets(&packet_list);
636 return kDtmfParsingError;
637 }
638 if (dtmf_buffer_->InsertEvent(event) != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000639 PacketBuffer::DeleteAllPackets(&packet_list);
640 return kDtmfInsertError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000641 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000642 delete current_packet;
643 it = packet_list.erase(it);
644 } else {
645 ++it;
646 }
647 }
648
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000649 // Check for FEC in packets, and separate payloads into several packets.
650 int ret = payload_splitter_->SplitFec(&packet_list, decoder_database_.get());
651 if (ret != PayloadSplitter::kOK) {
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000652 PacketBuffer::DeleteAllPackets(&packet_list);
653 switch (ret) {
654 case PayloadSplitter::kUnknownPayloadType:
655 return kUnknownRtpPayloadType;
656 default:
657 return kOtherError;
658 }
659 }
660
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000661 // Split payloads into smaller chunks. This also verifies that all payloads
ossu17e3fa12016-09-08 04:52:55 -0700662 // are of a known payload type.
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +0000663 ret = payload_splitter_->SplitAudio(&packet_list, *decoder_database_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000664 if (ret != PayloadSplitter::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000665 PacketBuffer::DeleteAllPackets(&packet_list);
666 switch (ret) {
667 case PayloadSplitter::kUnknownPayloadType:
668 return kUnknownRtpPayloadType;
669 case PayloadSplitter::kFrameSplitError:
670 return kFrameSplitError;
671 default:
672 return kOtherError;
673 }
674 }
675
ossu17e3fa12016-09-08 04:52:55 -0700676 // Update bandwidth estimate, if the packet is not comfort noise.
677 if (!packet_list.empty() &&
ossu97ba30e2016-04-25 07:55:58 -0700678 !decoder_database_->IsComfortNoise(main_header.payloadType)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000679 // The list can be empty here if we got nothing but DTMF payloads.
680 AudioDecoder* decoder =
681 decoder_database_->GetDecoder(main_header.payloadType);
682 assert(decoder); // Should always get a valid object, since we have
ossu97ba30e2016-04-25 07:55:58 -0700683 // already checked that the payload types are known.
ossudc431ce2016-08-31 08:51:13 -0700684 decoder->IncomingPacket(packet_list.front()->payload.data(),
685 packet_list.front()->payload.size(),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000686 packet_list.front()->header.sequenceNumber,
687 packet_list.front()->header.timestamp,
688 receive_timestamp);
689 }
690
ossu61a208b2016-09-20 01:38:00 -0700691 PacketList parsed_packet_list;
692 while (!packet_list.empty()) {
693 std::unique_ptr<Packet> packet(packet_list.front());
694 packet_list.pop_front();
695 const DecoderDatabase::DecoderInfo* info =
696 decoder_database_->GetDecoderInfo(packet->header.payloadType);
697 if (!info) {
698 LOG(LS_WARNING) << "SplitAudio unknown payload type";
699 return kUnknownRtpPayloadType;
700 }
701
702 if (info->IsComfortNoise()) {
703 // Carry comfort noise packets along.
704 parsed_packet_list.push_back(packet.release());
705 } else {
706 std::vector<AudioDecoder::ParseResult> results =
707 info->GetDecoder()->ParsePayload(std::move(packet->payload),
708 packet->header.timestamp,
709 packet->primary);
710 const RTPHeader& original_header = packet->header;
711 for (auto& result : results) {
712 RTC_DCHECK(result.frame);
713 // Reuse the packet if possible
714 if (!packet) {
715 packet.reset(new Packet);
716 packet->header = original_header;
717 }
718 packet->header.timestamp = result.timestamp;
719 // TODO(ossu): Move from primary to some sort of priority level.
720 packet->primary = result.primary;
721 packet->frame = std::move(result.frame);
722 parsed_packet_list.push_back(packet.release());
723 }
724 }
725 }
726
henrik.lundin48ed9302015-10-29 05:36:24 -0700727 if (nack_enabled_) {
728 RTC_DCHECK(nack_);
729 if (update_sample_rate_and_channels) {
730 nack_->Reset();
731 }
ossu61a208b2016-09-20 01:38:00 -0700732 nack_->UpdateLastReceivedPacket(
733 parsed_packet_list.front()->header.sequenceNumber,
734 parsed_packet_list.front()->header.timestamp);
henrik.lundin48ed9302015-10-29 05:36:24 -0700735 }
736
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000737 // Insert packets in buffer.
henrik.lundin116c84e2015-08-27 13:14:48 -0700738 const size_t buffer_length_before_insert =
739 packet_buffer_->NumPacketsInBuffer();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000740 ret = packet_buffer_->InsertPacketList(
ossu61a208b2016-09-20 01:38:00 -0700741 &parsed_packet_list, *decoder_database_, &current_rtp_payload_type_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000742 &current_cng_rtp_payload_type_);
743 if (ret == PacketBuffer::kFlushed) {
744 // Reset DSP timestamp etc. if packet buffer flushed.
745 new_codec_ = true;
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000746 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000747 } else if (ret != PacketBuffer::kOK) {
ossu61a208b2016-09-20 01:38:00 -0700748 PacketBuffer::DeleteAllPackets(&parsed_packet_list);
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000749 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000750 }
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000751
752 if (first_packet_) {
753 first_packet_ = false;
754 // Update the codec on the next GetAudio call.
755 new_codec_ = true;
756 }
757
henrik.lundinda8bbf62016-08-31 03:14:11 -0700758 if (current_rtp_payload_type_) {
759 RTC_DCHECK(decoder_database_->GetDecoderInfo(*current_rtp_payload_type_))
760 << "Payload type " << static_cast<int>(*current_rtp_payload_type_)
761 << " is unknown where it shouldn't be";
762 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000763
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000764 if (update_sample_rate_and_channels && !packet_buffer_->Empty()) {
765 // We do not use |current_rtp_payload_type_| to |set payload_type|, but
766 // get the next RTP header from |packet_buffer_| to obtain the payload type.
767 // The reason for it is the following corner case. If NetEq receives a
768 // CNG packet with a sample rate different than the current CNG then it
769 // flushes its buffer, assuming send codec must have been changed. However,
770 // payload type of the hypothetically new send codec is not known.
771 const RTPHeader* rtp_header = packet_buffer_->NextRtpHeader();
772 assert(rtp_header);
773 int payload_type = rtp_header->payloadType;
ossu97ba30e2016-04-25 07:55:58 -0700774 size_t channels = 1;
775 if (!decoder_database_->IsComfortNoise(payload_type)) {
776 AudioDecoder* decoder = decoder_database_->GetDecoder(payload_type);
777 assert(decoder); // Payloads are already checked to be valid.
778 channels = decoder->Channels();
779 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000780 const DecoderDatabase::DecoderInfo* decoder_info =
781 decoder_database_->GetDecoderInfo(payload_type);
782 assert(decoder_info);
kwibergc0f2dcf2016-05-31 06:28:03 -0700783 if (decoder_info->SampleRateHz() != fs_hz_ ||
ossu97ba30e2016-04-25 07:55:58 -0700784 channels != algorithm_buffer_->Channels()) {
kwibergc0f2dcf2016-05-31 06:28:03 -0700785 SetSampleRateAndChannels(decoder_info->SampleRateHz(),
786 channels);
henrik.lundin48ed9302015-10-29 05:36:24 -0700787 }
788 if (nack_enabled_) {
789 RTC_DCHECK(nack_);
790 // Update the sample rate even if the rate is not new, because of Reset().
791 nack_->UpdateSampleRate(fs_hz_);
792 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000793 }
794
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000795 // TODO(hlundin): Move this code to DelayManager class.
796 const DecoderDatabase::DecoderInfo* dec_info =
797 decoder_database_->GetDecoderInfo(main_header.payloadType);
798 assert(dec_info); // Already checked that the payload type is known.
799 delay_manager_->LastDecoderType(dec_info->codec_type);
800 if (delay_manager_->last_pack_cng_or_dtmf() == 0) {
801 // Calculate the total speech length carried in each packet.
henrik.lundin116c84e2015-08-27 13:14:48 -0700802 const size_t buffer_length_after_insert =
803 packet_buffer_->NumPacketsInBuffer();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000804
henrik.lundin116c84e2015-08-27 13:14:48 -0700805 if (buffer_length_after_insert > buffer_length_before_insert) {
806 const size_t packet_length_samples =
807 (buffer_length_after_insert - buffer_length_before_insert) *
808 decoder_frame_length_;
809 if (packet_length_samples != decision_logic_->packet_length_samples()) {
810 decision_logic_->set_packet_length_samples(packet_length_samples);
811 delay_manager_->SetPacketAudioLength(
812 rtc::checked_cast<int>((1000 * packet_length_samples) / fs_hz_));
813 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000814 }
815
816 // Update statistics.
pbos@webrtc.org0946a562013-04-09 00:28:06 +0000817 if ((int32_t) (main_header.timestamp - timestamp_) >= 0 &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000818 !new_codec_) {
819 // Only update statistics if incoming packet is not older than last played
820 // out packet, and if new codec flag is not set.
821 delay_manager_->Update(main_header.sequenceNumber, main_header.timestamp,
822 fs_hz_);
823 }
824 } else if (delay_manager_->last_pack_cng_or_dtmf() == -1) {
825 // This is first "normal" packet after CNG or DTMF.
826 // Reset packet time counter and measure time until next packet,
827 // but don't update statistics.
828 delay_manager_->set_last_pack_cng_or_dtmf(0);
829 delay_manager_->ResetPacketIatCount();
830 }
831 return 0;
832}
833
henrik.lundin7a926812016-05-12 13:51:28 -0700834int NetEqImpl::GetAudioInternal(AudioFrame* audio_frame, bool* muted) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000835 PacketList packet_list;
836 DtmfEvent dtmf_event;
837 Operations operation;
838 bool play_dtmf;
henrik.lundin7a926812016-05-12 13:51:28 -0700839 *muted = false;
henrik.lundined497212016-04-25 10:11:38 -0700840 tick_timer_->Increment();
henrik.lundin60f6ce22016-05-10 03:52:04 -0700841 stats_.IncreaseCounter(output_size_samples_, fs_hz_);
henrik.lundin7a926812016-05-12 13:51:28 -0700842
843 // Check for muted state.
844 if (enable_muted_state_ && expand_->Muted() && packet_buffer_->Empty()) {
845 RTC_DCHECK_EQ(last_mode_, kModeExpand);
846 playout_timestamp_ += static_cast<uint32_t>(output_size_samples_);
847 audio_frame->sample_rate_hz_ = fs_hz_;
848 audio_frame->samples_per_channel_ = output_size_samples_;
849 audio_frame->timestamp_ =
850 first_packet_
851 ? 0
852 : timestamp_scaler_->ToExternal(playout_timestamp_) -
853 static_cast<uint32_t>(audio_frame->samples_per_channel_);
854 audio_frame->num_channels_ = sync_buffer_->Channels();
henrik.lundin612c25e2016-05-25 08:21:04 -0700855 stats_.ExpandedNoiseSamples(output_size_samples_);
henrik.lundin7a926812016-05-12 13:51:28 -0700856 *muted = true;
857 return 0;
858 }
859
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000860 int return_value = GetDecision(&operation, &packet_list, &dtmf_event,
861 &play_dtmf);
862 if (return_value != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000863 last_mode_ = kModeError;
864 return return_value;
865 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000866
867 AudioDecoder::SpeechType speech_type;
868 int length = 0;
869 int decode_return_value = Decode(&packet_list, &operation,
870 &length, &speech_type);
871
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000872 assert(vad_.get());
873 bool sid_frame_available =
874 (operation == kRfc3389Cng && !packet_list.empty());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700875 vad_->Update(decoded_buffer_.get(), static_cast<size_t>(length), speech_type,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000876 sid_frame_available, fs_hz_);
877
henrik.lundinb1fb72b2016-05-03 08:18:47 -0700878 if (sid_frame_available || speech_type == AudioDecoder::kComfortNoise) {
879 // Start a new stopwatch since we are decoding a new CNG packet.
880 generated_noise_stopwatch_ = tick_timer_->GetNewStopwatch();
881 }
882
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000883 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000884 switch (operation) {
885 case kNormal: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000886 DoNormal(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000887 break;
888 }
889 case kMerge: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000890 DoMerge(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000891 break;
892 }
893 case kExpand: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000894 return_value = DoExpand(play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000895 break;
896 }
Henrik Lundincf808d22015-05-27 14:33:29 +0200897 case kAccelerate:
898 case kFastAccelerate: {
899 const bool fast_accelerate =
900 enable_fast_accelerate_ && (operation == kFastAccelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000901 return_value = DoAccelerate(decoded_buffer_.get(), length, speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +0200902 play_dtmf, fast_accelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000903 break;
904 }
905 case kPreemptiveExpand: {
906 return_value = DoPreemptiveExpand(decoded_buffer_.get(), length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000907 speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000908 break;
909 }
910 case kRfc3389Cng:
911 case kRfc3389CngNoPacket: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000912 return_value = DoRfc3389Cng(&packet_list, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000913 break;
914 }
915 case kCodecInternalCng: {
916 // This handles the case when there is no transmission and the decoder
917 // should produce internal comfort noise.
918 // TODO(hlundin): Write test for codec-internal CNG.
minyuel6d92bf52015-09-23 15:20:39 +0200919 DoCodecInternalCng(decoded_buffer_.get(), length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000920 break;
921 }
922 case kDtmf: {
923 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000924 return_value = DoDtmf(dtmf_event, &play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000925 break;
926 }
927 case kAlternativePlc: {
928 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000929 DoAlternativePlc(false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000930 break;
931 }
932 case kAlternativePlcIncreaseTimestamp: {
933 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000934 DoAlternativePlc(true);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000935 break;
936 }
937 case kAudioRepetitionIncreaseTimestamp: {
938 // TODO(hlundin): Write test for this.
Peter Kastingb7e50542015-06-11 12:55:50 -0700939 sync_buffer_->IncreaseEndTimestamp(
940 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000941 // Skipping break on purpose. Execution should move on into the
942 // next case.
kjellander@webrtc.org7d2b6a92015-01-28 18:37:58 +0000943 FALLTHROUGH();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000944 }
945 case kAudioRepetition: {
946 // TODO(hlundin): Write test for this.
947 // Copy last |output_size_samples_| from |sync_buffer_| to
948 // |algorithm_buffer|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000949 algorithm_buffer_->PushBackFromIndex(
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000950 *sync_buffer_, sync_buffer_->Size() - output_size_samples_);
951 expand_->Reset();
952 break;
953 }
954 case kUndefined: {
Henrik Lundind67a2192015-08-03 12:54:37 +0200955 LOG(LS_ERROR) << "Invalid operation kUndefined.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000956 assert(false); // This should not happen.
957 last_mode_ = kModeError;
958 return kInvalidOperation;
959 }
960 } // End of switch.
minyue5bd33972016-05-02 04:46:11 -0700961 last_operation_ = operation;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000962 if (return_value < 0) {
963 return return_value;
964 }
965
966 if (last_mode_ != kModeRfc3389Cng) {
967 comfort_noise_->Reset();
968 }
969
970 // Copy from |algorithm_buffer| to |sync_buffer_|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000971 sync_buffer_->PushBack(*algorithm_buffer_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000972
973 // Extract data from |sync_buffer_| to |output|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000974 size_t num_output_samples_per_channel = output_size_samples_;
975 size_t num_output_samples = output_size_samples_ * sync_buffer_->Channels();
henrik.lundin6d8e0112016-03-04 10:34:21 -0800976 if (num_output_samples > AudioFrame::kMaxDataSizeSamples) {
977 LOG(LS_WARNING) << "Output array is too short. "
978 << AudioFrame::kMaxDataSizeSamples << " < "
979 << output_size_samples_ << " * "
980 << sync_buffer_->Channels();
981 num_output_samples = AudioFrame::kMaxDataSizeSamples;
982 num_output_samples_per_channel =
983 AudioFrame::kMaxDataSizeSamples / sync_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000984 }
henrik.lundin6d8e0112016-03-04 10:34:21 -0800985 sync_buffer_->GetNextAudioInterleaved(num_output_samples_per_channel,
986 audio_frame);
987 audio_frame->sample_rate_hz_ = fs_hz_;
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200988 if (sync_buffer_->FutureLength() < expand_->overlap_length()) {
989 // The sync buffer should always contain |overlap_length| samples, but now
990 // too many samples have been extracted. Reinstall the |overlap_length|
991 // lookahead by moving the index.
992 const size_t missing_lookahead_samples =
993 expand_->overlap_length() - sync_buffer_->FutureLength();
henrikg91d6ede2015-09-17 00:24:34 -0700994 RTC_DCHECK_GE(sync_buffer_->next_index(), missing_lookahead_samples);
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200995 sync_buffer_->set_next_index(sync_buffer_->next_index() -
996 missing_lookahead_samples);
997 }
henrik.lundin6d8e0112016-03-04 10:34:21 -0800998 if (audio_frame->samples_per_channel_ != output_size_samples_) {
999 LOG(LS_ERROR) << "audio_frame->samples_per_channel_ ("
1000 << audio_frame->samples_per_channel_
Henrik Lundind67a2192015-08-03 12:54:37 +02001001 << ") != output_size_samples_ (" << output_size_samples_
1002 << ")";
minyue@webrtc.orgdb1cefc2013-08-13 01:39:21 +00001003 // TODO(minyue): treatment of under-run, filling zeros
henrik.lundin6d8e0112016-03-04 10:34:21 -08001004 memset(audio_frame->data_, 0, num_output_samples * sizeof(int16_t));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001005 return kSampleUnderrun;
1006 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001007
1008 // Should always have overlap samples left in the |sync_buffer_|.
henrikg91d6ede2015-09-17 00:24:34 -07001009 RTC_DCHECK_GE(sync_buffer_->FutureLength(), expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001010
1011 if (play_dtmf) {
henrik.lundin6d8e0112016-03-04 10:34:21 -08001012 return_value =
1013 DtmfOverdub(dtmf_event, sync_buffer_->Channels(), audio_frame->data_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001014 }
1015
1016 // Update the background noise parameters if last operation wrote data
1017 // straight from the decoder to the |sync_buffer_|. That is, none of the
1018 // operations that modify the signal can be followed by a parameter update.
1019 if ((last_mode_ == kModeNormal) ||
1020 (last_mode_ == kModeAccelerateFail) ||
1021 (last_mode_ == kModePreemptiveExpandFail) ||
1022 (last_mode_ == kModeRfc3389Cng) ||
1023 (last_mode_ == kModeCodecInternalCng)) {
1024 background_noise_->Update(*sync_buffer_, *vad_.get());
1025 }
1026
1027 if (operation == kDtmf) {
1028 // DTMF data was written the end of |sync_buffer_|.
1029 // Update index to end of DTMF data in |sync_buffer_|.
1030 sync_buffer_->set_dtmf_index(sync_buffer_->Size());
1031 }
1032
henrik.lundin@webrtc.orged865b52014-03-06 10:28:07 +00001033 if (last_mode_ != kModeExpand) {
1034 // If last operation was not expand, calculate the |playout_timestamp_| from
1035 // the |sync_buffer_|. However, do not update the |playout_timestamp_| if it
1036 // would be moved "backwards".
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001037 uint32_t temp_timestamp = sync_buffer_->end_timestamp() -
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001038 static_cast<uint32_t>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001039 if (static_cast<int32_t>(temp_timestamp - playout_timestamp_) > 0) {
1040 playout_timestamp_ = temp_timestamp;
1041 }
1042 } else {
1043 // Use dead reckoning to estimate the |playout_timestamp_|.
Peter Kastingb7e50542015-06-11 12:55:50 -07001044 playout_timestamp_ += static_cast<uint32_t>(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001045 }
henrik.lundin15c51e32016-04-06 08:38:56 -07001046 // Set the timestamp in the audio frame to zero before the first packet has
1047 // been inserted. Otherwise, subtract the frame size in samples to get the
1048 // timestamp of the first sample in the frame (playout_timestamp_ is the
1049 // last + 1).
1050 audio_frame->timestamp_ =
1051 first_packet_
1052 ? 0
1053 : timestamp_scaler_->ToExternal(playout_timestamp_) -
1054 static_cast<uint32_t>(audio_frame->samples_per_channel_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001055
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001056 if (!(last_mode_ == kModeRfc3389Cng ||
1057 last_mode_ == kModeCodecInternalCng ||
1058 last_mode_ == kModeExpand)) {
1059 generated_noise_stopwatch_.reset();
1060 }
1061
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001062 if (decode_return_value) return decode_return_value;
1063 return return_value;
1064}
1065
1066int NetEqImpl::GetDecision(Operations* operation,
1067 PacketList* packet_list,
1068 DtmfEvent* dtmf_event,
1069 bool* play_dtmf) {
1070 // Initialize output variables.
1071 *play_dtmf = false;
1072 *operation = kUndefined;
1073
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001074 assert(sync_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001075 uint32_t end_timestamp = sync_buffer_->end_timestamp();
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001076 if (!new_codec_) {
1077 const uint32_t five_seconds_samples = 5 * fs_hz_;
1078 packet_buffer_->DiscardOldPackets(end_timestamp, five_seconds_samples);
1079 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001080 const RTPHeader* header = packet_buffer_->NextRtpHeader();
1081
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001082 RTC_DCHECK(!generated_noise_stopwatch_ ||
1083 generated_noise_stopwatch_->ElapsedTicks() >= 1);
1084 uint64_t generated_noise_samples =
1085 generated_noise_stopwatch_
1086 ? (generated_noise_stopwatch_->ElapsedTicks() - 1) *
1087 output_size_samples_ +
1088 decision_logic_->noise_fast_forward()
1089 : 0;
1090
henrik.lundin@webrtc.orgca8cb952014-03-12 10:26:52 +00001091 if (decision_logic_->CngRfc3389On() || last_mode_ == kModeRfc3389Cng) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001092 // Because of timestamp peculiarities, we have to "manually" disallow using
1093 // a CNG packet with the same timestamp as the one that was last played.
1094 // This can happen when using redundancy and will cause the timing to shift.
henrik.lundin@webrtc.org24779fe2014-03-14 12:40:05 +00001095 while (header && decoder_database_->IsComfortNoise(header->payloadType) &&
1096 (end_timestamp >= header->timestamp ||
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001097 end_timestamp + generated_noise_samples > header->timestamp)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001098 // Don't use this packet, discard it.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001099 if (packet_buffer_->DiscardNextPacket() != PacketBuffer::kOK) {
1100 assert(false); // Must be ok by design.
1101 }
1102 // Check buffer again.
1103 if (!new_codec_) {
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001104 packet_buffer_->DiscardOldPackets(end_timestamp, 5 * fs_hz_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001105 }
1106 header = packet_buffer_->NextRtpHeader();
1107 }
1108 }
1109
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001110 assert(expand_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001111 const int samples_left = static_cast<int>(sync_buffer_->FutureLength() -
1112 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001113 if (last_mode_ == kModeAccelerateSuccess ||
1114 last_mode_ == kModeAccelerateLowEnergy ||
1115 last_mode_ == kModePreemptiveExpandSuccess ||
1116 last_mode_ == kModePreemptiveExpandLowEnergy) {
1117 // Subtract (samples_left + output_size_samples_) from sampleMemory.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001118 decision_logic_->AddSampleMemory(
1119 -(samples_left + rtc::checked_cast<int>(output_size_samples_)));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001120 }
1121
1122 // Check if it is time to play a DTMF event.
Peter Kastingb7e50542015-06-11 12:55:50 -07001123 if (dtmf_buffer_->GetEvent(
1124 static_cast<uint32_t>(
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001125 end_timestamp + generated_noise_samples),
Peter Kastingb7e50542015-06-11 12:55:50 -07001126 dtmf_event)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001127 *play_dtmf = true;
1128 }
1129
1130 // Get instruction.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001131 assert(sync_buffer_.get());
1132 assert(expand_.get());
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001133 generated_noise_samples =
1134 generated_noise_stopwatch_
1135 ? generated_noise_stopwatch_->ElapsedTicks() * output_size_samples_ +
1136 decision_logic_->noise_fast_forward()
1137 : 0;
1138 *operation = decision_logic_->GetDecision(
1139 *sync_buffer_, *expand_, decoder_frame_length_, header, last_mode_,
1140 *play_dtmf, generated_noise_samples, &reset_decoder_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001141
1142 // Check if we already have enough samples in the |sync_buffer_|. If so,
1143 // change decision to normal, unless the decision was merge, accelerate, or
1144 // preemptive expand.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001145 if (samples_left >= rtc::checked_cast<int>(output_size_samples_) &&
1146 *operation != kMerge &&
1147 *operation != kAccelerate &&
1148 *operation != kFastAccelerate &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001149 *operation != kPreemptiveExpand) {
1150 *operation = kNormal;
1151 return 0;
1152 }
1153
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001154 decision_logic_->ExpandDecision(*operation);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001155
1156 // Check conditions for reset.
1157 if (new_codec_ || *operation == kUndefined) {
1158 // The only valid reason to get kUndefined is that new_codec_ is set.
1159 assert(new_codec_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001160 if (*play_dtmf && !header) {
1161 timestamp_ = dtmf_event->timestamp;
1162 } else {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001163 if (!header) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001164 LOG(LS_ERROR) << "Packet missing where it shouldn't.";
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001165 return -1;
1166 }
1167 timestamp_ = header->timestamp;
ossu108ecec2016-07-08 08:45:18 -07001168 if (*operation == kRfc3389CngNoPacket &&
1169 decoder_database_->IsComfortNoise(header->payloadType)) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001170 // Change decision to CNG packet, since we do have a CNG packet, but it
1171 // was considered too early to use. Now, use it anyway.
1172 *operation = kRfc3389Cng;
1173 } else if (*operation != kRfc3389Cng) {
1174 *operation = kNormal;
1175 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001176 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001177 // Adjust |sync_buffer_| timestamp before setting |end_timestamp| to the
1178 // new value.
1179 sync_buffer_->IncreaseEndTimestamp(timestamp_ - end_timestamp);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001180 end_timestamp = timestamp_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001181 new_codec_ = false;
1182 decision_logic_->SoftReset();
1183 buffer_level_filter_->Reset();
1184 delay_manager_->Reset();
1185 stats_.ResetMcu();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001186 }
1187
Peter Kastingdce40cf2015-08-24 14:52:23 -07001188 size_t required_samples = output_size_samples_;
1189 const size_t samples_10_ms = static_cast<size_t>(80 * fs_mult_);
1190 const size_t samples_20_ms = 2 * samples_10_ms;
1191 const size_t samples_30_ms = 3 * samples_10_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001192
1193 switch (*operation) {
1194 case kExpand: {
1195 timestamp_ = end_timestamp;
1196 return 0;
1197 }
1198 case kRfc3389CngNoPacket:
1199 case kCodecInternalCng: {
1200 return 0;
1201 }
1202 case kDtmf: {
1203 // TODO(hlundin): Write test for this.
1204 // Update timestamp.
1205 timestamp_ = end_timestamp;
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001206 const uint64_t generated_noise_samples =
1207 generated_noise_stopwatch_
1208 ? generated_noise_stopwatch_->ElapsedTicks() *
1209 output_size_samples_ +
1210 decision_logic_->noise_fast_forward()
1211 : 0;
1212 if (generated_noise_samples > 0 && last_mode_ != kModeDtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001213 // Make a jump in timestamp due to the recently played comfort noise.
Peter Kastingb7e50542015-06-11 12:55:50 -07001214 uint32_t timestamp_jump =
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001215 static_cast<uint32_t>(generated_noise_samples);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001216 sync_buffer_->IncreaseEndTimestamp(timestamp_jump);
1217 timestamp_ += timestamp_jump;
1218 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001219 return 0;
1220 }
Henrik Lundincf808d22015-05-27 14:33:29 +02001221 case kAccelerate:
1222 case kFastAccelerate: {
1223 // In order to do an accelerate we need at least 30 ms of audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001224 if (samples_left >= static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001225 // Already have enough data, so we do not need to extract any more.
1226 decision_logic_->set_sample_memory(samples_left);
1227 decision_logic_->set_prev_time_scale(true);
1228 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001229 } else if (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001230 decoder_frame_length_ >= samples_30_ms) {
1231 // Avoid decoding more data as it might overflow the playout buffer.
1232 *operation = kNormal;
1233 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001234 } else if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001235 decoder_frame_length_ < samples_30_ms) {
1236 // Build up decoded data by decoding at least 20 ms of audio data. Do
1237 // not perform accelerate yet, but wait until we only need to do one
1238 // decoding.
1239 required_samples = 2 * output_size_samples_;
1240 *operation = kNormal;
1241 }
1242 // If none of the above is true, we have one of two possible situations:
1243 // (1) 20 ms <= samples_left < 30 ms and decoder_frame_length_ < 30 ms; or
1244 // (2) samples_left < 10 ms and decoder_frame_length_ >= 30 ms.
1245 // In either case, we move on with the accelerate decision, and decode one
1246 // frame now.
1247 break;
1248 }
1249 case kPreemptiveExpand: {
1250 // In order to do a preemptive expand we need at least 30 ms of decoded
1251 // audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001252 if ((samples_left >= static_cast<int>(samples_30_ms)) ||
1253 (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001254 decoder_frame_length_ >= samples_30_ms)) {
1255 // Already have enough data, so we do not need to extract any more.
1256 // Or, avoid decoding more data as it might overflow the playout buffer.
1257 // Still try preemptive expand, though.
1258 decision_logic_->set_sample_memory(samples_left);
1259 decision_logic_->set_prev_time_scale(true);
1260 return 0;
1261 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07001262 if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001263 decoder_frame_length_ < samples_30_ms) {
1264 // Build up decoded data by decoding at least 20 ms of audio data.
1265 // Still try to perform preemptive expand.
1266 required_samples = 2 * output_size_samples_;
1267 }
1268 // Move on with the preemptive expand decision.
1269 break;
1270 }
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001271 case kMerge: {
1272 required_samples =
1273 std::max(merge_->RequiredFutureSamples(), required_samples);
1274 break;
1275 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001276 default: {
1277 // Do nothing.
1278 }
1279 }
1280
1281 // Get packets from buffer.
1282 int extracted_samples = 0;
1283 if (header &&
1284 *operation != kAlternativePlc &&
1285 *operation != kAlternativePlcIncreaseTimestamp &&
1286 *operation != kAudioRepetition &&
1287 *operation != kAudioRepetitionIncreaseTimestamp) {
1288 sync_buffer_->IncreaseEndTimestamp(header->timestamp - end_timestamp);
1289 if (decision_logic_->CngOff()) {
1290 // Adjustment of timestamp only corresponds to an actual packet loss
1291 // if comfort noise is not played. If comfort noise was just played,
1292 // this adjustment of timestamp is only done to get back in sync with the
1293 // stream timestamp; no loss to report.
1294 stats_.LostSamples(header->timestamp - end_timestamp);
1295 }
1296
1297 if (*operation != kRfc3389Cng) {
1298 // We are about to decode and use a non-CNG packet.
1299 decision_logic_->SetCngOff();
1300 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001301
1302 extracted_samples = ExtractPackets(required_samples, packet_list);
1303 if (extracted_samples < 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001304 return kPacketBufferCorruption;
1305 }
1306 }
1307
Henrik Lundincf808d22015-05-27 14:33:29 +02001308 if (*operation == kAccelerate || *operation == kFastAccelerate ||
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001309 *operation == kPreemptiveExpand) {
1310 decision_logic_->set_sample_memory(samples_left + extracted_samples);
1311 decision_logic_->set_prev_time_scale(true);
1312 }
1313
Henrik Lundincf808d22015-05-27 14:33:29 +02001314 if (*operation == kAccelerate || *operation == kFastAccelerate) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001315 // Check that we have enough data (30ms) to do accelerate.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001316 if (extracted_samples + samples_left < static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001317 // TODO(hlundin): Write test for this.
1318 // Not enough, do normal operation instead.
1319 *operation = kNormal;
1320 }
1321 }
1322
1323 timestamp_ = end_timestamp;
1324 return 0;
1325}
1326
1327int NetEqImpl::Decode(PacketList* packet_list, Operations* operation,
1328 int* decoded_length,
1329 AudioDecoder::SpeechType* speech_type) {
1330 *speech_type = AudioDecoder::kSpeech;
minyuel6d92bf52015-09-23 15:20:39 +02001331
1332 // When packet_list is empty, we may be in kCodecInternalCng mode, and for
1333 // that we use current active decoder.
1334 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1335
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001336 if (!packet_list->empty()) {
1337 const Packet* packet = packet_list->front();
pkasting@chromium.org0e81fdf2015-02-02 23:54:03 +00001338 uint8_t payload_type = packet->header.payloadType;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001339 if (!decoder_database_->IsComfortNoise(payload_type)) {
1340 decoder = decoder_database_->GetDecoder(payload_type);
1341 assert(decoder);
1342 if (!decoder) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001343 LOG(LS_WARNING) << "Unknown payload type "
1344 << static_cast<int>(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001345 PacketBuffer::DeleteAllPackets(packet_list);
1346 return kDecoderNotFound;
1347 }
1348 bool decoder_changed;
1349 decoder_database_->SetActiveDecoder(payload_type, &decoder_changed);
1350 if (decoder_changed) {
1351 // We have a new decoder. Re-init some values.
1352 const DecoderDatabase::DecoderInfo* decoder_info = decoder_database_
1353 ->GetDecoderInfo(payload_type);
1354 assert(decoder_info);
1355 if (!decoder_info) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001356 LOG(LS_WARNING) << "Unknown payload type "
1357 << static_cast<int>(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001358 PacketBuffer::DeleteAllPackets(packet_list);
1359 return kDecoderNotFound;
1360 }
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001361 // If sampling rate or number of channels has changed, we need to make
1362 // a reset.
kwibergc0f2dcf2016-05-31 06:28:03 -07001363 if (decoder_info->SampleRateHz() != fs_hz_ ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001364 decoder->Channels() != algorithm_buffer_->Channels()) {
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001365 // TODO(tlegrand): Add unittest to cover this event.
kwibergc0f2dcf2016-05-31 06:28:03 -07001366 SetSampleRateAndChannels(decoder_info->SampleRateHz(),
1367 decoder->Channels());
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001368 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001369 sync_buffer_->set_end_timestamp(timestamp_);
1370 playout_timestamp_ = timestamp_;
1371 }
1372 }
1373 }
1374
1375 if (reset_decoder_) {
1376 // TODO(hlundin): Write test for this.
Karl Wiberg43766482015-08-27 15:22:11 +02001377 if (decoder)
1378 decoder->Reset();
1379
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001380 // Reset comfort noise decoder.
ossu97ba30e2016-04-25 07:55:58 -07001381 ComfortNoiseDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02001382 if (cng_decoder)
1383 cng_decoder->Reset();
1384
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001385 reset_decoder_ = false;
1386 }
1387
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001388 *decoded_length = 0;
1389 // Update codec-internal PLC state.
1390 if ((*operation == kMerge) && decoder && decoder->HasDecodePlc()) {
1391 decoder->DecodePlc(1, &decoded_buffer_[*decoded_length]);
1392 }
1393
minyuel6d92bf52015-09-23 15:20:39 +02001394 int return_value;
1395 if (*operation == kCodecInternalCng) {
1396 RTC_DCHECK(packet_list->empty());
1397 return_value = DecodeCng(decoder, decoded_length, speech_type);
1398 } else {
1399 return_value = DecodeLoop(packet_list, *operation, decoder,
1400 decoded_length, speech_type);
1401 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001402
1403 if (*decoded_length < 0) {
1404 // Error returned from the decoder.
1405 *decoded_length = 0;
Peter Kastingb7e50542015-06-11 12:55:50 -07001406 sync_buffer_->IncreaseEndTimestamp(
1407 static_cast<uint32_t>(decoder_frame_length_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001408 int error_code = 0;
1409 if (decoder)
1410 error_code = decoder->ErrorCode();
1411 if (error_code != 0) {
1412 // Got some error code from the decoder.
1413 decoder_error_code_ = error_code;
1414 return_value = kDecoderErrorCode;
Henrik Lundind67a2192015-08-03 12:54:37 +02001415 LOG(LS_WARNING) << "Decoder returned error code: " << error_code;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001416 } else {
1417 // Decoder does not implement error codes. Return generic error.
1418 return_value = kOtherDecoderError;
Henrik Lundind67a2192015-08-03 12:54:37 +02001419 LOG(LS_WARNING) << "Decoder error (no error code)";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001420 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001421 *operation = kExpand; // Do expansion to get data instead.
1422 }
1423 if (*speech_type != AudioDecoder::kComfortNoise) {
1424 // Don't increment timestamp if codec returned CNG speech type
1425 // since in this case, the we will increment the CNGplayedTS counter.
1426 // Increase with number of samples per channel.
1427 assert(*decoded_length == 0 ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001428 (decoder && decoder->Channels() == sync_buffer_->Channels()));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001429 sync_buffer_->IncreaseEndTimestamp(
1430 *decoded_length / static_cast<int>(sync_buffer_->Channels()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001431 }
1432 return return_value;
1433}
1434
minyuel6d92bf52015-09-23 15:20:39 +02001435int NetEqImpl::DecodeCng(AudioDecoder* decoder, int* decoded_length,
1436 AudioDecoder::SpeechType* speech_type) {
1437 if (!decoder) {
1438 // This happens when active decoder is not defined.
1439 *decoded_length = -1;
1440 return 0;
1441 }
1442
1443 while (*decoded_length < rtc::checked_cast<int>(output_size_samples_)) {
1444 const int length = decoder->Decode(
1445 nullptr, 0, fs_hz_,
1446 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1447 &decoded_buffer_[*decoded_length], speech_type);
1448 if (length > 0) {
1449 *decoded_length += length;
minyuel6d92bf52015-09-23 15:20:39 +02001450 } else {
1451 // Error.
1452 LOG(LS_WARNING) << "Failed to decode CNG";
1453 *decoded_length = -1;
1454 break;
1455 }
1456 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1457 // Guard against overflow.
1458 LOG(LS_WARNING) << "Decoded too much CNG.";
1459 return kDecodedTooMuch;
1460 }
1461 }
1462 return 0;
1463}
1464
1465int NetEqImpl::DecodeLoop(PacketList* packet_list, const Operations& operation,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001466 AudioDecoder* decoder, int* decoded_length,
1467 AudioDecoder::SpeechType* speech_type) {
1468 Packet* packet = NULL;
1469 if (!packet_list->empty()) {
1470 packet = packet_list->front();
1471 }
minyuel6d92bf52015-09-23 15:20:39 +02001472
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001473 // Do decoding.
1474 while (packet &&
1475 !decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1476 assert(decoder); // At this point, we must have a decoder object.
1477 // The number of channels in the |sync_buffer_| should be the same as the
1478 // number decoder channels.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001479 assert(sync_buffer_->Channels() == decoder->Channels());
1480 assert(decoded_buffer_length_ >= kMaxFrameSize * decoder->Channels());
minyuel6d92bf52015-09-23 15:20:39 +02001481 assert(operation == kNormal || operation == kAccelerate ||
1482 operation == kFastAccelerate || operation == kMerge ||
1483 operation == kPreemptiveExpand);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001484 packet_list->pop_front();
ossu61a208b2016-09-20 01:38:00 -07001485 auto opt_result = packet->frame->Decode(
1486 rtc::ArrayView<int16_t>(&decoded_buffer_[*decoded_length],
1487 decoded_buffer_length_ - *decoded_length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001488 delete packet;
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001489 packet = NULL;
ossu61a208b2016-09-20 01:38:00 -07001490 if (opt_result) {
1491 const auto& result = *opt_result;
1492 *speech_type = result.speech_type;
1493 if (result.num_decoded_samples > 0) {
1494 *decoded_length += rtc::checked_cast<int>(result.num_decoded_samples);
1495 // Update |decoder_frame_length_| with number of samples per channel.
1496 decoder_frame_length_ =
1497 result.num_decoded_samples / decoder->Channels();
1498 }
1499 } else {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001500 // Error.
ossu61a208b2016-09-20 01:38:00 -07001501 // TODO(ossu): What to put here?
1502 LOG(LS_WARNING) << "Decode error";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001503 *decoded_length = -1;
1504 PacketBuffer::DeleteAllPackets(packet_list);
1505 break;
1506 }
ossu61a208b2016-09-20 01:38:00 -07001507 if (*decoded_length > rtc::checked_cast<int>(decoded_buffer_length_)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001508 // Guard against overflow.
Henrik Lundind67a2192015-08-03 12:54:37 +02001509 LOG(LS_WARNING) << "Decoded too much.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001510 PacketBuffer::DeleteAllPackets(packet_list);
1511 return kDecodedTooMuch;
1512 }
1513 if (!packet_list->empty()) {
1514 packet = packet_list->front();
1515 } else {
1516 packet = NULL;
1517 }
1518 } // End of decode loop.
1519
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001520 // If the list is not empty at this point, either a decoding error terminated
1521 // the while-loop, or list must hold exactly one CNG packet.
1522 assert(packet_list->empty() || *decoded_length < 0 ||
1523 (packet_list->size() == 1 && packet &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001524 decoder_database_->IsComfortNoise(packet->header.payloadType)));
1525 return 0;
1526}
1527
1528void NetEqImpl::DoNormal(const int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001529 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001530 assert(normal_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001531 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001532 normal_->Process(decoded_buffer, decoded_length, last_mode_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001533 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001534 if (decoded_length != 0) {
1535 last_mode_ = kModeNormal;
1536 }
1537
1538 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1539 if ((speech_type == AudioDecoder::kComfortNoise)
1540 || ((last_mode_ == kModeCodecInternalCng)
1541 && (decoded_length == 0))) {
1542 // TODO(hlundin): Remove second part of || statement above.
1543 last_mode_ = kModeCodecInternalCng;
1544 }
1545
1546 if (!play_dtmf) {
1547 dtmf_tone_generator_->Reset();
1548 }
1549}
1550
1551void NetEqImpl::DoMerge(int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001552 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001553 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001554 assert(merge_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001555 size_t new_length = merge_->Process(decoded_buffer, decoded_length,
1556 mute_factor_array_.get(),
1557 algorithm_buffer_.get());
1558 size_t expand_length_correction = new_length -
1559 decoded_length / algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001560
1561 // Update in-call and post-call statistics.
1562 if (expand_->MuteFactor(0) == 0) {
1563 // Expand generates only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001564 stats_.ExpandedNoiseSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001565 } else {
1566 // Expansion generates more than only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001567 stats_.ExpandedVoiceSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001568 }
1569
1570 last_mode_ = kModeMerge;
1571 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1572 if (speech_type == AudioDecoder::kComfortNoise) {
1573 last_mode_ = kModeCodecInternalCng;
1574 }
1575 expand_->Reset();
1576 if (!play_dtmf) {
1577 dtmf_tone_generator_->Reset();
1578 }
1579}
1580
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001581int NetEqImpl::DoExpand(bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001582 while ((sync_buffer_->FutureLength() - expand_->overlap_length()) <
Peter Kastingdce40cf2015-08-24 14:52:23 -07001583 output_size_samples_) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001584 algorithm_buffer_->Clear();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001585 int return_value = expand_->Process(algorithm_buffer_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001586 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001587
1588 // Update in-call and post-call statistics.
1589 if (expand_->MuteFactor(0) == 0) {
1590 // Expand operation generates only noise.
1591 stats_.ExpandedNoiseSamples(length);
1592 } else {
1593 // Expand operation generates more than only noise.
1594 stats_.ExpandedVoiceSamples(length);
1595 }
1596
1597 last_mode_ = kModeExpand;
1598
1599 if (return_value < 0) {
1600 return return_value;
1601 }
1602
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001603 sync_buffer_->PushBack(*algorithm_buffer_);
1604 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001605 }
1606 if (!play_dtmf) {
1607 dtmf_tone_generator_->Reset();
1608 }
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001609
1610 if (!generated_noise_stopwatch_) {
1611 // Start a new stopwatch since we may be covering for a lost CNG packet.
1612 generated_noise_stopwatch_ = tick_timer_->GetNewStopwatch();
1613 }
1614
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001615 return 0;
1616}
1617
Henrik Lundincf808d22015-05-27 14:33:29 +02001618int NetEqImpl::DoAccelerate(int16_t* decoded_buffer,
1619 size_t decoded_length,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001620 AudioDecoder::SpeechType speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +02001621 bool play_dtmf,
1622 bool fast_accelerate) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001623 const size_t required_samples =
1624 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001625 size_t borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001626 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001627 size_t decoded_length_per_channel = decoded_length / num_channels;
1628 if (decoded_length_per_channel < required_samples) {
1629 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001630 borrowed_samples_per_channel = static_cast<int>(required_samples -
1631 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001632 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1633 decoded_buffer,
1634 sizeof(int16_t) * decoded_length);
1635 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1636 decoded_buffer);
1637 decoded_length = required_samples * num_channels;
1638 }
1639
Peter Kastingdce40cf2015-08-24 14:52:23 -07001640 size_t samples_removed;
Henrik Lundincf808d22015-05-27 14:33:29 +02001641 Accelerate::ReturnCodes return_code =
1642 accelerate_->Process(decoded_buffer, decoded_length, fast_accelerate,
1643 algorithm_buffer_.get(), &samples_removed);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001644 stats_.AcceleratedSamples(samples_removed);
1645 switch (return_code) {
1646 case Accelerate::kSuccess:
1647 last_mode_ = kModeAccelerateSuccess;
1648 break;
1649 case Accelerate::kSuccessLowEnergy:
1650 last_mode_ = kModeAccelerateLowEnergy;
1651 break;
1652 case Accelerate::kNoStretch:
1653 last_mode_ = kModeAccelerateFail;
1654 break;
1655 case Accelerate::kError:
1656 // TODO(hlundin): Map to kModeError instead?
1657 last_mode_ = kModeAccelerateFail;
1658 return kAccelerateError;
1659 }
1660
1661 if (borrowed_samples_per_channel > 0) {
1662 // Copy borrowed samples back to the |sync_buffer_|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001663 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001664 if (length < borrowed_samples_per_channel) {
1665 // This destroys the beginning of the buffer, but will not cause any
1666 // problems.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001667 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001668 sync_buffer_->Size() -
1669 borrowed_samples_per_channel);
1670 sync_buffer_->PushFrontZeros(borrowed_samples_per_channel - length);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001671 algorithm_buffer_->PopFront(length);
1672 assert(algorithm_buffer_->Empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001673 } else {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001674 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001675 borrowed_samples_per_channel,
1676 sync_buffer_->Size() -
1677 borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001678 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001679 }
1680 }
1681
1682 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1683 if (speech_type == AudioDecoder::kComfortNoise) {
1684 last_mode_ = kModeCodecInternalCng;
1685 }
1686 if (!play_dtmf) {
1687 dtmf_tone_generator_->Reset();
1688 }
1689 expand_->Reset();
1690 return 0;
1691}
1692
1693int NetEqImpl::DoPreemptiveExpand(int16_t* decoded_buffer,
1694 size_t decoded_length,
1695 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001696 bool play_dtmf) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001697 const size_t required_samples =
1698 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001699 size_t num_channels = algorithm_buffer_->Channels();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001700 size_t borrowed_samples_per_channel = 0;
1701 size_t old_borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001702 size_t decoded_length_per_channel = decoded_length / num_channels;
1703 if (decoded_length_per_channel < required_samples) {
1704 // Must move data from the |sync_buffer_| in order to get 30 ms.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001705 borrowed_samples_per_channel =
1706 required_samples - decoded_length_per_channel;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001707 // Calculate how many of these were already played out.
Peter Kastingf045e4d2015-06-10 21:15:38 -07001708 old_borrowed_samples_per_channel =
Peter Kastingdce40cf2015-08-24 14:52:23 -07001709 (borrowed_samples_per_channel > sync_buffer_->FutureLength()) ?
1710 (borrowed_samples_per_channel - sync_buffer_->FutureLength()) : 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001711 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1712 decoded_buffer,
1713 sizeof(int16_t) * decoded_length);
1714 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1715 decoded_buffer);
1716 decoded_length = required_samples * num_channels;
1717 }
1718
Peter Kastingdce40cf2015-08-24 14:52:23 -07001719 size_t samples_added;
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001720 PreemptiveExpand::ReturnCodes return_code = preemptive_expand_->Process(
Peter Kastingdce40cf2015-08-24 14:52:23 -07001721 decoded_buffer, decoded_length,
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001722 old_borrowed_samples_per_channel,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001723 algorithm_buffer_.get(), &samples_added);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001724 stats_.PreemptiveExpandedSamples(samples_added);
1725 switch (return_code) {
1726 case PreemptiveExpand::kSuccess:
1727 last_mode_ = kModePreemptiveExpandSuccess;
1728 break;
1729 case PreemptiveExpand::kSuccessLowEnergy:
1730 last_mode_ = kModePreemptiveExpandLowEnergy;
1731 break;
1732 case PreemptiveExpand::kNoStretch:
1733 last_mode_ = kModePreemptiveExpandFail;
1734 break;
1735 case PreemptiveExpand::kError:
1736 // TODO(hlundin): Map to kModeError instead?
1737 last_mode_ = kModePreemptiveExpandFail;
1738 return kPreemptiveExpandError;
1739 }
1740
1741 if (borrowed_samples_per_channel > 0) {
1742 // Copy borrowed samples back to the |sync_buffer_|.
1743 sync_buffer_->ReplaceAtIndex(
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001744 *algorithm_buffer_, borrowed_samples_per_channel,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001745 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001746 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001747 }
1748
1749 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1750 if (speech_type == AudioDecoder::kComfortNoise) {
1751 last_mode_ = kModeCodecInternalCng;
1752 }
1753 if (!play_dtmf) {
1754 dtmf_tone_generator_->Reset();
1755 }
1756 expand_->Reset();
1757 return 0;
1758}
1759
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001760int NetEqImpl::DoRfc3389Cng(PacketList* packet_list, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001761 if (!packet_list->empty()) {
1762 // Must have exactly one SID frame at this point.
1763 assert(packet_list->size() == 1);
1764 Packet* packet = packet_list->front();
1765 packet_list->pop_front();
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001766 if (!decoder_database_->IsComfortNoise(packet->header.payloadType)) {
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001767 LOG(LS_ERROR) << "Trying to decode non-CNG payload as CNG.";
1768 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001769 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001770 // UpdateParameters() deletes |packet|.
1771 if (comfort_noise_->UpdateParameters(packet) ==
1772 ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001773 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001774 return -comfort_noise_->internal_error_code();
1775 }
1776 }
1777 int cn_return = comfort_noise_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001778 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001779 expand_->Reset();
1780 last_mode_ = kModeRfc3389Cng;
1781 if (!play_dtmf) {
1782 dtmf_tone_generator_->Reset();
1783 }
1784 if (cn_return == ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001785 decoder_error_code_ = comfort_noise_->internal_error_code();
1786 return kComfortNoiseErrorCode;
1787 } else if (cn_return == ComfortNoise::kUnknownPayloadType) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001788 return kUnknownRtpPayloadType;
1789 }
1790 return 0;
1791}
1792
minyuel6d92bf52015-09-23 15:20:39 +02001793void NetEqImpl::DoCodecInternalCng(const int16_t* decoded_buffer,
1794 size_t decoded_length) {
1795 RTC_DCHECK(normal_.get());
1796 RTC_DCHECK(mute_factor_array_.get());
1797 normal_->Process(decoded_buffer, decoded_length, last_mode_,
1798 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001799 last_mode_ = kModeCodecInternalCng;
1800 expand_->Reset();
1801}
1802
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001803int NetEqImpl::DoDtmf(const DtmfEvent& dtmf_event, bool* play_dtmf) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001804 // This block of the code and the block further down, handling |dtmf_switch|
1805 // are commented out. Otherwise playing out-of-band DTMF would fail in VoE
1806 // test, DtmfTest.ManualSuccessfullySendsOutOfBandTelephoneEvents. This is
1807 // equivalent to |dtmf_switch| always be false.
1808 //
1809 // See http://webrtc-codereview.appspot.com/1195004/ for discussion
1810 // On this issue. This change might cause some glitches at the point of
1811 // switch from audio to DTMF. Issue 1545 is filed to track this.
1812 //
1813 // bool dtmf_switch = false;
1814 // if ((last_mode_ != kModeDtmf) && dtmf_tone_generator_->initialized()) {
1815 // // Special case; see below.
1816 // // We must catch this before calling Generate, since |initialized| is
1817 // // modified in that call.
1818 // dtmf_switch = true;
1819 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001820
1821 int dtmf_return_value = 0;
1822 if (!dtmf_tone_generator_->initialized()) {
1823 // Initialize if not already done.
1824 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1825 dtmf_event.volume);
1826 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001827
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001828 if (dtmf_return_value == 0) {
1829 // Generate DTMF signal.
1830 dtmf_return_value = dtmf_tone_generator_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001831 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001832 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001833
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001834 if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001835 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001836 return dtmf_return_value;
1837 }
1838
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001839 // if (dtmf_switch) {
1840 // // This is the special case where the previous operation was DTMF
1841 // // overdub, but the current instruction is "regular" DTMF. We must make
1842 // // sure that the DTMF does not have any discontinuities. The first DTMF
1843 // // sample that we generate now must be played out immediately, therefore
1844 // // it must be copied to the speech buffer.
1845 // // TODO(hlundin): This code seems incorrect. (Legacy.) Write test and
1846 // // verify correct operation.
1847 // assert(false);
1848 // // Must generate enough data to replace all of the |sync_buffer_|
1849 // // "future".
1850 // int required_length = sync_buffer_->FutureLength();
1851 // assert(dtmf_tone_generator_->initialized());
1852 // dtmf_return_value = dtmf_tone_generator_->Generate(required_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001853 // algorithm_buffer_);
1854 // assert((size_t) required_length == algorithm_buffer_->Size());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001855 // if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001856 // algorithm_buffer_->Zeros(output_size_samples_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001857 // return dtmf_return_value;
1858 // }
1859 //
1860 // // Overwrite the "future" part of the speech buffer with the new DTMF
1861 // // data.
1862 // // TODO(hlundin): It seems that this overwriting has gone lost.
1863 // // Not adapted for multi-channel yet.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001864 // assert(algorithm_buffer_->Channels() == 1);
1865 // if (algorithm_buffer_->Channels() != 1) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001866 // LOG(LS_WARNING) << "DTMF not supported for more than one channel";
1867 // return kStereoNotSupported;
1868 // }
1869 // // Shuffle the remaining data to the beginning of algorithm buffer.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001870 // algorithm_buffer_->PopFront(sync_buffer_->FutureLength());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001871 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001872
Peter Kastingb7e50542015-06-11 12:55:50 -07001873 sync_buffer_->IncreaseEndTimestamp(
1874 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001875 expand_->Reset();
1876 last_mode_ = kModeDtmf;
1877
1878 // Set to false because the DTMF is already in the algorithm buffer.
1879 *play_dtmf = false;
1880 return 0;
1881}
1882
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001883void NetEqImpl::DoAlternativePlc(bool increase_timestamp) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001884 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001885 size_t length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001886 if (decoder && decoder->HasDecodePlc()) {
1887 // Use the decoder's packet-loss concealment.
1888 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1889 int16_t decoded_buffer[kMaxFrameSize];
1890 length = decoder->DecodePlc(1, decoded_buffer);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001891 if (length > 0)
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001892 algorithm_buffer_->PushBackInterleaved(decoded_buffer, length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001893 } else {
1894 // Do simple zero-stuffing.
1895 length = output_size_samples_;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001896 algorithm_buffer_->Zeros(length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001897 // By not advancing the timestamp, NetEq inserts samples.
1898 stats_.AddZeros(length);
1899 }
1900 if (increase_timestamp) {
Peter Kastingb7e50542015-06-11 12:55:50 -07001901 sync_buffer_->IncreaseEndTimestamp(static_cast<uint32_t>(length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001902 }
1903 expand_->Reset();
1904}
1905
1906int NetEqImpl::DtmfOverdub(const DtmfEvent& dtmf_event, size_t num_channels,
1907 int16_t* output) const {
1908 size_t out_index = 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001909 size_t overdub_length = output_size_samples_; // Default value.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001910
1911 if (sync_buffer_->dtmf_index() > sync_buffer_->next_index()) {
1912 // Special operation for transition from "DTMF only" to "DTMF overdub".
1913 out_index = std::min(
1914 sync_buffer_->dtmf_index() - sync_buffer_->next_index(),
Peter Kastingdce40cf2015-08-24 14:52:23 -07001915 output_size_samples_);
1916 overdub_length = output_size_samples_ - out_index;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001917 }
1918
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001919 AudioMultiVector dtmf_output(num_channels);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001920 int dtmf_return_value = 0;
1921 if (!dtmf_tone_generator_->initialized()) {
1922 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1923 dtmf_event.volume);
1924 }
1925 if (dtmf_return_value == 0) {
1926 dtmf_return_value = dtmf_tone_generator_->Generate(overdub_length,
1927 &dtmf_output);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001928 assert(overdub_length == dtmf_output.Size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001929 }
1930 dtmf_output.ReadInterleaved(overdub_length, &output[out_index]);
1931 return dtmf_return_value < 0 ? dtmf_return_value : 0;
1932}
1933
Peter Kastingdce40cf2015-08-24 14:52:23 -07001934int NetEqImpl::ExtractPackets(size_t required_samples,
1935 PacketList* packet_list) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001936 bool first_packet = true;
1937 uint8_t prev_payload_type = 0;
1938 uint32_t prev_timestamp = 0;
1939 uint16_t prev_sequence_number = 0;
1940 bool next_packet_available = false;
1941
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001942 const RTPHeader* header = packet_buffer_->NextRtpHeader();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001943 assert(header);
1944 if (!header) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001945 LOG(LS_ERROR) << "Packet buffer unexpectedly empty.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001946 return -1;
1947 }
turaj@webrtc.org7df97062013-08-02 18:07:13 +00001948 uint32_t first_timestamp = header->timestamp;
ossu61a208b2016-09-20 01:38:00 -07001949 size_t extracted_samples = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001950
1951 // Packet extraction loop.
1952 do {
1953 timestamp_ = header->timestamp;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001954 size_t discard_count = 0;
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001955 Packet* packet = packet_buffer_->GetNextPacket(&discard_count);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001956 // |header| may be invalid after the |packet_buffer_| operation.
1957 header = NULL;
1958 if (!packet) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001959 LOG(LS_ERROR) << "Should always be able to extract a packet here";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001960 assert(false); // Should always be able to extract a packet here.
1961 return -1;
1962 }
1963 stats_.PacketsDiscarded(discard_count);
henrik.lundin84f8cd62016-04-26 07:45:16 -07001964 stats_.StoreWaitingTime(packet->waiting_time->ElapsedMs());
ossu61a208b2016-09-20 01:38:00 -07001965 RTC_DCHECK(!packet->empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001966 packet_list->push_back(packet); // Store packet in list.
1967
1968 if (first_packet) {
1969 first_packet = false;
henrik.lundin48ed9302015-10-29 05:36:24 -07001970 if (nack_enabled_) {
1971 RTC_DCHECK(nack_);
1972 // TODO(henrik.lundin): Should we update this for all decoded packets?
1973 nack_->UpdateLastDecodedPacket(packet->header.sequenceNumber,
1974 packet->header.timestamp);
1975 }
1976 prev_sequence_number = packet->header.sequenceNumber;
1977 prev_timestamp = packet->header.timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001978 prev_payload_type = packet->header.payloadType;
1979 }
1980
1981 // Store number of extracted samples.
ossu61a208b2016-09-20 01:38:00 -07001982 size_t packet_duration = 0;
1983 if (packet->frame) {
1984 packet_duration = packet->frame->Duration();
1985 // TODO(ossu): Is this the correct way to track samples decoded from a
1986 // redundant packet?
1987 if (packet_duration > 0 && !packet->primary) {
1988 stats_.SecondaryDecodedSamples(rtc::checked_cast<int>(packet_duration));
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001989 }
ossu97ba30e2016-04-25 07:55:58 -07001990 } else if (!decoder_database_->IsComfortNoise(packet->header.payloadType)) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001991 LOG(LS_WARNING) << "Unknown payload type "
1992 << static_cast<int>(packet->header.payloadType);
ossu61a208b2016-09-20 01:38:00 -07001993 RTC_NOTREACHED();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001994 }
ossu61a208b2016-09-20 01:38:00 -07001995
1996 if (packet_duration == 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001997 // Decoder did not return a packet duration. Assume that the packet
1998 // contains the same number of samples as the previous one.
ossu61a208b2016-09-20 01:38:00 -07001999 packet_duration = decoder_frame_length_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002000 }
2001 extracted_samples = packet->header.timestamp - first_timestamp +
2002 packet_duration;
2003
2004 // Check what packet is available next.
2005 header = packet_buffer_->NextRtpHeader();
2006 next_packet_available = false;
2007 if (header && prev_payload_type == header->payloadType) {
2008 int16_t seq_no_diff = header->sequenceNumber - prev_sequence_number;
Peter Kastingdce40cf2015-08-24 14:52:23 -07002009 size_t ts_diff = header->timestamp - prev_timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002010 if (seq_no_diff == 1 ||
2011 (seq_no_diff == 0 && ts_diff == decoder_frame_length_)) {
2012 // The next sequence number is available, or the next part of a packet
2013 // that was split into pieces upon insertion.
2014 next_packet_available = true;
2015 }
2016 prev_sequence_number = header->sequenceNumber;
2017 }
ossu61a208b2016-09-20 01:38:00 -07002018 } while (extracted_samples < required_samples && next_packet_available);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002019
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00002020 if (extracted_samples > 0) {
2021 // Delete old packets only when we are going to decode something. Otherwise,
2022 // we could end up in the situation where we never decode anything, since
2023 // all incoming packets are considered too old but the buffer will also
2024 // never be flooded and flushed.
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00002025 packet_buffer_->DiscardAllOldPackets(timestamp_);
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00002026 }
2027
ossu61a208b2016-09-20 01:38:00 -07002028 return rtc::checked_cast<int>(extracted_samples);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002029}
2030
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002031void NetEqImpl::UpdatePlcComponents(int fs_hz, size_t channels) {
2032 // Delete objects and create new ones.
2033 expand_.reset(expand_factory_->Create(background_noise_.get(),
2034 sync_buffer_.get(), &random_vector_,
Henrik Lundinbef77e22015-08-18 14:58:09 +02002035 &stats_, fs_hz, channels));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002036 merge_.reset(new Merge(fs_hz, channels, expand_.get(), sync_buffer_.get()));
2037}
2038
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002039void NetEqImpl::SetSampleRateAndChannels(int fs_hz, size_t channels) {
Henrik Lundind67a2192015-08-03 12:54:37 +02002040 LOG(LS_VERBOSE) << "SetSampleRateAndChannels " << fs_hz << " " << channels;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002041 // TODO(hlundin): Change to an enumerator and skip assert.
2042 assert(fs_hz == 8000 || fs_hz == 16000 || fs_hz == 32000 || fs_hz == 48000);
2043 assert(channels > 0);
2044
2045 fs_hz_ = fs_hz;
2046 fs_mult_ = fs_hz / 8000;
Peter Kastingdce40cf2015-08-24 14:52:23 -07002047 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002048 decoder_frame_length_ = 3 * output_size_samples_; // Initialize to 30ms.
2049
2050 last_mode_ = kModeNormal;
2051
2052 // Create a new array of mute factors and set all to 1.
2053 mute_factor_array_.reset(new int16_t[channels]);
2054 for (size_t i = 0; i < channels; ++i) {
2055 mute_factor_array_[i] = 16384; // 1.0 in Q14.
2056 }
2057
ossu97ba30e2016-04-25 07:55:58 -07002058 ComfortNoiseDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02002059 if (cng_decoder)
2060 cng_decoder->Reset();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002061
2062 // Reinit post-decode VAD with new sample rate.
2063 assert(vad_.get()); // Cannot be NULL here.
2064 vad_->Init();
2065
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002066 // Delete algorithm buffer and create a new one.
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00002067 algorithm_buffer_.reset(new AudioMultiVector(channels));
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002068
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002069 // Delete sync buffer and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002070 sync_buffer_.reset(new SyncBuffer(channels, kSyncBufferSize * fs_mult_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002071
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00002072 // Delete BackgroundNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002073 background_noise_.reset(new BackgroundNoise(channels));
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00002074 background_noise_->set_mode(background_noise_mode_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002075
2076 // Reset random vector.
2077 random_vector_.Reset();
2078
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002079 UpdatePlcComponents(fs_hz, channels);
2080
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002081 // Move index so that we create a small set of future samples (all 0).
2082 sync_buffer_->set_next_index(sync_buffer_->next_index() -
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002083 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002084
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002085 normal_.reset(new Normal(fs_hz, decoder_database_.get(), *background_noise_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002086 expand_.get()));
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +00002087 accelerate_.reset(
2088 accelerate_factory_->Create(fs_hz, channels, *background_noise_));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002089 preemptive_expand_.reset(preemptive_expand_factory_->Create(
Peter Kastingdce40cf2015-08-24 14:52:23 -07002090 fs_hz, channels, *background_noise_, expand_->overlap_length()));
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002091
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002092 // Delete ComfortNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002093 comfort_noise_.reset(new ComfortNoise(fs_hz, decoder_database_.get(),
2094 sync_buffer_.get()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002095
2096 // Verify that |decoded_buffer_| is long enough.
2097 if (decoded_buffer_length_ < kMaxFrameSize * channels) {
2098 // Reallocate to larger size.
2099 decoded_buffer_length_ = kMaxFrameSize * channels;
2100 decoded_buffer_.reset(new int16_t[decoded_buffer_length_]);
2101 }
2102
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002103 // Create DecisionLogic if it is not created yet, then communicate new sample
2104 // rate and output size to DecisionLogic object.
2105 if (!decision_logic_.get()) {
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002106 CreateDecisionLogic();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002107 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002108 decision_logic_->SetSampleRate(fs_hz_, output_size_samples_);
2109}
2110
henrik.lundin55480f52016-03-08 02:37:57 -08002111NetEqImpl::OutputType NetEqImpl::LastOutputType() {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002112 assert(vad_.get());
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002113 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002114 if (last_mode_ == kModeCodecInternalCng || last_mode_ == kModeRfc3389Cng) {
henrik.lundin55480f52016-03-08 02:37:57 -08002115 return OutputType::kCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002116 } else if (last_mode_ == kModeExpand && expand_->MuteFactor(0) == 0) {
2117 // Expand mode has faded down to background noise only (very long expand).
henrik.lundin55480f52016-03-08 02:37:57 -08002118 return OutputType::kPLCCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002119 } else if (last_mode_ == kModeExpand) {
henrik.lundin55480f52016-03-08 02:37:57 -08002120 return OutputType::kPLC;
wu@webrtc.org24301a62013-12-13 19:17:43 +00002121 } else if (vad_->running() && !vad_->active_speech()) {
henrik.lundin55480f52016-03-08 02:37:57 -08002122 return OutputType::kVadPassive;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002123 } else {
henrik.lundin55480f52016-03-08 02:37:57 -08002124 return OutputType::kNormalSpeech;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002125 }
2126}
2127
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002128void NetEqImpl::CreateDecisionLogic() {
Henrik Lundin47b17dc2016-05-10 10:20:59 +02002129 decision_logic_.reset(DecisionLogic::Create(
2130 fs_hz_, output_size_samples_, playout_mode_, decoder_database_.get(),
2131 *packet_buffer_.get(), delay_manager_.get(), buffer_level_filter_.get(),
2132 tick_timer_.get()));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002133}
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002134} // namespace webrtc