blob: b911d5a27f53c3dea42c73a115692684662a3906 [file] [log] [blame]
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001/*
2 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000011#include "webrtc/modules/audio_coding/neteq/neteq_impl.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000012
13#include <assert.h>
14#include <memory.h> // memset
15
16#include <algorithm>
ossu97ba30e2016-04-25 07:55:58 -070017#include <vector>
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000018
henrik.lundin9c3efd02015-08-27 13:12:22 -070019#include "webrtc/base/checks.h"
Henrik Lundind67a2192015-08-03 12:54:37 +020020#include "webrtc/base/logging.h"
Tommid44c0772016-03-11 17:12:32 -080021#include "webrtc/base/safe_conversions.h"
henrik.lundina689b442015-12-17 03:50:05 -080022#include "webrtc/base/trace_event.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000023#include "webrtc/common_audio/signal_processing/include/signal_processing_library.h"
kwiberg@webrtc.orge04a93b2014-12-09 10:12:53 +000024#include "webrtc/modules/audio_coding/codecs/audio_decoder.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000025#include "webrtc/modules/audio_coding/neteq/accelerate.h"
26#include "webrtc/modules/audio_coding/neteq/background_noise.h"
27#include "webrtc/modules/audio_coding/neteq/buffer_level_filter.h"
28#include "webrtc/modules/audio_coding/neteq/comfort_noise.h"
29#include "webrtc/modules/audio_coding/neteq/decision_logic.h"
30#include "webrtc/modules/audio_coding/neteq/decoder_database.h"
31#include "webrtc/modules/audio_coding/neteq/defines.h"
32#include "webrtc/modules/audio_coding/neteq/delay_manager.h"
33#include "webrtc/modules/audio_coding/neteq/delay_peak_detector.h"
34#include "webrtc/modules/audio_coding/neteq/dtmf_buffer.h"
35#include "webrtc/modules/audio_coding/neteq/dtmf_tone_generator.h"
36#include "webrtc/modules/audio_coding/neteq/expand.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000037#include "webrtc/modules/audio_coding/neteq/merge.h"
henrik.lundin91951862016-06-08 06:43:41 -070038#include "webrtc/modules/audio_coding/neteq/nack_tracker.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000039#include "webrtc/modules/audio_coding/neteq/normal.h"
40#include "webrtc/modules/audio_coding/neteq/packet_buffer.h"
41#include "webrtc/modules/audio_coding/neteq/packet.h"
42#include "webrtc/modules/audio_coding/neteq/payload_splitter.h"
43#include "webrtc/modules/audio_coding/neteq/post_decode_vad.h"
44#include "webrtc/modules/audio_coding/neteq/preemptive_expand.h"
45#include "webrtc/modules/audio_coding/neteq/sync_buffer.h"
henrik.lundined497212016-04-25 10:11:38 -070046#include "webrtc/modules/audio_coding/neteq/tick_timer.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000047#include "webrtc/modules/audio_coding/neteq/timestamp_scaler.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010048#include "webrtc/modules/include/module_common_types.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000049
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000050namespace webrtc {
51
ossue3525782016-05-25 07:37:43 -070052NetEqImpl::Dependencies::Dependencies(
53 const NetEq::Config& config,
54 const rtc::scoped_refptr<AudioDecoderFactory>& decoder_factory)
henrik.lundin1d9061e2016-04-26 12:19:34 -070055 : tick_timer(new TickTimer),
56 buffer_level_filter(new BufferLevelFilter),
ossue3525782016-05-25 07:37:43 -070057 decoder_database(new DecoderDatabase(decoder_factory)),
henrik.lundinf3933702016-04-28 01:53:52 -070058 delay_peak_detector(new DelayPeakDetector(tick_timer.get())),
henrik.lundin1d9061e2016-04-26 12:19:34 -070059 delay_manager(new DelayManager(config.max_packets_in_buffer,
henrik.lundin8f8c96d2016-04-28 23:19:20 -070060 delay_peak_detector.get(),
61 tick_timer.get())),
henrik.lundin1d9061e2016-04-26 12:19:34 -070062 dtmf_buffer(new DtmfBuffer(config.sample_rate_hz)),
63 dtmf_tone_generator(new DtmfToneGenerator),
64 packet_buffer(
65 new PacketBuffer(config.max_packets_in_buffer, tick_timer.get())),
66 payload_splitter(new PayloadSplitter),
67 timestamp_scaler(new TimestampScaler(*decoder_database)),
68 accelerate_factory(new AccelerateFactory),
69 expand_factory(new ExpandFactory),
70 preemptive_expand_factory(new PreemptiveExpandFactory) {}
71
72NetEqImpl::Dependencies::~Dependencies() = default;
73
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +000074NetEqImpl::NetEqImpl(const NetEq::Config& config,
henrik.lundin1d9061e2016-04-26 12:19:34 -070075 Dependencies&& deps,
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +000076 bool create_components)
henrik.lundin1d9061e2016-04-26 12:19:34 -070077 : tick_timer_(std::move(deps.tick_timer)),
78 buffer_level_filter_(std::move(deps.buffer_level_filter)),
79 decoder_database_(std::move(deps.decoder_database)),
80 delay_manager_(std::move(deps.delay_manager)),
81 delay_peak_detector_(std::move(deps.delay_peak_detector)),
82 dtmf_buffer_(std::move(deps.dtmf_buffer)),
83 dtmf_tone_generator_(std::move(deps.dtmf_tone_generator)),
84 packet_buffer_(std::move(deps.packet_buffer)),
85 payload_splitter_(std::move(deps.payload_splitter)),
86 timestamp_scaler_(std::move(deps.timestamp_scaler)),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000087 vad_(new PostDecodeVad()),
henrik.lundin1d9061e2016-04-26 12:19:34 -070088 expand_factory_(std::move(deps.expand_factory)),
89 accelerate_factory_(std::move(deps.accelerate_factory)),
90 preemptive_expand_factory_(std::move(deps.preemptive_expand_factory)),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000091 last_mode_(kModeNormal),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000092 decoded_buffer_length_(kMaxFrameSize),
93 decoded_buffer_(new int16_t[decoded_buffer_length_]),
94 playout_timestamp_(0),
95 new_codec_(false),
96 timestamp_(0),
97 reset_decoder_(false),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000098 ssrc_(0),
99 first_packet_(true),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000100 error_code_(0),
101 decoder_error_code_(0),
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +0000102 background_noise_mode_(config.background_noise_mode),
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000103 playout_mode_(config.playout_mode),
Henrik Lundincf808d22015-05-27 14:33:29 +0200104 enable_fast_accelerate_(config.enable_fast_accelerate),
henrik.lundin7a926812016-05-12 13:51:28 -0700105 nack_enabled_(false),
106 enable_muted_state_(config.enable_muted_state) {
Henrik Lundin905495c2015-05-25 16:58:41 +0200107 LOG(LS_INFO) << "NetEq config: " << config.ToString();
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +0000108 int fs = config.sample_rate_hz;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000109 if (fs != 8000 && fs != 16000 && fs != 32000 && fs != 48000) {
110 LOG(LS_ERROR) << "Sample rate " << fs << " Hz not supported. " <<
111 "Changing to 8000 Hz.";
112 fs = 8000;
113 }
henrik.lundin1d9061e2016-04-26 12:19:34 -0700114 delay_manager_->SetMaximumDelay(config.max_delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000115 fs_hz_ = fs;
116 fs_mult_ = fs / 8000;
henrik.lundind89814b2015-11-23 06:49:25 -0800117 last_output_sample_rate_hz_ = fs;
Peter Kastingdce40cf2015-08-24 14:52:23 -0700118 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000119 decoder_frame_length_ = 3 * output_size_samples_;
120 WebRtcSpl_Init();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000121 if (create_components) {
122 SetSampleRateAndChannels(fs, 1); // Default is 1 channel.
123 }
henrik.lundin9bc26672015-11-02 03:25:57 -0800124 RTC_DCHECK(!vad_->enabled());
125 if (config.enable_post_decode_vad) {
126 vad_->Enable();
127 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000128}
129
Henrik Lundind67a2192015-08-03 12:54:37 +0200130NetEqImpl::~NetEqImpl() = default;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000131
132int NetEqImpl::InsertPacket(const WebRtcRTPHeader& rtp_header,
kwibergee2bac22015-11-11 10:34:00 -0800133 rtc::ArrayView<const uint8_t> payload,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000134 uint32_t receive_timestamp) {
henrik.lundina689b442015-12-17 03:50:05 -0800135 TRACE_EVENT0("webrtc", "NetEqImpl::InsertPacket");
Tommi9090e0b2016-01-20 13:39:36 +0100136 rtc::CritScope lock(&crit_sect_);
kwibergee2bac22015-11-11 10:34:00 -0800137 int error =
138 InsertPacketInternal(rtp_header, payload, receive_timestamp, false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000139 if (error != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000140 error_code_ = error;
141 return kFail;
142 }
143 return kOK;
144}
145
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000146int NetEqImpl::InsertSyncPacket(const WebRtcRTPHeader& rtp_header,
147 uint32_t receive_timestamp) {
Tommi9090e0b2016-01-20 13:39:36 +0100148 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000149 const uint8_t kSyncPayload[] = { 's', 'y', 'n', 'c' };
kwibergee2bac22015-11-11 10:34:00 -0800150 int error =
151 InsertPacketInternal(rtp_header, kSyncPayload, receive_timestamp, true);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000152
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000153 if (error != 0) {
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000154 error_code_ = error;
155 return kFail;
156 }
157 return kOK;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000158}
159
henrik.lundin500c04b2016-03-08 02:36:04 -0800160namespace {
161void SetAudioFrameActivityAndType(bool vad_enabled,
henrik.lundin55480f52016-03-08 02:37:57 -0800162 NetEqImpl::OutputType type,
henrik.lundin500c04b2016-03-08 02:36:04 -0800163 AudioFrame::VADActivity last_vad_activity,
164 AudioFrame* audio_frame) {
165 switch (type) {
henrik.lundin55480f52016-03-08 02:37:57 -0800166 case NetEqImpl::OutputType::kNormalSpeech: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800167 audio_frame->speech_type_ = AudioFrame::kNormalSpeech;
168 audio_frame->vad_activity_ = AudioFrame::kVadActive;
169 break;
170 }
henrik.lundin55480f52016-03-08 02:37:57 -0800171 case NetEqImpl::OutputType::kVadPassive: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800172 // This should only be reached if the VAD is enabled.
173 RTC_DCHECK(vad_enabled);
174 audio_frame->speech_type_ = AudioFrame::kNormalSpeech;
175 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
176 break;
177 }
henrik.lundin55480f52016-03-08 02:37:57 -0800178 case NetEqImpl::OutputType::kCNG: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800179 audio_frame->speech_type_ = AudioFrame::kCNG;
180 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
181 break;
182 }
henrik.lundin55480f52016-03-08 02:37:57 -0800183 case NetEqImpl::OutputType::kPLC: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800184 audio_frame->speech_type_ = AudioFrame::kPLC;
185 audio_frame->vad_activity_ = last_vad_activity;
186 break;
187 }
henrik.lundin55480f52016-03-08 02:37:57 -0800188 case NetEqImpl::OutputType::kPLCCNG: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800189 audio_frame->speech_type_ = AudioFrame::kPLCCNG;
190 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
191 break;
192 }
193 default:
194 RTC_NOTREACHED();
195 }
196 if (!vad_enabled) {
197 // Always set kVadUnknown when receive VAD is inactive.
198 audio_frame->vad_activity_ = AudioFrame::kVadUnknown;
199 }
200}
henrik.lundinbc89de32016-03-08 05:20:14 -0800201} // namespace
henrik.lundin500c04b2016-03-08 02:36:04 -0800202
henrik.lundin7a926812016-05-12 13:51:28 -0700203int NetEqImpl::GetAudio(AudioFrame* audio_frame, bool* muted) {
henrik.lundine1ca1672016-01-08 03:50:08 -0800204 TRACE_EVENT0("webrtc", "NetEqImpl::GetAudio");
Tommi9090e0b2016-01-20 13:39:36 +0100205 rtc::CritScope lock(&crit_sect_);
henrik.lundin7a926812016-05-12 13:51:28 -0700206 int error = GetAudioInternal(audio_frame, muted);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000207 if (error != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000208 error_code_ = error;
209 return kFail;
210 }
henrik.lundin5fac3f02016-08-24 11:18:49 -0700211 RTC_DCHECK_EQ(
212 audio_frame->sample_rate_hz_,
213 rtc::checked_cast<int>(audio_frame->samples_per_channel_ * 100));
henrik.lundin500c04b2016-03-08 02:36:04 -0800214 SetAudioFrameActivityAndType(vad_->enabled(), LastOutputType(),
215 last_vad_activity_, audio_frame);
216 last_vad_activity_ = audio_frame->vad_activity_;
henrik.lundin6d8e0112016-03-04 10:34:21 -0800217 last_output_sample_rate_hz_ = audio_frame->sample_rate_hz_;
henrik.lundind89814b2015-11-23 06:49:25 -0800218 RTC_DCHECK(last_output_sample_rate_hz_ == 8000 ||
219 last_output_sample_rate_hz_ == 16000 ||
220 last_output_sample_rate_hz_ == 32000 ||
221 last_output_sample_rate_hz_ == 48000)
222 << "Unexpected sample rate " << last_output_sample_rate_hz_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000223 return kOK;
224}
225
kwibergee1879c2015-10-29 06:20:28 -0700226int NetEqImpl::RegisterPayloadType(NetEqDecoder codec,
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800227 const std::string& name,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000228 uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100229 rtc::CritScope lock(&crit_sect_);
Henrik Lundind67a2192015-08-03 12:54:37 +0200230 LOG(LS_VERBOSE) << "RegisterPayloadType "
kwibergee1879c2015-10-29 06:20:28 -0700231 << static_cast<int>(rtp_payload_type) << " "
232 << static_cast<int>(codec);
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800233 int ret = decoder_database_->RegisterPayload(rtp_payload_type, codec, name);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000234 if (ret != DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000235 switch (ret) {
236 case DecoderDatabase::kInvalidRtpPayloadType:
237 error_code_ = kInvalidRtpPayloadType;
238 break;
239 case DecoderDatabase::kCodecNotSupported:
240 error_code_ = kCodecNotSupported;
241 break;
242 case DecoderDatabase::kDecoderExists:
243 error_code_ = kDecoderExists;
244 break;
245 default:
246 error_code_ = kOtherError;
247 }
248 return kFail;
249 }
250 return kOK;
251}
252
253int NetEqImpl::RegisterExternalDecoder(AudioDecoder* decoder,
kwibergee1879c2015-10-29 06:20:28 -0700254 NetEqDecoder codec,
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800255 const std::string& codec_name,
kwiberg342f7402016-06-16 03:18:00 -0700256 uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100257 rtc::CritScope lock(&crit_sect_);
Henrik Lundind67a2192015-08-03 12:54:37 +0200258 LOG(LS_VERBOSE) << "RegisterExternalDecoder "
kwibergee1879c2015-10-29 06:20:28 -0700259 << static_cast<int>(rtp_payload_type) << " "
260 << static_cast<int>(codec);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000261 if (!decoder) {
262 LOG(LS_ERROR) << "Cannot register external decoder with NULL pointer";
263 assert(false);
264 return kFail;
265 }
kwiberg342f7402016-06-16 03:18:00 -0700266 int ret = decoder_database_->InsertExternal(rtp_payload_type, codec,
267 codec_name, decoder);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000268 if (ret != DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000269 switch (ret) {
270 case DecoderDatabase::kInvalidRtpPayloadType:
271 error_code_ = kInvalidRtpPayloadType;
272 break;
273 case DecoderDatabase::kCodecNotSupported:
274 error_code_ = kCodecNotSupported;
275 break;
276 case DecoderDatabase::kDecoderExists:
277 error_code_ = kDecoderExists;
278 break;
279 case DecoderDatabase::kInvalidSampleRate:
280 error_code_ = kInvalidSampleRate;
281 break;
282 case DecoderDatabase::kInvalidPointer:
283 error_code_ = kInvalidPointer;
284 break;
285 default:
286 error_code_ = kOtherError;
287 }
288 return kFail;
289 }
290 return kOK;
291}
292
293int NetEqImpl::RemovePayloadType(uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100294 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000295 int ret = decoder_database_->Remove(rtp_payload_type);
296 if (ret == DecoderDatabase::kOK) {
297 return kOK;
298 } else if (ret == DecoderDatabase::kDecoderNotFound) {
299 error_code_ = kDecoderNotFound;
300 } else {
301 error_code_ = kOtherError;
302 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000303 return kFail;
304}
305
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000306bool NetEqImpl::SetMinimumDelay(int delay_ms) {
Tommi9090e0b2016-01-20 13:39:36 +0100307 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000308 if (delay_ms >= 0 && delay_ms < 10000) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000309 assert(delay_manager_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000310 return delay_manager_->SetMinimumDelay(delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000311 }
312 return false;
313}
314
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000315bool NetEqImpl::SetMaximumDelay(int delay_ms) {
Tommi9090e0b2016-01-20 13:39:36 +0100316 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000317 if (delay_ms >= 0 && delay_ms < 10000) {
318 assert(delay_manager_.get());
319 return delay_manager_->SetMaximumDelay(delay_ms);
320 }
321 return false;
322}
323
324int NetEqImpl::LeastRequiredDelayMs() const {
Tommi9090e0b2016-01-20 13:39:36 +0100325 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000326 assert(delay_manager_.get());
327 return delay_manager_->least_required_delay_ms();
328}
329
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200330int NetEqImpl::SetTargetDelay() {
331 return kNotImplemented;
332}
333
334int NetEqImpl::TargetDelay() {
335 return kNotImplemented;
336}
337
henrik.lundin9c3efd02015-08-27 13:12:22 -0700338int NetEqImpl::CurrentDelayMs() const {
Tommi9090e0b2016-01-20 13:39:36 +0100339 rtc::CritScope lock(&crit_sect_);
henrik.lundin9c3efd02015-08-27 13:12:22 -0700340 if (fs_hz_ == 0)
341 return 0;
342 // Sum up the samples in the packet buffer with the future length of the sync
343 // buffer, and divide the sum by the sample rate.
344 const size_t delay_samples =
345 packet_buffer_->NumSamplesInBuffer(decoder_database_.get(),
346 decoder_frame_length_) +
347 sync_buffer_->FutureLength();
348 // The division below will truncate.
349 const int delay_ms =
350 static_cast<int>(delay_samples) / rtc::CheckedDivExact(fs_hz_, 1000);
351 return delay_ms;
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200352}
353
henrik.lundinb3f1c5d2016-08-22 15:39:53 -0700354int NetEqImpl::FilteredCurrentDelayMs() const {
355 rtc::CritScope lock(&crit_sect_);
356 // Calculate the filtered packet buffer level in samples. The value from
357 // |buffer_level_filter_| is in number of packets, represented in Q8.
358 const size_t packet_buffer_samples =
359 (buffer_level_filter_->filtered_current_level() *
360 decoder_frame_length_) >>
361 8;
362 // Sum up the filtered packet buffer level with the future length of the sync
363 // buffer, and divide the sum by the sample rate.
364 const size_t delay_samples =
365 packet_buffer_samples + sync_buffer_->FutureLength();
366 // The division below will truncate. The return value is in ms.
367 return static_cast<int>(delay_samples) / rtc::CheckedDivExact(fs_hz_, 1000);
368}
369
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000370// Deprecated.
371// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000372void NetEqImpl::SetPlayoutMode(NetEqPlayoutMode mode) {
Tommi9090e0b2016-01-20 13:39:36 +0100373 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000374 if (mode != playout_mode_) {
375 playout_mode_ = mode;
376 CreateDecisionLogic();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000377 }
378}
379
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000380// Deprecated.
381// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000382NetEqPlayoutMode NetEqImpl::PlayoutMode() const {
Tommi9090e0b2016-01-20 13:39:36 +0100383 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000384 return playout_mode_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000385}
386
387int NetEqImpl::NetworkStatistics(NetEqNetworkStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100388 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000389 assert(decoder_database_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700390 const size_t total_samples_in_buffers =
Peter Kasting728d9032015-06-11 14:31:38 -0700391 packet_buffer_->NumSamplesInBuffer(decoder_database_.get(),
392 decoder_frame_length_) +
Peter Kastingdce40cf2015-08-24 14:52:23 -0700393 sync_buffer_->FutureLength();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000394 assert(delay_manager_.get());
395 assert(decision_logic_.get());
396 stats_.GetNetworkStatistics(fs_hz_, total_samples_in_buffers,
397 decoder_frame_length_, *delay_manager_.get(),
398 *decision_logic_.get(), stats);
399 return 0;
400}
401
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000402void NetEqImpl::GetRtcpStatistics(RtcpStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100403 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000404 if (stats) {
405 rtcp_.GetStatistics(false, stats);
406 }
407}
408
409void NetEqImpl::GetRtcpStatisticsNoReset(RtcpStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100410 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000411 if (stats) {
412 rtcp_.GetStatistics(true, stats);
413 }
414}
415
416void NetEqImpl::EnableVad() {
Tommi9090e0b2016-01-20 13:39:36 +0100417 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000418 assert(vad_.get());
419 vad_->Enable();
420}
421
422void NetEqImpl::DisableVad() {
Tommi9090e0b2016-01-20 13:39:36 +0100423 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000424 assert(vad_.get());
425 vad_->Disable();
426}
427
henrik.lundin15c51e32016-04-06 08:38:56 -0700428rtc::Optional<uint32_t> NetEqImpl::GetPlayoutTimestamp() const {
Tommi9090e0b2016-01-20 13:39:36 +0100429 rtc::CritScope lock(&crit_sect_);
henrik.lundin0d96ab72016-04-06 12:28:26 -0700430 if (first_packet_ || last_mode_ == kModeRfc3389Cng ||
431 last_mode_ == kModeCodecInternalCng) {
wu@webrtc.org94454b72014-06-05 20:34:08 +0000432 // We don't have a valid RTP timestamp until we have decoded our first
henrik.lundin0d96ab72016-04-06 12:28:26 -0700433 // RTP packet. Also, the RTP timestamp is not accurate while playing CNG,
434 // which is indicated by returning an empty value.
henrik.lundin9a410dd2016-04-06 01:39:22 -0700435 return rtc::Optional<uint32_t>();
wu@webrtc.org94454b72014-06-05 20:34:08 +0000436 }
henrik.lundin9a410dd2016-04-06 01:39:22 -0700437 return rtc::Optional<uint32_t>(
438 timestamp_scaler_->ToExternal(playout_timestamp_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000439}
440
henrik.lundind89814b2015-11-23 06:49:25 -0800441int NetEqImpl::last_output_sample_rate_hz() const {
Tommi9090e0b2016-01-20 13:39:36 +0100442 rtc::CritScope lock(&crit_sect_);
henrik.lundind89814b2015-11-23 06:49:25 -0800443 return last_output_sample_rate_hz_;
444}
445
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200446int NetEqImpl::SetTargetNumberOfChannels() {
447 return kNotImplemented;
448}
449
450int NetEqImpl::SetTargetSampleRate() {
451 return kNotImplemented;
452}
453
henrik.lundin@webrtc.orgb0f4b3d2014-11-04 08:53:10 +0000454int NetEqImpl::LastError() const {
Tommi9090e0b2016-01-20 13:39:36 +0100455 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000456 return error_code_;
457}
458
459int NetEqImpl::LastDecoderError() {
Tommi9090e0b2016-01-20 13:39:36 +0100460 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000461 return decoder_error_code_;
462}
463
464void NetEqImpl::FlushBuffers() {
Tommi9090e0b2016-01-20 13:39:36 +0100465 rtc::CritScope lock(&crit_sect_);
Henrik Lundind67a2192015-08-03 12:54:37 +0200466 LOG(LS_VERBOSE) << "FlushBuffers";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000467 packet_buffer_->Flush();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000468 assert(sync_buffer_.get());
469 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000470 sync_buffer_->Flush();
471 sync_buffer_->set_next_index(sync_buffer_->next_index() -
472 expand_->overlap_length());
473 // Set to wait for new codec.
474 first_packet_ = true;
475}
476
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000477void NetEqImpl::PacketBufferStatistics(int* current_num_packets,
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000478 int* max_num_packets) const {
Tommi9090e0b2016-01-20 13:39:36 +0100479 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000480 packet_buffer_->BufferStat(current_num_packets, max_num_packets);
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000481}
482
henrik.lundin48ed9302015-10-29 05:36:24 -0700483void NetEqImpl::EnableNack(size_t max_nack_list_size) {
Tommi9090e0b2016-01-20 13:39:36 +0100484 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700485 if (!nack_enabled_) {
486 const int kNackThresholdPackets = 2;
henrik.lundin91951862016-06-08 06:43:41 -0700487 nack_.reset(NackTracker::Create(kNackThresholdPackets));
henrik.lundin48ed9302015-10-29 05:36:24 -0700488 nack_enabled_ = true;
489 nack_->UpdateSampleRate(fs_hz_);
490 }
491 nack_->SetMaxNackListSize(max_nack_list_size);
492}
493
494void NetEqImpl::DisableNack() {
Tommi9090e0b2016-01-20 13:39:36 +0100495 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700496 nack_.reset();
497 nack_enabled_ = false;
498}
499
500std::vector<uint16_t> NetEqImpl::GetNackList(int64_t round_trip_time_ms) const {
Tommi9090e0b2016-01-20 13:39:36 +0100501 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700502 if (!nack_enabled_) {
503 return std::vector<uint16_t>();
504 }
505 RTC_DCHECK(nack_.get());
506 return nack_->GetNackList(round_trip_time_ms);
minyue@webrtc.orgd7301772013-08-29 00:58:14 +0000507}
508
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000509const SyncBuffer* NetEqImpl::sync_buffer_for_test() const {
Tommi9090e0b2016-01-20 13:39:36 +0100510 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000511 return sync_buffer_.get();
512}
513
minyue5bd33972016-05-02 04:46:11 -0700514Operations NetEqImpl::last_operation_for_test() const {
515 rtc::CritScope lock(&crit_sect_);
516 return last_operation_;
517}
518
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000519// Methods below this line are private.
520
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000521int NetEqImpl::InsertPacketInternal(const WebRtcRTPHeader& rtp_header,
kwibergee2bac22015-11-11 10:34:00 -0800522 rtc::ArrayView<const uint8_t> payload,
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000523 uint32_t receive_timestamp,
524 bool is_sync_packet) {
kwibergee2bac22015-11-11 10:34:00 -0800525 if (payload.empty()) {
526 LOG_F(LS_ERROR) << "payload is empty";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000527 return kInvalidPointer;
528 }
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000529 // Sanity checks for sync-packets.
530 if (is_sync_packet) {
531 if (decoder_database_->IsDtmf(rtp_header.header.payloadType) ||
532 decoder_database_->IsRed(rtp_header.header.payloadType) ||
533 decoder_database_->IsComfortNoise(rtp_header.header.payloadType)) {
534 LOG_F(LS_ERROR) << "Sync-packet with an unacceptable payload type "
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000535 << static_cast<int>(rtp_header.header.payloadType);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000536 return kSyncPacketNotAccepted;
537 }
henrik.lundinda8bbf62016-08-31 03:14:11 -0700538 if (first_packet_ || !current_rtp_payload_type_ ||
539 rtp_header.header.payloadType != *current_rtp_payload_type_ ||
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000540 rtp_header.header.ssrc != ssrc_) {
henrik.lundinda8bbf62016-08-31 03:14:11 -0700541 // Even if |current_rtp_payload_type_| is empty, sync-packet isn't
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000542 // accepted.
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000543 LOG_F(LS_ERROR)
544 << "Changing codec, SSRC or first packet with sync-packet.";
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000545 return kSyncPacketNotAccepted;
546 }
547 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000548 PacketList packet_list;
549 RTPHeader main_header;
550 {
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000551 // Convert to Packet.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000552 // Create |packet| within this separate scope, since it should not be used
553 // directly once it's been inserted in the packet list. This way, |packet|
554 // is not defined outside of this block.
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000555 Packet* packet = new Packet;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000556 packet->header.markerBit = false;
557 packet->header.payloadType = rtp_header.header.payloadType;
558 packet->header.sequenceNumber = rtp_header.header.sequenceNumber;
559 packet->header.timestamp = rtp_header.header.timestamp;
560 packet->header.ssrc = rtp_header.header.ssrc;
561 packet->header.numCSRCs = 0;
ossudc431ce2016-08-31 08:51:13 -0700562 packet->payload.SetData(payload.data(), payload.size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000563 packet->primary = true;
henrik.lundin84f8cd62016-04-26 07:45:16 -0700564 // Waiting time will be set upon inserting the packet in the buffer.
565 RTC_DCHECK(!packet->waiting_time);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000566 packet->sync_packet = is_sync_packet;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000567 // Insert packet in a packet list.
568 packet_list.push_back(packet);
569 // Save main payloads header for later.
570 memcpy(&main_header, &packet->header, sizeof(main_header));
571 }
572
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000573 bool update_sample_rate_and_channels = false;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000574 // Reinitialize NetEq if it's needed (changed SSRC or first call).
575 if ((main_header.ssrc != ssrc_) || first_packet_) {
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000576 // Note: |first_packet_| will be cleared further down in this method, once
577 // the packet has been successfully inserted into the packet buffer.
578
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000579 rtcp_.Init(main_header.sequenceNumber);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000580
581 // Flush the packet buffer and DTMF buffer.
582 packet_buffer_->Flush();
583 dtmf_buffer_->Flush();
584
585 // Store new SSRC.
586 ssrc_ = main_header.ssrc;
587
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000588 // Update audio buffer timestamp.
589 sync_buffer_->IncreaseEndTimestamp(main_header.timestamp - timestamp_);
590
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000591 // Update codecs.
592 timestamp_ = main_header.timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000593
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000594 // Reset timestamp scaling.
595 timestamp_scaler_->Reset();
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000596
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000597 // Trigger an update of sampling rate and the number of channels.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000598 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000599 }
600
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000601 // Update RTCP statistics, only for regular packets.
602 if (!is_sync_packet)
603 rtcp_.Update(main_header, receive_timestamp);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000604
605 // Check for RED payload type, and separate payloads into several packets.
606 if (decoder_database_->IsRed(main_header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000607 assert(!is_sync_packet); // We had a sanity check for this.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000608 if (payload_splitter_->SplitRed(&packet_list) != PayloadSplitter::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000609 PacketBuffer::DeleteAllPackets(&packet_list);
610 return kRedundancySplitError;
611 }
612 // Only accept a few RED payloads of the same type as the main data,
613 // DTMF events and CNG.
614 payload_splitter_->CheckRedPayloads(&packet_list, *decoder_database_);
615 // Update the stored main payload header since the main payload has now
616 // changed.
617 memcpy(&main_header, &packet_list.front()->header, sizeof(main_header));
618 }
619
620 // Check payload types.
621 if (decoder_database_->CheckPayloadTypes(packet_list) ==
622 DecoderDatabase::kDecoderNotFound) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000623 PacketBuffer::DeleteAllPackets(&packet_list);
624 return kUnknownRtpPayloadType;
625 }
626
627 // Scale timestamp to internal domain (only for some codecs).
628 timestamp_scaler_->ToInternal(&packet_list);
629
630 // Process DTMF payloads. Cycle through the list of packets, and pick out any
631 // DTMF payloads found.
632 PacketList::iterator it = packet_list.begin();
633 while (it != packet_list.end()) {
634 Packet* current_packet = (*it);
635 assert(current_packet);
ossudc431ce2016-08-31 08:51:13 -0700636 assert(!current_packet->payload.empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000637 if (decoder_database_->IsDtmf(current_packet->header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000638 assert(!current_packet->sync_packet); // We had a sanity check for this.
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000639 DtmfEvent event;
ossudc431ce2016-08-31 08:51:13 -0700640 int ret = DtmfBuffer::ParseEvent(current_packet->header.timestamp,
641 current_packet->payload.data(),
642 current_packet->payload.size(), &event);
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000643 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 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000651 delete current_packet;
652 it = packet_list.erase(it);
653 } else {
654 ++it;
655 }
656 }
657
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000658 // Check for FEC in packets, and separate payloads into several packets.
659 int ret = payload_splitter_->SplitFec(&packet_list, decoder_database_.get());
660 if (ret != PayloadSplitter::kOK) {
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000661 PacketBuffer::DeleteAllPackets(&packet_list);
662 switch (ret) {
663 case PayloadSplitter::kUnknownPayloadType:
664 return kUnknownRtpPayloadType;
665 default:
666 return kOtherError;
667 }
668 }
669
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000670 // Split payloads into smaller chunks. This also verifies that all payloads
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000671 // are of a known payload type. SplitAudio() method is protected against
672 // sync-packets.
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +0000673 ret = payload_splitter_->SplitAudio(&packet_list, *decoder_database_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000674 if (ret != PayloadSplitter::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000675 PacketBuffer::DeleteAllPackets(&packet_list);
676 switch (ret) {
677 case PayloadSplitter::kUnknownPayloadType:
678 return kUnknownRtpPayloadType;
679 case PayloadSplitter::kFrameSplitError:
680 return kFrameSplitError;
681 default:
682 return kOtherError;
683 }
684 }
685
ossu97ba30e2016-04-25 07:55:58 -0700686 // Update bandwidth estimate, if the packet is not sync-packet nor comfort
687 // noise.
688 if (!packet_list.empty() && !packet_list.front()->sync_packet &&
689 !decoder_database_->IsComfortNoise(main_header.payloadType)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000690 // The list can be empty here if we got nothing but DTMF payloads.
691 AudioDecoder* decoder =
692 decoder_database_->GetDecoder(main_header.payloadType);
693 assert(decoder); // Should always get a valid object, since we have
ossu97ba30e2016-04-25 07:55:58 -0700694 // already checked that the payload types are known.
ossudc431ce2016-08-31 08:51:13 -0700695 decoder->IncomingPacket(packet_list.front()->payload.data(),
696 packet_list.front()->payload.size(),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000697 packet_list.front()->header.sequenceNumber,
698 packet_list.front()->header.timestamp,
699 receive_timestamp);
700 }
701
henrik.lundin48ed9302015-10-29 05:36:24 -0700702 if (nack_enabled_) {
703 RTC_DCHECK(nack_);
704 if (update_sample_rate_and_channels) {
705 nack_->Reset();
706 }
707 nack_->UpdateLastReceivedPacket(packet_list.front()->header.sequenceNumber,
708 packet_list.front()->header.timestamp);
709 }
710
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000711 // Insert packets in buffer.
henrik.lundin116c84e2015-08-27 13:14:48 -0700712 const size_t buffer_length_before_insert =
713 packet_buffer_->NumPacketsInBuffer();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000714 ret = packet_buffer_->InsertPacketList(
715 &packet_list,
716 *decoder_database_,
717 &current_rtp_payload_type_,
718 &current_cng_rtp_payload_type_);
719 if (ret == PacketBuffer::kFlushed) {
720 // Reset DSP timestamp etc. if packet buffer flushed.
721 new_codec_ = true;
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000722 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000723 } else if (ret != PacketBuffer::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000724 PacketBuffer::DeleteAllPackets(&packet_list);
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000725 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000726 }
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000727
728 if (first_packet_) {
729 first_packet_ = false;
730 // Update the codec on the next GetAudio call.
731 new_codec_ = true;
732 }
733
henrik.lundinda8bbf62016-08-31 03:14:11 -0700734 if (current_rtp_payload_type_) {
735 RTC_DCHECK(decoder_database_->GetDecoderInfo(*current_rtp_payload_type_))
736 << "Payload type " << static_cast<int>(*current_rtp_payload_type_)
737 << " is unknown where it shouldn't be";
738 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000739
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000740 if (update_sample_rate_and_channels && !packet_buffer_->Empty()) {
741 // We do not use |current_rtp_payload_type_| to |set payload_type|, but
742 // get the next RTP header from |packet_buffer_| to obtain the payload type.
743 // The reason for it is the following corner case. If NetEq receives a
744 // CNG packet with a sample rate different than the current CNG then it
745 // flushes its buffer, assuming send codec must have been changed. However,
746 // payload type of the hypothetically new send codec is not known.
747 const RTPHeader* rtp_header = packet_buffer_->NextRtpHeader();
748 assert(rtp_header);
749 int payload_type = rtp_header->payloadType;
ossu97ba30e2016-04-25 07:55:58 -0700750 size_t channels = 1;
751 if (!decoder_database_->IsComfortNoise(payload_type)) {
752 AudioDecoder* decoder = decoder_database_->GetDecoder(payload_type);
753 assert(decoder); // Payloads are already checked to be valid.
754 channels = decoder->Channels();
755 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000756 const DecoderDatabase::DecoderInfo* decoder_info =
757 decoder_database_->GetDecoderInfo(payload_type);
758 assert(decoder_info);
kwibergc0f2dcf2016-05-31 06:28:03 -0700759 if (decoder_info->SampleRateHz() != fs_hz_ ||
ossu97ba30e2016-04-25 07:55:58 -0700760 channels != algorithm_buffer_->Channels()) {
kwibergc0f2dcf2016-05-31 06:28:03 -0700761 SetSampleRateAndChannels(decoder_info->SampleRateHz(),
762 channels);
henrik.lundin48ed9302015-10-29 05:36:24 -0700763 }
764 if (nack_enabled_) {
765 RTC_DCHECK(nack_);
766 // Update the sample rate even if the rate is not new, because of Reset().
767 nack_->UpdateSampleRate(fs_hz_);
768 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000769 }
770
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000771 // TODO(hlundin): Move this code to DelayManager class.
772 const DecoderDatabase::DecoderInfo* dec_info =
773 decoder_database_->GetDecoderInfo(main_header.payloadType);
774 assert(dec_info); // Already checked that the payload type is known.
775 delay_manager_->LastDecoderType(dec_info->codec_type);
776 if (delay_manager_->last_pack_cng_or_dtmf() == 0) {
777 // Calculate the total speech length carried in each packet.
henrik.lundin116c84e2015-08-27 13:14:48 -0700778 const size_t buffer_length_after_insert =
779 packet_buffer_->NumPacketsInBuffer();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000780
henrik.lundin116c84e2015-08-27 13:14:48 -0700781 if (buffer_length_after_insert > buffer_length_before_insert) {
782 const size_t packet_length_samples =
783 (buffer_length_after_insert - buffer_length_before_insert) *
784 decoder_frame_length_;
785 if (packet_length_samples != decision_logic_->packet_length_samples()) {
786 decision_logic_->set_packet_length_samples(packet_length_samples);
787 delay_manager_->SetPacketAudioLength(
788 rtc::checked_cast<int>((1000 * packet_length_samples) / fs_hz_));
789 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000790 }
791
792 // Update statistics.
pbos@webrtc.org0946a562013-04-09 00:28:06 +0000793 if ((int32_t) (main_header.timestamp - timestamp_) >= 0 &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000794 !new_codec_) {
795 // Only update statistics if incoming packet is not older than last played
796 // out packet, and if new codec flag is not set.
797 delay_manager_->Update(main_header.sequenceNumber, main_header.timestamp,
798 fs_hz_);
799 }
800 } else if (delay_manager_->last_pack_cng_or_dtmf() == -1) {
801 // This is first "normal" packet after CNG or DTMF.
802 // Reset packet time counter and measure time until next packet,
803 // but don't update statistics.
804 delay_manager_->set_last_pack_cng_or_dtmf(0);
805 delay_manager_->ResetPacketIatCount();
806 }
807 return 0;
808}
809
henrik.lundin7a926812016-05-12 13:51:28 -0700810int NetEqImpl::GetAudioInternal(AudioFrame* audio_frame, bool* muted) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000811 PacketList packet_list;
812 DtmfEvent dtmf_event;
813 Operations operation;
814 bool play_dtmf;
henrik.lundin7a926812016-05-12 13:51:28 -0700815 *muted = false;
henrik.lundined497212016-04-25 10:11:38 -0700816 tick_timer_->Increment();
henrik.lundin60f6ce22016-05-10 03:52:04 -0700817 stats_.IncreaseCounter(output_size_samples_, fs_hz_);
henrik.lundin7a926812016-05-12 13:51:28 -0700818
819 // Check for muted state.
820 if (enable_muted_state_ && expand_->Muted() && packet_buffer_->Empty()) {
821 RTC_DCHECK_EQ(last_mode_, kModeExpand);
822 playout_timestamp_ += static_cast<uint32_t>(output_size_samples_);
823 audio_frame->sample_rate_hz_ = fs_hz_;
824 audio_frame->samples_per_channel_ = output_size_samples_;
825 audio_frame->timestamp_ =
826 first_packet_
827 ? 0
828 : timestamp_scaler_->ToExternal(playout_timestamp_) -
829 static_cast<uint32_t>(audio_frame->samples_per_channel_);
830 audio_frame->num_channels_ = sync_buffer_->Channels();
henrik.lundin612c25e2016-05-25 08:21:04 -0700831 stats_.ExpandedNoiseSamples(output_size_samples_);
henrik.lundin7a926812016-05-12 13:51:28 -0700832 *muted = true;
833 return 0;
834 }
835
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000836 int return_value = GetDecision(&operation, &packet_list, &dtmf_event,
837 &play_dtmf);
838 if (return_value != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000839 last_mode_ = kModeError;
840 return return_value;
841 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000842
843 AudioDecoder::SpeechType speech_type;
844 int length = 0;
845 int decode_return_value = Decode(&packet_list, &operation,
846 &length, &speech_type);
847
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000848 assert(vad_.get());
849 bool sid_frame_available =
850 (operation == kRfc3389Cng && !packet_list.empty());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700851 vad_->Update(decoded_buffer_.get(), static_cast<size_t>(length), speech_type,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000852 sid_frame_available, fs_hz_);
853
henrik.lundinb1fb72b2016-05-03 08:18:47 -0700854 if (sid_frame_available || speech_type == AudioDecoder::kComfortNoise) {
855 // Start a new stopwatch since we are decoding a new CNG packet.
856 generated_noise_stopwatch_ = tick_timer_->GetNewStopwatch();
857 }
858
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000859 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000860 switch (operation) {
861 case kNormal: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000862 DoNormal(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000863 break;
864 }
865 case kMerge: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000866 DoMerge(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000867 break;
868 }
869 case kExpand: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000870 return_value = DoExpand(play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000871 break;
872 }
Henrik Lundincf808d22015-05-27 14:33:29 +0200873 case kAccelerate:
874 case kFastAccelerate: {
875 const bool fast_accelerate =
876 enable_fast_accelerate_ && (operation == kFastAccelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000877 return_value = DoAccelerate(decoded_buffer_.get(), length, speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +0200878 play_dtmf, fast_accelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000879 break;
880 }
881 case kPreemptiveExpand: {
882 return_value = DoPreemptiveExpand(decoded_buffer_.get(), length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000883 speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000884 break;
885 }
886 case kRfc3389Cng:
887 case kRfc3389CngNoPacket: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000888 return_value = DoRfc3389Cng(&packet_list, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000889 break;
890 }
891 case kCodecInternalCng: {
892 // This handles the case when there is no transmission and the decoder
893 // should produce internal comfort noise.
894 // TODO(hlundin): Write test for codec-internal CNG.
minyuel6d92bf52015-09-23 15:20:39 +0200895 DoCodecInternalCng(decoded_buffer_.get(), length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000896 break;
897 }
898 case kDtmf: {
899 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000900 return_value = DoDtmf(dtmf_event, &play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000901 break;
902 }
903 case kAlternativePlc: {
904 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000905 DoAlternativePlc(false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000906 break;
907 }
908 case kAlternativePlcIncreaseTimestamp: {
909 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000910 DoAlternativePlc(true);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000911 break;
912 }
913 case kAudioRepetitionIncreaseTimestamp: {
914 // TODO(hlundin): Write test for this.
Peter Kastingb7e50542015-06-11 12:55:50 -0700915 sync_buffer_->IncreaseEndTimestamp(
916 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000917 // Skipping break on purpose. Execution should move on into the
918 // next case.
kjellander@webrtc.org7d2b6a92015-01-28 18:37:58 +0000919 FALLTHROUGH();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000920 }
921 case kAudioRepetition: {
922 // TODO(hlundin): Write test for this.
923 // Copy last |output_size_samples_| from |sync_buffer_| to
924 // |algorithm_buffer|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000925 algorithm_buffer_->PushBackFromIndex(
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000926 *sync_buffer_, sync_buffer_->Size() - output_size_samples_);
927 expand_->Reset();
928 break;
929 }
930 case kUndefined: {
Henrik Lundind67a2192015-08-03 12:54:37 +0200931 LOG(LS_ERROR) << "Invalid operation kUndefined.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000932 assert(false); // This should not happen.
933 last_mode_ = kModeError;
934 return kInvalidOperation;
935 }
936 } // End of switch.
minyue5bd33972016-05-02 04:46:11 -0700937 last_operation_ = operation;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000938 if (return_value < 0) {
939 return return_value;
940 }
941
942 if (last_mode_ != kModeRfc3389Cng) {
943 comfort_noise_->Reset();
944 }
945
946 // Copy from |algorithm_buffer| to |sync_buffer_|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000947 sync_buffer_->PushBack(*algorithm_buffer_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000948
949 // Extract data from |sync_buffer_| to |output|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000950 size_t num_output_samples_per_channel = output_size_samples_;
951 size_t num_output_samples = output_size_samples_ * sync_buffer_->Channels();
henrik.lundin6d8e0112016-03-04 10:34:21 -0800952 if (num_output_samples > AudioFrame::kMaxDataSizeSamples) {
953 LOG(LS_WARNING) << "Output array is too short. "
954 << AudioFrame::kMaxDataSizeSamples << " < "
955 << output_size_samples_ << " * "
956 << sync_buffer_->Channels();
957 num_output_samples = AudioFrame::kMaxDataSizeSamples;
958 num_output_samples_per_channel =
959 AudioFrame::kMaxDataSizeSamples / sync_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000960 }
henrik.lundin6d8e0112016-03-04 10:34:21 -0800961 sync_buffer_->GetNextAudioInterleaved(num_output_samples_per_channel,
962 audio_frame);
963 audio_frame->sample_rate_hz_ = fs_hz_;
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200964 if (sync_buffer_->FutureLength() < expand_->overlap_length()) {
965 // The sync buffer should always contain |overlap_length| samples, but now
966 // too many samples have been extracted. Reinstall the |overlap_length|
967 // lookahead by moving the index.
968 const size_t missing_lookahead_samples =
969 expand_->overlap_length() - sync_buffer_->FutureLength();
henrikg91d6ede2015-09-17 00:24:34 -0700970 RTC_DCHECK_GE(sync_buffer_->next_index(), missing_lookahead_samples);
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200971 sync_buffer_->set_next_index(sync_buffer_->next_index() -
972 missing_lookahead_samples);
973 }
henrik.lundin6d8e0112016-03-04 10:34:21 -0800974 if (audio_frame->samples_per_channel_ != output_size_samples_) {
975 LOG(LS_ERROR) << "audio_frame->samples_per_channel_ ("
976 << audio_frame->samples_per_channel_
Henrik Lundind67a2192015-08-03 12:54:37 +0200977 << ") != output_size_samples_ (" << output_size_samples_
978 << ")";
minyue@webrtc.orgdb1cefc2013-08-13 01:39:21 +0000979 // TODO(minyue): treatment of under-run, filling zeros
henrik.lundin6d8e0112016-03-04 10:34:21 -0800980 memset(audio_frame->data_, 0, num_output_samples * sizeof(int16_t));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000981 return kSampleUnderrun;
982 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000983
984 // Should always have overlap samples left in the |sync_buffer_|.
henrikg91d6ede2015-09-17 00:24:34 -0700985 RTC_DCHECK_GE(sync_buffer_->FutureLength(), expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000986
987 if (play_dtmf) {
henrik.lundin6d8e0112016-03-04 10:34:21 -0800988 return_value =
989 DtmfOverdub(dtmf_event, sync_buffer_->Channels(), audio_frame->data_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000990 }
991
992 // Update the background noise parameters if last operation wrote data
993 // straight from the decoder to the |sync_buffer_|. That is, none of the
994 // operations that modify the signal can be followed by a parameter update.
995 if ((last_mode_ == kModeNormal) ||
996 (last_mode_ == kModeAccelerateFail) ||
997 (last_mode_ == kModePreemptiveExpandFail) ||
998 (last_mode_ == kModeRfc3389Cng) ||
999 (last_mode_ == kModeCodecInternalCng)) {
1000 background_noise_->Update(*sync_buffer_, *vad_.get());
1001 }
1002
1003 if (operation == kDtmf) {
1004 // DTMF data was written the end of |sync_buffer_|.
1005 // Update index to end of DTMF data in |sync_buffer_|.
1006 sync_buffer_->set_dtmf_index(sync_buffer_->Size());
1007 }
1008
henrik.lundin@webrtc.orged865b52014-03-06 10:28:07 +00001009 if (last_mode_ != kModeExpand) {
1010 // If last operation was not expand, calculate the |playout_timestamp_| from
1011 // the |sync_buffer_|. However, do not update the |playout_timestamp_| if it
1012 // would be moved "backwards".
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001013 uint32_t temp_timestamp = sync_buffer_->end_timestamp() -
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001014 static_cast<uint32_t>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001015 if (static_cast<int32_t>(temp_timestamp - playout_timestamp_) > 0) {
1016 playout_timestamp_ = temp_timestamp;
1017 }
1018 } else {
1019 // Use dead reckoning to estimate the |playout_timestamp_|.
Peter Kastingb7e50542015-06-11 12:55:50 -07001020 playout_timestamp_ += static_cast<uint32_t>(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001021 }
henrik.lundin15c51e32016-04-06 08:38:56 -07001022 // Set the timestamp in the audio frame to zero before the first packet has
1023 // been inserted. Otherwise, subtract the frame size in samples to get the
1024 // timestamp of the first sample in the frame (playout_timestamp_ is the
1025 // last + 1).
1026 audio_frame->timestamp_ =
1027 first_packet_
1028 ? 0
1029 : timestamp_scaler_->ToExternal(playout_timestamp_) -
1030 static_cast<uint32_t>(audio_frame->samples_per_channel_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001031
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001032 if (!(last_mode_ == kModeRfc3389Cng ||
1033 last_mode_ == kModeCodecInternalCng ||
1034 last_mode_ == kModeExpand)) {
1035 generated_noise_stopwatch_.reset();
1036 }
1037
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001038 if (decode_return_value) return decode_return_value;
1039 return return_value;
1040}
1041
1042int NetEqImpl::GetDecision(Operations* operation,
1043 PacketList* packet_list,
1044 DtmfEvent* dtmf_event,
1045 bool* play_dtmf) {
1046 // Initialize output variables.
1047 *play_dtmf = false;
1048 *operation = kUndefined;
1049
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001050 assert(sync_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001051 uint32_t end_timestamp = sync_buffer_->end_timestamp();
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001052 if (!new_codec_) {
1053 const uint32_t five_seconds_samples = 5 * fs_hz_;
1054 packet_buffer_->DiscardOldPackets(end_timestamp, five_seconds_samples);
1055 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001056 const RTPHeader* header = packet_buffer_->NextRtpHeader();
1057
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001058 RTC_DCHECK(!generated_noise_stopwatch_ ||
1059 generated_noise_stopwatch_->ElapsedTicks() >= 1);
1060 uint64_t generated_noise_samples =
1061 generated_noise_stopwatch_
1062 ? (generated_noise_stopwatch_->ElapsedTicks() - 1) *
1063 output_size_samples_ +
1064 decision_logic_->noise_fast_forward()
1065 : 0;
1066
henrik.lundin@webrtc.orgca8cb952014-03-12 10:26:52 +00001067 if (decision_logic_->CngRfc3389On() || last_mode_ == kModeRfc3389Cng) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001068 // Because of timestamp peculiarities, we have to "manually" disallow using
1069 // a CNG packet with the same timestamp as the one that was last played.
1070 // This can happen when using redundancy and will cause the timing to shift.
henrik.lundin@webrtc.org24779fe2014-03-14 12:40:05 +00001071 while (header && decoder_database_->IsComfortNoise(header->payloadType) &&
1072 (end_timestamp >= header->timestamp ||
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001073 end_timestamp + generated_noise_samples > header->timestamp)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001074 // Don't use this packet, discard it.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001075 if (packet_buffer_->DiscardNextPacket() != PacketBuffer::kOK) {
1076 assert(false); // Must be ok by design.
1077 }
1078 // Check buffer again.
1079 if (!new_codec_) {
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001080 packet_buffer_->DiscardOldPackets(end_timestamp, 5 * fs_hz_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001081 }
1082 header = packet_buffer_->NextRtpHeader();
1083 }
1084 }
1085
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001086 assert(expand_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001087 const int samples_left = static_cast<int>(sync_buffer_->FutureLength() -
1088 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001089 if (last_mode_ == kModeAccelerateSuccess ||
1090 last_mode_ == kModeAccelerateLowEnergy ||
1091 last_mode_ == kModePreemptiveExpandSuccess ||
1092 last_mode_ == kModePreemptiveExpandLowEnergy) {
1093 // Subtract (samples_left + output_size_samples_) from sampleMemory.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001094 decision_logic_->AddSampleMemory(
1095 -(samples_left + rtc::checked_cast<int>(output_size_samples_)));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001096 }
1097
1098 // Check if it is time to play a DTMF event.
Peter Kastingb7e50542015-06-11 12:55:50 -07001099 if (dtmf_buffer_->GetEvent(
1100 static_cast<uint32_t>(
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001101 end_timestamp + generated_noise_samples),
Peter Kastingb7e50542015-06-11 12:55:50 -07001102 dtmf_event)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001103 *play_dtmf = true;
1104 }
1105
1106 // Get instruction.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001107 assert(sync_buffer_.get());
1108 assert(expand_.get());
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001109 generated_noise_samples =
1110 generated_noise_stopwatch_
1111 ? generated_noise_stopwatch_->ElapsedTicks() * output_size_samples_ +
1112 decision_logic_->noise_fast_forward()
1113 : 0;
1114 *operation = decision_logic_->GetDecision(
1115 *sync_buffer_, *expand_, decoder_frame_length_, header, last_mode_,
1116 *play_dtmf, generated_noise_samples, &reset_decoder_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001117
1118 // Check if we already have enough samples in the |sync_buffer_|. If so,
1119 // change decision to normal, unless the decision was merge, accelerate, or
1120 // preemptive expand.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001121 if (samples_left >= rtc::checked_cast<int>(output_size_samples_) &&
1122 *operation != kMerge &&
1123 *operation != kAccelerate &&
1124 *operation != kFastAccelerate &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001125 *operation != kPreemptiveExpand) {
1126 *operation = kNormal;
1127 return 0;
1128 }
1129
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001130 decision_logic_->ExpandDecision(*operation);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001131
1132 // Check conditions for reset.
1133 if (new_codec_ || *operation == kUndefined) {
1134 // The only valid reason to get kUndefined is that new_codec_ is set.
1135 assert(new_codec_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001136 if (*play_dtmf && !header) {
1137 timestamp_ = dtmf_event->timestamp;
1138 } else {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001139 if (!header) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001140 LOG(LS_ERROR) << "Packet missing where it shouldn't.";
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001141 return -1;
1142 }
1143 timestamp_ = header->timestamp;
ossu108ecec2016-07-08 08:45:18 -07001144 if (*operation == kRfc3389CngNoPacket &&
1145 decoder_database_->IsComfortNoise(header->payloadType)) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001146 // Change decision to CNG packet, since we do have a CNG packet, but it
1147 // was considered too early to use. Now, use it anyway.
1148 *operation = kRfc3389Cng;
1149 } else if (*operation != kRfc3389Cng) {
1150 *operation = kNormal;
1151 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001152 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001153 // Adjust |sync_buffer_| timestamp before setting |end_timestamp| to the
1154 // new value.
1155 sync_buffer_->IncreaseEndTimestamp(timestamp_ - end_timestamp);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001156 end_timestamp = timestamp_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001157 new_codec_ = false;
1158 decision_logic_->SoftReset();
1159 buffer_level_filter_->Reset();
1160 delay_manager_->Reset();
1161 stats_.ResetMcu();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001162 }
1163
Peter Kastingdce40cf2015-08-24 14:52:23 -07001164 size_t required_samples = output_size_samples_;
1165 const size_t samples_10_ms = static_cast<size_t>(80 * fs_mult_);
1166 const size_t samples_20_ms = 2 * samples_10_ms;
1167 const size_t samples_30_ms = 3 * samples_10_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001168
1169 switch (*operation) {
1170 case kExpand: {
1171 timestamp_ = end_timestamp;
1172 return 0;
1173 }
1174 case kRfc3389CngNoPacket:
1175 case kCodecInternalCng: {
1176 return 0;
1177 }
1178 case kDtmf: {
1179 // TODO(hlundin): Write test for this.
1180 // Update timestamp.
1181 timestamp_ = end_timestamp;
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001182 const uint64_t generated_noise_samples =
1183 generated_noise_stopwatch_
1184 ? generated_noise_stopwatch_->ElapsedTicks() *
1185 output_size_samples_ +
1186 decision_logic_->noise_fast_forward()
1187 : 0;
1188 if (generated_noise_samples > 0 && last_mode_ != kModeDtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001189 // Make a jump in timestamp due to the recently played comfort noise.
Peter Kastingb7e50542015-06-11 12:55:50 -07001190 uint32_t timestamp_jump =
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001191 static_cast<uint32_t>(generated_noise_samples);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001192 sync_buffer_->IncreaseEndTimestamp(timestamp_jump);
1193 timestamp_ += timestamp_jump;
1194 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001195 return 0;
1196 }
Henrik Lundincf808d22015-05-27 14:33:29 +02001197 case kAccelerate:
1198 case kFastAccelerate: {
1199 // In order to do an accelerate we need at least 30 ms of audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001200 if (samples_left >= static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001201 // Already have enough data, so we do not need to extract any more.
1202 decision_logic_->set_sample_memory(samples_left);
1203 decision_logic_->set_prev_time_scale(true);
1204 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001205 } else if (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001206 decoder_frame_length_ >= samples_30_ms) {
1207 // Avoid decoding more data as it might overflow the playout buffer.
1208 *operation = kNormal;
1209 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001210 } else if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001211 decoder_frame_length_ < samples_30_ms) {
1212 // Build up decoded data by decoding at least 20 ms of audio data. Do
1213 // not perform accelerate yet, but wait until we only need to do one
1214 // decoding.
1215 required_samples = 2 * output_size_samples_;
1216 *operation = kNormal;
1217 }
1218 // If none of the above is true, we have one of two possible situations:
1219 // (1) 20 ms <= samples_left < 30 ms and decoder_frame_length_ < 30 ms; or
1220 // (2) samples_left < 10 ms and decoder_frame_length_ >= 30 ms.
1221 // In either case, we move on with the accelerate decision, and decode one
1222 // frame now.
1223 break;
1224 }
1225 case kPreemptiveExpand: {
1226 // In order to do a preemptive expand we need at least 30 ms of decoded
1227 // audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001228 if ((samples_left >= static_cast<int>(samples_30_ms)) ||
1229 (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001230 decoder_frame_length_ >= samples_30_ms)) {
1231 // Already have enough data, so we do not need to extract any more.
1232 // Or, avoid decoding more data as it might overflow the playout buffer.
1233 // Still try preemptive expand, though.
1234 decision_logic_->set_sample_memory(samples_left);
1235 decision_logic_->set_prev_time_scale(true);
1236 return 0;
1237 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07001238 if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001239 decoder_frame_length_ < samples_30_ms) {
1240 // Build up decoded data by decoding at least 20 ms of audio data.
1241 // Still try to perform preemptive expand.
1242 required_samples = 2 * output_size_samples_;
1243 }
1244 // Move on with the preemptive expand decision.
1245 break;
1246 }
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001247 case kMerge: {
1248 required_samples =
1249 std::max(merge_->RequiredFutureSamples(), required_samples);
1250 break;
1251 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001252 default: {
1253 // Do nothing.
1254 }
1255 }
1256
1257 // Get packets from buffer.
1258 int extracted_samples = 0;
1259 if (header &&
1260 *operation != kAlternativePlc &&
1261 *operation != kAlternativePlcIncreaseTimestamp &&
1262 *operation != kAudioRepetition &&
1263 *operation != kAudioRepetitionIncreaseTimestamp) {
1264 sync_buffer_->IncreaseEndTimestamp(header->timestamp - end_timestamp);
1265 if (decision_logic_->CngOff()) {
1266 // Adjustment of timestamp only corresponds to an actual packet loss
1267 // if comfort noise is not played. If comfort noise was just played,
1268 // this adjustment of timestamp is only done to get back in sync with the
1269 // stream timestamp; no loss to report.
1270 stats_.LostSamples(header->timestamp - end_timestamp);
1271 }
1272
1273 if (*operation != kRfc3389Cng) {
1274 // We are about to decode and use a non-CNG packet.
1275 decision_logic_->SetCngOff();
1276 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001277
1278 extracted_samples = ExtractPackets(required_samples, packet_list);
1279 if (extracted_samples < 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001280 return kPacketBufferCorruption;
1281 }
1282 }
1283
Henrik Lundincf808d22015-05-27 14:33:29 +02001284 if (*operation == kAccelerate || *operation == kFastAccelerate ||
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001285 *operation == kPreemptiveExpand) {
1286 decision_logic_->set_sample_memory(samples_left + extracted_samples);
1287 decision_logic_->set_prev_time_scale(true);
1288 }
1289
Henrik Lundincf808d22015-05-27 14:33:29 +02001290 if (*operation == kAccelerate || *operation == kFastAccelerate) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001291 // Check that we have enough data (30ms) to do accelerate.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001292 if (extracted_samples + samples_left < static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001293 // TODO(hlundin): Write test for this.
1294 // Not enough, do normal operation instead.
1295 *operation = kNormal;
1296 }
1297 }
1298
1299 timestamp_ = end_timestamp;
1300 return 0;
1301}
1302
1303int NetEqImpl::Decode(PacketList* packet_list, Operations* operation,
1304 int* decoded_length,
1305 AudioDecoder::SpeechType* speech_type) {
1306 *speech_type = AudioDecoder::kSpeech;
minyuel6d92bf52015-09-23 15:20:39 +02001307
1308 // When packet_list is empty, we may be in kCodecInternalCng mode, and for
1309 // that we use current active decoder.
1310 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1311
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001312 if (!packet_list->empty()) {
1313 const Packet* packet = packet_list->front();
pkasting@chromium.org0e81fdf2015-02-02 23:54:03 +00001314 uint8_t payload_type = packet->header.payloadType;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001315 if (!decoder_database_->IsComfortNoise(payload_type)) {
1316 decoder = decoder_database_->GetDecoder(payload_type);
1317 assert(decoder);
1318 if (!decoder) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001319 LOG(LS_WARNING) << "Unknown payload type "
1320 << static_cast<int>(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001321 PacketBuffer::DeleteAllPackets(packet_list);
1322 return kDecoderNotFound;
1323 }
1324 bool decoder_changed;
1325 decoder_database_->SetActiveDecoder(payload_type, &decoder_changed);
1326 if (decoder_changed) {
1327 // We have a new decoder. Re-init some values.
1328 const DecoderDatabase::DecoderInfo* decoder_info = decoder_database_
1329 ->GetDecoderInfo(payload_type);
1330 assert(decoder_info);
1331 if (!decoder_info) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001332 LOG(LS_WARNING) << "Unknown payload type "
1333 << static_cast<int>(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001334 PacketBuffer::DeleteAllPackets(packet_list);
1335 return kDecoderNotFound;
1336 }
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001337 // If sampling rate or number of channels has changed, we need to make
1338 // a reset.
kwibergc0f2dcf2016-05-31 06:28:03 -07001339 if (decoder_info->SampleRateHz() != fs_hz_ ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001340 decoder->Channels() != algorithm_buffer_->Channels()) {
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001341 // TODO(tlegrand): Add unittest to cover this event.
kwibergc0f2dcf2016-05-31 06:28:03 -07001342 SetSampleRateAndChannels(decoder_info->SampleRateHz(),
1343 decoder->Channels());
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001344 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001345 sync_buffer_->set_end_timestamp(timestamp_);
1346 playout_timestamp_ = timestamp_;
1347 }
1348 }
1349 }
1350
1351 if (reset_decoder_) {
1352 // TODO(hlundin): Write test for this.
Karl Wiberg43766482015-08-27 15:22:11 +02001353 if (decoder)
1354 decoder->Reset();
1355
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001356 // Reset comfort noise decoder.
ossu97ba30e2016-04-25 07:55:58 -07001357 ComfortNoiseDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02001358 if (cng_decoder)
1359 cng_decoder->Reset();
1360
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001361 reset_decoder_ = false;
1362 }
1363
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001364 *decoded_length = 0;
1365 // Update codec-internal PLC state.
1366 if ((*operation == kMerge) && decoder && decoder->HasDecodePlc()) {
1367 decoder->DecodePlc(1, &decoded_buffer_[*decoded_length]);
1368 }
1369
minyuel6d92bf52015-09-23 15:20:39 +02001370 int return_value;
1371 if (*operation == kCodecInternalCng) {
1372 RTC_DCHECK(packet_list->empty());
1373 return_value = DecodeCng(decoder, decoded_length, speech_type);
1374 } else {
1375 return_value = DecodeLoop(packet_list, *operation, decoder,
1376 decoded_length, speech_type);
1377 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001378
1379 if (*decoded_length < 0) {
1380 // Error returned from the decoder.
1381 *decoded_length = 0;
Peter Kastingb7e50542015-06-11 12:55:50 -07001382 sync_buffer_->IncreaseEndTimestamp(
1383 static_cast<uint32_t>(decoder_frame_length_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001384 int error_code = 0;
1385 if (decoder)
1386 error_code = decoder->ErrorCode();
1387 if (error_code != 0) {
1388 // Got some error code from the decoder.
1389 decoder_error_code_ = error_code;
1390 return_value = kDecoderErrorCode;
Henrik Lundind67a2192015-08-03 12:54:37 +02001391 LOG(LS_WARNING) << "Decoder returned error code: " << error_code;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001392 } else {
1393 // Decoder does not implement error codes. Return generic error.
1394 return_value = kOtherDecoderError;
Henrik Lundind67a2192015-08-03 12:54:37 +02001395 LOG(LS_WARNING) << "Decoder error (no error code)";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001396 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001397 *operation = kExpand; // Do expansion to get data instead.
1398 }
1399 if (*speech_type != AudioDecoder::kComfortNoise) {
1400 // Don't increment timestamp if codec returned CNG speech type
1401 // since in this case, the we will increment the CNGplayedTS counter.
1402 // Increase with number of samples per channel.
1403 assert(*decoded_length == 0 ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001404 (decoder && decoder->Channels() == sync_buffer_->Channels()));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001405 sync_buffer_->IncreaseEndTimestamp(
1406 *decoded_length / static_cast<int>(sync_buffer_->Channels()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001407 }
1408 return return_value;
1409}
1410
minyuel6d92bf52015-09-23 15:20:39 +02001411int NetEqImpl::DecodeCng(AudioDecoder* decoder, int* decoded_length,
1412 AudioDecoder::SpeechType* speech_type) {
1413 if (!decoder) {
1414 // This happens when active decoder is not defined.
1415 *decoded_length = -1;
1416 return 0;
1417 }
1418
1419 while (*decoded_length < rtc::checked_cast<int>(output_size_samples_)) {
1420 const int length = decoder->Decode(
1421 nullptr, 0, fs_hz_,
1422 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1423 &decoded_buffer_[*decoded_length], speech_type);
1424 if (length > 0) {
1425 *decoded_length += length;
minyuel6d92bf52015-09-23 15:20:39 +02001426 } else {
1427 // Error.
1428 LOG(LS_WARNING) << "Failed to decode CNG";
1429 *decoded_length = -1;
1430 break;
1431 }
1432 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1433 // Guard against overflow.
1434 LOG(LS_WARNING) << "Decoded too much CNG.";
1435 return kDecodedTooMuch;
1436 }
1437 }
1438 return 0;
1439}
1440
1441int NetEqImpl::DecodeLoop(PacketList* packet_list, const Operations& operation,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001442 AudioDecoder* decoder, int* decoded_length,
1443 AudioDecoder::SpeechType* speech_type) {
1444 Packet* packet = NULL;
1445 if (!packet_list->empty()) {
1446 packet = packet_list->front();
1447 }
minyuel6d92bf52015-09-23 15:20:39 +02001448
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001449 // Do decoding.
1450 while (packet &&
1451 !decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1452 assert(decoder); // At this point, we must have a decoder object.
1453 // The number of channels in the |sync_buffer_| should be the same as the
1454 // number decoder channels.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001455 assert(sync_buffer_->Channels() == decoder->Channels());
1456 assert(decoded_buffer_length_ >= kMaxFrameSize * decoder->Channels());
minyuel6d92bf52015-09-23 15:20:39 +02001457 assert(operation == kNormal || operation == kAccelerate ||
1458 operation == kFastAccelerate || operation == kMerge ||
1459 operation == kPreemptiveExpand);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001460 packet_list->pop_front();
ossudc431ce2016-08-31 08:51:13 -07001461 const size_t payload_length = packet->payload.size();
Peter Kasting36b7cc32015-06-11 19:57:18 -07001462 int decode_length;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +00001463 if (packet->sync_packet) {
1464 // Decode to silence with the same frame size as the last decode.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001465 memset(&decoded_buffer_[*decoded_length], 0,
1466 decoder_frame_length_ * decoder->Channels() *
1467 sizeof(decoded_buffer_[0]));
Peter Kastingdce40cf2015-08-24 14:52:23 -07001468 decode_length = rtc::checked_cast<int>(decoder_frame_length_);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +00001469 } else if (!packet->primary) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001470 // This is a redundant payload; call the special decoder method.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001471 decode_length = decoder->DecodeRedundant(
ossudc431ce2016-08-31 08:51:13 -07001472 packet->payload.data(), packet->payload.size(), fs_hz_,
minyue@webrtc.org7f7d7e32015-03-16 12:30:37 +00001473 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001474 &decoded_buffer_[*decoded_length], speech_type);
1475 } else {
ossudc431ce2016-08-31 08:51:13 -07001476 decode_length = decoder->Decode(
1477 packet->payload.data(), packet->payload.size(), fs_hz_,
1478 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1479 &decoded_buffer_[*decoded_length], speech_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001480 }
1481
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001482 delete packet;
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001483 packet = NULL;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001484 if (decode_length > 0) {
1485 *decoded_length += decode_length;
1486 // Update |decoder_frame_length_| with number of samples per channel.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001487 decoder_frame_length_ =
Peter Kastingdce40cf2015-08-24 14:52:23 -07001488 static_cast<size_t>(decode_length) / decoder->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001489 } else if (decode_length < 0) {
1490 // Error.
Henrik Lundind67a2192015-08-03 12:54:37 +02001491 LOG(LS_WARNING) << "Decode " << decode_length << " " << payload_length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001492 *decoded_length = -1;
1493 PacketBuffer::DeleteAllPackets(packet_list);
1494 break;
1495 }
1496 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1497 // Guard against overflow.
Henrik Lundind67a2192015-08-03 12:54:37 +02001498 LOG(LS_WARNING) << "Decoded too much.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001499 PacketBuffer::DeleteAllPackets(packet_list);
1500 return kDecodedTooMuch;
1501 }
1502 if (!packet_list->empty()) {
1503 packet = packet_list->front();
1504 } else {
1505 packet = NULL;
1506 }
1507 } // End of decode loop.
1508
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001509 // If the list is not empty at this point, either a decoding error terminated
1510 // the while-loop, or list must hold exactly one CNG packet.
1511 assert(packet_list->empty() || *decoded_length < 0 ||
1512 (packet_list->size() == 1 && packet &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001513 decoder_database_->IsComfortNoise(packet->header.payloadType)));
1514 return 0;
1515}
1516
1517void NetEqImpl::DoNormal(const int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001518 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001519 assert(normal_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001520 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001521 normal_->Process(decoded_buffer, decoded_length, last_mode_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001522 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001523 if (decoded_length != 0) {
1524 last_mode_ = kModeNormal;
1525 }
1526
1527 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1528 if ((speech_type == AudioDecoder::kComfortNoise)
1529 || ((last_mode_ == kModeCodecInternalCng)
1530 && (decoded_length == 0))) {
1531 // TODO(hlundin): Remove second part of || statement above.
1532 last_mode_ = kModeCodecInternalCng;
1533 }
1534
1535 if (!play_dtmf) {
1536 dtmf_tone_generator_->Reset();
1537 }
1538}
1539
1540void NetEqImpl::DoMerge(int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001541 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001542 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001543 assert(merge_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001544 size_t new_length = merge_->Process(decoded_buffer, decoded_length,
1545 mute_factor_array_.get(),
1546 algorithm_buffer_.get());
1547 size_t expand_length_correction = new_length -
1548 decoded_length / algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001549
1550 // Update in-call and post-call statistics.
1551 if (expand_->MuteFactor(0) == 0) {
1552 // Expand generates only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001553 stats_.ExpandedNoiseSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001554 } else {
1555 // Expansion generates more than only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001556 stats_.ExpandedVoiceSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001557 }
1558
1559 last_mode_ = kModeMerge;
1560 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1561 if (speech_type == AudioDecoder::kComfortNoise) {
1562 last_mode_ = kModeCodecInternalCng;
1563 }
1564 expand_->Reset();
1565 if (!play_dtmf) {
1566 dtmf_tone_generator_->Reset();
1567 }
1568}
1569
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001570int NetEqImpl::DoExpand(bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001571 while ((sync_buffer_->FutureLength() - expand_->overlap_length()) <
Peter Kastingdce40cf2015-08-24 14:52:23 -07001572 output_size_samples_) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001573 algorithm_buffer_->Clear();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001574 int return_value = expand_->Process(algorithm_buffer_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001575 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001576
1577 // Update in-call and post-call statistics.
1578 if (expand_->MuteFactor(0) == 0) {
1579 // Expand operation generates only noise.
1580 stats_.ExpandedNoiseSamples(length);
1581 } else {
1582 // Expand operation generates more than only noise.
1583 stats_.ExpandedVoiceSamples(length);
1584 }
1585
1586 last_mode_ = kModeExpand;
1587
1588 if (return_value < 0) {
1589 return return_value;
1590 }
1591
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001592 sync_buffer_->PushBack(*algorithm_buffer_);
1593 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001594 }
1595 if (!play_dtmf) {
1596 dtmf_tone_generator_->Reset();
1597 }
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001598
1599 if (!generated_noise_stopwatch_) {
1600 // Start a new stopwatch since we may be covering for a lost CNG packet.
1601 generated_noise_stopwatch_ = tick_timer_->GetNewStopwatch();
1602 }
1603
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001604 return 0;
1605}
1606
Henrik Lundincf808d22015-05-27 14:33:29 +02001607int NetEqImpl::DoAccelerate(int16_t* decoded_buffer,
1608 size_t decoded_length,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001609 AudioDecoder::SpeechType speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +02001610 bool play_dtmf,
1611 bool fast_accelerate) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001612 const size_t required_samples =
1613 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001614 size_t borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001615 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001616 size_t decoded_length_per_channel = decoded_length / num_channels;
1617 if (decoded_length_per_channel < required_samples) {
1618 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001619 borrowed_samples_per_channel = static_cast<int>(required_samples -
1620 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001621 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1622 decoded_buffer,
1623 sizeof(int16_t) * decoded_length);
1624 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1625 decoded_buffer);
1626 decoded_length = required_samples * num_channels;
1627 }
1628
Peter Kastingdce40cf2015-08-24 14:52:23 -07001629 size_t samples_removed;
Henrik Lundincf808d22015-05-27 14:33:29 +02001630 Accelerate::ReturnCodes return_code =
1631 accelerate_->Process(decoded_buffer, decoded_length, fast_accelerate,
1632 algorithm_buffer_.get(), &samples_removed);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001633 stats_.AcceleratedSamples(samples_removed);
1634 switch (return_code) {
1635 case Accelerate::kSuccess:
1636 last_mode_ = kModeAccelerateSuccess;
1637 break;
1638 case Accelerate::kSuccessLowEnergy:
1639 last_mode_ = kModeAccelerateLowEnergy;
1640 break;
1641 case Accelerate::kNoStretch:
1642 last_mode_ = kModeAccelerateFail;
1643 break;
1644 case Accelerate::kError:
1645 // TODO(hlundin): Map to kModeError instead?
1646 last_mode_ = kModeAccelerateFail;
1647 return kAccelerateError;
1648 }
1649
1650 if (borrowed_samples_per_channel > 0) {
1651 // Copy borrowed samples back to the |sync_buffer_|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001652 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001653 if (length < borrowed_samples_per_channel) {
1654 // This destroys the beginning of the buffer, but will not cause any
1655 // problems.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001656 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001657 sync_buffer_->Size() -
1658 borrowed_samples_per_channel);
1659 sync_buffer_->PushFrontZeros(borrowed_samples_per_channel - length);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001660 algorithm_buffer_->PopFront(length);
1661 assert(algorithm_buffer_->Empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001662 } else {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001663 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001664 borrowed_samples_per_channel,
1665 sync_buffer_->Size() -
1666 borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001667 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001668 }
1669 }
1670
1671 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1672 if (speech_type == AudioDecoder::kComfortNoise) {
1673 last_mode_ = kModeCodecInternalCng;
1674 }
1675 if (!play_dtmf) {
1676 dtmf_tone_generator_->Reset();
1677 }
1678 expand_->Reset();
1679 return 0;
1680}
1681
1682int NetEqImpl::DoPreemptiveExpand(int16_t* decoded_buffer,
1683 size_t decoded_length,
1684 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001685 bool play_dtmf) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001686 const size_t required_samples =
1687 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001688 size_t num_channels = algorithm_buffer_->Channels();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001689 size_t borrowed_samples_per_channel = 0;
1690 size_t old_borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001691 size_t decoded_length_per_channel = decoded_length / num_channels;
1692 if (decoded_length_per_channel < required_samples) {
1693 // Must move data from the |sync_buffer_| in order to get 30 ms.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001694 borrowed_samples_per_channel =
1695 required_samples - decoded_length_per_channel;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001696 // Calculate how many of these were already played out.
Peter Kastingf045e4d2015-06-10 21:15:38 -07001697 old_borrowed_samples_per_channel =
Peter Kastingdce40cf2015-08-24 14:52:23 -07001698 (borrowed_samples_per_channel > sync_buffer_->FutureLength()) ?
1699 (borrowed_samples_per_channel - sync_buffer_->FutureLength()) : 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001700 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1701 decoded_buffer,
1702 sizeof(int16_t) * decoded_length);
1703 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1704 decoded_buffer);
1705 decoded_length = required_samples * num_channels;
1706 }
1707
Peter Kastingdce40cf2015-08-24 14:52:23 -07001708 size_t samples_added;
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001709 PreemptiveExpand::ReturnCodes return_code = preemptive_expand_->Process(
Peter Kastingdce40cf2015-08-24 14:52:23 -07001710 decoded_buffer, decoded_length,
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001711 old_borrowed_samples_per_channel,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001712 algorithm_buffer_.get(), &samples_added);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001713 stats_.PreemptiveExpandedSamples(samples_added);
1714 switch (return_code) {
1715 case PreemptiveExpand::kSuccess:
1716 last_mode_ = kModePreemptiveExpandSuccess;
1717 break;
1718 case PreemptiveExpand::kSuccessLowEnergy:
1719 last_mode_ = kModePreemptiveExpandLowEnergy;
1720 break;
1721 case PreemptiveExpand::kNoStretch:
1722 last_mode_ = kModePreemptiveExpandFail;
1723 break;
1724 case PreemptiveExpand::kError:
1725 // TODO(hlundin): Map to kModeError instead?
1726 last_mode_ = kModePreemptiveExpandFail;
1727 return kPreemptiveExpandError;
1728 }
1729
1730 if (borrowed_samples_per_channel > 0) {
1731 // Copy borrowed samples back to the |sync_buffer_|.
1732 sync_buffer_->ReplaceAtIndex(
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001733 *algorithm_buffer_, borrowed_samples_per_channel,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001734 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001735 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001736 }
1737
1738 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1739 if (speech_type == AudioDecoder::kComfortNoise) {
1740 last_mode_ = kModeCodecInternalCng;
1741 }
1742 if (!play_dtmf) {
1743 dtmf_tone_generator_->Reset();
1744 }
1745 expand_->Reset();
1746 return 0;
1747}
1748
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001749int NetEqImpl::DoRfc3389Cng(PacketList* packet_list, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001750 if (!packet_list->empty()) {
1751 // Must have exactly one SID frame at this point.
1752 assert(packet_list->size() == 1);
1753 Packet* packet = packet_list->front();
1754 packet_list->pop_front();
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001755 if (!decoder_database_->IsComfortNoise(packet->header.payloadType)) {
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001756 LOG(LS_ERROR) << "Trying to decode non-CNG payload as CNG.";
1757 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001758 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001759 // UpdateParameters() deletes |packet|.
1760 if (comfort_noise_->UpdateParameters(packet) ==
1761 ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001762 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001763 return -comfort_noise_->internal_error_code();
1764 }
1765 }
1766 int cn_return = comfort_noise_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001767 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001768 expand_->Reset();
1769 last_mode_ = kModeRfc3389Cng;
1770 if (!play_dtmf) {
1771 dtmf_tone_generator_->Reset();
1772 }
1773 if (cn_return == ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001774 decoder_error_code_ = comfort_noise_->internal_error_code();
1775 return kComfortNoiseErrorCode;
1776 } else if (cn_return == ComfortNoise::kUnknownPayloadType) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001777 return kUnknownRtpPayloadType;
1778 }
1779 return 0;
1780}
1781
minyuel6d92bf52015-09-23 15:20:39 +02001782void NetEqImpl::DoCodecInternalCng(const int16_t* decoded_buffer,
1783 size_t decoded_length) {
1784 RTC_DCHECK(normal_.get());
1785 RTC_DCHECK(mute_factor_array_.get());
1786 normal_->Process(decoded_buffer, decoded_length, last_mode_,
1787 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001788 last_mode_ = kModeCodecInternalCng;
1789 expand_->Reset();
1790}
1791
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001792int NetEqImpl::DoDtmf(const DtmfEvent& dtmf_event, bool* play_dtmf) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001793 // This block of the code and the block further down, handling |dtmf_switch|
1794 // are commented out. Otherwise playing out-of-band DTMF would fail in VoE
1795 // test, DtmfTest.ManualSuccessfullySendsOutOfBandTelephoneEvents. This is
1796 // equivalent to |dtmf_switch| always be false.
1797 //
1798 // See http://webrtc-codereview.appspot.com/1195004/ for discussion
1799 // On this issue. This change might cause some glitches at the point of
1800 // switch from audio to DTMF. Issue 1545 is filed to track this.
1801 //
1802 // bool dtmf_switch = false;
1803 // if ((last_mode_ != kModeDtmf) && dtmf_tone_generator_->initialized()) {
1804 // // Special case; see below.
1805 // // We must catch this before calling Generate, since |initialized| is
1806 // // modified in that call.
1807 // dtmf_switch = true;
1808 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001809
1810 int dtmf_return_value = 0;
1811 if (!dtmf_tone_generator_->initialized()) {
1812 // Initialize if not already done.
1813 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1814 dtmf_event.volume);
1815 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001816
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001817 if (dtmf_return_value == 0) {
1818 // Generate DTMF signal.
1819 dtmf_return_value = dtmf_tone_generator_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001820 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001821 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001822
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001823 if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001824 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001825 return dtmf_return_value;
1826 }
1827
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001828 // if (dtmf_switch) {
1829 // // This is the special case where the previous operation was DTMF
1830 // // overdub, but the current instruction is "regular" DTMF. We must make
1831 // // sure that the DTMF does not have any discontinuities. The first DTMF
1832 // // sample that we generate now must be played out immediately, therefore
1833 // // it must be copied to the speech buffer.
1834 // // TODO(hlundin): This code seems incorrect. (Legacy.) Write test and
1835 // // verify correct operation.
1836 // assert(false);
1837 // // Must generate enough data to replace all of the |sync_buffer_|
1838 // // "future".
1839 // int required_length = sync_buffer_->FutureLength();
1840 // assert(dtmf_tone_generator_->initialized());
1841 // dtmf_return_value = dtmf_tone_generator_->Generate(required_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001842 // algorithm_buffer_);
1843 // assert((size_t) required_length == algorithm_buffer_->Size());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001844 // if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001845 // algorithm_buffer_->Zeros(output_size_samples_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001846 // return dtmf_return_value;
1847 // }
1848 //
1849 // // Overwrite the "future" part of the speech buffer with the new DTMF
1850 // // data.
1851 // // TODO(hlundin): It seems that this overwriting has gone lost.
1852 // // Not adapted for multi-channel yet.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001853 // assert(algorithm_buffer_->Channels() == 1);
1854 // if (algorithm_buffer_->Channels() != 1) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001855 // LOG(LS_WARNING) << "DTMF not supported for more than one channel";
1856 // return kStereoNotSupported;
1857 // }
1858 // // Shuffle the remaining data to the beginning of algorithm buffer.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001859 // algorithm_buffer_->PopFront(sync_buffer_->FutureLength());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001860 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001861
Peter Kastingb7e50542015-06-11 12:55:50 -07001862 sync_buffer_->IncreaseEndTimestamp(
1863 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001864 expand_->Reset();
1865 last_mode_ = kModeDtmf;
1866
1867 // Set to false because the DTMF is already in the algorithm buffer.
1868 *play_dtmf = false;
1869 return 0;
1870}
1871
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001872void NetEqImpl::DoAlternativePlc(bool increase_timestamp) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001873 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001874 size_t length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001875 if (decoder && decoder->HasDecodePlc()) {
1876 // Use the decoder's packet-loss concealment.
1877 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1878 int16_t decoded_buffer[kMaxFrameSize];
1879 length = decoder->DecodePlc(1, decoded_buffer);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001880 if (length > 0)
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001881 algorithm_buffer_->PushBackInterleaved(decoded_buffer, length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001882 } else {
1883 // Do simple zero-stuffing.
1884 length = output_size_samples_;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001885 algorithm_buffer_->Zeros(length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001886 // By not advancing the timestamp, NetEq inserts samples.
1887 stats_.AddZeros(length);
1888 }
1889 if (increase_timestamp) {
Peter Kastingb7e50542015-06-11 12:55:50 -07001890 sync_buffer_->IncreaseEndTimestamp(static_cast<uint32_t>(length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001891 }
1892 expand_->Reset();
1893}
1894
1895int NetEqImpl::DtmfOverdub(const DtmfEvent& dtmf_event, size_t num_channels,
1896 int16_t* output) const {
1897 size_t out_index = 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001898 size_t overdub_length = output_size_samples_; // Default value.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001899
1900 if (sync_buffer_->dtmf_index() > sync_buffer_->next_index()) {
1901 // Special operation for transition from "DTMF only" to "DTMF overdub".
1902 out_index = std::min(
1903 sync_buffer_->dtmf_index() - sync_buffer_->next_index(),
Peter Kastingdce40cf2015-08-24 14:52:23 -07001904 output_size_samples_);
1905 overdub_length = output_size_samples_ - out_index;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001906 }
1907
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001908 AudioMultiVector dtmf_output(num_channels);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001909 int dtmf_return_value = 0;
1910 if (!dtmf_tone_generator_->initialized()) {
1911 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1912 dtmf_event.volume);
1913 }
1914 if (dtmf_return_value == 0) {
1915 dtmf_return_value = dtmf_tone_generator_->Generate(overdub_length,
1916 &dtmf_output);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001917 assert(overdub_length == dtmf_output.Size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001918 }
1919 dtmf_output.ReadInterleaved(overdub_length, &output[out_index]);
1920 return dtmf_return_value < 0 ? dtmf_return_value : 0;
1921}
1922
Peter Kastingdce40cf2015-08-24 14:52:23 -07001923int NetEqImpl::ExtractPackets(size_t required_samples,
1924 PacketList* packet_list) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001925 bool first_packet = true;
1926 uint8_t prev_payload_type = 0;
1927 uint32_t prev_timestamp = 0;
1928 uint16_t prev_sequence_number = 0;
1929 bool next_packet_available = false;
1930
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001931 const RTPHeader* header = packet_buffer_->NextRtpHeader();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001932 assert(header);
1933 if (!header) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001934 LOG(LS_ERROR) << "Packet buffer unexpectedly empty.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001935 return -1;
1936 }
turaj@webrtc.org7df97062013-08-02 18:07:13 +00001937 uint32_t first_timestamp = header->timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001938 int extracted_samples = 0;
1939
1940 // Packet extraction loop.
1941 do {
1942 timestamp_ = header->timestamp;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001943 size_t discard_count = 0;
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001944 Packet* packet = packet_buffer_->GetNextPacket(&discard_count);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001945 // |header| may be invalid after the |packet_buffer_| operation.
1946 header = NULL;
1947 if (!packet) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001948 LOG(LS_ERROR) << "Should always be able to extract a packet here";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001949 assert(false); // Should always be able to extract a packet here.
1950 return -1;
1951 }
1952 stats_.PacketsDiscarded(discard_count);
henrik.lundin84f8cd62016-04-26 07:45:16 -07001953 stats_.StoreWaitingTime(packet->waiting_time->ElapsedMs());
ossudc431ce2016-08-31 08:51:13 -07001954 assert(!packet->payload.empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001955 packet_list->push_back(packet); // Store packet in list.
1956
1957 if (first_packet) {
1958 first_packet = false;
henrik.lundin48ed9302015-10-29 05:36:24 -07001959 if (nack_enabled_) {
1960 RTC_DCHECK(nack_);
1961 // TODO(henrik.lundin): Should we update this for all decoded packets?
1962 nack_->UpdateLastDecodedPacket(packet->header.sequenceNumber,
1963 packet->header.timestamp);
1964 }
1965 prev_sequence_number = packet->header.sequenceNumber;
1966 prev_timestamp = packet->header.timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001967 prev_payload_type = packet->header.payloadType;
1968 }
1969
1970 // Store number of extracted samples.
1971 int packet_duration = 0;
1972 AudioDecoder* decoder = decoder_database_->GetDecoder(
1973 packet->header.payloadType);
1974 if (decoder) {
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001975 if (packet->sync_packet) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001976 packet_duration = rtc::checked_cast<int>(decoder_frame_length_);
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001977 } else {
minyue@webrtc.org2c1bcf22015-02-17 10:17:09 +00001978 if (packet->primary) {
ossudc431ce2016-08-31 08:51:13 -07001979 packet_duration = decoder->PacketDuration(packet->payload.data(),
1980 packet->payload.size());
minyue@webrtc.org2c1bcf22015-02-17 10:17:09 +00001981 } else {
ossudc431ce2016-08-31 08:51:13 -07001982 packet_duration = decoder->PacketDurationRedundant(
1983 packet->payload.data(), packet->payload.size());
minyue@webrtc.org2c1bcf22015-02-17 10:17:09 +00001984 stats_.SecondaryDecodedSamples(packet_duration);
1985 }
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001986 }
ossu97ba30e2016-04-25 07:55:58 -07001987 } else if (!decoder_database_->IsComfortNoise(packet->header.payloadType)) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001988 LOG(LS_WARNING) << "Unknown payload type "
1989 << static_cast<int>(packet->header.payloadType);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001990 assert(false);
1991 }
1992 if (packet_duration <= 0) {
1993 // Decoder did not return a packet duration. Assume that the packet
1994 // contains the same number of samples as the previous one.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001995 packet_duration = rtc::checked_cast<int>(decoder_frame_length_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001996 }
1997 extracted_samples = packet->header.timestamp - first_timestamp +
1998 packet_duration;
1999
2000 // Check what packet is available next.
2001 header = packet_buffer_->NextRtpHeader();
2002 next_packet_available = false;
2003 if (header && prev_payload_type == header->payloadType) {
2004 int16_t seq_no_diff = header->sequenceNumber - prev_sequence_number;
Peter Kastingdce40cf2015-08-24 14:52:23 -07002005 size_t ts_diff = header->timestamp - prev_timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002006 if (seq_no_diff == 1 ||
2007 (seq_no_diff == 0 && ts_diff == decoder_frame_length_)) {
2008 // The next sequence number is available, or the next part of a packet
2009 // that was split into pieces upon insertion.
2010 next_packet_available = true;
2011 }
2012 prev_sequence_number = header->sequenceNumber;
2013 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07002014 } while (extracted_samples < rtc::checked_cast<int>(required_samples) &&
2015 next_packet_available);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002016
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00002017 if (extracted_samples > 0) {
2018 // Delete old packets only when we are going to decode something. Otherwise,
2019 // we could end up in the situation where we never decode anything, since
2020 // all incoming packets are considered too old but the buffer will also
2021 // never be flooded and flushed.
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00002022 packet_buffer_->DiscardAllOldPackets(timestamp_);
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00002023 }
2024
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002025 return extracted_samples;
2026}
2027
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002028void NetEqImpl::UpdatePlcComponents(int fs_hz, size_t channels) {
2029 // Delete objects and create new ones.
2030 expand_.reset(expand_factory_->Create(background_noise_.get(),
2031 sync_buffer_.get(), &random_vector_,
Henrik Lundinbef77e22015-08-18 14:58:09 +02002032 &stats_, fs_hz, channels));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002033 merge_.reset(new Merge(fs_hz, channels, expand_.get(), sync_buffer_.get()));
2034}
2035
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002036void NetEqImpl::SetSampleRateAndChannels(int fs_hz, size_t channels) {
Henrik Lundind67a2192015-08-03 12:54:37 +02002037 LOG(LS_VERBOSE) << "SetSampleRateAndChannels " << fs_hz << " " << channels;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002038 // TODO(hlundin): Change to an enumerator and skip assert.
2039 assert(fs_hz == 8000 || fs_hz == 16000 || fs_hz == 32000 || fs_hz == 48000);
2040 assert(channels > 0);
2041
2042 fs_hz_ = fs_hz;
2043 fs_mult_ = fs_hz / 8000;
Peter Kastingdce40cf2015-08-24 14:52:23 -07002044 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002045 decoder_frame_length_ = 3 * output_size_samples_; // Initialize to 30ms.
2046
2047 last_mode_ = kModeNormal;
2048
2049 // Create a new array of mute factors and set all to 1.
2050 mute_factor_array_.reset(new int16_t[channels]);
2051 for (size_t i = 0; i < channels; ++i) {
2052 mute_factor_array_[i] = 16384; // 1.0 in Q14.
2053 }
2054
ossu97ba30e2016-04-25 07:55:58 -07002055 ComfortNoiseDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02002056 if (cng_decoder)
2057 cng_decoder->Reset();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002058
2059 // Reinit post-decode VAD with new sample rate.
2060 assert(vad_.get()); // Cannot be NULL here.
2061 vad_->Init();
2062
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002063 // Delete algorithm buffer and create a new one.
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00002064 algorithm_buffer_.reset(new AudioMultiVector(channels));
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002065
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002066 // Delete sync buffer and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002067 sync_buffer_.reset(new SyncBuffer(channels, kSyncBufferSize * fs_mult_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002068
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00002069 // Delete BackgroundNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002070 background_noise_.reset(new BackgroundNoise(channels));
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00002071 background_noise_->set_mode(background_noise_mode_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002072
2073 // Reset random vector.
2074 random_vector_.Reset();
2075
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002076 UpdatePlcComponents(fs_hz, channels);
2077
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002078 // Move index so that we create a small set of future samples (all 0).
2079 sync_buffer_->set_next_index(sync_buffer_->next_index() -
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002080 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002081
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002082 normal_.reset(new Normal(fs_hz, decoder_database_.get(), *background_noise_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002083 expand_.get()));
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +00002084 accelerate_.reset(
2085 accelerate_factory_->Create(fs_hz, channels, *background_noise_));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002086 preemptive_expand_.reset(preemptive_expand_factory_->Create(
Peter Kastingdce40cf2015-08-24 14:52:23 -07002087 fs_hz, channels, *background_noise_, expand_->overlap_length()));
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002088
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002089 // Delete ComfortNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002090 comfort_noise_.reset(new ComfortNoise(fs_hz, decoder_database_.get(),
2091 sync_buffer_.get()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002092
2093 // Verify that |decoded_buffer_| is long enough.
2094 if (decoded_buffer_length_ < kMaxFrameSize * channels) {
2095 // Reallocate to larger size.
2096 decoded_buffer_length_ = kMaxFrameSize * channels;
2097 decoded_buffer_.reset(new int16_t[decoded_buffer_length_]);
2098 }
2099
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002100 // Create DecisionLogic if it is not created yet, then communicate new sample
2101 // rate and output size to DecisionLogic object.
2102 if (!decision_logic_.get()) {
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002103 CreateDecisionLogic();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002104 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002105 decision_logic_->SetSampleRate(fs_hz_, output_size_samples_);
2106}
2107
henrik.lundin55480f52016-03-08 02:37:57 -08002108NetEqImpl::OutputType NetEqImpl::LastOutputType() {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002109 assert(vad_.get());
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002110 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002111 if (last_mode_ == kModeCodecInternalCng || last_mode_ == kModeRfc3389Cng) {
henrik.lundin55480f52016-03-08 02:37:57 -08002112 return OutputType::kCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002113 } else if (last_mode_ == kModeExpand && expand_->MuteFactor(0) == 0) {
2114 // Expand mode has faded down to background noise only (very long expand).
henrik.lundin55480f52016-03-08 02:37:57 -08002115 return OutputType::kPLCCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002116 } else if (last_mode_ == kModeExpand) {
henrik.lundin55480f52016-03-08 02:37:57 -08002117 return OutputType::kPLC;
wu@webrtc.org24301a62013-12-13 19:17:43 +00002118 } else if (vad_->running() && !vad_->active_speech()) {
henrik.lundin55480f52016-03-08 02:37:57 -08002119 return OutputType::kVadPassive;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002120 } else {
henrik.lundin55480f52016-03-08 02:37:57 -08002121 return OutputType::kNormalSpeech;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002122 }
2123}
2124
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002125void NetEqImpl::CreateDecisionLogic() {
Henrik Lundin47b17dc2016-05-10 10:20:59 +02002126 decision_logic_.reset(DecisionLogic::Create(
2127 fs_hz_, output_size_samples_, playout_mode_, decoder_database_.get(),
2128 *packet_buffer_.get(), delay_manager_.get(), buffer_level_filter_.get(),
2129 tick_timer_.get()));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002130}
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002131} // namespace webrtc