blob: 71eea2114c2d3892e13d160ba43d8e700e20dea7 [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>
ossu97ba30e2016-04-25 07:55:58 -070017#include <vector>
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000018
henrik.lundin9c3efd02015-08-27 13:12:22 -070019#include "webrtc/base/checks.h"
Henrik Lundind67a2192015-08-03 12:54:37 +020020#include "webrtc/base/logging.h"
Tommid44c0772016-03-11 17:12:32 -080021#include "webrtc/base/safe_conversions.h"
kwibergac554ee2016-09-02 00:39:33 -070022#include "webrtc/base/sanitizer.h"
henrik.lundina689b442015-12-17 03:50:05 -080023#include "webrtc/base/trace_event.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000024#include "webrtc/common_audio/signal_processing/include/signal_processing_library.h"
kwiberg@webrtc.orge04a93b2014-12-09 10:12:53 +000025#include "webrtc/modules/audio_coding/codecs/audio_decoder.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000026#include "webrtc/modules/audio_coding/neteq/accelerate.h"
27#include "webrtc/modules/audio_coding/neteq/background_noise.h"
28#include "webrtc/modules/audio_coding/neteq/buffer_level_filter.h"
29#include "webrtc/modules/audio_coding/neteq/comfort_noise.h"
30#include "webrtc/modules/audio_coding/neteq/decision_logic.h"
31#include "webrtc/modules/audio_coding/neteq/decoder_database.h"
32#include "webrtc/modules/audio_coding/neteq/defines.h"
33#include "webrtc/modules/audio_coding/neteq/delay_manager.h"
34#include "webrtc/modules/audio_coding/neteq/delay_peak_detector.h"
35#include "webrtc/modules/audio_coding/neteq/dtmf_buffer.h"
36#include "webrtc/modules/audio_coding/neteq/dtmf_tone_generator.h"
37#include "webrtc/modules/audio_coding/neteq/expand.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000038#include "webrtc/modules/audio_coding/neteq/merge.h"
henrik.lundin91951862016-06-08 06:43:41 -070039#include "webrtc/modules/audio_coding/neteq/nack_tracker.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000040#include "webrtc/modules/audio_coding/neteq/normal.h"
41#include "webrtc/modules/audio_coding/neteq/packet_buffer.h"
42#include "webrtc/modules/audio_coding/neteq/packet.h"
43#include "webrtc/modules/audio_coding/neteq/payload_splitter.h"
44#include "webrtc/modules/audio_coding/neteq/post_decode_vad.h"
45#include "webrtc/modules/audio_coding/neteq/preemptive_expand.h"
46#include "webrtc/modules/audio_coding/neteq/sync_buffer.h"
henrik.lundined497212016-04-25 10:11:38 -070047#include "webrtc/modules/audio_coding/neteq/tick_timer.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000048#include "webrtc/modules/audio_coding/neteq/timestamp_scaler.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010049#include "webrtc/modules/include/module_common_types.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000050
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000051namespace webrtc {
52
ossue3525782016-05-25 07:37:43 -070053NetEqImpl::Dependencies::Dependencies(
54 const NetEq::Config& config,
55 const rtc::scoped_refptr<AudioDecoderFactory>& decoder_factory)
henrik.lundin1d9061e2016-04-26 12:19:34 -070056 : tick_timer(new TickTimer),
57 buffer_level_filter(new BufferLevelFilter),
ossue3525782016-05-25 07:37:43 -070058 decoder_database(new DecoderDatabase(decoder_factory)),
henrik.lundinf3933702016-04-28 01:53:52 -070059 delay_peak_detector(new DelayPeakDetector(tick_timer.get())),
henrik.lundin1d9061e2016-04-26 12:19:34 -070060 delay_manager(new DelayManager(config.max_packets_in_buffer,
henrik.lundin8f8c96d2016-04-28 23:19:20 -070061 delay_peak_detector.get(),
62 tick_timer.get())),
henrik.lundin1d9061e2016-04-26 12:19:34 -070063 dtmf_buffer(new DtmfBuffer(config.sample_rate_hz)),
64 dtmf_tone_generator(new DtmfToneGenerator),
65 packet_buffer(
66 new PacketBuffer(config.max_packets_in_buffer, tick_timer.get())),
67 payload_splitter(new PayloadSplitter),
68 timestamp_scaler(new TimestampScaler(*decoder_database)),
69 accelerate_factory(new AccelerateFactory),
70 expand_factory(new ExpandFactory),
71 preemptive_expand_factory(new PreemptiveExpandFactory) {}
72
73NetEqImpl::Dependencies::~Dependencies() = default;
74
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +000075NetEqImpl::NetEqImpl(const NetEq::Config& config,
henrik.lundin1d9061e2016-04-26 12:19:34 -070076 Dependencies&& deps,
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +000077 bool create_components)
henrik.lundin1d9061e2016-04-26 12:19:34 -070078 : tick_timer_(std::move(deps.tick_timer)),
79 buffer_level_filter_(std::move(deps.buffer_level_filter)),
80 decoder_database_(std::move(deps.decoder_database)),
81 delay_manager_(std::move(deps.delay_manager)),
82 delay_peak_detector_(std::move(deps.delay_peak_detector)),
83 dtmf_buffer_(std::move(deps.dtmf_buffer)),
84 dtmf_tone_generator_(std::move(deps.dtmf_tone_generator)),
85 packet_buffer_(std::move(deps.packet_buffer)),
86 payload_splitter_(std::move(deps.payload_splitter)),
87 timestamp_scaler_(std::move(deps.timestamp_scaler)),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000088 vad_(new PostDecodeVad()),
henrik.lundin1d9061e2016-04-26 12:19:34 -070089 expand_factory_(std::move(deps.expand_factory)),
90 accelerate_factory_(std::move(deps.accelerate_factory)),
91 preemptive_expand_factory_(std::move(deps.preemptive_expand_factory)),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000092 last_mode_(kModeNormal),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000093 decoded_buffer_length_(kMaxFrameSize),
94 decoded_buffer_(new int16_t[decoded_buffer_length_]),
95 playout_timestamp_(0),
96 new_codec_(false),
97 timestamp_(0),
98 reset_decoder_(false),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000099 ssrc_(0),
100 first_packet_(true),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000101 error_code_(0),
102 decoder_error_code_(0),
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +0000103 background_noise_mode_(config.background_noise_mode),
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000104 playout_mode_(config.playout_mode),
Henrik Lundincf808d22015-05-27 14:33:29 +0200105 enable_fast_accelerate_(config.enable_fast_accelerate),
henrik.lundin7a926812016-05-12 13:51:28 -0700106 nack_enabled_(false),
107 enable_muted_state_(config.enable_muted_state) {
Henrik Lundin905495c2015-05-25 16:58:41 +0200108 LOG(LS_INFO) << "NetEq config: " << config.ToString();
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +0000109 int fs = config.sample_rate_hz;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000110 if (fs != 8000 && fs != 16000 && fs != 32000 && fs != 48000) {
111 LOG(LS_ERROR) << "Sample rate " << fs << " Hz not supported. " <<
112 "Changing to 8000 Hz.";
113 fs = 8000;
114 }
henrik.lundin1d9061e2016-04-26 12:19:34 -0700115 delay_manager_->SetMaximumDelay(config.max_delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000116 fs_hz_ = fs;
117 fs_mult_ = fs / 8000;
henrik.lundind89814b2015-11-23 06:49:25 -0800118 last_output_sample_rate_hz_ = fs;
Peter Kastingdce40cf2015-08-24 14:52:23 -0700119 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000120 decoder_frame_length_ = 3 * output_size_samples_;
121 WebRtcSpl_Init();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000122 if (create_components) {
123 SetSampleRateAndChannels(fs, 1); // Default is 1 channel.
124 }
henrik.lundin9bc26672015-11-02 03:25:57 -0800125 RTC_DCHECK(!vad_->enabled());
126 if (config.enable_post_decode_vad) {
127 vad_->Enable();
128 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000129}
130
Henrik Lundind67a2192015-08-03 12:54:37 +0200131NetEqImpl::~NetEqImpl() = default;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000132
133int NetEqImpl::InsertPacket(const WebRtcRTPHeader& rtp_header,
kwibergee2bac22015-11-11 10:34:00 -0800134 rtc::ArrayView<const uint8_t> payload,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000135 uint32_t receive_timestamp) {
kwibergac554ee2016-09-02 00:39:33 -0700136 rtc::MsanCheckInitialized(payload);
henrik.lundina689b442015-12-17 03:50:05 -0800137 TRACE_EVENT0("webrtc", "NetEqImpl::InsertPacket");
Tommi9090e0b2016-01-20 13:39:36 +0100138 rtc::CritScope lock(&crit_sect_);
kwibergee2bac22015-11-11 10:34:00 -0800139 int error =
ossu17e3fa12016-09-08 04:52:55 -0700140 InsertPacketInternal(rtp_header, payload, receive_timestamp);
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000141 if (error != 0) {
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000142 error_code_ = error;
143 return kFail;
144 }
145 return kOK;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000146}
147
henrik.lundin500c04b2016-03-08 02:36:04 -0800148namespace {
149void SetAudioFrameActivityAndType(bool vad_enabled,
henrik.lundin55480f52016-03-08 02:37:57 -0800150 NetEqImpl::OutputType type,
henrik.lundin500c04b2016-03-08 02:36:04 -0800151 AudioFrame::VADActivity last_vad_activity,
152 AudioFrame* audio_frame) {
153 switch (type) {
henrik.lundin55480f52016-03-08 02:37:57 -0800154 case NetEqImpl::OutputType::kNormalSpeech: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800155 audio_frame->speech_type_ = AudioFrame::kNormalSpeech;
156 audio_frame->vad_activity_ = AudioFrame::kVadActive;
157 break;
158 }
henrik.lundin55480f52016-03-08 02:37:57 -0800159 case NetEqImpl::OutputType::kVadPassive: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800160 // This should only be reached if the VAD is enabled.
161 RTC_DCHECK(vad_enabled);
162 audio_frame->speech_type_ = AudioFrame::kNormalSpeech;
163 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
164 break;
165 }
henrik.lundin55480f52016-03-08 02:37:57 -0800166 case NetEqImpl::OutputType::kCNG: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800167 audio_frame->speech_type_ = AudioFrame::kCNG;
168 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
169 break;
170 }
henrik.lundin55480f52016-03-08 02:37:57 -0800171 case NetEqImpl::OutputType::kPLC: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800172 audio_frame->speech_type_ = AudioFrame::kPLC;
173 audio_frame->vad_activity_ = last_vad_activity;
174 break;
175 }
henrik.lundin55480f52016-03-08 02:37:57 -0800176 case NetEqImpl::OutputType::kPLCCNG: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800177 audio_frame->speech_type_ = AudioFrame::kPLCCNG;
178 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
179 break;
180 }
181 default:
182 RTC_NOTREACHED();
183 }
184 if (!vad_enabled) {
185 // Always set kVadUnknown when receive VAD is inactive.
186 audio_frame->vad_activity_ = AudioFrame::kVadUnknown;
187 }
188}
henrik.lundinbc89de32016-03-08 05:20:14 -0800189} // namespace
henrik.lundin500c04b2016-03-08 02:36:04 -0800190
henrik.lundin7a926812016-05-12 13:51:28 -0700191int NetEqImpl::GetAudio(AudioFrame* audio_frame, bool* muted) {
henrik.lundine1ca1672016-01-08 03:50:08 -0800192 TRACE_EVENT0("webrtc", "NetEqImpl::GetAudio");
Tommi9090e0b2016-01-20 13:39:36 +0100193 rtc::CritScope lock(&crit_sect_);
henrik.lundin7a926812016-05-12 13:51:28 -0700194 int error = GetAudioInternal(audio_frame, muted);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000195 if (error != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000196 error_code_ = error;
197 return kFail;
198 }
henrik.lundin5fac3f02016-08-24 11:18:49 -0700199 RTC_DCHECK_EQ(
200 audio_frame->sample_rate_hz_,
201 rtc::checked_cast<int>(audio_frame->samples_per_channel_ * 100));
henrik.lundin500c04b2016-03-08 02:36:04 -0800202 SetAudioFrameActivityAndType(vad_->enabled(), LastOutputType(),
203 last_vad_activity_, audio_frame);
204 last_vad_activity_ = audio_frame->vad_activity_;
henrik.lundin6d8e0112016-03-04 10:34:21 -0800205 last_output_sample_rate_hz_ = audio_frame->sample_rate_hz_;
henrik.lundind89814b2015-11-23 06:49:25 -0800206 RTC_DCHECK(last_output_sample_rate_hz_ == 8000 ||
207 last_output_sample_rate_hz_ == 16000 ||
208 last_output_sample_rate_hz_ == 32000 ||
209 last_output_sample_rate_hz_ == 48000)
210 << "Unexpected sample rate " << last_output_sample_rate_hz_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000211 return kOK;
212}
213
kwibergee1879c2015-10-29 06:20:28 -0700214int NetEqImpl::RegisterPayloadType(NetEqDecoder codec,
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800215 const std::string& name,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000216 uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100217 rtc::CritScope lock(&crit_sect_);
Henrik Lundind67a2192015-08-03 12:54:37 +0200218 LOG(LS_VERBOSE) << "RegisterPayloadType "
kwibergee1879c2015-10-29 06:20:28 -0700219 << static_cast<int>(rtp_payload_type) << " "
220 << static_cast<int>(codec);
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800221 int ret = decoder_database_->RegisterPayload(rtp_payload_type, codec, name);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000222 if (ret != DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000223 switch (ret) {
224 case DecoderDatabase::kInvalidRtpPayloadType:
225 error_code_ = kInvalidRtpPayloadType;
226 break;
227 case DecoderDatabase::kCodecNotSupported:
228 error_code_ = kCodecNotSupported;
229 break;
230 case DecoderDatabase::kDecoderExists:
231 error_code_ = kDecoderExists;
232 break;
233 default:
234 error_code_ = kOtherError;
235 }
236 return kFail;
237 }
238 return kOK;
239}
240
241int NetEqImpl::RegisterExternalDecoder(AudioDecoder* decoder,
kwibergee1879c2015-10-29 06:20:28 -0700242 NetEqDecoder codec,
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800243 const std::string& codec_name,
kwiberg342f7402016-06-16 03:18:00 -0700244 uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100245 rtc::CritScope lock(&crit_sect_);
Henrik Lundind67a2192015-08-03 12:54:37 +0200246 LOG(LS_VERBOSE) << "RegisterExternalDecoder "
kwibergee1879c2015-10-29 06:20:28 -0700247 << static_cast<int>(rtp_payload_type) << " "
248 << static_cast<int>(codec);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000249 if (!decoder) {
250 LOG(LS_ERROR) << "Cannot register external decoder with NULL pointer";
251 assert(false);
252 return kFail;
253 }
kwiberg342f7402016-06-16 03:18:00 -0700254 int ret = decoder_database_->InsertExternal(rtp_payload_type, codec,
255 codec_name, decoder);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000256 if (ret != DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000257 switch (ret) {
258 case DecoderDatabase::kInvalidRtpPayloadType:
259 error_code_ = kInvalidRtpPayloadType;
260 break;
261 case DecoderDatabase::kCodecNotSupported:
262 error_code_ = kCodecNotSupported;
263 break;
264 case DecoderDatabase::kDecoderExists:
265 error_code_ = kDecoderExists;
266 break;
267 case DecoderDatabase::kInvalidSampleRate:
268 error_code_ = kInvalidSampleRate;
269 break;
270 case DecoderDatabase::kInvalidPointer:
271 error_code_ = kInvalidPointer;
272 break;
273 default:
274 error_code_ = kOtherError;
275 }
276 return kFail;
277 }
278 return kOK;
279}
280
281int NetEqImpl::RemovePayloadType(uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100282 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000283 int ret = decoder_database_->Remove(rtp_payload_type);
284 if (ret == DecoderDatabase::kOK) {
285 return kOK;
286 } else if (ret == DecoderDatabase::kDecoderNotFound) {
287 error_code_ = kDecoderNotFound;
288 } else {
289 error_code_ = kOtherError;
290 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000291 return kFail;
292}
293
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000294bool NetEqImpl::SetMinimumDelay(int delay_ms) {
Tommi9090e0b2016-01-20 13:39:36 +0100295 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000296 if (delay_ms >= 0 && delay_ms < 10000) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000297 assert(delay_manager_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000298 return delay_manager_->SetMinimumDelay(delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000299 }
300 return false;
301}
302
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000303bool NetEqImpl::SetMaximumDelay(int delay_ms) {
Tommi9090e0b2016-01-20 13:39:36 +0100304 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000305 if (delay_ms >= 0 && delay_ms < 10000) {
306 assert(delay_manager_.get());
307 return delay_manager_->SetMaximumDelay(delay_ms);
308 }
309 return false;
310}
311
312int NetEqImpl::LeastRequiredDelayMs() const {
Tommi9090e0b2016-01-20 13:39:36 +0100313 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000314 assert(delay_manager_.get());
315 return delay_manager_->least_required_delay_ms();
316}
317
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200318int NetEqImpl::SetTargetDelay() {
319 return kNotImplemented;
320}
321
322int NetEqImpl::TargetDelay() {
323 return kNotImplemented;
324}
325
henrik.lundin9c3efd02015-08-27 13:12:22 -0700326int NetEqImpl::CurrentDelayMs() const {
Tommi9090e0b2016-01-20 13:39:36 +0100327 rtc::CritScope lock(&crit_sect_);
henrik.lundin9c3efd02015-08-27 13:12:22 -0700328 if (fs_hz_ == 0)
329 return 0;
330 // Sum up the samples in the packet buffer with the future length of the sync
331 // buffer, and divide the sum by the sample rate.
332 const size_t delay_samples =
333 packet_buffer_->NumSamplesInBuffer(decoder_database_.get(),
334 decoder_frame_length_) +
335 sync_buffer_->FutureLength();
336 // The division below will truncate.
337 const int delay_ms =
338 static_cast<int>(delay_samples) / rtc::CheckedDivExact(fs_hz_, 1000);
339 return delay_ms;
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200340}
341
henrik.lundinb3f1c5d2016-08-22 15:39:53 -0700342int NetEqImpl::FilteredCurrentDelayMs() const {
343 rtc::CritScope lock(&crit_sect_);
344 // Calculate the filtered packet buffer level in samples. The value from
345 // |buffer_level_filter_| is in number of packets, represented in Q8.
346 const size_t packet_buffer_samples =
347 (buffer_level_filter_->filtered_current_level() *
348 decoder_frame_length_) >>
349 8;
350 // Sum up the filtered packet buffer level with the future length of the sync
351 // buffer, and divide the sum by the sample rate.
352 const size_t delay_samples =
353 packet_buffer_samples + sync_buffer_->FutureLength();
354 // The division below will truncate. The return value is in ms.
355 return static_cast<int>(delay_samples) / rtc::CheckedDivExact(fs_hz_, 1000);
356}
357
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000358// Deprecated.
359// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000360void NetEqImpl::SetPlayoutMode(NetEqPlayoutMode mode) {
Tommi9090e0b2016-01-20 13:39:36 +0100361 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000362 if (mode != playout_mode_) {
363 playout_mode_ = mode;
364 CreateDecisionLogic();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000365 }
366}
367
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000368// Deprecated.
369// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000370NetEqPlayoutMode NetEqImpl::PlayoutMode() const {
Tommi9090e0b2016-01-20 13:39:36 +0100371 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000372 return playout_mode_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000373}
374
375int NetEqImpl::NetworkStatistics(NetEqNetworkStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100376 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000377 assert(decoder_database_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700378 const size_t total_samples_in_buffers =
Peter Kasting728d9032015-06-11 14:31:38 -0700379 packet_buffer_->NumSamplesInBuffer(decoder_database_.get(),
380 decoder_frame_length_) +
Peter Kastingdce40cf2015-08-24 14:52:23 -0700381 sync_buffer_->FutureLength();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000382 assert(delay_manager_.get());
383 assert(decision_logic_.get());
384 stats_.GetNetworkStatistics(fs_hz_, total_samples_in_buffers,
385 decoder_frame_length_, *delay_manager_.get(),
386 *decision_logic_.get(), stats);
387 return 0;
388}
389
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000390void NetEqImpl::GetRtcpStatistics(RtcpStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100391 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000392 if (stats) {
393 rtcp_.GetStatistics(false, stats);
394 }
395}
396
397void NetEqImpl::GetRtcpStatisticsNoReset(RtcpStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100398 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000399 if (stats) {
400 rtcp_.GetStatistics(true, stats);
401 }
402}
403
404void NetEqImpl::EnableVad() {
Tommi9090e0b2016-01-20 13:39:36 +0100405 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000406 assert(vad_.get());
407 vad_->Enable();
408}
409
410void NetEqImpl::DisableVad() {
Tommi9090e0b2016-01-20 13:39:36 +0100411 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000412 assert(vad_.get());
413 vad_->Disable();
414}
415
henrik.lundin15c51e32016-04-06 08:38:56 -0700416rtc::Optional<uint32_t> NetEqImpl::GetPlayoutTimestamp() const {
Tommi9090e0b2016-01-20 13:39:36 +0100417 rtc::CritScope lock(&crit_sect_);
henrik.lundin0d96ab72016-04-06 12:28:26 -0700418 if (first_packet_ || last_mode_ == kModeRfc3389Cng ||
419 last_mode_ == kModeCodecInternalCng) {
wu@webrtc.org94454b72014-06-05 20:34:08 +0000420 // We don't have a valid RTP timestamp until we have decoded our first
henrik.lundin0d96ab72016-04-06 12:28:26 -0700421 // RTP packet. Also, the RTP timestamp is not accurate while playing CNG,
422 // which is indicated by returning an empty value.
henrik.lundin9a410dd2016-04-06 01:39:22 -0700423 return rtc::Optional<uint32_t>();
wu@webrtc.org94454b72014-06-05 20:34:08 +0000424 }
henrik.lundin9a410dd2016-04-06 01:39:22 -0700425 return rtc::Optional<uint32_t>(
426 timestamp_scaler_->ToExternal(playout_timestamp_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000427}
428
henrik.lundind89814b2015-11-23 06:49:25 -0800429int NetEqImpl::last_output_sample_rate_hz() const {
Tommi9090e0b2016-01-20 13:39:36 +0100430 rtc::CritScope lock(&crit_sect_);
henrik.lundind89814b2015-11-23 06:49:25 -0800431 return last_output_sample_rate_hz_;
432}
433
kwiberg1e4d8b52016-09-17 08:40:13 -0700434rtc::Optional<CodecInst> NetEqImpl::GetDecoder(int payload_type) const {
435 rtc::CritScope lock(&crit_sect_);
436 const DecoderDatabase::DecoderInfo* di =
437 decoder_database_->GetDecoderInfo(payload_type);
438 if (!di) {
439 return rtc::Optional<CodecInst>();
440 }
441
442 // Create a CodecInst with some fields set. The remaining fields are zeroed,
443 // but we tell MSan to consider them uninitialized.
444 CodecInst ci = {0};
445 rtc::MsanMarkUninitialized(rtc::MakeArrayView(&ci, 1));
446 ci.pltype = payload_type;
447 std::strncpy(ci.plname, di->name.c_str(), sizeof(ci.plname));
448 ci.plname[sizeof(ci.plname) - 1] = '\0';
449 ci.plfreq = di->IsRed() || di->IsDtmf() ? 8000 : di->SampleRateHz();
450 AudioDecoder* const decoder = di->GetDecoder();
451 ci.channels = decoder ? decoder->Channels() : 1;
452 return rtc::Optional<CodecInst>(ci);
453}
454
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200455int NetEqImpl::SetTargetNumberOfChannels() {
456 return kNotImplemented;
457}
458
459int NetEqImpl::SetTargetSampleRate() {
460 return kNotImplemented;
461}
462
henrik.lundin@webrtc.orgb0f4b3d2014-11-04 08:53:10 +0000463int NetEqImpl::LastError() const {
Tommi9090e0b2016-01-20 13:39:36 +0100464 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000465 return error_code_;
466}
467
468int NetEqImpl::LastDecoderError() {
Tommi9090e0b2016-01-20 13:39:36 +0100469 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000470 return decoder_error_code_;
471}
472
473void NetEqImpl::FlushBuffers() {
Tommi9090e0b2016-01-20 13:39:36 +0100474 rtc::CritScope lock(&crit_sect_);
Henrik Lundind67a2192015-08-03 12:54:37 +0200475 LOG(LS_VERBOSE) << "FlushBuffers";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000476 packet_buffer_->Flush();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000477 assert(sync_buffer_.get());
478 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000479 sync_buffer_->Flush();
480 sync_buffer_->set_next_index(sync_buffer_->next_index() -
481 expand_->overlap_length());
482 // Set to wait for new codec.
483 first_packet_ = true;
484}
485
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000486void NetEqImpl::PacketBufferStatistics(int* current_num_packets,
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000487 int* max_num_packets) const {
Tommi9090e0b2016-01-20 13:39:36 +0100488 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000489 packet_buffer_->BufferStat(current_num_packets, max_num_packets);
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000490}
491
henrik.lundin48ed9302015-10-29 05:36:24 -0700492void NetEqImpl::EnableNack(size_t max_nack_list_size) {
Tommi9090e0b2016-01-20 13:39:36 +0100493 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700494 if (!nack_enabled_) {
495 const int kNackThresholdPackets = 2;
henrik.lundin91951862016-06-08 06:43:41 -0700496 nack_.reset(NackTracker::Create(kNackThresholdPackets));
henrik.lundin48ed9302015-10-29 05:36:24 -0700497 nack_enabled_ = true;
498 nack_->UpdateSampleRate(fs_hz_);
499 }
500 nack_->SetMaxNackListSize(max_nack_list_size);
501}
502
503void NetEqImpl::DisableNack() {
Tommi9090e0b2016-01-20 13:39:36 +0100504 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700505 nack_.reset();
506 nack_enabled_ = false;
507}
508
509std::vector<uint16_t> NetEqImpl::GetNackList(int64_t round_trip_time_ms) const {
Tommi9090e0b2016-01-20 13:39:36 +0100510 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700511 if (!nack_enabled_) {
512 return std::vector<uint16_t>();
513 }
514 RTC_DCHECK(nack_.get());
515 return nack_->GetNackList(round_trip_time_ms);
minyue@webrtc.orgd7301772013-08-29 00:58:14 +0000516}
517
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000518const SyncBuffer* NetEqImpl::sync_buffer_for_test() const {
Tommi9090e0b2016-01-20 13:39:36 +0100519 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000520 return sync_buffer_.get();
521}
522
minyue5bd33972016-05-02 04:46:11 -0700523Operations NetEqImpl::last_operation_for_test() const {
524 rtc::CritScope lock(&crit_sect_);
525 return last_operation_;
526}
527
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000528// Methods below this line are private.
529
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000530int NetEqImpl::InsertPacketInternal(const WebRtcRTPHeader& rtp_header,
kwibergee2bac22015-11-11 10:34:00 -0800531 rtc::ArrayView<const uint8_t> payload,
ossu17e3fa12016-09-08 04:52:55 -0700532 uint32_t receive_timestamp) {
kwibergee2bac22015-11-11 10:34:00 -0800533 if (payload.empty()) {
534 LOG_F(LS_ERROR) << "payload is empty";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000535 return kInvalidPointer;
536 }
ossu17e3fa12016-09-08 04:52:55 -0700537
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000538 PacketList packet_list;
539 RTPHeader main_header;
540 {
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000541 // Convert to Packet.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000542 // Create |packet| within this separate scope, since it should not be used
543 // directly once it's been inserted in the packet list. This way, |packet|
544 // is not defined outside of this block.
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000545 Packet* packet = new Packet;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000546 packet->header.markerBit = false;
547 packet->header.payloadType = rtp_header.header.payloadType;
548 packet->header.sequenceNumber = rtp_header.header.sequenceNumber;
549 packet->header.timestamp = rtp_header.header.timestamp;
550 packet->header.ssrc = rtp_header.header.ssrc;
551 packet->header.numCSRCs = 0;
ossudc431ce2016-08-31 08:51:13 -0700552 packet->payload.SetData(payload.data(), payload.size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000553 packet->primary = true;
henrik.lundin84f8cd62016-04-26 07:45:16 -0700554 // Waiting time will be set upon inserting the packet in the buffer.
555 RTC_DCHECK(!packet->waiting_time);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000556 // Insert packet in a packet list.
557 packet_list.push_back(packet);
558 // Save main payloads header for later.
559 memcpy(&main_header, &packet->header, sizeof(main_header));
560 }
561
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000562 bool update_sample_rate_and_channels = false;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000563 // Reinitialize NetEq if it's needed (changed SSRC or first call).
564 if ((main_header.ssrc != ssrc_) || first_packet_) {
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000565 // Note: |first_packet_| will be cleared further down in this method, once
566 // the packet has been successfully inserted into the packet buffer.
567
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000568 rtcp_.Init(main_header.sequenceNumber);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000569
570 // Flush the packet buffer and DTMF buffer.
571 packet_buffer_->Flush();
572 dtmf_buffer_->Flush();
573
574 // Store new SSRC.
575 ssrc_ = main_header.ssrc;
576
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000577 // Update audio buffer timestamp.
578 sync_buffer_->IncreaseEndTimestamp(main_header.timestamp - timestamp_);
579
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000580 // Update codecs.
581 timestamp_ = main_header.timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000582
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000583 // Reset timestamp scaling.
584 timestamp_scaler_->Reset();
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000585
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000586 // Trigger an update of sampling rate and the number of channels.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000587 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000588 }
589
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000590 // Update RTCP statistics, only for regular packets.
ossu17e3fa12016-09-08 04:52:55 -0700591 rtcp_.Update(main_header, receive_timestamp);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000592
593 // Check for RED payload type, and separate payloads into several packets.
594 if (decoder_database_->IsRed(main_header.payloadType)) {
595 if (payload_splitter_->SplitRed(&packet_list) != PayloadSplitter::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000596 PacketBuffer::DeleteAllPackets(&packet_list);
597 return kRedundancySplitError;
598 }
599 // Only accept a few RED payloads of the same type as the main data,
600 // DTMF events and CNG.
601 payload_splitter_->CheckRedPayloads(&packet_list, *decoder_database_);
602 // Update the stored main payload header since the main payload has now
603 // changed.
604 memcpy(&main_header, &packet_list.front()->header, sizeof(main_header));
605 }
606
607 // Check payload types.
608 if (decoder_database_->CheckPayloadTypes(packet_list) ==
609 DecoderDatabase::kDecoderNotFound) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000610 PacketBuffer::DeleteAllPackets(&packet_list);
611 return kUnknownRtpPayloadType;
612 }
613
614 // Scale timestamp to internal domain (only for some codecs).
615 timestamp_scaler_->ToInternal(&packet_list);
616
617 // Process DTMF payloads. Cycle through the list of packets, and pick out any
618 // DTMF payloads found.
619 PacketList::iterator it = packet_list.begin();
620 while (it != packet_list.end()) {
621 Packet* current_packet = (*it);
622 assert(current_packet);
ossudc431ce2016-08-31 08:51:13 -0700623 assert(!current_packet->payload.empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000624 if (decoder_database_->IsDtmf(current_packet->header.payloadType)) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000625 DtmfEvent event;
ossudc431ce2016-08-31 08:51:13 -0700626 int ret = DtmfBuffer::ParseEvent(current_packet->header.timestamp,
627 current_packet->payload.data(),
628 current_packet->payload.size(), &event);
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000629 if (ret != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000630 PacketBuffer::DeleteAllPackets(&packet_list);
631 return kDtmfParsingError;
632 }
633 if (dtmf_buffer_->InsertEvent(event) != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000634 PacketBuffer::DeleteAllPackets(&packet_list);
635 return kDtmfInsertError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000636 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000637 delete current_packet;
638 it = packet_list.erase(it);
639 } else {
640 ++it;
641 }
642 }
643
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000644 // Check for FEC in packets, and separate payloads into several packets.
645 int ret = payload_splitter_->SplitFec(&packet_list, decoder_database_.get());
646 if (ret != PayloadSplitter::kOK) {
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000647 PacketBuffer::DeleteAllPackets(&packet_list);
648 switch (ret) {
649 case PayloadSplitter::kUnknownPayloadType:
650 return kUnknownRtpPayloadType;
651 default:
652 return kOtherError;
653 }
654 }
655
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000656 // Split payloads into smaller chunks. This also verifies that all payloads
ossu17e3fa12016-09-08 04:52:55 -0700657 // are of a known payload type.
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +0000658 ret = payload_splitter_->SplitAudio(&packet_list, *decoder_database_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000659 if (ret != PayloadSplitter::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000660 PacketBuffer::DeleteAllPackets(&packet_list);
661 switch (ret) {
662 case PayloadSplitter::kUnknownPayloadType:
663 return kUnknownRtpPayloadType;
664 case PayloadSplitter::kFrameSplitError:
665 return kFrameSplitError;
666 default:
667 return kOtherError;
668 }
669 }
670
ossu17e3fa12016-09-08 04:52:55 -0700671 // Update bandwidth estimate, if the packet is not comfort noise.
672 if (!packet_list.empty() &&
ossu97ba30e2016-04-25 07:55:58 -0700673 !decoder_database_->IsComfortNoise(main_header.payloadType)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000674 // The list can be empty here if we got nothing but DTMF payloads.
675 AudioDecoder* decoder =
676 decoder_database_->GetDecoder(main_header.payloadType);
677 assert(decoder); // Should always get a valid object, since we have
ossu97ba30e2016-04-25 07:55:58 -0700678 // already checked that the payload types are known.
ossudc431ce2016-08-31 08:51:13 -0700679 decoder->IncomingPacket(packet_list.front()->payload.data(),
680 packet_list.front()->payload.size(),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000681 packet_list.front()->header.sequenceNumber,
682 packet_list.front()->header.timestamp,
683 receive_timestamp);
684 }
685
henrik.lundin48ed9302015-10-29 05:36:24 -0700686 if (nack_enabled_) {
687 RTC_DCHECK(nack_);
688 if (update_sample_rate_and_channels) {
689 nack_->Reset();
690 }
691 nack_->UpdateLastReceivedPacket(packet_list.front()->header.sequenceNumber,
692 packet_list.front()->header.timestamp);
693 }
694
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000695 // Insert packets in buffer.
henrik.lundin116c84e2015-08-27 13:14:48 -0700696 const size_t buffer_length_before_insert =
697 packet_buffer_->NumPacketsInBuffer();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000698 ret = packet_buffer_->InsertPacketList(
699 &packet_list,
700 *decoder_database_,
701 &current_rtp_payload_type_,
702 &current_cng_rtp_payload_type_);
703 if (ret == PacketBuffer::kFlushed) {
704 // Reset DSP timestamp etc. if packet buffer flushed.
705 new_codec_ = true;
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000706 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000707 } else if (ret != PacketBuffer::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000708 PacketBuffer::DeleteAllPackets(&packet_list);
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000709 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000710 }
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000711
712 if (first_packet_) {
713 first_packet_ = false;
714 // Update the codec on the next GetAudio call.
715 new_codec_ = true;
716 }
717
henrik.lundinda8bbf62016-08-31 03:14:11 -0700718 if (current_rtp_payload_type_) {
719 RTC_DCHECK(decoder_database_->GetDecoderInfo(*current_rtp_payload_type_))
720 << "Payload type " << static_cast<int>(*current_rtp_payload_type_)
721 << " is unknown where it shouldn't be";
722 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000723
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000724 if (update_sample_rate_and_channels && !packet_buffer_->Empty()) {
725 // We do not use |current_rtp_payload_type_| to |set payload_type|, but
726 // get the next RTP header from |packet_buffer_| to obtain the payload type.
727 // The reason for it is the following corner case. If NetEq receives a
728 // CNG packet with a sample rate different than the current CNG then it
729 // flushes its buffer, assuming send codec must have been changed. However,
730 // payload type of the hypothetically new send codec is not known.
731 const RTPHeader* rtp_header = packet_buffer_->NextRtpHeader();
732 assert(rtp_header);
733 int payload_type = rtp_header->payloadType;
ossu97ba30e2016-04-25 07:55:58 -0700734 size_t channels = 1;
735 if (!decoder_database_->IsComfortNoise(payload_type)) {
736 AudioDecoder* decoder = decoder_database_->GetDecoder(payload_type);
737 assert(decoder); // Payloads are already checked to be valid.
738 channels = decoder->Channels();
739 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000740 const DecoderDatabase::DecoderInfo* decoder_info =
741 decoder_database_->GetDecoderInfo(payload_type);
742 assert(decoder_info);
kwibergc0f2dcf2016-05-31 06:28:03 -0700743 if (decoder_info->SampleRateHz() != fs_hz_ ||
ossu97ba30e2016-04-25 07:55:58 -0700744 channels != algorithm_buffer_->Channels()) {
kwibergc0f2dcf2016-05-31 06:28:03 -0700745 SetSampleRateAndChannels(decoder_info->SampleRateHz(),
746 channels);
henrik.lundin48ed9302015-10-29 05:36:24 -0700747 }
748 if (nack_enabled_) {
749 RTC_DCHECK(nack_);
750 // Update the sample rate even if the rate is not new, because of Reset().
751 nack_->UpdateSampleRate(fs_hz_);
752 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000753 }
754
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000755 // TODO(hlundin): Move this code to DelayManager class.
756 const DecoderDatabase::DecoderInfo* dec_info =
757 decoder_database_->GetDecoderInfo(main_header.payloadType);
758 assert(dec_info); // Already checked that the payload type is known.
759 delay_manager_->LastDecoderType(dec_info->codec_type);
760 if (delay_manager_->last_pack_cng_or_dtmf() == 0) {
761 // Calculate the total speech length carried in each packet.
henrik.lundin116c84e2015-08-27 13:14:48 -0700762 const size_t buffer_length_after_insert =
763 packet_buffer_->NumPacketsInBuffer();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000764
henrik.lundin116c84e2015-08-27 13:14:48 -0700765 if (buffer_length_after_insert > buffer_length_before_insert) {
766 const size_t packet_length_samples =
767 (buffer_length_after_insert - buffer_length_before_insert) *
768 decoder_frame_length_;
769 if (packet_length_samples != decision_logic_->packet_length_samples()) {
770 decision_logic_->set_packet_length_samples(packet_length_samples);
771 delay_manager_->SetPacketAudioLength(
772 rtc::checked_cast<int>((1000 * packet_length_samples) / fs_hz_));
773 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000774 }
775
776 // Update statistics.
pbos@webrtc.org0946a562013-04-09 00:28:06 +0000777 if ((int32_t) (main_header.timestamp - timestamp_) >= 0 &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000778 !new_codec_) {
779 // Only update statistics if incoming packet is not older than last played
780 // out packet, and if new codec flag is not set.
781 delay_manager_->Update(main_header.sequenceNumber, main_header.timestamp,
782 fs_hz_);
783 }
784 } else if (delay_manager_->last_pack_cng_or_dtmf() == -1) {
785 // This is first "normal" packet after CNG or DTMF.
786 // Reset packet time counter and measure time until next packet,
787 // but don't update statistics.
788 delay_manager_->set_last_pack_cng_or_dtmf(0);
789 delay_manager_->ResetPacketIatCount();
790 }
791 return 0;
792}
793
henrik.lundin7a926812016-05-12 13:51:28 -0700794int NetEqImpl::GetAudioInternal(AudioFrame* audio_frame, bool* muted) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000795 PacketList packet_list;
796 DtmfEvent dtmf_event;
797 Operations operation;
798 bool play_dtmf;
henrik.lundin7a926812016-05-12 13:51:28 -0700799 *muted = false;
henrik.lundined497212016-04-25 10:11:38 -0700800 tick_timer_->Increment();
henrik.lundin60f6ce22016-05-10 03:52:04 -0700801 stats_.IncreaseCounter(output_size_samples_, fs_hz_);
henrik.lundin7a926812016-05-12 13:51:28 -0700802
803 // Check for muted state.
804 if (enable_muted_state_ && expand_->Muted() && packet_buffer_->Empty()) {
805 RTC_DCHECK_EQ(last_mode_, kModeExpand);
806 playout_timestamp_ += static_cast<uint32_t>(output_size_samples_);
807 audio_frame->sample_rate_hz_ = fs_hz_;
808 audio_frame->samples_per_channel_ = output_size_samples_;
809 audio_frame->timestamp_ =
810 first_packet_
811 ? 0
812 : timestamp_scaler_->ToExternal(playout_timestamp_) -
813 static_cast<uint32_t>(audio_frame->samples_per_channel_);
814 audio_frame->num_channels_ = sync_buffer_->Channels();
henrik.lundin612c25e2016-05-25 08:21:04 -0700815 stats_.ExpandedNoiseSamples(output_size_samples_);
henrik.lundin7a926812016-05-12 13:51:28 -0700816 *muted = true;
817 return 0;
818 }
819
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000820 int return_value = GetDecision(&operation, &packet_list, &dtmf_event,
821 &play_dtmf);
822 if (return_value != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000823 last_mode_ = kModeError;
824 return return_value;
825 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000826
827 AudioDecoder::SpeechType speech_type;
828 int length = 0;
829 int decode_return_value = Decode(&packet_list, &operation,
830 &length, &speech_type);
831
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000832 assert(vad_.get());
833 bool sid_frame_available =
834 (operation == kRfc3389Cng && !packet_list.empty());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700835 vad_->Update(decoded_buffer_.get(), static_cast<size_t>(length), speech_type,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000836 sid_frame_available, fs_hz_);
837
henrik.lundinb1fb72b2016-05-03 08:18:47 -0700838 if (sid_frame_available || speech_type == AudioDecoder::kComfortNoise) {
839 // Start a new stopwatch since we are decoding a new CNG packet.
840 generated_noise_stopwatch_ = tick_timer_->GetNewStopwatch();
841 }
842
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000843 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000844 switch (operation) {
845 case kNormal: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000846 DoNormal(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000847 break;
848 }
849 case kMerge: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000850 DoMerge(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000851 break;
852 }
853 case kExpand: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000854 return_value = DoExpand(play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000855 break;
856 }
Henrik Lundincf808d22015-05-27 14:33:29 +0200857 case kAccelerate:
858 case kFastAccelerate: {
859 const bool fast_accelerate =
860 enable_fast_accelerate_ && (operation == kFastAccelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000861 return_value = DoAccelerate(decoded_buffer_.get(), length, speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +0200862 play_dtmf, fast_accelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000863 break;
864 }
865 case kPreemptiveExpand: {
866 return_value = DoPreemptiveExpand(decoded_buffer_.get(), length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000867 speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000868 break;
869 }
870 case kRfc3389Cng:
871 case kRfc3389CngNoPacket: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000872 return_value = DoRfc3389Cng(&packet_list, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000873 break;
874 }
875 case kCodecInternalCng: {
876 // This handles the case when there is no transmission and the decoder
877 // should produce internal comfort noise.
878 // TODO(hlundin): Write test for codec-internal CNG.
minyuel6d92bf52015-09-23 15:20:39 +0200879 DoCodecInternalCng(decoded_buffer_.get(), length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000880 break;
881 }
882 case kDtmf: {
883 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000884 return_value = DoDtmf(dtmf_event, &play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000885 break;
886 }
887 case kAlternativePlc: {
888 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000889 DoAlternativePlc(false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000890 break;
891 }
892 case kAlternativePlcIncreaseTimestamp: {
893 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000894 DoAlternativePlc(true);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000895 break;
896 }
897 case kAudioRepetitionIncreaseTimestamp: {
898 // TODO(hlundin): Write test for this.
Peter Kastingb7e50542015-06-11 12:55:50 -0700899 sync_buffer_->IncreaseEndTimestamp(
900 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000901 // Skipping break on purpose. Execution should move on into the
902 // next case.
kjellander@webrtc.org7d2b6a92015-01-28 18:37:58 +0000903 FALLTHROUGH();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000904 }
905 case kAudioRepetition: {
906 // TODO(hlundin): Write test for this.
907 // Copy last |output_size_samples_| from |sync_buffer_| to
908 // |algorithm_buffer|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000909 algorithm_buffer_->PushBackFromIndex(
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000910 *sync_buffer_, sync_buffer_->Size() - output_size_samples_);
911 expand_->Reset();
912 break;
913 }
914 case kUndefined: {
Henrik Lundind67a2192015-08-03 12:54:37 +0200915 LOG(LS_ERROR) << "Invalid operation kUndefined.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000916 assert(false); // This should not happen.
917 last_mode_ = kModeError;
918 return kInvalidOperation;
919 }
920 } // End of switch.
minyue5bd33972016-05-02 04:46:11 -0700921 last_operation_ = operation;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000922 if (return_value < 0) {
923 return return_value;
924 }
925
926 if (last_mode_ != kModeRfc3389Cng) {
927 comfort_noise_->Reset();
928 }
929
930 // Copy from |algorithm_buffer| to |sync_buffer_|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000931 sync_buffer_->PushBack(*algorithm_buffer_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000932
933 // Extract data from |sync_buffer_| to |output|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000934 size_t num_output_samples_per_channel = output_size_samples_;
935 size_t num_output_samples = output_size_samples_ * sync_buffer_->Channels();
henrik.lundin6d8e0112016-03-04 10:34:21 -0800936 if (num_output_samples > AudioFrame::kMaxDataSizeSamples) {
937 LOG(LS_WARNING) << "Output array is too short. "
938 << AudioFrame::kMaxDataSizeSamples << " < "
939 << output_size_samples_ << " * "
940 << sync_buffer_->Channels();
941 num_output_samples = AudioFrame::kMaxDataSizeSamples;
942 num_output_samples_per_channel =
943 AudioFrame::kMaxDataSizeSamples / sync_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000944 }
henrik.lundin6d8e0112016-03-04 10:34:21 -0800945 sync_buffer_->GetNextAudioInterleaved(num_output_samples_per_channel,
946 audio_frame);
947 audio_frame->sample_rate_hz_ = fs_hz_;
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200948 if (sync_buffer_->FutureLength() < expand_->overlap_length()) {
949 // The sync buffer should always contain |overlap_length| samples, but now
950 // too many samples have been extracted. Reinstall the |overlap_length|
951 // lookahead by moving the index.
952 const size_t missing_lookahead_samples =
953 expand_->overlap_length() - sync_buffer_->FutureLength();
henrikg91d6ede2015-09-17 00:24:34 -0700954 RTC_DCHECK_GE(sync_buffer_->next_index(), missing_lookahead_samples);
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200955 sync_buffer_->set_next_index(sync_buffer_->next_index() -
956 missing_lookahead_samples);
957 }
henrik.lundin6d8e0112016-03-04 10:34:21 -0800958 if (audio_frame->samples_per_channel_ != output_size_samples_) {
959 LOG(LS_ERROR) << "audio_frame->samples_per_channel_ ("
960 << audio_frame->samples_per_channel_
Henrik Lundind67a2192015-08-03 12:54:37 +0200961 << ") != output_size_samples_ (" << output_size_samples_
962 << ")";
minyue@webrtc.orgdb1cefc2013-08-13 01:39:21 +0000963 // TODO(minyue): treatment of under-run, filling zeros
henrik.lundin6d8e0112016-03-04 10:34:21 -0800964 memset(audio_frame->data_, 0, num_output_samples * sizeof(int16_t));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000965 return kSampleUnderrun;
966 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000967
968 // Should always have overlap samples left in the |sync_buffer_|.
henrikg91d6ede2015-09-17 00:24:34 -0700969 RTC_DCHECK_GE(sync_buffer_->FutureLength(), expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000970
971 if (play_dtmf) {
henrik.lundin6d8e0112016-03-04 10:34:21 -0800972 return_value =
973 DtmfOverdub(dtmf_event, sync_buffer_->Channels(), audio_frame->data_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000974 }
975
976 // Update the background noise parameters if last operation wrote data
977 // straight from the decoder to the |sync_buffer_|. That is, none of the
978 // operations that modify the signal can be followed by a parameter update.
979 if ((last_mode_ == kModeNormal) ||
980 (last_mode_ == kModeAccelerateFail) ||
981 (last_mode_ == kModePreemptiveExpandFail) ||
982 (last_mode_ == kModeRfc3389Cng) ||
983 (last_mode_ == kModeCodecInternalCng)) {
984 background_noise_->Update(*sync_buffer_, *vad_.get());
985 }
986
987 if (operation == kDtmf) {
988 // DTMF data was written the end of |sync_buffer_|.
989 // Update index to end of DTMF data in |sync_buffer_|.
990 sync_buffer_->set_dtmf_index(sync_buffer_->Size());
991 }
992
henrik.lundin@webrtc.orged865b52014-03-06 10:28:07 +0000993 if (last_mode_ != kModeExpand) {
994 // If last operation was not expand, calculate the |playout_timestamp_| from
995 // the |sync_buffer_|. However, do not update the |playout_timestamp_| if it
996 // would be moved "backwards".
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000997 uint32_t temp_timestamp = sync_buffer_->end_timestamp() -
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000998 static_cast<uint32_t>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000999 if (static_cast<int32_t>(temp_timestamp - playout_timestamp_) > 0) {
1000 playout_timestamp_ = temp_timestamp;
1001 }
1002 } else {
1003 // Use dead reckoning to estimate the |playout_timestamp_|.
Peter Kastingb7e50542015-06-11 12:55:50 -07001004 playout_timestamp_ += static_cast<uint32_t>(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001005 }
henrik.lundin15c51e32016-04-06 08:38:56 -07001006 // Set the timestamp in the audio frame to zero before the first packet has
1007 // been inserted. Otherwise, subtract the frame size in samples to get the
1008 // timestamp of the first sample in the frame (playout_timestamp_ is the
1009 // last + 1).
1010 audio_frame->timestamp_ =
1011 first_packet_
1012 ? 0
1013 : timestamp_scaler_->ToExternal(playout_timestamp_) -
1014 static_cast<uint32_t>(audio_frame->samples_per_channel_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001015
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001016 if (!(last_mode_ == kModeRfc3389Cng ||
1017 last_mode_ == kModeCodecInternalCng ||
1018 last_mode_ == kModeExpand)) {
1019 generated_noise_stopwatch_.reset();
1020 }
1021
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001022 if (decode_return_value) return decode_return_value;
1023 return return_value;
1024}
1025
1026int NetEqImpl::GetDecision(Operations* operation,
1027 PacketList* packet_list,
1028 DtmfEvent* dtmf_event,
1029 bool* play_dtmf) {
1030 // Initialize output variables.
1031 *play_dtmf = false;
1032 *operation = kUndefined;
1033
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001034 assert(sync_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001035 uint32_t end_timestamp = sync_buffer_->end_timestamp();
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001036 if (!new_codec_) {
1037 const uint32_t five_seconds_samples = 5 * fs_hz_;
1038 packet_buffer_->DiscardOldPackets(end_timestamp, five_seconds_samples);
1039 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001040 const RTPHeader* header = packet_buffer_->NextRtpHeader();
1041
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001042 RTC_DCHECK(!generated_noise_stopwatch_ ||
1043 generated_noise_stopwatch_->ElapsedTicks() >= 1);
1044 uint64_t generated_noise_samples =
1045 generated_noise_stopwatch_
1046 ? (generated_noise_stopwatch_->ElapsedTicks() - 1) *
1047 output_size_samples_ +
1048 decision_logic_->noise_fast_forward()
1049 : 0;
1050
henrik.lundin@webrtc.orgca8cb952014-03-12 10:26:52 +00001051 if (decision_logic_->CngRfc3389On() || last_mode_ == kModeRfc3389Cng) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001052 // Because of timestamp peculiarities, we have to "manually" disallow using
1053 // a CNG packet with the same timestamp as the one that was last played.
1054 // This can happen when using redundancy and will cause the timing to shift.
henrik.lundin@webrtc.org24779fe2014-03-14 12:40:05 +00001055 while (header && decoder_database_->IsComfortNoise(header->payloadType) &&
1056 (end_timestamp >= header->timestamp ||
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001057 end_timestamp + generated_noise_samples > header->timestamp)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001058 // Don't use this packet, discard it.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001059 if (packet_buffer_->DiscardNextPacket() != PacketBuffer::kOK) {
1060 assert(false); // Must be ok by design.
1061 }
1062 // Check buffer again.
1063 if (!new_codec_) {
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001064 packet_buffer_->DiscardOldPackets(end_timestamp, 5 * fs_hz_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001065 }
1066 header = packet_buffer_->NextRtpHeader();
1067 }
1068 }
1069
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001070 assert(expand_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001071 const int samples_left = static_cast<int>(sync_buffer_->FutureLength() -
1072 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001073 if (last_mode_ == kModeAccelerateSuccess ||
1074 last_mode_ == kModeAccelerateLowEnergy ||
1075 last_mode_ == kModePreemptiveExpandSuccess ||
1076 last_mode_ == kModePreemptiveExpandLowEnergy) {
1077 // Subtract (samples_left + output_size_samples_) from sampleMemory.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001078 decision_logic_->AddSampleMemory(
1079 -(samples_left + rtc::checked_cast<int>(output_size_samples_)));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001080 }
1081
1082 // Check if it is time to play a DTMF event.
Peter Kastingb7e50542015-06-11 12:55:50 -07001083 if (dtmf_buffer_->GetEvent(
1084 static_cast<uint32_t>(
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001085 end_timestamp + generated_noise_samples),
Peter Kastingb7e50542015-06-11 12:55:50 -07001086 dtmf_event)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001087 *play_dtmf = true;
1088 }
1089
1090 // Get instruction.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001091 assert(sync_buffer_.get());
1092 assert(expand_.get());
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001093 generated_noise_samples =
1094 generated_noise_stopwatch_
1095 ? generated_noise_stopwatch_->ElapsedTicks() * output_size_samples_ +
1096 decision_logic_->noise_fast_forward()
1097 : 0;
1098 *operation = decision_logic_->GetDecision(
1099 *sync_buffer_, *expand_, decoder_frame_length_, header, last_mode_,
1100 *play_dtmf, generated_noise_samples, &reset_decoder_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001101
1102 // Check if we already have enough samples in the |sync_buffer_|. If so,
1103 // change decision to normal, unless the decision was merge, accelerate, or
1104 // preemptive expand.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001105 if (samples_left >= rtc::checked_cast<int>(output_size_samples_) &&
1106 *operation != kMerge &&
1107 *operation != kAccelerate &&
1108 *operation != kFastAccelerate &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001109 *operation != kPreemptiveExpand) {
1110 *operation = kNormal;
1111 return 0;
1112 }
1113
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001114 decision_logic_->ExpandDecision(*operation);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001115
1116 // Check conditions for reset.
1117 if (new_codec_ || *operation == kUndefined) {
1118 // The only valid reason to get kUndefined is that new_codec_ is set.
1119 assert(new_codec_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001120 if (*play_dtmf && !header) {
1121 timestamp_ = dtmf_event->timestamp;
1122 } else {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001123 if (!header) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001124 LOG(LS_ERROR) << "Packet missing where it shouldn't.";
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001125 return -1;
1126 }
1127 timestamp_ = header->timestamp;
ossu108ecec2016-07-08 08:45:18 -07001128 if (*operation == kRfc3389CngNoPacket &&
1129 decoder_database_->IsComfortNoise(header->payloadType)) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001130 // Change decision to CNG packet, since we do have a CNG packet, but it
1131 // was considered too early to use. Now, use it anyway.
1132 *operation = kRfc3389Cng;
1133 } else if (*operation != kRfc3389Cng) {
1134 *operation = kNormal;
1135 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001136 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001137 // Adjust |sync_buffer_| timestamp before setting |end_timestamp| to the
1138 // new value.
1139 sync_buffer_->IncreaseEndTimestamp(timestamp_ - end_timestamp);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001140 end_timestamp = timestamp_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001141 new_codec_ = false;
1142 decision_logic_->SoftReset();
1143 buffer_level_filter_->Reset();
1144 delay_manager_->Reset();
1145 stats_.ResetMcu();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001146 }
1147
Peter Kastingdce40cf2015-08-24 14:52:23 -07001148 size_t required_samples = output_size_samples_;
1149 const size_t samples_10_ms = static_cast<size_t>(80 * fs_mult_);
1150 const size_t samples_20_ms = 2 * samples_10_ms;
1151 const size_t samples_30_ms = 3 * samples_10_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001152
1153 switch (*operation) {
1154 case kExpand: {
1155 timestamp_ = end_timestamp;
1156 return 0;
1157 }
1158 case kRfc3389CngNoPacket:
1159 case kCodecInternalCng: {
1160 return 0;
1161 }
1162 case kDtmf: {
1163 // TODO(hlundin): Write test for this.
1164 // Update timestamp.
1165 timestamp_ = end_timestamp;
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001166 const uint64_t generated_noise_samples =
1167 generated_noise_stopwatch_
1168 ? generated_noise_stopwatch_->ElapsedTicks() *
1169 output_size_samples_ +
1170 decision_logic_->noise_fast_forward()
1171 : 0;
1172 if (generated_noise_samples > 0 && last_mode_ != kModeDtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001173 // Make a jump in timestamp due to the recently played comfort noise.
Peter Kastingb7e50542015-06-11 12:55:50 -07001174 uint32_t timestamp_jump =
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001175 static_cast<uint32_t>(generated_noise_samples);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001176 sync_buffer_->IncreaseEndTimestamp(timestamp_jump);
1177 timestamp_ += timestamp_jump;
1178 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001179 return 0;
1180 }
Henrik Lundincf808d22015-05-27 14:33:29 +02001181 case kAccelerate:
1182 case kFastAccelerate: {
1183 // In order to do an accelerate we need at least 30 ms of audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001184 if (samples_left >= static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001185 // Already have enough data, so we do not need to extract any more.
1186 decision_logic_->set_sample_memory(samples_left);
1187 decision_logic_->set_prev_time_scale(true);
1188 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001189 } else if (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001190 decoder_frame_length_ >= samples_30_ms) {
1191 // Avoid decoding more data as it might overflow the playout buffer.
1192 *operation = kNormal;
1193 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001194 } else if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001195 decoder_frame_length_ < samples_30_ms) {
1196 // Build up decoded data by decoding at least 20 ms of audio data. Do
1197 // not perform accelerate yet, but wait until we only need to do one
1198 // decoding.
1199 required_samples = 2 * output_size_samples_;
1200 *operation = kNormal;
1201 }
1202 // If none of the above is true, we have one of two possible situations:
1203 // (1) 20 ms <= samples_left < 30 ms and decoder_frame_length_ < 30 ms; or
1204 // (2) samples_left < 10 ms and decoder_frame_length_ >= 30 ms.
1205 // In either case, we move on with the accelerate decision, and decode one
1206 // frame now.
1207 break;
1208 }
1209 case kPreemptiveExpand: {
1210 // In order to do a preemptive expand we need at least 30 ms of decoded
1211 // audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001212 if ((samples_left >= static_cast<int>(samples_30_ms)) ||
1213 (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001214 decoder_frame_length_ >= samples_30_ms)) {
1215 // Already have enough data, so we do not need to extract any more.
1216 // Or, avoid decoding more data as it might overflow the playout buffer.
1217 // Still try preemptive expand, though.
1218 decision_logic_->set_sample_memory(samples_left);
1219 decision_logic_->set_prev_time_scale(true);
1220 return 0;
1221 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07001222 if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001223 decoder_frame_length_ < samples_30_ms) {
1224 // Build up decoded data by decoding at least 20 ms of audio data.
1225 // Still try to perform preemptive expand.
1226 required_samples = 2 * output_size_samples_;
1227 }
1228 // Move on with the preemptive expand decision.
1229 break;
1230 }
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001231 case kMerge: {
1232 required_samples =
1233 std::max(merge_->RequiredFutureSamples(), required_samples);
1234 break;
1235 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001236 default: {
1237 // Do nothing.
1238 }
1239 }
1240
1241 // Get packets from buffer.
1242 int extracted_samples = 0;
1243 if (header &&
1244 *operation != kAlternativePlc &&
1245 *operation != kAlternativePlcIncreaseTimestamp &&
1246 *operation != kAudioRepetition &&
1247 *operation != kAudioRepetitionIncreaseTimestamp) {
1248 sync_buffer_->IncreaseEndTimestamp(header->timestamp - end_timestamp);
1249 if (decision_logic_->CngOff()) {
1250 // Adjustment of timestamp only corresponds to an actual packet loss
1251 // if comfort noise is not played. If comfort noise was just played,
1252 // this adjustment of timestamp is only done to get back in sync with the
1253 // stream timestamp; no loss to report.
1254 stats_.LostSamples(header->timestamp - end_timestamp);
1255 }
1256
1257 if (*operation != kRfc3389Cng) {
1258 // We are about to decode and use a non-CNG packet.
1259 decision_logic_->SetCngOff();
1260 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001261
1262 extracted_samples = ExtractPackets(required_samples, packet_list);
1263 if (extracted_samples < 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001264 return kPacketBufferCorruption;
1265 }
1266 }
1267
Henrik Lundincf808d22015-05-27 14:33:29 +02001268 if (*operation == kAccelerate || *operation == kFastAccelerate ||
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001269 *operation == kPreemptiveExpand) {
1270 decision_logic_->set_sample_memory(samples_left + extracted_samples);
1271 decision_logic_->set_prev_time_scale(true);
1272 }
1273
Henrik Lundincf808d22015-05-27 14:33:29 +02001274 if (*operation == kAccelerate || *operation == kFastAccelerate) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001275 // Check that we have enough data (30ms) to do accelerate.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001276 if (extracted_samples + samples_left < static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001277 // TODO(hlundin): Write test for this.
1278 // Not enough, do normal operation instead.
1279 *operation = kNormal;
1280 }
1281 }
1282
1283 timestamp_ = end_timestamp;
1284 return 0;
1285}
1286
1287int NetEqImpl::Decode(PacketList* packet_list, Operations* operation,
1288 int* decoded_length,
1289 AudioDecoder::SpeechType* speech_type) {
1290 *speech_type = AudioDecoder::kSpeech;
minyuel6d92bf52015-09-23 15:20:39 +02001291
1292 // When packet_list is empty, we may be in kCodecInternalCng mode, and for
1293 // that we use current active decoder.
1294 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1295
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001296 if (!packet_list->empty()) {
1297 const Packet* packet = packet_list->front();
pkasting@chromium.org0e81fdf2015-02-02 23:54:03 +00001298 uint8_t payload_type = packet->header.payloadType;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001299 if (!decoder_database_->IsComfortNoise(payload_type)) {
1300 decoder = decoder_database_->GetDecoder(payload_type);
1301 assert(decoder);
1302 if (!decoder) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001303 LOG(LS_WARNING) << "Unknown payload type "
1304 << static_cast<int>(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001305 PacketBuffer::DeleteAllPackets(packet_list);
1306 return kDecoderNotFound;
1307 }
1308 bool decoder_changed;
1309 decoder_database_->SetActiveDecoder(payload_type, &decoder_changed);
1310 if (decoder_changed) {
1311 // We have a new decoder. Re-init some values.
1312 const DecoderDatabase::DecoderInfo* decoder_info = decoder_database_
1313 ->GetDecoderInfo(payload_type);
1314 assert(decoder_info);
1315 if (!decoder_info) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001316 LOG(LS_WARNING) << "Unknown payload type "
1317 << static_cast<int>(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001318 PacketBuffer::DeleteAllPackets(packet_list);
1319 return kDecoderNotFound;
1320 }
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001321 // If sampling rate or number of channels has changed, we need to make
1322 // a reset.
kwibergc0f2dcf2016-05-31 06:28:03 -07001323 if (decoder_info->SampleRateHz() != fs_hz_ ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001324 decoder->Channels() != algorithm_buffer_->Channels()) {
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001325 // TODO(tlegrand): Add unittest to cover this event.
kwibergc0f2dcf2016-05-31 06:28:03 -07001326 SetSampleRateAndChannels(decoder_info->SampleRateHz(),
1327 decoder->Channels());
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001328 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001329 sync_buffer_->set_end_timestamp(timestamp_);
1330 playout_timestamp_ = timestamp_;
1331 }
1332 }
1333 }
1334
1335 if (reset_decoder_) {
1336 // TODO(hlundin): Write test for this.
Karl Wiberg43766482015-08-27 15:22:11 +02001337 if (decoder)
1338 decoder->Reset();
1339
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001340 // Reset comfort noise decoder.
ossu97ba30e2016-04-25 07:55:58 -07001341 ComfortNoiseDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02001342 if (cng_decoder)
1343 cng_decoder->Reset();
1344
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001345 reset_decoder_ = false;
1346 }
1347
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001348 *decoded_length = 0;
1349 // Update codec-internal PLC state.
1350 if ((*operation == kMerge) && decoder && decoder->HasDecodePlc()) {
1351 decoder->DecodePlc(1, &decoded_buffer_[*decoded_length]);
1352 }
1353
minyuel6d92bf52015-09-23 15:20:39 +02001354 int return_value;
1355 if (*operation == kCodecInternalCng) {
1356 RTC_DCHECK(packet_list->empty());
1357 return_value = DecodeCng(decoder, decoded_length, speech_type);
1358 } else {
1359 return_value = DecodeLoop(packet_list, *operation, decoder,
1360 decoded_length, speech_type);
1361 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001362
1363 if (*decoded_length < 0) {
1364 // Error returned from the decoder.
1365 *decoded_length = 0;
Peter Kastingb7e50542015-06-11 12:55:50 -07001366 sync_buffer_->IncreaseEndTimestamp(
1367 static_cast<uint32_t>(decoder_frame_length_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001368 int error_code = 0;
1369 if (decoder)
1370 error_code = decoder->ErrorCode();
1371 if (error_code != 0) {
1372 // Got some error code from the decoder.
1373 decoder_error_code_ = error_code;
1374 return_value = kDecoderErrorCode;
Henrik Lundind67a2192015-08-03 12:54:37 +02001375 LOG(LS_WARNING) << "Decoder returned error code: " << error_code;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001376 } else {
1377 // Decoder does not implement error codes. Return generic error.
1378 return_value = kOtherDecoderError;
Henrik Lundind67a2192015-08-03 12:54:37 +02001379 LOG(LS_WARNING) << "Decoder error (no error code)";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001380 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001381 *operation = kExpand; // Do expansion to get data instead.
1382 }
1383 if (*speech_type != AudioDecoder::kComfortNoise) {
1384 // Don't increment timestamp if codec returned CNG speech type
1385 // since in this case, the we will increment the CNGplayedTS counter.
1386 // Increase with number of samples per channel.
1387 assert(*decoded_length == 0 ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001388 (decoder && decoder->Channels() == sync_buffer_->Channels()));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001389 sync_buffer_->IncreaseEndTimestamp(
1390 *decoded_length / static_cast<int>(sync_buffer_->Channels()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001391 }
1392 return return_value;
1393}
1394
minyuel6d92bf52015-09-23 15:20:39 +02001395int NetEqImpl::DecodeCng(AudioDecoder* decoder, int* decoded_length,
1396 AudioDecoder::SpeechType* speech_type) {
1397 if (!decoder) {
1398 // This happens when active decoder is not defined.
1399 *decoded_length = -1;
1400 return 0;
1401 }
1402
1403 while (*decoded_length < rtc::checked_cast<int>(output_size_samples_)) {
1404 const int length = decoder->Decode(
1405 nullptr, 0, fs_hz_,
1406 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1407 &decoded_buffer_[*decoded_length], speech_type);
1408 if (length > 0) {
1409 *decoded_length += length;
minyuel6d92bf52015-09-23 15:20:39 +02001410 } else {
1411 // Error.
1412 LOG(LS_WARNING) << "Failed to decode CNG";
1413 *decoded_length = -1;
1414 break;
1415 }
1416 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1417 // Guard against overflow.
1418 LOG(LS_WARNING) << "Decoded too much CNG.";
1419 return kDecodedTooMuch;
1420 }
1421 }
1422 return 0;
1423}
1424
1425int NetEqImpl::DecodeLoop(PacketList* packet_list, const Operations& operation,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001426 AudioDecoder* decoder, int* decoded_length,
1427 AudioDecoder::SpeechType* speech_type) {
1428 Packet* packet = NULL;
1429 if (!packet_list->empty()) {
1430 packet = packet_list->front();
1431 }
minyuel6d92bf52015-09-23 15:20:39 +02001432
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001433 // Do decoding.
1434 while (packet &&
1435 !decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1436 assert(decoder); // At this point, we must have a decoder object.
1437 // The number of channels in the |sync_buffer_| should be the same as the
1438 // number decoder channels.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001439 assert(sync_buffer_->Channels() == decoder->Channels());
1440 assert(decoded_buffer_length_ >= kMaxFrameSize * decoder->Channels());
minyuel6d92bf52015-09-23 15:20:39 +02001441 assert(operation == kNormal || operation == kAccelerate ||
1442 operation == kFastAccelerate || operation == kMerge ||
1443 operation == kPreemptiveExpand);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001444 packet_list->pop_front();
ossudc431ce2016-08-31 08:51:13 -07001445 const size_t payload_length = packet->payload.size();
Peter Kasting36b7cc32015-06-11 19:57:18 -07001446 int decode_length;
ossu17e3fa12016-09-08 04:52:55 -07001447 if (!packet->primary) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001448 // This is a redundant payload; call the special decoder method.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001449 decode_length = decoder->DecodeRedundant(
ossudc431ce2016-08-31 08:51:13 -07001450 packet->payload.data(), packet->payload.size(), fs_hz_,
minyue@webrtc.org7f7d7e32015-03-16 12:30:37 +00001451 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001452 &decoded_buffer_[*decoded_length], speech_type);
1453 } else {
ossudc431ce2016-08-31 08:51:13 -07001454 decode_length = decoder->Decode(
1455 packet->payload.data(), packet->payload.size(), fs_hz_,
1456 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1457 &decoded_buffer_[*decoded_length], speech_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001458 }
1459
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001460 delete packet;
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001461 packet = NULL;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001462 if (decode_length > 0) {
1463 *decoded_length += decode_length;
1464 // Update |decoder_frame_length_| with number of samples per channel.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001465 decoder_frame_length_ =
Peter Kastingdce40cf2015-08-24 14:52:23 -07001466 static_cast<size_t>(decode_length) / decoder->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001467 } else if (decode_length < 0) {
1468 // Error.
Henrik Lundind67a2192015-08-03 12:54:37 +02001469 LOG(LS_WARNING) << "Decode " << decode_length << " " << payload_length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001470 *decoded_length = -1;
1471 PacketBuffer::DeleteAllPackets(packet_list);
1472 break;
1473 }
1474 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1475 // Guard against overflow.
Henrik Lundind67a2192015-08-03 12:54:37 +02001476 LOG(LS_WARNING) << "Decoded too much.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001477 PacketBuffer::DeleteAllPackets(packet_list);
1478 return kDecodedTooMuch;
1479 }
1480 if (!packet_list->empty()) {
1481 packet = packet_list->front();
1482 } else {
1483 packet = NULL;
1484 }
1485 } // End of decode loop.
1486
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001487 // If the list is not empty at this point, either a decoding error terminated
1488 // the while-loop, or list must hold exactly one CNG packet.
1489 assert(packet_list->empty() || *decoded_length < 0 ||
1490 (packet_list->size() == 1 && packet &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001491 decoder_database_->IsComfortNoise(packet->header.payloadType)));
1492 return 0;
1493}
1494
1495void NetEqImpl::DoNormal(const int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001496 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001497 assert(normal_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001498 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001499 normal_->Process(decoded_buffer, decoded_length, last_mode_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001500 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001501 if (decoded_length != 0) {
1502 last_mode_ = kModeNormal;
1503 }
1504
1505 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1506 if ((speech_type == AudioDecoder::kComfortNoise)
1507 || ((last_mode_ == kModeCodecInternalCng)
1508 && (decoded_length == 0))) {
1509 // TODO(hlundin): Remove second part of || statement above.
1510 last_mode_ = kModeCodecInternalCng;
1511 }
1512
1513 if (!play_dtmf) {
1514 dtmf_tone_generator_->Reset();
1515 }
1516}
1517
1518void NetEqImpl::DoMerge(int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001519 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001520 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001521 assert(merge_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001522 size_t new_length = merge_->Process(decoded_buffer, decoded_length,
1523 mute_factor_array_.get(),
1524 algorithm_buffer_.get());
1525 size_t expand_length_correction = new_length -
1526 decoded_length / algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001527
1528 // Update in-call and post-call statistics.
1529 if (expand_->MuteFactor(0) == 0) {
1530 // Expand generates only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001531 stats_.ExpandedNoiseSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001532 } else {
1533 // Expansion generates more than only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001534 stats_.ExpandedVoiceSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001535 }
1536
1537 last_mode_ = kModeMerge;
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 }
1542 expand_->Reset();
1543 if (!play_dtmf) {
1544 dtmf_tone_generator_->Reset();
1545 }
1546}
1547
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001548int NetEqImpl::DoExpand(bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001549 while ((sync_buffer_->FutureLength() - expand_->overlap_length()) <
Peter Kastingdce40cf2015-08-24 14:52:23 -07001550 output_size_samples_) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001551 algorithm_buffer_->Clear();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001552 int return_value = expand_->Process(algorithm_buffer_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001553 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001554
1555 // Update in-call and post-call statistics.
1556 if (expand_->MuteFactor(0) == 0) {
1557 // Expand operation generates only noise.
1558 stats_.ExpandedNoiseSamples(length);
1559 } else {
1560 // Expand operation generates more than only noise.
1561 stats_.ExpandedVoiceSamples(length);
1562 }
1563
1564 last_mode_ = kModeExpand;
1565
1566 if (return_value < 0) {
1567 return return_value;
1568 }
1569
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001570 sync_buffer_->PushBack(*algorithm_buffer_);
1571 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001572 }
1573 if (!play_dtmf) {
1574 dtmf_tone_generator_->Reset();
1575 }
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001576
1577 if (!generated_noise_stopwatch_) {
1578 // Start a new stopwatch since we may be covering for a lost CNG packet.
1579 generated_noise_stopwatch_ = tick_timer_->GetNewStopwatch();
1580 }
1581
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001582 return 0;
1583}
1584
Henrik Lundincf808d22015-05-27 14:33:29 +02001585int NetEqImpl::DoAccelerate(int16_t* decoded_buffer,
1586 size_t decoded_length,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001587 AudioDecoder::SpeechType speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +02001588 bool play_dtmf,
1589 bool fast_accelerate) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001590 const size_t required_samples =
1591 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001592 size_t borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001593 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001594 size_t decoded_length_per_channel = decoded_length / num_channels;
1595 if (decoded_length_per_channel < required_samples) {
1596 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001597 borrowed_samples_per_channel = static_cast<int>(required_samples -
1598 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001599 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1600 decoded_buffer,
1601 sizeof(int16_t) * decoded_length);
1602 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1603 decoded_buffer);
1604 decoded_length = required_samples * num_channels;
1605 }
1606
Peter Kastingdce40cf2015-08-24 14:52:23 -07001607 size_t samples_removed;
Henrik Lundincf808d22015-05-27 14:33:29 +02001608 Accelerate::ReturnCodes return_code =
1609 accelerate_->Process(decoded_buffer, decoded_length, fast_accelerate,
1610 algorithm_buffer_.get(), &samples_removed);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001611 stats_.AcceleratedSamples(samples_removed);
1612 switch (return_code) {
1613 case Accelerate::kSuccess:
1614 last_mode_ = kModeAccelerateSuccess;
1615 break;
1616 case Accelerate::kSuccessLowEnergy:
1617 last_mode_ = kModeAccelerateLowEnergy;
1618 break;
1619 case Accelerate::kNoStretch:
1620 last_mode_ = kModeAccelerateFail;
1621 break;
1622 case Accelerate::kError:
1623 // TODO(hlundin): Map to kModeError instead?
1624 last_mode_ = kModeAccelerateFail;
1625 return kAccelerateError;
1626 }
1627
1628 if (borrowed_samples_per_channel > 0) {
1629 // Copy borrowed samples back to the |sync_buffer_|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001630 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001631 if (length < borrowed_samples_per_channel) {
1632 // This destroys the beginning of the buffer, but will not cause any
1633 // problems.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001634 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001635 sync_buffer_->Size() -
1636 borrowed_samples_per_channel);
1637 sync_buffer_->PushFrontZeros(borrowed_samples_per_channel - length);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001638 algorithm_buffer_->PopFront(length);
1639 assert(algorithm_buffer_->Empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001640 } else {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001641 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001642 borrowed_samples_per_channel,
1643 sync_buffer_->Size() -
1644 borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001645 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001646 }
1647 }
1648
1649 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1650 if (speech_type == AudioDecoder::kComfortNoise) {
1651 last_mode_ = kModeCodecInternalCng;
1652 }
1653 if (!play_dtmf) {
1654 dtmf_tone_generator_->Reset();
1655 }
1656 expand_->Reset();
1657 return 0;
1658}
1659
1660int NetEqImpl::DoPreemptiveExpand(int16_t* decoded_buffer,
1661 size_t decoded_length,
1662 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001663 bool play_dtmf) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001664 const size_t required_samples =
1665 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001666 size_t num_channels = algorithm_buffer_->Channels();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001667 size_t borrowed_samples_per_channel = 0;
1668 size_t old_borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001669 size_t decoded_length_per_channel = decoded_length / num_channels;
1670 if (decoded_length_per_channel < required_samples) {
1671 // Must move data from the |sync_buffer_| in order to get 30 ms.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001672 borrowed_samples_per_channel =
1673 required_samples - decoded_length_per_channel;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001674 // Calculate how many of these were already played out.
Peter Kastingf045e4d2015-06-10 21:15:38 -07001675 old_borrowed_samples_per_channel =
Peter Kastingdce40cf2015-08-24 14:52:23 -07001676 (borrowed_samples_per_channel > sync_buffer_->FutureLength()) ?
1677 (borrowed_samples_per_channel - sync_buffer_->FutureLength()) : 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001678 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1679 decoded_buffer,
1680 sizeof(int16_t) * decoded_length);
1681 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1682 decoded_buffer);
1683 decoded_length = required_samples * num_channels;
1684 }
1685
Peter Kastingdce40cf2015-08-24 14:52:23 -07001686 size_t samples_added;
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001687 PreemptiveExpand::ReturnCodes return_code = preemptive_expand_->Process(
Peter Kastingdce40cf2015-08-24 14:52:23 -07001688 decoded_buffer, decoded_length,
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001689 old_borrowed_samples_per_channel,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001690 algorithm_buffer_.get(), &samples_added);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001691 stats_.PreemptiveExpandedSamples(samples_added);
1692 switch (return_code) {
1693 case PreemptiveExpand::kSuccess:
1694 last_mode_ = kModePreemptiveExpandSuccess;
1695 break;
1696 case PreemptiveExpand::kSuccessLowEnergy:
1697 last_mode_ = kModePreemptiveExpandLowEnergy;
1698 break;
1699 case PreemptiveExpand::kNoStretch:
1700 last_mode_ = kModePreemptiveExpandFail;
1701 break;
1702 case PreemptiveExpand::kError:
1703 // TODO(hlundin): Map to kModeError instead?
1704 last_mode_ = kModePreemptiveExpandFail;
1705 return kPreemptiveExpandError;
1706 }
1707
1708 if (borrowed_samples_per_channel > 0) {
1709 // Copy borrowed samples back to the |sync_buffer_|.
1710 sync_buffer_->ReplaceAtIndex(
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001711 *algorithm_buffer_, borrowed_samples_per_channel,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001712 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001713 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001714 }
1715
1716 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1717 if (speech_type == AudioDecoder::kComfortNoise) {
1718 last_mode_ = kModeCodecInternalCng;
1719 }
1720 if (!play_dtmf) {
1721 dtmf_tone_generator_->Reset();
1722 }
1723 expand_->Reset();
1724 return 0;
1725}
1726
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001727int NetEqImpl::DoRfc3389Cng(PacketList* packet_list, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001728 if (!packet_list->empty()) {
1729 // Must have exactly one SID frame at this point.
1730 assert(packet_list->size() == 1);
1731 Packet* packet = packet_list->front();
1732 packet_list->pop_front();
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001733 if (!decoder_database_->IsComfortNoise(packet->header.payloadType)) {
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001734 LOG(LS_ERROR) << "Trying to decode non-CNG payload as CNG.";
1735 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001736 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001737 // UpdateParameters() deletes |packet|.
1738 if (comfort_noise_->UpdateParameters(packet) ==
1739 ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001740 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001741 return -comfort_noise_->internal_error_code();
1742 }
1743 }
1744 int cn_return = comfort_noise_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001745 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001746 expand_->Reset();
1747 last_mode_ = kModeRfc3389Cng;
1748 if (!play_dtmf) {
1749 dtmf_tone_generator_->Reset();
1750 }
1751 if (cn_return == ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001752 decoder_error_code_ = comfort_noise_->internal_error_code();
1753 return kComfortNoiseErrorCode;
1754 } else if (cn_return == ComfortNoise::kUnknownPayloadType) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001755 return kUnknownRtpPayloadType;
1756 }
1757 return 0;
1758}
1759
minyuel6d92bf52015-09-23 15:20:39 +02001760void NetEqImpl::DoCodecInternalCng(const int16_t* decoded_buffer,
1761 size_t decoded_length) {
1762 RTC_DCHECK(normal_.get());
1763 RTC_DCHECK(mute_factor_array_.get());
1764 normal_->Process(decoded_buffer, decoded_length, last_mode_,
1765 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001766 last_mode_ = kModeCodecInternalCng;
1767 expand_->Reset();
1768}
1769
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001770int NetEqImpl::DoDtmf(const DtmfEvent& dtmf_event, bool* play_dtmf) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001771 // This block of the code and the block further down, handling |dtmf_switch|
1772 // are commented out. Otherwise playing out-of-band DTMF would fail in VoE
1773 // test, DtmfTest.ManualSuccessfullySendsOutOfBandTelephoneEvents. This is
1774 // equivalent to |dtmf_switch| always be false.
1775 //
1776 // See http://webrtc-codereview.appspot.com/1195004/ for discussion
1777 // On this issue. This change might cause some glitches at the point of
1778 // switch from audio to DTMF. Issue 1545 is filed to track this.
1779 //
1780 // bool dtmf_switch = false;
1781 // if ((last_mode_ != kModeDtmf) && dtmf_tone_generator_->initialized()) {
1782 // // Special case; see below.
1783 // // We must catch this before calling Generate, since |initialized| is
1784 // // modified in that call.
1785 // dtmf_switch = true;
1786 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001787
1788 int dtmf_return_value = 0;
1789 if (!dtmf_tone_generator_->initialized()) {
1790 // Initialize if not already done.
1791 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1792 dtmf_event.volume);
1793 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001794
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001795 if (dtmf_return_value == 0) {
1796 // Generate DTMF signal.
1797 dtmf_return_value = dtmf_tone_generator_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001798 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001799 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001800
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001801 if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001802 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001803 return dtmf_return_value;
1804 }
1805
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001806 // if (dtmf_switch) {
1807 // // This is the special case where the previous operation was DTMF
1808 // // overdub, but the current instruction is "regular" DTMF. We must make
1809 // // sure that the DTMF does not have any discontinuities. The first DTMF
1810 // // sample that we generate now must be played out immediately, therefore
1811 // // it must be copied to the speech buffer.
1812 // // TODO(hlundin): This code seems incorrect. (Legacy.) Write test and
1813 // // verify correct operation.
1814 // assert(false);
1815 // // Must generate enough data to replace all of the |sync_buffer_|
1816 // // "future".
1817 // int required_length = sync_buffer_->FutureLength();
1818 // assert(dtmf_tone_generator_->initialized());
1819 // dtmf_return_value = dtmf_tone_generator_->Generate(required_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001820 // algorithm_buffer_);
1821 // assert((size_t) required_length == algorithm_buffer_->Size());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001822 // if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001823 // algorithm_buffer_->Zeros(output_size_samples_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001824 // return dtmf_return_value;
1825 // }
1826 //
1827 // // Overwrite the "future" part of the speech buffer with the new DTMF
1828 // // data.
1829 // // TODO(hlundin): It seems that this overwriting has gone lost.
1830 // // Not adapted for multi-channel yet.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001831 // assert(algorithm_buffer_->Channels() == 1);
1832 // if (algorithm_buffer_->Channels() != 1) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001833 // LOG(LS_WARNING) << "DTMF not supported for more than one channel";
1834 // return kStereoNotSupported;
1835 // }
1836 // // Shuffle the remaining data to the beginning of algorithm buffer.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001837 // algorithm_buffer_->PopFront(sync_buffer_->FutureLength());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001838 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001839
Peter Kastingb7e50542015-06-11 12:55:50 -07001840 sync_buffer_->IncreaseEndTimestamp(
1841 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001842 expand_->Reset();
1843 last_mode_ = kModeDtmf;
1844
1845 // Set to false because the DTMF is already in the algorithm buffer.
1846 *play_dtmf = false;
1847 return 0;
1848}
1849
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001850void NetEqImpl::DoAlternativePlc(bool increase_timestamp) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001851 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001852 size_t length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001853 if (decoder && decoder->HasDecodePlc()) {
1854 // Use the decoder's packet-loss concealment.
1855 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1856 int16_t decoded_buffer[kMaxFrameSize];
1857 length = decoder->DecodePlc(1, decoded_buffer);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001858 if (length > 0)
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001859 algorithm_buffer_->PushBackInterleaved(decoded_buffer, length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001860 } else {
1861 // Do simple zero-stuffing.
1862 length = output_size_samples_;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001863 algorithm_buffer_->Zeros(length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001864 // By not advancing the timestamp, NetEq inserts samples.
1865 stats_.AddZeros(length);
1866 }
1867 if (increase_timestamp) {
Peter Kastingb7e50542015-06-11 12:55:50 -07001868 sync_buffer_->IncreaseEndTimestamp(static_cast<uint32_t>(length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001869 }
1870 expand_->Reset();
1871}
1872
1873int NetEqImpl::DtmfOverdub(const DtmfEvent& dtmf_event, size_t num_channels,
1874 int16_t* output) const {
1875 size_t out_index = 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001876 size_t overdub_length = output_size_samples_; // Default value.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001877
1878 if (sync_buffer_->dtmf_index() > sync_buffer_->next_index()) {
1879 // Special operation for transition from "DTMF only" to "DTMF overdub".
1880 out_index = std::min(
1881 sync_buffer_->dtmf_index() - sync_buffer_->next_index(),
Peter Kastingdce40cf2015-08-24 14:52:23 -07001882 output_size_samples_);
1883 overdub_length = output_size_samples_ - out_index;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001884 }
1885
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001886 AudioMultiVector dtmf_output(num_channels);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001887 int dtmf_return_value = 0;
1888 if (!dtmf_tone_generator_->initialized()) {
1889 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1890 dtmf_event.volume);
1891 }
1892 if (dtmf_return_value == 0) {
1893 dtmf_return_value = dtmf_tone_generator_->Generate(overdub_length,
1894 &dtmf_output);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001895 assert(overdub_length == dtmf_output.Size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001896 }
1897 dtmf_output.ReadInterleaved(overdub_length, &output[out_index]);
1898 return dtmf_return_value < 0 ? dtmf_return_value : 0;
1899}
1900
Peter Kastingdce40cf2015-08-24 14:52:23 -07001901int NetEqImpl::ExtractPackets(size_t required_samples,
1902 PacketList* packet_list) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001903 bool first_packet = true;
1904 uint8_t prev_payload_type = 0;
1905 uint32_t prev_timestamp = 0;
1906 uint16_t prev_sequence_number = 0;
1907 bool next_packet_available = false;
1908
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001909 const RTPHeader* header = packet_buffer_->NextRtpHeader();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001910 assert(header);
1911 if (!header) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001912 LOG(LS_ERROR) << "Packet buffer unexpectedly empty.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001913 return -1;
1914 }
turaj@webrtc.org7df97062013-08-02 18:07:13 +00001915 uint32_t first_timestamp = header->timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001916 int extracted_samples = 0;
1917
1918 // Packet extraction loop.
1919 do {
1920 timestamp_ = header->timestamp;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001921 size_t discard_count = 0;
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001922 Packet* packet = packet_buffer_->GetNextPacket(&discard_count);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001923 // |header| may be invalid after the |packet_buffer_| operation.
1924 header = NULL;
1925 if (!packet) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001926 LOG(LS_ERROR) << "Should always be able to extract a packet here";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001927 assert(false); // Should always be able to extract a packet here.
1928 return -1;
1929 }
1930 stats_.PacketsDiscarded(discard_count);
henrik.lundin84f8cd62016-04-26 07:45:16 -07001931 stats_.StoreWaitingTime(packet->waiting_time->ElapsedMs());
ossudc431ce2016-08-31 08:51:13 -07001932 assert(!packet->payload.empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001933 packet_list->push_back(packet); // Store packet in list.
1934
1935 if (first_packet) {
1936 first_packet = false;
henrik.lundin48ed9302015-10-29 05:36:24 -07001937 if (nack_enabled_) {
1938 RTC_DCHECK(nack_);
1939 // TODO(henrik.lundin): Should we update this for all decoded packets?
1940 nack_->UpdateLastDecodedPacket(packet->header.sequenceNumber,
1941 packet->header.timestamp);
1942 }
1943 prev_sequence_number = packet->header.sequenceNumber;
1944 prev_timestamp = packet->header.timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001945 prev_payload_type = packet->header.payloadType;
1946 }
1947
1948 // Store number of extracted samples.
1949 int packet_duration = 0;
1950 AudioDecoder* decoder = decoder_database_->GetDecoder(
1951 packet->header.payloadType);
1952 if (decoder) {
ossu17e3fa12016-09-08 04:52:55 -07001953 if (packet->primary) {
1954 packet_duration = decoder->PacketDuration(packet->payload.data(),
1955 packet->payload.size());
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001956 } else {
ossu17e3fa12016-09-08 04:52:55 -07001957 packet_duration = decoder->PacketDurationRedundant(
1958 packet->payload.data(), packet->payload.size());
1959 stats_.SecondaryDecodedSamples(packet_duration);
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001960 }
ossu97ba30e2016-04-25 07:55:58 -07001961 } else if (!decoder_database_->IsComfortNoise(packet->header.payloadType)) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001962 LOG(LS_WARNING) << "Unknown payload type "
1963 << static_cast<int>(packet->header.payloadType);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001964 assert(false);
1965 }
1966 if (packet_duration <= 0) {
1967 // Decoder did not return a packet duration. Assume that the packet
1968 // contains the same number of samples as the previous one.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001969 packet_duration = rtc::checked_cast<int>(decoder_frame_length_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001970 }
1971 extracted_samples = packet->header.timestamp - first_timestamp +
1972 packet_duration;
1973
1974 // Check what packet is available next.
1975 header = packet_buffer_->NextRtpHeader();
1976 next_packet_available = false;
1977 if (header && prev_payload_type == header->payloadType) {
1978 int16_t seq_no_diff = header->sequenceNumber - prev_sequence_number;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001979 size_t ts_diff = header->timestamp - prev_timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001980 if (seq_no_diff == 1 ||
1981 (seq_no_diff == 0 && ts_diff == decoder_frame_length_)) {
1982 // The next sequence number is available, or the next part of a packet
1983 // that was split into pieces upon insertion.
1984 next_packet_available = true;
1985 }
1986 prev_sequence_number = header->sequenceNumber;
1987 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07001988 } while (extracted_samples < rtc::checked_cast<int>(required_samples) &&
1989 next_packet_available);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001990
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00001991 if (extracted_samples > 0) {
1992 // Delete old packets only when we are going to decode something. Otherwise,
1993 // we could end up in the situation where we never decode anything, since
1994 // all incoming packets are considered too old but the buffer will also
1995 // never be flooded and flushed.
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001996 packet_buffer_->DiscardAllOldPackets(timestamp_);
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00001997 }
1998
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001999 return extracted_samples;
2000}
2001
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002002void NetEqImpl::UpdatePlcComponents(int fs_hz, size_t channels) {
2003 // Delete objects and create new ones.
2004 expand_.reset(expand_factory_->Create(background_noise_.get(),
2005 sync_buffer_.get(), &random_vector_,
Henrik Lundinbef77e22015-08-18 14:58:09 +02002006 &stats_, fs_hz, channels));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002007 merge_.reset(new Merge(fs_hz, channels, expand_.get(), sync_buffer_.get()));
2008}
2009
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002010void NetEqImpl::SetSampleRateAndChannels(int fs_hz, size_t channels) {
Henrik Lundind67a2192015-08-03 12:54:37 +02002011 LOG(LS_VERBOSE) << "SetSampleRateAndChannels " << fs_hz << " " << channels;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002012 // TODO(hlundin): Change to an enumerator and skip assert.
2013 assert(fs_hz == 8000 || fs_hz == 16000 || fs_hz == 32000 || fs_hz == 48000);
2014 assert(channels > 0);
2015
2016 fs_hz_ = fs_hz;
2017 fs_mult_ = fs_hz / 8000;
Peter Kastingdce40cf2015-08-24 14:52:23 -07002018 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002019 decoder_frame_length_ = 3 * output_size_samples_; // Initialize to 30ms.
2020
2021 last_mode_ = kModeNormal;
2022
2023 // Create a new array of mute factors and set all to 1.
2024 mute_factor_array_.reset(new int16_t[channels]);
2025 for (size_t i = 0; i < channels; ++i) {
2026 mute_factor_array_[i] = 16384; // 1.0 in Q14.
2027 }
2028
ossu97ba30e2016-04-25 07:55:58 -07002029 ComfortNoiseDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02002030 if (cng_decoder)
2031 cng_decoder->Reset();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002032
2033 // Reinit post-decode VAD with new sample rate.
2034 assert(vad_.get()); // Cannot be NULL here.
2035 vad_->Init();
2036
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002037 // Delete algorithm buffer and create a new one.
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00002038 algorithm_buffer_.reset(new AudioMultiVector(channels));
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002039
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002040 // Delete sync buffer and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002041 sync_buffer_.reset(new SyncBuffer(channels, kSyncBufferSize * fs_mult_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002042
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00002043 // Delete BackgroundNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002044 background_noise_.reset(new BackgroundNoise(channels));
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00002045 background_noise_->set_mode(background_noise_mode_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002046
2047 // Reset random vector.
2048 random_vector_.Reset();
2049
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002050 UpdatePlcComponents(fs_hz, channels);
2051
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002052 // Move index so that we create a small set of future samples (all 0).
2053 sync_buffer_->set_next_index(sync_buffer_->next_index() -
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002054 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002055
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002056 normal_.reset(new Normal(fs_hz, decoder_database_.get(), *background_noise_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002057 expand_.get()));
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +00002058 accelerate_.reset(
2059 accelerate_factory_->Create(fs_hz, channels, *background_noise_));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002060 preemptive_expand_.reset(preemptive_expand_factory_->Create(
Peter Kastingdce40cf2015-08-24 14:52:23 -07002061 fs_hz, channels, *background_noise_, expand_->overlap_length()));
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002062
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002063 // Delete ComfortNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002064 comfort_noise_.reset(new ComfortNoise(fs_hz, decoder_database_.get(),
2065 sync_buffer_.get()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002066
2067 // Verify that |decoded_buffer_| is long enough.
2068 if (decoded_buffer_length_ < kMaxFrameSize * channels) {
2069 // Reallocate to larger size.
2070 decoded_buffer_length_ = kMaxFrameSize * channels;
2071 decoded_buffer_.reset(new int16_t[decoded_buffer_length_]);
2072 }
2073
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002074 // Create DecisionLogic if it is not created yet, then communicate new sample
2075 // rate and output size to DecisionLogic object.
2076 if (!decision_logic_.get()) {
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002077 CreateDecisionLogic();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002078 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002079 decision_logic_->SetSampleRate(fs_hz_, output_size_samples_);
2080}
2081
henrik.lundin55480f52016-03-08 02:37:57 -08002082NetEqImpl::OutputType NetEqImpl::LastOutputType() {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002083 assert(vad_.get());
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002084 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002085 if (last_mode_ == kModeCodecInternalCng || last_mode_ == kModeRfc3389Cng) {
henrik.lundin55480f52016-03-08 02:37:57 -08002086 return OutputType::kCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002087 } else if (last_mode_ == kModeExpand && expand_->MuteFactor(0) == 0) {
2088 // Expand mode has faded down to background noise only (very long expand).
henrik.lundin55480f52016-03-08 02:37:57 -08002089 return OutputType::kPLCCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002090 } else if (last_mode_ == kModeExpand) {
henrik.lundin55480f52016-03-08 02:37:57 -08002091 return OutputType::kPLC;
wu@webrtc.org24301a62013-12-13 19:17:43 +00002092 } else if (vad_->running() && !vad_->active_speech()) {
henrik.lundin55480f52016-03-08 02:37:57 -08002093 return OutputType::kVadPassive;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002094 } else {
henrik.lundin55480f52016-03-08 02:37:57 -08002095 return OutputType::kNormalSpeech;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002096 }
2097}
2098
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002099void NetEqImpl::CreateDecisionLogic() {
Henrik Lundin47b17dc2016-05-10 10:20:59 +02002100 decision_logic_.reset(DecisionLogic::Create(
2101 fs_hz_, output_size_samples_, playout_mode_, decoder_database_.get(),
2102 *packet_buffer_.get(), delay_manager_.get(), buffer_level_filter_.get(),
2103 tick_timer_.get()));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002104}
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002105} // namespace webrtc