blob: 221b07c969f90992b74ba663491ffafb3005ae59 [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>
ossu61a208b2016-09-20 01:38:00 -070017#include <utility>
ossu97ba30e2016-04-25 07:55:58 -070018#include <vector>
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000019
henrik.lundin9c3efd02015-08-27 13:12:22 -070020#include "webrtc/base/checks.h"
Henrik Lundind67a2192015-08-03 12:54:37 +020021#include "webrtc/base/logging.h"
Tommid44c0772016-03-11 17:12:32 -080022#include "webrtc/base/safe_conversions.h"
kwibergac554ee2016-09-02 00:39:33 -070023#include "webrtc/base/sanitizer.h"
henrik.lundina689b442015-12-17 03:50:05 -080024#include "webrtc/base/trace_event.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000025#include "webrtc/common_audio/signal_processing/include/signal_processing_library.h"
kwiberg@webrtc.orge04a93b2014-12-09 10:12:53 +000026#include "webrtc/modules/audio_coding/codecs/audio_decoder.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000027#include "webrtc/modules/audio_coding/neteq/accelerate.h"
28#include "webrtc/modules/audio_coding/neteq/background_noise.h"
29#include "webrtc/modules/audio_coding/neteq/buffer_level_filter.h"
30#include "webrtc/modules/audio_coding/neteq/comfort_noise.h"
31#include "webrtc/modules/audio_coding/neteq/decision_logic.h"
32#include "webrtc/modules/audio_coding/neteq/decoder_database.h"
33#include "webrtc/modules/audio_coding/neteq/defines.h"
34#include "webrtc/modules/audio_coding/neteq/delay_manager.h"
35#include "webrtc/modules/audio_coding/neteq/delay_peak_detector.h"
36#include "webrtc/modules/audio_coding/neteq/dtmf_buffer.h"
37#include "webrtc/modules/audio_coding/neteq/dtmf_tone_generator.h"
38#include "webrtc/modules/audio_coding/neteq/expand.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000039#include "webrtc/modules/audio_coding/neteq/merge.h"
henrik.lundin91951862016-06-08 06:43:41 -070040#include "webrtc/modules/audio_coding/neteq/nack_tracker.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000041#include "webrtc/modules/audio_coding/neteq/normal.h"
42#include "webrtc/modules/audio_coding/neteq/packet_buffer.h"
43#include "webrtc/modules/audio_coding/neteq/packet.h"
44#include "webrtc/modules/audio_coding/neteq/payload_splitter.h"
45#include "webrtc/modules/audio_coding/neteq/post_decode_vad.h"
46#include "webrtc/modules/audio_coding/neteq/preemptive_expand.h"
47#include "webrtc/modules/audio_coding/neteq/sync_buffer.h"
henrik.lundined497212016-04-25 10:11:38 -070048#include "webrtc/modules/audio_coding/neteq/tick_timer.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000049#include "webrtc/modules/audio_coding/neteq/timestamp_scaler.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010050#include "webrtc/modules/include/module_common_types.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000051
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000052namespace webrtc {
53
ossue3525782016-05-25 07:37:43 -070054NetEqImpl::Dependencies::Dependencies(
55 const NetEq::Config& config,
56 const rtc::scoped_refptr<AudioDecoderFactory>& decoder_factory)
henrik.lundin1d9061e2016-04-26 12:19:34 -070057 : tick_timer(new TickTimer),
58 buffer_level_filter(new BufferLevelFilter),
ossue3525782016-05-25 07:37:43 -070059 decoder_database(new DecoderDatabase(decoder_factory)),
henrik.lundinf3933702016-04-28 01:53:52 -070060 delay_peak_detector(new DelayPeakDetector(tick_timer.get())),
henrik.lundin1d9061e2016-04-26 12:19:34 -070061 delay_manager(new DelayManager(config.max_packets_in_buffer,
henrik.lundin8f8c96d2016-04-28 23:19:20 -070062 delay_peak_detector.get(),
63 tick_timer.get())),
henrik.lundin1d9061e2016-04-26 12:19:34 -070064 dtmf_buffer(new DtmfBuffer(config.sample_rate_hz)),
65 dtmf_tone_generator(new DtmfToneGenerator),
66 packet_buffer(
67 new PacketBuffer(config.max_packets_in_buffer, tick_timer.get())),
68 payload_splitter(new PayloadSplitter),
69 timestamp_scaler(new TimestampScaler(*decoder_database)),
70 accelerate_factory(new AccelerateFactory),
71 expand_factory(new ExpandFactory),
72 preemptive_expand_factory(new PreemptiveExpandFactory) {}
73
74NetEqImpl::Dependencies::~Dependencies() = default;
75
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +000076NetEqImpl::NetEqImpl(const NetEq::Config& config,
henrik.lundin1d9061e2016-04-26 12:19:34 -070077 Dependencies&& deps,
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +000078 bool create_components)
henrik.lundin1d9061e2016-04-26 12:19:34 -070079 : tick_timer_(std::move(deps.tick_timer)),
80 buffer_level_filter_(std::move(deps.buffer_level_filter)),
81 decoder_database_(std::move(deps.decoder_database)),
82 delay_manager_(std::move(deps.delay_manager)),
83 delay_peak_detector_(std::move(deps.delay_peak_detector)),
84 dtmf_buffer_(std::move(deps.dtmf_buffer)),
85 dtmf_tone_generator_(std::move(deps.dtmf_tone_generator)),
86 packet_buffer_(std::move(deps.packet_buffer)),
87 payload_splitter_(std::move(deps.payload_splitter)),
88 timestamp_scaler_(std::move(deps.timestamp_scaler)),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000089 vad_(new PostDecodeVad()),
henrik.lundin1d9061e2016-04-26 12:19:34 -070090 expand_factory_(std::move(deps.expand_factory)),
91 accelerate_factory_(std::move(deps.accelerate_factory)),
92 preemptive_expand_factory_(std::move(deps.preemptive_expand_factory)),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000093 last_mode_(kModeNormal),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000094 decoded_buffer_length_(kMaxFrameSize),
95 decoded_buffer_(new int16_t[decoded_buffer_length_]),
96 playout_timestamp_(0),
97 new_codec_(false),
98 timestamp_(0),
99 reset_decoder_(false),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000100 ssrc_(0),
101 first_packet_(true),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000102 error_code_(0),
103 decoder_error_code_(0),
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +0000104 background_noise_mode_(config.background_noise_mode),
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000105 playout_mode_(config.playout_mode),
Henrik Lundincf808d22015-05-27 14:33:29 +0200106 enable_fast_accelerate_(config.enable_fast_accelerate),
henrik.lundin7a926812016-05-12 13:51:28 -0700107 nack_enabled_(false),
108 enable_muted_state_(config.enable_muted_state) {
Henrik Lundin905495c2015-05-25 16:58:41 +0200109 LOG(LS_INFO) << "NetEq config: " << config.ToString();
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +0000110 int fs = config.sample_rate_hz;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000111 if (fs != 8000 && fs != 16000 && fs != 32000 && fs != 48000) {
112 LOG(LS_ERROR) << "Sample rate " << fs << " Hz not supported. " <<
113 "Changing to 8000 Hz.";
114 fs = 8000;
115 }
henrik.lundin1d9061e2016-04-26 12:19:34 -0700116 delay_manager_->SetMaximumDelay(config.max_delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000117 fs_hz_ = fs;
118 fs_mult_ = fs / 8000;
henrik.lundind89814b2015-11-23 06:49:25 -0800119 last_output_sample_rate_hz_ = fs;
Peter Kastingdce40cf2015-08-24 14:52:23 -0700120 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000121 decoder_frame_length_ = 3 * output_size_samples_;
122 WebRtcSpl_Init();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000123 if (create_components) {
124 SetSampleRateAndChannels(fs, 1); // Default is 1 channel.
125 }
henrik.lundin9bc26672015-11-02 03:25:57 -0800126 RTC_DCHECK(!vad_->enabled());
127 if (config.enable_post_decode_vad) {
128 vad_->Enable();
129 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000130}
131
Henrik Lundind67a2192015-08-03 12:54:37 +0200132NetEqImpl::~NetEqImpl() = default;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000133
134int NetEqImpl::InsertPacket(const WebRtcRTPHeader& rtp_header,
kwibergee2bac22015-11-11 10:34:00 -0800135 rtc::ArrayView<const uint8_t> payload,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000136 uint32_t receive_timestamp) {
kwibergac554ee2016-09-02 00:39:33 -0700137 rtc::MsanCheckInitialized(payload);
henrik.lundina689b442015-12-17 03:50:05 -0800138 TRACE_EVENT0("webrtc", "NetEqImpl::InsertPacket");
Tommi9090e0b2016-01-20 13:39:36 +0100139 rtc::CritScope lock(&crit_sect_);
kwibergee2bac22015-11-11 10:34:00 -0800140 int error =
ossu17e3fa12016-09-08 04:52:55 -0700141 InsertPacketInternal(rtp_header, payload, receive_timestamp);
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000142 if (error != 0) {
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000143 error_code_ = error;
144 return kFail;
145 }
146 return kOK;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000147}
148
henrik.lundin500c04b2016-03-08 02:36:04 -0800149namespace {
150void SetAudioFrameActivityAndType(bool vad_enabled,
henrik.lundin55480f52016-03-08 02:37:57 -0800151 NetEqImpl::OutputType type,
henrik.lundin500c04b2016-03-08 02:36:04 -0800152 AudioFrame::VADActivity last_vad_activity,
153 AudioFrame* audio_frame) {
154 switch (type) {
henrik.lundin55480f52016-03-08 02:37:57 -0800155 case NetEqImpl::OutputType::kNormalSpeech: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800156 audio_frame->speech_type_ = AudioFrame::kNormalSpeech;
157 audio_frame->vad_activity_ = AudioFrame::kVadActive;
158 break;
159 }
henrik.lundin55480f52016-03-08 02:37:57 -0800160 case NetEqImpl::OutputType::kVadPassive: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800161 // This should only be reached if the VAD is enabled.
162 RTC_DCHECK(vad_enabled);
163 audio_frame->speech_type_ = AudioFrame::kNormalSpeech;
164 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
165 break;
166 }
henrik.lundin55480f52016-03-08 02:37:57 -0800167 case NetEqImpl::OutputType::kCNG: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800168 audio_frame->speech_type_ = AudioFrame::kCNG;
169 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
170 break;
171 }
henrik.lundin55480f52016-03-08 02:37:57 -0800172 case NetEqImpl::OutputType::kPLC: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800173 audio_frame->speech_type_ = AudioFrame::kPLC;
174 audio_frame->vad_activity_ = last_vad_activity;
175 break;
176 }
henrik.lundin55480f52016-03-08 02:37:57 -0800177 case NetEqImpl::OutputType::kPLCCNG: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800178 audio_frame->speech_type_ = AudioFrame::kPLCCNG;
179 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
180 break;
181 }
182 default:
183 RTC_NOTREACHED();
184 }
185 if (!vad_enabled) {
186 // Always set kVadUnknown when receive VAD is inactive.
187 audio_frame->vad_activity_ = AudioFrame::kVadUnknown;
188 }
189}
henrik.lundinbc89de32016-03-08 05:20:14 -0800190} // namespace
henrik.lundin500c04b2016-03-08 02:36:04 -0800191
henrik.lundin7a926812016-05-12 13:51:28 -0700192int NetEqImpl::GetAudio(AudioFrame* audio_frame, bool* muted) {
henrik.lundine1ca1672016-01-08 03:50:08 -0800193 TRACE_EVENT0("webrtc", "NetEqImpl::GetAudio");
Tommi9090e0b2016-01-20 13:39:36 +0100194 rtc::CritScope lock(&crit_sect_);
henrik.lundin7a926812016-05-12 13:51:28 -0700195 int error = GetAudioInternal(audio_frame, muted);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000196 if (error != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000197 error_code_ = error;
198 return kFail;
199 }
henrik.lundin5fac3f02016-08-24 11:18:49 -0700200 RTC_DCHECK_EQ(
201 audio_frame->sample_rate_hz_,
202 rtc::checked_cast<int>(audio_frame->samples_per_channel_ * 100));
henrik.lundin500c04b2016-03-08 02:36:04 -0800203 SetAudioFrameActivityAndType(vad_->enabled(), LastOutputType(),
204 last_vad_activity_, audio_frame);
205 last_vad_activity_ = audio_frame->vad_activity_;
henrik.lundin6d8e0112016-03-04 10:34:21 -0800206 last_output_sample_rate_hz_ = audio_frame->sample_rate_hz_;
henrik.lundind89814b2015-11-23 06:49:25 -0800207 RTC_DCHECK(last_output_sample_rate_hz_ == 8000 ||
208 last_output_sample_rate_hz_ == 16000 ||
209 last_output_sample_rate_hz_ == 32000 ||
210 last_output_sample_rate_hz_ == 48000)
211 << "Unexpected sample rate " << last_output_sample_rate_hz_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000212 return kOK;
213}
214
kwibergee1879c2015-10-29 06:20:28 -0700215int NetEqImpl::RegisterPayloadType(NetEqDecoder codec,
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800216 const std::string& name,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000217 uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100218 rtc::CritScope lock(&crit_sect_);
Henrik Lundind67a2192015-08-03 12:54:37 +0200219 LOG(LS_VERBOSE) << "RegisterPayloadType "
kwibergee1879c2015-10-29 06:20:28 -0700220 << static_cast<int>(rtp_payload_type) << " "
221 << static_cast<int>(codec);
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800222 int ret = decoder_database_->RegisterPayload(rtp_payload_type, codec, name);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000223 if (ret != DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000224 switch (ret) {
225 case DecoderDatabase::kInvalidRtpPayloadType:
226 error_code_ = kInvalidRtpPayloadType;
227 break;
228 case DecoderDatabase::kCodecNotSupported:
229 error_code_ = kCodecNotSupported;
230 break;
231 case DecoderDatabase::kDecoderExists:
232 error_code_ = kDecoderExists;
233 break;
234 default:
235 error_code_ = kOtherError;
236 }
237 return kFail;
238 }
239 return kOK;
240}
241
242int NetEqImpl::RegisterExternalDecoder(AudioDecoder* decoder,
kwibergee1879c2015-10-29 06:20:28 -0700243 NetEqDecoder codec,
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800244 const std::string& codec_name,
kwiberg342f7402016-06-16 03:18:00 -0700245 uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100246 rtc::CritScope lock(&crit_sect_);
Henrik Lundind67a2192015-08-03 12:54:37 +0200247 LOG(LS_VERBOSE) << "RegisterExternalDecoder "
kwibergee1879c2015-10-29 06:20:28 -0700248 << static_cast<int>(rtp_payload_type) << " "
249 << static_cast<int>(codec);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000250 if (!decoder) {
251 LOG(LS_ERROR) << "Cannot register external decoder with NULL pointer";
252 assert(false);
253 return kFail;
254 }
kwiberg342f7402016-06-16 03:18:00 -0700255 int ret = decoder_database_->InsertExternal(rtp_payload_type, codec,
256 codec_name, decoder);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000257 if (ret != DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000258 switch (ret) {
259 case DecoderDatabase::kInvalidRtpPayloadType:
260 error_code_ = kInvalidRtpPayloadType;
261 break;
262 case DecoderDatabase::kCodecNotSupported:
263 error_code_ = kCodecNotSupported;
264 break;
265 case DecoderDatabase::kDecoderExists:
266 error_code_ = kDecoderExists;
267 break;
268 case DecoderDatabase::kInvalidSampleRate:
269 error_code_ = kInvalidSampleRate;
270 break;
271 case DecoderDatabase::kInvalidPointer:
272 error_code_ = kInvalidPointer;
273 break;
274 default:
275 error_code_ = kOtherError;
276 }
277 return kFail;
278 }
279 return kOK;
280}
281
282int NetEqImpl::RemovePayloadType(uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100283 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000284 int ret = decoder_database_->Remove(rtp_payload_type);
285 if (ret == DecoderDatabase::kOK) {
ossu61a208b2016-09-20 01:38:00 -0700286 packet_buffer_->DiscardPacketsWithPayloadType(rtp_payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000287 return kOK;
288 } else if (ret == DecoderDatabase::kDecoderNotFound) {
289 error_code_ = kDecoderNotFound;
290 } else {
291 error_code_ = kOtherError;
292 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000293 return kFail;
294}
295
kwiberg6b19b562016-09-20 04:02:25 -0700296void NetEqImpl::RemoveAllPayloadTypes() {
297 rtc::CritScope lock(&crit_sect_);
298 decoder_database_->RemoveAll();
299}
300
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000301bool NetEqImpl::SetMinimumDelay(int delay_ms) {
Tommi9090e0b2016-01-20 13:39:36 +0100302 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000303 if (delay_ms >= 0 && delay_ms < 10000) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000304 assert(delay_manager_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000305 return delay_manager_->SetMinimumDelay(delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000306 }
307 return false;
308}
309
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000310bool NetEqImpl::SetMaximumDelay(int delay_ms) {
Tommi9090e0b2016-01-20 13:39:36 +0100311 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000312 if (delay_ms >= 0 && delay_ms < 10000) {
313 assert(delay_manager_.get());
314 return delay_manager_->SetMaximumDelay(delay_ms);
315 }
316 return false;
317}
318
319int NetEqImpl::LeastRequiredDelayMs() const {
Tommi9090e0b2016-01-20 13:39:36 +0100320 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000321 assert(delay_manager_.get());
322 return delay_manager_->least_required_delay_ms();
323}
324
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200325int NetEqImpl::SetTargetDelay() {
326 return kNotImplemented;
327}
328
329int NetEqImpl::TargetDelay() {
330 return kNotImplemented;
331}
332
henrik.lundin9c3efd02015-08-27 13:12:22 -0700333int NetEqImpl::CurrentDelayMs() const {
Tommi9090e0b2016-01-20 13:39:36 +0100334 rtc::CritScope lock(&crit_sect_);
henrik.lundin9c3efd02015-08-27 13:12:22 -0700335 if (fs_hz_ == 0)
336 return 0;
337 // Sum up the samples in the packet buffer with the future length of the sync
338 // buffer, and divide the sum by the sample rate.
339 const size_t delay_samples =
ossu61a208b2016-09-20 01:38:00 -0700340 packet_buffer_->NumSamplesInBuffer(decoder_frame_length_) +
henrik.lundin9c3efd02015-08-27 13:12:22 -0700341 sync_buffer_->FutureLength();
342 // The division below will truncate.
343 const int delay_ms =
344 static_cast<int>(delay_samples) / rtc::CheckedDivExact(fs_hz_, 1000);
345 return delay_ms;
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200346}
347
henrik.lundinb3f1c5d2016-08-22 15:39:53 -0700348int NetEqImpl::FilteredCurrentDelayMs() const {
349 rtc::CritScope lock(&crit_sect_);
350 // Calculate the filtered packet buffer level in samples. The value from
351 // |buffer_level_filter_| is in number of packets, represented in Q8.
352 const size_t packet_buffer_samples =
353 (buffer_level_filter_->filtered_current_level() *
354 decoder_frame_length_) >>
355 8;
356 // Sum up the filtered packet buffer level with the future length of the sync
357 // buffer, and divide the sum by the sample rate.
358 const size_t delay_samples =
359 packet_buffer_samples + sync_buffer_->FutureLength();
360 // The division below will truncate. The return value is in ms.
361 return static_cast<int>(delay_samples) / rtc::CheckedDivExact(fs_hz_, 1000);
362}
363
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000364// Deprecated.
365// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000366void NetEqImpl::SetPlayoutMode(NetEqPlayoutMode mode) {
Tommi9090e0b2016-01-20 13:39:36 +0100367 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000368 if (mode != playout_mode_) {
369 playout_mode_ = mode;
370 CreateDecisionLogic();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000371 }
372}
373
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000374// Deprecated.
375// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000376NetEqPlayoutMode NetEqImpl::PlayoutMode() const {
Tommi9090e0b2016-01-20 13:39:36 +0100377 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000378 return playout_mode_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000379}
380
381int NetEqImpl::NetworkStatistics(NetEqNetworkStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100382 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000383 assert(decoder_database_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700384 const size_t total_samples_in_buffers =
ossu61a208b2016-09-20 01:38:00 -0700385 packet_buffer_->NumSamplesInBuffer(decoder_frame_length_) +
Peter Kastingdce40cf2015-08-24 14:52:23 -0700386 sync_buffer_->FutureLength();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000387 assert(delay_manager_.get());
388 assert(decision_logic_.get());
389 stats_.GetNetworkStatistics(fs_hz_, total_samples_in_buffers,
390 decoder_frame_length_, *delay_manager_.get(),
391 *decision_logic_.get(), stats);
392 return 0;
393}
394
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000395void NetEqImpl::GetRtcpStatistics(RtcpStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100396 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000397 if (stats) {
398 rtcp_.GetStatistics(false, stats);
399 }
400}
401
402void NetEqImpl::GetRtcpStatisticsNoReset(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(true, stats);
406 }
407}
408
409void NetEqImpl::EnableVad() {
Tommi9090e0b2016-01-20 13:39:36 +0100410 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000411 assert(vad_.get());
412 vad_->Enable();
413}
414
415void NetEqImpl::DisableVad() {
Tommi9090e0b2016-01-20 13:39:36 +0100416 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000417 assert(vad_.get());
418 vad_->Disable();
419}
420
henrik.lundin15c51e32016-04-06 08:38:56 -0700421rtc::Optional<uint32_t> NetEqImpl::GetPlayoutTimestamp() const {
Tommi9090e0b2016-01-20 13:39:36 +0100422 rtc::CritScope lock(&crit_sect_);
henrik.lundin0d96ab72016-04-06 12:28:26 -0700423 if (first_packet_ || last_mode_ == kModeRfc3389Cng ||
424 last_mode_ == kModeCodecInternalCng) {
wu@webrtc.org94454b72014-06-05 20:34:08 +0000425 // We don't have a valid RTP timestamp until we have decoded our first
henrik.lundin0d96ab72016-04-06 12:28:26 -0700426 // RTP packet. Also, the RTP timestamp is not accurate while playing CNG,
427 // which is indicated by returning an empty value.
henrik.lundin9a410dd2016-04-06 01:39:22 -0700428 return rtc::Optional<uint32_t>();
wu@webrtc.org94454b72014-06-05 20:34:08 +0000429 }
henrik.lundin9a410dd2016-04-06 01:39:22 -0700430 return rtc::Optional<uint32_t>(
431 timestamp_scaler_->ToExternal(playout_timestamp_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000432}
433
henrik.lundind89814b2015-11-23 06:49:25 -0800434int NetEqImpl::last_output_sample_rate_hz() const {
Tommi9090e0b2016-01-20 13:39:36 +0100435 rtc::CritScope lock(&crit_sect_);
henrik.lundind89814b2015-11-23 06:49:25 -0800436 return last_output_sample_rate_hz_;
437}
438
kwiberg6f0f6162016-09-20 03:07:46 -0700439rtc::Optional<CodecInst> NetEqImpl::GetDecoder(int payload_type) const {
440 rtc::CritScope lock(&crit_sect_);
441 const DecoderDatabase::DecoderInfo* di =
442 decoder_database_->GetDecoderInfo(payload_type);
443 if (!di) {
444 return rtc::Optional<CodecInst>();
445 }
446
447 // Create a CodecInst with some fields set. The remaining fields are zeroed,
448 // but we tell MSan to consider them uninitialized.
449 CodecInst ci = {0};
450 rtc::MsanMarkUninitialized(rtc::MakeArrayView(&ci, 1));
451 ci.pltype = payload_type;
452 std::strncpy(ci.plname, di->name.c_str(), sizeof(ci.plname));
453 ci.plname[sizeof(ci.plname) - 1] = '\0';
454 ci.plfreq = di->IsRed() || di->IsDtmf() ? 8000 : di->SampleRateHz();
455 AudioDecoder* const decoder = di->GetDecoder();
456 ci.channels = decoder ? decoder->Channels() : 1;
457 return rtc::Optional<CodecInst>(ci);
458}
459
kwibergc4ccd4d2016-09-21 10:55:15 -0700460const SdpAudioFormat* NetEqImpl::GetDecoderFormat(int payload_type) const {
461 rtc::CritScope lock(&crit_sect_);
462 const DecoderDatabase::DecoderInfo* const di =
463 decoder_database_->GetDecoderInfo(payload_type);
464 if (!di) {
465 return nullptr; // Payload type not registered.
466 }
467 // This will return null if the payload type was registered without an
468 // SdpAudioFormat.
469 return di->GetFormat();
470}
471
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200472int NetEqImpl::SetTargetNumberOfChannels() {
473 return kNotImplemented;
474}
475
476int NetEqImpl::SetTargetSampleRate() {
477 return kNotImplemented;
478}
479
henrik.lundin@webrtc.orgb0f4b3d2014-11-04 08:53:10 +0000480int NetEqImpl::LastError() const {
Tommi9090e0b2016-01-20 13:39:36 +0100481 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000482 return error_code_;
483}
484
485int NetEqImpl::LastDecoderError() {
Tommi9090e0b2016-01-20 13:39:36 +0100486 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000487 return decoder_error_code_;
488}
489
490void NetEqImpl::FlushBuffers() {
Tommi9090e0b2016-01-20 13:39:36 +0100491 rtc::CritScope lock(&crit_sect_);
Henrik Lundind67a2192015-08-03 12:54:37 +0200492 LOG(LS_VERBOSE) << "FlushBuffers";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000493 packet_buffer_->Flush();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000494 assert(sync_buffer_.get());
495 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000496 sync_buffer_->Flush();
497 sync_buffer_->set_next_index(sync_buffer_->next_index() -
498 expand_->overlap_length());
499 // Set to wait for new codec.
500 first_packet_ = true;
501}
502
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000503void NetEqImpl::PacketBufferStatistics(int* current_num_packets,
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000504 int* max_num_packets) const {
Tommi9090e0b2016-01-20 13:39:36 +0100505 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000506 packet_buffer_->BufferStat(current_num_packets, max_num_packets);
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000507}
508
henrik.lundin48ed9302015-10-29 05:36:24 -0700509void NetEqImpl::EnableNack(size_t max_nack_list_size) {
Tommi9090e0b2016-01-20 13:39:36 +0100510 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700511 if (!nack_enabled_) {
512 const int kNackThresholdPackets = 2;
henrik.lundin91951862016-06-08 06:43:41 -0700513 nack_.reset(NackTracker::Create(kNackThresholdPackets));
henrik.lundin48ed9302015-10-29 05:36:24 -0700514 nack_enabled_ = true;
515 nack_->UpdateSampleRate(fs_hz_);
516 }
517 nack_->SetMaxNackListSize(max_nack_list_size);
518}
519
520void NetEqImpl::DisableNack() {
Tommi9090e0b2016-01-20 13:39:36 +0100521 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700522 nack_.reset();
523 nack_enabled_ = false;
524}
525
526std::vector<uint16_t> NetEqImpl::GetNackList(int64_t round_trip_time_ms) const {
Tommi9090e0b2016-01-20 13:39:36 +0100527 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700528 if (!nack_enabled_) {
529 return std::vector<uint16_t>();
530 }
531 RTC_DCHECK(nack_.get());
532 return nack_->GetNackList(round_trip_time_ms);
minyue@webrtc.orgd7301772013-08-29 00:58:14 +0000533}
534
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000535const SyncBuffer* NetEqImpl::sync_buffer_for_test() const {
Tommi9090e0b2016-01-20 13:39:36 +0100536 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000537 return sync_buffer_.get();
538}
539
minyue5bd33972016-05-02 04:46:11 -0700540Operations NetEqImpl::last_operation_for_test() const {
541 rtc::CritScope lock(&crit_sect_);
542 return last_operation_;
543}
544
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000545// Methods below this line are private.
546
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000547int NetEqImpl::InsertPacketInternal(const WebRtcRTPHeader& rtp_header,
kwibergee2bac22015-11-11 10:34:00 -0800548 rtc::ArrayView<const uint8_t> payload,
ossu17e3fa12016-09-08 04:52:55 -0700549 uint32_t receive_timestamp) {
kwibergee2bac22015-11-11 10:34:00 -0800550 if (payload.empty()) {
551 LOG_F(LS_ERROR) << "payload is empty";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000552 return kInvalidPointer;
553 }
ossu17e3fa12016-09-08 04:52:55 -0700554
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000555 PacketList packet_list;
556 RTPHeader main_header;
557 {
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000558 // Convert to Packet.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000559 // Create |packet| within this separate scope, since it should not be used
560 // directly once it's been inserted in the packet list. This way, |packet|
561 // is not defined outside of this block.
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000562 Packet* packet = new Packet;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000563 packet->header.markerBit = false;
564 packet->header.payloadType = rtp_header.header.payloadType;
565 packet->header.sequenceNumber = rtp_header.header.sequenceNumber;
566 packet->header.timestamp = rtp_header.header.timestamp;
567 packet->header.ssrc = rtp_header.header.ssrc;
568 packet->header.numCSRCs = 0;
ossudc431ce2016-08-31 08:51:13 -0700569 packet->payload.SetData(payload.data(), payload.size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000570 packet->primary = true;
henrik.lundin84f8cd62016-04-26 07:45:16 -0700571 // Waiting time will be set upon inserting the packet in the buffer.
572 RTC_DCHECK(!packet->waiting_time);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000573 // Insert packet in a packet list.
574 packet_list.push_back(packet);
575 // Save main payloads header for later.
576 memcpy(&main_header, &packet->header, sizeof(main_header));
577 }
578
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000579 bool update_sample_rate_and_channels = false;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000580 // Reinitialize NetEq if it's needed (changed SSRC or first call).
581 if ((main_header.ssrc != ssrc_) || first_packet_) {
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000582 // Note: |first_packet_| will be cleared further down in this method, once
583 // the packet has been successfully inserted into the packet buffer.
584
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000585 rtcp_.Init(main_header.sequenceNumber);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000586
587 // Flush the packet buffer and DTMF buffer.
588 packet_buffer_->Flush();
589 dtmf_buffer_->Flush();
590
591 // Store new SSRC.
592 ssrc_ = main_header.ssrc;
593
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000594 // Update audio buffer timestamp.
595 sync_buffer_->IncreaseEndTimestamp(main_header.timestamp - timestamp_);
596
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000597 // Update codecs.
598 timestamp_ = main_header.timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000599
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000600 // Reset timestamp scaling.
601 timestamp_scaler_->Reset();
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000602
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000603 // Trigger an update of sampling rate and the number of channels.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000604 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000605 }
606
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000607 // Update RTCP statistics, only for regular packets.
ossu17e3fa12016-09-08 04:52:55 -0700608 rtcp_.Update(main_header, receive_timestamp);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000609
610 // Check for RED payload type, and separate payloads into several packets.
611 if (decoder_database_->IsRed(main_header.payloadType)) {
612 if (payload_splitter_->SplitRed(&packet_list) != PayloadSplitter::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000613 PacketBuffer::DeleteAllPackets(&packet_list);
614 return kRedundancySplitError;
615 }
616 // Only accept a few RED payloads of the same type as the main data,
617 // DTMF events and CNG.
618 payload_splitter_->CheckRedPayloads(&packet_list, *decoder_database_);
619 // Update the stored main payload header since the main payload has now
620 // changed.
621 memcpy(&main_header, &packet_list.front()->header, sizeof(main_header));
622 }
623
624 // Check payload types.
625 if (decoder_database_->CheckPayloadTypes(packet_list) ==
626 DecoderDatabase::kDecoderNotFound) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000627 PacketBuffer::DeleteAllPackets(&packet_list);
628 return kUnknownRtpPayloadType;
629 }
630
631 // Scale timestamp to internal domain (only for some codecs).
632 timestamp_scaler_->ToInternal(&packet_list);
633
634 // Process DTMF payloads. Cycle through the list of packets, and pick out any
635 // DTMF payloads found.
636 PacketList::iterator it = packet_list.begin();
637 while (it != packet_list.end()) {
638 Packet* current_packet = (*it);
639 assert(current_packet);
ossudc431ce2016-08-31 08:51:13 -0700640 assert(!current_packet->payload.empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000641 if (decoder_database_->IsDtmf(current_packet->header.payloadType)) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000642 DtmfEvent event;
ossudc431ce2016-08-31 08:51:13 -0700643 int ret = DtmfBuffer::ParseEvent(current_packet->header.timestamp,
644 current_packet->payload.data(),
645 current_packet->payload.size(), &event);
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000646 if (ret != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000647 PacketBuffer::DeleteAllPackets(&packet_list);
648 return kDtmfParsingError;
649 }
650 if (dtmf_buffer_->InsertEvent(event) != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000651 PacketBuffer::DeleteAllPackets(&packet_list);
652 return kDtmfInsertError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000653 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000654 delete current_packet;
655 it = packet_list.erase(it);
656 } else {
657 ++it;
658 }
659 }
660
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000661 // Check for FEC in packets, and separate payloads into several packets.
662 int ret = payload_splitter_->SplitFec(&packet_list, decoder_database_.get());
663 if (ret != PayloadSplitter::kOK) {
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000664 PacketBuffer::DeleteAllPackets(&packet_list);
665 switch (ret) {
666 case PayloadSplitter::kUnknownPayloadType:
667 return kUnknownRtpPayloadType;
668 default:
669 return kOtherError;
670 }
671 }
672
ossu17e3fa12016-09-08 04:52:55 -0700673 // Update bandwidth estimate, if the packet is not comfort noise.
674 if (!packet_list.empty() &&
ossu97ba30e2016-04-25 07:55:58 -0700675 !decoder_database_->IsComfortNoise(main_header.payloadType)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000676 // The list can be empty here if we got nothing but DTMF payloads.
677 AudioDecoder* decoder =
678 decoder_database_->GetDecoder(main_header.payloadType);
679 assert(decoder); // Should always get a valid object, since we have
ossu97ba30e2016-04-25 07:55:58 -0700680 // already checked that the payload types are known.
ossudc431ce2016-08-31 08:51:13 -0700681 decoder->IncomingPacket(packet_list.front()->payload.data(),
682 packet_list.front()->payload.size(),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000683 packet_list.front()->header.sequenceNumber,
684 packet_list.front()->header.timestamp,
685 receive_timestamp);
686 }
687
ossu61a208b2016-09-20 01:38:00 -0700688 PacketList parsed_packet_list;
689 while (!packet_list.empty()) {
690 std::unique_ptr<Packet> packet(packet_list.front());
691 packet_list.pop_front();
692 const DecoderDatabase::DecoderInfo* info =
693 decoder_database_->GetDecoderInfo(packet->header.payloadType);
694 if (!info) {
695 LOG(LS_WARNING) << "SplitAudio unknown payload type";
696 return kUnknownRtpPayloadType;
697 }
698
699 if (info->IsComfortNoise()) {
700 // Carry comfort noise packets along.
701 parsed_packet_list.push_back(packet.release());
702 } else {
703 std::vector<AudioDecoder::ParseResult> results =
704 info->GetDecoder()->ParsePayload(std::move(packet->payload),
705 packet->header.timestamp,
706 packet->primary);
707 const RTPHeader& original_header = packet->header;
708 for (auto& result : results) {
709 RTC_DCHECK(result.frame);
ossu0d526d52016-09-21 01:57:31 -0700710 // Reuse the packet if possible.
ossu61a208b2016-09-20 01:38:00 -0700711 if (!packet) {
712 packet.reset(new Packet);
713 packet->header = original_header;
714 }
715 packet->header.timestamp = result.timestamp;
716 // TODO(ossu): Move from primary to some sort of priority level.
717 packet->primary = result.primary;
718 packet->frame = std::move(result.frame);
719 parsed_packet_list.push_back(packet.release());
720 }
721 }
722 }
723
henrik.lundin48ed9302015-10-29 05:36:24 -0700724 if (nack_enabled_) {
725 RTC_DCHECK(nack_);
726 if (update_sample_rate_and_channels) {
727 nack_->Reset();
728 }
ossu61a208b2016-09-20 01:38:00 -0700729 nack_->UpdateLastReceivedPacket(
730 parsed_packet_list.front()->header.sequenceNumber,
731 parsed_packet_list.front()->header.timestamp);
henrik.lundin48ed9302015-10-29 05:36:24 -0700732 }
733
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000734 // Insert packets in buffer.
henrik.lundin116c84e2015-08-27 13:14:48 -0700735 const size_t buffer_length_before_insert =
736 packet_buffer_->NumPacketsInBuffer();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000737 ret = packet_buffer_->InsertPacketList(
ossu61a208b2016-09-20 01:38:00 -0700738 &parsed_packet_list, *decoder_database_, &current_rtp_payload_type_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000739 &current_cng_rtp_payload_type_);
740 if (ret == PacketBuffer::kFlushed) {
741 // Reset DSP timestamp etc. if packet buffer flushed.
742 new_codec_ = true;
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000743 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000744 } else if (ret != PacketBuffer::kOK) {
ossu61a208b2016-09-20 01:38:00 -0700745 PacketBuffer::DeleteAllPackets(&parsed_packet_list);
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000746 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000747 }
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000748
749 if (first_packet_) {
750 first_packet_ = false;
751 // Update the codec on the next GetAudio call.
752 new_codec_ = true;
753 }
754
henrik.lundinda8bbf62016-08-31 03:14:11 -0700755 if (current_rtp_payload_type_) {
756 RTC_DCHECK(decoder_database_->GetDecoderInfo(*current_rtp_payload_type_))
757 << "Payload type " << static_cast<int>(*current_rtp_payload_type_)
758 << " is unknown where it shouldn't be";
759 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000760
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000761 if (update_sample_rate_and_channels && !packet_buffer_->Empty()) {
762 // We do not use |current_rtp_payload_type_| to |set payload_type|, but
763 // get the next RTP header from |packet_buffer_| to obtain the payload type.
764 // The reason for it is the following corner case. If NetEq receives a
765 // CNG packet with a sample rate different than the current CNG then it
766 // flushes its buffer, assuming send codec must have been changed. However,
767 // payload type of the hypothetically new send codec is not known.
768 const RTPHeader* rtp_header = packet_buffer_->NextRtpHeader();
769 assert(rtp_header);
770 int payload_type = rtp_header->payloadType;
ossu97ba30e2016-04-25 07:55:58 -0700771 size_t channels = 1;
772 if (!decoder_database_->IsComfortNoise(payload_type)) {
773 AudioDecoder* decoder = decoder_database_->GetDecoder(payload_type);
774 assert(decoder); // Payloads are already checked to be valid.
775 channels = decoder->Channels();
776 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000777 const DecoderDatabase::DecoderInfo* decoder_info =
778 decoder_database_->GetDecoderInfo(payload_type);
779 assert(decoder_info);
kwibergc0f2dcf2016-05-31 06:28:03 -0700780 if (decoder_info->SampleRateHz() != fs_hz_ ||
ossu97ba30e2016-04-25 07:55:58 -0700781 channels != algorithm_buffer_->Channels()) {
kwibergc0f2dcf2016-05-31 06:28:03 -0700782 SetSampleRateAndChannels(decoder_info->SampleRateHz(),
783 channels);
henrik.lundin48ed9302015-10-29 05:36:24 -0700784 }
785 if (nack_enabled_) {
786 RTC_DCHECK(nack_);
787 // Update the sample rate even if the rate is not new, because of Reset().
788 nack_->UpdateSampleRate(fs_hz_);
789 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000790 }
791
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000792 // TODO(hlundin): Move this code to DelayManager class.
793 const DecoderDatabase::DecoderInfo* dec_info =
794 decoder_database_->GetDecoderInfo(main_header.payloadType);
795 assert(dec_info); // Already checked that the payload type is known.
796 delay_manager_->LastDecoderType(dec_info->codec_type);
797 if (delay_manager_->last_pack_cng_or_dtmf() == 0) {
798 // Calculate the total speech length carried in each packet.
henrik.lundin116c84e2015-08-27 13:14:48 -0700799 const size_t buffer_length_after_insert =
800 packet_buffer_->NumPacketsInBuffer();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000801
henrik.lundin116c84e2015-08-27 13:14:48 -0700802 if (buffer_length_after_insert > buffer_length_before_insert) {
803 const size_t packet_length_samples =
804 (buffer_length_after_insert - buffer_length_before_insert) *
805 decoder_frame_length_;
806 if (packet_length_samples != decision_logic_->packet_length_samples()) {
807 decision_logic_->set_packet_length_samples(packet_length_samples);
808 delay_manager_->SetPacketAudioLength(
809 rtc::checked_cast<int>((1000 * packet_length_samples) / fs_hz_));
810 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000811 }
812
813 // Update statistics.
pbos@webrtc.org0946a562013-04-09 00:28:06 +0000814 if ((int32_t) (main_header.timestamp - timestamp_) >= 0 &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000815 !new_codec_) {
816 // Only update statistics if incoming packet is not older than last played
817 // out packet, and if new codec flag is not set.
818 delay_manager_->Update(main_header.sequenceNumber, main_header.timestamp,
819 fs_hz_);
820 }
821 } else if (delay_manager_->last_pack_cng_or_dtmf() == -1) {
822 // This is first "normal" packet after CNG or DTMF.
823 // Reset packet time counter and measure time until next packet,
824 // but don't update statistics.
825 delay_manager_->set_last_pack_cng_or_dtmf(0);
826 delay_manager_->ResetPacketIatCount();
827 }
828 return 0;
829}
830
henrik.lundin7a926812016-05-12 13:51:28 -0700831int NetEqImpl::GetAudioInternal(AudioFrame* audio_frame, bool* muted) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000832 PacketList packet_list;
833 DtmfEvent dtmf_event;
834 Operations operation;
835 bool play_dtmf;
henrik.lundin7a926812016-05-12 13:51:28 -0700836 *muted = false;
henrik.lundined497212016-04-25 10:11:38 -0700837 tick_timer_->Increment();
henrik.lundin60f6ce22016-05-10 03:52:04 -0700838 stats_.IncreaseCounter(output_size_samples_, fs_hz_);
henrik.lundin7a926812016-05-12 13:51:28 -0700839
840 // Check for muted state.
841 if (enable_muted_state_ && expand_->Muted() && packet_buffer_->Empty()) {
842 RTC_DCHECK_EQ(last_mode_, kModeExpand);
843 playout_timestamp_ += static_cast<uint32_t>(output_size_samples_);
844 audio_frame->sample_rate_hz_ = fs_hz_;
845 audio_frame->samples_per_channel_ = output_size_samples_;
846 audio_frame->timestamp_ =
847 first_packet_
848 ? 0
849 : timestamp_scaler_->ToExternal(playout_timestamp_) -
850 static_cast<uint32_t>(audio_frame->samples_per_channel_);
851 audio_frame->num_channels_ = sync_buffer_->Channels();
henrik.lundin612c25e2016-05-25 08:21:04 -0700852 stats_.ExpandedNoiseSamples(output_size_samples_);
henrik.lundin7a926812016-05-12 13:51:28 -0700853 *muted = true;
854 return 0;
855 }
856
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000857 int return_value = GetDecision(&operation, &packet_list, &dtmf_event,
858 &play_dtmf);
859 if (return_value != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000860 last_mode_ = kModeError;
861 return return_value;
862 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000863
864 AudioDecoder::SpeechType speech_type;
865 int length = 0;
866 int decode_return_value = Decode(&packet_list, &operation,
867 &length, &speech_type);
868
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000869 assert(vad_.get());
870 bool sid_frame_available =
871 (operation == kRfc3389Cng && !packet_list.empty());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700872 vad_->Update(decoded_buffer_.get(), static_cast<size_t>(length), speech_type,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000873 sid_frame_available, fs_hz_);
874
henrik.lundinb1fb72b2016-05-03 08:18:47 -0700875 if (sid_frame_available || speech_type == AudioDecoder::kComfortNoise) {
876 // Start a new stopwatch since we are decoding a new CNG packet.
877 generated_noise_stopwatch_ = tick_timer_->GetNewStopwatch();
878 }
879
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000880 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000881 switch (operation) {
882 case kNormal: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000883 DoNormal(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000884 break;
885 }
886 case kMerge: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000887 DoMerge(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000888 break;
889 }
890 case kExpand: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000891 return_value = DoExpand(play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000892 break;
893 }
Henrik Lundincf808d22015-05-27 14:33:29 +0200894 case kAccelerate:
895 case kFastAccelerate: {
896 const bool fast_accelerate =
897 enable_fast_accelerate_ && (operation == kFastAccelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000898 return_value = DoAccelerate(decoded_buffer_.get(), length, speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +0200899 play_dtmf, fast_accelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000900 break;
901 }
902 case kPreemptiveExpand: {
903 return_value = DoPreemptiveExpand(decoded_buffer_.get(), length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000904 speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000905 break;
906 }
907 case kRfc3389Cng:
908 case kRfc3389CngNoPacket: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000909 return_value = DoRfc3389Cng(&packet_list, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000910 break;
911 }
912 case kCodecInternalCng: {
913 // This handles the case when there is no transmission and the decoder
914 // should produce internal comfort noise.
915 // TODO(hlundin): Write test for codec-internal CNG.
minyuel6d92bf52015-09-23 15:20:39 +0200916 DoCodecInternalCng(decoded_buffer_.get(), length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000917 break;
918 }
919 case kDtmf: {
920 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000921 return_value = DoDtmf(dtmf_event, &play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000922 break;
923 }
924 case kAlternativePlc: {
925 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000926 DoAlternativePlc(false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000927 break;
928 }
929 case kAlternativePlcIncreaseTimestamp: {
930 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000931 DoAlternativePlc(true);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000932 break;
933 }
934 case kAudioRepetitionIncreaseTimestamp: {
935 // TODO(hlundin): Write test for this.
Peter Kastingb7e50542015-06-11 12:55:50 -0700936 sync_buffer_->IncreaseEndTimestamp(
937 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000938 // Skipping break on purpose. Execution should move on into the
939 // next case.
kjellander@webrtc.org7d2b6a92015-01-28 18:37:58 +0000940 FALLTHROUGH();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000941 }
942 case kAudioRepetition: {
943 // TODO(hlundin): Write test for this.
944 // Copy last |output_size_samples_| from |sync_buffer_| to
945 // |algorithm_buffer|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000946 algorithm_buffer_->PushBackFromIndex(
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000947 *sync_buffer_, sync_buffer_->Size() - output_size_samples_);
948 expand_->Reset();
949 break;
950 }
951 case kUndefined: {
Henrik Lundind67a2192015-08-03 12:54:37 +0200952 LOG(LS_ERROR) << "Invalid operation kUndefined.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000953 assert(false); // This should not happen.
954 last_mode_ = kModeError;
955 return kInvalidOperation;
956 }
957 } // End of switch.
minyue5bd33972016-05-02 04:46:11 -0700958 last_operation_ = operation;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000959 if (return_value < 0) {
960 return return_value;
961 }
962
963 if (last_mode_ != kModeRfc3389Cng) {
964 comfort_noise_->Reset();
965 }
966
967 // Copy from |algorithm_buffer| to |sync_buffer_|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000968 sync_buffer_->PushBack(*algorithm_buffer_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000969
970 // Extract data from |sync_buffer_| to |output|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000971 size_t num_output_samples_per_channel = output_size_samples_;
972 size_t num_output_samples = output_size_samples_ * sync_buffer_->Channels();
henrik.lundin6d8e0112016-03-04 10:34:21 -0800973 if (num_output_samples > AudioFrame::kMaxDataSizeSamples) {
974 LOG(LS_WARNING) << "Output array is too short. "
975 << AudioFrame::kMaxDataSizeSamples << " < "
976 << output_size_samples_ << " * "
977 << sync_buffer_->Channels();
978 num_output_samples = AudioFrame::kMaxDataSizeSamples;
979 num_output_samples_per_channel =
980 AudioFrame::kMaxDataSizeSamples / sync_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000981 }
henrik.lundin6d8e0112016-03-04 10:34:21 -0800982 sync_buffer_->GetNextAudioInterleaved(num_output_samples_per_channel,
983 audio_frame);
984 audio_frame->sample_rate_hz_ = fs_hz_;
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200985 if (sync_buffer_->FutureLength() < expand_->overlap_length()) {
986 // The sync buffer should always contain |overlap_length| samples, but now
987 // too many samples have been extracted. Reinstall the |overlap_length|
988 // lookahead by moving the index.
989 const size_t missing_lookahead_samples =
990 expand_->overlap_length() - sync_buffer_->FutureLength();
henrikg91d6ede2015-09-17 00:24:34 -0700991 RTC_DCHECK_GE(sync_buffer_->next_index(), missing_lookahead_samples);
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200992 sync_buffer_->set_next_index(sync_buffer_->next_index() -
993 missing_lookahead_samples);
994 }
henrik.lundin6d8e0112016-03-04 10:34:21 -0800995 if (audio_frame->samples_per_channel_ != output_size_samples_) {
996 LOG(LS_ERROR) << "audio_frame->samples_per_channel_ ("
997 << audio_frame->samples_per_channel_
Henrik Lundind67a2192015-08-03 12:54:37 +0200998 << ") != output_size_samples_ (" << output_size_samples_
999 << ")";
minyue@webrtc.orgdb1cefc2013-08-13 01:39:21 +00001000 // TODO(minyue): treatment of under-run, filling zeros
henrik.lundin6d8e0112016-03-04 10:34:21 -08001001 memset(audio_frame->data_, 0, num_output_samples * sizeof(int16_t));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001002 return kSampleUnderrun;
1003 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001004
1005 // Should always have overlap samples left in the |sync_buffer_|.
henrikg91d6ede2015-09-17 00:24:34 -07001006 RTC_DCHECK_GE(sync_buffer_->FutureLength(), expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001007
1008 if (play_dtmf) {
henrik.lundin6d8e0112016-03-04 10:34:21 -08001009 return_value =
1010 DtmfOverdub(dtmf_event, sync_buffer_->Channels(), audio_frame->data_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001011 }
1012
1013 // Update the background noise parameters if last operation wrote data
1014 // straight from the decoder to the |sync_buffer_|. That is, none of the
1015 // operations that modify the signal can be followed by a parameter update.
1016 if ((last_mode_ == kModeNormal) ||
1017 (last_mode_ == kModeAccelerateFail) ||
1018 (last_mode_ == kModePreemptiveExpandFail) ||
1019 (last_mode_ == kModeRfc3389Cng) ||
1020 (last_mode_ == kModeCodecInternalCng)) {
1021 background_noise_->Update(*sync_buffer_, *vad_.get());
1022 }
1023
1024 if (operation == kDtmf) {
1025 // DTMF data was written the end of |sync_buffer_|.
1026 // Update index to end of DTMF data in |sync_buffer_|.
1027 sync_buffer_->set_dtmf_index(sync_buffer_->Size());
1028 }
1029
henrik.lundin@webrtc.orged865b52014-03-06 10:28:07 +00001030 if (last_mode_ != kModeExpand) {
1031 // If last operation was not expand, calculate the |playout_timestamp_| from
1032 // the |sync_buffer_|. However, do not update the |playout_timestamp_| if it
1033 // would be moved "backwards".
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001034 uint32_t temp_timestamp = sync_buffer_->end_timestamp() -
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001035 static_cast<uint32_t>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001036 if (static_cast<int32_t>(temp_timestamp - playout_timestamp_) > 0) {
1037 playout_timestamp_ = temp_timestamp;
1038 }
1039 } else {
1040 // Use dead reckoning to estimate the |playout_timestamp_|.
Peter Kastingb7e50542015-06-11 12:55:50 -07001041 playout_timestamp_ += static_cast<uint32_t>(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001042 }
henrik.lundin15c51e32016-04-06 08:38:56 -07001043 // Set the timestamp in the audio frame to zero before the first packet has
1044 // been inserted. Otherwise, subtract the frame size in samples to get the
1045 // timestamp of the first sample in the frame (playout_timestamp_ is the
1046 // last + 1).
1047 audio_frame->timestamp_ =
1048 first_packet_
1049 ? 0
1050 : timestamp_scaler_->ToExternal(playout_timestamp_) -
1051 static_cast<uint32_t>(audio_frame->samples_per_channel_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001052
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001053 if (!(last_mode_ == kModeRfc3389Cng ||
1054 last_mode_ == kModeCodecInternalCng ||
1055 last_mode_ == kModeExpand)) {
1056 generated_noise_stopwatch_.reset();
1057 }
1058
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001059 if (decode_return_value) return decode_return_value;
1060 return return_value;
1061}
1062
1063int NetEqImpl::GetDecision(Operations* operation,
1064 PacketList* packet_list,
1065 DtmfEvent* dtmf_event,
1066 bool* play_dtmf) {
1067 // Initialize output variables.
1068 *play_dtmf = false;
1069 *operation = kUndefined;
1070
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001071 assert(sync_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001072 uint32_t end_timestamp = sync_buffer_->end_timestamp();
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001073 if (!new_codec_) {
1074 const uint32_t five_seconds_samples = 5 * fs_hz_;
1075 packet_buffer_->DiscardOldPackets(end_timestamp, five_seconds_samples);
1076 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001077 const RTPHeader* header = packet_buffer_->NextRtpHeader();
1078
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001079 RTC_DCHECK(!generated_noise_stopwatch_ ||
1080 generated_noise_stopwatch_->ElapsedTicks() >= 1);
1081 uint64_t generated_noise_samples =
1082 generated_noise_stopwatch_
1083 ? (generated_noise_stopwatch_->ElapsedTicks() - 1) *
1084 output_size_samples_ +
1085 decision_logic_->noise_fast_forward()
1086 : 0;
1087
henrik.lundin@webrtc.orgca8cb952014-03-12 10:26:52 +00001088 if (decision_logic_->CngRfc3389On() || last_mode_ == kModeRfc3389Cng) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001089 // Because of timestamp peculiarities, we have to "manually" disallow using
1090 // a CNG packet with the same timestamp as the one that was last played.
1091 // This can happen when using redundancy and will cause the timing to shift.
henrik.lundin@webrtc.org24779fe2014-03-14 12:40:05 +00001092 while (header && decoder_database_->IsComfortNoise(header->payloadType) &&
1093 (end_timestamp >= header->timestamp ||
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001094 end_timestamp + generated_noise_samples > header->timestamp)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001095 // Don't use this packet, discard it.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001096 if (packet_buffer_->DiscardNextPacket() != PacketBuffer::kOK) {
1097 assert(false); // Must be ok by design.
1098 }
1099 // Check buffer again.
1100 if (!new_codec_) {
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001101 packet_buffer_->DiscardOldPackets(end_timestamp, 5 * fs_hz_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001102 }
1103 header = packet_buffer_->NextRtpHeader();
1104 }
1105 }
1106
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001107 assert(expand_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001108 const int samples_left = static_cast<int>(sync_buffer_->FutureLength() -
1109 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001110 if (last_mode_ == kModeAccelerateSuccess ||
1111 last_mode_ == kModeAccelerateLowEnergy ||
1112 last_mode_ == kModePreemptiveExpandSuccess ||
1113 last_mode_ == kModePreemptiveExpandLowEnergy) {
1114 // Subtract (samples_left + output_size_samples_) from sampleMemory.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001115 decision_logic_->AddSampleMemory(
1116 -(samples_left + rtc::checked_cast<int>(output_size_samples_)));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001117 }
1118
1119 // Check if it is time to play a DTMF event.
Peter Kastingb7e50542015-06-11 12:55:50 -07001120 if (dtmf_buffer_->GetEvent(
1121 static_cast<uint32_t>(
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001122 end_timestamp + generated_noise_samples),
Peter Kastingb7e50542015-06-11 12:55:50 -07001123 dtmf_event)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001124 *play_dtmf = true;
1125 }
1126
1127 // Get instruction.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001128 assert(sync_buffer_.get());
1129 assert(expand_.get());
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001130 generated_noise_samples =
1131 generated_noise_stopwatch_
1132 ? generated_noise_stopwatch_->ElapsedTicks() * output_size_samples_ +
1133 decision_logic_->noise_fast_forward()
1134 : 0;
1135 *operation = decision_logic_->GetDecision(
1136 *sync_buffer_, *expand_, decoder_frame_length_, header, last_mode_,
1137 *play_dtmf, generated_noise_samples, &reset_decoder_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001138
1139 // Check if we already have enough samples in the |sync_buffer_|. If so,
1140 // change decision to normal, unless the decision was merge, accelerate, or
1141 // preemptive expand.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001142 if (samples_left >= rtc::checked_cast<int>(output_size_samples_) &&
1143 *operation != kMerge &&
1144 *operation != kAccelerate &&
1145 *operation != kFastAccelerate &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001146 *operation != kPreemptiveExpand) {
1147 *operation = kNormal;
1148 return 0;
1149 }
1150
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001151 decision_logic_->ExpandDecision(*operation);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001152
1153 // Check conditions for reset.
1154 if (new_codec_ || *operation == kUndefined) {
1155 // The only valid reason to get kUndefined is that new_codec_ is set.
1156 assert(new_codec_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001157 if (*play_dtmf && !header) {
1158 timestamp_ = dtmf_event->timestamp;
1159 } else {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001160 if (!header) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001161 LOG(LS_ERROR) << "Packet missing where it shouldn't.";
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001162 return -1;
1163 }
1164 timestamp_ = header->timestamp;
ossu108ecec2016-07-08 08:45:18 -07001165 if (*operation == kRfc3389CngNoPacket &&
1166 decoder_database_->IsComfortNoise(header->payloadType)) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001167 // Change decision to CNG packet, since we do have a CNG packet, but it
1168 // was considered too early to use. Now, use it anyway.
1169 *operation = kRfc3389Cng;
1170 } else if (*operation != kRfc3389Cng) {
1171 *operation = kNormal;
1172 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001173 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001174 // Adjust |sync_buffer_| timestamp before setting |end_timestamp| to the
1175 // new value.
1176 sync_buffer_->IncreaseEndTimestamp(timestamp_ - end_timestamp);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001177 end_timestamp = timestamp_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001178 new_codec_ = false;
1179 decision_logic_->SoftReset();
1180 buffer_level_filter_->Reset();
1181 delay_manager_->Reset();
1182 stats_.ResetMcu();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001183 }
1184
Peter Kastingdce40cf2015-08-24 14:52:23 -07001185 size_t required_samples = output_size_samples_;
1186 const size_t samples_10_ms = static_cast<size_t>(80 * fs_mult_);
1187 const size_t samples_20_ms = 2 * samples_10_ms;
1188 const size_t samples_30_ms = 3 * samples_10_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001189
1190 switch (*operation) {
1191 case kExpand: {
1192 timestamp_ = end_timestamp;
1193 return 0;
1194 }
1195 case kRfc3389CngNoPacket:
1196 case kCodecInternalCng: {
1197 return 0;
1198 }
1199 case kDtmf: {
1200 // TODO(hlundin): Write test for this.
1201 // Update timestamp.
1202 timestamp_ = end_timestamp;
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001203 const uint64_t generated_noise_samples =
1204 generated_noise_stopwatch_
1205 ? generated_noise_stopwatch_->ElapsedTicks() *
1206 output_size_samples_ +
1207 decision_logic_->noise_fast_forward()
1208 : 0;
1209 if (generated_noise_samples > 0 && last_mode_ != kModeDtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001210 // Make a jump in timestamp due to the recently played comfort noise.
Peter Kastingb7e50542015-06-11 12:55:50 -07001211 uint32_t timestamp_jump =
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001212 static_cast<uint32_t>(generated_noise_samples);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001213 sync_buffer_->IncreaseEndTimestamp(timestamp_jump);
1214 timestamp_ += timestamp_jump;
1215 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001216 return 0;
1217 }
Henrik Lundincf808d22015-05-27 14:33:29 +02001218 case kAccelerate:
1219 case kFastAccelerate: {
1220 // In order to do an accelerate we need at least 30 ms of audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001221 if (samples_left >= static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001222 // Already have enough data, so we do not need to extract any more.
1223 decision_logic_->set_sample_memory(samples_left);
1224 decision_logic_->set_prev_time_scale(true);
1225 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001226 } else if (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001227 decoder_frame_length_ >= samples_30_ms) {
1228 // Avoid decoding more data as it might overflow the playout buffer.
1229 *operation = kNormal;
1230 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001231 } else if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001232 decoder_frame_length_ < samples_30_ms) {
1233 // Build up decoded data by decoding at least 20 ms of audio data. Do
1234 // not perform accelerate yet, but wait until we only need to do one
1235 // decoding.
1236 required_samples = 2 * output_size_samples_;
1237 *operation = kNormal;
1238 }
1239 // If none of the above is true, we have one of two possible situations:
1240 // (1) 20 ms <= samples_left < 30 ms and decoder_frame_length_ < 30 ms; or
1241 // (2) samples_left < 10 ms and decoder_frame_length_ >= 30 ms.
1242 // In either case, we move on with the accelerate decision, and decode one
1243 // frame now.
1244 break;
1245 }
1246 case kPreemptiveExpand: {
1247 // In order to do a preemptive expand we need at least 30 ms of decoded
1248 // audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001249 if ((samples_left >= static_cast<int>(samples_30_ms)) ||
1250 (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001251 decoder_frame_length_ >= samples_30_ms)) {
1252 // Already have enough data, so we do not need to extract any more.
1253 // Or, avoid decoding more data as it might overflow the playout buffer.
1254 // Still try preemptive expand, though.
1255 decision_logic_->set_sample_memory(samples_left);
1256 decision_logic_->set_prev_time_scale(true);
1257 return 0;
1258 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07001259 if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001260 decoder_frame_length_ < samples_30_ms) {
1261 // Build up decoded data by decoding at least 20 ms of audio data.
1262 // Still try to perform preemptive expand.
1263 required_samples = 2 * output_size_samples_;
1264 }
1265 // Move on with the preemptive expand decision.
1266 break;
1267 }
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001268 case kMerge: {
1269 required_samples =
1270 std::max(merge_->RequiredFutureSamples(), required_samples);
1271 break;
1272 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001273 default: {
1274 // Do nothing.
1275 }
1276 }
1277
1278 // Get packets from buffer.
1279 int extracted_samples = 0;
1280 if (header &&
1281 *operation != kAlternativePlc &&
1282 *operation != kAlternativePlcIncreaseTimestamp &&
1283 *operation != kAudioRepetition &&
1284 *operation != kAudioRepetitionIncreaseTimestamp) {
1285 sync_buffer_->IncreaseEndTimestamp(header->timestamp - end_timestamp);
1286 if (decision_logic_->CngOff()) {
1287 // Adjustment of timestamp only corresponds to an actual packet loss
1288 // if comfort noise is not played. If comfort noise was just played,
1289 // this adjustment of timestamp is only done to get back in sync with the
1290 // stream timestamp; no loss to report.
1291 stats_.LostSamples(header->timestamp - end_timestamp);
1292 }
1293
1294 if (*operation != kRfc3389Cng) {
1295 // We are about to decode and use a non-CNG packet.
1296 decision_logic_->SetCngOff();
1297 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001298
1299 extracted_samples = ExtractPackets(required_samples, packet_list);
1300 if (extracted_samples < 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001301 return kPacketBufferCorruption;
1302 }
1303 }
1304
Henrik Lundincf808d22015-05-27 14:33:29 +02001305 if (*operation == kAccelerate || *operation == kFastAccelerate ||
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001306 *operation == kPreemptiveExpand) {
1307 decision_logic_->set_sample_memory(samples_left + extracted_samples);
1308 decision_logic_->set_prev_time_scale(true);
1309 }
1310
Henrik Lundincf808d22015-05-27 14:33:29 +02001311 if (*operation == kAccelerate || *operation == kFastAccelerate) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001312 // Check that we have enough data (30ms) to do accelerate.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001313 if (extracted_samples + samples_left < static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001314 // TODO(hlundin): Write test for this.
1315 // Not enough, do normal operation instead.
1316 *operation = kNormal;
1317 }
1318 }
1319
1320 timestamp_ = end_timestamp;
1321 return 0;
1322}
1323
1324int NetEqImpl::Decode(PacketList* packet_list, Operations* operation,
1325 int* decoded_length,
1326 AudioDecoder::SpeechType* speech_type) {
1327 *speech_type = AudioDecoder::kSpeech;
minyuel6d92bf52015-09-23 15:20:39 +02001328
1329 // When packet_list is empty, we may be in kCodecInternalCng mode, and for
1330 // that we use current active decoder.
1331 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1332
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001333 if (!packet_list->empty()) {
1334 const Packet* packet = packet_list->front();
pkasting@chromium.org0e81fdf2015-02-02 23:54:03 +00001335 uint8_t payload_type = packet->header.payloadType;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001336 if (!decoder_database_->IsComfortNoise(payload_type)) {
1337 decoder = decoder_database_->GetDecoder(payload_type);
1338 assert(decoder);
1339 if (!decoder) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001340 LOG(LS_WARNING) << "Unknown payload type "
1341 << static_cast<int>(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001342 PacketBuffer::DeleteAllPackets(packet_list);
1343 return kDecoderNotFound;
1344 }
1345 bool decoder_changed;
1346 decoder_database_->SetActiveDecoder(payload_type, &decoder_changed);
1347 if (decoder_changed) {
1348 // We have a new decoder. Re-init some values.
1349 const DecoderDatabase::DecoderInfo* decoder_info = decoder_database_
1350 ->GetDecoderInfo(payload_type);
1351 assert(decoder_info);
1352 if (!decoder_info) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001353 LOG(LS_WARNING) << "Unknown payload type "
1354 << static_cast<int>(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001355 PacketBuffer::DeleteAllPackets(packet_list);
1356 return kDecoderNotFound;
1357 }
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001358 // If sampling rate or number of channels has changed, we need to make
1359 // a reset.
kwibergc0f2dcf2016-05-31 06:28:03 -07001360 if (decoder_info->SampleRateHz() != fs_hz_ ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001361 decoder->Channels() != algorithm_buffer_->Channels()) {
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001362 // TODO(tlegrand): Add unittest to cover this event.
kwibergc0f2dcf2016-05-31 06:28:03 -07001363 SetSampleRateAndChannels(decoder_info->SampleRateHz(),
1364 decoder->Channels());
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001365 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001366 sync_buffer_->set_end_timestamp(timestamp_);
1367 playout_timestamp_ = timestamp_;
1368 }
1369 }
1370 }
1371
1372 if (reset_decoder_) {
1373 // TODO(hlundin): Write test for this.
Karl Wiberg43766482015-08-27 15:22:11 +02001374 if (decoder)
1375 decoder->Reset();
1376
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001377 // Reset comfort noise decoder.
ossu97ba30e2016-04-25 07:55:58 -07001378 ComfortNoiseDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02001379 if (cng_decoder)
1380 cng_decoder->Reset();
1381
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001382 reset_decoder_ = false;
1383 }
1384
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001385 *decoded_length = 0;
1386 // Update codec-internal PLC state.
1387 if ((*operation == kMerge) && decoder && decoder->HasDecodePlc()) {
1388 decoder->DecodePlc(1, &decoded_buffer_[*decoded_length]);
1389 }
1390
minyuel6d92bf52015-09-23 15:20:39 +02001391 int return_value;
1392 if (*operation == kCodecInternalCng) {
1393 RTC_DCHECK(packet_list->empty());
1394 return_value = DecodeCng(decoder, decoded_length, speech_type);
1395 } else {
1396 return_value = DecodeLoop(packet_list, *operation, decoder,
1397 decoded_length, speech_type);
1398 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001399
1400 if (*decoded_length < 0) {
1401 // Error returned from the decoder.
1402 *decoded_length = 0;
Peter Kastingb7e50542015-06-11 12:55:50 -07001403 sync_buffer_->IncreaseEndTimestamp(
1404 static_cast<uint32_t>(decoder_frame_length_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001405 int error_code = 0;
1406 if (decoder)
1407 error_code = decoder->ErrorCode();
1408 if (error_code != 0) {
1409 // Got some error code from the decoder.
1410 decoder_error_code_ = error_code;
1411 return_value = kDecoderErrorCode;
Henrik Lundind67a2192015-08-03 12:54:37 +02001412 LOG(LS_WARNING) << "Decoder returned error code: " << error_code;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001413 } else {
1414 // Decoder does not implement error codes. Return generic error.
1415 return_value = kOtherDecoderError;
Henrik Lundind67a2192015-08-03 12:54:37 +02001416 LOG(LS_WARNING) << "Decoder error (no error code)";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001417 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001418 *operation = kExpand; // Do expansion to get data instead.
1419 }
1420 if (*speech_type != AudioDecoder::kComfortNoise) {
1421 // Don't increment timestamp if codec returned CNG speech type
1422 // since in this case, the we will increment the CNGplayedTS counter.
1423 // Increase with number of samples per channel.
1424 assert(*decoded_length == 0 ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001425 (decoder && decoder->Channels() == sync_buffer_->Channels()));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001426 sync_buffer_->IncreaseEndTimestamp(
1427 *decoded_length / static_cast<int>(sync_buffer_->Channels()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001428 }
1429 return return_value;
1430}
1431
minyuel6d92bf52015-09-23 15:20:39 +02001432int NetEqImpl::DecodeCng(AudioDecoder* decoder, int* decoded_length,
1433 AudioDecoder::SpeechType* speech_type) {
1434 if (!decoder) {
1435 // This happens when active decoder is not defined.
1436 *decoded_length = -1;
1437 return 0;
1438 }
1439
1440 while (*decoded_length < rtc::checked_cast<int>(output_size_samples_)) {
1441 const int length = decoder->Decode(
1442 nullptr, 0, fs_hz_,
1443 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1444 &decoded_buffer_[*decoded_length], speech_type);
1445 if (length > 0) {
1446 *decoded_length += length;
minyuel6d92bf52015-09-23 15:20:39 +02001447 } else {
1448 // Error.
1449 LOG(LS_WARNING) << "Failed to decode CNG";
1450 *decoded_length = -1;
1451 break;
1452 }
1453 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1454 // Guard against overflow.
1455 LOG(LS_WARNING) << "Decoded too much CNG.";
1456 return kDecodedTooMuch;
1457 }
1458 }
1459 return 0;
1460}
1461
1462int NetEqImpl::DecodeLoop(PacketList* packet_list, const Operations& operation,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001463 AudioDecoder* decoder, int* decoded_length,
1464 AudioDecoder::SpeechType* speech_type) {
1465 Packet* packet = NULL;
1466 if (!packet_list->empty()) {
1467 packet = packet_list->front();
1468 }
minyuel6d92bf52015-09-23 15:20:39 +02001469
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001470 // Do decoding.
1471 while (packet &&
1472 !decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1473 assert(decoder); // At this point, we must have a decoder object.
1474 // The number of channels in the |sync_buffer_| should be the same as the
1475 // number decoder channels.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001476 assert(sync_buffer_->Channels() == decoder->Channels());
1477 assert(decoded_buffer_length_ >= kMaxFrameSize * decoder->Channels());
minyuel6d92bf52015-09-23 15:20:39 +02001478 assert(operation == kNormal || operation == kAccelerate ||
1479 operation == kFastAccelerate || operation == kMerge ||
1480 operation == kPreemptiveExpand);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001481 packet_list->pop_front();
ossu61a208b2016-09-20 01:38:00 -07001482 auto opt_result = packet->frame->Decode(
1483 rtc::ArrayView<int16_t>(&decoded_buffer_[*decoded_length],
1484 decoded_buffer_length_ - *decoded_length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001485 delete packet;
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001486 packet = NULL;
ossu61a208b2016-09-20 01:38:00 -07001487 if (opt_result) {
1488 const auto& result = *opt_result;
1489 *speech_type = result.speech_type;
1490 if (result.num_decoded_samples > 0) {
1491 *decoded_length += rtc::checked_cast<int>(result.num_decoded_samples);
1492 // Update |decoder_frame_length_| with number of samples per channel.
1493 decoder_frame_length_ =
1494 result.num_decoded_samples / decoder->Channels();
1495 }
1496 } else {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001497 // Error.
ossu61a208b2016-09-20 01:38:00 -07001498 // TODO(ossu): What to put here?
1499 LOG(LS_WARNING) << "Decode error";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001500 *decoded_length = -1;
1501 PacketBuffer::DeleteAllPackets(packet_list);
1502 break;
1503 }
ossu61a208b2016-09-20 01:38:00 -07001504 if (*decoded_length > rtc::checked_cast<int>(decoded_buffer_length_)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001505 // Guard against overflow.
Henrik Lundind67a2192015-08-03 12:54:37 +02001506 LOG(LS_WARNING) << "Decoded too much.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001507 PacketBuffer::DeleteAllPackets(packet_list);
1508 return kDecodedTooMuch;
1509 }
1510 if (!packet_list->empty()) {
1511 packet = packet_list->front();
1512 } else {
1513 packet = NULL;
1514 }
1515 } // End of decode loop.
1516
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001517 // If the list is not empty at this point, either a decoding error terminated
1518 // the while-loop, or list must hold exactly one CNG packet.
1519 assert(packet_list->empty() || *decoded_length < 0 ||
1520 (packet_list->size() == 1 && packet &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001521 decoder_database_->IsComfortNoise(packet->header.payloadType)));
1522 return 0;
1523}
1524
1525void NetEqImpl::DoNormal(const int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001526 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001527 assert(normal_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001528 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001529 normal_->Process(decoded_buffer, decoded_length, last_mode_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001530 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001531 if (decoded_length != 0) {
1532 last_mode_ = kModeNormal;
1533 }
1534
1535 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1536 if ((speech_type == AudioDecoder::kComfortNoise)
1537 || ((last_mode_ == kModeCodecInternalCng)
1538 && (decoded_length == 0))) {
1539 // TODO(hlundin): Remove second part of || statement above.
1540 last_mode_ = kModeCodecInternalCng;
1541 }
1542
1543 if (!play_dtmf) {
1544 dtmf_tone_generator_->Reset();
1545 }
1546}
1547
1548void NetEqImpl::DoMerge(int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001549 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001550 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001551 assert(merge_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001552 size_t new_length = merge_->Process(decoded_buffer, decoded_length,
1553 mute_factor_array_.get(),
1554 algorithm_buffer_.get());
1555 size_t expand_length_correction = new_length -
1556 decoded_length / algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001557
1558 // Update in-call and post-call statistics.
1559 if (expand_->MuteFactor(0) == 0) {
1560 // Expand generates only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001561 stats_.ExpandedNoiseSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001562 } else {
1563 // Expansion generates more than only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001564 stats_.ExpandedVoiceSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001565 }
1566
1567 last_mode_ = kModeMerge;
1568 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1569 if (speech_type == AudioDecoder::kComfortNoise) {
1570 last_mode_ = kModeCodecInternalCng;
1571 }
1572 expand_->Reset();
1573 if (!play_dtmf) {
1574 dtmf_tone_generator_->Reset();
1575 }
1576}
1577
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001578int NetEqImpl::DoExpand(bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001579 while ((sync_buffer_->FutureLength() - expand_->overlap_length()) <
Peter Kastingdce40cf2015-08-24 14:52:23 -07001580 output_size_samples_) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001581 algorithm_buffer_->Clear();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001582 int return_value = expand_->Process(algorithm_buffer_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001583 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001584
1585 // Update in-call and post-call statistics.
1586 if (expand_->MuteFactor(0) == 0) {
1587 // Expand operation generates only noise.
1588 stats_.ExpandedNoiseSamples(length);
1589 } else {
1590 // Expand operation generates more than only noise.
1591 stats_.ExpandedVoiceSamples(length);
1592 }
1593
1594 last_mode_ = kModeExpand;
1595
1596 if (return_value < 0) {
1597 return return_value;
1598 }
1599
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001600 sync_buffer_->PushBack(*algorithm_buffer_);
1601 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001602 }
1603 if (!play_dtmf) {
1604 dtmf_tone_generator_->Reset();
1605 }
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001606
1607 if (!generated_noise_stopwatch_) {
1608 // Start a new stopwatch since we may be covering for a lost CNG packet.
1609 generated_noise_stopwatch_ = tick_timer_->GetNewStopwatch();
1610 }
1611
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001612 return 0;
1613}
1614
Henrik Lundincf808d22015-05-27 14:33:29 +02001615int NetEqImpl::DoAccelerate(int16_t* decoded_buffer,
1616 size_t decoded_length,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001617 AudioDecoder::SpeechType speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +02001618 bool play_dtmf,
1619 bool fast_accelerate) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001620 const size_t required_samples =
1621 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001622 size_t borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001623 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001624 size_t decoded_length_per_channel = decoded_length / num_channels;
1625 if (decoded_length_per_channel < required_samples) {
1626 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001627 borrowed_samples_per_channel = static_cast<int>(required_samples -
1628 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001629 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1630 decoded_buffer,
1631 sizeof(int16_t) * decoded_length);
1632 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1633 decoded_buffer);
1634 decoded_length = required_samples * num_channels;
1635 }
1636
Peter Kastingdce40cf2015-08-24 14:52:23 -07001637 size_t samples_removed;
Henrik Lundincf808d22015-05-27 14:33:29 +02001638 Accelerate::ReturnCodes return_code =
1639 accelerate_->Process(decoded_buffer, decoded_length, fast_accelerate,
1640 algorithm_buffer_.get(), &samples_removed);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001641 stats_.AcceleratedSamples(samples_removed);
1642 switch (return_code) {
1643 case Accelerate::kSuccess:
1644 last_mode_ = kModeAccelerateSuccess;
1645 break;
1646 case Accelerate::kSuccessLowEnergy:
1647 last_mode_ = kModeAccelerateLowEnergy;
1648 break;
1649 case Accelerate::kNoStretch:
1650 last_mode_ = kModeAccelerateFail;
1651 break;
1652 case Accelerate::kError:
1653 // TODO(hlundin): Map to kModeError instead?
1654 last_mode_ = kModeAccelerateFail;
1655 return kAccelerateError;
1656 }
1657
1658 if (borrowed_samples_per_channel > 0) {
1659 // Copy borrowed samples back to the |sync_buffer_|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001660 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001661 if (length < borrowed_samples_per_channel) {
1662 // This destroys the beginning of the buffer, but will not cause any
1663 // problems.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001664 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001665 sync_buffer_->Size() -
1666 borrowed_samples_per_channel);
1667 sync_buffer_->PushFrontZeros(borrowed_samples_per_channel - length);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001668 algorithm_buffer_->PopFront(length);
1669 assert(algorithm_buffer_->Empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001670 } else {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001671 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001672 borrowed_samples_per_channel,
1673 sync_buffer_->Size() -
1674 borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001675 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001676 }
1677 }
1678
1679 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1680 if (speech_type == AudioDecoder::kComfortNoise) {
1681 last_mode_ = kModeCodecInternalCng;
1682 }
1683 if (!play_dtmf) {
1684 dtmf_tone_generator_->Reset();
1685 }
1686 expand_->Reset();
1687 return 0;
1688}
1689
1690int NetEqImpl::DoPreemptiveExpand(int16_t* decoded_buffer,
1691 size_t decoded_length,
1692 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001693 bool play_dtmf) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001694 const size_t required_samples =
1695 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001696 size_t num_channels = algorithm_buffer_->Channels();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001697 size_t borrowed_samples_per_channel = 0;
1698 size_t old_borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001699 size_t decoded_length_per_channel = decoded_length / num_channels;
1700 if (decoded_length_per_channel < required_samples) {
1701 // Must move data from the |sync_buffer_| in order to get 30 ms.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001702 borrowed_samples_per_channel =
1703 required_samples - decoded_length_per_channel;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001704 // Calculate how many of these were already played out.
Peter Kastingf045e4d2015-06-10 21:15:38 -07001705 old_borrowed_samples_per_channel =
Peter Kastingdce40cf2015-08-24 14:52:23 -07001706 (borrowed_samples_per_channel > sync_buffer_->FutureLength()) ?
1707 (borrowed_samples_per_channel - sync_buffer_->FutureLength()) : 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001708 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1709 decoded_buffer,
1710 sizeof(int16_t) * decoded_length);
1711 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1712 decoded_buffer);
1713 decoded_length = required_samples * num_channels;
1714 }
1715
Peter Kastingdce40cf2015-08-24 14:52:23 -07001716 size_t samples_added;
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001717 PreemptiveExpand::ReturnCodes return_code = preemptive_expand_->Process(
Peter Kastingdce40cf2015-08-24 14:52:23 -07001718 decoded_buffer, decoded_length,
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001719 old_borrowed_samples_per_channel,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001720 algorithm_buffer_.get(), &samples_added);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001721 stats_.PreemptiveExpandedSamples(samples_added);
1722 switch (return_code) {
1723 case PreemptiveExpand::kSuccess:
1724 last_mode_ = kModePreemptiveExpandSuccess;
1725 break;
1726 case PreemptiveExpand::kSuccessLowEnergy:
1727 last_mode_ = kModePreemptiveExpandLowEnergy;
1728 break;
1729 case PreemptiveExpand::kNoStretch:
1730 last_mode_ = kModePreemptiveExpandFail;
1731 break;
1732 case PreemptiveExpand::kError:
1733 // TODO(hlundin): Map to kModeError instead?
1734 last_mode_ = kModePreemptiveExpandFail;
1735 return kPreemptiveExpandError;
1736 }
1737
1738 if (borrowed_samples_per_channel > 0) {
1739 // Copy borrowed samples back to the |sync_buffer_|.
1740 sync_buffer_->ReplaceAtIndex(
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001741 *algorithm_buffer_, borrowed_samples_per_channel,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001742 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001743 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001744 }
1745
1746 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1747 if (speech_type == AudioDecoder::kComfortNoise) {
1748 last_mode_ = kModeCodecInternalCng;
1749 }
1750 if (!play_dtmf) {
1751 dtmf_tone_generator_->Reset();
1752 }
1753 expand_->Reset();
1754 return 0;
1755}
1756
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001757int NetEqImpl::DoRfc3389Cng(PacketList* packet_list, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001758 if (!packet_list->empty()) {
1759 // Must have exactly one SID frame at this point.
1760 assert(packet_list->size() == 1);
1761 Packet* packet = packet_list->front();
1762 packet_list->pop_front();
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001763 if (!decoder_database_->IsComfortNoise(packet->header.payloadType)) {
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001764 LOG(LS_ERROR) << "Trying to decode non-CNG payload as CNG.";
1765 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001766 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001767 // UpdateParameters() deletes |packet|.
1768 if (comfort_noise_->UpdateParameters(packet) ==
1769 ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001770 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001771 return -comfort_noise_->internal_error_code();
1772 }
1773 }
1774 int cn_return = comfort_noise_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001775 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001776 expand_->Reset();
1777 last_mode_ = kModeRfc3389Cng;
1778 if (!play_dtmf) {
1779 dtmf_tone_generator_->Reset();
1780 }
1781 if (cn_return == ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001782 decoder_error_code_ = comfort_noise_->internal_error_code();
1783 return kComfortNoiseErrorCode;
1784 } else if (cn_return == ComfortNoise::kUnknownPayloadType) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001785 return kUnknownRtpPayloadType;
1786 }
1787 return 0;
1788}
1789
minyuel6d92bf52015-09-23 15:20:39 +02001790void NetEqImpl::DoCodecInternalCng(const int16_t* decoded_buffer,
1791 size_t decoded_length) {
1792 RTC_DCHECK(normal_.get());
1793 RTC_DCHECK(mute_factor_array_.get());
1794 normal_->Process(decoded_buffer, decoded_length, last_mode_,
1795 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001796 last_mode_ = kModeCodecInternalCng;
1797 expand_->Reset();
1798}
1799
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001800int NetEqImpl::DoDtmf(const DtmfEvent& dtmf_event, bool* play_dtmf) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001801 // This block of the code and the block further down, handling |dtmf_switch|
1802 // are commented out. Otherwise playing out-of-band DTMF would fail in VoE
1803 // test, DtmfTest.ManualSuccessfullySendsOutOfBandTelephoneEvents. This is
1804 // equivalent to |dtmf_switch| always be false.
1805 //
1806 // See http://webrtc-codereview.appspot.com/1195004/ for discussion
1807 // On this issue. This change might cause some glitches at the point of
1808 // switch from audio to DTMF. Issue 1545 is filed to track this.
1809 //
1810 // bool dtmf_switch = false;
1811 // if ((last_mode_ != kModeDtmf) && dtmf_tone_generator_->initialized()) {
1812 // // Special case; see below.
1813 // // We must catch this before calling Generate, since |initialized| is
1814 // // modified in that call.
1815 // dtmf_switch = true;
1816 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001817
1818 int dtmf_return_value = 0;
1819 if (!dtmf_tone_generator_->initialized()) {
1820 // Initialize if not already done.
1821 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1822 dtmf_event.volume);
1823 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001824
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001825 if (dtmf_return_value == 0) {
1826 // Generate DTMF signal.
1827 dtmf_return_value = dtmf_tone_generator_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001828 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001829 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001830
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001831 if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001832 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001833 return dtmf_return_value;
1834 }
1835
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001836 // if (dtmf_switch) {
1837 // // This is the special case where the previous operation was DTMF
1838 // // overdub, but the current instruction is "regular" DTMF. We must make
1839 // // sure that the DTMF does not have any discontinuities. The first DTMF
1840 // // sample that we generate now must be played out immediately, therefore
1841 // // it must be copied to the speech buffer.
1842 // // TODO(hlundin): This code seems incorrect. (Legacy.) Write test and
1843 // // verify correct operation.
1844 // assert(false);
1845 // // Must generate enough data to replace all of the |sync_buffer_|
1846 // // "future".
1847 // int required_length = sync_buffer_->FutureLength();
1848 // assert(dtmf_tone_generator_->initialized());
1849 // dtmf_return_value = dtmf_tone_generator_->Generate(required_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001850 // algorithm_buffer_);
1851 // assert((size_t) required_length == algorithm_buffer_->Size());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001852 // if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001853 // algorithm_buffer_->Zeros(output_size_samples_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001854 // return dtmf_return_value;
1855 // }
1856 //
1857 // // Overwrite the "future" part of the speech buffer with the new DTMF
1858 // // data.
1859 // // TODO(hlundin): It seems that this overwriting has gone lost.
1860 // // Not adapted for multi-channel yet.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001861 // assert(algorithm_buffer_->Channels() == 1);
1862 // if (algorithm_buffer_->Channels() != 1) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001863 // LOG(LS_WARNING) << "DTMF not supported for more than one channel";
1864 // return kStereoNotSupported;
1865 // }
1866 // // Shuffle the remaining data to the beginning of algorithm buffer.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001867 // algorithm_buffer_->PopFront(sync_buffer_->FutureLength());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001868 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001869
Peter Kastingb7e50542015-06-11 12:55:50 -07001870 sync_buffer_->IncreaseEndTimestamp(
1871 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001872 expand_->Reset();
1873 last_mode_ = kModeDtmf;
1874
1875 // Set to false because the DTMF is already in the algorithm buffer.
1876 *play_dtmf = false;
1877 return 0;
1878}
1879
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001880void NetEqImpl::DoAlternativePlc(bool increase_timestamp) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001881 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001882 size_t length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001883 if (decoder && decoder->HasDecodePlc()) {
1884 // Use the decoder's packet-loss concealment.
1885 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1886 int16_t decoded_buffer[kMaxFrameSize];
1887 length = decoder->DecodePlc(1, decoded_buffer);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001888 if (length > 0)
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001889 algorithm_buffer_->PushBackInterleaved(decoded_buffer, length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001890 } else {
1891 // Do simple zero-stuffing.
1892 length = output_size_samples_;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001893 algorithm_buffer_->Zeros(length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001894 // By not advancing the timestamp, NetEq inserts samples.
1895 stats_.AddZeros(length);
1896 }
1897 if (increase_timestamp) {
Peter Kastingb7e50542015-06-11 12:55:50 -07001898 sync_buffer_->IncreaseEndTimestamp(static_cast<uint32_t>(length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001899 }
1900 expand_->Reset();
1901}
1902
1903int NetEqImpl::DtmfOverdub(const DtmfEvent& dtmf_event, size_t num_channels,
1904 int16_t* output) const {
1905 size_t out_index = 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001906 size_t overdub_length = output_size_samples_; // Default value.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001907
1908 if (sync_buffer_->dtmf_index() > sync_buffer_->next_index()) {
1909 // Special operation for transition from "DTMF only" to "DTMF overdub".
1910 out_index = std::min(
1911 sync_buffer_->dtmf_index() - sync_buffer_->next_index(),
Peter Kastingdce40cf2015-08-24 14:52:23 -07001912 output_size_samples_);
1913 overdub_length = output_size_samples_ - out_index;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001914 }
1915
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001916 AudioMultiVector dtmf_output(num_channels);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001917 int dtmf_return_value = 0;
1918 if (!dtmf_tone_generator_->initialized()) {
1919 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1920 dtmf_event.volume);
1921 }
1922 if (dtmf_return_value == 0) {
1923 dtmf_return_value = dtmf_tone_generator_->Generate(overdub_length,
1924 &dtmf_output);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001925 assert(overdub_length == dtmf_output.Size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001926 }
1927 dtmf_output.ReadInterleaved(overdub_length, &output[out_index]);
1928 return dtmf_return_value < 0 ? dtmf_return_value : 0;
1929}
1930
Peter Kastingdce40cf2015-08-24 14:52:23 -07001931int NetEqImpl::ExtractPackets(size_t required_samples,
1932 PacketList* packet_list) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001933 bool first_packet = true;
1934 uint8_t prev_payload_type = 0;
1935 uint32_t prev_timestamp = 0;
1936 uint16_t prev_sequence_number = 0;
1937 bool next_packet_available = false;
1938
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001939 const RTPHeader* header = packet_buffer_->NextRtpHeader();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001940 assert(header);
1941 if (!header) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001942 LOG(LS_ERROR) << "Packet buffer unexpectedly empty.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001943 return -1;
1944 }
turaj@webrtc.org7df97062013-08-02 18:07:13 +00001945 uint32_t first_timestamp = header->timestamp;
ossu61a208b2016-09-20 01:38:00 -07001946 size_t extracted_samples = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001947
1948 // Packet extraction loop.
1949 do {
1950 timestamp_ = header->timestamp;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001951 size_t discard_count = 0;
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001952 Packet* packet = packet_buffer_->GetNextPacket(&discard_count);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001953 // |header| may be invalid after the |packet_buffer_| operation.
1954 header = NULL;
1955 if (!packet) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001956 LOG(LS_ERROR) << "Should always be able to extract a packet here";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001957 assert(false); // Should always be able to extract a packet here.
1958 return -1;
1959 }
1960 stats_.PacketsDiscarded(discard_count);
henrik.lundin84f8cd62016-04-26 07:45:16 -07001961 stats_.StoreWaitingTime(packet->waiting_time->ElapsedMs());
ossu61a208b2016-09-20 01:38:00 -07001962 RTC_DCHECK(!packet->empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001963 packet_list->push_back(packet); // Store packet in list.
1964
1965 if (first_packet) {
1966 first_packet = false;
henrik.lundin48ed9302015-10-29 05:36:24 -07001967 if (nack_enabled_) {
1968 RTC_DCHECK(nack_);
1969 // TODO(henrik.lundin): Should we update this for all decoded packets?
1970 nack_->UpdateLastDecodedPacket(packet->header.sequenceNumber,
1971 packet->header.timestamp);
1972 }
1973 prev_sequence_number = packet->header.sequenceNumber;
1974 prev_timestamp = packet->header.timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001975 prev_payload_type = packet->header.payloadType;
1976 }
1977
1978 // Store number of extracted samples.
ossu61a208b2016-09-20 01:38:00 -07001979 size_t packet_duration = 0;
1980 if (packet->frame) {
1981 packet_duration = packet->frame->Duration();
1982 // TODO(ossu): Is this the correct way to track samples decoded from a
1983 // redundant packet?
1984 if (packet_duration > 0 && !packet->primary) {
1985 stats_.SecondaryDecodedSamples(rtc::checked_cast<int>(packet_duration));
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);
ossu61a208b2016-09-20 01:38:00 -07001990 RTC_NOTREACHED();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001991 }
ossu61a208b2016-09-20 01:38:00 -07001992
1993 if (packet_duration == 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001994 // Decoder did not return a packet duration. Assume that the packet
1995 // contains the same number of samples as the previous one.
ossu61a208b2016-09-20 01:38:00 -07001996 packet_duration = decoder_frame_length_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001997 }
1998 extracted_samples = packet->header.timestamp - first_timestamp +
1999 packet_duration;
2000
2001 // Check what packet is available next.
2002 header = packet_buffer_->NextRtpHeader();
2003 next_packet_available = false;
2004 if (header && prev_payload_type == header->payloadType) {
2005 int16_t seq_no_diff = header->sequenceNumber - prev_sequence_number;
Peter Kastingdce40cf2015-08-24 14:52:23 -07002006 size_t ts_diff = header->timestamp - prev_timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002007 if (seq_no_diff == 1 ||
2008 (seq_no_diff == 0 && ts_diff == decoder_frame_length_)) {
2009 // The next sequence number is available, or the next part of a packet
2010 // that was split into pieces upon insertion.
2011 next_packet_available = true;
2012 }
2013 prev_sequence_number = header->sequenceNumber;
2014 }
ossu61a208b2016-09-20 01:38:00 -07002015 } while (extracted_samples < required_samples && 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
ossu61a208b2016-09-20 01:38:00 -07002025 return rtc::checked_cast<int>(extracted_samples);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002026}
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