blob: 555d3c71bcc3ad238518de1de699ddcc24ca7155 [file] [log] [blame]
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001/*
2 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000011#include "webrtc/modules/audio_coding/neteq/neteq_impl.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000012
13#include <assert.h>
14#include <memory.h> // memset
15
16#include <algorithm>
ossu97ba30e2016-04-25 07:55:58 -070017#include <vector>
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000018
henrik.lundin9c3efd02015-08-27 13:12:22 -070019#include "webrtc/base/checks.h"
Henrik Lundind67a2192015-08-03 12:54:37 +020020#include "webrtc/base/logging.h"
Tommid44c0772016-03-11 17:12:32 -080021#include "webrtc/base/safe_conversions.h"
henrik.lundina689b442015-12-17 03:50:05 -080022#include "webrtc/base/trace_event.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000023#include "webrtc/common_audio/signal_processing/include/signal_processing_library.h"
kwiberg@webrtc.orge04a93b2014-12-09 10:12:53 +000024#include "webrtc/modules/audio_coding/codecs/audio_decoder.h"
kwiberg5178ee82016-05-03 01:39:01 -070025#include "webrtc/modules/audio_coding/codecs/builtin_audio_decoder_factory.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000026#include "webrtc/modules/audio_coding/neteq/accelerate.h"
27#include "webrtc/modules/audio_coding/neteq/background_noise.h"
28#include "webrtc/modules/audio_coding/neteq/buffer_level_filter.h"
29#include "webrtc/modules/audio_coding/neteq/comfort_noise.h"
30#include "webrtc/modules/audio_coding/neteq/decision_logic.h"
31#include "webrtc/modules/audio_coding/neteq/decoder_database.h"
32#include "webrtc/modules/audio_coding/neteq/defines.h"
33#include "webrtc/modules/audio_coding/neteq/delay_manager.h"
34#include "webrtc/modules/audio_coding/neteq/delay_peak_detector.h"
35#include "webrtc/modules/audio_coding/neteq/dtmf_buffer.h"
36#include "webrtc/modules/audio_coding/neteq/dtmf_tone_generator.h"
37#include "webrtc/modules/audio_coding/neteq/expand.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000038#include "webrtc/modules/audio_coding/neteq/merge.h"
henrik.lundin48ed9302015-10-29 05:36:24 -070039#include "webrtc/modules/audio_coding/neteq/nack.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000040#include "webrtc/modules/audio_coding/neteq/normal.h"
41#include "webrtc/modules/audio_coding/neteq/packet_buffer.h"
42#include "webrtc/modules/audio_coding/neteq/packet.h"
43#include "webrtc/modules/audio_coding/neteq/payload_splitter.h"
44#include "webrtc/modules/audio_coding/neteq/post_decode_vad.h"
45#include "webrtc/modules/audio_coding/neteq/preemptive_expand.h"
46#include "webrtc/modules/audio_coding/neteq/sync_buffer.h"
henrik.lundined497212016-04-25 10:11:38 -070047#include "webrtc/modules/audio_coding/neteq/tick_timer.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000048#include "webrtc/modules/audio_coding/neteq/timestamp_scaler.h"
Henrik Kjellanderff761fb2015-11-04 08:31:52 +010049#include "webrtc/modules/include/module_common_types.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000050
51// Modify the code to obtain backwards bit-exactness. Once bit-exactness is no
52// longer required, this #define should be removed (and the code that it
53// enables).
54#define LEGACY_BITEXACT
55
56namespace webrtc {
57
henrik.lundin1d9061e2016-04-26 12:19:34 -070058NetEqImpl::Dependencies::Dependencies(const NetEq::Config& config)
59 : tick_timer(new TickTimer),
60 buffer_level_filter(new BufferLevelFilter),
kwiberg5178ee82016-05-03 01:39:01 -070061 decoder_database(new DecoderDatabase(CreateBuiltinAudioDecoderFactory())),
henrik.lundinf3933702016-04-28 01:53:52 -070062 delay_peak_detector(new DelayPeakDetector(tick_timer.get())),
henrik.lundin1d9061e2016-04-26 12:19:34 -070063 delay_manager(new DelayManager(config.max_packets_in_buffer,
henrik.lundin8f8c96d2016-04-28 23:19:20 -070064 delay_peak_detector.get(),
65 tick_timer.get())),
henrik.lundin1d9061e2016-04-26 12:19:34 -070066 dtmf_buffer(new DtmfBuffer(config.sample_rate_hz)),
67 dtmf_tone_generator(new DtmfToneGenerator),
68 packet_buffer(
69 new PacketBuffer(config.max_packets_in_buffer, tick_timer.get())),
70 payload_splitter(new PayloadSplitter),
71 timestamp_scaler(new TimestampScaler(*decoder_database)),
72 accelerate_factory(new AccelerateFactory),
73 expand_factory(new ExpandFactory),
74 preemptive_expand_factory(new PreemptiveExpandFactory) {}
75
76NetEqImpl::Dependencies::~Dependencies() = default;
77
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +000078NetEqImpl::NetEqImpl(const NetEq::Config& config,
henrik.lundin1d9061e2016-04-26 12:19:34 -070079 Dependencies&& deps,
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +000080 bool create_components)
henrik.lundin1d9061e2016-04-26 12:19:34 -070081 : tick_timer_(std::move(deps.tick_timer)),
82 buffer_level_filter_(std::move(deps.buffer_level_filter)),
83 decoder_database_(std::move(deps.decoder_database)),
84 delay_manager_(std::move(deps.delay_manager)),
85 delay_peak_detector_(std::move(deps.delay_peak_detector)),
86 dtmf_buffer_(std::move(deps.dtmf_buffer)),
87 dtmf_tone_generator_(std::move(deps.dtmf_tone_generator)),
88 packet_buffer_(std::move(deps.packet_buffer)),
89 payload_splitter_(std::move(deps.payload_splitter)),
90 timestamp_scaler_(std::move(deps.timestamp_scaler)),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000091 vad_(new PostDecodeVad()),
henrik.lundin1d9061e2016-04-26 12:19:34 -070092 expand_factory_(std::move(deps.expand_factory)),
93 accelerate_factory_(std::move(deps.accelerate_factory)),
94 preemptive_expand_factory_(std::move(deps.preemptive_expand_factory)),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000095 last_mode_(kModeNormal),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000096 decoded_buffer_length_(kMaxFrameSize),
97 decoded_buffer_(new int16_t[decoded_buffer_length_]),
98 playout_timestamp_(0),
99 new_codec_(false),
100 timestamp_(0),
101 reset_decoder_(false),
henrik.lundin48ed9302015-10-29 05:36:24 -0700102 current_rtp_payload_type_(0xFF), // Invalid RTP payload type.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000103 current_cng_rtp_payload_type_(0xFF), // Invalid RTP payload type.
104 ssrc_(0),
105 first_packet_(true),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000106 error_code_(0),
107 decoder_error_code_(0),
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +0000108 background_noise_mode_(config.background_noise_mode),
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000109 playout_mode_(config.playout_mode),
Henrik Lundincf808d22015-05-27 14:33:29 +0200110 enable_fast_accelerate_(config.enable_fast_accelerate),
henrik.lundin48ed9302015-10-29 05:36:24 -0700111 nack_enabled_(false) {
Henrik Lundin905495c2015-05-25 16:58:41 +0200112 LOG(LS_INFO) << "NetEq config: " << config.ToString();
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +0000113 int fs = config.sample_rate_hz;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000114 if (fs != 8000 && fs != 16000 && fs != 32000 && fs != 48000) {
115 LOG(LS_ERROR) << "Sample rate " << fs << " Hz not supported. " <<
116 "Changing to 8000 Hz.";
117 fs = 8000;
118 }
henrik.lundin1d9061e2016-04-26 12:19:34 -0700119 delay_manager_->SetMaximumDelay(config.max_delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000120 fs_hz_ = fs;
121 fs_mult_ = fs / 8000;
henrik.lundind89814b2015-11-23 06:49:25 -0800122 last_output_sample_rate_hz_ = fs;
Peter Kastingdce40cf2015-08-24 14:52:23 -0700123 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000124 decoder_frame_length_ = 3 * output_size_samples_;
125 WebRtcSpl_Init();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000126 if (create_components) {
127 SetSampleRateAndChannels(fs, 1); // Default is 1 channel.
128 }
henrik.lundin9bc26672015-11-02 03:25:57 -0800129 RTC_DCHECK(!vad_->enabled());
130 if (config.enable_post_decode_vad) {
131 vad_->Enable();
132 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000133}
134
Henrik Lundind67a2192015-08-03 12:54:37 +0200135NetEqImpl::~NetEqImpl() = default;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000136
137int NetEqImpl::InsertPacket(const WebRtcRTPHeader& rtp_header,
kwibergee2bac22015-11-11 10:34:00 -0800138 rtc::ArrayView<const uint8_t> payload,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000139 uint32_t receive_timestamp) {
henrik.lundina689b442015-12-17 03:50:05 -0800140 TRACE_EVENT0("webrtc", "NetEqImpl::InsertPacket");
Tommi9090e0b2016-01-20 13:39:36 +0100141 rtc::CritScope lock(&crit_sect_);
kwibergee2bac22015-11-11 10:34:00 -0800142 int error =
143 InsertPacketInternal(rtp_header, payload, receive_timestamp, false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000144 if (error != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000145 error_code_ = error;
146 return kFail;
147 }
148 return kOK;
149}
150
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000151int NetEqImpl::InsertSyncPacket(const WebRtcRTPHeader& rtp_header,
152 uint32_t receive_timestamp) {
Tommi9090e0b2016-01-20 13:39:36 +0100153 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000154 const uint8_t kSyncPayload[] = { 's', 'y', 'n', 'c' };
kwibergee2bac22015-11-11 10:34:00 -0800155 int error =
156 InsertPacketInternal(rtp_header, kSyncPayload, receive_timestamp, true);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000157
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000158 if (error != 0) {
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000159 error_code_ = error;
160 return kFail;
161 }
162 return kOK;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000163}
164
henrik.lundin500c04b2016-03-08 02:36:04 -0800165namespace {
166void SetAudioFrameActivityAndType(bool vad_enabled,
henrik.lundin55480f52016-03-08 02:37:57 -0800167 NetEqImpl::OutputType type,
henrik.lundin500c04b2016-03-08 02:36:04 -0800168 AudioFrame::VADActivity last_vad_activity,
169 AudioFrame* audio_frame) {
170 switch (type) {
henrik.lundin55480f52016-03-08 02:37:57 -0800171 case NetEqImpl::OutputType::kNormalSpeech: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800172 audio_frame->speech_type_ = AudioFrame::kNormalSpeech;
173 audio_frame->vad_activity_ = AudioFrame::kVadActive;
174 break;
175 }
henrik.lundin55480f52016-03-08 02:37:57 -0800176 case NetEqImpl::OutputType::kVadPassive: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800177 // This should only be reached if the VAD is enabled.
178 RTC_DCHECK(vad_enabled);
179 audio_frame->speech_type_ = AudioFrame::kNormalSpeech;
180 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
181 break;
182 }
henrik.lundin55480f52016-03-08 02:37:57 -0800183 case NetEqImpl::OutputType::kCNG: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800184 audio_frame->speech_type_ = AudioFrame::kCNG;
185 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
186 break;
187 }
henrik.lundin55480f52016-03-08 02:37:57 -0800188 case NetEqImpl::OutputType::kPLC: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800189 audio_frame->speech_type_ = AudioFrame::kPLC;
190 audio_frame->vad_activity_ = last_vad_activity;
191 break;
192 }
henrik.lundin55480f52016-03-08 02:37:57 -0800193 case NetEqImpl::OutputType::kPLCCNG: {
henrik.lundin500c04b2016-03-08 02:36:04 -0800194 audio_frame->speech_type_ = AudioFrame::kPLCCNG;
195 audio_frame->vad_activity_ = AudioFrame::kVadPassive;
196 break;
197 }
198 default:
199 RTC_NOTREACHED();
200 }
201 if (!vad_enabled) {
202 // Always set kVadUnknown when receive VAD is inactive.
203 audio_frame->vad_activity_ = AudioFrame::kVadUnknown;
204 }
205}
henrik.lundinbc89de32016-03-08 05:20:14 -0800206} // namespace
henrik.lundin500c04b2016-03-08 02:36:04 -0800207
henrik.lundin55480f52016-03-08 02:37:57 -0800208int NetEqImpl::GetAudio(AudioFrame* audio_frame) {
henrik.lundine1ca1672016-01-08 03:50:08 -0800209 TRACE_EVENT0("webrtc", "NetEqImpl::GetAudio");
Tommi9090e0b2016-01-20 13:39:36 +0100210 rtc::CritScope lock(&crit_sect_);
henrik.lundin6d8e0112016-03-04 10:34:21 -0800211 int error = GetAudioInternal(audio_frame);
212 RTC_DCHECK_EQ(
213 audio_frame->sample_rate_hz_,
214 rtc::checked_cast<int>(audio_frame->samples_per_channel_ * 100));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000215 if (error != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000216 error_code_ = error;
217 return kFail;
218 }
henrik.lundin500c04b2016-03-08 02:36:04 -0800219 SetAudioFrameActivityAndType(vad_->enabled(), LastOutputType(),
220 last_vad_activity_, audio_frame);
221 last_vad_activity_ = audio_frame->vad_activity_;
henrik.lundin6d8e0112016-03-04 10:34:21 -0800222 last_output_sample_rate_hz_ = audio_frame->sample_rate_hz_;
henrik.lundind89814b2015-11-23 06:49:25 -0800223 RTC_DCHECK(last_output_sample_rate_hz_ == 8000 ||
224 last_output_sample_rate_hz_ == 16000 ||
225 last_output_sample_rate_hz_ == 32000 ||
226 last_output_sample_rate_hz_ == 48000)
227 << "Unexpected sample rate " << last_output_sample_rate_hz_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000228 return kOK;
229}
230
kwibergee1879c2015-10-29 06:20:28 -0700231int NetEqImpl::RegisterPayloadType(NetEqDecoder codec,
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800232 const std::string& name,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000233 uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100234 rtc::CritScope lock(&crit_sect_);
Henrik Lundind67a2192015-08-03 12:54:37 +0200235 LOG(LS_VERBOSE) << "RegisterPayloadType "
kwibergee1879c2015-10-29 06:20:28 -0700236 << static_cast<int>(rtp_payload_type) << " "
237 << static_cast<int>(codec);
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800238 int ret = decoder_database_->RegisterPayload(rtp_payload_type, codec, name);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000239 if (ret != DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000240 switch (ret) {
241 case DecoderDatabase::kInvalidRtpPayloadType:
242 error_code_ = kInvalidRtpPayloadType;
243 break;
244 case DecoderDatabase::kCodecNotSupported:
245 error_code_ = kCodecNotSupported;
246 break;
247 case DecoderDatabase::kDecoderExists:
248 error_code_ = kDecoderExists;
249 break;
250 default:
251 error_code_ = kOtherError;
252 }
253 return kFail;
254 }
255 return kOK;
256}
257
258int NetEqImpl::RegisterExternalDecoder(AudioDecoder* decoder,
kwibergee1879c2015-10-29 06:20:28 -0700259 NetEqDecoder codec,
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800260 const std::string& codec_name,
Karl Wibergd8399e62015-05-25 14:39:56 +0200261 uint8_t rtp_payload_type,
262 int sample_rate_hz) {
Tommi9090e0b2016-01-20 13:39:36 +0100263 rtc::CritScope lock(&crit_sect_);
Henrik Lundind67a2192015-08-03 12:54:37 +0200264 LOG(LS_VERBOSE) << "RegisterExternalDecoder "
kwibergee1879c2015-10-29 06:20:28 -0700265 << static_cast<int>(rtp_payload_type) << " "
266 << static_cast<int>(codec);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000267 if (!decoder) {
268 LOG(LS_ERROR) << "Cannot register external decoder with NULL pointer";
269 assert(false);
270 return kFail;
271 }
henrik.lundin4cf61dd2015-12-09 06:20:58 -0800272 int ret = decoder_database_->InsertExternal(
273 rtp_payload_type, codec, codec_name, sample_rate_hz, decoder);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000274 if (ret != DecoderDatabase::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000275 switch (ret) {
276 case DecoderDatabase::kInvalidRtpPayloadType:
277 error_code_ = kInvalidRtpPayloadType;
278 break;
279 case DecoderDatabase::kCodecNotSupported:
280 error_code_ = kCodecNotSupported;
281 break;
282 case DecoderDatabase::kDecoderExists:
283 error_code_ = kDecoderExists;
284 break;
285 case DecoderDatabase::kInvalidSampleRate:
286 error_code_ = kInvalidSampleRate;
287 break;
288 case DecoderDatabase::kInvalidPointer:
289 error_code_ = kInvalidPointer;
290 break;
291 default:
292 error_code_ = kOtherError;
293 }
294 return kFail;
295 }
296 return kOK;
297}
298
299int NetEqImpl::RemovePayloadType(uint8_t rtp_payload_type) {
Tommi9090e0b2016-01-20 13:39:36 +0100300 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000301 int ret = decoder_database_->Remove(rtp_payload_type);
302 if (ret == DecoderDatabase::kOK) {
303 return kOK;
304 } else if (ret == DecoderDatabase::kDecoderNotFound) {
305 error_code_ = kDecoderNotFound;
306 } else {
307 error_code_ = kOtherError;
308 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000309 return kFail;
310}
311
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000312bool NetEqImpl::SetMinimumDelay(int delay_ms) {
Tommi9090e0b2016-01-20 13:39:36 +0100313 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000314 if (delay_ms >= 0 && delay_ms < 10000) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000315 assert(delay_manager_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000316 return delay_manager_->SetMinimumDelay(delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000317 }
318 return false;
319}
320
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000321bool NetEqImpl::SetMaximumDelay(int delay_ms) {
Tommi9090e0b2016-01-20 13:39:36 +0100322 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000323 if (delay_ms >= 0 && delay_ms < 10000) {
324 assert(delay_manager_.get());
325 return delay_manager_->SetMaximumDelay(delay_ms);
326 }
327 return false;
328}
329
330int NetEqImpl::LeastRequiredDelayMs() const {
Tommi9090e0b2016-01-20 13:39:36 +0100331 rtc::CritScope lock(&crit_sect_);
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000332 assert(delay_manager_.get());
333 return delay_manager_->least_required_delay_ms();
334}
335
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200336int NetEqImpl::SetTargetDelay() {
337 return kNotImplemented;
338}
339
340int NetEqImpl::TargetDelay() {
341 return kNotImplemented;
342}
343
henrik.lundin9c3efd02015-08-27 13:12:22 -0700344int NetEqImpl::CurrentDelayMs() const {
Tommi9090e0b2016-01-20 13:39:36 +0100345 rtc::CritScope lock(&crit_sect_);
henrik.lundin9c3efd02015-08-27 13:12:22 -0700346 if (fs_hz_ == 0)
347 return 0;
348 // Sum up the samples in the packet buffer with the future length of the sync
349 // buffer, and divide the sum by the sample rate.
350 const size_t delay_samples =
351 packet_buffer_->NumSamplesInBuffer(decoder_database_.get(),
352 decoder_frame_length_) +
353 sync_buffer_->FutureLength();
354 // The division below will truncate.
355 const int delay_ms =
356 static_cast<int>(delay_samples) / rtc::CheckedDivExact(fs_hz_, 1000);
357 return delay_ms;
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200358}
359
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000360// Deprecated.
361// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000362void NetEqImpl::SetPlayoutMode(NetEqPlayoutMode mode) {
Tommi9090e0b2016-01-20 13:39:36 +0100363 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000364 if (mode != playout_mode_) {
365 playout_mode_ = mode;
366 CreateDecisionLogic();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000367 }
368}
369
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000370// Deprecated.
371// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000372NetEqPlayoutMode NetEqImpl::PlayoutMode() const {
Tommi9090e0b2016-01-20 13:39:36 +0100373 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000374 return playout_mode_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000375}
376
377int NetEqImpl::NetworkStatistics(NetEqNetworkStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100378 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000379 assert(decoder_database_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700380 const size_t total_samples_in_buffers =
Peter Kasting728d9032015-06-11 14:31:38 -0700381 packet_buffer_->NumSamplesInBuffer(decoder_database_.get(),
382 decoder_frame_length_) +
Peter Kastingdce40cf2015-08-24 14:52:23 -0700383 sync_buffer_->FutureLength();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000384 assert(delay_manager_.get());
385 assert(decision_logic_.get());
386 stats_.GetNetworkStatistics(fs_hz_, total_samples_in_buffers,
387 decoder_frame_length_, *delay_manager_.get(),
388 *decision_logic_.get(), stats);
389 return 0;
390}
391
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000392void NetEqImpl::GetRtcpStatistics(RtcpStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100393 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000394 if (stats) {
395 rtcp_.GetStatistics(false, stats);
396 }
397}
398
399void NetEqImpl::GetRtcpStatisticsNoReset(RtcpStatistics* stats) {
Tommi9090e0b2016-01-20 13:39:36 +0100400 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000401 if (stats) {
402 rtcp_.GetStatistics(true, stats);
403 }
404}
405
406void NetEqImpl::EnableVad() {
Tommi9090e0b2016-01-20 13:39:36 +0100407 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000408 assert(vad_.get());
409 vad_->Enable();
410}
411
412void NetEqImpl::DisableVad() {
Tommi9090e0b2016-01-20 13:39:36 +0100413 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000414 assert(vad_.get());
415 vad_->Disable();
416}
417
henrik.lundin15c51e32016-04-06 08:38:56 -0700418rtc::Optional<uint32_t> NetEqImpl::GetPlayoutTimestamp() const {
Tommi9090e0b2016-01-20 13:39:36 +0100419 rtc::CritScope lock(&crit_sect_);
henrik.lundin0d96ab72016-04-06 12:28:26 -0700420 if (first_packet_ || last_mode_ == kModeRfc3389Cng ||
421 last_mode_ == kModeCodecInternalCng) {
wu@webrtc.org94454b72014-06-05 20:34:08 +0000422 // We don't have a valid RTP timestamp until we have decoded our first
henrik.lundin0d96ab72016-04-06 12:28:26 -0700423 // RTP packet. Also, the RTP timestamp is not accurate while playing CNG,
424 // which is indicated by returning an empty value.
henrik.lundin9a410dd2016-04-06 01:39:22 -0700425 return rtc::Optional<uint32_t>();
wu@webrtc.org94454b72014-06-05 20:34:08 +0000426 }
henrik.lundin9a410dd2016-04-06 01:39:22 -0700427 return rtc::Optional<uint32_t>(
428 timestamp_scaler_->ToExternal(playout_timestamp_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000429}
430
henrik.lundind89814b2015-11-23 06:49:25 -0800431int NetEqImpl::last_output_sample_rate_hz() const {
Tommi9090e0b2016-01-20 13:39:36 +0100432 rtc::CritScope lock(&crit_sect_);
henrik.lundind89814b2015-11-23 06:49:25 -0800433 return last_output_sample_rate_hz_;
434}
435
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200436int NetEqImpl::SetTargetNumberOfChannels() {
437 return kNotImplemented;
438}
439
440int NetEqImpl::SetTargetSampleRate() {
441 return kNotImplemented;
442}
443
henrik.lundin@webrtc.orgb0f4b3d2014-11-04 08:53:10 +0000444int NetEqImpl::LastError() const {
Tommi9090e0b2016-01-20 13:39:36 +0100445 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000446 return error_code_;
447}
448
449int NetEqImpl::LastDecoderError() {
Tommi9090e0b2016-01-20 13:39:36 +0100450 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000451 return decoder_error_code_;
452}
453
454void NetEqImpl::FlushBuffers() {
Tommi9090e0b2016-01-20 13:39:36 +0100455 rtc::CritScope lock(&crit_sect_);
Henrik Lundind67a2192015-08-03 12:54:37 +0200456 LOG(LS_VERBOSE) << "FlushBuffers";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000457 packet_buffer_->Flush();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000458 assert(sync_buffer_.get());
459 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000460 sync_buffer_->Flush();
461 sync_buffer_->set_next_index(sync_buffer_->next_index() -
462 expand_->overlap_length());
463 // Set to wait for new codec.
464 first_packet_ = true;
465}
466
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000467void NetEqImpl::PacketBufferStatistics(int* current_num_packets,
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000468 int* max_num_packets) const {
Tommi9090e0b2016-01-20 13:39:36 +0100469 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000470 packet_buffer_->BufferStat(current_num_packets, max_num_packets);
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000471}
472
henrik.lundin48ed9302015-10-29 05:36:24 -0700473void NetEqImpl::EnableNack(size_t max_nack_list_size) {
Tommi9090e0b2016-01-20 13:39:36 +0100474 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700475 if (!nack_enabled_) {
476 const int kNackThresholdPackets = 2;
477 nack_.reset(Nack::Create(kNackThresholdPackets));
478 nack_enabled_ = true;
479 nack_->UpdateSampleRate(fs_hz_);
480 }
481 nack_->SetMaxNackListSize(max_nack_list_size);
482}
483
484void NetEqImpl::DisableNack() {
Tommi9090e0b2016-01-20 13:39:36 +0100485 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700486 nack_.reset();
487 nack_enabled_ = false;
488}
489
490std::vector<uint16_t> NetEqImpl::GetNackList(int64_t round_trip_time_ms) const {
Tommi9090e0b2016-01-20 13:39:36 +0100491 rtc::CritScope lock(&crit_sect_);
henrik.lundin48ed9302015-10-29 05:36:24 -0700492 if (!nack_enabled_) {
493 return std::vector<uint16_t>();
494 }
495 RTC_DCHECK(nack_.get());
496 return nack_->GetNackList(round_trip_time_ms);
minyue@webrtc.orgd7301772013-08-29 00:58:14 +0000497}
498
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000499const SyncBuffer* NetEqImpl::sync_buffer_for_test() const {
Tommi9090e0b2016-01-20 13:39:36 +0100500 rtc::CritScope lock(&crit_sect_);
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000501 return sync_buffer_.get();
502}
503
minyue5bd33972016-05-02 04:46:11 -0700504Operations NetEqImpl::last_operation_for_test() const {
505 rtc::CritScope lock(&crit_sect_);
506 return last_operation_;
507}
508
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000509// Methods below this line are private.
510
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000511int NetEqImpl::InsertPacketInternal(const WebRtcRTPHeader& rtp_header,
kwibergee2bac22015-11-11 10:34:00 -0800512 rtc::ArrayView<const uint8_t> payload,
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000513 uint32_t receive_timestamp,
514 bool is_sync_packet) {
kwibergee2bac22015-11-11 10:34:00 -0800515 if (payload.empty()) {
516 LOG_F(LS_ERROR) << "payload is empty";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000517 return kInvalidPointer;
518 }
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000519 // Sanity checks for sync-packets.
520 if (is_sync_packet) {
521 if (decoder_database_->IsDtmf(rtp_header.header.payloadType) ||
522 decoder_database_->IsRed(rtp_header.header.payloadType) ||
523 decoder_database_->IsComfortNoise(rtp_header.header.payloadType)) {
524 LOG_F(LS_ERROR) << "Sync-packet with an unacceptable payload type "
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000525 << static_cast<int>(rtp_header.header.payloadType);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000526 return kSyncPacketNotAccepted;
527 }
528 if (first_packet_ ||
529 rtp_header.header.payloadType != current_rtp_payload_type_ ||
530 rtp_header.header.ssrc != ssrc_) {
531 // Even if |current_rtp_payload_type_| is 0xFF, sync-packet isn't
532 // accepted.
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000533 LOG_F(LS_ERROR)
534 << "Changing codec, SSRC or first packet with sync-packet.";
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000535 return kSyncPacketNotAccepted;
536 }
537 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000538 PacketList packet_list;
539 RTPHeader main_header;
540 {
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000541 // Convert to Packet.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000542 // Create |packet| within this separate scope, since it should not be used
543 // directly once it's been inserted in the packet list. This way, |packet|
544 // is not defined outside of this block.
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000545 Packet* packet = new Packet;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000546 packet->header.markerBit = false;
547 packet->header.payloadType = rtp_header.header.payloadType;
548 packet->header.sequenceNumber = rtp_header.header.sequenceNumber;
549 packet->header.timestamp = rtp_header.header.timestamp;
550 packet->header.ssrc = rtp_header.header.ssrc;
551 packet->header.numCSRCs = 0;
kwibergee2bac22015-11-11 10:34:00 -0800552 packet->payload_length = payload.size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000553 packet->primary = true;
henrik.lundin84f8cd62016-04-26 07:45:16 -0700554 // Waiting time will be set upon inserting the packet in the buffer.
555 RTC_DCHECK(!packet->waiting_time);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000556 packet->payload = new uint8_t[packet->payload_length];
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000557 packet->sync_packet = is_sync_packet;
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +0000558 if (!packet->payload) {
559 LOG_F(LS_ERROR) << "Payload pointer is NULL.";
560 }
kwibergee2bac22015-11-11 10:34:00 -0800561 assert(!payload.empty()); // Already checked above.
562 memcpy(packet->payload, payload.data(), packet->payload_length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000563 // Insert packet in a packet list.
564 packet_list.push_back(packet);
565 // Save main payloads header for later.
566 memcpy(&main_header, &packet->header, sizeof(main_header));
567 }
568
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000569 bool update_sample_rate_and_channels = false;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000570 // Reinitialize NetEq if it's needed (changed SSRC or first call).
571 if ((main_header.ssrc != ssrc_) || first_packet_) {
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000572 // Note: |first_packet_| will be cleared further down in this method, once
573 // the packet has been successfully inserted into the packet buffer.
574
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000575 rtcp_.Init(main_header.sequenceNumber);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000576
577 // Flush the packet buffer and DTMF buffer.
578 packet_buffer_->Flush();
579 dtmf_buffer_->Flush();
580
581 // Store new SSRC.
582 ssrc_ = main_header.ssrc;
583
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000584 // Update audio buffer timestamp.
585 sync_buffer_->IncreaseEndTimestamp(main_header.timestamp - timestamp_);
586
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000587 // Update codecs.
588 timestamp_ = main_header.timestamp;
589 current_rtp_payload_type_ = main_header.payloadType;
590
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000591 // Reset timestamp scaling.
592 timestamp_scaler_->Reset();
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000593
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000594 // Trigger an update of sampling rate and the number of channels.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000595 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000596 }
597
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000598 // Update RTCP statistics, only for regular packets.
599 if (!is_sync_packet)
600 rtcp_.Update(main_header, receive_timestamp);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000601
602 // Check for RED payload type, and separate payloads into several packets.
603 if (decoder_database_->IsRed(main_header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000604 assert(!is_sync_packet); // We had a sanity check for this.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000605 if (payload_splitter_->SplitRed(&packet_list) != PayloadSplitter::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000606 PacketBuffer::DeleteAllPackets(&packet_list);
607 return kRedundancySplitError;
608 }
609 // Only accept a few RED payloads of the same type as the main data,
610 // DTMF events and CNG.
611 payload_splitter_->CheckRedPayloads(&packet_list, *decoder_database_);
612 // Update the stored main payload header since the main payload has now
613 // changed.
614 memcpy(&main_header, &packet_list.front()->header, sizeof(main_header));
615 }
616
617 // Check payload types.
618 if (decoder_database_->CheckPayloadTypes(packet_list) ==
619 DecoderDatabase::kDecoderNotFound) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000620 PacketBuffer::DeleteAllPackets(&packet_list);
621 return kUnknownRtpPayloadType;
622 }
623
624 // Scale timestamp to internal domain (only for some codecs).
625 timestamp_scaler_->ToInternal(&packet_list);
626
627 // Process DTMF payloads. Cycle through the list of packets, and pick out any
628 // DTMF payloads found.
629 PacketList::iterator it = packet_list.begin();
630 while (it != packet_list.end()) {
631 Packet* current_packet = (*it);
632 assert(current_packet);
633 assert(current_packet->payload);
634 if (decoder_database_->IsDtmf(current_packet->header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000635 assert(!current_packet->sync_packet); // We had a sanity check for this.
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000636 DtmfEvent event;
637 int ret = DtmfBuffer::ParseEvent(
638 current_packet->header.timestamp,
639 current_packet->payload,
640 current_packet->payload_length,
641 &event);
642 if (ret != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000643 PacketBuffer::DeleteAllPackets(&packet_list);
644 return kDtmfParsingError;
645 }
646 if (dtmf_buffer_->InsertEvent(event) != DtmfBuffer::kOK) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000647 PacketBuffer::DeleteAllPackets(&packet_list);
648 return kDtmfInsertError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000649 }
650 // TODO(hlundin): Let the destructor of Packet handle the payload.
651 delete [] current_packet->payload;
652 delete current_packet;
653 it = packet_list.erase(it);
654 } else {
655 ++it;
656 }
657 }
658
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000659 // Check for FEC in packets, and separate payloads into several packets.
660 int ret = payload_splitter_->SplitFec(&packet_list, decoder_database_.get());
661 if (ret != PayloadSplitter::kOK) {
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000662 PacketBuffer::DeleteAllPackets(&packet_list);
663 switch (ret) {
664 case PayloadSplitter::kUnknownPayloadType:
665 return kUnknownRtpPayloadType;
666 default:
667 return kOtherError;
668 }
669 }
670
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000671 // Split payloads into smaller chunks. This also verifies that all payloads
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000672 // are of a known payload type. SplitAudio() method is protected against
673 // sync-packets.
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +0000674 ret = payload_splitter_->SplitAudio(&packet_list, *decoder_database_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000675 if (ret != PayloadSplitter::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000676 PacketBuffer::DeleteAllPackets(&packet_list);
677 switch (ret) {
678 case PayloadSplitter::kUnknownPayloadType:
679 return kUnknownRtpPayloadType;
680 case PayloadSplitter::kFrameSplitError:
681 return kFrameSplitError;
682 default:
683 return kOtherError;
684 }
685 }
686
ossu97ba30e2016-04-25 07:55:58 -0700687 // Update bandwidth estimate, if the packet is not sync-packet nor comfort
688 // noise.
689 if (!packet_list.empty() && !packet_list.front()->sync_packet &&
690 !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.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000696 decoder->IncomingPacket(packet_list.front()->payload,
697 packet_list.front()->payload_length,
698 packet_list.front()->header.sequenceNumber,
699 packet_list.front()->header.timestamp,
700 receive_timestamp);
701 }
702
henrik.lundin48ed9302015-10-29 05:36:24 -0700703 if (nack_enabled_) {
704 RTC_DCHECK(nack_);
705 if (update_sample_rate_and_channels) {
706 nack_->Reset();
707 }
708 nack_->UpdateLastReceivedPacket(packet_list.front()->header.sequenceNumber,
709 packet_list.front()->header.timestamp);
710 }
711
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000712 // Insert packets in buffer.
henrik.lundin116c84e2015-08-27 13:14:48 -0700713 const size_t buffer_length_before_insert =
714 packet_buffer_->NumPacketsInBuffer();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000715 ret = packet_buffer_->InsertPacketList(
716 &packet_list,
717 *decoder_database_,
718 &current_rtp_payload_type_,
719 &current_cng_rtp_payload_type_);
720 if (ret == PacketBuffer::kFlushed) {
721 // Reset DSP timestamp etc. if packet buffer flushed.
722 new_codec_ = true;
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000723 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000724 } else if (ret != PacketBuffer::kOK) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000725 PacketBuffer::DeleteAllPackets(&packet_list);
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000726 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000727 }
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000728
729 if (first_packet_) {
730 first_packet_ = false;
731 // Update the codec on the next GetAudio call.
732 new_codec_ = true;
733 }
734
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000735 if (current_rtp_payload_type_ != 0xFF) {
736 const DecoderDatabase::DecoderInfo* dec_info =
737 decoder_database_->GetDecoderInfo(current_rtp_payload_type_);
738 if (!dec_info) {
739 assert(false); // Already checked that the payload type is known.
740 }
741 }
742
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000743 if (update_sample_rate_and_channels && !packet_buffer_->Empty()) {
744 // We do not use |current_rtp_payload_type_| to |set payload_type|, but
745 // get the next RTP header from |packet_buffer_| to obtain the payload type.
746 // The reason for it is the following corner case. If NetEq receives a
747 // CNG packet with a sample rate different than the current CNG then it
748 // flushes its buffer, assuming send codec must have been changed. However,
749 // payload type of the hypothetically new send codec is not known.
750 const RTPHeader* rtp_header = packet_buffer_->NextRtpHeader();
751 assert(rtp_header);
752 int payload_type = rtp_header->payloadType;
ossu97ba30e2016-04-25 07:55:58 -0700753 size_t channels = 1;
754 if (!decoder_database_->IsComfortNoise(payload_type)) {
755 AudioDecoder* decoder = decoder_database_->GetDecoder(payload_type);
756 assert(decoder); // Payloads are already checked to be valid.
757 channels = decoder->Channels();
758 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000759 const DecoderDatabase::DecoderInfo* decoder_info =
760 decoder_database_->GetDecoderInfo(payload_type);
761 assert(decoder_info);
762 if (decoder_info->fs_hz != fs_hz_ ||
ossu97ba30e2016-04-25 07:55:58 -0700763 channels != algorithm_buffer_->Channels()) {
764 SetSampleRateAndChannels(decoder_info->fs_hz, channels);
henrik.lundin48ed9302015-10-29 05:36:24 -0700765 }
766 if (nack_enabled_) {
767 RTC_DCHECK(nack_);
768 // Update the sample rate even if the rate is not new, because of Reset().
769 nack_->UpdateSampleRate(fs_hz_);
770 }
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000771 }
772
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000773 // TODO(hlundin): Move this code to DelayManager class.
774 const DecoderDatabase::DecoderInfo* dec_info =
775 decoder_database_->GetDecoderInfo(main_header.payloadType);
776 assert(dec_info); // Already checked that the payload type is known.
777 delay_manager_->LastDecoderType(dec_info->codec_type);
778 if (delay_manager_->last_pack_cng_or_dtmf() == 0) {
779 // Calculate the total speech length carried in each packet.
henrik.lundin116c84e2015-08-27 13:14:48 -0700780 const size_t buffer_length_after_insert =
781 packet_buffer_->NumPacketsInBuffer();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000782
henrik.lundin116c84e2015-08-27 13:14:48 -0700783 if (buffer_length_after_insert > buffer_length_before_insert) {
784 const size_t packet_length_samples =
785 (buffer_length_after_insert - buffer_length_before_insert) *
786 decoder_frame_length_;
787 if (packet_length_samples != decision_logic_->packet_length_samples()) {
788 decision_logic_->set_packet_length_samples(packet_length_samples);
789 delay_manager_->SetPacketAudioLength(
790 rtc::checked_cast<int>((1000 * packet_length_samples) / fs_hz_));
791 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000792 }
793
794 // Update statistics.
pbos@webrtc.org0946a562013-04-09 00:28:06 +0000795 if ((int32_t) (main_header.timestamp - timestamp_) >= 0 &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000796 !new_codec_) {
797 // Only update statistics if incoming packet is not older than last played
798 // out packet, and if new codec flag is not set.
799 delay_manager_->Update(main_header.sequenceNumber, main_header.timestamp,
800 fs_hz_);
801 }
802 } else if (delay_manager_->last_pack_cng_or_dtmf() == -1) {
803 // This is first "normal" packet after CNG or DTMF.
804 // Reset packet time counter and measure time until next packet,
805 // but don't update statistics.
806 delay_manager_->set_last_pack_cng_or_dtmf(0);
807 delay_manager_->ResetPacketIatCount();
808 }
809 return 0;
810}
811
henrik.lundin6d8e0112016-03-04 10:34:21 -0800812int NetEqImpl::GetAudioInternal(AudioFrame* audio_frame) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000813 PacketList packet_list;
814 DtmfEvent dtmf_event;
815 Operations operation;
816 bool play_dtmf;
henrik.lundined497212016-04-25 10:11:38 -0700817 tick_timer_->Increment();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000818 int return_value = GetDecision(&operation, &packet_list, &dtmf_event,
819 &play_dtmf);
820 if (return_value != 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000821 last_mode_ = kModeError;
822 return return_value;
823 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000824
825 AudioDecoder::SpeechType speech_type;
826 int length = 0;
827 int decode_return_value = Decode(&packet_list, &operation,
828 &length, &speech_type);
829
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000830 assert(vad_.get());
831 bool sid_frame_available =
832 (operation == kRfc3389Cng && !packet_list.empty());
Peter Kastingdce40cf2015-08-24 14:52:23 -0700833 vad_->Update(decoded_buffer_.get(), static_cast<size_t>(length), speech_type,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000834 sid_frame_available, fs_hz_);
835
henrik.lundinb1fb72b2016-05-03 08:18:47 -0700836 if (sid_frame_available || speech_type == AudioDecoder::kComfortNoise) {
837 // Start a new stopwatch since we are decoding a new CNG packet.
838 generated_noise_stopwatch_ = tick_timer_->GetNewStopwatch();
839 }
840
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000841 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000842 switch (operation) {
843 case kNormal: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000844 DoNormal(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000845 break;
846 }
847 case kMerge: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000848 DoMerge(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000849 break;
850 }
851 case kExpand: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000852 return_value = DoExpand(play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000853 break;
854 }
Henrik Lundincf808d22015-05-27 14:33:29 +0200855 case kAccelerate:
856 case kFastAccelerate: {
857 const bool fast_accelerate =
858 enable_fast_accelerate_ && (operation == kFastAccelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000859 return_value = DoAccelerate(decoded_buffer_.get(), length, speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +0200860 play_dtmf, fast_accelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000861 break;
862 }
863 case kPreemptiveExpand: {
864 return_value = DoPreemptiveExpand(decoded_buffer_.get(), length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000865 speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000866 break;
867 }
868 case kRfc3389Cng:
869 case kRfc3389CngNoPacket: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000870 return_value = DoRfc3389Cng(&packet_list, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000871 break;
872 }
873 case kCodecInternalCng: {
874 // This handles the case when there is no transmission and the decoder
875 // should produce internal comfort noise.
876 // TODO(hlundin): Write test for codec-internal CNG.
minyuel6d92bf52015-09-23 15:20:39 +0200877 DoCodecInternalCng(decoded_buffer_.get(), length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000878 break;
879 }
880 case kDtmf: {
881 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000882 return_value = DoDtmf(dtmf_event, &play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000883 break;
884 }
885 case kAlternativePlc: {
886 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000887 DoAlternativePlc(false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000888 break;
889 }
890 case kAlternativePlcIncreaseTimestamp: {
891 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000892 DoAlternativePlc(true);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000893 break;
894 }
895 case kAudioRepetitionIncreaseTimestamp: {
896 // TODO(hlundin): Write test for this.
Peter Kastingb7e50542015-06-11 12:55:50 -0700897 sync_buffer_->IncreaseEndTimestamp(
898 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000899 // Skipping break on purpose. Execution should move on into the
900 // next case.
kjellander@webrtc.org7d2b6a92015-01-28 18:37:58 +0000901 FALLTHROUGH();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000902 }
903 case kAudioRepetition: {
904 // TODO(hlundin): Write test for this.
905 // Copy last |output_size_samples_| from |sync_buffer_| to
906 // |algorithm_buffer|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000907 algorithm_buffer_->PushBackFromIndex(
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000908 *sync_buffer_, sync_buffer_->Size() - output_size_samples_);
909 expand_->Reset();
910 break;
911 }
912 case kUndefined: {
Henrik Lundind67a2192015-08-03 12:54:37 +0200913 LOG(LS_ERROR) << "Invalid operation kUndefined.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000914 assert(false); // This should not happen.
915 last_mode_ = kModeError;
916 return kInvalidOperation;
917 }
918 } // End of switch.
minyue5bd33972016-05-02 04:46:11 -0700919 last_operation_ = operation;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000920 if (return_value < 0) {
921 return return_value;
922 }
923
924 if (last_mode_ != kModeRfc3389Cng) {
925 comfort_noise_->Reset();
926 }
927
928 // Copy from |algorithm_buffer| to |sync_buffer_|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000929 sync_buffer_->PushBack(*algorithm_buffer_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000930
931 // Extract data from |sync_buffer_| to |output|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000932 size_t num_output_samples_per_channel = output_size_samples_;
933 size_t num_output_samples = output_size_samples_ * sync_buffer_->Channels();
henrik.lundin6d8e0112016-03-04 10:34:21 -0800934 if (num_output_samples > AudioFrame::kMaxDataSizeSamples) {
935 LOG(LS_WARNING) << "Output array is too short. "
936 << AudioFrame::kMaxDataSizeSamples << " < "
937 << output_size_samples_ << " * "
938 << sync_buffer_->Channels();
939 num_output_samples = AudioFrame::kMaxDataSizeSamples;
940 num_output_samples_per_channel =
941 AudioFrame::kMaxDataSizeSamples / sync_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000942 }
henrik.lundin6d8e0112016-03-04 10:34:21 -0800943 sync_buffer_->GetNextAudioInterleaved(num_output_samples_per_channel,
944 audio_frame);
945 audio_frame->sample_rate_hz_ = fs_hz_;
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200946 if (sync_buffer_->FutureLength() < expand_->overlap_length()) {
947 // The sync buffer should always contain |overlap_length| samples, but now
948 // too many samples have been extracted. Reinstall the |overlap_length|
949 // lookahead by moving the index.
950 const size_t missing_lookahead_samples =
951 expand_->overlap_length() - sync_buffer_->FutureLength();
henrikg91d6ede2015-09-17 00:24:34 -0700952 RTC_DCHECK_GE(sync_buffer_->next_index(), missing_lookahead_samples);
Henrik Lundin05f71fc2015-09-01 11:51:58 +0200953 sync_buffer_->set_next_index(sync_buffer_->next_index() -
954 missing_lookahead_samples);
955 }
henrik.lundin6d8e0112016-03-04 10:34:21 -0800956 if (audio_frame->samples_per_channel_ != output_size_samples_) {
957 LOG(LS_ERROR) << "audio_frame->samples_per_channel_ ("
958 << audio_frame->samples_per_channel_
Henrik Lundind67a2192015-08-03 12:54:37 +0200959 << ") != output_size_samples_ (" << output_size_samples_
960 << ")";
minyue@webrtc.orgdb1cefc2013-08-13 01:39:21 +0000961 // TODO(minyue): treatment of under-run, filling zeros
henrik.lundin6d8e0112016-03-04 10:34:21 -0800962 memset(audio_frame->data_, 0, num_output_samples * sizeof(int16_t));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000963 return kSampleUnderrun;
964 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000965
966 // Should always have overlap samples left in the |sync_buffer_|.
henrikg91d6ede2015-09-17 00:24:34 -0700967 RTC_DCHECK_GE(sync_buffer_->FutureLength(), expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000968
969 if (play_dtmf) {
henrik.lundin6d8e0112016-03-04 10:34:21 -0800970 return_value =
971 DtmfOverdub(dtmf_event, sync_buffer_->Channels(), audio_frame->data_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000972 }
973
974 // Update the background noise parameters if last operation wrote data
975 // straight from the decoder to the |sync_buffer_|. That is, none of the
976 // operations that modify the signal can be followed by a parameter update.
977 if ((last_mode_ == kModeNormal) ||
978 (last_mode_ == kModeAccelerateFail) ||
979 (last_mode_ == kModePreemptiveExpandFail) ||
980 (last_mode_ == kModeRfc3389Cng) ||
981 (last_mode_ == kModeCodecInternalCng)) {
982 background_noise_->Update(*sync_buffer_, *vad_.get());
983 }
984
985 if (operation == kDtmf) {
986 // DTMF data was written the end of |sync_buffer_|.
987 // Update index to end of DTMF data in |sync_buffer_|.
988 sync_buffer_->set_dtmf_index(sync_buffer_->Size());
989 }
990
henrik.lundin@webrtc.orged865b52014-03-06 10:28:07 +0000991 if (last_mode_ != kModeExpand) {
992 // If last operation was not expand, calculate the |playout_timestamp_| from
993 // the |sync_buffer_|. However, do not update the |playout_timestamp_| if it
994 // would be moved "backwards".
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000995 uint32_t temp_timestamp = sync_buffer_->end_timestamp() -
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000996 static_cast<uint32_t>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000997 if (static_cast<int32_t>(temp_timestamp - playout_timestamp_) > 0) {
998 playout_timestamp_ = temp_timestamp;
999 }
1000 } else {
1001 // Use dead reckoning to estimate the |playout_timestamp_|.
Peter Kastingb7e50542015-06-11 12:55:50 -07001002 playout_timestamp_ += static_cast<uint32_t>(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001003 }
henrik.lundin15c51e32016-04-06 08:38:56 -07001004 // Set the timestamp in the audio frame to zero before the first packet has
1005 // been inserted. Otherwise, subtract the frame size in samples to get the
1006 // timestamp of the first sample in the frame (playout_timestamp_ is the
1007 // last + 1).
1008 audio_frame->timestamp_ =
1009 first_packet_
1010 ? 0
1011 : timestamp_scaler_->ToExternal(playout_timestamp_) -
1012 static_cast<uint32_t>(audio_frame->samples_per_channel_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001013
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001014 if (!(last_mode_ == kModeRfc3389Cng ||
1015 last_mode_ == kModeCodecInternalCng ||
1016 last_mode_ == kModeExpand)) {
1017 generated_noise_stopwatch_.reset();
1018 }
1019
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001020 if (decode_return_value) return decode_return_value;
1021 return return_value;
1022}
1023
1024int NetEqImpl::GetDecision(Operations* operation,
1025 PacketList* packet_list,
1026 DtmfEvent* dtmf_event,
1027 bool* play_dtmf) {
1028 // Initialize output variables.
1029 *play_dtmf = false;
1030 *operation = kUndefined;
1031
1032 // Increment time counters.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001033 stats_.IncreaseCounter(output_size_samples_, fs_hz_);
1034
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001035 assert(sync_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001036 uint32_t end_timestamp = sync_buffer_->end_timestamp();
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001037 if (!new_codec_) {
1038 const uint32_t five_seconds_samples = 5 * fs_hz_;
1039 packet_buffer_->DiscardOldPackets(end_timestamp, five_seconds_samples);
1040 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001041 const RTPHeader* header = packet_buffer_->NextRtpHeader();
1042
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001043 RTC_DCHECK(!generated_noise_stopwatch_ ||
1044 generated_noise_stopwatch_->ElapsedTicks() >= 1);
1045 uint64_t generated_noise_samples =
1046 generated_noise_stopwatch_
1047 ? (generated_noise_stopwatch_->ElapsedTicks() - 1) *
1048 output_size_samples_ +
1049 decision_logic_->noise_fast_forward()
1050 : 0;
1051
henrik.lundin@webrtc.orgca8cb952014-03-12 10:26:52 +00001052 if (decision_logic_->CngRfc3389On() || last_mode_ == kModeRfc3389Cng) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001053 // Because of timestamp peculiarities, we have to "manually" disallow using
1054 // a CNG packet with the same timestamp as the one that was last played.
1055 // This can happen when using redundancy and will cause the timing to shift.
henrik.lundin@webrtc.org24779fe2014-03-14 12:40:05 +00001056 while (header && decoder_database_->IsComfortNoise(header->payloadType) &&
1057 (end_timestamp >= header->timestamp ||
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001058 end_timestamp + generated_noise_samples > header->timestamp)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001059 // Don't use this packet, discard it.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001060 if (packet_buffer_->DiscardNextPacket() != PacketBuffer::kOK) {
1061 assert(false); // Must be ok by design.
1062 }
1063 // Check buffer again.
1064 if (!new_codec_) {
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001065 packet_buffer_->DiscardOldPackets(end_timestamp, 5 * fs_hz_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001066 }
1067 header = packet_buffer_->NextRtpHeader();
1068 }
1069 }
1070
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001071 assert(expand_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001072 const int samples_left = static_cast<int>(sync_buffer_->FutureLength() -
1073 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001074 if (last_mode_ == kModeAccelerateSuccess ||
1075 last_mode_ == kModeAccelerateLowEnergy ||
1076 last_mode_ == kModePreemptiveExpandSuccess ||
1077 last_mode_ == kModePreemptiveExpandLowEnergy) {
1078 // Subtract (samples_left + output_size_samples_) from sampleMemory.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001079 decision_logic_->AddSampleMemory(
1080 -(samples_left + rtc::checked_cast<int>(output_size_samples_)));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001081 }
1082
1083 // Check if it is time to play a DTMF event.
Peter Kastingb7e50542015-06-11 12:55:50 -07001084 if (dtmf_buffer_->GetEvent(
1085 static_cast<uint32_t>(
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001086 end_timestamp + generated_noise_samples),
Peter Kastingb7e50542015-06-11 12:55:50 -07001087 dtmf_event)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001088 *play_dtmf = true;
1089 }
1090
1091 // Get instruction.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001092 assert(sync_buffer_.get());
1093 assert(expand_.get());
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001094 generated_noise_samples =
1095 generated_noise_stopwatch_
1096 ? generated_noise_stopwatch_->ElapsedTicks() * output_size_samples_ +
1097 decision_logic_->noise_fast_forward()
1098 : 0;
1099 *operation = decision_logic_->GetDecision(
1100 *sync_buffer_, *expand_, decoder_frame_length_, header, last_mode_,
1101 *play_dtmf, generated_noise_samples, &reset_decoder_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001102
1103 // Check if we already have enough samples in the |sync_buffer_|. If so,
1104 // change decision to normal, unless the decision was merge, accelerate, or
1105 // preemptive expand.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001106 if (samples_left >= rtc::checked_cast<int>(output_size_samples_) &&
1107 *operation != kMerge &&
1108 *operation != kAccelerate &&
1109 *operation != kFastAccelerate &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001110 *operation != kPreemptiveExpand) {
1111 *operation = kNormal;
1112 return 0;
1113 }
1114
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001115 decision_logic_->ExpandDecision(*operation);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001116
1117 // Check conditions for reset.
1118 if (new_codec_ || *operation == kUndefined) {
1119 // The only valid reason to get kUndefined is that new_codec_ is set.
1120 assert(new_codec_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001121 if (*play_dtmf && !header) {
1122 timestamp_ = dtmf_event->timestamp;
1123 } else {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001124 if (!header) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001125 LOG(LS_ERROR) << "Packet missing where it shouldn't.";
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001126 return -1;
1127 }
1128 timestamp_ = header->timestamp;
1129 if (*operation == kRfc3389CngNoPacket
1130#ifndef LEGACY_BITEXACT
1131 // Without this check, it can happen that a non-CNG packet is sent to
1132 // the CNG decoder as if it was a SID frame. This is clearly a bug,
1133 // but is kept for now to maintain bit-exactness with the test
1134 // vectors.
1135 && decoder_database_->IsComfortNoise(header->payloadType)
1136#endif
1137 ) {
1138 // Change decision to CNG packet, since we do have a CNG packet, but it
1139 // was considered too early to use. Now, use it anyway.
1140 *operation = kRfc3389Cng;
1141 } else if (*operation != kRfc3389Cng) {
1142 *operation = kNormal;
1143 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001144 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001145 // Adjust |sync_buffer_| timestamp before setting |end_timestamp| to the
1146 // new value.
1147 sync_buffer_->IncreaseEndTimestamp(timestamp_ - end_timestamp);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001148 end_timestamp = timestamp_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001149 new_codec_ = false;
1150 decision_logic_->SoftReset();
1151 buffer_level_filter_->Reset();
1152 delay_manager_->Reset();
1153 stats_.ResetMcu();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001154 }
1155
Peter Kastingdce40cf2015-08-24 14:52:23 -07001156 size_t required_samples = output_size_samples_;
1157 const size_t samples_10_ms = static_cast<size_t>(80 * fs_mult_);
1158 const size_t samples_20_ms = 2 * samples_10_ms;
1159 const size_t samples_30_ms = 3 * samples_10_ms;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001160
1161 switch (*operation) {
1162 case kExpand: {
1163 timestamp_ = end_timestamp;
1164 return 0;
1165 }
1166 case kRfc3389CngNoPacket:
1167 case kCodecInternalCng: {
1168 return 0;
1169 }
1170 case kDtmf: {
1171 // TODO(hlundin): Write test for this.
1172 // Update timestamp.
1173 timestamp_ = end_timestamp;
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001174 const uint64_t generated_noise_samples =
1175 generated_noise_stopwatch_
1176 ? generated_noise_stopwatch_->ElapsedTicks() *
1177 output_size_samples_ +
1178 decision_logic_->noise_fast_forward()
1179 : 0;
1180 if (generated_noise_samples > 0 && last_mode_ != kModeDtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001181 // Make a jump in timestamp due to the recently played comfort noise.
Peter Kastingb7e50542015-06-11 12:55:50 -07001182 uint32_t timestamp_jump =
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001183 static_cast<uint32_t>(generated_noise_samples);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001184 sync_buffer_->IncreaseEndTimestamp(timestamp_jump);
1185 timestamp_ += timestamp_jump;
1186 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001187 return 0;
1188 }
Henrik Lundincf808d22015-05-27 14:33:29 +02001189 case kAccelerate:
1190 case kFastAccelerate: {
1191 // In order to do an accelerate we need at least 30 ms of audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001192 if (samples_left >= static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001193 // Already have enough data, so we do not need to extract any more.
1194 decision_logic_->set_sample_memory(samples_left);
1195 decision_logic_->set_prev_time_scale(true);
1196 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001197 } else if (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001198 decoder_frame_length_ >= samples_30_ms) {
1199 // Avoid decoding more data as it might overflow the playout buffer.
1200 *operation = kNormal;
1201 return 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001202 } else if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001203 decoder_frame_length_ < samples_30_ms) {
1204 // Build up decoded data by decoding at least 20 ms of audio data. Do
1205 // not perform accelerate yet, but wait until we only need to do one
1206 // decoding.
1207 required_samples = 2 * output_size_samples_;
1208 *operation = kNormal;
1209 }
1210 // If none of the above is true, we have one of two possible situations:
1211 // (1) 20 ms <= samples_left < 30 ms and decoder_frame_length_ < 30 ms; or
1212 // (2) samples_left < 10 ms and decoder_frame_length_ >= 30 ms.
1213 // In either case, we move on with the accelerate decision, and decode one
1214 // frame now.
1215 break;
1216 }
1217 case kPreemptiveExpand: {
1218 // In order to do a preemptive expand we need at least 30 ms of decoded
1219 // audio data.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001220 if ((samples_left >= static_cast<int>(samples_30_ms)) ||
1221 (samples_left >= static_cast<int>(samples_10_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001222 decoder_frame_length_ >= samples_30_ms)) {
1223 // Already have enough data, so we do not need to extract any more.
1224 // Or, avoid decoding more data as it might overflow the playout buffer.
1225 // Still try preemptive expand, though.
1226 decision_logic_->set_sample_memory(samples_left);
1227 decision_logic_->set_prev_time_scale(true);
1228 return 0;
1229 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07001230 if (samples_left < static_cast<int>(samples_20_ms) &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001231 decoder_frame_length_ < samples_30_ms) {
1232 // Build up decoded data by decoding at least 20 ms of audio data.
1233 // Still try to perform preemptive expand.
1234 required_samples = 2 * output_size_samples_;
1235 }
1236 // Move on with the preemptive expand decision.
1237 break;
1238 }
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001239 case kMerge: {
1240 required_samples =
1241 std::max(merge_->RequiredFutureSamples(), required_samples);
1242 break;
1243 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001244 default: {
1245 // Do nothing.
1246 }
1247 }
1248
1249 // Get packets from buffer.
1250 int extracted_samples = 0;
1251 if (header &&
1252 *operation != kAlternativePlc &&
1253 *operation != kAlternativePlcIncreaseTimestamp &&
1254 *operation != kAudioRepetition &&
1255 *operation != kAudioRepetitionIncreaseTimestamp) {
1256 sync_buffer_->IncreaseEndTimestamp(header->timestamp - end_timestamp);
1257 if (decision_logic_->CngOff()) {
1258 // Adjustment of timestamp only corresponds to an actual packet loss
1259 // if comfort noise is not played. If comfort noise was just played,
1260 // this adjustment of timestamp is only done to get back in sync with the
1261 // stream timestamp; no loss to report.
1262 stats_.LostSamples(header->timestamp - end_timestamp);
1263 }
1264
1265 if (*operation != kRfc3389Cng) {
1266 // We are about to decode and use a non-CNG packet.
1267 decision_logic_->SetCngOff();
1268 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001269
1270 extracted_samples = ExtractPackets(required_samples, packet_list);
1271 if (extracted_samples < 0) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001272 return kPacketBufferCorruption;
1273 }
1274 }
1275
Henrik Lundincf808d22015-05-27 14:33:29 +02001276 if (*operation == kAccelerate || *operation == kFastAccelerate ||
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001277 *operation == kPreemptiveExpand) {
1278 decision_logic_->set_sample_memory(samples_left + extracted_samples);
1279 decision_logic_->set_prev_time_scale(true);
1280 }
1281
Henrik Lundincf808d22015-05-27 14:33:29 +02001282 if (*operation == kAccelerate || *operation == kFastAccelerate) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001283 // Check that we have enough data (30ms) to do accelerate.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001284 if (extracted_samples + samples_left < static_cast<int>(samples_30_ms)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001285 // TODO(hlundin): Write test for this.
1286 // Not enough, do normal operation instead.
1287 *operation = kNormal;
1288 }
1289 }
1290
1291 timestamp_ = end_timestamp;
1292 return 0;
1293}
1294
1295int NetEqImpl::Decode(PacketList* packet_list, Operations* operation,
1296 int* decoded_length,
1297 AudioDecoder::SpeechType* speech_type) {
1298 *speech_type = AudioDecoder::kSpeech;
minyuel6d92bf52015-09-23 15:20:39 +02001299
1300 // When packet_list is empty, we may be in kCodecInternalCng mode, and for
1301 // that we use current active decoder.
1302 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1303
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001304 if (!packet_list->empty()) {
1305 const Packet* packet = packet_list->front();
pkasting@chromium.org0e81fdf2015-02-02 23:54:03 +00001306 uint8_t payload_type = packet->header.payloadType;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001307 if (!decoder_database_->IsComfortNoise(payload_type)) {
1308 decoder = decoder_database_->GetDecoder(payload_type);
1309 assert(decoder);
1310 if (!decoder) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001311 LOG(LS_WARNING) << "Unknown payload type "
1312 << static_cast<int>(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001313 PacketBuffer::DeleteAllPackets(packet_list);
1314 return kDecoderNotFound;
1315 }
1316 bool decoder_changed;
1317 decoder_database_->SetActiveDecoder(payload_type, &decoder_changed);
1318 if (decoder_changed) {
1319 // We have a new decoder. Re-init some values.
1320 const DecoderDatabase::DecoderInfo* decoder_info = decoder_database_
1321 ->GetDecoderInfo(payload_type);
1322 assert(decoder_info);
1323 if (!decoder_info) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001324 LOG(LS_WARNING) << "Unknown payload type "
1325 << static_cast<int>(payload_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001326 PacketBuffer::DeleteAllPackets(packet_list);
1327 return kDecoderNotFound;
1328 }
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001329 // If sampling rate or number of channels has changed, we need to make
1330 // a reset.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001331 if (decoder_info->fs_hz != fs_hz_ ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001332 decoder->Channels() != algorithm_buffer_->Channels()) {
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001333 // TODO(tlegrand): Add unittest to cover this event.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001334 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->Channels());
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001335 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001336 sync_buffer_->set_end_timestamp(timestamp_);
1337 playout_timestamp_ = timestamp_;
1338 }
1339 }
1340 }
1341
1342 if (reset_decoder_) {
1343 // TODO(hlundin): Write test for this.
Karl Wiberg43766482015-08-27 15:22:11 +02001344 if (decoder)
1345 decoder->Reset();
1346
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001347 // Reset comfort noise decoder.
ossu97ba30e2016-04-25 07:55:58 -07001348 ComfortNoiseDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02001349 if (cng_decoder)
1350 cng_decoder->Reset();
1351
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001352 reset_decoder_ = false;
1353 }
1354
1355#ifdef LEGACY_BITEXACT
1356 // Due to a bug in old SignalMCU, it could happen that CNG operation was
1357 // decided, but a speech packet was provided. The speech packet will be used
1358 // to update the comfort noise decoder, as if it was a SID frame, which is
1359 // clearly wrong.
1360 if (*operation == kRfc3389Cng) {
1361 return 0;
1362 }
1363#endif
1364
1365 *decoded_length = 0;
1366 // Update codec-internal PLC state.
1367 if ((*operation == kMerge) && decoder && decoder->HasDecodePlc()) {
1368 decoder->DecodePlc(1, &decoded_buffer_[*decoded_length]);
1369 }
1370
minyuel6d92bf52015-09-23 15:20:39 +02001371 int return_value;
1372 if (*operation == kCodecInternalCng) {
1373 RTC_DCHECK(packet_list->empty());
1374 return_value = DecodeCng(decoder, decoded_length, speech_type);
1375 } else {
1376 return_value = DecodeLoop(packet_list, *operation, decoder,
1377 decoded_length, speech_type);
1378 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001379
1380 if (*decoded_length < 0) {
1381 // Error returned from the decoder.
1382 *decoded_length = 0;
Peter Kastingb7e50542015-06-11 12:55:50 -07001383 sync_buffer_->IncreaseEndTimestamp(
1384 static_cast<uint32_t>(decoder_frame_length_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001385 int error_code = 0;
1386 if (decoder)
1387 error_code = decoder->ErrorCode();
1388 if (error_code != 0) {
1389 // Got some error code from the decoder.
1390 decoder_error_code_ = error_code;
1391 return_value = kDecoderErrorCode;
Henrik Lundind67a2192015-08-03 12:54:37 +02001392 LOG(LS_WARNING) << "Decoder returned error code: " << error_code;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001393 } else {
1394 // Decoder does not implement error codes. Return generic error.
1395 return_value = kOtherDecoderError;
Henrik Lundind67a2192015-08-03 12:54:37 +02001396 LOG(LS_WARNING) << "Decoder error (no error code)";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001397 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001398 *operation = kExpand; // Do expansion to get data instead.
1399 }
1400 if (*speech_type != AudioDecoder::kComfortNoise) {
1401 // Don't increment timestamp if codec returned CNG speech type
1402 // since in this case, the we will increment the CNGplayedTS counter.
1403 // Increase with number of samples per channel.
1404 assert(*decoded_length == 0 ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001405 (decoder && decoder->Channels() == sync_buffer_->Channels()));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001406 sync_buffer_->IncreaseEndTimestamp(
1407 *decoded_length / static_cast<int>(sync_buffer_->Channels()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001408 }
1409 return return_value;
1410}
1411
minyuel6d92bf52015-09-23 15:20:39 +02001412int NetEqImpl::DecodeCng(AudioDecoder* decoder, int* decoded_length,
1413 AudioDecoder::SpeechType* speech_type) {
1414 if (!decoder) {
1415 // This happens when active decoder is not defined.
1416 *decoded_length = -1;
1417 return 0;
1418 }
1419
1420 while (*decoded_length < rtc::checked_cast<int>(output_size_samples_)) {
1421 const int length = decoder->Decode(
1422 nullptr, 0, fs_hz_,
1423 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1424 &decoded_buffer_[*decoded_length], speech_type);
1425 if (length > 0) {
1426 *decoded_length += length;
minyuel6d92bf52015-09-23 15:20:39 +02001427 } else {
1428 // Error.
1429 LOG(LS_WARNING) << "Failed to decode CNG";
1430 *decoded_length = -1;
1431 break;
1432 }
1433 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1434 // Guard against overflow.
1435 LOG(LS_WARNING) << "Decoded too much CNG.";
1436 return kDecodedTooMuch;
1437 }
1438 }
1439 return 0;
1440}
1441
1442int NetEqImpl::DecodeLoop(PacketList* packet_list, const Operations& operation,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001443 AudioDecoder* decoder, int* decoded_length,
1444 AudioDecoder::SpeechType* speech_type) {
1445 Packet* packet = NULL;
1446 if (!packet_list->empty()) {
1447 packet = packet_list->front();
1448 }
minyuel6d92bf52015-09-23 15:20:39 +02001449
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001450 // Do decoding.
1451 while (packet &&
1452 !decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1453 assert(decoder); // At this point, we must have a decoder object.
1454 // The number of channels in the |sync_buffer_| should be the same as the
1455 // number decoder channels.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001456 assert(sync_buffer_->Channels() == decoder->Channels());
1457 assert(decoded_buffer_length_ >= kMaxFrameSize * decoder->Channels());
minyuel6d92bf52015-09-23 15:20:39 +02001458 assert(operation == kNormal || operation == kAccelerate ||
1459 operation == kFastAccelerate || operation == kMerge ||
1460 operation == kPreemptiveExpand);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001461 packet_list->pop_front();
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001462 size_t payload_length = packet->payload_length;
Peter Kasting36b7cc32015-06-11 19:57:18 -07001463 int decode_length;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +00001464 if (packet->sync_packet) {
1465 // Decode to silence with the same frame size as the last decode.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001466 memset(&decoded_buffer_[*decoded_length], 0,
1467 decoder_frame_length_ * decoder->Channels() *
1468 sizeof(decoded_buffer_[0]));
Peter Kastingdce40cf2015-08-24 14:52:23 -07001469 decode_length = rtc::checked_cast<int>(decoder_frame_length_);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +00001470 } else if (!packet->primary) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001471 // This is a redundant payload; call the special decoder method.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001472 decode_length = decoder->DecodeRedundant(
henrik.lundin@webrtc.org1eda4e32015-02-25 10:02:29 +00001473 packet->payload, packet->payload_length, fs_hz_,
minyue@webrtc.org7f7d7e32015-03-16 12:30:37 +00001474 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001475 &decoded_buffer_[*decoded_length], speech_type);
1476 } else {
henrik.lundin@webrtc.org1eda4e32015-02-25 10:02:29 +00001477 decode_length =
minyue@webrtc.org7f7d7e32015-03-16 12:30:37 +00001478 decoder->Decode(
1479 packet->payload, packet->payload_length, fs_hz_,
1480 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1481 &decoded_buffer_[*decoded_length], speech_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001482 }
1483
1484 delete[] packet->payload;
1485 delete packet;
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001486 packet = NULL;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001487 if (decode_length > 0) {
1488 *decoded_length += decode_length;
1489 // Update |decoder_frame_length_| with number of samples per channel.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001490 decoder_frame_length_ =
Peter Kastingdce40cf2015-08-24 14:52:23 -07001491 static_cast<size_t>(decode_length) / decoder->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001492 } else if (decode_length < 0) {
1493 // Error.
Henrik Lundind67a2192015-08-03 12:54:37 +02001494 LOG(LS_WARNING) << "Decode " << decode_length << " " << payload_length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001495 *decoded_length = -1;
1496 PacketBuffer::DeleteAllPackets(packet_list);
1497 break;
1498 }
1499 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1500 // Guard against overflow.
Henrik Lundind67a2192015-08-03 12:54:37 +02001501 LOG(LS_WARNING) << "Decoded too much.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001502 PacketBuffer::DeleteAllPackets(packet_list);
1503 return kDecodedTooMuch;
1504 }
1505 if (!packet_list->empty()) {
1506 packet = packet_list->front();
1507 } else {
1508 packet = NULL;
1509 }
1510 } // End of decode loop.
1511
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001512 // If the list is not empty at this point, either a decoding error terminated
1513 // the while-loop, or list must hold exactly one CNG packet.
1514 assert(packet_list->empty() || *decoded_length < 0 ||
1515 (packet_list->size() == 1 && packet &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001516 decoder_database_->IsComfortNoise(packet->header.payloadType)));
1517 return 0;
1518}
1519
1520void NetEqImpl::DoNormal(const int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001521 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001522 assert(normal_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001523 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001524 normal_->Process(decoded_buffer, decoded_length, last_mode_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001525 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001526 if (decoded_length != 0) {
1527 last_mode_ = kModeNormal;
1528 }
1529
1530 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1531 if ((speech_type == AudioDecoder::kComfortNoise)
1532 || ((last_mode_ == kModeCodecInternalCng)
1533 && (decoded_length == 0))) {
1534 // TODO(hlundin): Remove second part of || statement above.
1535 last_mode_ = kModeCodecInternalCng;
1536 }
1537
1538 if (!play_dtmf) {
1539 dtmf_tone_generator_->Reset();
1540 }
1541}
1542
1543void NetEqImpl::DoMerge(int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001544 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
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 assert(merge_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001547 size_t new_length = merge_->Process(decoded_buffer, decoded_length,
1548 mute_factor_array_.get(),
1549 algorithm_buffer_.get());
1550 size_t expand_length_correction = new_length -
1551 decoded_length / algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001552
1553 // Update in-call and post-call statistics.
1554 if (expand_->MuteFactor(0) == 0) {
1555 // Expand generates only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001556 stats_.ExpandedNoiseSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001557 } else {
1558 // Expansion generates more than only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001559 stats_.ExpandedVoiceSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001560 }
1561
1562 last_mode_ = kModeMerge;
1563 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1564 if (speech_type == AudioDecoder::kComfortNoise) {
1565 last_mode_ = kModeCodecInternalCng;
1566 }
1567 expand_->Reset();
1568 if (!play_dtmf) {
1569 dtmf_tone_generator_->Reset();
1570 }
1571}
1572
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001573int NetEqImpl::DoExpand(bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001574 while ((sync_buffer_->FutureLength() - expand_->overlap_length()) <
Peter Kastingdce40cf2015-08-24 14:52:23 -07001575 output_size_samples_) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001576 algorithm_buffer_->Clear();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001577 int return_value = expand_->Process(algorithm_buffer_.get());
Peter Kastingdce40cf2015-08-24 14:52:23 -07001578 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001579
1580 // Update in-call and post-call statistics.
1581 if (expand_->MuteFactor(0) == 0) {
1582 // Expand operation generates only noise.
1583 stats_.ExpandedNoiseSamples(length);
1584 } else {
1585 // Expand operation generates more than only noise.
1586 stats_.ExpandedVoiceSamples(length);
1587 }
1588
1589 last_mode_ = kModeExpand;
1590
1591 if (return_value < 0) {
1592 return return_value;
1593 }
1594
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001595 sync_buffer_->PushBack(*algorithm_buffer_);
1596 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001597 }
1598 if (!play_dtmf) {
1599 dtmf_tone_generator_->Reset();
1600 }
henrik.lundinb1fb72b2016-05-03 08:18:47 -07001601
1602 if (!generated_noise_stopwatch_) {
1603 // Start a new stopwatch since we may be covering for a lost CNG packet.
1604 generated_noise_stopwatch_ = tick_timer_->GetNewStopwatch();
1605 }
1606
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001607 return 0;
1608}
1609
Henrik Lundincf808d22015-05-27 14:33:29 +02001610int NetEqImpl::DoAccelerate(int16_t* decoded_buffer,
1611 size_t decoded_length,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001612 AudioDecoder::SpeechType speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +02001613 bool play_dtmf,
1614 bool fast_accelerate) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001615 const size_t required_samples =
1616 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001617 size_t borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001618 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001619 size_t decoded_length_per_channel = decoded_length / num_channels;
1620 if (decoded_length_per_channel < required_samples) {
1621 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001622 borrowed_samples_per_channel = static_cast<int>(required_samples -
1623 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001624 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1625 decoded_buffer,
1626 sizeof(int16_t) * decoded_length);
1627 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1628 decoded_buffer);
1629 decoded_length = required_samples * num_channels;
1630 }
1631
Peter Kastingdce40cf2015-08-24 14:52:23 -07001632 size_t samples_removed;
Henrik Lundincf808d22015-05-27 14:33:29 +02001633 Accelerate::ReturnCodes return_code =
1634 accelerate_->Process(decoded_buffer, decoded_length, fast_accelerate,
1635 algorithm_buffer_.get(), &samples_removed);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001636 stats_.AcceleratedSamples(samples_removed);
1637 switch (return_code) {
1638 case Accelerate::kSuccess:
1639 last_mode_ = kModeAccelerateSuccess;
1640 break;
1641 case Accelerate::kSuccessLowEnergy:
1642 last_mode_ = kModeAccelerateLowEnergy;
1643 break;
1644 case Accelerate::kNoStretch:
1645 last_mode_ = kModeAccelerateFail;
1646 break;
1647 case Accelerate::kError:
1648 // TODO(hlundin): Map to kModeError instead?
1649 last_mode_ = kModeAccelerateFail;
1650 return kAccelerateError;
1651 }
1652
1653 if (borrowed_samples_per_channel > 0) {
1654 // Copy borrowed samples back to the |sync_buffer_|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001655 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001656 if (length < borrowed_samples_per_channel) {
1657 // This destroys the beginning of the buffer, but will not cause any
1658 // problems.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001659 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001660 sync_buffer_->Size() -
1661 borrowed_samples_per_channel);
1662 sync_buffer_->PushFrontZeros(borrowed_samples_per_channel - length);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001663 algorithm_buffer_->PopFront(length);
1664 assert(algorithm_buffer_->Empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001665 } else {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001666 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001667 borrowed_samples_per_channel,
1668 sync_buffer_->Size() -
1669 borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001670 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001671 }
1672 }
1673
1674 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1675 if (speech_type == AudioDecoder::kComfortNoise) {
1676 last_mode_ = kModeCodecInternalCng;
1677 }
1678 if (!play_dtmf) {
1679 dtmf_tone_generator_->Reset();
1680 }
1681 expand_->Reset();
1682 return 0;
1683}
1684
1685int NetEqImpl::DoPreemptiveExpand(int16_t* decoded_buffer,
1686 size_t decoded_length,
1687 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001688 bool play_dtmf) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07001689 const size_t required_samples =
1690 static_cast<size_t>(240 * fs_mult_); // Must have 30 ms.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001691 size_t num_channels = algorithm_buffer_->Channels();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001692 size_t borrowed_samples_per_channel = 0;
1693 size_t old_borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001694 size_t decoded_length_per_channel = decoded_length / num_channels;
1695 if (decoded_length_per_channel < required_samples) {
1696 // Must move data from the |sync_buffer_| in order to get 30 ms.
Peter Kastingdce40cf2015-08-24 14:52:23 -07001697 borrowed_samples_per_channel =
1698 required_samples - decoded_length_per_channel;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001699 // Calculate how many of these were already played out.
Peter Kastingf045e4d2015-06-10 21:15:38 -07001700 old_borrowed_samples_per_channel =
Peter Kastingdce40cf2015-08-24 14:52:23 -07001701 (borrowed_samples_per_channel > sync_buffer_->FutureLength()) ?
1702 (borrowed_samples_per_channel - sync_buffer_->FutureLength()) : 0;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001703 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1704 decoded_buffer,
1705 sizeof(int16_t) * decoded_length);
1706 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1707 decoded_buffer);
1708 decoded_length = required_samples * num_channels;
1709 }
1710
Peter Kastingdce40cf2015-08-24 14:52:23 -07001711 size_t samples_added;
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001712 PreemptiveExpand::ReturnCodes return_code = preemptive_expand_->Process(
Peter Kastingdce40cf2015-08-24 14:52:23 -07001713 decoded_buffer, decoded_length,
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001714 old_borrowed_samples_per_channel,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001715 algorithm_buffer_.get(), &samples_added);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001716 stats_.PreemptiveExpandedSamples(samples_added);
1717 switch (return_code) {
1718 case PreemptiveExpand::kSuccess:
1719 last_mode_ = kModePreemptiveExpandSuccess;
1720 break;
1721 case PreemptiveExpand::kSuccessLowEnergy:
1722 last_mode_ = kModePreemptiveExpandLowEnergy;
1723 break;
1724 case PreemptiveExpand::kNoStretch:
1725 last_mode_ = kModePreemptiveExpandFail;
1726 break;
1727 case PreemptiveExpand::kError:
1728 // TODO(hlundin): Map to kModeError instead?
1729 last_mode_ = kModePreemptiveExpandFail;
1730 return kPreemptiveExpandError;
1731 }
1732
1733 if (borrowed_samples_per_channel > 0) {
1734 // Copy borrowed samples back to the |sync_buffer_|.
1735 sync_buffer_->ReplaceAtIndex(
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001736 *algorithm_buffer_, borrowed_samples_per_channel,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001737 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001738 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001739 }
1740
1741 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1742 if (speech_type == AudioDecoder::kComfortNoise) {
1743 last_mode_ = kModeCodecInternalCng;
1744 }
1745 if (!play_dtmf) {
1746 dtmf_tone_generator_->Reset();
1747 }
1748 expand_->Reset();
1749 return 0;
1750}
1751
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001752int NetEqImpl::DoRfc3389Cng(PacketList* packet_list, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001753 if (!packet_list->empty()) {
1754 // Must have exactly one SID frame at this point.
1755 assert(packet_list->size() == 1);
1756 Packet* packet = packet_list->front();
1757 packet_list->pop_front();
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001758 if (!decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1759#ifdef LEGACY_BITEXACT
1760 // This can happen due to a bug in GetDecision. Change the payload type
1761 // to a CNG type, and move on. Note that this means that we are in fact
1762 // sending a non-CNG payload to the comfort noise decoder for decoding.
1763 // Clearly wrong, but will maintain bit-exactness with legacy.
1764 if (fs_hz_ == 8000) {
1765 packet->header.payloadType =
kwibergee1879c2015-10-29 06:20:28 -07001766 decoder_database_->GetRtpPayloadType(NetEqDecoder::kDecoderCNGnb);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001767 } else if (fs_hz_ == 16000) {
1768 packet->header.payloadType =
kwibergee1879c2015-10-29 06:20:28 -07001769 decoder_database_->GetRtpPayloadType(NetEqDecoder::kDecoderCNGwb);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001770 } else if (fs_hz_ == 32000) {
kwibergee1879c2015-10-29 06:20:28 -07001771 packet->header.payloadType = decoder_database_->GetRtpPayloadType(
1772 NetEqDecoder::kDecoderCNGswb32kHz);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001773 } else if (fs_hz_ == 48000) {
kwibergee1879c2015-10-29 06:20:28 -07001774 packet->header.payloadType = decoder_database_->GetRtpPayloadType(
1775 NetEqDecoder::kDecoderCNGswb48kHz);
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001776 }
1777 assert(decoder_database_->IsComfortNoise(packet->header.payloadType));
1778#else
1779 LOG(LS_ERROR) << "Trying to decode non-CNG payload as CNG.";
1780 return kOtherError;
1781#endif
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001782 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001783 // UpdateParameters() deletes |packet|.
1784 if (comfort_noise_->UpdateParameters(packet) ==
1785 ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001786 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001787 return -comfort_noise_->internal_error_code();
1788 }
1789 }
1790 int cn_return = comfort_noise_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001791 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001792 expand_->Reset();
1793 last_mode_ = kModeRfc3389Cng;
1794 if (!play_dtmf) {
1795 dtmf_tone_generator_->Reset();
1796 }
1797 if (cn_return == ComfortNoise::kInternalError) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001798 decoder_error_code_ = comfort_noise_->internal_error_code();
1799 return kComfortNoiseErrorCode;
1800 } else if (cn_return == ComfortNoise::kUnknownPayloadType) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001801 return kUnknownRtpPayloadType;
1802 }
1803 return 0;
1804}
1805
minyuel6d92bf52015-09-23 15:20:39 +02001806void NetEqImpl::DoCodecInternalCng(const int16_t* decoded_buffer,
1807 size_t decoded_length) {
1808 RTC_DCHECK(normal_.get());
1809 RTC_DCHECK(mute_factor_array_.get());
1810 normal_->Process(decoded_buffer, decoded_length, last_mode_,
1811 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001812 last_mode_ = kModeCodecInternalCng;
1813 expand_->Reset();
1814}
1815
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001816int NetEqImpl::DoDtmf(const DtmfEvent& dtmf_event, bool* play_dtmf) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001817 // This block of the code and the block further down, handling |dtmf_switch|
1818 // are commented out. Otherwise playing out-of-band DTMF would fail in VoE
1819 // test, DtmfTest.ManualSuccessfullySendsOutOfBandTelephoneEvents. This is
1820 // equivalent to |dtmf_switch| always be false.
1821 //
1822 // See http://webrtc-codereview.appspot.com/1195004/ for discussion
1823 // On this issue. This change might cause some glitches at the point of
1824 // switch from audio to DTMF. Issue 1545 is filed to track this.
1825 //
1826 // bool dtmf_switch = false;
1827 // if ((last_mode_ != kModeDtmf) && dtmf_tone_generator_->initialized()) {
1828 // // Special case; see below.
1829 // // We must catch this before calling Generate, since |initialized| is
1830 // // modified in that call.
1831 // dtmf_switch = true;
1832 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001833
1834 int dtmf_return_value = 0;
1835 if (!dtmf_tone_generator_->initialized()) {
1836 // Initialize if not already done.
1837 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1838 dtmf_event.volume);
1839 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001840
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001841 if (dtmf_return_value == 0) {
1842 // Generate DTMF signal.
1843 dtmf_return_value = dtmf_tone_generator_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001844 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001845 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001846
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001847 if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001848 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001849 return dtmf_return_value;
1850 }
1851
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001852 // if (dtmf_switch) {
1853 // // This is the special case where the previous operation was DTMF
1854 // // overdub, but the current instruction is "regular" DTMF. We must make
1855 // // sure that the DTMF does not have any discontinuities. The first DTMF
1856 // // sample that we generate now must be played out immediately, therefore
1857 // // it must be copied to the speech buffer.
1858 // // TODO(hlundin): This code seems incorrect. (Legacy.) Write test and
1859 // // verify correct operation.
1860 // assert(false);
1861 // // Must generate enough data to replace all of the |sync_buffer_|
1862 // // "future".
1863 // int required_length = sync_buffer_->FutureLength();
1864 // assert(dtmf_tone_generator_->initialized());
1865 // dtmf_return_value = dtmf_tone_generator_->Generate(required_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001866 // algorithm_buffer_);
1867 // assert((size_t) required_length == algorithm_buffer_->Size());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001868 // if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001869 // algorithm_buffer_->Zeros(output_size_samples_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001870 // return dtmf_return_value;
1871 // }
1872 //
1873 // // Overwrite the "future" part of the speech buffer with the new DTMF
1874 // // data.
1875 // // TODO(hlundin): It seems that this overwriting has gone lost.
1876 // // Not adapted for multi-channel yet.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001877 // assert(algorithm_buffer_->Channels() == 1);
1878 // if (algorithm_buffer_->Channels() != 1) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001879 // LOG(LS_WARNING) << "DTMF not supported for more than one channel";
1880 // return kStereoNotSupported;
1881 // }
1882 // // Shuffle the remaining data to the beginning of algorithm buffer.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001883 // algorithm_buffer_->PopFront(sync_buffer_->FutureLength());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001884 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001885
Peter Kastingb7e50542015-06-11 12:55:50 -07001886 sync_buffer_->IncreaseEndTimestamp(
1887 static_cast<uint32_t>(output_size_samples_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001888 expand_->Reset();
1889 last_mode_ = kModeDtmf;
1890
1891 // Set to false because the DTMF is already in the algorithm buffer.
1892 *play_dtmf = false;
1893 return 0;
1894}
1895
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001896void NetEqImpl::DoAlternativePlc(bool increase_timestamp) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001897 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
Peter Kastingdce40cf2015-08-24 14:52:23 -07001898 size_t length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001899 if (decoder && decoder->HasDecodePlc()) {
1900 // Use the decoder's packet-loss concealment.
1901 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1902 int16_t decoded_buffer[kMaxFrameSize];
1903 length = decoder->DecodePlc(1, decoded_buffer);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001904 if (length > 0)
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001905 algorithm_buffer_->PushBackInterleaved(decoded_buffer, length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001906 } else {
1907 // Do simple zero-stuffing.
1908 length = output_size_samples_;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001909 algorithm_buffer_->Zeros(length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001910 // By not advancing the timestamp, NetEq inserts samples.
1911 stats_.AddZeros(length);
1912 }
1913 if (increase_timestamp) {
Peter Kastingb7e50542015-06-11 12:55:50 -07001914 sync_buffer_->IncreaseEndTimestamp(static_cast<uint32_t>(length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001915 }
1916 expand_->Reset();
1917}
1918
1919int NetEqImpl::DtmfOverdub(const DtmfEvent& dtmf_event, size_t num_channels,
1920 int16_t* output) const {
1921 size_t out_index = 0;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001922 size_t overdub_length = output_size_samples_; // Default value.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001923
1924 if (sync_buffer_->dtmf_index() > sync_buffer_->next_index()) {
1925 // Special operation for transition from "DTMF only" to "DTMF overdub".
1926 out_index = std::min(
1927 sync_buffer_->dtmf_index() - sync_buffer_->next_index(),
Peter Kastingdce40cf2015-08-24 14:52:23 -07001928 output_size_samples_);
1929 overdub_length = output_size_samples_ - out_index;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001930 }
1931
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001932 AudioMultiVector dtmf_output(num_channels);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001933 int dtmf_return_value = 0;
1934 if (!dtmf_tone_generator_->initialized()) {
1935 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1936 dtmf_event.volume);
1937 }
1938 if (dtmf_return_value == 0) {
1939 dtmf_return_value = dtmf_tone_generator_->Generate(overdub_length,
1940 &dtmf_output);
Peter Kastingdce40cf2015-08-24 14:52:23 -07001941 assert(overdub_length == dtmf_output.Size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001942 }
1943 dtmf_output.ReadInterleaved(overdub_length, &output[out_index]);
1944 return dtmf_return_value < 0 ? dtmf_return_value : 0;
1945}
1946
Peter Kastingdce40cf2015-08-24 14:52:23 -07001947int NetEqImpl::ExtractPackets(size_t required_samples,
1948 PacketList* packet_list) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001949 bool first_packet = true;
1950 uint8_t prev_payload_type = 0;
1951 uint32_t prev_timestamp = 0;
1952 uint16_t prev_sequence_number = 0;
1953 bool next_packet_available = false;
1954
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001955 const RTPHeader* header = packet_buffer_->NextRtpHeader();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001956 assert(header);
1957 if (!header) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001958 LOG(LS_ERROR) << "Packet buffer unexpectedly empty.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001959 return -1;
1960 }
turaj@webrtc.org7df97062013-08-02 18:07:13 +00001961 uint32_t first_timestamp = header->timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001962 int extracted_samples = 0;
1963
1964 // Packet extraction loop.
1965 do {
1966 timestamp_ = header->timestamp;
Peter Kastingdce40cf2015-08-24 14:52:23 -07001967 size_t discard_count = 0;
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001968 Packet* packet = packet_buffer_->GetNextPacket(&discard_count);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001969 // |header| may be invalid after the |packet_buffer_| operation.
1970 header = NULL;
1971 if (!packet) {
Henrik Lundind67a2192015-08-03 12:54:37 +02001972 LOG(LS_ERROR) << "Should always be able to extract a packet here";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001973 assert(false); // Should always be able to extract a packet here.
1974 return -1;
1975 }
1976 stats_.PacketsDiscarded(discard_count);
henrik.lundin84f8cd62016-04-26 07:45:16 -07001977 stats_.StoreWaitingTime(packet->waiting_time->ElapsedMs());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001978 assert(packet->payload_length > 0);
1979 packet_list->push_back(packet); // Store packet in list.
1980
1981 if (first_packet) {
1982 first_packet = false;
henrik.lundin48ed9302015-10-29 05:36:24 -07001983 if (nack_enabled_) {
1984 RTC_DCHECK(nack_);
1985 // TODO(henrik.lundin): Should we update this for all decoded packets?
1986 nack_->UpdateLastDecodedPacket(packet->header.sequenceNumber,
1987 packet->header.timestamp);
1988 }
1989 prev_sequence_number = packet->header.sequenceNumber;
1990 prev_timestamp = packet->header.timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001991 prev_payload_type = packet->header.payloadType;
1992 }
1993
1994 // Store number of extracted samples.
1995 int packet_duration = 0;
1996 AudioDecoder* decoder = decoder_database_->GetDecoder(
1997 packet->header.payloadType);
1998 if (decoder) {
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001999 if (packet->sync_packet) {
Peter Kastingdce40cf2015-08-24 14:52:23 -07002000 packet_duration = rtc::checked_cast<int>(decoder_frame_length_);
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00002001 } else {
minyue@webrtc.org2c1bcf22015-02-17 10:17:09 +00002002 if (packet->primary) {
2003 packet_duration = decoder->PacketDuration(packet->payload,
2004 packet->payload_length);
2005 } else {
2006 packet_duration = decoder->
2007 PacketDurationRedundant(packet->payload, packet->payload_length);
2008 stats_.SecondaryDecodedSamples(packet_duration);
2009 }
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00002010 }
ossu97ba30e2016-04-25 07:55:58 -07002011 } else if (!decoder_database_->IsComfortNoise(packet->header.payloadType)) {
Henrik Lundind67a2192015-08-03 12:54:37 +02002012 LOG(LS_WARNING) << "Unknown payload type "
2013 << static_cast<int>(packet->header.payloadType);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002014 assert(false);
2015 }
2016 if (packet_duration <= 0) {
2017 // Decoder did not return a packet duration. Assume that the packet
2018 // contains the same number of samples as the previous one.
Peter Kastingdce40cf2015-08-24 14:52:23 -07002019 packet_duration = rtc::checked_cast<int>(decoder_frame_length_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002020 }
2021 extracted_samples = packet->header.timestamp - first_timestamp +
2022 packet_duration;
2023
2024 // Check what packet is available next.
2025 header = packet_buffer_->NextRtpHeader();
2026 next_packet_available = false;
2027 if (header && prev_payload_type == header->payloadType) {
2028 int16_t seq_no_diff = header->sequenceNumber - prev_sequence_number;
Peter Kastingdce40cf2015-08-24 14:52:23 -07002029 size_t ts_diff = header->timestamp - prev_timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002030 if (seq_no_diff == 1 ||
2031 (seq_no_diff == 0 && ts_diff == decoder_frame_length_)) {
2032 // The next sequence number is available, or the next part of a packet
2033 // that was split into pieces upon insertion.
2034 next_packet_available = true;
2035 }
2036 prev_sequence_number = header->sequenceNumber;
2037 }
Peter Kastingdce40cf2015-08-24 14:52:23 -07002038 } while (extracted_samples < rtc::checked_cast<int>(required_samples) &&
2039 next_packet_available);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002040
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00002041 if (extracted_samples > 0) {
2042 // Delete old packets only when we are going to decode something. Otherwise,
2043 // we could end up in the situation where we never decode anything, since
2044 // all incoming packets are considered too old but the buffer will also
2045 // never be flooded and flushed.
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00002046 packet_buffer_->DiscardAllOldPackets(timestamp_);
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00002047 }
2048
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002049 return extracted_samples;
2050}
2051
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002052void NetEqImpl::UpdatePlcComponents(int fs_hz, size_t channels) {
2053 // Delete objects and create new ones.
2054 expand_.reset(expand_factory_->Create(background_noise_.get(),
2055 sync_buffer_.get(), &random_vector_,
Henrik Lundinbef77e22015-08-18 14:58:09 +02002056 &stats_, fs_hz, channels));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002057 merge_.reset(new Merge(fs_hz, channels, expand_.get(), sync_buffer_.get()));
2058}
2059
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002060void NetEqImpl::SetSampleRateAndChannels(int fs_hz, size_t channels) {
Henrik Lundind67a2192015-08-03 12:54:37 +02002061 LOG(LS_VERBOSE) << "SetSampleRateAndChannels " << fs_hz << " " << channels;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002062 // TODO(hlundin): Change to an enumerator and skip assert.
2063 assert(fs_hz == 8000 || fs_hz == 16000 || fs_hz == 32000 || fs_hz == 48000);
2064 assert(channels > 0);
2065
2066 fs_hz_ = fs_hz;
2067 fs_mult_ = fs_hz / 8000;
Peter Kastingdce40cf2015-08-24 14:52:23 -07002068 output_size_samples_ = static_cast<size_t>(kOutputSizeMs * 8 * fs_mult_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002069 decoder_frame_length_ = 3 * output_size_samples_; // Initialize to 30ms.
2070
2071 last_mode_ = kModeNormal;
2072
2073 // Create a new array of mute factors and set all to 1.
2074 mute_factor_array_.reset(new int16_t[channels]);
2075 for (size_t i = 0; i < channels; ++i) {
2076 mute_factor_array_[i] = 16384; // 1.0 in Q14.
2077 }
2078
ossu97ba30e2016-04-25 07:55:58 -07002079 ComfortNoiseDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
Karl Wiberg43766482015-08-27 15:22:11 +02002080 if (cng_decoder)
2081 cng_decoder->Reset();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002082
2083 // Reinit post-decode VAD with new sample rate.
2084 assert(vad_.get()); // Cannot be NULL here.
2085 vad_->Init();
2086
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002087 // Delete algorithm buffer and create a new one.
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00002088 algorithm_buffer_.reset(new AudioMultiVector(channels));
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00002089
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002090 // Delete sync buffer and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002091 sync_buffer_.reset(new SyncBuffer(channels, kSyncBufferSize * fs_mult_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002092
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00002093 // Delete BackgroundNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002094 background_noise_.reset(new BackgroundNoise(channels));
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00002095 background_noise_->set_mode(background_noise_mode_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002096
2097 // Reset random vector.
2098 random_vector_.Reset();
2099
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002100 UpdatePlcComponents(fs_hz, channels);
2101
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002102 // Move index so that we create a small set of future samples (all 0).
2103 sync_buffer_->set_next_index(sync_buffer_->next_index() -
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002104 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002105
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002106 normal_.reset(new Normal(fs_hz, decoder_database_.get(), *background_noise_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002107 expand_.get()));
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +00002108 accelerate_.reset(
2109 accelerate_factory_->Create(fs_hz, channels, *background_noise_));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002110 preemptive_expand_.reset(preemptive_expand_factory_->Create(
Peter Kastingdce40cf2015-08-24 14:52:23 -07002111 fs_hz, channels, *background_noise_, expand_->overlap_length()));
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00002112
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002113 // Delete ComfortNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002114 comfort_noise_.reset(new ComfortNoise(fs_hz, decoder_database_.get(),
2115 sync_buffer_.get()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002116
2117 // Verify that |decoded_buffer_| is long enough.
2118 if (decoded_buffer_length_ < kMaxFrameSize * channels) {
2119 // Reallocate to larger size.
2120 decoded_buffer_length_ = kMaxFrameSize * channels;
2121 decoded_buffer_.reset(new int16_t[decoded_buffer_length_]);
2122 }
2123
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002124 // Create DecisionLogic if it is not created yet, then communicate new sample
2125 // rate and output size to DecisionLogic object.
2126 if (!decision_logic_.get()) {
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002127 CreateDecisionLogic();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002128 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002129 decision_logic_->SetSampleRate(fs_hz_, output_size_samples_);
2130}
2131
henrik.lundin55480f52016-03-08 02:37:57 -08002132NetEqImpl::OutputType NetEqImpl::LastOutputType() {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002133 assert(vad_.get());
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00002134 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002135 if (last_mode_ == kModeCodecInternalCng || last_mode_ == kModeRfc3389Cng) {
henrik.lundin55480f52016-03-08 02:37:57 -08002136 return OutputType::kCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002137 } else if (last_mode_ == kModeExpand && expand_->MuteFactor(0) == 0) {
2138 // Expand mode has faded down to background noise only (very long expand).
henrik.lundin55480f52016-03-08 02:37:57 -08002139 return OutputType::kPLCCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002140 } else if (last_mode_ == kModeExpand) {
henrik.lundin55480f52016-03-08 02:37:57 -08002141 return OutputType::kPLC;
wu@webrtc.org24301a62013-12-13 19:17:43 +00002142 } else if (vad_->running() && !vad_->active_speech()) {
henrik.lundin55480f52016-03-08 02:37:57 -08002143 return OutputType::kVadPassive;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002144 } else {
henrik.lundin55480f52016-03-08 02:37:57 -08002145 return OutputType::kNormalSpeech;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002146 }
2147}
2148
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00002149void NetEqImpl::CreateDecisionLogic() {
Henrik Lundin47b17dc2016-05-10 10:20:59 +02002150 decision_logic_.reset(DecisionLogic::Create(
2151 fs_hz_, output_size_samples_, playout_mode_, decoder_database_.get(),
2152 *packet_buffer_.get(), delay_manager_.get(), buffer_level_filter_.get(),
2153 tick_timer_.get()));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00002154}
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00002155} // namespace webrtc