blob: d62d44f2b4a08dd8635d3c0ffc105f75c6cc023e [file] [log] [blame]
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001/*
2 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000011#include "webrtc/modules/audio_coding/neteq/neteq_impl.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000012
13#include <assert.h>
14#include <memory.h> // memset
15
16#include <algorithm>
ossu61a208b2016-09-20 01:38:00 -070017#include <utility>
ossu97ba30e2016-04-25 07:55:58 -070018#include <vector>
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000019
henrik.lundin9c3efd02015-08-27 13:12:22 -070020#include "webrtc/base/checks.h"
Henrik Lundind67a2192015-08-03 12:54:37 +020021#include "webrtc/base/logging.h"
Tommid44c0772016-03-11 17:12:32 -080022#include "webrtc/base/safe_conversions.h"
kwibergac554ee2016-09-02 00:39:33 -070023#include "webrtc/base/sanitizer.h"
henrik.lundina689b442015-12-17 03:50:05 -080024#include "webrtc/base/trace_event.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000025#include "webrtc/common_audio/signal_processing/include/signal_processing_library.h"
kwiberg@webrtc.orge04a93b2014-12-09 10:12:53 +000026#include "webrtc/modules/audio_coding/codecs/audio_decoder.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000027#include "webrtc/modules/audio_coding/neteq/accelerate.h"
28#include "webrtc/modules/audio_coding/neteq/background_noise.h"
29#include "webrtc/modules/audio_coding/neteq/buffer_level_filter.h"
30#include "webrtc/modules/audio_coding/neteq/comfort_noise.h"
31#include "webrtc/modules/audio_coding/neteq/decision_logic.h"
32#include "webrtc/modules/audio_coding/neteq/decoder_database.h"
33#include "webrtc/modules/audio_coding/neteq/defines.h"
34#include "webrtc/modules/audio_coding/neteq/delay_manager.h"
35#include "webrtc/modules/audio_coding/neteq/delay_peak_detector.h"
36#include "webrtc/modules/audio_coding/neteq/dtmf_buffer.h"
37#include "webrtc/modules/audio_coding/neteq/dtmf_tone_generator.h"
38#include "webrtc/modules/audio_coding/neteq/expand.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000039#include "webrtc/modules/audio_coding/neteq/merge.h"
henrik.lundin91951862016-06-08 06:43:41 -070040#include "webrtc/modules/audio_coding/neteq/nack_tracker.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000041#include "webrtc/modules/audio_coding/neteq/normal.h"
42#include "webrtc/modules/audio_coding/neteq/packet_buffer.h"
43#include "webrtc/modules/audio_coding/neteq/packet.h"
44#include "webrtc/modules/audio_coding/neteq/payload_splitter.h"
45#include "webrtc/modules/audio_coding/neteq/post_decode_vad.h"
46#include "webrtc/modules/audio_coding/neteq/preemptive_expand.h"
47#include "webrtc/modules/audio_coding/neteq/sync_buffer.h"
henrik.lundined497212016-04-25 10:11:38 -070048#include "webrtc/modules/audio_coding/neteq/tick_timer.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000049#include "webrtc/modules/audio_coding/neteq/timestamp_scaler.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010050#include "webrtc/modules/include/module_common_types.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000051
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000052namespace webrtc {
53
ossue3525782016-05-25 07:37:43 -070054NetEqImpl::Dependencies::Dependencies(
55 const NetEq::Config& config,
56 const rtc::scoped_refptr<AudioDecoderFactory>& decoder_factory)
henrik.lundin1d9061e2016-04-26 12:19:34 -070057 : tick_timer(new TickTimer),
58 buffer_level_filter(new BufferLevelFilter),
ossue3525782016-05-25 07:37:43 -070059 decoder_database(new DecoderDatabase(decoder_factory)),
henrik.lundinf3933702016-04-28 01:53:52 -070060 delay_peak_detector(new DelayPeakDetector(tick_timer.get())),
henrik.lundin1d9061e2016-04-26 12:19:34 -070061 delay_manager(new DelayManager(config.max_packets_in_buffer,
henrik.lundin8f8c96d2016-04-28 23:19:20 -070062 delay_peak_detector.get(),
63 tick_timer.get())),
henrik.lundin1d9061e2016-04-26 12:19:34 -070064 dtmf_buffer(new DtmfBuffer(config.sample_rate_hz)),
65 dtmf_tone_generator(new DtmfToneGenerator),
66 packet_buffer(
67 new PacketBuffer(config.max_packets_in_buffer, tick_timer.get())),
68 payload_splitter(new PayloadSplitter),
69 timestamp_scaler(new TimestampScaler(*decoder_database)),
70 accelerate_factory(new AccelerateFactory),
71 expand_factory(new ExpandFactory),
72 preemptive_expand_factory(new PreemptiveExpandFactory) {}
73
74NetEqImpl::Dependencies::~Dependencies() = default;
75
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +000076NetEqImpl::NetEqImpl(const NetEq::Config& config,
henrik.lundin1d9061e2016-04-26 12:19:34 -070077 Dependencies&& deps,
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +000078 bool create_components)
henrik.lundin1d9061e2016-04-26 12:19:34 -070079 : tick_timer_(std::move(deps.tick_timer)),
80 buffer_level_filter_(std::move(deps.buffer_level_filter)),
81 decoder_database_(std::move(deps.decoder_database)),
82 delay_manager_(std::move(deps.delay_manager)),
83 delay_peak_detector_(std::move(deps.delay_peak_detector)),
84 dtmf_buffer_(std::move(deps.dtmf_buffer)),
85 dtmf_tone_generator_(std::move(deps.dtmf_tone_generator)),
86 packet_buffer_(std::move(deps.packet_buffer)),
87 payload_splitter_(std::move(deps.payload_splitter)),
88 timestamp_scaler_(std::move(deps.timestamp_scaler)),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000089 vad_(new PostDecodeVad()),
henrik.lundin1d9061e2016-04-26 12:19:34 -070090 expand_factory_(std::move(deps.expand_factory)),
91 accelerate_factory_(std::move(deps.accelerate_factory)),
92 preemptive_expand_factory_(std::move(deps.preemptive_expand_factory)),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000093 last_mode_(kModeNormal),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000094 decoded_buffer_length_(kMaxFrameSize),
95 decoded_buffer_(new int16_t[decoded_buffer_length_]),
96 playout_timestamp_(0),
97 new_codec_(false),
98 timestamp_(0),
99 reset_decoder_(false),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000100 ssrc_(0),
101 first_packet_(true),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000102 error_code_(0),
103 decoder_error_code_(0),
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +0000104 background_noise_mode_(config.background_noise_mode),
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000105 playout_mode_(config.playout_mode),
Henrik Lundincf808d22015-05-27 14:33:29 +0200106 enable_fast_accelerate_(config.enable_fast_accelerate),
henrik.lundin7a926812016-05-12 13:51:28 -0700107 nack_enabled_(false),
108 enable_muted_state_(config.enable_muted_state) {
Henrik Lundin905495c2015-05-25 16:58:41 +0200109 LOG(LS_INFO) << "NetEq config: " << config.ToString();
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +0000110 int fs = config.sample_rate_hz;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000111 if (fs != 8000 && fs != 16000 && fs != 32000 && fs != 48000) {
112 LOG(LS_ERROR) << "Sample rate " << fs << " Hz not supported. " <<
113 "Changing to 8000 Hz.";
114 fs = 8000;
115 }
henrik.lundin1d9061e2016-04-26 12:19:34 -0700116 delay_manager_->SetMaximumDelay(config.max_delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000117 fs_hz_ = fs;
118 fs_mult_ = fs / 8000;
henrik.lundind89814b2015-11-23 06:49:25 -0800119 last_output_sample_rate_hz_ = fs;
Peter Kastingdce40cf2015-08-24 14:52:23 -0700120 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000121 decoder_frame_length_ = 3 * output_size_samples_;
122 WebRtcSpl_Init();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000123 if (create_components) {
124 SetSampleRateAndChannels(fs, 1); // Default is 1 channel.
125 }
henrik.lundin9bc26672015-11-02 03:25:57 -0800126 RTC_DCHECK(!vad_->enabled());
127 if (config.enable_post_decode_vad) {
128 vad_->Enable();
129 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000130}
131
Henrik Lundind67a2192015-08-03 12:54:37 +0200132NetEqImpl::~NetEqImpl() = default;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000133
134int NetEqImpl::InsertPacket(const WebRtcRTPHeader& rtp_header,
kwibergee2bac22015-11-11 10:34:00 -0800135 rtc::ArrayView<const uint8_t> payload,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000136 uint32_t receive_timestamp) {
kwibergac554ee2016-09-02 00:39:33 -0700137 rtc::MsanCheckInitialized(payload);
henrik.lundina689b442015-12-17 03:50:05 -0800138 TRACE_EVENT0("webrtc", "NetEqImpl::InsertPacket");
Tommi9090e0b2016-01-20 13:39:36 +0100139 rtc::CritScope lock(&crit_sect_);
kwibergee2bac22015-11-11 10:34:00 -0800140 int error =
ossu17e3fa12016-09-08 04:52:55 -0700141 InsertPacketInternal(rtp_header, payload, receive_timestamp);
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000142 if (error != 0) {
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000143 error_code_ = error;
144 return kFail;
145 }
146 return kOK;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000147}
148
henrik.lundin500c04b2016-03-08 02:36:04 -0800149namespace {
150void SetAudioFrameActivityAndType(bool vad_enabled,
henrik.lundin55480f52016-03-08 02:37:57 -0800151 NetEqImpl::OutputType type,
henrik.lundin500c04b2016-03-08 02:36:04 -0800152 AudioFrame::VADActivity last_vad_activity,
153 AudioFrame* audio_frame) {
154 switch (type) {
henrik.lundin55480f52016-03-08 02:37:57 -0800155 case NetEqImpl::OutputType::kNormalSpeech: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800156 audio_frame->speech_type_ = AudioFrame::kNormalSpeech;
157 audio_frame->vad_activity_ = AudioFrame::kVadActive;
158 break;
159 }
henrik.lundin55480f52016-03-08 02:37:57 -0800160 case NetEqImpl::OutputType::kVadPassive: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800161 // This should only be reached if the VAD is enabled.
162 RTC_DCHECK(vad_enabled);
163 audio_frame->speech_type_ = AudioFrame::kNormalSpeech;
164 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
165 break;
166 }
henrik.lundin55480f52016-03-08 02:37:57 -0800167 case NetEqImpl::OutputType::kCNG: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800168 audio_frame->speech_type_ = AudioFrame::kCNG;
169 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
170 break;
171 }
henrik.lundin55480f52016-03-08 02:37:57 -0800172 case NetEqImpl::OutputType::kPLC: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800173 audio_frame->speech_type_ = AudioFrame::kPLC;
174 audio_frame->vad_activity_ = last_vad_activity;
175 break;
176 }
henrik.lundin55480f52016-03-08 02:37:57 -0800177 case NetEqImpl::OutputType::kPLCCNG: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800178 audio_frame->speech_type_ = AudioFrame::kPLCCNG;
179 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
180 break;
181 }
182 default:
183 RTC_NOTREACHED();
184 }
185 if (!vad_enabled) {
186 // Always set kVadUnknown when receive VAD is inactive.
187 audio_frame->vad_activity_ = AudioFrame::kVadUnknown;
188 }
189}
henrik.lundinbc89de32016-03-08 05:20:14 -0800190} // namespace
henrik.lundin500c04b2016-03-08 02:36:04 -0800191
henrik.lundin7a926812016-05-12 13:51:28 -0700192int NetEqImpl::GetAudio(AudioFrame* audio_frame, bool* muted) {
henrik.lundine1ca1672016-01-08 03:50:08 -0800193 TRACE_EVENT0("webrtc", "NetEqImpl::GetAudio");
Tommi9090e0b2016-01-20 13:39:36 +0100194 rtc::CritScope lock(&crit_sect_);
henrik.lundin7a926812016-05-12 13:51:28 -0700195 int error = GetAudioInternal(audio_frame, muted);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000196 if (error != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000197 error_code_ = error;
198 return kFail;
199 }
henrik.lundin5fac3f02016-08-24 11:18:49 -0700200 RTC_DCHECK_EQ(
201 audio_frame->sample_rate_hz_,
202 rtc::checked_cast<int>(audio_frame->samples_per_channel_ * 100));
henrik.lundin500c04b2016-03-08 02:36:04 -0800203 SetAudioFrameActivityAndType(vad_->enabled(), LastOutputType(),
204 last_vad_activity_, audio_frame);
205 last_vad_activity_ = audio_frame->vad_activity_;
henrik.lundin6d8e0112016-03-04 10:34:21 -0800206 last_output_sample_rate_hz_ = audio_frame->sample_rate_hz_;
henrik.lundind89814b2015-11-23 06:49:25 -0800207 RTC_DCHECK(last_output_sample_rate_hz_ == 8000 ||
208 last_output_sample_rate_hz_ == 16000 ||
209 last_output_sample_rate_hz_ == 32000 ||
210 last_output_sample_rate_hz_ == 48000)
211 << "Unexpected sample rate " << last_output_sample_rate_hz_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000212 return kOK;
213}
214
kwibergee1879c2015-10-29 06:20:28 -0700215int NetEqImpl::RegisterPayloadType(NetEqDecoder codec,
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800216 const std::string& name,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000217 uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100218 rtc::CritScope lock(&crit_sect_);
Henrik Lundind67a2192015-08-03 12:54:37 +0200219 LOG(LS_VERBOSE) << "RegisterPayloadType "
kwibergee1879c2015-10-29 06:20:28 -0700220 << static_cast<int>(rtp_payload_type) << " "
221 << static_cast<int>(codec);
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800222 int ret = decoder_database_->RegisterPayload(rtp_payload_type, codec, name);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000223 if (ret != DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000224 switch (ret) {
225 case DecoderDatabase::kInvalidRtpPayloadType:
226 error_code_ = kInvalidRtpPayloadType;
227 break;
228 case DecoderDatabase::kCodecNotSupported:
229 error_code_ = kCodecNotSupported;
230 break;
231 case DecoderDatabase::kDecoderExists:
232 error_code_ = kDecoderExists;
233 break;
234 default:
235 error_code_ = kOtherError;
236 }
237 return kFail;
238 }
239 return kOK;
240}
241
242int NetEqImpl::RegisterExternalDecoder(AudioDecoder* decoder,
kwibergee1879c2015-10-29 06:20:28 -0700243 NetEqDecoder codec,
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800244 const std::string& codec_name,
kwiberg342f7402016-06-16 03:18:00 -0700245 uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100246 rtc::CritScope lock(&crit_sect_);
Henrik Lundind67a2192015-08-03 12:54:37 +0200247 LOG(LS_VERBOSE) << "RegisterExternalDecoder "
kwibergee1879c2015-10-29 06:20:28 -0700248 << static_cast<int>(rtp_payload_type) << " "
249 << static_cast<int>(codec);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000250 if (!decoder) {
251 LOG(LS_ERROR) << "Cannot register external decoder with NULL pointer";
252 assert(false);
253 return kFail;
254 }
kwiberg342f7402016-06-16 03:18:00 -0700255 int ret = decoder_database_->InsertExternal(rtp_payload_type, codec,
256 codec_name, decoder);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000257 if (ret != DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000258 switch (ret) {
259 case DecoderDatabase::kInvalidRtpPayloadType:
260 error_code_ = kInvalidRtpPayloadType;
261 break;
262 case DecoderDatabase::kCodecNotSupported:
263 error_code_ = kCodecNotSupported;
264 break;
265 case DecoderDatabase::kDecoderExists:
266 error_code_ = kDecoderExists;
267 break;
268 case DecoderDatabase::kInvalidSampleRate:
269 error_code_ = kInvalidSampleRate;
270 break;
271 case DecoderDatabase::kInvalidPointer:
272 error_code_ = kInvalidPointer;
273 break;
274 default:
275 error_code_ = kOtherError;
276 }
277 return kFail;
278 }
279 return kOK;
280}
281
282int NetEqImpl::RemovePayloadType(uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100283 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000284 int ret = decoder_database_->Remove(rtp_payload_type);
285 if (ret == DecoderDatabase::kOK) {
ossu61a208b2016-09-20 01:38:00 -0700286 packet_buffer_->DiscardPacketsWithPayloadType(rtp_payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000287 return kOK;
288 } else if (ret == DecoderDatabase::kDecoderNotFound) {
289 error_code_ = kDecoderNotFound;
290 } else {
291 error_code_ = kOtherError;
292 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000293 return kFail;
294}
295
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000296bool NetEqImpl::SetMinimumDelay(int delay_ms) {
Tommi9090e0b2016-01-20 13:39:36 +0100297 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000298 if (delay_ms >= 0 && delay_ms < 10000) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000299 assert(delay_manager_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000300 return delay_manager_->SetMinimumDelay(delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000301 }
302 return false;
303}
304
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000305bool NetEqImpl::SetMaximumDelay(int delay_ms) {
Tommi9090e0b2016-01-20 13:39:36 +0100306 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000307 if (delay_ms >= 0 && delay_ms < 10000) {
308 assert(delay_manager_.get());
309 return delay_manager_->SetMaximumDelay(delay_ms);
310 }
311 return false;
312}
313
314int NetEqImpl::LeastRequiredDelayMs() const {
Tommi9090e0b2016-01-20 13:39:36 +0100315 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000316 assert(delay_manager_.get());
317 return delay_manager_->least_required_delay_ms();
318}
319
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200320int NetEqImpl::SetTargetDelay() {
321 return kNotImplemented;
322}
323
324int NetEqImpl::TargetDelay() {
325 return kNotImplemented;
326}
327
henrik.lundin9c3efd02015-08-27 13:12:22 -0700328int NetEqImpl::CurrentDelayMs() const {
Tommi9090e0b2016-01-20 13:39:36 +0100329 rtc::CritScope lock(&crit_sect_);
henrik.lundin9c3efd02015-08-27 13:12:22 -0700330 if (fs_hz_ == 0)
331 return 0;
332 // Sum up the samples in the packet buffer with the future length of the sync
333 // buffer, and divide the sum by the sample rate.
334 const size_t delay_samples =
ossu61a208b2016-09-20 01:38:00 -0700335 packet_buffer_->NumSamplesInBuffer(decoder_frame_length_) +
henrik.lundin9c3efd02015-08-27 13:12:22 -0700336 sync_buffer_->FutureLength();
337 // The division below will truncate.
338 const int delay_ms =
339 static_cast<int>(delay_samples) / rtc::CheckedDivExact(fs_hz_, 1000);
340 return delay_ms;
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200341}
342
henrik.lundinb3f1c5d2016-08-22 15:39:53 -0700343int NetEqImpl::FilteredCurrentDelayMs() const {
344 rtc::CritScope lock(&crit_sect_);
345 // Calculate the filtered packet buffer level in samples. The value from
346 // |buffer_level_filter_| is in number of packets, represented in Q8.
347 const size_t packet_buffer_samples =
348 (buffer_level_filter_->filtered_current_level() *
349 decoder_frame_length_) >>
350 8;
351 // Sum up the filtered packet buffer level with the future length of the sync
352 // buffer, and divide the sum by the sample rate.
353 const size_t delay_samples =
354 packet_buffer_samples + sync_buffer_->FutureLength();
355 // The division below will truncate. The return value is in ms.
356 return static_cast<int>(delay_samples) / rtc::CheckedDivExact(fs_hz_, 1000);
357}
358
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000359// Deprecated.
360// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000361void NetEqImpl::SetPlayoutMode(NetEqPlayoutMode mode) {
Tommi9090e0b2016-01-20 13:39:36 +0100362 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000363 if (mode != playout_mode_) {
364 playout_mode_ = mode;
365 CreateDecisionLogic();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000366 }
367}
368
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000369// Deprecated.
370// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000371NetEqPlayoutMode NetEqImpl::PlayoutMode() const {
Tommi9090e0b2016-01-20 13:39:36 +0100372 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000373 return playout_mode_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000374}
375
376int NetEqImpl::NetworkStatistics(NetEqNetworkStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100377 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000378 assert(decoder_database_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700379 const size_t total_samples_in_buffers =
ossu61a208b2016-09-20 01:38:00 -0700380 packet_buffer_->NumSamplesInBuffer(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
ossu61a208b2016-09-20 01:38:00 -0700665 PacketList parsed_packet_list;
666 while (!packet_list.empty()) {
667 std::unique_ptr<Packet> packet(packet_list.front());
668 packet_list.pop_front();
669 const DecoderDatabase::DecoderInfo* info =
670 decoder_database_->GetDecoderInfo(packet->header.payloadType);
671 if (!info) {
672 LOG(LS_WARNING) << "SplitAudio unknown payload type";
673 return kUnknownRtpPayloadType;
674 }
675
676 if (info->IsComfortNoise()) {
677 // Carry comfort noise packets along.
678 parsed_packet_list.push_back(packet.release());
679 } else {
680 std::vector<AudioDecoder::ParseResult> results =
681 info->GetDecoder()->ParsePayload(std::move(packet->payload),
682 packet->header.timestamp,
683 packet->primary);
684 const RTPHeader& original_header = packet->header;
685 for (auto& result : results) {
686 RTC_DCHECK(result.frame);
687 // Reuse the packet if possible
688 if (!packet) {
689 packet.reset(new Packet);
690 packet->header = original_header;
691 }
692 packet->header.timestamp = result.timestamp;
693 // TODO(ossu): Move from primary to some sort of priority level.
694 packet->primary = result.primary;
695 packet->frame = std::move(result.frame);
696 parsed_packet_list.push_back(packet.release());
697 }
698 }
699 }
700
henrik.lundin48ed9302015-10-29 05:36:24 -0700701 if (nack_enabled_) {
702 RTC_DCHECK(nack_);
703 if (update_sample_rate_and_channels) {
704 nack_->Reset();
705 }
ossu61a208b2016-09-20 01:38:00 -0700706 nack_->UpdateLastReceivedPacket(
707 parsed_packet_list.front()->header.sequenceNumber,
708 parsed_packet_list.front()->header.timestamp);
henrik.lundin48ed9302015-10-29 05:36:24 -0700709 }
710
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000711 // Insert packets in buffer.
henrik.lundin116c84e2015-08-27 13:14:48 -0700712 const size_t buffer_length_before_insert =
713 packet_buffer_->NumPacketsInBuffer();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000714 ret = packet_buffer_->InsertPacketList(
ossu61a208b2016-09-20 01:38:00 -0700715 &parsed_packet_list, *decoder_database_, &current_rtp_payload_type_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000716 &current_cng_rtp_payload_type_);
717 if (ret == PacketBuffer::kFlushed) {
718 // Reset DSP timestamp etc. if packet buffer flushed.
719 new_codec_ = true;
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000720 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000721 } else if (ret != PacketBuffer::kOK) {
ossu61a208b2016-09-20 01:38:00 -0700722 PacketBuffer::DeleteAllPackets(&parsed_packet_list);
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000723 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000724 }
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000725
726 if (first_packet_) {
727 first_packet_ = false;
728 // Update the codec on the next GetAudio call.
729 new_codec_ = true;
730 }
731
henrik.lundinda8bbf62016-08-31 03:14:11 -0700732 if (current_rtp_payload_type_) {
733 RTC_DCHECK(decoder_database_->GetDecoderInfo(*current_rtp_payload_type_))
734 << "Payload type " << static_cast<int>(*current_rtp_payload_type_)
735 << " is unknown where it shouldn't be";
736 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000737
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000738 if (update_sample_rate_and_channels && !packet_buffer_->Empty()) {
739 // We do not use |current_rtp_payload_type_| to |set payload_type|, but
740 // get the next RTP header from |packet_buffer_| to obtain the payload type.
741 // The reason for it is the following corner case. If NetEq receives a
742 // CNG packet with a sample rate different than the current CNG then it
743 // flushes its buffer, assuming send codec must have been changed. However,
744 // payload type of the hypothetically new send codec is not known.
745 const RTPHeader* rtp_header = packet_buffer_->NextRtpHeader();
746 assert(rtp_header);
747 int payload_type = rtp_header->payloadType;
ossu97ba30e2016-04-25 07:55:58 -0700748 size_t channels = 1;
749 if (!decoder_database_->IsComfortNoise(payload_type)) {
750 AudioDecoder* decoder = decoder_database_->GetDecoder(payload_type);
751 assert(decoder); // Payloads are already checked to be valid.
752 channels = decoder->Channels();
753 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000754 const DecoderDatabase::DecoderInfo* decoder_info =
755 decoder_database_->GetDecoderInfo(payload_type);
756 assert(decoder_info);
kwibergc0f2dcf2016-05-31 06:28:03 -0700757 if (decoder_info->SampleRateHz() != fs_hz_ ||
ossu97ba30e2016-04-25 07:55:58 -0700758 channels != algorithm_buffer_->Channels()) {
kwibergc0f2dcf2016-05-31 06:28:03 -0700759 SetSampleRateAndChannels(decoder_info->SampleRateHz(),
760 channels);
henrik.lundin48ed9302015-10-29 05:36:24 -0700761 }
762 if (nack_enabled_) {
763 RTC_DCHECK(nack_);
764 // Update the sample rate even if the rate is not new, because of Reset().
765 nack_->UpdateSampleRate(fs_hz_);
766 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000767 }
768
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000769 // TODO(hlundin): Move this code to DelayManager class.
770 const DecoderDatabase::DecoderInfo* dec_info =
771 decoder_database_->GetDecoderInfo(main_header.payloadType);
772 assert(dec_info); // Already checked that the payload type is known.
773 delay_manager_->LastDecoderType(dec_info->codec_type);
774 if (delay_manager_->last_pack_cng_or_dtmf() == 0) {
775 // Calculate the total speech length carried in each packet.
henrik.lundin116c84e2015-08-27 13:14:48 -0700776 const size_t buffer_length_after_insert =
777 packet_buffer_->NumPacketsInBuffer();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000778
henrik.lundin116c84e2015-08-27 13:14:48 -0700779 if (buffer_length_after_insert > buffer_length_before_insert) {
780 const size_t packet_length_samples =
781 (buffer_length_after_insert - buffer_length_before_insert) *
782 decoder_frame_length_;
783 if (packet_length_samples != decision_logic_->packet_length_samples()) {
784 decision_logic_->set_packet_length_samples(packet_length_samples);
785 delay_manager_->SetPacketAudioLength(
786 rtc::checked_cast<int>((1000 * packet_length_samples) / fs_hz_));
787 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000788 }
789
790 // Update statistics.
pbos@webrtc.org0946a562013-04-09 00:28:06 +0000791 if ((int32_t) (main_header.timestamp - timestamp_) >= 0 &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000792 !new_codec_) {
793 // Only update statistics if incoming packet is not older than last played
794 // out packet, and if new codec flag is not set.
795 delay_manager_->Update(main_header.sequenceNumber, main_header.timestamp,
796 fs_hz_);
797 }
798 } else if (delay_manager_->last_pack_cng_or_dtmf() == -1) {
799 // This is first "normal" packet after CNG or DTMF.
800 // Reset packet time counter and measure time until next packet,
801 // but don't update statistics.
802 delay_manager_->set_last_pack_cng_or_dtmf(0);
803 delay_manager_->ResetPacketIatCount();
804 }
805 return 0;
806}
807
henrik.lundin7a926812016-05-12 13:51:28 -0700808int NetEqImpl::GetAudioInternal(AudioFrame* audio_frame, bool* muted) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000809 PacketList packet_list;
810 DtmfEvent dtmf_event;
811 Operations operation;
812 bool play_dtmf;
henrik.lundin7a926812016-05-12 13:51:28 -0700813 *muted = false;
henrik.lundined497212016-04-25 10:11:38 -0700814 tick_timer_->Increment();
henrik.lundin60f6ce22016-05-10 03:52:04 -0700815 stats_.IncreaseCounter(output_size_samples_, fs_hz_);
henrik.lundin7a926812016-05-12 13:51:28 -0700816
817 // Check for muted state.
818 if (enable_muted_state_ && expand_->Muted() && packet_buffer_->Empty()) {
819 RTC_DCHECK_EQ(last_mode_, kModeExpand);
820 playout_timestamp_ += static_cast<uint32_t>(output_size_samples_);
821 audio_frame->sample_rate_hz_ = fs_hz_;
822 audio_frame->samples_per_channel_ = output_size_samples_;
823 audio_frame->timestamp_ =
824 first_packet_
825 ? 0
826 : timestamp_scaler_->ToExternal(playout_timestamp_) -
827 static_cast<uint32_t>(audio_frame->samples_per_channel_);
828 audio_frame->num_channels_ = sync_buffer_->Channels();
henrik.lundin612c25e2016-05-25 08:21:04 -0700829 stats_.ExpandedNoiseSamples(output_size_samples_);
henrik.lundin7a926812016-05-12 13:51:28 -0700830 *muted = true;
831 return 0;
832 }
833
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000834 int return_value = GetDecision(&operation, &packet_list, &dtmf_event,
835 &play_dtmf);
836 if (return_value != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000837 last_mode_ = kModeError;
838 return return_value;
839 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000840
841 AudioDecoder::SpeechType speech_type;
842 int length = 0;
843 int decode_return_value = Decode(&packet_list, &operation,
844 &length, &speech_type);
845
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000846 assert(vad_.get());
847 bool sid_frame_available =
848 (operation == kRfc3389Cng && !packet_list.empty());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700849 vad_->Update(decoded_buffer_.get(), static_cast<size_t>(length), speech_type,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000850 sid_frame_available, fs_hz_);
851
henrik.lundinb1fb72b2016-05-03 08:18:47 -0700852 if (sid_frame_available || speech_type == AudioDecoder::kComfortNoise) {
853 // Start a new stopwatch since we are decoding a new CNG packet.
854 generated_noise_stopwatch_ = tick_timer_->GetNewStopwatch();
855 }
856
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000857 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000858 switch (operation) {
859 case kNormal: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000860 DoNormal(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000861 break;
862 }
863 case kMerge: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000864 DoMerge(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000865 break;
866 }
867 case kExpand: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000868 return_value = DoExpand(play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000869 break;
870 }
Henrik Lundincf808d22015-05-27 14:33:29 +0200871 case kAccelerate:
872 case kFastAccelerate: {
873 const bool fast_accelerate =
874 enable_fast_accelerate_ && (operation == kFastAccelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000875 return_value = DoAccelerate(decoded_buffer_.get(), length, speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +0200876 play_dtmf, fast_accelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000877 break;
878 }
879 case kPreemptiveExpand: {
880 return_value = DoPreemptiveExpand(decoded_buffer_.get(), length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000881 speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000882 break;
883 }
884 case kRfc3389Cng:
885 case kRfc3389CngNoPacket: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000886 return_value = DoRfc3389Cng(&packet_list, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000887 break;
888 }
889 case kCodecInternalCng: {
890 // This handles the case when there is no transmission and the decoder
891 // should produce internal comfort noise.
892 // TODO(hlundin): Write test for codec-internal CNG.
minyuel6d92bf52015-09-23 15:20:39 +0200893 DoCodecInternalCng(decoded_buffer_.get(), length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000894 break;
895 }
896 case kDtmf: {
897 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000898 return_value = DoDtmf(dtmf_event, &play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000899 break;
900 }
901 case kAlternativePlc: {
902 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000903 DoAlternativePlc(false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000904 break;
905 }
906 case kAlternativePlcIncreaseTimestamp: {
907 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000908 DoAlternativePlc(true);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000909 break;
910 }
911 case kAudioRepetitionIncreaseTimestamp: {
912 // TODO(hlundin): Write test for this.
Peter Kastingb7e50542015-06-11 12:55:50 -0700913 sync_buffer_->IncreaseEndTimestamp(
914 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000915 // Skipping break on purpose. Execution should move on into the
916 // next case.
kjellander@webrtc.org7d2b6a92015-01-28 18:37:58 +0000917 FALLTHROUGH();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000918 }
919 case kAudioRepetition: {
920 // TODO(hlundin): Write test for this.
921 // Copy last |output_size_samples_| from |sync_buffer_| to
922 // |algorithm_buffer|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000923 algorithm_buffer_->PushBackFromIndex(
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000924 *sync_buffer_, sync_buffer_->Size() - output_size_samples_);
925 expand_->Reset();
926 break;
927 }
928 case kUndefined: {
Henrik Lundind67a2192015-08-03 12:54:37 +0200929 LOG(LS_ERROR) << "Invalid operation kUndefined.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000930 assert(false); // This should not happen.
931 last_mode_ = kModeError;
932 return kInvalidOperation;
933 }
934 } // End of switch.
minyue5bd33972016-05-02 04:46:11 -0700935 last_operation_ = operation;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000936 if (return_value < 0) {
937 return return_value;
938 }
939
940 if (last_mode_ != kModeRfc3389Cng) {
941 comfort_noise_->Reset();
942 }
943
944 // Copy from |algorithm_buffer| to |sync_buffer_|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000945 sync_buffer_->PushBack(*algorithm_buffer_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000946
947 // Extract data from |sync_buffer_| to |output|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000948 size_t num_output_samples_per_channel = output_size_samples_;
949 size_t num_output_samples = output_size_samples_ * sync_buffer_->Channels();
henrik.lundin6d8e0112016-03-04 10:34:21 -0800950 if (num_output_samples > AudioFrame::kMaxDataSizeSamples) {
951 LOG(LS_WARNING) << "Output array is too short. "
952 << AudioFrame::kMaxDataSizeSamples << " < "
953 << output_size_samples_ << " * "
954 << sync_buffer_->Channels();
955 num_output_samples = AudioFrame::kMaxDataSizeSamples;
956 num_output_samples_per_channel =
957 AudioFrame::kMaxDataSizeSamples / sync_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000958 }
henrik.lundin6d8e0112016-03-04 10:34:21 -0800959 sync_buffer_->GetNextAudioInterleaved(num_output_samples_per_channel,
960 audio_frame);
961 audio_frame->sample_rate_hz_ = fs_hz_;
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200962 if (sync_buffer_->FutureLength() < expand_->overlap_length()) {
963 // The sync buffer should always contain |overlap_length| samples, but now
964 // too many samples have been extracted. Reinstall the |overlap_length|
965 // lookahead by moving the index.
966 const size_t missing_lookahead_samples =
967 expand_->overlap_length() - sync_buffer_->FutureLength();
henrikg91d6ede2015-09-17 00:24:34 -0700968 RTC_DCHECK_GE(sync_buffer_->next_index(), missing_lookahead_samples);
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200969 sync_buffer_->set_next_index(sync_buffer_->next_index() -
970 missing_lookahead_samples);
971 }
henrik.lundin6d8e0112016-03-04 10:34:21 -0800972 if (audio_frame->samples_per_channel_ != output_size_samples_) {
973 LOG(LS_ERROR) << "audio_frame->samples_per_channel_ ("
974 << audio_frame->samples_per_channel_
Henrik Lundind67a2192015-08-03 12:54:37 +0200975 << ") != output_size_samples_ (" << output_size_samples_
976 << ")";
minyue@webrtc.orgdb1cefc2013-08-13 01:39:21 +0000977 // TODO(minyue): treatment of under-run, filling zeros
henrik.lundin6d8e0112016-03-04 10:34:21 -0800978 memset(audio_frame->data_, 0, num_output_samples * sizeof(int16_t));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000979 return kSampleUnderrun;
980 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000981
982 // Should always have overlap samples left in the |sync_buffer_|.
henrikg91d6ede2015-09-17 00:24:34 -0700983 RTC_DCHECK_GE(sync_buffer_->FutureLength(), expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000984
985 if (play_dtmf) {
henrik.lundin6d8e0112016-03-04 10:34:21 -0800986 return_value =
987 DtmfOverdub(dtmf_event, sync_buffer_->Channels(), audio_frame->data_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000988 }
989
990 // Update the background noise parameters if last operation wrote data
991 // straight from the decoder to the |sync_buffer_|. That is, none of the
992 // operations that modify the signal can be followed by a parameter update.
993 if ((last_mode_ == kModeNormal) ||
994 (last_mode_ == kModeAccelerateFail) ||
995 (last_mode_ == kModePreemptiveExpandFail) ||
996 (last_mode_ == kModeRfc3389Cng) ||
997 (last_mode_ == kModeCodecInternalCng)) {
998 background_noise_->Update(*sync_buffer_, *vad_.get());
999 }
1000
1001 if (operation == kDtmf) {
1002 // DTMF data was written the end of |sync_buffer_|.
1003 // Update index to end of DTMF data in |sync_buffer_|.
1004 sync_buffer_->set_dtmf_index(sync_buffer_->Size());
1005 }
1006
henrik.lundin@webrtc.orged865b52014-03-06 10:28:07 +00001007 if (last_mode_ != kModeExpand) {
1008 // If last operation was not expand, calculate the |playout_timestamp_| from
1009 // the |sync_buffer_|. However, do not update the |playout_timestamp_| if it
1010 // would be moved "backwards".
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001011 uint32_t temp_timestamp = sync_buffer_->end_timestamp() -
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001012 static_cast<uint32_t>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001013 if (static_cast<int32_t>(temp_timestamp - playout_timestamp_) > 0) {
1014 playout_timestamp_ = temp_timestamp;
1015 }
1016 } else {
1017 // Use dead reckoning to estimate the |playout_timestamp_|.
Peter Kastingb7e50542015-06-11 12:55:50 -07001018 playout_timestamp_ += static_cast<uint32_t>(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001019 }
henrik.lundin15c51e32016-04-06 08:38:56 -07001020 // Set the timestamp in the audio frame to zero before the first packet has
1021 // been inserted. Otherwise, subtract the frame size in samples to get the
1022 // timestamp of the first sample in the frame (playout_timestamp_ is the
1023 // last + 1).
1024 audio_frame->timestamp_ =
1025 first_packet_
1026 ? 0
1027 : timestamp_scaler_->ToExternal(playout_timestamp_) -
1028 static_cast<uint32_t>(audio_frame->samples_per_channel_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001029
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001030 if (!(last_mode_ == kModeRfc3389Cng ||
1031 last_mode_ == kModeCodecInternalCng ||
1032 last_mode_ == kModeExpand)) {
1033 generated_noise_stopwatch_.reset();
1034 }
1035
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001036 if (decode_return_value) return decode_return_value;
1037 return return_value;
1038}
1039
1040int NetEqImpl::GetDecision(Operations* operation,
1041 PacketList* packet_list,
1042 DtmfEvent* dtmf_event,
1043 bool* play_dtmf) {
1044 // Initialize output variables.
1045 *play_dtmf = false;
1046 *operation = kUndefined;
1047
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001048 assert(sync_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001049 uint32_t end_timestamp = sync_buffer_->end_timestamp();
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001050 if (!new_codec_) {
1051 const uint32_t five_seconds_samples = 5 * fs_hz_;
1052 packet_buffer_->DiscardOldPackets(end_timestamp, five_seconds_samples);
1053 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001054 const RTPHeader* header = packet_buffer_->NextRtpHeader();
1055
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001056 RTC_DCHECK(!generated_noise_stopwatch_ ||
1057 generated_noise_stopwatch_->ElapsedTicks() >= 1);
1058 uint64_t generated_noise_samples =
1059 generated_noise_stopwatch_
1060 ? (generated_noise_stopwatch_->ElapsedTicks() - 1) *
1061 output_size_samples_ +
1062 decision_logic_->noise_fast_forward()
1063 : 0;
1064
henrik.lundin@webrtc.orgca8cb952014-03-12 10:26:52 +00001065 if (decision_logic_->CngRfc3389On() || last_mode_ == kModeRfc3389Cng) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001066 // Because of timestamp peculiarities, we have to "manually" disallow using
1067 // a CNG packet with the same timestamp as the one that was last played.
1068 // This can happen when using redundancy and will cause the timing to shift.
henrik.lundin@webrtc.org24779fe2014-03-14 12:40:05 +00001069 while (header && decoder_database_->IsComfortNoise(header->payloadType) &&
1070 (end_timestamp >= header->timestamp ||
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001071 end_timestamp + generated_noise_samples > header->timestamp)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001072 // Don't use this packet, discard it.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001073 if (packet_buffer_->DiscardNextPacket() != PacketBuffer::kOK) {
1074 assert(false); // Must be ok by design.
1075 }
1076 // Check buffer again.
1077 if (!new_codec_) {
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001078 packet_buffer_->DiscardOldPackets(end_timestamp, 5 * fs_hz_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001079 }
1080 header = packet_buffer_->NextRtpHeader();
1081 }
1082 }
1083
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001084 assert(expand_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001085 const int samples_left = static_cast<int>(sync_buffer_->FutureLength() -
1086 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001087 if (last_mode_ == kModeAccelerateSuccess ||
1088 last_mode_ == kModeAccelerateLowEnergy ||
1089 last_mode_ == kModePreemptiveExpandSuccess ||
1090 last_mode_ == kModePreemptiveExpandLowEnergy) {
1091 // Subtract (samples_left + output_size_samples_) from sampleMemory.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001092 decision_logic_->AddSampleMemory(
1093 -(samples_left + rtc::checked_cast<int>(output_size_samples_)));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001094 }
1095
1096 // Check if it is time to play a DTMF event.
Peter Kastingb7e50542015-06-11 12:55:50 -07001097 if (dtmf_buffer_->GetEvent(
1098 static_cast<uint32_t>(
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001099 end_timestamp + generated_noise_samples),
Peter Kastingb7e50542015-06-11 12:55:50 -07001100 dtmf_event)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001101 *play_dtmf = true;
1102 }
1103
1104 // Get instruction.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001105 assert(sync_buffer_.get());
1106 assert(expand_.get());
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001107 generated_noise_samples =
1108 generated_noise_stopwatch_
1109 ? generated_noise_stopwatch_->ElapsedTicks() * output_size_samples_ +
1110 decision_logic_->noise_fast_forward()
1111 : 0;
1112 *operation = decision_logic_->GetDecision(
1113 *sync_buffer_, *expand_, decoder_frame_length_, header, last_mode_,
1114 *play_dtmf, generated_noise_samples, &reset_decoder_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001115
1116 // Check if we already have enough samples in the |sync_buffer_|. If so,
1117 // change decision to normal, unless the decision was merge, accelerate, or
1118 // preemptive expand.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001119 if (samples_left >= rtc::checked_cast<int>(output_size_samples_) &&
1120 *operation != kMerge &&
1121 *operation != kAccelerate &&
1122 *operation != kFastAccelerate &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001123 *operation != kPreemptiveExpand) {
1124 *operation = kNormal;
1125 return 0;
1126 }
1127
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001128 decision_logic_->ExpandDecision(*operation);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001129
1130 // Check conditions for reset.
1131 if (new_codec_ || *operation == kUndefined) {
1132 // The only valid reason to get kUndefined is that new_codec_ is set.
1133 assert(new_codec_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001134 if (*play_dtmf && !header) {
1135 timestamp_ = dtmf_event->timestamp;
1136 } else {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001137 if (!header) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001138 LOG(LS_ERROR) << "Packet missing where it shouldn't.";
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001139 return -1;
1140 }
1141 timestamp_ = header->timestamp;
ossu108ecec2016-07-08 08:45:18 -07001142 if (*operation == kRfc3389CngNoPacket &&
1143 decoder_database_->IsComfortNoise(header->payloadType)) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001144 // Change decision to CNG packet, since we do have a CNG packet, but it
1145 // was considered too early to use. Now, use it anyway.
1146 *operation = kRfc3389Cng;
1147 } else if (*operation != kRfc3389Cng) {
1148 *operation = kNormal;
1149 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001150 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001151 // Adjust |sync_buffer_| timestamp before setting |end_timestamp| to the
1152 // new value.
1153 sync_buffer_->IncreaseEndTimestamp(timestamp_ - end_timestamp);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001154 end_timestamp = timestamp_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001155 new_codec_ = false;
1156 decision_logic_->SoftReset();
1157 buffer_level_filter_->Reset();
1158 delay_manager_->Reset();
1159 stats_.ResetMcu();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001160 }
1161
Peter Kastingdce40cf2015-08-24 14:52:23 -07001162 size_t required_samples = output_size_samples_;
1163 const size_t samples_10_ms = static_cast<size_t>(80 * fs_mult_);
1164 const size_t samples_20_ms = 2 * samples_10_ms;
1165 const size_t samples_30_ms = 3 * samples_10_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001166
1167 switch (*operation) {
1168 case kExpand: {
1169 timestamp_ = end_timestamp;
1170 return 0;
1171 }
1172 case kRfc3389CngNoPacket:
1173 case kCodecInternalCng: {
1174 return 0;
1175 }
1176 case kDtmf: {
1177 // TODO(hlundin): Write test for this.
1178 // Update timestamp.
1179 timestamp_ = end_timestamp;
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001180 const uint64_t generated_noise_samples =
1181 generated_noise_stopwatch_
1182 ? generated_noise_stopwatch_->ElapsedTicks() *
1183 output_size_samples_ +
1184 decision_logic_->noise_fast_forward()
1185 : 0;
1186 if (generated_noise_samples > 0 && last_mode_ != kModeDtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001187 // Make a jump in timestamp due to the recently played comfort noise.
Peter Kastingb7e50542015-06-11 12:55:50 -07001188 uint32_t timestamp_jump =
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001189 static_cast<uint32_t>(generated_noise_samples);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001190 sync_buffer_->IncreaseEndTimestamp(timestamp_jump);
1191 timestamp_ += timestamp_jump;
1192 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001193 return 0;
1194 }
Henrik Lundincf808d22015-05-27 14:33:29 +02001195 case kAccelerate:
1196 case kFastAccelerate: {
1197 // In order to do an accelerate we need at least 30 ms of audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001198 if (samples_left >= static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001199 // Already have enough data, so we do not need to extract any more.
1200 decision_logic_->set_sample_memory(samples_left);
1201 decision_logic_->set_prev_time_scale(true);
1202 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001203 } else if (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001204 decoder_frame_length_ >= samples_30_ms) {
1205 // Avoid decoding more data as it might overflow the playout buffer.
1206 *operation = kNormal;
1207 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001208 } else if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001209 decoder_frame_length_ < samples_30_ms) {
1210 // Build up decoded data by decoding at least 20 ms of audio data. Do
1211 // not perform accelerate yet, but wait until we only need to do one
1212 // decoding.
1213 required_samples = 2 * output_size_samples_;
1214 *operation = kNormal;
1215 }
1216 // If none of the above is true, we have one of two possible situations:
1217 // (1) 20 ms <= samples_left < 30 ms and decoder_frame_length_ < 30 ms; or
1218 // (2) samples_left < 10 ms and decoder_frame_length_ >= 30 ms.
1219 // In either case, we move on with the accelerate decision, and decode one
1220 // frame now.
1221 break;
1222 }
1223 case kPreemptiveExpand: {
1224 // In order to do a preemptive expand we need at least 30 ms of decoded
1225 // audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001226 if ((samples_left >= static_cast<int>(samples_30_ms)) ||
1227 (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001228 decoder_frame_length_ >= samples_30_ms)) {
1229 // Already have enough data, so we do not need to extract any more.
1230 // Or, avoid decoding more data as it might overflow the playout buffer.
1231 // Still try preemptive expand, though.
1232 decision_logic_->set_sample_memory(samples_left);
1233 decision_logic_->set_prev_time_scale(true);
1234 return 0;
1235 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07001236 if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001237 decoder_frame_length_ < samples_30_ms) {
1238 // Build up decoded data by decoding at least 20 ms of audio data.
1239 // Still try to perform preemptive expand.
1240 required_samples = 2 * output_size_samples_;
1241 }
1242 // Move on with the preemptive expand decision.
1243 break;
1244 }
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001245 case kMerge: {
1246 required_samples =
1247 std::max(merge_->RequiredFutureSamples(), required_samples);
1248 break;
1249 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001250 default: {
1251 // Do nothing.
1252 }
1253 }
1254
1255 // Get packets from buffer.
1256 int extracted_samples = 0;
1257 if (header &&
1258 *operation != kAlternativePlc &&
1259 *operation != kAlternativePlcIncreaseTimestamp &&
1260 *operation != kAudioRepetition &&
1261 *operation != kAudioRepetitionIncreaseTimestamp) {
1262 sync_buffer_->IncreaseEndTimestamp(header->timestamp - end_timestamp);
1263 if (decision_logic_->CngOff()) {
1264 // Adjustment of timestamp only corresponds to an actual packet loss
1265 // if comfort noise is not played. If comfort noise was just played,
1266 // this adjustment of timestamp is only done to get back in sync with the
1267 // stream timestamp; no loss to report.
1268 stats_.LostSamples(header->timestamp - end_timestamp);
1269 }
1270
1271 if (*operation != kRfc3389Cng) {
1272 // We are about to decode and use a non-CNG packet.
1273 decision_logic_->SetCngOff();
1274 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001275
1276 extracted_samples = ExtractPackets(required_samples, packet_list);
1277 if (extracted_samples < 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001278 return kPacketBufferCorruption;
1279 }
1280 }
1281
Henrik Lundincf808d22015-05-27 14:33:29 +02001282 if (*operation == kAccelerate || *operation == kFastAccelerate ||
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001283 *operation == kPreemptiveExpand) {
1284 decision_logic_->set_sample_memory(samples_left + extracted_samples);
1285 decision_logic_->set_prev_time_scale(true);
1286 }
1287
Henrik Lundincf808d22015-05-27 14:33:29 +02001288 if (*operation == kAccelerate || *operation == kFastAccelerate) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001289 // Check that we have enough data (30ms) to do accelerate.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001290 if (extracted_samples + samples_left < static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001291 // TODO(hlundin): Write test for this.
1292 // Not enough, do normal operation instead.
1293 *operation = kNormal;
1294 }
1295 }
1296
1297 timestamp_ = end_timestamp;
1298 return 0;
1299}
1300
1301int NetEqImpl::Decode(PacketList* packet_list, Operations* operation,
1302 int* decoded_length,
1303 AudioDecoder::SpeechType* speech_type) {
1304 *speech_type = AudioDecoder::kSpeech;
minyuel6d92bf52015-09-23 15:20:39 +02001305
1306 // When packet_list is empty, we may be in kCodecInternalCng mode, and for
1307 // that we use current active decoder.
1308 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1309
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001310 if (!packet_list->empty()) {
1311 const Packet* packet = packet_list->front();
pkasting@chromium.org0e81fdf2015-02-02 23:54:03 +00001312 uint8_t payload_type = packet->header.payloadType;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001313 if (!decoder_database_->IsComfortNoise(payload_type)) {
1314 decoder = decoder_database_->GetDecoder(payload_type);
1315 assert(decoder);
1316 if (!decoder) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001317 LOG(LS_WARNING) << "Unknown payload type "
1318 << static_cast<int>(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001319 PacketBuffer::DeleteAllPackets(packet_list);
1320 return kDecoderNotFound;
1321 }
1322 bool decoder_changed;
1323 decoder_database_->SetActiveDecoder(payload_type, &decoder_changed);
1324 if (decoder_changed) {
1325 // We have a new decoder. Re-init some values.
1326 const DecoderDatabase::DecoderInfo* decoder_info = decoder_database_
1327 ->GetDecoderInfo(payload_type);
1328 assert(decoder_info);
1329 if (!decoder_info) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001330 LOG(LS_WARNING) << "Unknown payload type "
1331 << static_cast<int>(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001332 PacketBuffer::DeleteAllPackets(packet_list);
1333 return kDecoderNotFound;
1334 }
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001335 // If sampling rate or number of channels has changed, we need to make
1336 // a reset.
kwibergc0f2dcf2016-05-31 06:28:03 -07001337 if (decoder_info->SampleRateHz() != fs_hz_ ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001338 decoder->Channels() != algorithm_buffer_->Channels()) {
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001339 // TODO(tlegrand): Add unittest to cover this event.
kwibergc0f2dcf2016-05-31 06:28:03 -07001340 SetSampleRateAndChannels(decoder_info->SampleRateHz(),
1341 decoder->Channels());
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001342 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001343 sync_buffer_->set_end_timestamp(timestamp_);
1344 playout_timestamp_ = timestamp_;
1345 }
1346 }
1347 }
1348
1349 if (reset_decoder_) {
1350 // TODO(hlundin): Write test for this.
Karl Wiberg43766482015-08-27 15:22:11 +02001351 if (decoder)
1352 decoder->Reset();
1353
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001354 // Reset comfort noise decoder.
ossu97ba30e2016-04-25 07:55:58 -07001355 ComfortNoiseDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02001356 if (cng_decoder)
1357 cng_decoder->Reset();
1358
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001359 reset_decoder_ = false;
1360 }
1361
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001362 *decoded_length = 0;
1363 // Update codec-internal PLC state.
1364 if ((*operation == kMerge) && decoder && decoder->HasDecodePlc()) {
1365 decoder->DecodePlc(1, &decoded_buffer_[*decoded_length]);
1366 }
1367
minyuel6d92bf52015-09-23 15:20:39 +02001368 int return_value;
1369 if (*operation == kCodecInternalCng) {
1370 RTC_DCHECK(packet_list->empty());
1371 return_value = DecodeCng(decoder, decoded_length, speech_type);
1372 } else {
1373 return_value = DecodeLoop(packet_list, *operation, decoder,
1374 decoded_length, speech_type);
1375 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001376
1377 if (*decoded_length < 0) {
1378 // Error returned from the decoder.
1379 *decoded_length = 0;
Peter Kastingb7e50542015-06-11 12:55:50 -07001380 sync_buffer_->IncreaseEndTimestamp(
1381 static_cast<uint32_t>(decoder_frame_length_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001382 int error_code = 0;
1383 if (decoder)
1384 error_code = decoder->ErrorCode();
1385 if (error_code != 0) {
1386 // Got some error code from the decoder.
1387 decoder_error_code_ = error_code;
1388 return_value = kDecoderErrorCode;
Henrik Lundind67a2192015-08-03 12:54:37 +02001389 LOG(LS_WARNING) << "Decoder returned error code: " << error_code;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001390 } else {
1391 // Decoder does not implement error codes. Return generic error.
1392 return_value = kOtherDecoderError;
Henrik Lundind67a2192015-08-03 12:54:37 +02001393 LOG(LS_WARNING) << "Decoder error (no error code)";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001394 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001395 *operation = kExpand; // Do expansion to get data instead.
1396 }
1397 if (*speech_type != AudioDecoder::kComfortNoise) {
1398 // Don't increment timestamp if codec returned CNG speech type
1399 // since in this case, the we will increment the CNGplayedTS counter.
1400 // Increase with number of samples per channel.
1401 assert(*decoded_length == 0 ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001402 (decoder && decoder->Channels() == sync_buffer_->Channels()));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001403 sync_buffer_->IncreaseEndTimestamp(
1404 *decoded_length / static_cast<int>(sync_buffer_->Channels()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001405 }
1406 return return_value;
1407}
1408
minyuel6d92bf52015-09-23 15:20:39 +02001409int NetEqImpl::DecodeCng(AudioDecoder* decoder, int* decoded_length,
1410 AudioDecoder::SpeechType* speech_type) {
1411 if (!decoder) {
1412 // This happens when active decoder is not defined.
1413 *decoded_length = -1;
1414 return 0;
1415 }
1416
1417 while (*decoded_length < rtc::checked_cast<int>(output_size_samples_)) {
1418 const int length = decoder->Decode(
1419 nullptr, 0, fs_hz_,
1420 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1421 &decoded_buffer_[*decoded_length], speech_type);
1422 if (length > 0) {
1423 *decoded_length += length;
minyuel6d92bf52015-09-23 15:20:39 +02001424 } else {
1425 // Error.
1426 LOG(LS_WARNING) << "Failed to decode CNG";
1427 *decoded_length = -1;
1428 break;
1429 }
1430 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1431 // Guard against overflow.
1432 LOG(LS_WARNING) << "Decoded too much CNG.";
1433 return kDecodedTooMuch;
1434 }
1435 }
1436 return 0;
1437}
1438
1439int NetEqImpl::DecodeLoop(PacketList* packet_list, const Operations& operation,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001440 AudioDecoder* decoder, int* decoded_length,
1441 AudioDecoder::SpeechType* speech_type) {
1442 Packet* packet = NULL;
1443 if (!packet_list->empty()) {
1444 packet = packet_list->front();
1445 }
minyuel6d92bf52015-09-23 15:20:39 +02001446
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001447 // Do decoding.
1448 while (packet &&
1449 !decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1450 assert(decoder); // At this point, we must have a decoder object.
1451 // The number of channels in the |sync_buffer_| should be the same as the
1452 // number decoder channels.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001453 assert(sync_buffer_->Channels() == decoder->Channels());
1454 assert(decoded_buffer_length_ >= kMaxFrameSize * decoder->Channels());
minyuel6d92bf52015-09-23 15:20:39 +02001455 assert(operation == kNormal || operation == kAccelerate ||
1456 operation == kFastAccelerate || operation == kMerge ||
1457 operation == kPreemptiveExpand);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001458 packet_list->pop_front();
ossu61a208b2016-09-20 01:38:00 -07001459 auto opt_result = packet->frame->Decode(
1460 rtc::ArrayView<int16_t>(&decoded_buffer_[*decoded_length],
1461 decoded_buffer_length_ - *decoded_length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001462 delete packet;
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001463 packet = NULL;
ossu61a208b2016-09-20 01:38:00 -07001464 if (opt_result) {
1465 const auto& result = *opt_result;
1466 *speech_type = result.speech_type;
1467 if (result.num_decoded_samples > 0) {
1468 *decoded_length += rtc::checked_cast<int>(result.num_decoded_samples);
1469 // Update |decoder_frame_length_| with number of samples per channel.
1470 decoder_frame_length_ =
1471 result.num_decoded_samples / decoder->Channels();
1472 }
1473 } else {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001474 // Error.
ossu61a208b2016-09-20 01:38:00 -07001475 // TODO(ossu): What to put here?
1476 LOG(LS_WARNING) << "Decode error";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001477 *decoded_length = -1;
1478 PacketBuffer::DeleteAllPackets(packet_list);
1479 break;
1480 }
ossu61a208b2016-09-20 01:38:00 -07001481 if (*decoded_length > rtc::checked_cast<int>(decoded_buffer_length_)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001482 // Guard against overflow.
Henrik Lundind67a2192015-08-03 12:54:37 +02001483 LOG(LS_WARNING) << "Decoded too much.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001484 PacketBuffer::DeleteAllPackets(packet_list);
1485 return kDecodedTooMuch;
1486 }
1487 if (!packet_list->empty()) {
1488 packet = packet_list->front();
1489 } else {
1490 packet = NULL;
1491 }
1492 } // End of decode loop.
1493
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001494 // If the list is not empty at this point, either a decoding error terminated
1495 // the while-loop, or list must hold exactly one CNG packet.
1496 assert(packet_list->empty() || *decoded_length < 0 ||
1497 (packet_list->size() == 1 && packet &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001498 decoder_database_->IsComfortNoise(packet->header.payloadType)));
1499 return 0;
1500}
1501
1502void NetEqImpl::DoNormal(const int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001503 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001504 assert(normal_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001505 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001506 normal_->Process(decoded_buffer, decoded_length, last_mode_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001507 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001508 if (decoded_length != 0) {
1509 last_mode_ = kModeNormal;
1510 }
1511
1512 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1513 if ((speech_type == AudioDecoder::kComfortNoise)
1514 || ((last_mode_ == kModeCodecInternalCng)
1515 && (decoded_length == 0))) {
1516 // TODO(hlundin): Remove second part of || statement above.
1517 last_mode_ = kModeCodecInternalCng;
1518 }
1519
1520 if (!play_dtmf) {
1521 dtmf_tone_generator_->Reset();
1522 }
1523}
1524
1525void NetEqImpl::DoMerge(int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001526 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001527 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001528 assert(merge_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001529 size_t new_length = merge_->Process(decoded_buffer, decoded_length,
1530 mute_factor_array_.get(),
1531 algorithm_buffer_.get());
1532 size_t expand_length_correction = new_length -
1533 decoded_length / algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001534
1535 // Update in-call and post-call statistics.
1536 if (expand_->MuteFactor(0) == 0) {
1537 // Expand generates only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001538 stats_.ExpandedNoiseSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001539 } else {
1540 // Expansion generates more than only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001541 stats_.ExpandedVoiceSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001542 }
1543
1544 last_mode_ = kModeMerge;
1545 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1546 if (speech_type == AudioDecoder::kComfortNoise) {
1547 last_mode_ = kModeCodecInternalCng;
1548 }
1549 expand_->Reset();
1550 if (!play_dtmf) {
1551 dtmf_tone_generator_->Reset();
1552 }
1553}
1554
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001555int NetEqImpl::DoExpand(bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001556 while ((sync_buffer_->FutureLength() - expand_->overlap_length()) <
Peter Kastingdce40cf2015-08-24 14:52:23 -07001557 output_size_samples_) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001558 algorithm_buffer_->Clear();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001559 int return_value = expand_->Process(algorithm_buffer_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001560 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001561
1562 // Update in-call and post-call statistics.
1563 if (expand_->MuteFactor(0) == 0) {
1564 // Expand operation generates only noise.
1565 stats_.ExpandedNoiseSamples(length);
1566 } else {
1567 // Expand operation generates more than only noise.
1568 stats_.ExpandedVoiceSamples(length);
1569 }
1570
1571 last_mode_ = kModeExpand;
1572
1573 if (return_value < 0) {
1574 return return_value;
1575 }
1576
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001577 sync_buffer_->PushBack(*algorithm_buffer_);
1578 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001579 }
1580 if (!play_dtmf) {
1581 dtmf_tone_generator_->Reset();
1582 }
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001583
1584 if (!generated_noise_stopwatch_) {
1585 // Start a new stopwatch since we may be covering for a lost CNG packet.
1586 generated_noise_stopwatch_ = tick_timer_->GetNewStopwatch();
1587 }
1588
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001589 return 0;
1590}
1591
Henrik Lundincf808d22015-05-27 14:33:29 +02001592int NetEqImpl::DoAccelerate(int16_t* decoded_buffer,
1593 size_t decoded_length,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001594 AudioDecoder::SpeechType speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +02001595 bool play_dtmf,
1596 bool fast_accelerate) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001597 const size_t required_samples =
1598 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001599 size_t borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001600 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001601 size_t decoded_length_per_channel = decoded_length / num_channels;
1602 if (decoded_length_per_channel < required_samples) {
1603 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001604 borrowed_samples_per_channel = static_cast<int>(required_samples -
1605 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001606 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1607 decoded_buffer,
1608 sizeof(int16_t) * decoded_length);
1609 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1610 decoded_buffer);
1611 decoded_length = required_samples * num_channels;
1612 }
1613
Peter Kastingdce40cf2015-08-24 14:52:23 -07001614 size_t samples_removed;
Henrik Lundincf808d22015-05-27 14:33:29 +02001615 Accelerate::ReturnCodes return_code =
1616 accelerate_->Process(decoded_buffer, decoded_length, fast_accelerate,
1617 algorithm_buffer_.get(), &samples_removed);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001618 stats_.AcceleratedSamples(samples_removed);
1619 switch (return_code) {
1620 case Accelerate::kSuccess:
1621 last_mode_ = kModeAccelerateSuccess;
1622 break;
1623 case Accelerate::kSuccessLowEnergy:
1624 last_mode_ = kModeAccelerateLowEnergy;
1625 break;
1626 case Accelerate::kNoStretch:
1627 last_mode_ = kModeAccelerateFail;
1628 break;
1629 case Accelerate::kError:
1630 // TODO(hlundin): Map to kModeError instead?
1631 last_mode_ = kModeAccelerateFail;
1632 return kAccelerateError;
1633 }
1634
1635 if (borrowed_samples_per_channel > 0) {
1636 // Copy borrowed samples back to the |sync_buffer_|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001637 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001638 if (length < borrowed_samples_per_channel) {
1639 // This destroys the beginning of the buffer, but will not cause any
1640 // problems.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001641 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001642 sync_buffer_->Size() -
1643 borrowed_samples_per_channel);
1644 sync_buffer_->PushFrontZeros(borrowed_samples_per_channel - length);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001645 algorithm_buffer_->PopFront(length);
1646 assert(algorithm_buffer_->Empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001647 } else {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001648 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001649 borrowed_samples_per_channel,
1650 sync_buffer_->Size() -
1651 borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001652 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001653 }
1654 }
1655
1656 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1657 if (speech_type == AudioDecoder::kComfortNoise) {
1658 last_mode_ = kModeCodecInternalCng;
1659 }
1660 if (!play_dtmf) {
1661 dtmf_tone_generator_->Reset();
1662 }
1663 expand_->Reset();
1664 return 0;
1665}
1666
1667int NetEqImpl::DoPreemptiveExpand(int16_t* decoded_buffer,
1668 size_t decoded_length,
1669 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001670 bool play_dtmf) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001671 const size_t required_samples =
1672 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001673 size_t num_channels = algorithm_buffer_->Channels();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001674 size_t borrowed_samples_per_channel = 0;
1675 size_t old_borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001676 size_t decoded_length_per_channel = decoded_length / num_channels;
1677 if (decoded_length_per_channel < required_samples) {
1678 // Must move data from the |sync_buffer_| in order to get 30 ms.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001679 borrowed_samples_per_channel =
1680 required_samples - decoded_length_per_channel;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001681 // Calculate how many of these were already played out.
Peter Kastingf045e4d2015-06-10 21:15:38 -07001682 old_borrowed_samples_per_channel =
Peter Kastingdce40cf2015-08-24 14:52:23 -07001683 (borrowed_samples_per_channel > sync_buffer_->FutureLength()) ?
1684 (borrowed_samples_per_channel - sync_buffer_->FutureLength()) : 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001685 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1686 decoded_buffer,
1687 sizeof(int16_t) * decoded_length);
1688 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1689 decoded_buffer);
1690 decoded_length = required_samples * num_channels;
1691 }
1692
Peter Kastingdce40cf2015-08-24 14:52:23 -07001693 size_t samples_added;
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001694 PreemptiveExpand::ReturnCodes return_code = preemptive_expand_->Process(
Peter Kastingdce40cf2015-08-24 14:52:23 -07001695 decoded_buffer, decoded_length,
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001696 old_borrowed_samples_per_channel,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001697 algorithm_buffer_.get(), &samples_added);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001698 stats_.PreemptiveExpandedSamples(samples_added);
1699 switch (return_code) {
1700 case PreemptiveExpand::kSuccess:
1701 last_mode_ = kModePreemptiveExpandSuccess;
1702 break;
1703 case PreemptiveExpand::kSuccessLowEnergy:
1704 last_mode_ = kModePreemptiveExpandLowEnergy;
1705 break;
1706 case PreemptiveExpand::kNoStretch:
1707 last_mode_ = kModePreemptiveExpandFail;
1708 break;
1709 case PreemptiveExpand::kError:
1710 // TODO(hlundin): Map to kModeError instead?
1711 last_mode_ = kModePreemptiveExpandFail;
1712 return kPreemptiveExpandError;
1713 }
1714
1715 if (borrowed_samples_per_channel > 0) {
1716 // Copy borrowed samples back to the |sync_buffer_|.
1717 sync_buffer_->ReplaceAtIndex(
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001718 *algorithm_buffer_, borrowed_samples_per_channel,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001719 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001720 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001721 }
1722
1723 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1724 if (speech_type == AudioDecoder::kComfortNoise) {
1725 last_mode_ = kModeCodecInternalCng;
1726 }
1727 if (!play_dtmf) {
1728 dtmf_tone_generator_->Reset();
1729 }
1730 expand_->Reset();
1731 return 0;
1732}
1733
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001734int NetEqImpl::DoRfc3389Cng(PacketList* packet_list, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001735 if (!packet_list->empty()) {
1736 // Must have exactly one SID frame at this point.
1737 assert(packet_list->size() == 1);
1738 Packet* packet = packet_list->front();
1739 packet_list->pop_front();
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001740 if (!decoder_database_->IsComfortNoise(packet->header.payloadType)) {
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001741 LOG(LS_ERROR) << "Trying to decode non-CNG payload as CNG.";
1742 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001743 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001744 // UpdateParameters() deletes |packet|.
1745 if (comfort_noise_->UpdateParameters(packet) ==
1746 ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001747 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001748 return -comfort_noise_->internal_error_code();
1749 }
1750 }
1751 int cn_return = comfort_noise_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001752 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001753 expand_->Reset();
1754 last_mode_ = kModeRfc3389Cng;
1755 if (!play_dtmf) {
1756 dtmf_tone_generator_->Reset();
1757 }
1758 if (cn_return == ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001759 decoder_error_code_ = comfort_noise_->internal_error_code();
1760 return kComfortNoiseErrorCode;
1761 } else if (cn_return == ComfortNoise::kUnknownPayloadType) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001762 return kUnknownRtpPayloadType;
1763 }
1764 return 0;
1765}
1766
minyuel6d92bf52015-09-23 15:20:39 +02001767void NetEqImpl::DoCodecInternalCng(const int16_t* decoded_buffer,
1768 size_t decoded_length) {
1769 RTC_DCHECK(normal_.get());
1770 RTC_DCHECK(mute_factor_array_.get());
1771 normal_->Process(decoded_buffer, decoded_length, last_mode_,
1772 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001773 last_mode_ = kModeCodecInternalCng;
1774 expand_->Reset();
1775}
1776
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001777int NetEqImpl::DoDtmf(const DtmfEvent& dtmf_event, bool* play_dtmf) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001778 // This block of the code and the block further down, handling |dtmf_switch|
1779 // are commented out. Otherwise playing out-of-band DTMF would fail in VoE
1780 // test, DtmfTest.ManualSuccessfullySendsOutOfBandTelephoneEvents. This is
1781 // equivalent to |dtmf_switch| always be false.
1782 //
1783 // See http://webrtc-codereview.appspot.com/1195004/ for discussion
1784 // On this issue. This change might cause some glitches at the point of
1785 // switch from audio to DTMF. Issue 1545 is filed to track this.
1786 //
1787 // bool dtmf_switch = false;
1788 // if ((last_mode_ != kModeDtmf) && dtmf_tone_generator_->initialized()) {
1789 // // Special case; see below.
1790 // // We must catch this before calling Generate, since |initialized| is
1791 // // modified in that call.
1792 // dtmf_switch = true;
1793 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001794
1795 int dtmf_return_value = 0;
1796 if (!dtmf_tone_generator_->initialized()) {
1797 // Initialize if not already done.
1798 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1799 dtmf_event.volume);
1800 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001801
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001802 if (dtmf_return_value == 0) {
1803 // Generate DTMF signal.
1804 dtmf_return_value = dtmf_tone_generator_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001805 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001806 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001807
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001808 if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001809 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001810 return dtmf_return_value;
1811 }
1812
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001813 // if (dtmf_switch) {
1814 // // This is the special case where the previous operation was DTMF
1815 // // overdub, but the current instruction is "regular" DTMF. We must make
1816 // // sure that the DTMF does not have any discontinuities. The first DTMF
1817 // // sample that we generate now must be played out immediately, therefore
1818 // // it must be copied to the speech buffer.
1819 // // TODO(hlundin): This code seems incorrect. (Legacy.) Write test and
1820 // // verify correct operation.
1821 // assert(false);
1822 // // Must generate enough data to replace all of the |sync_buffer_|
1823 // // "future".
1824 // int required_length = sync_buffer_->FutureLength();
1825 // assert(dtmf_tone_generator_->initialized());
1826 // dtmf_return_value = dtmf_tone_generator_->Generate(required_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001827 // algorithm_buffer_);
1828 // assert((size_t) required_length == algorithm_buffer_->Size());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001829 // if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001830 // algorithm_buffer_->Zeros(output_size_samples_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001831 // return dtmf_return_value;
1832 // }
1833 //
1834 // // Overwrite the "future" part of the speech buffer with the new DTMF
1835 // // data.
1836 // // TODO(hlundin): It seems that this overwriting has gone lost.
1837 // // Not adapted for multi-channel yet.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001838 // assert(algorithm_buffer_->Channels() == 1);
1839 // if (algorithm_buffer_->Channels() != 1) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001840 // LOG(LS_WARNING) << "DTMF not supported for more than one channel";
1841 // return kStereoNotSupported;
1842 // }
1843 // // Shuffle the remaining data to the beginning of algorithm buffer.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001844 // algorithm_buffer_->PopFront(sync_buffer_->FutureLength());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001845 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001846
Peter Kastingb7e50542015-06-11 12:55:50 -07001847 sync_buffer_->IncreaseEndTimestamp(
1848 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001849 expand_->Reset();
1850 last_mode_ = kModeDtmf;
1851
1852 // Set to false because the DTMF is already in the algorithm buffer.
1853 *play_dtmf = false;
1854 return 0;
1855}
1856
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001857void NetEqImpl::DoAlternativePlc(bool increase_timestamp) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001858 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001859 size_t length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001860 if (decoder && decoder->HasDecodePlc()) {
1861 // Use the decoder's packet-loss concealment.
1862 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1863 int16_t decoded_buffer[kMaxFrameSize];
1864 length = decoder->DecodePlc(1, decoded_buffer);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001865 if (length > 0)
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001866 algorithm_buffer_->PushBackInterleaved(decoded_buffer, length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001867 } else {
1868 // Do simple zero-stuffing.
1869 length = output_size_samples_;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001870 algorithm_buffer_->Zeros(length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001871 // By not advancing the timestamp, NetEq inserts samples.
1872 stats_.AddZeros(length);
1873 }
1874 if (increase_timestamp) {
Peter Kastingb7e50542015-06-11 12:55:50 -07001875 sync_buffer_->IncreaseEndTimestamp(static_cast<uint32_t>(length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001876 }
1877 expand_->Reset();
1878}
1879
1880int NetEqImpl::DtmfOverdub(const DtmfEvent& dtmf_event, size_t num_channels,
1881 int16_t* output) const {
1882 size_t out_index = 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001883 size_t overdub_length = output_size_samples_; // Default value.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001884
1885 if (sync_buffer_->dtmf_index() > sync_buffer_->next_index()) {
1886 // Special operation for transition from "DTMF only" to "DTMF overdub".
1887 out_index = std::min(
1888 sync_buffer_->dtmf_index() - sync_buffer_->next_index(),
Peter Kastingdce40cf2015-08-24 14:52:23 -07001889 output_size_samples_);
1890 overdub_length = output_size_samples_ - out_index;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001891 }
1892
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001893 AudioMultiVector dtmf_output(num_channels);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001894 int dtmf_return_value = 0;
1895 if (!dtmf_tone_generator_->initialized()) {
1896 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1897 dtmf_event.volume);
1898 }
1899 if (dtmf_return_value == 0) {
1900 dtmf_return_value = dtmf_tone_generator_->Generate(overdub_length,
1901 &dtmf_output);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001902 assert(overdub_length == dtmf_output.Size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001903 }
1904 dtmf_output.ReadInterleaved(overdub_length, &output[out_index]);
1905 return dtmf_return_value < 0 ? dtmf_return_value : 0;
1906}
1907
Peter Kastingdce40cf2015-08-24 14:52:23 -07001908int NetEqImpl::ExtractPackets(size_t required_samples,
1909 PacketList* packet_list) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001910 bool first_packet = true;
1911 uint8_t prev_payload_type = 0;
1912 uint32_t prev_timestamp = 0;
1913 uint16_t prev_sequence_number = 0;
1914 bool next_packet_available = false;
1915
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001916 const RTPHeader* header = packet_buffer_->NextRtpHeader();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001917 assert(header);
1918 if (!header) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001919 LOG(LS_ERROR) << "Packet buffer unexpectedly empty.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001920 return -1;
1921 }
turaj@webrtc.org7df97062013-08-02 18:07:13 +00001922 uint32_t first_timestamp = header->timestamp;
ossu61a208b2016-09-20 01:38:00 -07001923 size_t extracted_samples = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001924
1925 // Packet extraction loop.
1926 do {
1927 timestamp_ = header->timestamp;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001928 size_t discard_count = 0;
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001929 Packet* packet = packet_buffer_->GetNextPacket(&discard_count);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001930 // |header| may be invalid after the |packet_buffer_| operation.
1931 header = NULL;
1932 if (!packet) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001933 LOG(LS_ERROR) << "Should always be able to extract a packet here";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001934 assert(false); // Should always be able to extract a packet here.
1935 return -1;
1936 }
1937 stats_.PacketsDiscarded(discard_count);
henrik.lundin84f8cd62016-04-26 07:45:16 -07001938 stats_.StoreWaitingTime(packet->waiting_time->ElapsedMs());
ossu61a208b2016-09-20 01:38:00 -07001939 RTC_DCHECK(!packet->empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001940 packet_list->push_back(packet); // Store packet in list.
1941
1942 if (first_packet) {
1943 first_packet = false;
henrik.lundin48ed9302015-10-29 05:36:24 -07001944 if (nack_enabled_) {
1945 RTC_DCHECK(nack_);
1946 // TODO(henrik.lundin): Should we update this for all decoded packets?
1947 nack_->UpdateLastDecodedPacket(packet->header.sequenceNumber,
1948 packet->header.timestamp);
1949 }
1950 prev_sequence_number = packet->header.sequenceNumber;
1951 prev_timestamp = packet->header.timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001952 prev_payload_type = packet->header.payloadType;
1953 }
1954
1955 // Store number of extracted samples.
ossu61a208b2016-09-20 01:38:00 -07001956 size_t packet_duration = 0;
1957 if (packet->frame) {
1958 packet_duration = packet->frame->Duration();
1959 // TODO(ossu): Is this the correct way to track samples decoded from a
1960 // redundant packet?
1961 if (packet_duration > 0 && !packet->primary) {
1962 stats_.SecondaryDecodedSamples(rtc::checked_cast<int>(packet_duration));
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001963 }
ossu97ba30e2016-04-25 07:55:58 -07001964 } else if (!decoder_database_->IsComfortNoise(packet->header.payloadType)) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001965 LOG(LS_WARNING) << "Unknown payload type "
1966 << static_cast<int>(packet->header.payloadType);
ossu61a208b2016-09-20 01:38:00 -07001967 RTC_NOTREACHED();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001968 }
ossu61a208b2016-09-20 01:38:00 -07001969
1970 if (packet_duration == 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001971 // Decoder did not return a packet duration. Assume that the packet
1972 // contains the same number of samples as the previous one.
ossu61a208b2016-09-20 01:38:00 -07001973 packet_duration = decoder_frame_length_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001974 }
1975 extracted_samples = packet->header.timestamp - first_timestamp +
1976 packet_duration;
1977
1978 // Check what packet is available next.
1979 header = packet_buffer_->NextRtpHeader();
1980 next_packet_available = false;
1981 if (header && prev_payload_type == header->payloadType) {
1982 int16_t seq_no_diff = header->sequenceNumber - prev_sequence_number;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001983 size_t ts_diff = header->timestamp - prev_timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001984 if (seq_no_diff == 1 ||
1985 (seq_no_diff == 0 && ts_diff == decoder_frame_length_)) {
1986 // The next sequence number is available, or the next part of a packet
1987 // that was split into pieces upon insertion.
1988 next_packet_available = true;
1989 }
1990 prev_sequence_number = header->sequenceNumber;
1991 }
ossu61a208b2016-09-20 01:38:00 -07001992 } while (extracted_samples < required_samples && next_packet_available);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001993
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00001994 if (extracted_samples > 0) {
1995 // Delete old packets only when we are going to decode something. Otherwise,
1996 // we could end up in the situation where we never decode anything, since
1997 // all incoming packets are considered too old but the buffer will also
1998 // never be flooded and flushed.
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001999 packet_buffer_->DiscardAllOldPackets(timestamp_);
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00002000 }
2001
ossu61a208b2016-09-20 01:38:00 -07002002 return rtc::checked_cast<int>(extracted_samples);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002003}
2004
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002005void NetEqImpl::UpdatePlcComponents(int fs_hz, size_t channels) {
2006 // Delete objects and create new ones.
2007 expand_.reset(expand_factory_->Create(background_noise_.get(),
2008 sync_buffer_.get(), &random_vector_,
Henrik Lundinbef77e22015-08-18 14:58:09 +02002009 &stats_, fs_hz, channels));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002010 merge_.reset(new Merge(fs_hz, channels, expand_.get(), sync_buffer_.get()));
2011}
2012
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002013void NetEqImpl::SetSampleRateAndChannels(int fs_hz, size_t channels) {
Henrik Lundind67a2192015-08-03 12:54:37 +02002014 LOG(LS_VERBOSE) << "SetSampleRateAndChannels " << fs_hz << " " << channels;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002015 // TODO(hlundin): Change to an enumerator and skip assert.
2016 assert(fs_hz == 8000 || fs_hz == 16000 || fs_hz == 32000 || fs_hz == 48000);
2017 assert(channels > 0);
2018
2019 fs_hz_ = fs_hz;
2020 fs_mult_ = fs_hz / 8000;
Peter Kastingdce40cf2015-08-24 14:52:23 -07002021 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002022 decoder_frame_length_ = 3 * output_size_samples_; // Initialize to 30ms.
2023
2024 last_mode_ = kModeNormal;
2025
2026 // Create a new array of mute factors and set all to 1.
2027 mute_factor_array_.reset(new int16_t[channels]);
2028 for (size_t i = 0; i < channels; ++i) {
2029 mute_factor_array_[i] = 16384; // 1.0 in Q14.
2030 }
2031
ossu97ba30e2016-04-25 07:55:58 -07002032 ComfortNoiseDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02002033 if (cng_decoder)
2034 cng_decoder->Reset();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002035
2036 // Reinit post-decode VAD with new sample rate.
2037 assert(vad_.get()); // Cannot be NULL here.
2038 vad_->Init();
2039
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002040 // Delete algorithm buffer and create a new one.
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00002041 algorithm_buffer_.reset(new AudioMultiVector(channels));
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002042
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002043 // Delete sync buffer and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002044 sync_buffer_.reset(new SyncBuffer(channels, kSyncBufferSize * fs_mult_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002045
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00002046 // Delete BackgroundNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002047 background_noise_.reset(new BackgroundNoise(channels));
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00002048 background_noise_->set_mode(background_noise_mode_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002049
2050 // Reset random vector.
2051 random_vector_.Reset();
2052
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002053 UpdatePlcComponents(fs_hz, channels);
2054
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002055 // Move index so that we create a small set of future samples (all 0).
2056 sync_buffer_->set_next_index(sync_buffer_->next_index() -
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002057 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002058
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002059 normal_.reset(new Normal(fs_hz, decoder_database_.get(), *background_noise_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002060 expand_.get()));
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +00002061 accelerate_.reset(
2062 accelerate_factory_->Create(fs_hz, channels, *background_noise_));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002063 preemptive_expand_.reset(preemptive_expand_factory_->Create(
Peter Kastingdce40cf2015-08-24 14:52:23 -07002064 fs_hz, channels, *background_noise_, expand_->overlap_length()));
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002065
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002066 // Delete ComfortNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002067 comfort_noise_.reset(new ComfortNoise(fs_hz, decoder_database_.get(),
2068 sync_buffer_.get()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002069
2070 // Verify that |decoded_buffer_| is long enough.
2071 if (decoded_buffer_length_ < kMaxFrameSize * channels) {
2072 // Reallocate to larger size.
2073 decoded_buffer_length_ = kMaxFrameSize * channels;
2074 decoded_buffer_.reset(new int16_t[decoded_buffer_length_]);
2075 }
2076
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002077 // Create DecisionLogic if it is not created yet, then communicate new sample
2078 // rate and output size to DecisionLogic object.
2079 if (!decision_logic_.get()) {
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002080 CreateDecisionLogic();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002081 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002082 decision_logic_->SetSampleRate(fs_hz_, output_size_samples_);
2083}
2084
henrik.lundin55480f52016-03-08 02:37:57 -08002085NetEqImpl::OutputType NetEqImpl::LastOutputType() {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002086 assert(vad_.get());
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002087 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002088 if (last_mode_ == kModeCodecInternalCng || last_mode_ == kModeRfc3389Cng) {
henrik.lundin55480f52016-03-08 02:37:57 -08002089 return OutputType::kCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002090 } else if (last_mode_ == kModeExpand && expand_->MuteFactor(0) == 0) {
2091 // Expand mode has faded down to background noise only (very long expand).
henrik.lundin55480f52016-03-08 02:37:57 -08002092 return OutputType::kPLCCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002093 } else if (last_mode_ == kModeExpand) {
henrik.lundin55480f52016-03-08 02:37:57 -08002094 return OutputType::kPLC;
wu@webrtc.org24301a62013-12-13 19:17:43 +00002095 } else if (vad_->running() && !vad_->active_speech()) {
henrik.lundin55480f52016-03-08 02:37:57 -08002096 return OutputType::kVadPassive;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002097 } else {
henrik.lundin55480f52016-03-08 02:37:57 -08002098 return OutputType::kNormalSpeech;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002099 }
2100}
2101
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002102void NetEqImpl::CreateDecisionLogic() {
Henrik Lundin47b17dc2016-05-10 10:20:59 +02002103 decision_logic_.reset(DecisionLogic::Create(
2104 fs_hz_, output_size_samples_, playout_mode_, decoder_database_.get(),
2105 *packet_buffer_.get(), delay_manager_.get(), buffer_level_filter_.get(),
2106 tick_timer_.get()));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002107}
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002108} // namespace webrtc