blob: 9c4f5809068f8964ef74882c0414f184ce37eef0 [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
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200434int NetEqImpl::SetTargetNumberOfChannels() {
435 return kNotImplemented;
436}
437
438int NetEqImpl::SetTargetSampleRate() {
439 return kNotImplemented;
440}
441
henrik.lundin@webrtc.orgb0f4b3d2014-11-04 08:53:10 +0000442int NetEqImpl::LastError() const {
Tommi9090e0b2016-01-20 13:39:36 +0100443 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000444 return error_code_;
445}
446
447int NetEqImpl::LastDecoderError() {
Tommi9090e0b2016-01-20 13:39:36 +0100448 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000449 return decoder_error_code_;
450}
451
452void NetEqImpl::FlushBuffers() {
Tommi9090e0b2016-01-20 13:39:36 +0100453 rtc::CritScope lock(&crit_sect_);
Henrik Lundind67a2192015-08-03 12:54:37 +0200454 LOG(LS_VERBOSE) << "FlushBuffers";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000455 packet_buffer_->Flush();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000456 assert(sync_buffer_.get());
457 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000458 sync_buffer_->Flush();
459 sync_buffer_->set_next_index(sync_buffer_->next_index() -
460 expand_->overlap_length());
461 // Set to wait for new codec.
462 first_packet_ = true;
463}
464
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000465void NetEqImpl::PacketBufferStatistics(int* current_num_packets,
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000466 int* max_num_packets) const {
Tommi9090e0b2016-01-20 13:39:36 +0100467 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000468 packet_buffer_->BufferStat(current_num_packets, max_num_packets);
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000469}
470
henrik.lundin48ed9302015-10-29 05:36:24 -0700471void NetEqImpl::EnableNack(size_t max_nack_list_size) {
Tommi9090e0b2016-01-20 13:39:36 +0100472 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700473 if (!nack_enabled_) {
474 const int kNackThresholdPackets = 2;
henrik.lundin91951862016-06-08 06:43:41 -0700475 nack_.reset(NackTracker::Create(kNackThresholdPackets));
henrik.lundin48ed9302015-10-29 05:36:24 -0700476 nack_enabled_ = true;
477 nack_->UpdateSampleRate(fs_hz_);
478 }
479 nack_->SetMaxNackListSize(max_nack_list_size);
480}
481
482void NetEqImpl::DisableNack() {
Tommi9090e0b2016-01-20 13:39:36 +0100483 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700484 nack_.reset();
485 nack_enabled_ = false;
486}
487
488std::vector<uint16_t> NetEqImpl::GetNackList(int64_t round_trip_time_ms) const {
Tommi9090e0b2016-01-20 13:39:36 +0100489 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700490 if (!nack_enabled_) {
491 return std::vector<uint16_t>();
492 }
493 RTC_DCHECK(nack_.get());
494 return nack_->GetNackList(round_trip_time_ms);
minyue@webrtc.orgd7301772013-08-29 00:58:14 +0000495}
496
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000497const SyncBuffer* NetEqImpl::sync_buffer_for_test() const {
Tommi9090e0b2016-01-20 13:39:36 +0100498 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000499 return sync_buffer_.get();
500}
501
minyue5bd33972016-05-02 04:46:11 -0700502Operations NetEqImpl::last_operation_for_test() const {
503 rtc::CritScope lock(&crit_sect_);
504 return last_operation_;
505}
506
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000507// Methods below this line are private.
508
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000509int NetEqImpl::InsertPacketInternal(const WebRtcRTPHeader& rtp_header,
kwibergee2bac22015-11-11 10:34:00 -0800510 rtc::ArrayView<const uint8_t> payload,
ossu17e3fa12016-09-08 04:52:55 -0700511 uint32_t receive_timestamp) {
kwibergee2bac22015-11-11 10:34:00 -0800512 if (payload.empty()) {
513 LOG_F(LS_ERROR) << "payload is empty";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000514 return kInvalidPointer;
515 }
ossu17e3fa12016-09-08 04:52:55 -0700516
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000517 PacketList packet_list;
518 RTPHeader main_header;
519 {
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000520 // Convert to Packet.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000521 // Create |packet| within this separate scope, since it should not be used
522 // directly once it's been inserted in the packet list. This way, |packet|
523 // is not defined outside of this block.
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000524 Packet* packet = new Packet;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000525 packet->header.markerBit = false;
526 packet->header.payloadType = rtp_header.header.payloadType;
527 packet->header.sequenceNumber = rtp_header.header.sequenceNumber;
528 packet->header.timestamp = rtp_header.header.timestamp;
529 packet->header.ssrc = rtp_header.header.ssrc;
530 packet->header.numCSRCs = 0;
ossudc431ce2016-08-31 08:51:13 -0700531 packet->payload.SetData(payload.data(), payload.size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000532 packet->primary = true;
henrik.lundin84f8cd62016-04-26 07:45:16 -0700533 // Waiting time will be set upon inserting the packet in the buffer.
534 RTC_DCHECK(!packet->waiting_time);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000535 // Insert packet in a packet list.
536 packet_list.push_back(packet);
537 // Save main payloads header for later.
538 memcpy(&main_header, &packet->header, sizeof(main_header));
539 }
540
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000541 bool update_sample_rate_and_channels = false;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000542 // Reinitialize NetEq if it's needed (changed SSRC or first call).
543 if ((main_header.ssrc != ssrc_) || first_packet_) {
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000544 // Note: |first_packet_| will be cleared further down in this method, once
545 // the packet has been successfully inserted into the packet buffer.
546
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000547 rtcp_.Init(main_header.sequenceNumber);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000548
549 // Flush the packet buffer and DTMF buffer.
550 packet_buffer_->Flush();
551 dtmf_buffer_->Flush();
552
553 // Store new SSRC.
554 ssrc_ = main_header.ssrc;
555
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000556 // Update audio buffer timestamp.
557 sync_buffer_->IncreaseEndTimestamp(main_header.timestamp - timestamp_);
558
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000559 // Update codecs.
560 timestamp_ = main_header.timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000561
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000562 // Reset timestamp scaling.
563 timestamp_scaler_->Reset();
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000564
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000565 // Trigger an update of sampling rate and the number of channels.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000566 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000567 }
568
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000569 // Update RTCP statistics, only for regular packets.
ossu17e3fa12016-09-08 04:52:55 -0700570 rtcp_.Update(main_header, receive_timestamp);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000571
572 // Check for RED payload type, and separate payloads into several packets.
573 if (decoder_database_->IsRed(main_header.payloadType)) {
574 if (payload_splitter_->SplitRed(&packet_list) != PayloadSplitter::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000575 PacketBuffer::DeleteAllPackets(&packet_list);
576 return kRedundancySplitError;
577 }
578 // Only accept a few RED payloads of the same type as the main data,
579 // DTMF events and CNG.
580 payload_splitter_->CheckRedPayloads(&packet_list, *decoder_database_);
581 // Update the stored main payload header since the main payload has now
582 // changed.
583 memcpy(&main_header, &packet_list.front()->header, sizeof(main_header));
584 }
585
586 // Check payload types.
587 if (decoder_database_->CheckPayloadTypes(packet_list) ==
588 DecoderDatabase::kDecoderNotFound) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000589 PacketBuffer::DeleteAllPackets(&packet_list);
590 return kUnknownRtpPayloadType;
591 }
592
593 // Scale timestamp to internal domain (only for some codecs).
594 timestamp_scaler_->ToInternal(&packet_list);
595
596 // Process DTMF payloads. Cycle through the list of packets, and pick out any
597 // DTMF payloads found.
598 PacketList::iterator it = packet_list.begin();
599 while (it != packet_list.end()) {
600 Packet* current_packet = (*it);
601 assert(current_packet);
ossudc431ce2016-08-31 08:51:13 -0700602 assert(!current_packet->payload.empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000603 if (decoder_database_->IsDtmf(current_packet->header.payloadType)) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000604 DtmfEvent event;
ossudc431ce2016-08-31 08:51:13 -0700605 int ret = DtmfBuffer::ParseEvent(current_packet->header.timestamp,
606 current_packet->payload.data(),
607 current_packet->payload.size(), &event);
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000608 if (ret != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000609 PacketBuffer::DeleteAllPackets(&packet_list);
610 return kDtmfParsingError;
611 }
612 if (dtmf_buffer_->InsertEvent(event) != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000613 PacketBuffer::DeleteAllPackets(&packet_list);
614 return kDtmfInsertError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000615 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000616 delete current_packet;
617 it = packet_list.erase(it);
618 } else {
619 ++it;
620 }
621 }
622
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000623 // Check for FEC in packets, and separate payloads into several packets.
624 int ret = payload_splitter_->SplitFec(&packet_list, decoder_database_.get());
625 if (ret != PayloadSplitter::kOK) {
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000626 PacketBuffer::DeleteAllPackets(&packet_list);
627 switch (ret) {
628 case PayloadSplitter::kUnknownPayloadType:
629 return kUnknownRtpPayloadType;
630 default:
631 return kOtherError;
632 }
633 }
634
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000635 // Split payloads into smaller chunks. This also verifies that all payloads
ossu17e3fa12016-09-08 04:52:55 -0700636 // are of a known payload type.
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +0000637 ret = payload_splitter_->SplitAudio(&packet_list, *decoder_database_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000638 if (ret != PayloadSplitter::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000639 PacketBuffer::DeleteAllPackets(&packet_list);
640 switch (ret) {
641 case PayloadSplitter::kUnknownPayloadType:
642 return kUnknownRtpPayloadType;
643 case PayloadSplitter::kFrameSplitError:
644 return kFrameSplitError;
645 default:
646 return kOtherError;
647 }
648 }
649
ossu17e3fa12016-09-08 04:52:55 -0700650 // Update bandwidth estimate, if the packet is not comfort noise.
651 if (!packet_list.empty() &&
ossu97ba30e2016-04-25 07:55:58 -0700652 !decoder_database_->IsComfortNoise(main_header.payloadType)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000653 // The list can be empty here if we got nothing but DTMF payloads.
654 AudioDecoder* decoder =
655 decoder_database_->GetDecoder(main_header.payloadType);
656 assert(decoder); // Should always get a valid object, since we have
ossu97ba30e2016-04-25 07:55:58 -0700657 // already checked that the payload types are known.
ossudc431ce2016-08-31 08:51:13 -0700658 decoder->IncomingPacket(packet_list.front()->payload.data(),
659 packet_list.front()->payload.size(),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000660 packet_list.front()->header.sequenceNumber,
661 packet_list.front()->header.timestamp,
662 receive_timestamp);
663 }
664
henrik.lundin48ed9302015-10-29 05:36:24 -0700665 if (nack_enabled_) {
666 RTC_DCHECK(nack_);
667 if (update_sample_rate_and_channels) {
668 nack_->Reset();
669 }
670 nack_->UpdateLastReceivedPacket(packet_list.front()->header.sequenceNumber,
671 packet_list.front()->header.timestamp);
672 }
673
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000674 // Insert packets in buffer.
henrik.lundin116c84e2015-08-27 13:14:48 -0700675 const size_t buffer_length_before_insert =
676 packet_buffer_->NumPacketsInBuffer();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000677 ret = packet_buffer_->InsertPacketList(
678 &packet_list,
679 *decoder_database_,
680 &current_rtp_payload_type_,
681 &current_cng_rtp_payload_type_);
682 if (ret == PacketBuffer::kFlushed) {
683 // Reset DSP timestamp etc. if packet buffer flushed.
684 new_codec_ = true;
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000685 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000686 } else if (ret != PacketBuffer::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000687 PacketBuffer::DeleteAllPackets(&packet_list);
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000688 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000689 }
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000690
691 if (first_packet_) {
692 first_packet_ = false;
693 // Update the codec on the next GetAudio call.
694 new_codec_ = true;
695 }
696
henrik.lundinda8bbf62016-08-31 03:14:11 -0700697 if (current_rtp_payload_type_) {
698 RTC_DCHECK(decoder_database_->GetDecoderInfo(*current_rtp_payload_type_))
699 << "Payload type " << static_cast<int>(*current_rtp_payload_type_)
700 << " is unknown where it shouldn't be";
701 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000702
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000703 if (update_sample_rate_and_channels && !packet_buffer_->Empty()) {
704 // We do not use |current_rtp_payload_type_| to |set payload_type|, but
705 // get the next RTP header from |packet_buffer_| to obtain the payload type.
706 // The reason for it is the following corner case. If NetEq receives a
707 // CNG packet with a sample rate different than the current CNG then it
708 // flushes its buffer, assuming send codec must have been changed. However,
709 // payload type of the hypothetically new send codec is not known.
710 const RTPHeader* rtp_header = packet_buffer_->NextRtpHeader();
711 assert(rtp_header);
712 int payload_type = rtp_header->payloadType;
ossu97ba30e2016-04-25 07:55:58 -0700713 size_t channels = 1;
714 if (!decoder_database_->IsComfortNoise(payload_type)) {
715 AudioDecoder* decoder = decoder_database_->GetDecoder(payload_type);
716 assert(decoder); // Payloads are already checked to be valid.
717 channels = decoder->Channels();
718 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000719 const DecoderDatabase::DecoderInfo* decoder_info =
720 decoder_database_->GetDecoderInfo(payload_type);
721 assert(decoder_info);
kwibergc0f2dcf2016-05-31 06:28:03 -0700722 if (decoder_info->SampleRateHz() != fs_hz_ ||
ossu97ba30e2016-04-25 07:55:58 -0700723 channels != algorithm_buffer_->Channels()) {
kwibergc0f2dcf2016-05-31 06:28:03 -0700724 SetSampleRateAndChannels(decoder_info->SampleRateHz(),
725 channels);
henrik.lundin48ed9302015-10-29 05:36:24 -0700726 }
727 if (nack_enabled_) {
728 RTC_DCHECK(nack_);
729 // Update the sample rate even if the rate is not new, because of Reset().
730 nack_->UpdateSampleRate(fs_hz_);
731 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000732 }
733
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000734 // TODO(hlundin): Move this code to DelayManager class.
735 const DecoderDatabase::DecoderInfo* dec_info =
736 decoder_database_->GetDecoderInfo(main_header.payloadType);
737 assert(dec_info); // Already checked that the payload type is known.
738 delay_manager_->LastDecoderType(dec_info->codec_type);
739 if (delay_manager_->last_pack_cng_or_dtmf() == 0) {
740 // Calculate the total speech length carried in each packet.
henrik.lundin116c84e2015-08-27 13:14:48 -0700741 const size_t buffer_length_after_insert =
742 packet_buffer_->NumPacketsInBuffer();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000743
henrik.lundin116c84e2015-08-27 13:14:48 -0700744 if (buffer_length_after_insert > buffer_length_before_insert) {
745 const size_t packet_length_samples =
746 (buffer_length_after_insert - buffer_length_before_insert) *
747 decoder_frame_length_;
748 if (packet_length_samples != decision_logic_->packet_length_samples()) {
749 decision_logic_->set_packet_length_samples(packet_length_samples);
750 delay_manager_->SetPacketAudioLength(
751 rtc::checked_cast<int>((1000 * packet_length_samples) / fs_hz_));
752 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000753 }
754
755 // Update statistics.
pbos@webrtc.org0946a562013-04-09 00:28:06 +0000756 if ((int32_t) (main_header.timestamp - timestamp_) >= 0 &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000757 !new_codec_) {
758 // Only update statistics if incoming packet is not older than last played
759 // out packet, and if new codec flag is not set.
760 delay_manager_->Update(main_header.sequenceNumber, main_header.timestamp,
761 fs_hz_);
762 }
763 } else if (delay_manager_->last_pack_cng_or_dtmf() == -1) {
764 // This is first "normal" packet after CNG or DTMF.
765 // Reset packet time counter and measure time until next packet,
766 // but don't update statistics.
767 delay_manager_->set_last_pack_cng_or_dtmf(0);
768 delay_manager_->ResetPacketIatCount();
769 }
770 return 0;
771}
772
henrik.lundin7a926812016-05-12 13:51:28 -0700773int NetEqImpl::GetAudioInternal(AudioFrame* audio_frame, bool* muted) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000774 PacketList packet_list;
775 DtmfEvent dtmf_event;
776 Operations operation;
777 bool play_dtmf;
henrik.lundin7a926812016-05-12 13:51:28 -0700778 *muted = false;
henrik.lundined497212016-04-25 10:11:38 -0700779 tick_timer_->Increment();
henrik.lundin60f6ce22016-05-10 03:52:04 -0700780 stats_.IncreaseCounter(output_size_samples_, fs_hz_);
henrik.lundin7a926812016-05-12 13:51:28 -0700781
782 // Check for muted state.
783 if (enable_muted_state_ && expand_->Muted() && packet_buffer_->Empty()) {
784 RTC_DCHECK_EQ(last_mode_, kModeExpand);
785 playout_timestamp_ += static_cast<uint32_t>(output_size_samples_);
786 audio_frame->sample_rate_hz_ = fs_hz_;
787 audio_frame->samples_per_channel_ = output_size_samples_;
788 audio_frame->timestamp_ =
789 first_packet_
790 ? 0
791 : timestamp_scaler_->ToExternal(playout_timestamp_) -
792 static_cast<uint32_t>(audio_frame->samples_per_channel_);
793 audio_frame->num_channels_ = sync_buffer_->Channels();
henrik.lundin612c25e2016-05-25 08:21:04 -0700794 stats_.ExpandedNoiseSamples(output_size_samples_);
henrik.lundin7a926812016-05-12 13:51:28 -0700795 *muted = true;
796 return 0;
797 }
798
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000799 int return_value = GetDecision(&operation, &packet_list, &dtmf_event,
800 &play_dtmf);
801 if (return_value != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000802 last_mode_ = kModeError;
803 return return_value;
804 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000805
806 AudioDecoder::SpeechType speech_type;
807 int length = 0;
808 int decode_return_value = Decode(&packet_list, &operation,
809 &length, &speech_type);
810
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000811 assert(vad_.get());
812 bool sid_frame_available =
813 (operation == kRfc3389Cng && !packet_list.empty());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700814 vad_->Update(decoded_buffer_.get(), static_cast<size_t>(length), speech_type,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000815 sid_frame_available, fs_hz_);
816
henrik.lundinb1fb72b2016-05-03 08:18:47 -0700817 if (sid_frame_available || speech_type == AudioDecoder::kComfortNoise) {
818 // Start a new stopwatch since we are decoding a new CNG packet.
819 generated_noise_stopwatch_ = tick_timer_->GetNewStopwatch();
820 }
821
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000822 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000823 switch (operation) {
824 case kNormal: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000825 DoNormal(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000826 break;
827 }
828 case kMerge: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000829 DoMerge(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000830 break;
831 }
832 case kExpand: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000833 return_value = DoExpand(play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000834 break;
835 }
Henrik Lundincf808d22015-05-27 14:33:29 +0200836 case kAccelerate:
837 case kFastAccelerate: {
838 const bool fast_accelerate =
839 enable_fast_accelerate_ && (operation == kFastAccelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000840 return_value = DoAccelerate(decoded_buffer_.get(), length, speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +0200841 play_dtmf, fast_accelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000842 break;
843 }
844 case kPreemptiveExpand: {
845 return_value = DoPreemptiveExpand(decoded_buffer_.get(), length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000846 speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000847 break;
848 }
849 case kRfc3389Cng:
850 case kRfc3389CngNoPacket: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000851 return_value = DoRfc3389Cng(&packet_list, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000852 break;
853 }
854 case kCodecInternalCng: {
855 // This handles the case when there is no transmission and the decoder
856 // should produce internal comfort noise.
857 // TODO(hlundin): Write test for codec-internal CNG.
minyuel6d92bf52015-09-23 15:20:39 +0200858 DoCodecInternalCng(decoded_buffer_.get(), length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000859 break;
860 }
861 case kDtmf: {
862 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000863 return_value = DoDtmf(dtmf_event, &play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000864 break;
865 }
866 case kAlternativePlc: {
867 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000868 DoAlternativePlc(false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000869 break;
870 }
871 case kAlternativePlcIncreaseTimestamp: {
872 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000873 DoAlternativePlc(true);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000874 break;
875 }
876 case kAudioRepetitionIncreaseTimestamp: {
877 // TODO(hlundin): Write test for this.
Peter Kastingb7e50542015-06-11 12:55:50 -0700878 sync_buffer_->IncreaseEndTimestamp(
879 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000880 // Skipping break on purpose. Execution should move on into the
881 // next case.
kjellander@webrtc.org7d2b6a92015-01-28 18:37:58 +0000882 FALLTHROUGH();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000883 }
884 case kAudioRepetition: {
885 // TODO(hlundin): Write test for this.
886 // Copy last |output_size_samples_| from |sync_buffer_| to
887 // |algorithm_buffer|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000888 algorithm_buffer_->PushBackFromIndex(
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000889 *sync_buffer_, sync_buffer_->Size() - output_size_samples_);
890 expand_->Reset();
891 break;
892 }
893 case kUndefined: {
Henrik Lundind67a2192015-08-03 12:54:37 +0200894 LOG(LS_ERROR) << "Invalid operation kUndefined.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000895 assert(false); // This should not happen.
896 last_mode_ = kModeError;
897 return kInvalidOperation;
898 }
899 } // End of switch.
minyue5bd33972016-05-02 04:46:11 -0700900 last_operation_ = operation;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000901 if (return_value < 0) {
902 return return_value;
903 }
904
905 if (last_mode_ != kModeRfc3389Cng) {
906 comfort_noise_->Reset();
907 }
908
909 // Copy from |algorithm_buffer| to |sync_buffer_|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000910 sync_buffer_->PushBack(*algorithm_buffer_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000911
912 // Extract data from |sync_buffer_| to |output|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000913 size_t num_output_samples_per_channel = output_size_samples_;
914 size_t num_output_samples = output_size_samples_ * sync_buffer_->Channels();
henrik.lundin6d8e0112016-03-04 10:34:21 -0800915 if (num_output_samples > AudioFrame::kMaxDataSizeSamples) {
916 LOG(LS_WARNING) << "Output array is too short. "
917 << AudioFrame::kMaxDataSizeSamples << " < "
918 << output_size_samples_ << " * "
919 << sync_buffer_->Channels();
920 num_output_samples = AudioFrame::kMaxDataSizeSamples;
921 num_output_samples_per_channel =
922 AudioFrame::kMaxDataSizeSamples / sync_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000923 }
henrik.lundin6d8e0112016-03-04 10:34:21 -0800924 sync_buffer_->GetNextAudioInterleaved(num_output_samples_per_channel,
925 audio_frame);
926 audio_frame->sample_rate_hz_ = fs_hz_;
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200927 if (sync_buffer_->FutureLength() < expand_->overlap_length()) {
928 // The sync buffer should always contain |overlap_length| samples, but now
929 // too many samples have been extracted. Reinstall the |overlap_length|
930 // lookahead by moving the index.
931 const size_t missing_lookahead_samples =
932 expand_->overlap_length() - sync_buffer_->FutureLength();
henrikg91d6ede2015-09-17 00:24:34 -0700933 RTC_DCHECK_GE(sync_buffer_->next_index(), missing_lookahead_samples);
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200934 sync_buffer_->set_next_index(sync_buffer_->next_index() -
935 missing_lookahead_samples);
936 }
henrik.lundin6d8e0112016-03-04 10:34:21 -0800937 if (audio_frame->samples_per_channel_ != output_size_samples_) {
938 LOG(LS_ERROR) << "audio_frame->samples_per_channel_ ("
939 << audio_frame->samples_per_channel_
Henrik Lundind67a2192015-08-03 12:54:37 +0200940 << ") != output_size_samples_ (" << output_size_samples_
941 << ")";
minyue@webrtc.orgdb1cefc2013-08-13 01:39:21 +0000942 // TODO(minyue): treatment of under-run, filling zeros
henrik.lundin6d8e0112016-03-04 10:34:21 -0800943 memset(audio_frame->data_, 0, num_output_samples * sizeof(int16_t));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000944 return kSampleUnderrun;
945 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000946
947 // Should always have overlap samples left in the |sync_buffer_|.
henrikg91d6ede2015-09-17 00:24:34 -0700948 RTC_DCHECK_GE(sync_buffer_->FutureLength(), expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000949
950 if (play_dtmf) {
henrik.lundin6d8e0112016-03-04 10:34:21 -0800951 return_value =
952 DtmfOverdub(dtmf_event, sync_buffer_->Channels(), audio_frame->data_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000953 }
954
955 // Update the background noise parameters if last operation wrote data
956 // straight from the decoder to the |sync_buffer_|. That is, none of the
957 // operations that modify the signal can be followed by a parameter update.
958 if ((last_mode_ == kModeNormal) ||
959 (last_mode_ == kModeAccelerateFail) ||
960 (last_mode_ == kModePreemptiveExpandFail) ||
961 (last_mode_ == kModeRfc3389Cng) ||
962 (last_mode_ == kModeCodecInternalCng)) {
963 background_noise_->Update(*sync_buffer_, *vad_.get());
964 }
965
966 if (operation == kDtmf) {
967 // DTMF data was written the end of |sync_buffer_|.
968 // Update index to end of DTMF data in |sync_buffer_|.
969 sync_buffer_->set_dtmf_index(sync_buffer_->Size());
970 }
971
henrik.lundin@webrtc.orged865b52014-03-06 10:28:07 +0000972 if (last_mode_ != kModeExpand) {
973 // If last operation was not expand, calculate the |playout_timestamp_| from
974 // the |sync_buffer_|. However, do not update the |playout_timestamp_| if it
975 // would be moved "backwards".
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000976 uint32_t temp_timestamp = sync_buffer_->end_timestamp() -
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000977 static_cast<uint32_t>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000978 if (static_cast<int32_t>(temp_timestamp - playout_timestamp_) > 0) {
979 playout_timestamp_ = temp_timestamp;
980 }
981 } else {
982 // Use dead reckoning to estimate the |playout_timestamp_|.
Peter Kastingb7e50542015-06-11 12:55:50 -0700983 playout_timestamp_ += static_cast<uint32_t>(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000984 }
henrik.lundin15c51e32016-04-06 08:38:56 -0700985 // Set the timestamp in the audio frame to zero before the first packet has
986 // been inserted. Otherwise, subtract the frame size in samples to get the
987 // timestamp of the first sample in the frame (playout_timestamp_ is the
988 // last + 1).
989 audio_frame->timestamp_ =
990 first_packet_
991 ? 0
992 : timestamp_scaler_->ToExternal(playout_timestamp_) -
993 static_cast<uint32_t>(audio_frame->samples_per_channel_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000994
henrik.lundinb1fb72b2016-05-03 08:18:47 -0700995 if (!(last_mode_ == kModeRfc3389Cng ||
996 last_mode_ == kModeCodecInternalCng ||
997 last_mode_ == kModeExpand)) {
998 generated_noise_stopwatch_.reset();
999 }
1000
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001001 if (decode_return_value) return decode_return_value;
1002 return return_value;
1003}
1004
1005int NetEqImpl::GetDecision(Operations* operation,
1006 PacketList* packet_list,
1007 DtmfEvent* dtmf_event,
1008 bool* play_dtmf) {
1009 // Initialize output variables.
1010 *play_dtmf = false;
1011 *operation = kUndefined;
1012
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001013 assert(sync_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001014 uint32_t end_timestamp = sync_buffer_->end_timestamp();
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001015 if (!new_codec_) {
1016 const uint32_t five_seconds_samples = 5 * fs_hz_;
1017 packet_buffer_->DiscardOldPackets(end_timestamp, five_seconds_samples);
1018 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001019 const RTPHeader* header = packet_buffer_->NextRtpHeader();
1020
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001021 RTC_DCHECK(!generated_noise_stopwatch_ ||
1022 generated_noise_stopwatch_->ElapsedTicks() >= 1);
1023 uint64_t generated_noise_samples =
1024 generated_noise_stopwatch_
1025 ? (generated_noise_stopwatch_->ElapsedTicks() - 1) *
1026 output_size_samples_ +
1027 decision_logic_->noise_fast_forward()
1028 : 0;
1029
henrik.lundin@webrtc.orgca8cb952014-03-12 10:26:52 +00001030 if (decision_logic_->CngRfc3389On() || last_mode_ == kModeRfc3389Cng) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001031 // Because of timestamp peculiarities, we have to "manually" disallow using
1032 // a CNG packet with the same timestamp as the one that was last played.
1033 // This can happen when using redundancy and will cause the timing to shift.
henrik.lundin@webrtc.org24779fe2014-03-14 12:40:05 +00001034 while (header && decoder_database_->IsComfortNoise(header->payloadType) &&
1035 (end_timestamp >= header->timestamp ||
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001036 end_timestamp + generated_noise_samples > header->timestamp)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001037 // Don't use this packet, discard it.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001038 if (packet_buffer_->DiscardNextPacket() != PacketBuffer::kOK) {
1039 assert(false); // Must be ok by design.
1040 }
1041 // Check buffer again.
1042 if (!new_codec_) {
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001043 packet_buffer_->DiscardOldPackets(end_timestamp, 5 * fs_hz_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001044 }
1045 header = packet_buffer_->NextRtpHeader();
1046 }
1047 }
1048
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001049 assert(expand_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001050 const int samples_left = static_cast<int>(sync_buffer_->FutureLength() -
1051 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001052 if (last_mode_ == kModeAccelerateSuccess ||
1053 last_mode_ == kModeAccelerateLowEnergy ||
1054 last_mode_ == kModePreemptiveExpandSuccess ||
1055 last_mode_ == kModePreemptiveExpandLowEnergy) {
1056 // Subtract (samples_left + output_size_samples_) from sampleMemory.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001057 decision_logic_->AddSampleMemory(
1058 -(samples_left + rtc::checked_cast<int>(output_size_samples_)));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001059 }
1060
1061 // Check if it is time to play a DTMF event.
Peter Kastingb7e50542015-06-11 12:55:50 -07001062 if (dtmf_buffer_->GetEvent(
1063 static_cast<uint32_t>(
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001064 end_timestamp + generated_noise_samples),
Peter Kastingb7e50542015-06-11 12:55:50 -07001065 dtmf_event)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001066 *play_dtmf = true;
1067 }
1068
1069 // Get instruction.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001070 assert(sync_buffer_.get());
1071 assert(expand_.get());
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001072 generated_noise_samples =
1073 generated_noise_stopwatch_
1074 ? generated_noise_stopwatch_->ElapsedTicks() * output_size_samples_ +
1075 decision_logic_->noise_fast_forward()
1076 : 0;
1077 *operation = decision_logic_->GetDecision(
1078 *sync_buffer_, *expand_, decoder_frame_length_, header, last_mode_,
1079 *play_dtmf, generated_noise_samples, &reset_decoder_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001080
1081 // Check if we already have enough samples in the |sync_buffer_|. If so,
1082 // change decision to normal, unless the decision was merge, accelerate, or
1083 // preemptive expand.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001084 if (samples_left >= rtc::checked_cast<int>(output_size_samples_) &&
1085 *operation != kMerge &&
1086 *operation != kAccelerate &&
1087 *operation != kFastAccelerate &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001088 *operation != kPreemptiveExpand) {
1089 *operation = kNormal;
1090 return 0;
1091 }
1092
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001093 decision_logic_->ExpandDecision(*operation);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001094
1095 // Check conditions for reset.
1096 if (new_codec_ || *operation == kUndefined) {
1097 // The only valid reason to get kUndefined is that new_codec_ is set.
1098 assert(new_codec_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001099 if (*play_dtmf && !header) {
1100 timestamp_ = dtmf_event->timestamp;
1101 } else {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001102 if (!header) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001103 LOG(LS_ERROR) << "Packet missing where it shouldn't.";
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001104 return -1;
1105 }
1106 timestamp_ = header->timestamp;
ossu108ecec2016-07-08 08:45:18 -07001107 if (*operation == kRfc3389CngNoPacket &&
1108 decoder_database_->IsComfortNoise(header->payloadType)) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001109 // Change decision to CNG packet, since we do have a CNG packet, but it
1110 // was considered too early to use. Now, use it anyway.
1111 *operation = kRfc3389Cng;
1112 } else if (*operation != kRfc3389Cng) {
1113 *operation = kNormal;
1114 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001115 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001116 // Adjust |sync_buffer_| timestamp before setting |end_timestamp| to the
1117 // new value.
1118 sync_buffer_->IncreaseEndTimestamp(timestamp_ - end_timestamp);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001119 end_timestamp = timestamp_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001120 new_codec_ = false;
1121 decision_logic_->SoftReset();
1122 buffer_level_filter_->Reset();
1123 delay_manager_->Reset();
1124 stats_.ResetMcu();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001125 }
1126
Peter Kastingdce40cf2015-08-24 14:52:23 -07001127 size_t required_samples = output_size_samples_;
1128 const size_t samples_10_ms = static_cast<size_t>(80 * fs_mult_);
1129 const size_t samples_20_ms = 2 * samples_10_ms;
1130 const size_t samples_30_ms = 3 * samples_10_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001131
1132 switch (*operation) {
1133 case kExpand: {
1134 timestamp_ = end_timestamp;
1135 return 0;
1136 }
1137 case kRfc3389CngNoPacket:
1138 case kCodecInternalCng: {
1139 return 0;
1140 }
1141 case kDtmf: {
1142 // TODO(hlundin): Write test for this.
1143 // Update timestamp.
1144 timestamp_ = end_timestamp;
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001145 const uint64_t generated_noise_samples =
1146 generated_noise_stopwatch_
1147 ? generated_noise_stopwatch_->ElapsedTicks() *
1148 output_size_samples_ +
1149 decision_logic_->noise_fast_forward()
1150 : 0;
1151 if (generated_noise_samples > 0 && last_mode_ != kModeDtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001152 // Make a jump in timestamp due to the recently played comfort noise.
Peter Kastingb7e50542015-06-11 12:55:50 -07001153 uint32_t timestamp_jump =
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001154 static_cast<uint32_t>(generated_noise_samples);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001155 sync_buffer_->IncreaseEndTimestamp(timestamp_jump);
1156 timestamp_ += timestamp_jump;
1157 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001158 return 0;
1159 }
Henrik Lundincf808d22015-05-27 14:33:29 +02001160 case kAccelerate:
1161 case kFastAccelerate: {
1162 // In order to do an accelerate we need at least 30 ms of audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001163 if (samples_left >= static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001164 // Already have enough data, so we do not need to extract any more.
1165 decision_logic_->set_sample_memory(samples_left);
1166 decision_logic_->set_prev_time_scale(true);
1167 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001168 } else if (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001169 decoder_frame_length_ >= samples_30_ms) {
1170 // Avoid decoding more data as it might overflow the playout buffer.
1171 *operation = kNormal;
1172 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001173 } else if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001174 decoder_frame_length_ < samples_30_ms) {
1175 // Build up decoded data by decoding at least 20 ms of audio data. Do
1176 // not perform accelerate yet, but wait until we only need to do one
1177 // decoding.
1178 required_samples = 2 * output_size_samples_;
1179 *operation = kNormal;
1180 }
1181 // If none of the above is true, we have one of two possible situations:
1182 // (1) 20 ms <= samples_left < 30 ms and decoder_frame_length_ < 30 ms; or
1183 // (2) samples_left < 10 ms and decoder_frame_length_ >= 30 ms.
1184 // In either case, we move on with the accelerate decision, and decode one
1185 // frame now.
1186 break;
1187 }
1188 case kPreemptiveExpand: {
1189 // In order to do a preemptive expand we need at least 30 ms of decoded
1190 // audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001191 if ((samples_left >= static_cast<int>(samples_30_ms)) ||
1192 (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001193 decoder_frame_length_ >= samples_30_ms)) {
1194 // Already have enough data, so we do not need to extract any more.
1195 // Or, avoid decoding more data as it might overflow the playout buffer.
1196 // Still try preemptive expand, though.
1197 decision_logic_->set_sample_memory(samples_left);
1198 decision_logic_->set_prev_time_scale(true);
1199 return 0;
1200 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07001201 if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001202 decoder_frame_length_ < samples_30_ms) {
1203 // Build up decoded data by decoding at least 20 ms of audio data.
1204 // Still try to perform preemptive expand.
1205 required_samples = 2 * output_size_samples_;
1206 }
1207 // Move on with the preemptive expand decision.
1208 break;
1209 }
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001210 case kMerge: {
1211 required_samples =
1212 std::max(merge_->RequiredFutureSamples(), required_samples);
1213 break;
1214 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001215 default: {
1216 // Do nothing.
1217 }
1218 }
1219
1220 // Get packets from buffer.
1221 int extracted_samples = 0;
1222 if (header &&
1223 *operation != kAlternativePlc &&
1224 *operation != kAlternativePlcIncreaseTimestamp &&
1225 *operation != kAudioRepetition &&
1226 *operation != kAudioRepetitionIncreaseTimestamp) {
1227 sync_buffer_->IncreaseEndTimestamp(header->timestamp - end_timestamp);
1228 if (decision_logic_->CngOff()) {
1229 // Adjustment of timestamp only corresponds to an actual packet loss
1230 // if comfort noise is not played. If comfort noise was just played,
1231 // this adjustment of timestamp is only done to get back in sync with the
1232 // stream timestamp; no loss to report.
1233 stats_.LostSamples(header->timestamp - end_timestamp);
1234 }
1235
1236 if (*operation != kRfc3389Cng) {
1237 // We are about to decode and use a non-CNG packet.
1238 decision_logic_->SetCngOff();
1239 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001240
1241 extracted_samples = ExtractPackets(required_samples, packet_list);
1242 if (extracted_samples < 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001243 return kPacketBufferCorruption;
1244 }
1245 }
1246
Henrik Lundincf808d22015-05-27 14:33:29 +02001247 if (*operation == kAccelerate || *operation == kFastAccelerate ||
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001248 *operation == kPreemptiveExpand) {
1249 decision_logic_->set_sample_memory(samples_left + extracted_samples);
1250 decision_logic_->set_prev_time_scale(true);
1251 }
1252
Henrik Lundincf808d22015-05-27 14:33:29 +02001253 if (*operation == kAccelerate || *operation == kFastAccelerate) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001254 // Check that we have enough data (30ms) to do accelerate.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001255 if (extracted_samples + samples_left < static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001256 // TODO(hlundin): Write test for this.
1257 // Not enough, do normal operation instead.
1258 *operation = kNormal;
1259 }
1260 }
1261
1262 timestamp_ = end_timestamp;
1263 return 0;
1264}
1265
1266int NetEqImpl::Decode(PacketList* packet_list, Operations* operation,
1267 int* decoded_length,
1268 AudioDecoder::SpeechType* speech_type) {
1269 *speech_type = AudioDecoder::kSpeech;
minyuel6d92bf52015-09-23 15:20:39 +02001270
1271 // When packet_list is empty, we may be in kCodecInternalCng mode, and for
1272 // that we use current active decoder.
1273 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1274
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001275 if (!packet_list->empty()) {
1276 const Packet* packet = packet_list->front();
pkasting@chromium.org0e81fdf2015-02-02 23:54:03 +00001277 uint8_t payload_type = packet->header.payloadType;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001278 if (!decoder_database_->IsComfortNoise(payload_type)) {
1279 decoder = decoder_database_->GetDecoder(payload_type);
1280 assert(decoder);
1281 if (!decoder) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001282 LOG(LS_WARNING) << "Unknown payload type "
1283 << static_cast<int>(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001284 PacketBuffer::DeleteAllPackets(packet_list);
1285 return kDecoderNotFound;
1286 }
1287 bool decoder_changed;
1288 decoder_database_->SetActiveDecoder(payload_type, &decoder_changed);
1289 if (decoder_changed) {
1290 // We have a new decoder. Re-init some values.
1291 const DecoderDatabase::DecoderInfo* decoder_info = decoder_database_
1292 ->GetDecoderInfo(payload_type);
1293 assert(decoder_info);
1294 if (!decoder_info) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001295 LOG(LS_WARNING) << "Unknown payload type "
1296 << static_cast<int>(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001297 PacketBuffer::DeleteAllPackets(packet_list);
1298 return kDecoderNotFound;
1299 }
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001300 // If sampling rate or number of channels has changed, we need to make
1301 // a reset.
kwibergc0f2dcf2016-05-31 06:28:03 -07001302 if (decoder_info->SampleRateHz() != fs_hz_ ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001303 decoder->Channels() != algorithm_buffer_->Channels()) {
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001304 // TODO(tlegrand): Add unittest to cover this event.
kwibergc0f2dcf2016-05-31 06:28:03 -07001305 SetSampleRateAndChannels(decoder_info->SampleRateHz(),
1306 decoder->Channels());
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001307 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001308 sync_buffer_->set_end_timestamp(timestamp_);
1309 playout_timestamp_ = timestamp_;
1310 }
1311 }
1312 }
1313
1314 if (reset_decoder_) {
1315 // TODO(hlundin): Write test for this.
Karl Wiberg43766482015-08-27 15:22:11 +02001316 if (decoder)
1317 decoder->Reset();
1318
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001319 // Reset comfort noise decoder.
ossu97ba30e2016-04-25 07:55:58 -07001320 ComfortNoiseDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02001321 if (cng_decoder)
1322 cng_decoder->Reset();
1323
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001324 reset_decoder_ = false;
1325 }
1326
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001327 *decoded_length = 0;
1328 // Update codec-internal PLC state.
1329 if ((*operation == kMerge) && decoder && decoder->HasDecodePlc()) {
1330 decoder->DecodePlc(1, &decoded_buffer_[*decoded_length]);
1331 }
1332
minyuel6d92bf52015-09-23 15:20:39 +02001333 int return_value;
1334 if (*operation == kCodecInternalCng) {
1335 RTC_DCHECK(packet_list->empty());
1336 return_value = DecodeCng(decoder, decoded_length, speech_type);
1337 } else {
1338 return_value = DecodeLoop(packet_list, *operation, decoder,
1339 decoded_length, speech_type);
1340 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001341
1342 if (*decoded_length < 0) {
1343 // Error returned from the decoder.
1344 *decoded_length = 0;
Peter Kastingb7e50542015-06-11 12:55:50 -07001345 sync_buffer_->IncreaseEndTimestamp(
1346 static_cast<uint32_t>(decoder_frame_length_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001347 int error_code = 0;
1348 if (decoder)
1349 error_code = decoder->ErrorCode();
1350 if (error_code != 0) {
1351 // Got some error code from the decoder.
1352 decoder_error_code_ = error_code;
1353 return_value = kDecoderErrorCode;
Henrik Lundind67a2192015-08-03 12:54:37 +02001354 LOG(LS_WARNING) << "Decoder returned error code: " << error_code;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001355 } else {
1356 // Decoder does not implement error codes. Return generic error.
1357 return_value = kOtherDecoderError;
Henrik Lundind67a2192015-08-03 12:54:37 +02001358 LOG(LS_WARNING) << "Decoder error (no error code)";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001359 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001360 *operation = kExpand; // Do expansion to get data instead.
1361 }
1362 if (*speech_type != AudioDecoder::kComfortNoise) {
1363 // Don't increment timestamp if codec returned CNG speech type
1364 // since in this case, the we will increment the CNGplayedTS counter.
1365 // Increase with number of samples per channel.
1366 assert(*decoded_length == 0 ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001367 (decoder && decoder->Channels() == sync_buffer_->Channels()));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001368 sync_buffer_->IncreaseEndTimestamp(
1369 *decoded_length / static_cast<int>(sync_buffer_->Channels()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001370 }
1371 return return_value;
1372}
1373
minyuel6d92bf52015-09-23 15:20:39 +02001374int NetEqImpl::DecodeCng(AudioDecoder* decoder, int* decoded_length,
1375 AudioDecoder::SpeechType* speech_type) {
1376 if (!decoder) {
1377 // This happens when active decoder is not defined.
1378 *decoded_length = -1;
1379 return 0;
1380 }
1381
1382 while (*decoded_length < rtc::checked_cast<int>(output_size_samples_)) {
1383 const int length = decoder->Decode(
1384 nullptr, 0, fs_hz_,
1385 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1386 &decoded_buffer_[*decoded_length], speech_type);
1387 if (length > 0) {
1388 *decoded_length += length;
minyuel6d92bf52015-09-23 15:20:39 +02001389 } else {
1390 // Error.
1391 LOG(LS_WARNING) << "Failed to decode CNG";
1392 *decoded_length = -1;
1393 break;
1394 }
1395 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1396 // Guard against overflow.
1397 LOG(LS_WARNING) << "Decoded too much CNG.";
1398 return kDecodedTooMuch;
1399 }
1400 }
1401 return 0;
1402}
1403
1404int NetEqImpl::DecodeLoop(PacketList* packet_list, const Operations& operation,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001405 AudioDecoder* decoder, int* decoded_length,
1406 AudioDecoder::SpeechType* speech_type) {
1407 Packet* packet = NULL;
1408 if (!packet_list->empty()) {
1409 packet = packet_list->front();
1410 }
minyuel6d92bf52015-09-23 15:20:39 +02001411
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001412 // Do decoding.
1413 while (packet &&
1414 !decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1415 assert(decoder); // At this point, we must have a decoder object.
1416 // The number of channels in the |sync_buffer_| should be the same as the
1417 // number decoder channels.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001418 assert(sync_buffer_->Channels() == decoder->Channels());
1419 assert(decoded_buffer_length_ >= kMaxFrameSize * decoder->Channels());
minyuel6d92bf52015-09-23 15:20:39 +02001420 assert(operation == kNormal || operation == kAccelerate ||
1421 operation == kFastAccelerate || operation == kMerge ||
1422 operation == kPreemptiveExpand);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001423 packet_list->pop_front();
ossudc431ce2016-08-31 08:51:13 -07001424 const size_t payload_length = packet->payload.size();
Peter Kasting36b7cc32015-06-11 19:57:18 -07001425 int decode_length;
ossu17e3fa12016-09-08 04:52:55 -07001426 if (!packet->primary) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001427 // This is a redundant payload; call the special decoder method.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001428 decode_length = decoder->DecodeRedundant(
ossudc431ce2016-08-31 08:51:13 -07001429 packet->payload.data(), packet->payload.size(), fs_hz_,
minyue@webrtc.org7f7d7e32015-03-16 12:30:37 +00001430 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001431 &decoded_buffer_[*decoded_length], speech_type);
1432 } else {
ossudc431ce2016-08-31 08:51:13 -07001433 decode_length = decoder->Decode(
1434 packet->payload.data(), packet->payload.size(), fs_hz_,
1435 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1436 &decoded_buffer_[*decoded_length], speech_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001437 }
1438
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001439 delete packet;
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001440 packet = NULL;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001441 if (decode_length > 0) {
1442 *decoded_length += decode_length;
1443 // Update |decoder_frame_length_| with number of samples per channel.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001444 decoder_frame_length_ =
Peter Kastingdce40cf2015-08-24 14:52:23 -07001445 static_cast<size_t>(decode_length) / decoder->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001446 } else if (decode_length < 0) {
1447 // Error.
Henrik Lundind67a2192015-08-03 12:54:37 +02001448 LOG(LS_WARNING) << "Decode " << decode_length << " " << payload_length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001449 *decoded_length = -1;
1450 PacketBuffer::DeleteAllPackets(packet_list);
1451 break;
1452 }
1453 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1454 // Guard against overflow.
Henrik Lundind67a2192015-08-03 12:54:37 +02001455 LOG(LS_WARNING) << "Decoded too much.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001456 PacketBuffer::DeleteAllPackets(packet_list);
1457 return kDecodedTooMuch;
1458 }
1459 if (!packet_list->empty()) {
1460 packet = packet_list->front();
1461 } else {
1462 packet = NULL;
1463 }
1464 } // End of decode loop.
1465
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001466 // If the list is not empty at this point, either a decoding error terminated
1467 // the while-loop, or list must hold exactly one CNG packet.
1468 assert(packet_list->empty() || *decoded_length < 0 ||
1469 (packet_list->size() == 1 && packet &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001470 decoder_database_->IsComfortNoise(packet->header.payloadType)));
1471 return 0;
1472}
1473
1474void NetEqImpl::DoNormal(const int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001475 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001476 assert(normal_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001477 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001478 normal_->Process(decoded_buffer, decoded_length, last_mode_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001479 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001480 if (decoded_length != 0) {
1481 last_mode_ = kModeNormal;
1482 }
1483
1484 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1485 if ((speech_type == AudioDecoder::kComfortNoise)
1486 || ((last_mode_ == kModeCodecInternalCng)
1487 && (decoded_length == 0))) {
1488 // TODO(hlundin): Remove second part of || statement above.
1489 last_mode_ = kModeCodecInternalCng;
1490 }
1491
1492 if (!play_dtmf) {
1493 dtmf_tone_generator_->Reset();
1494 }
1495}
1496
1497void NetEqImpl::DoMerge(int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001498 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001499 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001500 assert(merge_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001501 size_t new_length = merge_->Process(decoded_buffer, decoded_length,
1502 mute_factor_array_.get(),
1503 algorithm_buffer_.get());
1504 size_t expand_length_correction = new_length -
1505 decoded_length / algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001506
1507 // Update in-call and post-call statistics.
1508 if (expand_->MuteFactor(0) == 0) {
1509 // Expand generates only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001510 stats_.ExpandedNoiseSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001511 } else {
1512 // Expansion generates more than only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001513 stats_.ExpandedVoiceSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001514 }
1515
1516 last_mode_ = kModeMerge;
1517 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1518 if (speech_type == AudioDecoder::kComfortNoise) {
1519 last_mode_ = kModeCodecInternalCng;
1520 }
1521 expand_->Reset();
1522 if (!play_dtmf) {
1523 dtmf_tone_generator_->Reset();
1524 }
1525}
1526
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001527int NetEqImpl::DoExpand(bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001528 while ((sync_buffer_->FutureLength() - expand_->overlap_length()) <
Peter Kastingdce40cf2015-08-24 14:52:23 -07001529 output_size_samples_) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001530 algorithm_buffer_->Clear();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001531 int return_value = expand_->Process(algorithm_buffer_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001532 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001533
1534 // Update in-call and post-call statistics.
1535 if (expand_->MuteFactor(0) == 0) {
1536 // Expand operation generates only noise.
1537 stats_.ExpandedNoiseSamples(length);
1538 } else {
1539 // Expand operation generates more than only noise.
1540 stats_.ExpandedVoiceSamples(length);
1541 }
1542
1543 last_mode_ = kModeExpand;
1544
1545 if (return_value < 0) {
1546 return return_value;
1547 }
1548
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001549 sync_buffer_->PushBack(*algorithm_buffer_);
1550 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001551 }
1552 if (!play_dtmf) {
1553 dtmf_tone_generator_->Reset();
1554 }
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001555
1556 if (!generated_noise_stopwatch_) {
1557 // Start a new stopwatch since we may be covering for a lost CNG packet.
1558 generated_noise_stopwatch_ = tick_timer_->GetNewStopwatch();
1559 }
1560
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001561 return 0;
1562}
1563
Henrik Lundincf808d22015-05-27 14:33:29 +02001564int NetEqImpl::DoAccelerate(int16_t* decoded_buffer,
1565 size_t decoded_length,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001566 AudioDecoder::SpeechType speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +02001567 bool play_dtmf,
1568 bool fast_accelerate) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001569 const size_t required_samples =
1570 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001571 size_t borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001572 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001573 size_t decoded_length_per_channel = decoded_length / num_channels;
1574 if (decoded_length_per_channel < required_samples) {
1575 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001576 borrowed_samples_per_channel = static_cast<int>(required_samples -
1577 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001578 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1579 decoded_buffer,
1580 sizeof(int16_t) * decoded_length);
1581 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1582 decoded_buffer);
1583 decoded_length = required_samples * num_channels;
1584 }
1585
Peter Kastingdce40cf2015-08-24 14:52:23 -07001586 size_t samples_removed;
Henrik Lundincf808d22015-05-27 14:33:29 +02001587 Accelerate::ReturnCodes return_code =
1588 accelerate_->Process(decoded_buffer, decoded_length, fast_accelerate,
1589 algorithm_buffer_.get(), &samples_removed);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001590 stats_.AcceleratedSamples(samples_removed);
1591 switch (return_code) {
1592 case Accelerate::kSuccess:
1593 last_mode_ = kModeAccelerateSuccess;
1594 break;
1595 case Accelerate::kSuccessLowEnergy:
1596 last_mode_ = kModeAccelerateLowEnergy;
1597 break;
1598 case Accelerate::kNoStretch:
1599 last_mode_ = kModeAccelerateFail;
1600 break;
1601 case Accelerate::kError:
1602 // TODO(hlundin): Map to kModeError instead?
1603 last_mode_ = kModeAccelerateFail;
1604 return kAccelerateError;
1605 }
1606
1607 if (borrowed_samples_per_channel > 0) {
1608 // Copy borrowed samples back to the |sync_buffer_|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001609 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001610 if (length < borrowed_samples_per_channel) {
1611 // This destroys the beginning of the buffer, but will not cause any
1612 // problems.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001613 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001614 sync_buffer_->Size() -
1615 borrowed_samples_per_channel);
1616 sync_buffer_->PushFrontZeros(borrowed_samples_per_channel - length);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001617 algorithm_buffer_->PopFront(length);
1618 assert(algorithm_buffer_->Empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001619 } else {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001620 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001621 borrowed_samples_per_channel,
1622 sync_buffer_->Size() -
1623 borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001624 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001625 }
1626 }
1627
1628 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1629 if (speech_type == AudioDecoder::kComfortNoise) {
1630 last_mode_ = kModeCodecInternalCng;
1631 }
1632 if (!play_dtmf) {
1633 dtmf_tone_generator_->Reset();
1634 }
1635 expand_->Reset();
1636 return 0;
1637}
1638
1639int NetEqImpl::DoPreemptiveExpand(int16_t* decoded_buffer,
1640 size_t decoded_length,
1641 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001642 bool play_dtmf) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001643 const size_t required_samples =
1644 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001645 size_t num_channels = algorithm_buffer_->Channels();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001646 size_t borrowed_samples_per_channel = 0;
1647 size_t old_borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001648 size_t decoded_length_per_channel = decoded_length / num_channels;
1649 if (decoded_length_per_channel < required_samples) {
1650 // Must move data from the |sync_buffer_| in order to get 30 ms.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001651 borrowed_samples_per_channel =
1652 required_samples - decoded_length_per_channel;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001653 // Calculate how many of these were already played out.
Peter Kastingf045e4d2015-06-10 21:15:38 -07001654 old_borrowed_samples_per_channel =
Peter Kastingdce40cf2015-08-24 14:52:23 -07001655 (borrowed_samples_per_channel > sync_buffer_->FutureLength()) ?
1656 (borrowed_samples_per_channel - sync_buffer_->FutureLength()) : 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001657 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1658 decoded_buffer,
1659 sizeof(int16_t) * decoded_length);
1660 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1661 decoded_buffer);
1662 decoded_length = required_samples * num_channels;
1663 }
1664
Peter Kastingdce40cf2015-08-24 14:52:23 -07001665 size_t samples_added;
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001666 PreemptiveExpand::ReturnCodes return_code = preemptive_expand_->Process(
Peter Kastingdce40cf2015-08-24 14:52:23 -07001667 decoded_buffer, decoded_length,
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001668 old_borrowed_samples_per_channel,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001669 algorithm_buffer_.get(), &samples_added);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001670 stats_.PreemptiveExpandedSamples(samples_added);
1671 switch (return_code) {
1672 case PreemptiveExpand::kSuccess:
1673 last_mode_ = kModePreemptiveExpandSuccess;
1674 break;
1675 case PreemptiveExpand::kSuccessLowEnergy:
1676 last_mode_ = kModePreemptiveExpandLowEnergy;
1677 break;
1678 case PreemptiveExpand::kNoStretch:
1679 last_mode_ = kModePreemptiveExpandFail;
1680 break;
1681 case PreemptiveExpand::kError:
1682 // TODO(hlundin): Map to kModeError instead?
1683 last_mode_ = kModePreemptiveExpandFail;
1684 return kPreemptiveExpandError;
1685 }
1686
1687 if (borrowed_samples_per_channel > 0) {
1688 // Copy borrowed samples back to the |sync_buffer_|.
1689 sync_buffer_->ReplaceAtIndex(
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001690 *algorithm_buffer_, borrowed_samples_per_channel,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001691 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001692 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001693 }
1694
1695 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1696 if (speech_type == AudioDecoder::kComfortNoise) {
1697 last_mode_ = kModeCodecInternalCng;
1698 }
1699 if (!play_dtmf) {
1700 dtmf_tone_generator_->Reset();
1701 }
1702 expand_->Reset();
1703 return 0;
1704}
1705
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001706int NetEqImpl::DoRfc3389Cng(PacketList* packet_list, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001707 if (!packet_list->empty()) {
1708 // Must have exactly one SID frame at this point.
1709 assert(packet_list->size() == 1);
1710 Packet* packet = packet_list->front();
1711 packet_list->pop_front();
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001712 if (!decoder_database_->IsComfortNoise(packet->header.payloadType)) {
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001713 LOG(LS_ERROR) << "Trying to decode non-CNG payload as CNG.";
1714 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001715 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001716 // UpdateParameters() deletes |packet|.
1717 if (comfort_noise_->UpdateParameters(packet) ==
1718 ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001719 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001720 return -comfort_noise_->internal_error_code();
1721 }
1722 }
1723 int cn_return = comfort_noise_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001724 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001725 expand_->Reset();
1726 last_mode_ = kModeRfc3389Cng;
1727 if (!play_dtmf) {
1728 dtmf_tone_generator_->Reset();
1729 }
1730 if (cn_return == ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001731 decoder_error_code_ = comfort_noise_->internal_error_code();
1732 return kComfortNoiseErrorCode;
1733 } else if (cn_return == ComfortNoise::kUnknownPayloadType) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001734 return kUnknownRtpPayloadType;
1735 }
1736 return 0;
1737}
1738
minyuel6d92bf52015-09-23 15:20:39 +02001739void NetEqImpl::DoCodecInternalCng(const int16_t* decoded_buffer,
1740 size_t decoded_length) {
1741 RTC_DCHECK(normal_.get());
1742 RTC_DCHECK(mute_factor_array_.get());
1743 normal_->Process(decoded_buffer, decoded_length, last_mode_,
1744 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001745 last_mode_ = kModeCodecInternalCng;
1746 expand_->Reset();
1747}
1748
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001749int NetEqImpl::DoDtmf(const DtmfEvent& dtmf_event, bool* play_dtmf) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001750 // This block of the code and the block further down, handling |dtmf_switch|
1751 // are commented out. Otherwise playing out-of-band DTMF would fail in VoE
1752 // test, DtmfTest.ManualSuccessfullySendsOutOfBandTelephoneEvents. This is
1753 // equivalent to |dtmf_switch| always be false.
1754 //
1755 // See http://webrtc-codereview.appspot.com/1195004/ for discussion
1756 // On this issue. This change might cause some glitches at the point of
1757 // switch from audio to DTMF. Issue 1545 is filed to track this.
1758 //
1759 // bool dtmf_switch = false;
1760 // if ((last_mode_ != kModeDtmf) && dtmf_tone_generator_->initialized()) {
1761 // // Special case; see below.
1762 // // We must catch this before calling Generate, since |initialized| is
1763 // // modified in that call.
1764 // dtmf_switch = true;
1765 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001766
1767 int dtmf_return_value = 0;
1768 if (!dtmf_tone_generator_->initialized()) {
1769 // Initialize if not already done.
1770 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1771 dtmf_event.volume);
1772 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001773
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001774 if (dtmf_return_value == 0) {
1775 // Generate DTMF signal.
1776 dtmf_return_value = dtmf_tone_generator_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001777 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001778 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001779
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001780 if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001781 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001782 return dtmf_return_value;
1783 }
1784
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001785 // if (dtmf_switch) {
1786 // // This is the special case where the previous operation was DTMF
1787 // // overdub, but the current instruction is "regular" DTMF. We must make
1788 // // sure that the DTMF does not have any discontinuities. The first DTMF
1789 // // sample that we generate now must be played out immediately, therefore
1790 // // it must be copied to the speech buffer.
1791 // // TODO(hlundin): This code seems incorrect. (Legacy.) Write test and
1792 // // verify correct operation.
1793 // assert(false);
1794 // // Must generate enough data to replace all of the |sync_buffer_|
1795 // // "future".
1796 // int required_length = sync_buffer_->FutureLength();
1797 // assert(dtmf_tone_generator_->initialized());
1798 // dtmf_return_value = dtmf_tone_generator_->Generate(required_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001799 // algorithm_buffer_);
1800 // assert((size_t) required_length == algorithm_buffer_->Size());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001801 // if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001802 // algorithm_buffer_->Zeros(output_size_samples_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001803 // return dtmf_return_value;
1804 // }
1805 //
1806 // // Overwrite the "future" part of the speech buffer with the new DTMF
1807 // // data.
1808 // // TODO(hlundin): It seems that this overwriting has gone lost.
1809 // // Not adapted for multi-channel yet.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001810 // assert(algorithm_buffer_->Channels() == 1);
1811 // if (algorithm_buffer_->Channels() != 1) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001812 // LOG(LS_WARNING) << "DTMF not supported for more than one channel";
1813 // return kStereoNotSupported;
1814 // }
1815 // // Shuffle the remaining data to the beginning of algorithm buffer.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001816 // algorithm_buffer_->PopFront(sync_buffer_->FutureLength());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001817 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001818
Peter Kastingb7e50542015-06-11 12:55:50 -07001819 sync_buffer_->IncreaseEndTimestamp(
1820 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001821 expand_->Reset();
1822 last_mode_ = kModeDtmf;
1823
1824 // Set to false because the DTMF is already in the algorithm buffer.
1825 *play_dtmf = false;
1826 return 0;
1827}
1828
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001829void NetEqImpl::DoAlternativePlc(bool increase_timestamp) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001830 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001831 size_t length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001832 if (decoder && decoder->HasDecodePlc()) {
1833 // Use the decoder's packet-loss concealment.
1834 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1835 int16_t decoded_buffer[kMaxFrameSize];
1836 length = decoder->DecodePlc(1, decoded_buffer);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001837 if (length > 0)
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001838 algorithm_buffer_->PushBackInterleaved(decoded_buffer, length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001839 } else {
1840 // Do simple zero-stuffing.
1841 length = output_size_samples_;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001842 algorithm_buffer_->Zeros(length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001843 // By not advancing the timestamp, NetEq inserts samples.
1844 stats_.AddZeros(length);
1845 }
1846 if (increase_timestamp) {
Peter Kastingb7e50542015-06-11 12:55:50 -07001847 sync_buffer_->IncreaseEndTimestamp(static_cast<uint32_t>(length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001848 }
1849 expand_->Reset();
1850}
1851
1852int NetEqImpl::DtmfOverdub(const DtmfEvent& dtmf_event, size_t num_channels,
1853 int16_t* output) const {
1854 size_t out_index = 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001855 size_t overdub_length = output_size_samples_; // Default value.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001856
1857 if (sync_buffer_->dtmf_index() > sync_buffer_->next_index()) {
1858 // Special operation for transition from "DTMF only" to "DTMF overdub".
1859 out_index = std::min(
1860 sync_buffer_->dtmf_index() - sync_buffer_->next_index(),
Peter Kastingdce40cf2015-08-24 14:52:23 -07001861 output_size_samples_);
1862 overdub_length = output_size_samples_ - out_index;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001863 }
1864
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001865 AudioMultiVector dtmf_output(num_channels);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001866 int dtmf_return_value = 0;
1867 if (!dtmf_tone_generator_->initialized()) {
1868 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1869 dtmf_event.volume);
1870 }
1871 if (dtmf_return_value == 0) {
1872 dtmf_return_value = dtmf_tone_generator_->Generate(overdub_length,
1873 &dtmf_output);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001874 assert(overdub_length == dtmf_output.Size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001875 }
1876 dtmf_output.ReadInterleaved(overdub_length, &output[out_index]);
1877 return dtmf_return_value < 0 ? dtmf_return_value : 0;
1878}
1879
Peter Kastingdce40cf2015-08-24 14:52:23 -07001880int NetEqImpl::ExtractPackets(size_t required_samples,
1881 PacketList* packet_list) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001882 bool first_packet = true;
1883 uint8_t prev_payload_type = 0;
1884 uint32_t prev_timestamp = 0;
1885 uint16_t prev_sequence_number = 0;
1886 bool next_packet_available = false;
1887
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001888 const RTPHeader* header = packet_buffer_->NextRtpHeader();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001889 assert(header);
1890 if (!header) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001891 LOG(LS_ERROR) << "Packet buffer unexpectedly empty.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001892 return -1;
1893 }
turaj@webrtc.org7df97062013-08-02 18:07:13 +00001894 uint32_t first_timestamp = header->timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001895 int extracted_samples = 0;
1896
1897 // Packet extraction loop.
1898 do {
1899 timestamp_ = header->timestamp;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001900 size_t discard_count = 0;
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001901 Packet* packet = packet_buffer_->GetNextPacket(&discard_count);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001902 // |header| may be invalid after the |packet_buffer_| operation.
1903 header = NULL;
1904 if (!packet) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001905 LOG(LS_ERROR) << "Should always be able to extract a packet here";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001906 assert(false); // Should always be able to extract a packet here.
1907 return -1;
1908 }
1909 stats_.PacketsDiscarded(discard_count);
henrik.lundin84f8cd62016-04-26 07:45:16 -07001910 stats_.StoreWaitingTime(packet->waiting_time->ElapsedMs());
ossudc431ce2016-08-31 08:51:13 -07001911 assert(!packet->payload.empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001912 packet_list->push_back(packet); // Store packet in list.
1913
1914 if (first_packet) {
1915 first_packet = false;
henrik.lundin48ed9302015-10-29 05:36:24 -07001916 if (nack_enabled_) {
1917 RTC_DCHECK(nack_);
1918 // TODO(henrik.lundin): Should we update this for all decoded packets?
1919 nack_->UpdateLastDecodedPacket(packet->header.sequenceNumber,
1920 packet->header.timestamp);
1921 }
1922 prev_sequence_number = packet->header.sequenceNumber;
1923 prev_timestamp = packet->header.timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001924 prev_payload_type = packet->header.payloadType;
1925 }
1926
1927 // Store number of extracted samples.
1928 int packet_duration = 0;
1929 AudioDecoder* decoder = decoder_database_->GetDecoder(
1930 packet->header.payloadType);
1931 if (decoder) {
ossu17e3fa12016-09-08 04:52:55 -07001932 if (packet->primary) {
1933 packet_duration = decoder->PacketDuration(packet->payload.data(),
1934 packet->payload.size());
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001935 } else {
ossu17e3fa12016-09-08 04:52:55 -07001936 packet_duration = decoder->PacketDurationRedundant(
1937 packet->payload.data(), packet->payload.size());
1938 stats_.SecondaryDecodedSamples(packet_duration);
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001939 }
ossu97ba30e2016-04-25 07:55:58 -07001940 } else if (!decoder_database_->IsComfortNoise(packet->header.payloadType)) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001941 LOG(LS_WARNING) << "Unknown payload type "
1942 << static_cast<int>(packet->header.payloadType);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001943 assert(false);
1944 }
1945 if (packet_duration <= 0) {
1946 // Decoder did not return a packet duration. Assume that the packet
1947 // contains the same number of samples as the previous one.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001948 packet_duration = rtc::checked_cast<int>(decoder_frame_length_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001949 }
1950 extracted_samples = packet->header.timestamp - first_timestamp +
1951 packet_duration;
1952
1953 // Check what packet is available next.
1954 header = packet_buffer_->NextRtpHeader();
1955 next_packet_available = false;
1956 if (header && prev_payload_type == header->payloadType) {
1957 int16_t seq_no_diff = header->sequenceNumber - prev_sequence_number;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001958 size_t ts_diff = header->timestamp - prev_timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001959 if (seq_no_diff == 1 ||
1960 (seq_no_diff == 0 && ts_diff == decoder_frame_length_)) {
1961 // The next sequence number is available, or the next part of a packet
1962 // that was split into pieces upon insertion.
1963 next_packet_available = true;
1964 }
1965 prev_sequence_number = header->sequenceNumber;
1966 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07001967 } while (extracted_samples < rtc::checked_cast<int>(required_samples) &&
1968 next_packet_available);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001969
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00001970 if (extracted_samples > 0) {
1971 // Delete old packets only when we are going to decode something. Otherwise,
1972 // we could end up in the situation where we never decode anything, since
1973 // all incoming packets are considered too old but the buffer will also
1974 // never be flooded and flushed.
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001975 packet_buffer_->DiscardAllOldPackets(timestamp_);
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00001976 }
1977
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001978 return extracted_samples;
1979}
1980
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001981void NetEqImpl::UpdatePlcComponents(int fs_hz, size_t channels) {
1982 // Delete objects and create new ones.
1983 expand_.reset(expand_factory_->Create(background_noise_.get(),
1984 sync_buffer_.get(), &random_vector_,
Henrik Lundinbef77e22015-08-18 14:58:09 +02001985 &stats_, fs_hz, channels));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001986 merge_.reset(new Merge(fs_hz, channels, expand_.get(), sync_buffer_.get()));
1987}
1988
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001989void NetEqImpl::SetSampleRateAndChannels(int fs_hz, size_t channels) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001990 LOG(LS_VERBOSE) << "SetSampleRateAndChannels " << fs_hz << " " << channels;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001991 // TODO(hlundin): Change to an enumerator and skip assert.
1992 assert(fs_hz == 8000 || fs_hz == 16000 || fs_hz == 32000 || fs_hz == 48000);
1993 assert(channels > 0);
1994
1995 fs_hz_ = fs_hz;
1996 fs_mult_ = fs_hz / 8000;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001997 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001998 decoder_frame_length_ = 3 * output_size_samples_; // Initialize to 30ms.
1999
2000 last_mode_ = kModeNormal;
2001
2002 // Create a new array of mute factors and set all to 1.
2003 mute_factor_array_.reset(new int16_t[channels]);
2004 for (size_t i = 0; i < channels; ++i) {
2005 mute_factor_array_[i] = 16384; // 1.0 in Q14.
2006 }
2007
ossu97ba30e2016-04-25 07:55:58 -07002008 ComfortNoiseDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02002009 if (cng_decoder)
2010 cng_decoder->Reset();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002011
2012 // Reinit post-decode VAD with new sample rate.
2013 assert(vad_.get()); // Cannot be NULL here.
2014 vad_->Init();
2015
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002016 // Delete algorithm buffer and create a new one.
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00002017 algorithm_buffer_.reset(new AudioMultiVector(channels));
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002018
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002019 // Delete sync buffer and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002020 sync_buffer_.reset(new SyncBuffer(channels, kSyncBufferSize * fs_mult_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002021
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00002022 // Delete BackgroundNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002023 background_noise_.reset(new BackgroundNoise(channels));
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00002024 background_noise_->set_mode(background_noise_mode_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002025
2026 // Reset random vector.
2027 random_vector_.Reset();
2028
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002029 UpdatePlcComponents(fs_hz, channels);
2030
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002031 // Move index so that we create a small set of future samples (all 0).
2032 sync_buffer_->set_next_index(sync_buffer_->next_index() -
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002033 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002034
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002035 normal_.reset(new Normal(fs_hz, decoder_database_.get(), *background_noise_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002036 expand_.get()));
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +00002037 accelerate_.reset(
2038 accelerate_factory_->Create(fs_hz, channels, *background_noise_));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002039 preemptive_expand_.reset(preemptive_expand_factory_->Create(
Peter Kastingdce40cf2015-08-24 14:52:23 -07002040 fs_hz, channels, *background_noise_, expand_->overlap_length()));
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002041
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002042 // Delete ComfortNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002043 comfort_noise_.reset(new ComfortNoise(fs_hz, decoder_database_.get(),
2044 sync_buffer_.get()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002045
2046 // Verify that |decoded_buffer_| is long enough.
2047 if (decoded_buffer_length_ < kMaxFrameSize * channels) {
2048 // Reallocate to larger size.
2049 decoded_buffer_length_ = kMaxFrameSize * channels;
2050 decoded_buffer_.reset(new int16_t[decoded_buffer_length_]);
2051 }
2052
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002053 // Create DecisionLogic if it is not created yet, then communicate new sample
2054 // rate and output size to DecisionLogic object.
2055 if (!decision_logic_.get()) {
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002056 CreateDecisionLogic();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002057 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002058 decision_logic_->SetSampleRate(fs_hz_, output_size_samples_);
2059}
2060
henrik.lundin55480f52016-03-08 02:37:57 -08002061NetEqImpl::OutputType NetEqImpl::LastOutputType() {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002062 assert(vad_.get());
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002063 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002064 if (last_mode_ == kModeCodecInternalCng || last_mode_ == kModeRfc3389Cng) {
henrik.lundin55480f52016-03-08 02:37:57 -08002065 return OutputType::kCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002066 } else if (last_mode_ == kModeExpand && expand_->MuteFactor(0) == 0) {
2067 // Expand mode has faded down to background noise only (very long expand).
henrik.lundin55480f52016-03-08 02:37:57 -08002068 return OutputType::kPLCCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002069 } else if (last_mode_ == kModeExpand) {
henrik.lundin55480f52016-03-08 02:37:57 -08002070 return OutputType::kPLC;
wu@webrtc.org24301a62013-12-13 19:17:43 +00002071 } else if (vad_->running() && !vad_->active_speech()) {
henrik.lundin55480f52016-03-08 02:37:57 -08002072 return OutputType::kVadPassive;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002073 } else {
henrik.lundin55480f52016-03-08 02:37:57 -08002074 return OutputType::kNormalSpeech;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002075 }
2076}
2077
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002078void NetEqImpl::CreateDecisionLogic() {
Henrik Lundin47b17dc2016-05-10 10:20:59 +02002079 decision_logic_.reset(DecisionLogic::Create(
2080 fs_hz_, output_size_samples_, playout_mode_, decoder_database_.get(),
2081 *packet_buffer_.get(), delay_manager_.get(), buffer_level_filter_.get(),
2082 tick_timer_.get()));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002083}
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002084} // namespace webrtc