blob: 2eb22772ee0f31fd9604259351636af251800914 [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.lundin1d9061e2016-04-26 12:19:34 -070057NetEqImpl::Dependencies::Dependencies(const NetEq::Config& config)
58 : tick_timer(new TickTimer),
59 buffer_level_filter(new BufferLevelFilter),
60 decoder_database(new DecoderDatabase),
henrik.lundinf3933702016-04-28 01:53:52 -070061 delay_peak_detector(new DelayPeakDetector(tick_timer.get())),
henrik.lundin1d9061e2016-04-26 12:19:34 -070062 delay_manager(new DelayManager(config.max_packets_in_buffer,
henrik.lundin8f8c96d2016-04-28 23:19:20 -070063 delay_peak_detector.get(),
64 tick_timer.get())),
henrik.lundin1d9061e2016-04-26 12:19:34 -070065 dtmf_buffer(new DtmfBuffer(config.sample_rate_hz)),
66 dtmf_tone_generator(new DtmfToneGenerator),
67 packet_buffer(
68 new PacketBuffer(config.max_packets_in_buffer, tick_timer.get())),
69 payload_splitter(new PayloadSplitter),
70 timestamp_scaler(new TimestampScaler(*decoder_database)),
71 accelerate_factory(new AccelerateFactory),
72 expand_factory(new ExpandFactory),
73 preemptive_expand_factory(new PreemptiveExpandFactory) {}
74
75NetEqImpl::Dependencies::~Dependencies() = default;
76
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +000077NetEqImpl::NetEqImpl(const NetEq::Config& config,
henrik.lundin1d9061e2016-04-26 12:19:34 -070078 Dependencies&& deps,
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +000079 bool create_components)
henrik.lundin1d9061e2016-04-26 12:19:34 -070080 : tick_timer_(std::move(deps.tick_timer)),
81 buffer_level_filter_(std::move(deps.buffer_level_filter)),
82 decoder_database_(std::move(deps.decoder_database)),
83 delay_manager_(std::move(deps.delay_manager)),
84 delay_peak_detector_(std::move(deps.delay_peak_detector)),
85 dtmf_buffer_(std::move(deps.dtmf_buffer)),
86 dtmf_tone_generator_(std::move(deps.dtmf_tone_generator)),
87 packet_buffer_(std::move(deps.packet_buffer)),
88 payload_splitter_(std::move(deps.payload_splitter)),
89 timestamp_scaler_(std::move(deps.timestamp_scaler)),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000090 vad_(new PostDecodeVad()),
henrik.lundin1d9061e2016-04-26 12:19:34 -070091 expand_factory_(std::move(deps.expand_factory)),
92 accelerate_factory_(std::move(deps.accelerate_factory)),
93 preemptive_expand_factory_(std::move(deps.preemptive_expand_factory)),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000094 last_mode_(kModeNormal),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000095 decoded_buffer_length_(kMaxFrameSize),
96 decoded_buffer_(new int16_t[decoded_buffer_length_]),
97 playout_timestamp_(0),
98 new_codec_(false),
99 timestamp_(0),
100 reset_decoder_(false),
henrik.lundin48ed9302015-10-29 05:36:24 -0700101 current_rtp_payload_type_(0xFF), // Invalid RTP payload type.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000102 current_cng_rtp_payload_type_(0xFF), // Invalid RTP payload type.
103 ssrc_(0),
104 first_packet_(true),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000105 error_code_(0),
106 decoder_error_code_(0),
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +0000107 background_noise_mode_(config.background_noise_mode),
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000108 playout_mode_(config.playout_mode),
Henrik Lundincf808d22015-05-27 14:33:29 +0200109 enable_fast_accelerate_(config.enable_fast_accelerate),
henrik.lundin48ed9302015-10-29 05:36:24 -0700110 nack_enabled_(false) {
Henrik Lundin905495c2015-05-25 16:58:41 +0200111 LOG(LS_INFO) << "NetEq config: " << config.ToString();
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +0000112 int fs = config.sample_rate_hz;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000113 if (fs != 8000 && fs != 16000 && fs != 32000 && fs != 48000) {
114 LOG(LS_ERROR) << "Sample rate " << fs << " Hz not supported. " <<
115 "Changing to 8000 Hz.";
116 fs = 8000;
117 }
henrik.lundin1d9061e2016-04-26 12:19:34 -0700118 delay_manager_->SetMaximumDelay(config.max_delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000119 fs_hz_ = fs;
120 fs_mult_ = fs / 8000;
henrik.lundind89814b2015-11-23 06:49:25 -0800121 last_output_sample_rate_hz_ = fs;
Peter Kastingdce40cf2015-08-24 14:52:23 -0700122 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000123 decoder_frame_length_ = 3 * output_size_samples_;
124 WebRtcSpl_Init();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000125 if (create_components) {
126 SetSampleRateAndChannels(fs, 1); // Default is 1 channel.
127 }
henrik.lundin9bc26672015-11-02 03:25:57 -0800128 RTC_DCHECK(!vad_->enabled());
129 if (config.enable_post_decode_vad) {
130 vad_->Enable();
131 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000132}
133
Henrik Lundind67a2192015-08-03 12:54:37 +0200134NetEqImpl::~NetEqImpl() = default;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000135
136int NetEqImpl::InsertPacket(const WebRtcRTPHeader& rtp_header,
kwibergee2bac22015-11-11 10:34:00 -0800137 rtc::ArrayView<const uint8_t> payload,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000138 uint32_t receive_timestamp) {
henrik.lundina689b442015-12-17 03:50:05 -0800139 TRACE_EVENT0("webrtc", "NetEqImpl::InsertPacket");
Tommi9090e0b2016-01-20 13:39:36 +0100140 rtc::CritScope lock(&crit_sect_);
kwibergee2bac22015-11-11 10:34:00 -0800141 int error =
142 InsertPacketInternal(rtp_header, payload, receive_timestamp, false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000143 if (error != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000144 error_code_ = error;
145 return kFail;
146 }
147 return kOK;
148}
149
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000150int NetEqImpl::InsertSyncPacket(const WebRtcRTPHeader& rtp_header,
151 uint32_t receive_timestamp) {
Tommi9090e0b2016-01-20 13:39:36 +0100152 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000153 const uint8_t kSyncPayload[] = { 's', 'y', 'n', 'c' };
kwibergee2bac22015-11-11 10:34:00 -0800154 int error =
155 InsertPacketInternal(rtp_header, kSyncPayload, receive_timestamp, true);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000156
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000157 if (error != 0) {
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000158 error_code_ = error;
159 return kFail;
160 }
161 return kOK;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000162}
163
henrik.lundin500c04b2016-03-08 02:36:04 -0800164namespace {
165void SetAudioFrameActivityAndType(bool vad_enabled,
henrik.lundin55480f52016-03-08 02:37:57 -0800166 NetEqImpl::OutputType type,
henrik.lundin500c04b2016-03-08 02:36:04 -0800167 AudioFrame::VADActivity last_vad_activity,
168 AudioFrame* audio_frame) {
169 switch (type) {
henrik.lundin55480f52016-03-08 02:37:57 -0800170 case NetEqImpl::OutputType::kNormalSpeech: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800171 audio_frame->speech_type_ = AudioFrame::kNormalSpeech;
172 audio_frame->vad_activity_ = AudioFrame::kVadActive;
173 break;
174 }
henrik.lundin55480f52016-03-08 02:37:57 -0800175 case NetEqImpl::OutputType::kVadPassive: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800176 // This should only be reached if the VAD is enabled.
177 RTC_DCHECK(vad_enabled);
178 audio_frame->speech_type_ = AudioFrame::kNormalSpeech;
179 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
180 break;
181 }
henrik.lundin55480f52016-03-08 02:37:57 -0800182 case NetEqImpl::OutputType::kCNG: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800183 audio_frame->speech_type_ = AudioFrame::kCNG;
184 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
185 break;
186 }
henrik.lundin55480f52016-03-08 02:37:57 -0800187 case NetEqImpl::OutputType::kPLC: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800188 audio_frame->speech_type_ = AudioFrame::kPLC;
189 audio_frame->vad_activity_ = last_vad_activity;
190 break;
191 }
henrik.lundin55480f52016-03-08 02:37:57 -0800192 case NetEqImpl::OutputType::kPLCCNG: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800193 audio_frame->speech_type_ = AudioFrame::kPLCCNG;
194 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
195 break;
196 }
197 default:
198 RTC_NOTREACHED();
199 }
200 if (!vad_enabled) {
201 // Always set kVadUnknown when receive VAD is inactive.
202 audio_frame->vad_activity_ = AudioFrame::kVadUnknown;
203 }
204}
henrik.lundinbc89de32016-03-08 05:20:14 -0800205} // namespace
henrik.lundin500c04b2016-03-08 02:36:04 -0800206
henrik.lundin55480f52016-03-08 02:37:57 -0800207int NetEqImpl::GetAudio(AudioFrame* audio_frame) {
henrik.lundine1ca1672016-01-08 03:50:08 -0800208 TRACE_EVENT0("webrtc", "NetEqImpl::GetAudio");
Tommi9090e0b2016-01-20 13:39:36 +0100209 rtc::CritScope lock(&crit_sect_);
henrik.lundin6d8e0112016-03-04 10:34:21 -0800210 int error = GetAudioInternal(audio_frame);
211 RTC_DCHECK_EQ(
212 audio_frame->sample_rate_hz_,
213 rtc::checked_cast<int>(audio_frame->samples_per_channel_ * 100));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000214 if (error != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000215 error_code_ = error;
216 return kFail;
217 }
henrik.lundin500c04b2016-03-08 02:36:04 -0800218 SetAudioFrameActivityAndType(vad_->enabled(), LastOutputType(),
219 last_vad_activity_, audio_frame);
220 last_vad_activity_ = audio_frame->vad_activity_;
henrik.lundin6d8e0112016-03-04 10:34:21 -0800221 last_output_sample_rate_hz_ = audio_frame->sample_rate_hz_;
henrik.lundind89814b2015-11-23 06:49:25 -0800222 RTC_DCHECK(last_output_sample_rate_hz_ == 8000 ||
223 last_output_sample_rate_hz_ == 16000 ||
224 last_output_sample_rate_hz_ == 32000 ||
225 last_output_sample_rate_hz_ == 48000)
226 << "Unexpected sample rate " << last_output_sample_rate_hz_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000227 return kOK;
228}
229
kwibergee1879c2015-10-29 06:20:28 -0700230int NetEqImpl::RegisterPayloadType(NetEqDecoder codec,
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800231 const std::string& name,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000232 uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100233 rtc::CritScope lock(&crit_sect_);
Henrik Lundind67a2192015-08-03 12:54:37 +0200234 LOG(LS_VERBOSE) << "RegisterPayloadType "
kwibergee1879c2015-10-29 06:20:28 -0700235 << static_cast<int>(rtp_payload_type) << " "
236 << static_cast<int>(codec);
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800237 int ret = decoder_database_->RegisterPayload(rtp_payload_type, codec, name);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000238 if (ret != DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000239 switch (ret) {
240 case DecoderDatabase::kInvalidRtpPayloadType:
241 error_code_ = kInvalidRtpPayloadType;
242 break;
243 case DecoderDatabase::kCodecNotSupported:
244 error_code_ = kCodecNotSupported;
245 break;
246 case DecoderDatabase::kDecoderExists:
247 error_code_ = kDecoderExists;
248 break;
249 default:
250 error_code_ = kOtherError;
251 }
252 return kFail;
253 }
254 return kOK;
255}
256
257int NetEqImpl::RegisterExternalDecoder(AudioDecoder* decoder,
kwibergee1879c2015-10-29 06:20:28 -0700258 NetEqDecoder codec,
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800259 const std::string& codec_name,
Karl Wibergd8399e62015-05-25 14:39:56 +0200260 uint8_t rtp_payload_type,
261 int sample_rate_hz) {
Tommi9090e0b2016-01-20 13:39:36 +0100262 rtc::CritScope lock(&crit_sect_);
Henrik Lundind67a2192015-08-03 12:54:37 +0200263 LOG(LS_VERBOSE) << "RegisterExternalDecoder "
kwibergee1879c2015-10-29 06:20:28 -0700264 << static_cast<int>(rtp_payload_type) << " "
265 << static_cast<int>(codec);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000266 if (!decoder) {
267 LOG(LS_ERROR) << "Cannot register external decoder with NULL pointer";
268 assert(false);
269 return kFail;
270 }
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800271 int ret = decoder_database_->InsertExternal(
272 rtp_payload_type, codec, codec_name, sample_rate_hz, decoder);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000273 if (ret != DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000274 switch (ret) {
275 case DecoderDatabase::kInvalidRtpPayloadType:
276 error_code_ = kInvalidRtpPayloadType;
277 break;
278 case DecoderDatabase::kCodecNotSupported:
279 error_code_ = kCodecNotSupported;
280 break;
281 case DecoderDatabase::kDecoderExists:
282 error_code_ = kDecoderExists;
283 break;
284 case DecoderDatabase::kInvalidSampleRate:
285 error_code_ = kInvalidSampleRate;
286 break;
287 case DecoderDatabase::kInvalidPointer:
288 error_code_ = kInvalidPointer;
289 break;
290 default:
291 error_code_ = kOtherError;
292 }
293 return kFail;
294 }
295 return kOK;
296}
297
298int NetEqImpl::RemovePayloadType(uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100299 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000300 int ret = decoder_database_->Remove(rtp_payload_type);
301 if (ret == DecoderDatabase::kOK) {
302 return kOK;
303 } else if (ret == DecoderDatabase::kDecoderNotFound) {
304 error_code_ = kDecoderNotFound;
305 } else {
306 error_code_ = kOtherError;
307 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000308 return kFail;
309}
310
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000311bool NetEqImpl::SetMinimumDelay(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) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000314 assert(delay_manager_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000315 return delay_manager_->SetMinimumDelay(delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000316 }
317 return false;
318}
319
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000320bool NetEqImpl::SetMaximumDelay(int delay_ms) {
Tommi9090e0b2016-01-20 13:39:36 +0100321 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000322 if (delay_ms >= 0 && delay_ms < 10000) {
323 assert(delay_manager_.get());
324 return delay_manager_->SetMaximumDelay(delay_ms);
325 }
326 return false;
327}
328
329int NetEqImpl::LeastRequiredDelayMs() const {
Tommi9090e0b2016-01-20 13:39:36 +0100330 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000331 assert(delay_manager_.get());
332 return delay_manager_->least_required_delay_ms();
333}
334
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200335int NetEqImpl::SetTargetDelay() {
336 return kNotImplemented;
337}
338
339int NetEqImpl::TargetDelay() {
340 return kNotImplemented;
341}
342
henrik.lundin9c3efd02015-08-27 13:12:22 -0700343int NetEqImpl::CurrentDelayMs() const {
Tommi9090e0b2016-01-20 13:39:36 +0100344 rtc::CritScope lock(&crit_sect_);
henrik.lundin9c3efd02015-08-27 13:12:22 -0700345 if (fs_hz_ == 0)
346 return 0;
347 // Sum up the samples in the packet buffer with the future length of the sync
348 // buffer, and divide the sum by the sample rate.
349 const size_t delay_samples =
350 packet_buffer_->NumSamplesInBuffer(decoder_database_.get(),
351 decoder_frame_length_) +
352 sync_buffer_->FutureLength();
353 // The division below will truncate.
354 const int delay_ms =
355 static_cast<int>(delay_samples) / rtc::CheckedDivExact(fs_hz_, 1000);
356 return delay_ms;
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200357}
358
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000359// Deprecated.
360// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000361void NetEqImpl::SetPlayoutMode(NetEqPlayoutMode mode) {
Tommi9090e0b2016-01-20 13:39:36 +0100362 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000363 if (mode != playout_mode_) {
364 playout_mode_ = mode;
365 CreateDecisionLogic();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000366 }
367}
368
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000369// Deprecated.
370// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000371NetEqPlayoutMode NetEqImpl::PlayoutMode() const {
Tommi9090e0b2016-01-20 13:39:36 +0100372 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000373 return playout_mode_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000374}
375
376int NetEqImpl::NetworkStatistics(NetEqNetworkStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100377 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000378 assert(decoder_database_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700379 const size_t total_samples_in_buffers =
Peter Kasting728d9032015-06-11 14:31:38 -0700380 packet_buffer_->NumSamplesInBuffer(decoder_database_.get(),
381 decoder_frame_length_) +
Peter Kastingdce40cf2015-08-24 14:52:23 -0700382 sync_buffer_->FutureLength();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000383 assert(delay_manager_.get());
384 assert(decision_logic_.get());
385 stats_.GetNetworkStatistics(fs_hz_, total_samples_in_buffers,
386 decoder_frame_length_, *delay_manager_.get(),
387 *decision_logic_.get(), stats);
388 return 0;
389}
390
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000391void NetEqImpl::GetRtcpStatistics(RtcpStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100392 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000393 if (stats) {
394 rtcp_.GetStatistics(false, stats);
395 }
396}
397
398void NetEqImpl::GetRtcpStatisticsNoReset(RtcpStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100399 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000400 if (stats) {
401 rtcp_.GetStatistics(true, stats);
402 }
403}
404
405void NetEqImpl::EnableVad() {
Tommi9090e0b2016-01-20 13:39:36 +0100406 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000407 assert(vad_.get());
408 vad_->Enable();
409}
410
411void NetEqImpl::DisableVad() {
Tommi9090e0b2016-01-20 13:39:36 +0100412 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000413 assert(vad_.get());
414 vad_->Disable();
415}
416
henrik.lundin15c51e32016-04-06 08:38:56 -0700417rtc::Optional<uint32_t> NetEqImpl::GetPlayoutTimestamp() const {
Tommi9090e0b2016-01-20 13:39:36 +0100418 rtc::CritScope lock(&crit_sect_);
henrik.lundin0d96ab72016-04-06 12:28:26 -0700419 if (first_packet_ || last_mode_ == kModeRfc3389Cng ||
420 last_mode_ == kModeCodecInternalCng) {
wu@webrtc.org94454b72014-06-05 20:34:08 +0000421 // We don't have a valid RTP timestamp until we have decoded our first
henrik.lundin0d96ab72016-04-06 12:28:26 -0700422 // RTP packet. Also, the RTP timestamp is not accurate while playing CNG,
423 // which is indicated by returning an empty value.
henrik.lundin9a410dd2016-04-06 01:39:22 -0700424 return rtc::Optional<uint32_t>();
wu@webrtc.org94454b72014-06-05 20:34:08 +0000425 }
henrik.lundin9a410dd2016-04-06 01:39:22 -0700426 return rtc::Optional<uint32_t>(
427 timestamp_scaler_->ToExternal(playout_timestamp_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000428}
429
henrik.lundind89814b2015-11-23 06:49:25 -0800430int NetEqImpl::last_output_sample_rate_hz() const {
Tommi9090e0b2016-01-20 13:39:36 +0100431 rtc::CritScope lock(&crit_sect_);
henrik.lundind89814b2015-11-23 06:49:25 -0800432 return last_output_sample_rate_hz_;
433}
434
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200435int NetEqImpl::SetTargetNumberOfChannels() {
436 return kNotImplemented;
437}
438
439int NetEqImpl::SetTargetSampleRate() {
440 return kNotImplemented;
441}
442
henrik.lundin@webrtc.orgb0f4b3d2014-11-04 08:53:10 +0000443int NetEqImpl::LastError() const {
Tommi9090e0b2016-01-20 13:39:36 +0100444 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000445 return error_code_;
446}
447
448int NetEqImpl::LastDecoderError() {
Tommi9090e0b2016-01-20 13:39:36 +0100449 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000450 return decoder_error_code_;
451}
452
453void NetEqImpl::FlushBuffers() {
Tommi9090e0b2016-01-20 13:39:36 +0100454 rtc::CritScope lock(&crit_sect_);
Henrik Lundind67a2192015-08-03 12:54:37 +0200455 LOG(LS_VERBOSE) << "FlushBuffers";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000456 packet_buffer_->Flush();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000457 assert(sync_buffer_.get());
458 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000459 sync_buffer_->Flush();
460 sync_buffer_->set_next_index(sync_buffer_->next_index() -
461 expand_->overlap_length());
462 // Set to wait for new codec.
463 first_packet_ = true;
464}
465
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000466void NetEqImpl::PacketBufferStatistics(int* current_num_packets,
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000467 int* max_num_packets) const {
Tommi9090e0b2016-01-20 13:39:36 +0100468 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000469 packet_buffer_->BufferStat(current_num_packets, max_num_packets);
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000470}
471
henrik.lundin48ed9302015-10-29 05:36:24 -0700472void NetEqImpl::EnableNack(size_t max_nack_list_size) {
Tommi9090e0b2016-01-20 13:39:36 +0100473 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700474 if (!nack_enabled_) {
475 const int kNackThresholdPackets = 2;
476 nack_.reset(Nack::Create(kNackThresholdPackets));
477 nack_enabled_ = true;
478 nack_->UpdateSampleRate(fs_hz_);
479 }
480 nack_->SetMaxNackListSize(max_nack_list_size);
481}
482
483void NetEqImpl::DisableNack() {
Tommi9090e0b2016-01-20 13:39:36 +0100484 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700485 nack_.reset();
486 nack_enabled_ = false;
487}
488
489std::vector<uint16_t> NetEqImpl::GetNackList(int64_t round_trip_time_ms) const {
Tommi9090e0b2016-01-20 13:39:36 +0100490 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700491 if (!nack_enabled_) {
492 return std::vector<uint16_t>();
493 }
494 RTC_DCHECK(nack_.get());
495 return nack_->GetNackList(round_trip_time_ms);
minyue@webrtc.orgd7301772013-08-29 00:58:14 +0000496}
497
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000498const SyncBuffer* NetEqImpl::sync_buffer_for_test() const {
Tommi9090e0b2016-01-20 13:39:36 +0100499 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000500 return sync_buffer_.get();
501}
502
minyue5bd33972016-05-02 04:46:11 -0700503Operations NetEqImpl::last_operation_for_test() const {
504 rtc::CritScope lock(&crit_sect_);
505 return last_operation_;
506}
507
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000508// Methods below this line are private.
509
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000510int NetEqImpl::InsertPacketInternal(const WebRtcRTPHeader& rtp_header,
kwibergee2bac22015-11-11 10:34:00 -0800511 rtc::ArrayView<const uint8_t> payload,
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000512 uint32_t receive_timestamp,
513 bool is_sync_packet) {
kwibergee2bac22015-11-11 10:34:00 -0800514 if (payload.empty()) {
515 LOG_F(LS_ERROR) << "payload is empty";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000516 return kInvalidPointer;
517 }
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000518 // Sanity checks for sync-packets.
519 if (is_sync_packet) {
520 if (decoder_database_->IsDtmf(rtp_header.header.payloadType) ||
521 decoder_database_->IsRed(rtp_header.header.payloadType) ||
522 decoder_database_->IsComfortNoise(rtp_header.header.payloadType)) {
523 LOG_F(LS_ERROR) << "Sync-packet with an unacceptable payload type "
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000524 << static_cast<int>(rtp_header.header.payloadType);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000525 return kSyncPacketNotAccepted;
526 }
527 if (first_packet_ ||
528 rtp_header.header.payloadType != current_rtp_payload_type_ ||
529 rtp_header.header.ssrc != ssrc_) {
530 // Even if |current_rtp_payload_type_| is 0xFF, sync-packet isn't
531 // accepted.
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000532 LOG_F(LS_ERROR)
533 << "Changing codec, SSRC or first packet with sync-packet.";
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000534 return kSyncPacketNotAccepted;
535 }
536 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000537 PacketList packet_list;
538 RTPHeader main_header;
539 {
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000540 // Convert to Packet.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000541 // Create |packet| within this separate scope, since it should not be used
542 // directly once it's been inserted in the packet list. This way, |packet|
543 // is not defined outside of this block.
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000544 Packet* packet = new Packet;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000545 packet->header.markerBit = false;
546 packet->header.payloadType = rtp_header.header.payloadType;
547 packet->header.sequenceNumber = rtp_header.header.sequenceNumber;
548 packet->header.timestamp = rtp_header.header.timestamp;
549 packet->header.ssrc = rtp_header.header.ssrc;
550 packet->header.numCSRCs = 0;
kwibergee2bac22015-11-11 10:34:00 -0800551 packet->payload_length = payload.size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000552 packet->primary = true;
henrik.lundin84f8cd62016-04-26 07:45:16 -0700553 // Waiting time will be set upon inserting the packet in the buffer.
554 RTC_DCHECK(!packet->waiting_time);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000555 packet->payload = new uint8_t[packet->payload_length];
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000556 packet->sync_packet = is_sync_packet;
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +0000557 if (!packet->payload) {
558 LOG_F(LS_ERROR) << "Payload pointer is NULL.";
559 }
kwibergee2bac22015-11-11 10:34:00 -0800560 assert(!payload.empty()); // Already checked above.
561 memcpy(packet->payload, payload.data(), packet->payload_length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000562 // Insert packet in a packet list.
563 packet_list.push_back(packet);
564 // Save main payloads header for later.
565 memcpy(&main_header, &packet->header, sizeof(main_header));
566 }
567
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000568 bool update_sample_rate_and_channels = false;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000569 // Reinitialize NetEq if it's needed (changed SSRC or first call).
570 if ((main_header.ssrc != ssrc_) || first_packet_) {
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000571 // Note: |first_packet_| will be cleared further down in this method, once
572 // the packet has been successfully inserted into the packet buffer.
573
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000574 rtcp_.Init(main_header.sequenceNumber);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000575
576 // Flush the packet buffer and DTMF buffer.
577 packet_buffer_->Flush();
578 dtmf_buffer_->Flush();
579
580 // Store new SSRC.
581 ssrc_ = main_header.ssrc;
582
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000583 // Update audio buffer timestamp.
584 sync_buffer_->IncreaseEndTimestamp(main_header.timestamp - timestamp_);
585
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000586 // Update codecs.
587 timestamp_ = main_header.timestamp;
588 current_rtp_payload_type_ = main_header.payloadType;
589
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000590 // Reset timestamp scaling.
591 timestamp_scaler_->Reset();
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000592
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000593 // Trigger an update of sampling rate and the number of channels.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000594 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000595 }
596
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000597 // Update RTCP statistics, only for regular packets.
598 if (!is_sync_packet)
599 rtcp_.Update(main_header, receive_timestamp);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000600
601 // Check for RED payload type, and separate payloads into several packets.
602 if (decoder_database_->IsRed(main_header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000603 assert(!is_sync_packet); // We had a sanity check for this.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000604 if (payload_splitter_->SplitRed(&packet_list) != PayloadSplitter::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000605 PacketBuffer::DeleteAllPackets(&packet_list);
606 return kRedundancySplitError;
607 }
608 // Only accept a few RED payloads of the same type as the main data,
609 // DTMF events and CNG.
610 payload_splitter_->CheckRedPayloads(&packet_list, *decoder_database_);
611 // Update the stored main payload header since the main payload has now
612 // changed.
613 memcpy(&main_header, &packet_list.front()->header, sizeof(main_header));
614 }
615
616 // Check payload types.
617 if (decoder_database_->CheckPayloadTypes(packet_list) ==
618 DecoderDatabase::kDecoderNotFound) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000619 PacketBuffer::DeleteAllPackets(&packet_list);
620 return kUnknownRtpPayloadType;
621 }
622
623 // Scale timestamp to internal domain (only for some codecs).
624 timestamp_scaler_->ToInternal(&packet_list);
625
626 // Process DTMF payloads. Cycle through the list of packets, and pick out any
627 // DTMF payloads found.
628 PacketList::iterator it = packet_list.begin();
629 while (it != packet_list.end()) {
630 Packet* current_packet = (*it);
631 assert(current_packet);
632 assert(current_packet->payload);
633 if (decoder_database_->IsDtmf(current_packet->header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000634 assert(!current_packet->sync_packet); // We had a sanity check for this.
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000635 DtmfEvent event;
636 int ret = DtmfBuffer::ParseEvent(
637 current_packet->header.timestamp,
638 current_packet->payload,
639 current_packet->payload_length,
640 &event);
641 if (ret != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000642 PacketBuffer::DeleteAllPackets(&packet_list);
643 return kDtmfParsingError;
644 }
645 if (dtmf_buffer_->InsertEvent(event) != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000646 PacketBuffer::DeleteAllPackets(&packet_list);
647 return kDtmfInsertError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000648 }
649 // TODO(hlundin): Let the destructor of Packet handle the payload.
650 delete [] current_packet->payload;
651 delete current_packet;
652 it = packet_list.erase(it);
653 } else {
654 ++it;
655 }
656 }
657
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000658 // Check for FEC in packets, and separate payloads into several packets.
659 int ret = payload_splitter_->SplitFec(&packet_list, decoder_database_.get());
660 if (ret != PayloadSplitter::kOK) {
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000661 PacketBuffer::DeleteAllPackets(&packet_list);
662 switch (ret) {
663 case PayloadSplitter::kUnknownPayloadType:
664 return kUnknownRtpPayloadType;
665 default:
666 return kOtherError;
667 }
668 }
669
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000670 // Split payloads into smaller chunks. This also verifies that all payloads
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000671 // are of a known payload type. SplitAudio() method is protected against
672 // sync-packets.
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +0000673 ret = payload_splitter_->SplitAudio(&packet_list, *decoder_database_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000674 if (ret != PayloadSplitter::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000675 PacketBuffer::DeleteAllPackets(&packet_list);
676 switch (ret) {
677 case PayloadSplitter::kUnknownPayloadType:
678 return kUnknownRtpPayloadType;
679 case PayloadSplitter::kFrameSplitError:
680 return kFrameSplitError;
681 default:
682 return kOtherError;
683 }
684 }
685
ossu97ba30e2016-04-25 07:55:58 -0700686 // Update bandwidth estimate, if the packet is not sync-packet nor comfort
687 // noise.
688 if (!packet_list.empty() && !packet_list.front()->sync_packet &&
689 !decoder_database_->IsComfortNoise(main_header.payloadType)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000690 // The list can be empty here if we got nothing but DTMF payloads.
691 AudioDecoder* decoder =
692 decoder_database_->GetDecoder(main_header.payloadType);
693 assert(decoder); // Should always get a valid object, since we have
ossu97ba30e2016-04-25 07:55:58 -0700694 // already checked that the payload types are known.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000695 decoder->IncomingPacket(packet_list.front()->payload,
696 packet_list.front()->payload_length,
697 packet_list.front()->header.sequenceNumber,
698 packet_list.front()->header.timestamp,
699 receive_timestamp);
700 }
701
henrik.lundin48ed9302015-10-29 05:36:24 -0700702 if (nack_enabled_) {
703 RTC_DCHECK(nack_);
704 if (update_sample_rate_and_channels) {
705 nack_->Reset();
706 }
707 nack_->UpdateLastReceivedPacket(packet_list.front()->header.sequenceNumber,
708 packet_list.front()->header.timestamp);
709 }
710
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000711 // Insert packets in buffer.
henrik.lundin116c84e2015-08-27 13:14:48 -0700712 const size_t buffer_length_before_insert =
713 packet_buffer_->NumPacketsInBuffer();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000714 ret = packet_buffer_->InsertPacketList(
715 &packet_list,
716 *decoder_database_,
717 &current_rtp_payload_type_,
718 &current_cng_rtp_payload_type_);
719 if (ret == PacketBuffer::kFlushed) {
720 // Reset DSP timestamp etc. if packet buffer flushed.
721 new_codec_ = true;
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000722 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000723 } else if (ret != PacketBuffer::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000724 PacketBuffer::DeleteAllPackets(&packet_list);
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000725 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000726 }
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000727
728 if (first_packet_) {
729 first_packet_ = false;
730 // Update the codec on the next GetAudio call.
731 new_codec_ = true;
732 }
733
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000734 if (current_rtp_payload_type_ != 0xFF) {
735 const DecoderDatabase::DecoderInfo* dec_info =
736 decoder_database_->GetDecoderInfo(current_rtp_payload_type_);
737 if (!dec_info) {
738 assert(false); // Already checked that the payload type is known.
739 }
740 }
741
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000742 if (update_sample_rate_and_channels && !packet_buffer_->Empty()) {
743 // We do not use |current_rtp_payload_type_| to |set payload_type|, but
744 // get the next RTP header from |packet_buffer_| to obtain the payload type.
745 // The reason for it is the following corner case. If NetEq receives a
746 // CNG packet with a sample rate different than the current CNG then it
747 // flushes its buffer, assuming send codec must have been changed. However,
748 // payload type of the hypothetically new send codec is not known.
749 const RTPHeader* rtp_header = packet_buffer_->NextRtpHeader();
750 assert(rtp_header);
751 int payload_type = rtp_header->payloadType;
ossu97ba30e2016-04-25 07:55:58 -0700752 size_t channels = 1;
753 if (!decoder_database_->IsComfortNoise(payload_type)) {
754 AudioDecoder* decoder = decoder_database_->GetDecoder(payload_type);
755 assert(decoder); // Payloads are already checked to be valid.
756 channels = decoder->Channels();
757 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000758 const DecoderDatabase::DecoderInfo* decoder_info =
759 decoder_database_->GetDecoderInfo(payload_type);
760 assert(decoder_info);
761 if (decoder_info->fs_hz != fs_hz_ ||
ossu97ba30e2016-04-25 07:55:58 -0700762 channels != algorithm_buffer_->Channels()) {
763 SetSampleRateAndChannels(decoder_info->fs_hz, channels);
henrik.lundin48ed9302015-10-29 05:36:24 -0700764 }
765 if (nack_enabled_) {
766 RTC_DCHECK(nack_);
767 // Update the sample rate even if the rate is not new, because of Reset().
768 nack_->UpdateSampleRate(fs_hz_);
769 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000770 }
771
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000772 // TODO(hlundin): Move this code to DelayManager class.
773 const DecoderDatabase::DecoderInfo* dec_info =
774 decoder_database_->GetDecoderInfo(main_header.payloadType);
775 assert(dec_info); // Already checked that the payload type is known.
776 delay_manager_->LastDecoderType(dec_info->codec_type);
777 if (delay_manager_->last_pack_cng_or_dtmf() == 0) {
778 // Calculate the total speech length carried in each packet.
henrik.lundin116c84e2015-08-27 13:14:48 -0700779 const size_t buffer_length_after_insert =
780 packet_buffer_->NumPacketsInBuffer();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000781
henrik.lundin116c84e2015-08-27 13:14:48 -0700782 if (buffer_length_after_insert > buffer_length_before_insert) {
783 const size_t packet_length_samples =
784 (buffer_length_after_insert - buffer_length_before_insert) *
785 decoder_frame_length_;
786 if (packet_length_samples != decision_logic_->packet_length_samples()) {
787 decision_logic_->set_packet_length_samples(packet_length_samples);
788 delay_manager_->SetPacketAudioLength(
789 rtc::checked_cast<int>((1000 * packet_length_samples) / fs_hz_));
790 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000791 }
792
793 // Update statistics.
pbos@webrtc.org0946a562013-04-09 00:28:06 +0000794 if ((int32_t) (main_header.timestamp - timestamp_) >= 0 &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000795 !new_codec_) {
796 // Only update statistics if incoming packet is not older than last played
797 // out packet, and if new codec flag is not set.
798 delay_manager_->Update(main_header.sequenceNumber, main_header.timestamp,
799 fs_hz_);
800 }
801 } else if (delay_manager_->last_pack_cng_or_dtmf() == -1) {
802 // This is first "normal" packet after CNG or DTMF.
803 // Reset packet time counter and measure time until next packet,
804 // but don't update statistics.
805 delay_manager_->set_last_pack_cng_or_dtmf(0);
806 delay_manager_->ResetPacketIatCount();
807 }
808 return 0;
809}
810
henrik.lundin6d8e0112016-03-04 10:34:21 -0800811int NetEqImpl::GetAudioInternal(AudioFrame* audio_frame) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000812 PacketList packet_list;
813 DtmfEvent dtmf_event;
814 Operations operation;
815 bool play_dtmf;
henrik.lundined497212016-04-25 10:11:38 -0700816 tick_timer_->Increment();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000817 int return_value = GetDecision(&operation, &packet_list, &dtmf_event,
818 &play_dtmf);
819 if (return_value != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000820 last_mode_ = kModeError;
821 return return_value;
822 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000823
824 AudioDecoder::SpeechType speech_type;
825 int length = 0;
826 int decode_return_value = Decode(&packet_list, &operation,
827 &length, &speech_type);
828
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000829 assert(vad_.get());
830 bool sid_frame_available =
831 (operation == kRfc3389Cng && !packet_list.empty());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700832 vad_->Update(decoded_buffer_.get(), static_cast<size_t>(length), speech_type,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000833 sid_frame_available, fs_hz_);
834
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000835 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000836 switch (operation) {
837 case kNormal: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000838 DoNormal(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000839 break;
840 }
841 case kMerge: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000842 DoMerge(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000843 break;
844 }
845 case kExpand: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000846 return_value = DoExpand(play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000847 break;
848 }
Henrik Lundincf808d22015-05-27 14:33:29 +0200849 case kAccelerate:
850 case kFastAccelerate: {
851 const bool fast_accelerate =
852 enable_fast_accelerate_ && (operation == kFastAccelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000853 return_value = DoAccelerate(decoded_buffer_.get(), length, speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +0200854 play_dtmf, fast_accelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000855 break;
856 }
857 case kPreemptiveExpand: {
858 return_value = DoPreemptiveExpand(decoded_buffer_.get(), length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000859 speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000860 break;
861 }
862 case kRfc3389Cng:
863 case kRfc3389CngNoPacket: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000864 return_value = DoRfc3389Cng(&packet_list, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000865 break;
866 }
867 case kCodecInternalCng: {
868 // This handles the case when there is no transmission and the decoder
869 // should produce internal comfort noise.
870 // TODO(hlundin): Write test for codec-internal CNG.
minyuel6d92bf52015-09-23 15:20:39 +0200871 DoCodecInternalCng(decoded_buffer_.get(), length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000872 break;
873 }
874 case kDtmf: {
875 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000876 return_value = DoDtmf(dtmf_event, &play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000877 break;
878 }
879 case kAlternativePlc: {
880 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000881 DoAlternativePlc(false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000882 break;
883 }
884 case kAlternativePlcIncreaseTimestamp: {
885 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000886 DoAlternativePlc(true);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000887 break;
888 }
889 case kAudioRepetitionIncreaseTimestamp: {
890 // TODO(hlundin): Write test for this.
Peter Kastingb7e50542015-06-11 12:55:50 -0700891 sync_buffer_->IncreaseEndTimestamp(
892 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000893 // Skipping break on purpose. Execution should move on into the
894 // next case.
kjellander@webrtc.org7d2b6a92015-01-28 18:37:58 +0000895 FALLTHROUGH();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000896 }
897 case kAudioRepetition: {
898 // TODO(hlundin): Write test for this.
899 // Copy last |output_size_samples_| from |sync_buffer_| to
900 // |algorithm_buffer|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000901 algorithm_buffer_->PushBackFromIndex(
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000902 *sync_buffer_, sync_buffer_->Size() - output_size_samples_);
903 expand_->Reset();
904 break;
905 }
906 case kUndefined: {
Henrik Lundind67a2192015-08-03 12:54:37 +0200907 LOG(LS_ERROR) << "Invalid operation kUndefined.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000908 assert(false); // This should not happen.
909 last_mode_ = kModeError;
910 return kInvalidOperation;
911 }
912 } // End of switch.
minyue5bd33972016-05-02 04:46:11 -0700913 last_operation_ = operation;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000914 if (return_value < 0) {
915 return return_value;
916 }
917
918 if (last_mode_ != kModeRfc3389Cng) {
919 comfort_noise_->Reset();
920 }
921
922 // Copy from |algorithm_buffer| to |sync_buffer_|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000923 sync_buffer_->PushBack(*algorithm_buffer_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000924
925 // Extract data from |sync_buffer_| to |output|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000926 size_t num_output_samples_per_channel = output_size_samples_;
927 size_t num_output_samples = output_size_samples_ * sync_buffer_->Channels();
henrik.lundin6d8e0112016-03-04 10:34:21 -0800928 if (num_output_samples > AudioFrame::kMaxDataSizeSamples) {
929 LOG(LS_WARNING) << "Output array is too short. "
930 << AudioFrame::kMaxDataSizeSamples << " < "
931 << output_size_samples_ << " * "
932 << sync_buffer_->Channels();
933 num_output_samples = AudioFrame::kMaxDataSizeSamples;
934 num_output_samples_per_channel =
935 AudioFrame::kMaxDataSizeSamples / sync_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000936 }
henrik.lundin6d8e0112016-03-04 10:34:21 -0800937 sync_buffer_->GetNextAudioInterleaved(num_output_samples_per_channel,
938 audio_frame);
939 audio_frame->sample_rate_hz_ = fs_hz_;
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200940 if (sync_buffer_->FutureLength() < expand_->overlap_length()) {
941 // The sync buffer should always contain |overlap_length| samples, but now
942 // too many samples have been extracted. Reinstall the |overlap_length|
943 // lookahead by moving the index.
944 const size_t missing_lookahead_samples =
945 expand_->overlap_length() - sync_buffer_->FutureLength();
henrikg91d6ede2015-09-17 00:24:34 -0700946 RTC_DCHECK_GE(sync_buffer_->next_index(), missing_lookahead_samples);
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200947 sync_buffer_->set_next_index(sync_buffer_->next_index() -
948 missing_lookahead_samples);
949 }
henrik.lundin6d8e0112016-03-04 10:34:21 -0800950 if (audio_frame->samples_per_channel_ != output_size_samples_) {
951 LOG(LS_ERROR) << "audio_frame->samples_per_channel_ ("
952 << audio_frame->samples_per_channel_
Henrik Lundind67a2192015-08-03 12:54:37 +0200953 << ") != output_size_samples_ (" << output_size_samples_
954 << ")";
minyue@webrtc.orgdb1cefc2013-08-13 01:39:21 +0000955 // TODO(minyue): treatment of under-run, filling zeros
henrik.lundin6d8e0112016-03-04 10:34:21 -0800956 memset(audio_frame->data_, 0, num_output_samples * sizeof(int16_t));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000957 return kSampleUnderrun;
958 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000959
960 // Should always have overlap samples left in the |sync_buffer_|.
henrikg91d6ede2015-09-17 00:24:34 -0700961 RTC_DCHECK_GE(sync_buffer_->FutureLength(), expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000962
963 if (play_dtmf) {
henrik.lundin6d8e0112016-03-04 10:34:21 -0800964 return_value =
965 DtmfOverdub(dtmf_event, sync_buffer_->Channels(), audio_frame->data_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000966 }
967
968 // Update the background noise parameters if last operation wrote data
969 // straight from the decoder to the |sync_buffer_|. That is, none of the
970 // operations that modify the signal can be followed by a parameter update.
971 if ((last_mode_ == kModeNormal) ||
972 (last_mode_ == kModeAccelerateFail) ||
973 (last_mode_ == kModePreemptiveExpandFail) ||
974 (last_mode_ == kModeRfc3389Cng) ||
975 (last_mode_ == kModeCodecInternalCng)) {
976 background_noise_->Update(*sync_buffer_, *vad_.get());
977 }
978
979 if (operation == kDtmf) {
980 // DTMF data was written the end of |sync_buffer_|.
981 // Update index to end of DTMF data in |sync_buffer_|.
982 sync_buffer_->set_dtmf_index(sync_buffer_->Size());
983 }
984
henrik.lundin@webrtc.orged865b52014-03-06 10:28:07 +0000985 if (last_mode_ != kModeExpand) {
986 // If last operation was not expand, calculate the |playout_timestamp_| from
987 // the |sync_buffer_|. However, do not update the |playout_timestamp_| if it
988 // would be moved "backwards".
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000989 uint32_t temp_timestamp = sync_buffer_->end_timestamp() -
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000990 static_cast<uint32_t>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000991 if (static_cast<int32_t>(temp_timestamp - playout_timestamp_) > 0) {
992 playout_timestamp_ = temp_timestamp;
993 }
994 } else {
995 // Use dead reckoning to estimate the |playout_timestamp_|.
Peter Kastingb7e50542015-06-11 12:55:50 -0700996 playout_timestamp_ += static_cast<uint32_t>(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000997 }
henrik.lundin15c51e32016-04-06 08:38:56 -0700998 // Set the timestamp in the audio frame to zero before the first packet has
999 // been inserted. Otherwise, subtract the frame size in samples to get the
1000 // timestamp of the first sample in the frame (playout_timestamp_ is the
1001 // last + 1).
1002 audio_frame->timestamp_ =
1003 first_packet_
1004 ? 0
1005 : timestamp_scaler_->ToExternal(playout_timestamp_) -
1006 static_cast<uint32_t>(audio_frame->samples_per_channel_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001007
1008 if (decode_return_value) return decode_return_value;
1009 return return_value;
1010}
1011
1012int NetEqImpl::GetDecision(Operations* operation,
1013 PacketList* packet_list,
1014 DtmfEvent* dtmf_event,
1015 bool* play_dtmf) {
1016 // Initialize output variables.
1017 *play_dtmf = false;
1018 *operation = kUndefined;
1019
1020 // Increment time counters.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001021 stats_.IncreaseCounter(output_size_samples_, fs_hz_);
1022
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001023 assert(sync_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001024 uint32_t end_timestamp = sync_buffer_->end_timestamp();
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001025 if (!new_codec_) {
1026 const uint32_t five_seconds_samples = 5 * fs_hz_;
1027 packet_buffer_->DiscardOldPackets(end_timestamp, five_seconds_samples);
1028 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001029 const RTPHeader* header = packet_buffer_->NextRtpHeader();
1030
henrik.lundin@webrtc.orgca8cb952014-03-12 10:26:52 +00001031 if (decision_logic_->CngRfc3389On() || last_mode_ == kModeRfc3389Cng) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001032 // Because of timestamp peculiarities, we have to "manually" disallow using
1033 // a CNG packet with the same timestamp as the one that was last played.
1034 // This can happen when using redundancy and will cause the timing to shift.
henrik.lundin@webrtc.org24779fe2014-03-14 12:40:05 +00001035 while (header && decoder_database_->IsComfortNoise(header->payloadType) &&
1036 (end_timestamp >= header->timestamp ||
1037 end_timestamp + decision_logic_->generated_noise_samples() >
1038 header->timestamp)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001039 // Don't use this packet, discard it.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001040 if (packet_buffer_->DiscardNextPacket() != PacketBuffer::kOK) {
1041 assert(false); // Must be ok by design.
1042 }
1043 // Check buffer again.
1044 if (!new_codec_) {
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001045 packet_buffer_->DiscardOldPackets(end_timestamp, 5 * fs_hz_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001046 }
1047 header = packet_buffer_->NextRtpHeader();
1048 }
1049 }
1050
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001051 assert(expand_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001052 const int samples_left = static_cast<int>(sync_buffer_->FutureLength() -
1053 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001054 if (last_mode_ == kModeAccelerateSuccess ||
1055 last_mode_ == kModeAccelerateLowEnergy ||
1056 last_mode_ == kModePreemptiveExpandSuccess ||
1057 last_mode_ == kModePreemptiveExpandLowEnergy) {
1058 // Subtract (samples_left + output_size_samples_) from sampleMemory.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001059 decision_logic_->AddSampleMemory(
1060 -(samples_left + rtc::checked_cast<int>(output_size_samples_)));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001061 }
1062
1063 // Check if it is time to play a DTMF event.
Peter Kastingb7e50542015-06-11 12:55:50 -07001064 if (dtmf_buffer_->GetEvent(
1065 static_cast<uint32_t>(
1066 end_timestamp + decision_logic_->generated_noise_samples()),
1067 dtmf_event)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001068 *play_dtmf = true;
1069 }
1070
1071 // Get instruction.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001072 assert(sync_buffer_.get());
1073 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001074 *operation = decision_logic_->GetDecision(*sync_buffer_,
1075 *expand_,
1076 decoder_frame_length_,
1077 header,
1078 last_mode_,
1079 *play_dtmf,
1080 &reset_decoder_);
1081
1082 // Check if we already have enough samples in the |sync_buffer_|. If so,
1083 // change decision to normal, unless the decision was merge, accelerate, or
1084 // preemptive expand.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001085 if (samples_left >= rtc::checked_cast<int>(output_size_samples_) &&
1086 *operation != kMerge &&
1087 *operation != kAccelerate &&
1088 *operation != kFastAccelerate &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001089 *operation != kPreemptiveExpand) {
1090 *operation = kNormal;
1091 return 0;
1092 }
1093
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001094 decision_logic_->ExpandDecision(*operation);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001095
1096 // Check conditions for reset.
1097 if (new_codec_ || *operation == kUndefined) {
1098 // The only valid reason to get kUndefined is that new_codec_ is set.
1099 assert(new_codec_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001100 if (*play_dtmf && !header) {
1101 timestamp_ = dtmf_event->timestamp;
1102 } else {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001103 if (!header) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001104 LOG(LS_ERROR) << "Packet missing where it shouldn't.";
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001105 return -1;
1106 }
1107 timestamp_ = header->timestamp;
1108 if (*operation == kRfc3389CngNoPacket
1109#ifndef LEGACY_BITEXACT
1110 // Without this check, it can happen that a non-CNG packet is sent to
1111 // the CNG decoder as if it was a SID frame. This is clearly a bug,
1112 // but is kept for now to maintain bit-exactness with the test
1113 // vectors.
1114 && decoder_database_->IsComfortNoise(header->payloadType)
1115#endif
1116 ) {
1117 // Change decision to CNG packet, since we do have a CNG packet, but it
1118 // was considered too early to use. Now, use it anyway.
1119 *operation = kRfc3389Cng;
1120 } else if (*operation != kRfc3389Cng) {
1121 *operation = kNormal;
1122 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001123 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001124 // Adjust |sync_buffer_| timestamp before setting |end_timestamp| to the
1125 // new value.
1126 sync_buffer_->IncreaseEndTimestamp(timestamp_ - end_timestamp);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001127 end_timestamp = timestamp_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001128 new_codec_ = false;
1129 decision_logic_->SoftReset();
1130 buffer_level_filter_->Reset();
1131 delay_manager_->Reset();
1132 stats_.ResetMcu();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001133 }
1134
Peter Kastingdce40cf2015-08-24 14:52:23 -07001135 size_t required_samples = output_size_samples_;
1136 const size_t samples_10_ms = static_cast<size_t>(80 * fs_mult_);
1137 const size_t samples_20_ms = 2 * samples_10_ms;
1138 const size_t samples_30_ms = 3 * samples_10_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001139
1140 switch (*operation) {
1141 case kExpand: {
1142 timestamp_ = end_timestamp;
1143 return 0;
1144 }
1145 case kRfc3389CngNoPacket:
1146 case kCodecInternalCng: {
1147 return 0;
1148 }
1149 case kDtmf: {
1150 // TODO(hlundin): Write test for this.
1151 // Update timestamp.
1152 timestamp_ = end_timestamp;
1153 if (decision_logic_->generated_noise_samples() > 0 &&
1154 last_mode_ != kModeDtmf) {
1155 // Make a jump in timestamp due to the recently played comfort noise.
Peter Kastingb7e50542015-06-11 12:55:50 -07001156 uint32_t timestamp_jump =
1157 static_cast<uint32_t>(decision_logic_->generated_noise_samples());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001158 sync_buffer_->IncreaseEndTimestamp(timestamp_jump);
1159 timestamp_ += timestamp_jump;
1160 }
1161 decision_logic_->set_generated_noise_samples(0);
1162 return 0;
1163 }
Henrik Lundincf808d22015-05-27 14:33:29 +02001164 case kAccelerate:
1165 case kFastAccelerate: {
1166 // In order to do an accelerate we need at least 30 ms of audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001167 if (samples_left >= static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001168 // Already have enough data, so we do not need to extract any more.
1169 decision_logic_->set_sample_memory(samples_left);
1170 decision_logic_->set_prev_time_scale(true);
1171 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001172 } else if (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001173 decoder_frame_length_ >= samples_30_ms) {
1174 // Avoid decoding more data as it might overflow the playout buffer.
1175 *operation = kNormal;
1176 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001177 } else if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001178 decoder_frame_length_ < samples_30_ms) {
1179 // Build up decoded data by decoding at least 20 ms of audio data. Do
1180 // not perform accelerate yet, but wait until we only need to do one
1181 // decoding.
1182 required_samples = 2 * output_size_samples_;
1183 *operation = kNormal;
1184 }
1185 // If none of the above is true, we have one of two possible situations:
1186 // (1) 20 ms <= samples_left < 30 ms and decoder_frame_length_ < 30 ms; or
1187 // (2) samples_left < 10 ms and decoder_frame_length_ >= 30 ms.
1188 // In either case, we move on with the accelerate decision, and decode one
1189 // frame now.
1190 break;
1191 }
1192 case kPreemptiveExpand: {
1193 // In order to do a preemptive expand we need at least 30 ms of decoded
1194 // audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001195 if ((samples_left >= static_cast<int>(samples_30_ms)) ||
1196 (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001197 decoder_frame_length_ >= samples_30_ms)) {
1198 // Already have enough data, so we do not need to extract any more.
1199 // Or, avoid decoding more data as it might overflow the playout buffer.
1200 // Still try preemptive expand, though.
1201 decision_logic_->set_sample_memory(samples_left);
1202 decision_logic_->set_prev_time_scale(true);
1203 return 0;
1204 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07001205 if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001206 decoder_frame_length_ < samples_30_ms) {
1207 // Build up decoded data by decoding at least 20 ms of audio data.
1208 // Still try to perform preemptive expand.
1209 required_samples = 2 * output_size_samples_;
1210 }
1211 // Move on with the preemptive expand decision.
1212 break;
1213 }
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001214 case kMerge: {
1215 required_samples =
1216 std::max(merge_->RequiredFutureSamples(), required_samples);
1217 break;
1218 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001219 default: {
1220 // Do nothing.
1221 }
1222 }
1223
1224 // Get packets from buffer.
1225 int extracted_samples = 0;
1226 if (header &&
1227 *operation != kAlternativePlc &&
1228 *operation != kAlternativePlcIncreaseTimestamp &&
1229 *operation != kAudioRepetition &&
1230 *operation != kAudioRepetitionIncreaseTimestamp) {
1231 sync_buffer_->IncreaseEndTimestamp(header->timestamp - end_timestamp);
1232 if (decision_logic_->CngOff()) {
1233 // Adjustment of timestamp only corresponds to an actual packet loss
1234 // if comfort noise is not played. If comfort noise was just played,
1235 // this adjustment of timestamp is only done to get back in sync with the
1236 // stream timestamp; no loss to report.
1237 stats_.LostSamples(header->timestamp - end_timestamp);
1238 }
1239
1240 if (*operation != kRfc3389Cng) {
1241 // We are about to decode and use a non-CNG packet.
1242 decision_logic_->SetCngOff();
1243 }
1244 // Reset CNG timestamp as a new packet will be delivered.
1245 // (Also if this is a CNG packet, since playedOutTS is updated.)
1246 decision_logic_->set_generated_noise_samples(0);
1247
1248 extracted_samples = ExtractPackets(required_samples, packet_list);
1249 if (extracted_samples < 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001250 return kPacketBufferCorruption;
1251 }
1252 }
1253
Henrik Lundincf808d22015-05-27 14:33:29 +02001254 if (*operation == kAccelerate || *operation == kFastAccelerate ||
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001255 *operation == kPreemptiveExpand) {
1256 decision_logic_->set_sample_memory(samples_left + extracted_samples);
1257 decision_logic_->set_prev_time_scale(true);
1258 }
1259
Henrik Lundincf808d22015-05-27 14:33:29 +02001260 if (*operation == kAccelerate || *operation == kFastAccelerate) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001261 // Check that we have enough data (30ms) to do accelerate.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001262 if (extracted_samples + samples_left < static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001263 // TODO(hlundin): Write test for this.
1264 // Not enough, do normal operation instead.
1265 *operation = kNormal;
1266 }
1267 }
1268
1269 timestamp_ = end_timestamp;
1270 return 0;
1271}
1272
1273int NetEqImpl::Decode(PacketList* packet_list, Operations* operation,
1274 int* decoded_length,
1275 AudioDecoder::SpeechType* speech_type) {
1276 *speech_type = AudioDecoder::kSpeech;
minyuel6d92bf52015-09-23 15:20:39 +02001277
1278 // When packet_list is empty, we may be in kCodecInternalCng mode, and for
1279 // that we use current active decoder.
1280 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1281
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001282 if (!packet_list->empty()) {
1283 const Packet* packet = packet_list->front();
pkasting@chromium.org0e81fdf2015-02-02 23:54:03 +00001284 uint8_t payload_type = packet->header.payloadType;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001285 if (!decoder_database_->IsComfortNoise(payload_type)) {
1286 decoder = decoder_database_->GetDecoder(payload_type);
1287 assert(decoder);
1288 if (!decoder) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001289 LOG(LS_WARNING) << "Unknown payload type "
1290 << static_cast<int>(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001291 PacketBuffer::DeleteAllPackets(packet_list);
1292 return kDecoderNotFound;
1293 }
1294 bool decoder_changed;
1295 decoder_database_->SetActiveDecoder(payload_type, &decoder_changed);
1296 if (decoder_changed) {
1297 // We have a new decoder. Re-init some values.
1298 const DecoderDatabase::DecoderInfo* decoder_info = decoder_database_
1299 ->GetDecoderInfo(payload_type);
1300 assert(decoder_info);
1301 if (!decoder_info) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001302 LOG(LS_WARNING) << "Unknown payload type "
1303 << static_cast<int>(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001304 PacketBuffer::DeleteAllPackets(packet_list);
1305 return kDecoderNotFound;
1306 }
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001307 // If sampling rate or number of channels has changed, we need to make
1308 // a reset.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001309 if (decoder_info->fs_hz != fs_hz_ ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001310 decoder->Channels() != algorithm_buffer_->Channels()) {
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001311 // TODO(tlegrand): Add unittest to cover this event.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001312 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->Channels());
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001313 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001314 sync_buffer_->set_end_timestamp(timestamp_);
1315 playout_timestamp_ = timestamp_;
1316 }
1317 }
1318 }
1319
1320 if (reset_decoder_) {
1321 // TODO(hlundin): Write test for this.
Karl Wiberg43766482015-08-27 15:22:11 +02001322 if (decoder)
1323 decoder->Reset();
1324
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001325 // Reset comfort noise decoder.
ossu97ba30e2016-04-25 07:55:58 -07001326 ComfortNoiseDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02001327 if (cng_decoder)
1328 cng_decoder->Reset();
1329
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001330 reset_decoder_ = false;
1331 }
1332
1333#ifdef LEGACY_BITEXACT
1334 // Due to a bug in old SignalMCU, it could happen that CNG operation was
1335 // decided, but a speech packet was provided. The speech packet will be used
1336 // to update the comfort noise decoder, as if it was a SID frame, which is
1337 // clearly wrong.
1338 if (*operation == kRfc3389Cng) {
1339 return 0;
1340 }
1341#endif
1342
1343 *decoded_length = 0;
1344 // Update codec-internal PLC state.
1345 if ((*operation == kMerge) && decoder && decoder->HasDecodePlc()) {
1346 decoder->DecodePlc(1, &decoded_buffer_[*decoded_length]);
1347 }
1348
minyuel6d92bf52015-09-23 15:20:39 +02001349 int return_value;
1350 if (*operation == kCodecInternalCng) {
1351 RTC_DCHECK(packet_list->empty());
1352 return_value = DecodeCng(decoder, decoded_length, speech_type);
1353 } else {
1354 return_value = DecodeLoop(packet_list, *operation, decoder,
1355 decoded_length, speech_type);
1356 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001357
1358 if (*decoded_length < 0) {
1359 // Error returned from the decoder.
1360 *decoded_length = 0;
Peter Kastingb7e50542015-06-11 12:55:50 -07001361 sync_buffer_->IncreaseEndTimestamp(
1362 static_cast<uint32_t>(decoder_frame_length_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001363 int error_code = 0;
1364 if (decoder)
1365 error_code = decoder->ErrorCode();
1366 if (error_code != 0) {
1367 // Got some error code from the decoder.
1368 decoder_error_code_ = error_code;
1369 return_value = kDecoderErrorCode;
Henrik Lundind67a2192015-08-03 12:54:37 +02001370 LOG(LS_WARNING) << "Decoder returned error code: " << error_code;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001371 } else {
1372 // Decoder does not implement error codes. Return generic error.
1373 return_value = kOtherDecoderError;
Henrik Lundind67a2192015-08-03 12:54:37 +02001374 LOG(LS_WARNING) << "Decoder error (no error code)";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001375 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001376 *operation = kExpand; // Do expansion to get data instead.
1377 }
1378 if (*speech_type != AudioDecoder::kComfortNoise) {
1379 // Don't increment timestamp if codec returned CNG speech type
1380 // since in this case, the we will increment the CNGplayedTS counter.
1381 // Increase with number of samples per channel.
1382 assert(*decoded_length == 0 ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001383 (decoder && decoder->Channels() == sync_buffer_->Channels()));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001384 sync_buffer_->IncreaseEndTimestamp(
1385 *decoded_length / static_cast<int>(sync_buffer_->Channels()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001386 }
1387 return return_value;
1388}
1389
minyuel6d92bf52015-09-23 15:20:39 +02001390int NetEqImpl::DecodeCng(AudioDecoder* decoder, int* decoded_length,
1391 AudioDecoder::SpeechType* speech_type) {
1392 if (!decoder) {
1393 // This happens when active decoder is not defined.
1394 *decoded_length = -1;
1395 return 0;
1396 }
1397
1398 while (*decoded_length < rtc::checked_cast<int>(output_size_samples_)) {
1399 const int length = decoder->Decode(
1400 nullptr, 0, fs_hz_,
1401 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1402 &decoded_buffer_[*decoded_length], speech_type);
1403 if (length > 0) {
1404 *decoded_length += length;
minyuel6d92bf52015-09-23 15:20:39 +02001405 } else {
1406 // Error.
1407 LOG(LS_WARNING) << "Failed to decode CNG";
1408 *decoded_length = -1;
1409 break;
1410 }
1411 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1412 // Guard against overflow.
1413 LOG(LS_WARNING) << "Decoded too much CNG.";
1414 return kDecodedTooMuch;
1415 }
1416 }
1417 return 0;
1418}
1419
1420int NetEqImpl::DecodeLoop(PacketList* packet_list, const Operations& operation,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001421 AudioDecoder* decoder, int* decoded_length,
1422 AudioDecoder::SpeechType* speech_type) {
1423 Packet* packet = NULL;
1424 if (!packet_list->empty()) {
1425 packet = packet_list->front();
1426 }
minyuel6d92bf52015-09-23 15:20:39 +02001427
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001428 // Do decoding.
1429 while (packet &&
1430 !decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1431 assert(decoder); // At this point, we must have a decoder object.
1432 // The number of channels in the |sync_buffer_| should be the same as the
1433 // number decoder channels.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001434 assert(sync_buffer_->Channels() == decoder->Channels());
1435 assert(decoded_buffer_length_ >= kMaxFrameSize * decoder->Channels());
minyuel6d92bf52015-09-23 15:20:39 +02001436 assert(operation == kNormal || operation == kAccelerate ||
1437 operation == kFastAccelerate || operation == kMerge ||
1438 operation == kPreemptiveExpand);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001439 packet_list->pop_front();
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001440 size_t payload_length = packet->payload_length;
Peter Kasting36b7cc32015-06-11 19:57:18 -07001441 int decode_length;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +00001442 if (packet->sync_packet) {
1443 // Decode to silence with the same frame size as the last decode.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001444 memset(&decoded_buffer_[*decoded_length], 0,
1445 decoder_frame_length_ * decoder->Channels() *
1446 sizeof(decoded_buffer_[0]));
Peter Kastingdce40cf2015-08-24 14:52:23 -07001447 decode_length = rtc::checked_cast<int>(decoder_frame_length_);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +00001448 } else if (!packet->primary) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001449 // This is a redundant payload; call the special decoder method.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001450 decode_length = decoder->DecodeRedundant(
henrik.lundin@webrtc.org1eda4e32015-02-25 10:02:29 +00001451 packet->payload, packet->payload_length, fs_hz_,
minyue@webrtc.org7f7d7e32015-03-16 12:30:37 +00001452 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001453 &decoded_buffer_[*decoded_length], speech_type);
1454 } else {
henrik.lundin@webrtc.org1eda4e32015-02-25 10:02:29 +00001455 decode_length =
minyue@webrtc.org7f7d7e32015-03-16 12:30:37 +00001456 decoder->Decode(
1457 packet->payload, packet->payload_length, fs_hz_,
1458 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1459 &decoded_buffer_[*decoded_length], speech_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001460 }
1461
1462 delete[] packet->payload;
1463 delete packet;
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001464 packet = NULL;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001465 if (decode_length > 0) {
1466 *decoded_length += decode_length;
1467 // Update |decoder_frame_length_| with number of samples per channel.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001468 decoder_frame_length_ =
Peter Kastingdce40cf2015-08-24 14:52:23 -07001469 static_cast<size_t>(decode_length) / decoder->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001470 } else if (decode_length < 0) {
1471 // Error.
Henrik Lundind67a2192015-08-03 12:54:37 +02001472 LOG(LS_WARNING) << "Decode " << decode_length << " " << payload_length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001473 *decoded_length = -1;
1474 PacketBuffer::DeleteAllPackets(packet_list);
1475 break;
1476 }
1477 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1478 // Guard against overflow.
Henrik Lundind67a2192015-08-03 12:54:37 +02001479 LOG(LS_WARNING) << "Decoded too much.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001480 PacketBuffer::DeleteAllPackets(packet_list);
1481 return kDecodedTooMuch;
1482 }
1483 if (!packet_list->empty()) {
1484 packet = packet_list->front();
1485 } else {
1486 packet = NULL;
1487 }
1488 } // End of decode loop.
1489
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001490 // If the list is not empty at this point, either a decoding error terminated
1491 // the while-loop, or list must hold exactly one CNG packet.
1492 assert(packet_list->empty() || *decoded_length < 0 ||
1493 (packet_list->size() == 1 && packet &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001494 decoder_database_->IsComfortNoise(packet->header.payloadType)));
1495 return 0;
1496}
1497
1498void NetEqImpl::DoNormal(const int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001499 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001500 assert(normal_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001501 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001502 normal_->Process(decoded_buffer, decoded_length, last_mode_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001503 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001504 if (decoded_length != 0) {
1505 last_mode_ = kModeNormal;
1506 }
1507
1508 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1509 if ((speech_type == AudioDecoder::kComfortNoise)
1510 || ((last_mode_ == kModeCodecInternalCng)
1511 && (decoded_length == 0))) {
1512 // TODO(hlundin): Remove second part of || statement above.
1513 last_mode_ = kModeCodecInternalCng;
1514 }
1515
1516 if (!play_dtmf) {
1517 dtmf_tone_generator_->Reset();
1518 }
1519}
1520
1521void NetEqImpl::DoMerge(int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001522 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001523 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001524 assert(merge_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001525 size_t new_length = merge_->Process(decoded_buffer, decoded_length,
1526 mute_factor_array_.get(),
1527 algorithm_buffer_.get());
1528 size_t expand_length_correction = new_length -
1529 decoded_length / algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001530
1531 // Update in-call and post-call statistics.
1532 if (expand_->MuteFactor(0) == 0) {
1533 // Expand generates only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001534 stats_.ExpandedNoiseSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001535 } else {
1536 // Expansion generates more than only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001537 stats_.ExpandedVoiceSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001538 }
1539
1540 last_mode_ = kModeMerge;
1541 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1542 if (speech_type == AudioDecoder::kComfortNoise) {
1543 last_mode_ = kModeCodecInternalCng;
1544 }
1545 expand_->Reset();
1546 if (!play_dtmf) {
1547 dtmf_tone_generator_->Reset();
1548 }
1549}
1550
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001551int NetEqImpl::DoExpand(bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001552 while ((sync_buffer_->FutureLength() - expand_->overlap_length()) <
Peter Kastingdce40cf2015-08-24 14:52:23 -07001553 output_size_samples_) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001554 algorithm_buffer_->Clear();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001555 int return_value = expand_->Process(algorithm_buffer_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001556 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001557
1558 // Update in-call and post-call statistics.
1559 if (expand_->MuteFactor(0) == 0) {
1560 // Expand operation generates only noise.
1561 stats_.ExpandedNoiseSamples(length);
1562 } else {
1563 // Expand operation generates more than only noise.
1564 stats_.ExpandedVoiceSamples(length);
1565 }
1566
1567 last_mode_ = kModeExpand;
1568
1569 if (return_value < 0) {
1570 return return_value;
1571 }
1572
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001573 sync_buffer_->PushBack(*algorithm_buffer_);
1574 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001575 }
1576 if (!play_dtmf) {
1577 dtmf_tone_generator_->Reset();
1578 }
1579 return 0;
1580}
1581
Henrik Lundincf808d22015-05-27 14:33:29 +02001582int NetEqImpl::DoAccelerate(int16_t* decoded_buffer,
1583 size_t decoded_length,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001584 AudioDecoder::SpeechType speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +02001585 bool play_dtmf,
1586 bool fast_accelerate) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001587 const size_t required_samples =
1588 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001589 size_t borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001590 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001591 size_t decoded_length_per_channel = decoded_length / num_channels;
1592 if (decoded_length_per_channel < required_samples) {
1593 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001594 borrowed_samples_per_channel = static_cast<int>(required_samples -
1595 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001596 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1597 decoded_buffer,
1598 sizeof(int16_t) * decoded_length);
1599 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1600 decoded_buffer);
1601 decoded_length = required_samples * num_channels;
1602 }
1603
Peter Kastingdce40cf2015-08-24 14:52:23 -07001604 size_t samples_removed;
Henrik Lundincf808d22015-05-27 14:33:29 +02001605 Accelerate::ReturnCodes return_code =
1606 accelerate_->Process(decoded_buffer, decoded_length, fast_accelerate,
1607 algorithm_buffer_.get(), &samples_removed);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001608 stats_.AcceleratedSamples(samples_removed);
1609 switch (return_code) {
1610 case Accelerate::kSuccess:
1611 last_mode_ = kModeAccelerateSuccess;
1612 break;
1613 case Accelerate::kSuccessLowEnergy:
1614 last_mode_ = kModeAccelerateLowEnergy;
1615 break;
1616 case Accelerate::kNoStretch:
1617 last_mode_ = kModeAccelerateFail;
1618 break;
1619 case Accelerate::kError:
1620 // TODO(hlundin): Map to kModeError instead?
1621 last_mode_ = kModeAccelerateFail;
1622 return kAccelerateError;
1623 }
1624
1625 if (borrowed_samples_per_channel > 0) {
1626 // Copy borrowed samples back to the |sync_buffer_|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001627 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001628 if (length < borrowed_samples_per_channel) {
1629 // This destroys the beginning of the buffer, but will not cause any
1630 // problems.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001631 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001632 sync_buffer_->Size() -
1633 borrowed_samples_per_channel);
1634 sync_buffer_->PushFrontZeros(borrowed_samples_per_channel - length);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001635 algorithm_buffer_->PopFront(length);
1636 assert(algorithm_buffer_->Empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001637 } else {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001638 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001639 borrowed_samples_per_channel,
1640 sync_buffer_->Size() -
1641 borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001642 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001643 }
1644 }
1645
1646 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1647 if (speech_type == AudioDecoder::kComfortNoise) {
1648 last_mode_ = kModeCodecInternalCng;
1649 }
1650 if (!play_dtmf) {
1651 dtmf_tone_generator_->Reset();
1652 }
1653 expand_->Reset();
1654 return 0;
1655}
1656
1657int NetEqImpl::DoPreemptiveExpand(int16_t* decoded_buffer,
1658 size_t decoded_length,
1659 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001660 bool play_dtmf) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001661 const size_t required_samples =
1662 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001663 size_t num_channels = algorithm_buffer_->Channels();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001664 size_t borrowed_samples_per_channel = 0;
1665 size_t old_borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001666 size_t decoded_length_per_channel = decoded_length / num_channels;
1667 if (decoded_length_per_channel < required_samples) {
1668 // Must move data from the |sync_buffer_| in order to get 30 ms.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001669 borrowed_samples_per_channel =
1670 required_samples - decoded_length_per_channel;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001671 // Calculate how many of these were already played out.
Peter Kastingf045e4d2015-06-10 21:15:38 -07001672 old_borrowed_samples_per_channel =
Peter Kastingdce40cf2015-08-24 14:52:23 -07001673 (borrowed_samples_per_channel > sync_buffer_->FutureLength()) ?
1674 (borrowed_samples_per_channel - sync_buffer_->FutureLength()) : 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001675 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1676 decoded_buffer,
1677 sizeof(int16_t) * decoded_length);
1678 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1679 decoded_buffer);
1680 decoded_length = required_samples * num_channels;
1681 }
1682
Peter Kastingdce40cf2015-08-24 14:52:23 -07001683 size_t samples_added;
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001684 PreemptiveExpand::ReturnCodes return_code = preemptive_expand_->Process(
Peter Kastingdce40cf2015-08-24 14:52:23 -07001685 decoded_buffer, decoded_length,
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001686 old_borrowed_samples_per_channel,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001687 algorithm_buffer_.get(), &samples_added);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001688 stats_.PreemptiveExpandedSamples(samples_added);
1689 switch (return_code) {
1690 case PreemptiveExpand::kSuccess:
1691 last_mode_ = kModePreemptiveExpandSuccess;
1692 break;
1693 case PreemptiveExpand::kSuccessLowEnergy:
1694 last_mode_ = kModePreemptiveExpandLowEnergy;
1695 break;
1696 case PreemptiveExpand::kNoStretch:
1697 last_mode_ = kModePreemptiveExpandFail;
1698 break;
1699 case PreemptiveExpand::kError:
1700 // TODO(hlundin): Map to kModeError instead?
1701 last_mode_ = kModePreemptiveExpandFail;
1702 return kPreemptiveExpandError;
1703 }
1704
1705 if (borrowed_samples_per_channel > 0) {
1706 // Copy borrowed samples back to the |sync_buffer_|.
1707 sync_buffer_->ReplaceAtIndex(
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001708 *algorithm_buffer_, borrowed_samples_per_channel,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001709 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001710 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001711 }
1712
1713 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1714 if (speech_type == AudioDecoder::kComfortNoise) {
1715 last_mode_ = kModeCodecInternalCng;
1716 }
1717 if (!play_dtmf) {
1718 dtmf_tone_generator_->Reset();
1719 }
1720 expand_->Reset();
1721 return 0;
1722}
1723
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001724int NetEqImpl::DoRfc3389Cng(PacketList* packet_list, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001725 if (!packet_list->empty()) {
1726 // Must have exactly one SID frame at this point.
1727 assert(packet_list->size() == 1);
1728 Packet* packet = packet_list->front();
1729 packet_list->pop_front();
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001730 if (!decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1731#ifdef LEGACY_BITEXACT
1732 // This can happen due to a bug in GetDecision. Change the payload type
1733 // to a CNG type, and move on. Note that this means that we are in fact
1734 // sending a non-CNG payload to the comfort noise decoder for decoding.
1735 // Clearly wrong, but will maintain bit-exactness with legacy.
1736 if (fs_hz_ == 8000) {
1737 packet->header.payloadType =
kwibergee1879c2015-10-29 06:20:28 -07001738 decoder_database_->GetRtpPayloadType(NetEqDecoder::kDecoderCNGnb);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001739 } else if (fs_hz_ == 16000) {
1740 packet->header.payloadType =
kwibergee1879c2015-10-29 06:20:28 -07001741 decoder_database_->GetRtpPayloadType(NetEqDecoder::kDecoderCNGwb);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001742 } else if (fs_hz_ == 32000) {
kwibergee1879c2015-10-29 06:20:28 -07001743 packet->header.payloadType = decoder_database_->GetRtpPayloadType(
1744 NetEqDecoder::kDecoderCNGswb32kHz);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001745 } else if (fs_hz_ == 48000) {
kwibergee1879c2015-10-29 06:20:28 -07001746 packet->header.payloadType = decoder_database_->GetRtpPayloadType(
1747 NetEqDecoder::kDecoderCNGswb48kHz);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001748 }
1749 assert(decoder_database_->IsComfortNoise(packet->header.payloadType));
1750#else
1751 LOG(LS_ERROR) << "Trying to decode non-CNG payload as CNG.";
1752 return kOtherError;
1753#endif
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001754 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001755 // UpdateParameters() deletes |packet|.
1756 if (comfort_noise_->UpdateParameters(packet) ==
1757 ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001758 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001759 return -comfort_noise_->internal_error_code();
1760 }
1761 }
1762 int cn_return = comfort_noise_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001763 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001764 expand_->Reset();
1765 last_mode_ = kModeRfc3389Cng;
1766 if (!play_dtmf) {
1767 dtmf_tone_generator_->Reset();
1768 }
1769 if (cn_return == ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001770 decoder_error_code_ = comfort_noise_->internal_error_code();
1771 return kComfortNoiseErrorCode;
1772 } else if (cn_return == ComfortNoise::kUnknownPayloadType) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001773 return kUnknownRtpPayloadType;
1774 }
1775 return 0;
1776}
1777
minyuel6d92bf52015-09-23 15:20:39 +02001778void NetEqImpl::DoCodecInternalCng(const int16_t* decoded_buffer,
1779 size_t decoded_length) {
1780 RTC_DCHECK(normal_.get());
1781 RTC_DCHECK(mute_factor_array_.get());
1782 normal_->Process(decoded_buffer, decoded_length, last_mode_,
1783 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001784 last_mode_ = kModeCodecInternalCng;
1785 expand_->Reset();
1786}
1787
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001788int NetEqImpl::DoDtmf(const DtmfEvent& dtmf_event, bool* play_dtmf) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001789 // This block of the code and the block further down, handling |dtmf_switch|
1790 // are commented out. Otherwise playing out-of-band DTMF would fail in VoE
1791 // test, DtmfTest.ManualSuccessfullySendsOutOfBandTelephoneEvents. This is
1792 // equivalent to |dtmf_switch| always be false.
1793 //
1794 // See http://webrtc-codereview.appspot.com/1195004/ for discussion
1795 // On this issue. This change might cause some glitches at the point of
1796 // switch from audio to DTMF. Issue 1545 is filed to track this.
1797 //
1798 // bool dtmf_switch = false;
1799 // if ((last_mode_ != kModeDtmf) && dtmf_tone_generator_->initialized()) {
1800 // // Special case; see below.
1801 // // We must catch this before calling Generate, since |initialized| is
1802 // // modified in that call.
1803 // dtmf_switch = true;
1804 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001805
1806 int dtmf_return_value = 0;
1807 if (!dtmf_tone_generator_->initialized()) {
1808 // Initialize if not already done.
1809 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1810 dtmf_event.volume);
1811 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001812
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001813 if (dtmf_return_value == 0) {
1814 // Generate DTMF signal.
1815 dtmf_return_value = dtmf_tone_generator_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001816 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001817 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001818
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001819 if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001820 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001821 return dtmf_return_value;
1822 }
1823
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001824 // if (dtmf_switch) {
1825 // // This is the special case where the previous operation was DTMF
1826 // // overdub, but the current instruction is "regular" DTMF. We must make
1827 // // sure that the DTMF does not have any discontinuities. The first DTMF
1828 // // sample that we generate now must be played out immediately, therefore
1829 // // it must be copied to the speech buffer.
1830 // // TODO(hlundin): This code seems incorrect. (Legacy.) Write test and
1831 // // verify correct operation.
1832 // assert(false);
1833 // // Must generate enough data to replace all of the |sync_buffer_|
1834 // // "future".
1835 // int required_length = sync_buffer_->FutureLength();
1836 // assert(dtmf_tone_generator_->initialized());
1837 // dtmf_return_value = dtmf_tone_generator_->Generate(required_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001838 // algorithm_buffer_);
1839 // assert((size_t) required_length == algorithm_buffer_->Size());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001840 // if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001841 // algorithm_buffer_->Zeros(output_size_samples_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001842 // return dtmf_return_value;
1843 // }
1844 //
1845 // // Overwrite the "future" part of the speech buffer with the new DTMF
1846 // // data.
1847 // // TODO(hlundin): It seems that this overwriting has gone lost.
1848 // // Not adapted for multi-channel yet.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001849 // assert(algorithm_buffer_->Channels() == 1);
1850 // if (algorithm_buffer_->Channels() != 1) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001851 // LOG(LS_WARNING) << "DTMF not supported for more than one channel";
1852 // return kStereoNotSupported;
1853 // }
1854 // // Shuffle the remaining data to the beginning of algorithm buffer.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001855 // algorithm_buffer_->PopFront(sync_buffer_->FutureLength());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001856 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001857
Peter Kastingb7e50542015-06-11 12:55:50 -07001858 sync_buffer_->IncreaseEndTimestamp(
1859 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001860 expand_->Reset();
1861 last_mode_ = kModeDtmf;
1862
1863 // Set to false because the DTMF is already in the algorithm buffer.
1864 *play_dtmf = false;
1865 return 0;
1866}
1867
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001868void NetEqImpl::DoAlternativePlc(bool increase_timestamp) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001869 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001870 size_t length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001871 if (decoder && decoder->HasDecodePlc()) {
1872 // Use the decoder's packet-loss concealment.
1873 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1874 int16_t decoded_buffer[kMaxFrameSize];
1875 length = decoder->DecodePlc(1, decoded_buffer);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001876 if (length > 0)
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001877 algorithm_buffer_->PushBackInterleaved(decoded_buffer, length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001878 } else {
1879 // Do simple zero-stuffing.
1880 length = output_size_samples_;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001881 algorithm_buffer_->Zeros(length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001882 // By not advancing the timestamp, NetEq inserts samples.
1883 stats_.AddZeros(length);
1884 }
1885 if (increase_timestamp) {
Peter Kastingb7e50542015-06-11 12:55:50 -07001886 sync_buffer_->IncreaseEndTimestamp(static_cast<uint32_t>(length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001887 }
1888 expand_->Reset();
1889}
1890
1891int NetEqImpl::DtmfOverdub(const DtmfEvent& dtmf_event, size_t num_channels,
1892 int16_t* output) const {
1893 size_t out_index = 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001894 size_t overdub_length = output_size_samples_; // Default value.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001895
1896 if (sync_buffer_->dtmf_index() > sync_buffer_->next_index()) {
1897 // Special operation for transition from "DTMF only" to "DTMF overdub".
1898 out_index = std::min(
1899 sync_buffer_->dtmf_index() - sync_buffer_->next_index(),
Peter Kastingdce40cf2015-08-24 14:52:23 -07001900 output_size_samples_);
1901 overdub_length = output_size_samples_ - out_index;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001902 }
1903
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001904 AudioMultiVector dtmf_output(num_channels);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001905 int dtmf_return_value = 0;
1906 if (!dtmf_tone_generator_->initialized()) {
1907 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1908 dtmf_event.volume);
1909 }
1910 if (dtmf_return_value == 0) {
1911 dtmf_return_value = dtmf_tone_generator_->Generate(overdub_length,
1912 &dtmf_output);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001913 assert(overdub_length == dtmf_output.Size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001914 }
1915 dtmf_output.ReadInterleaved(overdub_length, &output[out_index]);
1916 return dtmf_return_value < 0 ? dtmf_return_value : 0;
1917}
1918
Peter Kastingdce40cf2015-08-24 14:52:23 -07001919int NetEqImpl::ExtractPackets(size_t required_samples,
1920 PacketList* packet_list) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001921 bool first_packet = true;
1922 uint8_t prev_payload_type = 0;
1923 uint32_t prev_timestamp = 0;
1924 uint16_t prev_sequence_number = 0;
1925 bool next_packet_available = false;
1926
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001927 const RTPHeader* header = packet_buffer_->NextRtpHeader();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001928 assert(header);
1929 if (!header) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001930 LOG(LS_ERROR) << "Packet buffer unexpectedly empty.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001931 return -1;
1932 }
turaj@webrtc.org7df97062013-08-02 18:07:13 +00001933 uint32_t first_timestamp = header->timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001934 int extracted_samples = 0;
1935
1936 // Packet extraction loop.
1937 do {
1938 timestamp_ = header->timestamp;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001939 size_t discard_count = 0;
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001940 Packet* packet = packet_buffer_->GetNextPacket(&discard_count);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001941 // |header| may be invalid after the |packet_buffer_| operation.
1942 header = NULL;
1943 if (!packet) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001944 LOG(LS_ERROR) << "Should always be able to extract a packet here";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001945 assert(false); // Should always be able to extract a packet here.
1946 return -1;
1947 }
1948 stats_.PacketsDiscarded(discard_count);
henrik.lundin84f8cd62016-04-26 07:45:16 -07001949 stats_.StoreWaitingTime(packet->waiting_time->ElapsedMs());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001950 assert(packet->payload_length > 0);
1951 packet_list->push_back(packet); // Store packet in list.
1952
1953 if (first_packet) {
1954 first_packet = false;
henrik.lundin48ed9302015-10-29 05:36:24 -07001955 if (nack_enabled_) {
1956 RTC_DCHECK(nack_);
1957 // TODO(henrik.lundin): Should we update this for all decoded packets?
1958 nack_->UpdateLastDecodedPacket(packet->header.sequenceNumber,
1959 packet->header.timestamp);
1960 }
1961 prev_sequence_number = packet->header.sequenceNumber;
1962 prev_timestamp = packet->header.timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001963 prev_payload_type = packet->header.payloadType;
1964 }
1965
1966 // Store number of extracted samples.
1967 int packet_duration = 0;
1968 AudioDecoder* decoder = decoder_database_->GetDecoder(
1969 packet->header.payloadType);
1970 if (decoder) {
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001971 if (packet->sync_packet) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001972 packet_duration = rtc::checked_cast<int>(decoder_frame_length_);
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001973 } else {
minyue@webrtc.org2c1bcf22015-02-17 10:17:09 +00001974 if (packet->primary) {
1975 packet_duration = decoder->PacketDuration(packet->payload,
1976 packet->payload_length);
1977 } else {
1978 packet_duration = decoder->
1979 PacketDurationRedundant(packet->payload, packet->payload_length);
1980 stats_.SecondaryDecodedSamples(packet_duration);
1981 }
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001982 }
ossu97ba30e2016-04-25 07:55:58 -07001983 } else if (!decoder_database_->IsComfortNoise(packet->header.payloadType)) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001984 LOG(LS_WARNING) << "Unknown payload type "
1985 << static_cast<int>(packet->header.payloadType);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001986 assert(false);
1987 }
1988 if (packet_duration <= 0) {
1989 // Decoder did not return a packet duration. Assume that the packet
1990 // contains the same number of samples as the previous one.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001991 packet_duration = rtc::checked_cast<int>(decoder_frame_length_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001992 }
1993 extracted_samples = packet->header.timestamp - first_timestamp +
1994 packet_duration;
1995
1996 // Check what packet is available next.
1997 header = packet_buffer_->NextRtpHeader();
1998 next_packet_available = false;
1999 if (header && prev_payload_type == header->payloadType) {
2000 int16_t seq_no_diff = header->sequenceNumber - prev_sequence_number;
Peter Kastingdce40cf2015-08-24 14:52:23 -07002001 size_t ts_diff = header->timestamp - prev_timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002002 if (seq_no_diff == 1 ||
2003 (seq_no_diff == 0 && ts_diff == decoder_frame_length_)) {
2004 // The next sequence number is available, or the next part of a packet
2005 // that was split into pieces upon insertion.
2006 next_packet_available = true;
2007 }
2008 prev_sequence_number = header->sequenceNumber;
2009 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07002010 } while (extracted_samples < rtc::checked_cast<int>(required_samples) &&
2011 next_packet_available);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002012
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00002013 if (extracted_samples > 0) {
2014 // Delete old packets only when we are going to decode something. Otherwise,
2015 // we could end up in the situation where we never decode anything, since
2016 // all incoming packets are considered too old but the buffer will also
2017 // never be flooded and flushed.
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00002018 packet_buffer_->DiscardAllOldPackets(timestamp_);
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00002019 }
2020
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002021 return extracted_samples;
2022}
2023
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002024void NetEqImpl::UpdatePlcComponents(int fs_hz, size_t channels) {
2025 // Delete objects and create new ones.
2026 expand_.reset(expand_factory_->Create(background_noise_.get(),
2027 sync_buffer_.get(), &random_vector_,
Henrik Lundinbef77e22015-08-18 14:58:09 +02002028 &stats_, fs_hz, channels));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002029 merge_.reset(new Merge(fs_hz, channels, expand_.get(), sync_buffer_.get()));
2030}
2031
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002032void NetEqImpl::SetSampleRateAndChannels(int fs_hz, size_t channels) {
Henrik Lundind67a2192015-08-03 12:54:37 +02002033 LOG(LS_VERBOSE) << "SetSampleRateAndChannels " << fs_hz << " " << channels;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002034 // TODO(hlundin): Change to an enumerator and skip assert.
2035 assert(fs_hz == 8000 || fs_hz == 16000 || fs_hz == 32000 || fs_hz == 48000);
2036 assert(channels > 0);
2037
2038 fs_hz_ = fs_hz;
2039 fs_mult_ = fs_hz / 8000;
Peter Kastingdce40cf2015-08-24 14:52:23 -07002040 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002041 decoder_frame_length_ = 3 * output_size_samples_; // Initialize to 30ms.
2042
2043 last_mode_ = kModeNormal;
2044
2045 // Create a new array of mute factors and set all to 1.
2046 mute_factor_array_.reset(new int16_t[channels]);
2047 for (size_t i = 0; i < channels; ++i) {
2048 mute_factor_array_[i] = 16384; // 1.0 in Q14.
2049 }
2050
ossu97ba30e2016-04-25 07:55:58 -07002051 ComfortNoiseDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02002052 if (cng_decoder)
2053 cng_decoder->Reset();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002054
2055 // Reinit post-decode VAD with new sample rate.
2056 assert(vad_.get()); // Cannot be NULL here.
2057 vad_->Init();
2058
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002059 // Delete algorithm buffer and create a new one.
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00002060 algorithm_buffer_.reset(new AudioMultiVector(channels));
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002061
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002062 // Delete sync buffer and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002063 sync_buffer_.reset(new SyncBuffer(channels, kSyncBufferSize * fs_mult_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002064
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00002065 // Delete BackgroundNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002066 background_noise_.reset(new BackgroundNoise(channels));
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00002067 background_noise_->set_mode(background_noise_mode_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002068
2069 // Reset random vector.
2070 random_vector_.Reset();
2071
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002072 UpdatePlcComponents(fs_hz, channels);
2073
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002074 // Move index so that we create a small set of future samples (all 0).
2075 sync_buffer_->set_next_index(sync_buffer_->next_index() -
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002076 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002077
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002078 normal_.reset(new Normal(fs_hz, decoder_database_.get(), *background_noise_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002079 expand_.get()));
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +00002080 accelerate_.reset(
2081 accelerate_factory_->Create(fs_hz, channels, *background_noise_));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002082 preemptive_expand_.reset(preemptive_expand_factory_->Create(
Peter Kastingdce40cf2015-08-24 14:52:23 -07002083 fs_hz, channels, *background_noise_, expand_->overlap_length()));
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002084
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002085 // Delete ComfortNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002086 comfort_noise_.reset(new ComfortNoise(fs_hz, decoder_database_.get(),
2087 sync_buffer_.get()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002088
2089 // Verify that |decoded_buffer_| is long enough.
2090 if (decoded_buffer_length_ < kMaxFrameSize * channels) {
2091 // Reallocate to larger size.
2092 decoded_buffer_length_ = kMaxFrameSize * channels;
2093 decoded_buffer_.reset(new int16_t[decoded_buffer_length_]);
2094 }
2095
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002096 // Create DecisionLogic if it is not created yet, then communicate new sample
2097 // rate and output size to DecisionLogic object.
2098 if (!decision_logic_.get()) {
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002099 CreateDecisionLogic();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002100 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002101 decision_logic_->SetSampleRate(fs_hz_, output_size_samples_);
2102}
2103
henrik.lundin55480f52016-03-08 02:37:57 -08002104NetEqImpl::OutputType NetEqImpl::LastOutputType() {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002105 assert(vad_.get());
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002106 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002107 if (last_mode_ == kModeCodecInternalCng || last_mode_ == kModeRfc3389Cng) {
henrik.lundin55480f52016-03-08 02:37:57 -08002108 return OutputType::kCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002109 } else if (last_mode_ == kModeExpand && expand_->MuteFactor(0) == 0) {
2110 // Expand mode has faded down to background noise only (very long expand).
henrik.lundin55480f52016-03-08 02:37:57 -08002111 return OutputType::kPLCCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002112 } else if (last_mode_ == kModeExpand) {
henrik.lundin55480f52016-03-08 02:37:57 -08002113 return OutputType::kPLC;
wu@webrtc.org24301a62013-12-13 19:17:43 +00002114 } else if (vad_->running() && !vad_->active_speech()) {
henrik.lundin55480f52016-03-08 02:37:57 -08002115 return OutputType::kVadPassive;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002116 } else {
henrik.lundin55480f52016-03-08 02:37:57 -08002117 return OutputType::kNormalSpeech;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002118 }
2119}
2120
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002121void NetEqImpl::CreateDecisionLogic() {
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002122 decision_logic_.reset(DecisionLogic::Create(fs_hz_, output_size_samples_,
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002123 playout_mode_,
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002124 decoder_database_.get(),
2125 *packet_buffer_.get(),
2126 delay_manager_.get(),
2127 buffer_level_filter_.get()));
2128}
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002129} // namespace webrtc