blob: b60f1b86e58a1cf05dd97eb3511edb607a8867fa [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"
ossua70695a2016-09-22 02:06:28 -070044#include "webrtc/modules/audio_coding/neteq/red_payload_splitter.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000045#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())),
ossua70695a2016-09-22 02:06:28 -070068 red_payload_splitter(new RedPayloadSplitter),
henrik.lundin1d9061e2016-04-26 12:19:34 -070069 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)),
ossua70695a2016-09-22 02:06:28 -070087 red_payload_splitter_(std::move(deps.red_payload_splitter)),
henrik.lundin1d9061e2016-04-26 12:19:34 -070088 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
kwiberg5adaf732016-10-04 09:33:27 -0700282bool NetEqImpl::RegisterPayloadType(int rtp_payload_type,
283 const SdpAudioFormat& audio_format) {
284 LOG(LS_VERBOSE) << "NetEqImpl::RegisterPayloadType: payload type "
285 << rtp_payload_type << ", codec " << audio_format;
286 rtc::CritScope lock(&crit_sect_);
287 switch (decoder_database_->RegisterPayload(rtp_payload_type, audio_format)) {
288 case DecoderDatabase::kOK:
289 return true;
290 case DecoderDatabase::kInvalidRtpPayloadType:
291 error_code_ = kInvalidRtpPayloadType;
292 return false;
293 case DecoderDatabase::kCodecNotSupported:
294 error_code_ = kCodecNotSupported;
295 return false;
296 case DecoderDatabase::kDecoderExists:
297 error_code_ = kDecoderExists;
298 return false;
299 case DecoderDatabase::kInvalidSampleRate:
300 error_code_ = kInvalidSampleRate;
301 return false;
302 case DecoderDatabase::kInvalidPointer:
303 error_code_ = kInvalidPointer;
304 return false;
305 default:
306 error_code_ = kOtherError;
307 return false;
308 }
309}
310
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000311int NetEqImpl::RemovePayloadType(uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100312 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000313 int ret = decoder_database_->Remove(rtp_payload_type);
314 if (ret == DecoderDatabase::kOK) {
ossu61a208b2016-09-20 01:38:00 -0700315 packet_buffer_->DiscardPacketsWithPayloadType(rtp_payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000316 return kOK;
317 } else if (ret == DecoderDatabase::kDecoderNotFound) {
318 error_code_ = kDecoderNotFound;
319 } else {
320 error_code_ = kOtherError;
321 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000322 return kFail;
323}
324
kwiberg6b19b562016-09-20 04:02:25 -0700325void NetEqImpl::RemoveAllPayloadTypes() {
326 rtc::CritScope lock(&crit_sect_);
327 decoder_database_->RemoveAll();
328}
329
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000330bool NetEqImpl::SetMinimumDelay(int delay_ms) {
Tommi9090e0b2016-01-20 13:39:36 +0100331 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000332 if (delay_ms >= 0 && delay_ms < 10000) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000333 assert(delay_manager_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000334 return delay_manager_->SetMinimumDelay(delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000335 }
336 return false;
337}
338
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000339bool NetEqImpl::SetMaximumDelay(int delay_ms) {
Tommi9090e0b2016-01-20 13:39:36 +0100340 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000341 if (delay_ms >= 0 && delay_ms < 10000) {
342 assert(delay_manager_.get());
343 return delay_manager_->SetMaximumDelay(delay_ms);
344 }
345 return false;
346}
347
348int NetEqImpl::LeastRequiredDelayMs() const {
Tommi9090e0b2016-01-20 13:39:36 +0100349 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000350 assert(delay_manager_.get());
351 return delay_manager_->least_required_delay_ms();
352}
353
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200354int NetEqImpl::SetTargetDelay() {
355 return kNotImplemented;
356}
357
358int NetEqImpl::TargetDelay() {
359 return kNotImplemented;
360}
361
henrik.lundin9c3efd02015-08-27 13:12:22 -0700362int NetEqImpl::CurrentDelayMs() const {
Tommi9090e0b2016-01-20 13:39:36 +0100363 rtc::CritScope lock(&crit_sect_);
henrik.lundin9c3efd02015-08-27 13:12:22 -0700364 if (fs_hz_ == 0)
365 return 0;
366 // Sum up the samples in the packet buffer with the future length of the sync
367 // buffer, and divide the sum by the sample rate.
368 const size_t delay_samples =
ossu61a208b2016-09-20 01:38:00 -0700369 packet_buffer_->NumSamplesInBuffer(decoder_frame_length_) +
henrik.lundin9c3efd02015-08-27 13:12:22 -0700370 sync_buffer_->FutureLength();
371 // The division below will truncate.
372 const int delay_ms =
373 static_cast<int>(delay_samples) / rtc::CheckedDivExact(fs_hz_, 1000);
374 return delay_ms;
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200375}
376
henrik.lundinb3f1c5d2016-08-22 15:39:53 -0700377int NetEqImpl::FilteredCurrentDelayMs() const {
378 rtc::CritScope lock(&crit_sect_);
379 // Calculate the filtered packet buffer level in samples. The value from
380 // |buffer_level_filter_| is in number of packets, represented in Q8.
381 const size_t packet_buffer_samples =
382 (buffer_level_filter_->filtered_current_level() *
383 decoder_frame_length_) >>
384 8;
385 // Sum up the filtered packet buffer level with the future length of the sync
386 // buffer, and divide the sum by the sample rate.
387 const size_t delay_samples =
388 packet_buffer_samples + sync_buffer_->FutureLength();
389 // The division below will truncate. The return value is in ms.
390 return static_cast<int>(delay_samples) / rtc::CheckedDivExact(fs_hz_, 1000);
391}
392
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000393// Deprecated.
394// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000395void NetEqImpl::SetPlayoutMode(NetEqPlayoutMode mode) {
Tommi9090e0b2016-01-20 13:39:36 +0100396 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000397 if (mode != playout_mode_) {
398 playout_mode_ = mode;
399 CreateDecisionLogic();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000400 }
401}
402
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000403// Deprecated.
404// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000405NetEqPlayoutMode NetEqImpl::PlayoutMode() const {
Tommi9090e0b2016-01-20 13:39:36 +0100406 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000407 return playout_mode_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000408}
409
410int NetEqImpl::NetworkStatistics(NetEqNetworkStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100411 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000412 assert(decoder_database_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700413 const size_t total_samples_in_buffers =
ossu61a208b2016-09-20 01:38:00 -0700414 packet_buffer_->NumSamplesInBuffer(decoder_frame_length_) +
Peter Kastingdce40cf2015-08-24 14:52:23 -0700415 sync_buffer_->FutureLength();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000416 assert(delay_manager_.get());
417 assert(decision_logic_.get());
418 stats_.GetNetworkStatistics(fs_hz_, total_samples_in_buffers,
419 decoder_frame_length_, *delay_manager_.get(),
420 *decision_logic_.get(), stats);
421 return 0;
422}
423
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000424void NetEqImpl::GetRtcpStatistics(RtcpStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100425 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000426 if (stats) {
427 rtcp_.GetStatistics(false, stats);
428 }
429}
430
431void NetEqImpl::GetRtcpStatisticsNoReset(RtcpStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100432 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000433 if (stats) {
434 rtcp_.GetStatistics(true, stats);
435 }
436}
437
438void NetEqImpl::EnableVad() {
Tommi9090e0b2016-01-20 13:39:36 +0100439 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000440 assert(vad_.get());
441 vad_->Enable();
442}
443
444void NetEqImpl::DisableVad() {
Tommi9090e0b2016-01-20 13:39:36 +0100445 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000446 assert(vad_.get());
447 vad_->Disable();
448}
449
henrik.lundin15c51e32016-04-06 08:38:56 -0700450rtc::Optional<uint32_t> NetEqImpl::GetPlayoutTimestamp() const {
Tommi9090e0b2016-01-20 13:39:36 +0100451 rtc::CritScope lock(&crit_sect_);
henrik.lundin0d96ab72016-04-06 12:28:26 -0700452 if (first_packet_ || last_mode_ == kModeRfc3389Cng ||
453 last_mode_ == kModeCodecInternalCng) {
wu@webrtc.org94454b72014-06-05 20:34:08 +0000454 // We don't have a valid RTP timestamp until we have decoded our first
henrik.lundin0d96ab72016-04-06 12:28:26 -0700455 // RTP packet. Also, the RTP timestamp is not accurate while playing CNG,
456 // which is indicated by returning an empty value.
henrik.lundin9a410dd2016-04-06 01:39:22 -0700457 return rtc::Optional<uint32_t>();
wu@webrtc.org94454b72014-06-05 20:34:08 +0000458 }
henrik.lundin9a410dd2016-04-06 01:39:22 -0700459 return rtc::Optional<uint32_t>(
460 timestamp_scaler_->ToExternal(playout_timestamp_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000461}
462
henrik.lundind89814b2015-11-23 06:49:25 -0800463int NetEqImpl::last_output_sample_rate_hz() const {
Tommi9090e0b2016-01-20 13:39:36 +0100464 rtc::CritScope lock(&crit_sect_);
henrik.lundind89814b2015-11-23 06:49:25 -0800465 return last_output_sample_rate_hz_;
466}
467
kwiberg6f0f6162016-09-20 03:07:46 -0700468rtc::Optional<CodecInst> NetEqImpl::GetDecoder(int payload_type) const {
469 rtc::CritScope lock(&crit_sect_);
470 const DecoderDatabase::DecoderInfo* di =
471 decoder_database_->GetDecoderInfo(payload_type);
472 if (!di) {
473 return rtc::Optional<CodecInst>();
474 }
475
476 // Create a CodecInst with some fields set. The remaining fields are zeroed,
477 // but we tell MSan to consider them uninitialized.
478 CodecInst ci = {0};
479 rtc::MsanMarkUninitialized(rtc::MakeArrayView(&ci, 1));
480 ci.pltype = payload_type;
481 std::strncpy(ci.plname, di->name.c_str(), sizeof(ci.plname));
482 ci.plname[sizeof(ci.plname) - 1] = '\0';
483 ci.plfreq = di->IsRed() || di->IsDtmf() ? 8000 : di->SampleRateHz();
484 AudioDecoder* const decoder = di->GetDecoder();
485 ci.channels = decoder ? decoder->Channels() : 1;
486 return rtc::Optional<CodecInst>(ci);
487}
488
ossuf1b08da2016-09-23 02:19:43 -0700489rtc::Optional<SdpAudioFormat> NetEqImpl::GetDecoderFormat(
490 int payload_type) const {
kwibergc4ccd4d2016-09-21 10:55:15 -0700491 rtc::CritScope lock(&crit_sect_);
492 const DecoderDatabase::DecoderInfo* const di =
493 decoder_database_->GetDecoderInfo(payload_type);
494 if (!di) {
ossuf1b08da2016-09-23 02:19:43 -0700495 return rtc::Optional<SdpAudioFormat>(); // Payload type not registered.
kwibergc4ccd4d2016-09-21 10:55:15 -0700496 }
ossuf1b08da2016-09-23 02:19:43 -0700497 return rtc::Optional<SdpAudioFormat>(di->GetFormat());
kwibergc4ccd4d2016-09-21 10:55:15 -0700498}
499
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200500int NetEqImpl::SetTargetNumberOfChannels() {
501 return kNotImplemented;
502}
503
504int NetEqImpl::SetTargetSampleRate() {
505 return kNotImplemented;
506}
507
henrik.lundin@webrtc.orgb0f4b3d2014-11-04 08:53:10 +0000508int NetEqImpl::LastError() const {
Tommi9090e0b2016-01-20 13:39:36 +0100509 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000510 return error_code_;
511}
512
513int NetEqImpl::LastDecoderError() {
Tommi9090e0b2016-01-20 13:39:36 +0100514 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000515 return decoder_error_code_;
516}
517
518void NetEqImpl::FlushBuffers() {
Tommi9090e0b2016-01-20 13:39:36 +0100519 rtc::CritScope lock(&crit_sect_);
Henrik Lundind67a2192015-08-03 12:54:37 +0200520 LOG(LS_VERBOSE) << "FlushBuffers";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000521 packet_buffer_->Flush();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000522 assert(sync_buffer_.get());
523 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000524 sync_buffer_->Flush();
525 sync_buffer_->set_next_index(sync_buffer_->next_index() -
526 expand_->overlap_length());
527 // Set to wait for new codec.
528 first_packet_ = true;
529}
530
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000531void NetEqImpl::PacketBufferStatistics(int* current_num_packets,
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000532 int* max_num_packets) const {
Tommi9090e0b2016-01-20 13:39:36 +0100533 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000534 packet_buffer_->BufferStat(current_num_packets, max_num_packets);
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000535}
536
henrik.lundin48ed9302015-10-29 05:36:24 -0700537void NetEqImpl::EnableNack(size_t max_nack_list_size) {
Tommi9090e0b2016-01-20 13:39:36 +0100538 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700539 if (!nack_enabled_) {
540 const int kNackThresholdPackets = 2;
henrik.lundin91951862016-06-08 06:43:41 -0700541 nack_.reset(NackTracker::Create(kNackThresholdPackets));
henrik.lundin48ed9302015-10-29 05:36:24 -0700542 nack_enabled_ = true;
543 nack_->UpdateSampleRate(fs_hz_);
544 }
545 nack_->SetMaxNackListSize(max_nack_list_size);
546}
547
548void NetEqImpl::DisableNack() {
Tommi9090e0b2016-01-20 13:39:36 +0100549 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700550 nack_.reset();
551 nack_enabled_ = false;
552}
553
554std::vector<uint16_t> NetEqImpl::GetNackList(int64_t round_trip_time_ms) const {
Tommi9090e0b2016-01-20 13:39:36 +0100555 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700556 if (!nack_enabled_) {
557 return std::vector<uint16_t>();
558 }
559 RTC_DCHECK(nack_.get());
560 return nack_->GetNackList(round_trip_time_ms);
minyue@webrtc.orgd7301772013-08-29 00:58:14 +0000561}
562
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000563const SyncBuffer* NetEqImpl::sync_buffer_for_test() const {
Tommi9090e0b2016-01-20 13:39:36 +0100564 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000565 return sync_buffer_.get();
566}
567
minyue5bd33972016-05-02 04:46:11 -0700568Operations NetEqImpl::last_operation_for_test() const {
569 rtc::CritScope lock(&crit_sect_);
570 return last_operation_;
571}
572
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000573// Methods below this line are private.
574
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000575int NetEqImpl::InsertPacketInternal(const WebRtcRTPHeader& rtp_header,
kwibergee2bac22015-11-11 10:34:00 -0800576 rtc::ArrayView<const uint8_t> payload,
ossu17e3fa12016-09-08 04:52:55 -0700577 uint32_t receive_timestamp) {
kwibergee2bac22015-11-11 10:34:00 -0800578 if (payload.empty()) {
579 LOG_F(LS_ERROR) << "payload is empty";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000580 return kInvalidPointer;
581 }
ossu17e3fa12016-09-08 04:52:55 -0700582
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000583 PacketList packet_list;
584 RTPHeader main_header;
585 {
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000586 // Convert to Packet.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000587 // Create |packet| within this separate scope, since it should not be used
588 // directly once it's been inserted in the packet list. This way, |packet|
589 // is not defined outside of this block.
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000590 Packet* packet = new Packet;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000591 packet->header.markerBit = false;
592 packet->header.payloadType = rtp_header.header.payloadType;
593 packet->header.sequenceNumber = rtp_header.header.sequenceNumber;
594 packet->header.timestamp = rtp_header.header.timestamp;
595 packet->header.ssrc = rtp_header.header.ssrc;
596 packet->header.numCSRCs = 0;
ossudc431ce2016-08-31 08:51:13 -0700597 packet->payload.SetData(payload.data(), payload.size());
henrik.lundin84f8cd62016-04-26 07:45:16 -0700598 // Waiting time will be set upon inserting the packet in the buffer.
599 RTC_DCHECK(!packet->waiting_time);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000600 // Insert packet in a packet list.
601 packet_list.push_back(packet);
602 // Save main payloads header for later.
603 memcpy(&main_header, &packet->header, sizeof(main_header));
604 }
605
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000606 bool update_sample_rate_and_channels = false;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000607 // Reinitialize NetEq if it's needed (changed SSRC or first call).
608 if ((main_header.ssrc != ssrc_) || first_packet_) {
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000609 // Note: |first_packet_| will be cleared further down in this method, once
610 // the packet has been successfully inserted into the packet buffer.
611
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000612 rtcp_.Init(main_header.sequenceNumber);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000613
614 // Flush the packet buffer and DTMF buffer.
615 packet_buffer_->Flush();
616 dtmf_buffer_->Flush();
617
618 // Store new SSRC.
619 ssrc_ = main_header.ssrc;
620
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000621 // Update audio buffer timestamp.
622 sync_buffer_->IncreaseEndTimestamp(main_header.timestamp - timestamp_);
623
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000624 // Update codecs.
625 timestamp_ = main_header.timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000626
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000627 // Reset timestamp scaling.
628 timestamp_scaler_->Reset();
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000629
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000630 // Trigger an update of sampling rate and the number of channels.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000631 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000632 }
633
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000634 // Update RTCP statistics, only for regular packets.
ossu17e3fa12016-09-08 04:52:55 -0700635 rtcp_.Update(main_header, receive_timestamp);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000636
637 // Check for RED payload type, and separate payloads into several packets.
638 if (decoder_database_->IsRed(main_header.payloadType)) {
ossua70695a2016-09-22 02:06:28 -0700639 if (!red_payload_splitter_->SplitRed(&packet_list)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000640 PacketBuffer::DeleteAllPackets(&packet_list);
641 return kRedundancySplitError;
642 }
643 // Only accept a few RED payloads of the same type as the main data,
644 // DTMF events and CNG.
ossua70695a2016-09-22 02:06:28 -0700645 red_payload_splitter_->CheckRedPayloads(&packet_list, *decoder_database_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000646 // Update the stored main payload header since the main payload has now
647 // changed.
648 memcpy(&main_header, &packet_list.front()->header, sizeof(main_header));
649 }
650
651 // Check payload types.
652 if (decoder_database_->CheckPayloadTypes(packet_list) ==
653 DecoderDatabase::kDecoderNotFound) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000654 PacketBuffer::DeleteAllPackets(&packet_list);
655 return kUnknownRtpPayloadType;
656 }
657
658 // Scale timestamp to internal domain (only for some codecs).
659 timestamp_scaler_->ToInternal(&packet_list);
660
661 // Process DTMF payloads. Cycle through the list of packets, and pick out any
662 // DTMF payloads found.
663 PacketList::iterator it = packet_list.begin();
664 while (it != packet_list.end()) {
665 Packet* current_packet = (*it);
666 assert(current_packet);
ossudc431ce2016-08-31 08:51:13 -0700667 assert(!current_packet->payload.empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000668 if (decoder_database_->IsDtmf(current_packet->header.payloadType)) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000669 DtmfEvent event;
ossudc431ce2016-08-31 08:51:13 -0700670 int ret = DtmfBuffer::ParseEvent(current_packet->header.timestamp,
671 current_packet->payload.data(),
672 current_packet->payload.size(), &event);
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000673 if (ret != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000674 PacketBuffer::DeleteAllPackets(&packet_list);
675 return kDtmfParsingError;
676 }
677 if (dtmf_buffer_->InsertEvent(event) != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000678 PacketBuffer::DeleteAllPackets(&packet_list);
679 return kDtmfInsertError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000680 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000681 delete current_packet;
682 it = packet_list.erase(it);
683 } else {
684 ++it;
685 }
686 }
687
ossu17e3fa12016-09-08 04:52:55 -0700688 // Update bandwidth estimate, if the packet is not comfort noise.
689 if (!packet_list.empty() &&
ossu97ba30e2016-04-25 07:55:58 -0700690 !decoder_database_->IsComfortNoise(main_header.payloadType)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000691 // The list can be empty here if we got nothing but DTMF payloads.
692 AudioDecoder* decoder =
693 decoder_database_->GetDecoder(main_header.payloadType);
694 assert(decoder); // Should always get a valid object, since we have
ossu97ba30e2016-04-25 07:55:58 -0700695 // already checked that the payload types are known.
ossudc431ce2016-08-31 08:51:13 -0700696 decoder->IncomingPacket(packet_list.front()->payload.data(),
697 packet_list.front()->payload.size(),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000698 packet_list.front()->header.sequenceNumber,
699 packet_list.front()->header.timestamp,
700 receive_timestamp);
701 }
702
ossu61a208b2016-09-20 01:38:00 -0700703 PacketList parsed_packet_list;
704 while (!packet_list.empty()) {
705 std::unique_ptr<Packet> packet(packet_list.front());
706 packet_list.pop_front();
707 const DecoderDatabase::DecoderInfo* info =
708 decoder_database_->GetDecoderInfo(packet->header.payloadType);
709 if (!info) {
710 LOG(LS_WARNING) << "SplitAudio unknown payload type";
711 return kUnknownRtpPayloadType;
712 }
713
714 if (info->IsComfortNoise()) {
715 // Carry comfort noise packets along.
716 parsed_packet_list.push_back(packet.release());
717 } else {
718 std::vector<AudioDecoder::ParseResult> results =
719 info->GetDecoder()->ParsePayload(std::move(packet->payload),
ossua70695a2016-09-22 02:06:28 -0700720 packet->header.timestamp);
ossu61a208b2016-09-20 01:38:00 -0700721 const RTPHeader& original_header = packet->header;
ossua70695a2016-09-22 02:06:28 -0700722 const Packet::Priority original_priority = packet->priority;
ossu61a208b2016-09-20 01:38:00 -0700723 for (auto& result : results) {
724 RTC_DCHECK(result.frame);
ossu0d526d52016-09-21 01:57:31 -0700725 // Reuse the packet if possible.
ossu61a208b2016-09-20 01:38:00 -0700726 if (!packet) {
727 packet.reset(new Packet);
728 packet->header = original_header;
729 }
730 packet->header.timestamp = result.timestamp;
ossua70695a2016-09-22 02:06:28 -0700731 RTC_DCHECK_GE(result.priority, 0);
732 packet->priority.codec_level = result.priority;
733 packet->priority.red_level = original_priority.red_level;
ossu61a208b2016-09-20 01:38:00 -0700734 packet->frame = std::move(result.frame);
735 parsed_packet_list.push_back(packet.release());
736 }
737 }
738 }
739
henrik.lundin48ed9302015-10-29 05:36:24 -0700740 if (nack_enabled_) {
741 RTC_DCHECK(nack_);
742 if (update_sample_rate_and_channels) {
743 nack_->Reset();
744 }
ossu61a208b2016-09-20 01:38:00 -0700745 nack_->UpdateLastReceivedPacket(
746 parsed_packet_list.front()->header.sequenceNumber,
747 parsed_packet_list.front()->header.timestamp);
henrik.lundin48ed9302015-10-29 05:36:24 -0700748 }
749
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000750 // Insert packets in buffer.
henrik.lundin116c84e2015-08-27 13:14:48 -0700751 const size_t buffer_length_before_insert =
752 packet_buffer_->NumPacketsInBuffer();
ossua70695a2016-09-22 02:06:28 -0700753 const int ret = packet_buffer_->InsertPacketList(
ossu61a208b2016-09-20 01:38:00 -0700754 &parsed_packet_list, *decoder_database_, &current_rtp_payload_type_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000755 &current_cng_rtp_payload_type_);
756 if (ret == PacketBuffer::kFlushed) {
757 // Reset DSP timestamp etc. if packet buffer flushed.
758 new_codec_ = true;
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000759 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000760 } else if (ret != PacketBuffer::kOK) {
ossu61a208b2016-09-20 01:38:00 -0700761 PacketBuffer::DeleteAllPackets(&parsed_packet_list);
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000762 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000763 }
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000764
765 if (first_packet_) {
766 first_packet_ = false;
767 // Update the codec on the next GetAudio call.
768 new_codec_ = true;
769 }
770
henrik.lundinda8bbf62016-08-31 03:14:11 -0700771 if (current_rtp_payload_type_) {
772 RTC_DCHECK(decoder_database_->GetDecoderInfo(*current_rtp_payload_type_))
773 << "Payload type " << static_cast<int>(*current_rtp_payload_type_)
774 << " is unknown where it shouldn't be";
775 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000776
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000777 if (update_sample_rate_and_channels && !packet_buffer_->Empty()) {
778 // We do not use |current_rtp_payload_type_| to |set payload_type|, but
779 // get the next RTP header from |packet_buffer_| to obtain the payload type.
780 // The reason for it is the following corner case. If NetEq receives a
781 // CNG packet with a sample rate different than the current CNG then it
782 // flushes its buffer, assuming send codec must have been changed. However,
783 // payload type of the hypothetically new send codec is not known.
784 const RTPHeader* rtp_header = packet_buffer_->NextRtpHeader();
785 assert(rtp_header);
786 int payload_type = rtp_header->payloadType;
ossu97ba30e2016-04-25 07:55:58 -0700787 size_t channels = 1;
788 if (!decoder_database_->IsComfortNoise(payload_type)) {
789 AudioDecoder* decoder = decoder_database_->GetDecoder(payload_type);
790 assert(decoder); // Payloads are already checked to be valid.
791 channels = decoder->Channels();
792 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000793 const DecoderDatabase::DecoderInfo* decoder_info =
794 decoder_database_->GetDecoderInfo(payload_type);
795 assert(decoder_info);
kwibergc0f2dcf2016-05-31 06:28:03 -0700796 if (decoder_info->SampleRateHz() != fs_hz_ ||
ossu97ba30e2016-04-25 07:55:58 -0700797 channels != algorithm_buffer_->Channels()) {
kwibergc0f2dcf2016-05-31 06:28:03 -0700798 SetSampleRateAndChannels(decoder_info->SampleRateHz(),
799 channels);
henrik.lundin48ed9302015-10-29 05:36:24 -0700800 }
801 if (nack_enabled_) {
802 RTC_DCHECK(nack_);
803 // Update the sample rate even if the rate is not new, because of Reset().
804 nack_->UpdateSampleRate(fs_hz_);
805 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000806 }
807
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000808 // TODO(hlundin): Move this code to DelayManager class.
809 const DecoderDatabase::DecoderInfo* dec_info =
810 decoder_database_->GetDecoderInfo(main_header.payloadType);
811 assert(dec_info); // Already checked that the payload type is known.
ossuf1b08da2016-09-23 02:19:43 -0700812 delay_manager_->LastDecodedWasCngOrDtmf(dec_info->IsComfortNoise() ||
813 dec_info->IsDtmf());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000814 if (delay_manager_->last_pack_cng_or_dtmf() == 0) {
815 // Calculate the total speech length carried in each packet.
henrik.lundin116c84e2015-08-27 13:14:48 -0700816 const size_t buffer_length_after_insert =
817 packet_buffer_->NumPacketsInBuffer();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000818
henrik.lundin116c84e2015-08-27 13:14:48 -0700819 if (buffer_length_after_insert > buffer_length_before_insert) {
820 const size_t packet_length_samples =
821 (buffer_length_after_insert - buffer_length_before_insert) *
822 decoder_frame_length_;
823 if (packet_length_samples != decision_logic_->packet_length_samples()) {
824 decision_logic_->set_packet_length_samples(packet_length_samples);
825 delay_manager_->SetPacketAudioLength(
826 rtc::checked_cast<int>((1000 * packet_length_samples) / fs_hz_));
827 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000828 }
829
830 // Update statistics.
pbos@webrtc.org0946a562013-04-09 00:28:06 +0000831 if ((int32_t) (main_header.timestamp - timestamp_) >= 0 &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000832 !new_codec_) {
833 // Only update statistics if incoming packet is not older than last played
834 // out packet, and if new codec flag is not set.
835 delay_manager_->Update(main_header.sequenceNumber, main_header.timestamp,
836 fs_hz_);
837 }
838 } else if (delay_manager_->last_pack_cng_or_dtmf() == -1) {
839 // This is first "normal" packet after CNG or DTMF.
840 // Reset packet time counter and measure time until next packet,
841 // but don't update statistics.
842 delay_manager_->set_last_pack_cng_or_dtmf(0);
843 delay_manager_->ResetPacketIatCount();
844 }
845 return 0;
846}
847
henrik.lundin7a926812016-05-12 13:51:28 -0700848int NetEqImpl::GetAudioInternal(AudioFrame* audio_frame, bool* muted) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000849 PacketList packet_list;
850 DtmfEvent dtmf_event;
851 Operations operation;
852 bool play_dtmf;
henrik.lundin7a926812016-05-12 13:51:28 -0700853 *muted = false;
henrik.lundined497212016-04-25 10:11:38 -0700854 tick_timer_->Increment();
henrik.lundin60f6ce22016-05-10 03:52:04 -0700855 stats_.IncreaseCounter(output_size_samples_, fs_hz_);
henrik.lundin7a926812016-05-12 13:51:28 -0700856
857 // Check for muted state.
858 if (enable_muted_state_ && expand_->Muted() && packet_buffer_->Empty()) {
859 RTC_DCHECK_EQ(last_mode_, kModeExpand);
860 playout_timestamp_ += static_cast<uint32_t>(output_size_samples_);
861 audio_frame->sample_rate_hz_ = fs_hz_;
862 audio_frame->samples_per_channel_ = output_size_samples_;
863 audio_frame->timestamp_ =
864 first_packet_
865 ? 0
866 : timestamp_scaler_->ToExternal(playout_timestamp_) -
867 static_cast<uint32_t>(audio_frame->samples_per_channel_);
868 audio_frame->num_channels_ = sync_buffer_->Channels();
henrik.lundin612c25e2016-05-25 08:21:04 -0700869 stats_.ExpandedNoiseSamples(output_size_samples_);
henrik.lundin7a926812016-05-12 13:51:28 -0700870 *muted = true;
871 return 0;
872 }
873
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000874 int return_value = GetDecision(&operation, &packet_list, &dtmf_event,
875 &play_dtmf);
876 if (return_value != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000877 last_mode_ = kModeError;
878 return return_value;
879 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000880
881 AudioDecoder::SpeechType speech_type;
882 int length = 0;
883 int decode_return_value = Decode(&packet_list, &operation,
884 &length, &speech_type);
885
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000886 assert(vad_.get());
887 bool sid_frame_available =
888 (operation == kRfc3389Cng && !packet_list.empty());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700889 vad_->Update(decoded_buffer_.get(), static_cast<size_t>(length), speech_type,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000890 sid_frame_available, fs_hz_);
891
henrik.lundinb1fb72b2016-05-03 08:18:47 -0700892 if (sid_frame_available || speech_type == AudioDecoder::kComfortNoise) {
893 // Start a new stopwatch since we are decoding a new CNG packet.
894 generated_noise_stopwatch_ = tick_timer_->GetNewStopwatch();
895 }
896
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000897 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000898 switch (operation) {
899 case kNormal: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000900 DoNormal(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000901 break;
902 }
903 case kMerge: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000904 DoMerge(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000905 break;
906 }
907 case kExpand: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000908 return_value = DoExpand(play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000909 break;
910 }
Henrik Lundincf808d22015-05-27 14:33:29 +0200911 case kAccelerate:
912 case kFastAccelerate: {
913 const bool fast_accelerate =
914 enable_fast_accelerate_ && (operation == kFastAccelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000915 return_value = DoAccelerate(decoded_buffer_.get(), length, speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +0200916 play_dtmf, fast_accelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000917 break;
918 }
919 case kPreemptiveExpand: {
920 return_value = DoPreemptiveExpand(decoded_buffer_.get(), length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000921 speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000922 break;
923 }
924 case kRfc3389Cng:
925 case kRfc3389CngNoPacket: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000926 return_value = DoRfc3389Cng(&packet_list, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000927 break;
928 }
929 case kCodecInternalCng: {
930 // This handles the case when there is no transmission and the decoder
931 // should produce internal comfort noise.
932 // TODO(hlundin): Write test for codec-internal CNG.
minyuel6d92bf52015-09-23 15:20:39 +0200933 DoCodecInternalCng(decoded_buffer_.get(), length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000934 break;
935 }
936 case kDtmf: {
937 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000938 return_value = DoDtmf(dtmf_event, &play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000939 break;
940 }
941 case kAlternativePlc: {
942 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000943 DoAlternativePlc(false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000944 break;
945 }
946 case kAlternativePlcIncreaseTimestamp: {
947 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000948 DoAlternativePlc(true);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000949 break;
950 }
951 case kAudioRepetitionIncreaseTimestamp: {
952 // TODO(hlundin): Write test for this.
Peter Kastingb7e50542015-06-11 12:55:50 -0700953 sync_buffer_->IncreaseEndTimestamp(
954 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000955 // Skipping break on purpose. Execution should move on into the
956 // next case.
kjellander@webrtc.org7d2b6a92015-01-28 18:37:58 +0000957 FALLTHROUGH();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000958 }
959 case kAudioRepetition: {
960 // TODO(hlundin): Write test for this.
961 // Copy last |output_size_samples_| from |sync_buffer_| to
962 // |algorithm_buffer|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000963 algorithm_buffer_->PushBackFromIndex(
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000964 *sync_buffer_, sync_buffer_->Size() - output_size_samples_);
965 expand_->Reset();
966 break;
967 }
968 case kUndefined: {
Henrik Lundind67a2192015-08-03 12:54:37 +0200969 LOG(LS_ERROR) << "Invalid operation kUndefined.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000970 assert(false); // This should not happen.
971 last_mode_ = kModeError;
972 return kInvalidOperation;
973 }
974 } // End of switch.
minyue5bd33972016-05-02 04:46:11 -0700975 last_operation_ = operation;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000976 if (return_value < 0) {
977 return return_value;
978 }
979
980 if (last_mode_ != kModeRfc3389Cng) {
981 comfort_noise_->Reset();
982 }
983
984 // Copy from |algorithm_buffer| to |sync_buffer_|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000985 sync_buffer_->PushBack(*algorithm_buffer_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000986
987 // Extract data from |sync_buffer_| to |output|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000988 size_t num_output_samples_per_channel = output_size_samples_;
989 size_t num_output_samples = output_size_samples_ * sync_buffer_->Channels();
henrik.lundin6d8e0112016-03-04 10:34:21 -0800990 if (num_output_samples > AudioFrame::kMaxDataSizeSamples) {
991 LOG(LS_WARNING) << "Output array is too short. "
992 << AudioFrame::kMaxDataSizeSamples << " < "
993 << output_size_samples_ << " * "
994 << sync_buffer_->Channels();
995 num_output_samples = AudioFrame::kMaxDataSizeSamples;
996 num_output_samples_per_channel =
997 AudioFrame::kMaxDataSizeSamples / sync_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000998 }
henrik.lundin6d8e0112016-03-04 10:34:21 -0800999 sync_buffer_->GetNextAudioInterleaved(num_output_samples_per_channel,
1000 audio_frame);
1001 audio_frame->sample_rate_hz_ = fs_hz_;
Henrik Lundin05f71fc2015-09-01 11:51:58 +02001002 if (sync_buffer_->FutureLength() < expand_->overlap_length()) {
1003 // The sync buffer should always contain |overlap_length| samples, but now
1004 // too many samples have been extracted. Reinstall the |overlap_length|
1005 // lookahead by moving the index.
1006 const size_t missing_lookahead_samples =
1007 expand_->overlap_length() - sync_buffer_->FutureLength();
henrikg91d6ede2015-09-17 00:24:34 -07001008 RTC_DCHECK_GE(sync_buffer_->next_index(), missing_lookahead_samples);
Henrik Lundin05f71fc2015-09-01 11:51:58 +02001009 sync_buffer_->set_next_index(sync_buffer_->next_index() -
1010 missing_lookahead_samples);
1011 }
henrik.lundin6d8e0112016-03-04 10:34:21 -08001012 if (audio_frame->samples_per_channel_ != output_size_samples_) {
1013 LOG(LS_ERROR) << "audio_frame->samples_per_channel_ ("
1014 << audio_frame->samples_per_channel_
Henrik Lundind67a2192015-08-03 12:54:37 +02001015 << ") != output_size_samples_ (" << output_size_samples_
1016 << ")";
minyue@webrtc.orgdb1cefc2013-08-13 01:39:21 +00001017 // TODO(minyue): treatment of under-run, filling zeros
henrik.lundin6d8e0112016-03-04 10:34:21 -08001018 memset(audio_frame->data_, 0, num_output_samples * sizeof(int16_t));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001019 return kSampleUnderrun;
1020 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001021
1022 // Should always have overlap samples left in the |sync_buffer_|.
henrikg91d6ede2015-09-17 00:24:34 -07001023 RTC_DCHECK_GE(sync_buffer_->FutureLength(), expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001024
1025 if (play_dtmf) {
henrik.lundin6d8e0112016-03-04 10:34:21 -08001026 return_value =
1027 DtmfOverdub(dtmf_event, sync_buffer_->Channels(), audio_frame->data_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001028 }
1029
1030 // Update the background noise parameters if last operation wrote data
1031 // straight from the decoder to the |sync_buffer_|. That is, none of the
1032 // operations that modify the signal can be followed by a parameter update.
1033 if ((last_mode_ == kModeNormal) ||
1034 (last_mode_ == kModeAccelerateFail) ||
1035 (last_mode_ == kModePreemptiveExpandFail) ||
1036 (last_mode_ == kModeRfc3389Cng) ||
1037 (last_mode_ == kModeCodecInternalCng)) {
1038 background_noise_->Update(*sync_buffer_, *vad_.get());
1039 }
1040
1041 if (operation == kDtmf) {
1042 // DTMF data was written the end of |sync_buffer_|.
1043 // Update index to end of DTMF data in |sync_buffer_|.
1044 sync_buffer_->set_dtmf_index(sync_buffer_->Size());
1045 }
1046
henrik.lundin@webrtc.orged865b52014-03-06 10:28:07 +00001047 if (last_mode_ != kModeExpand) {
1048 // If last operation was not expand, calculate the |playout_timestamp_| from
1049 // the |sync_buffer_|. However, do not update the |playout_timestamp_| if it
1050 // would be moved "backwards".
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001051 uint32_t temp_timestamp = sync_buffer_->end_timestamp() -
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001052 static_cast<uint32_t>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001053 if (static_cast<int32_t>(temp_timestamp - playout_timestamp_) > 0) {
1054 playout_timestamp_ = temp_timestamp;
1055 }
1056 } else {
1057 // Use dead reckoning to estimate the |playout_timestamp_|.
Peter Kastingb7e50542015-06-11 12:55:50 -07001058 playout_timestamp_ += static_cast<uint32_t>(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001059 }
henrik.lundin15c51e32016-04-06 08:38:56 -07001060 // Set the timestamp in the audio frame to zero before the first packet has
1061 // been inserted. Otherwise, subtract the frame size in samples to get the
1062 // timestamp of the first sample in the frame (playout_timestamp_ is the
1063 // last + 1).
1064 audio_frame->timestamp_ =
1065 first_packet_
1066 ? 0
1067 : timestamp_scaler_->ToExternal(playout_timestamp_) -
1068 static_cast<uint32_t>(audio_frame->samples_per_channel_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001069
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001070 if (!(last_mode_ == kModeRfc3389Cng ||
1071 last_mode_ == kModeCodecInternalCng ||
1072 last_mode_ == kModeExpand)) {
1073 generated_noise_stopwatch_.reset();
1074 }
1075
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001076 if (decode_return_value) return decode_return_value;
1077 return return_value;
1078}
1079
1080int NetEqImpl::GetDecision(Operations* operation,
1081 PacketList* packet_list,
1082 DtmfEvent* dtmf_event,
1083 bool* play_dtmf) {
1084 // Initialize output variables.
1085 *play_dtmf = false;
1086 *operation = kUndefined;
1087
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001088 assert(sync_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001089 uint32_t end_timestamp = sync_buffer_->end_timestamp();
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001090 if (!new_codec_) {
1091 const uint32_t five_seconds_samples = 5 * fs_hz_;
1092 packet_buffer_->DiscardOldPackets(end_timestamp, five_seconds_samples);
1093 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001094 const RTPHeader* header = packet_buffer_->NextRtpHeader();
1095
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001096 RTC_DCHECK(!generated_noise_stopwatch_ ||
1097 generated_noise_stopwatch_->ElapsedTicks() >= 1);
1098 uint64_t generated_noise_samples =
1099 generated_noise_stopwatch_
1100 ? (generated_noise_stopwatch_->ElapsedTicks() - 1) *
1101 output_size_samples_ +
1102 decision_logic_->noise_fast_forward()
1103 : 0;
1104
henrik.lundin@webrtc.orgca8cb952014-03-12 10:26:52 +00001105 if (decision_logic_->CngRfc3389On() || last_mode_ == kModeRfc3389Cng) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001106 // Because of timestamp peculiarities, we have to "manually" disallow using
1107 // a CNG packet with the same timestamp as the one that was last played.
1108 // This can happen when using redundancy and will cause the timing to shift.
henrik.lundin@webrtc.org24779fe2014-03-14 12:40:05 +00001109 while (header && decoder_database_->IsComfortNoise(header->payloadType) &&
1110 (end_timestamp >= header->timestamp ||
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001111 end_timestamp + generated_noise_samples > header->timestamp)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001112 // Don't use this packet, discard it.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001113 if (packet_buffer_->DiscardNextPacket() != PacketBuffer::kOK) {
1114 assert(false); // Must be ok by design.
1115 }
1116 // Check buffer again.
1117 if (!new_codec_) {
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001118 packet_buffer_->DiscardOldPackets(end_timestamp, 5 * fs_hz_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001119 }
1120 header = packet_buffer_->NextRtpHeader();
1121 }
1122 }
1123
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001124 assert(expand_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001125 const int samples_left = static_cast<int>(sync_buffer_->FutureLength() -
1126 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001127 if (last_mode_ == kModeAccelerateSuccess ||
1128 last_mode_ == kModeAccelerateLowEnergy ||
1129 last_mode_ == kModePreemptiveExpandSuccess ||
1130 last_mode_ == kModePreemptiveExpandLowEnergy) {
1131 // Subtract (samples_left + output_size_samples_) from sampleMemory.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001132 decision_logic_->AddSampleMemory(
1133 -(samples_left + rtc::checked_cast<int>(output_size_samples_)));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001134 }
1135
1136 // Check if it is time to play a DTMF event.
Peter Kastingb7e50542015-06-11 12:55:50 -07001137 if (dtmf_buffer_->GetEvent(
1138 static_cast<uint32_t>(
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001139 end_timestamp + generated_noise_samples),
Peter Kastingb7e50542015-06-11 12:55:50 -07001140 dtmf_event)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001141 *play_dtmf = true;
1142 }
1143
1144 // Get instruction.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001145 assert(sync_buffer_.get());
1146 assert(expand_.get());
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001147 generated_noise_samples =
1148 generated_noise_stopwatch_
1149 ? generated_noise_stopwatch_->ElapsedTicks() * output_size_samples_ +
1150 decision_logic_->noise_fast_forward()
1151 : 0;
1152 *operation = decision_logic_->GetDecision(
1153 *sync_buffer_, *expand_, decoder_frame_length_, header, last_mode_,
1154 *play_dtmf, generated_noise_samples, &reset_decoder_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001155
1156 // Check if we already have enough samples in the |sync_buffer_|. If so,
1157 // change decision to normal, unless the decision was merge, accelerate, or
1158 // preemptive expand.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001159 if (samples_left >= rtc::checked_cast<int>(output_size_samples_) &&
1160 *operation != kMerge &&
1161 *operation != kAccelerate &&
1162 *operation != kFastAccelerate &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001163 *operation != kPreemptiveExpand) {
1164 *operation = kNormal;
1165 return 0;
1166 }
1167
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001168 decision_logic_->ExpandDecision(*operation);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001169
1170 // Check conditions for reset.
1171 if (new_codec_ || *operation == kUndefined) {
1172 // The only valid reason to get kUndefined is that new_codec_ is set.
1173 assert(new_codec_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001174 if (*play_dtmf && !header) {
1175 timestamp_ = dtmf_event->timestamp;
1176 } else {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001177 if (!header) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001178 LOG(LS_ERROR) << "Packet missing where it shouldn't.";
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001179 return -1;
1180 }
1181 timestamp_ = header->timestamp;
ossu108ecec2016-07-08 08:45:18 -07001182 if (*operation == kRfc3389CngNoPacket &&
1183 decoder_database_->IsComfortNoise(header->payloadType)) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001184 // Change decision to CNG packet, since we do have a CNG packet, but it
1185 // was considered too early to use. Now, use it anyway.
1186 *operation = kRfc3389Cng;
1187 } else if (*operation != kRfc3389Cng) {
1188 *operation = kNormal;
1189 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001190 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001191 // Adjust |sync_buffer_| timestamp before setting |end_timestamp| to the
1192 // new value.
1193 sync_buffer_->IncreaseEndTimestamp(timestamp_ - end_timestamp);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001194 end_timestamp = timestamp_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001195 new_codec_ = false;
1196 decision_logic_->SoftReset();
1197 buffer_level_filter_->Reset();
1198 delay_manager_->Reset();
1199 stats_.ResetMcu();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001200 }
1201
Peter Kastingdce40cf2015-08-24 14:52:23 -07001202 size_t required_samples = output_size_samples_;
1203 const size_t samples_10_ms = static_cast<size_t>(80 * fs_mult_);
1204 const size_t samples_20_ms = 2 * samples_10_ms;
1205 const size_t samples_30_ms = 3 * samples_10_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001206
1207 switch (*operation) {
1208 case kExpand: {
1209 timestamp_ = end_timestamp;
1210 return 0;
1211 }
1212 case kRfc3389CngNoPacket:
1213 case kCodecInternalCng: {
1214 return 0;
1215 }
1216 case kDtmf: {
1217 // TODO(hlundin): Write test for this.
1218 // Update timestamp.
1219 timestamp_ = end_timestamp;
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001220 const uint64_t generated_noise_samples =
1221 generated_noise_stopwatch_
1222 ? generated_noise_stopwatch_->ElapsedTicks() *
1223 output_size_samples_ +
1224 decision_logic_->noise_fast_forward()
1225 : 0;
1226 if (generated_noise_samples > 0 && last_mode_ != kModeDtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001227 // Make a jump in timestamp due to the recently played comfort noise.
Peter Kastingb7e50542015-06-11 12:55:50 -07001228 uint32_t timestamp_jump =
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001229 static_cast<uint32_t>(generated_noise_samples);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001230 sync_buffer_->IncreaseEndTimestamp(timestamp_jump);
1231 timestamp_ += timestamp_jump;
1232 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001233 return 0;
1234 }
Henrik Lundincf808d22015-05-27 14:33:29 +02001235 case kAccelerate:
1236 case kFastAccelerate: {
1237 // In order to do an accelerate we need at least 30 ms of audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001238 if (samples_left >= static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001239 // Already have enough data, so we do not need to extract any more.
1240 decision_logic_->set_sample_memory(samples_left);
1241 decision_logic_->set_prev_time_scale(true);
1242 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001243 } else if (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001244 decoder_frame_length_ >= samples_30_ms) {
1245 // Avoid decoding more data as it might overflow the playout buffer.
1246 *operation = kNormal;
1247 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001248 } else if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001249 decoder_frame_length_ < samples_30_ms) {
1250 // Build up decoded data by decoding at least 20 ms of audio data. Do
1251 // not perform accelerate yet, but wait until we only need to do one
1252 // decoding.
1253 required_samples = 2 * output_size_samples_;
1254 *operation = kNormal;
1255 }
1256 // If none of the above is true, we have one of two possible situations:
1257 // (1) 20 ms <= samples_left < 30 ms and decoder_frame_length_ < 30 ms; or
1258 // (2) samples_left < 10 ms and decoder_frame_length_ >= 30 ms.
1259 // In either case, we move on with the accelerate decision, and decode one
1260 // frame now.
1261 break;
1262 }
1263 case kPreemptiveExpand: {
1264 // In order to do a preemptive expand we need at least 30 ms of decoded
1265 // audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001266 if ((samples_left >= static_cast<int>(samples_30_ms)) ||
1267 (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001268 decoder_frame_length_ >= samples_30_ms)) {
1269 // Already have enough data, so we do not need to extract any more.
1270 // Or, avoid decoding more data as it might overflow the playout buffer.
1271 // Still try preemptive expand, though.
1272 decision_logic_->set_sample_memory(samples_left);
1273 decision_logic_->set_prev_time_scale(true);
1274 return 0;
1275 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07001276 if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001277 decoder_frame_length_ < samples_30_ms) {
1278 // Build up decoded data by decoding at least 20 ms of audio data.
1279 // Still try to perform preemptive expand.
1280 required_samples = 2 * output_size_samples_;
1281 }
1282 // Move on with the preemptive expand decision.
1283 break;
1284 }
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001285 case kMerge: {
1286 required_samples =
1287 std::max(merge_->RequiredFutureSamples(), required_samples);
1288 break;
1289 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001290 default: {
1291 // Do nothing.
1292 }
1293 }
1294
1295 // Get packets from buffer.
1296 int extracted_samples = 0;
1297 if (header &&
1298 *operation != kAlternativePlc &&
1299 *operation != kAlternativePlcIncreaseTimestamp &&
1300 *operation != kAudioRepetition &&
1301 *operation != kAudioRepetitionIncreaseTimestamp) {
1302 sync_buffer_->IncreaseEndTimestamp(header->timestamp - end_timestamp);
1303 if (decision_logic_->CngOff()) {
1304 // Adjustment of timestamp only corresponds to an actual packet loss
1305 // if comfort noise is not played. If comfort noise was just played,
1306 // this adjustment of timestamp is only done to get back in sync with the
1307 // stream timestamp; no loss to report.
1308 stats_.LostSamples(header->timestamp - end_timestamp);
1309 }
1310
1311 if (*operation != kRfc3389Cng) {
1312 // We are about to decode and use a non-CNG packet.
1313 decision_logic_->SetCngOff();
1314 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001315
1316 extracted_samples = ExtractPackets(required_samples, packet_list);
1317 if (extracted_samples < 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001318 return kPacketBufferCorruption;
1319 }
1320 }
1321
Henrik Lundincf808d22015-05-27 14:33:29 +02001322 if (*operation == kAccelerate || *operation == kFastAccelerate ||
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001323 *operation == kPreemptiveExpand) {
1324 decision_logic_->set_sample_memory(samples_left + extracted_samples);
1325 decision_logic_->set_prev_time_scale(true);
1326 }
1327
Henrik Lundincf808d22015-05-27 14:33:29 +02001328 if (*operation == kAccelerate || *operation == kFastAccelerate) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001329 // Check that we have enough data (30ms) to do accelerate.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001330 if (extracted_samples + samples_left < static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001331 // TODO(hlundin): Write test for this.
1332 // Not enough, do normal operation instead.
1333 *operation = kNormal;
1334 }
1335 }
1336
1337 timestamp_ = end_timestamp;
1338 return 0;
1339}
1340
1341int NetEqImpl::Decode(PacketList* packet_list, Operations* operation,
1342 int* decoded_length,
1343 AudioDecoder::SpeechType* speech_type) {
1344 *speech_type = AudioDecoder::kSpeech;
minyuel6d92bf52015-09-23 15:20:39 +02001345
1346 // When packet_list is empty, we may be in kCodecInternalCng mode, and for
1347 // that we use current active decoder.
1348 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1349
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001350 if (!packet_list->empty()) {
1351 const Packet* packet = packet_list->front();
pkasting@chromium.org0e81fdf2015-02-02 23:54:03 +00001352 uint8_t payload_type = packet->header.payloadType;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001353 if (!decoder_database_->IsComfortNoise(payload_type)) {
1354 decoder = decoder_database_->GetDecoder(payload_type);
1355 assert(decoder);
1356 if (!decoder) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001357 LOG(LS_WARNING) << "Unknown payload type "
1358 << static_cast<int>(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001359 PacketBuffer::DeleteAllPackets(packet_list);
1360 return kDecoderNotFound;
1361 }
1362 bool decoder_changed;
1363 decoder_database_->SetActiveDecoder(payload_type, &decoder_changed);
1364 if (decoder_changed) {
1365 // We have a new decoder. Re-init some values.
1366 const DecoderDatabase::DecoderInfo* decoder_info = decoder_database_
1367 ->GetDecoderInfo(payload_type);
1368 assert(decoder_info);
1369 if (!decoder_info) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001370 LOG(LS_WARNING) << "Unknown payload type "
1371 << static_cast<int>(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001372 PacketBuffer::DeleteAllPackets(packet_list);
1373 return kDecoderNotFound;
1374 }
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001375 // If sampling rate or number of channels has changed, we need to make
1376 // a reset.
kwibergc0f2dcf2016-05-31 06:28:03 -07001377 if (decoder_info->SampleRateHz() != fs_hz_ ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001378 decoder->Channels() != algorithm_buffer_->Channels()) {
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001379 // TODO(tlegrand): Add unittest to cover this event.
kwibergc0f2dcf2016-05-31 06:28:03 -07001380 SetSampleRateAndChannels(decoder_info->SampleRateHz(),
1381 decoder->Channels());
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001382 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001383 sync_buffer_->set_end_timestamp(timestamp_);
1384 playout_timestamp_ = timestamp_;
1385 }
1386 }
1387 }
1388
1389 if (reset_decoder_) {
1390 // TODO(hlundin): Write test for this.
Karl Wiberg43766482015-08-27 15:22:11 +02001391 if (decoder)
1392 decoder->Reset();
1393
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001394 // Reset comfort noise decoder.
ossu97ba30e2016-04-25 07:55:58 -07001395 ComfortNoiseDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02001396 if (cng_decoder)
1397 cng_decoder->Reset();
1398
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001399 reset_decoder_ = false;
1400 }
1401
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001402 *decoded_length = 0;
1403 // Update codec-internal PLC state.
1404 if ((*operation == kMerge) && decoder && decoder->HasDecodePlc()) {
1405 decoder->DecodePlc(1, &decoded_buffer_[*decoded_length]);
1406 }
1407
minyuel6d92bf52015-09-23 15:20:39 +02001408 int return_value;
1409 if (*operation == kCodecInternalCng) {
1410 RTC_DCHECK(packet_list->empty());
1411 return_value = DecodeCng(decoder, decoded_length, speech_type);
1412 } else {
1413 return_value = DecodeLoop(packet_list, *operation, decoder,
1414 decoded_length, speech_type);
1415 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001416
1417 if (*decoded_length < 0) {
1418 // Error returned from the decoder.
1419 *decoded_length = 0;
Peter Kastingb7e50542015-06-11 12:55:50 -07001420 sync_buffer_->IncreaseEndTimestamp(
1421 static_cast<uint32_t>(decoder_frame_length_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001422 int error_code = 0;
1423 if (decoder)
1424 error_code = decoder->ErrorCode();
1425 if (error_code != 0) {
1426 // Got some error code from the decoder.
1427 decoder_error_code_ = error_code;
1428 return_value = kDecoderErrorCode;
Henrik Lundind67a2192015-08-03 12:54:37 +02001429 LOG(LS_WARNING) << "Decoder returned error code: " << error_code;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001430 } else {
1431 // Decoder does not implement error codes. Return generic error.
1432 return_value = kOtherDecoderError;
Henrik Lundind67a2192015-08-03 12:54:37 +02001433 LOG(LS_WARNING) << "Decoder error (no error code)";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001434 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001435 *operation = kExpand; // Do expansion to get data instead.
1436 }
1437 if (*speech_type != AudioDecoder::kComfortNoise) {
1438 // Don't increment timestamp if codec returned CNG speech type
1439 // since in this case, the we will increment the CNGplayedTS counter.
1440 // Increase with number of samples per channel.
1441 assert(*decoded_length == 0 ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001442 (decoder && decoder->Channels() == sync_buffer_->Channels()));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001443 sync_buffer_->IncreaseEndTimestamp(
1444 *decoded_length / static_cast<int>(sync_buffer_->Channels()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001445 }
1446 return return_value;
1447}
1448
minyuel6d92bf52015-09-23 15:20:39 +02001449int NetEqImpl::DecodeCng(AudioDecoder* decoder, int* decoded_length,
1450 AudioDecoder::SpeechType* speech_type) {
1451 if (!decoder) {
1452 // This happens when active decoder is not defined.
1453 *decoded_length = -1;
1454 return 0;
1455 }
1456
1457 while (*decoded_length < rtc::checked_cast<int>(output_size_samples_)) {
1458 const int length = decoder->Decode(
1459 nullptr, 0, fs_hz_,
1460 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1461 &decoded_buffer_[*decoded_length], speech_type);
1462 if (length > 0) {
1463 *decoded_length += length;
minyuel6d92bf52015-09-23 15:20:39 +02001464 } else {
1465 // Error.
1466 LOG(LS_WARNING) << "Failed to decode CNG";
1467 *decoded_length = -1;
1468 break;
1469 }
1470 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1471 // Guard against overflow.
1472 LOG(LS_WARNING) << "Decoded too much CNG.";
1473 return kDecodedTooMuch;
1474 }
1475 }
1476 return 0;
1477}
1478
1479int NetEqImpl::DecodeLoop(PacketList* packet_list, const Operations& operation,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001480 AudioDecoder* decoder, int* decoded_length,
1481 AudioDecoder::SpeechType* speech_type) {
1482 Packet* packet = NULL;
1483 if (!packet_list->empty()) {
1484 packet = packet_list->front();
1485 }
minyuel6d92bf52015-09-23 15:20:39 +02001486
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001487 // Do decoding.
1488 while (packet &&
1489 !decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1490 assert(decoder); // At this point, we must have a decoder object.
1491 // The number of channels in the |sync_buffer_| should be the same as the
1492 // number decoder channels.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001493 assert(sync_buffer_->Channels() == decoder->Channels());
1494 assert(decoded_buffer_length_ >= kMaxFrameSize * decoder->Channels());
minyuel6d92bf52015-09-23 15:20:39 +02001495 assert(operation == kNormal || operation == kAccelerate ||
1496 operation == kFastAccelerate || operation == kMerge ||
1497 operation == kPreemptiveExpand);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001498 packet_list->pop_front();
ossu61a208b2016-09-20 01:38:00 -07001499 auto opt_result = packet->frame->Decode(
1500 rtc::ArrayView<int16_t>(&decoded_buffer_[*decoded_length],
1501 decoded_buffer_length_ - *decoded_length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001502 delete packet;
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001503 packet = NULL;
ossu61a208b2016-09-20 01:38:00 -07001504 if (opt_result) {
1505 const auto& result = *opt_result;
1506 *speech_type = result.speech_type;
1507 if (result.num_decoded_samples > 0) {
1508 *decoded_length += rtc::checked_cast<int>(result.num_decoded_samples);
1509 // Update |decoder_frame_length_| with number of samples per channel.
1510 decoder_frame_length_ =
1511 result.num_decoded_samples / decoder->Channels();
1512 }
1513 } else {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001514 // Error.
ossu61a208b2016-09-20 01:38:00 -07001515 // TODO(ossu): What to put here?
1516 LOG(LS_WARNING) << "Decode error";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001517 *decoded_length = -1;
1518 PacketBuffer::DeleteAllPackets(packet_list);
1519 break;
1520 }
ossu61a208b2016-09-20 01:38:00 -07001521 if (*decoded_length > rtc::checked_cast<int>(decoded_buffer_length_)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001522 // Guard against overflow.
Henrik Lundind67a2192015-08-03 12:54:37 +02001523 LOG(LS_WARNING) << "Decoded too much.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001524 PacketBuffer::DeleteAllPackets(packet_list);
1525 return kDecodedTooMuch;
1526 }
1527 if (!packet_list->empty()) {
1528 packet = packet_list->front();
1529 } else {
1530 packet = NULL;
1531 }
1532 } // End of decode loop.
1533
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001534 // If the list is not empty at this point, either a decoding error terminated
1535 // the while-loop, or list must hold exactly one CNG packet.
1536 assert(packet_list->empty() || *decoded_length < 0 ||
1537 (packet_list->size() == 1 && packet &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001538 decoder_database_->IsComfortNoise(packet->header.payloadType)));
1539 return 0;
1540}
1541
1542void NetEqImpl::DoNormal(const int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001543 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001544 assert(normal_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001545 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001546 normal_->Process(decoded_buffer, decoded_length, last_mode_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001547 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001548 if (decoded_length != 0) {
1549 last_mode_ = kModeNormal;
1550 }
1551
1552 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1553 if ((speech_type == AudioDecoder::kComfortNoise)
1554 || ((last_mode_ == kModeCodecInternalCng)
1555 && (decoded_length == 0))) {
1556 // TODO(hlundin): Remove second part of || statement above.
1557 last_mode_ = kModeCodecInternalCng;
1558 }
1559
1560 if (!play_dtmf) {
1561 dtmf_tone_generator_->Reset();
1562 }
1563}
1564
1565void NetEqImpl::DoMerge(int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001566 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001567 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001568 assert(merge_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001569 size_t new_length = merge_->Process(decoded_buffer, decoded_length,
1570 mute_factor_array_.get(),
1571 algorithm_buffer_.get());
1572 size_t expand_length_correction = new_length -
1573 decoded_length / algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001574
1575 // Update in-call and post-call statistics.
1576 if (expand_->MuteFactor(0) == 0) {
1577 // Expand generates only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001578 stats_.ExpandedNoiseSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001579 } else {
1580 // Expansion generates more than only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001581 stats_.ExpandedVoiceSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001582 }
1583
1584 last_mode_ = kModeMerge;
1585 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1586 if (speech_type == AudioDecoder::kComfortNoise) {
1587 last_mode_ = kModeCodecInternalCng;
1588 }
1589 expand_->Reset();
1590 if (!play_dtmf) {
1591 dtmf_tone_generator_->Reset();
1592 }
1593}
1594
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001595int NetEqImpl::DoExpand(bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001596 while ((sync_buffer_->FutureLength() - expand_->overlap_length()) <
Peter Kastingdce40cf2015-08-24 14:52:23 -07001597 output_size_samples_) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001598 algorithm_buffer_->Clear();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001599 int return_value = expand_->Process(algorithm_buffer_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001600 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001601
1602 // Update in-call and post-call statistics.
1603 if (expand_->MuteFactor(0) == 0) {
1604 // Expand operation generates only noise.
1605 stats_.ExpandedNoiseSamples(length);
1606 } else {
1607 // Expand operation generates more than only noise.
1608 stats_.ExpandedVoiceSamples(length);
1609 }
1610
1611 last_mode_ = kModeExpand;
1612
1613 if (return_value < 0) {
1614 return return_value;
1615 }
1616
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001617 sync_buffer_->PushBack(*algorithm_buffer_);
1618 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001619 }
1620 if (!play_dtmf) {
1621 dtmf_tone_generator_->Reset();
1622 }
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001623
1624 if (!generated_noise_stopwatch_) {
1625 // Start a new stopwatch since we may be covering for a lost CNG packet.
1626 generated_noise_stopwatch_ = tick_timer_->GetNewStopwatch();
1627 }
1628
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001629 return 0;
1630}
1631
Henrik Lundincf808d22015-05-27 14:33:29 +02001632int NetEqImpl::DoAccelerate(int16_t* decoded_buffer,
1633 size_t decoded_length,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001634 AudioDecoder::SpeechType speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +02001635 bool play_dtmf,
1636 bool fast_accelerate) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001637 const size_t required_samples =
1638 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001639 size_t borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001640 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001641 size_t decoded_length_per_channel = decoded_length / num_channels;
1642 if (decoded_length_per_channel < required_samples) {
1643 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001644 borrowed_samples_per_channel = static_cast<int>(required_samples -
1645 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001646 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1647 decoded_buffer,
1648 sizeof(int16_t) * decoded_length);
1649 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1650 decoded_buffer);
1651 decoded_length = required_samples * num_channels;
1652 }
1653
Peter Kastingdce40cf2015-08-24 14:52:23 -07001654 size_t samples_removed;
Henrik Lundincf808d22015-05-27 14:33:29 +02001655 Accelerate::ReturnCodes return_code =
1656 accelerate_->Process(decoded_buffer, decoded_length, fast_accelerate,
1657 algorithm_buffer_.get(), &samples_removed);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001658 stats_.AcceleratedSamples(samples_removed);
1659 switch (return_code) {
1660 case Accelerate::kSuccess:
1661 last_mode_ = kModeAccelerateSuccess;
1662 break;
1663 case Accelerate::kSuccessLowEnergy:
1664 last_mode_ = kModeAccelerateLowEnergy;
1665 break;
1666 case Accelerate::kNoStretch:
1667 last_mode_ = kModeAccelerateFail;
1668 break;
1669 case Accelerate::kError:
1670 // TODO(hlundin): Map to kModeError instead?
1671 last_mode_ = kModeAccelerateFail;
1672 return kAccelerateError;
1673 }
1674
1675 if (borrowed_samples_per_channel > 0) {
1676 // Copy borrowed samples back to the |sync_buffer_|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001677 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001678 if (length < borrowed_samples_per_channel) {
1679 // This destroys the beginning of the buffer, but will not cause any
1680 // problems.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001681 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001682 sync_buffer_->Size() -
1683 borrowed_samples_per_channel);
1684 sync_buffer_->PushFrontZeros(borrowed_samples_per_channel - length);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001685 algorithm_buffer_->PopFront(length);
1686 assert(algorithm_buffer_->Empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001687 } else {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001688 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001689 borrowed_samples_per_channel,
1690 sync_buffer_->Size() -
1691 borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001692 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001693 }
1694 }
1695
1696 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1697 if (speech_type == AudioDecoder::kComfortNoise) {
1698 last_mode_ = kModeCodecInternalCng;
1699 }
1700 if (!play_dtmf) {
1701 dtmf_tone_generator_->Reset();
1702 }
1703 expand_->Reset();
1704 return 0;
1705}
1706
1707int NetEqImpl::DoPreemptiveExpand(int16_t* decoded_buffer,
1708 size_t decoded_length,
1709 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001710 bool play_dtmf) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001711 const size_t required_samples =
1712 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001713 size_t num_channels = algorithm_buffer_->Channels();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001714 size_t borrowed_samples_per_channel = 0;
1715 size_t old_borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001716 size_t decoded_length_per_channel = decoded_length / num_channels;
1717 if (decoded_length_per_channel < required_samples) {
1718 // Must move data from the |sync_buffer_| in order to get 30 ms.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001719 borrowed_samples_per_channel =
1720 required_samples - decoded_length_per_channel;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001721 // Calculate how many of these were already played out.
Peter Kastingf045e4d2015-06-10 21:15:38 -07001722 old_borrowed_samples_per_channel =
Peter Kastingdce40cf2015-08-24 14:52:23 -07001723 (borrowed_samples_per_channel > sync_buffer_->FutureLength()) ?
1724 (borrowed_samples_per_channel - sync_buffer_->FutureLength()) : 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001725 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1726 decoded_buffer,
1727 sizeof(int16_t) * decoded_length);
1728 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1729 decoded_buffer);
1730 decoded_length = required_samples * num_channels;
1731 }
1732
Peter Kastingdce40cf2015-08-24 14:52:23 -07001733 size_t samples_added;
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001734 PreemptiveExpand::ReturnCodes return_code = preemptive_expand_->Process(
Peter Kastingdce40cf2015-08-24 14:52:23 -07001735 decoded_buffer, decoded_length,
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001736 old_borrowed_samples_per_channel,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001737 algorithm_buffer_.get(), &samples_added);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001738 stats_.PreemptiveExpandedSamples(samples_added);
1739 switch (return_code) {
1740 case PreemptiveExpand::kSuccess:
1741 last_mode_ = kModePreemptiveExpandSuccess;
1742 break;
1743 case PreemptiveExpand::kSuccessLowEnergy:
1744 last_mode_ = kModePreemptiveExpandLowEnergy;
1745 break;
1746 case PreemptiveExpand::kNoStretch:
1747 last_mode_ = kModePreemptiveExpandFail;
1748 break;
1749 case PreemptiveExpand::kError:
1750 // TODO(hlundin): Map to kModeError instead?
1751 last_mode_ = kModePreemptiveExpandFail;
1752 return kPreemptiveExpandError;
1753 }
1754
1755 if (borrowed_samples_per_channel > 0) {
1756 // Copy borrowed samples back to the |sync_buffer_|.
1757 sync_buffer_->ReplaceAtIndex(
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001758 *algorithm_buffer_, borrowed_samples_per_channel,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001759 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001760 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001761 }
1762
1763 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1764 if (speech_type == AudioDecoder::kComfortNoise) {
1765 last_mode_ = kModeCodecInternalCng;
1766 }
1767 if (!play_dtmf) {
1768 dtmf_tone_generator_->Reset();
1769 }
1770 expand_->Reset();
1771 return 0;
1772}
1773
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001774int NetEqImpl::DoRfc3389Cng(PacketList* packet_list, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001775 if (!packet_list->empty()) {
1776 // Must have exactly one SID frame at this point.
1777 assert(packet_list->size() == 1);
1778 Packet* packet = packet_list->front();
1779 packet_list->pop_front();
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001780 if (!decoder_database_->IsComfortNoise(packet->header.payloadType)) {
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001781 LOG(LS_ERROR) << "Trying to decode non-CNG payload as CNG.";
1782 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001783 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001784 // UpdateParameters() deletes |packet|.
1785 if (comfort_noise_->UpdateParameters(packet) ==
1786 ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001787 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001788 return -comfort_noise_->internal_error_code();
1789 }
1790 }
1791 int cn_return = comfort_noise_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001792 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001793 expand_->Reset();
1794 last_mode_ = kModeRfc3389Cng;
1795 if (!play_dtmf) {
1796 dtmf_tone_generator_->Reset();
1797 }
1798 if (cn_return == ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001799 decoder_error_code_ = comfort_noise_->internal_error_code();
1800 return kComfortNoiseErrorCode;
1801 } else if (cn_return == ComfortNoise::kUnknownPayloadType) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001802 return kUnknownRtpPayloadType;
1803 }
1804 return 0;
1805}
1806
minyuel6d92bf52015-09-23 15:20:39 +02001807void NetEqImpl::DoCodecInternalCng(const int16_t* decoded_buffer,
1808 size_t decoded_length) {
1809 RTC_DCHECK(normal_.get());
1810 RTC_DCHECK(mute_factor_array_.get());
1811 normal_->Process(decoded_buffer, decoded_length, last_mode_,
1812 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001813 last_mode_ = kModeCodecInternalCng;
1814 expand_->Reset();
1815}
1816
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001817int NetEqImpl::DoDtmf(const DtmfEvent& dtmf_event, bool* play_dtmf) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001818 // This block of the code and the block further down, handling |dtmf_switch|
1819 // are commented out. Otherwise playing out-of-band DTMF would fail in VoE
1820 // test, DtmfTest.ManualSuccessfullySendsOutOfBandTelephoneEvents. This is
1821 // equivalent to |dtmf_switch| always be false.
1822 //
1823 // See http://webrtc-codereview.appspot.com/1195004/ for discussion
1824 // On this issue. This change might cause some glitches at the point of
1825 // switch from audio to DTMF. Issue 1545 is filed to track this.
1826 //
1827 // bool dtmf_switch = false;
1828 // if ((last_mode_ != kModeDtmf) && dtmf_tone_generator_->initialized()) {
1829 // // Special case; see below.
1830 // // We must catch this before calling Generate, since |initialized| is
1831 // // modified in that call.
1832 // dtmf_switch = true;
1833 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001834
1835 int dtmf_return_value = 0;
1836 if (!dtmf_tone_generator_->initialized()) {
1837 // Initialize if not already done.
1838 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1839 dtmf_event.volume);
1840 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001841
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001842 if (dtmf_return_value == 0) {
1843 // Generate DTMF signal.
1844 dtmf_return_value = dtmf_tone_generator_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001845 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001846 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001847
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001848 if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001849 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001850 return dtmf_return_value;
1851 }
1852
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001853 // if (dtmf_switch) {
1854 // // This is the special case where the previous operation was DTMF
1855 // // overdub, but the current instruction is "regular" DTMF. We must make
1856 // // sure that the DTMF does not have any discontinuities. The first DTMF
1857 // // sample that we generate now must be played out immediately, therefore
1858 // // it must be copied to the speech buffer.
1859 // // TODO(hlundin): This code seems incorrect. (Legacy.) Write test and
1860 // // verify correct operation.
1861 // assert(false);
1862 // // Must generate enough data to replace all of the |sync_buffer_|
1863 // // "future".
1864 // int required_length = sync_buffer_->FutureLength();
1865 // assert(dtmf_tone_generator_->initialized());
1866 // dtmf_return_value = dtmf_tone_generator_->Generate(required_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001867 // algorithm_buffer_);
1868 // assert((size_t) required_length == algorithm_buffer_->Size());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001869 // if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001870 // algorithm_buffer_->Zeros(output_size_samples_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001871 // return dtmf_return_value;
1872 // }
1873 //
1874 // // Overwrite the "future" part of the speech buffer with the new DTMF
1875 // // data.
1876 // // TODO(hlundin): It seems that this overwriting has gone lost.
1877 // // Not adapted for multi-channel yet.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001878 // assert(algorithm_buffer_->Channels() == 1);
1879 // if (algorithm_buffer_->Channels() != 1) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001880 // LOG(LS_WARNING) << "DTMF not supported for more than one channel";
1881 // return kStereoNotSupported;
1882 // }
1883 // // Shuffle the remaining data to the beginning of algorithm buffer.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001884 // algorithm_buffer_->PopFront(sync_buffer_->FutureLength());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001885 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001886
Peter Kastingb7e50542015-06-11 12:55:50 -07001887 sync_buffer_->IncreaseEndTimestamp(
1888 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001889 expand_->Reset();
1890 last_mode_ = kModeDtmf;
1891
1892 // Set to false because the DTMF is already in the algorithm buffer.
1893 *play_dtmf = false;
1894 return 0;
1895}
1896
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001897void NetEqImpl::DoAlternativePlc(bool increase_timestamp) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001898 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001899 size_t length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001900 if (decoder && decoder->HasDecodePlc()) {
1901 // Use the decoder's packet-loss concealment.
1902 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1903 int16_t decoded_buffer[kMaxFrameSize];
1904 length = decoder->DecodePlc(1, decoded_buffer);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001905 if (length > 0)
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001906 algorithm_buffer_->PushBackInterleaved(decoded_buffer, length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001907 } else {
1908 // Do simple zero-stuffing.
1909 length = output_size_samples_;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001910 algorithm_buffer_->Zeros(length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001911 // By not advancing the timestamp, NetEq inserts samples.
1912 stats_.AddZeros(length);
1913 }
1914 if (increase_timestamp) {
Peter Kastingb7e50542015-06-11 12:55:50 -07001915 sync_buffer_->IncreaseEndTimestamp(static_cast<uint32_t>(length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001916 }
1917 expand_->Reset();
1918}
1919
1920int NetEqImpl::DtmfOverdub(const DtmfEvent& dtmf_event, size_t num_channels,
1921 int16_t* output) const {
1922 size_t out_index = 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001923 size_t overdub_length = output_size_samples_; // Default value.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001924
1925 if (sync_buffer_->dtmf_index() > sync_buffer_->next_index()) {
1926 // Special operation for transition from "DTMF only" to "DTMF overdub".
1927 out_index = std::min(
1928 sync_buffer_->dtmf_index() - sync_buffer_->next_index(),
Peter Kastingdce40cf2015-08-24 14:52:23 -07001929 output_size_samples_);
1930 overdub_length = output_size_samples_ - out_index;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001931 }
1932
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001933 AudioMultiVector dtmf_output(num_channels);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001934 int dtmf_return_value = 0;
1935 if (!dtmf_tone_generator_->initialized()) {
1936 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1937 dtmf_event.volume);
1938 }
1939 if (dtmf_return_value == 0) {
1940 dtmf_return_value = dtmf_tone_generator_->Generate(overdub_length,
1941 &dtmf_output);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001942 assert(overdub_length == dtmf_output.Size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001943 }
1944 dtmf_output.ReadInterleaved(overdub_length, &output[out_index]);
1945 return dtmf_return_value < 0 ? dtmf_return_value : 0;
1946}
1947
Peter Kastingdce40cf2015-08-24 14:52:23 -07001948int NetEqImpl::ExtractPackets(size_t required_samples,
1949 PacketList* packet_list) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001950 bool first_packet = true;
1951 uint8_t prev_payload_type = 0;
1952 uint32_t prev_timestamp = 0;
1953 uint16_t prev_sequence_number = 0;
1954 bool next_packet_available = false;
1955
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001956 const RTPHeader* header = packet_buffer_->NextRtpHeader();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001957 assert(header);
1958 if (!header) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001959 LOG(LS_ERROR) << "Packet buffer unexpectedly empty.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001960 return -1;
1961 }
turaj@webrtc.org7df97062013-08-02 18:07:13 +00001962 uint32_t first_timestamp = header->timestamp;
ossu61a208b2016-09-20 01:38:00 -07001963 size_t extracted_samples = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001964
1965 // Packet extraction loop.
1966 do {
1967 timestamp_ = header->timestamp;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001968 size_t discard_count = 0;
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001969 Packet* packet = packet_buffer_->GetNextPacket(&discard_count);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001970 // |header| may be invalid after the |packet_buffer_| operation.
1971 header = NULL;
1972 if (!packet) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001973 LOG(LS_ERROR) << "Should always be able to extract a packet here";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001974 assert(false); // Should always be able to extract a packet here.
1975 return -1;
1976 }
1977 stats_.PacketsDiscarded(discard_count);
henrik.lundin84f8cd62016-04-26 07:45:16 -07001978 stats_.StoreWaitingTime(packet->waiting_time->ElapsedMs());
ossu61a208b2016-09-20 01:38:00 -07001979 RTC_DCHECK(!packet->empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001980 packet_list->push_back(packet); // Store packet in list.
1981
1982 if (first_packet) {
1983 first_packet = false;
henrik.lundin48ed9302015-10-29 05:36:24 -07001984 if (nack_enabled_) {
1985 RTC_DCHECK(nack_);
1986 // TODO(henrik.lundin): Should we update this for all decoded packets?
1987 nack_->UpdateLastDecodedPacket(packet->header.sequenceNumber,
1988 packet->header.timestamp);
1989 }
1990 prev_sequence_number = packet->header.sequenceNumber;
1991 prev_timestamp = packet->header.timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001992 prev_payload_type = packet->header.payloadType;
1993 }
1994
1995 // Store number of extracted samples.
ossu61a208b2016-09-20 01:38:00 -07001996 size_t packet_duration = 0;
1997 if (packet->frame) {
1998 packet_duration = packet->frame->Duration();
ossua70695a2016-09-22 02:06:28 -07001999 // TODO(ossu): Is this the correct way to track Opus FEC packets?
2000 if (packet->priority.codec_level > 0) {
ossu61a208b2016-09-20 01:38:00 -07002001 stats_.SecondaryDecodedSamples(rtc::checked_cast<int>(packet_duration));
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00002002 }
ossu97ba30e2016-04-25 07:55:58 -07002003 } else if (!decoder_database_->IsComfortNoise(packet->header.payloadType)) {
Henrik Lundind67a2192015-08-03 12:54:37 +02002004 LOG(LS_WARNING) << "Unknown payload type "
2005 << static_cast<int>(packet->header.payloadType);
ossu61a208b2016-09-20 01:38:00 -07002006 RTC_NOTREACHED();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002007 }
ossu61a208b2016-09-20 01:38:00 -07002008
2009 if (packet_duration == 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002010 // Decoder did not return a packet duration. Assume that the packet
2011 // contains the same number of samples as the previous one.
ossu61a208b2016-09-20 01:38:00 -07002012 packet_duration = decoder_frame_length_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002013 }
2014 extracted_samples = packet->header.timestamp - first_timestamp +
2015 packet_duration;
2016
2017 // Check what packet is available next.
2018 header = packet_buffer_->NextRtpHeader();
2019 next_packet_available = false;
2020 if (header && prev_payload_type == header->payloadType) {
2021 int16_t seq_no_diff = header->sequenceNumber - prev_sequence_number;
Peter Kastingdce40cf2015-08-24 14:52:23 -07002022 size_t ts_diff = header->timestamp - prev_timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002023 if (seq_no_diff == 1 ||
2024 (seq_no_diff == 0 && ts_diff == decoder_frame_length_)) {
2025 // The next sequence number is available, or the next part of a packet
2026 // that was split into pieces upon insertion.
2027 next_packet_available = true;
2028 }
2029 prev_sequence_number = header->sequenceNumber;
2030 }
ossu61a208b2016-09-20 01:38:00 -07002031 } while (extracted_samples < required_samples && next_packet_available);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002032
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00002033 if (extracted_samples > 0) {
2034 // Delete old packets only when we are going to decode something. Otherwise,
2035 // we could end up in the situation where we never decode anything, since
2036 // all incoming packets are considered too old but the buffer will also
2037 // never be flooded and flushed.
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00002038 packet_buffer_->DiscardAllOldPackets(timestamp_);
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00002039 }
2040
ossu61a208b2016-09-20 01:38:00 -07002041 return rtc::checked_cast<int>(extracted_samples);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002042}
2043
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002044void NetEqImpl::UpdatePlcComponents(int fs_hz, size_t channels) {
2045 // Delete objects and create new ones.
2046 expand_.reset(expand_factory_->Create(background_noise_.get(),
2047 sync_buffer_.get(), &random_vector_,
Henrik Lundinbef77e22015-08-18 14:58:09 +02002048 &stats_, fs_hz, channels));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002049 merge_.reset(new Merge(fs_hz, channels, expand_.get(), sync_buffer_.get()));
2050}
2051
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002052void NetEqImpl::SetSampleRateAndChannels(int fs_hz, size_t channels) {
Henrik Lundind67a2192015-08-03 12:54:37 +02002053 LOG(LS_VERBOSE) << "SetSampleRateAndChannels " << fs_hz << " " << channels;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002054 // TODO(hlundin): Change to an enumerator and skip assert.
2055 assert(fs_hz == 8000 || fs_hz == 16000 || fs_hz == 32000 || fs_hz == 48000);
2056 assert(channels > 0);
2057
2058 fs_hz_ = fs_hz;
2059 fs_mult_ = fs_hz / 8000;
Peter Kastingdce40cf2015-08-24 14:52:23 -07002060 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002061 decoder_frame_length_ = 3 * output_size_samples_; // Initialize to 30ms.
2062
2063 last_mode_ = kModeNormal;
2064
2065 // Create a new array of mute factors and set all to 1.
2066 mute_factor_array_.reset(new int16_t[channels]);
2067 for (size_t i = 0; i < channels; ++i) {
2068 mute_factor_array_[i] = 16384; // 1.0 in Q14.
2069 }
2070
ossu97ba30e2016-04-25 07:55:58 -07002071 ComfortNoiseDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02002072 if (cng_decoder)
2073 cng_decoder->Reset();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002074
2075 // Reinit post-decode VAD with new sample rate.
2076 assert(vad_.get()); // Cannot be NULL here.
2077 vad_->Init();
2078
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002079 // Delete algorithm buffer and create a new one.
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00002080 algorithm_buffer_.reset(new AudioMultiVector(channels));
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002081
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002082 // Delete sync buffer and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002083 sync_buffer_.reset(new SyncBuffer(channels, kSyncBufferSize * fs_mult_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002084
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00002085 // Delete BackgroundNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002086 background_noise_.reset(new BackgroundNoise(channels));
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00002087 background_noise_->set_mode(background_noise_mode_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002088
2089 // Reset random vector.
2090 random_vector_.Reset();
2091
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002092 UpdatePlcComponents(fs_hz, channels);
2093
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002094 // Move index so that we create a small set of future samples (all 0).
2095 sync_buffer_->set_next_index(sync_buffer_->next_index() -
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002096 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002097
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002098 normal_.reset(new Normal(fs_hz, decoder_database_.get(), *background_noise_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002099 expand_.get()));
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +00002100 accelerate_.reset(
2101 accelerate_factory_->Create(fs_hz, channels, *background_noise_));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002102 preemptive_expand_.reset(preemptive_expand_factory_->Create(
Peter Kastingdce40cf2015-08-24 14:52:23 -07002103 fs_hz, channels, *background_noise_, expand_->overlap_length()));
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002104
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002105 // Delete ComfortNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002106 comfort_noise_.reset(new ComfortNoise(fs_hz, decoder_database_.get(),
2107 sync_buffer_.get()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002108
2109 // Verify that |decoded_buffer_| is long enough.
2110 if (decoded_buffer_length_ < kMaxFrameSize * channels) {
2111 // Reallocate to larger size.
2112 decoded_buffer_length_ = kMaxFrameSize * channels;
2113 decoded_buffer_.reset(new int16_t[decoded_buffer_length_]);
2114 }
2115
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002116 // Create DecisionLogic if it is not created yet, then communicate new sample
2117 // rate and output size to DecisionLogic object.
2118 if (!decision_logic_.get()) {
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002119 CreateDecisionLogic();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002120 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002121 decision_logic_->SetSampleRate(fs_hz_, output_size_samples_);
2122}
2123
henrik.lundin55480f52016-03-08 02:37:57 -08002124NetEqImpl::OutputType NetEqImpl::LastOutputType() {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002125 assert(vad_.get());
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002126 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002127 if (last_mode_ == kModeCodecInternalCng || last_mode_ == kModeRfc3389Cng) {
henrik.lundin55480f52016-03-08 02:37:57 -08002128 return OutputType::kCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002129 } else if (last_mode_ == kModeExpand && expand_->MuteFactor(0) == 0) {
2130 // Expand mode has faded down to background noise only (very long expand).
henrik.lundin55480f52016-03-08 02:37:57 -08002131 return OutputType::kPLCCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002132 } else if (last_mode_ == kModeExpand) {
henrik.lundin55480f52016-03-08 02:37:57 -08002133 return OutputType::kPLC;
wu@webrtc.org24301a62013-12-13 19:17:43 +00002134 } else if (vad_->running() && !vad_->active_speech()) {
henrik.lundin55480f52016-03-08 02:37:57 -08002135 return OutputType::kVadPassive;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002136 } else {
henrik.lundin55480f52016-03-08 02:37:57 -08002137 return OutputType::kNormalSpeech;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002138 }
2139}
2140
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002141void NetEqImpl::CreateDecisionLogic() {
Henrik Lundin47b17dc2016-05-10 10:20:59 +02002142 decision_logic_.reset(DecisionLogic::Create(
2143 fs_hz_, output_size_samples_, playout_mode_, decoder_database_.get(),
2144 *packet_buffer_.get(), delay_manager_.get(), buffer_level_filter_.get(),
2145 tick_timer_.get()));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002146}
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002147} // namespace webrtc