blob: 5e98b88ff46263997aa93271d7a2ba1fc42d4072 [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"
kwiberg5178ee82016-05-03 01:39:01 -070025#include "webrtc/modules/audio_coding/codecs/builtin_audio_decoder_factory.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000026#include "webrtc/modules/audio_coding/neteq/accelerate.h"
27#include "webrtc/modules/audio_coding/neteq/background_noise.h"
28#include "webrtc/modules/audio_coding/neteq/buffer_level_filter.h"
29#include "webrtc/modules/audio_coding/neteq/comfort_noise.h"
30#include "webrtc/modules/audio_coding/neteq/decision_logic.h"
31#include "webrtc/modules/audio_coding/neteq/decoder_database.h"
32#include "webrtc/modules/audio_coding/neteq/defines.h"
33#include "webrtc/modules/audio_coding/neteq/delay_manager.h"
34#include "webrtc/modules/audio_coding/neteq/delay_peak_detector.h"
35#include "webrtc/modules/audio_coding/neteq/dtmf_buffer.h"
36#include "webrtc/modules/audio_coding/neteq/dtmf_tone_generator.h"
37#include "webrtc/modules/audio_coding/neteq/expand.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000038#include "webrtc/modules/audio_coding/neteq/merge.h"
henrik.lundin48ed9302015-10-29 05:36:24 -070039#include "webrtc/modules/audio_coding/neteq/nack.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000040#include "webrtc/modules/audio_coding/neteq/normal.h"
41#include "webrtc/modules/audio_coding/neteq/packet_buffer.h"
42#include "webrtc/modules/audio_coding/neteq/packet.h"
43#include "webrtc/modules/audio_coding/neteq/payload_splitter.h"
44#include "webrtc/modules/audio_coding/neteq/post_decode_vad.h"
45#include "webrtc/modules/audio_coding/neteq/preemptive_expand.h"
46#include "webrtc/modules/audio_coding/neteq/sync_buffer.h"
henrik.lundined497212016-04-25 10:11:38 -070047#include "webrtc/modules/audio_coding/neteq/tick_timer.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000048#include "webrtc/modules/audio_coding/neteq/timestamp_scaler.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010049#include "webrtc/modules/include/module_common_types.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000050
51// Modify the code to obtain backwards bit-exactness. Once bit-exactness is no
52// longer required, this #define should be removed (and the code that it
53// enables).
54#define LEGACY_BITEXACT
55
56namespace webrtc {
57
henrik.lundin1d9061e2016-04-26 12:19:34 -070058NetEqImpl::Dependencies::Dependencies(const NetEq::Config& config)
59 : tick_timer(new TickTimer),
60 buffer_level_filter(new BufferLevelFilter),
kwiberg5178ee82016-05-03 01:39:01 -070061 decoder_database(new DecoderDatabase(CreateBuiltinAudioDecoderFactory())),
henrik.lundinf3933702016-04-28 01:53:52 -070062 delay_peak_detector(new DelayPeakDetector(tick_timer.get())),
henrik.lundin1d9061e2016-04-26 12:19:34 -070063 delay_manager(new DelayManager(config.max_packets_in_buffer,
henrik.lundin8f8c96d2016-04-28 23:19:20 -070064 delay_peak_detector.get(),
65 tick_timer.get())),
henrik.lundin1d9061e2016-04-26 12:19:34 -070066 dtmf_buffer(new DtmfBuffer(config.sample_rate_hz)),
67 dtmf_tone_generator(new DtmfToneGenerator),
68 packet_buffer(
69 new PacketBuffer(config.max_packets_in_buffer, tick_timer.get())),
70 payload_splitter(new PayloadSplitter),
71 timestamp_scaler(new TimestampScaler(*decoder_database)),
72 accelerate_factory(new AccelerateFactory),
73 expand_factory(new ExpandFactory),
74 preemptive_expand_factory(new PreemptiveExpandFactory) {}
75
76NetEqImpl::Dependencies::~Dependencies() = default;
77
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +000078NetEqImpl::NetEqImpl(const NetEq::Config& config,
henrik.lundin1d9061e2016-04-26 12:19:34 -070079 Dependencies&& deps,
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +000080 bool create_components)
henrik.lundin1d9061e2016-04-26 12:19:34 -070081 : tick_timer_(std::move(deps.tick_timer)),
82 buffer_level_filter_(std::move(deps.buffer_level_filter)),
83 decoder_database_(std::move(deps.decoder_database)),
84 delay_manager_(std::move(deps.delay_manager)),
85 delay_peak_detector_(std::move(deps.delay_peak_detector)),
86 dtmf_buffer_(std::move(deps.dtmf_buffer)),
87 dtmf_tone_generator_(std::move(deps.dtmf_tone_generator)),
88 packet_buffer_(std::move(deps.packet_buffer)),
89 payload_splitter_(std::move(deps.payload_splitter)),
90 timestamp_scaler_(std::move(deps.timestamp_scaler)),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000091 vad_(new PostDecodeVad()),
henrik.lundin1d9061e2016-04-26 12:19:34 -070092 expand_factory_(std::move(deps.expand_factory)),
93 accelerate_factory_(std::move(deps.accelerate_factory)),
94 preemptive_expand_factory_(std::move(deps.preemptive_expand_factory)),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000095 last_mode_(kModeNormal),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000096 decoded_buffer_length_(kMaxFrameSize),
97 decoded_buffer_(new int16_t[decoded_buffer_length_]),
98 playout_timestamp_(0),
99 new_codec_(false),
100 timestamp_(0),
101 reset_decoder_(false),
henrik.lundin48ed9302015-10-29 05:36:24 -0700102 current_rtp_payload_type_(0xFF), // Invalid RTP payload type.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000103 current_cng_rtp_payload_type_(0xFF), // Invalid RTP payload type.
104 ssrc_(0),
105 first_packet_(true),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000106 error_code_(0),
107 decoder_error_code_(0),
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +0000108 background_noise_mode_(config.background_noise_mode),
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000109 playout_mode_(config.playout_mode),
Henrik Lundincf808d22015-05-27 14:33:29 +0200110 enable_fast_accelerate_(config.enable_fast_accelerate),
henrik.lundin7a926812016-05-12 13:51:28 -0700111 nack_enabled_(false),
112 enable_muted_state_(config.enable_muted_state) {
Henrik Lundin905495c2015-05-25 16:58:41 +0200113 LOG(LS_INFO) << "NetEq config: " << config.ToString();
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +0000114 int fs = config.sample_rate_hz;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000115 if (fs != 8000 && fs != 16000 && fs != 32000 && fs != 48000) {
116 LOG(LS_ERROR) << "Sample rate " << fs << " Hz not supported. " <<
117 "Changing to 8000 Hz.";
118 fs = 8000;
119 }
henrik.lundin1d9061e2016-04-26 12:19:34 -0700120 delay_manager_->SetMaximumDelay(config.max_delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000121 fs_hz_ = fs;
122 fs_mult_ = fs / 8000;
henrik.lundind89814b2015-11-23 06:49:25 -0800123 last_output_sample_rate_hz_ = fs;
Peter Kastingdce40cf2015-08-24 14:52:23 -0700124 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000125 decoder_frame_length_ = 3 * output_size_samples_;
126 WebRtcSpl_Init();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000127 if (create_components) {
128 SetSampleRateAndChannels(fs, 1); // Default is 1 channel.
129 }
henrik.lundin9bc26672015-11-02 03:25:57 -0800130 RTC_DCHECK(!vad_->enabled());
131 if (config.enable_post_decode_vad) {
132 vad_->Enable();
133 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000134}
135
Henrik Lundind67a2192015-08-03 12:54:37 +0200136NetEqImpl::~NetEqImpl() = default;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000137
138int NetEqImpl::InsertPacket(const WebRtcRTPHeader& rtp_header,
kwibergee2bac22015-11-11 10:34:00 -0800139 rtc::ArrayView<const uint8_t> payload,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000140 uint32_t receive_timestamp) {
henrik.lundina689b442015-12-17 03:50:05 -0800141 TRACE_EVENT0("webrtc", "NetEqImpl::InsertPacket");
Tommi9090e0b2016-01-20 13:39:36 +0100142 rtc::CritScope lock(&crit_sect_);
kwibergee2bac22015-11-11 10:34:00 -0800143 int error =
144 InsertPacketInternal(rtp_header, payload, receive_timestamp, false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000145 if (error != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000146 error_code_ = error;
147 return kFail;
148 }
149 return kOK;
150}
151
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000152int NetEqImpl::InsertSyncPacket(const WebRtcRTPHeader& rtp_header,
153 uint32_t receive_timestamp) {
Tommi9090e0b2016-01-20 13:39:36 +0100154 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000155 const uint8_t kSyncPayload[] = { 's', 'y', 'n', 'c' };
kwibergee2bac22015-11-11 10:34:00 -0800156 int error =
157 InsertPacketInternal(rtp_header, kSyncPayload, receive_timestamp, true);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000158
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000159 if (error != 0) {
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000160 error_code_ = error;
161 return kFail;
162 }
163 return kOK;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000164}
165
henrik.lundin500c04b2016-03-08 02:36:04 -0800166namespace {
167void SetAudioFrameActivityAndType(bool vad_enabled,
henrik.lundin55480f52016-03-08 02:37:57 -0800168 NetEqImpl::OutputType type,
henrik.lundin500c04b2016-03-08 02:36:04 -0800169 AudioFrame::VADActivity last_vad_activity,
170 AudioFrame* audio_frame) {
171 switch (type) {
henrik.lundin55480f52016-03-08 02:37:57 -0800172 case NetEqImpl::OutputType::kNormalSpeech: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800173 audio_frame->speech_type_ = AudioFrame::kNormalSpeech;
174 audio_frame->vad_activity_ = AudioFrame::kVadActive;
175 break;
176 }
henrik.lundin55480f52016-03-08 02:37:57 -0800177 case NetEqImpl::OutputType::kVadPassive: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800178 // This should only be reached if the VAD is enabled.
179 RTC_DCHECK(vad_enabled);
180 audio_frame->speech_type_ = AudioFrame::kNormalSpeech;
181 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
182 break;
183 }
henrik.lundin55480f52016-03-08 02:37:57 -0800184 case NetEqImpl::OutputType::kCNG: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800185 audio_frame->speech_type_ = AudioFrame::kCNG;
186 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
187 break;
188 }
henrik.lundin55480f52016-03-08 02:37:57 -0800189 case NetEqImpl::OutputType::kPLC: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800190 audio_frame->speech_type_ = AudioFrame::kPLC;
191 audio_frame->vad_activity_ = last_vad_activity;
192 break;
193 }
henrik.lundin55480f52016-03-08 02:37:57 -0800194 case NetEqImpl::OutputType::kPLCCNG: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800195 audio_frame->speech_type_ = AudioFrame::kPLCCNG;
196 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
197 break;
198 }
199 default:
200 RTC_NOTREACHED();
201 }
202 if (!vad_enabled) {
203 // Always set kVadUnknown when receive VAD is inactive.
204 audio_frame->vad_activity_ = AudioFrame::kVadUnknown;
205 }
206}
henrik.lundinbc89de32016-03-08 05:20:14 -0800207} // namespace
henrik.lundin500c04b2016-03-08 02:36:04 -0800208
henrik.lundin7a926812016-05-12 13:51:28 -0700209int NetEqImpl::GetAudio(AudioFrame* audio_frame, bool* muted) {
henrik.lundine1ca1672016-01-08 03:50:08 -0800210 TRACE_EVENT0("webrtc", "NetEqImpl::GetAudio");
Tommi9090e0b2016-01-20 13:39:36 +0100211 rtc::CritScope lock(&crit_sect_);
henrik.lundin7a926812016-05-12 13:51:28 -0700212 int error = GetAudioInternal(audio_frame, muted);
henrik.lundin6d8e0112016-03-04 10:34:21 -0800213 RTC_DCHECK_EQ(
214 audio_frame->sample_rate_hz_,
215 rtc::checked_cast<int>(audio_frame->samples_per_channel_ * 100));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000216 if (error != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000217 error_code_ = error;
218 return kFail;
219 }
henrik.lundin500c04b2016-03-08 02:36:04 -0800220 SetAudioFrameActivityAndType(vad_->enabled(), LastOutputType(),
221 last_vad_activity_, audio_frame);
222 last_vad_activity_ = audio_frame->vad_activity_;
henrik.lundin6d8e0112016-03-04 10:34:21 -0800223 last_output_sample_rate_hz_ = audio_frame->sample_rate_hz_;
henrik.lundind89814b2015-11-23 06:49:25 -0800224 RTC_DCHECK(last_output_sample_rate_hz_ == 8000 ||
225 last_output_sample_rate_hz_ == 16000 ||
226 last_output_sample_rate_hz_ == 32000 ||
227 last_output_sample_rate_hz_ == 48000)
228 << "Unexpected sample rate " << last_output_sample_rate_hz_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000229 return kOK;
230}
231
kwibergee1879c2015-10-29 06:20:28 -0700232int NetEqImpl::RegisterPayloadType(NetEqDecoder codec,
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800233 const std::string& name,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000234 uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100235 rtc::CritScope lock(&crit_sect_);
Henrik Lundind67a2192015-08-03 12:54:37 +0200236 LOG(LS_VERBOSE) << "RegisterPayloadType "
kwibergee1879c2015-10-29 06:20:28 -0700237 << static_cast<int>(rtp_payload_type) << " "
238 << static_cast<int>(codec);
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800239 int ret = decoder_database_->RegisterPayload(rtp_payload_type, codec, name);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000240 if (ret != DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000241 switch (ret) {
242 case DecoderDatabase::kInvalidRtpPayloadType:
243 error_code_ = kInvalidRtpPayloadType;
244 break;
245 case DecoderDatabase::kCodecNotSupported:
246 error_code_ = kCodecNotSupported;
247 break;
248 case DecoderDatabase::kDecoderExists:
249 error_code_ = kDecoderExists;
250 break;
251 default:
252 error_code_ = kOtherError;
253 }
254 return kFail;
255 }
256 return kOK;
257}
258
259int NetEqImpl::RegisterExternalDecoder(AudioDecoder* decoder,
kwibergee1879c2015-10-29 06:20:28 -0700260 NetEqDecoder codec,
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800261 const std::string& codec_name,
Karl Wibergd8399e62015-05-25 14:39:56 +0200262 uint8_t rtp_payload_type,
263 int sample_rate_hz) {
Tommi9090e0b2016-01-20 13:39:36 +0100264 rtc::CritScope lock(&crit_sect_);
Henrik Lundind67a2192015-08-03 12:54:37 +0200265 LOG(LS_VERBOSE) << "RegisterExternalDecoder "
kwibergee1879c2015-10-29 06:20:28 -0700266 << static_cast<int>(rtp_payload_type) << " "
267 << static_cast<int>(codec);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000268 if (!decoder) {
269 LOG(LS_ERROR) << "Cannot register external decoder with NULL pointer";
270 assert(false);
271 return kFail;
272 }
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800273 int ret = decoder_database_->InsertExternal(
274 rtp_payload_type, codec, codec_name, sample_rate_hz, decoder);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000275 if (ret != DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000276 switch (ret) {
277 case DecoderDatabase::kInvalidRtpPayloadType:
278 error_code_ = kInvalidRtpPayloadType;
279 break;
280 case DecoderDatabase::kCodecNotSupported:
281 error_code_ = kCodecNotSupported;
282 break;
283 case DecoderDatabase::kDecoderExists:
284 error_code_ = kDecoderExists;
285 break;
286 case DecoderDatabase::kInvalidSampleRate:
287 error_code_ = kInvalidSampleRate;
288 break;
289 case DecoderDatabase::kInvalidPointer:
290 error_code_ = kInvalidPointer;
291 break;
292 default:
293 error_code_ = kOtherError;
294 }
295 return kFail;
296 }
297 return kOK;
298}
299
300int NetEqImpl::RemovePayloadType(uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100301 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000302 int ret = decoder_database_->Remove(rtp_payload_type);
303 if (ret == DecoderDatabase::kOK) {
304 return kOK;
305 } else if (ret == DecoderDatabase::kDecoderNotFound) {
306 error_code_ = kDecoderNotFound;
307 } else {
308 error_code_ = kOtherError;
309 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000310 return kFail;
311}
312
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000313bool NetEqImpl::SetMinimumDelay(int delay_ms) {
Tommi9090e0b2016-01-20 13:39:36 +0100314 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000315 if (delay_ms >= 0 && delay_ms < 10000) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000316 assert(delay_manager_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000317 return delay_manager_->SetMinimumDelay(delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000318 }
319 return false;
320}
321
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000322bool NetEqImpl::SetMaximumDelay(int delay_ms) {
Tommi9090e0b2016-01-20 13:39:36 +0100323 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000324 if (delay_ms >= 0 && delay_ms < 10000) {
325 assert(delay_manager_.get());
326 return delay_manager_->SetMaximumDelay(delay_ms);
327 }
328 return false;
329}
330
331int NetEqImpl::LeastRequiredDelayMs() const {
Tommi9090e0b2016-01-20 13:39:36 +0100332 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000333 assert(delay_manager_.get());
334 return delay_manager_->least_required_delay_ms();
335}
336
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200337int NetEqImpl::SetTargetDelay() {
338 return kNotImplemented;
339}
340
341int NetEqImpl::TargetDelay() {
342 return kNotImplemented;
343}
344
henrik.lundin9c3efd02015-08-27 13:12:22 -0700345int NetEqImpl::CurrentDelayMs() const {
Tommi9090e0b2016-01-20 13:39:36 +0100346 rtc::CritScope lock(&crit_sect_);
henrik.lundin9c3efd02015-08-27 13:12:22 -0700347 if (fs_hz_ == 0)
348 return 0;
349 // Sum up the samples in the packet buffer with the future length of the sync
350 // buffer, and divide the sum by the sample rate.
351 const size_t delay_samples =
352 packet_buffer_->NumSamplesInBuffer(decoder_database_.get(),
353 decoder_frame_length_) +
354 sync_buffer_->FutureLength();
355 // The division below will truncate.
356 const int delay_ms =
357 static_cast<int>(delay_samples) / rtc::CheckedDivExact(fs_hz_, 1000);
358 return delay_ms;
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200359}
360
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000361// Deprecated.
362// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000363void NetEqImpl::SetPlayoutMode(NetEqPlayoutMode mode) {
Tommi9090e0b2016-01-20 13:39:36 +0100364 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000365 if (mode != playout_mode_) {
366 playout_mode_ = mode;
367 CreateDecisionLogic();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000368 }
369}
370
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000371// Deprecated.
372// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000373NetEqPlayoutMode NetEqImpl::PlayoutMode() const {
Tommi9090e0b2016-01-20 13:39:36 +0100374 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000375 return playout_mode_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000376}
377
378int NetEqImpl::NetworkStatistics(NetEqNetworkStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100379 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000380 assert(decoder_database_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700381 const size_t total_samples_in_buffers =
Peter Kasting728d9032015-06-11 14:31:38 -0700382 packet_buffer_->NumSamplesInBuffer(decoder_database_.get(),
383 decoder_frame_length_) +
Peter Kastingdce40cf2015-08-24 14:52:23 -0700384 sync_buffer_->FutureLength();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000385 assert(delay_manager_.get());
386 assert(decision_logic_.get());
387 stats_.GetNetworkStatistics(fs_hz_, total_samples_in_buffers,
388 decoder_frame_length_, *delay_manager_.get(),
389 *decision_logic_.get(), stats);
390 return 0;
391}
392
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000393void NetEqImpl::GetRtcpStatistics(RtcpStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100394 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000395 if (stats) {
396 rtcp_.GetStatistics(false, stats);
397 }
398}
399
400void NetEqImpl::GetRtcpStatisticsNoReset(RtcpStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100401 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000402 if (stats) {
403 rtcp_.GetStatistics(true, stats);
404 }
405}
406
407void NetEqImpl::EnableVad() {
Tommi9090e0b2016-01-20 13:39:36 +0100408 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000409 assert(vad_.get());
410 vad_->Enable();
411}
412
413void NetEqImpl::DisableVad() {
Tommi9090e0b2016-01-20 13:39:36 +0100414 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000415 assert(vad_.get());
416 vad_->Disable();
417}
418
henrik.lundin15c51e32016-04-06 08:38:56 -0700419rtc::Optional<uint32_t> NetEqImpl::GetPlayoutTimestamp() const {
Tommi9090e0b2016-01-20 13:39:36 +0100420 rtc::CritScope lock(&crit_sect_);
henrik.lundin0d96ab72016-04-06 12:28:26 -0700421 if (first_packet_ || last_mode_ == kModeRfc3389Cng ||
422 last_mode_ == kModeCodecInternalCng) {
wu@webrtc.org94454b72014-06-05 20:34:08 +0000423 // We don't have a valid RTP timestamp until we have decoded our first
henrik.lundin0d96ab72016-04-06 12:28:26 -0700424 // RTP packet. Also, the RTP timestamp is not accurate while playing CNG,
425 // which is indicated by returning an empty value.
henrik.lundin9a410dd2016-04-06 01:39:22 -0700426 return rtc::Optional<uint32_t>();
wu@webrtc.org94454b72014-06-05 20:34:08 +0000427 }
henrik.lundin9a410dd2016-04-06 01:39:22 -0700428 return rtc::Optional<uint32_t>(
429 timestamp_scaler_->ToExternal(playout_timestamp_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000430}
431
henrik.lundind89814b2015-11-23 06:49:25 -0800432int NetEqImpl::last_output_sample_rate_hz() const {
Tommi9090e0b2016-01-20 13:39:36 +0100433 rtc::CritScope lock(&crit_sect_);
henrik.lundind89814b2015-11-23 06:49:25 -0800434 return last_output_sample_rate_hz_;
435}
436
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200437int NetEqImpl::SetTargetNumberOfChannels() {
438 return kNotImplemented;
439}
440
441int NetEqImpl::SetTargetSampleRate() {
442 return kNotImplemented;
443}
444
henrik.lundin@webrtc.orgb0f4b3d2014-11-04 08:53:10 +0000445int NetEqImpl::LastError() const {
Tommi9090e0b2016-01-20 13:39:36 +0100446 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000447 return error_code_;
448}
449
450int NetEqImpl::LastDecoderError() {
Tommi9090e0b2016-01-20 13:39:36 +0100451 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000452 return decoder_error_code_;
453}
454
455void NetEqImpl::FlushBuffers() {
Tommi9090e0b2016-01-20 13:39:36 +0100456 rtc::CritScope lock(&crit_sect_);
Henrik Lundind67a2192015-08-03 12:54:37 +0200457 LOG(LS_VERBOSE) << "FlushBuffers";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000458 packet_buffer_->Flush();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000459 assert(sync_buffer_.get());
460 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000461 sync_buffer_->Flush();
462 sync_buffer_->set_next_index(sync_buffer_->next_index() -
463 expand_->overlap_length());
464 // Set to wait for new codec.
465 first_packet_ = true;
466}
467
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000468void NetEqImpl::PacketBufferStatistics(int* current_num_packets,
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000469 int* max_num_packets) const {
Tommi9090e0b2016-01-20 13:39:36 +0100470 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000471 packet_buffer_->BufferStat(current_num_packets, max_num_packets);
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000472}
473
henrik.lundin48ed9302015-10-29 05:36:24 -0700474void NetEqImpl::EnableNack(size_t max_nack_list_size) {
Tommi9090e0b2016-01-20 13:39:36 +0100475 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700476 if (!nack_enabled_) {
477 const int kNackThresholdPackets = 2;
478 nack_.reset(Nack::Create(kNackThresholdPackets));
479 nack_enabled_ = true;
480 nack_->UpdateSampleRate(fs_hz_);
481 }
482 nack_->SetMaxNackListSize(max_nack_list_size);
483}
484
485void NetEqImpl::DisableNack() {
Tommi9090e0b2016-01-20 13:39:36 +0100486 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700487 nack_.reset();
488 nack_enabled_ = false;
489}
490
491std::vector<uint16_t> NetEqImpl::GetNackList(int64_t round_trip_time_ms) const {
Tommi9090e0b2016-01-20 13:39:36 +0100492 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700493 if (!nack_enabled_) {
494 return std::vector<uint16_t>();
495 }
496 RTC_DCHECK(nack_.get());
497 return nack_->GetNackList(round_trip_time_ms);
minyue@webrtc.orgd7301772013-08-29 00:58:14 +0000498}
499
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000500const SyncBuffer* NetEqImpl::sync_buffer_for_test() const {
Tommi9090e0b2016-01-20 13:39:36 +0100501 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000502 return sync_buffer_.get();
503}
504
minyue5bd33972016-05-02 04:46:11 -0700505Operations NetEqImpl::last_operation_for_test() const {
506 rtc::CritScope lock(&crit_sect_);
507 return last_operation_;
508}
509
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000510// Methods below this line are private.
511
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000512int NetEqImpl::InsertPacketInternal(const WebRtcRTPHeader& rtp_header,
kwibergee2bac22015-11-11 10:34:00 -0800513 rtc::ArrayView<const uint8_t> payload,
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000514 uint32_t receive_timestamp,
515 bool is_sync_packet) {
kwibergee2bac22015-11-11 10:34:00 -0800516 if (payload.empty()) {
517 LOG_F(LS_ERROR) << "payload is empty";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000518 return kInvalidPointer;
519 }
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000520 // Sanity checks for sync-packets.
521 if (is_sync_packet) {
522 if (decoder_database_->IsDtmf(rtp_header.header.payloadType) ||
523 decoder_database_->IsRed(rtp_header.header.payloadType) ||
524 decoder_database_->IsComfortNoise(rtp_header.header.payloadType)) {
525 LOG_F(LS_ERROR) << "Sync-packet with an unacceptable payload type "
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000526 << static_cast<int>(rtp_header.header.payloadType);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000527 return kSyncPacketNotAccepted;
528 }
529 if (first_packet_ ||
530 rtp_header.header.payloadType != current_rtp_payload_type_ ||
531 rtp_header.header.ssrc != ssrc_) {
532 // Even if |current_rtp_payload_type_| is 0xFF, sync-packet isn't
533 // accepted.
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000534 LOG_F(LS_ERROR)
535 << "Changing codec, SSRC or first packet with sync-packet.";
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000536 return kSyncPacketNotAccepted;
537 }
538 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000539 PacketList packet_list;
540 RTPHeader main_header;
541 {
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000542 // Convert to Packet.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000543 // Create |packet| within this separate scope, since it should not be used
544 // directly once it's been inserted in the packet list. This way, |packet|
545 // is not defined outside of this block.
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000546 Packet* packet = new Packet;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000547 packet->header.markerBit = false;
548 packet->header.payloadType = rtp_header.header.payloadType;
549 packet->header.sequenceNumber = rtp_header.header.sequenceNumber;
550 packet->header.timestamp = rtp_header.header.timestamp;
551 packet->header.ssrc = rtp_header.header.ssrc;
552 packet->header.numCSRCs = 0;
kwibergee2bac22015-11-11 10:34:00 -0800553 packet->payload_length = payload.size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000554 packet->primary = true;
henrik.lundin84f8cd62016-04-26 07:45:16 -0700555 // Waiting time will be set upon inserting the packet in the buffer.
556 RTC_DCHECK(!packet->waiting_time);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000557 packet->payload = new uint8_t[packet->payload_length];
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000558 packet->sync_packet = is_sync_packet;
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +0000559 if (!packet->payload) {
560 LOG_F(LS_ERROR) << "Payload pointer is NULL.";
561 }
kwibergee2bac22015-11-11 10:34:00 -0800562 assert(!payload.empty()); // Already checked above.
563 memcpy(packet->payload, payload.data(), packet->payload_length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000564 // Insert packet in a packet list.
565 packet_list.push_back(packet);
566 // Save main payloads header for later.
567 memcpy(&main_header, &packet->header, sizeof(main_header));
568 }
569
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000570 bool update_sample_rate_and_channels = false;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000571 // Reinitialize NetEq if it's needed (changed SSRC or first call).
572 if ((main_header.ssrc != ssrc_) || first_packet_) {
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000573 // Note: |first_packet_| will be cleared further down in this method, once
574 // the packet has been successfully inserted into the packet buffer.
575
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000576 rtcp_.Init(main_header.sequenceNumber);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000577
578 // Flush the packet buffer and DTMF buffer.
579 packet_buffer_->Flush();
580 dtmf_buffer_->Flush();
581
582 // Store new SSRC.
583 ssrc_ = main_header.ssrc;
584
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000585 // Update audio buffer timestamp.
586 sync_buffer_->IncreaseEndTimestamp(main_header.timestamp - timestamp_);
587
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000588 // Update codecs.
589 timestamp_ = main_header.timestamp;
590 current_rtp_payload_type_ = main_header.payloadType;
591
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000592 // Reset timestamp scaling.
593 timestamp_scaler_->Reset();
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000594
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000595 // Trigger an update of sampling rate and the number of channels.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000596 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000597 }
598
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000599 // Update RTCP statistics, only for regular packets.
600 if (!is_sync_packet)
601 rtcp_.Update(main_header, receive_timestamp);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000602
603 // Check for RED payload type, and separate payloads into several packets.
604 if (decoder_database_->IsRed(main_header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000605 assert(!is_sync_packet); // We had a sanity check for this.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000606 if (payload_splitter_->SplitRed(&packet_list) != PayloadSplitter::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000607 PacketBuffer::DeleteAllPackets(&packet_list);
608 return kRedundancySplitError;
609 }
610 // Only accept a few RED payloads of the same type as the main data,
611 // DTMF events and CNG.
612 payload_splitter_->CheckRedPayloads(&packet_list, *decoder_database_);
613 // Update the stored main payload header since the main payload has now
614 // changed.
615 memcpy(&main_header, &packet_list.front()->header, sizeof(main_header));
616 }
617
618 // Check payload types.
619 if (decoder_database_->CheckPayloadTypes(packet_list) ==
620 DecoderDatabase::kDecoderNotFound) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000621 PacketBuffer::DeleteAllPackets(&packet_list);
622 return kUnknownRtpPayloadType;
623 }
624
625 // Scale timestamp to internal domain (only for some codecs).
626 timestamp_scaler_->ToInternal(&packet_list);
627
628 // Process DTMF payloads. Cycle through the list of packets, and pick out any
629 // DTMF payloads found.
630 PacketList::iterator it = packet_list.begin();
631 while (it != packet_list.end()) {
632 Packet* current_packet = (*it);
633 assert(current_packet);
634 assert(current_packet->payload);
635 if (decoder_database_->IsDtmf(current_packet->header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000636 assert(!current_packet->sync_packet); // We had a sanity check for this.
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000637 DtmfEvent event;
638 int ret = DtmfBuffer::ParseEvent(
639 current_packet->header.timestamp,
640 current_packet->payload,
641 current_packet->payload_length,
642 &event);
643 if (ret != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000644 PacketBuffer::DeleteAllPackets(&packet_list);
645 return kDtmfParsingError;
646 }
647 if (dtmf_buffer_->InsertEvent(event) != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000648 PacketBuffer::DeleteAllPackets(&packet_list);
649 return kDtmfInsertError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000650 }
651 // TODO(hlundin): Let the destructor of Packet handle the payload.
652 delete [] current_packet->payload;
653 delete current_packet;
654 it = packet_list.erase(it);
655 } else {
656 ++it;
657 }
658 }
659
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000660 // Check for FEC in packets, and separate payloads into several packets.
661 int ret = payload_splitter_->SplitFec(&packet_list, decoder_database_.get());
662 if (ret != PayloadSplitter::kOK) {
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000663 PacketBuffer::DeleteAllPackets(&packet_list);
664 switch (ret) {
665 case PayloadSplitter::kUnknownPayloadType:
666 return kUnknownRtpPayloadType;
667 default:
668 return kOtherError;
669 }
670 }
671
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000672 // Split payloads into smaller chunks. This also verifies that all payloads
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000673 // are of a known payload type. SplitAudio() method is protected against
674 // sync-packets.
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +0000675 ret = payload_splitter_->SplitAudio(&packet_list, *decoder_database_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000676 if (ret != PayloadSplitter::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000677 PacketBuffer::DeleteAllPackets(&packet_list);
678 switch (ret) {
679 case PayloadSplitter::kUnknownPayloadType:
680 return kUnknownRtpPayloadType;
681 case PayloadSplitter::kFrameSplitError:
682 return kFrameSplitError;
683 default:
684 return kOtherError;
685 }
686 }
687
ossu97ba30e2016-04-25 07:55:58 -0700688 // Update bandwidth estimate, if the packet is not sync-packet nor comfort
689 // noise.
690 if (!packet_list.empty() && !packet_list.front()->sync_packet &&
691 !decoder_database_->IsComfortNoise(main_header.payloadType)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000692 // The list can be empty here if we got nothing but DTMF payloads.
693 AudioDecoder* decoder =
694 decoder_database_->GetDecoder(main_header.payloadType);
695 assert(decoder); // Should always get a valid object, since we have
ossu97ba30e2016-04-25 07:55:58 -0700696 // already checked that the payload types are known.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000697 decoder->IncomingPacket(packet_list.front()->payload,
698 packet_list.front()->payload_length,
699 packet_list.front()->header.sequenceNumber,
700 packet_list.front()->header.timestamp,
701 receive_timestamp);
702 }
703
henrik.lundin48ed9302015-10-29 05:36:24 -0700704 if (nack_enabled_) {
705 RTC_DCHECK(nack_);
706 if (update_sample_rate_and_channels) {
707 nack_->Reset();
708 }
709 nack_->UpdateLastReceivedPacket(packet_list.front()->header.sequenceNumber,
710 packet_list.front()->header.timestamp);
711 }
712
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000713 // Insert packets in buffer.
henrik.lundin116c84e2015-08-27 13:14:48 -0700714 const size_t buffer_length_before_insert =
715 packet_buffer_->NumPacketsInBuffer();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000716 ret = packet_buffer_->InsertPacketList(
717 &packet_list,
718 *decoder_database_,
719 &current_rtp_payload_type_,
720 &current_cng_rtp_payload_type_);
721 if (ret == PacketBuffer::kFlushed) {
722 // Reset DSP timestamp etc. if packet buffer flushed.
723 new_codec_ = true;
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000724 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000725 } else if (ret != PacketBuffer::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000726 PacketBuffer::DeleteAllPackets(&packet_list);
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000727 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000728 }
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000729
730 if (first_packet_) {
731 first_packet_ = false;
732 // Update the codec on the next GetAudio call.
733 new_codec_ = true;
734 }
735
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000736 if (current_rtp_payload_type_ != 0xFF) {
737 const DecoderDatabase::DecoderInfo* dec_info =
738 decoder_database_->GetDecoderInfo(current_rtp_payload_type_);
739 if (!dec_info) {
740 assert(false); // Already checked that the payload type is known.
741 }
742 }
743
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000744 if (update_sample_rate_and_channels && !packet_buffer_->Empty()) {
745 // We do not use |current_rtp_payload_type_| to |set payload_type|, but
746 // get the next RTP header from |packet_buffer_| to obtain the payload type.
747 // The reason for it is the following corner case. If NetEq receives a
748 // CNG packet with a sample rate different than the current CNG then it
749 // flushes its buffer, assuming send codec must have been changed. However,
750 // payload type of the hypothetically new send codec is not known.
751 const RTPHeader* rtp_header = packet_buffer_->NextRtpHeader();
752 assert(rtp_header);
753 int payload_type = rtp_header->payloadType;
ossu97ba30e2016-04-25 07:55:58 -0700754 size_t channels = 1;
755 if (!decoder_database_->IsComfortNoise(payload_type)) {
756 AudioDecoder* decoder = decoder_database_->GetDecoder(payload_type);
757 assert(decoder); // Payloads are already checked to be valid.
758 channels = decoder->Channels();
759 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000760 const DecoderDatabase::DecoderInfo* decoder_info =
761 decoder_database_->GetDecoderInfo(payload_type);
762 assert(decoder_info);
763 if (decoder_info->fs_hz != fs_hz_ ||
ossu97ba30e2016-04-25 07:55:58 -0700764 channels != algorithm_buffer_->Channels()) {
765 SetSampleRateAndChannels(decoder_info->fs_hz, channels);
henrik.lundin48ed9302015-10-29 05:36:24 -0700766 }
767 if (nack_enabled_) {
768 RTC_DCHECK(nack_);
769 // Update the sample rate even if the rate is not new, because of Reset().
770 nack_->UpdateSampleRate(fs_hz_);
771 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000772 }
773
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000774 // TODO(hlundin): Move this code to DelayManager class.
775 const DecoderDatabase::DecoderInfo* dec_info =
776 decoder_database_->GetDecoderInfo(main_header.payloadType);
777 assert(dec_info); // Already checked that the payload type is known.
778 delay_manager_->LastDecoderType(dec_info->codec_type);
779 if (delay_manager_->last_pack_cng_or_dtmf() == 0) {
780 // Calculate the total speech length carried in each packet.
henrik.lundin116c84e2015-08-27 13:14:48 -0700781 const size_t buffer_length_after_insert =
782 packet_buffer_->NumPacketsInBuffer();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000783
henrik.lundin116c84e2015-08-27 13:14:48 -0700784 if (buffer_length_after_insert > buffer_length_before_insert) {
785 const size_t packet_length_samples =
786 (buffer_length_after_insert - buffer_length_before_insert) *
787 decoder_frame_length_;
788 if (packet_length_samples != decision_logic_->packet_length_samples()) {
789 decision_logic_->set_packet_length_samples(packet_length_samples);
790 delay_manager_->SetPacketAudioLength(
791 rtc::checked_cast<int>((1000 * packet_length_samples) / fs_hz_));
792 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000793 }
794
795 // Update statistics.
pbos@webrtc.org0946a562013-04-09 00:28:06 +0000796 if ((int32_t) (main_header.timestamp - timestamp_) >= 0 &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000797 !new_codec_) {
798 // Only update statistics if incoming packet is not older than last played
799 // out packet, and if new codec flag is not set.
800 delay_manager_->Update(main_header.sequenceNumber, main_header.timestamp,
801 fs_hz_);
802 }
803 } else if (delay_manager_->last_pack_cng_or_dtmf() == -1) {
804 // This is first "normal" packet after CNG or DTMF.
805 // Reset packet time counter and measure time until next packet,
806 // but don't update statistics.
807 delay_manager_->set_last_pack_cng_or_dtmf(0);
808 delay_manager_->ResetPacketIatCount();
809 }
810 return 0;
811}
812
henrik.lundin7a926812016-05-12 13:51:28 -0700813int NetEqImpl::GetAudioInternal(AudioFrame* audio_frame, bool* muted) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000814 PacketList packet_list;
815 DtmfEvent dtmf_event;
816 Operations operation;
817 bool play_dtmf;
henrik.lundin7a926812016-05-12 13:51:28 -0700818 *muted = false;
henrik.lundined497212016-04-25 10:11:38 -0700819 tick_timer_->Increment();
henrik.lundin60f6ce22016-05-10 03:52:04 -0700820 stats_.IncreaseCounter(output_size_samples_, fs_hz_);
henrik.lundin7a926812016-05-12 13:51:28 -0700821
822 // Check for muted state.
823 if (enable_muted_state_ && expand_->Muted() && packet_buffer_->Empty()) {
824 RTC_DCHECK_EQ(last_mode_, kModeExpand);
825 playout_timestamp_ += static_cast<uint32_t>(output_size_samples_);
826 audio_frame->sample_rate_hz_ = fs_hz_;
827 audio_frame->samples_per_channel_ = output_size_samples_;
828 audio_frame->timestamp_ =
829 first_packet_
830 ? 0
831 : timestamp_scaler_->ToExternal(playout_timestamp_) -
832 static_cast<uint32_t>(audio_frame->samples_per_channel_);
833 audio_frame->num_channels_ = sync_buffer_->Channels();
834 *muted = true;
835 return 0;
836 }
837
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000838 int return_value = GetDecision(&operation, &packet_list, &dtmf_event,
839 &play_dtmf);
840 if (return_value != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000841 last_mode_ = kModeError;
842 return return_value;
843 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000844
845 AudioDecoder::SpeechType speech_type;
846 int length = 0;
847 int decode_return_value = Decode(&packet_list, &operation,
848 &length, &speech_type);
849
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000850 assert(vad_.get());
851 bool sid_frame_available =
852 (operation == kRfc3389Cng && !packet_list.empty());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700853 vad_->Update(decoded_buffer_.get(), static_cast<size_t>(length), speech_type,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000854 sid_frame_available, fs_hz_);
855
henrik.lundinb1fb72b2016-05-03 08:18:47 -0700856 if (sid_frame_available || speech_type == AudioDecoder::kComfortNoise) {
857 // Start a new stopwatch since we are decoding a new CNG packet.
858 generated_noise_stopwatch_ = tick_timer_->GetNewStopwatch();
859 }
860
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000861 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000862 switch (operation) {
863 case kNormal: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000864 DoNormal(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000865 break;
866 }
867 case kMerge: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000868 DoMerge(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000869 break;
870 }
871 case kExpand: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000872 return_value = DoExpand(play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000873 break;
874 }
Henrik Lundincf808d22015-05-27 14:33:29 +0200875 case kAccelerate:
876 case kFastAccelerate: {
877 const bool fast_accelerate =
878 enable_fast_accelerate_ && (operation == kFastAccelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000879 return_value = DoAccelerate(decoded_buffer_.get(), length, speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +0200880 play_dtmf, fast_accelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000881 break;
882 }
883 case kPreemptiveExpand: {
884 return_value = DoPreemptiveExpand(decoded_buffer_.get(), length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000885 speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000886 break;
887 }
888 case kRfc3389Cng:
889 case kRfc3389CngNoPacket: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000890 return_value = DoRfc3389Cng(&packet_list, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000891 break;
892 }
893 case kCodecInternalCng: {
894 // This handles the case when there is no transmission and the decoder
895 // should produce internal comfort noise.
896 // TODO(hlundin): Write test for codec-internal CNG.
minyuel6d92bf52015-09-23 15:20:39 +0200897 DoCodecInternalCng(decoded_buffer_.get(), length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000898 break;
899 }
900 case kDtmf: {
901 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000902 return_value = DoDtmf(dtmf_event, &play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000903 break;
904 }
905 case kAlternativePlc: {
906 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000907 DoAlternativePlc(false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000908 break;
909 }
910 case kAlternativePlcIncreaseTimestamp: {
911 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000912 DoAlternativePlc(true);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000913 break;
914 }
915 case kAudioRepetitionIncreaseTimestamp: {
916 // TODO(hlundin): Write test for this.
Peter Kastingb7e50542015-06-11 12:55:50 -0700917 sync_buffer_->IncreaseEndTimestamp(
918 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000919 // Skipping break on purpose. Execution should move on into the
920 // next case.
kjellander@webrtc.org7d2b6a92015-01-28 18:37:58 +0000921 FALLTHROUGH();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000922 }
923 case kAudioRepetition: {
924 // TODO(hlundin): Write test for this.
925 // Copy last |output_size_samples_| from |sync_buffer_| to
926 // |algorithm_buffer|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000927 algorithm_buffer_->PushBackFromIndex(
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000928 *sync_buffer_, sync_buffer_->Size() - output_size_samples_);
929 expand_->Reset();
930 break;
931 }
932 case kUndefined: {
Henrik Lundind67a2192015-08-03 12:54:37 +0200933 LOG(LS_ERROR) << "Invalid operation kUndefined.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000934 assert(false); // This should not happen.
935 last_mode_ = kModeError;
936 return kInvalidOperation;
937 }
938 } // End of switch.
minyue5bd33972016-05-02 04:46:11 -0700939 last_operation_ = operation;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000940 if (return_value < 0) {
941 return return_value;
942 }
943
944 if (last_mode_ != kModeRfc3389Cng) {
945 comfort_noise_->Reset();
946 }
947
948 // Copy from |algorithm_buffer| to |sync_buffer_|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000949 sync_buffer_->PushBack(*algorithm_buffer_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000950
951 // Extract data from |sync_buffer_| to |output|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000952 size_t num_output_samples_per_channel = output_size_samples_;
953 size_t num_output_samples = output_size_samples_ * sync_buffer_->Channels();
henrik.lundin6d8e0112016-03-04 10:34:21 -0800954 if (num_output_samples > AudioFrame::kMaxDataSizeSamples) {
955 LOG(LS_WARNING) << "Output array is too short. "
956 << AudioFrame::kMaxDataSizeSamples << " < "
957 << output_size_samples_ << " * "
958 << sync_buffer_->Channels();
959 num_output_samples = AudioFrame::kMaxDataSizeSamples;
960 num_output_samples_per_channel =
961 AudioFrame::kMaxDataSizeSamples / sync_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000962 }
henrik.lundin6d8e0112016-03-04 10:34:21 -0800963 sync_buffer_->GetNextAudioInterleaved(num_output_samples_per_channel,
964 audio_frame);
965 audio_frame->sample_rate_hz_ = fs_hz_;
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200966 if (sync_buffer_->FutureLength() < expand_->overlap_length()) {
967 // The sync buffer should always contain |overlap_length| samples, but now
968 // too many samples have been extracted. Reinstall the |overlap_length|
969 // lookahead by moving the index.
970 const size_t missing_lookahead_samples =
971 expand_->overlap_length() - sync_buffer_->FutureLength();
henrikg91d6ede2015-09-17 00:24:34 -0700972 RTC_DCHECK_GE(sync_buffer_->next_index(), missing_lookahead_samples);
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200973 sync_buffer_->set_next_index(sync_buffer_->next_index() -
974 missing_lookahead_samples);
975 }
henrik.lundin6d8e0112016-03-04 10:34:21 -0800976 if (audio_frame->samples_per_channel_ != output_size_samples_) {
977 LOG(LS_ERROR) << "audio_frame->samples_per_channel_ ("
978 << audio_frame->samples_per_channel_
Henrik Lundind67a2192015-08-03 12:54:37 +0200979 << ") != output_size_samples_ (" << output_size_samples_
980 << ")";
minyue@webrtc.orgdb1cefc2013-08-13 01:39:21 +0000981 // TODO(minyue): treatment of under-run, filling zeros
henrik.lundin6d8e0112016-03-04 10:34:21 -0800982 memset(audio_frame->data_, 0, num_output_samples * sizeof(int16_t));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000983 return kSampleUnderrun;
984 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000985
986 // Should always have overlap samples left in the |sync_buffer_|.
henrikg91d6ede2015-09-17 00:24:34 -0700987 RTC_DCHECK_GE(sync_buffer_->FutureLength(), expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000988
989 if (play_dtmf) {
henrik.lundin6d8e0112016-03-04 10:34:21 -0800990 return_value =
991 DtmfOverdub(dtmf_event, sync_buffer_->Channels(), audio_frame->data_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000992 }
993
994 // Update the background noise parameters if last operation wrote data
995 // straight from the decoder to the |sync_buffer_|. That is, none of the
996 // operations that modify the signal can be followed by a parameter update.
997 if ((last_mode_ == kModeNormal) ||
998 (last_mode_ == kModeAccelerateFail) ||
999 (last_mode_ == kModePreemptiveExpandFail) ||
1000 (last_mode_ == kModeRfc3389Cng) ||
1001 (last_mode_ == kModeCodecInternalCng)) {
1002 background_noise_->Update(*sync_buffer_, *vad_.get());
1003 }
1004
1005 if (operation == kDtmf) {
1006 // DTMF data was written the end of |sync_buffer_|.
1007 // Update index to end of DTMF data in |sync_buffer_|.
1008 sync_buffer_->set_dtmf_index(sync_buffer_->Size());
1009 }
1010
henrik.lundin@webrtc.orged865b52014-03-06 10:28:07 +00001011 if (last_mode_ != kModeExpand) {
1012 // If last operation was not expand, calculate the |playout_timestamp_| from
1013 // the |sync_buffer_|. However, do not update the |playout_timestamp_| if it
1014 // would be moved "backwards".
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001015 uint32_t temp_timestamp = sync_buffer_->end_timestamp() -
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001016 static_cast<uint32_t>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001017 if (static_cast<int32_t>(temp_timestamp - playout_timestamp_) > 0) {
1018 playout_timestamp_ = temp_timestamp;
1019 }
1020 } else {
1021 // Use dead reckoning to estimate the |playout_timestamp_|.
Peter Kastingb7e50542015-06-11 12:55:50 -07001022 playout_timestamp_ += static_cast<uint32_t>(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001023 }
henrik.lundin15c51e32016-04-06 08:38:56 -07001024 // Set the timestamp in the audio frame to zero before the first packet has
1025 // been inserted. Otherwise, subtract the frame size in samples to get the
1026 // timestamp of the first sample in the frame (playout_timestamp_ is the
1027 // last + 1).
1028 audio_frame->timestamp_ =
1029 first_packet_
1030 ? 0
1031 : timestamp_scaler_->ToExternal(playout_timestamp_) -
1032 static_cast<uint32_t>(audio_frame->samples_per_channel_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001033
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001034 if (!(last_mode_ == kModeRfc3389Cng ||
1035 last_mode_ == kModeCodecInternalCng ||
1036 last_mode_ == kModeExpand)) {
1037 generated_noise_stopwatch_.reset();
1038 }
1039
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001040 if (decode_return_value) return decode_return_value;
1041 return return_value;
1042}
1043
1044int NetEqImpl::GetDecision(Operations* operation,
1045 PacketList* packet_list,
1046 DtmfEvent* dtmf_event,
1047 bool* play_dtmf) {
1048 // Initialize output variables.
1049 *play_dtmf = false;
1050 *operation = kUndefined;
1051
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001052 assert(sync_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001053 uint32_t end_timestamp = sync_buffer_->end_timestamp();
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001054 if (!new_codec_) {
1055 const uint32_t five_seconds_samples = 5 * fs_hz_;
1056 packet_buffer_->DiscardOldPackets(end_timestamp, five_seconds_samples);
1057 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001058 const RTPHeader* header = packet_buffer_->NextRtpHeader();
1059
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001060 RTC_DCHECK(!generated_noise_stopwatch_ ||
1061 generated_noise_stopwatch_->ElapsedTicks() >= 1);
1062 uint64_t generated_noise_samples =
1063 generated_noise_stopwatch_
1064 ? (generated_noise_stopwatch_->ElapsedTicks() - 1) *
1065 output_size_samples_ +
1066 decision_logic_->noise_fast_forward()
1067 : 0;
1068
henrik.lundin@webrtc.orgca8cb952014-03-12 10:26:52 +00001069 if (decision_logic_->CngRfc3389On() || last_mode_ == kModeRfc3389Cng) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001070 // Because of timestamp peculiarities, we have to "manually" disallow using
1071 // a CNG packet with the same timestamp as the one that was last played.
1072 // This can happen when using redundancy and will cause the timing to shift.
henrik.lundin@webrtc.org24779fe2014-03-14 12:40:05 +00001073 while (header && decoder_database_->IsComfortNoise(header->payloadType) &&
1074 (end_timestamp >= header->timestamp ||
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001075 end_timestamp + generated_noise_samples > header->timestamp)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001076 // Don't use this packet, discard it.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001077 if (packet_buffer_->DiscardNextPacket() != PacketBuffer::kOK) {
1078 assert(false); // Must be ok by design.
1079 }
1080 // Check buffer again.
1081 if (!new_codec_) {
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001082 packet_buffer_->DiscardOldPackets(end_timestamp, 5 * fs_hz_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001083 }
1084 header = packet_buffer_->NextRtpHeader();
1085 }
1086 }
1087
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001088 assert(expand_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001089 const int samples_left = static_cast<int>(sync_buffer_->FutureLength() -
1090 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001091 if (last_mode_ == kModeAccelerateSuccess ||
1092 last_mode_ == kModeAccelerateLowEnergy ||
1093 last_mode_ == kModePreemptiveExpandSuccess ||
1094 last_mode_ == kModePreemptiveExpandLowEnergy) {
1095 // Subtract (samples_left + output_size_samples_) from sampleMemory.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001096 decision_logic_->AddSampleMemory(
1097 -(samples_left + rtc::checked_cast<int>(output_size_samples_)));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001098 }
1099
1100 // Check if it is time to play a DTMF event.
Peter Kastingb7e50542015-06-11 12:55:50 -07001101 if (dtmf_buffer_->GetEvent(
1102 static_cast<uint32_t>(
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001103 end_timestamp + generated_noise_samples),
Peter Kastingb7e50542015-06-11 12:55:50 -07001104 dtmf_event)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001105 *play_dtmf = true;
1106 }
1107
1108 // Get instruction.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001109 assert(sync_buffer_.get());
1110 assert(expand_.get());
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001111 generated_noise_samples =
1112 generated_noise_stopwatch_
1113 ? generated_noise_stopwatch_->ElapsedTicks() * output_size_samples_ +
1114 decision_logic_->noise_fast_forward()
1115 : 0;
1116 *operation = decision_logic_->GetDecision(
1117 *sync_buffer_, *expand_, decoder_frame_length_, header, last_mode_,
1118 *play_dtmf, generated_noise_samples, &reset_decoder_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001119
1120 // Check if we already have enough samples in the |sync_buffer_|. If so,
1121 // change decision to normal, unless the decision was merge, accelerate, or
1122 // preemptive expand.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001123 if (samples_left >= rtc::checked_cast<int>(output_size_samples_) &&
1124 *operation != kMerge &&
1125 *operation != kAccelerate &&
1126 *operation != kFastAccelerate &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001127 *operation != kPreemptiveExpand) {
1128 *operation = kNormal;
1129 return 0;
1130 }
1131
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001132 decision_logic_->ExpandDecision(*operation);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001133
1134 // Check conditions for reset.
1135 if (new_codec_ || *operation == kUndefined) {
1136 // The only valid reason to get kUndefined is that new_codec_ is set.
1137 assert(new_codec_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001138 if (*play_dtmf && !header) {
1139 timestamp_ = dtmf_event->timestamp;
1140 } else {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001141 if (!header) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001142 LOG(LS_ERROR) << "Packet missing where it shouldn't.";
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001143 return -1;
1144 }
1145 timestamp_ = header->timestamp;
1146 if (*operation == kRfc3389CngNoPacket
1147#ifndef LEGACY_BITEXACT
1148 // Without this check, it can happen that a non-CNG packet is sent to
1149 // the CNG decoder as if it was a SID frame. This is clearly a bug,
1150 // but is kept for now to maintain bit-exactness with the test
1151 // vectors.
1152 && decoder_database_->IsComfortNoise(header->payloadType)
1153#endif
1154 ) {
1155 // Change decision to CNG packet, since we do have a CNG packet, but it
1156 // was considered too early to use. Now, use it anyway.
1157 *operation = kRfc3389Cng;
1158 } else if (*operation != kRfc3389Cng) {
1159 *operation = kNormal;
1160 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001161 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001162 // Adjust |sync_buffer_| timestamp before setting |end_timestamp| to the
1163 // new value.
1164 sync_buffer_->IncreaseEndTimestamp(timestamp_ - end_timestamp);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001165 end_timestamp = timestamp_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001166 new_codec_ = false;
1167 decision_logic_->SoftReset();
1168 buffer_level_filter_->Reset();
1169 delay_manager_->Reset();
1170 stats_.ResetMcu();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001171 }
1172
Peter Kastingdce40cf2015-08-24 14:52:23 -07001173 size_t required_samples = output_size_samples_;
1174 const size_t samples_10_ms = static_cast<size_t>(80 * fs_mult_);
1175 const size_t samples_20_ms = 2 * samples_10_ms;
1176 const size_t samples_30_ms = 3 * samples_10_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001177
1178 switch (*operation) {
1179 case kExpand: {
1180 timestamp_ = end_timestamp;
1181 return 0;
1182 }
1183 case kRfc3389CngNoPacket:
1184 case kCodecInternalCng: {
1185 return 0;
1186 }
1187 case kDtmf: {
1188 // TODO(hlundin): Write test for this.
1189 // Update timestamp.
1190 timestamp_ = end_timestamp;
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001191 const uint64_t generated_noise_samples =
1192 generated_noise_stopwatch_
1193 ? generated_noise_stopwatch_->ElapsedTicks() *
1194 output_size_samples_ +
1195 decision_logic_->noise_fast_forward()
1196 : 0;
1197 if (generated_noise_samples > 0 && last_mode_ != kModeDtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001198 // Make a jump in timestamp due to the recently played comfort noise.
Peter Kastingb7e50542015-06-11 12:55:50 -07001199 uint32_t timestamp_jump =
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001200 static_cast<uint32_t>(generated_noise_samples);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001201 sync_buffer_->IncreaseEndTimestamp(timestamp_jump);
1202 timestamp_ += timestamp_jump;
1203 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001204 return 0;
1205 }
Henrik Lundincf808d22015-05-27 14:33:29 +02001206 case kAccelerate:
1207 case kFastAccelerate: {
1208 // In order to do an accelerate we need at least 30 ms of audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001209 if (samples_left >= static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001210 // Already have enough data, so we do not need to extract any more.
1211 decision_logic_->set_sample_memory(samples_left);
1212 decision_logic_->set_prev_time_scale(true);
1213 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001214 } else if (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001215 decoder_frame_length_ >= samples_30_ms) {
1216 // Avoid decoding more data as it might overflow the playout buffer.
1217 *operation = kNormal;
1218 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001219 } else if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001220 decoder_frame_length_ < samples_30_ms) {
1221 // Build up decoded data by decoding at least 20 ms of audio data. Do
1222 // not perform accelerate yet, but wait until we only need to do one
1223 // decoding.
1224 required_samples = 2 * output_size_samples_;
1225 *operation = kNormal;
1226 }
1227 // If none of the above is true, we have one of two possible situations:
1228 // (1) 20 ms <= samples_left < 30 ms and decoder_frame_length_ < 30 ms; or
1229 // (2) samples_left < 10 ms and decoder_frame_length_ >= 30 ms.
1230 // In either case, we move on with the accelerate decision, and decode one
1231 // frame now.
1232 break;
1233 }
1234 case kPreemptiveExpand: {
1235 // In order to do a preemptive expand we need at least 30 ms of decoded
1236 // audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001237 if ((samples_left >= static_cast<int>(samples_30_ms)) ||
1238 (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001239 decoder_frame_length_ >= samples_30_ms)) {
1240 // Already have enough data, so we do not need to extract any more.
1241 // Or, avoid decoding more data as it might overflow the playout buffer.
1242 // Still try preemptive expand, though.
1243 decision_logic_->set_sample_memory(samples_left);
1244 decision_logic_->set_prev_time_scale(true);
1245 return 0;
1246 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07001247 if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001248 decoder_frame_length_ < samples_30_ms) {
1249 // Build up decoded data by decoding at least 20 ms of audio data.
1250 // Still try to perform preemptive expand.
1251 required_samples = 2 * output_size_samples_;
1252 }
1253 // Move on with the preemptive expand decision.
1254 break;
1255 }
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001256 case kMerge: {
1257 required_samples =
1258 std::max(merge_->RequiredFutureSamples(), required_samples);
1259 break;
1260 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001261 default: {
1262 // Do nothing.
1263 }
1264 }
1265
1266 // Get packets from buffer.
1267 int extracted_samples = 0;
1268 if (header &&
1269 *operation != kAlternativePlc &&
1270 *operation != kAlternativePlcIncreaseTimestamp &&
1271 *operation != kAudioRepetition &&
1272 *operation != kAudioRepetitionIncreaseTimestamp) {
1273 sync_buffer_->IncreaseEndTimestamp(header->timestamp - end_timestamp);
1274 if (decision_logic_->CngOff()) {
1275 // Adjustment of timestamp only corresponds to an actual packet loss
1276 // if comfort noise is not played. If comfort noise was just played,
1277 // this adjustment of timestamp is only done to get back in sync with the
1278 // stream timestamp; no loss to report.
1279 stats_.LostSamples(header->timestamp - end_timestamp);
1280 }
1281
1282 if (*operation != kRfc3389Cng) {
1283 // We are about to decode and use a non-CNG packet.
1284 decision_logic_->SetCngOff();
1285 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001286
1287 extracted_samples = ExtractPackets(required_samples, packet_list);
1288 if (extracted_samples < 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001289 return kPacketBufferCorruption;
1290 }
1291 }
1292
Henrik Lundincf808d22015-05-27 14:33:29 +02001293 if (*operation == kAccelerate || *operation == kFastAccelerate ||
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001294 *operation == kPreemptiveExpand) {
1295 decision_logic_->set_sample_memory(samples_left + extracted_samples);
1296 decision_logic_->set_prev_time_scale(true);
1297 }
1298
Henrik Lundincf808d22015-05-27 14:33:29 +02001299 if (*operation == kAccelerate || *operation == kFastAccelerate) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001300 // Check that we have enough data (30ms) to do accelerate.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001301 if (extracted_samples + samples_left < static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001302 // TODO(hlundin): Write test for this.
1303 // Not enough, do normal operation instead.
1304 *operation = kNormal;
1305 }
1306 }
1307
1308 timestamp_ = end_timestamp;
1309 return 0;
1310}
1311
1312int NetEqImpl::Decode(PacketList* packet_list, Operations* operation,
1313 int* decoded_length,
1314 AudioDecoder::SpeechType* speech_type) {
1315 *speech_type = AudioDecoder::kSpeech;
minyuel6d92bf52015-09-23 15:20:39 +02001316
1317 // When packet_list is empty, we may be in kCodecInternalCng mode, and for
1318 // that we use current active decoder.
1319 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1320
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001321 if (!packet_list->empty()) {
1322 const Packet* packet = packet_list->front();
pkasting@chromium.org0e81fdf2015-02-02 23:54:03 +00001323 uint8_t payload_type = packet->header.payloadType;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001324 if (!decoder_database_->IsComfortNoise(payload_type)) {
1325 decoder = decoder_database_->GetDecoder(payload_type);
1326 assert(decoder);
1327 if (!decoder) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001328 LOG(LS_WARNING) << "Unknown payload type "
1329 << static_cast<int>(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001330 PacketBuffer::DeleteAllPackets(packet_list);
1331 return kDecoderNotFound;
1332 }
1333 bool decoder_changed;
1334 decoder_database_->SetActiveDecoder(payload_type, &decoder_changed);
1335 if (decoder_changed) {
1336 // We have a new decoder. Re-init some values.
1337 const DecoderDatabase::DecoderInfo* decoder_info = decoder_database_
1338 ->GetDecoderInfo(payload_type);
1339 assert(decoder_info);
1340 if (!decoder_info) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001341 LOG(LS_WARNING) << "Unknown payload type "
1342 << static_cast<int>(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001343 PacketBuffer::DeleteAllPackets(packet_list);
1344 return kDecoderNotFound;
1345 }
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001346 // If sampling rate or number of channels has changed, we need to make
1347 // a reset.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001348 if (decoder_info->fs_hz != fs_hz_ ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001349 decoder->Channels() != algorithm_buffer_->Channels()) {
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001350 // TODO(tlegrand): Add unittest to cover this event.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001351 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->Channels());
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001352 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001353 sync_buffer_->set_end_timestamp(timestamp_);
1354 playout_timestamp_ = timestamp_;
1355 }
1356 }
1357 }
1358
1359 if (reset_decoder_) {
1360 // TODO(hlundin): Write test for this.
Karl Wiberg43766482015-08-27 15:22:11 +02001361 if (decoder)
1362 decoder->Reset();
1363
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001364 // Reset comfort noise decoder.
ossu97ba30e2016-04-25 07:55:58 -07001365 ComfortNoiseDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02001366 if (cng_decoder)
1367 cng_decoder->Reset();
1368
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001369 reset_decoder_ = false;
1370 }
1371
1372#ifdef LEGACY_BITEXACT
1373 // Due to a bug in old SignalMCU, it could happen that CNG operation was
1374 // decided, but a speech packet was provided. The speech packet will be used
1375 // to update the comfort noise decoder, as if it was a SID frame, which is
1376 // clearly wrong.
1377 if (*operation == kRfc3389Cng) {
1378 return 0;
1379 }
1380#endif
1381
1382 *decoded_length = 0;
1383 // Update codec-internal PLC state.
1384 if ((*operation == kMerge) && decoder && decoder->HasDecodePlc()) {
1385 decoder->DecodePlc(1, &decoded_buffer_[*decoded_length]);
1386 }
1387
minyuel6d92bf52015-09-23 15:20:39 +02001388 int return_value;
1389 if (*operation == kCodecInternalCng) {
1390 RTC_DCHECK(packet_list->empty());
1391 return_value = DecodeCng(decoder, decoded_length, speech_type);
1392 } else {
1393 return_value = DecodeLoop(packet_list, *operation, decoder,
1394 decoded_length, speech_type);
1395 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001396
1397 if (*decoded_length < 0) {
1398 // Error returned from the decoder.
1399 *decoded_length = 0;
Peter Kastingb7e50542015-06-11 12:55:50 -07001400 sync_buffer_->IncreaseEndTimestamp(
1401 static_cast<uint32_t>(decoder_frame_length_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001402 int error_code = 0;
1403 if (decoder)
1404 error_code = decoder->ErrorCode();
1405 if (error_code != 0) {
1406 // Got some error code from the decoder.
1407 decoder_error_code_ = error_code;
1408 return_value = kDecoderErrorCode;
Henrik Lundind67a2192015-08-03 12:54:37 +02001409 LOG(LS_WARNING) << "Decoder returned error code: " << error_code;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001410 } else {
1411 // Decoder does not implement error codes. Return generic error.
1412 return_value = kOtherDecoderError;
Henrik Lundind67a2192015-08-03 12:54:37 +02001413 LOG(LS_WARNING) << "Decoder error (no error code)";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001414 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001415 *operation = kExpand; // Do expansion to get data instead.
1416 }
1417 if (*speech_type != AudioDecoder::kComfortNoise) {
1418 // Don't increment timestamp if codec returned CNG speech type
1419 // since in this case, the we will increment the CNGplayedTS counter.
1420 // Increase with number of samples per channel.
1421 assert(*decoded_length == 0 ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001422 (decoder && decoder->Channels() == sync_buffer_->Channels()));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001423 sync_buffer_->IncreaseEndTimestamp(
1424 *decoded_length / static_cast<int>(sync_buffer_->Channels()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001425 }
1426 return return_value;
1427}
1428
minyuel6d92bf52015-09-23 15:20:39 +02001429int NetEqImpl::DecodeCng(AudioDecoder* decoder, int* decoded_length,
1430 AudioDecoder::SpeechType* speech_type) {
1431 if (!decoder) {
1432 // This happens when active decoder is not defined.
1433 *decoded_length = -1;
1434 return 0;
1435 }
1436
1437 while (*decoded_length < rtc::checked_cast<int>(output_size_samples_)) {
1438 const int length = decoder->Decode(
1439 nullptr, 0, fs_hz_,
1440 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1441 &decoded_buffer_[*decoded_length], speech_type);
1442 if (length > 0) {
1443 *decoded_length += length;
minyuel6d92bf52015-09-23 15:20:39 +02001444 } else {
1445 // Error.
1446 LOG(LS_WARNING) << "Failed to decode CNG";
1447 *decoded_length = -1;
1448 break;
1449 }
1450 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1451 // Guard against overflow.
1452 LOG(LS_WARNING) << "Decoded too much CNG.";
1453 return kDecodedTooMuch;
1454 }
1455 }
1456 return 0;
1457}
1458
1459int NetEqImpl::DecodeLoop(PacketList* packet_list, const Operations& operation,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001460 AudioDecoder* decoder, int* decoded_length,
1461 AudioDecoder::SpeechType* speech_type) {
1462 Packet* packet = NULL;
1463 if (!packet_list->empty()) {
1464 packet = packet_list->front();
1465 }
minyuel6d92bf52015-09-23 15:20:39 +02001466
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001467 // Do decoding.
1468 while (packet &&
1469 !decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1470 assert(decoder); // At this point, we must have a decoder object.
1471 // The number of channels in the |sync_buffer_| should be the same as the
1472 // number decoder channels.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001473 assert(sync_buffer_->Channels() == decoder->Channels());
1474 assert(decoded_buffer_length_ >= kMaxFrameSize * decoder->Channels());
minyuel6d92bf52015-09-23 15:20:39 +02001475 assert(operation == kNormal || operation == kAccelerate ||
1476 operation == kFastAccelerate || operation == kMerge ||
1477 operation == kPreemptiveExpand);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001478 packet_list->pop_front();
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001479 size_t payload_length = packet->payload_length;
Peter Kasting36b7cc32015-06-11 19:57:18 -07001480 int decode_length;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +00001481 if (packet->sync_packet) {
1482 // Decode to silence with the same frame size as the last decode.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001483 memset(&decoded_buffer_[*decoded_length], 0,
1484 decoder_frame_length_ * decoder->Channels() *
1485 sizeof(decoded_buffer_[0]));
Peter Kastingdce40cf2015-08-24 14:52:23 -07001486 decode_length = rtc::checked_cast<int>(decoder_frame_length_);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +00001487 } else if (!packet->primary) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001488 // This is a redundant payload; call the special decoder method.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001489 decode_length = decoder->DecodeRedundant(
henrik.lundin@webrtc.org1eda4e32015-02-25 10:02:29 +00001490 packet->payload, packet->payload_length, fs_hz_,
minyue@webrtc.org7f7d7e32015-03-16 12:30:37 +00001491 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001492 &decoded_buffer_[*decoded_length], speech_type);
1493 } else {
henrik.lundin@webrtc.org1eda4e32015-02-25 10:02:29 +00001494 decode_length =
minyue@webrtc.org7f7d7e32015-03-16 12:30:37 +00001495 decoder->Decode(
1496 packet->payload, packet->payload_length, fs_hz_,
1497 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1498 &decoded_buffer_[*decoded_length], speech_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001499 }
1500
1501 delete[] packet->payload;
1502 delete packet;
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001503 packet = NULL;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001504 if (decode_length > 0) {
1505 *decoded_length += decode_length;
1506 // Update |decoder_frame_length_| with number of samples per channel.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001507 decoder_frame_length_ =
Peter Kastingdce40cf2015-08-24 14:52:23 -07001508 static_cast<size_t>(decode_length) / decoder->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001509 } else if (decode_length < 0) {
1510 // Error.
Henrik Lundind67a2192015-08-03 12:54:37 +02001511 LOG(LS_WARNING) << "Decode " << decode_length << " " << payload_length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001512 *decoded_length = -1;
1513 PacketBuffer::DeleteAllPackets(packet_list);
1514 break;
1515 }
1516 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1517 // Guard against overflow.
Henrik Lundind67a2192015-08-03 12:54:37 +02001518 LOG(LS_WARNING) << "Decoded too much.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001519 PacketBuffer::DeleteAllPackets(packet_list);
1520 return kDecodedTooMuch;
1521 }
1522 if (!packet_list->empty()) {
1523 packet = packet_list->front();
1524 } else {
1525 packet = NULL;
1526 }
1527 } // End of decode loop.
1528
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001529 // If the list is not empty at this point, either a decoding error terminated
1530 // the while-loop, or list must hold exactly one CNG packet.
1531 assert(packet_list->empty() || *decoded_length < 0 ||
1532 (packet_list->size() == 1 && packet &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001533 decoder_database_->IsComfortNoise(packet->header.payloadType)));
1534 return 0;
1535}
1536
1537void NetEqImpl::DoNormal(const int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001538 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001539 assert(normal_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001540 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001541 normal_->Process(decoded_buffer, decoded_length, last_mode_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001542 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001543 if (decoded_length != 0) {
1544 last_mode_ = kModeNormal;
1545 }
1546
1547 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1548 if ((speech_type == AudioDecoder::kComfortNoise)
1549 || ((last_mode_ == kModeCodecInternalCng)
1550 && (decoded_length == 0))) {
1551 // TODO(hlundin): Remove second part of || statement above.
1552 last_mode_ = kModeCodecInternalCng;
1553 }
1554
1555 if (!play_dtmf) {
1556 dtmf_tone_generator_->Reset();
1557 }
1558}
1559
1560void NetEqImpl::DoMerge(int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001561 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001562 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001563 assert(merge_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001564 size_t new_length = merge_->Process(decoded_buffer, decoded_length,
1565 mute_factor_array_.get(),
1566 algorithm_buffer_.get());
1567 size_t expand_length_correction = new_length -
1568 decoded_length / algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001569
1570 // Update in-call and post-call statistics.
1571 if (expand_->MuteFactor(0) == 0) {
1572 // Expand generates only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001573 stats_.ExpandedNoiseSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001574 } else {
1575 // Expansion generates more than only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001576 stats_.ExpandedVoiceSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001577 }
1578
1579 last_mode_ = kModeMerge;
1580 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1581 if (speech_type == AudioDecoder::kComfortNoise) {
1582 last_mode_ = kModeCodecInternalCng;
1583 }
1584 expand_->Reset();
1585 if (!play_dtmf) {
1586 dtmf_tone_generator_->Reset();
1587 }
1588}
1589
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001590int NetEqImpl::DoExpand(bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001591 while ((sync_buffer_->FutureLength() - expand_->overlap_length()) <
Peter Kastingdce40cf2015-08-24 14:52:23 -07001592 output_size_samples_) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001593 algorithm_buffer_->Clear();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001594 int return_value = expand_->Process(algorithm_buffer_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001595 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001596
1597 // Update in-call and post-call statistics.
1598 if (expand_->MuteFactor(0) == 0) {
1599 // Expand operation generates only noise.
1600 stats_.ExpandedNoiseSamples(length);
1601 } else {
1602 // Expand operation generates more than only noise.
1603 stats_.ExpandedVoiceSamples(length);
1604 }
1605
1606 last_mode_ = kModeExpand;
1607
1608 if (return_value < 0) {
1609 return return_value;
1610 }
1611
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001612 sync_buffer_->PushBack(*algorithm_buffer_);
1613 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001614 }
1615 if (!play_dtmf) {
1616 dtmf_tone_generator_->Reset();
1617 }
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001618
1619 if (!generated_noise_stopwatch_) {
1620 // Start a new stopwatch since we may be covering for a lost CNG packet.
1621 generated_noise_stopwatch_ = tick_timer_->GetNewStopwatch();
1622 }
1623
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001624 return 0;
1625}
1626
Henrik Lundincf808d22015-05-27 14:33:29 +02001627int NetEqImpl::DoAccelerate(int16_t* decoded_buffer,
1628 size_t decoded_length,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001629 AudioDecoder::SpeechType speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +02001630 bool play_dtmf,
1631 bool fast_accelerate) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001632 const size_t required_samples =
1633 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001634 size_t borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001635 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001636 size_t decoded_length_per_channel = decoded_length / num_channels;
1637 if (decoded_length_per_channel < required_samples) {
1638 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001639 borrowed_samples_per_channel = static_cast<int>(required_samples -
1640 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001641 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1642 decoded_buffer,
1643 sizeof(int16_t) * decoded_length);
1644 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1645 decoded_buffer);
1646 decoded_length = required_samples * num_channels;
1647 }
1648
Peter Kastingdce40cf2015-08-24 14:52:23 -07001649 size_t samples_removed;
Henrik Lundincf808d22015-05-27 14:33:29 +02001650 Accelerate::ReturnCodes return_code =
1651 accelerate_->Process(decoded_buffer, decoded_length, fast_accelerate,
1652 algorithm_buffer_.get(), &samples_removed);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001653 stats_.AcceleratedSamples(samples_removed);
1654 switch (return_code) {
1655 case Accelerate::kSuccess:
1656 last_mode_ = kModeAccelerateSuccess;
1657 break;
1658 case Accelerate::kSuccessLowEnergy:
1659 last_mode_ = kModeAccelerateLowEnergy;
1660 break;
1661 case Accelerate::kNoStretch:
1662 last_mode_ = kModeAccelerateFail;
1663 break;
1664 case Accelerate::kError:
1665 // TODO(hlundin): Map to kModeError instead?
1666 last_mode_ = kModeAccelerateFail;
1667 return kAccelerateError;
1668 }
1669
1670 if (borrowed_samples_per_channel > 0) {
1671 // Copy borrowed samples back to the |sync_buffer_|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001672 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001673 if (length < borrowed_samples_per_channel) {
1674 // This destroys the beginning of the buffer, but will not cause any
1675 // problems.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001676 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001677 sync_buffer_->Size() -
1678 borrowed_samples_per_channel);
1679 sync_buffer_->PushFrontZeros(borrowed_samples_per_channel - length);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001680 algorithm_buffer_->PopFront(length);
1681 assert(algorithm_buffer_->Empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001682 } else {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001683 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001684 borrowed_samples_per_channel,
1685 sync_buffer_->Size() -
1686 borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001687 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001688 }
1689 }
1690
1691 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1692 if (speech_type == AudioDecoder::kComfortNoise) {
1693 last_mode_ = kModeCodecInternalCng;
1694 }
1695 if (!play_dtmf) {
1696 dtmf_tone_generator_->Reset();
1697 }
1698 expand_->Reset();
1699 return 0;
1700}
1701
1702int NetEqImpl::DoPreemptiveExpand(int16_t* decoded_buffer,
1703 size_t decoded_length,
1704 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001705 bool play_dtmf) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001706 const size_t required_samples =
1707 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001708 size_t num_channels = algorithm_buffer_->Channels();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001709 size_t borrowed_samples_per_channel = 0;
1710 size_t old_borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001711 size_t decoded_length_per_channel = decoded_length / num_channels;
1712 if (decoded_length_per_channel < required_samples) {
1713 // Must move data from the |sync_buffer_| in order to get 30 ms.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001714 borrowed_samples_per_channel =
1715 required_samples - decoded_length_per_channel;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001716 // Calculate how many of these were already played out.
Peter Kastingf045e4d2015-06-10 21:15:38 -07001717 old_borrowed_samples_per_channel =
Peter Kastingdce40cf2015-08-24 14:52:23 -07001718 (borrowed_samples_per_channel > sync_buffer_->FutureLength()) ?
1719 (borrowed_samples_per_channel - sync_buffer_->FutureLength()) : 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001720 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1721 decoded_buffer,
1722 sizeof(int16_t) * decoded_length);
1723 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1724 decoded_buffer);
1725 decoded_length = required_samples * num_channels;
1726 }
1727
Peter Kastingdce40cf2015-08-24 14:52:23 -07001728 size_t samples_added;
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001729 PreemptiveExpand::ReturnCodes return_code = preemptive_expand_->Process(
Peter Kastingdce40cf2015-08-24 14:52:23 -07001730 decoded_buffer, decoded_length,
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001731 old_borrowed_samples_per_channel,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001732 algorithm_buffer_.get(), &samples_added);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001733 stats_.PreemptiveExpandedSamples(samples_added);
1734 switch (return_code) {
1735 case PreemptiveExpand::kSuccess:
1736 last_mode_ = kModePreemptiveExpandSuccess;
1737 break;
1738 case PreemptiveExpand::kSuccessLowEnergy:
1739 last_mode_ = kModePreemptiveExpandLowEnergy;
1740 break;
1741 case PreemptiveExpand::kNoStretch:
1742 last_mode_ = kModePreemptiveExpandFail;
1743 break;
1744 case PreemptiveExpand::kError:
1745 // TODO(hlundin): Map to kModeError instead?
1746 last_mode_ = kModePreemptiveExpandFail;
1747 return kPreemptiveExpandError;
1748 }
1749
1750 if (borrowed_samples_per_channel > 0) {
1751 // Copy borrowed samples back to the |sync_buffer_|.
1752 sync_buffer_->ReplaceAtIndex(
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001753 *algorithm_buffer_, borrowed_samples_per_channel,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001754 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001755 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001756 }
1757
1758 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1759 if (speech_type == AudioDecoder::kComfortNoise) {
1760 last_mode_ = kModeCodecInternalCng;
1761 }
1762 if (!play_dtmf) {
1763 dtmf_tone_generator_->Reset();
1764 }
1765 expand_->Reset();
1766 return 0;
1767}
1768
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001769int NetEqImpl::DoRfc3389Cng(PacketList* packet_list, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001770 if (!packet_list->empty()) {
1771 // Must have exactly one SID frame at this point.
1772 assert(packet_list->size() == 1);
1773 Packet* packet = packet_list->front();
1774 packet_list->pop_front();
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001775 if (!decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1776#ifdef LEGACY_BITEXACT
1777 // This can happen due to a bug in GetDecision. Change the payload type
1778 // to a CNG type, and move on. Note that this means that we are in fact
1779 // sending a non-CNG payload to the comfort noise decoder for decoding.
1780 // Clearly wrong, but will maintain bit-exactness with legacy.
1781 if (fs_hz_ == 8000) {
1782 packet->header.payloadType =
kwibergee1879c2015-10-29 06:20:28 -07001783 decoder_database_->GetRtpPayloadType(NetEqDecoder::kDecoderCNGnb);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001784 } else if (fs_hz_ == 16000) {
1785 packet->header.payloadType =
kwibergee1879c2015-10-29 06:20:28 -07001786 decoder_database_->GetRtpPayloadType(NetEqDecoder::kDecoderCNGwb);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001787 } else if (fs_hz_ == 32000) {
kwibergee1879c2015-10-29 06:20:28 -07001788 packet->header.payloadType = decoder_database_->GetRtpPayloadType(
1789 NetEqDecoder::kDecoderCNGswb32kHz);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001790 } else if (fs_hz_ == 48000) {
kwibergee1879c2015-10-29 06:20:28 -07001791 packet->header.payloadType = decoder_database_->GetRtpPayloadType(
1792 NetEqDecoder::kDecoderCNGswb48kHz);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001793 }
1794 assert(decoder_database_->IsComfortNoise(packet->header.payloadType));
1795#else
1796 LOG(LS_ERROR) << "Trying to decode non-CNG payload as CNG.";
1797 return kOtherError;
1798#endif
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001799 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001800 // UpdateParameters() deletes |packet|.
1801 if (comfort_noise_->UpdateParameters(packet) ==
1802 ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001803 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001804 return -comfort_noise_->internal_error_code();
1805 }
1806 }
1807 int cn_return = comfort_noise_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001808 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001809 expand_->Reset();
1810 last_mode_ = kModeRfc3389Cng;
1811 if (!play_dtmf) {
1812 dtmf_tone_generator_->Reset();
1813 }
1814 if (cn_return == ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001815 decoder_error_code_ = comfort_noise_->internal_error_code();
1816 return kComfortNoiseErrorCode;
1817 } else if (cn_return == ComfortNoise::kUnknownPayloadType) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001818 return kUnknownRtpPayloadType;
1819 }
1820 return 0;
1821}
1822
minyuel6d92bf52015-09-23 15:20:39 +02001823void NetEqImpl::DoCodecInternalCng(const int16_t* decoded_buffer,
1824 size_t decoded_length) {
1825 RTC_DCHECK(normal_.get());
1826 RTC_DCHECK(mute_factor_array_.get());
1827 normal_->Process(decoded_buffer, decoded_length, last_mode_,
1828 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001829 last_mode_ = kModeCodecInternalCng;
1830 expand_->Reset();
1831}
1832
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001833int NetEqImpl::DoDtmf(const DtmfEvent& dtmf_event, bool* play_dtmf) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001834 // This block of the code and the block further down, handling |dtmf_switch|
1835 // are commented out. Otherwise playing out-of-band DTMF would fail in VoE
1836 // test, DtmfTest.ManualSuccessfullySendsOutOfBandTelephoneEvents. This is
1837 // equivalent to |dtmf_switch| always be false.
1838 //
1839 // See http://webrtc-codereview.appspot.com/1195004/ for discussion
1840 // On this issue. This change might cause some glitches at the point of
1841 // switch from audio to DTMF. Issue 1545 is filed to track this.
1842 //
1843 // bool dtmf_switch = false;
1844 // if ((last_mode_ != kModeDtmf) && dtmf_tone_generator_->initialized()) {
1845 // // Special case; see below.
1846 // // We must catch this before calling Generate, since |initialized| is
1847 // // modified in that call.
1848 // dtmf_switch = true;
1849 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001850
1851 int dtmf_return_value = 0;
1852 if (!dtmf_tone_generator_->initialized()) {
1853 // Initialize if not already done.
1854 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1855 dtmf_event.volume);
1856 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001857
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001858 if (dtmf_return_value == 0) {
1859 // Generate DTMF signal.
1860 dtmf_return_value = dtmf_tone_generator_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001861 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001862 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001863
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001864 if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001865 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001866 return dtmf_return_value;
1867 }
1868
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001869 // if (dtmf_switch) {
1870 // // This is the special case where the previous operation was DTMF
1871 // // overdub, but the current instruction is "regular" DTMF. We must make
1872 // // sure that the DTMF does not have any discontinuities. The first DTMF
1873 // // sample that we generate now must be played out immediately, therefore
1874 // // it must be copied to the speech buffer.
1875 // // TODO(hlundin): This code seems incorrect. (Legacy.) Write test and
1876 // // verify correct operation.
1877 // assert(false);
1878 // // Must generate enough data to replace all of the |sync_buffer_|
1879 // // "future".
1880 // int required_length = sync_buffer_->FutureLength();
1881 // assert(dtmf_tone_generator_->initialized());
1882 // dtmf_return_value = dtmf_tone_generator_->Generate(required_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001883 // algorithm_buffer_);
1884 // assert((size_t) required_length == algorithm_buffer_->Size());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001885 // if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001886 // algorithm_buffer_->Zeros(output_size_samples_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001887 // return dtmf_return_value;
1888 // }
1889 //
1890 // // Overwrite the "future" part of the speech buffer with the new DTMF
1891 // // data.
1892 // // TODO(hlundin): It seems that this overwriting has gone lost.
1893 // // Not adapted for multi-channel yet.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001894 // assert(algorithm_buffer_->Channels() == 1);
1895 // if (algorithm_buffer_->Channels() != 1) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001896 // LOG(LS_WARNING) << "DTMF not supported for more than one channel";
1897 // return kStereoNotSupported;
1898 // }
1899 // // Shuffle the remaining data to the beginning of algorithm buffer.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001900 // algorithm_buffer_->PopFront(sync_buffer_->FutureLength());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001901 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001902
Peter Kastingb7e50542015-06-11 12:55:50 -07001903 sync_buffer_->IncreaseEndTimestamp(
1904 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001905 expand_->Reset();
1906 last_mode_ = kModeDtmf;
1907
1908 // Set to false because the DTMF is already in the algorithm buffer.
1909 *play_dtmf = false;
1910 return 0;
1911}
1912
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001913void NetEqImpl::DoAlternativePlc(bool increase_timestamp) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001914 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001915 size_t length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001916 if (decoder && decoder->HasDecodePlc()) {
1917 // Use the decoder's packet-loss concealment.
1918 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1919 int16_t decoded_buffer[kMaxFrameSize];
1920 length = decoder->DecodePlc(1, decoded_buffer);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001921 if (length > 0)
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001922 algorithm_buffer_->PushBackInterleaved(decoded_buffer, length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001923 } else {
1924 // Do simple zero-stuffing.
1925 length = output_size_samples_;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001926 algorithm_buffer_->Zeros(length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001927 // By not advancing the timestamp, NetEq inserts samples.
1928 stats_.AddZeros(length);
1929 }
1930 if (increase_timestamp) {
Peter Kastingb7e50542015-06-11 12:55:50 -07001931 sync_buffer_->IncreaseEndTimestamp(static_cast<uint32_t>(length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001932 }
1933 expand_->Reset();
1934}
1935
1936int NetEqImpl::DtmfOverdub(const DtmfEvent& dtmf_event, size_t num_channels,
1937 int16_t* output) const {
1938 size_t out_index = 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001939 size_t overdub_length = output_size_samples_; // Default value.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001940
1941 if (sync_buffer_->dtmf_index() > sync_buffer_->next_index()) {
1942 // Special operation for transition from "DTMF only" to "DTMF overdub".
1943 out_index = std::min(
1944 sync_buffer_->dtmf_index() - sync_buffer_->next_index(),
Peter Kastingdce40cf2015-08-24 14:52:23 -07001945 output_size_samples_);
1946 overdub_length = output_size_samples_ - out_index;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001947 }
1948
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001949 AudioMultiVector dtmf_output(num_channels);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001950 int dtmf_return_value = 0;
1951 if (!dtmf_tone_generator_->initialized()) {
1952 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1953 dtmf_event.volume);
1954 }
1955 if (dtmf_return_value == 0) {
1956 dtmf_return_value = dtmf_tone_generator_->Generate(overdub_length,
1957 &dtmf_output);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001958 assert(overdub_length == dtmf_output.Size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001959 }
1960 dtmf_output.ReadInterleaved(overdub_length, &output[out_index]);
1961 return dtmf_return_value < 0 ? dtmf_return_value : 0;
1962}
1963
Peter Kastingdce40cf2015-08-24 14:52:23 -07001964int NetEqImpl::ExtractPackets(size_t required_samples,
1965 PacketList* packet_list) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001966 bool first_packet = true;
1967 uint8_t prev_payload_type = 0;
1968 uint32_t prev_timestamp = 0;
1969 uint16_t prev_sequence_number = 0;
1970 bool next_packet_available = false;
1971
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001972 const RTPHeader* header = packet_buffer_->NextRtpHeader();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001973 assert(header);
1974 if (!header) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001975 LOG(LS_ERROR) << "Packet buffer unexpectedly empty.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001976 return -1;
1977 }
turaj@webrtc.org7df97062013-08-02 18:07:13 +00001978 uint32_t first_timestamp = header->timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001979 int extracted_samples = 0;
1980
1981 // Packet extraction loop.
1982 do {
1983 timestamp_ = header->timestamp;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001984 size_t discard_count = 0;
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001985 Packet* packet = packet_buffer_->GetNextPacket(&discard_count);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001986 // |header| may be invalid after the |packet_buffer_| operation.
1987 header = NULL;
1988 if (!packet) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001989 LOG(LS_ERROR) << "Should always be able to extract a packet here";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001990 assert(false); // Should always be able to extract a packet here.
1991 return -1;
1992 }
1993 stats_.PacketsDiscarded(discard_count);
henrik.lundin84f8cd62016-04-26 07:45:16 -07001994 stats_.StoreWaitingTime(packet->waiting_time->ElapsedMs());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001995 assert(packet->payload_length > 0);
1996 packet_list->push_back(packet); // Store packet in list.
1997
1998 if (first_packet) {
1999 first_packet = false;
henrik.lundin48ed9302015-10-29 05:36:24 -07002000 if (nack_enabled_) {
2001 RTC_DCHECK(nack_);
2002 // TODO(henrik.lundin): Should we update this for all decoded packets?
2003 nack_->UpdateLastDecodedPacket(packet->header.sequenceNumber,
2004 packet->header.timestamp);
2005 }
2006 prev_sequence_number = packet->header.sequenceNumber;
2007 prev_timestamp = packet->header.timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002008 prev_payload_type = packet->header.payloadType;
2009 }
2010
2011 // Store number of extracted samples.
2012 int packet_duration = 0;
2013 AudioDecoder* decoder = decoder_database_->GetDecoder(
2014 packet->header.payloadType);
2015 if (decoder) {
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00002016 if (packet->sync_packet) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07002017 packet_duration = rtc::checked_cast<int>(decoder_frame_length_);
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00002018 } else {
minyue@webrtc.org2c1bcf22015-02-17 10:17:09 +00002019 if (packet->primary) {
2020 packet_duration = decoder->PacketDuration(packet->payload,
2021 packet->payload_length);
2022 } else {
2023 packet_duration = decoder->
2024 PacketDurationRedundant(packet->payload, packet->payload_length);
2025 stats_.SecondaryDecodedSamples(packet_duration);
2026 }
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00002027 }
ossu97ba30e2016-04-25 07:55:58 -07002028 } else if (!decoder_database_->IsComfortNoise(packet->header.payloadType)) {
Henrik Lundind67a2192015-08-03 12:54:37 +02002029 LOG(LS_WARNING) << "Unknown payload type "
2030 << static_cast<int>(packet->header.payloadType);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002031 assert(false);
2032 }
2033 if (packet_duration <= 0) {
2034 // Decoder did not return a packet duration. Assume that the packet
2035 // contains the same number of samples as the previous one.
Peter Kastingdce40cf2015-08-24 14:52:23 -07002036 packet_duration = rtc::checked_cast<int>(decoder_frame_length_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002037 }
2038 extracted_samples = packet->header.timestamp - first_timestamp +
2039 packet_duration;
2040
2041 // Check what packet is available next.
2042 header = packet_buffer_->NextRtpHeader();
2043 next_packet_available = false;
2044 if (header && prev_payload_type == header->payloadType) {
2045 int16_t seq_no_diff = header->sequenceNumber - prev_sequence_number;
Peter Kastingdce40cf2015-08-24 14:52:23 -07002046 size_t ts_diff = header->timestamp - prev_timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002047 if (seq_no_diff == 1 ||
2048 (seq_no_diff == 0 && ts_diff == decoder_frame_length_)) {
2049 // The next sequence number is available, or the next part of a packet
2050 // that was split into pieces upon insertion.
2051 next_packet_available = true;
2052 }
2053 prev_sequence_number = header->sequenceNumber;
2054 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07002055 } while (extracted_samples < rtc::checked_cast<int>(required_samples) &&
2056 next_packet_available);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002057
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00002058 if (extracted_samples > 0) {
2059 // Delete old packets only when we are going to decode something. Otherwise,
2060 // we could end up in the situation where we never decode anything, since
2061 // all incoming packets are considered too old but the buffer will also
2062 // never be flooded and flushed.
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00002063 packet_buffer_->DiscardAllOldPackets(timestamp_);
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00002064 }
2065
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002066 return extracted_samples;
2067}
2068
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002069void NetEqImpl::UpdatePlcComponents(int fs_hz, size_t channels) {
2070 // Delete objects and create new ones.
2071 expand_.reset(expand_factory_->Create(background_noise_.get(),
2072 sync_buffer_.get(), &random_vector_,
Henrik Lundinbef77e22015-08-18 14:58:09 +02002073 &stats_, fs_hz, channels));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002074 merge_.reset(new Merge(fs_hz, channels, expand_.get(), sync_buffer_.get()));
2075}
2076
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002077void NetEqImpl::SetSampleRateAndChannels(int fs_hz, size_t channels) {
Henrik Lundind67a2192015-08-03 12:54:37 +02002078 LOG(LS_VERBOSE) << "SetSampleRateAndChannels " << fs_hz << " " << channels;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002079 // TODO(hlundin): Change to an enumerator and skip assert.
2080 assert(fs_hz == 8000 || fs_hz == 16000 || fs_hz == 32000 || fs_hz == 48000);
2081 assert(channels > 0);
2082
2083 fs_hz_ = fs_hz;
2084 fs_mult_ = fs_hz / 8000;
Peter Kastingdce40cf2015-08-24 14:52:23 -07002085 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002086 decoder_frame_length_ = 3 * output_size_samples_; // Initialize to 30ms.
2087
2088 last_mode_ = kModeNormal;
2089
2090 // Create a new array of mute factors and set all to 1.
2091 mute_factor_array_.reset(new int16_t[channels]);
2092 for (size_t i = 0; i < channels; ++i) {
2093 mute_factor_array_[i] = 16384; // 1.0 in Q14.
2094 }
2095
ossu97ba30e2016-04-25 07:55:58 -07002096 ComfortNoiseDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02002097 if (cng_decoder)
2098 cng_decoder->Reset();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002099
2100 // Reinit post-decode VAD with new sample rate.
2101 assert(vad_.get()); // Cannot be NULL here.
2102 vad_->Init();
2103
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002104 // Delete algorithm buffer and create a new one.
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00002105 algorithm_buffer_.reset(new AudioMultiVector(channels));
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002106
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002107 // Delete sync buffer and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002108 sync_buffer_.reset(new SyncBuffer(channels, kSyncBufferSize * fs_mult_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002109
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00002110 // Delete BackgroundNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002111 background_noise_.reset(new BackgroundNoise(channels));
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00002112 background_noise_->set_mode(background_noise_mode_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002113
2114 // Reset random vector.
2115 random_vector_.Reset();
2116
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002117 UpdatePlcComponents(fs_hz, channels);
2118
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002119 // Move index so that we create a small set of future samples (all 0).
2120 sync_buffer_->set_next_index(sync_buffer_->next_index() -
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002121 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002122
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002123 normal_.reset(new Normal(fs_hz, decoder_database_.get(), *background_noise_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002124 expand_.get()));
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +00002125 accelerate_.reset(
2126 accelerate_factory_->Create(fs_hz, channels, *background_noise_));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002127 preemptive_expand_.reset(preemptive_expand_factory_->Create(
Peter Kastingdce40cf2015-08-24 14:52:23 -07002128 fs_hz, channels, *background_noise_, expand_->overlap_length()));
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002129
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002130 // Delete ComfortNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002131 comfort_noise_.reset(new ComfortNoise(fs_hz, decoder_database_.get(),
2132 sync_buffer_.get()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002133
2134 // Verify that |decoded_buffer_| is long enough.
2135 if (decoded_buffer_length_ < kMaxFrameSize * channels) {
2136 // Reallocate to larger size.
2137 decoded_buffer_length_ = kMaxFrameSize * channels;
2138 decoded_buffer_.reset(new int16_t[decoded_buffer_length_]);
2139 }
2140
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002141 // Create DecisionLogic if it is not created yet, then communicate new sample
2142 // rate and output size to DecisionLogic object.
2143 if (!decision_logic_.get()) {
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002144 CreateDecisionLogic();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002145 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002146 decision_logic_->SetSampleRate(fs_hz_, output_size_samples_);
2147}
2148
henrik.lundin55480f52016-03-08 02:37:57 -08002149NetEqImpl::OutputType NetEqImpl::LastOutputType() {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002150 assert(vad_.get());
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002151 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002152 if (last_mode_ == kModeCodecInternalCng || last_mode_ == kModeRfc3389Cng) {
henrik.lundin55480f52016-03-08 02:37:57 -08002153 return OutputType::kCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002154 } else if (last_mode_ == kModeExpand && expand_->MuteFactor(0) == 0) {
2155 // Expand mode has faded down to background noise only (very long expand).
henrik.lundin55480f52016-03-08 02:37:57 -08002156 return OutputType::kPLCCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002157 } else if (last_mode_ == kModeExpand) {
henrik.lundin55480f52016-03-08 02:37:57 -08002158 return OutputType::kPLC;
wu@webrtc.org24301a62013-12-13 19:17:43 +00002159 } else if (vad_->running() && !vad_->active_speech()) {
henrik.lundin55480f52016-03-08 02:37:57 -08002160 return OutputType::kVadPassive;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002161 } else {
henrik.lundin55480f52016-03-08 02:37:57 -08002162 return OutputType::kNormalSpeech;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002163 }
2164}
2165
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002166void NetEqImpl::CreateDecisionLogic() {
Henrik Lundin47b17dc2016-05-10 10:20:59 +02002167 decision_logic_.reset(DecisionLogic::Create(
2168 fs_hz_, output_size_samples_, playout_mode_, decoder_database_.get(),
2169 *packet_buffer_.get(), delay_manager_.get(), buffer_level_filter_.get(),
2170 tick_timer_.get()));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002171}
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002172} // namespace webrtc