blob: 27d47c104b6c6b437363245045e1127a60ee4d84 [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
kwiberg6f0f6162016-09-20 03:07:46 -0700434rtc::Optional<CodecInst> NetEqImpl::GetDecoder(int payload_type) const {
435 rtc::CritScope lock(&crit_sect_);
436 const DecoderDatabase::DecoderInfo* di =
437 decoder_database_->GetDecoderInfo(payload_type);
438 if (!di) {
439 return rtc::Optional<CodecInst>();
440 }
441
442 // Create a CodecInst with some fields set. The remaining fields are zeroed,
443 // but we tell MSan to consider them uninitialized.
444 CodecInst ci = {0};
445 rtc::MsanMarkUninitialized(rtc::MakeArrayView(&ci, 1));
446 ci.pltype = payload_type;
447 std::strncpy(ci.plname, di->name.c_str(), sizeof(ci.plname));
448 ci.plname[sizeof(ci.plname) - 1] = '\0';
449 ci.plfreq = di->IsRed() || di->IsDtmf() ? 8000 : di->SampleRateHz();
450 AudioDecoder* const decoder = di->GetDecoder();
451 ci.channels = decoder ? decoder->Channels() : 1;
452 return rtc::Optional<CodecInst>(ci);
453}
454
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200455int NetEqImpl::SetTargetNumberOfChannels() {
456 return kNotImplemented;
457}
458
459int NetEqImpl::SetTargetSampleRate() {
460 return kNotImplemented;
461}
462
henrik.lundin@webrtc.orgb0f4b3d2014-11-04 08:53:10 +0000463int NetEqImpl::LastError() const {
Tommi9090e0b2016-01-20 13:39:36 +0100464 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000465 return error_code_;
466}
467
468int NetEqImpl::LastDecoderError() {
Tommi9090e0b2016-01-20 13:39:36 +0100469 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000470 return decoder_error_code_;
471}
472
473void NetEqImpl::FlushBuffers() {
Tommi9090e0b2016-01-20 13:39:36 +0100474 rtc::CritScope lock(&crit_sect_);
Henrik Lundind67a2192015-08-03 12:54:37 +0200475 LOG(LS_VERBOSE) << "FlushBuffers";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000476 packet_buffer_->Flush();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000477 assert(sync_buffer_.get());
478 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000479 sync_buffer_->Flush();
480 sync_buffer_->set_next_index(sync_buffer_->next_index() -
481 expand_->overlap_length());
482 // Set to wait for new codec.
483 first_packet_ = true;
484}
485
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000486void NetEqImpl::PacketBufferStatistics(int* current_num_packets,
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000487 int* max_num_packets) const {
Tommi9090e0b2016-01-20 13:39:36 +0100488 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000489 packet_buffer_->BufferStat(current_num_packets, max_num_packets);
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000490}
491
henrik.lundin48ed9302015-10-29 05:36:24 -0700492void NetEqImpl::EnableNack(size_t max_nack_list_size) {
Tommi9090e0b2016-01-20 13:39:36 +0100493 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700494 if (!nack_enabled_) {
495 const int kNackThresholdPackets = 2;
henrik.lundin91951862016-06-08 06:43:41 -0700496 nack_.reset(NackTracker::Create(kNackThresholdPackets));
henrik.lundin48ed9302015-10-29 05:36:24 -0700497 nack_enabled_ = true;
498 nack_->UpdateSampleRate(fs_hz_);
499 }
500 nack_->SetMaxNackListSize(max_nack_list_size);
501}
502
503void NetEqImpl::DisableNack() {
Tommi9090e0b2016-01-20 13:39:36 +0100504 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700505 nack_.reset();
506 nack_enabled_ = false;
507}
508
509std::vector<uint16_t> NetEqImpl::GetNackList(int64_t round_trip_time_ms) const {
Tommi9090e0b2016-01-20 13:39:36 +0100510 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700511 if (!nack_enabled_) {
512 return std::vector<uint16_t>();
513 }
514 RTC_DCHECK(nack_.get());
515 return nack_->GetNackList(round_trip_time_ms);
minyue@webrtc.orgd7301772013-08-29 00:58:14 +0000516}
517
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000518const SyncBuffer* NetEqImpl::sync_buffer_for_test() const {
Tommi9090e0b2016-01-20 13:39:36 +0100519 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000520 return sync_buffer_.get();
521}
522
minyue5bd33972016-05-02 04:46:11 -0700523Operations NetEqImpl::last_operation_for_test() const {
524 rtc::CritScope lock(&crit_sect_);
525 return last_operation_;
526}
527
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000528// Methods below this line are private.
529
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000530int NetEqImpl::InsertPacketInternal(const WebRtcRTPHeader& rtp_header,
kwibergee2bac22015-11-11 10:34:00 -0800531 rtc::ArrayView<const uint8_t> payload,
ossu17e3fa12016-09-08 04:52:55 -0700532 uint32_t receive_timestamp) {
kwibergee2bac22015-11-11 10:34:00 -0800533 if (payload.empty()) {
534 LOG_F(LS_ERROR) << "payload is empty";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000535 return kInvalidPointer;
536 }
ossu17e3fa12016-09-08 04:52:55 -0700537
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000538 PacketList packet_list;
539 RTPHeader main_header;
540 {
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000541 // Convert to Packet.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000542 // Create |packet| within this separate scope, since it should not be used
543 // directly once it's been inserted in the packet list. This way, |packet|
544 // is not defined outside of this block.
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000545 Packet* packet = new Packet;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000546 packet->header.markerBit = false;
547 packet->header.payloadType = rtp_header.header.payloadType;
548 packet->header.sequenceNumber = rtp_header.header.sequenceNumber;
549 packet->header.timestamp = rtp_header.header.timestamp;
550 packet->header.ssrc = rtp_header.header.ssrc;
551 packet->header.numCSRCs = 0;
ossudc431ce2016-08-31 08:51:13 -0700552 packet->payload.SetData(payload.data(), payload.size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000553 packet->primary = true;
henrik.lundin84f8cd62016-04-26 07:45:16 -0700554 // Waiting time will be set upon inserting the packet in the buffer.
555 RTC_DCHECK(!packet->waiting_time);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000556 // Insert packet in a packet list.
557 packet_list.push_back(packet);
558 // Save main payloads header for later.
559 memcpy(&main_header, &packet->header, sizeof(main_header));
560 }
561
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000562 bool update_sample_rate_and_channels = false;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000563 // Reinitialize NetEq if it's needed (changed SSRC or first call).
564 if ((main_header.ssrc != ssrc_) || first_packet_) {
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000565 // Note: |first_packet_| will be cleared further down in this method, once
566 // the packet has been successfully inserted into the packet buffer.
567
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000568 rtcp_.Init(main_header.sequenceNumber);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000569
570 // Flush the packet buffer and DTMF buffer.
571 packet_buffer_->Flush();
572 dtmf_buffer_->Flush();
573
574 // Store new SSRC.
575 ssrc_ = main_header.ssrc;
576
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000577 // Update audio buffer timestamp.
578 sync_buffer_->IncreaseEndTimestamp(main_header.timestamp - timestamp_);
579
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000580 // Update codecs.
581 timestamp_ = main_header.timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000582
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000583 // Reset timestamp scaling.
584 timestamp_scaler_->Reset();
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000585
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000586 // Trigger an update of sampling rate and the number of channels.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000587 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000588 }
589
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000590 // Update RTCP statistics, only for regular packets.
ossu17e3fa12016-09-08 04:52:55 -0700591 rtcp_.Update(main_header, receive_timestamp);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000592
593 // Check for RED payload type, and separate payloads into several packets.
594 if (decoder_database_->IsRed(main_header.payloadType)) {
595 if (payload_splitter_->SplitRed(&packet_list) != PayloadSplitter::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000596 PacketBuffer::DeleteAllPackets(&packet_list);
597 return kRedundancySplitError;
598 }
599 // Only accept a few RED payloads of the same type as the main data,
600 // DTMF events and CNG.
601 payload_splitter_->CheckRedPayloads(&packet_list, *decoder_database_);
602 // Update the stored main payload header since the main payload has now
603 // changed.
604 memcpy(&main_header, &packet_list.front()->header, sizeof(main_header));
605 }
606
607 // Check payload types.
608 if (decoder_database_->CheckPayloadTypes(packet_list) ==
609 DecoderDatabase::kDecoderNotFound) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000610 PacketBuffer::DeleteAllPackets(&packet_list);
611 return kUnknownRtpPayloadType;
612 }
613
614 // Scale timestamp to internal domain (only for some codecs).
615 timestamp_scaler_->ToInternal(&packet_list);
616
617 // Process DTMF payloads. Cycle through the list of packets, and pick out any
618 // DTMF payloads found.
619 PacketList::iterator it = packet_list.begin();
620 while (it != packet_list.end()) {
621 Packet* current_packet = (*it);
622 assert(current_packet);
ossudc431ce2016-08-31 08:51:13 -0700623 assert(!current_packet->payload.empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000624 if (decoder_database_->IsDtmf(current_packet->header.payloadType)) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000625 DtmfEvent event;
ossudc431ce2016-08-31 08:51:13 -0700626 int ret = DtmfBuffer::ParseEvent(current_packet->header.timestamp,
627 current_packet->payload.data(),
628 current_packet->payload.size(), &event);
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000629 if (ret != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000630 PacketBuffer::DeleteAllPackets(&packet_list);
631 return kDtmfParsingError;
632 }
633 if (dtmf_buffer_->InsertEvent(event) != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000634 PacketBuffer::DeleteAllPackets(&packet_list);
635 return kDtmfInsertError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000636 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000637 delete current_packet;
638 it = packet_list.erase(it);
639 } else {
640 ++it;
641 }
642 }
643
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000644 // Check for FEC in packets, and separate payloads into several packets.
645 int ret = payload_splitter_->SplitFec(&packet_list, decoder_database_.get());
646 if (ret != PayloadSplitter::kOK) {
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000647 PacketBuffer::DeleteAllPackets(&packet_list);
648 switch (ret) {
649 case PayloadSplitter::kUnknownPayloadType:
650 return kUnknownRtpPayloadType;
651 default:
652 return kOtherError;
653 }
654 }
655
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000656 // Split payloads into smaller chunks. This also verifies that all payloads
ossu17e3fa12016-09-08 04:52:55 -0700657 // are of a known payload type.
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +0000658 ret = payload_splitter_->SplitAudio(&packet_list, *decoder_database_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000659 if (ret != PayloadSplitter::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000660 PacketBuffer::DeleteAllPackets(&packet_list);
661 switch (ret) {
662 case PayloadSplitter::kUnknownPayloadType:
663 return kUnknownRtpPayloadType;
664 case PayloadSplitter::kFrameSplitError:
665 return kFrameSplitError;
666 default:
667 return kOtherError;
668 }
669 }
670
ossu17e3fa12016-09-08 04:52:55 -0700671 // Update bandwidth estimate, if the packet is not comfort noise.
672 if (!packet_list.empty() &&
ossu97ba30e2016-04-25 07:55:58 -0700673 !decoder_database_->IsComfortNoise(main_header.payloadType)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000674 // The list can be empty here if we got nothing but DTMF payloads.
675 AudioDecoder* decoder =
676 decoder_database_->GetDecoder(main_header.payloadType);
677 assert(decoder); // Should always get a valid object, since we have
ossu97ba30e2016-04-25 07:55:58 -0700678 // already checked that the payload types are known.
ossudc431ce2016-08-31 08:51:13 -0700679 decoder->IncomingPacket(packet_list.front()->payload.data(),
680 packet_list.front()->payload.size(),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000681 packet_list.front()->header.sequenceNumber,
682 packet_list.front()->header.timestamp,
683 receive_timestamp);
684 }
685
ossu61a208b2016-09-20 01:38:00 -0700686 PacketList parsed_packet_list;
687 while (!packet_list.empty()) {
688 std::unique_ptr<Packet> packet(packet_list.front());
689 packet_list.pop_front();
690 const DecoderDatabase::DecoderInfo* info =
691 decoder_database_->GetDecoderInfo(packet->header.payloadType);
692 if (!info) {
693 LOG(LS_WARNING) << "SplitAudio unknown payload type";
694 return kUnknownRtpPayloadType;
695 }
696
697 if (info->IsComfortNoise()) {
698 // Carry comfort noise packets along.
699 parsed_packet_list.push_back(packet.release());
700 } else {
701 std::vector<AudioDecoder::ParseResult> results =
702 info->GetDecoder()->ParsePayload(std::move(packet->payload),
703 packet->header.timestamp,
704 packet->primary);
705 const RTPHeader& original_header = packet->header;
706 for (auto& result : results) {
707 RTC_DCHECK(result.frame);
708 // Reuse the packet if possible
709 if (!packet) {
710 packet.reset(new Packet);
711 packet->header = original_header;
712 }
713 packet->header.timestamp = result.timestamp;
714 // TODO(ossu): Move from primary to some sort of priority level.
715 packet->primary = result.primary;
716 packet->frame = std::move(result.frame);
717 parsed_packet_list.push_back(packet.release());
718 }
719 }
720 }
721
henrik.lundin48ed9302015-10-29 05:36:24 -0700722 if (nack_enabled_) {
723 RTC_DCHECK(nack_);
724 if (update_sample_rate_and_channels) {
725 nack_->Reset();
726 }
ossu61a208b2016-09-20 01:38:00 -0700727 nack_->UpdateLastReceivedPacket(
728 parsed_packet_list.front()->header.sequenceNumber,
729 parsed_packet_list.front()->header.timestamp);
henrik.lundin48ed9302015-10-29 05:36:24 -0700730 }
731
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000732 // Insert packets in buffer.
henrik.lundin116c84e2015-08-27 13:14:48 -0700733 const size_t buffer_length_before_insert =
734 packet_buffer_->NumPacketsInBuffer();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000735 ret = packet_buffer_->InsertPacketList(
ossu61a208b2016-09-20 01:38:00 -0700736 &parsed_packet_list, *decoder_database_, &current_rtp_payload_type_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000737 &current_cng_rtp_payload_type_);
738 if (ret == PacketBuffer::kFlushed) {
739 // Reset DSP timestamp etc. if packet buffer flushed.
740 new_codec_ = true;
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000741 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000742 } else if (ret != PacketBuffer::kOK) {
ossu61a208b2016-09-20 01:38:00 -0700743 PacketBuffer::DeleteAllPackets(&parsed_packet_list);
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000744 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000745 }
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000746
747 if (first_packet_) {
748 first_packet_ = false;
749 // Update the codec on the next GetAudio call.
750 new_codec_ = true;
751 }
752
henrik.lundinda8bbf62016-08-31 03:14:11 -0700753 if (current_rtp_payload_type_) {
754 RTC_DCHECK(decoder_database_->GetDecoderInfo(*current_rtp_payload_type_))
755 << "Payload type " << static_cast<int>(*current_rtp_payload_type_)
756 << " is unknown where it shouldn't be";
757 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000758
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000759 if (update_sample_rate_and_channels && !packet_buffer_->Empty()) {
760 // We do not use |current_rtp_payload_type_| to |set payload_type|, but
761 // get the next RTP header from |packet_buffer_| to obtain the payload type.
762 // The reason for it is the following corner case. If NetEq receives a
763 // CNG packet with a sample rate different than the current CNG then it
764 // flushes its buffer, assuming send codec must have been changed. However,
765 // payload type of the hypothetically new send codec is not known.
766 const RTPHeader* rtp_header = packet_buffer_->NextRtpHeader();
767 assert(rtp_header);
768 int payload_type = rtp_header->payloadType;
ossu97ba30e2016-04-25 07:55:58 -0700769 size_t channels = 1;
770 if (!decoder_database_->IsComfortNoise(payload_type)) {
771 AudioDecoder* decoder = decoder_database_->GetDecoder(payload_type);
772 assert(decoder); // Payloads are already checked to be valid.
773 channels = decoder->Channels();
774 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000775 const DecoderDatabase::DecoderInfo* decoder_info =
776 decoder_database_->GetDecoderInfo(payload_type);
777 assert(decoder_info);
kwibergc0f2dcf2016-05-31 06:28:03 -0700778 if (decoder_info->SampleRateHz() != fs_hz_ ||
ossu97ba30e2016-04-25 07:55:58 -0700779 channels != algorithm_buffer_->Channels()) {
kwibergc0f2dcf2016-05-31 06:28:03 -0700780 SetSampleRateAndChannels(decoder_info->SampleRateHz(),
781 channels);
henrik.lundin48ed9302015-10-29 05:36:24 -0700782 }
783 if (nack_enabled_) {
784 RTC_DCHECK(nack_);
785 // Update the sample rate even if the rate is not new, because of Reset().
786 nack_->UpdateSampleRate(fs_hz_);
787 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000788 }
789
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000790 // TODO(hlundin): Move this code to DelayManager class.
791 const DecoderDatabase::DecoderInfo* dec_info =
792 decoder_database_->GetDecoderInfo(main_header.payloadType);
793 assert(dec_info); // Already checked that the payload type is known.
794 delay_manager_->LastDecoderType(dec_info->codec_type);
795 if (delay_manager_->last_pack_cng_or_dtmf() == 0) {
796 // Calculate the total speech length carried in each packet.
henrik.lundin116c84e2015-08-27 13:14:48 -0700797 const size_t buffer_length_after_insert =
798 packet_buffer_->NumPacketsInBuffer();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000799
henrik.lundin116c84e2015-08-27 13:14:48 -0700800 if (buffer_length_after_insert > buffer_length_before_insert) {
801 const size_t packet_length_samples =
802 (buffer_length_after_insert - buffer_length_before_insert) *
803 decoder_frame_length_;
804 if (packet_length_samples != decision_logic_->packet_length_samples()) {
805 decision_logic_->set_packet_length_samples(packet_length_samples);
806 delay_manager_->SetPacketAudioLength(
807 rtc::checked_cast<int>((1000 * packet_length_samples) / fs_hz_));
808 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000809 }
810
811 // Update statistics.
pbos@webrtc.org0946a562013-04-09 00:28:06 +0000812 if ((int32_t) (main_header.timestamp - timestamp_) >= 0 &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000813 !new_codec_) {
814 // Only update statistics if incoming packet is not older than last played
815 // out packet, and if new codec flag is not set.
816 delay_manager_->Update(main_header.sequenceNumber, main_header.timestamp,
817 fs_hz_);
818 }
819 } else if (delay_manager_->last_pack_cng_or_dtmf() == -1) {
820 // This is first "normal" packet after CNG or DTMF.
821 // Reset packet time counter and measure time until next packet,
822 // but don't update statistics.
823 delay_manager_->set_last_pack_cng_or_dtmf(0);
824 delay_manager_->ResetPacketIatCount();
825 }
826 return 0;
827}
828
henrik.lundin7a926812016-05-12 13:51:28 -0700829int NetEqImpl::GetAudioInternal(AudioFrame* audio_frame, bool* muted) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000830 PacketList packet_list;
831 DtmfEvent dtmf_event;
832 Operations operation;
833 bool play_dtmf;
henrik.lundin7a926812016-05-12 13:51:28 -0700834 *muted = false;
henrik.lundined497212016-04-25 10:11:38 -0700835 tick_timer_->Increment();
henrik.lundin60f6ce22016-05-10 03:52:04 -0700836 stats_.IncreaseCounter(output_size_samples_, fs_hz_);
henrik.lundin7a926812016-05-12 13:51:28 -0700837
838 // Check for muted state.
839 if (enable_muted_state_ && expand_->Muted() && packet_buffer_->Empty()) {
840 RTC_DCHECK_EQ(last_mode_, kModeExpand);
841 playout_timestamp_ += static_cast<uint32_t>(output_size_samples_);
842 audio_frame->sample_rate_hz_ = fs_hz_;
843 audio_frame->samples_per_channel_ = output_size_samples_;
844 audio_frame->timestamp_ =
845 first_packet_
846 ? 0
847 : timestamp_scaler_->ToExternal(playout_timestamp_) -
848 static_cast<uint32_t>(audio_frame->samples_per_channel_);
849 audio_frame->num_channels_ = sync_buffer_->Channels();
henrik.lundin612c25e2016-05-25 08:21:04 -0700850 stats_.ExpandedNoiseSamples(output_size_samples_);
henrik.lundin7a926812016-05-12 13:51:28 -0700851 *muted = true;
852 return 0;
853 }
854
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000855 int return_value = GetDecision(&operation, &packet_list, &dtmf_event,
856 &play_dtmf);
857 if (return_value != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000858 last_mode_ = kModeError;
859 return return_value;
860 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000861
862 AudioDecoder::SpeechType speech_type;
863 int length = 0;
864 int decode_return_value = Decode(&packet_list, &operation,
865 &length, &speech_type);
866
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000867 assert(vad_.get());
868 bool sid_frame_available =
869 (operation == kRfc3389Cng && !packet_list.empty());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700870 vad_->Update(decoded_buffer_.get(), static_cast<size_t>(length), speech_type,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000871 sid_frame_available, fs_hz_);
872
henrik.lundinb1fb72b2016-05-03 08:18:47 -0700873 if (sid_frame_available || speech_type == AudioDecoder::kComfortNoise) {
874 // Start a new stopwatch since we are decoding a new CNG packet.
875 generated_noise_stopwatch_ = tick_timer_->GetNewStopwatch();
876 }
877
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000878 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000879 switch (operation) {
880 case kNormal: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000881 DoNormal(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000882 break;
883 }
884 case kMerge: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000885 DoMerge(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000886 break;
887 }
888 case kExpand: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000889 return_value = DoExpand(play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000890 break;
891 }
Henrik Lundincf808d22015-05-27 14:33:29 +0200892 case kAccelerate:
893 case kFastAccelerate: {
894 const bool fast_accelerate =
895 enable_fast_accelerate_ && (operation == kFastAccelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000896 return_value = DoAccelerate(decoded_buffer_.get(), length, speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +0200897 play_dtmf, fast_accelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000898 break;
899 }
900 case kPreemptiveExpand: {
901 return_value = DoPreemptiveExpand(decoded_buffer_.get(), length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000902 speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000903 break;
904 }
905 case kRfc3389Cng:
906 case kRfc3389CngNoPacket: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000907 return_value = DoRfc3389Cng(&packet_list, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000908 break;
909 }
910 case kCodecInternalCng: {
911 // This handles the case when there is no transmission and the decoder
912 // should produce internal comfort noise.
913 // TODO(hlundin): Write test for codec-internal CNG.
minyuel6d92bf52015-09-23 15:20:39 +0200914 DoCodecInternalCng(decoded_buffer_.get(), length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000915 break;
916 }
917 case kDtmf: {
918 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000919 return_value = DoDtmf(dtmf_event, &play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000920 break;
921 }
922 case kAlternativePlc: {
923 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000924 DoAlternativePlc(false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000925 break;
926 }
927 case kAlternativePlcIncreaseTimestamp: {
928 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000929 DoAlternativePlc(true);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000930 break;
931 }
932 case kAudioRepetitionIncreaseTimestamp: {
933 // TODO(hlundin): Write test for this.
Peter Kastingb7e50542015-06-11 12:55:50 -0700934 sync_buffer_->IncreaseEndTimestamp(
935 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000936 // Skipping break on purpose. Execution should move on into the
937 // next case.
kjellander@webrtc.org7d2b6a92015-01-28 18:37:58 +0000938 FALLTHROUGH();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000939 }
940 case kAudioRepetition: {
941 // TODO(hlundin): Write test for this.
942 // Copy last |output_size_samples_| from |sync_buffer_| to
943 // |algorithm_buffer|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000944 algorithm_buffer_->PushBackFromIndex(
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000945 *sync_buffer_, sync_buffer_->Size() - output_size_samples_);
946 expand_->Reset();
947 break;
948 }
949 case kUndefined: {
Henrik Lundind67a2192015-08-03 12:54:37 +0200950 LOG(LS_ERROR) << "Invalid operation kUndefined.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000951 assert(false); // This should not happen.
952 last_mode_ = kModeError;
953 return kInvalidOperation;
954 }
955 } // End of switch.
minyue5bd33972016-05-02 04:46:11 -0700956 last_operation_ = operation;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000957 if (return_value < 0) {
958 return return_value;
959 }
960
961 if (last_mode_ != kModeRfc3389Cng) {
962 comfort_noise_->Reset();
963 }
964
965 // Copy from |algorithm_buffer| to |sync_buffer_|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000966 sync_buffer_->PushBack(*algorithm_buffer_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000967
968 // Extract data from |sync_buffer_| to |output|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000969 size_t num_output_samples_per_channel = output_size_samples_;
970 size_t num_output_samples = output_size_samples_ * sync_buffer_->Channels();
henrik.lundin6d8e0112016-03-04 10:34:21 -0800971 if (num_output_samples > AudioFrame::kMaxDataSizeSamples) {
972 LOG(LS_WARNING) << "Output array is too short. "
973 << AudioFrame::kMaxDataSizeSamples << " < "
974 << output_size_samples_ << " * "
975 << sync_buffer_->Channels();
976 num_output_samples = AudioFrame::kMaxDataSizeSamples;
977 num_output_samples_per_channel =
978 AudioFrame::kMaxDataSizeSamples / sync_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000979 }
henrik.lundin6d8e0112016-03-04 10:34:21 -0800980 sync_buffer_->GetNextAudioInterleaved(num_output_samples_per_channel,
981 audio_frame);
982 audio_frame->sample_rate_hz_ = fs_hz_;
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200983 if (sync_buffer_->FutureLength() < expand_->overlap_length()) {
984 // The sync buffer should always contain |overlap_length| samples, but now
985 // too many samples have been extracted. Reinstall the |overlap_length|
986 // lookahead by moving the index.
987 const size_t missing_lookahead_samples =
988 expand_->overlap_length() - sync_buffer_->FutureLength();
henrikg91d6ede2015-09-17 00:24:34 -0700989 RTC_DCHECK_GE(sync_buffer_->next_index(), missing_lookahead_samples);
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200990 sync_buffer_->set_next_index(sync_buffer_->next_index() -
991 missing_lookahead_samples);
992 }
henrik.lundin6d8e0112016-03-04 10:34:21 -0800993 if (audio_frame->samples_per_channel_ != output_size_samples_) {
994 LOG(LS_ERROR) << "audio_frame->samples_per_channel_ ("
995 << audio_frame->samples_per_channel_
Henrik Lundind67a2192015-08-03 12:54:37 +0200996 << ") != output_size_samples_ (" << output_size_samples_
997 << ")";
minyue@webrtc.orgdb1cefc2013-08-13 01:39:21 +0000998 // TODO(minyue): treatment of under-run, filling zeros
henrik.lundin6d8e0112016-03-04 10:34:21 -0800999 memset(audio_frame->data_, 0, num_output_samples * sizeof(int16_t));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001000 return kSampleUnderrun;
1001 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001002
1003 // Should always have overlap samples left in the |sync_buffer_|.
henrikg91d6ede2015-09-17 00:24:34 -07001004 RTC_DCHECK_GE(sync_buffer_->FutureLength(), expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001005
1006 if (play_dtmf) {
henrik.lundin6d8e0112016-03-04 10:34:21 -08001007 return_value =
1008 DtmfOverdub(dtmf_event, sync_buffer_->Channels(), audio_frame->data_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001009 }
1010
1011 // Update the background noise parameters if last operation wrote data
1012 // straight from the decoder to the |sync_buffer_|. That is, none of the
1013 // operations that modify the signal can be followed by a parameter update.
1014 if ((last_mode_ == kModeNormal) ||
1015 (last_mode_ == kModeAccelerateFail) ||
1016 (last_mode_ == kModePreemptiveExpandFail) ||
1017 (last_mode_ == kModeRfc3389Cng) ||
1018 (last_mode_ == kModeCodecInternalCng)) {
1019 background_noise_->Update(*sync_buffer_, *vad_.get());
1020 }
1021
1022 if (operation == kDtmf) {
1023 // DTMF data was written the end of |sync_buffer_|.
1024 // Update index to end of DTMF data in |sync_buffer_|.
1025 sync_buffer_->set_dtmf_index(sync_buffer_->Size());
1026 }
1027
henrik.lundin@webrtc.orged865b52014-03-06 10:28:07 +00001028 if (last_mode_ != kModeExpand) {
1029 // If last operation was not expand, calculate the |playout_timestamp_| from
1030 // the |sync_buffer_|. However, do not update the |playout_timestamp_| if it
1031 // would be moved "backwards".
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001032 uint32_t temp_timestamp = sync_buffer_->end_timestamp() -
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001033 static_cast<uint32_t>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001034 if (static_cast<int32_t>(temp_timestamp - playout_timestamp_) > 0) {
1035 playout_timestamp_ = temp_timestamp;
1036 }
1037 } else {
1038 // Use dead reckoning to estimate the |playout_timestamp_|.
Peter Kastingb7e50542015-06-11 12:55:50 -07001039 playout_timestamp_ += static_cast<uint32_t>(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001040 }
henrik.lundin15c51e32016-04-06 08:38:56 -07001041 // Set the timestamp in the audio frame to zero before the first packet has
1042 // been inserted. Otherwise, subtract the frame size in samples to get the
1043 // timestamp of the first sample in the frame (playout_timestamp_ is the
1044 // last + 1).
1045 audio_frame->timestamp_ =
1046 first_packet_
1047 ? 0
1048 : timestamp_scaler_->ToExternal(playout_timestamp_) -
1049 static_cast<uint32_t>(audio_frame->samples_per_channel_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001050
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001051 if (!(last_mode_ == kModeRfc3389Cng ||
1052 last_mode_ == kModeCodecInternalCng ||
1053 last_mode_ == kModeExpand)) {
1054 generated_noise_stopwatch_.reset();
1055 }
1056
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001057 if (decode_return_value) return decode_return_value;
1058 return return_value;
1059}
1060
1061int NetEqImpl::GetDecision(Operations* operation,
1062 PacketList* packet_list,
1063 DtmfEvent* dtmf_event,
1064 bool* play_dtmf) {
1065 // Initialize output variables.
1066 *play_dtmf = false;
1067 *operation = kUndefined;
1068
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001069 assert(sync_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001070 uint32_t end_timestamp = sync_buffer_->end_timestamp();
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001071 if (!new_codec_) {
1072 const uint32_t five_seconds_samples = 5 * fs_hz_;
1073 packet_buffer_->DiscardOldPackets(end_timestamp, five_seconds_samples);
1074 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001075 const RTPHeader* header = packet_buffer_->NextRtpHeader();
1076
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001077 RTC_DCHECK(!generated_noise_stopwatch_ ||
1078 generated_noise_stopwatch_->ElapsedTicks() >= 1);
1079 uint64_t generated_noise_samples =
1080 generated_noise_stopwatch_
1081 ? (generated_noise_stopwatch_->ElapsedTicks() - 1) *
1082 output_size_samples_ +
1083 decision_logic_->noise_fast_forward()
1084 : 0;
1085
henrik.lundin@webrtc.orgca8cb952014-03-12 10:26:52 +00001086 if (decision_logic_->CngRfc3389On() || last_mode_ == kModeRfc3389Cng) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001087 // Because of timestamp peculiarities, we have to "manually" disallow using
1088 // a CNG packet with the same timestamp as the one that was last played.
1089 // This can happen when using redundancy and will cause the timing to shift.
henrik.lundin@webrtc.org24779fe2014-03-14 12:40:05 +00001090 while (header && decoder_database_->IsComfortNoise(header->payloadType) &&
1091 (end_timestamp >= header->timestamp ||
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001092 end_timestamp + generated_noise_samples > header->timestamp)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001093 // Don't use this packet, discard it.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001094 if (packet_buffer_->DiscardNextPacket() != PacketBuffer::kOK) {
1095 assert(false); // Must be ok by design.
1096 }
1097 // Check buffer again.
1098 if (!new_codec_) {
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001099 packet_buffer_->DiscardOldPackets(end_timestamp, 5 * fs_hz_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001100 }
1101 header = packet_buffer_->NextRtpHeader();
1102 }
1103 }
1104
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001105 assert(expand_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001106 const int samples_left = static_cast<int>(sync_buffer_->FutureLength() -
1107 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001108 if (last_mode_ == kModeAccelerateSuccess ||
1109 last_mode_ == kModeAccelerateLowEnergy ||
1110 last_mode_ == kModePreemptiveExpandSuccess ||
1111 last_mode_ == kModePreemptiveExpandLowEnergy) {
1112 // Subtract (samples_left + output_size_samples_) from sampleMemory.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001113 decision_logic_->AddSampleMemory(
1114 -(samples_left + rtc::checked_cast<int>(output_size_samples_)));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001115 }
1116
1117 // Check if it is time to play a DTMF event.
Peter Kastingb7e50542015-06-11 12:55:50 -07001118 if (dtmf_buffer_->GetEvent(
1119 static_cast<uint32_t>(
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001120 end_timestamp + generated_noise_samples),
Peter Kastingb7e50542015-06-11 12:55:50 -07001121 dtmf_event)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001122 *play_dtmf = true;
1123 }
1124
1125 // Get instruction.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001126 assert(sync_buffer_.get());
1127 assert(expand_.get());
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001128 generated_noise_samples =
1129 generated_noise_stopwatch_
1130 ? generated_noise_stopwatch_->ElapsedTicks() * output_size_samples_ +
1131 decision_logic_->noise_fast_forward()
1132 : 0;
1133 *operation = decision_logic_->GetDecision(
1134 *sync_buffer_, *expand_, decoder_frame_length_, header, last_mode_,
1135 *play_dtmf, generated_noise_samples, &reset_decoder_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001136
1137 // Check if we already have enough samples in the |sync_buffer_|. If so,
1138 // change decision to normal, unless the decision was merge, accelerate, or
1139 // preemptive expand.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001140 if (samples_left >= rtc::checked_cast<int>(output_size_samples_) &&
1141 *operation != kMerge &&
1142 *operation != kAccelerate &&
1143 *operation != kFastAccelerate &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001144 *operation != kPreemptiveExpand) {
1145 *operation = kNormal;
1146 return 0;
1147 }
1148
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001149 decision_logic_->ExpandDecision(*operation);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001150
1151 // Check conditions for reset.
1152 if (new_codec_ || *operation == kUndefined) {
1153 // The only valid reason to get kUndefined is that new_codec_ is set.
1154 assert(new_codec_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001155 if (*play_dtmf && !header) {
1156 timestamp_ = dtmf_event->timestamp;
1157 } else {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001158 if (!header) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001159 LOG(LS_ERROR) << "Packet missing where it shouldn't.";
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001160 return -1;
1161 }
1162 timestamp_ = header->timestamp;
ossu108ecec2016-07-08 08:45:18 -07001163 if (*operation == kRfc3389CngNoPacket &&
1164 decoder_database_->IsComfortNoise(header->payloadType)) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001165 // Change decision to CNG packet, since we do have a CNG packet, but it
1166 // was considered too early to use. Now, use it anyway.
1167 *operation = kRfc3389Cng;
1168 } else if (*operation != kRfc3389Cng) {
1169 *operation = kNormal;
1170 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001171 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001172 // Adjust |sync_buffer_| timestamp before setting |end_timestamp| to the
1173 // new value.
1174 sync_buffer_->IncreaseEndTimestamp(timestamp_ - end_timestamp);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001175 end_timestamp = timestamp_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001176 new_codec_ = false;
1177 decision_logic_->SoftReset();
1178 buffer_level_filter_->Reset();
1179 delay_manager_->Reset();
1180 stats_.ResetMcu();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001181 }
1182
Peter Kastingdce40cf2015-08-24 14:52:23 -07001183 size_t required_samples = output_size_samples_;
1184 const size_t samples_10_ms = static_cast<size_t>(80 * fs_mult_);
1185 const size_t samples_20_ms = 2 * samples_10_ms;
1186 const size_t samples_30_ms = 3 * samples_10_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001187
1188 switch (*operation) {
1189 case kExpand: {
1190 timestamp_ = end_timestamp;
1191 return 0;
1192 }
1193 case kRfc3389CngNoPacket:
1194 case kCodecInternalCng: {
1195 return 0;
1196 }
1197 case kDtmf: {
1198 // TODO(hlundin): Write test for this.
1199 // Update timestamp.
1200 timestamp_ = end_timestamp;
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001201 const uint64_t generated_noise_samples =
1202 generated_noise_stopwatch_
1203 ? generated_noise_stopwatch_->ElapsedTicks() *
1204 output_size_samples_ +
1205 decision_logic_->noise_fast_forward()
1206 : 0;
1207 if (generated_noise_samples > 0 && last_mode_ != kModeDtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001208 // Make a jump in timestamp due to the recently played comfort noise.
Peter Kastingb7e50542015-06-11 12:55:50 -07001209 uint32_t timestamp_jump =
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001210 static_cast<uint32_t>(generated_noise_samples);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001211 sync_buffer_->IncreaseEndTimestamp(timestamp_jump);
1212 timestamp_ += timestamp_jump;
1213 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001214 return 0;
1215 }
Henrik Lundincf808d22015-05-27 14:33:29 +02001216 case kAccelerate:
1217 case kFastAccelerate: {
1218 // In order to do an accelerate we need at least 30 ms of audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001219 if (samples_left >= static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001220 // Already have enough data, so we do not need to extract any more.
1221 decision_logic_->set_sample_memory(samples_left);
1222 decision_logic_->set_prev_time_scale(true);
1223 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001224 } else if (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001225 decoder_frame_length_ >= samples_30_ms) {
1226 // Avoid decoding more data as it might overflow the playout buffer.
1227 *operation = kNormal;
1228 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001229 } else if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001230 decoder_frame_length_ < samples_30_ms) {
1231 // Build up decoded data by decoding at least 20 ms of audio data. Do
1232 // not perform accelerate yet, but wait until we only need to do one
1233 // decoding.
1234 required_samples = 2 * output_size_samples_;
1235 *operation = kNormal;
1236 }
1237 // If none of the above is true, we have one of two possible situations:
1238 // (1) 20 ms <= samples_left < 30 ms and decoder_frame_length_ < 30 ms; or
1239 // (2) samples_left < 10 ms and decoder_frame_length_ >= 30 ms.
1240 // In either case, we move on with the accelerate decision, and decode one
1241 // frame now.
1242 break;
1243 }
1244 case kPreemptiveExpand: {
1245 // In order to do a preemptive expand we need at least 30 ms of decoded
1246 // audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001247 if ((samples_left >= static_cast<int>(samples_30_ms)) ||
1248 (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001249 decoder_frame_length_ >= samples_30_ms)) {
1250 // Already have enough data, so we do not need to extract any more.
1251 // Or, avoid decoding more data as it might overflow the playout buffer.
1252 // Still try preemptive expand, though.
1253 decision_logic_->set_sample_memory(samples_left);
1254 decision_logic_->set_prev_time_scale(true);
1255 return 0;
1256 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07001257 if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001258 decoder_frame_length_ < samples_30_ms) {
1259 // Build up decoded data by decoding at least 20 ms of audio data.
1260 // Still try to perform preemptive expand.
1261 required_samples = 2 * output_size_samples_;
1262 }
1263 // Move on with the preemptive expand decision.
1264 break;
1265 }
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001266 case kMerge: {
1267 required_samples =
1268 std::max(merge_->RequiredFutureSamples(), required_samples);
1269 break;
1270 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001271 default: {
1272 // Do nothing.
1273 }
1274 }
1275
1276 // Get packets from buffer.
1277 int extracted_samples = 0;
1278 if (header &&
1279 *operation != kAlternativePlc &&
1280 *operation != kAlternativePlcIncreaseTimestamp &&
1281 *operation != kAudioRepetition &&
1282 *operation != kAudioRepetitionIncreaseTimestamp) {
1283 sync_buffer_->IncreaseEndTimestamp(header->timestamp - end_timestamp);
1284 if (decision_logic_->CngOff()) {
1285 // Adjustment of timestamp only corresponds to an actual packet loss
1286 // if comfort noise is not played. If comfort noise was just played,
1287 // this adjustment of timestamp is only done to get back in sync with the
1288 // stream timestamp; no loss to report.
1289 stats_.LostSamples(header->timestamp - end_timestamp);
1290 }
1291
1292 if (*operation != kRfc3389Cng) {
1293 // We are about to decode and use a non-CNG packet.
1294 decision_logic_->SetCngOff();
1295 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001296
1297 extracted_samples = ExtractPackets(required_samples, packet_list);
1298 if (extracted_samples < 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001299 return kPacketBufferCorruption;
1300 }
1301 }
1302
Henrik Lundincf808d22015-05-27 14:33:29 +02001303 if (*operation == kAccelerate || *operation == kFastAccelerate ||
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001304 *operation == kPreemptiveExpand) {
1305 decision_logic_->set_sample_memory(samples_left + extracted_samples);
1306 decision_logic_->set_prev_time_scale(true);
1307 }
1308
Henrik Lundincf808d22015-05-27 14:33:29 +02001309 if (*operation == kAccelerate || *operation == kFastAccelerate) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001310 // Check that we have enough data (30ms) to do accelerate.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001311 if (extracted_samples + samples_left < static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001312 // TODO(hlundin): Write test for this.
1313 // Not enough, do normal operation instead.
1314 *operation = kNormal;
1315 }
1316 }
1317
1318 timestamp_ = end_timestamp;
1319 return 0;
1320}
1321
1322int NetEqImpl::Decode(PacketList* packet_list, Operations* operation,
1323 int* decoded_length,
1324 AudioDecoder::SpeechType* speech_type) {
1325 *speech_type = AudioDecoder::kSpeech;
minyuel6d92bf52015-09-23 15:20:39 +02001326
1327 // When packet_list is empty, we may be in kCodecInternalCng mode, and for
1328 // that we use current active decoder.
1329 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1330
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001331 if (!packet_list->empty()) {
1332 const Packet* packet = packet_list->front();
pkasting@chromium.org0e81fdf2015-02-02 23:54:03 +00001333 uint8_t payload_type = packet->header.payloadType;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001334 if (!decoder_database_->IsComfortNoise(payload_type)) {
1335 decoder = decoder_database_->GetDecoder(payload_type);
1336 assert(decoder);
1337 if (!decoder) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001338 LOG(LS_WARNING) << "Unknown payload type "
1339 << static_cast<int>(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001340 PacketBuffer::DeleteAllPackets(packet_list);
1341 return kDecoderNotFound;
1342 }
1343 bool decoder_changed;
1344 decoder_database_->SetActiveDecoder(payload_type, &decoder_changed);
1345 if (decoder_changed) {
1346 // We have a new decoder. Re-init some values.
1347 const DecoderDatabase::DecoderInfo* decoder_info = decoder_database_
1348 ->GetDecoderInfo(payload_type);
1349 assert(decoder_info);
1350 if (!decoder_info) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001351 LOG(LS_WARNING) << "Unknown payload type "
1352 << static_cast<int>(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001353 PacketBuffer::DeleteAllPackets(packet_list);
1354 return kDecoderNotFound;
1355 }
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001356 // If sampling rate or number of channels has changed, we need to make
1357 // a reset.
kwibergc0f2dcf2016-05-31 06:28:03 -07001358 if (decoder_info->SampleRateHz() != fs_hz_ ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001359 decoder->Channels() != algorithm_buffer_->Channels()) {
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001360 // TODO(tlegrand): Add unittest to cover this event.
kwibergc0f2dcf2016-05-31 06:28:03 -07001361 SetSampleRateAndChannels(decoder_info->SampleRateHz(),
1362 decoder->Channels());
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001363 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001364 sync_buffer_->set_end_timestamp(timestamp_);
1365 playout_timestamp_ = timestamp_;
1366 }
1367 }
1368 }
1369
1370 if (reset_decoder_) {
1371 // TODO(hlundin): Write test for this.
Karl Wiberg43766482015-08-27 15:22:11 +02001372 if (decoder)
1373 decoder->Reset();
1374
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001375 // Reset comfort noise decoder.
ossu97ba30e2016-04-25 07:55:58 -07001376 ComfortNoiseDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02001377 if (cng_decoder)
1378 cng_decoder->Reset();
1379
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001380 reset_decoder_ = false;
1381 }
1382
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001383 *decoded_length = 0;
1384 // Update codec-internal PLC state.
1385 if ((*operation == kMerge) && decoder && decoder->HasDecodePlc()) {
1386 decoder->DecodePlc(1, &decoded_buffer_[*decoded_length]);
1387 }
1388
minyuel6d92bf52015-09-23 15:20:39 +02001389 int return_value;
1390 if (*operation == kCodecInternalCng) {
1391 RTC_DCHECK(packet_list->empty());
1392 return_value = DecodeCng(decoder, decoded_length, speech_type);
1393 } else {
1394 return_value = DecodeLoop(packet_list, *operation, decoder,
1395 decoded_length, speech_type);
1396 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001397
1398 if (*decoded_length < 0) {
1399 // Error returned from the decoder.
1400 *decoded_length = 0;
Peter Kastingb7e50542015-06-11 12:55:50 -07001401 sync_buffer_->IncreaseEndTimestamp(
1402 static_cast<uint32_t>(decoder_frame_length_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001403 int error_code = 0;
1404 if (decoder)
1405 error_code = decoder->ErrorCode();
1406 if (error_code != 0) {
1407 // Got some error code from the decoder.
1408 decoder_error_code_ = error_code;
1409 return_value = kDecoderErrorCode;
Henrik Lundind67a2192015-08-03 12:54:37 +02001410 LOG(LS_WARNING) << "Decoder returned error code: " << error_code;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001411 } else {
1412 // Decoder does not implement error codes. Return generic error.
1413 return_value = kOtherDecoderError;
Henrik Lundind67a2192015-08-03 12:54:37 +02001414 LOG(LS_WARNING) << "Decoder error (no error code)";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001415 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001416 *operation = kExpand; // Do expansion to get data instead.
1417 }
1418 if (*speech_type != AudioDecoder::kComfortNoise) {
1419 // Don't increment timestamp if codec returned CNG speech type
1420 // since in this case, the we will increment the CNGplayedTS counter.
1421 // Increase with number of samples per channel.
1422 assert(*decoded_length == 0 ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001423 (decoder && decoder->Channels() == sync_buffer_->Channels()));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001424 sync_buffer_->IncreaseEndTimestamp(
1425 *decoded_length / static_cast<int>(sync_buffer_->Channels()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001426 }
1427 return return_value;
1428}
1429
minyuel6d92bf52015-09-23 15:20:39 +02001430int NetEqImpl::DecodeCng(AudioDecoder* decoder, int* decoded_length,
1431 AudioDecoder::SpeechType* speech_type) {
1432 if (!decoder) {
1433 // This happens when active decoder is not defined.
1434 *decoded_length = -1;
1435 return 0;
1436 }
1437
1438 while (*decoded_length < rtc::checked_cast<int>(output_size_samples_)) {
1439 const int length = decoder->Decode(
1440 nullptr, 0, fs_hz_,
1441 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1442 &decoded_buffer_[*decoded_length], speech_type);
1443 if (length > 0) {
1444 *decoded_length += length;
minyuel6d92bf52015-09-23 15:20:39 +02001445 } else {
1446 // Error.
1447 LOG(LS_WARNING) << "Failed to decode CNG";
1448 *decoded_length = -1;
1449 break;
1450 }
1451 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1452 // Guard against overflow.
1453 LOG(LS_WARNING) << "Decoded too much CNG.";
1454 return kDecodedTooMuch;
1455 }
1456 }
1457 return 0;
1458}
1459
1460int NetEqImpl::DecodeLoop(PacketList* packet_list, const Operations& operation,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001461 AudioDecoder* decoder, int* decoded_length,
1462 AudioDecoder::SpeechType* speech_type) {
1463 Packet* packet = NULL;
1464 if (!packet_list->empty()) {
1465 packet = packet_list->front();
1466 }
minyuel6d92bf52015-09-23 15:20:39 +02001467
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001468 // Do decoding.
1469 while (packet &&
1470 !decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1471 assert(decoder); // At this point, we must have a decoder object.
1472 // The number of channels in the |sync_buffer_| should be the same as the
1473 // number decoder channels.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001474 assert(sync_buffer_->Channels() == decoder->Channels());
1475 assert(decoded_buffer_length_ >= kMaxFrameSize * decoder->Channels());
minyuel6d92bf52015-09-23 15:20:39 +02001476 assert(operation == kNormal || operation == kAccelerate ||
1477 operation == kFastAccelerate || operation == kMerge ||
1478 operation == kPreemptiveExpand);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001479 packet_list->pop_front();
ossu61a208b2016-09-20 01:38:00 -07001480 auto opt_result = packet->frame->Decode(
1481 rtc::ArrayView<int16_t>(&decoded_buffer_[*decoded_length],
1482 decoded_buffer_length_ - *decoded_length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001483 delete packet;
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001484 packet = NULL;
ossu61a208b2016-09-20 01:38:00 -07001485 if (opt_result) {
1486 const auto& result = *opt_result;
1487 *speech_type = result.speech_type;
1488 if (result.num_decoded_samples > 0) {
1489 *decoded_length += rtc::checked_cast<int>(result.num_decoded_samples);
1490 // Update |decoder_frame_length_| with number of samples per channel.
1491 decoder_frame_length_ =
1492 result.num_decoded_samples / decoder->Channels();
1493 }
1494 } else {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001495 // Error.
ossu61a208b2016-09-20 01:38:00 -07001496 // TODO(ossu): What to put here?
1497 LOG(LS_WARNING) << "Decode error";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001498 *decoded_length = -1;
1499 PacketBuffer::DeleteAllPackets(packet_list);
1500 break;
1501 }
ossu61a208b2016-09-20 01:38:00 -07001502 if (*decoded_length > rtc::checked_cast<int>(decoded_buffer_length_)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001503 // Guard against overflow.
Henrik Lundind67a2192015-08-03 12:54:37 +02001504 LOG(LS_WARNING) << "Decoded too much.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001505 PacketBuffer::DeleteAllPackets(packet_list);
1506 return kDecodedTooMuch;
1507 }
1508 if (!packet_list->empty()) {
1509 packet = packet_list->front();
1510 } else {
1511 packet = NULL;
1512 }
1513 } // End of decode loop.
1514
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001515 // If the list is not empty at this point, either a decoding error terminated
1516 // the while-loop, or list must hold exactly one CNG packet.
1517 assert(packet_list->empty() || *decoded_length < 0 ||
1518 (packet_list->size() == 1 && packet &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001519 decoder_database_->IsComfortNoise(packet->header.payloadType)));
1520 return 0;
1521}
1522
1523void NetEqImpl::DoNormal(const int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001524 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001525 assert(normal_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001526 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001527 normal_->Process(decoded_buffer, decoded_length, last_mode_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001528 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001529 if (decoded_length != 0) {
1530 last_mode_ = kModeNormal;
1531 }
1532
1533 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1534 if ((speech_type == AudioDecoder::kComfortNoise)
1535 || ((last_mode_ == kModeCodecInternalCng)
1536 && (decoded_length == 0))) {
1537 // TODO(hlundin): Remove second part of || statement above.
1538 last_mode_ = kModeCodecInternalCng;
1539 }
1540
1541 if (!play_dtmf) {
1542 dtmf_tone_generator_->Reset();
1543 }
1544}
1545
1546void NetEqImpl::DoMerge(int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001547 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001548 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001549 assert(merge_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001550 size_t new_length = merge_->Process(decoded_buffer, decoded_length,
1551 mute_factor_array_.get(),
1552 algorithm_buffer_.get());
1553 size_t expand_length_correction = new_length -
1554 decoded_length / algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001555
1556 // Update in-call and post-call statistics.
1557 if (expand_->MuteFactor(0) == 0) {
1558 // Expand generates only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001559 stats_.ExpandedNoiseSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001560 } else {
1561 // Expansion generates more than only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001562 stats_.ExpandedVoiceSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001563 }
1564
1565 last_mode_ = kModeMerge;
1566 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1567 if (speech_type == AudioDecoder::kComfortNoise) {
1568 last_mode_ = kModeCodecInternalCng;
1569 }
1570 expand_->Reset();
1571 if (!play_dtmf) {
1572 dtmf_tone_generator_->Reset();
1573 }
1574}
1575
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001576int NetEqImpl::DoExpand(bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001577 while ((sync_buffer_->FutureLength() - expand_->overlap_length()) <
Peter Kastingdce40cf2015-08-24 14:52:23 -07001578 output_size_samples_) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001579 algorithm_buffer_->Clear();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001580 int return_value = expand_->Process(algorithm_buffer_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001581 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001582
1583 // Update in-call and post-call statistics.
1584 if (expand_->MuteFactor(0) == 0) {
1585 // Expand operation generates only noise.
1586 stats_.ExpandedNoiseSamples(length);
1587 } else {
1588 // Expand operation generates more than only noise.
1589 stats_.ExpandedVoiceSamples(length);
1590 }
1591
1592 last_mode_ = kModeExpand;
1593
1594 if (return_value < 0) {
1595 return return_value;
1596 }
1597
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001598 sync_buffer_->PushBack(*algorithm_buffer_);
1599 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001600 }
1601 if (!play_dtmf) {
1602 dtmf_tone_generator_->Reset();
1603 }
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001604
1605 if (!generated_noise_stopwatch_) {
1606 // Start a new stopwatch since we may be covering for a lost CNG packet.
1607 generated_noise_stopwatch_ = tick_timer_->GetNewStopwatch();
1608 }
1609
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001610 return 0;
1611}
1612
Henrik Lundincf808d22015-05-27 14:33:29 +02001613int NetEqImpl::DoAccelerate(int16_t* decoded_buffer,
1614 size_t decoded_length,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001615 AudioDecoder::SpeechType speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +02001616 bool play_dtmf,
1617 bool fast_accelerate) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001618 const size_t required_samples =
1619 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001620 size_t borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001621 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001622 size_t decoded_length_per_channel = decoded_length / num_channels;
1623 if (decoded_length_per_channel < required_samples) {
1624 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001625 borrowed_samples_per_channel = static_cast<int>(required_samples -
1626 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001627 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1628 decoded_buffer,
1629 sizeof(int16_t) * decoded_length);
1630 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1631 decoded_buffer);
1632 decoded_length = required_samples * num_channels;
1633 }
1634
Peter Kastingdce40cf2015-08-24 14:52:23 -07001635 size_t samples_removed;
Henrik Lundincf808d22015-05-27 14:33:29 +02001636 Accelerate::ReturnCodes return_code =
1637 accelerate_->Process(decoded_buffer, decoded_length, fast_accelerate,
1638 algorithm_buffer_.get(), &samples_removed);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001639 stats_.AcceleratedSamples(samples_removed);
1640 switch (return_code) {
1641 case Accelerate::kSuccess:
1642 last_mode_ = kModeAccelerateSuccess;
1643 break;
1644 case Accelerate::kSuccessLowEnergy:
1645 last_mode_ = kModeAccelerateLowEnergy;
1646 break;
1647 case Accelerate::kNoStretch:
1648 last_mode_ = kModeAccelerateFail;
1649 break;
1650 case Accelerate::kError:
1651 // TODO(hlundin): Map to kModeError instead?
1652 last_mode_ = kModeAccelerateFail;
1653 return kAccelerateError;
1654 }
1655
1656 if (borrowed_samples_per_channel > 0) {
1657 // Copy borrowed samples back to the |sync_buffer_|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001658 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001659 if (length < borrowed_samples_per_channel) {
1660 // This destroys the beginning of the buffer, but will not cause any
1661 // problems.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001662 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001663 sync_buffer_->Size() -
1664 borrowed_samples_per_channel);
1665 sync_buffer_->PushFrontZeros(borrowed_samples_per_channel - length);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001666 algorithm_buffer_->PopFront(length);
1667 assert(algorithm_buffer_->Empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001668 } else {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001669 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001670 borrowed_samples_per_channel,
1671 sync_buffer_->Size() -
1672 borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001673 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001674 }
1675 }
1676
1677 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1678 if (speech_type == AudioDecoder::kComfortNoise) {
1679 last_mode_ = kModeCodecInternalCng;
1680 }
1681 if (!play_dtmf) {
1682 dtmf_tone_generator_->Reset();
1683 }
1684 expand_->Reset();
1685 return 0;
1686}
1687
1688int NetEqImpl::DoPreemptiveExpand(int16_t* decoded_buffer,
1689 size_t decoded_length,
1690 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001691 bool play_dtmf) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001692 const size_t required_samples =
1693 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001694 size_t num_channels = algorithm_buffer_->Channels();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001695 size_t borrowed_samples_per_channel = 0;
1696 size_t old_borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001697 size_t decoded_length_per_channel = decoded_length / num_channels;
1698 if (decoded_length_per_channel < required_samples) {
1699 // Must move data from the |sync_buffer_| in order to get 30 ms.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001700 borrowed_samples_per_channel =
1701 required_samples - decoded_length_per_channel;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001702 // Calculate how many of these were already played out.
Peter Kastingf045e4d2015-06-10 21:15:38 -07001703 old_borrowed_samples_per_channel =
Peter Kastingdce40cf2015-08-24 14:52:23 -07001704 (borrowed_samples_per_channel > sync_buffer_->FutureLength()) ?
1705 (borrowed_samples_per_channel - sync_buffer_->FutureLength()) : 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001706 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1707 decoded_buffer,
1708 sizeof(int16_t) * decoded_length);
1709 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1710 decoded_buffer);
1711 decoded_length = required_samples * num_channels;
1712 }
1713
Peter Kastingdce40cf2015-08-24 14:52:23 -07001714 size_t samples_added;
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001715 PreemptiveExpand::ReturnCodes return_code = preemptive_expand_->Process(
Peter Kastingdce40cf2015-08-24 14:52:23 -07001716 decoded_buffer, decoded_length,
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001717 old_borrowed_samples_per_channel,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001718 algorithm_buffer_.get(), &samples_added);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001719 stats_.PreemptiveExpandedSamples(samples_added);
1720 switch (return_code) {
1721 case PreemptiveExpand::kSuccess:
1722 last_mode_ = kModePreemptiveExpandSuccess;
1723 break;
1724 case PreemptiveExpand::kSuccessLowEnergy:
1725 last_mode_ = kModePreemptiveExpandLowEnergy;
1726 break;
1727 case PreemptiveExpand::kNoStretch:
1728 last_mode_ = kModePreemptiveExpandFail;
1729 break;
1730 case PreemptiveExpand::kError:
1731 // TODO(hlundin): Map to kModeError instead?
1732 last_mode_ = kModePreemptiveExpandFail;
1733 return kPreemptiveExpandError;
1734 }
1735
1736 if (borrowed_samples_per_channel > 0) {
1737 // Copy borrowed samples back to the |sync_buffer_|.
1738 sync_buffer_->ReplaceAtIndex(
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001739 *algorithm_buffer_, borrowed_samples_per_channel,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001740 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001741 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001742 }
1743
1744 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1745 if (speech_type == AudioDecoder::kComfortNoise) {
1746 last_mode_ = kModeCodecInternalCng;
1747 }
1748 if (!play_dtmf) {
1749 dtmf_tone_generator_->Reset();
1750 }
1751 expand_->Reset();
1752 return 0;
1753}
1754
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001755int NetEqImpl::DoRfc3389Cng(PacketList* packet_list, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001756 if (!packet_list->empty()) {
1757 // Must have exactly one SID frame at this point.
1758 assert(packet_list->size() == 1);
1759 Packet* packet = packet_list->front();
1760 packet_list->pop_front();
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001761 if (!decoder_database_->IsComfortNoise(packet->header.payloadType)) {
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001762 LOG(LS_ERROR) << "Trying to decode non-CNG payload as CNG.";
1763 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001764 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001765 // UpdateParameters() deletes |packet|.
1766 if (comfort_noise_->UpdateParameters(packet) ==
1767 ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001768 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001769 return -comfort_noise_->internal_error_code();
1770 }
1771 }
1772 int cn_return = comfort_noise_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001773 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001774 expand_->Reset();
1775 last_mode_ = kModeRfc3389Cng;
1776 if (!play_dtmf) {
1777 dtmf_tone_generator_->Reset();
1778 }
1779 if (cn_return == ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001780 decoder_error_code_ = comfort_noise_->internal_error_code();
1781 return kComfortNoiseErrorCode;
1782 } else if (cn_return == ComfortNoise::kUnknownPayloadType) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001783 return kUnknownRtpPayloadType;
1784 }
1785 return 0;
1786}
1787
minyuel6d92bf52015-09-23 15:20:39 +02001788void NetEqImpl::DoCodecInternalCng(const int16_t* decoded_buffer,
1789 size_t decoded_length) {
1790 RTC_DCHECK(normal_.get());
1791 RTC_DCHECK(mute_factor_array_.get());
1792 normal_->Process(decoded_buffer, decoded_length, last_mode_,
1793 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001794 last_mode_ = kModeCodecInternalCng;
1795 expand_->Reset();
1796}
1797
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001798int NetEqImpl::DoDtmf(const DtmfEvent& dtmf_event, bool* play_dtmf) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001799 // This block of the code and the block further down, handling |dtmf_switch|
1800 // are commented out. Otherwise playing out-of-band DTMF would fail in VoE
1801 // test, DtmfTest.ManualSuccessfullySendsOutOfBandTelephoneEvents. This is
1802 // equivalent to |dtmf_switch| always be false.
1803 //
1804 // See http://webrtc-codereview.appspot.com/1195004/ for discussion
1805 // On this issue. This change might cause some glitches at the point of
1806 // switch from audio to DTMF. Issue 1545 is filed to track this.
1807 //
1808 // bool dtmf_switch = false;
1809 // if ((last_mode_ != kModeDtmf) && dtmf_tone_generator_->initialized()) {
1810 // // Special case; see below.
1811 // // We must catch this before calling Generate, since |initialized| is
1812 // // modified in that call.
1813 // dtmf_switch = true;
1814 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001815
1816 int dtmf_return_value = 0;
1817 if (!dtmf_tone_generator_->initialized()) {
1818 // Initialize if not already done.
1819 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1820 dtmf_event.volume);
1821 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001822
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001823 if (dtmf_return_value == 0) {
1824 // Generate DTMF signal.
1825 dtmf_return_value = dtmf_tone_generator_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001826 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001827 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001828
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001829 if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001830 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001831 return dtmf_return_value;
1832 }
1833
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001834 // if (dtmf_switch) {
1835 // // This is the special case where the previous operation was DTMF
1836 // // overdub, but the current instruction is "regular" DTMF. We must make
1837 // // sure that the DTMF does not have any discontinuities. The first DTMF
1838 // // sample that we generate now must be played out immediately, therefore
1839 // // it must be copied to the speech buffer.
1840 // // TODO(hlundin): This code seems incorrect. (Legacy.) Write test and
1841 // // verify correct operation.
1842 // assert(false);
1843 // // Must generate enough data to replace all of the |sync_buffer_|
1844 // // "future".
1845 // int required_length = sync_buffer_->FutureLength();
1846 // assert(dtmf_tone_generator_->initialized());
1847 // dtmf_return_value = dtmf_tone_generator_->Generate(required_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001848 // algorithm_buffer_);
1849 // assert((size_t) required_length == algorithm_buffer_->Size());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001850 // if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001851 // algorithm_buffer_->Zeros(output_size_samples_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001852 // return dtmf_return_value;
1853 // }
1854 //
1855 // // Overwrite the "future" part of the speech buffer with the new DTMF
1856 // // data.
1857 // // TODO(hlundin): It seems that this overwriting has gone lost.
1858 // // Not adapted for multi-channel yet.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001859 // assert(algorithm_buffer_->Channels() == 1);
1860 // if (algorithm_buffer_->Channels() != 1) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001861 // LOG(LS_WARNING) << "DTMF not supported for more than one channel";
1862 // return kStereoNotSupported;
1863 // }
1864 // // Shuffle the remaining data to the beginning of algorithm buffer.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001865 // algorithm_buffer_->PopFront(sync_buffer_->FutureLength());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001866 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001867
Peter Kastingb7e50542015-06-11 12:55:50 -07001868 sync_buffer_->IncreaseEndTimestamp(
1869 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001870 expand_->Reset();
1871 last_mode_ = kModeDtmf;
1872
1873 // Set to false because the DTMF is already in the algorithm buffer.
1874 *play_dtmf = false;
1875 return 0;
1876}
1877
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001878void NetEqImpl::DoAlternativePlc(bool increase_timestamp) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001879 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001880 size_t length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001881 if (decoder && decoder->HasDecodePlc()) {
1882 // Use the decoder's packet-loss concealment.
1883 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1884 int16_t decoded_buffer[kMaxFrameSize];
1885 length = decoder->DecodePlc(1, decoded_buffer);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001886 if (length > 0)
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001887 algorithm_buffer_->PushBackInterleaved(decoded_buffer, length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001888 } else {
1889 // Do simple zero-stuffing.
1890 length = output_size_samples_;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001891 algorithm_buffer_->Zeros(length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001892 // By not advancing the timestamp, NetEq inserts samples.
1893 stats_.AddZeros(length);
1894 }
1895 if (increase_timestamp) {
Peter Kastingb7e50542015-06-11 12:55:50 -07001896 sync_buffer_->IncreaseEndTimestamp(static_cast<uint32_t>(length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001897 }
1898 expand_->Reset();
1899}
1900
1901int NetEqImpl::DtmfOverdub(const DtmfEvent& dtmf_event, size_t num_channels,
1902 int16_t* output) const {
1903 size_t out_index = 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001904 size_t overdub_length = output_size_samples_; // Default value.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001905
1906 if (sync_buffer_->dtmf_index() > sync_buffer_->next_index()) {
1907 // Special operation for transition from "DTMF only" to "DTMF overdub".
1908 out_index = std::min(
1909 sync_buffer_->dtmf_index() - sync_buffer_->next_index(),
Peter Kastingdce40cf2015-08-24 14:52:23 -07001910 output_size_samples_);
1911 overdub_length = output_size_samples_ - out_index;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001912 }
1913
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001914 AudioMultiVector dtmf_output(num_channels);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001915 int dtmf_return_value = 0;
1916 if (!dtmf_tone_generator_->initialized()) {
1917 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1918 dtmf_event.volume);
1919 }
1920 if (dtmf_return_value == 0) {
1921 dtmf_return_value = dtmf_tone_generator_->Generate(overdub_length,
1922 &dtmf_output);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001923 assert(overdub_length == dtmf_output.Size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001924 }
1925 dtmf_output.ReadInterleaved(overdub_length, &output[out_index]);
1926 return dtmf_return_value < 0 ? dtmf_return_value : 0;
1927}
1928
Peter Kastingdce40cf2015-08-24 14:52:23 -07001929int NetEqImpl::ExtractPackets(size_t required_samples,
1930 PacketList* packet_list) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001931 bool first_packet = true;
1932 uint8_t prev_payload_type = 0;
1933 uint32_t prev_timestamp = 0;
1934 uint16_t prev_sequence_number = 0;
1935 bool next_packet_available = false;
1936
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001937 const RTPHeader* header = packet_buffer_->NextRtpHeader();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001938 assert(header);
1939 if (!header) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001940 LOG(LS_ERROR) << "Packet buffer unexpectedly empty.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001941 return -1;
1942 }
turaj@webrtc.org7df97062013-08-02 18:07:13 +00001943 uint32_t first_timestamp = header->timestamp;
ossu61a208b2016-09-20 01:38:00 -07001944 size_t extracted_samples = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001945
1946 // Packet extraction loop.
1947 do {
1948 timestamp_ = header->timestamp;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001949 size_t discard_count = 0;
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001950 Packet* packet = packet_buffer_->GetNextPacket(&discard_count);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001951 // |header| may be invalid after the |packet_buffer_| operation.
1952 header = NULL;
1953 if (!packet) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001954 LOG(LS_ERROR) << "Should always be able to extract a packet here";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001955 assert(false); // Should always be able to extract a packet here.
1956 return -1;
1957 }
1958 stats_.PacketsDiscarded(discard_count);
henrik.lundin84f8cd62016-04-26 07:45:16 -07001959 stats_.StoreWaitingTime(packet->waiting_time->ElapsedMs());
ossu61a208b2016-09-20 01:38:00 -07001960 RTC_DCHECK(!packet->empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001961 packet_list->push_back(packet); // Store packet in list.
1962
1963 if (first_packet) {
1964 first_packet = false;
henrik.lundin48ed9302015-10-29 05:36:24 -07001965 if (nack_enabled_) {
1966 RTC_DCHECK(nack_);
1967 // TODO(henrik.lundin): Should we update this for all decoded packets?
1968 nack_->UpdateLastDecodedPacket(packet->header.sequenceNumber,
1969 packet->header.timestamp);
1970 }
1971 prev_sequence_number = packet->header.sequenceNumber;
1972 prev_timestamp = packet->header.timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001973 prev_payload_type = packet->header.payloadType;
1974 }
1975
1976 // Store number of extracted samples.
ossu61a208b2016-09-20 01:38:00 -07001977 size_t packet_duration = 0;
1978 if (packet->frame) {
1979 packet_duration = packet->frame->Duration();
1980 // TODO(ossu): Is this the correct way to track samples decoded from a
1981 // redundant packet?
1982 if (packet_duration > 0 && !packet->primary) {
1983 stats_.SecondaryDecodedSamples(rtc::checked_cast<int>(packet_duration));
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001984 }
ossu97ba30e2016-04-25 07:55:58 -07001985 } else if (!decoder_database_->IsComfortNoise(packet->header.payloadType)) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001986 LOG(LS_WARNING) << "Unknown payload type "
1987 << static_cast<int>(packet->header.payloadType);
ossu61a208b2016-09-20 01:38:00 -07001988 RTC_NOTREACHED();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001989 }
ossu61a208b2016-09-20 01:38:00 -07001990
1991 if (packet_duration == 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001992 // Decoder did not return a packet duration. Assume that the packet
1993 // contains the same number of samples as the previous one.
ossu61a208b2016-09-20 01:38:00 -07001994 packet_duration = decoder_frame_length_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001995 }
1996 extracted_samples = packet->header.timestamp - first_timestamp +
1997 packet_duration;
1998
1999 // Check what packet is available next.
2000 header = packet_buffer_->NextRtpHeader();
2001 next_packet_available = false;
2002 if (header && prev_payload_type == header->payloadType) {
2003 int16_t seq_no_diff = header->sequenceNumber - prev_sequence_number;
Peter Kastingdce40cf2015-08-24 14:52:23 -07002004 size_t ts_diff = header->timestamp - prev_timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002005 if (seq_no_diff == 1 ||
2006 (seq_no_diff == 0 && ts_diff == decoder_frame_length_)) {
2007 // The next sequence number is available, or the next part of a packet
2008 // that was split into pieces upon insertion.
2009 next_packet_available = true;
2010 }
2011 prev_sequence_number = header->sequenceNumber;
2012 }
ossu61a208b2016-09-20 01:38:00 -07002013 } while (extracted_samples < required_samples && next_packet_available);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002014
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00002015 if (extracted_samples > 0) {
2016 // Delete old packets only when we are going to decode something. Otherwise,
2017 // we could end up in the situation where we never decode anything, since
2018 // all incoming packets are considered too old but the buffer will also
2019 // never be flooded and flushed.
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00002020 packet_buffer_->DiscardAllOldPackets(timestamp_);
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00002021 }
2022
ossu61a208b2016-09-20 01:38:00 -07002023 return rtc::checked_cast<int>(extracted_samples);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002024}
2025
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002026void NetEqImpl::UpdatePlcComponents(int fs_hz, size_t channels) {
2027 // Delete objects and create new ones.
2028 expand_.reset(expand_factory_->Create(background_noise_.get(),
2029 sync_buffer_.get(), &random_vector_,
Henrik Lundinbef77e22015-08-18 14:58:09 +02002030 &stats_, fs_hz, channels));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002031 merge_.reset(new Merge(fs_hz, channels, expand_.get(), sync_buffer_.get()));
2032}
2033
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002034void NetEqImpl::SetSampleRateAndChannels(int fs_hz, size_t channels) {
Henrik Lundind67a2192015-08-03 12:54:37 +02002035 LOG(LS_VERBOSE) << "SetSampleRateAndChannels " << fs_hz << " " << channels;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002036 // TODO(hlundin): Change to an enumerator and skip assert.
2037 assert(fs_hz == 8000 || fs_hz == 16000 || fs_hz == 32000 || fs_hz == 48000);
2038 assert(channels > 0);
2039
2040 fs_hz_ = fs_hz;
2041 fs_mult_ = fs_hz / 8000;
Peter Kastingdce40cf2015-08-24 14:52:23 -07002042 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002043 decoder_frame_length_ = 3 * output_size_samples_; // Initialize to 30ms.
2044
2045 last_mode_ = kModeNormal;
2046
2047 // Create a new array of mute factors and set all to 1.
2048 mute_factor_array_.reset(new int16_t[channels]);
2049 for (size_t i = 0; i < channels; ++i) {
2050 mute_factor_array_[i] = 16384; // 1.0 in Q14.
2051 }
2052
ossu97ba30e2016-04-25 07:55:58 -07002053 ComfortNoiseDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02002054 if (cng_decoder)
2055 cng_decoder->Reset();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002056
2057 // Reinit post-decode VAD with new sample rate.
2058 assert(vad_.get()); // Cannot be NULL here.
2059 vad_->Init();
2060
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002061 // Delete algorithm buffer and create a new one.
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00002062 algorithm_buffer_.reset(new AudioMultiVector(channels));
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002063
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002064 // Delete sync buffer and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002065 sync_buffer_.reset(new SyncBuffer(channels, kSyncBufferSize * fs_mult_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002066
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00002067 // Delete BackgroundNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002068 background_noise_.reset(new BackgroundNoise(channels));
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00002069 background_noise_->set_mode(background_noise_mode_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002070
2071 // Reset random vector.
2072 random_vector_.Reset();
2073
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002074 UpdatePlcComponents(fs_hz, channels);
2075
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002076 // Move index so that we create a small set of future samples (all 0).
2077 sync_buffer_->set_next_index(sync_buffer_->next_index() -
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002078 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002079
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002080 normal_.reset(new Normal(fs_hz, decoder_database_.get(), *background_noise_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002081 expand_.get()));
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +00002082 accelerate_.reset(
2083 accelerate_factory_->Create(fs_hz, channels, *background_noise_));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002084 preemptive_expand_.reset(preemptive_expand_factory_->Create(
Peter Kastingdce40cf2015-08-24 14:52:23 -07002085 fs_hz, channels, *background_noise_, expand_->overlap_length()));
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002086
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002087 // Delete ComfortNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002088 comfort_noise_.reset(new ComfortNoise(fs_hz, decoder_database_.get(),
2089 sync_buffer_.get()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002090
2091 // Verify that |decoded_buffer_| is long enough.
2092 if (decoded_buffer_length_ < kMaxFrameSize * channels) {
2093 // Reallocate to larger size.
2094 decoded_buffer_length_ = kMaxFrameSize * channels;
2095 decoded_buffer_.reset(new int16_t[decoded_buffer_length_]);
2096 }
2097
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002098 // Create DecisionLogic if it is not created yet, then communicate new sample
2099 // rate and output size to DecisionLogic object.
2100 if (!decision_logic_.get()) {
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002101 CreateDecisionLogic();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002102 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002103 decision_logic_->SetSampleRate(fs_hz_, output_size_samples_);
2104}
2105
henrik.lundin55480f52016-03-08 02:37:57 -08002106NetEqImpl::OutputType NetEqImpl::LastOutputType() {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002107 assert(vad_.get());
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002108 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002109 if (last_mode_ == kModeCodecInternalCng || last_mode_ == kModeRfc3389Cng) {
henrik.lundin55480f52016-03-08 02:37:57 -08002110 return OutputType::kCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002111 } else if (last_mode_ == kModeExpand && expand_->MuteFactor(0) == 0) {
2112 // Expand mode has faded down to background noise only (very long expand).
henrik.lundin55480f52016-03-08 02:37:57 -08002113 return OutputType::kPLCCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002114 } else if (last_mode_ == kModeExpand) {
henrik.lundin55480f52016-03-08 02:37:57 -08002115 return OutputType::kPLC;
wu@webrtc.org24301a62013-12-13 19:17:43 +00002116 } else if (vad_->running() && !vad_->active_speech()) {
henrik.lundin55480f52016-03-08 02:37:57 -08002117 return OutputType::kVadPassive;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002118 } else {
henrik.lundin55480f52016-03-08 02:37:57 -08002119 return OutputType::kNormalSpeech;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002120 }
2121}
2122
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002123void NetEqImpl::CreateDecisionLogic() {
Henrik Lundin47b17dc2016-05-10 10:20:59 +02002124 decision_logic_.reset(DecisionLogic::Create(
2125 fs_hz_, output_size_samples_, playout_mode_, decoder_database_.get(),
2126 *packet_buffer_.get(), delay_manager_.get(), buffer_level_filter_.get(),
2127 tick_timer_.get()));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002128}
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002129} // namespace webrtc