blob: 1351e666347a97b505923d139c2268e789b30eed [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>
17
18#include "webrtc/common_audio/signal_processing/include/signal_processing_library.h"
kwiberg@webrtc.orge04a93b2014-12-09 10:12:53 +000019#include "webrtc/modules/audio_coding/codecs/audio_decoder.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000020#include "webrtc/modules/audio_coding/neteq/accelerate.h"
21#include "webrtc/modules/audio_coding/neteq/background_noise.h"
22#include "webrtc/modules/audio_coding/neteq/buffer_level_filter.h"
23#include "webrtc/modules/audio_coding/neteq/comfort_noise.h"
24#include "webrtc/modules/audio_coding/neteq/decision_logic.h"
25#include "webrtc/modules/audio_coding/neteq/decoder_database.h"
26#include "webrtc/modules/audio_coding/neteq/defines.h"
27#include "webrtc/modules/audio_coding/neteq/delay_manager.h"
28#include "webrtc/modules/audio_coding/neteq/delay_peak_detector.h"
29#include "webrtc/modules/audio_coding/neteq/dtmf_buffer.h"
30#include "webrtc/modules/audio_coding/neteq/dtmf_tone_generator.h"
31#include "webrtc/modules/audio_coding/neteq/expand.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000032#include "webrtc/modules/audio_coding/neteq/merge.h"
33#include "webrtc/modules/audio_coding/neteq/normal.h"
34#include "webrtc/modules/audio_coding/neteq/packet_buffer.h"
35#include "webrtc/modules/audio_coding/neteq/packet.h"
36#include "webrtc/modules/audio_coding/neteq/payload_splitter.h"
37#include "webrtc/modules/audio_coding/neteq/post_decode_vad.h"
38#include "webrtc/modules/audio_coding/neteq/preemptive_expand.h"
39#include "webrtc/modules/audio_coding/neteq/sync_buffer.h"
40#include "webrtc/modules/audio_coding/neteq/timestamp_scaler.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000041#include "webrtc/modules/interface/module_common_types.h"
42#include "webrtc/system_wrappers/interface/critical_section_wrapper.h"
43#include "webrtc/system_wrappers/interface/logging.h"
44
45// Modify the code to obtain backwards bit-exactness. Once bit-exactness is no
46// longer required, this #define should be removed (and the code that it
47// enables).
48#define LEGACY_BITEXACT
49
50namespace webrtc {
51
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +000052NetEqImpl::NetEqImpl(const NetEq::Config& config,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000053 BufferLevelFilter* buffer_level_filter,
54 DecoderDatabase* decoder_database,
55 DelayManager* delay_manager,
56 DelayPeakDetector* delay_peak_detector,
57 DtmfBuffer* dtmf_buffer,
58 DtmfToneGenerator* dtmf_tone_generator,
59 PacketBuffer* packet_buffer,
60 PayloadSplitter* payload_splitter,
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +000061 TimestampScaler* timestamp_scaler,
62 AccelerateFactory* accelerate_factory,
63 ExpandFactory* expand_factory,
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +000064 PreemptiveExpandFactory* preemptive_expand_factory,
65 bool create_components)
henrik.lundin@webrtc.org2f816bb2014-06-05 10:37:13 +000066 : crit_sect_(CriticalSectionWrapper::CreateCriticalSection()),
67 buffer_level_filter_(buffer_level_filter),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000068 decoder_database_(decoder_database),
69 delay_manager_(delay_manager),
70 delay_peak_detector_(delay_peak_detector),
71 dtmf_buffer_(dtmf_buffer),
72 dtmf_tone_generator_(dtmf_tone_generator),
73 packet_buffer_(packet_buffer),
74 payload_splitter_(payload_splitter),
75 timestamp_scaler_(timestamp_scaler),
76 vad_(new PostDecodeVad()),
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +000077 expand_factory_(expand_factory),
78 accelerate_factory_(accelerate_factory),
79 preemptive_expand_factory_(preemptive_expand_factory),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000080 last_mode_(kModeNormal),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000081 decoded_buffer_length_(kMaxFrameSize),
82 decoded_buffer_(new int16_t[decoded_buffer_length_]),
83 playout_timestamp_(0),
84 new_codec_(false),
85 timestamp_(0),
86 reset_decoder_(false),
87 current_rtp_payload_type_(0xFF), // Invalid RTP payload type.
88 current_cng_rtp_payload_type_(0xFF), // Invalid RTP payload type.
89 ssrc_(0),
90 first_packet_(true),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000091 error_code_(0),
92 decoder_error_code_(0),
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +000093 background_noise_mode_(config.background_noise_mode),
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +000094 playout_mode_(config.playout_mode),
Henrik Lundincf808d22015-05-27 14:33:29 +020095 enable_fast_accelerate_(config.enable_fast_accelerate),
minyue@webrtc.orgd7301772013-08-29 00:58:14 +000096 decoded_packet_sequence_number_(-1),
97 decoded_packet_timestamp_(0) {
Henrik Lundin905495c2015-05-25 16:58:41 +020098 LOG(LS_INFO) << "NetEq config: " << config.ToString();
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +000099 int fs = config.sample_rate_hz;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000100 if (fs != 8000 && fs != 16000 && fs != 32000 && fs != 48000) {
101 LOG(LS_ERROR) << "Sample rate " << fs << " Hz not supported. " <<
102 "Changing to 8000 Hz.";
103 fs = 8000;
104 }
andrew@webrtc.org0569d932014-04-09 17:48:48 +0000105 LOG(LS_VERBOSE) << "Create NetEqImpl object with fs = " << fs << ".";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000106 fs_hz_ = fs;
107 fs_mult_ = fs / 8000;
108 output_size_samples_ = kOutputSizeMs * 8 * fs_mult_;
109 decoder_frame_length_ = 3 * output_size_samples_;
110 WebRtcSpl_Init();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000111 if (create_components) {
112 SetSampleRateAndChannels(fs, 1); // Default is 1 channel.
113 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000114}
115
116NetEqImpl::~NetEqImpl() {
117 LOG(LS_INFO) << "Deleting NetEqImpl object.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000118}
119
120int NetEqImpl::InsertPacket(const WebRtcRTPHeader& rtp_header,
121 const uint8_t* payload,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000122 size_t length_bytes,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000123 uint32_t receive_timestamp) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000124 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000125 LOG(LS_VERBOSE) << "InsertPacket: ts=" << rtp_header.header.timestamp <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000126 ", sn=" << rtp_header.header.sequenceNumber <<
127 ", pt=" << static_cast<int>(rtp_header.header.payloadType) <<
128 ", ssrc=" << rtp_header.header.ssrc <<
129 ", len=" << length_bytes;
130 int error = InsertPacketInternal(rtp_header, payload, length_bytes,
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000131 receive_timestamp, false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000132 if (error != 0) {
133 LOG_FERR1(LS_WARNING, InsertPacketInternal, error);
134 error_code_ = error;
135 return kFail;
136 }
137 return kOK;
138}
139
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000140int NetEqImpl::InsertSyncPacket(const WebRtcRTPHeader& rtp_header,
141 uint32_t receive_timestamp) {
142 CriticalSectionScoped lock(crit_sect_.get());
143 LOG(LS_VERBOSE) << "InsertPacket-Sync: ts="
144 << rtp_header.header.timestamp <<
145 ", sn=" << rtp_header.header.sequenceNumber <<
146 ", pt=" << static_cast<int>(rtp_header.header.payloadType) <<
147 ", ssrc=" << rtp_header.header.ssrc;
148
149 const uint8_t kSyncPayload[] = { 's', 'y', 'n', 'c' };
150 int error = InsertPacketInternal(
151 rtp_header, kSyncPayload, sizeof(kSyncPayload), receive_timestamp, true);
152
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000153 if (error != 0) {
154 LOG_FERR1(LS_WARNING, InsertPacketInternal, error);
155 error_code_ = error;
156 return kFail;
157 }
158 return kOK;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000159}
160
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000161int NetEqImpl::GetAudio(size_t max_length, int16_t* output_audio,
162 int* samples_per_channel, int* num_channels,
163 NetEqOutputType* type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000164 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000165 LOG(LS_VERBOSE) << "GetAudio";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000166 int error = GetAudioInternal(max_length, output_audio, samples_per_channel,
167 num_channels);
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000168 LOG(LS_VERBOSE) << "Produced " << *samples_per_channel <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000169 " samples/channel for " << *num_channels << " channel(s)";
170 if (error != 0) {
171 LOG_FERR1(LS_WARNING, GetAudioInternal, error);
172 error_code_ = error;
173 return kFail;
174 }
175 if (type) {
176 *type = LastOutputType();
177 }
178 return kOK;
179}
180
181int NetEqImpl::RegisterPayloadType(enum NetEqDecoder codec,
182 uint8_t rtp_payload_type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000183 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000184 LOG_API2(static_cast<int>(rtp_payload_type), codec);
185 int ret = decoder_database_->RegisterPayload(rtp_payload_type, codec);
186 if (ret != DecoderDatabase::kOK) {
pkasting@chromium.org026b8922015-01-30 19:53:42 +0000187 LOG_FERR2(LS_WARNING, RegisterPayload, static_cast<int>(rtp_payload_type),
188 codec);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000189 switch (ret) {
190 case DecoderDatabase::kInvalidRtpPayloadType:
191 error_code_ = kInvalidRtpPayloadType;
192 break;
193 case DecoderDatabase::kCodecNotSupported:
194 error_code_ = kCodecNotSupported;
195 break;
196 case DecoderDatabase::kDecoderExists:
197 error_code_ = kDecoderExists;
198 break;
199 default:
200 error_code_ = kOtherError;
201 }
202 return kFail;
203 }
204 return kOK;
205}
206
207int NetEqImpl::RegisterExternalDecoder(AudioDecoder* decoder,
208 enum NetEqDecoder codec,
Karl Wibergd8399e62015-05-25 14:39:56 +0200209 uint8_t rtp_payload_type,
210 int sample_rate_hz) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000211 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000212 LOG_API2(static_cast<int>(rtp_payload_type), codec);
213 if (!decoder) {
214 LOG(LS_ERROR) << "Cannot register external decoder with NULL pointer";
215 assert(false);
216 return kFail;
217 }
218 int ret = decoder_database_->InsertExternal(rtp_payload_type, codec,
219 sample_rate_hz, decoder);
220 if (ret != DecoderDatabase::kOK) {
pkasting@chromium.org026b8922015-01-30 19:53:42 +0000221 LOG_FERR2(LS_WARNING, InsertExternal, static_cast<int>(rtp_payload_type),
222 codec);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000223 switch (ret) {
224 case DecoderDatabase::kInvalidRtpPayloadType:
225 error_code_ = kInvalidRtpPayloadType;
226 break;
227 case DecoderDatabase::kCodecNotSupported:
228 error_code_ = kCodecNotSupported;
229 break;
230 case DecoderDatabase::kDecoderExists:
231 error_code_ = kDecoderExists;
232 break;
233 case DecoderDatabase::kInvalidSampleRate:
234 error_code_ = kInvalidSampleRate;
235 break;
236 case DecoderDatabase::kInvalidPointer:
237 error_code_ = kInvalidPointer;
238 break;
239 default:
240 error_code_ = kOtherError;
241 }
242 return kFail;
243 }
244 return kOK;
245}
246
247int NetEqImpl::RemovePayloadType(uint8_t rtp_payload_type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000248 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000249 LOG_API1(static_cast<int>(rtp_payload_type));
250 int ret = decoder_database_->Remove(rtp_payload_type);
251 if (ret == DecoderDatabase::kOK) {
252 return kOK;
253 } else if (ret == DecoderDatabase::kDecoderNotFound) {
254 error_code_ = kDecoderNotFound;
255 } else {
256 error_code_ = kOtherError;
257 }
pkasting@chromium.org026b8922015-01-30 19:53:42 +0000258 LOG_FERR1(LS_WARNING, Remove, static_cast<int>(rtp_payload_type));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000259 return kFail;
260}
261
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000262bool NetEqImpl::SetMinimumDelay(int delay_ms) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000263 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000264 if (delay_ms >= 0 && delay_ms < 10000) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000265 assert(delay_manager_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000266 return delay_manager_->SetMinimumDelay(delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000267 }
268 return false;
269}
270
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000271bool NetEqImpl::SetMaximumDelay(int delay_ms) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000272 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000273 if (delay_ms >= 0 && delay_ms < 10000) {
274 assert(delay_manager_.get());
275 return delay_manager_->SetMaximumDelay(delay_ms);
276 }
277 return false;
278}
279
280int NetEqImpl::LeastRequiredDelayMs() const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000281 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000282 assert(delay_manager_.get());
283 return delay_manager_->least_required_delay_ms();
284}
285
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200286int NetEqImpl::SetTargetDelay() {
287 return kNotImplemented;
288}
289
290int NetEqImpl::TargetDelay() {
291 return kNotImplemented;
292}
293
294int NetEqImpl::CurrentDelay() {
295 return kNotImplemented;
296}
297
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000298// Deprecated.
299// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000300void NetEqImpl::SetPlayoutMode(NetEqPlayoutMode mode) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000301 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000302 if (mode != playout_mode_) {
303 playout_mode_ = mode;
304 CreateDecisionLogic();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000305 }
306}
307
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000308// Deprecated.
309// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000310NetEqPlayoutMode NetEqImpl::PlayoutMode() const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000311 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000312 return playout_mode_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000313}
314
315int NetEqImpl::NetworkStatistics(NetEqNetworkStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000316 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000317 assert(decoder_database_.get());
318 const int total_samples_in_buffers = packet_buffer_->NumSamplesInBuffer(
319 decoder_database_.get(), decoder_frame_length_) +
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000320 static_cast<int>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000321 assert(delay_manager_.get());
322 assert(decision_logic_.get());
323 stats_.GetNetworkStatistics(fs_hz_, total_samples_in_buffers,
324 decoder_frame_length_, *delay_manager_.get(),
325 *decision_logic_.get(), stats);
326 return 0;
327}
328
329void NetEqImpl::WaitingTimes(std::vector<int>* waiting_times) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000330 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000331 stats_.WaitingTimes(waiting_times);
332}
333
334void NetEqImpl::GetRtcpStatistics(RtcpStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000335 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000336 if (stats) {
337 rtcp_.GetStatistics(false, stats);
338 }
339}
340
341void NetEqImpl::GetRtcpStatisticsNoReset(RtcpStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000342 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000343 if (stats) {
344 rtcp_.GetStatistics(true, stats);
345 }
346}
347
348void NetEqImpl::EnableVad() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000349 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000350 assert(vad_.get());
351 vad_->Enable();
352}
353
354void NetEqImpl::DisableVad() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000355 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000356 assert(vad_.get());
357 vad_->Disable();
358}
359
wu@webrtc.org94454b72014-06-05 20:34:08 +0000360bool NetEqImpl::GetPlayoutTimestamp(uint32_t* timestamp) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000361 CriticalSectionScoped lock(crit_sect_.get());
wu@webrtc.org94454b72014-06-05 20:34:08 +0000362 if (first_packet_) {
363 // We don't have a valid RTP timestamp until we have decoded our first
364 // RTP packet.
365 return false;
366 }
367 *timestamp = timestamp_scaler_->ToExternal(playout_timestamp_);
368 return true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000369}
370
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200371int NetEqImpl::SetTargetNumberOfChannels() {
372 return kNotImplemented;
373}
374
375int NetEqImpl::SetTargetSampleRate() {
376 return kNotImplemented;
377}
378
henrik.lundin@webrtc.orgb0f4b3d2014-11-04 08:53:10 +0000379int NetEqImpl::LastError() const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000380 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000381 return error_code_;
382}
383
384int NetEqImpl::LastDecoderError() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000385 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000386 return decoder_error_code_;
387}
388
389void NetEqImpl::FlushBuffers() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000390 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000391 LOG_API0();
392 packet_buffer_->Flush();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000393 assert(sync_buffer_.get());
394 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000395 sync_buffer_->Flush();
396 sync_buffer_->set_next_index(sync_buffer_->next_index() -
397 expand_->overlap_length());
398 // Set to wait for new codec.
399 first_packet_ = true;
400}
401
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000402void NetEqImpl::PacketBufferStatistics(int* current_num_packets,
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000403 int* max_num_packets) const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000404 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000405 packet_buffer_->BufferStat(current_num_packets, max_num_packets);
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000406}
407
turaj@webrtc.orgff43c852013-09-25 00:07:27 +0000408int NetEqImpl::DecodedRtpInfo(int* sequence_number, uint32_t* timestamp) const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000409 CriticalSectionScoped lock(crit_sect_.get());
minyue@webrtc.orgd7301772013-08-29 00:58:14 +0000410 if (decoded_packet_sequence_number_ < 0)
411 return -1;
412 *sequence_number = decoded_packet_sequence_number_;
413 *timestamp = decoded_packet_timestamp_;
414 return 0;
415}
416
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000417const SyncBuffer* NetEqImpl::sync_buffer_for_test() const {
418 CriticalSectionScoped lock(crit_sect_.get());
419 return sync_buffer_.get();
420}
421
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000422// Methods below this line are private.
423
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000424int NetEqImpl::InsertPacketInternal(const WebRtcRTPHeader& rtp_header,
425 const uint8_t* payload,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000426 size_t length_bytes,
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000427 uint32_t receive_timestamp,
428 bool is_sync_packet) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000429 if (!payload) {
430 LOG_F(LS_ERROR) << "payload == NULL";
431 return kInvalidPointer;
432 }
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000433 // Sanity checks for sync-packets.
434 if (is_sync_packet) {
435 if (decoder_database_->IsDtmf(rtp_header.header.payloadType) ||
436 decoder_database_->IsRed(rtp_header.header.payloadType) ||
437 decoder_database_->IsComfortNoise(rtp_header.header.payloadType)) {
438 LOG_F(LS_ERROR) << "Sync-packet with an unacceptable payload type "
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000439 << static_cast<int>(rtp_header.header.payloadType);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000440 return kSyncPacketNotAccepted;
441 }
442 if (first_packet_ ||
443 rtp_header.header.payloadType != current_rtp_payload_type_ ||
444 rtp_header.header.ssrc != ssrc_) {
445 // Even if |current_rtp_payload_type_| is 0xFF, sync-packet isn't
446 // accepted.
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000447 LOG_F(LS_ERROR)
448 << "Changing codec, SSRC or first packet with sync-packet.";
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000449 return kSyncPacketNotAccepted;
450 }
451 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000452 PacketList packet_list;
453 RTPHeader main_header;
454 {
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000455 // Convert to Packet.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000456 // Create |packet| within this separate scope, since it should not be used
457 // directly once it's been inserted in the packet list. This way, |packet|
458 // is not defined outside of this block.
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000459 Packet* packet = new Packet;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000460 packet->header.markerBit = false;
461 packet->header.payloadType = rtp_header.header.payloadType;
462 packet->header.sequenceNumber = rtp_header.header.sequenceNumber;
463 packet->header.timestamp = rtp_header.header.timestamp;
464 packet->header.ssrc = rtp_header.header.ssrc;
465 packet->header.numCSRCs = 0;
466 packet->payload_length = length_bytes;
467 packet->primary = true;
468 packet->waiting_time = 0;
469 packet->payload = new uint8_t[packet->payload_length];
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000470 packet->sync_packet = is_sync_packet;
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +0000471 if (!packet->payload) {
472 LOG_F(LS_ERROR) << "Payload pointer is NULL.";
473 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000474 assert(payload); // Already checked above.
475 memcpy(packet->payload, payload, packet->payload_length);
476 // Insert packet in a packet list.
477 packet_list.push_back(packet);
478 // Save main payloads header for later.
479 memcpy(&main_header, &packet->header, sizeof(main_header));
480 }
481
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000482 bool update_sample_rate_and_channels = false;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000483 // Reinitialize NetEq if it's needed (changed SSRC or first call).
484 if ((main_header.ssrc != ssrc_) || first_packet_) {
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000485 // Note: |first_packet_| will be cleared further down in this method, once
486 // the packet has been successfully inserted into the packet buffer.
487
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000488 rtcp_.Init(main_header.sequenceNumber);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000489
490 // Flush the packet buffer and DTMF buffer.
491 packet_buffer_->Flush();
492 dtmf_buffer_->Flush();
493
494 // Store new SSRC.
495 ssrc_ = main_header.ssrc;
496
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000497 // Update audio buffer timestamp.
498 sync_buffer_->IncreaseEndTimestamp(main_header.timestamp - timestamp_);
499
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000500 // Update codecs.
501 timestamp_ = main_header.timestamp;
502 current_rtp_payload_type_ = main_header.payloadType;
503
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000504 // Reset timestamp scaling.
505 timestamp_scaler_->Reset();
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000506
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000507 // Trigger an update of sampling rate and the number of channels.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000508 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000509 }
510
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000511 // Update RTCP statistics, only for regular packets.
512 if (!is_sync_packet)
513 rtcp_.Update(main_header, receive_timestamp);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000514
515 // Check for RED payload type, and separate payloads into several packets.
516 if (decoder_database_->IsRed(main_header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000517 assert(!is_sync_packet); // We had a sanity check for this.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000518 if (payload_splitter_->SplitRed(&packet_list) != PayloadSplitter::kOK) {
519 LOG_FERR1(LS_WARNING, SplitRed, packet_list.size());
520 PacketBuffer::DeleteAllPackets(&packet_list);
521 return kRedundancySplitError;
522 }
523 // Only accept a few RED payloads of the same type as the main data,
524 // DTMF events and CNG.
525 payload_splitter_->CheckRedPayloads(&packet_list, *decoder_database_);
526 // Update the stored main payload header since the main payload has now
527 // changed.
528 memcpy(&main_header, &packet_list.front()->header, sizeof(main_header));
529 }
530
531 // Check payload types.
532 if (decoder_database_->CheckPayloadTypes(packet_list) ==
533 DecoderDatabase::kDecoderNotFound) {
534 LOG_FERR1(LS_WARNING, CheckPayloadTypes, packet_list.size());
535 PacketBuffer::DeleteAllPackets(&packet_list);
536 return kUnknownRtpPayloadType;
537 }
538
539 // Scale timestamp to internal domain (only for some codecs).
540 timestamp_scaler_->ToInternal(&packet_list);
541
542 // Process DTMF payloads. Cycle through the list of packets, and pick out any
543 // DTMF payloads found.
544 PacketList::iterator it = packet_list.begin();
545 while (it != packet_list.end()) {
546 Packet* current_packet = (*it);
547 assert(current_packet);
548 assert(current_packet->payload);
549 if (decoder_database_->IsDtmf(current_packet->header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000550 assert(!current_packet->sync_packet); // We had a sanity check for this.
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000551 DtmfEvent event;
552 int ret = DtmfBuffer::ParseEvent(
553 current_packet->header.timestamp,
554 current_packet->payload,
555 current_packet->payload_length,
556 &event);
557 if (ret != DtmfBuffer::kOK) {
558 LOG_FERR2(LS_WARNING, ParseEvent, ret,
559 current_packet->payload_length);
560 PacketBuffer::DeleteAllPackets(&packet_list);
561 return kDtmfParsingError;
562 }
563 if (dtmf_buffer_->InsertEvent(event) != DtmfBuffer::kOK) {
564 LOG_FERR0(LS_WARNING, InsertEvent);
565 PacketBuffer::DeleteAllPackets(&packet_list);
566 return kDtmfInsertError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000567 }
568 // TODO(hlundin): Let the destructor of Packet handle the payload.
569 delete [] current_packet->payload;
570 delete current_packet;
571 it = packet_list.erase(it);
572 } else {
573 ++it;
574 }
575 }
576
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000577 // Check for FEC in packets, and separate payloads into several packets.
578 int ret = payload_splitter_->SplitFec(&packet_list, decoder_database_.get());
579 if (ret != PayloadSplitter::kOK) {
580 LOG_FERR1(LS_WARNING, SplitFec, packet_list.size());
581 PacketBuffer::DeleteAllPackets(&packet_list);
582 switch (ret) {
583 case PayloadSplitter::kUnknownPayloadType:
584 return kUnknownRtpPayloadType;
585 default:
586 return kOtherError;
587 }
588 }
589
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000590 // Split payloads into smaller chunks. This also verifies that all payloads
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000591 // are of a known payload type. SplitAudio() method is protected against
592 // sync-packets.
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +0000593 ret = payload_splitter_->SplitAudio(&packet_list, *decoder_database_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000594 if (ret != PayloadSplitter::kOK) {
595 LOG_FERR1(LS_WARNING, SplitAudio, packet_list.size());
596 PacketBuffer::DeleteAllPackets(&packet_list);
597 switch (ret) {
598 case PayloadSplitter::kUnknownPayloadType:
599 return kUnknownRtpPayloadType;
600 case PayloadSplitter::kFrameSplitError:
601 return kFrameSplitError;
602 default:
603 return kOtherError;
604 }
605 }
606
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000607 // Update bandwidth estimate, if the packet is not sync-packet.
608 if (!packet_list.empty() && !packet_list.front()->sync_packet) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000609 // The list can be empty here if we got nothing but DTMF payloads.
610 AudioDecoder* decoder =
611 decoder_database_->GetDecoder(main_header.payloadType);
612 assert(decoder); // Should always get a valid object, since we have
613 // already checked that the payload types are known.
614 decoder->IncomingPacket(packet_list.front()->payload,
615 packet_list.front()->payload_length,
616 packet_list.front()->header.sequenceNumber,
617 packet_list.front()->header.timestamp,
618 receive_timestamp);
619 }
620
621 // Insert packets in buffer.
622 int temp_bufsize = packet_buffer_->NumPacketsInBuffer();
623 ret = packet_buffer_->InsertPacketList(
624 &packet_list,
625 *decoder_database_,
626 &current_rtp_payload_type_,
627 &current_cng_rtp_payload_type_);
628 if (ret == PacketBuffer::kFlushed) {
629 // Reset DSP timestamp etc. if packet buffer flushed.
630 new_codec_ = true;
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000631 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000632 LOG_F(LS_WARNING) << "Packet buffer flushed";
633 } else if (ret != PacketBuffer::kOK) {
634 LOG_FERR1(LS_WARNING, InsertPacketList, packet_list.size());
635 PacketBuffer::DeleteAllPackets(&packet_list);
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000636 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000637 }
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000638
639 if (first_packet_) {
640 first_packet_ = false;
641 // Update the codec on the next GetAudio call.
642 new_codec_ = true;
643 }
644
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000645 if (current_rtp_payload_type_ != 0xFF) {
646 const DecoderDatabase::DecoderInfo* dec_info =
647 decoder_database_->GetDecoderInfo(current_rtp_payload_type_);
648 if (!dec_info) {
649 assert(false); // Already checked that the payload type is known.
650 }
651 }
652
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000653 if (update_sample_rate_and_channels && !packet_buffer_->Empty()) {
654 // We do not use |current_rtp_payload_type_| to |set payload_type|, but
655 // get the next RTP header from |packet_buffer_| to obtain the payload type.
656 // The reason for it is the following corner case. If NetEq receives a
657 // CNG packet with a sample rate different than the current CNG then it
658 // flushes its buffer, assuming send codec must have been changed. However,
659 // payload type of the hypothetically new send codec is not known.
660 const RTPHeader* rtp_header = packet_buffer_->NextRtpHeader();
661 assert(rtp_header);
662 int payload_type = rtp_header->payloadType;
663 AudioDecoder* decoder = decoder_database_->GetDecoder(payload_type);
664 assert(decoder); // Payloads are already checked to be valid.
665 const DecoderDatabase::DecoderInfo* decoder_info =
666 decoder_database_->GetDecoderInfo(payload_type);
667 assert(decoder_info);
668 if (decoder_info->fs_hz != fs_hz_ ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +0000669 decoder->Channels() != algorithm_buffer_->Channels())
670 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->Channels());
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000671 }
672
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000673 // TODO(hlundin): Move this code to DelayManager class.
674 const DecoderDatabase::DecoderInfo* dec_info =
675 decoder_database_->GetDecoderInfo(main_header.payloadType);
676 assert(dec_info); // Already checked that the payload type is known.
677 delay_manager_->LastDecoderType(dec_info->codec_type);
678 if (delay_manager_->last_pack_cng_or_dtmf() == 0) {
679 // Calculate the total speech length carried in each packet.
680 temp_bufsize = packet_buffer_->NumPacketsInBuffer() - temp_bufsize;
681 temp_bufsize *= decoder_frame_length_;
682
683 if ((temp_bufsize > 0) &&
684 (temp_bufsize != decision_logic_->packet_length_samples())) {
685 decision_logic_->set_packet_length_samples(temp_bufsize);
686 delay_manager_->SetPacketAudioLength((1000 * temp_bufsize) / fs_hz_);
687 }
688
689 // Update statistics.
pbos@webrtc.org0946a562013-04-09 00:28:06 +0000690 if ((int32_t) (main_header.timestamp - timestamp_) >= 0 &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000691 !new_codec_) {
692 // Only update statistics if incoming packet is not older than last played
693 // out packet, and if new codec flag is not set.
694 delay_manager_->Update(main_header.sequenceNumber, main_header.timestamp,
695 fs_hz_);
696 }
697 } else if (delay_manager_->last_pack_cng_or_dtmf() == -1) {
698 // This is first "normal" packet after CNG or DTMF.
699 // Reset packet time counter and measure time until next packet,
700 // but don't update statistics.
701 delay_manager_->set_last_pack_cng_or_dtmf(0);
702 delay_manager_->ResetPacketIatCount();
703 }
704 return 0;
705}
706
707int NetEqImpl::GetAudioInternal(size_t max_length, int16_t* output,
708 int* samples_per_channel, int* num_channels) {
709 PacketList packet_list;
710 DtmfEvent dtmf_event;
711 Operations operation;
712 bool play_dtmf;
713 int return_value = GetDecision(&operation, &packet_list, &dtmf_event,
714 &play_dtmf);
715 if (return_value != 0) {
716 LOG_FERR1(LS_WARNING, GetDecision, return_value);
717 assert(false);
718 last_mode_ = kModeError;
719 return return_value;
720 }
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000721 LOG(LS_VERBOSE) << "GetDecision returned operation=" << operation <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000722 " and " << packet_list.size() << " packet(s)";
723
724 AudioDecoder::SpeechType speech_type;
725 int length = 0;
726 int decode_return_value = Decode(&packet_list, &operation,
727 &length, &speech_type);
728
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000729 assert(vad_.get());
730 bool sid_frame_available =
731 (operation == kRfc3389Cng && !packet_list.empty());
732 vad_->Update(decoded_buffer_.get(), length, speech_type,
733 sid_frame_available, fs_hz_);
734
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000735 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000736 switch (operation) {
737 case kNormal: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000738 DoNormal(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000739 break;
740 }
741 case kMerge: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000742 DoMerge(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000743 break;
744 }
745 case kExpand: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000746 return_value = DoExpand(play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000747 break;
748 }
Henrik Lundincf808d22015-05-27 14:33:29 +0200749 case kAccelerate:
750 case kFastAccelerate: {
751 const bool fast_accelerate =
752 enable_fast_accelerate_ && (operation == kFastAccelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000753 return_value = DoAccelerate(decoded_buffer_.get(), length, speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +0200754 play_dtmf, fast_accelerate);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000755 break;
756 }
757 case kPreemptiveExpand: {
758 return_value = DoPreemptiveExpand(decoded_buffer_.get(), length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000759 speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000760 break;
761 }
762 case kRfc3389Cng:
763 case kRfc3389CngNoPacket: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000764 return_value = DoRfc3389Cng(&packet_list, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000765 break;
766 }
767 case kCodecInternalCng: {
768 // This handles the case when there is no transmission and the decoder
769 // should produce internal comfort noise.
770 // TODO(hlundin): Write test for codec-internal CNG.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000771 DoCodecInternalCng();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000772 break;
773 }
774 case kDtmf: {
775 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000776 return_value = DoDtmf(dtmf_event, &play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000777 break;
778 }
779 case kAlternativePlc: {
780 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000781 DoAlternativePlc(false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000782 break;
783 }
784 case kAlternativePlcIncreaseTimestamp: {
785 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000786 DoAlternativePlc(true);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000787 break;
788 }
789 case kAudioRepetitionIncreaseTimestamp: {
790 // TODO(hlundin): Write test for this.
791 sync_buffer_->IncreaseEndTimestamp(output_size_samples_);
792 // Skipping break on purpose. Execution should move on into the
793 // next case.
kjellander@webrtc.org7d2b6a92015-01-28 18:37:58 +0000794 FALLTHROUGH();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000795 }
796 case kAudioRepetition: {
797 // TODO(hlundin): Write test for this.
798 // Copy last |output_size_samples_| from |sync_buffer_| to
799 // |algorithm_buffer|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000800 algorithm_buffer_->PushBackFromIndex(
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000801 *sync_buffer_, sync_buffer_->Size() - output_size_samples_);
802 expand_->Reset();
803 break;
804 }
805 case kUndefined: {
806 LOG_F(LS_ERROR) << "Invalid operation kUndefined.";
807 assert(false); // This should not happen.
808 last_mode_ = kModeError;
809 return kInvalidOperation;
810 }
811 } // End of switch.
812 if (return_value < 0) {
813 return return_value;
814 }
815
816 if (last_mode_ != kModeRfc3389Cng) {
817 comfort_noise_->Reset();
818 }
819
820 // Copy from |algorithm_buffer| to |sync_buffer_|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000821 sync_buffer_->PushBack(*algorithm_buffer_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000822
823 // Extract data from |sync_buffer_| to |output|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000824 size_t num_output_samples_per_channel = output_size_samples_;
825 size_t num_output_samples = output_size_samples_ * sync_buffer_->Channels();
826 if (num_output_samples > max_length) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000827 LOG(LS_WARNING) << "Output array is too short. " << max_length << " < " <<
828 output_size_samples_ << " * " << sync_buffer_->Channels();
829 num_output_samples = max_length;
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000830 num_output_samples_per_channel = static_cast<int>(
831 max_length / sync_buffer_->Channels());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000832 }
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000833 int samples_from_sync = static_cast<int>(
834 sync_buffer_->GetNextAudioInterleaved(num_output_samples_per_channel,
835 output));
836 *num_channels = static_cast<int>(sync_buffer_->Channels());
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000837 LOG(LS_VERBOSE) << "Sync buffer (" << *num_channels << " channel(s)):" <<
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000838 " insert " << algorithm_buffer_->Size() << " samples, extract " <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000839 samples_from_sync << " samples";
840 if (samples_from_sync != output_size_samples_) {
841 LOG_F(LS_ERROR) << "samples_from_sync != output_size_samples_";
minyue@webrtc.orgdb1cefc2013-08-13 01:39:21 +0000842 // TODO(minyue): treatment of under-run, filling zeros
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000843 memset(output, 0, num_output_samples * sizeof(int16_t));
844 *samples_per_channel = output_size_samples_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000845 return kSampleUnderrun;
846 }
847 *samples_per_channel = output_size_samples_;
848
849 // Should always have overlap samples left in the |sync_buffer_|.
850 assert(sync_buffer_->FutureLength() >= expand_->overlap_length());
851
852 if (play_dtmf) {
853 return_value = DtmfOverdub(dtmf_event, sync_buffer_->Channels(), output);
854 }
855
856 // Update the background noise parameters if last operation wrote data
857 // straight from the decoder to the |sync_buffer_|. That is, none of the
858 // operations that modify the signal can be followed by a parameter update.
859 if ((last_mode_ == kModeNormal) ||
860 (last_mode_ == kModeAccelerateFail) ||
861 (last_mode_ == kModePreemptiveExpandFail) ||
862 (last_mode_ == kModeRfc3389Cng) ||
863 (last_mode_ == kModeCodecInternalCng)) {
864 background_noise_->Update(*sync_buffer_, *vad_.get());
865 }
866
867 if (operation == kDtmf) {
868 // DTMF data was written the end of |sync_buffer_|.
869 // Update index to end of DTMF data in |sync_buffer_|.
870 sync_buffer_->set_dtmf_index(sync_buffer_->Size());
871 }
872
henrik.lundin@webrtc.orged865b52014-03-06 10:28:07 +0000873 if (last_mode_ != kModeExpand) {
874 // If last operation was not expand, calculate the |playout_timestamp_| from
875 // the |sync_buffer_|. However, do not update the |playout_timestamp_| if it
876 // would be moved "backwards".
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000877 uint32_t temp_timestamp = sync_buffer_->end_timestamp() -
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000878 static_cast<uint32_t>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000879 if (static_cast<int32_t>(temp_timestamp - playout_timestamp_) > 0) {
880 playout_timestamp_ = temp_timestamp;
881 }
882 } else {
883 // Use dead reckoning to estimate the |playout_timestamp_|.
884 playout_timestamp_ += output_size_samples_;
885 }
886
887 if (decode_return_value) return decode_return_value;
888 return return_value;
889}
890
891int NetEqImpl::GetDecision(Operations* operation,
892 PacketList* packet_list,
893 DtmfEvent* dtmf_event,
894 bool* play_dtmf) {
895 // Initialize output variables.
896 *play_dtmf = false;
897 *operation = kUndefined;
898
899 // Increment time counters.
900 packet_buffer_->IncrementWaitingTimes();
901 stats_.IncreaseCounter(output_size_samples_, fs_hz_);
902
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000903 assert(sync_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000904 uint32_t end_timestamp = sync_buffer_->end_timestamp();
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +0000905 if (!new_codec_) {
906 const uint32_t five_seconds_samples = 5 * fs_hz_;
907 packet_buffer_->DiscardOldPackets(end_timestamp, five_seconds_samples);
908 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000909 const RTPHeader* header = packet_buffer_->NextRtpHeader();
910
henrik.lundin@webrtc.orgca8cb952014-03-12 10:26:52 +0000911 if (decision_logic_->CngRfc3389On() || last_mode_ == kModeRfc3389Cng) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000912 // Because of timestamp peculiarities, we have to "manually" disallow using
913 // a CNG packet with the same timestamp as the one that was last played.
914 // This can happen when using redundancy and will cause the timing to shift.
henrik.lundin@webrtc.org24779fe2014-03-14 12:40:05 +0000915 while (header && decoder_database_->IsComfortNoise(header->payloadType) &&
916 (end_timestamp >= header->timestamp ||
917 end_timestamp + decision_logic_->generated_noise_samples() >
918 header->timestamp)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000919 // Don't use this packet, discard it.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000920 if (packet_buffer_->DiscardNextPacket() != PacketBuffer::kOK) {
921 assert(false); // Must be ok by design.
922 }
923 // Check buffer again.
924 if (!new_codec_) {
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +0000925 packet_buffer_->DiscardOldPackets(end_timestamp, 5 * fs_hz_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000926 }
927 header = packet_buffer_->NextRtpHeader();
928 }
929 }
930
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000931 assert(expand_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000932 const int samples_left = static_cast<int>(sync_buffer_->FutureLength() -
933 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000934 if (last_mode_ == kModeAccelerateSuccess ||
935 last_mode_ == kModeAccelerateLowEnergy ||
936 last_mode_ == kModePreemptiveExpandSuccess ||
937 last_mode_ == kModePreemptiveExpandLowEnergy) {
938 // Subtract (samples_left + output_size_samples_) from sampleMemory.
939 decision_logic_->AddSampleMemory(-(samples_left + output_size_samples_));
940 }
941
942 // Check if it is time to play a DTMF event.
943 if (dtmf_buffer_->GetEvent(end_timestamp +
944 decision_logic_->generated_noise_samples(),
945 dtmf_event)) {
946 *play_dtmf = true;
947 }
948
949 // Get instruction.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000950 assert(sync_buffer_.get());
951 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000952 *operation = decision_logic_->GetDecision(*sync_buffer_,
953 *expand_,
954 decoder_frame_length_,
955 header,
956 last_mode_,
957 *play_dtmf,
958 &reset_decoder_);
959
960 // Check if we already have enough samples in the |sync_buffer_|. If so,
961 // change decision to normal, unless the decision was merge, accelerate, or
962 // preemptive expand.
Henrik Lundincf808d22015-05-27 14:33:29 +0200963 if (samples_left >= output_size_samples_ && *operation != kMerge &&
964 *operation != kAccelerate && *operation != kFastAccelerate &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000965 *operation != kPreemptiveExpand) {
966 *operation = kNormal;
967 return 0;
968 }
969
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000970 decision_logic_->ExpandDecision(*operation);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000971
972 // Check conditions for reset.
973 if (new_codec_ || *operation == kUndefined) {
974 // The only valid reason to get kUndefined is that new_codec_ is set.
975 assert(new_codec_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000976 if (*play_dtmf && !header) {
977 timestamp_ = dtmf_event->timestamp;
978 } else {
979 assert(header);
980 if (!header) {
981 LOG_F(LS_ERROR) << "Packet missing where it shouldn't.";
982 return -1;
983 }
984 timestamp_ = header->timestamp;
985 if (*operation == kRfc3389CngNoPacket
986#ifndef LEGACY_BITEXACT
987 // Without this check, it can happen that a non-CNG packet is sent to
988 // the CNG decoder as if it was a SID frame. This is clearly a bug,
989 // but is kept for now to maintain bit-exactness with the test
990 // vectors.
991 && decoder_database_->IsComfortNoise(header->payloadType)
992#endif
993 ) {
994 // Change decision to CNG packet, since we do have a CNG packet, but it
995 // was considered too early to use. Now, use it anyway.
996 *operation = kRfc3389Cng;
997 } else if (*operation != kRfc3389Cng) {
998 *operation = kNormal;
999 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001000 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001001 // Adjust |sync_buffer_| timestamp before setting |end_timestamp| to the
1002 // new value.
1003 sync_buffer_->IncreaseEndTimestamp(timestamp_ - end_timestamp);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001004 end_timestamp = timestamp_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001005 new_codec_ = false;
1006 decision_logic_->SoftReset();
1007 buffer_level_filter_->Reset();
1008 delay_manager_->Reset();
1009 stats_.ResetMcu();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001010 }
1011
1012 int required_samples = output_size_samples_;
1013 const int samples_10_ms = 80 * fs_mult_;
1014 const int samples_20_ms = 2 * samples_10_ms;
1015 const int samples_30_ms = 3 * samples_10_ms;
1016
1017 switch (*operation) {
1018 case kExpand: {
1019 timestamp_ = end_timestamp;
1020 return 0;
1021 }
1022 case kRfc3389CngNoPacket:
1023 case kCodecInternalCng: {
1024 return 0;
1025 }
1026 case kDtmf: {
1027 // TODO(hlundin): Write test for this.
1028 // Update timestamp.
1029 timestamp_ = end_timestamp;
1030 if (decision_logic_->generated_noise_samples() > 0 &&
1031 last_mode_ != kModeDtmf) {
1032 // Make a jump in timestamp due to the recently played comfort noise.
1033 uint32_t timestamp_jump = decision_logic_->generated_noise_samples();
1034 sync_buffer_->IncreaseEndTimestamp(timestamp_jump);
1035 timestamp_ += timestamp_jump;
1036 }
1037 decision_logic_->set_generated_noise_samples(0);
1038 return 0;
1039 }
Henrik Lundincf808d22015-05-27 14:33:29 +02001040 case kAccelerate:
1041 case kFastAccelerate: {
1042 // In order to do an accelerate we need at least 30 ms of audio data.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001043 if (samples_left >= samples_30_ms) {
1044 // Already have enough data, so we do not need to extract any more.
1045 decision_logic_->set_sample_memory(samples_left);
1046 decision_logic_->set_prev_time_scale(true);
1047 return 0;
1048 } else if (samples_left >= samples_10_ms &&
1049 decoder_frame_length_ >= samples_30_ms) {
1050 // Avoid decoding more data as it might overflow the playout buffer.
1051 *operation = kNormal;
1052 return 0;
1053 } else if (samples_left < samples_20_ms &&
1054 decoder_frame_length_ < samples_30_ms) {
1055 // Build up decoded data by decoding at least 20 ms of audio data. Do
1056 // not perform accelerate yet, but wait until we only need to do one
1057 // decoding.
1058 required_samples = 2 * output_size_samples_;
1059 *operation = kNormal;
1060 }
1061 // If none of the above is true, we have one of two possible situations:
1062 // (1) 20 ms <= samples_left < 30 ms and decoder_frame_length_ < 30 ms; or
1063 // (2) samples_left < 10 ms and decoder_frame_length_ >= 30 ms.
1064 // In either case, we move on with the accelerate decision, and decode one
1065 // frame now.
1066 break;
1067 }
1068 case kPreemptiveExpand: {
1069 // In order to do a preemptive expand we need at least 30 ms of decoded
1070 // audio data.
1071 if ((samples_left >= samples_30_ms) ||
1072 (samples_left >= samples_10_ms &&
1073 decoder_frame_length_ >= samples_30_ms)) {
1074 // Already have enough data, so we do not need to extract any more.
1075 // Or, avoid decoding more data as it might overflow the playout buffer.
1076 // Still try preemptive expand, though.
1077 decision_logic_->set_sample_memory(samples_left);
1078 decision_logic_->set_prev_time_scale(true);
1079 return 0;
1080 }
1081 if (samples_left < samples_20_ms &&
1082 decoder_frame_length_ < samples_30_ms) {
1083 // Build up decoded data by decoding at least 20 ms of audio data.
1084 // Still try to perform preemptive expand.
1085 required_samples = 2 * output_size_samples_;
1086 }
1087 // Move on with the preemptive expand decision.
1088 break;
1089 }
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001090 case kMerge: {
1091 required_samples =
1092 std::max(merge_->RequiredFutureSamples(), required_samples);
1093 break;
1094 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001095 default: {
1096 // Do nothing.
1097 }
1098 }
1099
1100 // Get packets from buffer.
1101 int extracted_samples = 0;
1102 if (header &&
1103 *operation != kAlternativePlc &&
1104 *operation != kAlternativePlcIncreaseTimestamp &&
1105 *operation != kAudioRepetition &&
1106 *operation != kAudioRepetitionIncreaseTimestamp) {
1107 sync_buffer_->IncreaseEndTimestamp(header->timestamp - end_timestamp);
1108 if (decision_logic_->CngOff()) {
1109 // Adjustment of timestamp only corresponds to an actual packet loss
1110 // if comfort noise is not played. If comfort noise was just played,
1111 // this adjustment of timestamp is only done to get back in sync with the
1112 // stream timestamp; no loss to report.
1113 stats_.LostSamples(header->timestamp - end_timestamp);
1114 }
1115
1116 if (*operation != kRfc3389Cng) {
1117 // We are about to decode and use a non-CNG packet.
1118 decision_logic_->SetCngOff();
1119 }
1120 // Reset CNG timestamp as a new packet will be delivered.
1121 // (Also if this is a CNG packet, since playedOutTS is updated.)
1122 decision_logic_->set_generated_noise_samples(0);
1123
1124 extracted_samples = ExtractPackets(required_samples, packet_list);
1125 if (extracted_samples < 0) {
1126 LOG_F(LS_WARNING) << "Failed to extract packets from buffer.";
1127 return kPacketBufferCorruption;
1128 }
1129 }
1130
Henrik Lundincf808d22015-05-27 14:33:29 +02001131 if (*operation == kAccelerate || *operation == kFastAccelerate ||
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001132 *operation == kPreemptiveExpand) {
1133 decision_logic_->set_sample_memory(samples_left + extracted_samples);
1134 decision_logic_->set_prev_time_scale(true);
1135 }
1136
Henrik Lundincf808d22015-05-27 14:33:29 +02001137 if (*operation == kAccelerate || *operation == kFastAccelerate) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001138 // Check that we have enough data (30ms) to do accelerate.
1139 if (extracted_samples + samples_left < samples_30_ms) {
1140 // TODO(hlundin): Write test for this.
1141 // Not enough, do normal operation instead.
1142 *operation = kNormal;
1143 }
1144 }
1145
1146 timestamp_ = end_timestamp;
1147 return 0;
1148}
1149
1150int NetEqImpl::Decode(PacketList* packet_list, Operations* operation,
1151 int* decoded_length,
1152 AudioDecoder::SpeechType* speech_type) {
1153 *speech_type = AudioDecoder::kSpeech;
1154 AudioDecoder* decoder = NULL;
1155 if (!packet_list->empty()) {
1156 const Packet* packet = packet_list->front();
pkasting@chromium.org0e81fdf2015-02-02 23:54:03 +00001157 uint8_t payload_type = packet->header.payloadType;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001158 if (!decoder_database_->IsComfortNoise(payload_type)) {
1159 decoder = decoder_database_->GetDecoder(payload_type);
1160 assert(decoder);
1161 if (!decoder) {
pkasting@chromium.org0e81fdf2015-02-02 23:54:03 +00001162 LOG_FERR1(LS_WARNING, GetDecoder, static_cast<int>(payload_type));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001163 PacketBuffer::DeleteAllPackets(packet_list);
1164 return kDecoderNotFound;
1165 }
1166 bool decoder_changed;
1167 decoder_database_->SetActiveDecoder(payload_type, &decoder_changed);
1168 if (decoder_changed) {
1169 // We have a new decoder. Re-init some values.
1170 const DecoderDatabase::DecoderInfo* decoder_info = decoder_database_
1171 ->GetDecoderInfo(payload_type);
1172 assert(decoder_info);
1173 if (!decoder_info) {
pkasting@chromium.org0e81fdf2015-02-02 23:54:03 +00001174 LOG_FERR1(LS_WARNING, GetDecoderInfo, static_cast<int>(payload_type));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001175 PacketBuffer::DeleteAllPackets(packet_list);
1176 return kDecoderNotFound;
1177 }
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001178 // If sampling rate or number of channels has changed, we need to make
1179 // a reset.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001180 if (decoder_info->fs_hz != fs_hz_ ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001181 decoder->Channels() != algorithm_buffer_->Channels()) {
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001182 // TODO(tlegrand): Add unittest to cover this event.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001183 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->Channels());
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001184 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001185 sync_buffer_->set_end_timestamp(timestamp_);
1186 playout_timestamp_ = timestamp_;
1187 }
1188 }
1189 }
1190
1191 if (reset_decoder_) {
1192 // TODO(hlundin): Write test for this.
1193 // Reset decoder.
1194 if (decoder) {
1195 decoder->Init();
1196 }
1197 // Reset comfort noise decoder.
1198 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
1199 if (cng_decoder) {
1200 cng_decoder->Init();
1201 }
1202 reset_decoder_ = false;
1203 }
1204
1205#ifdef LEGACY_BITEXACT
1206 // Due to a bug in old SignalMCU, it could happen that CNG operation was
1207 // decided, but a speech packet was provided. The speech packet will be used
1208 // to update the comfort noise decoder, as if it was a SID frame, which is
1209 // clearly wrong.
1210 if (*operation == kRfc3389Cng) {
1211 return 0;
1212 }
1213#endif
1214
1215 *decoded_length = 0;
1216 // Update codec-internal PLC state.
1217 if ((*operation == kMerge) && decoder && decoder->HasDecodePlc()) {
1218 decoder->DecodePlc(1, &decoded_buffer_[*decoded_length]);
1219 }
1220
1221 int return_value = DecodeLoop(packet_list, operation, decoder,
1222 decoded_length, speech_type);
1223
1224 if (*decoded_length < 0) {
1225 // Error returned from the decoder.
1226 *decoded_length = 0;
1227 sync_buffer_->IncreaseEndTimestamp(decoder_frame_length_);
1228 int error_code = 0;
1229 if (decoder)
1230 error_code = decoder->ErrorCode();
1231 if (error_code != 0) {
1232 // Got some error code from the decoder.
1233 decoder_error_code_ = error_code;
1234 return_value = kDecoderErrorCode;
1235 } else {
1236 // Decoder does not implement error codes. Return generic error.
1237 return_value = kOtherDecoderError;
1238 }
1239 LOG_FERR2(LS_WARNING, DecodeLoop, error_code, packet_list->size());
1240 *operation = kExpand; // Do expansion to get data instead.
1241 }
1242 if (*speech_type != AudioDecoder::kComfortNoise) {
1243 // Don't increment timestamp if codec returned CNG speech type
1244 // since in this case, the we will increment the CNGplayedTS counter.
1245 // Increase with number of samples per channel.
1246 assert(*decoded_length == 0 ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001247 (decoder && decoder->Channels() == sync_buffer_->Channels()));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001248 sync_buffer_->IncreaseEndTimestamp(
1249 *decoded_length / static_cast<int>(sync_buffer_->Channels()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001250 }
1251 return return_value;
1252}
1253
1254int NetEqImpl::DecodeLoop(PacketList* packet_list, Operations* operation,
1255 AudioDecoder* decoder, int* decoded_length,
1256 AudioDecoder::SpeechType* speech_type) {
1257 Packet* packet = NULL;
1258 if (!packet_list->empty()) {
1259 packet = packet_list->front();
1260 }
1261 // Do decoding.
1262 while (packet &&
1263 !decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1264 assert(decoder); // At this point, we must have a decoder object.
1265 // The number of channels in the |sync_buffer_| should be the same as the
1266 // number decoder channels.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001267 assert(sync_buffer_->Channels() == decoder->Channels());
1268 assert(decoded_buffer_length_ >= kMaxFrameSize * decoder->Channels());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001269 assert(*operation == kNormal || *operation == kAccelerate ||
Henrik Lundincf808d22015-05-27 14:33:29 +02001270 *operation == kFastAccelerate || *operation == kMerge ||
1271 *operation == kPreemptiveExpand);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001272 packet_list->pop_front();
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001273 size_t payload_length = packet->payload_length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001274 int16_t decode_length;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +00001275 if (packet->sync_packet) {
1276 // Decode to silence with the same frame size as the last decode.
1277 LOG(LS_VERBOSE) << "Decoding sync-packet: " <<
1278 " ts=" << packet->header.timestamp <<
1279 ", sn=" << packet->header.sequenceNumber <<
1280 ", pt=" << static_cast<int>(packet->header.payloadType) <<
1281 ", ssrc=" << packet->header.ssrc <<
1282 ", len=" << packet->payload_length;
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001283 memset(&decoded_buffer_[*decoded_length], 0,
1284 decoder_frame_length_ * decoder->Channels() *
1285 sizeof(decoded_buffer_[0]));
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +00001286 decode_length = decoder_frame_length_;
1287 } else if (!packet->primary) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001288 // This is a redundant payload; call the special decoder method.
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +00001289 LOG(LS_VERBOSE) << "Decoding packet (redundant):" <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001290 " ts=" << packet->header.timestamp <<
1291 ", sn=" << packet->header.sequenceNumber <<
1292 ", pt=" << static_cast<int>(packet->header.payloadType) <<
1293 ", ssrc=" << packet->header.ssrc <<
1294 ", len=" << packet->payload_length;
1295 decode_length = decoder->DecodeRedundant(
henrik.lundin@webrtc.org1eda4e32015-02-25 10:02:29 +00001296 packet->payload, packet->payload_length, fs_hz_,
minyue@webrtc.org7f7d7e32015-03-16 12:30:37 +00001297 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001298 &decoded_buffer_[*decoded_length], speech_type);
1299 } else {
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +00001300 LOG(LS_VERBOSE) << "Decoding packet: ts=" << packet->header.timestamp <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001301 ", sn=" << packet->header.sequenceNumber <<
1302 ", pt=" << static_cast<int>(packet->header.payloadType) <<
1303 ", ssrc=" << packet->header.ssrc <<
1304 ", len=" << packet->payload_length;
henrik.lundin@webrtc.org1eda4e32015-02-25 10:02:29 +00001305 decode_length =
minyue@webrtc.org7f7d7e32015-03-16 12:30:37 +00001306 decoder->Decode(
1307 packet->payload, packet->payload_length, fs_hz_,
1308 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1309 &decoded_buffer_[*decoded_length], speech_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001310 }
1311
1312 delete[] packet->payload;
1313 delete packet;
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001314 packet = NULL;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001315 if (decode_length > 0) {
1316 *decoded_length += decode_length;
1317 // Update |decoder_frame_length_| with number of samples per channel.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001318 decoder_frame_length_ =
1319 decode_length / static_cast<int>(decoder->Channels());
1320 LOG(LS_VERBOSE) << "Decoded " << decode_length << " samples ("
1321 << decoder->Channels() << " channel(s) -> "
1322 << decoder_frame_length_ << " samples per channel)";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001323 } else if (decode_length < 0) {
1324 // Error.
henrik.lundin@webrtc.org63464a92013-01-30 09:41:56 +00001325 LOG_FERR2(LS_WARNING, Decode, decode_length, payload_length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001326 *decoded_length = -1;
1327 PacketBuffer::DeleteAllPackets(packet_list);
1328 break;
1329 }
1330 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1331 // Guard against overflow.
1332 LOG_F(LS_WARNING) << "Decoded too much.";
1333 PacketBuffer::DeleteAllPackets(packet_list);
1334 return kDecodedTooMuch;
1335 }
1336 if (!packet_list->empty()) {
1337 packet = packet_list->front();
1338 } else {
1339 packet = NULL;
1340 }
1341 } // End of decode loop.
1342
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001343 // If the list is not empty at this point, either a decoding error terminated
1344 // the while-loop, or list must hold exactly one CNG packet.
1345 assert(packet_list->empty() || *decoded_length < 0 ||
1346 (packet_list->size() == 1 && packet &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001347 decoder_database_->IsComfortNoise(packet->header.payloadType)));
1348 return 0;
1349}
1350
1351void NetEqImpl::DoNormal(const int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001352 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001353 assert(normal_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001354 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001355 normal_->Process(decoded_buffer, decoded_length, last_mode_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001356 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001357 if (decoded_length != 0) {
1358 last_mode_ = kModeNormal;
1359 }
1360
1361 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1362 if ((speech_type == AudioDecoder::kComfortNoise)
1363 || ((last_mode_ == kModeCodecInternalCng)
1364 && (decoded_length == 0))) {
1365 // TODO(hlundin): Remove second part of || statement above.
1366 last_mode_ = kModeCodecInternalCng;
1367 }
1368
1369 if (!play_dtmf) {
1370 dtmf_tone_generator_->Reset();
1371 }
1372}
1373
1374void NetEqImpl::DoMerge(int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001375 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001376 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001377 assert(merge_.get());
1378 int new_length = merge_->Process(decoded_buffer, decoded_length,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001379 mute_factor_array_.get(),
1380 algorithm_buffer_.get());
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001381 int expand_length_correction = new_length -
1382 static_cast<int>(decoded_length / algorithm_buffer_->Channels());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001383
1384 // Update in-call and post-call statistics.
1385 if (expand_->MuteFactor(0) == 0) {
1386 // Expand generates only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001387 stats_.ExpandedNoiseSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001388 } else {
1389 // Expansion generates more than only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001390 stats_.ExpandedVoiceSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001391 }
1392
1393 last_mode_ = kModeMerge;
1394 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1395 if (speech_type == AudioDecoder::kComfortNoise) {
1396 last_mode_ = kModeCodecInternalCng;
1397 }
1398 expand_->Reset();
1399 if (!play_dtmf) {
1400 dtmf_tone_generator_->Reset();
1401 }
1402}
1403
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001404int NetEqImpl::DoExpand(bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001405 while ((sync_buffer_->FutureLength() - expand_->overlap_length()) <
1406 static_cast<size_t>(output_size_samples_)) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001407 algorithm_buffer_->Clear();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001408 int return_value = expand_->Process(algorithm_buffer_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001409 int length = static_cast<int>(algorithm_buffer_->Size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001410
1411 // Update in-call and post-call statistics.
1412 if (expand_->MuteFactor(0) == 0) {
1413 // Expand operation generates only noise.
1414 stats_.ExpandedNoiseSamples(length);
1415 } else {
1416 // Expand operation generates more than only noise.
1417 stats_.ExpandedVoiceSamples(length);
1418 }
1419
1420 last_mode_ = kModeExpand;
1421
1422 if (return_value < 0) {
1423 return return_value;
1424 }
1425
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001426 sync_buffer_->PushBack(*algorithm_buffer_);
1427 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001428 }
1429 if (!play_dtmf) {
1430 dtmf_tone_generator_->Reset();
1431 }
1432 return 0;
1433}
1434
Henrik Lundincf808d22015-05-27 14:33:29 +02001435int NetEqImpl::DoAccelerate(int16_t* decoded_buffer,
1436 size_t decoded_length,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001437 AudioDecoder::SpeechType speech_type,
Henrik Lundincf808d22015-05-27 14:33:29 +02001438 bool play_dtmf,
1439 bool fast_accelerate) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001440 const size_t required_samples = 240 * fs_mult_; // Must have 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001441 size_t borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001442 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001443 size_t decoded_length_per_channel = decoded_length / num_channels;
1444 if (decoded_length_per_channel < required_samples) {
1445 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001446 borrowed_samples_per_channel = static_cast<int>(required_samples -
1447 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001448 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1449 decoded_buffer,
1450 sizeof(int16_t) * decoded_length);
1451 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1452 decoded_buffer);
1453 decoded_length = required_samples * num_channels;
1454 }
1455
1456 int16_t samples_removed;
Henrik Lundincf808d22015-05-27 14:33:29 +02001457 Accelerate::ReturnCodes return_code =
1458 accelerate_->Process(decoded_buffer, decoded_length, fast_accelerate,
1459 algorithm_buffer_.get(), &samples_removed);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001460 stats_.AcceleratedSamples(samples_removed);
1461 switch (return_code) {
1462 case Accelerate::kSuccess:
1463 last_mode_ = kModeAccelerateSuccess;
1464 break;
1465 case Accelerate::kSuccessLowEnergy:
1466 last_mode_ = kModeAccelerateLowEnergy;
1467 break;
1468 case Accelerate::kNoStretch:
1469 last_mode_ = kModeAccelerateFail;
1470 break;
1471 case Accelerate::kError:
1472 // TODO(hlundin): Map to kModeError instead?
1473 last_mode_ = kModeAccelerateFail;
1474 return kAccelerateError;
1475 }
1476
1477 if (borrowed_samples_per_channel > 0) {
1478 // Copy borrowed samples back to the |sync_buffer_|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001479 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001480 if (length < borrowed_samples_per_channel) {
1481 // This destroys the beginning of the buffer, but will not cause any
1482 // problems.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001483 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001484 sync_buffer_->Size() -
1485 borrowed_samples_per_channel);
1486 sync_buffer_->PushFrontZeros(borrowed_samples_per_channel - length);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001487 algorithm_buffer_->PopFront(length);
1488 assert(algorithm_buffer_->Empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001489 } else {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001490 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001491 borrowed_samples_per_channel,
1492 sync_buffer_->Size() -
1493 borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001494 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001495 }
1496 }
1497
1498 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1499 if (speech_type == AudioDecoder::kComfortNoise) {
1500 last_mode_ = kModeCodecInternalCng;
1501 }
1502 if (!play_dtmf) {
1503 dtmf_tone_generator_->Reset();
1504 }
1505 expand_->Reset();
1506 return 0;
1507}
1508
1509int NetEqImpl::DoPreemptiveExpand(int16_t* decoded_buffer,
1510 size_t decoded_length,
1511 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001512 bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001513 const size_t required_samples = 240 * fs_mult_; // Must have 30 ms.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001514 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001515 int borrowed_samples_per_channel = 0;
1516 int old_borrowed_samples_per_channel = 0;
1517 size_t decoded_length_per_channel = decoded_length / num_channels;
1518 if (decoded_length_per_channel < required_samples) {
1519 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001520 borrowed_samples_per_channel = static_cast<int>(required_samples -
1521 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001522 // Calculate how many of these were already played out.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001523 old_borrowed_samples_per_channel = static_cast<int>(
1524 borrowed_samples_per_channel - sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001525 old_borrowed_samples_per_channel = std::max(
1526 0, old_borrowed_samples_per_channel);
1527 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1528 decoded_buffer,
1529 sizeof(int16_t) * decoded_length);
1530 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1531 decoded_buffer);
1532 decoded_length = required_samples * num_channels;
1533 }
1534
1535 int16_t samples_added;
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001536 PreemptiveExpand::ReturnCodes return_code = preemptive_expand_->Process(
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001537 decoded_buffer, static_cast<int>(decoded_length),
1538 old_borrowed_samples_per_channel,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001539 algorithm_buffer_.get(), &samples_added);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001540 stats_.PreemptiveExpandedSamples(samples_added);
1541 switch (return_code) {
1542 case PreemptiveExpand::kSuccess:
1543 last_mode_ = kModePreemptiveExpandSuccess;
1544 break;
1545 case PreemptiveExpand::kSuccessLowEnergy:
1546 last_mode_ = kModePreemptiveExpandLowEnergy;
1547 break;
1548 case PreemptiveExpand::kNoStretch:
1549 last_mode_ = kModePreemptiveExpandFail;
1550 break;
1551 case PreemptiveExpand::kError:
1552 // TODO(hlundin): Map to kModeError instead?
1553 last_mode_ = kModePreemptiveExpandFail;
1554 return kPreemptiveExpandError;
1555 }
1556
1557 if (borrowed_samples_per_channel > 0) {
1558 // Copy borrowed samples back to the |sync_buffer_|.
1559 sync_buffer_->ReplaceAtIndex(
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001560 *algorithm_buffer_, borrowed_samples_per_channel,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001561 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001562 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001563 }
1564
1565 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1566 if (speech_type == AudioDecoder::kComfortNoise) {
1567 last_mode_ = kModeCodecInternalCng;
1568 }
1569 if (!play_dtmf) {
1570 dtmf_tone_generator_->Reset();
1571 }
1572 expand_->Reset();
1573 return 0;
1574}
1575
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001576int NetEqImpl::DoRfc3389Cng(PacketList* packet_list, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001577 if (!packet_list->empty()) {
1578 // Must have exactly one SID frame at this point.
1579 assert(packet_list->size() == 1);
1580 Packet* packet = packet_list->front();
1581 packet_list->pop_front();
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001582 if (!decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1583#ifdef LEGACY_BITEXACT
1584 // This can happen due to a bug in GetDecision. Change the payload type
1585 // to a CNG type, and move on. Note that this means that we are in fact
1586 // sending a non-CNG payload to the comfort noise decoder for decoding.
1587 // Clearly wrong, but will maintain bit-exactness with legacy.
1588 if (fs_hz_ == 8000) {
1589 packet->header.payloadType =
1590 decoder_database_->GetRtpPayloadType(kDecoderCNGnb);
1591 } else if (fs_hz_ == 16000) {
1592 packet->header.payloadType =
1593 decoder_database_->GetRtpPayloadType(kDecoderCNGwb);
1594 } else if (fs_hz_ == 32000) {
1595 packet->header.payloadType =
1596 decoder_database_->GetRtpPayloadType(kDecoderCNGswb32kHz);
1597 } else if (fs_hz_ == 48000) {
1598 packet->header.payloadType =
1599 decoder_database_->GetRtpPayloadType(kDecoderCNGswb48kHz);
1600 }
1601 assert(decoder_database_->IsComfortNoise(packet->header.payloadType));
1602#else
1603 LOG(LS_ERROR) << "Trying to decode non-CNG payload as CNG.";
1604 return kOtherError;
1605#endif
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001606 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001607 // UpdateParameters() deletes |packet|.
1608 if (comfort_noise_->UpdateParameters(packet) ==
1609 ComfortNoise::kInternalError) {
1610 LOG_FERR0(LS_WARNING, UpdateParameters);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001611 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001612 return -comfort_noise_->internal_error_code();
1613 }
1614 }
1615 int cn_return = comfort_noise_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001616 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001617 expand_->Reset();
1618 last_mode_ = kModeRfc3389Cng;
1619 if (!play_dtmf) {
1620 dtmf_tone_generator_->Reset();
1621 }
1622 if (cn_return == ComfortNoise::kInternalError) {
1623 LOG_FERR1(LS_WARNING, comfort_noise_->Generate, cn_return);
1624 decoder_error_code_ = comfort_noise_->internal_error_code();
1625 return kComfortNoiseErrorCode;
1626 } else if (cn_return == ComfortNoise::kUnknownPayloadType) {
1627 LOG_FERR1(LS_WARNING, comfort_noise_->Generate, cn_return);
1628 return kUnknownRtpPayloadType;
1629 }
1630 return 0;
1631}
1632
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001633void NetEqImpl::DoCodecInternalCng() {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001634 int length = 0;
1635 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1636 int16_t decoded_buffer[kMaxFrameSize];
1637 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1638 if (decoder) {
1639 const uint8_t* dummy_payload = NULL;
1640 AudioDecoder::SpeechType speech_type;
minyue@webrtc.org7f7d7e32015-03-16 12:30:37 +00001641 length = decoder->Decode(
1642 dummy_payload, 0, fs_hz_, kMaxFrameSize * sizeof(int16_t),
1643 decoded_buffer, &speech_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001644 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001645 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001646 normal_->Process(decoded_buffer, length, last_mode_, mute_factor_array_.get(),
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001647 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001648 last_mode_ = kModeCodecInternalCng;
1649 expand_->Reset();
1650}
1651
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001652int NetEqImpl::DoDtmf(const DtmfEvent& dtmf_event, bool* play_dtmf) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001653 // This block of the code and the block further down, handling |dtmf_switch|
1654 // are commented out. Otherwise playing out-of-band DTMF would fail in VoE
1655 // test, DtmfTest.ManualSuccessfullySendsOutOfBandTelephoneEvents. This is
1656 // equivalent to |dtmf_switch| always be false.
1657 //
1658 // See http://webrtc-codereview.appspot.com/1195004/ for discussion
1659 // On this issue. This change might cause some glitches at the point of
1660 // switch from audio to DTMF. Issue 1545 is filed to track this.
1661 //
1662 // bool dtmf_switch = false;
1663 // if ((last_mode_ != kModeDtmf) && dtmf_tone_generator_->initialized()) {
1664 // // Special case; see below.
1665 // // We must catch this before calling Generate, since |initialized| is
1666 // // modified in that call.
1667 // dtmf_switch = true;
1668 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001669
1670 int dtmf_return_value = 0;
1671 if (!dtmf_tone_generator_->initialized()) {
1672 // Initialize if not already done.
1673 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1674 dtmf_event.volume);
1675 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001676
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001677 if (dtmf_return_value == 0) {
1678 // Generate DTMF signal.
1679 dtmf_return_value = dtmf_tone_generator_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001680 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001681 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001682
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001683 if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001684 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001685 return dtmf_return_value;
1686 }
1687
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001688 // if (dtmf_switch) {
1689 // // This is the special case where the previous operation was DTMF
1690 // // overdub, but the current instruction is "regular" DTMF. We must make
1691 // // sure that the DTMF does not have any discontinuities. The first DTMF
1692 // // sample that we generate now must be played out immediately, therefore
1693 // // it must be copied to the speech buffer.
1694 // // TODO(hlundin): This code seems incorrect. (Legacy.) Write test and
1695 // // verify correct operation.
1696 // assert(false);
1697 // // Must generate enough data to replace all of the |sync_buffer_|
1698 // // "future".
1699 // int required_length = sync_buffer_->FutureLength();
1700 // assert(dtmf_tone_generator_->initialized());
1701 // dtmf_return_value = dtmf_tone_generator_->Generate(required_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001702 // algorithm_buffer_);
1703 // assert((size_t) required_length == algorithm_buffer_->Size());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001704 // if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001705 // algorithm_buffer_->Zeros(output_size_samples_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001706 // return dtmf_return_value;
1707 // }
1708 //
1709 // // Overwrite the "future" part of the speech buffer with the new DTMF
1710 // // data.
1711 // // TODO(hlundin): It seems that this overwriting has gone lost.
1712 // // Not adapted for multi-channel yet.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001713 // assert(algorithm_buffer_->Channels() == 1);
1714 // if (algorithm_buffer_->Channels() != 1) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001715 // LOG(LS_WARNING) << "DTMF not supported for more than one channel";
1716 // return kStereoNotSupported;
1717 // }
1718 // // Shuffle the remaining data to the beginning of algorithm buffer.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001719 // algorithm_buffer_->PopFront(sync_buffer_->FutureLength());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001720 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001721
1722 sync_buffer_->IncreaseEndTimestamp(output_size_samples_);
1723 expand_->Reset();
1724 last_mode_ = kModeDtmf;
1725
1726 // Set to false because the DTMF is already in the algorithm buffer.
1727 *play_dtmf = false;
1728 return 0;
1729}
1730
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001731void NetEqImpl::DoAlternativePlc(bool increase_timestamp) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001732 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1733 int length;
1734 if (decoder && decoder->HasDecodePlc()) {
1735 // Use the decoder's packet-loss concealment.
1736 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1737 int16_t decoded_buffer[kMaxFrameSize];
1738 length = decoder->DecodePlc(1, decoded_buffer);
1739 if (length > 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001740 algorithm_buffer_->PushBackInterleaved(decoded_buffer, length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001741 } else {
1742 length = 0;
1743 }
1744 } else {
1745 // Do simple zero-stuffing.
1746 length = output_size_samples_;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001747 algorithm_buffer_->Zeros(length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001748 // By not advancing the timestamp, NetEq inserts samples.
1749 stats_.AddZeros(length);
1750 }
1751 if (increase_timestamp) {
1752 sync_buffer_->IncreaseEndTimestamp(length);
1753 }
1754 expand_->Reset();
1755}
1756
1757int NetEqImpl::DtmfOverdub(const DtmfEvent& dtmf_event, size_t num_channels,
1758 int16_t* output) const {
1759 size_t out_index = 0;
1760 int overdub_length = output_size_samples_; // Default value.
1761
1762 if (sync_buffer_->dtmf_index() > sync_buffer_->next_index()) {
1763 // Special operation for transition from "DTMF only" to "DTMF overdub".
1764 out_index = std::min(
1765 sync_buffer_->dtmf_index() - sync_buffer_->next_index(),
1766 static_cast<size_t>(output_size_samples_));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001767 overdub_length = output_size_samples_ - static_cast<int>(out_index);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001768 }
1769
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001770 AudioMultiVector dtmf_output(num_channels);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001771 int dtmf_return_value = 0;
1772 if (!dtmf_tone_generator_->initialized()) {
1773 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1774 dtmf_event.volume);
1775 }
1776 if (dtmf_return_value == 0) {
1777 dtmf_return_value = dtmf_tone_generator_->Generate(overdub_length,
1778 &dtmf_output);
1779 assert((size_t) overdub_length == dtmf_output.Size());
1780 }
1781 dtmf_output.ReadInterleaved(overdub_length, &output[out_index]);
1782 return dtmf_return_value < 0 ? dtmf_return_value : 0;
1783}
1784
1785int NetEqImpl::ExtractPackets(int required_samples, PacketList* packet_list) {
1786 bool first_packet = true;
1787 uint8_t prev_payload_type = 0;
1788 uint32_t prev_timestamp = 0;
1789 uint16_t prev_sequence_number = 0;
1790 bool next_packet_available = false;
1791
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001792 const RTPHeader* header = packet_buffer_->NextRtpHeader();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001793 assert(header);
1794 if (!header) {
1795 return -1;
1796 }
turaj@webrtc.org7df97062013-08-02 18:07:13 +00001797 uint32_t first_timestamp = header->timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001798 int extracted_samples = 0;
1799
1800 // Packet extraction loop.
1801 do {
1802 timestamp_ = header->timestamp;
1803 int discard_count = 0;
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001804 Packet* packet = packet_buffer_->GetNextPacket(&discard_count);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001805 // |header| may be invalid after the |packet_buffer_| operation.
1806 header = NULL;
1807 if (!packet) {
1808 LOG_FERR1(LS_ERROR, GetNextPacket, discard_count) <<
1809 "Should always be able to extract a packet here";
1810 assert(false); // Should always be able to extract a packet here.
1811 return -1;
1812 }
1813 stats_.PacketsDiscarded(discard_count);
1814 // Store waiting time in ms; packets->waiting_time is in "output blocks".
1815 stats_.StoreWaitingTime(packet->waiting_time * kOutputSizeMs);
1816 assert(packet->payload_length > 0);
1817 packet_list->push_back(packet); // Store packet in list.
1818
1819 if (first_packet) {
1820 first_packet = false;
minyue@webrtc.orgd7301772013-08-29 00:58:14 +00001821 decoded_packet_sequence_number_ = prev_sequence_number =
1822 packet->header.sequenceNumber;
1823 decoded_packet_timestamp_ = prev_timestamp = packet->header.timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001824 prev_payload_type = packet->header.payloadType;
1825 }
1826
1827 // Store number of extracted samples.
1828 int packet_duration = 0;
1829 AudioDecoder* decoder = decoder_database_->GetDecoder(
1830 packet->header.payloadType);
1831 if (decoder) {
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001832 if (packet->sync_packet) {
1833 packet_duration = decoder_frame_length_;
1834 } else {
minyue@webrtc.org2c1bcf22015-02-17 10:17:09 +00001835 if (packet->primary) {
1836 packet_duration = decoder->PacketDuration(packet->payload,
1837 packet->payload_length);
1838 } else {
1839 packet_duration = decoder->
1840 PacketDurationRedundant(packet->payload, packet->payload_length);
1841 stats_.SecondaryDecodedSamples(packet_duration);
1842 }
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001843 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001844 } else {
pkasting@chromium.org026b8922015-01-30 19:53:42 +00001845 LOG_FERR1(LS_WARNING, GetDecoder,
1846 static_cast<int>(packet->header.payloadType))
1847 << "Could not find a decoder for a packet about to be extracted.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001848 assert(false);
1849 }
1850 if (packet_duration <= 0) {
1851 // Decoder did not return a packet duration. Assume that the packet
1852 // contains the same number of samples as the previous one.
1853 packet_duration = decoder_frame_length_;
1854 }
1855 extracted_samples = packet->header.timestamp - first_timestamp +
1856 packet_duration;
1857
1858 // Check what packet is available next.
1859 header = packet_buffer_->NextRtpHeader();
1860 next_packet_available = false;
1861 if (header && prev_payload_type == header->payloadType) {
1862 int16_t seq_no_diff = header->sequenceNumber - prev_sequence_number;
1863 int32_t ts_diff = header->timestamp - prev_timestamp;
1864 if (seq_no_diff == 1 ||
1865 (seq_no_diff == 0 && ts_diff == decoder_frame_length_)) {
1866 // The next sequence number is available, or the next part of a packet
1867 // that was split into pieces upon insertion.
1868 next_packet_available = true;
1869 }
1870 prev_sequence_number = header->sequenceNumber;
1871 }
1872 } while (extracted_samples < required_samples && next_packet_available);
1873
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00001874 if (extracted_samples > 0) {
1875 // Delete old packets only when we are going to decode something. Otherwise,
1876 // we could end up in the situation where we never decode anything, since
1877 // all incoming packets are considered too old but the buffer will also
1878 // never be flooded and flushed.
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001879 packet_buffer_->DiscardAllOldPackets(timestamp_);
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00001880 }
1881
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001882 return extracted_samples;
1883}
1884
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001885void NetEqImpl::UpdatePlcComponents(int fs_hz, size_t channels) {
1886 // Delete objects and create new ones.
1887 expand_.reset(expand_factory_->Create(background_noise_.get(),
1888 sync_buffer_.get(), &random_vector_,
1889 fs_hz, channels));
1890 merge_.reset(new Merge(fs_hz, channels, expand_.get(), sync_buffer_.get()));
1891}
1892
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001893void NetEqImpl::SetSampleRateAndChannels(int fs_hz, size_t channels) {
1894 LOG_API2(fs_hz, channels);
1895 // TODO(hlundin): Change to an enumerator and skip assert.
1896 assert(fs_hz == 8000 || fs_hz == 16000 || fs_hz == 32000 || fs_hz == 48000);
1897 assert(channels > 0);
1898
1899 fs_hz_ = fs_hz;
1900 fs_mult_ = fs_hz / 8000;
1901 output_size_samples_ = kOutputSizeMs * 8 * fs_mult_;
1902 decoder_frame_length_ = 3 * output_size_samples_; // Initialize to 30ms.
1903
1904 last_mode_ = kModeNormal;
1905
1906 // Create a new array of mute factors and set all to 1.
1907 mute_factor_array_.reset(new int16_t[channels]);
1908 for (size_t i = 0; i < channels; ++i) {
1909 mute_factor_array_[i] = 16384; // 1.0 in Q14.
1910 }
1911
1912 // Reset comfort noise decoder, if there is one active.
1913 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
1914 if (cng_decoder) {
1915 cng_decoder->Init();
1916 }
1917
1918 // Reinit post-decode VAD with new sample rate.
1919 assert(vad_.get()); // Cannot be NULL here.
1920 vad_->Init();
1921
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001922 // Delete algorithm buffer and create a new one.
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001923 algorithm_buffer_.reset(new AudioMultiVector(channels));
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001924
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001925 // Delete sync buffer and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001926 sync_buffer_.reset(new SyncBuffer(channels, kSyncBufferSize * fs_mult_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001927
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00001928 // Delete BackgroundNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001929 background_noise_.reset(new BackgroundNoise(channels));
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00001930 background_noise_->set_mode(background_noise_mode_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001931
1932 // Reset random vector.
1933 random_vector_.Reset();
1934
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001935 UpdatePlcComponents(fs_hz, channels);
1936
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001937 // Move index so that we create a small set of future samples (all 0).
1938 sync_buffer_->set_next_index(sync_buffer_->next_index() -
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001939 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001940
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001941 normal_.reset(new Normal(fs_hz, decoder_database_.get(), *background_noise_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001942 expand_.get()));
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +00001943 accelerate_.reset(
1944 accelerate_factory_->Create(fs_hz, channels, *background_noise_));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001945 preemptive_expand_.reset(preemptive_expand_factory_->Create(
1946 fs_hz, channels,
1947 *background_noise_,
1948 static_cast<int>(expand_->overlap_length())));
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001949
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001950 // Delete ComfortNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001951 comfort_noise_.reset(new ComfortNoise(fs_hz, decoder_database_.get(),
1952 sync_buffer_.get()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001953
1954 // Verify that |decoded_buffer_| is long enough.
1955 if (decoded_buffer_length_ < kMaxFrameSize * channels) {
1956 // Reallocate to larger size.
1957 decoded_buffer_length_ = kMaxFrameSize * channels;
1958 decoded_buffer_.reset(new int16_t[decoded_buffer_length_]);
1959 }
1960
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001961 // Create DecisionLogic if it is not created yet, then communicate new sample
1962 // rate and output size to DecisionLogic object.
1963 if (!decision_logic_.get()) {
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00001964 CreateDecisionLogic();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001965 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001966 decision_logic_->SetSampleRate(fs_hz_, output_size_samples_);
1967}
1968
1969NetEqOutputType NetEqImpl::LastOutputType() {
1970 assert(vad_.get());
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001971 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001972 if (last_mode_ == kModeCodecInternalCng || last_mode_ == kModeRfc3389Cng) {
1973 return kOutputCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001974 } else if (last_mode_ == kModeExpand && expand_->MuteFactor(0) == 0) {
1975 // Expand mode has faded down to background noise only (very long expand).
1976 return kOutputPLCtoCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001977 } else if (last_mode_ == kModeExpand) {
1978 return kOutputPLC;
wu@webrtc.org24301a62013-12-13 19:17:43 +00001979 } else if (vad_->running() && !vad_->active_speech()) {
1980 return kOutputVADPassive;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001981 } else {
1982 return kOutputNormal;
1983 }
1984}
1985
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00001986void NetEqImpl::CreateDecisionLogic() {
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001987 decision_logic_.reset(DecisionLogic::Create(fs_hz_, output_size_samples_,
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00001988 playout_mode_,
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001989 decoder_database_.get(),
1990 *packet_buffer_.get(),
1991 delay_manager_.get(),
1992 buffer_level_filter_.get()));
1993}
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001994} // namespace webrtc