blob: 784174f33a352b1ed9b8c40c236f4ac6e659da06 [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),
minyue@webrtc.orgd7301772013-08-29 00:58:14 +000095 decoded_packet_sequence_number_(-1),
96 decoded_packet_timestamp_(0) {
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +000097 int fs = config.sample_rate_hz;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000098 if (fs != 8000 && fs != 16000 && fs != 32000 && fs != 48000) {
99 LOG(LS_ERROR) << "Sample rate " << fs << " Hz not supported. " <<
100 "Changing to 8000 Hz.";
101 fs = 8000;
102 }
andrew@webrtc.org0569d932014-04-09 17:48:48 +0000103 LOG(LS_VERBOSE) << "Create NetEqImpl object with fs = " << fs << ".";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000104 fs_hz_ = fs;
105 fs_mult_ = fs / 8000;
106 output_size_samples_ = kOutputSizeMs * 8 * fs_mult_;
107 decoder_frame_length_ = 3 * output_size_samples_;
108 WebRtcSpl_Init();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000109 if (create_components) {
110 SetSampleRateAndChannels(fs, 1); // Default is 1 channel.
111 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000112}
113
114NetEqImpl::~NetEqImpl() {
115 LOG(LS_INFO) << "Deleting NetEqImpl object.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000116}
117
118int NetEqImpl::InsertPacket(const WebRtcRTPHeader& rtp_header,
119 const uint8_t* payload,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000120 size_t length_bytes,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000121 uint32_t receive_timestamp) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000122 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000123 LOG(LS_VERBOSE) << "InsertPacket: ts=" << rtp_header.header.timestamp <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000124 ", sn=" << rtp_header.header.sequenceNumber <<
125 ", pt=" << static_cast<int>(rtp_header.header.payloadType) <<
126 ", ssrc=" << rtp_header.header.ssrc <<
127 ", len=" << length_bytes;
128 int error = InsertPacketInternal(rtp_header, payload, length_bytes,
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000129 receive_timestamp, false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000130 if (error != 0) {
131 LOG_FERR1(LS_WARNING, InsertPacketInternal, error);
132 error_code_ = error;
133 return kFail;
134 }
135 return kOK;
136}
137
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000138int NetEqImpl::InsertSyncPacket(const WebRtcRTPHeader& rtp_header,
139 uint32_t receive_timestamp) {
140 CriticalSectionScoped lock(crit_sect_.get());
141 LOG(LS_VERBOSE) << "InsertPacket-Sync: ts="
142 << rtp_header.header.timestamp <<
143 ", sn=" << rtp_header.header.sequenceNumber <<
144 ", pt=" << static_cast<int>(rtp_header.header.payloadType) <<
145 ", ssrc=" << rtp_header.header.ssrc;
146
147 const uint8_t kSyncPayload[] = { 's', 'y', 'n', 'c' };
148 int error = InsertPacketInternal(
149 rtp_header, kSyncPayload, sizeof(kSyncPayload), receive_timestamp, true);
150
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000151 if (error != 0) {
152 LOG_FERR1(LS_WARNING, InsertPacketInternal, error);
153 error_code_ = error;
154 return kFail;
155 }
156 return kOK;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000157}
158
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000159int NetEqImpl::GetAudio(size_t max_length, int16_t* output_audio,
160 int* samples_per_channel, int* num_channels,
161 NetEqOutputType* type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000162 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000163 LOG(LS_VERBOSE) << "GetAudio";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000164 int error = GetAudioInternal(max_length, output_audio, samples_per_channel,
165 num_channels);
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000166 LOG(LS_VERBOSE) << "Produced " << *samples_per_channel <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000167 " samples/channel for " << *num_channels << " channel(s)";
168 if (error != 0) {
169 LOG_FERR1(LS_WARNING, GetAudioInternal, error);
170 error_code_ = error;
171 return kFail;
172 }
173 if (type) {
174 *type = LastOutputType();
175 }
176 return kOK;
177}
178
179int NetEqImpl::RegisterPayloadType(enum NetEqDecoder codec,
180 uint8_t rtp_payload_type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000181 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000182 LOG_API2(static_cast<int>(rtp_payload_type), codec);
183 int ret = decoder_database_->RegisterPayload(rtp_payload_type, codec);
184 if (ret != DecoderDatabase::kOK) {
pkasting@chromium.org026b8922015-01-30 19:53:42 +0000185 LOG_FERR2(LS_WARNING, RegisterPayload, static_cast<int>(rtp_payload_type),
186 codec);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000187 switch (ret) {
188 case DecoderDatabase::kInvalidRtpPayloadType:
189 error_code_ = kInvalidRtpPayloadType;
190 break;
191 case DecoderDatabase::kCodecNotSupported:
192 error_code_ = kCodecNotSupported;
193 break;
194 case DecoderDatabase::kDecoderExists:
195 error_code_ = kDecoderExists;
196 break;
197 default:
198 error_code_ = kOtherError;
199 }
200 return kFail;
201 }
202 return kOK;
203}
204
205int NetEqImpl::RegisterExternalDecoder(AudioDecoder* decoder,
206 enum NetEqDecoder codec,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000207 uint8_t rtp_payload_type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000208 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000209 LOG_API2(static_cast<int>(rtp_payload_type), codec);
210 if (!decoder) {
211 LOG(LS_ERROR) << "Cannot register external decoder with NULL pointer";
212 assert(false);
213 return kFail;
214 }
kwiberg@webrtc.orge04a93b2014-12-09 10:12:53 +0000215 const int sample_rate_hz = CodecSampleRateHz(codec);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000216 int ret = decoder_database_->InsertExternal(rtp_payload_type, codec,
217 sample_rate_hz, decoder);
218 if (ret != DecoderDatabase::kOK) {
pkasting@chromium.org026b8922015-01-30 19:53:42 +0000219 LOG_FERR2(LS_WARNING, InsertExternal, static_cast<int>(rtp_payload_type),
220 codec);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000221 switch (ret) {
222 case DecoderDatabase::kInvalidRtpPayloadType:
223 error_code_ = kInvalidRtpPayloadType;
224 break;
225 case DecoderDatabase::kCodecNotSupported:
226 error_code_ = kCodecNotSupported;
227 break;
228 case DecoderDatabase::kDecoderExists:
229 error_code_ = kDecoderExists;
230 break;
231 case DecoderDatabase::kInvalidSampleRate:
232 error_code_ = kInvalidSampleRate;
233 break;
234 case DecoderDatabase::kInvalidPointer:
235 error_code_ = kInvalidPointer;
236 break;
237 default:
238 error_code_ = kOtherError;
239 }
240 return kFail;
241 }
242 return kOK;
243}
244
245int NetEqImpl::RemovePayloadType(uint8_t rtp_payload_type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000246 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000247 LOG_API1(static_cast<int>(rtp_payload_type));
248 int ret = decoder_database_->Remove(rtp_payload_type);
249 if (ret == DecoderDatabase::kOK) {
250 return kOK;
251 } else if (ret == DecoderDatabase::kDecoderNotFound) {
252 error_code_ = kDecoderNotFound;
253 } else {
254 error_code_ = kOtherError;
255 }
pkasting@chromium.org026b8922015-01-30 19:53:42 +0000256 LOG_FERR1(LS_WARNING, Remove, static_cast<int>(rtp_payload_type));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000257 return kFail;
258}
259
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000260bool NetEqImpl::SetMinimumDelay(int delay_ms) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000261 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000262 if (delay_ms >= 0 && delay_ms < 10000) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000263 assert(delay_manager_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000264 return delay_manager_->SetMinimumDelay(delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000265 }
266 return false;
267}
268
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000269bool NetEqImpl::SetMaximumDelay(int delay_ms) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000270 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000271 if (delay_ms >= 0 && delay_ms < 10000) {
272 assert(delay_manager_.get());
273 return delay_manager_->SetMaximumDelay(delay_ms);
274 }
275 return false;
276}
277
278int NetEqImpl::LeastRequiredDelayMs() const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000279 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000280 assert(delay_manager_.get());
281 return delay_manager_->least_required_delay_ms();
282}
283
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200284int NetEqImpl::SetTargetDelay() {
285 return kNotImplemented;
286}
287
288int NetEqImpl::TargetDelay() {
289 return kNotImplemented;
290}
291
292int NetEqImpl::CurrentDelay() {
293 return kNotImplemented;
294}
295
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000296// Deprecated.
297// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000298void NetEqImpl::SetPlayoutMode(NetEqPlayoutMode mode) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000299 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000300 if (mode != playout_mode_) {
301 playout_mode_ = mode;
302 CreateDecisionLogic();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000303 }
304}
305
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000306// Deprecated.
307// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000308NetEqPlayoutMode NetEqImpl::PlayoutMode() const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000309 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000310 return playout_mode_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000311}
312
313int NetEqImpl::NetworkStatistics(NetEqNetworkStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000314 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000315 assert(decoder_database_.get());
316 const int total_samples_in_buffers = packet_buffer_->NumSamplesInBuffer(
317 decoder_database_.get(), decoder_frame_length_) +
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000318 static_cast<int>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000319 assert(delay_manager_.get());
320 assert(decision_logic_.get());
321 stats_.GetNetworkStatistics(fs_hz_, total_samples_in_buffers,
322 decoder_frame_length_, *delay_manager_.get(),
323 *decision_logic_.get(), stats);
324 return 0;
325}
326
327void NetEqImpl::WaitingTimes(std::vector<int>* waiting_times) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000328 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000329 stats_.WaitingTimes(waiting_times);
330}
331
332void NetEqImpl::GetRtcpStatistics(RtcpStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000333 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000334 if (stats) {
335 rtcp_.GetStatistics(false, stats);
336 }
337}
338
339void NetEqImpl::GetRtcpStatisticsNoReset(RtcpStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000340 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000341 if (stats) {
342 rtcp_.GetStatistics(true, stats);
343 }
344}
345
346void NetEqImpl::EnableVad() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000347 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000348 assert(vad_.get());
349 vad_->Enable();
350}
351
352void NetEqImpl::DisableVad() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000353 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000354 assert(vad_.get());
355 vad_->Disable();
356}
357
wu@webrtc.org94454b72014-06-05 20:34:08 +0000358bool NetEqImpl::GetPlayoutTimestamp(uint32_t* timestamp) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000359 CriticalSectionScoped lock(crit_sect_.get());
wu@webrtc.org94454b72014-06-05 20:34:08 +0000360 if (first_packet_) {
361 // We don't have a valid RTP timestamp until we have decoded our first
362 // RTP packet.
363 return false;
364 }
365 *timestamp = timestamp_scaler_->ToExternal(playout_timestamp_);
366 return true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000367}
368
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200369int NetEqImpl::SetTargetNumberOfChannels() {
370 return kNotImplemented;
371}
372
373int NetEqImpl::SetTargetSampleRate() {
374 return kNotImplemented;
375}
376
henrik.lundin@webrtc.orgb0f4b3d2014-11-04 08:53:10 +0000377int NetEqImpl::LastError() const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000378 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000379 return error_code_;
380}
381
382int NetEqImpl::LastDecoderError() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000383 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000384 return decoder_error_code_;
385}
386
387void NetEqImpl::FlushBuffers() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000388 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000389 LOG_API0();
390 packet_buffer_->Flush();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000391 assert(sync_buffer_.get());
392 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000393 sync_buffer_->Flush();
394 sync_buffer_->set_next_index(sync_buffer_->next_index() -
395 expand_->overlap_length());
396 // Set to wait for new codec.
397 first_packet_ = true;
398}
399
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000400void NetEqImpl::PacketBufferStatistics(int* current_num_packets,
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000401 int* max_num_packets) const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000402 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000403 packet_buffer_->BufferStat(current_num_packets, max_num_packets);
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000404}
405
turaj@webrtc.orgff43c852013-09-25 00:07:27 +0000406int NetEqImpl::DecodedRtpInfo(int* sequence_number, uint32_t* timestamp) const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000407 CriticalSectionScoped lock(crit_sect_.get());
minyue@webrtc.orgd7301772013-08-29 00:58:14 +0000408 if (decoded_packet_sequence_number_ < 0)
409 return -1;
410 *sequence_number = decoded_packet_sequence_number_;
411 *timestamp = decoded_packet_timestamp_;
412 return 0;
413}
414
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000415const SyncBuffer* NetEqImpl::sync_buffer_for_test() const {
416 CriticalSectionScoped lock(crit_sect_.get());
417 return sync_buffer_.get();
418}
419
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000420// Methods below this line are private.
421
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000422int NetEqImpl::InsertPacketInternal(const WebRtcRTPHeader& rtp_header,
423 const uint8_t* payload,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000424 size_t length_bytes,
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000425 uint32_t receive_timestamp,
426 bool is_sync_packet) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000427 if (!payload) {
428 LOG_F(LS_ERROR) << "payload == NULL";
429 return kInvalidPointer;
430 }
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000431 // Sanity checks for sync-packets.
432 if (is_sync_packet) {
433 if (decoder_database_->IsDtmf(rtp_header.header.payloadType) ||
434 decoder_database_->IsRed(rtp_header.header.payloadType) ||
435 decoder_database_->IsComfortNoise(rtp_header.header.payloadType)) {
436 LOG_F(LS_ERROR) << "Sync-packet with an unacceptable payload type "
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000437 << static_cast<int>(rtp_header.header.payloadType);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000438 return kSyncPacketNotAccepted;
439 }
440 if (first_packet_ ||
441 rtp_header.header.payloadType != current_rtp_payload_type_ ||
442 rtp_header.header.ssrc != ssrc_) {
443 // Even if |current_rtp_payload_type_| is 0xFF, sync-packet isn't
444 // accepted.
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000445 LOG_F(LS_ERROR)
446 << "Changing codec, SSRC or first packet with sync-packet.";
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000447 return kSyncPacketNotAccepted;
448 }
449 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000450 PacketList packet_list;
451 RTPHeader main_header;
452 {
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000453 // Convert to Packet.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000454 // Create |packet| within this separate scope, since it should not be used
455 // directly once it's been inserted in the packet list. This way, |packet|
456 // is not defined outside of this block.
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000457 Packet* packet = new Packet;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000458 packet->header.markerBit = false;
459 packet->header.payloadType = rtp_header.header.payloadType;
460 packet->header.sequenceNumber = rtp_header.header.sequenceNumber;
461 packet->header.timestamp = rtp_header.header.timestamp;
462 packet->header.ssrc = rtp_header.header.ssrc;
463 packet->header.numCSRCs = 0;
464 packet->payload_length = length_bytes;
465 packet->primary = true;
466 packet->waiting_time = 0;
467 packet->payload = new uint8_t[packet->payload_length];
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000468 packet->sync_packet = is_sync_packet;
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +0000469 if (!packet->payload) {
470 LOG_F(LS_ERROR) << "Payload pointer is NULL.";
471 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000472 assert(payload); // Already checked above.
473 memcpy(packet->payload, payload, packet->payload_length);
474 // Insert packet in a packet list.
475 packet_list.push_back(packet);
476 // Save main payloads header for later.
477 memcpy(&main_header, &packet->header, sizeof(main_header));
478 }
479
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000480 bool update_sample_rate_and_channels = false;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000481 // Reinitialize NetEq if it's needed (changed SSRC or first call).
482 if ((main_header.ssrc != ssrc_) || first_packet_) {
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000483 // Note: |first_packet_| will be cleared further down in this method, once
484 // the packet has been successfully inserted into the packet buffer.
485
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000486 rtcp_.Init(main_header.sequenceNumber);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000487
488 // Flush the packet buffer and DTMF buffer.
489 packet_buffer_->Flush();
490 dtmf_buffer_->Flush();
491
492 // Store new SSRC.
493 ssrc_ = main_header.ssrc;
494
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000495 // Update audio buffer timestamp.
496 sync_buffer_->IncreaseEndTimestamp(main_header.timestamp - timestamp_);
497
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000498 // Update codecs.
499 timestamp_ = main_header.timestamp;
500 current_rtp_payload_type_ = main_header.payloadType;
501
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000502 // Reset timestamp scaling.
503 timestamp_scaler_->Reset();
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000504
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000505 // Trigger an update of sampling rate and the number of channels.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000506 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000507 }
508
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000509 // Update RTCP statistics, only for regular packets.
510 if (!is_sync_packet)
511 rtcp_.Update(main_header, receive_timestamp);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000512
513 // Check for RED payload type, and separate payloads into several packets.
514 if (decoder_database_->IsRed(main_header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000515 assert(!is_sync_packet); // We had a sanity check for this.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000516 if (payload_splitter_->SplitRed(&packet_list) != PayloadSplitter::kOK) {
517 LOG_FERR1(LS_WARNING, SplitRed, packet_list.size());
518 PacketBuffer::DeleteAllPackets(&packet_list);
519 return kRedundancySplitError;
520 }
521 // Only accept a few RED payloads of the same type as the main data,
522 // DTMF events and CNG.
523 payload_splitter_->CheckRedPayloads(&packet_list, *decoder_database_);
524 // Update the stored main payload header since the main payload has now
525 // changed.
526 memcpy(&main_header, &packet_list.front()->header, sizeof(main_header));
527 }
528
529 // Check payload types.
530 if (decoder_database_->CheckPayloadTypes(packet_list) ==
531 DecoderDatabase::kDecoderNotFound) {
532 LOG_FERR1(LS_WARNING, CheckPayloadTypes, packet_list.size());
533 PacketBuffer::DeleteAllPackets(&packet_list);
534 return kUnknownRtpPayloadType;
535 }
536
537 // Scale timestamp to internal domain (only for some codecs).
538 timestamp_scaler_->ToInternal(&packet_list);
539
540 // Process DTMF payloads. Cycle through the list of packets, and pick out any
541 // DTMF payloads found.
542 PacketList::iterator it = packet_list.begin();
543 while (it != packet_list.end()) {
544 Packet* current_packet = (*it);
545 assert(current_packet);
546 assert(current_packet->payload);
547 if (decoder_database_->IsDtmf(current_packet->header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000548 assert(!current_packet->sync_packet); // We had a sanity check for this.
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000549 DtmfEvent event;
550 int ret = DtmfBuffer::ParseEvent(
551 current_packet->header.timestamp,
552 current_packet->payload,
553 current_packet->payload_length,
554 &event);
555 if (ret != DtmfBuffer::kOK) {
556 LOG_FERR2(LS_WARNING, ParseEvent, ret,
557 current_packet->payload_length);
558 PacketBuffer::DeleteAllPackets(&packet_list);
559 return kDtmfParsingError;
560 }
561 if (dtmf_buffer_->InsertEvent(event) != DtmfBuffer::kOK) {
562 LOG_FERR0(LS_WARNING, InsertEvent);
563 PacketBuffer::DeleteAllPackets(&packet_list);
564 return kDtmfInsertError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000565 }
566 // TODO(hlundin): Let the destructor of Packet handle the payload.
567 delete [] current_packet->payload;
568 delete current_packet;
569 it = packet_list.erase(it);
570 } else {
571 ++it;
572 }
573 }
574
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000575 // Check for FEC in packets, and separate payloads into several packets.
576 int ret = payload_splitter_->SplitFec(&packet_list, decoder_database_.get());
577 if (ret != PayloadSplitter::kOK) {
578 LOG_FERR1(LS_WARNING, SplitFec, packet_list.size());
579 PacketBuffer::DeleteAllPackets(&packet_list);
580 switch (ret) {
581 case PayloadSplitter::kUnknownPayloadType:
582 return kUnknownRtpPayloadType;
583 default:
584 return kOtherError;
585 }
586 }
587
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000588 // Split payloads into smaller chunks. This also verifies that all payloads
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000589 // are of a known payload type. SplitAudio() method is protected against
590 // sync-packets.
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +0000591 ret = payload_splitter_->SplitAudio(&packet_list, *decoder_database_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000592 if (ret != PayloadSplitter::kOK) {
593 LOG_FERR1(LS_WARNING, SplitAudio, packet_list.size());
594 PacketBuffer::DeleteAllPackets(&packet_list);
595 switch (ret) {
596 case PayloadSplitter::kUnknownPayloadType:
597 return kUnknownRtpPayloadType;
598 case PayloadSplitter::kFrameSplitError:
599 return kFrameSplitError;
600 default:
601 return kOtherError;
602 }
603 }
604
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000605 // Update bandwidth estimate, if the packet is not sync-packet.
606 if (!packet_list.empty() && !packet_list.front()->sync_packet) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000607 // The list can be empty here if we got nothing but DTMF payloads.
608 AudioDecoder* decoder =
609 decoder_database_->GetDecoder(main_header.payloadType);
610 assert(decoder); // Should always get a valid object, since we have
611 // already checked that the payload types are known.
612 decoder->IncomingPacket(packet_list.front()->payload,
613 packet_list.front()->payload_length,
614 packet_list.front()->header.sequenceNumber,
615 packet_list.front()->header.timestamp,
616 receive_timestamp);
617 }
618
619 // Insert packets in buffer.
620 int temp_bufsize = packet_buffer_->NumPacketsInBuffer();
621 ret = packet_buffer_->InsertPacketList(
622 &packet_list,
623 *decoder_database_,
624 &current_rtp_payload_type_,
625 &current_cng_rtp_payload_type_);
626 if (ret == PacketBuffer::kFlushed) {
627 // Reset DSP timestamp etc. if packet buffer flushed.
628 new_codec_ = true;
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000629 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000630 LOG_F(LS_WARNING) << "Packet buffer flushed";
631 } else if (ret != PacketBuffer::kOK) {
632 LOG_FERR1(LS_WARNING, InsertPacketList, packet_list.size());
633 PacketBuffer::DeleteAllPackets(&packet_list);
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000634 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000635 }
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000636
637 if (first_packet_) {
638 first_packet_ = false;
639 // Update the codec on the next GetAudio call.
640 new_codec_ = true;
641 }
642
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000643 if (current_rtp_payload_type_ != 0xFF) {
644 const DecoderDatabase::DecoderInfo* dec_info =
645 decoder_database_->GetDecoderInfo(current_rtp_payload_type_);
646 if (!dec_info) {
647 assert(false); // Already checked that the payload type is known.
648 }
649 }
650
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000651 if (update_sample_rate_and_channels && !packet_buffer_->Empty()) {
652 // We do not use |current_rtp_payload_type_| to |set payload_type|, but
653 // get the next RTP header from |packet_buffer_| to obtain the payload type.
654 // The reason for it is the following corner case. If NetEq receives a
655 // CNG packet with a sample rate different than the current CNG then it
656 // flushes its buffer, assuming send codec must have been changed. However,
657 // payload type of the hypothetically new send codec is not known.
658 const RTPHeader* rtp_header = packet_buffer_->NextRtpHeader();
659 assert(rtp_header);
660 int payload_type = rtp_header->payloadType;
661 AudioDecoder* decoder = decoder_database_->GetDecoder(payload_type);
662 assert(decoder); // Payloads are already checked to be valid.
663 const DecoderDatabase::DecoderInfo* decoder_info =
664 decoder_database_->GetDecoderInfo(payload_type);
665 assert(decoder_info);
666 if (decoder_info->fs_hz != fs_hz_ ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +0000667 decoder->Channels() != algorithm_buffer_->Channels())
668 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->Channels());
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000669 }
670
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000671 // TODO(hlundin): Move this code to DelayManager class.
672 const DecoderDatabase::DecoderInfo* dec_info =
673 decoder_database_->GetDecoderInfo(main_header.payloadType);
674 assert(dec_info); // Already checked that the payload type is known.
675 delay_manager_->LastDecoderType(dec_info->codec_type);
676 if (delay_manager_->last_pack_cng_or_dtmf() == 0) {
677 // Calculate the total speech length carried in each packet.
678 temp_bufsize = packet_buffer_->NumPacketsInBuffer() - temp_bufsize;
679 temp_bufsize *= decoder_frame_length_;
680
681 if ((temp_bufsize > 0) &&
682 (temp_bufsize != decision_logic_->packet_length_samples())) {
683 decision_logic_->set_packet_length_samples(temp_bufsize);
684 delay_manager_->SetPacketAudioLength((1000 * temp_bufsize) / fs_hz_);
685 }
686
687 // Update statistics.
pbos@webrtc.org0946a562013-04-09 00:28:06 +0000688 if ((int32_t) (main_header.timestamp - timestamp_) >= 0 &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000689 !new_codec_) {
690 // Only update statistics if incoming packet is not older than last played
691 // out packet, and if new codec flag is not set.
692 delay_manager_->Update(main_header.sequenceNumber, main_header.timestamp,
693 fs_hz_);
694 }
695 } else if (delay_manager_->last_pack_cng_or_dtmf() == -1) {
696 // This is first "normal" packet after CNG or DTMF.
697 // Reset packet time counter and measure time until next packet,
698 // but don't update statistics.
699 delay_manager_->set_last_pack_cng_or_dtmf(0);
700 delay_manager_->ResetPacketIatCount();
701 }
702 return 0;
703}
704
705int NetEqImpl::GetAudioInternal(size_t max_length, int16_t* output,
706 int* samples_per_channel, int* num_channels) {
707 PacketList packet_list;
708 DtmfEvent dtmf_event;
709 Operations operation;
710 bool play_dtmf;
711 int return_value = GetDecision(&operation, &packet_list, &dtmf_event,
712 &play_dtmf);
713 if (return_value != 0) {
714 LOG_FERR1(LS_WARNING, GetDecision, return_value);
715 assert(false);
716 last_mode_ = kModeError;
717 return return_value;
718 }
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000719 LOG(LS_VERBOSE) << "GetDecision returned operation=" << operation <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000720 " and " << packet_list.size() << " packet(s)";
721
722 AudioDecoder::SpeechType speech_type;
723 int length = 0;
724 int decode_return_value = Decode(&packet_list, &operation,
725 &length, &speech_type);
726
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000727 assert(vad_.get());
728 bool sid_frame_available =
729 (operation == kRfc3389Cng && !packet_list.empty());
730 vad_->Update(decoded_buffer_.get(), length, speech_type,
731 sid_frame_available, fs_hz_);
732
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000733 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000734 switch (operation) {
735 case kNormal: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000736 DoNormal(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000737 break;
738 }
739 case kMerge: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000740 DoMerge(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000741 break;
742 }
743 case kExpand: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000744 return_value = DoExpand(play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000745 break;
746 }
747 case kAccelerate: {
748 return_value = DoAccelerate(decoded_buffer_.get(), length, speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000749 play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000750 break;
751 }
752 case kPreemptiveExpand: {
753 return_value = DoPreemptiveExpand(decoded_buffer_.get(), length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000754 speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000755 break;
756 }
757 case kRfc3389Cng:
758 case kRfc3389CngNoPacket: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000759 return_value = DoRfc3389Cng(&packet_list, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000760 break;
761 }
762 case kCodecInternalCng: {
763 // This handles the case when there is no transmission and the decoder
764 // should produce internal comfort noise.
765 // TODO(hlundin): Write test for codec-internal CNG.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000766 DoCodecInternalCng();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000767 break;
768 }
769 case kDtmf: {
770 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000771 return_value = DoDtmf(dtmf_event, &play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000772 break;
773 }
774 case kAlternativePlc: {
775 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000776 DoAlternativePlc(false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000777 break;
778 }
779 case kAlternativePlcIncreaseTimestamp: {
780 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000781 DoAlternativePlc(true);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000782 break;
783 }
784 case kAudioRepetitionIncreaseTimestamp: {
785 // TODO(hlundin): Write test for this.
786 sync_buffer_->IncreaseEndTimestamp(output_size_samples_);
787 // Skipping break on purpose. Execution should move on into the
788 // next case.
kjellander@webrtc.org7d2b6a92015-01-28 18:37:58 +0000789 FALLTHROUGH();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000790 }
791 case kAudioRepetition: {
792 // TODO(hlundin): Write test for this.
793 // Copy last |output_size_samples_| from |sync_buffer_| to
794 // |algorithm_buffer|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000795 algorithm_buffer_->PushBackFromIndex(
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000796 *sync_buffer_, sync_buffer_->Size() - output_size_samples_);
797 expand_->Reset();
798 break;
799 }
800 case kUndefined: {
801 LOG_F(LS_ERROR) << "Invalid operation kUndefined.";
802 assert(false); // This should not happen.
803 last_mode_ = kModeError;
804 return kInvalidOperation;
805 }
806 } // End of switch.
807 if (return_value < 0) {
808 return return_value;
809 }
810
811 if (last_mode_ != kModeRfc3389Cng) {
812 comfort_noise_->Reset();
813 }
814
815 // Copy from |algorithm_buffer| to |sync_buffer_|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000816 sync_buffer_->PushBack(*algorithm_buffer_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000817
818 // Extract data from |sync_buffer_| to |output|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000819 size_t num_output_samples_per_channel = output_size_samples_;
820 size_t num_output_samples = output_size_samples_ * sync_buffer_->Channels();
821 if (num_output_samples > max_length) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000822 LOG(LS_WARNING) << "Output array is too short. " << max_length << " < " <<
823 output_size_samples_ << " * " << sync_buffer_->Channels();
824 num_output_samples = max_length;
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000825 num_output_samples_per_channel = static_cast<int>(
826 max_length / sync_buffer_->Channels());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000827 }
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000828 int samples_from_sync = static_cast<int>(
829 sync_buffer_->GetNextAudioInterleaved(num_output_samples_per_channel,
830 output));
831 *num_channels = static_cast<int>(sync_buffer_->Channels());
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000832 LOG(LS_VERBOSE) << "Sync buffer (" << *num_channels << " channel(s)):" <<
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000833 " insert " << algorithm_buffer_->Size() << " samples, extract " <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000834 samples_from_sync << " samples";
835 if (samples_from_sync != output_size_samples_) {
836 LOG_F(LS_ERROR) << "samples_from_sync != output_size_samples_";
minyue@webrtc.orgdb1cefc2013-08-13 01:39:21 +0000837 // TODO(minyue): treatment of under-run, filling zeros
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000838 memset(output, 0, num_output_samples * sizeof(int16_t));
839 *samples_per_channel = output_size_samples_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000840 return kSampleUnderrun;
841 }
842 *samples_per_channel = output_size_samples_;
843
844 // Should always have overlap samples left in the |sync_buffer_|.
845 assert(sync_buffer_->FutureLength() >= expand_->overlap_length());
846
847 if (play_dtmf) {
848 return_value = DtmfOverdub(dtmf_event, sync_buffer_->Channels(), output);
849 }
850
851 // Update the background noise parameters if last operation wrote data
852 // straight from the decoder to the |sync_buffer_|. That is, none of the
853 // operations that modify the signal can be followed by a parameter update.
854 if ((last_mode_ == kModeNormal) ||
855 (last_mode_ == kModeAccelerateFail) ||
856 (last_mode_ == kModePreemptiveExpandFail) ||
857 (last_mode_ == kModeRfc3389Cng) ||
858 (last_mode_ == kModeCodecInternalCng)) {
859 background_noise_->Update(*sync_buffer_, *vad_.get());
860 }
861
862 if (operation == kDtmf) {
863 // DTMF data was written the end of |sync_buffer_|.
864 // Update index to end of DTMF data in |sync_buffer_|.
865 sync_buffer_->set_dtmf_index(sync_buffer_->Size());
866 }
867
henrik.lundin@webrtc.orged865b52014-03-06 10:28:07 +0000868 if (last_mode_ != kModeExpand) {
869 // If last operation was not expand, calculate the |playout_timestamp_| from
870 // the |sync_buffer_|. However, do not update the |playout_timestamp_| if it
871 // would be moved "backwards".
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000872 uint32_t temp_timestamp = sync_buffer_->end_timestamp() -
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000873 static_cast<uint32_t>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000874 if (static_cast<int32_t>(temp_timestamp - playout_timestamp_) > 0) {
875 playout_timestamp_ = temp_timestamp;
876 }
877 } else {
878 // Use dead reckoning to estimate the |playout_timestamp_|.
879 playout_timestamp_ += output_size_samples_;
880 }
881
882 if (decode_return_value) return decode_return_value;
883 return return_value;
884}
885
886int NetEqImpl::GetDecision(Operations* operation,
887 PacketList* packet_list,
888 DtmfEvent* dtmf_event,
889 bool* play_dtmf) {
890 // Initialize output variables.
891 *play_dtmf = false;
892 *operation = kUndefined;
893
894 // Increment time counters.
895 packet_buffer_->IncrementWaitingTimes();
896 stats_.IncreaseCounter(output_size_samples_, fs_hz_);
897
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000898 assert(sync_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000899 uint32_t end_timestamp = sync_buffer_->end_timestamp();
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +0000900 if (!new_codec_) {
901 const uint32_t five_seconds_samples = 5 * fs_hz_;
902 packet_buffer_->DiscardOldPackets(end_timestamp, five_seconds_samples);
903 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000904 const RTPHeader* header = packet_buffer_->NextRtpHeader();
905
henrik.lundin@webrtc.orgca8cb952014-03-12 10:26:52 +0000906 if (decision_logic_->CngRfc3389On() || last_mode_ == kModeRfc3389Cng) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000907 // Because of timestamp peculiarities, we have to "manually" disallow using
908 // a CNG packet with the same timestamp as the one that was last played.
909 // This can happen when using redundancy and will cause the timing to shift.
henrik.lundin@webrtc.org24779fe2014-03-14 12:40:05 +0000910 while (header && decoder_database_->IsComfortNoise(header->payloadType) &&
911 (end_timestamp >= header->timestamp ||
912 end_timestamp + decision_logic_->generated_noise_samples() >
913 header->timestamp)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000914 // Don't use this packet, discard it.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000915 if (packet_buffer_->DiscardNextPacket() != PacketBuffer::kOK) {
916 assert(false); // Must be ok by design.
917 }
918 // Check buffer again.
919 if (!new_codec_) {
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +0000920 packet_buffer_->DiscardOldPackets(end_timestamp, 5 * fs_hz_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000921 }
922 header = packet_buffer_->NextRtpHeader();
923 }
924 }
925
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000926 assert(expand_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000927 const int samples_left = static_cast<int>(sync_buffer_->FutureLength() -
928 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000929 if (last_mode_ == kModeAccelerateSuccess ||
930 last_mode_ == kModeAccelerateLowEnergy ||
931 last_mode_ == kModePreemptiveExpandSuccess ||
932 last_mode_ == kModePreemptiveExpandLowEnergy) {
933 // Subtract (samples_left + output_size_samples_) from sampleMemory.
934 decision_logic_->AddSampleMemory(-(samples_left + output_size_samples_));
935 }
936
937 // Check if it is time to play a DTMF event.
938 if (dtmf_buffer_->GetEvent(end_timestamp +
939 decision_logic_->generated_noise_samples(),
940 dtmf_event)) {
941 *play_dtmf = true;
942 }
943
944 // Get instruction.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000945 assert(sync_buffer_.get());
946 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000947 *operation = decision_logic_->GetDecision(*sync_buffer_,
948 *expand_,
949 decoder_frame_length_,
950 header,
951 last_mode_,
952 *play_dtmf,
953 &reset_decoder_);
954
955 // Check if we already have enough samples in the |sync_buffer_|. If so,
956 // change decision to normal, unless the decision was merge, accelerate, or
957 // preemptive expand.
958 if (samples_left >= output_size_samples_ &&
959 *operation != kMerge &&
960 *operation != kAccelerate &&
961 *operation != kPreemptiveExpand) {
962 *operation = kNormal;
963 return 0;
964 }
965
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000966 decision_logic_->ExpandDecision(*operation);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000967
968 // Check conditions for reset.
969 if (new_codec_ || *operation == kUndefined) {
970 // The only valid reason to get kUndefined is that new_codec_ is set.
971 assert(new_codec_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000972 if (*play_dtmf && !header) {
973 timestamp_ = dtmf_event->timestamp;
974 } else {
975 assert(header);
976 if (!header) {
977 LOG_F(LS_ERROR) << "Packet missing where it shouldn't.";
978 return -1;
979 }
980 timestamp_ = header->timestamp;
981 if (*operation == kRfc3389CngNoPacket
982#ifndef LEGACY_BITEXACT
983 // Without this check, it can happen that a non-CNG packet is sent to
984 // the CNG decoder as if it was a SID frame. This is clearly a bug,
985 // but is kept for now to maintain bit-exactness with the test
986 // vectors.
987 && decoder_database_->IsComfortNoise(header->payloadType)
988#endif
989 ) {
990 // Change decision to CNG packet, since we do have a CNG packet, but it
991 // was considered too early to use. Now, use it anyway.
992 *operation = kRfc3389Cng;
993 } else if (*operation != kRfc3389Cng) {
994 *operation = kNormal;
995 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000996 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000997 // Adjust |sync_buffer_| timestamp before setting |end_timestamp| to the
998 // new value.
999 sync_buffer_->IncreaseEndTimestamp(timestamp_ - end_timestamp);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001000 end_timestamp = timestamp_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001001 new_codec_ = false;
1002 decision_logic_->SoftReset();
1003 buffer_level_filter_->Reset();
1004 delay_manager_->Reset();
1005 stats_.ResetMcu();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001006 }
1007
1008 int required_samples = output_size_samples_;
1009 const int samples_10_ms = 80 * fs_mult_;
1010 const int samples_20_ms = 2 * samples_10_ms;
1011 const int samples_30_ms = 3 * samples_10_ms;
1012
1013 switch (*operation) {
1014 case kExpand: {
1015 timestamp_ = end_timestamp;
1016 return 0;
1017 }
1018 case kRfc3389CngNoPacket:
1019 case kCodecInternalCng: {
1020 return 0;
1021 }
1022 case kDtmf: {
1023 // TODO(hlundin): Write test for this.
1024 // Update timestamp.
1025 timestamp_ = end_timestamp;
1026 if (decision_logic_->generated_noise_samples() > 0 &&
1027 last_mode_ != kModeDtmf) {
1028 // Make a jump in timestamp due to the recently played comfort noise.
1029 uint32_t timestamp_jump = decision_logic_->generated_noise_samples();
1030 sync_buffer_->IncreaseEndTimestamp(timestamp_jump);
1031 timestamp_ += timestamp_jump;
1032 }
1033 decision_logic_->set_generated_noise_samples(0);
1034 return 0;
1035 }
1036 case kAccelerate: {
1037 // In order to do a accelerate we need at least 30 ms of audio data.
1038 if (samples_left >= samples_30_ms) {
1039 // Already have enough data, so we do not need to extract any more.
1040 decision_logic_->set_sample_memory(samples_left);
1041 decision_logic_->set_prev_time_scale(true);
1042 return 0;
1043 } else if (samples_left >= samples_10_ms &&
1044 decoder_frame_length_ >= samples_30_ms) {
1045 // Avoid decoding more data as it might overflow the playout buffer.
1046 *operation = kNormal;
1047 return 0;
1048 } else if (samples_left < samples_20_ms &&
1049 decoder_frame_length_ < samples_30_ms) {
1050 // Build up decoded data by decoding at least 20 ms of audio data. Do
1051 // not perform accelerate yet, but wait until we only need to do one
1052 // decoding.
1053 required_samples = 2 * output_size_samples_;
1054 *operation = kNormal;
1055 }
1056 // If none of the above is true, we have one of two possible situations:
1057 // (1) 20 ms <= samples_left < 30 ms and decoder_frame_length_ < 30 ms; or
1058 // (2) samples_left < 10 ms and decoder_frame_length_ >= 30 ms.
1059 // In either case, we move on with the accelerate decision, and decode one
1060 // frame now.
1061 break;
1062 }
1063 case kPreemptiveExpand: {
1064 // In order to do a preemptive expand we need at least 30 ms of decoded
1065 // audio data.
1066 if ((samples_left >= samples_30_ms) ||
1067 (samples_left >= samples_10_ms &&
1068 decoder_frame_length_ >= samples_30_ms)) {
1069 // Already have enough data, so we do not need to extract any more.
1070 // Or, avoid decoding more data as it might overflow the playout buffer.
1071 // Still try preemptive expand, though.
1072 decision_logic_->set_sample_memory(samples_left);
1073 decision_logic_->set_prev_time_scale(true);
1074 return 0;
1075 }
1076 if (samples_left < samples_20_ms &&
1077 decoder_frame_length_ < samples_30_ms) {
1078 // Build up decoded data by decoding at least 20 ms of audio data.
1079 // Still try to perform preemptive expand.
1080 required_samples = 2 * output_size_samples_;
1081 }
1082 // Move on with the preemptive expand decision.
1083 break;
1084 }
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001085 case kMerge: {
1086 required_samples =
1087 std::max(merge_->RequiredFutureSamples(), required_samples);
1088 break;
1089 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001090 default: {
1091 // Do nothing.
1092 }
1093 }
1094
1095 // Get packets from buffer.
1096 int extracted_samples = 0;
1097 if (header &&
1098 *operation != kAlternativePlc &&
1099 *operation != kAlternativePlcIncreaseTimestamp &&
1100 *operation != kAudioRepetition &&
1101 *operation != kAudioRepetitionIncreaseTimestamp) {
1102 sync_buffer_->IncreaseEndTimestamp(header->timestamp - end_timestamp);
1103 if (decision_logic_->CngOff()) {
1104 // Adjustment of timestamp only corresponds to an actual packet loss
1105 // if comfort noise is not played. If comfort noise was just played,
1106 // this adjustment of timestamp is only done to get back in sync with the
1107 // stream timestamp; no loss to report.
1108 stats_.LostSamples(header->timestamp - end_timestamp);
1109 }
1110
1111 if (*operation != kRfc3389Cng) {
1112 // We are about to decode and use a non-CNG packet.
1113 decision_logic_->SetCngOff();
1114 }
1115 // Reset CNG timestamp as a new packet will be delivered.
1116 // (Also if this is a CNG packet, since playedOutTS is updated.)
1117 decision_logic_->set_generated_noise_samples(0);
1118
1119 extracted_samples = ExtractPackets(required_samples, packet_list);
1120 if (extracted_samples < 0) {
1121 LOG_F(LS_WARNING) << "Failed to extract packets from buffer.";
1122 return kPacketBufferCorruption;
1123 }
1124 }
1125
1126 if (*operation == kAccelerate ||
1127 *operation == kPreemptiveExpand) {
1128 decision_logic_->set_sample_memory(samples_left + extracted_samples);
1129 decision_logic_->set_prev_time_scale(true);
1130 }
1131
1132 if (*operation == kAccelerate) {
1133 // Check that we have enough data (30ms) to do accelerate.
1134 if (extracted_samples + samples_left < samples_30_ms) {
1135 // TODO(hlundin): Write test for this.
1136 // Not enough, do normal operation instead.
1137 *operation = kNormal;
1138 }
1139 }
1140
1141 timestamp_ = end_timestamp;
1142 return 0;
1143}
1144
1145int NetEqImpl::Decode(PacketList* packet_list, Operations* operation,
1146 int* decoded_length,
1147 AudioDecoder::SpeechType* speech_type) {
1148 *speech_type = AudioDecoder::kSpeech;
1149 AudioDecoder* decoder = NULL;
1150 if (!packet_list->empty()) {
1151 const Packet* packet = packet_list->front();
pkasting@chromium.org0e81fdf2015-02-02 23:54:03 +00001152 uint8_t payload_type = packet->header.payloadType;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001153 if (!decoder_database_->IsComfortNoise(payload_type)) {
1154 decoder = decoder_database_->GetDecoder(payload_type);
1155 assert(decoder);
1156 if (!decoder) {
pkasting@chromium.org0e81fdf2015-02-02 23:54:03 +00001157 LOG_FERR1(LS_WARNING, GetDecoder, static_cast<int>(payload_type));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001158 PacketBuffer::DeleteAllPackets(packet_list);
1159 return kDecoderNotFound;
1160 }
1161 bool decoder_changed;
1162 decoder_database_->SetActiveDecoder(payload_type, &decoder_changed);
1163 if (decoder_changed) {
1164 // We have a new decoder. Re-init some values.
1165 const DecoderDatabase::DecoderInfo* decoder_info = decoder_database_
1166 ->GetDecoderInfo(payload_type);
1167 assert(decoder_info);
1168 if (!decoder_info) {
pkasting@chromium.org0e81fdf2015-02-02 23:54:03 +00001169 LOG_FERR1(LS_WARNING, GetDecoderInfo, static_cast<int>(payload_type));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001170 PacketBuffer::DeleteAllPackets(packet_list);
1171 return kDecoderNotFound;
1172 }
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001173 // If sampling rate or number of channels has changed, we need to make
1174 // a reset.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001175 if (decoder_info->fs_hz != fs_hz_ ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001176 decoder->Channels() != algorithm_buffer_->Channels()) {
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001177 // TODO(tlegrand): Add unittest to cover this event.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001178 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->Channels());
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001179 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001180 sync_buffer_->set_end_timestamp(timestamp_);
1181 playout_timestamp_ = timestamp_;
1182 }
1183 }
1184 }
1185
1186 if (reset_decoder_) {
1187 // TODO(hlundin): Write test for this.
1188 // Reset decoder.
1189 if (decoder) {
1190 decoder->Init();
1191 }
1192 // Reset comfort noise decoder.
1193 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
1194 if (cng_decoder) {
1195 cng_decoder->Init();
1196 }
1197 reset_decoder_ = false;
1198 }
1199
1200#ifdef LEGACY_BITEXACT
1201 // Due to a bug in old SignalMCU, it could happen that CNG operation was
1202 // decided, but a speech packet was provided. The speech packet will be used
1203 // to update the comfort noise decoder, as if it was a SID frame, which is
1204 // clearly wrong.
1205 if (*operation == kRfc3389Cng) {
1206 return 0;
1207 }
1208#endif
1209
1210 *decoded_length = 0;
1211 // Update codec-internal PLC state.
1212 if ((*operation == kMerge) && decoder && decoder->HasDecodePlc()) {
1213 decoder->DecodePlc(1, &decoded_buffer_[*decoded_length]);
1214 }
1215
1216 int return_value = DecodeLoop(packet_list, operation, decoder,
1217 decoded_length, speech_type);
1218
1219 if (*decoded_length < 0) {
1220 // Error returned from the decoder.
1221 *decoded_length = 0;
1222 sync_buffer_->IncreaseEndTimestamp(decoder_frame_length_);
1223 int error_code = 0;
1224 if (decoder)
1225 error_code = decoder->ErrorCode();
1226 if (error_code != 0) {
1227 // Got some error code from the decoder.
1228 decoder_error_code_ = error_code;
1229 return_value = kDecoderErrorCode;
1230 } else {
1231 // Decoder does not implement error codes. Return generic error.
1232 return_value = kOtherDecoderError;
1233 }
1234 LOG_FERR2(LS_WARNING, DecodeLoop, error_code, packet_list->size());
1235 *operation = kExpand; // Do expansion to get data instead.
1236 }
1237 if (*speech_type != AudioDecoder::kComfortNoise) {
1238 // Don't increment timestamp if codec returned CNG speech type
1239 // since in this case, the we will increment the CNGplayedTS counter.
1240 // Increase with number of samples per channel.
1241 assert(*decoded_length == 0 ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001242 (decoder && decoder->Channels() == sync_buffer_->Channels()));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001243 sync_buffer_->IncreaseEndTimestamp(
1244 *decoded_length / static_cast<int>(sync_buffer_->Channels()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001245 }
1246 return return_value;
1247}
1248
1249int NetEqImpl::DecodeLoop(PacketList* packet_list, Operations* operation,
1250 AudioDecoder* decoder, int* decoded_length,
1251 AudioDecoder::SpeechType* speech_type) {
1252 Packet* packet = NULL;
1253 if (!packet_list->empty()) {
1254 packet = packet_list->front();
1255 }
1256 // Do decoding.
1257 while (packet &&
1258 !decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1259 assert(decoder); // At this point, we must have a decoder object.
1260 // The number of channels in the |sync_buffer_| should be the same as the
1261 // number decoder channels.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001262 assert(sync_buffer_->Channels() == decoder->Channels());
1263 assert(decoded_buffer_length_ >= kMaxFrameSize * decoder->Channels());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001264 assert(*operation == kNormal || *operation == kAccelerate ||
1265 *operation == kMerge || *operation == kPreemptiveExpand);
1266 packet_list->pop_front();
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001267 size_t payload_length = packet->payload_length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001268 int16_t decode_length;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +00001269 if (packet->sync_packet) {
1270 // Decode to silence with the same frame size as the last decode.
1271 LOG(LS_VERBOSE) << "Decoding sync-packet: " <<
1272 " ts=" << packet->header.timestamp <<
1273 ", sn=" << packet->header.sequenceNumber <<
1274 ", pt=" << static_cast<int>(packet->header.payloadType) <<
1275 ", ssrc=" << packet->header.ssrc <<
1276 ", len=" << packet->payload_length;
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001277 memset(&decoded_buffer_[*decoded_length], 0,
1278 decoder_frame_length_ * decoder->Channels() *
1279 sizeof(decoded_buffer_[0]));
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +00001280 decode_length = decoder_frame_length_;
1281 } else if (!packet->primary) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001282 // This is a redundant payload; call the special decoder method.
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +00001283 LOG(LS_VERBOSE) << "Decoding packet (redundant):" <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001284 " ts=" << packet->header.timestamp <<
1285 ", sn=" << packet->header.sequenceNumber <<
1286 ", pt=" << static_cast<int>(packet->header.payloadType) <<
1287 ", ssrc=" << packet->header.ssrc <<
1288 ", len=" << packet->payload_length;
1289 decode_length = decoder->DecodeRedundant(
henrik.lundin@webrtc.org1eda4e32015-02-25 10:02:29 +00001290 packet->payload, packet->payload_length, fs_hz_,
minyue@webrtc.org7f7d7e32015-03-16 12:30:37 +00001291 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001292 &decoded_buffer_[*decoded_length], speech_type);
1293 } else {
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +00001294 LOG(LS_VERBOSE) << "Decoding packet: ts=" << packet->header.timestamp <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001295 ", sn=" << packet->header.sequenceNumber <<
1296 ", pt=" << static_cast<int>(packet->header.payloadType) <<
1297 ", ssrc=" << packet->header.ssrc <<
1298 ", len=" << packet->payload_length;
henrik.lundin@webrtc.org1eda4e32015-02-25 10:02:29 +00001299 decode_length =
minyue@webrtc.org7f7d7e32015-03-16 12:30:37 +00001300 decoder->Decode(
1301 packet->payload, packet->payload_length, fs_hz_,
1302 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1303 &decoded_buffer_[*decoded_length], speech_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001304 }
1305
1306 delete[] packet->payload;
1307 delete packet;
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001308 packet = NULL;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001309 if (decode_length > 0) {
1310 *decoded_length += decode_length;
1311 // Update |decoder_frame_length_| with number of samples per channel.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001312 decoder_frame_length_ =
1313 decode_length / static_cast<int>(decoder->Channels());
1314 LOG(LS_VERBOSE) << "Decoded " << decode_length << " samples ("
1315 << decoder->Channels() << " channel(s) -> "
1316 << decoder_frame_length_ << " samples per channel)";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001317 } else if (decode_length < 0) {
1318 // Error.
henrik.lundin@webrtc.org63464a92013-01-30 09:41:56 +00001319 LOG_FERR2(LS_WARNING, Decode, decode_length, payload_length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001320 *decoded_length = -1;
1321 PacketBuffer::DeleteAllPackets(packet_list);
1322 break;
1323 }
1324 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1325 // Guard against overflow.
1326 LOG_F(LS_WARNING) << "Decoded too much.";
1327 PacketBuffer::DeleteAllPackets(packet_list);
1328 return kDecodedTooMuch;
1329 }
1330 if (!packet_list->empty()) {
1331 packet = packet_list->front();
1332 } else {
1333 packet = NULL;
1334 }
1335 } // End of decode loop.
1336
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001337 // If the list is not empty at this point, either a decoding error terminated
1338 // the while-loop, or list must hold exactly one CNG packet.
1339 assert(packet_list->empty() || *decoded_length < 0 ||
1340 (packet_list->size() == 1 && packet &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001341 decoder_database_->IsComfortNoise(packet->header.payloadType)));
1342 return 0;
1343}
1344
1345void NetEqImpl::DoNormal(const int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001346 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001347 assert(normal_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001348 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001349 normal_->Process(decoded_buffer, decoded_length, last_mode_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001350 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001351 if (decoded_length != 0) {
1352 last_mode_ = kModeNormal;
1353 }
1354
1355 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1356 if ((speech_type == AudioDecoder::kComfortNoise)
1357 || ((last_mode_ == kModeCodecInternalCng)
1358 && (decoded_length == 0))) {
1359 // TODO(hlundin): Remove second part of || statement above.
1360 last_mode_ = kModeCodecInternalCng;
1361 }
1362
1363 if (!play_dtmf) {
1364 dtmf_tone_generator_->Reset();
1365 }
1366}
1367
1368void NetEqImpl::DoMerge(int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001369 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001370 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001371 assert(merge_.get());
1372 int new_length = merge_->Process(decoded_buffer, decoded_length,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001373 mute_factor_array_.get(),
1374 algorithm_buffer_.get());
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001375 int expand_length_correction = new_length -
1376 static_cast<int>(decoded_length / algorithm_buffer_->Channels());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001377
1378 // Update in-call and post-call statistics.
1379 if (expand_->MuteFactor(0) == 0) {
1380 // Expand generates only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001381 stats_.ExpandedNoiseSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001382 } else {
1383 // Expansion generates more than only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001384 stats_.ExpandedVoiceSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001385 }
1386
1387 last_mode_ = kModeMerge;
1388 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1389 if (speech_type == AudioDecoder::kComfortNoise) {
1390 last_mode_ = kModeCodecInternalCng;
1391 }
1392 expand_->Reset();
1393 if (!play_dtmf) {
1394 dtmf_tone_generator_->Reset();
1395 }
1396}
1397
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001398int NetEqImpl::DoExpand(bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001399 while ((sync_buffer_->FutureLength() - expand_->overlap_length()) <
1400 static_cast<size_t>(output_size_samples_)) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001401 algorithm_buffer_->Clear();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001402 int return_value = expand_->Process(algorithm_buffer_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001403 int length = static_cast<int>(algorithm_buffer_->Size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001404
1405 // Update in-call and post-call statistics.
1406 if (expand_->MuteFactor(0) == 0) {
1407 // Expand operation generates only noise.
1408 stats_.ExpandedNoiseSamples(length);
1409 } else {
1410 // Expand operation generates more than only noise.
1411 stats_.ExpandedVoiceSamples(length);
1412 }
1413
1414 last_mode_ = kModeExpand;
1415
1416 if (return_value < 0) {
1417 return return_value;
1418 }
1419
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001420 sync_buffer_->PushBack(*algorithm_buffer_);
1421 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001422 }
1423 if (!play_dtmf) {
1424 dtmf_tone_generator_->Reset();
1425 }
1426 return 0;
1427}
1428
1429int NetEqImpl::DoAccelerate(int16_t* decoded_buffer, size_t decoded_length,
1430 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001431 bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001432 const size_t required_samples = 240 * fs_mult_; // Must have 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001433 size_t borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001434 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001435 size_t decoded_length_per_channel = decoded_length / num_channels;
1436 if (decoded_length_per_channel < required_samples) {
1437 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001438 borrowed_samples_per_channel = static_cast<int>(required_samples -
1439 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001440 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1441 decoded_buffer,
1442 sizeof(int16_t) * decoded_length);
1443 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1444 decoded_buffer);
1445 decoded_length = required_samples * num_channels;
1446 }
1447
1448 int16_t samples_removed;
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001449 Accelerate::ReturnCodes return_code = accelerate_->Process(
1450 decoded_buffer, decoded_length, algorithm_buffer_.get(),
1451 &samples_removed);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001452 stats_.AcceleratedSamples(samples_removed);
1453 switch (return_code) {
1454 case Accelerate::kSuccess:
1455 last_mode_ = kModeAccelerateSuccess;
1456 break;
1457 case Accelerate::kSuccessLowEnergy:
1458 last_mode_ = kModeAccelerateLowEnergy;
1459 break;
1460 case Accelerate::kNoStretch:
1461 last_mode_ = kModeAccelerateFail;
1462 break;
1463 case Accelerate::kError:
1464 // TODO(hlundin): Map to kModeError instead?
1465 last_mode_ = kModeAccelerateFail;
1466 return kAccelerateError;
1467 }
1468
1469 if (borrowed_samples_per_channel > 0) {
1470 // Copy borrowed samples back to the |sync_buffer_|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001471 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001472 if (length < borrowed_samples_per_channel) {
1473 // This destroys the beginning of the buffer, but will not cause any
1474 // problems.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001475 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001476 sync_buffer_->Size() -
1477 borrowed_samples_per_channel);
1478 sync_buffer_->PushFrontZeros(borrowed_samples_per_channel - length);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001479 algorithm_buffer_->PopFront(length);
1480 assert(algorithm_buffer_->Empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001481 } else {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001482 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001483 borrowed_samples_per_channel,
1484 sync_buffer_->Size() -
1485 borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001486 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001487 }
1488 }
1489
1490 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1491 if (speech_type == AudioDecoder::kComfortNoise) {
1492 last_mode_ = kModeCodecInternalCng;
1493 }
1494 if (!play_dtmf) {
1495 dtmf_tone_generator_->Reset();
1496 }
1497 expand_->Reset();
1498 return 0;
1499}
1500
1501int NetEqImpl::DoPreemptiveExpand(int16_t* decoded_buffer,
1502 size_t decoded_length,
1503 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001504 bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001505 const size_t required_samples = 240 * fs_mult_; // Must have 30 ms.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001506 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001507 int borrowed_samples_per_channel = 0;
1508 int old_borrowed_samples_per_channel = 0;
1509 size_t decoded_length_per_channel = decoded_length / num_channels;
1510 if (decoded_length_per_channel < required_samples) {
1511 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001512 borrowed_samples_per_channel = static_cast<int>(required_samples -
1513 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001514 // Calculate how many of these were already played out.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001515 old_borrowed_samples_per_channel = static_cast<int>(
1516 borrowed_samples_per_channel - sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001517 old_borrowed_samples_per_channel = std::max(
1518 0, old_borrowed_samples_per_channel);
1519 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1520 decoded_buffer,
1521 sizeof(int16_t) * decoded_length);
1522 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1523 decoded_buffer);
1524 decoded_length = required_samples * num_channels;
1525 }
1526
1527 int16_t samples_added;
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001528 PreemptiveExpand::ReturnCodes return_code = preemptive_expand_->Process(
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001529 decoded_buffer, static_cast<int>(decoded_length),
1530 old_borrowed_samples_per_channel,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001531 algorithm_buffer_.get(), &samples_added);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001532 stats_.PreemptiveExpandedSamples(samples_added);
1533 switch (return_code) {
1534 case PreemptiveExpand::kSuccess:
1535 last_mode_ = kModePreemptiveExpandSuccess;
1536 break;
1537 case PreemptiveExpand::kSuccessLowEnergy:
1538 last_mode_ = kModePreemptiveExpandLowEnergy;
1539 break;
1540 case PreemptiveExpand::kNoStretch:
1541 last_mode_ = kModePreemptiveExpandFail;
1542 break;
1543 case PreemptiveExpand::kError:
1544 // TODO(hlundin): Map to kModeError instead?
1545 last_mode_ = kModePreemptiveExpandFail;
1546 return kPreemptiveExpandError;
1547 }
1548
1549 if (borrowed_samples_per_channel > 0) {
1550 // Copy borrowed samples back to the |sync_buffer_|.
1551 sync_buffer_->ReplaceAtIndex(
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001552 *algorithm_buffer_, borrowed_samples_per_channel,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001553 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001554 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001555 }
1556
1557 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1558 if (speech_type == AudioDecoder::kComfortNoise) {
1559 last_mode_ = kModeCodecInternalCng;
1560 }
1561 if (!play_dtmf) {
1562 dtmf_tone_generator_->Reset();
1563 }
1564 expand_->Reset();
1565 return 0;
1566}
1567
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001568int NetEqImpl::DoRfc3389Cng(PacketList* packet_list, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001569 if (!packet_list->empty()) {
1570 // Must have exactly one SID frame at this point.
1571 assert(packet_list->size() == 1);
1572 Packet* packet = packet_list->front();
1573 packet_list->pop_front();
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001574 if (!decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1575#ifdef LEGACY_BITEXACT
1576 // This can happen due to a bug in GetDecision. Change the payload type
1577 // to a CNG type, and move on. Note that this means that we are in fact
1578 // sending a non-CNG payload to the comfort noise decoder for decoding.
1579 // Clearly wrong, but will maintain bit-exactness with legacy.
1580 if (fs_hz_ == 8000) {
1581 packet->header.payloadType =
1582 decoder_database_->GetRtpPayloadType(kDecoderCNGnb);
1583 } else if (fs_hz_ == 16000) {
1584 packet->header.payloadType =
1585 decoder_database_->GetRtpPayloadType(kDecoderCNGwb);
1586 } else if (fs_hz_ == 32000) {
1587 packet->header.payloadType =
1588 decoder_database_->GetRtpPayloadType(kDecoderCNGswb32kHz);
1589 } else if (fs_hz_ == 48000) {
1590 packet->header.payloadType =
1591 decoder_database_->GetRtpPayloadType(kDecoderCNGswb48kHz);
1592 }
1593 assert(decoder_database_->IsComfortNoise(packet->header.payloadType));
1594#else
1595 LOG(LS_ERROR) << "Trying to decode non-CNG payload as CNG.";
1596 return kOtherError;
1597#endif
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001598 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001599 // UpdateParameters() deletes |packet|.
1600 if (comfort_noise_->UpdateParameters(packet) ==
1601 ComfortNoise::kInternalError) {
1602 LOG_FERR0(LS_WARNING, UpdateParameters);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001603 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001604 return -comfort_noise_->internal_error_code();
1605 }
1606 }
1607 int cn_return = comfort_noise_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001608 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001609 expand_->Reset();
1610 last_mode_ = kModeRfc3389Cng;
1611 if (!play_dtmf) {
1612 dtmf_tone_generator_->Reset();
1613 }
1614 if (cn_return == ComfortNoise::kInternalError) {
1615 LOG_FERR1(LS_WARNING, comfort_noise_->Generate, cn_return);
1616 decoder_error_code_ = comfort_noise_->internal_error_code();
1617 return kComfortNoiseErrorCode;
1618 } else if (cn_return == ComfortNoise::kUnknownPayloadType) {
1619 LOG_FERR1(LS_WARNING, comfort_noise_->Generate, cn_return);
1620 return kUnknownRtpPayloadType;
1621 }
1622 return 0;
1623}
1624
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001625void NetEqImpl::DoCodecInternalCng() {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001626 int length = 0;
1627 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1628 int16_t decoded_buffer[kMaxFrameSize];
1629 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1630 if (decoder) {
1631 const uint8_t* dummy_payload = NULL;
1632 AudioDecoder::SpeechType speech_type;
minyue@webrtc.org7f7d7e32015-03-16 12:30:37 +00001633 length = decoder->Decode(
1634 dummy_payload, 0, fs_hz_, kMaxFrameSize * sizeof(int16_t),
1635 decoded_buffer, &speech_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001636 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001637 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001638 normal_->Process(decoded_buffer, length, last_mode_, mute_factor_array_.get(),
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001639 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001640 last_mode_ = kModeCodecInternalCng;
1641 expand_->Reset();
1642}
1643
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001644int NetEqImpl::DoDtmf(const DtmfEvent& dtmf_event, bool* play_dtmf) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001645 // This block of the code and the block further down, handling |dtmf_switch|
1646 // are commented out. Otherwise playing out-of-band DTMF would fail in VoE
1647 // test, DtmfTest.ManualSuccessfullySendsOutOfBandTelephoneEvents. This is
1648 // equivalent to |dtmf_switch| always be false.
1649 //
1650 // See http://webrtc-codereview.appspot.com/1195004/ for discussion
1651 // On this issue. This change might cause some glitches at the point of
1652 // switch from audio to DTMF. Issue 1545 is filed to track this.
1653 //
1654 // bool dtmf_switch = false;
1655 // if ((last_mode_ != kModeDtmf) && dtmf_tone_generator_->initialized()) {
1656 // // Special case; see below.
1657 // // We must catch this before calling Generate, since |initialized| is
1658 // // modified in that call.
1659 // dtmf_switch = true;
1660 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001661
1662 int dtmf_return_value = 0;
1663 if (!dtmf_tone_generator_->initialized()) {
1664 // Initialize if not already done.
1665 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1666 dtmf_event.volume);
1667 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001668
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001669 if (dtmf_return_value == 0) {
1670 // Generate DTMF signal.
1671 dtmf_return_value = dtmf_tone_generator_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001672 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001673 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001674
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001675 if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001676 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001677 return dtmf_return_value;
1678 }
1679
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001680 // if (dtmf_switch) {
1681 // // This is the special case where the previous operation was DTMF
1682 // // overdub, but the current instruction is "regular" DTMF. We must make
1683 // // sure that the DTMF does not have any discontinuities. The first DTMF
1684 // // sample that we generate now must be played out immediately, therefore
1685 // // it must be copied to the speech buffer.
1686 // // TODO(hlundin): This code seems incorrect. (Legacy.) Write test and
1687 // // verify correct operation.
1688 // assert(false);
1689 // // Must generate enough data to replace all of the |sync_buffer_|
1690 // // "future".
1691 // int required_length = sync_buffer_->FutureLength();
1692 // assert(dtmf_tone_generator_->initialized());
1693 // dtmf_return_value = dtmf_tone_generator_->Generate(required_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001694 // algorithm_buffer_);
1695 // assert((size_t) required_length == algorithm_buffer_->Size());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001696 // if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001697 // algorithm_buffer_->Zeros(output_size_samples_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001698 // return dtmf_return_value;
1699 // }
1700 //
1701 // // Overwrite the "future" part of the speech buffer with the new DTMF
1702 // // data.
1703 // // TODO(hlundin): It seems that this overwriting has gone lost.
1704 // // Not adapted for multi-channel yet.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001705 // assert(algorithm_buffer_->Channels() == 1);
1706 // if (algorithm_buffer_->Channels() != 1) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001707 // LOG(LS_WARNING) << "DTMF not supported for more than one channel";
1708 // return kStereoNotSupported;
1709 // }
1710 // // Shuffle the remaining data to the beginning of algorithm buffer.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001711 // algorithm_buffer_->PopFront(sync_buffer_->FutureLength());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001712 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001713
1714 sync_buffer_->IncreaseEndTimestamp(output_size_samples_);
1715 expand_->Reset();
1716 last_mode_ = kModeDtmf;
1717
1718 // Set to false because the DTMF is already in the algorithm buffer.
1719 *play_dtmf = false;
1720 return 0;
1721}
1722
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001723void NetEqImpl::DoAlternativePlc(bool increase_timestamp) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001724 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1725 int length;
1726 if (decoder && decoder->HasDecodePlc()) {
1727 // Use the decoder's packet-loss concealment.
1728 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1729 int16_t decoded_buffer[kMaxFrameSize];
1730 length = decoder->DecodePlc(1, decoded_buffer);
1731 if (length > 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001732 algorithm_buffer_->PushBackInterleaved(decoded_buffer, length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001733 } else {
1734 length = 0;
1735 }
1736 } else {
1737 // Do simple zero-stuffing.
1738 length = output_size_samples_;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001739 algorithm_buffer_->Zeros(length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001740 // By not advancing the timestamp, NetEq inserts samples.
1741 stats_.AddZeros(length);
1742 }
1743 if (increase_timestamp) {
1744 sync_buffer_->IncreaseEndTimestamp(length);
1745 }
1746 expand_->Reset();
1747}
1748
1749int NetEqImpl::DtmfOverdub(const DtmfEvent& dtmf_event, size_t num_channels,
1750 int16_t* output) const {
1751 size_t out_index = 0;
1752 int overdub_length = output_size_samples_; // Default value.
1753
1754 if (sync_buffer_->dtmf_index() > sync_buffer_->next_index()) {
1755 // Special operation for transition from "DTMF only" to "DTMF overdub".
1756 out_index = std::min(
1757 sync_buffer_->dtmf_index() - sync_buffer_->next_index(),
1758 static_cast<size_t>(output_size_samples_));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001759 overdub_length = output_size_samples_ - static_cast<int>(out_index);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001760 }
1761
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001762 AudioMultiVector dtmf_output(num_channels);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001763 int dtmf_return_value = 0;
1764 if (!dtmf_tone_generator_->initialized()) {
1765 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1766 dtmf_event.volume);
1767 }
1768 if (dtmf_return_value == 0) {
1769 dtmf_return_value = dtmf_tone_generator_->Generate(overdub_length,
1770 &dtmf_output);
1771 assert((size_t) overdub_length == dtmf_output.Size());
1772 }
1773 dtmf_output.ReadInterleaved(overdub_length, &output[out_index]);
1774 return dtmf_return_value < 0 ? dtmf_return_value : 0;
1775}
1776
1777int NetEqImpl::ExtractPackets(int required_samples, PacketList* packet_list) {
1778 bool first_packet = true;
1779 uint8_t prev_payload_type = 0;
1780 uint32_t prev_timestamp = 0;
1781 uint16_t prev_sequence_number = 0;
1782 bool next_packet_available = false;
1783
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001784 const RTPHeader* header = packet_buffer_->NextRtpHeader();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001785 assert(header);
1786 if (!header) {
1787 return -1;
1788 }
turaj@webrtc.org7df97062013-08-02 18:07:13 +00001789 uint32_t first_timestamp = header->timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001790 int extracted_samples = 0;
1791
1792 // Packet extraction loop.
1793 do {
1794 timestamp_ = header->timestamp;
1795 int discard_count = 0;
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001796 Packet* packet = packet_buffer_->GetNextPacket(&discard_count);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001797 // |header| may be invalid after the |packet_buffer_| operation.
1798 header = NULL;
1799 if (!packet) {
1800 LOG_FERR1(LS_ERROR, GetNextPacket, discard_count) <<
1801 "Should always be able to extract a packet here";
1802 assert(false); // Should always be able to extract a packet here.
1803 return -1;
1804 }
1805 stats_.PacketsDiscarded(discard_count);
1806 // Store waiting time in ms; packets->waiting_time is in "output blocks".
1807 stats_.StoreWaitingTime(packet->waiting_time * kOutputSizeMs);
1808 assert(packet->payload_length > 0);
1809 packet_list->push_back(packet); // Store packet in list.
1810
1811 if (first_packet) {
1812 first_packet = false;
minyue@webrtc.orgd7301772013-08-29 00:58:14 +00001813 decoded_packet_sequence_number_ = prev_sequence_number =
1814 packet->header.sequenceNumber;
1815 decoded_packet_timestamp_ = prev_timestamp = packet->header.timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001816 prev_payload_type = packet->header.payloadType;
1817 }
1818
1819 // Store number of extracted samples.
1820 int packet_duration = 0;
1821 AudioDecoder* decoder = decoder_database_->GetDecoder(
1822 packet->header.payloadType);
1823 if (decoder) {
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001824 if (packet->sync_packet) {
1825 packet_duration = decoder_frame_length_;
1826 } else {
minyue@webrtc.org2c1bcf22015-02-17 10:17:09 +00001827 if (packet->primary) {
1828 packet_duration = decoder->PacketDuration(packet->payload,
1829 packet->payload_length);
1830 } else {
1831 packet_duration = decoder->
1832 PacketDurationRedundant(packet->payload, packet->payload_length);
1833 stats_.SecondaryDecodedSamples(packet_duration);
1834 }
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001835 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001836 } else {
pkasting@chromium.org026b8922015-01-30 19:53:42 +00001837 LOG_FERR1(LS_WARNING, GetDecoder,
1838 static_cast<int>(packet->header.payloadType))
1839 << "Could not find a decoder for a packet about to be extracted.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001840 assert(false);
1841 }
1842 if (packet_duration <= 0) {
1843 // Decoder did not return a packet duration. Assume that the packet
1844 // contains the same number of samples as the previous one.
1845 packet_duration = decoder_frame_length_;
1846 }
1847 extracted_samples = packet->header.timestamp - first_timestamp +
1848 packet_duration;
1849
1850 // Check what packet is available next.
1851 header = packet_buffer_->NextRtpHeader();
1852 next_packet_available = false;
1853 if (header && prev_payload_type == header->payloadType) {
1854 int16_t seq_no_diff = header->sequenceNumber - prev_sequence_number;
1855 int32_t ts_diff = header->timestamp - prev_timestamp;
1856 if (seq_no_diff == 1 ||
1857 (seq_no_diff == 0 && ts_diff == decoder_frame_length_)) {
1858 // The next sequence number is available, or the next part of a packet
1859 // that was split into pieces upon insertion.
1860 next_packet_available = true;
1861 }
1862 prev_sequence_number = header->sequenceNumber;
1863 }
1864 } while (extracted_samples < required_samples && next_packet_available);
1865
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00001866 if (extracted_samples > 0) {
1867 // Delete old packets only when we are going to decode something. Otherwise,
1868 // we could end up in the situation where we never decode anything, since
1869 // all incoming packets are considered too old but the buffer will also
1870 // never be flooded and flushed.
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001871 packet_buffer_->DiscardAllOldPackets(timestamp_);
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00001872 }
1873
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001874 return extracted_samples;
1875}
1876
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001877void NetEqImpl::UpdatePlcComponents(int fs_hz, size_t channels) {
1878 // Delete objects and create new ones.
1879 expand_.reset(expand_factory_->Create(background_noise_.get(),
1880 sync_buffer_.get(), &random_vector_,
1881 fs_hz, channels));
1882 merge_.reset(new Merge(fs_hz, channels, expand_.get(), sync_buffer_.get()));
1883}
1884
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001885void NetEqImpl::SetSampleRateAndChannels(int fs_hz, size_t channels) {
1886 LOG_API2(fs_hz, channels);
1887 // TODO(hlundin): Change to an enumerator and skip assert.
1888 assert(fs_hz == 8000 || fs_hz == 16000 || fs_hz == 32000 || fs_hz == 48000);
1889 assert(channels > 0);
1890
1891 fs_hz_ = fs_hz;
1892 fs_mult_ = fs_hz / 8000;
1893 output_size_samples_ = kOutputSizeMs * 8 * fs_mult_;
1894 decoder_frame_length_ = 3 * output_size_samples_; // Initialize to 30ms.
1895
1896 last_mode_ = kModeNormal;
1897
1898 // Create a new array of mute factors and set all to 1.
1899 mute_factor_array_.reset(new int16_t[channels]);
1900 for (size_t i = 0; i < channels; ++i) {
1901 mute_factor_array_[i] = 16384; // 1.0 in Q14.
1902 }
1903
1904 // Reset comfort noise decoder, if there is one active.
1905 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
1906 if (cng_decoder) {
1907 cng_decoder->Init();
1908 }
1909
1910 // Reinit post-decode VAD with new sample rate.
1911 assert(vad_.get()); // Cannot be NULL here.
1912 vad_->Init();
1913
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001914 // Delete algorithm buffer and create a new one.
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001915 algorithm_buffer_.reset(new AudioMultiVector(channels));
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001916
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001917 // Delete sync buffer and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001918 sync_buffer_.reset(new SyncBuffer(channels, kSyncBufferSize * fs_mult_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001919
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00001920 // Delete BackgroundNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001921 background_noise_.reset(new BackgroundNoise(channels));
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00001922 background_noise_->set_mode(background_noise_mode_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001923
1924 // Reset random vector.
1925 random_vector_.Reset();
1926
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001927 UpdatePlcComponents(fs_hz, channels);
1928
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001929 // Move index so that we create a small set of future samples (all 0).
1930 sync_buffer_->set_next_index(sync_buffer_->next_index() -
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001931 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001932
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001933 normal_.reset(new Normal(fs_hz, decoder_database_.get(), *background_noise_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001934 expand_.get()));
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +00001935 accelerate_.reset(
1936 accelerate_factory_->Create(fs_hz, channels, *background_noise_));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001937 preemptive_expand_.reset(preemptive_expand_factory_->Create(
1938 fs_hz, channels,
1939 *background_noise_,
1940 static_cast<int>(expand_->overlap_length())));
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001941
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001942 // Delete ComfortNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001943 comfort_noise_.reset(new ComfortNoise(fs_hz, decoder_database_.get(),
1944 sync_buffer_.get()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001945
1946 // Verify that |decoded_buffer_| is long enough.
1947 if (decoded_buffer_length_ < kMaxFrameSize * channels) {
1948 // Reallocate to larger size.
1949 decoded_buffer_length_ = kMaxFrameSize * channels;
1950 decoded_buffer_.reset(new int16_t[decoded_buffer_length_]);
1951 }
1952
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001953 // Create DecisionLogic if it is not created yet, then communicate new sample
1954 // rate and output size to DecisionLogic object.
1955 if (!decision_logic_.get()) {
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00001956 CreateDecisionLogic();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001957 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001958 decision_logic_->SetSampleRate(fs_hz_, output_size_samples_);
1959}
1960
1961NetEqOutputType NetEqImpl::LastOutputType() {
1962 assert(vad_.get());
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001963 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001964 if (last_mode_ == kModeCodecInternalCng || last_mode_ == kModeRfc3389Cng) {
1965 return kOutputCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001966 } else if (last_mode_ == kModeExpand && expand_->MuteFactor(0) == 0) {
1967 // Expand mode has faded down to background noise only (very long expand).
1968 return kOutputPLCtoCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001969 } else if (last_mode_ == kModeExpand) {
1970 return kOutputPLC;
wu@webrtc.org24301a62013-12-13 19:17:43 +00001971 } else if (vad_->running() && !vad_->active_speech()) {
1972 return kOutputVADPassive;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001973 } else {
1974 return kOutputNormal;
1975 }
1976}
1977
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00001978void NetEqImpl::CreateDecisionLogic() {
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001979 decision_logic_.reset(DecisionLogic::Create(fs_hz_, output_size_samples_,
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00001980 playout_mode_,
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001981 decoder_database_.get(),
1982 *packet_buffer_.get(),
1983 delay_manager_.get(),
1984 buffer_level_filter_.get()));
1985}
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001986} // namespace webrtc