blob: b6ec655af3f073aadb1a4c5676127addb6d61d50 [file] [log] [blame]
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001/*
2 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000011#include "webrtc/modules/audio_coding/neteq/neteq_impl.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000012
13#include <assert.h>
14#include <memory.h> // memset
15
16#include <algorithm>
ossu97ba30e2016-04-25 07:55:58 -070017#include <vector>
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000018
henrik.lundin9c3efd02015-08-27 13:12:22 -070019#include "webrtc/base/checks.h"
Henrik Lundind67a2192015-08-03 12:54:37 +020020#include "webrtc/base/logging.h"
Tommid44c0772016-03-11 17:12:32 -080021#include "webrtc/base/safe_conversions.h"
henrik.lundina689b442015-12-17 03:50:05 -080022#include "webrtc/base/trace_event.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000023#include "webrtc/common_audio/signal_processing/include/signal_processing_library.h"
kwiberg@webrtc.orge04a93b2014-12-09 10:12:53 +000024#include "webrtc/modules/audio_coding/codecs/audio_decoder.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000025#include "webrtc/modules/audio_coding/neteq/accelerate.h"
26#include "webrtc/modules/audio_coding/neteq/background_noise.h"
27#include "webrtc/modules/audio_coding/neteq/buffer_level_filter.h"
28#include "webrtc/modules/audio_coding/neteq/comfort_noise.h"
29#include "webrtc/modules/audio_coding/neteq/decision_logic.h"
30#include "webrtc/modules/audio_coding/neteq/decoder_database.h"
31#include "webrtc/modules/audio_coding/neteq/defines.h"
32#include "webrtc/modules/audio_coding/neteq/delay_manager.h"
33#include "webrtc/modules/audio_coding/neteq/delay_peak_detector.h"
34#include "webrtc/modules/audio_coding/neteq/dtmf_buffer.h"
35#include "webrtc/modules/audio_coding/neteq/dtmf_tone_generator.h"
36#include "webrtc/modules/audio_coding/neteq/expand.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000037#include "webrtc/modules/audio_coding/neteq/merge.h"
henrik.lundin48ed9302015-10-29 05:36:24 -070038#include "webrtc/modules/audio_coding/neteq/nack.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000039#include "webrtc/modules/audio_coding/neteq/normal.h"
40#include "webrtc/modules/audio_coding/neteq/packet_buffer.h"
41#include "webrtc/modules/audio_coding/neteq/packet.h"
42#include "webrtc/modules/audio_coding/neteq/payload_splitter.h"
43#include "webrtc/modules/audio_coding/neteq/post_decode_vad.h"
44#include "webrtc/modules/audio_coding/neteq/preemptive_expand.h"
45#include "webrtc/modules/audio_coding/neteq/sync_buffer.h"
46#include "webrtc/modules/audio_coding/neteq/timestamp_scaler.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010047#include "webrtc/modules/include/module_common_types.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000048
49// Modify the code to obtain backwards bit-exactness. Once bit-exactness is no
50// longer required, this #define should be removed (and the code that it
51// enables).
52#define LEGACY_BITEXACT
53
54namespace webrtc {
55
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +000056NetEqImpl::NetEqImpl(const NetEq::Config& config,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000057 BufferLevelFilter* buffer_level_filter,
58 DecoderDatabase* decoder_database,
59 DelayManager* delay_manager,
60 DelayPeakDetector* delay_peak_detector,
61 DtmfBuffer* dtmf_buffer,
62 DtmfToneGenerator* dtmf_tone_generator,
63 PacketBuffer* packet_buffer,
64 PayloadSplitter* payload_splitter,
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +000065 TimestampScaler* timestamp_scaler,
66 AccelerateFactory* accelerate_factory,
67 ExpandFactory* expand_factory,
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +000068 PreemptiveExpandFactory* preemptive_expand_factory,
69 bool create_components)
Tommi9090e0b2016-01-20 13:39:36 +010070 : buffer_level_filter_(buffer_level_filter),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000071 decoder_database_(decoder_database),
72 delay_manager_(delay_manager),
73 delay_peak_detector_(delay_peak_detector),
74 dtmf_buffer_(dtmf_buffer),
75 dtmf_tone_generator_(dtmf_tone_generator),
76 packet_buffer_(packet_buffer),
77 payload_splitter_(payload_splitter),
78 timestamp_scaler_(timestamp_scaler),
79 vad_(new PostDecodeVad()),
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +000080 expand_factory_(expand_factory),
81 accelerate_factory_(accelerate_factory),
82 preemptive_expand_factory_(preemptive_expand_factory),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000083 last_mode_(kModeNormal),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000084 decoded_buffer_length_(kMaxFrameSize),
85 decoded_buffer_(new int16_t[decoded_buffer_length_]),
86 playout_timestamp_(0),
87 new_codec_(false),
88 timestamp_(0),
89 reset_decoder_(false),
henrik.lundin48ed9302015-10-29 05:36:24 -070090 current_rtp_payload_type_(0xFF), // Invalid RTP payload type.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000091 current_cng_rtp_payload_type_(0xFF), // Invalid RTP payload type.
92 ssrc_(0),
93 first_packet_(true),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000094 error_code_(0),
95 decoder_error_code_(0),
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +000096 background_noise_mode_(config.background_noise_mode),
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +000097 playout_mode_(config.playout_mode),
Henrik Lundincf808d22015-05-27 14:33:29 +020098 enable_fast_accelerate_(config.enable_fast_accelerate),
henrik.lundin48ed9302015-10-29 05:36:24 -070099 nack_enabled_(false) {
Henrik Lundin905495c2015-05-25 16:58:41 +0200100 LOG(LS_INFO) << "NetEq config: " << config.ToString();
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +0000101 int fs = config.sample_rate_hz;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000102 if (fs != 8000 && fs != 16000 && fs != 32000 && fs != 48000) {
103 LOG(LS_ERROR) << "Sample rate " << fs << " Hz not supported. " <<
104 "Changing to 8000 Hz.";
105 fs = 8000;
106 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000107 fs_hz_ = fs;
108 fs_mult_ = fs / 8000;
henrik.lundind89814b2015-11-23 06:49:25 -0800109 last_output_sample_rate_hz_ = fs;
Peter Kastingdce40cf2015-08-24 14:52:23 -0700110 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000111 decoder_frame_length_ = 3 * output_size_samples_;
112 WebRtcSpl_Init();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000113 if (create_components) {
114 SetSampleRateAndChannels(fs, 1); // Default is 1 channel.
115 }
henrik.lundin9bc26672015-11-02 03:25:57 -0800116 RTC_DCHECK(!vad_->enabled());
117 if (config.enable_post_decode_vad) {
118 vad_->Enable();
119 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000120}
121
Henrik Lundind67a2192015-08-03 12:54:37 +0200122NetEqImpl::~NetEqImpl() = default;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000123
124int NetEqImpl::InsertPacket(const WebRtcRTPHeader& rtp_header,
kwibergee2bac22015-11-11 10:34:00 -0800125 rtc::ArrayView<const uint8_t> payload,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000126 uint32_t receive_timestamp) {
henrik.lundina689b442015-12-17 03:50:05 -0800127 TRACE_EVENT0("webrtc", "NetEqImpl::InsertPacket");
Tommi9090e0b2016-01-20 13:39:36 +0100128 rtc::CritScope lock(&crit_sect_);
kwibergee2bac22015-11-11 10:34:00 -0800129 int error =
130 InsertPacketInternal(rtp_header, payload, receive_timestamp, false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000131 if (error != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000132 error_code_ = error;
133 return kFail;
134 }
135 return kOK;
136}
137
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000138int NetEqImpl::InsertSyncPacket(const WebRtcRTPHeader& rtp_header,
139 uint32_t receive_timestamp) {
Tommi9090e0b2016-01-20 13:39:36 +0100140 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000141 const uint8_t kSyncPayload[] = { 's', 'y', 'n', 'c' };
kwibergee2bac22015-11-11 10:34:00 -0800142 int error =
143 InsertPacketInternal(rtp_header, kSyncPayload, receive_timestamp, true);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000144
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000145 if (error != 0) {
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000146 error_code_ = error;
147 return kFail;
148 }
149 return kOK;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000150}
151
henrik.lundin500c04b2016-03-08 02:36:04 -0800152namespace {
153void SetAudioFrameActivityAndType(bool vad_enabled,
henrik.lundin55480f52016-03-08 02:37:57 -0800154 NetEqImpl::OutputType type,
henrik.lundin500c04b2016-03-08 02:36:04 -0800155 AudioFrame::VADActivity last_vad_activity,
156 AudioFrame* audio_frame) {
157 switch (type) {
henrik.lundin55480f52016-03-08 02:37:57 -0800158 case NetEqImpl::OutputType::kNormalSpeech: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800159 audio_frame->speech_type_ = AudioFrame::kNormalSpeech;
160 audio_frame->vad_activity_ = AudioFrame::kVadActive;
161 break;
162 }
henrik.lundin55480f52016-03-08 02:37:57 -0800163 case NetEqImpl::OutputType::kVadPassive: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800164 // This should only be reached if the VAD is enabled.
165 RTC_DCHECK(vad_enabled);
166 audio_frame->speech_type_ = AudioFrame::kNormalSpeech;
167 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
168 break;
169 }
henrik.lundin55480f52016-03-08 02:37:57 -0800170 case NetEqImpl::OutputType::kCNG: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800171 audio_frame->speech_type_ = AudioFrame::kCNG;
172 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
173 break;
174 }
henrik.lundin55480f52016-03-08 02:37:57 -0800175 case NetEqImpl::OutputType::kPLC: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800176 audio_frame->speech_type_ = AudioFrame::kPLC;
177 audio_frame->vad_activity_ = last_vad_activity;
178 break;
179 }
henrik.lundin55480f52016-03-08 02:37:57 -0800180 case NetEqImpl::OutputType::kPLCCNG: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800181 audio_frame->speech_type_ = AudioFrame::kPLCCNG;
182 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
183 break;
184 }
185 default:
186 RTC_NOTREACHED();
187 }
188 if (!vad_enabled) {
189 // Always set kVadUnknown when receive VAD is inactive.
190 audio_frame->vad_activity_ = AudioFrame::kVadUnknown;
191 }
192}
henrik.lundinbc89de32016-03-08 05:20:14 -0800193} // namespace
henrik.lundin500c04b2016-03-08 02:36:04 -0800194
henrik.lundin55480f52016-03-08 02:37:57 -0800195int NetEqImpl::GetAudio(AudioFrame* audio_frame) {
henrik.lundine1ca1672016-01-08 03:50:08 -0800196 TRACE_EVENT0("webrtc", "NetEqImpl::GetAudio");
Tommi9090e0b2016-01-20 13:39:36 +0100197 rtc::CritScope lock(&crit_sect_);
henrik.lundin6d8e0112016-03-04 10:34:21 -0800198 int error = GetAudioInternal(audio_frame);
199 RTC_DCHECK_EQ(
200 audio_frame->sample_rate_hz_,
201 rtc::checked_cast<int>(audio_frame->samples_per_channel_ * 100));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000202 if (error != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000203 error_code_ = error;
204 return kFail;
205 }
henrik.lundin500c04b2016-03-08 02:36:04 -0800206 SetAudioFrameActivityAndType(vad_->enabled(), LastOutputType(),
207 last_vad_activity_, audio_frame);
208 last_vad_activity_ = audio_frame->vad_activity_;
henrik.lundin6d8e0112016-03-04 10:34:21 -0800209 last_output_sample_rate_hz_ = audio_frame->sample_rate_hz_;
henrik.lundind89814b2015-11-23 06:49:25 -0800210 RTC_DCHECK(last_output_sample_rate_hz_ == 8000 ||
211 last_output_sample_rate_hz_ == 16000 ||
212 last_output_sample_rate_hz_ == 32000 ||
213 last_output_sample_rate_hz_ == 48000)
214 << "Unexpected sample rate " << last_output_sample_rate_hz_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000215 return kOK;
216}
217
kwibergee1879c2015-10-29 06:20:28 -0700218int NetEqImpl::RegisterPayloadType(NetEqDecoder codec,
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800219 const std::string& name,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000220 uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100221 rtc::CritScope lock(&crit_sect_);
Henrik Lundind67a2192015-08-03 12:54:37 +0200222 LOG(LS_VERBOSE) << "RegisterPayloadType "
kwibergee1879c2015-10-29 06:20:28 -0700223 << static_cast<int>(rtp_payload_type) << " "
224 << static_cast<int>(codec);
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800225 int ret = decoder_database_->RegisterPayload(rtp_payload_type, codec, name);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000226 if (ret != DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000227 switch (ret) {
228 case DecoderDatabase::kInvalidRtpPayloadType:
229 error_code_ = kInvalidRtpPayloadType;
230 break;
231 case DecoderDatabase::kCodecNotSupported:
232 error_code_ = kCodecNotSupported;
233 break;
234 case DecoderDatabase::kDecoderExists:
235 error_code_ = kDecoderExists;
236 break;
237 default:
238 error_code_ = kOtherError;
239 }
240 return kFail;
241 }
242 return kOK;
243}
244
245int NetEqImpl::RegisterExternalDecoder(AudioDecoder* decoder,
kwibergee1879c2015-10-29 06:20:28 -0700246 NetEqDecoder codec,
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800247 const std::string& codec_name,
Karl Wibergd8399e62015-05-25 14:39:56 +0200248 uint8_t rtp_payload_type,
249 int sample_rate_hz) {
Tommi9090e0b2016-01-20 13:39:36 +0100250 rtc::CritScope lock(&crit_sect_);
Henrik Lundind67a2192015-08-03 12:54:37 +0200251 LOG(LS_VERBOSE) << "RegisterExternalDecoder "
kwibergee1879c2015-10-29 06:20:28 -0700252 << static_cast<int>(rtp_payload_type) << " "
253 << static_cast<int>(codec);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000254 if (!decoder) {
255 LOG(LS_ERROR) << "Cannot register external decoder with NULL pointer";
256 assert(false);
257 return kFail;
258 }
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800259 int ret = decoder_database_->InsertExternal(
260 rtp_payload_type, codec, codec_name, sample_rate_hz, decoder);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000261 if (ret != DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000262 switch (ret) {
263 case DecoderDatabase::kInvalidRtpPayloadType:
264 error_code_ = kInvalidRtpPayloadType;
265 break;
266 case DecoderDatabase::kCodecNotSupported:
267 error_code_ = kCodecNotSupported;
268 break;
269 case DecoderDatabase::kDecoderExists:
270 error_code_ = kDecoderExists;
271 break;
272 case DecoderDatabase::kInvalidSampleRate:
273 error_code_ = kInvalidSampleRate;
274 break;
275 case DecoderDatabase::kInvalidPointer:
276 error_code_ = kInvalidPointer;
277 break;
278 default:
279 error_code_ = kOtherError;
280 }
281 return kFail;
282 }
283 return kOK;
284}
285
286int NetEqImpl::RemovePayloadType(uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100287 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000288 int ret = decoder_database_->Remove(rtp_payload_type);
289 if (ret == DecoderDatabase::kOK) {
290 return kOK;
291 } else if (ret == DecoderDatabase::kDecoderNotFound) {
292 error_code_ = kDecoderNotFound;
293 } else {
294 error_code_ = kOtherError;
295 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000296 return kFail;
297}
298
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000299bool NetEqImpl::SetMinimumDelay(int delay_ms) {
Tommi9090e0b2016-01-20 13:39:36 +0100300 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000301 if (delay_ms >= 0 && delay_ms < 10000) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000302 assert(delay_manager_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000303 return delay_manager_->SetMinimumDelay(delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000304 }
305 return false;
306}
307
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000308bool NetEqImpl::SetMaximumDelay(int delay_ms) {
Tommi9090e0b2016-01-20 13:39:36 +0100309 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000310 if (delay_ms >= 0 && delay_ms < 10000) {
311 assert(delay_manager_.get());
312 return delay_manager_->SetMaximumDelay(delay_ms);
313 }
314 return false;
315}
316
317int NetEqImpl::LeastRequiredDelayMs() const {
Tommi9090e0b2016-01-20 13:39:36 +0100318 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000319 assert(delay_manager_.get());
320 return delay_manager_->least_required_delay_ms();
321}
322
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200323int NetEqImpl::SetTargetDelay() {
324 return kNotImplemented;
325}
326
327int NetEqImpl::TargetDelay() {
328 return kNotImplemented;
329}
330
henrik.lundin9c3efd02015-08-27 13:12:22 -0700331int NetEqImpl::CurrentDelayMs() const {
Tommi9090e0b2016-01-20 13:39:36 +0100332 rtc::CritScope lock(&crit_sect_);
henrik.lundin9c3efd02015-08-27 13:12:22 -0700333 if (fs_hz_ == 0)
334 return 0;
335 // Sum up the samples in the packet buffer with the future length of the sync
336 // buffer, and divide the sum by the sample rate.
337 const size_t delay_samples =
338 packet_buffer_->NumSamplesInBuffer(decoder_database_.get(),
339 decoder_frame_length_) +
340 sync_buffer_->FutureLength();
341 // The division below will truncate.
342 const int delay_ms =
343 static_cast<int>(delay_samples) / rtc::CheckedDivExact(fs_hz_, 1000);
344 return delay_ms;
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200345}
346
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000347// Deprecated.
348// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000349void NetEqImpl::SetPlayoutMode(NetEqPlayoutMode mode) {
Tommi9090e0b2016-01-20 13:39:36 +0100350 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000351 if (mode != playout_mode_) {
352 playout_mode_ = mode;
353 CreateDecisionLogic();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000354 }
355}
356
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000357// Deprecated.
358// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000359NetEqPlayoutMode NetEqImpl::PlayoutMode() const {
Tommi9090e0b2016-01-20 13:39:36 +0100360 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000361 return playout_mode_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000362}
363
364int NetEqImpl::NetworkStatistics(NetEqNetworkStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100365 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000366 assert(decoder_database_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700367 const size_t total_samples_in_buffers =
Peter Kasting728d9032015-06-11 14:31:38 -0700368 packet_buffer_->NumSamplesInBuffer(decoder_database_.get(),
369 decoder_frame_length_) +
Peter Kastingdce40cf2015-08-24 14:52:23 -0700370 sync_buffer_->FutureLength();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000371 assert(delay_manager_.get());
372 assert(decision_logic_.get());
373 stats_.GetNetworkStatistics(fs_hz_, total_samples_in_buffers,
374 decoder_frame_length_, *delay_manager_.get(),
375 *decision_logic_.get(), stats);
376 return 0;
377}
378
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000379void NetEqImpl::GetRtcpStatistics(RtcpStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100380 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000381 if (stats) {
382 rtcp_.GetStatistics(false, stats);
383 }
384}
385
386void NetEqImpl::GetRtcpStatisticsNoReset(RtcpStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100387 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000388 if (stats) {
389 rtcp_.GetStatistics(true, stats);
390 }
391}
392
393void NetEqImpl::EnableVad() {
Tommi9090e0b2016-01-20 13:39:36 +0100394 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000395 assert(vad_.get());
396 vad_->Enable();
397}
398
399void NetEqImpl::DisableVad() {
Tommi9090e0b2016-01-20 13:39:36 +0100400 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000401 assert(vad_.get());
402 vad_->Disable();
403}
404
henrik.lundin15c51e32016-04-06 08:38:56 -0700405rtc::Optional<uint32_t> NetEqImpl::GetPlayoutTimestamp() const {
Tommi9090e0b2016-01-20 13:39:36 +0100406 rtc::CritScope lock(&crit_sect_);
henrik.lundin0d96ab72016-04-06 12:28:26 -0700407 if (first_packet_ || last_mode_ == kModeRfc3389Cng ||
408 last_mode_ == kModeCodecInternalCng) {
wu@webrtc.org94454b72014-06-05 20:34:08 +0000409 // We don't have a valid RTP timestamp until we have decoded our first
henrik.lundin0d96ab72016-04-06 12:28:26 -0700410 // RTP packet. Also, the RTP timestamp is not accurate while playing CNG,
411 // which is indicated by returning an empty value.
henrik.lundin9a410dd2016-04-06 01:39:22 -0700412 return rtc::Optional<uint32_t>();
wu@webrtc.org94454b72014-06-05 20:34:08 +0000413 }
henrik.lundin9a410dd2016-04-06 01:39:22 -0700414 return rtc::Optional<uint32_t>(
415 timestamp_scaler_->ToExternal(playout_timestamp_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000416}
417
henrik.lundind89814b2015-11-23 06:49:25 -0800418int NetEqImpl::last_output_sample_rate_hz() const {
Tommi9090e0b2016-01-20 13:39:36 +0100419 rtc::CritScope lock(&crit_sect_);
henrik.lundind89814b2015-11-23 06:49:25 -0800420 return last_output_sample_rate_hz_;
421}
422
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200423int NetEqImpl::SetTargetNumberOfChannels() {
424 return kNotImplemented;
425}
426
427int NetEqImpl::SetTargetSampleRate() {
428 return kNotImplemented;
429}
430
henrik.lundin@webrtc.orgb0f4b3d2014-11-04 08:53:10 +0000431int NetEqImpl::LastError() const {
Tommi9090e0b2016-01-20 13:39:36 +0100432 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000433 return error_code_;
434}
435
436int NetEqImpl::LastDecoderError() {
Tommi9090e0b2016-01-20 13:39:36 +0100437 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000438 return decoder_error_code_;
439}
440
441void NetEqImpl::FlushBuffers() {
Tommi9090e0b2016-01-20 13:39:36 +0100442 rtc::CritScope lock(&crit_sect_);
Henrik Lundind67a2192015-08-03 12:54:37 +0200443 LOG(LS_VERBOSE) << "FlushBuffers";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000444 packet_buffer_->Flush();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000445 assert(sync_buffer_.get());
446 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000447 sync_buffer_->Flush();
448 sync_buffer_->set_next_index(sync_buffer_->next_index() -
449 expand_->overlap_length());
450 // Set to wait for new codec.
451 first_packet_ = true;
452}
453
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000454void NetEqImpl::PacketBufferStatistics(int* current_num_packets,
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000455 int* max_num_packets) const {
Tommi9090e0b2016-01-20 13:39:36 +0100456 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000457 packet_buffer_->BufferStat(current_num_packets, max_num_packets);
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000458}
459
henrik.lundin48ed9302015-10-29 05:36:24 -0700460void NetEqImpl::EnableNack(size_t max_nack_list_size) {
Tommi9090e0b2016-01-20 13:39:36 +0100461 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700462 if (!nack_enabled_) {
463 const int kNackThresholdPackets = 2;
464 nack_.reset(Nack::Create(kNackThresholdPackets));
465 nack_enabled_ = true;
466 nack_->UpdateSampleRate(fs_hz_);
467 }
468 nack_->SetMaxNackListSize(max_nack_list_size);
469}
470
471void NetEqImpl::DisableNack() {
Tommi9090e0b2016-01-20 13:39:36 +0100472 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700473 nack_.reset();
474 nack_enabled_ = false;
475}
476
477std::vector<uint16_t> NetEqImpl::GetNackList(int64_t round_trip_time_ms) const {
Tommi9090e0b2016-01-20 13:39:36 +0100478 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700479 if (!nack_enabled_) {
480 return std::vector<uint16_t>();
481 }
482 RTC_DCHECK(nack_.get());
483 return nack_->GetNackList(round_trip_time_ms);
minyue@webrtc.orgd7301772013-08-29 00:58:14 +0000484}
485
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000486const SyncBuffer* NetEqImpl::sync_buffer_for_test() const {
Tommi9090e0b2016-01-20 13:39:36 +0100487 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000488 return sync_buffer_.get();
489}
490
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000491// Methods below this line are private.
492
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000493int NetEqImpl::InsertPacketInternal(const WebRtcRTPHeader& rtp_header,
kwibergee2bac22015-11-11 10:34:00 -0800494 rtc::ArrayView<const uint8_t> payload,
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000495 uint32_t receive_timestamp,
496 bool is_sync_packet) {
kwibergee2bac22015-11-11 10:34:00 -0800497 if (payload.empty()) {
498 LOG_F(LS_ERROR) << "payload is empty";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000499 return kInvalidPointer;
500 }
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000501 // Sanity checks for sync-packets.
502 if (is_sync_packet) {
503 if (decoder_database_->IsDtmf(rtp_header.header.payloadType) ||
504 decoder_database_->IsRed(rtp_header.header.payloadType) ||
505 decoder_database_->IsComfortNoise(rtp_header.header.payloadType)) {
506 LOG_F(LS_ERROR) << "Sync-packet with an unacceptable payload type "
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000507 << static_cast<int>(rtp_header.header.payloadType);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000508 return kSyncPacketNotAccepted;
509 }
510 if (first_packet_ ||
511 rtp_header.header.payloadType != current_rtp_payload_type_ ||
512 rtp_header.header.ssrc != ssrc_) {
513 // Even if |current_rtp_payload_type_| is 0xFF, sync-packet isn't
514 // accepted.
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000515 LOG_F(LS_ERROR)
516 << "Changing codec, SSRC or first packet with sync-packet.";
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000517 return kSyncPacketNotAccepted;
518 }
519 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000520 PacketList packet_list;
521 RTPHeader main_header;
522 {
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000523 // Convert to Packet.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000524 // Create |packet| within this separate scope, since it should not be used
525 // directly once it's been inserted in the packet list. This way, |packet|
526 // is not defined outside of this block.
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000527 Packet* packet = new Packet;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000528 packet->header.markerBit = false;
529 packet->header.payloadType = rtp_header.header.payloadType;
530 packet->header.sequenceNumber = rtp_header.header.sequenceNumber;
531 packet->header.timestamp = rtp_header.header.timestamp;
532 packet->header.ssrc = rtp_header.header.ssrc;
533 packet->header.numCSRCs = 0;
kwibergee2bac22015-11-11 10:34:00 -0800534 packet->payload_length = payload.size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000535 packet->primary = true;
536 packet->waiting_time = 0;
537 packet->payload = new uint8_t[packet->payload_length];
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000538 packet->sync_packet = is_sync_packet;
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +0000539 if (!packet->payload) {
540 LOG_F(LS_ERROR) << "Payload pointer is NULL.";
541 }
kwibergee2bac22015-11-11 10:34:00 -0800542 assert(!payload.empty()); // Already checked above.
543 memcpy(packet->payload, payload.data(), packet->payload_length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000544 // Insert packet in a packet list.
545 packet_list.push_back(packet);
546 // Save main payloads header for later.
547 memcpy(&main_header, &packet->header, sizeof(main_header));
548 }
549
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000550 bool update_sample_rate_and_channels = false;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000551 // Reinitialize NetEq if it's needed (changed SSRC or first call).
552 if ((main_header.ssrc != ssrc_) || first_packet_) {
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000553 // Note: |first_packet_| will be cleared further down in this method, once
554 // the packet has been successfully inserted into the packet buffer.
555
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000556 rtcp_.Init(main_header.sequenceNumber);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000557
558 // Flush the packet buffer and DTMF buffer.
559 packet_buffer_->Flush();
560 dtmf_buffer_->Flush();
561
562 // Store new SSRC.
563 ssrc_ = main_header.ssrc;
564
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000565 // Update audio buffer timestamp.
566 sync_buffer_->IncreaseEndTimestamp(main_header.timestamp - timestamp_);
567
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000568 // Update codecs.
569 timestamp_ = main_header.timestamp;
570 current_rtp_payload_type_ = main_header.payloadType;
571
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000572 // Reset timestamp scaling.
573 timestamp_scaler_->Reset();
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000574
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000575 // Trigger an update of sampling rate and the number of channels.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000576 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000577 }
578
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000579 // Update RTCP statistics, only for regular packets.
580 if (!is_sync_packet)
581 rtcp_.Update(main_header, receive_timestamp);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000582
583 // Check for RED payload type, and separate payloads into several packets.
584 if (decoder_database_->IsRed(main_header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000585 assert(!is_sync_packet); // We had a sanity check for this.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000586 if (payload_splitter_->SplitRed(&packet_list) != PayloadSplitter::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000587 PacketBuffer::DeleteAllPackets(&packet_list);
588 return kRedundancySplitError;
589 }
590 // Only accept a few RED payloads of the same type as the main data,
591 // DTMF events and CNG.
592 payload_splitter_->CheckRedPayloads(&packet_list, *decoder_database_);
593 // Update the stored main payload header since the main payload has now
594 // changed.
595 memcpy(&main_header, &packet_list.front()->header, sizeof(main_header));
596 }
597
598 // Check payload types.
599 if (decoder_database_->CheckPayloadTypes(packet_list) ==
600 DecoderDatabase::kDecoderNotFound) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000601 PacketBuffer::DeleteAllPackets(&packet_list);
602 return kUnknownRtpPayloadType;
603 }
604
605 // Scale timestamp to internal domain (only for some codecs).
606 timestamp_scaler_->ToInternal(&packet_list);
607
608 // Process DTMF payloads. Cycle through the list of packets, and pick out any
609 // DTMF payloads found.
610 PacketList::iterator it = packet_list.begin();
611 while (it != packet_list.end()) {
612 Packet* current_packet = (*it);
613 assert(current_packet);
614 assert(current_packet->payload);
615 if (decoder_database_->IsDtmf(current_packet->header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000616 assert(!current_packet->sync_packet); // We had a sanity check for this.
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000617 DtmfEvent event;
618 int ret = DtmfBuffer::ParseEvent(
619 current_packet->header.timestamp,
620 current_packet->payload,
621 current_packet->payload_length,
622 &event);
623 if (ret != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000624 PacketBuffer::DeleteAllPackets(&packet_list);
625 return kDtmfParsingError;
626 }
627 if (dtmf_buffer_->InsertEvent(event) != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000628 PacketBuffer::DeleteAllPackets(&packet_list);
629 return kDtmfInsertError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000630 }
631 // TODO(hlundin): Let the destructor of Packet handle the payload.
632 delete [] current_packet->payload;
633 delete current_packet;
634 it = packet_list.erase(it);
635 } else {
636 ++it;
637 }
638 }
639
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000640 // Check for FEC in packets, and separate payloads into several packets.
641 int ret = payload_splitter_->SplitFec(&packet_list, decoder_database_.get());
642 if (ret != PayloadSplitter::kOK) {
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000643 PacketBuffer::DeleteAllPackets(&packet_list);
644 switch (ret) {
645 case PayloadSplitter::kUnknownPayloadType:
646 return kUnknownRtpPayloadType;
647 default:
648 return kOtherError;
649 }
650 }
651
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000652 // Split payloads into smaller chunks. This also verifies that all payloads
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000653 // are of a known payload type. SplitAudio() method is protected against
654 // sync-packets.
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +0000655 ret = payload_splitter_->SplitAudio(&packet_list, *decoder_database_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000656 if (ret != PayloadSplitter::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000657 PacketBuffer::DeleteAllPackets(&packet_list);
658 switch (ret) {
659 case PayloadSplitter::kUnknownPayloadType:
660 return kUnknownRtpPayloadType;
661 case PayloadSplitter::kFrameSplitError:
662 return kFrameSplitError;
663 default:
664 return kOtherError;
665 }
666 }
667
ossu97ba30e2016-04-25 07:55:58 -0700668 // Update bandwidth estimate, if the packet is not sync-packet nor comfort
669 // noise.
670 if (!packet_list.empty() && !packet_list.front()->sync_packet &&
671 !decoder_database_->IsComfortNoise(main_header.payloadType)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000672 // The list can be empty here if we got nothing but DTMF payloads.
673 AudioDecoder* decoder =
674 decoder_database_->GetDecoder(main_header.payloadType);
675 assert(decoder); // Should always get a valid object, since we have
ossu97ba30e2016-04-25 07:55:58 -0700676 // already checked that the payload types are known.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000677 decoder->IncomingPacket(packet_list.front()->payload,
678 packet_list.front()->payload_length,
679 packet_list.front()->header.sequenceNumber,
680 packet_list.front()->header.timestamp,
681 receive_timestamp);
682 }
683
henrik.lundin48ed9302015-10-29 05:36:24 -0700684 if (nack_enabled_) {
685 RTC_DCHECK(nack_);
686 if (update_sample_rate_and_channels) {
687 nack_->Reset();
688 }
689 nack_->UpdateLastReceivedPacket(packet_list.front()->header.sequenceNumber,
690 packet_list.front()->header.timestamp);
691 }
692
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000693 // Insert packets in buffer.
henrik.lundin116c84e2015-08-27 13:14:48 -0700694 const size_t buffer_length_before_insert =
695 packet_buffer_->NumPacketsInBuffer();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000696 ret = packet_buffer_->InsertPacketList(
697 &packet_list,
698 *decoder_database_,
699 &current_rtp_payload_type_,
700 &current_cng_rtp_payload_type_);
701 if (ret == PacketBuffer::kFlushed) {
702 // Reset DSP timestamp etc. if packet buffer flushed.
703 new_codec_ = true;
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000704 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000705 } else if (ret != PacketBuffer::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000706 PacketBuffer::DeleteAllPackets(&packet_list);
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000707 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000708 }
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000709
710 if (first_packet_) {
711 first_packet_ = false;
712 // Update the codec on the next GetAudio call.
713 new_codec_ = true;
714 }
715
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000716 if (current_rtp_payload_type_ != 0xFF) {
717 const DecoderDatabase::DecoderInfo* dec_info =
718 decoder_database_->GetDecoderInfo(current_rtp_payload_type_);
719 if (!dec_info) {
720 assert(false); // Already checked that the payload type is known.
721 }
722 }
723
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000724 if (update_sample_rate_and_channels && !packet_buffer_->Empty()) {
725 // We do not use |current_rtp_payload_type_| to |set payload_type|, but
726 // get the next RTP header from |packet_buffer_| to obtain the payload type.
727 // The reason for it is the following corner case. If NetEq receives a
728 // CNG packet with a sample rate different than the current CNG then it
729 // flushes its buffer, assuming send codec must have been changed. However,
730 // payload type of the hypothetically new send codec is not known.
731 const RTPHeader* rtp_header = packet_buffer_->NextRtpHeader();
732 assert(rtp_header);
733 int payload_type = rtp_header->payloadType;
ossu97ba30e2016-04-25 07:55:58 -0700734 size_t channels = 1;
735 if (!decoder_database_->IsComfortNoise(payload_type)) {
736 AudioDecoder* decoder = decoder_database_->GetDecoder(payload_type);
737 assert(decoder); // Payloads are already checked to be valid.
738 channels = decoder->Channels();
739 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000740 const DecoderDatabase::DecoderInfo* decoder_info =
741 decoder_database_->GetDecoderInfo(payload_type);
742 assert(decoder_info);
743 if (decoder_info->fs_hz != fs_hz_ ||
ossu97ba30e2016-04-25 07:55:58 -0700744 channels != algorithm_buffer_->Channels()) {
745 SetSampleRateAndChannels(decoder_info->fs_hz, channels);
henrik.lundin48ed9302015-10-29 05:36:24 -0700746 }
747 if (nack_enabled_) {
748 RTC_DCHECK(nack_);
749 // Update the sample rate even if the rate is not new, because of Reset().
750 nack_->UpdateSampleRate(fs_hz_);
751 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000752 }
753
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000754 // TODO(hlundin): Move this code to DelayManager class.
755 const DecoderDatabase::DecoderInfo* dec_info =
756 decoder_database_->GetDecoderInfo(main_header.payloadType);
757 assert(dec_info); // Already checked that the payload type is known.
758 delay_manager_->LastDecoderType(dec_info->codec_type);
759 if (delay_manager_->last_pack_cng_or_dtmf() == 0) {
760 // Calculate the total speech length carried in each packet.
henrik.lundin116c84e2015-08-27 13:14:48 -0700761 const size_t buffer_length_after_insert =
762 packet_buffer_->NumPacketsInBuffer();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000763
henrik.lundin116c84e2015-08-27 13:14:48 -0700764 if (buffer_length_after_insert > buffer_length_before_insert) {
765 const size_t packet_length_samples =
766 (buffer_length_after_insert - buffer_length_before_insert) *
767 decoder_frame_length_;
768 if (packet_length_samples != decision_logic_->packet_length_samples()) {
769 decision_logic_->set_packet_length_samples(packet_length_samples);
770 delay_manager_->SetPacketAudioLength(
771 rtc::checked_cast<int>((1000 * packet_length_samples) / fs_hz_));
772 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000773 }
774
775 // Update statistics.
pbos@webrtc.org0946a562013-04-09 00:28:06 +0000776 if ((int32_t) (main_header.timestamp - timestamp_) >= 0 &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000777 !new_codec_) {
778 // Only update statistics if incoming packet is not older than last played
779 // out packet, and if new codec flag is not set.
780 delay_manager_->Update(main_header.sequenceNumber, main_header.timestamp,
781 fs_hz_);
782 }
783 } else if (delay_manager_->last_pack_cng_or_dtmf() == -1) {
784 // This is first "normal" packet after CNG or DTMF.
785 // Reset packet time counter and measure time until next packet,
786 // but don't update statistics.
787 delay_manager_->set_last_pack_cng_or_dtmf(0);
788 delay_manager_->ResetPacketIatCount();
789 }
790 return 0;
791}
792
henrik.lundin6d8e0112016-03-04 10:34:21 -0800793int NetEqImpl::GetAudioInternal(AudioFrame* audio_frame) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000794 PacketList packet_list;
795 DtmfEvent dtmf_event;
796 Operations operation;
797 bool play_dtmf;
798 int return_value = GetDecision(&operation, &packet_list, &dtmf_event,
799 &play_dtmf);
800 if (return_value != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000801 last_mode_ = kModeError;
802 return return_value;
803 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000804
805 AudioDecoder::SpeechType speech_type;
806 int length = 0;
807 int decode_return_value = Decode(&packet_list, &operation,
808 &length, &speech_type);
809
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000810 assert(vad_.get());
811 bool sid_frame_available =
812 (operation == kRfc3389Cng && !packet_list.empty());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700813 vad_->Update(decoded_buffer_.get(), static_cast<size_t>(length), speech_type,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000814 sid_frame_available, fs_hz_);
815
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000816 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000817 switch (operation) {
818 case kNormal: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000819 DoNormal(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000820 break;
821 }
822 case kMerge: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000823 DoMerge(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000824 break;
825 }
826 case kExpand: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000827 return_value = DoExpand(play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000828 break;
829 }
Henrik Lundincf808d22015-05-27 14:33:29 +0200830 case kAccelerate:
831 case kFastAccelerate: {
832 const bool fast_accelerate =
833 enable_fast_accelerate_ && (operation == kFastAccelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000834 return_value = DoAccelerate(decoded_buffer_.get(), length, speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +0200835 play_dtmf, fast_accelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000836 break;
837 }
838 case kPreemptiveExpand: {
839 return_value = DoPreemptiveExpand(decoded_buffer_.get(), length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000840 speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000841 break;
842 }
843 case kRfc3389Cng:
844 case kRfc3389CngNoPacket: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000845 return_value = DoRfc3389Cng(&packet_list, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000846 break;
847 }
848 case kCodecInternalCng: {
849 // This handles the case when there is no transmission and the decoder
850 // should produce internal comfort noise.
851 // TODO(hlundin): Write test for codec-internal CNG.
minyuel6d92bf52015-09-23 15:20:39 +0200852 DoCodecInternalCng(decoded_buffer_.get(), length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000853 break;
854 }
855 case kDtmf: {
856 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000857 return_value = DoDtmf(dtmf_event, &play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000858 break;
859 }
860 case kAlternativePlc: {
861 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000862 DoAlternativePlc(false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000863 break;
864 }
865 case kAlternativePlcIncreaseTimestamp: {
866 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000867 DoAlternativePlc(true);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000868 break;
869 }
870 case kAudioRepetitionIncreaseTimestamp: {
871 // TODO(hlundin): Write test for this.
Peter Kastingb7e50542015-06-11 12:55:50 -0700872 sync_buffer_->IncreaseEndTimestamp(
873 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000874 // Skipping break on purpose. Execution should move on into the
875 // next case.
kjellander@webrtc.org7d2b6a92015-01-28 18:37:58 +0000876 FALLTHROUGH();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000877 }
878 case kAudioRepetition: {
879 // TODO(hlundin): Write test for this.
880 // Copy last |output_size_samples_| from |sync_buffer_| to
881 // |algorithm_buffer|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000882 algorithm_buffer_->PushBackFromIndex(
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000883 *sync_buffer_, sync_buffer_->Size() - output_size_samples_);
884 expand_->Reset();
885 break;
886 }
887 case kUndefined: {
Henrik Lundind67a2192015-08-03 12:54:37 +0200888 LOG(LS_ERROR) << "Invalid operation kUndefined.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000889 assert(false); // This should not happen.
890 last_mode_ = kModeError;
891 return kInvalidOperation;
892 }
893 } // End of switch.
894 if (return_value < 0) {
895 return return_value;
896 }
897
898 if (last_mode_ != kModeRfc3389Cng) {
899 comfort_noise_->Reset();
900 }
901
902 // Copy from |algorithm_buffer| to |sync_buffer_|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000903 sync_buffer_->PushBack(*algorithm_buffer_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000904
905 // Extract data from |sync_buffer_| to |output|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000906 size_t num_output_samples_per_channel = output_size_samples_;
907 size_t num_output_samples = output_size_samples_ * sync_buffer_->Channels();
henrik.lundin6d8e0112016-03-04 10:34:21 -0800908 if (num_output_samples > AudioFrame::kMaxDataSizeSamples) {
909 LOG(LS_WARNING) << "Output array is too short. "
910 << AudioFrame::kMaxDataSizeSamples << " < "
911 << output_size_samples_ << " * "
912 << sync_buffer_->Channels();
913 num_output_samples = AudioFrame::kMaxDataSizeSamples;
914 num_output_samples_per_channel =
915 AudioFrame::kMaxDataSizeSamples / sync_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000916 }
henrik.lundin6d8e0112016-03-04 10:34:21 -0800917 sync_buffer_->GetNextAudioInterleaved(num_output_samples_per_channel,
918 audio_frame);
919 audio_frame->sample_rate_hz_ = fs_hz_;
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200920 if (sync_buffer_->FutureLength() < expand_->overlap_length()) {
921 // The sync buffer should always contain |overlap_length| samples, but now
922 // too many samples have been extracted. Reinstall the |overlap_length|
923 // lookahead by moving the index.
924 const size_t missing_lookahead_samples =
925 expand_->overlap_length() - sync_buffer_->FutureLength();
henrikg91d6ede2015-09-17 00:24:34 -0700926 RTC_DCHECK_GE(sync_buffer_->next_index(), missing_lookahead_samples);
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200927 sync_buffer_->set_next_index(sync_buffer_->next_index() -
928 missing_lookahead_samples);
929 }
henrik.lundin6d8e0112016-03-04 10:34:21 -0800930 if (audio_frame->samples_per_channel_ != output_size_samples_) {
931 LOG(LS_ERROR) << "audio_frame->samples_per_channel_ ("
932 << audio_frame->samples_per_channel_
Henrik Lundind67a2192015-08-03 12:54:37 +0200933 << ") != output_size_samples_ (" << output_size_samples_
934 << ")";
minyue@webrtc.orgdb1cefc2013-08-13 01:39:21 +0000935 // TODO(minyue): treatment of under-run, filling zeros
henrik.lundin6d8e0112016-03-04 10:34:21 -0800936 memset(audio_frame->data_, 0, num_output_samples * sizeof(int16_t));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000937 return kSampleUnderrun;
938 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000939
940 // Should always have overlap samples left in the |sync_buffer_|.
henrikg91d6ede2015-09-17 00:24:34 -0700941 RTC_DCHECK_GE(sync_buffer_->FutureLength(), expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000942
943 if (play_dtmf) {
henrik.lundin6d8e0112016-03-04 10:34:21 -0800944 return_value =
945 DtmfOverdub(dtmf_event, sync_buffer_->Channels(), audio_frame->data_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000946 }
947
948 // Update the background noise parameters if last operation wrote data
949 // straight from the decoder to the |sync_buffer_|. That is, none of the
950 // operations that modify the signal can be followed by a parameter update.
951 if ((last_mode_ == kModeNormal) ||
952 (last_mode_ == kModeAccelerateFail) ||
953 (last_mode_ == kModePreemptiveExpandFail) ||
954 (last_mode_ == kModeRfc3389Cng) ||
955 (last_mode_ == kModeCodecInternalCng)) {
956 background_noise_->Update(*sync_buffer_, *vad_.get());
957 }
958
959 if (operation == kDtmf) {
960 // DTMF data was written the end of |sync_buffer_|.
961 // Update index to end of DTMF data in |sync_buffer_|.
962 sync_buffer_->set_dtmf_index(sync_buffer_->Size());
963 }
964
henrik.lundin@webrtc.orged865b52014-03-06 10:28:07 +0000965 if (last_mode_ != kModeExpand) {
966 // If last operation was not expand, calculate the |playout_timestamp_| from
967 // the |sync_buffer_|. However, do not update the |playout_timestamp_| if it
968 // would be moved "backwards".
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000969 uint32_t temp_timestamp = sync_buffer_->end_timestamp() -
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000970 static_cast<uint32_t>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000971 if (static_cast<int32_t>(temp_timestamp - playout_timestamp_) > 0) {
972 playout_timestamp_ = temp_timestamp;
973 }
974 } else {
975 // Use dead reckoning to estimate the |playout_timestamp_|.
Peter Kastingb7e50542015-06-11 12:55:50 -0700976 playout_timestamp_ += static_cast<uint32_t>(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000977 }
henrik.lundin15c51e32016-04-06 08:38:56 -0700978 // Set the timestamp in the audio frame to zero before the first packet has
979 // been inserted. Otherwise, subtract the frame size in samples to get the
980 // timestamp of the first sample in the frame (playout_timestamp_ is the
981 // last + 1).
982 audio_frame->timestamp_ =
983 first_packet_
984 ? 0
985 : timestamp_scaler_->ToExternal(playout_timestamp_) -
986 static_cast<uint32_t>(audio_frame->samples_per_channel_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000987
988 if (decode_return_value) return decode_return_value;
989 return return_value;
990}
991
992int NetEqImpl::GetDecision(Operations* operation,
993 PacketList* packet_list,
994 DtmfEvent* dtmf_event,
995 bool* play_dtmf) {
996 // Initialize output variables.
997 *play_dtmf = false;
998 *operation = kUndefined;
999
1000 // Increment time counters.
1001 packet_buffer_->IncrementWaitingTimes();
1002 stats_.IncreaseCounter(output_size_samples_, fs_hz_);
1003
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001004 assert(sync_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001005 uint32_t end_timestamp = sync_buffer_->end_timestamp();
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001006 if (!new_codec_) {
1007 const uint32_t five_seconds_samples = 5 * fs_hz_;
1008 packet_buffer_->DiscardOldPackets(end_timestamp, five_seconds_samples);
1009 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001010 const RTPHeader* header = packet_buffer_->NextRtpHeader();
1011
henrik.lundin@webrtc.orgca8cb952014-03-12 10:26:52 +00001012 if (decision_logic_->CngRfc3389On() || last_mode_ == kModeRfc3389Cng) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001013 // Because of timestamp peculiarities, we have to "manually" disallow using
1014 // a CNG packet with the same timestamp as the one that was last played.
1015 // This can happen when using redundancy and will cause the timing to shift.
henrik.lundin@webrtc.org24779fe2014-03-14 12:40:05 +00001016 while (header && decoder_database_->IsComfortNoise(header->payloadType) &&
1017 (end_timestamp >= header->timestamp ||
1018 end_timestamp + decision_logic_->generated_noise_samples() >
1019 header->timestamp)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001020 // Don't use this packet, discard it.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001021 if (packet_buffer_->DiscardNextPacket() != PacketBuffer::kOK) {
1022 assert(false); // Must be ok by design.
1023 }
1024 // Check buffer again.
1025 if (!new_codec_) {
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001026 packet_buffer_->DiscardOldPackets(end_timestamp, 5 * fs_hz_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001027 }
1028 header = packet_buffer_->NextRtpHeader();
1029 }
1030 }
1031
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001032 assert(expand_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001033 const int samples_left = static_cast<int>(sync_buffer_->FutureLength() -
1034 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001035 if (last_mode_ == kModeAccelerateSuccess ||
1036 last_mode_ == kModeAccelerateLowEnergy ||
1037 last_mode_ == kModePreemptiveExpandSuccess ||
1038 last_mode_ == kModePreemptiveExpandLowEnergy) {
1039 // Subtract (samples_left + output_size_samples_) from sampleMemory.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001040 decision_logic_->AddSampleMemory(
1041 -(samples_left + rtc::checked_cast<int>(output_size_samples_)));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001042 }
1043
1044 // Check if it is time to play a DTMF event.
Peter Kastingb7e50542015-06-11 12:55:50 -07001045 if (dtmf_buffer_->GetEvent(
1046 static_cast<uint32_t>(
1047 end_timestamp + decision_logic_->generated_noise_samples()),
1048 dtmf_event)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001049 *play_dtmf = true;
1050 }
1051
1052 // Get instruction.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001053 assert(sync_buffer_.get());
1054 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001055 *operation = decision_logic_->GetDecision(*sync_buffer_,
1056 *expand_,
1057 decoder_frame_length_,
1058 header,
1059 last_mode_,
1060 *play_dtmf,
1061 &reset_decoder_);
1062
1063 // Check if we already have enough samples in the |sync_buffer_|. If so,
1064 // change decision to normal, unless the decision was merge, accelerate, or
1065 // preemptive expand.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001066 if (samples_left >= rtc::checked_cast<int>(output_size_samples_) &&
1067 *operation != kMerge &&
1068 *operation != kAccelerate &&
1069 *operation != kFastAccelerate &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001070 *operation != kPreemptiveExpand) {
1071 *operation = kNormal;
1072 return 0;
1073 }
1074
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001075 decision_logic_->ExpandDecision(*operation);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001076
1077 // Check conditions for reset.
1078 if (new_codec_ || *operation == kUndefined) {
1079 // The only valid reason to get kUndefined is that new_codec_ is set.
1080 assert(new_codec_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001081 if (*play_dtmf && !header) {
1082 timestamp_ = dtmf_event->timestamp;
1083 } else {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001084 if (!header) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001085 LOG(LS_ERROR) << "Packet missing where it shouldn't.";
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001086 return -1;
1087 }
1088 timestamp_ = header->timestamp;
1089 if (*operation == kRfc3389CngNoPacket
1090#ifndef LEGACY_BITEXACT
1091 // Without this check, it can happen that a non-CNG packet is sent to
1092 // the CNG decoder as if it was a SID frame. This is clearly a bug,
1093 // but is kept for now to maintain bit-exactness with the test
1094 // vectors.
1095 && decoder_database_->IsComfortNoise(header->payloadType)
1096#endif
1097 ) {
1098 // Change decision to CNG packet, since we do have a CNG packet, but it
1099 // was considered too early to use. Now, use it anyway.
1100 *operation = kRfc3389Cng;
1101 } else if (*operation != kRfc3389Cng) {
1102 *operation = kNormal;
1103 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001104 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001105 // Adjust |sync_buffer_| timestamp before setting |end_timestamp| to the
1106 // new value.
1107 sync_buffer_->IncreaseEndTimestamp(timestamp_ - end_timestamp);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001108 end_timestamp = timestamp_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001109 new_codec_ = false;
1110 decision_logic_->SoftReset();
1111 buffer_level_filter_->Reset();
1112 delay_manager_->Reset();
1113 stats_.ResetMcu();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001114 }
1115
Peter Kastingdce40cf2015-08-24 14:52:23 -07001116 size_t required_samples = output_size_samples_;
1117 const size_t samples_10_ms = static_cast<size_t>(80 * fs_mult_);
1118 const size_t samples_20_ms = 2 * samples_10_ms;
1119 const size_t samples_30_ms = 3 * samples_10_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001120
1121 switch (*operation) {
1122 case kExpand: {
1123 timestamp_ = end_timestamp;
1124 return 0;
1125 }
1126 case kRfc3389CngNoPacket:
1127 case kCodecInternalCng: {
1128 return 0;
1129 }
1130 case kDtmf: {
1131 // TODO(hlundin): Write test for this.
1132 // Update timestamp.
1133 timestamp_ = end_timestamp;
1134 if (decision_logic_->generated_noise_samples() > 0 &&
1135 last_mode_ != kModeDtmf) {
1136 // Make a jump in timestamp due to the recently played comfort noise.
Peter Kastingb7e50542015-06-11 12:55:50 -07001137 uint32_t timestamp_jump =
1138 static_cast<uint32_t>(decision_logic_->generated_noise_samples());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001139 sync_buffer_->IncreaseEndTimestamp(timestamp_jump);
1140 timestamp_ += timestamp_jump;
1141 }
1142 decision_logic_->set_generated_noise_samples(0);
1143 return 0;
1144 }
Henrik Lundincf808d22015-05-27 14:33:29 +02001145 case kAccelerate:
1146 case kFastAccelerate: {
1147 // In order to do an accelerate we need at least 30 ms of audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001148 if (samples_left >= static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001149 // Already have enough data, so we do not need to extract any more.
1150 decision_logic_->set_sample_memory(samples_left);
1151 decision_logic_->set_prev_time_scale(true);
1152 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001153 } else if (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001154 decoder_frame_length_ >= samples_30_ms) {
1155 // Avoid decoding more data as it might overflow the playout buffer.
1156 *operation = kNormal;
1157 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001158 } else if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001159 decoder_frame_length_ < samples_30_ms) {
1160 // Build up decoded data by decoding at least 20 ms of audio data. Do
1161 // not perform accelerate yet, but wait until we only need to do one
1162 // decoding.
1163 required_samples = 2 * output_size_samples_;
1164 *operation = kNormal;
1165 }
1166 // If none of the above is true, we have one of two possible situations:
1167 // (1) 20 ms <= samples_left < 30 ms and decoder_frame_length_ < 30 ms; or
1168 // (2) samples_left < 10 ms and decoder_frame_length_ >= 30 ms.
1169 // In either case, we move on with the accelerate decision, and decode one
1170 // frame now.
1171 break;
1172 }
1173 case kPreemptiveExpand: {
1174 // In order to do a preemptive expand we need at least 30 ms of decoded
1175 // audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001176 if ((samples_left >= static_cast<int>(samples_30_ms)) ||
1177 (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001178 decoder_frame_length_ >= samples_30_ms)) {
1179 // Already have enough data, so we do not need to extract any more.
1180 // Or, avoid decoding more data as it might overflow the playout buffer.
1181 // Still try preemptive expand, though.
1182 decision_logic_->set_sample_memory(samples_left);
1183 decision_logic_->set_prev_time_scale(true);
1184 return 0;
1185 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07001186 if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001187 decoder_frame_length_ < samples_30_ms) {
1188 // Build up decoded data by decoding at least 20 ms of audio data.
1189 // Still try to perform preemptive expand.
1190 required_samples = 2 * output_size_samples_;
1191 }
1192 // Move on with the preemptive expand decision.
1193 break;
1194 }
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001195 case kMerge: {
1196 required_samples =
1197 std::max(merge_->RequiredFutureSamples(), required_samples);
1198 break;
1199 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001200 default: {
1201 // Do nothing.
1202 }
1203 }
1204
1205 // Get packets from buffer.
1206 int extracted_samples = 0;
1207 if (header &&
1208 *operation != kAlternativePlc &&
1209 *operation != kAlternativePlcIncreaseTimestamp &&
1210 *operation != kAudioRepetition &&
1211 *operation != kAudioRepetitionIncreaseTimestamp) {
1212 sync_buffer_->IncreaseEndTimestamp(header->timestamp - end_timestamp);
1213 if (decision_logic_->CngOff()) {
1214 // Adjustment of timestamp only corresponds to an actual packet loss
1215 // if comfort noise is not played. If comfort noise was just played,
1216 // this adjustment of timestamp is only done to get back in sync with the
1217 // stream timestamp; no loss to report.
1218 stats_.LostSamples(header->timestamp - end_timestamp);
1219 }
1220
1221 if (*operation != kRfc3389Cng) {
1222 // We are about to decode and use a non-CNG packet.
1223 decision_logic_->SetCngOff();
1224 }
1225 // Reset CNG timestamp as a new packet will be delivered.
1226 // (Also if this is a CNG packet, since playedOutTS is updated.)
1227 decision_logic_->set_generated_noise_samples(0);
1228
1229 extracted_samples = ExtractPackets(required_samples, packet_list);
1230 if (extracted_samples < 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001231 return kPacketBufferCorruption;
1232 }
1233 }
1234
Henrik Lundincf808d22015-05-27 14:33:29 +02001235 if (*operation == kAccelerate || *operation == kFastAccelerate ||
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001236 *operation == kPreemptiveExpand) {
1237 decision_logic_->set_sample_memory(samples_left + extracted_samples);
1238 decision_logic_->set_prev_time_scale(true);
1239 }
1240
Henrik Lundincf808d22015-05-27 14:33:29 +02001241 if (*operation == kAccelerate || *operation == kFastAccelerate) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001242 // Check that we have enough data (30ms) to do accelerate.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001243 if (extracted_samples + samples_left < static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001244 // TODO(hlundin): Write test for this.
1245 // Not enough, do normal operation instead.
1246 *operation = kNormal;
1247 }
1248 }
1249
1250 timestamp_ = end_timestamp;
1251 return 0;
1252}
1253
1254int NetEqImpl::Decode(PacketList* packet_list, Operations* operation,
1255 int* decoded_length,
1256 AudioDecoder::SpeechType* speech_type) {
1257 *speech_type = AudioDecoder::kSpeech;
minyuel6d92bf52015-09-23 15:20:39 +02001258
1259 // When packet_list is empty, we may be in kCodecInternalCng mode, and for
1260 // that we use current active decoder.
1261 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1262
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001263 if (!packet_list->empty()) {
1264 const Packet* packet = packet_list->front();
pkasting@chromium.org0e81fdf2015-02-02 23:54:03 +00001265 uint8_t payload_type = packet->header.payloadType;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001266 if (!decoder_database_->IsComfortNoise(payload_type)) {
1267 decoder = decoder_database_->GetDecoder(payload_type);
1268 assert(decoder);
1269 if (!decoder) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001270 LOG(LS_WARNING) << "Unknown payload type "
1271 << static_cast<int>(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001272 PacketBuffer::DeleteAllPackets(packet_list);
1273 return kDecoderNotFound;
1274 }
1275 bool decoder_changed;
1276 decoder_database_->SetActiveDecoder(payload_type, &decoder_changed);
1277 if (decoder_changed) {
1278 // We have a new decoder. Re-init some values.
1279 const DecoderDatabase::DecoderInfo* decoder_info = decoder_database_
1280 ->GetDecoderInfo(payload_type);
1281 assert(decoder_info);
1282 if (!decoder_info) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001283 LOG(LS_WARNING) << "Unknown payload type "
1284 << static_cast<int>(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001285 PacketBuffer::DeleteAllPackets(packet_list);
1286 return kDecoderNotFound;
1287 }
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001288 // If sampling rate or number of channels has changed, we need to make
1289 // a reset.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001290 if (decoder_info->fs_hz != fs_hz_ ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001291 decoder->Channels() != algorithm_buffer_->Channels()) {
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001292 // TODO(tlegrand): Add unittest to cover this event.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001293 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->Channels());
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001294 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001295 sync_buffer_->set_end_timestamp(timestamp_);
1296 playout_timestamp_ = timestamp_;
1297 }
1298 }
1299 }
1300
1301 if (reset_decoder_) {
1302 // TODO(hlundin): Write test for this.
Karl Wiberg43766482015-08-27 15:22:11 +02001303 if (decoder)
1304 decoder->Reset();
1305
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001306 // Reset comfort noise decoder.
ossu97ba30e2016-04-25 07:55:58 -07001307 ComfortNoiseDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02001308 if (cng_decoder)
1309 cng_decoder->Reset();
1310
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001311 reset_decoder_ = false;
1312 }
1313
1314#ifdef LEGACY_BITEXACT
1315 // Due to a bug in old SignalMCU, it could happen that CNG operation was
1316 // decided, but a speech packet was provided. The speech packet will be used
1317 // to update the comfort noise decoder, as if it was a SID frame, which is
1318 // clearly wrong.
1319 if (*operation == kRfc3389Cng) {
1320 return 0;
1321 }
1322#endif
1323
1324 *decoded_length = 0;
1325 // Update codec-internal PLC state.
1326 if ((*operation == kMerge) && decoder && decoder->HasDecodePlc()) {
1327 decoder->DecodePlc(1, &decoded_buffer_[*decoded_length]);
1328 }
1329
minyuel6d92bf52015-09-23 15:20:39 +02001330 int return_value;
1331 if (*operation == kCodecInternalCng) {
1332 RTC_DCHECK(packet_list->empty());
1333 return_value = DecodeCng(decoder, decoded_length, speech_type);
1334 } else {
1335 return_value = DecodeLoop(packet_list, *operation, decoder,
1336 decoded_length, speech_type);
1337 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001338
1339 if (*decoded_length < 0) {
1340 // Error returned from the decoder.
1341 *decoded_length = 0;
Peter Kastingb7e50542015-06-11 12:55:50 -07001342 sync_buffer_->IncreaseEndTimestamp(
1343 static_cast<uint32_t>(decoder_frame_length_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001344 int error_code = 0;
1345 if (decoder)
1346 error_code = decoder->ErrorCode();
1347 if (error_code != 0) {
1348 // Got some error code from the decoder.
1349 decoder_error_code_ = error_code;
1350 return_value = kDecoderErrorCode;
Henrik Lundind67a2192015-08-03 12:54:37 +02001351 LOG(LS_WARNING) << "Decoder returned error code: " << error_code;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001352 } else {
1353 // Decoder does not implement error codes. Return generic error.
1354 return_value = kOtherDecoderError;
Henrik Lundind67a2192015-08-03 12:54:37 +02001355 LOG(LS_WARNING) << "Decoder error (no error code)";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001356 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001357 *operation = kExpand; // Do expansion to get data instead.
1358 }
1359 if (*speech_type != AudioDecoder::kComfortNoise) {
1360 // Don't increment timestamp if codec returned CNG speech type
1361 // since in this case, the we will increment the CNGplayedTS counter.
1362 // Increase with number of samples per channel.
1363 assert(*decoded_length == 0 ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001364 (decoder && decoder->Channels() == sync_buffer_->Channels()));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001365 sync_buffer_->IncreaseEndTimestamp(
1366 *decoded_length / static_cast<int>(sync_buffer_->Channels()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001367 }
1368 return return_value;
1369}
1370
minyuel6d92bf52015-09-23 15:20:39 +02001371int NetEqImpl::DecodeCng(AudioDecoder* decoder, int* decoded_length,
1372 AudioDecoder::SpeechType* speech_type) {
1373 if (!decoder) {
1374 // This happens when active decoder is not defined.
1375 *decoded_length = -1;
1376 return 0;
1377 }
1378
1379 while (*decoded_length < rtc::checked_cast<int>(output_size_samples_)) {
1380 const int length = decoder->Decode(
1381 nullptr, 0, fs_hz_,
1382 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1383 &decoded_buffer_[*decoded_length], speech_type);
1384 if (length > 0) {
1385 *decoded_length += length;
minyuel6d92bf52015-09-23 15:20:39 +02001386 } else {
1387 // Error.
1388 LOG(LS_WARNING) << "Failed to decode CNG";
1389 *decoded_length = -1;
1390 break;
1391 }
1392 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1393 // Guard against overflow.
1394 LOG(LS_WARNING) << "Decoded too much CNG.";
1395 return kDecodedTooMuch;
1396 }
1397 }
1398 return 0;
1399}
1400
1401int NetEqImpl::DecodeLoop(PacketList* packet_list, const Operations& operation,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001402 AudioDecoder* decoder, int* decoded_length,
1403 AudioDecoder::SpeechType* speech_type) {
1404 Packet* packet = NULL;
1405 if (!packet_list->empty()) {
1406 packet = packet_list->front();
1407 }
minyuel6d92bf52015-09-23 15:20:39 +02001408
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001409 // Do decoding.
1410 while (packet &&
1411 !decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1412 assert(decoder); // At this point, we must have a decoder object.
1413 // The number of channels in the |sync_buffer_| should be the same as the
1414 // number decoder channels.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001415 assert(sync_buffer_->Channels() == decoder->Channels());
1416 assert(decoded_buffer_length_ >= kMaxFrameSize * decoder->Channels());
minyuel6d92bf52015-09-23 15:20:39 +02001417 assert(operation == kNormal || operation == kAccelerate ||
1418 operation == kFastAccelerate || operation == kMerge ||
1419 operation == kPreemptiveExpand);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001420 packet_list->pop_front();
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001421 size_t payload_length = packet->payload_length;
Peter Kasting36b7cc32015-06-11 19:57:18 -07001422 int decode_length;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +00001423 if (packet->sync_packet) {
1424 // Decode to silence with the same frame size as the last decode.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001425 memset(&decoded_buffer_[*decoded_length], 0,
1426 decoder_frame_length_ * decoder->Channels() *
1427 sizeof(decoded_buffer_[0]));
Peter Kastingdce40cf2015-08-24 14:52:23 -07001428 decode_length = rtc::checked_cast<int>(decoder_frame_length_);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +00001429 } else if (!packet->primary) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001430 // This is a redundant payload; call the special decoder method.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001431 decode_length = decoder->DecodeRedundant(
henrik.lundin@webrtc.org1eda4e32015-02-25 10:02:29 +00001432 packet->payload, packet->payload_length, fs_hz_,
minyue@webrtc.org7f7d7e32015-03-16 12:30:37 +00001433 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001434 &decoded_buffer_[*decoded_length], speech_type);
1435 } else {
henrik.lundin@webrtc.org1eda4e32015-02-25 10:02:29 +00001436 decode_length =
minyue@webrtc.org7f7d7e32015-03-16 12:30:37 +00001437 decoder->Decode(
1438 packet->payload, packet->payload_length, fs_hz_,
1439 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1440 &decoded_buffer_[*decoded_length], speech_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001441 }
1442
1443 delete[] packet->payload;
1444 delete packet;
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001445 packet = NULL;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001446 if (decode_length > 0) {
1447 *decoded_length += decode_length;
1448 // Update |decoder_frame_length_| with number of samples per channel.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001449 decoder_frame_length_ =
Peter Kastingdce40cf2015-08-24 14:52:23 -07001450 static_cast<size_t>(decode_length) / decoder->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001451 } else if (decode_length < 0) {
1452 // Error.
Henrik Lundind67a2192015-08-03 12:54:37 +02001453 LOG(LS_WARNING) << "Decode " << decode_length << " " << payload_length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001454 *decoded_length = -1;
1455 PacketBuffer::DeleteAllPackets(packet_list);
1456 break;
1457 }
1458 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1459 // Guard against overflow.
Henrik Lundind67a2192015-08-03 12:54:37 +02001460 LOG(LS_WARNING) << "Decoded too much.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001461 PacketBuffer::DeleteAllPackets(packet_list);
1462 return kDecodedTooMuch;
1463 }
1464 if (!packet_list->empty()) {
1465 packet = packet_list->front();
1466 } else {
1467 packet = NULL;
1468 }
1469 } // End of decode loop.
1470
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001471 // If the list is not empty at this point, either a decoding error terminated
1472 // the while-loop, or list must hold exactly one CNG packet.
1473 assert(packet_list->empty() || *decoded_length < 0 ||
1474 (packet_list->size() == 1 && packet &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001475 decoder_database_->IsComfortNoise(packet->header.payloadType)));
1476 return 0;
1477}
1478
1479void NetEqImpl::DoNormal(const int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001480 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001481 assert(normal_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001482 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001483 normal_->Process(decoded_buffer, decoded_length, last_mode_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001484 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001485 if (decoded_length != 0) {
1486 last_mode_ = kModeNormal;
1487 }
1488
1489 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1490 if ((speech_type == AudioDecoder::kComfortNoise)
1491 || ((last_mode_ == kModeCodecInternalCng)
1492 && (decoded_length == 0))) {
1493 // TODO(hlundin): Remove second part of || statement above.
1494 last_mode_ = kModeCodecInternalCng;
1495 }
1496
1497 if (!play_dtmf) {
1498 dtmf_tone_generator_->Reset();
1499 }
1500}
1501
1502void NetEqImpl::DoMerge(int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001503 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001504 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001505 assert(merge_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001506 size_t new_length = merge_->Process(decoded_buffer, decoded_length,
1507 mute_factor_array_.get(),
1508 algorithm_buffer_.get());
1509 size_t expand_length_correction = new_length -
1510 decoded_length / algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001511
1512 // Update in-call and post-call statistics.
1513 if (expand_->MuteFactor(0) == 0) {
1514 // Expand generates only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001515 stats_.ExpandedNoiseSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001516 } else {
1517 // Expansion generates more than only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001518 stats_.ExpandedVoiceSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001519 }
1520
1521 last_mode_ = kModeMerge;
1522 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1523 if (speech_type == AudioDecoder::kComfortNoise) {
1524 last_mode_ = kModeCodecInternalCng;
1525 }
1526 expand_->Reset();
1527 if (!play_dtmf) {
1528 dtmf_tone_generator_->Reset();
1529 }
1530}
1531
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001532int NetEqImpl::DoExpand(bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001533 while ((sync_buffer_->FutureLength() - expand_->overlap_length()) <
Peter Kastingdce40cf2015-08-24 14:52:23 -07001534 output_size_samples_) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001535 algorithm_buffer_->Clear();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001536 int return_value = expand_->Process(algorithm_buffer_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001537 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001538
1539 // Update in-call and post-call statistics.
1540 if (expand_->MuteFactor(0) == 0) {
1541 // Expand operation generates only noise.
1542 stats_.ExpandedNoiseSamples(length);
1543 } else {
1544 // Expand operation generates more than only noise.
1545 stats_.ExpandedVoiceSamples(length);
1546 }
1547
1548 last_mode_ = kModeExpand;
1549
1550 if (return_value < 0) {
1551 return return_value;
1552 }
1553
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001554 sync_buffer_->PushBack(*algorithm_buffer_);
1555 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001556 }
1557 if (!play_dtmf) {
1558 dtmf_tone_generator_->Reset();
1559 }
1560 return 0;
1561}
1562
Henrik Lundincf808d22015-05-27 14:33:29 +02001563int NetEqImpl::DoAccelerate(int16_t* decoded_buffer,
1564 size_t decoded_length,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001565 AudioDecoder::SpeechType speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +02001566 bool play_dtmf,
1567 bool fast_accelerate) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001568 const size_t required_samples =
1569 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001570 size_t borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001571 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001572 size_t decoded_length_per_channel = decoded_length / num_channels;
1573 if (decoded_length_per_channel < required_samples) {
1574 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001575 borrowed_samples_per_channel = static_cast<int>(required_samples -
1576 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001577 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1578 decoded_buffer,
1579 sizeof(int16_t) * decoded_length);
1580 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1581 decoded_buffer);
1582 decoded_length = required_samples * num_channels;
1583 }
1584
Peter Kastingdce40cf2015-08-24 14:52:23 -07001585 size_t samples_removed;
Henrik Lundincf808d22015-05-27 14:33:29 +02001586 Accelerate::ReturnCodes return_code =
1587 accelerate_->Process(decoded_buffer, decoded_length, fast_accelerate,
1588 algorithm_buffer_.get(), &samples_removed);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001589 stats_.AcceleratedSamples(samples_removed);
1590 switch (return_code) {
1591 case Accelerate::kSuccess:
1592 last_mode_ = kModeAccelerateSuccess;
1593 break;
1594 case Accelerate::kSuccessLowEnergy:
1595 last_mode_ = kModeAccelerateLowEnergy;
1596 break;
1597 case Accelerate::kNoStretch:
1598 last_mode_ = kModeAccelerateFail;
1599 break;
1600 case Accelerate::kError:
1601 // TODO(hlundin): Map to kModeError instead?
1602 last_mode_ = kModeAccelerateFail;
1603 return kAccelerateError;
1604 }
1605
1606 if (borrowed_samples_per_channel > 0) {
1607 // Copy borrowed samples back to the |sync_buffer_|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001608 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001609 if (length < borrowed_samples_per_channel) {
1610 // This destroys the beginning of the buffer, but will not cause any
1611 // problems.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001612 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001613 sync_buffer_->Size() -
1614 borrowed_samples_per_channel);
1615 sync_buffer_->PushFrontZeros(borrowed_samples_per_channel - length);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001616 algorithm_buffer_->PopFront(length);
1617 assert(algorithm_buffer_->Empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001618 } else {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001619 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001620 borrowed_samples_per_channel,
1621 sync_buffer_->Size() -
1622 borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001623 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001624 }
1625 }
1626
1627 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1628 if (speech_type == AudioDecoder::kComfortNoise) {
1629 last_mode_ = kModeCodecInternalCng;
1630 }
1631 if (!play_dtmf) {
1632 dtmf_tone_generator_->Reset();
1633 }
1634 expand_->Reset();
1635 return 0;
1636}
1637
1638int NetEqImpl::DoPreemptiveExpand(int16_t* decoded_buffer,
1639 size_t decoded_length,
1640 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001641 bool play_dtmf) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001642 const size_t required_samples =
1643 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001644 size_t num_channels = algorithm_buffer_->Channels();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001645 size_t borrowed_samples_per_channel = 0;
1646 size_t old_borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001647 size_t decoded_length_per_channel = decoded_length / num_channels;
1648 if (decoded_length_per_channel < required_samples) {
1649 // Must move data from the |sync_buffer_| in order to get 30 ms.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001650 borrowed_samples_per_channel =
1651 required_samples - decoded_length_per_channel;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001652 // Calculate how many of these were already played out.
Peter Kastingf045e4d2015-06-10 21:15:38 -07001653 old_borrowed_samples_per_channel =
Peter Kastingdce40cf2015-08-24 14:52:23 -07001654 (borrowed_samples_per_channel > sync_buffer_->FutureLength()) ?
1655 (borrowed_samples_per_channel - sync_buffer_->FutureLength()) : 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001656 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1657 decoded_buffer,
1658 sizeof(int16_t) * decoded_length);
1659 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1660 decoded_buffer);
1661 decoded_length = required_samples * num_channels;
1662 }
1663
Peter Kastingdce40cf2015-08-24 14:52:23 -07001664 size_t samples_added;
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001665 PreemptiveExpand::ReturnCodes return_code = preemptive_expand_->Process(
Peter Kastingdce40cf2015-08-24 14:52:23 -07001666 decoded_buffer, decoded_length,
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001667 old_borrowed_samples_per_channel,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001668 algorithm_buffer_.get(), &samples_added);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001669 stats_.PreemptiveExpandedSamples(samples_added);
1670 switch (return_code) {
1671 case PreemptiveExpand::kSuccess:
1672 last_mode_ = kModePreemptiveExpandSuccess;
1673 break;
1674 case PreemptiveExpand::kSuccessLowEnergy:
1675 last_mode_ = kModePreemptiveExpandLowEnergy;
1676 break;
1677 case PreemptiveExpand::kNoStretch:
1678 last_mode_ = kModePreemptiveExpandFail;
1679 break;
1680 case PreemptiveExpand::kError:
1681 // TODO(hlundin): Map to kModeError instead?
1682 last_mode_ = kModePreemptiveExpandFail;
1683 return kPreemptiveExpandError;
1684 }
1685
1686 if (borrowed_samples_per_channel > 0) {
1687 // Copy borrowed samples back to the |sync_buffer_|.
1688 sync_buffer_->ReplaceAtIndex(
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001689 *algorithm_buffer_, borrowed_samples_per_channel,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001690 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001691 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001692 }
1693
1694 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1695 if (speech_type == AudioDecoder::kComfortNoise) {
1696 last_mode_ = kModeCodecInternalCng;
1697 }
1698 if (!play_dtmf) {
1699 dtmf_tone_generator_->Reset();
1700 }
1701 expand_->Reset();
1702 return 0;
1703}
1704
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001705int NetEqImpl::DoRfc3389Cng(PacketList* packet_list, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001706 if (!packet_list->empty()) {
1707 // Must have exactly one SID frame at this point.
1708 assert(packet_list->size() == 1);
1709 Packet* packet = packet_list->front();
1710 packet_list->pop_front();
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001711 if (!decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1712#ifdef LEGACY_BITEXACT
1713 // This can happen due to a bug in GetDecision. Change the payload type
1714 // to a CNG type, and move on. Note that this means that we are in fact
1715 // sending a non-CNG payload to the comfort noise decoder for decoding.
1716 // Clearly wrong, but will maintain bit-exactness with legacy.
1717 if (fs_hz_ == 8000) {
1718 packet->header.payloadType =
kwibergee1879c2015-10-29 06:20:28 -07001719 decoder_database_->GetRtpPayloadType(NetEqDecoder::kDecoderCNGnb);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001720 } else if (fs_hz_ == 16000) {
1721 packet->header.payloadType =
kwibergee1879c2015-10-29 06:20:28 -07001722 decoder_database_->GetRtpPayloadType(NetEqDecoder::kDecoderCNGwb);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001723 } else if (fs_hz_ == 32000) {
kwibergee1879c2015-10-29 06:20:28 -07001724 packet->header.payloadType = decoder_database_->GetRtpPayloadType(
1725 NetEqDecoder::kDecoderCNGswb32kHz);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001726 } else if (fs_hz_ == 48000) {
kwibergee1879c2015-10-29 06:20:28 -07001727 packet->header.payloadType = decoder_database_->GetRtpPayloadType(
1728 NetEqDecoder::kDecoderCNGswb48kHz);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001729 }
1730 assert(decoder_database_->IsComfortNoise(packet->header.payloadType));
1731#else
1732 LOG(LS_ERROR) << "Trying to decode non-CNG payload as CNG.";
1733 return kOtherError;
1734#endif
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001735 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001736 // UpdateParameters() deletes |packet|.
1737 if (comfort_noise_->UpdateParameters(packet) ==
1738 ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001739 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001740 return -comfort_noise_->internal_error_code();
1741 }
1742 }
1743 int cn_return = comfort_noise_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001744 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001745 expand_->Reset();
1746 last_mode_ = kModeRfc3389Cng;
1747 if (!play_dtmf) {
1748 dtmf_tone_generator_->Reset();
1749 }
1750 if (cn_return == ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001751 decoder_error_code_ = comfort_noise_->internal_error_code();
1752 return kComfortNoiseErrorCode;
1753 } else if (cn_return == ComfortNoise::kUnknownPayloadType) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001754 return kUnknownRtpPayloadType;
1755 }
1756 return 0;
1757}
1758
minyuel6d92bf52015-09-23 15:20:39 +02001759void NetEqImpl::DoCodecInternalCng(const int16_t* decoded_buffer,
1760 size_t decoded_length) {
1761 RTC_DCHECK(normal_.get());
1762 RTC_DCHECK(mute_factor_array_.get());
1763 normal_->Process(decoded_buffer, decoded_length, last_mode_,
1764 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001765 last_mode_ = kModeCodecInternalCng;
1766 expand_->Reset();
1767}
1768
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001769int NetEqImpl::DoDtmf(const DtmfEvent& dtmf_event, bool* play_dtmf) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001770 // This block of the code and the block further down, handling |dtmf_switch|
1771 // are commented out. Otherwise playing out-of-band DTMF would fail in VoE
1772 // test, DtmfTest.ManualSuccessfullySendsOutOfBandTelephoneEvents. This is
1773 // equivalent to |dtmf_switch| always be false.
1774 //
1775 // See http://webrtc-codereview.appspot.com/1195004/ for discussion
1776 // On this issue. This change might cause some glitches at the point of
1777 // switch from audio to DTMF. Issue 1545 is filed to track this.
1778 //
1779 // bool dtmf_switch = false;
1780 // if ((last_mode_ != kModeDtmf) && dtmf_tone_generator_->initialized()) {
1781 // // Special case; see below.
1782 // // We must catch this before calling Generate, since |initialized| is
1783 // // modified in that call.
1784 // dtmf_switch = true;
1785 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001786
1787 int dtmf_return_value = 0;
1788 if (!dtmf_tone_generator_->initialized()) {
1789 // Initialize if not already done.
1790 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1791 dtmf_event.volume);
1792 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001793
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001794 if (dtmf_return_value == 0) {
1795 // Generate DTMF signal.
1796 dtmf_return_value = dtmf_tone_generator_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001797 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001798 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001799
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001800 if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001801 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001802 return dtmf_return_value;
1803 }
1804
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001805 // if (dtmf_switch) {
1806 // // This is the special case where the previous operation was DTMF
1807 // // overdub, but the current instruction is "regular" DTMF. We must make
1808 // // sure that the DTMF does not have any discontinuities. The first DTMF
1809 // // sample that we generate now must be played out immediately, therefore
1810 // // it must be copied to the speech buffer.
1811 // // TODO(hlundin): This code seems incorrect. (Legacy.) Write test and
1812 // // verify correct operation.
1813 // assert(false);
1814 // // Must generate enough data to replace all of the |sync_buffer_|
1815 // // "future".
1816 // int required_length = sync_buffer_->FutureLength();
1817 // assert(dtmf_tone_generator_->initialized());
1818 // dtmf_return_value = dtmf_tone_generator_->Generate(required_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001819 // algorithm_buffer_);
1820 // assert((size_t) required_length == algorithm_buffer_->Size());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001821 // if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001822 // algorithm_buffer_->Zeros(output_size_samples_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001823 // return dtmf_return_value;
1824 // }
1825 //
1826 // // Overwrite the "future" part of the speech buffer with the new DTMF
1827 // // data.
1828 // // TODO(hlundin): It seems that this overwriting has gone lost.
1829 // // Not adapted for multi-channel yet.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001830 // assert(algorithm_buffer_->Channels() == 1);
1831 // if (algorithm_buffer_->Channels() != 1) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001832 // LOG(LS_WARNING) << "DTMF not supported for more than one channel";
1833 // return kStereoNotSupported;
1834 // }
1835 // // Shuffle the remaining data to the beginning of algorithm buffer.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001836 // algorithm_buffer_->PopFront(sync_buffer_->FutureLength());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001837 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001838
Peter Kastingb7e50542015-06-11 12:55:50 -07001839 sync_buffer_->IncreaseEndTimestamp(
1840 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001841 expand_->Reset();
1842 last_mode_ = kModeDtmf;
1843
1844 // Set to false because the DTMF is already in the algorithm buffer.
1845 *play_dtmf = false;
1846 return 0;
1847}
1848
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001849void NetEqImpl::DoAlternativePlc(bool increase_timestamp) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001850 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001851 size_t length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001852 if (decoder && decoder->HasDecodePlc()) {
1853 // Use the decoder's packet-loss concealment.
1854 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1855 int16_t decoded_buffer[kMaxFrameSize];
1856 length = decoder->DecodePlc(1, decoded_buffer);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001857 if (length > 0)
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001858 algorithm_buffer_->PushBackInterleaved(decoded_buffer, length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001859 } else {
1860 // Do simple zero-stuffing.
1861 length = output_size_samples_;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001862 algorithm_buffer_->Zeros(length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001863 // By not advancing the timestamp, NetEq inserts samples.
1864 stats_.AddZeros(length);
1865 }
1866 if (increase_timestamp) {
Peter Kastingb7e50542015-06-11 12:55:50 -07001867 sync_buffer_->IncreaseEndTimestamp(static_cast<uint32_t>(length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001868 }
1869 expand_->Reset();
1870}
1871
1872int NetEqImpl::DtmfOverdub(const DtmfEvent& dtmf_event, size_t num_channels,
1873 int16_t* output) const {
1874 size_t out_index = 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001875 size_t overdub_length = output_size_samples_; // Default value.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001876
1877 if (sync_buffer_->dtmf_index() > sync_buffer_->next_index()) {
1878 // Special operation for transition from "DTMF only" to "DTMF overdub".
1879 out_index = std::min(
1880 sync_buffer_->dtmf_index() - sync_buffer_->next_index(),
Peter Kastingdce40cf2015-08-24 14:52:23 -07001881 output_size_samples_);
1882 overdub_length = output_size_samples_ - out_index;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001883 }
1884
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001885 AudioMultiVector dtmf_output(num_channels);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001886 int dtmf_return_value = 0;
1887 if (!dtmf_tone_generator_->initialized()) {
1888 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1889 dtmf_event.volume);
1890 }
1891 if (dtmf_return_value == 0) {
1892 dtmf_return_value = dtmf_tone_generator_->Generate(overdub_length,
1893 &dtmf_output);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001894 assert(overdub_length == dtmf_output.Size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001895 }
1896 dtmf_output.ReadInterleaved(overdub_length, &output[out_index]);
1897 return dtmf_return_value < 0 ? dtmf_return_value : 0;
1898}
1899
Peter Kastingdce40cf2015-08-24 14:52:23 -07001900int NetEqImpl::ExtractPackets(size_t required_samples,
1901 PacketList* packet_list) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001902 bool first_packet = true;
1903 uint8_t prev_payload_type = 0;
1904 uint32_t prev_timestamp = 0;
1905 uint16_t prev_sequence_number = 0;
1906 bool next_packet_available = false;
1907
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001908 const RTPHeader* header = packet_buffer_->NextRtpHeader();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001909 assert(header);
1910 if (!header) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001911 LOG(LS_ERROR) << "Packet buffer unexpectedly empty.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001912 return -1;
1913 }
turaj@webrtc.org7df97062013-08-02 18:07:13 +00001914 uint32_t first_timestamp = header->timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001915 int extracted_samples = 0;
1916
1917 // Packet extraction loop.
1918 do {
1919 timestamp_ = header->timestamp;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001920 size_t discard_count = 0;
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001921 Packet* packet = packet_buffer_->GetNextPacket(&discard_count);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001922 // |header| may be invalid after the |packet_buffer_| operation.
1923 header = NULL;
1924 if (!packet) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001925 LOG(LS_ERROR) << "Should always be able to extract a packet here";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001926 assert(false); // Should always be able to extract a packet here.
1927 return -1;
1928 }
1929 stats_.PacketsDiscarded(discard_count);
1930 // Store waiting time in ms; packets->waiting_time is in "output blocks".
1931 stats_.StoreWaitingTime(packet->waiting_time * kOutputSizeMs);
1932 assert(packet->payload_length > 0);
1933 packet_list->push_back(packet); // Store packet in list.
1934
1935 if (first_packet) {
1936 first_packet = false;
henrik.lundin48ed9302015-10-29 05:36:24 -07001937 if (nack_enabled_) {
1938 RTC_DCHECK(nack_);
1939 // TODO(henrik.lundin): Should we update this for all decoded packets?
1940 nack_->UpdateLastDecodedPacket(packet->header.sequenceNumber,
1941 packet->header.timestamp);
1942 }
1943 prev_sequence_number = packet->header.sequenceNumber;
1944 prev_timestamp = packet->header.timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001945 prev_payload_type = packet->header.payloadType;
1946 }
1947
1948 // Store number of extracted samples.
1949 int packet_duration = 0;
1950 AudioDecoder* decoder = decoder_database_->GetDecoder(
1951 packet->header.payloadType);
1952 if (decoder) {
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001953 if (packet->sync_packet) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001954 packet_duration = rtc::checked_cast<int>(decoder_frame_length_);
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001955 } else {
minyue@webrtc.org2c1bcf22015-02-17 10:17:09 +00001956 if (packet->primary) {
1957 packet_duration = decoder->PacketDuration(packet->payload,
1958 packet->payload_length);
1959 } else {
1960 packet_duration = decoder->
1961 PacketDurationRedundant(packet->payload, packet->payload_length);
1962 stats_.SecondaryDecodedSamples(packet_duration);
1963 }
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001964 }
ossu97ba30e2016-04-25 07:55:58 -07001965 } else if (!decoder_database_->IsComfortNoise(packet->header.payloadType)) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001966 LOG(LS_WARNING) << "Unknown payload type "
1967 << static_cast<int>(packet->header.payloadType);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001968 assert(false);
1969 }
1970 if (packet_duration <= 0) {
1971 // Decoder did not return a packet duration. Assume that the packet
1972 // contains the same number of samples as the previous one.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001973 packet_duration = rtc::checked_cast<int>(decoder_frame_length_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001974 }
1975 extracted_samples = packet->header.timestamp - first_timestamp +
1976 packet_duration;
1977
1978 // Check what packet is available next.
1979 header = packet_buffer_->NextRtpHeader();
1980 next_packet_available = false;
1981 if (header && prev_payload_type == header->payloadType) {
1982 int16_t seq_no_diff = header->sequenceNumber - prev_sequence_number;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001983 size_t ts_diff = header->timestamp - prev_timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001984 if (seq_no_diff == 1 ||
1985 (seq_no_diff == 0 && ts_diff == decoder_frame_length_)) {
1986 // The next sequence number is available, or the next part of a packet
1987 // that was split into pieces upon insertion.
1988 next_packet_available = true;
1989 }
1990 prev_sequence_number = header->sequenceNumber;
1991 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07001992 } while (extracted_samples < rtc::checked_cast<int>(required_samples) &&
1993 next_packet_available);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001994
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00001995 if (extracted_samples > 0) {
1996 // Delete old packets only when we are going to decode something. Otherwise,
1997 // we could end up in the situation where we never decode anything, since
1998 // all incoming packets are considered too old but the buffer will also
1999 // never be flooded and flushed.
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00002000 packet_buffer_->DiscardAllOldPackets(timestamp_);
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00002001 }
2002
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002003 return extracted_samples;
2004}
2005
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002006void NetEqImpl::UpdatePlcComponents(int fs_hz, size_t channels) {
2007 // Delete objects and create new ones.
2008 expand_.reset(expand_factory_->Create(background_noise_.get(),
2009 sync_buffer_.get(), &random_vector_,
Henrik Lundinbef77e22015-08-18 14:58:09 +02002010 &stats_, fs_hz, channels));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002011 merge_.reset(new Merge(fs_hz, channels, expand_.get(), sync_buffer_.get()));
2012}
2013
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002014void NetEqImpl::SetSampleRateAndChannels(int fs_hz, size_t channels) {
Henrik Lundind67a2192015-08-03 12:54:37 +02002015 LOG(LS_VERBOSE) << "SetSampleRateAndChannels " << fs_hz << " " << channels;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002016 // TODO(hlundin): Change to an enumerator and skip assert.
2017 assert(fs_hz == 8000 || fs_hz == 16000 || fs_hz == 32000 || fs_hz == 48000);
2018 assert(channels > 0);
2019
2020 fs_hz_ = fs_hz;
2021 fs_mult_ = fs_hz / 8000;
Peter Kastingdce40cf2015-08-24 14:52:23 -07002022 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002023 decoder_frame_length_ = 3 * output_size_samples_; // Initialize to 30ms.
2024
2025 last_mode_ = kModeNormal;
2026
2027 // Create a new array of mute factors and set all to 1.
2028 mute_factor_array_.reset(new int16_t[channels]);
2029 for (size_t i = 0; i < channels; ++i) {
2030 mute_factor_array_[i] = 16384; // 1.0 in Q14.
2031 }
2032
ossu97ba30e2016-04-25 07:55:58 -07002033 ComfortNoiseDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02002034 if (cng_decoder)
2035 cng_decoder->Reset();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002036
2037 // Reinit post-decode VAD with new sample rate.
2038 assert(vad_.get()); // Cannot be NULL here.
2039 vad_->Init();
2040
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002041 // Delete algorithm buffer and create a new one.
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00002042 algorithm_buffer_.reset(new AudioMultiVector(channels));
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002043
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002044 // Delete sync buffer and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002045 sync_buffer_.reset(new SyncBuffer(channels, kSyncBufferSize * fs_mult_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002046
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00002047 // Delete BackgroundNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002048 background_noise_.reset(new BackgroundNoise(channels));
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00002049 background_noise_->set_mode(background_noise_mode_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002050
2051 // Reset random vector.
2052 random_vector_.Reset();
2053
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002054 UpdatePlcComponents(fs_hz, channels);
2055
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002056 // Move index so that we create a small set of future samples (all 0).
2057 sync_buffer_->set_next_index(sync_buffer_->next_index() -
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002058 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002059
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002060 normal_.reset(new Normal(fs_hz, decoder_database_.get(), *background_noise_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002061 expand_.get()));
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +00002062 accelerate_.reset(
2063 accelerate_factory_->Create(fs_hz, channels, *background_noise_));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002064 preemptive_expand_.reset(preemptive_expand_factory_->Create(
Peter Kastingdce40cf2015-08-24 14:52:23 -07002065 fs_hz, channels, *background_noise_, expand_->overlap_length()));
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002066
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002067 // Delete ComfortNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002068 comfort_noise_.reset(new ComfortNoise(fs_hz, decoder_database_.get(),
2069 sync_buffer_.get()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002070
2071 // Verify that |decoded_buffer_| is long enough.
2072 if (decoded_buffer_length_ < kMaxFrameSize * channels) {
2073 // Reallocate to larger size.
2074 decoded_buffer_length_ = kMaxFrameSize * channels;
2075 decoded_buffer_.reset(new int16_t[decoded_buffer_length_]);
2076 }
2077
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002078 // Create DecisionLogic if it is not created yet, then communicate new sample
2079 // rate and output size to DecisionLogic object.
2080 if (!decision_logic_.get()) {
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002081 CreateDecisionLogic();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002082 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002083 decision_logic_->SetSampleRate(fs_hz_, output_size_samples_);
2084}
2085
henrik.lundin55480f52016-03-08 02:37:57 -08002086NetEqImpl::OutputType NetEqImpl::LastOutputType() {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002087 assert(vad_.get());
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002088 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002089 if (last_mode_ == kModeCodecInternalCng || last_mode_ == kModeRfc3389Cng) {
henrik.lundin55480f52016-03-08 02:37:57 -08002090 return OutputType::kCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002091 } else if (last_mode_ == kModeExpand && expand_->MuteFactor(0) == 0) {
2092 // Expand mode has faded down to background noise only (very long expand).
henrik.lundin55480f52016-03-08 02:37:57 -08002093 return OutputType::kPLCCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002094 } else if (last_mode_ == kModeExpand) {
henrik.lundin55480f52016-03-08 02:37:57 -08002095 return OutputType::kPLC;
wu@webrtc.org24301a62013-12-13 19:17:43 +00002096 } else if (vad_->running() && !vad_->active_speech()) {
henrik.lundin55480f52016-03-08 02:37:57 -08002097 return OutputType::kVadPassive;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002098 } else {
henrik.lundin55480f52016-03-08 02:37:57 -08002099 return OutputType::kNormalSpeech;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002100 }
2101}
2102
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002103void NetEqImpl::CreateDecisionLogic() {
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002104 decision_logic_.reset(DecisionLogic::Create(fs_hz_, output_size_samples_,
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002105 playout_mode_,
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002106 decoder_database_.get(),
2107 *packet_buffer_.get(),
2108 delay_manager_.get(),
2109 buffer_level_filter_.get()));
2110}
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002111} // namespace webrtc