blob: ef470e5d4eaa48b1304c082052016f17cb760b62 [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"
henrik.lundined497212016-04-25 10:11:38 -070046#include "webrtc/modules/audio_coding/neteq/tick_timer.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000047#include "webrtc/modules/audio_coding/neteq/timestamp_scaler.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010048#include "webrtc/modules/include/module_common_types.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000049
50// Modify the code to obtain backwards bit-exactness. Once bit-exactness is no
51// longer required, this #define should be removed (and the code that it
52// enables).
53#define LEGACY_BITEXACT
54
55namespace webrtc {
56
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +000057NetEqImpl::NetEqImpl(const NetEq::Config& config,
henrik.lundined497212016-04-25 10:11:38 -070058 std::unique_ptr<TickTimer> tick_timer,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000059 BufferLevelFilter* buffer_level_filter,
60 DecoderDatabase* decoder_database,
61 DelayManager* delay_manager,
62 DelayPeakDetector* delay_peak_detector,
63 DtmfBuffer* dtmf_buffer,
64 DtmfToneGenerator* dtmf_tone_generator,
65 PacketBuffer* packet_buffer,
66 PayloadSplitter* payload_splitter,
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +000067 TimestampScaler* timestamp_scaler,
68 AccelerateFactory* accelerate_factory,
69 ExpandFactory* expand_factory,
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +000070 PreemptiveExpandFactory* preemptive_expand_factory,
71 bool create_components)
henrik.lundined497212016-04-25 10:11:38 -070072 : tick_timer_(std::move(tick_timer)),
73 buffer_level_filter_(buffer_level_filter),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000074 decoder_database_(decoder_database),
75 delay_manager_(delay_manager),
76 delay_peak_detector_(delay_peak_detector),
77 dtmf_buffer_(dtmf_buffer),
78 dtmf_tone_generator_(dtmf_tone_generator),
79 packet_buffer_(packet_buffer),
80 payload_splitter_(payload_splitter),
81 timestamp_scaler_(timestamp_scaler),
82 vad_(new PostDecodeVad()),
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +000083 expand_factory_(expand_factory),
84 accelerate_factory_(accelerate_factory),
85 preemptive_expand_factory_(preemptive_expand_factory),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000086 last_mode_(kModeNormal),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000087 decoded_buffer_length_(kMaxFrameSize),
88 decoded_buffer_(new int16_t[decoded_buffer_length_]),
89 playout_timestamp_(0),
90 new_codec_(false),
91 timestamp_(0),
92 reset_decoder_(false),
henrik.lundin48ed9302015-10-29 05:36:24 -070093 current_rtp_payload_type_(0xFF), // Invalid RTP payload type.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000094 current_cng_rtp_payload_type_(0xFF), // Invalid RTP payload type.
95 ssrc_(0),
96 first_packet_(true),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000097 error_code_(0),
98 decoder_error_code_(0),
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +000099 background_noise_mode_(config.background_noise_mode),
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000100 playout_mode_(config.playout_mode),
Henrik Lundincf808d22015-05-27 14:33:29 +0200101 enable_fast_accelerate_(config.enable_fast_accelerate),
henrik.lundin48ed9302015-10-29 05:36:24 -0700102 nack_enabled_(false) {
Henrik Lundin905495c2015-05-25 16:58:41 +0200103 LOG(LS_INFO) << "NetEq config: " << config.ToString();
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +0000104 int fs = config.sample_rate_hz;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000105 if (fs != 8000 && fs != 16000 && fs != 32000 && fs != 48000) {
106 LOG(LS_ERROR) << "Sample rate " << fs << " Hz not supported. " <<
107 "Changing to 8000 Hz.";
108 fs = 8000;
109 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000110 fs_hz_ = fs;
111 fs_mult_ = fs / 8000;
henrik.lundind89814b2015-11-23 06:49:25 -0800112 last_output_sample_rate_hz_ = fs;
Peter Kastingdce40cf2015-08-24 14:52:23 -0700113 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000114 decoder_frame_length_ = 3 * output_size_samples_;
115 WebRtcSpl_Init();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000116 if (create_components) {
117 SetSampleRateAndChannels(fs, 1); // Default is 1 channel.
118 }
henrik.lundin9bc26672015-11-02 03:25:57 -0800119 RTC_DCHECK(!vad_->enabled());
120 if (config.enable_post_decode_vad) {
121 vad_->Enable();
122 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000123}
124
Henrik Lundind67a2192015-08-03 12:54:37 +0200125NetEqImpl::~NetEqImpl() = default;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000126
127int NetEqImpl::InsertPacket(const WebRtcRTPHeader& rtp_header,
kwibergee2bac22015-11-11 10:34:00 -0800128 rtc::ArrayView<const uint8_t> payload,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000129 uint32_t receive_timestamp) {
henrik.lundina689b442015-12-17 03:50:05 -0800130 TRACE_EVENT0("webrtc", "NetEqImpl::InsertPacket");
Tommi9090e0b2016-01-20 13:39:36 +0100131 rtc::CritScope lock(&crit_sect_);
kwibergee2bac22015-11-11 10:34:00 -0800132 int error =
133 InsertPacketInternal(rtp_header, payload, receive_timestamp, false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000134 if (error != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000135 error_code_ = error;
136 return kFail;
137 }
138 return kOK;
139}
140
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000141int NetEqImpl::InsertSyncPacket(const WebRtcRTPHeader& rtp_header,
142 uint32_t receive_timestamp) {
Tommi9090e0b2016-01-20 13:39:36 +0100143 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000144 const uint8_t kSyncPayload[] = { 's', 'y', 'n', 'c' };
kwibergee2bac22015-11-11 10:34:00 -0800145 int error =
146 InsertPacketInternal(rtp_header, kSyncPayload, receive_timestamp, true);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000147
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000148 if (error != 0) {
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000149 error_code_ = error;
150 return kFail;
151 }
152 return kOK;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000153}
154
henrik.lundin500c04b2016-03-08 02:36:04 -0800155namespace {
156void SetAudioFrameActivityAndType(bool vad_enabled,
henrik.lundin55480f52016-03-08 02:37:57 -0800157 NetEqImpl::OutputType type,
henrik.lundin500c04b2016-03-08 02:36:04 -0800158 AudioFrame::VADActivity last_vad_activity,
159 AudioFrame* audio_frame) {
160 switch (type) {
henrik.lundin55480f52016-03-08 02:37:57 -0800161 case NetEqImpl::OutputType::kNormalSpeech: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800162 audio_frame->speech_type_ = AudioFrame::kNormalSpeech;
163 audio_frame->vad_activity_ = AudioFrame::kVadActive;
164 break;
165 }
henrik.lundin55480f52016-03-08 02:37:57 -0800166 case NetEqImpl::OutputType::kVadPassive: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800167 // This should only be reached if the VAD is enabled.
168 RTC_DCHECK(vad_enabled);
169 audio_frame->speech_type_ = AudioFrame::kNormalSpeech;
170 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
171 break;
172 }
henrik.lundin55480f52016-03-08 02:37:57 -0800173 case NetEqImpl::OutputType::kCNG: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800174 audio_frame->speech_type_ = AudioFrame::kCNG;
175 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
176 break;
177 }
henrik.lundin55480f52016-03-08 02:37:57 -0800178 case NetEqImpl::OutputType::kPLC: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800179 audio_frame->speech_type_ = AudioFrame::kPLC;
180 audio_frame->vad_activity_ = last_vad_activity;
181 break;
182 }
henrik.lundin55480f52016-03-08 02:37:57 -0800183 case NetEqImpl::OutputType::kPLCCNG: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800184 audio_frame->speech_type_ = AudioFrame::kPLCCNG;
185 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
186 break;
187 }
188 default:
189 RTC_NOTREACHED();
190 }
191 if (!vad_enabled) {
192 // Always set kVadUnknown when receive VAD is inactive.
193 audio_frame->vad_activity_ = AudioFrame::kVadUnknown;
194 }
195}
henrik.lundinbc89de32016-03-08 05:20:14 -0800196} // namespace
henrik.lundin500c04b2016-03-08 02:36:04 -0800197
henrik.lundin55480f52016-03-08 02:37:57 -0800198int NetEqImpl::GetAudio(AudioFrame* audio_frame) {
henrik.lundine1ca1672016-01-08 03:50:08 -0800199 TRACE_EVENT0("webrtc", "NetEqImpl::GetAudio");
Tommi9090e0b2016-01-20 13:39:36 +0100200 rtc::CritScope lock(&crit_sect_);
henrik.lundin6d8e0112016-03-04 10:34:21 -0800201 int error = GetAudioInternal(audio_frame);
202 RTC_DCHECK_EQ(
203 audio_frame->sample_rate_hz_,
204 rtc::checked_cast<int>(audio_frame->samples_per_channel_ * 100));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000205 if (error != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000206 error_code_ = error;
207 return kFail;
208 }
henrik.lundin500c04b2016-03-08 02:36:04 -0800209 SetAudioFrameActivityAndType(vad_->enabled(), LastOutputType(),
210 last_vad_activity_, audio_frame);
211 last_vad_activity_ = audio_frame->vad_activity_;
henrik.lundin6d8e0112016-03-04 10:34:21 -0800212 last_output_sample_rate_hz_ = audio_frame->sample_rate_hz_;
henrik.lundind89814b2015-11-23 06:49:25 -0800213 RTC_DCHECK(last_output_sample_rate_hz_ == 8000 ||
214 last_output_sample_rate_hz_ == 16000 ||
215 last_output_sample_rate_hz_ == 32000 ||
216 last_output_sample_rate_hz_ == 48000)
217 << "Unexpected sample rate " << last_output_sample_rate_hz_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000218 return kOK;
219}
220
kwibergee1879c2015-10-29 06:20:28 -0700221int NetEqImpl::RegisterPayloadType(NetEqDecoder codec,
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800222 const std::string& name,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000223 uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100224 rtc::CritScope lock(&crit_sect_);
Henrik Lundind67a2192015-08-03 12:54:37 +0200225 LOG(LS_VERBOSE) << "RegisterPayloadType "
kwibergee1879c2015-10-29 06:20:28 -0700226 << static_cast<int>(rtp_payload_type) << " "
227 << static_cast<int>(codec);
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800228 int ret = decoder_database_->RegisterPayload(rtp_payload_type, codec, name);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000229 if (ret != DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000230 switch (ret) {
231 case DecoderDatabase::kInvalidRtpPayloadType:
232 error_code_ = kInvalidRtpPayloadType;
233 break;
234 case DecoderDatabase::kCodecNotSupported:
235 error_code_ = kCodecNotSupported;
236 break;
237 case DecoderDatabase::kDecoderExists:
238 error_code_ = kDecoderExists;
239 break;
240 default:
241 error_code_ = kOtherError;
242 }
243 return kFail;
244 }
245 return kOK;
246}
247
248int NetEqImpl::RegisterExternalDecoder(AudioDecoder* decoder,
kwibergee1879c2015-10-29 06:20:28 -0700249 NetEqDecoder codec,
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800250 const std::string& codec_name,
Karl Wibergd8399e62015-05-25 14:39:56 +0200251 uint8_t rtp_payload_type,
252 int sample_rate_hz) {
Tommi9090e0b2016-01-20 13:39:36 +0100253 rtc::CritScope lock(&crit_sect_);
Henrik Lundind67a2192015-08-03 12:54:37 +0200254 LOG(LS_VERBOSE) << "RegisterExternalDecoder "
kwibergee1879c2015-10-29 06:20:28 -0700255 << static_cast<int>(rtp_payload_type) << " "
256 << static_cast<int>(codec);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000257 if (!decoder) {
258 LOG(LS_ERROR) << "Cannot register external decoder with NULL pointer";
259 assert(false);
260 return kFail;
261 }
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800262 int ret = decoder_database_->InsertExternal(
263 rtp_payload_type, codec, codec_name, sample_rate_hz, decoder);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000264 if (ret != DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000265 switch (ret) {
266 case DecoderDatabase::kInvalidRtpPayloadType:
267 error_code_ = kInvalidRtpPayloadType;
268 break;
269 case DecoderDatabase::kCodecNotSupported:
270 error_code_ = kCodecNotSupported;
271 break;
272 case DecoderDatabase::kDecoderExists:
273 error_code_ = kDecoderExists;
274 break;
275 case DecoderDatabase::kInvalidSampleRate:
276 error_code_ = kInvalidSampleRate;
277 break;
278 case DecoderDatabase::kInvalidPointer:
279 error_code_ = kInvalidPointer;
280 break;
281 default:
282 error_code_ = kOtherError;
283 }
284 return kFail;
285 }
286 return kOK;
287}
288
289int NetEqImpl::RemovePayloadType(uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100290 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000291 int ret = decoder_database_->Remove(rtp_payload_type);
292 if (ret == DecoderDatabase::kOK) {
293 return kOK;
294 } else if (ret == DecoderDatabase::kDecoderNotFound) {
295 error_code_ = kDecoderNotFound;
296 } else {
297 error_code_ = kOtherError;
298 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000299 return kFail;
300}
301
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000302bool NetEqImpl::SetMinimumDelay(int delay_ms) {
Tommi9090e0b2016-01-20 13:39:36 +0100303 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000304 if (delay_ms >= 0 && delay_ms < 10000) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000305 assert(delay_manager_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000306 return delay_manager_->SetMinimumDelay(delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000307 }
308 return false;
309}
310
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000311bool NetEqImpl::SetMaximumDelay(int delay_ms) {
Tommi9090e0b2016-01-20 13:39:36 +0100312 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000313 if (delay_ms >= 0 && delay_ms < 10000) {
314 assert(delay_manager_.get());
315 return delay_manager_->SetMaximumDelay(delay_ms);
316 }
317 return false;
318}
319
320int NetEqImpl::LeastRequiredDelayMs() const {
Tommi9090e0b2016-01-20 13:39:36 +0100321 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000322 assert(delay_manager_.get());
323 return delay_manager_->least_required_delay_ms();
324}
325
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200326int NetEqImpl::SetTargetDelay() {
327 return kNotImplemented;
328}
329
330int NetEqImpl::TargetDelay() {
331 return kNotImplemented;
332}
333
henrik.lundin9c3efd02015-08-27 13:12:22 -0700334int NetEqImpl::CurrentDelayMs() const {
Tommi9090e0b2016-01-20 13:39:36 +0100335 rtc::CritScope lock(&crit_sect_);
henrik.lundin9c3efd02015-08-27 13:12:22 -0700336 if (fs_hz_ == 0)
337 return 0;
338 // Sum up the samples in the packet buffer with the future length of the sync
339 // buffer, and divide the sum by the sample rate.
340 const size_t delay_samples =
341 packet_buffer_->NumSamplesInBuffer(decoder_database_.get(),
342 decoder_frame_length_) +
343 sync_buffer_->FutureLength();
344 // The division below will truncate.
345 const int delay_ms =
346 static_cast<int>(delay_samples) / rtc::CheckedDivExact(fs_hz_, 1000);
347 return delay_ms;
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200348}
349
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000350// Deprecated.
351// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000352void NetEqImpl::SetPlayoutMode(NetEqPlayoutMode mode) {
Tommi9090e0b2016-01-20 13:39:36 +0100353 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000354 if (mode != playout_mode_) {
355 playout_mode_ = mode;
356 CreateDecisionLogic();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000357 }
358}
359
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000360// Deprecated.
361// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000362NetEqPlayoutMode NetEqImpl::PlayoutMode() const {
Tommi9090e0b2016-01-20 13:39:36 +0100363 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000364 return playout_mode_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000365}
366
367int NetEqImpl::NetworkStatistics(NetEqNetworkStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100368 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000369 assert(decoder_database_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700370 const size_t total_samples_in_buffers =
Peter Kasting728d9032015-06-11 14:31:38 -0700371 packet_buffer_->NumSamplesInBuffer(decoder_database_.get(),
372 decoder_frame_length_) +
Peter Kastingdce40cf2015-08-24 14:52:23 -0700373 sync_buffer_->FutureLength();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000374 assert(delay_manager_.get());
375 assert(decision_logic_.get());
376 stats_.GetNetworkStatistics(fs_hz_, total_samples_in_buffers,
377 decoder_frame_length_, *delay_manager_.get(),
378 *decision_logic_.get(), stats);
379 return 0;
380}
381
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000382void NetEqImpl::GetRtcpStatistics(RtcpStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100383 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000384 if (stats) {
385 rtcp_.GetStatistics(false, stats);
386 }
387}
388
389void NetEqImpl::GetRtcpStatisticsNoReset(RtcpStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100390 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000391 if (stats) {
392 rtcp_.GetStatistics(true, stats);
393 }
394}
395
396void NetEqImpl::EnableVad() {
Tommi9090e0b2016-01-20 13:39:36 +0100397 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000398 assert(vad_.get());
399 vad_->Enable();
400}
401
402void NetEqImpl::DisableVad() {
Tommi9090e0b2016-01-20 13:39:36 +0100403 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000404 assert(vad_.get());
405 vad_->Disable();
406}
407
henrik.lundin15c51e32016-04-06 08:38:56 -0700408rtc::Optional<uint32_t> NetEqImpl::GetPlayoutTimestamp() const {
Tommi9090e0b2016-01-20 13:39:36 +0100409 rtc::CritScope lock(&crit_sect_);
henrik.lundin0d96ab72016-04-06 12:28:26 -0700410 if (first_packet_ || last_mode_ == kModeRfc3389Cng ||
411 last_mode_ == kModeCodecInternalCng) {
wu@webrtc.org94454b72014-06-05 20:34:08 +0000412 // We don't have a valid RTP timestamp until we have decoded our first
henrik.lundin0d96ab72016-04-06 12:28:26 -0700413 // RTP packet. Also, the RTP timestamp is not accurate while playing CNG,
414 // which is indicated by returning an empty value.
henrik.lundin9a410dd2016-04-06 01:39:22 -0700415 return rtc::Optional<uint32_t>();
wu@webrtc.org94454b72014-06-05 20:34:08 +0000416 }
henrik.lundin9a410dd2016-04-06 01:39:22 -0700417 return rtc::Optional<uint32_t>(
418 timestamp_scaler_->ToExternal(playout_timestamp_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000419}
420
henrik.lundind89814b2015-11-23 06:49:25 -0800421int NetEqImpl::last_output_sample_rate_hz() const {
Tommi9090e0b2016-01-20 13:39:36 +0100422 rtc::CritScope lock(&crit_sect_);
henrik.lundind89814b2015-11-23 06:49:25 -0800423 return last_output_sample_rate_hz_;
424}
425
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200426int NetEqImpl::SetTargetNumberOfChannels() {
427 return kNotImplemented;
428}
429
430int NetEqImpl::SetTargetSampleRate() {
431 return kNotImplemented;
432}
433
henrik.lundin@webrtc.orgb0f4b3d2014-11-04 08:53:10 +0000434int NetEqImpl::LastError() const {
Tommi9090e0b2016-01-20 13:39:36 +0100435 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000436 return error_code_;
437}
438
439int NetEqImpl::LastDecoderError() {
Tommi9090e0b2016-01-20 13:39:36 +0100440 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000441 return decoder_error_code_;
442}
443
444void NetEqImpl::FlushBuffers() {
Tommi9090e0b2016-01-20 13:39:36 +0100445 rtc::CritScope lock(&crit_sect_);
Henrik Lundind67a2192015-08-03 12:54:37 +0200446 LOG(LS_VERBOSE) << "FlushBuffers";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000447 packet_buffer_->Flush();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000448 assert(sync_buffer_.get());
449 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000450 sync_buffer_->Flush();
451 sync_buffer_->set_next_index(sync_buffer_->next_index() -
452 expand_->overlap_length());
453 // Set to wait for new codec.
454 first_packet_ = true;
455}
456
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000457void NetEqImpl::PacketBufferStatistics(int* current_num_packets,
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000458 int* max_num_packets) const {
Tommi9090e0b2016-01-20 13:39:36 +0100459 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000460 packet_buffer_->BufferStat(current_num_packets, max_num_packets);
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000461}
462
henrik.lundin48ed9302015-10-29 05:36:24 -0700463void NetEqImpl::EnableNack(size_t max_nack_list_size) {
Tommi9090e0b2016-01-20 13:39:36 +0100464 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700465 if (!nack_enabled_) {
466 const int kNackThresholdPackets = 2;
467 nack_.reset(Nack::Create(kNackThresholdPackets));
468 nack_enabled_ = true;
469 nack_->UpdateSampleRate(fs_hz_);
470 }
471 nack_->SetMaxNackListSize(max_nack_list_size);
472}
473
474void NetEqImpl::DisableNack() {
Tommi9090e0b2016-01-20 13:39:36 +0100475 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700476 nack_.reset();
477 nack_enabled_ = false;
478}
479
480std::vector<uint16_t> NetEqImpl::GetNackList(int64_t round_trip_time_ms) const {
Tommi9090e0b2016-01-20 13:39:36 +0100481 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700482 if (!nack_enabled_) {
483 return std::vector<uint16_t>();
484 }
485 RTC_DCHECK(nack_.get());
486 return nack_->GetNackList(round_trip_time_ms);
minyue@webrtc.orgd7301772013-08-29 00:58:14 +0000487}
488
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000489const SyncBuffer* NetEqImpl::sync_buffer_for_test() const {
Tommi9090e0b2016-01-20 13:39:36 +0100490 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000491 return sync_buffer_.get();
492}
493
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000494// Methods below this line are private.
495
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000496int NetEqImpl::InsertPacketInternal(const WebRtcRTPHeader& rtp_header,
kwibergee2bac22015-11-11 10:34:00 -0800497 rtc::ArrayView<const uint8_t> payload,
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000498 uint32_t receive_timestamp,
499 bool is_sync_packet) {
kwibergee2bac22015-11-11 10:34:00 -0800500 if (payload.empty()) {
501 LOG_F(LS_ERROR) << "payload is empty";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000502 return kInvalidPointer;
503 }
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000504 // Sanity checks for sync-packets.
505 if (is_sync_packet) {
506 if (decoder_database_->IsDtmf(rtp_header.header.payloadType) ||
507 decoder_database_->IsRed(rtp_header.header.payloadType) ||
508 decoder_database_->IsComfortNoise(rtp_header.header.payloadType)) {
509 LOG_F(LS_ERROR) << "Sync-packet with an unacceptable payload type "
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000510 << static_cast<int>(rtp_header.header.payloadType);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000511 return kSyncPacketNotAccepted;
512 }
513 if (first_packet_ ||
514 rtp_header.header.payloadType != current_rtp_payload_type_ ||
515 rtp_header.header.ssrc != ssrc_) {
516 // Even if |current_rtp_payload_type_| is 0xFF, sync-packet isn't
517 // accepted.
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000518 LOG_F(LS_ERROR)
519 << "Changing codec, SSRC or first packet with sync-packet.";
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000520 return kSyncPacketNotAccepted;
521 }
522 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000523 PacketList packet_list;
524 RTPHeader main_header;
525 {
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000526 // Convert to Packet.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000527 // Create |packet| within this separate scope, since it should not be used
528 // directly once it's been inserted in the packet list. This way, |packet|
529 // is not defined outside of this block.
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000530 Packet* packet = new Packet;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000531 packet->header.markerBit = false;
532 packet->header.payloadType = rtp_header.header.payloadType;
533 packet->header.sequenceNumber = rtp_header.header.sequenceNumber;
534 packet->header.timestamp = rtp_header.header.timestamp;
535 packet->header.ssrc = rtp_header.header.ssrc;
536 packet->header.numCSRCs = 0;
kwibergee2bac22015-11-11 10:34:00 -0800537 packet->payload_length = payload.size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000538 packet->primary = true;
539 packet->waiting_time = 0;
540 packet->payload = new uint8_t[packet->payload_length];
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000541 packet->sync_packet = is_sync_packet;
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +0000542 if (!packet->payload) {
543 LOG_F(LS_ERROR) << "Payload pointer is NULL.";
544 }
kwibergee2bac22015-11-11 10:34:00 -0800545 assert(!payload.empty()); // Already checked above.
546 memcpy(packet->payload, payload.data(), packet->payload_length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000547 // Insert packet in a packet list.
548 packet_list.push_back(packet);
549 // Save main payloads header for later.
550 memcpy(&main_header, &packet->header, sizeof(main_header));
551 }
552
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000553 bool update_sample_rate_and_channels = false;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000554 // Reinitialize NetEq if it's needed (changed SSRC or first call).
555 if ((main_header.ssrc != ssrc_) || first_packet_) {
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000556 // Note: |first_packet_| will be cleared further down in this method, once
557 // the packet has been successfully inserted into the packet buffer.
558
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000559 rtcp_.Init(main_header.sequenceNumber);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000560
561 // Flush the packet buffer and DTMF buffer.
562 packet_buffer_->Flush();
563 dtmf_buffer_->Flush();
564
565 // Store new SSRC.
566 ssrc_ = main_header.ssrc;
567
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000568 // Update audio buffer timestamp.
569 sync_buffer_->IncreaseEndTimestamp(main_header.timestamp - timestamp_);
570
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000571 // Update codecs.
572 timestamp_ = main_header.timestamp;
573 current_rtp_payload_type_ = main_header.payloadType;
574
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000575 // Reset timestamp scaling.
576 timestamp_scaler_->Reset();
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000577
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000578 // Trigger an update of sampling rate and the number of channels.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000579 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000580 }
581
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000582 // Update RTCP statistics, only for regular packets.
583 if (!is_sync_packet)
584 rtcp_.Update(main_header, receive_timestamp);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000585
586 // Check for RED payload type, and separate payloads into several packets.
587 if (decoder_database_->IsRed(main_header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000588 assert(!is_sync_packet); // We had a sanity check for this.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000589 if (payload_splitter_->SplitRed(&packet_list) != PayloadSplitter::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000590 PacketBuffer::DeleteAllPackets(&packet_list);
591 return kRedundancySplitError;
592 }
593 // Only accept a few RED payloads of the same type as the main data,
594 // DTMF events and CNG.
595 payload_splitter_->CheckRedPayloads(&packet_list, *decoder_database_);
596 // Update the stored main payload header since the main payload has now
597 // changed.
598 memcpy(&main_header, &packet_list.front()->header, sizeof(main_header));
599 }
600
601 // Check payload types.
602 if (decoder_database_->CheckPayloadTypes(packet_list) ==
603 DecoderDatabase::kDecoderNotFound) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000604 PacketBuffer::DeleteAllPackets(&packet_list);
605 return kUnknownRtpPayloadType;
606 }
607
608 // Scale timestamp to internal domain (only for some codecs).
609 timestamp_scaler_->ToInternal(&packet_list);
610
611 // Process DTMF payloads. Cycle through the list of packets, and pick out any
612 // DTMF payloads found.
613 PacketList::iterator it = packet_list.begin();
614 while (it != packet_list.end()) {
615 Packet* current_packet = (*it);
616 assert(current_packet);
617 assert(current_packet->payload);
618 if (decoder_database_->IsDtmf(current_packet->header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000619 assert(!current_packet->sync_packet); // We had a sanity check for this.
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000620 DtmfEvent event;
621 int ret = DtmfBuffer::ParseEvent(
622 current_packet->header.timestamp,
623 current_packet->payload,
624 current_packet->payload_length,
625 &event);
626 if (ret != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000627 PacketBuffer::DeleteAllPackets(&packet_list);
628 return kDtmfParsingError;
629 }
630 if (dtmf_buffer_->InsertEvent(event) != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000631 PacketBuffer::DeleteAllPackets(&packet_list);
632 return kDtmfInsertError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000633 }
634 // TODO(hlundin): Let the destructor of Packet handle the payload.
635 delete [] current_packet->payload;
636 delete current_packet;
637 it = packet_list.erase(it);
638 } else {
639 ++it;
640 }
641 }
642
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000643 // Check for FEC in packets, and separate payloads into several packets.
644 int ret = payload_splitter_->SplitFec(&packet_list, decoder_database_.get());
645 if (ret != PayloadSplitter::kOK) {
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000646 PacketBuffer::DeleteAllPackets(&packet_list);
647 switch (ret) {
648 case PayloadSplitter::kUnknownPayloadType:
649 return kUnknownRtpPayloadType;
650 default:
651 return kOtherError;
652 }
653 }
654
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000655 // Split payloads into smaller chunks. This also verifies that all payloads
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000656 // are of a known payload type. SplitAudio() method is protected against
657 // sync-packets.
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +0000658 ret = payload_splitter_->SplitAudio(&packet_list, *decoder_database_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000659 if (ret != PayloadSplitter::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000660 PacketBuffer::DeleteAllPackets(&packet_list);
661 switch (ret) {
662 case PayloadSplitter::kUnknownPayloadType:
663 return kUnknownRtpPayloadType;
664 case PayloadSplitter::kFrameSplitError:
665 return kFrameSplitError;
666 default:
667 return kOtherError;
668 }
669 }
670
ossu97ba30e2016-04-25 07:55:58 -0700671 // Update bandwidth estimate, if the packet is not sync-packet nor comfort
672 // noise.
673 if (!packet_list.empty() && !packet_list.front()->sync_packet &&
674 !decoder_database_->IsComfortNoise(main_header.payloadType)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000675 // The list can be empty here if we got nothing but DTMF payloads.
676 AudioDecoder* decoder =
677 decoder_database_->GetDecoder(main_header.payloadType);
678 assert(decoder); // Should always get a valid object, since we have
ossu97ba30e2016-04-25 07:55:58 -0700679 // already checked that the payload types are known.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000680 decoder->IncomingPacket(packet_list.front()->payload,
681 packet_list.front()->payload_length,
682 packet_list.front()->header.sequenceNumber,
683 packet_list.front()->header.timestamp,
684 receive_timestamp);
685 }
686
henrik.lundin48ed9302015-10-29 05:36:24 -0700687 if (nack_enabled_) {
688 RTC_DCHECK(nack_);
689 if (update_sample_rate_and_channels) {
690 nack_->Reset();
691 }
692 nack_->UpdateLastReceivedPacket(packet_list.front()->header.sequenceNumber,
693 packet_list.front()->header.timestamp);
694 }
695
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000696 // Insert packets in buffer.
henrik.lundin116c84e2015-08-27 13:14:48 -0700697 const size_t buffer_length_before_insert =
698 packet_buffer_->NumPacketsInBuffer();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000699 ret = packet_buffer_->InsertPacketList(
700 &packet_list,
701 *decoder_database_,
702 &current_rtp_payload_type_,
703 &current_cng_rtp_payload_type_);
704 if (ret == PacketBuffer::kFlushed) {
705 // Reset DSP timestamp etc. if packet buffer flushed.
706 new_codec_ = true;
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000707 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000708 } else if (ret != PacketBuffer::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000709 PacketBuffer::DeleteAllPackets(&packet_list);
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000710 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000711 }
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000712
713 if (first_packet_) {
714 first_packet_ = false;
715 // Update the codec on the next GetAudio call.
716 new_codec_ = true;
717 }
718
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000719 if (current_rtp_payload_type_ != 0xFF) {
720 const DecoderDatabase::DecoderInfo* dec_info =
721 decoder_database_->GetDecoderInfo(current_rtp_payload_type_);
722 if (!dec_info) {
723 assert(false); // Already checked that the payload type is known.
724 }
725 }
726
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000727 if (update_sample_rate_and_channels && !packet_buffer_->Empty()) {
728 // We do not use |current_rtp_payload_type_| to |set payload_type|, but
729 // get the next RTP header from |packet_buffer_| to obtain the payload type.
730 // The reason for it is the following corner case. If NetEq receives a
731 // CNG packet with a sample rate different than the current CNG then it
732 // flushes its buffer, assuming send codec must have been changed. However,
733 // payload type of the hypothetically new send codec is not known.
734 const RTPHeader* rtp_header = packet_buffer_->NextRtpHeader();
735 assert(rtp_header);
736 int payload_type = rtp_header->payloadType;
ossu97ba30e2016-04-25 07:55:58 -0700737 size_t channels = 1;
738 if (!decoder_database_->IsComfortNoise(payload_type)) {
739 AudioDecoder* decoder = decoder_database_->GetDecoder(payload_type);
740 assert(decoder); // Payloads are already checked to be valid.
741 channels = decoder->Channels();
742 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000743 const DecoderDatabase::DecoderInfo* decoder_info =
744 decoder_database_->GetDecoderInfo(payload_type);
745 assert(decoder_info);
746 if (decoder_info->fs_hz != fs_hz_ ||
ossu97ba30e2016-04-25 07:55:58 -0700747 channels != algorithm_buffer_->Channels()) {
748 SetSampleRateAndChannels(decoder_info->fs_hz, channels);
henrik.lundin48ed9302015-10-29 05:36:24 -0700749 }
750 if (nack_enabled_) {
751 RTC_DCHECK(nack_);
752 // Update the sample rate even if the rate is not new, because of Reset().
753 nack_->UpdateSampleRate(fs_hz_);
754 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000755 }
756
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000757 // TODO(hlundin): Move this code to DelayManager class.
758 const DecoderDatabase::DecoderInfo* dec_info =
759 decoder_database_->GetDecoderInfo(main_header.payloadType);
760 assert(dec_info); // Already checked that the payload type is known.
761 delay_manager_->LastDecoderType(dec_info->codec_type);
762 if (delay_manager_->last_pack_cng_or_dtmf() == 0) {
763 // Calculate the total speech length carried in each packet.
henrik.lundin116c84e2015-08-27 13:14:48 -0700764 const size_t buffer_length_after_insert =
765 packet_buffer_->NumPacketsInBuffer();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000766
henrik.lundin116c84e2015-08-27 13:14:48 -0700767 if (buffer_length_after_insert > buffer_length_before_insert) {
768 const size_t packet_length_samples =
769 (buffer_length_after_insert - buffer_length_before_insert) *
770 decoder_frame_length_;
771 if (packet_length_samples != decision_logic_->packet_length_samples()) {
772 decision_logic_->set_packet_length_samples(packet_length_samples);
773 delay_manager_->SetPacketAudioLength(
774 rtc::checked_cast<int>((1000 * packet_length_samples) / fs_hz_));
775 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000776 }
777
778 // Update statistics.
pbos@webrtc.org0946a562013-04-09 00:28:06 +0000779 if ((int32_t) (main_header.timestamp - timestamp_) >= 0 &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000780 !new_codec_) {
781 // Only update statistics if incoming packet is not older than last played
782 // out packet, and if new codec flag is not set.
783 delay_manager_->Update(main_header.sequenceNumber, main_header.timestamp,
784 fs_hz_);
785 }
786 } else if (delay_manager_->last_pack_cng_or_dtmf() == -1) {
787 // This is first "normal" packet after CNG or DTMF.
788 // Reset packet time counter and measure time until next packet,
789 // but don't update statistics.
790 delay_manager_->set_last_pack_cng_or_dtmf(0);
791 delay_manager_->ResetPacketIatCount();
792 }
793 return 0;
794}
795
henrik.lundin6d8e0112016-03-04 10:34:21 -0800796int NetEqImpl::GetAudioInternal(AudioFrame* audio_frame) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000797 PacketList packet_list;
798 DtmfEvent dtmf_event;
799 Operations operation;
800 bool play_dtmf;
henrik.lundined497212016-04-25 10:11:38 -0700801 tick_timer_->Increment();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000802 int return_value = GetDecision(&operation, &packet_list, &dtmf_event,
803 &play_dtmf);
804 if (return_value != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000805 last_mode_ = kModeError;
806 return return_value;
807 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000808
809 AudioDecoder::SpeechType speech_type;
810 int length = 0;
811 int decode_return_value = Decode(&packet_list, &operation,
812 &length, &speech_type);
813
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000814 assert(vad_.get());
815 bool sid_frame_available =
816 (operation == kRfc3389Cng && !packet_list.empty());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700817 vad_->Update(decoded_buffer_.get(), static_cast<size_t>(length), speech_type,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000818 sid_frame_available, fs_hz_);
819
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000820 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000821 switch (operation) {
822 case kNormal: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000823 DoNormal(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000824 break;
825 }
826 case kMerge: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000827 DoMerge(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000828 break;
829 }
830 case kExpand: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000831 return_value = DoExpand(play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000832 break;
833 }
Henrik Lundincf808d22015-05-27 14:33:29 +0200834 case kAccelerate:
835 case kFastAccelerate: {
836 const bool fast_accelerate =
837 enable_fast_accelerate_ && (operation == kFastAccelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000838 return_value = DoAccelerate(decoded_buffer_.get(), length, speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +0200839 play_dtmf, fast_accelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000840 break;
841 }
842 case kPreemptiveExpand: {
843 return_value = DoPreemptiveExpand(decoded_buffer_.get(), length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000844 speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000845 break;
846 }
847 case kRfc3389Cng:
848 case kRfc3389CngNoPacket: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000849 return_value = DoRfc3389Cng(&packet_list, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000850 break;
851 }
852 case kCodecInternalCng: {
853 // This handles the case when there is no transmission and the decoder
854 // should produce internal comfort noise.
855 // TODO(hlundin): Write test for codec-internal CNG.
minyuel6d92bf52015-09-23 15:20:39 +0200856 DoCodecInternalCng(decoded_buffer_.get(), length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000857 break;
858 }
859 case kDtmf: {
860 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000861 return_value = DoDtmf(dtmf_event, &play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000862 break;
863 }
864 case kAlternativePlc: {
865 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000866 DoAlternativePlc(false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000867 break;
868 }
869 case kAlternativePlcIncreaseTimestamp: {
870 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000871 DoAlternativePlc(true);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000872 break;
873 }
874 case kAudioRepetitionIncreaseTimestamp: {
875 // TODO(hlundin): Write test for this.
Peter Kastingb7e50542015-06-11 12:55:50 -0700876 sync_buffer_->IncreaseEndTimestamp(
877 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000878 // Skipping break on purpose. Execution should move on into the
879 // next case.
kjellander@webrtc.org7d2b6a92015-01-28 18:37:58 +0000880 FALLTHROUGH();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000881 }
882 case kAudioRepetition: {
883 // TODO(hlundin): Write test for this.
884 // Copy last |output_size_samples_| from |sync_buffer_| to
885 // |algorithm_buffer|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000886 algorithm_buffer_->PushBackFromIndex(
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000887 *sync_buffer_, sync_buffer_->Size() - output_size_samples_);
888 expand_->Reset();
889 break;
890 }
891 case kUndefined: {
Henrik Lundind67a2192015-08-03 12:54:37 +0200892 LOG(LS_ERROR) << "Invalid operation kUndefined.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000893 assert(false); // This should not happen.
894 last_mode_ = kModeError;
895 return kInvalidOperation;
896 }
897 } // End of switch.
898 if (return_value < 0) {
899 return return_value;
900 }
901
902 if (last_mode_ != kModeRfc3389Cng) {
903 comfort_noise_->Reset();
904 }
905
906 // Copy from |algorithm_buffer| to |sync_buffer_|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000907 sync_buffer_->PushBack(*algorithm_buffer_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000908
909 // Extract data from |sync_buffer_| to |output|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000910 size_t num_output_samples_per_channel = output_size_samples_;
911 size_t num_output_samples = output_size_samples_ * sync_buffer_->Channels();
henrik.lundin6d8e0112016-03-04 10:34:21 -0800912 if (num_output_samples > AudioFrame::kMaxDataSizeSamples) {
913 LOG(LS_WARNING) << "Output array is too short. "
914 << AudioFrame::kMaxDataSizeSamples << " < "
915 << output_size_samples_ << " * "
916 << sync_buffer_->Channels();
917 num_output_samples = AudioFrame::kMaxDataSizeSamples;
918 num_output_samples_per_channel =
919 AudioFrame::kMaxDataSizeSamples / sync_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000920 }
henrik.lundin6d8e0112016-03-04 10:34:21 -0800921 sync_buffer_->GetNextAudioInterleaved(num_output_samples_per_channel,
922 audio_frame);
923 audio_frame->sample_rate_hz_ = fs_hz_;
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200924 if (sync_buffer_->FutureLength() < expand_->overlap_length()) {
925 // The sync buffer should always contain |overlap_length| samples, but now
926 // too many samples have been extracted. Reinstall the |overlap_length|
927 // lookahead by moving the index.
928 const size_t missing_lookahead_samples =
929 expand_->overlap_length() - sync_buffer_->FutureLength();
henrikg91d6ede2015-09-17 00:24:34 -0700930 RTC_DCHECK_GE(sync_buffer_->next_index(), missing_lookahead_samples);
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200931 sync_buffer_->set_next_index(sync_buffer_->next_index() -
932 missing_lookahead_samples);
933 }
henrik.lundin6d8e0112016-03-04 10:34:21 -0800934 if (audio_frame->samples_per_channel_ != output_size_samples_) {
935 LOG(LS_ERROR) << "audio_frame->samples_per_channel_ ("
936 << audio_frame->samples_per_channel_
Henrik Lundind67a2192015-08-03 12:54:37 +0200937 << ") != output_size_samples_ (" << output_size_samples_
938 << ")";
minyue@webrtc.orgdb1cefc2013-08-13 01:39:21 +0000939 // TODO(minyue): treatment of under-run, filling zeros
henrik.lundin6d8e0112016-03-04 10:34:21 -0800940 memset(audio_frame->data_, 0, num_output_samples * sizeof(int16_t));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000941 return kSampleUnderrun;
942 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000943
944 // Should always have overlap samples left in the |sync_buffer_|.
henrikg91d6ede2015-09-17 00:24:34 -0700945 RTC_DCHECK_GE(sync_buffer_->FutureLength(), expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000946
947 if (play_dtmf) {
henrik.lundin6d8e0112016-03-04 10:34:21 -0800948 return_value =
949 DtmfOverdub(dtmf_event, sync_buffer_->Channels(), audio_frame->data_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000950 }
951
952 // Update the background noise parameters if last operation wrote data
953 // straight from the decoder to the |sync_buffer_|. That is, none of the
954 // operations that modify the signal can be followed by a parameter update.
955 if ((last_mode_ == kModeNormal) ||
956 (last_mode_ == kModeAccelerateFail) ||
957 (last_mode_ == kModePreemptiveExpandFail) ||
958 (last_mode_ == kModeRfc3389Cng) ||
959 (last_mode_ == kModeCodecInternalCng)) {
960 background_noise_->Update(*sync_buffer_, *vad_.get());
961 }
962
963 if (operation == kDtmf) {
964 // DTMF data was written the end of |sync_buffer_|.
965 // Update index to end of DTMF data in |sync_buffer_|.
966 sync_buffer_->set_dtmf_index(sync_buffer_->Size());
967 }
968
henrik.lundin@webrtc.orged865b52014-03-06 10:28:07 +0000969 if (last_mode_ != kModeExpand) {
970 // If last operation was not expand, calculate the |playout_timestamp_| from
971 // the |sync_buffer_|. However, do not update the |playout_timestamp_| if it
972 // would be moved "backwards".
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000973 uint32_t temp_timestamp = sync_buffer_->end_timestamp() -
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000974 static_cast<uint32_t>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000975 if (static_cast<int32_t>(temp_timestamp - playout_timestamp_) > 0) {
976 playout_timestamp_ = temp_timestamp;
977 }
978 } else {
979 // Use dead reckoning to estimate the |playout_timestamp_|.
Peter Kastingb7e50542015-06-11 12:55:50 -0700980 playout_timestamp_ += static_cast<uint32_t>(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000981 }
henrik.lundin15c51e32016-04-06 08:38:56 -0700982 // Set the timestamp in the audio frame to zero before the first packet has
983 // been inserted. Otherwise, subtract the frame size in samples to get the
984 // timestamp of the first sample in the frame (playout_timestamp_ is the
985 // last + 1).
986 audio_frame->timestamp_ =
987 first_packet_
988 ? 0
989 : timestamp_scaler_->ToExternal(playout_timestamp_) -
990 static_cast<uint32_t>(audio_frame->samples_per_channel_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000991
992 if (decode_return_value) return decode_return_value;
993 return return_value;
994}
995
996int NetEqImpl::GetDecision(Operations* operation,
997 PacketList* packet_list,
998 DtmfEvent* dtmf_event,
999 bool* play_dtmf) {
1000 // Initialize output variables.
1001 *play_dtmf = false;
1002 *operation = kUndefined;
1003
1004 // Increment time counters.
1005 packet_buffer_->IncrementWaitingTimes();
1006 stats_.IncreaseCounter(output_size_samples_, fs_hz_);
1007
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001008 assert(sync_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001009 uint32_t end_timestamp = sync_buffer_->end_timestamp();
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001010 if (!new_codec_) {
1011 const uint32_t five_seconds_samples = 5 * fs_hz_;
1012 packet_buffer_->DiscardOldPackets(end_timestamp, five_seconds_samples);
1013 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001014 const RTPHeader* header = packet_buffer_->NextRtpHeader();
1015
henrik.lundin@webrtc.orgca8cb952014-03-12 10:26:52 +00001016 if (decision_logic_->CngRfc3389On() || last_mode_ == kModeRfc3389Cng) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001017 // Because of timestamp peculiarities, we have to "manually" disallow using
1018 // a CNG packet with the same timestamp as the one that was last played.
1019 // This can happen when using redundancy and will cause the timing to shift.
henrik.lundin@webrtc.org24779fe2014-03-14 12:40:05 +00001020 while (header && decoder_database_->IsComfortNoise(header->payloadType) &&
1021 (end_timestamp >= header->timestamp ||
1022 end_timestamp + decision_logic_->generated_noise_samples() >
1023 header->timestamp)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001024 // Don't use this packet, discard it.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001025 if (packet_buffer_->DiscardNextPacket() != PacketBuffer::kOK) {
1026 assert(false); // Must be ok by design.
1027 }
1028 // Check buffer again.
1029 if (!new_codec_) {
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001030 packet_buffer_->DiscardOldPackets(end_timestamp, 5 * fs_hz_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001031 }
1032 header = packet_buffer_->NextRtpHeader();
1033 }
1034 }
1035
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001036 assert(expand_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001037 const int samples_left = static_cast<int>(sync_buffer_->FutureLength() -
1038 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001039 if (last_mode_ == kModeAccelerateSuccess ||
1040 last_mode_ == kModeAccelerateLowEnergy ||
1041 last_mode_ == kModePreemptiveExpandSuccess ||
1042 last_mode_ == kModePreemptiveExpandLowEnergy) {
1043 // Subtract (samples_left + output_size_samples_) from sampleMemory.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001044 decision_logic_->AddSampleMemory(
1045 -(samples_left + rtc::checked_cast<int>(output_size_samples_)));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001046 }
1047
1048 // Check if it is time to play a DTMF event.
Peter Kastingb7e50542015-06-11 12:55:50 -07001049 if (dtmf_buffer_->GetEvent(
1050 static_cast<uint32_t>(
1051 end_timestamp + decision_logic_->generated_noise_samples()),
1052 dtmf_event)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001053 *play_dtmf = true;
1054 }
1055
1056 // Get instruction.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001057 assert(sync_buffer_.get());
1058 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001059 *operation = decision_logic_->GetDecision(*sync_buffer_,
1060 *expand_,
1061 decoder_frame_length_,
1062 header,
1063 last_mode_,
1064 *play_dtmf,
1065 &reset_decoder_);
1066
1067 // Check if we already have enough samples in the |sync_buffer_|. If so,
1068 // change decision to normal, unless the decision was merge, accelerate, or
1069 // preemptive expand.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001070 if (samples_left >= rtc::checked_cast<int>(output_size_samples_) &&
1071 *operation != kMerge &&
1072 *operation != kAccelerate &&
1073 *operation != kFastAccelerate &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001074 *operation != kPreemptiveExpand) {
1075 *operation = kNormal;
1076 return 0;
1077 }
1078
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001079 decision_logic_->ExpandDecision(*operation);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001080
1081 // Check conditions for reset.
1082 if (new_codec_ || *operation == kUndefined) {
1083 // The only valid reason to get kUndefined is that new_codec_ is set.
1084 assert(new_codec_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001085 if (*play_dtmf && !header) {
1086 timestamp_ = dtmf_event->timestamp;
1087 } else {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001088 if (!header) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001089 LOG(LS_ERROR) << "Packet missing where it shouldn't.";
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001090 return -1;
1091 }
1092 timestamp_ = header->timestamp;
1093 if (*operation == kRfc3389CngNoPacket
1094#ifndef LEGACY_BITEXACT
1095 // Without this check, it can happen that a non-CNG packet is sent to
1096 // the CNG decoder as if it was a SID frame. This is clearly a bug,
1097 // but is kept for now to maintain bit-exactness with the test
1098 // vectors.
1099 && decoder_database_->IsComfortNoise(header->payloadType)
1100#endif
1101 ) {
1102 // Change decision to CNG packet, since we do have a CNG packet, but it
1103 // was considered too early to use. Now, use it anyway.
1104 *operation = kRfc3389Cng;
1105 } else if (*operation != kRfc3389Cng) {
1106 *operation = kNormal;
1107 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001108 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001109 // Adjust |sync_buffer_| timestamp before setting |end_timestamp| to the
1110 // new value.
1111 sync_buffer_->IncreaseEndTimestamp(timestamp_ - end_timestamp);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001112 end_timestamp = timestamp_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001113 new_codec_ = false;
1114 decision_logic_->SoftReset();
1115 buffer_level_filter_->Reset();
1116 delay_manager_->Reset();
1117 stats_.ResetMcu();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001118 }
1119
Peter Kastingdce40cf2015-08-24 14:52:23 -07001120 size_t required_samples = output_size_samples_;
1121 const size_t samples_10_ms = static_cast<size_t>(80 * fs_mult_);
1122 const size_t samples_20_ms = 2 * samples_10_ms;
1123 const size_t samples_30_ms = 3 * samples_10_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001124
1125 switch (*operation) {
1126 case kExpand: {
1127 timestamp_ = end_timestamp;
1128 return 0;
1129 }
1130 case kRfc3389CngNoPacket:
1131 case kCodecInternalCng: {
1132 return 0;
1133 }
1134 case kDtmf: {
1135 // TODO(hlundin): Write test for this.
1136 // Update timestamp.
1137 timestamp_ = end_timestamp;
1138 if (decision_logic_->generated_noise_samples() > 0 &&
1139 last_mode_ != kModeDtmf) {
1140 // Make a jump in timestamp due to the recently played comfort noise.
Peter Kastingb7e50542015-06-11 12:55:50 -07001141 uint32_t timestamp_jump =
1142 static_cast<uint32_t>(decision_logic_->generated_noise_samples());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001143 sync_buffer_->IncreaseEndTimestamp(timestamp_jump);
1144 timestamp_ += timestamp_jump;
1145 }
1146 decision_logic_->set_generated_noise_samples(0);
1147 return 0;
1148 }
Henrik Lundincf808d22015-05-27 14:33:29 +02001149 case kAccelerate:
1150 case kFastAccelerate: {
1151 // In order to do an accelerate we need at least 30 ms of audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001152 if (samples_left >= static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001153 // Already have enough data, so we do not need to extract any more.
1154 decision_logic_->set_sample_memory(samples_left);
1155 decision_logic_->set_prev_time_scale(true);
1156 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001157 } else if (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001158 decoder_frame_length_ >= samples_30_ms) {
1159 // Avoid decoding more data as it might overflow the playout buffer.
1160 *operation = kNormal;
1161 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001162 } else if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001163 decoder_frame_length_ < samples_30_ms) {
1164 // Build up decoded data by decoding at least 20 ms of audio data. Do
1165 // not perform accelerate yet, but wait until we only need to do one
1166 // decoding.
1167 required_samples = 2 * output_size_samples_;
1168 *operation = kNormal;
1169 }
1170 // If none of the above is true, we have one of two possible situations:
1171 // (1) 20 ms <= samples_left < 30 ms and decoder_frame_length_ < 30 ms; or
1172 // (2) samples_left < 10 ms and decoder_frame_length_ >= 30 ms.
1173 // In either case, we move on with the accelerate decision, and decode one
1174 // frame now.
1175 break;
1176 }
1177 case kPreemptiveExpand: {
1178 // In order to do a preemptive expand we need at least 30 ms of decoded
1179 // audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001180 if ((samples_left >= static_cast<int>(samples_30_ms)) ||
1181 (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001182 decoder_frame_length_ >= samples_30_ms)) {
1183 // Already have enough data, so we do not need to extract any more.
1184 // Or, avoid decoding more data as it might overflow the playout buffer.
1185 // Still try preemptive expand, though.
1186 decision_logic_->set_sample_memory(samples_left);
1187 decision_logic_->set_prev_time_scale(true);
1188 return 0;
1189 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07001190 if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001191 decoder_frame_length_ < samples_30_ms) {
1192 // Build up decoded data by decoding at least 20 ms of audio data.
1193 // Still try to perform preemptive expand.
1194 required_samples = 2 * output_size_samples_;
1195 }
1196 // Move on with the preemptive expand decision.
1197 break;
1198 }
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001199 case kMerge: {
1200 required_samples =
1201 std::max(merge_->RequiredFutureSamples(), required_samples);
1202 break;
1203 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001204 default: {
1205 // Do nothing.
1206 }
1207 }
1208
1209 // Get packets from buffer.
1210 int extracted_samples = 0;
1211 if (header &&
1212 *operation != kAlternativePlc &&
1213 *operation != kAlternativePlcIncreaseTimestamp &&
1214 *operation != kAudioRepetition &&
1215 *operation != kAudioRepetitionIncreaseTimestamp) {
1216 sync_buffer_->IncreaseEndTimestamp(header->timestamp - end_timestamp);
1217 if (decision_logic_->CngOff()) {
1218 // Adjustment of timestamp only corresponds to an actual packet loss
1219 // if comfort noise is not played. If comfort noise was just played,
1220 // this adjustment of timestamp is only done to get back in sync with the
1221 // stream timestamp; no loss to report.
1222 stats_.LostSamples(header->timestamp - end_timestamp);
1223 }
1224
1225 if (*operation != kRfc3389Cng) {
1226 // We are about to decode and use a non-CNG packet.
1227 decision_logic_->SetCngOff();
1228 }
1229 // Reset CNG timestamp as a new packet will be delivered.
1230 // (Also if this is a CNG packet, since playedOutTS is updated.)
1231 decision_logic_->set_generated_noise_samples(0);
1232
1233 extracted_samples = ExtractPackets(required_samples, packet_list);
1234 if (extracted_samples < 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001235 return kPacketBufferCorruption;
1236 }
1237 }
1238
Henrik Lundincf808d22015-05-27 14:33:29 +02001239 if (*operation == kAccelerate || *operation == kFastAccelerate ||
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001240 *operation == kPreemptiveExpand) {
1241 decision_logic_->set_sample_memory(samples_left + extracted_samples);
1242 decision_logic_->set_prev_time_scale(true);
1243 }
1244
Henrik Lundincf808d22015-05-27 14:33:29 +02001245 if (*operation == kAccelerate || *operation == kFastAccelerate) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001246 // Check that we have enough data (30ms) to do accelerate.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001247 if (extracted_samples + samples_left < static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001248 // TODO(hlundin): Write test for this.
1249 // Not enough, do normal operation instead.
1250 *operation = kNormal;
1251 }
1252 }
1253
1254 timestamp_ = end_timestamp;
1255 return 0;
1256}
1257
1258int NetEqImpl::Decode(PacketList* packet_list, Operations* operation,
1259 int* decoded_length,
1260 AudioDecoder::SpeechType* speech_type) {
1261 *speech_type = AudioDecoder::kSpeech;
minyuel6d92bf52015-09-23 15:20:39 +02001262
1263 // When packet_list is empty, we may be in kCodecInternalCng mode, and for
1264 // that we use current active decoder.
1265 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1266
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001267 if (!packet_list->empty()) {
1268 const Packet* packet = packet_list->front();
pkasting@chromium.org0e81fdf2015-02-02 23:54:03 +00001269 uint8_t payload_type = packet->header.payloadType;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001270 if (!decoder_database_->IsComfortNoise(payload_type)) {
1271 decoder = decoder_database_->GetDecoder(payload_type);
1272 assert(decoder);
1273 if (!decoder) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001274 LOG(LS_WARNING) << "Unknown payload type "
1275 << static_cast<int>(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001276 PacketBuffer::DeleteAllPackets(packet_list);
1277 return kDecoderNotFound;
1278 }
1279 bool decoder_changed;
1280 decoder_database_->SetActiveDecoder(payload_type, &decoder_changed);
1281 if (decoder_changed) {
1282 // We have a new decoder. Re-init some values.
1283 const DecoderDatabase::DecoderInfo* decoder_info = decoder_database_
1284 ->GetDecoderInfo(payload_type);
1285 assert(decoder_info);
1286 if (!decoder_info) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001287 LOG(LS_WARNING) << "Unknown payload type "
1288 << static_cast<int>(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001289 PacketBuffer::DeleteAllPackets(packet_list);
1290 return kDecoderNotFound;
1291 }
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001292 // If sampling rate or number of channels has changed, we need to make
1293 // a reset.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001294 if (decoder_info->fs_hz != fs_hz_ ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001295 decoder->Channels() != algorithm_buffer_->Channels()) {
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001296 // TODO(tlegrand): Add unittest to cover this event.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001297 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->Channels());
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001298 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001299 sync_buffer_->set_end_timestamp(timestamp_);
1300 playout_timestamp_ = timestamp_;
1301 }
1302 }
1303 }
1304
1305 if (reset_decoder_) {
1306 // TODO(hlundin): Write test for this.
Karl Wiberg43766482015-08-27 15:22:11 +02001307 if (decoder)
1308 decoder->Reset();
1309
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001310 // Reset comfort noise decoder.
ossu97ba30e2016-04-25 07:55:58 -07001311 ComfortNoiseDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02001312 if (cng_decoder)
1313 cng_decoder->Reset();
1314
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001315 reset_decoder_ = false;
1316 }
1317
1318#ifdef LEGACY_BITEXACT
1319 // Due to a bug in old SignalMCU, it could happen that CNG operation was
1320 // decided, but a speech packet was provided. The speech packet will be used
1321 // to update the comfort noise decoder, as if it was a SID frame, which is
1322 // clearly wrong.
1323 if (*operation == kRfc3389Cng) {
1324 return 0;
1325 }
1326#endif
1327
1328 *decoded_length = 0;
1329 // Update codec-internal PLC state.
1330 if ((*operation == kMerge) && decoder && decoder->HasDecodePlc()) {
1331 decoder->DecodePlc(1, &decoded_buffer_[*decoded_length]);
1332 }
1333
minyuel6d92bf52015-09-23 15:20:39 +02001334 int return_value;
1335 if (*operation == kCodecInternalCng) {
1336 RTC_DCHECK(packet_list->empty());
1337 return_value = DecodeCng(decoder, decoded_length, speech_type);
1338 } else {
1339 return_value = DecodeLoop(packet_list, *operation, decoder,
1340 decoded_length, speech_type);
1341 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001342
1343 if (*decoded_length < 0) {
1344 // Error returned from the decoder.
1345 *decoded_length = 0;
Peter Kastingb7e50542015-06-11 12:55:50 -07001346 sync_buffer_->IncreaseEndTimestamp(
1347 static_cast<uint32_t>(decoder_frame_length_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001348 int error_code = 0;
1349 if (decoder)
1350 error_code = decoder->ErrorCode();
1351 if (error_code != 0) {
1352 // Got some error code from the decoder.
1353 decoder_error_code_ = error_code;
1354 return_value = kDecoderErrorCode;
Henrik Lundind67a2192015-08-03 12:54:37 +02001355 LOG(LS_WARNING) << "Decoder returned error code: " << error_code;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001356 } else {
1357 // Decoder does not implement error codes. Return generic error.
1358 return_value = kOtherDecoderError;
Henrik Lundind67a2192015-08-03 12:54:37 +02001359 LOG(LS_WARNING) << "Decoder error (no error code)";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001360 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001361 *operation = kExpand; // Do expansion to get data instead.
1362 }
1363 if (*speech_type != AudioDecoder::kComfortNoise) {
1364 // Don't increment timestamp if codec returned CNG speech type
1365 // since in this case, the we will increment the CNGplayedTS counter.
1366 // Increase with number of samples per channel.
1367 assert(*decoded_length == 0 ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001368 (decoder && decoder->Channels() == sync_buffer_->Channels()));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001369 sync_buffer_->IncreaseEndTimestamp(
1370 *decoded_length / static_cast<int>(sync_buffer_->Channels()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001371 }
1372 return return_value;
1373}
1374
minyuel6d92bf52015-09-23 15:20:39 +02001375int NetEqImpl::DecodeCng(AudioDecoder* decoder, int* decoded_length,
1376 AudioDecoder::SpeechType* speech_type) {
1377 if (!decoder) {
1378 // This happens when active decoder is not defined.
1379 *decoded_length = -1;
1380 return 0;
1381 }
1382
1383 while (*decoded_length < rtc::checked_cast<int>(output_size_samples_)) {
1384 const int length = decoder->Decode(
1385 nullptr, 0, fs_hz_,
1386 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1387 &decoded_buffer_[*decoded_length], speech_type);
1388 if (length > 0) {
1389 *decoded_length += length;
minyuel6d92bf52015-09-23 15:20:39 +02001390 } else {
1391 // Error.
1392 LOG(LS_WARNING) << "Failed to decode CNG";
1393 *decoded_length = -1;
1394 break;
1395 }
1396 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1397 // Guard against overflow.
1398 LOG(LS_WARNING) << "Decoded too much CNG.";
1399 return kDecodedTooMuch;
1400 }
1401 }
1402 return 0;
1403}
1404
1405int NetEqImpl::DecodeLoop(PacketList* packet_list, const Operations& operation,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001406 AudioDecoder* decoder, int* decoded_length,
1407 AudioDecoder::SpeechType* speech_type) {
1408 Packet* packet = NULL;
1409 if (!packet_list->empty()) {
1410 packet = packet_list->front();
1411 }
minyuel6d92bf52015-09-23 15:20:39 +02001412
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001413 // Do decoding.
1414 while (packet &&
1415 !decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1416 assert(decoder); // At this point, we must have a decoder object.
1417 // The number of channels in the |sync_buffer_| should be the same as the
1418 // number decoder channels.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001419 assert(sync_buffer_->Channels() == decoder->Channels());
1420 assert(decoded_buffer_length_ >= kMaxFrameSize * decoder->Channels());
minyuel6d92bf52015-09-23 15:20:39 +02001421 assert(operation == kNormal || operation == kAccelerate ||
1422 operation == kFastAccelerate || operation == kMerge ||
1423 operation == kPreemptiveExpand);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001424 packet_list->pop_front();
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001425 size_t payload_length = packet->payload_length;
Peter Kasting36b7cc32015-06-11 19:57:18 -07001426 int decode_length;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +00001427 if (packet->sync_packet) {
1428 // Decode to silence with the same frame size as the last decode.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001429 memset(&decoded_buffer_[*decoded_length], 0,
1430 decoder_frame_length_ * decoder->Channels() *
1431 sizeof(decoded_buffer_[0]));
Peter Kastingdce40cf2015-08-24 14:52:23 -07001432 decode_length = rtc::checked_cast<int>(decoder_frame_length_);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +00001433 } else if (!packet->primary) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001434 // This is a redundant payload; call the special decoder method.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001435 decode_length = decoder->DecodeRedundant(
henrik.lundin@webrtc.org1eda4e32015-02-25 10:02:29 +00001436 packet->payload, packet->payload_length, fs_hz_,
minyue@webrtc.org7f7d7e32015-03-16 12:30:37 +00001437 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001438 &decoded_buffer_[*decoded_length], speech_type);
1439 } else {
henrik.lundin@webrtc.org1eda4e32015-02-25 10:02:29 +00001440 decode_length =
minyue@webrtc.org7f7d7e32015-03-16 12:30:37 +00001441 decoder->Decode(
1442 packet->payload, packet->payload_length, fs_hz_,
1443 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1444 &decoded_buffer_[*decoded_length], speech_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001445 }
1446
1447 delete[] packet->payload;
1448 delete packet;
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001449 packet = NULL;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001450 if (decode_length > 0) {
1451 *decoded_length += decode_length;
1452 // Update |decoder_frame_length_| with number of samples per channel.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001453 decoder_frame_length_ =
Peter Kastingdce40cf2015-08-24 14:52:23 -07001454 static_cast<size_t>(decode_length) / decoder->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001455 } else if (decode_length < 0) {
1456 // Error.
Henrik Lundind67a2192015-08-03 12:54:37 +02001457 LOG(LS_WARNING) << "Decode " << decode_length << " " << payload_length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001458 *decoded_length = -1;
1459 PacketBuffer::DeleteAllPackets(packet_list);
1460 break;
1461 }
1462 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1463 // Guard against overflow.
Henrik Lundind67a2192015-08-03 12:54:37 +02001464 LOG(LS_WARNING) << "Decoded too much.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001465 PacketBuffer::DeleteAllPackets(packet_list);
1466 return kDecodedTooMuch;
1467 }
1468 if (!packet_list->empty()) {
1469 packet = packet_list->front();
1470 } else {
1471 packet = NULL;
1472 }
1473 } // End of decode loop.
1474
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001475 // If the list is not empty at this point, either a decoding error terminated
1476 // the while-loop, or list must hold exactly one CNG packet.
1477 assert(packet_list->empty() || *decoded_length < 0 ||
1478 (packet_list->size() == 1 && packet &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001479 decoder_database_->IsComfortNoise(packet->header.payloadType)));
1480 return 0;
1481}
1482
1483void NetEqImpl::DoNormal(const int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001484 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001485 assert(normal_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001486 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001487 normal_->Process(decoded_buffer, decoded_length, last_mode_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001488 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001489 if (decoded_length != 0) {
1490 last_mode_ = kModeNormal;
1491 }
1492
1493 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1494 if ((speech_type == AudioDecoder::kComfortNoise)
1495 || ((last_mode_ == kModeCodecInternalCng)
1496 && (decoded_length == 0))) {
1497 // TODO(hlundin): Remove second part of || statement above.
1498 last_mode_ = kModeCodecInternalCng;
1499 }
1500
1501 if (!play_dtmf) {
1502 dtmf_tone_generator_->Reset();
1503 }
1504}
1505
1506void NetEqImpl::DoMerge(int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001507 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001508 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001509 assert(merge_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001510 size_t new_length = merge_->Process(decoded_buffer, decoded_length,
1511 mute_factor_array_.get(),
1512 algorithm_buffer_.get());
1513 size_t expand_length_correction = new_length -
1514 decoded_length / algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001515
1516 // Update in-call and post-call statistics.
1517 if (expand_->MuteFactor(0) == 0) {
1518 // Expand generates only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001519 stats_.ExpandedNoiseSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001520 } else {
1521 // Expansion generates more than only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001522 stats_.ExpandedVoiceSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001523 }
1524
1525 last_mode_ = kModeMerge;
1526 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1527 if (speech_type == AudioDecoder::kComfortNoise) {
1528 last_mode_ = kModeCodecInternalCng;
1529 }
1530 expand_->Reset();
1531 if (!play_dtmf) {
1532 dtmf_tone_generator_->Reset();
1533 }
1534}
1535
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001536int NetEqImpl::DoExpand(bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001537 while ((sync_buffer_->FutureLength() - expand_->overlap_length()) <
Peter Kastingdce40cf2015-08-24 14:52:23 -07001538 output_size_samples_) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001539 algorithm_buffer_->Clear();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001540 int return_value = expand_->Process(algorithm_buffer_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001541 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001542
1543 // Update in-call and post-call statistics.
1544 if (expand_->MuteFactor(0) == 0) {
1545 // Expand operation generates only noise.
1546 stats_.ExpandedNoiseSamples(length);
1547 } else {
1548 // Expand operation generates more than only noise.
1549 stats_.ExpandedVoiceSamples(length);
1550 }
1551
1552 last_mode_ = kModeExpand;
1553
1554 if (return_value < 0) {
1555 return return_value;
1556 }
1557
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001558 sync_buffer_->PushBack(*algorithm_buffer_);
1559 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001560 }
1561 if (!play_dtmf) {
1562 dtmf_tone_generator_->Reset();
1563 }
1564 return 0;
1565}
1566
Henrik Lundincf808d22015-05-27 14:33:29 +02001567int NetEqImpl::DoAccelerate(int16_t* decoded_buffer,
1568 size_t decoded_length,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001569 AudioDecoder::SpeechType speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +02001570 bool play_dtmf,
1571 bool fast_accelerate) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001572 const size_t required_samples =
1573 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001574 size_t borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001575 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001576 size_t decoded_length_per_channel = decoded_length / num_channels;
1577 if (decoded_length_per_channel < required_samples) {
1578 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001579 borrowed_samples_per_channel = static_cast<int>(required_samples -
1580 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001581 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1582 decoded_buffer,
1583 sizeof(int16_t) * decoded_length);
1584 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1585 decoded_buffer);
1586 decoded_length = required_samples * num_channels;
1587 }
1588
Peter Kastingdce40cf2015-08-24 14:52:23 -07001589 size_t samples_removed;
Henrik Lundincf808d22015-05-27 14:33:29 +02001590 Accelerate::ReturnCodes return_code =
1591 accelerate_->Process(decoded_buffer, decoded_length, fast_accelerate,
1592 algorithm_buffer_.get(), &samples_removed);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001593 stats_.AcceleratedSamples(samples_removed);
1594 switch (return_code) {
1595 case Accelerate::kSuccess:
1596 last_mode_ = kModeAccelerateSuccess;
1597 break;
1598 case Accelerate::kSuccessLowEnergy:
1599 last_mode_ = kModeAccelerateLowEnergy;
1600 break;
1601 case Accelerate::kNoStretch:
1602 last_mode_ = kModeAccelerateFail;
1603 break;
1604 case Accelerate::kError:
1605 // TODO(hlundin): Map to kModeError instead?
1606 last_mode_ = kModeAccelerateFail;
1607 return kAccelerateError;
1608 }
1609
1610 if (borrowed_samples_per_channel > 0) {
1611 // Copy borrowed samples back to the |sync_buffer_|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001612 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001613 if (length < borrowed_samples_per_channel) {
1614 // This destroys the beginning of the buffer, but will not cause any
1615 // problems.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001616 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001617 sync_buffer_->Size() -
1618 borrowed_samples_per_channel);
1619 sync_buffer_->PushFrontZeros(borrowed_samples_per_channel - length);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001620 algorithm_buffer_->PopFront(length);
1621 assert(algorithm_buffer_->Empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001622 } else {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001623 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001624 borrowed_samples_per_channel,
1625 sync_buffer_->Size() -
1626 borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001627 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001628 }
1629 }
1630
1631 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1632 if (speech_type == AudioDecoder::kComfortNoise) {
1633 last_mode_ = kModeCodecInternalCng;
1634 }
1635 if (!play_dtmf) {
1636 dtmf_tone_generator_->Reset();
1637 }
1638 expand_->Reset();
1639 return 0;
1640}
1641
1642int NetEqImpl::DoPreemptiveExpand(int16_t* decoded_buffer,
1643 size_t decoded_length,
1644 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001645 bool play_dtmf) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001646 const size_t required_samples =
1647 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001648 size_t num_channels = algorithm_buffer_->Channels();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001649 size_t borrowed_samples_per_channel = 0;
1650 size_t old_borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001651 size_t decoded_length_per_channel = decoded_length / num_channels;
1652 if (decoded_length_per_channel < required_samples) {
1653 // Must move data from the |sync_buffer_| in order to get 30 ms.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001654 borrowed_samples_per_channel =
1655 required_samples - decoded_length_per_channel;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001656 // Calculate how many of these were already played out.
Peter Kastingf045e4d2015-06-10 21:15:38 -07001657 old_borrowed_samples_per_channel =
Peter Kastingdce40cf2015-08-24 14:52:23 -07001658 (borrowed_samples_per_channel > sync_buffer_->FutureLength()) ?
1659 (borrowed_samples_per_channel - sync_buffer_->FutureLength()) : 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001660 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1661 decoded_buffer,
1662 sizeof(int16_t) * decoded_length);
1663 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1664 decoded_buffer);
1665 decoded_length = required_samples * num_channels;
1666 }
1667
Peter Kastingdce40cf2015-08-24 14:52:23 -07001668 size_t samples_added;
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001669 PreemptiveExpand::ReturnCodes return_code = preemptive_expand_->Process(
Peter Kastingdce40cf2015-08-24 14:52:23 -07001670 decoded_buffer, decoded_length,
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001671 old_borrowed_samples_per_channel,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001672 algorithm_buffer_.get(), &samples_added);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001673 stats_.PreemptiveExpandedSamples(samples_added);
1674 switch (return_code) {
1675 case PreemptiveExpand::kSuccess:
1676 last_mode_ = kModePreemptiveExpandSuccess;
1677 break;
1678 case PreemptiveExpand::kSuccessLowEnergy:
1679 last_mode_ = kModePreemptiveExpandLowEnergy;
1680 break;
1681 case PreemptiveExpand::kNoStretch:
1682 last_mode_ = kModePreemptiveExpandFail;
1683 break;
1684 case PreemptiveExpand::kError:
1685 // TODO(hlundin): Map to kModeError instead?
1686 last_mode_ = kModePreemptiveExpandFail;
1687 return kPreemptiveExpandError;
1688 }
1689
1690 if (borrowed_samples_per_channel > 0) {
1691 // Copy borrowed samples back to the |sync_buffer_|.
1692 sync_buffer_->ReplaceAtIndex(
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001693 *algorithm_buffer_, borrowed_samples_per_channel,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001694 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001695 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001696 }
1697
1698 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1699 if (speech_type == AudioDecoder::kComfortNoise) {
1700 last_mode_ = kModeCodecInternalCng;
1701 }
1702 if (!play_dtmf) {
1703 dtmf_tone_generator_->Reset();
1704 }
1705 expand_->Reset();
1706 return 0;
1707}
1708
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001709int NetEqImpl::DoRfc3389Cng(PacketList* packet_list, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001710 if (!packet_list->empty()) {
1711 // Must have exactly one SID frame at this point.
1712 assert(packet_list->size() == 1);
1713 Packet* packet = packet_list->front();
1714 packet_list->pop_front();
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001715 if (!decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1716#ifdef LEGACY_BITEXACT
1717 // This can happen due to a bug in GetDecision. Change the payload type
1718 // to a CNG type, and move on. Note that this means that we are in fact
1719 // sending a non-CNG payload to the comfort noise decoder for decoding.
1720 // Clearly wrong, but will maintain bit-exactness with legacy.
1721 if (fs_hz_ == 8000) {
1722 packet->header.payloadType =
kwibergee1879c2015-10-29 06:20:28 -07001723 decoder_database_->GetRtpPayloadType(NetEqDecoder::kDecoderCNGnb);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001724 } else if (fs_hz_ == 16000) {
1725 packet->header.payloadType =
kwibergee1879c2015-10-29 06:20:28 -07001726 decoder_database_->GetRtpPayloadType(NetEqDecoder::kDecoderCNGwb);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001727 } else if (fs_hz_ == 32000) {
kwibergee1879c2015-10-29 06:20:28 -07001728 packet->header.payloadType = decoder_database_->GetRtpPayloadType(
1729 NetEqDecoder::kDecoderCNGswb32kHz);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001730 } else if (fs_hz_ == 48000) {
kwibergee1879c2015-10-29 06:20:28 -07001731 packet->header.payloadType = decoder_database_->GetRtpPayloadType(
1732 NetEqDecoder::kDecoderCNGswb48kHz);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001733 }
1734 assert(decoder_database_->IsComfortNoise(packet->header.payloadType));
1735#else
1736 LOG(LS_ERROR) << "Trying to decode non-CNG payload as CNG.";
1737 return kOtherError;
1738#endif
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001739 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001740 // UpdateParameters() deletes |packet|.
1741 if (comfort_noise_->UpdateParameters(packet) ==
1742 ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001743 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001744 return -comfort_noise_->internal_error_code();
1745 }
1746 }
1747 int cn_return = comfort_noise_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001748 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001749 expand_->Reset();
1750 last_mode_ = kModeRfc3389Cng;
1751 if (!play_dtmf) {
1752 dtmf_tone_generator_->Reset();
1753 }
1754 if (cn_return == ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001755 decoder_error_code_ = comfort_noise_->internal_error_code();
1756 return kComfortNoiseErrorCode;
1757 } else if (cn_return == ComfortNoise::kUnknownPayloadType) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001758 return kUnknownRtpPayloadType;
1759 }
1760 return 0;
1761}
1762
minyuel6d92bf52015-09-23 15:20:39 +02001763void NetEqImpl::DoCodecInternalCng(const int16_t* decoded_buffer,
1764 size_t decoded_length) {
1765 RTC_DCHECK(normal_.get());
1766 RTC_DCHECK(mute_factor_array_.get());
1767 normal_->Process(decoded_buffer, decoded_length, last_mode_,
1768 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001769 last_mode_ = kModeCodecInternalCng;
1770 expand_->Reset();
1771}
1772
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001773int NetEqImpl::DoDtmf(const DtmfEvent& dtmf_event, bool* play_dtmf) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001774 // This block of the code and the block further down, handling |dtmf_switch|
1775 // are commented out. Otherwise playing out-of-band DTMF would fail in VoE
1776 // test, DtmfTest.ManualSuccessfullySendsOutOfBandTelephoneEvents. This is
1777 // equivalent to |dtmf_switch| always be false.
1778 //
1779 // See http://webrtc-codereview.appspot.com/1195004/ for discussion
1780 // On this issue. This change might cause some glitches at the point of
1781 // switch from audio to DTMF. Issue 1545 is filed to track this.
1782 //
1783 // bool dtmf_switch = false;
1784 // if ((last_mode_ != kModeDtmf) && dtmf_tone_generator_->initialized()) {
1785 // // Special case; see below.
1786 // // We must catch this before calling Generate, since |initialized| is
1787 // // modified in that call.
1788 // dtmf_switch = true;
1789 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001790
1791 int dtmf_return_value = 0;
1792 if (!dtmf_tone_generator_->initialized()) {
1793 // Initialize if not already done.
1794 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1795 dtmf_event.volume);
1796 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001797
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001798 if (dtmf_return_value == 0) {
1799 // Generate DTMF signal.
1800 dtmf_return_value = dtmf_tone_generator_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001801 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001802 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001803
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001804 if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001805 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001806 return dtmf_return_value;
1807 }
1808
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001809 // if (dtmf_switch) {
1810 // // This is the special case where the previous operation was DTMF
1811 // // overdub, but the current instruction is "regular" DTMF. We must make
1812 // // sure that the DTMF does not have any discontinuities. The first DTMF
1813 // // sample that we generate now must be played out immediately, therefore
1814 // // it must be copied to the speech buffer.
1815 // // TODO(hlundin): This code seems incorrect. (Legacy.) Write test and
1816 // // verify correct operation.
1817 // assert(false);
1818 // // Must generate enough data to replace all of the |sync_buffer_|
1819 // // "future".
1820 // int required_length = sync_buffer_->FutureLength();
1821 // assert(dtmf_tone_generator_->initialized());
1822 // dtmf_return_value = dtmf_tone_generator_->Generate(required_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001823 // algorithm_buffer_);
1824 // assert((size_t) required_length == algorithm_buffer_->Size());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001825 // if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001826 // algorithm_buffer_->Zeros(output_size_samples_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001827 // return dtmf_return_value;
1828 // }
1829 //
1830 // // Overwrite the "future" part of the speech buffer with the new DTMF
1831 // // data.
1832 // // TODO(hlundin): It seems that this overwriting has gone lost.
1833 // // Not adapted for multi-channel yet.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001834 // assert(algorithm_buffer_->Channels() == 1);
1835 // if (algorithm_buffer_->Channels() != 1) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001836 // LOG(LS_WARNING) << "DTMF not supported for more than one channel";
1837 // return kStereoNotSupported;
1838 // }
1839 // // Shuffle the remaining data to the beginning of algorithm buffer.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001840 // algorithm_buffer_->PopFront(sync_buffer_->FutureLength());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001841 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001842
Peter Kastingb7e50542015-06-11 12:55:50 -07001843 sync_buffer_->IncreaseEndTimestamp(
1844 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001845 expand_->Reset();
1846 last_mode_ = kModeDtmf;
1847
1848 // Set to false because the DTMF is already in the algorithm buffer.
1849 *play_dtmf = false;
1850 return 0;
1851}
1852
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001853void NetEqImpl::DoAlternativePlc(bool increase_timestamp) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001854 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001855 size_t length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001856 if (decoder && decoder->HasDecodePlc()) {
1857 // Use the decoder's packet-loss concealment.
1858 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1859 int16_t decoded_buffer[kMaxFrameSize];
1860 length = decoder->DecodePlc(1, decoded_buffer);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001861 if (length > 0)
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001862 algorithm_buffer_->PushBackInterleaved(decoded_buffer, length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001863 } else {
1864 // Do simple zero-stuffing.
1865 length = output_size_samples_;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001866 algorithm_buffer_->Zeros(length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001867 // By not advancing the timestamp, NetEq inserts samples.
1868 stats_.AddZeros(length);
1869 }
1870 if (increase_timestamp) {
Peter Kastingb7e50542015-06-11 12:55:50 -07001871 sync_buffer_->IncreaseEndTimestamp(static_cast<uint32_t>(length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001872 }
1873 expand_->Reset();
1874}
1875
1876int NetEqImpl::DtmfOverdub(const DtmfEvent& dtmf_event, size_t num_channels,
1877 int16_t* output) const {
1878 size_t out_index = 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001879 size_t overdub_length = output_size_samples_; // Default value.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001880
1881 if (sync_buffer_->dtmf_index() > sync_buffer_->next_index()) {
1882 // Special operation for transition from "DTMF only" to "DTMF overdub".
1883 out_index = std::min(
1884 sync_buffer_->dtmf_index() - sync_buffer_->next_index(),
Peter Kastingdce40cf2015-08-24 14:52:23 -07001885 output_size_samples_);
1886 overdub_length = output_size_samples_ - out_index;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001887 }
1888
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001889 AudioMultiVector dtmf_output(num_channels);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001890 int dtmf_return_value = 0;
1891 if (!dtmf_tone_generator_->initialized()) {
1892 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1893 dtmf_event.volume);
1894 }
1895 if (dtmf_return_value == 0) {
1896 dtmf_return_value = dtmf_tone_generator_->Generate(overdub_length,
1897 &dtmf_output);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001898 assert(overdub_length == dtmf_output.Size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001899 }
1900 dtmf_output.ReadInterleaved(overdub_length, &output[out_index]);
1901 return dtmf_return_value < 0 ? dtmf_return_value : 0;
1902}
1903
Peter Kastingdce40cf2015-08-24 14:52:23 -07001904int NetEqImpl::ExtractPackets(size_t required_samples,
1905 PacketList* packet_list) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001906 bool first_packet = true;
1907 uint8_t prev_payload_type = 0;
1908 uint32_t prev_timestamp = 0;
1909 uint16_t prev_sequence_number = 0;
1910 bool next_packet_available = false;
1911
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001912 const RTPHeader* header = packet_buffer_->NextRtpHeader();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001913 assert(header);
1914 if (!header) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001915 LOG(LS_ERROR) << "Packet buffer unexpectedly empty.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001916 return -1;
1917 }
turaj@webrtc.org7df97062013-08-02 18:07:13 +00001918 uint32_t first_timestamp = header->timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001919 int extracted_samples = 0;
1920
1921 // Packet extraction loop.
1922 do {
1923 timestamp_ = header->timestamp;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001924 size_t discard_count = 0;
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001925 Packet* packet = packet_buffer_->GetNextPacket(&discard_count);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001926 // |header| may be invalid after the |packet_buffer_| operation.
1927 header = NULL;
1928 if (!packet) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001929 LOG(LS_ERROR) << "Should always be able to extract a packet here";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001930 assert(false); // Should always be able to extract a packet here.
1931 return -1;
1932 }
1933 stats_.PacketsDiscarded(discard_count);
1934 // Store waiting time in ms; packets->waiting_time is in "output blocks".
1935 stats_.StoreWaitingTime(packet->waiting_time * kOutputSizeMs);
1936 assert(packet->payload_length > 0);
1937 packet_list->push_back(packet); // Store packet in list.
1938
1939 if (first_packet) {
1940 first_packet = false;
henrik.lundin48ed9302015-10-29 05:36:24 -07001941 if (nack_enabled_) {
1942 RTC_DCHECK(nack_);
1943 // TODO(henrik.lundin): Should we update this for all decoded packets?
1944 nack_->UpdateLastDecodedPacket(packet->header.sequenceNumber,
1945 packet->header.timestamp);
1946 }
1947 prev_sequence_number = packet->header.sequenceNumber;
1948 prev_timestamp = packet->header.timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001949 prev_payload_type = packet->header.payloadType;
1950 }
1951
1952 // Store number of extracted samples.
1953 int packet_duration = 0;
1954 AudioDecoder* decoder = decoder_database_->GetDecoder(
1955 packet->header.payloadType);
1956 if (decoder) {
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001957 if (packet->sync_packet) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001958 packet_duration = rtc::checked_cast<int>(decoder_frame_length_);
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001959 } else {
minyue@webrtc.org2c1bcf22015-02-17 10:17:09 +00001960 if (packet->primary) {
1961 packet_duration = decoder->PacketDuration(packet->payload,
1962 packet->payload_length);
1963 } else {
1964 packet_duration = decoder->
1965 PacketDurationRedundant(packet->payload, packet->payload_length);
1966 stats_.SecondaryDecodedSamples(packet_duration);
1967 }
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001968 }
ossu97ba30e2016-04-25 07:55:58 -07001969 } else if (!decoder_database_->IsComfortNoise(packet->header.payloadType)) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001970 LOG(LS_WARNING) << "Unknown payload type "
1971 << static_cast<int>(packet->header.payloadType);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001972 assert(false);
1973 }
1974 if (packet_duration <= 0) {
1975 // Decoder did not return a packet duration. Assume that the packet
1976 // contains the same number of samples as the previous one.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001977 packet_duration = rtc::checked_cast<int>(decoder_frame_length_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001978 }
1979 extracted_samples = packet->header.timestamp - first_timestamp +
1980 packet_duration;
1981
1982 // Check what packet is available next.
1983 header = packet_buffer_->NextRtpHeader();
1984 next_packet_available = false;
1985 if (header && prev_payload_type == header->payloadType) {
1986 int16_t seq_no_diff = header->sequenceNumber - prev_sequence_number;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001987 size_t ts_diff = header->timestamp - prev_timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001988 if (seq_no_diff == 1 ||
1989 (seq_no_diff == 0 && ts_diff == decoder_frame_length_)) {
1990 // The next sequence number is available, or the next part of a packet
1991 // that was split into pieces upon insertion.
1992 next_packet_available = true;
1993 }
1994 prev_sequence_number = header->sequenceNumber;
1995 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07001996 } while (extracted_samples < rtc::checked_cast<int>(required_samples) &&
1997 next_packet_available);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001998
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00001999 if (extracted_samples > 0) {
2000 // Delete old packets only when we are going to decode something. Otherwise,
2001 // we could end up in the situation where we never decode anything, since
2002 // all incoming packets are considered too old but the buffer will also
2003 // never be flooded and flushed.
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00002004 packet_buffer_->DiscardAllOldPackets(timestamp_);
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00002005 }
2006
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002007 return extracted_samples;
2008}
2009
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002010void NetEqImpl::UpdatePlcComponents(int fs_hz, size_t channels) {
2011 // Delete objects and create new ones.
2012 expand_.reset(expand_factory_->Create(background_noise_.get(),
2013 sync_buffer_.get(), &random_vector_,
Henrik Lundinbef77e22015-08-18 14:58:09 +02002014 &stats_, fs_hz, channels));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002015 merge_.reset(new Merge(fs_hz, channels, expand_.get(), sync_buffer_.get()));
2016}
2017
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002018void NetEqImpl::SetSampleRateAndChannels(int fs_hz, size_t channels) {
Henrik Lundind67a2192015-08-03 12:54:37 +02002019 LOG(LS_VERBOSE) << "SetSampleRateAndChannels " << fs_hz << " " << channels;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002020 // TODO(hlundin): Change to an enumerator and skip assert.
2021 assert(fs_hz == 8000 || fs_hz == 16000 || fs_hz == 32000 || fs_hz == 48000);
2022 assert(channels > 0);
2023
2024 fs_hz_ = fs_hz;
2025 fs_mult_ = fs_hz / 8000;
Peter Kastingdce40cf2015-08-24 14:52:23 -07002026 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002027 decoder_frame_length_ = 3 * output_size_samples_; // Initialize to 30ms.
2028
2029 last_mode_ = kModeNormal;
2030
2031 // Create a new array of mute factors and set all to 1.
2032 mute_factor_array_.reset(new int16_t[channels]);
2033 for (size_t i = 0; i < channels; ++i) {
2034 mute_factor_array_[i] = 16384; // 1.0 in Q14.
2035 }
2036
ossu97ba30e2016-04-25 07:55:58 -07002037 ComfortNoiseDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02002038 if (cng_decoder)
2039 cng_decoder->Reset();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002040
2041 // Reinit post-decode VAD with new sample rate.
2042 assert(vad_.get()); // Cannot be NULL here.
2043 vad_->Init();
2044
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002045 // Delete algorithm buffer and create a new one.
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00002046 algorithm_buffer_.reset(new AudioMultiVector(channels));
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002047
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002048 // Delete sync buffer and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002049 sync_buffer_.reset(new SyncBuffer(channels, kSyncBufferSize * fs_mult_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002050
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00002051 // Delete BackgroundNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002052 background_noise_.reset(new BackgroundNoise(channels));
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00002053 background_noise_->set_mode(background_noise_mode_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002054
2055 // Reset random vector.
2056 random_vector_.Reset();
2057
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002058 UpdatePlcComponents(fs_hz, channels);
2059
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002060 // Move index so that we create a small set of future samples (all 0).
2061 sync_buffer_->set_next_index(sync_buffer_->next_index() -
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002062 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002063
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002064 normal_.reset(new Normal(fs_hz, decoder_database_.get(), *background_noise_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002065 expand_.get()));
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +00002066 accelerate_.reset(
2067 accelerate_factory_->Create(fs_hz, channels, *background_noise_));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002068 preemptive_expand_.reset(preemptive_expand_factory_->Create(
Peter Kastingdce40cf2015-08-24 14:52:23 -07002069 fs_hz, channels, *background_noise_, expand_->overlap_length()));
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002070
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002071 // Delete ComfortNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002072 comfort_noise_.reset(new ComfortNoise(fs_hz, decoder_database_.get(),
2073 sync_buffer_.get()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002074
2075 // Verify that |decoded_buffer_| is long enough.
2076 if (decoded_buffer_length_ < kMaxFrameSize * channels) {
2077 // Reallocate to larger size.
2078 decoded_buffer_length_ = kMaxFrameSize * channels;
2079 decoded_buffer_.reset(new int16_t[decoded_buffer_length_]);
2080 }
2081
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002082 // Create DecisionLogic if it is not created yet, then communicate new sample
2083 // rate and output size to DecisionLogic object.
2084 if (!decision_logic_.get()) {
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002085 CreateDecisionLogic();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002086 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002087 decision_logic_->SetSampleRate(fs_hz_, output_size_samples_);
2088}
2089
henrik.lundin55480f52016-03-08 02:37:57 -08002090NetEqImpl::OutputType NetEqImpl::LastOutputType() {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002091 assert(vad_.get());
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002092 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002093 if (last_mode_ == kModeCodecInternalCng || last_mode_ == kModeRfc3389Cng) {
henrik.lundin55480f52016-03-08 02:37:57 -08002094 return OutputType::kCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002095 } else if (last_mode_ == kModeExpand && expand_->MuteFactor(0) == 0) {
2096 // Expand mode has faded down to background noise only (very long expand).
henrik.lundin55480f52016-03-08 02:37:57 -08002097 return OutputType::kPLCCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002098 } else if (last_mode_ == kModeExpand) {
henrik.lundin55480f52016-03-08 02:37:57 -08002099 return OutputType::kPLC;
wu@webrtc.org24301a62013-12-13 19:17:43 +00002100 } else if (vad_->running() && !vad_->active_speech()) {
henrik.lundin55480f52016-03-08 02:37:57 -08002101 return OutputType::kVadPassive;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002102 } else {
henrik.lundin55480f52016-03-08 02:37:57 -08002103 return OutputType::kNormalSpeech;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002104 }
2105}
2106
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002107void NetEqImpl::CreateDecisionLogic() {
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002108 decision_logic_.reset(DecisionLogic::Create(fs_hz_, output_size_samples_,
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002109 playout_mode_,
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002110 decoder_database_.get(),
2111 *packet_buffer_.get(),
2112 delay_manager_.get(),
2113 buffer_level_filter_.get()));
2114}
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002115} // namespace webrtc