blob: fe078fd89052f1bcef056fd39ff1c99633db062f [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 Lundin905495c2015-05-25 16:58:41 +020097 LOG(LS_INFO) << "NetEq config: " << config.ToString();
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +000098 int fs = config.sample_rate_hz;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000099 if (fs != 8000 && fs != 16000 && fs != 32000 && fs != 48000) {
100 LOG(LS_ERROR) << "Sample rate " << fs << " Hz not supported. " <<
101 "Changing to 8000 Hz.";
102 fs = 8000;
103 }
andrew@webrtc.org0569d932014-04-09 17:48:48 +0000104 LOG(LS_VERBOSE) << "Create NetEqImpl object with fs = " << fs << ".";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000105 fs_hz_ = fs;
106 fs_mult_ = fs / 8000;
107 output_size_samples_ = kOutputSizeMs * 8 * fs_mult_;
108 decoder_frame_length_ = 3 * output_size_samples_;
109 WebRtcSpl_Init();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000110 if (create_components) {
111 SetSampleRateAndChannels(fs, 1); // Default is 1 channel.
112 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000113}
114
115NetEqImpl::~NetEqImpl() {
116 LOG(LS_INFO) << "Deleting NetEqImpl object.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000117}
118
119int NetEqImpl::InsertPacket(const WebRtcRTPHeader& rtp_header,
120 const uint8_t* payload,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000121 size_t length_bytes,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000122 uint32_t receive_timestamp) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000123 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000124 LOG(LS_VERBOSE) << "InsertPacket: ts=" << rtp_header.header.timestamp <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000125 ", sn=" << rtp_header.header.sequenceNumber <<
126 ", pt=" << static_cast<int>(rtp_header.header.payloadType) <<
127 ", ssrc=" << rtp_header.header.ssrc <<
128 ", len=" << length_bytes;
129 int error = InsertPacketInternal(rtp_header, payload, length_bytes,
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000130 receive_timestamp, false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000131 if (error != 0) {
132 LOG_FERR1(LS_WARNING, InsertPacketInternal, error);
133 error_code_ = error;
134 return kFail;
135 }
136 return kOK;
137}
138
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000139int NetEqImpl::InsertSyncPacket(const WebRtcRTPHeader& rtp_header,
140 uint32_t receive_timestamp) {
141 CriticalSectionScoped lock(crit_sect_.get());
142 LOG(LS_VERBOSE) << "InsertPacket-Sync: ts="
143 << rtp_header.header.timestamp <<
144 ", sn=" << rtp_header.header.sequenceNumber <<
145 ", pt=" << static_cast<int>(rtp_header.header.payloadType) <<
146 ", ssrc=" << rtp_header.header.ssrc;
147
148 const uint8_t kSyncPayload[] = { 's', 'y', 'n', 'c' };
149 int error = InsertPacketInternal(
150 rtp_header, kSyncPayload, sizeof(kSyncPayload), receive_timestamp, true);
151
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000152 if (error != 0) {
153 LOG_FERR1(LS_WARNING, InsertPacketInternal, error);
154 error_code_ = error;
155 return kFail;
156 }
157 return kOK;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000158}
159
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000160int NetEqImpl::GetAudio(size_t max_length, int16_t* output_audio,
161 int* samples_per_channel, int* num_channels,
162 NetEqOutputType* type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000163 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000164 LOG(LS_VERBOSE) << "GetAudio";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000165 int error = GetAudioInternal(max_length, output_audio, samples_per_channel,
166 num_channels);
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000167 LOG(LS_VERBOSE) << "Produced " << *samples_per_channel <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000168 " samples/channel for " << *num_channels << " channel(s)";
169 if (error != 0) {
170 LOG_FERR1(LS_WARNING, GetAudioInternal, error);
171 error_code_ = error;
172 return kFail;
173 }
174 if (type) {
175 *type = LastOutputType();
176 }
177 return kOK;
178}
179
180int NetEqImpl::RegisterPayloadType(enum NetEqDecoder codec,
181 uint8_t rtp_payload_type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000182 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000183 LOG_API2(static_cast<int>(rtp_payload_type), codec);
184 int ret = decoder_database_->RegisterPayload(rtp_payload_type, codec);
185 if (ret != DecoderDatabase::kOK) {
pkasting@chromium.org026b8922015-01-30 19:53:42 +0000186 LOG_FERR2(LS_WARNING, RegisterPayload, static_cast<int>(rtp_payload_type),
187 codec);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000188 switch (ret) {
189 case DecoderDatabase::kInvalidRtpPayloadType:
190 error_code_ = kInvalidRtpPayloadType;
191 break;
192 case DecoderDatabase::kCodecNotSupported:
193 error_code_ = kCodecNotSupported;
194 break;
195 case DecoderDatabase::kDecoderExists:
196 error_code_ = kDecoderExists;
197 break;
198 default:
199 error_code_ = kOtherError;
200 }
201 return kFail;
202 }
203 return kOK;
204}
205
206int NetEqImpl::RegisterExternalDecoder(AudioDecoder* decoder,
207 enum NetEqDecoder codec,
Karl Wibergd8399e62015-05-25 14:39:56 +0200208 uint8_t rtp_payload_type,
209 int sample_rate_hz) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000210 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000211 LOG_API2(static_cast<int>(rtp_payload_type), codec);
212 if (!decoder) {
213 LOG(LS_ERROR) << "Cannot register external decoder with NULL pointer";
214 assert(false);
215 return kFail;
216 }
217 int ret = decoder_database_->InsertExternal(rtp_payload_type, codec,
218 sample_rate_hz, decoder);
219 if (ret != DecoderDatabase::kOK) {
pkasting@chromium.org026b8922015-01-30 19:53:42 +0000220 LOG_FERR2(LS_WARNING, InsertExternal, static_cast<int>(rtp_payload_type),
221 codec);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000222 switch (ret) {
223 case DecoderDatabase::kInvalidRtpPayloadType:
224 error_code_ = kInvalidRtpPayloadType;
225 break;
226 case DecoderDatabase::kCodecNotSupported:
227 error_code_ = kCodecNotSupported;
228 break;
229 case DecoderDatabase::kDecoderExists:
230 error_code_ = kDecoderExists;
231 break;
232 case DecoderDatabase::kInvalidSampleRate:
233 error_code_ = kInvalidSampleRate;
234 break;
235 case DecoderDatabase::kInvalidPointer:
236 error_code_ = kInvalidPointer;
237 break;
238 default:
239 error_code_ = kOtherError;
240 }
241 return kFail;
242 }
243 return kOK;
244}
245
246int NetEqImpl::RemovePayloadType(uint8_t rtp_payload_type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000247 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000248 LOG_API1(static_cast<int>(rtp_payload_type));
249 int ret = decoder_database_->Remove(rtp_payload_type);
250 if (ret == DecoderDatabase::kOK) {
251 return kOK;
252 } else if (ret == DecoderDatabase::kDecoderNotFound) {
253 error_code_ = kDecoderNotFound;
254 } else {
255 error_code_ = kOtherError;
256 }
pkasting@chromium.org026b8922015-01-30 19:53:42 +0000257 LOG_FERR1(LS_WARNING, Remove, static_cast<int>(rtp_payload_type));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000258 return kFail;
259}
260
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000261bool NetEqImpl::SetMinimumDelay(int delay_ms) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000262 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000263 if (delay_ms >= 0 && delay_ms < 10000) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000264 assert(delay_manager_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000265 return delay_manager_->SetMinimumDelay(delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000266 }
267 return false;
268}
269
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000270bool NetEqImpl::SetMaximumDelay(int delay_ms) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000271 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000272 if (delay_ms >= 0 && delay_ms < 10000) {
273 assert(delay_manager_.get());
274 return delay_manager_->SetMaximumDelay(delay_ms);
275 }
276 return false;
277}
278
279int NetEqImpl::LeastRequiredDelayMs() const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000280 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000281 assert(delay_manager_.get());
282 return delay_manager_->least_required_delay_ms();
283}
284
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200285int NetEqImpl::SetTargetDelay() {
286 return kNotImplemented;
287}
288
289int NetEqImpl::TargetDelay() {
290 return kNotImplemented;
291}
292
293int NetEqImpl::CurrentDelay() {
294 return kNotImplemented;
295}
296
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000297// Deprecated.
298// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000299void NetEqImpl::SetPlayoutMode(NetEqPlayoutMode mode) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000300 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000301 if (mode != playout_mode_) {
302 playout_mode_ = mode;
303 CreateDecisionLogic();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000304 }
305}
306
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000307// Deprecated.
308// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000309NetEqPlayoutMode NetEqImpl::PlayoutMode() const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000310 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000311 return playout_mode_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000312}
313
314int NetEqImpl::NetworkStatistics(NetEqNetworkStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000315 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000316 assert(decoder_database_.get());
317 const int total_samples_in_buffers = packet_buffer_->NumSamplesInBuffer(
318 decoder_database_.get(), decoder_frame_length_) +
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000319 static_cast<int>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000320 assert(delay_manager_.get());
321 assert(decision_logic_.get());
322 stats_.GetNetworkStatistics(fs_hz_, total_samples_in_buffers,
323 decoder_frame_length_, *delay_manager_.get(),
324 *decision_logic_.get(), stats);
325 return 0;
326}
327
328void NetEqImpl::WaitingTimes(std::vector<int>* waiting_times) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000329 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000330 stats_.WaitingTimes(waiting_times);
331}
332
333void NetEqImpl::GetRtcpStatistics(RtcpStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000334 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000335 if (stats) {
336 rtcp_.GetStatistics(false, stats);
337 }
338}
339
340void NetEqImpl::GetRtcpStatisticsNoReset(RtcpStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000341 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000342 if (stats) {
343 rtcp_.GetStatistics(true, stats);
344 }
345}
346
347void NetEqImpl::EnableVad() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000348 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000349 assert(vad_.get());
350 vad_->Enable();
351}
352
353void NetEqImpl::DisableVad() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000354 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000355 assert(vad_.get());
356 vad_->Disable();
357}
358
wu@webrtc.org94454b72014-06-05 20:34:08 +0000359bool NetEqImpl::GetPlayoutTimestamp(uint32_t* timestamp) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000360 CriticalSectionScoped lock(crit_sect_.get());
wu@webrtc.org94454b72014-06-05 20:34:08 +0000361 if (first_packet_) {
362 // We don't have a valid RTP timestamp until we have decoded our first
363 // RTP packet.
364 return false;
365 }
366 *timestamp = timestamp_scaler_->ToExternal(playout_timestamp_);
367 return true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000368}
369
Karl Wiberg7f6c4d42015-04-09 15:44:22 +0200370int NetEqImpl::SetTargetNumberOfChannels() {
371 return kNotImplemented;
372}
373
374int NetEqImpl::SetTargetSampleRate() {
375 return kNotImplemented;
376}
377
henrik.lundin@webrtc.orgb0f4b3d2014-11-04 08:53:10 +0000378int NetEqImpl::LastError() const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000379 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000380 return error_code_;
381}
382
383int NetEqImpl::LastDecoderError() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000384 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000385 return decoder_error_code_;
386}
387
388void NetEqImpl::FlushBuffers() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000389 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000390 LOG_API0();
391 packet_buffer_->Flush();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000392 assert(sync_buffer_.get());
393 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000394 sync_buffer_->Flush();
395 sync_buffer_->set_next_index(sync_buffer_->next_index() -
396 expand_->overlap_length());
397 // Set to wait for new codec.
398 first_packet_ = true;
399}
400
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000401void NetEqImpl::PacketBufferStatistics(int* current_num_packets,
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000402 int* max_num_packets) const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000403 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000404 packet_buffer_->BufferStat(current_num_packets, max_num_packets);
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000405}
406
turaj@webrtc.orgff43c852013-09-25 00:07:27 +0000407int NetEqImpl::DecodedRtpInfo(int* sequence_number, uint32_t* timestamp) const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000408 CriticalSectionScoped lock(crit_sect_.get());
minyue@webrtc.orgd7301772013-08-29 00:58:14 +0000409 if (decoded_packet_sequence_number_ < 0)
410 return -1;
411 *sequence_number = decoded_packet_sequence_number_;
412 *timestamp = decoded_packet_timestamp_;
413 return 0;
414}
415
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000416const SyncBuffer* NetEqImpl::sync_buffer_for_test() const {
417 CriticalSectionScoped lock(crit_sect_.get());
418 return sync_buffer_.get();
419}
420
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000421// Methods below this line are private.
422
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000423int NetEqImpl::InsertPacketInternal(const WebRtcRTPHeader& rtp_header,
424 const uint8_t* payload,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000425 size_t length_bytes,
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000426 uint32_t receive_timestamp,
427 bool is_sync_packet) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000428 if (!payload) {
429 LOG_F(LS_ERROR) << "payload == NULL";
430 return kInvalidPointer;
431 }
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000432 // Sanity checks for sync-packets.
433 if (is_sync_packet) {
434 if (decoder_database_->IsDtmf(rtp_header.header.payloadType) ||
435 decoder_database_->IsRed(rtp_header.header.payloadType) ||
436 decoder_database_->IsComfortNoise(rtp_header.header.payloadType)) {
437 LOG_F(LS_ERROR) << "Sync-packet with an unacceptable payload type "
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000438 << static_cast<int>(rtp_header.header.payloadType);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000439 return kSyncPacketNotAccepted;
440 }
441 if (first_packet_ ||
442 rtp_header.header.payloadType != current_rtp_payload_type_ ||
443 rtp_header.header.ssrc != ssrc_) {
444 // Even if |current_rtp_payload_type_| is 0xFF, sync-packet isn't
445 // accepted.
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000446 LOG_F(LS_ERROR)
447 << "Changing codec, SSRC or first packet with sync-packet.";
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000448 return kSyncPacketNotAccepted;
449 }
450 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000451 PacketList packet_list;
452 RTPHeader main_header;
453 {
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000454 // Convert to Packet.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000455 // Create |packet| within this separate scope, since it should not be used
456 // directly once it's been inserted in the packet list. This way, |packet|
457 // is not defined outside of this block.
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000458 Packet* packet = new Packet;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000459 packet->header.markerBit = false;
460 packet->header.payloadType = rtp_header.header.payloadType;
461 packet->header.sequenceNumber = rtp_header.header.sequenceNumber;
462 packet->header.timestamp = rtp_header.header.timestamp;
463 packet->header.ssrc = rtp_header.header.ssrc;
464 packet->header.numCSRCs = 0;
465 packet->payload_length = length_bytes;
466 packet->primary = true;
467 packet->waiting_time = 0;
468 packet->payload = new uint8_t[packet->payload_length];
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000469 packet->sync_packet = is_sync_packet;
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +0000470 if (!packet->payload) {
471 LOG_F(LS_ERROR) << "Payload pointer is NULL.";
472 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000473 assert(payload); // Already checked above.
474 memcpy(packet->payload, payload, packet->payload_length);
475 // Insert packet in a packet list.
476 packet_list.push_back(packet);
477 // Save main payloads header for later.
478 memcpy(&main_header, &packet->header, sizeof(main_header));
479 }
480
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000481 bool update_sample_rate_and_channels = false;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000482 // Reinitialize NetEq if it's needed (changed SSRC or first call).
483 if ((main_header.ssrc != ssrc_) || first_packet_) {
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000484 // Note: |first_packet_| will be cleared further down in this method, once
485 // the packet has been successfully inserted into the packet buffer.
486
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000487 rtcp_.Init(main_header.sequenceNumber);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000488
489 // Flush the packet buffer and DTMF buffer.
490 packet_buffer_->Flush();
491 dtmf_buffer_->Flush();
492
493 // Store new SSRC.
494 ssrc_ = main_header.ssrc;
495
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000496 // Update audio buffer timestamp.
497 sync_buffer_->IncreaseEndTimestamp(main_header.timestamp - timestamp_);
498
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000499 // Update codecs.
500 timestamp_ = main_header.timestamp;
501 current_rtp_payload_type_ = main_header.payloadType;
502
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000503 // Reset timestamp scaling.
504 timestamp_scaler_->Reset();
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000505
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000506 // Trigger an update of sampling rate and the number of channels.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000507 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000508 }
509
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000510 // Update RTCP statistics, only for regular packets.
511 if (!is_sync_packet)
512 rtcp_.Update(main_header, receive_timestamp);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000513
514 // Check for RED payload type, and separate payloads into several packets.
515 if (decoder_database_->IsRed(main_header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000516 assert(!is_sync_packet); // We had a sanity check for this.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000517 if (payload_splitter_->SplitRed(&packet_list) != PayloadSplitter::kOK) {
518 LOG_FERR1(LS_WARNING, SplitRed, packet_list.size());
519 PacketBuffer::DeleteAllPackets(&packet_list);
520 return kRedundancySplitError;
521 }
522 // Only accept a few RED payloads of the same type as the main data,
523 // DTMF events and CNG.
524 payload_splitter_->CheckRedPayloads(&packet_list, *decoder_database_);
525 // Update the stored main payload header since the main payload has now
526 // changed.
527 memcpy(&main_header, &packet_list.front()->header, sizeof(main_header));
528 }
529
530 // Check payload types.
531 if (decoder_database_->CheckPayloadTypes(packet_list) ==
532 DecoderDatabase::kDecoderNotFound) {
533 LOG_FERR1(LS_WARNING, CheckPayloadTypes, packet_list.size());
534 PacketBuffer::DeleteAllPackets(&packet_list);
535 return kUnknownRtpPayloadType;
536 }
537
538 // Scale timestamp to internal domain (only for some codecs).
539 timestamp_scaler_->ToInternal(&packet_list);
540
541 // Process DTMF payloads. Cycle through the list of packets, and pick out any
542 // DTMF payloads found.
543 PacketList::iterator it = packet_list.begin();
544 while (it != packet_list.end()) {
545 Packet* current_packet = (*it);
546 assert(current_packet);
547 assert(current_packet->payload);
548 if (decoder_database_->IsDtmf(current_packet->header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000549 assert(!current_packet->sync_packet); // We had a sanity check for this.
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000550 DtmfEvent event;
551 int ret = DtmfBuffer::ParseEvent(
552 current_packet->header.timestamp,
553 current_packet->payload,
554 current_packet->payload_length,
555 &event);
556 if (ret != DtmfBuffer::kOK) {
557 LOG_FERR2(LS_WARNING, ParseEvent, ret,
558 current_packet->payload_length);
559 PacketBuffer::DeleteAllPackets(&packet_list);
560 return kDtmfParsingError;
561 }
562 if (dtmf_buffer_->InsertEvent(event) != DtmfBuffer::kOK) {
563 LOG_FERR0(LS_WARNING, InsertEvent);
564 PacketBuffer::DeleteAllPackets(&packet_list);
565 return kDtmfInsertError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000566 }
567 // TODO(hlundin): Let the destructor of Packet handle the payload.
568 delete [] current_packet->payload;
569 delete current_packet;
570 it = packet_list.erase(it);
571 } else {
572 ++it;
573 }
574 }
575
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000576 // Check for FEC in packets, and separate payloads into several packets.
577 int ret = payload_splitter_->SplitFec(&packet_list, decoder_database_.get());
578 if (ret != PayloadSplitter::kOK) {
579 LOG_FERR1(LS_WARNING, SplitFec, packet_list.size());
580 PacketBuffer::DeleteAllPackets(&packet_list);
581 switch (ret) {
582 case PayloadSplitter::kUnknownPayloadType:
583 return kUnknownRtpPayloadType;
584 default:
585 return kOtherError;
586 }
587 }
588
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000589 // Split payloads into smaller chunks. This also verifies that all payloads
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000590 // are of a known payload type. SplitAudio() method is protected against
591 // sync-packets.
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +0000592 ret = payload_splitter_->SplitAudio(&packet_list, *decoder_database_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000593 if (ret != PayloadSplitter::kOK) {
594 LOG_FERR1(LS_WARNING, SplitAudio, packet_list.size());
595 PacketBuffer::DeleteAllPackets(&packet_list);
596 switch (ret) {
597 case PayloadSplitter::kUnknownPayloadType:
598 return kUnknownRtpPayloadType;
599 case PayloadSplitter::kFrameSplitError:
600 return kFrameSplitError;
601 default:
602 return kOtherError;
603 }
604 }
605
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000606 // Update bandwidth estimate, if the packet is not sync-packet.
607 if (!packet_list.empty() && !packet_list.front()->sync_packet) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000608 // The list can be empty here if we got nothing but DTMF payloads.
609 AudioDecoder* decoder =
610 decoder_database_->GetDecoder(main_header.payloadType);
611 assert(decoder); // Should always get a valid object, since we have
612 // already checked that the payload types are known.
613 decoder->IncomingPacket(packet_list.front()->payload,
614 packet_list.front()->payload_length,
615 packet_list.front()->header.sequenceNumber,
616 packet_list.front()->header.timestamp,
617 receive_timestamp);
618 }
619
620 // Insert packets in buffer.
621 int temp_bufsize = packet_buffer_->NumPacketsInBuffer();
622 ret = packet_buffer_->InsertPacketList(
623 &packet_list,
624 *decoder_database_,
625 &current_rtp_payload_type_,
626 &current_cng_rtp_payload_type_);
627 if (ret == PacketBuffer::kFlushed) {
628 // Reset DSP timestamp etc. if packet buffer flushed.
629 new_codec_ = true;
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000630 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000631 LOG_F(LS_WARNING) << "Packet buffer flushed";
632 } else if (ret != PacketBuffer::kOK) {
633 LOG_FERR1(LS_WARNING, InsertPacketList, packet_list.size());
634 PacketBuffer::DeleteAllPackets(&packet_list);
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000635 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000636 }
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000637
638 if (first_packet_) {
639 first_packet_ = false;
640 // Update the codec on the next GetAudio call.
641 new_codec_ = true;
642 }
643
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000644 if (current_rtp_payload_type_ != 0xFF) {
645 const DecoderDatabase::DecoderInfo* dec_info =
646 decoder_database_->GetDecoderInfo(current_rtp_payload_type_);
647 if (!dec_info) {
648 assert(false); // Already checked that the payload type is known.
649 }
650 }
651
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000652 if (update_sample_rate_and_channels && !packet_buffer_->Empty()) {
653 // We do not use |current_rtp_payload_type_| to |set payload_type|, but
654 // get the next RTP header from |packet_buffer_| to obtain the payload type.
655 // The reason for it is the following corner case. If NetEq receives a
656 // CNG packet with a sample rate different than the current CNG then it
657 // flushes its buffer, assuming send codec must have been changed. However,
658 // payload type of the hypothetically new send codec is not known.
659 const RTPHeader* rtp_header = packet_buffer_->NextRtpHeader();
660 assert(rtp_header);
661 int payload_type = rtp_header->payloadType;
662 AudioDecoder* decoder = decoder_database_->GetDecoder(payload_type);
663 assert(decoder); // Payloads are already checked to be valid.
664 const DecoderDatabase::DecoderInfo* decoder_info =
665 decoder_database_->GetDecoderInfo(payload_type);
666 assert(decoder_info);
667 if (decoder_info->fs_hz != fs_hz_ ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +0000668 decoder->Channels() != algorithm_buffer_->Channels())
669 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->Channels());
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000670 }
671
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000672 // TODO(hlundin): Move this code to DelayManager class.
673 const DecoderDatabase::DecoderInfo* dec_info =
674 decoder_database_->GetDecoderInfo(main_header.payloadType);
675 assert(dec_info); // Already checked that the payload type is known.
676 delay_manager_->LastDecoderType(dec_info->codec_type);
677 if (delay_manager_->last_pack_cng_or_dtmf() == 0) {
678 // Calculate the total speech length carried in each packet.
679 temp_bufsize = packet_buffer_->NumPacketsInBuffer() - temp_bufsize;
680 temp_bufsize *= decoder_frame_length_;
681
682 if ((temp_bufsize > 0) &&
683 (temp_bufsize != decision_logic_->packet_length_samples())) {
684 decision_logic_->set_packet_length_samples(temp_bufsize);
685 delay_manager_->SetPacketAudioLength((1000 * temp_bufsize) / fs_hz_);
686 }
687
688 // Update statistics.
pbos@webrtc.org0946a562013-04-09 00:28:06 +0000689 if ((int32_t) (main_header.timestamp - timestamp_) >= 0 &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000690 !new_codec_) {
691 // Only update statistics if incoming packet is not older than last played
692 // out packet, and if new codec flag is not set.
693 delay_manager_->Update(main_header.sequenceNumber, main_header.timestamp,
694 fs_hz_);
695 }
696 } else if (delay_manager_->last_pack_cng_or_dtmf() == -1) {
697 // This is first "normal" packet after CNG or DTMF.
698 // Reset packet time counter and measure time until next packet,
699 // but don't update statistics.
700 delay_manager_->set_last_pack_cng_or_dtmf(0);
701 delay_manager_->ResetPacketIatCount();
702 }
703 return 0;
704}
705
706int NetEqImpl::GetAudioInternal(size_t max_length, int16_t* output,
707 int* samples_per_channel, int* num_channels) {
708 PacketList packet_list;
709 DtmfEvent dtmf_event;
710 Operations operation;
711 bool play_dtmf;
712 int return_value = GetDecision(&operation, &packet_list, &dtmf_event,
713 &play_dtmf);
714 if (return_value != 0) {
715 LOG_FERR1(LS_WARNING, GetDecision, return_value);
716 assert(false);
717 last_mode_ = kModeError;
718 return return_value;
719 }
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000720 LOG(LS_VERBOSE) << "GetDecision returned operation=" << operation <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000721 " and " << packet_list.size() << " packet(s)";
722
723 AudioDecoder::SpeechType speech_type;
724 int length = 0;
725 int decode_return_value = Decode(&packet_list, &operation,
726 &length, &speech_type);
727
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000728 assert(vad_.get());
729 bool sid_frame_available =
730 (operation == kRfc3389Cng && !packet_list.empty());
731 vad_->Update(decoded_buffer_.get(), length, speech_type,
732 sid_frame_available, fs_hz_);
733
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000734 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000735 switch (operation) {
736 case kNormal: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000737 DoNormal(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000738 break;
739 }
740 case kMerge: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000741 DoMerge(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000742 break;
743 }
744 case kExpand: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000745 return_value = DoExpand(play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000746 break;
747 }
748 case kAccelerate: {
749 return_value = DoAccelerate(decoded_buffer_.get(), length, speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000750 play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000751 break;
752 }
753 case kPreemptiveExpand: {
754 return_value = DoPreemptiveExpand(decoded_buffer_.get(), length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000755 speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000756 break;
757 }
758 case kRfc3389Cng:
759 case kRfc3389CngNoPacket: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000760 return_value = DoRfc3389Cng(&packet_list, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000761 break;
762 }
763 case kCodecInternalCng: {
764 // This handles the case when there is no transmission and the decoder
765 // should produce internal comfort noise.
766 // TODO(hlundin): Write test for codec-internal CNG.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000767 DoCodecInternalCng();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000768 break;
769 }
770 case kDtmf: {
771 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000772 return_value = DoDtmf(dtmf_event, &play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000773 break;
774 }
775 case kAlternativePlc: {
776 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000777 DoAlternativePlc(false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000778 break;
779 }
780 case kAlternativePlcIncreaseTimestamp: {
781 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000782 DoAlternativePlc(true);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000783 break;
784 }
785 case kAudioRepetitionIncreaseTimestamp: {
786 // TODO(hlundin): Write test for this.
787 sync_buffer_->IncreaseEndTimestamp(output_size_samples_);
788 // Skipping break on purpose. Execution should move on into the
789 // next case.
kjellander@webrtc.org7d2b6a92015-01-28 18:37:58 +0000790 FALLTHROUGH();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000791 }
792 case kAudioRepetition: {
793 // TODO(hlundin): Write test for this.
794 // Copy last |output_size_samples_| from |sync_buffer_| to
795 // |algorithm_buffer|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000796 algorithm_buffer_->PushBackFromIndex(
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000797 *sync_buffer_, sync_buffer_->Size() - output_size_samples_);
798 expand_->Reset();
799 break;
800 }
801 case kUndefined: {
802 LOG_F(LS_ERROR) << "Invalid operation kUndefined.";
803 assert(false); // This should not happen.
804 last_mode_ = kModeError;
805 return kInvalidOperation;
806 }
807 } // End of switch.
808 if (return_value < 0) {
809 return return_value;
810 }
811
812 if (last_mode_ != kModeRfc3389Cng) {
813 comfort_noise_->Reset();
814 }
815
816 // Copy from |algorithm_buffer| to |sync_buffer_|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000817 sync_buffer_->PushBack(*algorithm_buffer_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000818
819 // Extract data from |sync_buffer_| to |output|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000820 size_t num_output_samples_per_channel = output_size_samples_;
821 size_t num_output_samples = output_size_samples_ * sync_buffer_->Channels();
822 if (num_output_samples > max_length) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000823 LOG(LS_WARNING) << "Output array is too short. " << max_length << " < " <<
824 output_size_samples_ << " * " << sync_buffer_->Channels();
825 num_output_samples = max_length;
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000826 num_output_samples_per_channel = static_cast<int>(
827 max_length / sync_buffer_->Channels());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000828 }
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000829 int samples_from_sync = static_cast<int>(
830 sync_buffer_->GetNextAudioInterleaved(num_output_samples_per_channel,
831 output));
832 *num_channels = static_cast<int>(sync_buffer_->Channels());
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000833 LOG(LS_VERBOSE) << "Sync buffer (" << *num_channels << " channel(s)):" <<
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000834 " insert " << algorithm_buffer_->Size() << " samples, extract " <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000835 samples_from_sync << " samples";
836 if (samples_from_sync != output_size_samples_) {
837 LOG_F(LS_ERROR) << "samples_from_sync != output_size_samples_";
minyue@webrtc.orgdb1cefc2013-08-13 01:39:21 +0000838 // TODO(minyue): treatment of under-run, filling zeros
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000839 memset(output, 0, num_output_samples * sizeof(int16_t));
840 *samples_per_channel = output_size_samples_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000841 return kSampleUnderrun;
842 }
843 *samples_per_channel = output_size_samples_;
844
845 // Should always have overlap samples left in the |sync_buffer_|.
846 assert(sync_buffer_->FutureLength() >= expand_->overlap_length());
847
848 if (play_dtmf) {
849 return_value = DtmfOverdub(dtmf_event, sync_buffer_->Channels(), output);
850 }
851
852 // Update the background noise parameters if last operation wrote data
853 // straight from the decoder to the |sync_buffer_|. That is, none of the
854 // operations that modify the signal can be followed by a parameter update.
855 if ((last_mode_ == kModeNormal) ||
856 (last_mode_ == kModeAccelerateFail) ||
857 (last_mode_ == kModePreemptiveExpandFail) ||
858 (last_mode_ == kModeRfc3389Cng) ||
859 (last_mode_ == kModeCodecInternalCng)) {
860 background_noise_->Update(*sync_buffer_, *vad_.get());
861 }
862
863 if (operation == kDtmf) {
864 // DTMF data was written the end of |sync_buffer_|.
865 // Update index to end of DTMF data in |sync_buffer_|.
866 sync_buffer_->set_dtmf_index(sync_buffer_->Size());
867 }
868
henrik.lundin@webrtc.orged865b52014-03-06 10:28:07 +0000869 if (last_mode_ != kModeExpand) {
870 // If last operation was not expand, calculate the |playout_timestamp_| from
871 // the |sync_buffer_|. However, do not update the |playout_timestamp_| if it
872 // would be moved "backwards".
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000873 uint32_t temp_timestamp = sync_buffer_->end_timestamp() -
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000874 static_cast<uint32_t>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000875 if (static_cast<int32_t>(temp_timestamp - playout_timestamp_) > 0) {
876 playout_timestamp_ = temp_timestamp;
877 }
878 } else {
879 // Use dead reckoning to estimate the |playout_timestamp_|.
880 playout_timestamp_ += output_size_samples_;
881 }
882
883 if (decode_return_value) return decode_return_value;
884 return return_value;
885}
886
887int NetEqImpl::GetDecision(Operations* operation,
888 PacketList* packet_list,
889 DtmfEvent* dtmf_event,
890 bool* play_dtmf) {
891 // Initialize output variables.
892 *play_dtmf = false;
893 *operation = kUndefined;
894
895 // Increment time counters.
896 packet_buffer_->IncrementWaitingTimes();
897 stats_.IncreaseCounter(output_size_samples_, fs_hz_);
898
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000899 assert(sync_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000900 uint32_t end_timestamp = sync_buffer_->end_timestamp();
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +0000901 if (!new_codec_) {
902 const uint32_t five_seconds_samples = 5 * fs_hz_;
903 packet_buffer_->DiscardOldPackets(end_timestamp, five_seconds_samples);
904 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000905 const RTPHeader* header = packet_buffer_->NextRtpHeader();
906
henrik.lundin@webrtc.orgca8cb952014-03-12 10:26:52 +0000907 if (decision_logic_->CngRfc3389On() || last_mode_ == kModeRfc3389Cng) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000908 // Because of timestamp peculiarities, we have to "manually" disallow using
909 // a CNG packet with the same timestamp as the one that was last played.
910 // This can happen when using redundancy and will cause the timing to shift.
henrik.lundin@webrtc.org24779fe2014-03-14 12:40:05 +0000911 while (header && decoder_database_->IsComfortNoise(header->payloadType) &&
912 (end_timestamp >= header->timestamp ||
913 end_timestamp + decision_logic_->generated_noise_samples() >
914 header->timestamp)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000915 // Don't use this packet, discard it.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000916 if (packet_buffer_->DiscardNextPacket() != PacketBuffer::kOK) {
917 assert(false); // Must be ok by design.
918 }
919 // Check buffer again.
920 if (!new_codec_) {
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +0000921 packet_buffer_->DiscardOldPackets(end_timestamp, 5 * fs_hz_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000922 }
923 header = packet_buffer_->NextRtpHeader();
924 }
925 }
926
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000927 assert(expand_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000928 const int samples_left = static_cast<int>(sync_buffer_->FutureLength() -
929 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000930 if (last_mode_ == kModeAccelerateSuccess ||
931 last_mode_ == kModeAccelerateLowEnergy ||
932 last_mode_ == kModePreemptiveExpandSuccess ||
933 last_mode_ == kModePreemptiveExpandLowEnergy) {
934 // Subtract (samples_left + output_size_samples_) from sampleMemory.
935 decision_logic_->AddSampleMemory(-(samples_left + output_size_samples_));
936 }
937
938 // Check if it is time to play a DTMF event.
939 if (dtmf_buffer_->GetEvent(end_timestamp +
940 decision_logic_->generated_noise_samples(),
941 dtmf_event)) {
942 *play_dtmf = true;
943 }
944
945 // Get instruction.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000946 assert(sync_buffer_.get());
947 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000948 *operation = decision_logic_->GetDecision(*sync_buffer_,
949 *expand_,
950 decoder_frame_length_,
951 header,
952 last_mode_,
953 *play_dtmf,
954 &reset_decoder_);
955
956 // Check if we already have enough samples in the |sync_buffer_|. If so,
957 // change decision to normal, unless the decision was merge, accelerate, or
958 // preemptive expand.
959 if (samples_left >= output_size_samples_ &&
960 *operation != kMerge &&
961 *operation != kAccelerate &&
962 *operation != kPreemptiveExpand) {
963 *operation = kNormal;
964 return 0;
965 }
966
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000967 decision_logic_->ExpandDecision(*operation);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000968
969 // Check conditions for reset.
970 if (new_codec_ || *operation == kUndefined) {
971 // The only valid reason to get kUndefined is that new_codec_ is set.
972 assert(new_codec_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000973 if (*play_dtmf && !header) {
974 timestamp_ = dtmf_event->timestamp;
975 } else {
976 assert(header);
977 if (!header) {
978 LOG_F(LS_ERROR) << "Packet missing where it shouldn't.";
979 return -1;
980 }
981 timestamp_ = header->timestamp;
982 if (*operation == kRfc3389CngNoPacket
983#ifndef LEGACY_BITEXACT
984 // Without this check, it can happen that a non-CNG packet is sent to
985 // the CNG decoder as if it was a SID frame. This is clearly a bug,
986 // but is kept for now to maintain bit-exactness with the test
987 // vectors.
988 && decoder_database_->IsComfortNoise(header->payloadType)
989#endif
990 ) {
991 // Change decision to CNG packet, since we do have a CNG packet, but it
992 // was considered too early to use. Now, use it anyway.
993 *operation = kRfc3389Cng;
994 } else if (*operation != kRfc3389Cng) {
995 *operation = kNormal;
996 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000997 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000998 // Adjust |sync_buffer_| timestamp before setting |end_timestamp| to the
999 // new value.
1000 sync_buffer_->IncreaseEndTimestamp(timestamp_ - end_timestamp);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001001 end_timestamp = timestamp_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001002 new_codec_ = false;
1003 decision_logic_->SoftReset();
1004 buffer_level_filter_->Reset();
1005 delay_manager_->Reset();
1006 stats_.ResetMcu();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001007 }
1008
1009 int required_samples = output_size_samples_;
1010 const int samples_10_ms = 80 * fs_mult_;
1011 const int samples_20_ms = 2 * samples_10_ms;
1012 const int samples_30_ms = 3 * samples_10_ms;
1013
1014 switch (*operation) {
1015 case kExpand: {
1016 timestamp_ = end_timestamp;
1017 return 0;
1018 }
1019 case kRfc3389CngNoPacket:
1020 case kCodecInternalCng: {
1021 return 0;
1022 }
1023 case kDtmf: {
1024 // TODO(hlundin): Write test for this.
1025 // Update timestamp.
1026 timestamp_ = end_timestamp;
1027 if (decision_logic_->generated_noise_samples() > 0 &&
1028 last_mode_ != kModeDtmf) {
1029 // Make a jump in timestamp due to the recently played comfort noise.
1030 uint32_t timestamp_jump = decision_logic_->generated_noise_samples();
1031 sync_buffer_->IncreaseEndTimestamp(timestamp_jump);
1032 timestamp_ += timestamp_jump;
1033 }
1034 decision_logic_->set_generated_noise_samples(0);
1035 return 0;
1036 }
1037 case kAccelerate: {
1038 // In order to do a accelerate we need at least 30 ms of audio data.
1039 if (samples_left >= samples_30_ms) {
1040 // Already have enough data, so we do not need to extract any more.
1041 decision_logic_->set_sample_memory(samples_left);
1042 decision_logic_->set_prev_time_scale(true);
1043 return 0;
1044 } else if (samples_left >= samples_10_ms &&
1045 decoder_frame_length_ >= samples_30_ms) {
1046 // Avoid decoding more data as it might overflow the playout buffer.
1047 *operation = kNormal;
1048 return 0;
1049 } else if (samples_left < samples_20_ms &&
1050 decoder_frame_length_ < samples_30_ms) {
1051 // Build up decoded data by decoding at least 20 ms of audio data. Do
1052 // not perform accelerate yet, but wait until we only need to do one
1053 // decoding.
1054 required_samples = 2 * output_size_samples_;
1055 *operation = kNormal;
1056 }
1057 // If none of the above is true, we have one of two possible situations:
1058 // (1) 20 ms <= samples_left < 30 ms and decoder_frame_length_ < 30 ms; or
1059 // (2) samples_left < 10 ms and decoder_frame_length_ >= 30 ms.
1060 // In either case, we move on with the accelerate decision, and decode one
1061 // frame now.
1062 break;
1063 }
1064 case kPreemptiveExpand: {
1065 // In order to do a preemptive expand we need at least 30 ms of decoded
1066 // audio data.
1067 if ((samples_left >= samples_30_ms) ||
1068 (samples_left >= samples_10_ms &&
1069 decoder_frame_length_ >= samples_30_ms)) {
1070 // Already have enough data, so we do not need to extract any more.
1071 // Or, avoid decoding more data as it might overflow the playout buffer.
1072 // Still try preemptive expand, though.
1073 decision_logic_->set_sample_memory(samples_left);
1074 decision_logic_->set_prev_time_scale(true);
1075 return 0;
1076 }
1077 if (samples_left < samples_20_ms &&
1078 decoder_frame_length_ < samples_30_ms) {
1079 // Build up decoded data by decoding at least 20 ms of audio data.
1080 // Still try to perform preemptive expand.
1081 required_samples = 2 * output_size_samples_;
1082 }
1083 // Move on with the preemptive expand decision.
1084 break;
1085 }
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001086 case kMerge: {
1087 required_samples =
1088 std::max(merge_->RequiredFutureSamples(), required_samples);
1089 break;
1090 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001091 default: {
1092 // Do nothing.
1093 }
1094 }
1095
1096 // Get packets from buffer.
1097 int extracted_samples = 0;
1098 if (header &&
1099 *operation != kAlternativePlc &&
1100 *operation != kAlternativePlcIncreaseTimestamp &&
1101 *operation != kAudioRepetition &&
1102 *operation != kAudioRepetitionIncreaseTimestamp) {
1103 sync_buffer_->IncreaseEndTimestamp(header->timestamp - end_timestamp);
1104 if (decision_logic_->CngOff()) {
1105 // Adjustment of timestamp only corresponds to an actual packet loss
1106 // if comfort noise is not played. If comfort noise was just played,
1107 // this adjustment of timestamp is only done to get back in sync with the
1108 // stream timestamp; no loss to report.
1109 stats_.LostSamples(header->timestamp - end_timestamp);
1110 }
1111
1112 if (*operation != kRfc3389Cng) {
1113 // We are about to decode and use a non-CNG packet.
1114 decision_logic_->SetCngOff();
1115 }
1116 // Reset CNG timestamp as a new packet will be delivered.
1117 // (Also if this is a CNG packet, since playedOutTS is updated.)
1118 decision_logic_->set_generated_noise_samples(0);
1119
1120 extracted_samples = ExtractPackets(required_samples, packet_list);
1121 if (extracted_samples < 0) {
1122 LOG_F(LS_WARNING) << "Failed to extract packets from buffer.";
1123 return kPacketBufferCorruption;
1124 }
1125 }
1126
1127 if (*operation == kAccelerate ||
1128 *operation == kPreemptiveExpand) {
1129 decision_logic_->set_sample_memory(samples_left + extracted_samples);
1130 decision_logic_->set_prev_time_scale(true);
1131 }
1132
1133 if (*operation == kAccelerate) {
1134 // Check that we have enough data (30ms) to do accelerate.
1135 if (extracted_samples + samples_left < samples_30_ms) {
1136 // TODO(hlundin): Write test for this.
1137 // Not enough, do normal operation instead.
1138 *operation = kNormal;
1139 }
1140 }
1141
1142 timestamp_ = end_timestamp;
1143 return 0;
1144}
1145
1146int NetEqImpl::Decode(PacketList* packet_list, Operations* operation,
1147 int* decoded_length,
1148 AudioDecoder::SpeechType* speech_type) {
1149 *speech_type = AudioDecoder::kSpeech;
1150 AudioDecoder* decoder = NULL;
1151 if (!packet_list->empty()) {
1152 const Packet* packet = packet_list->front();
pkasting@chromium.org0e81fdf2015-02-02 23:54:03 +00001153 uint8_t payload_type = packet->header.payloadType;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001154 if (!decoder_database_->IsComfortNoise(payload_type)) {
1155 decoder = decoder_database_->GetDecoder(payload_type);
1156 assert(decoder);
1157 if (!decoder) {
pkasting@chromium.org0e81fdf2015-02-02 23:54:03 +00001158 LOG_FERR1(LS_WARNING, GetDecoder, static_cast<int>(payload_type));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001159 PacketBuffer::DeleteAllPackets(packet_list);
1160 return kDecoderNotFound;
1161 }
1162 bool decoder_changed;
1163 decoder_database_->SetActiveDecoder(payload_type, &decoder_changed);
1164 if (decoder_changed) {
1165 // We have a new decoder. Re-init some values.
1166 const DecoderDatabase::DecoderInfo* decoder_info = decoder_database_
1167 ->GetDecoderInfo(payload_type);
1168 assert(decoder_info);
1169 if (!decoder_info) {
pkasting@chromium.org0e81fdf2015-02-02 23:54:03 +00001170 LOG_FERR1(LS_WARNING, GetDecoderInfo, static_cast<int>(payload_type));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001171 PacketBuffer::DeleteAllPackets(packet_list);
1172 return kDecoderNotFound;
1173 }
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001174 // If sampling rate or number of channels has changed, we need to make
1175 // a reset.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001176 if (decoder_info->fs_hz != fs_hz_ ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001177 decoder->Channels() != algorithm_buffer_->Channels()) {
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001178 // TODO(tlegrand): Add unittest to cover this event.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001179 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->Channels());
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001180 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001181 sync_buffer_->set_end_timestamp(timestamp_);
1182 playout_timestamp_ = timestamp_;
1183 }
1184 }
1185 }
1186
1187 if (reset_decoder_) {
1188 // TODO(hlundin): Write test for this.
1189 // Reset decoder.
1190 if (decoder) {
1191 decoder->Init();
1192 }
1193 // Reset comfort noise decoder.
1194 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
1195 if (cng_decoder) {
1196 cng_decoder->Init();
1197 }
1198 reset_decoder_ = false;
1199 }
1200
1201#ifdef LEGACY_BITEXACT
1202 // Due to a bug in old SignalMCU, it could happen that CNG operation was
1203 // decided, but a speech packet was provided. The speech packet will be used
1204 // to update the comfort noise decoder, as if it was a SID frame, which is
1205 // clearly wrong.
1206 if (*operation == kRfc3389Cng) {
1207 return 0;
1208 }
1209#endif
1210
1211 *decoded_length = 0;
1212 // Update codec-internal PLC state.
1213 if ((*operation == kMerge) && decoder && decoder->HasDecodePlc()) {
1214 decoder->DecodePlc(1, &decoded_buffer_[*decoded_length]);
1215 }
1216
1217 int return_value = DecodeLoop(packet_list, operation, decoder,
1218 decoded_length, speech_type);
1219
1220 if (*decoded_length < 0) {
1221 // Error returned from the decoder.
1222 *decoded_length = 0;
1223 sync_buffer_->IncreaseEndTimestamp(decoder_frame_length_);
1224 int error_code = 0;
1225 if (decoder)
1226 error_code = decoder->ErrorCode();
1227 if (error_code != 0) {
1228 // Got some error code from the decoder.
1229 decoder_error_code_ = error_code;
1230 return_value = kDecoderErrorCode;
1231 } else {
1232 // Decoder does not implement error codes. Return generic error.
1233 return_value = kOtherDecoderError;
1234 }
1235 LOG_FERR2(LS_WARNING, DecodeLoop, error_code, packet_list->size());
1236 *operation = kExpand; // Do expansion to get data instead.
1237 }
1238 if (*speech_type != AudioDecoder::kComfortNoise) {
1239 // Don't increment timestamp if codec returned CNG speech type
1240 // since in this case, the we will increment the CNGplayedTS counter.
1241 // Increase with number of samples per channel.
1242 assert(*decoded_length == 0 ||
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001243 (decoder && decoder->Channels() == sync_buffer_->Channels()));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001244 sync_buffer_->IncreaseEndTimestamp(
1245 *decoded_length / static_cast<int>(sync_buffer_->Channels()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001246 }
1247 return return_value;
1248}
1249
1250int NetEqImpl::DecodeLoop(PacketList* packet_list, Operations* operation,
1251 AudioDecoder* decoder, int* decoded_length,
1252 AudioDecoder::SpeechType* speech_type) {
1253 Packet* packet = NULL;
1254 if (!packet_list->empty()) {
1255 packet = packet_list->front();
1256 }
1257 // Do decoding.
1258 while (packet &&
1259 !decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1260 assert(decoder); // At this point, we must have a decoder object.
1261 // The number of channels in the |sync_buffer_| should be the same as the
1262 // number decoder channels.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001263 assert(sync_buffer_->Channels() == decoder->Channels());
1264 assert(decoded_buffer_length_ >= kMaxFrameSize * decoder->Channels());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001265 assert(*operation == kNormal || *operation == kAccelerate ||
1266 *operation == kMerge || *operation == kPreemptiveExpand);
1267 packet_list->pop_front();
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001268 size_t payload_length = packet->payload_length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001269 int16_t decode_length;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +00001270 if (packet->sync_packet) {
1271 // Decode to silence with the same frame size as the last decode.
1272 LOG(LS_VERBOSE) << "Decoding sync-packet: " <<
1273 " ts=" << packet->header.timestamp <<
1274 ", sn=" << packet->header.sequenceNumber <<
1275 ", pt=" << static_cast<int>(packet->header.payloadType) <<
1276 ", ssrc=" << packet->header.ssrc <<
1277 ", len=" << packet->payload_length;
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001278 memset(&decoded_buffer_[*decoded_length], 0,
1279 decoder_frame_length_ * decoder->Channels() *
1280 sizeof(decoded_buffer_[0]));
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +00001281 decode_length = decoder_frame_length_;
1282 } else if (!packet->primary) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001283 // This is a redundant payload; call the special decoder method.
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +00001284 LOG(LS_VERBOSE) << "Decoding packet (redundant):" <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001285 " ts=" << packet->header.timestamp <<
1286 ", sn=" << packet->header.sequenceNumber <<
1287 ", pt=" << static_cast<int>(packet->header.payloadType) <<
1288 ", ssrc=" << packet->header.ssrc <<
1289 ", len=" << packet->payload_length;
1290 decode_length = decoder->DecodeRedundant(
henrik.lundin@webrtc.org1eda4e32015-02-25 10:02:29 +00001291 packet->payload, packet->payload_length, fs_hz_,
minyue@webrtc.org7f7d7e32015-03-16 12:30:37 +00001292 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001293 &decoded_buffer_[*decoded_length], speech_type);
1294 } else {
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +00001295 LOG(LS_VERBOSE) << "Decoding packet: ts=" << packet->header.timestamp <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001296 ", sn=" << packet->header.sequenceNumber <<
1297 ", pt=" << static_cast<int>(packet->header.payloadType) <<
1298 ", ssrc=" << packet->header.ssrc <<
1299 ", len=" << packet->payload_length;
henrik.lundin@webrtc.org1eda4e32015-02-25 10:02:29 +00001300 decode_length =
minyue@webrtc.org7f7d7e32015-03-16 12:30:37 +00001301 decoder->Decode(
1302 packet->payload, packet->payload_length, fs_hz_,
1303 (decoded_buffer_length_ - *decoded_length) * sizeof(int16_t),
1304 &decoded_buffer_[*decoded_length], speech_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001305 }
1306
1307 delete[] packet->payload;
1308 delete packet;
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001309 packet = NULL;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001310 if (decode_length > 0) {
1311 *decoded_length += decode_length;
1312 // Update |decoder_frame_length_| with number of samples per channel.
henrik.lundin@webrtc.org6dba1eb2015-03-18 09:47:08 +00001313 decoder_frame_length_ =
1314 decode_length / static_cast<int>(decoder->Channels());
1315 LOG(LS_VERBOSE) << "Decoded " << decode_length << " samples ("
1316 << decoder->Channels() << " channel(s) -> "
1317 << decoder_frame_length_ << " samples per channel)";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001318 } else if (decode_length < 0) {
1319 // Error.
henrik.lundin@webrtc.org63464a92013-01-30 09:41:56 +00001320 LOG_FERR2(LS_WARNING, Decode, decode_length, payload_length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001321 *decoded_length = -1;
1322 PacketBuffer::DeleteAllPackets(packet_list);
1323 break;
1324 }
1325 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1326 // Guard against overflow.
1327 LOG_F(LS_WARNING) << "Decoded too much.";
1328 PacketBuffer::DeleteAllPackets(packet_list);
1329 return kDecodedTooMuch;
1330 }
1331 if (!packet_list->empty()) {
1332 packet = packet_list->front();
1333 } else {
1334 packet = NULL;
1335 }
1336 } // End of decode loop.
1337
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001338 // If the list is not empty at this point, either a decoding error terminated
1339 // the while-loop, or list must hold exactly one CNG packet.
1340 assert(packet_list->empty() || *decoded_length < 0 ||
1341 (packet_list->size() == 1 && packet &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001342 decoder_database_->IsComfortNoise(packet->header.payloadType)));
1343 return 0;
1344}
1345
1346void NetEqImpl::DoNormal(const int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001347 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001348 assert(normal_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001349 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001350 normal_->Process(decoded_buffer, decoded_length, last_mode_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001351 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001352 if (decoded_length != 0) {
1353 last_mode_ = kModeNormal;
1354 }
1355
1356 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1357 if ((speech_type == AudioDecoder::kComfortNoise)
1358 || ((last_mode_ == kModeCodecInternalCng)
1359 && (decoded_length == 0))) {
1360 // TODO(hlundin): Remove second part of || statement above.
1361 last_mode_ = kModeCodecInternalCng;
1362 }
1363
1364 if (!play_dtmf) {
1365 dtmf_tone_generator_->Reset();
1366 }
1367}
1368
1369void NetEqImpl::DoMerge(int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001370 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001371 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001372 assert(merge_.get());
1373 int new_length = merge_->Process(decoded_buffer, decoded_length,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001374 mute_factor_array_.get(),
1375 algorithm_buffer_.get());
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001376 int expand_length_correction = new_length -
1377 static_cast<int>(decoded_length / algorithm_buffer_->Channels());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001378
1379 // Update in-call and post-call statistics.
1380 if (expand_->MuteFactor(0) == 0) {
1381 // Expand generates only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001382 stats_.ExpandedNoiseSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001383 } else {
1384 // Expansion generates more than only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001385 stats_.ExpandedVoiceSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001386 }
1387
1388 last_mode_ = kModeMerge;
1389 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1390 if (speech_type == AudioDecoder::kComfortNoise) {
1391 last_mode_ = kModeCodecInternalCng;
1392 }
1393 expand_->Reset();
1394 if (!play_dtmf) {
1395 dtmf_tone_generator_->Reset();
1396 }
1397}
1398
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001399int NetEqImpl::DoExpand(bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001400 while ((sync_buffer_->FutureLength() - expand_->overlap_length()) <
1401 static_cast<size_t>(output_size_samples_)) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001402 algorithm_buffer_->Clear();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001403 int return_value = expand_->Process(algorithm_buffer_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001404 int length = static_cast<int>(algorithm_buffer_->Size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001405
1406 // Update in-call and post-call statistics.
1407 if (expand_->MuteFactor(0) == 0) {
1408 // Expand operation generates only noise.
1409 stats_.ExpandedNoiseSamples(length);
1410 } else {
1411 // Expand operation generates more than only noise.
1412 stats_.ExpandedVoiceSamples(length);
1413 }
1414
1415 last_mode_ = kModeExpand;
1416
1417 if (return_value < 0) {
1418 return return_value;
1419 }
1420
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001421 sync_buffer_->PushBack(*algorithm_buffer_);
1422 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001423 }
1424 if (!play_dtmf) {
1425 dtmf_tone_generator_->Reset();
1426 }
1427 return 0;
1428}
1429
1430int NetEqImpl::DoAccelerate(int16_t* decoded_buffer, size_t decoded_length,
1431 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001432 bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001433 const size_t required_samples = 240 * fs_mult_; // Must have 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001434 size_t borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001435 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001436 size_t decoded_length_per_channel = decoded_length / num_channels;
1437 if (decoded_length_per_channel < required_samples) {
1438 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001439 borrowed_samples_per_channel = static_cast<int>(required_samples -
1440 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001441 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1442 decoded_buffer,
1443 sizeof(int16_t) * decoded_length);
1444 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1445 decoded_buffer);
1446 decoded_length = required_samples * num_channels;
1447 }
1448
1449 int16_t samples_removed;
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001450 Accelerate::ReturnCodes return_code = accelerate_->Process(
1451 decoded_buffer, decoded_length, algorithm_buffer_.get(),
1452 &samples_removed);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001453 stats_.AcceleratedSamples(samples_removed);
1454 switch (return_code) {
1455 case Accelerate::kSuccess:
1456 last_mode_ = kModeAccelerateSuccess;
1457 break;
1458 case Accelerate::kSuccessLowEnergy:
1459 last_mode_ = kModeAccelerateLowEnergy;
1460 break;
1461 case Accelerate::kNoStretch:
1462 last_mode_ = kModeAccelerateFail;
1463 break;
1464 case Accelerate::kError:
1465 // TODO(hlundin): Map to kModeError instead?
1466 last_mode_ = kModeAccelerateFail;
1467 return kAccelerateError;
1468 }
1469
1470 if (borrowed_samples_per_channel > 0) {
1471 // Copy borrowed samples back to the |sync_buffer_|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001472 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001473 if (length < borrowed_samples_per_channel) {
1474 // This destroys the beginning of the buffer, but will not cause any
1475 // problems.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001476 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001477 sync_buffer_->Size() -
1478 borrowed_samples_per_channel);
1479 sync_buffer_->PushFrontZeros(borrowed_samples_per_channel - length);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001480 algorithm_buffer_->PopFront(length);
1481 assert(algorithm_buffer_->Empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001482 } else {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001483 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001484 borrowed_samples_per_channel,
1485 sync_buffer_->Size() -
1486 borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001487 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001488 }
1489 }
1490
1491 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1492 if (speech_type == AudioDecoder::kComfortNoise) {
1493 last_mode_ = kModeCodecInternalCng;
1494 }
1495 if (!play_dtmf) {
1496 dtmf_tone_generator_->Reset();
1497 }
1498 expand_->Reset();
1499 return 0;
1500}
1501
1502int NetEqImpl::DoPreemptiveExpand(int16_t* decoded_buffer,
1503 size_t decoded_length,
1504 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001505 bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001506 const size_t required_samples = 240 * fs_mult_; // Must have 30 ms.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001507 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001508 int borrowed_samples_per_channel = 0;
1509 int old_borrowed_samples_per_channel = 0;
1510 size_t decoded_length_per_channel = decoded_length / num_channels;
1511 if (decoded_length_per_channel < required_samples) {
1512 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001513 borrowed_samples_per_channel = static_cast<int>(required_samples -
1514 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001515 // Calculate how many of these were already played out.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001516 old_borrowed_samples_per_channel = static_cast<int>(
1517 borrowed_samples_per_channel - sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001518 old_borrowed_samples_per_channel = std::max(
1519 0, old_borrowed_samples_per_channel);
1520 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1521 decoded_buffer,
1522 sizeof(int16_t) * decoded_length);
1523 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1524 decoded_buffer);
1525 decoded_length = required_samples * num_channels;
1526 }
1527
1528 int16_t samples_added;
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001529 PreemptiveExpand::ReturnCodes return_code = preemptive_expand_->Process(
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001530 decoded_buffer, static_cast<int>(decoded_length),
1531 old_borrowed_samples_per_channel,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001532 algorithm_buffer_.get(), &samples_added);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001533 stats_.PreemptiveExpandedSamples(samples_added);
1534 switch (return_code) {
1535 case PreemptiveExpand::kSuccess:
1536 last_mode_ = kModePreemptiveExpandSuccess;
1537 break;
1538 case PreemptiveExpand::kSuccessLowEnergy:
1539 last_mode_ = kModePreemptiveExpandLowEnergy;
1540 break;
1541 case PreemptiveExpand::kNoStretch:
1542 last_mode_ = kModePreemptiveExpandFail;
1543 break;
1544 case PreemptiveExpand::kError:
1545 // TODO(hlundin): Map to kModeError instead?
1546 last_mode_ = kModePreemptiveExpandFail;
1547 return kPreemptiveExpandError;
1548 }
1549
1550 if (borrowed_samples_per_channel > 0) {
1551 // Copy borrowed samples back to the |sync_buffer_|.
1552 sync_buffer_->ReplaceAtIndex(
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001553 *algorithm_buffer_, borrowed_samples_per_channel,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001554 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001555 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001556 }
1557
1558 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1559 if (speech_type == AudioDecoder::kComfortNoise) {
1560 last_mode_ = kModeCodecInternalCng;
1561 }
1562 if (!play_dtmf) {
1563 dtmf_tone_generator_->Reset();
1564 }
1565 expand_->Reset();
1566 return 0;
1567}
1568
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001569int NetEqImpl::DoRfc3389Cng(PacketList* packet_list, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001570 if (!packet_list->empty()) {
1571 // Must have exactly one SID frame at this point.
1572 assert(packet_list->size() == 1);
1573 Packet* packet = packet_list->front();
1574 packet_list->pop_front();
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001575 if (!decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1576#ifdef LEGACY_BITEXACT
1577 // This can happen due to a bug in GetDecision. Change the payload type
1578 // to a CNG type, and move on. Note that this means that we are in fact
1579 // sending a non-CNG payload to the comfort noise decoder for decoding.
1580 // Clearly wrong, but will maintain bit-exactness with legacy.
1581 if (fs_hz_ == 8000) {
1582 packet->header.payloadType =
1583 decoder_database_->GetRtpPayloadType(kDecoderCNGnb);
1584 } else if (fs_hz_ == 16000) {
1585 packet->header.payloadType =
1586 decoder_database_->GetRtpPayloadType(kDecoderCNGwb);
1587 } else if (fs_hz_ == 32000) {
1588 packet->header.payloadType =
1589 decoder_database_->GetRtpPayloadType(kDecoderCNGswb32kHz);
1590 } else if (fs_hz_ == 48000) {
1591 packet->header.payloadType =
1592 decoder_database_->GetRtpPayloadType(kDecoderCNGswb48kHz);
1593 }
1594 assert(decoder_database_->IsComfortNoise(packet->header.payloadType));
1595#else
1596 LOG(LS_ERROR) << "Trying to decode non-CNG payload as CNG.";
1597 return kOtherError;
1598#endif
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001599 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001600 // UpdateParameters() deletes |packet|.
1601 if (comfort_noise_->UpdateParameters(packet) ==
1602 ComfortNoise::kInternalError) {
1603 LOG_FERR0(LS_WARNING, UpdateParameters);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001604 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001605 return -comfort_noise_->internal_error_code();
1606 }
1607 }
1608 int cn_return = comfort_noise_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001609 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001610 expand_->Reset();
1611 last_mode_ = kModeRfc3389Cng;
1612 if (!play_dtmf) {
1613 dtmf_tone_generator_->Reset();
1614 }
1615 if (cn_return == ComfortNoise::kInternalError) {
1616 LOG_FERR1(LS_WARNING, comfort_noise_->Generate, cn_return);
1617 decoder_error_code_ = comfort_noise_->internal_error_code();
1618 return kComfortNoiseErrorCode;
1619 } else if (cn_return == ComfortNoise::kUnknownPayloadType) {
1620 LOG_FERR1(LS_WARNING, comfort_noise_->Generate, cn_return);
1621 return kUnknownRtpPayloadType;
1622 }
1623 return 0;
1624}
1625
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001626void NetEqImpl::DoCodecInternalCng() {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001627 int length = 0;
1628 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1629 int16_t decoded_buffer[kMaxFrameSize];
1630 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1631 if (decoder) {
1632 const uint8_t* dummy_payload = NULL;
1633 AudioDecoder::SpeechType speech_type;
minyue@webrtc.org7f7d7e32015-03-16 12:30:37 +00001634 length = decoder->Decode(
1635 dummy_payload, 0, fs_hz_, kMaxFrameSize * sizeof(int16_t),
1636 decoded_buffer, &speech_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001637 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001638 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001639 normal_->Process(decoded_buffer, length, last_mode_, mute_factor_array_.get(),
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001640 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001641 last_mode_ = kModeCodecInternalCng;
1642 expand_->Reset();
1643}
1644
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001645int NetEqImpl::DoDtmf(const DtmfEvent& dtmf_event, bool* play_dtmf) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001646 // This block of the code and the block further down, handling |dtmf_switch|
1647 // are commented out. Otherwise playing out-of-band DTMF would fail in VoE
1648 // test, DtmfTest.ManualSuccessfullySendsOutOfBandTelephoneEvents. This is
1649 // equivalent to |dtmf_switch| always be false.
1650 //
1651 // See http://webrtc-codereview.appspot.com/1195004/ for discussion
1652 // On this issue. This change might cause some glitches at the point of
1653 // switch from audio to DTMF. Issue 1545 is filed to track this.
1654 //
1655 // bool dtmf_switch = false;
1656 // if ((last_mode_ != kModeDtmf) && dtmf_tone_generator_->initialized()) {
1657 // // Special case; see below.
1658 // // We must catch this before calling Generate, since |initialized| is
1659 // // modified in that call.
1660 // dtmf_switch = true;
1661 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001662
1663 int dtmf_return_value = 0;
1664 if (!dtmf_tone_generator_->initialized()) {
1665 // Initialize if not already done.
1666 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1667 dtmf_event.volume);
1668 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001669
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001670 if (dtmf_return_value == 0) {
1671 // Generate DTMF signal.
1672 dtmf_return_value = dtmf_tone_generator_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001673 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001674 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001675
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001676 if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001677 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001678 return dtmf_return_value;
1679 }
1680
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001681 // if (dtmf_switch) {
1682 // // This is the special case where the previous operation was DTMF
1683 // // overdub, but the current instruction is "regular" DTMF. We must make
1684 // // sure that the DTMF does not have any discontinuities. The first DTMF
1685 // // sample that we generate now must be played out immediately, therefore
1686 // // it must be copied to the speech buffer.
1687 // // TODO(hlundin): This code seems incorrect. (Legacy.) Write test and
1688 // // verify correct operation.
1689 // assert(false);
1690 // // Must generate enough data to replace all of the |sync_buffer_|
1691 // // "future".
1692 // int required_length = sync_buffer_->FutureLength();
1693 // assert(dtmf_tone_generator_->initialized());
1694 // dtmf_return_value = dtmf_tone_generator_->Generate(required_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001695 // algorithm_buffer_);
1696 // assert((size_t) required_length == algorithm_buffer_->Size());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001697 // if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001698 // algorithm_buffer_->Zeros(output_size_samples_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001699 // return dtmf_return_value;
1700 // }
1701 //
1702 // // Overwrite the "future" part of the speech buffer with the new DTMF
1703 // // data.
1704 // // TODO(hlundin): It seems that this overwriting has gone lost.
1705 // // Not adapted for multi-channel yet.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001706 // assert(algorithm_buffer_->Channels() == 1);
1707 // if (algorithm_buffer_->Channels() != 1) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001708 // LOG(LS_WARNING) << "DTMF not supported for more than one channel";
1709 // return kStereoNotSupported;
1710 // }
1711 // // Shuffle the remaining data to the beginning of algorithm buffer.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001712 // algorithm_buffer_->PopFront(sync_buffer_->FutureLength());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001713 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001714
1715 sync_buffer_->IncreaseEndTimestamp(output_size_samples_);
1716 expand_->Reset();
1717 last_mode_ = kModeDtmf;
1718
1719 // Set to false because the DTMF is already in the algorithm buffer.
1720 *play_dtmf = false;
1721 return 0;
1722}
1723
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001724void NetEqImpl::DoAlternativePlc(bool increase_timestamp) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001725 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1726 int length;
1727 if (decoder && decoder->HasDecodePlc()) {
1728 // Use the decoder's packet-loss concealment.
1729 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1730 int16_t decoded_buffer[kMaxFrameSize];
1731 length = decoder->DecodePlc(1, decoded_buffer);
1732 if (length > 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001733 algorithm_buffer_->PushBackInterleaved(decoded_buffer, length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001734 } else {
1735 length = 0;
1736 }
1737 } else {
1738 // Do simple zero-stuffing.
1739 length = output_size_samples_;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001740 algorithm_buffer_->Zeros(length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001741 // By not advancing the timestamp, NetEq inserts samples.
1742 stats_.AddZeros(length);
1743 }
1744 if (increase_timestamp) {
1745 sync_buffer_->IncreaseEndTimestamp(length);
1746 }
1747 expand_->Reset();
1748}
1749
1750int NetEqImpl::DtmfOverdub(const DtmfEvent& dtmf_event, size_t num_channels,
1751 int16_t* output) const {
1752 size_t out_index = 0;
1753 int overdub_length = output_size_samples_; // Default value.
1754
1755 if (sync_buffer_->dtmf_index() > sync_buffer_->next_index()) {
1756 // Special operation for transition from "DTMF only" to "DTMF overdub".
1757 out_index = std::min(
1758 sync_buffer_->dtmf_index() - sync_buffer_->next_index(),
1759 static_cast<size_t>(output_size_samples_));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001760 overdub_length = output_size_samples_ - static_cast<int>(out_index);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001761 }
1762
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001763 AudioMultiVector dtmf_output(num_channels);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001764 int dtmf_return_value = 0;
1765 if (!dtmf_tone_generator_->initialized()) {
1766 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1767 dtmf_event.volume);
1768 }
1769 if (dtmf_return_value == 0) {
1770 dtmf_return_value = dtmf_tone_generator_->Generate(overdub_length,
1771 &dtmf_output);
1772 assert((size_t) overdub_length == dtmf_output.Size());
1773 }
1774 dtmf_output.ReadInterleaved(overdub_length, &output[out_index]);
1775 return dtmf_return_value < 0 ? dtmf_return_value : 0;
1776}
1777
1778int NetEqImpl::ExtractPackets(int required_samples, PacketList* packet_list) {
1779 bool first_packet = true;
1780 uint8_t prev_payload_type = 0;
1781 uint32_t prev_timestamp = 0;
1782 uint16_t prev_sequence_number = 0;
1783 bool next_packet_available = false;
1784
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001785 const RTPHeader* header = packet_buffer_->NextRtpHeader();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001786 assert(header);
1787 if (!header) {
1788 return -1;
1789 }
turaj@webrtc.org7df97062013-08-02 18:07:13 +00001790 uint32_t first_timestamp = header->timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001791 int extracted_samples = 0;
1792
1793 // Packet extraction loop.
1794 do {
1795 timestamp_ = header->timestamp;
1796 int discard_count = 0;
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001797 Packet* packet = packet_buffer_->GetNextPacket(&discard_count);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001798 // |header| may be invalid after the |packet_buffer_| operation.
1799 header = NULL;
1800 if (!packet) {
1801 LOG_FERR1(LS_ERROR, GetNextPacket, discard_count) <<
1802 "Should always be able to extract a packet here";
1803 assert(false); // Should always be able to extract a packet here.
1804 return -1;
1805 }
1806 stats_.PacketsDiscarded(discard_count);
1807 // Store waiting time in ms; packets->waiting_time is in "output blocks".
1808 stats_.StoreWaitingTime(packet->waiting_time * kOutputSizeMs);
1809 assert(packet->payload_length > 0);
1810 packet_list->push_back(packet); // Store packet in list.
1811
1812 if (first_packet) {
1813 first_packet = false;
minyue@webrtc.orgd7301772013-08-29 00:58:14 +00001814 decoded_packet_sequence_number_ = prev_sequence_number =
1815 packet->header.sequenceNumber;
1816 decoded_packet_timestamp_ = prev_timestamp = packet->header.timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001817 prev_payload_type = packet->header.payloadType;
1818 }
1819
1820 // Store number of extracted samples.
1821 int packet_duration = 0;
1822 AudioDecoder* decoder = decoder_database_->GetDecoder(
1823 packet->header.payloadType);
1824 if (decoder) {
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001825 if (packet->sync_packet) {
1826 packet_duration = decoder_frame_length_;
1827 } else {
minyue@webrtc.org2c1bcf22015-02-17 10:17:09 +00001828 if (packet->primary) {
1829 packet_duration = decoder->PacketDuration(packet->payload,
1830 packet->payload_length);
1831 } else {
1832 packet_duration = decoder->
1833 PacketDurationRedundant(packet->payload, packet->payload_length);
1834 stats_.SecondaryDecodedSamples(packet_duration);
1835 }
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001836 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001837 } else {
pkasting@chromium.org026b8922015-01-30 19:53:42 +00001838 LOG_FERR1(LS_WARNING, GetDecoder,
1839 static_cast<int>(packet->header.payloadType))
1840 << "Could not find a decoder for a packet about to be extracted.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001841 assert(false);
1842 }
1843 if (packet_duration <= 0) {
1844 // Decoder did not return a packet duration. Assume that the packet
1845 // contains the same number of samples as the previous one.
1846 packet_duration = decoder_frame_length_;
1847 }
1848 extracted_samples = packet->header.timestamp - first_timestamp +
1849 packet_duration;
1850
1851 // Check what packet is available next.
1852 header = packet_buffer_->NextRtpHeader();
1853 next_packet_available = false;
1854 if (header && prev_payload_type == header->payloadType) {
1855 int16_t seq_no_diff = header->sequenceNumber - prev_sequence_number;
1856 int32_t ts_diff = header->timestamp - prev_timestamp;
1857 if (seq_no_diff == 1 ||
1858 (seq_no_diff == 0 && ts_diff == decoder_frame_length_)) {
1859 // The next sequence number is available, or the next part of a packet
1860 // that was split into pieces upon insertion.
1861 next_packet_available = true;
1862 }
1863 prev_sequence_number = header->sequenceNumber;
1864 }
1865 } while (extracted_samples < required_samples && next_packet_available);
1866
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00001867 if (extracted_samples > 0) {
1868 // Delete old packets only when we are going to decode something. Otherwise,
1869 // we could end up in the situation where we never decode anything, since
1870 // all incoming packets are considered too old but the buffer will also
1871 // never be flooded and flushed.
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001872 packet_buffer_->DiscardAllOldPackets(timestamp_);
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00001873 }
1874
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001875 return extracted_samples;
1876}
1877
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001878void NetEqImpl::UpdatePlcComponents(int fs_hz, size_t channels) {
1879 // Delete objects and create new ones.
1880 expand_.reset(expand_factory_->Create(background_noise_.get(),
1881 sync_buffer_.get(), &random_vector_,
1882 fs_hz, channels));
1883 merge_.reset(new Merge(fs_hz, channels, expand_.get(), sync_buffer_.get()));
1884}
1885
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001886void NetEqImpl::SetSampleRateAndChannels(int fs_hz, size_t channels) {
1887 LOG_API2(fs_hz, channels);
1888 // TODO(hlundin): Change to an enumerator and skip assert.
1889 assert(fs_hz == 8000 || fs_hz == 16000 || fs_hz == 32000 || fs_hz == 48000);
1890 assert(channels > 0);
1891
1892 fs_hz_ = fs_hz;
1893 fs_mult_ = fs_hz / 8000;
1894 output_size_samples_ = kOutputSizeMs * 8 * fs_mult_;
1895 decoder_frame_length_ = 3 * output_size_samples_; // Initialize to 30ms.
1896
1897 last_mode_ = kModeNormal;
1898
1899 // Create a new array of mute factors and set all to 1.
1900 mute_factor_array_.reset(new int16_t[channels]);
1901 for (size_t i = 0; i < channels; ++i) {
1902 mute_factor_array_[i] = 16384; // 1.0 in Q14.
1903 }
1904
1905 // Reset comfort noise decoder, if there is one active.
1906 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
1907 if (cng_decoder) {
1908 cng_decoder->Init();
1909 }
1910
1911 // Reinit post-decode VAD with new sample rate.
1912 assert(vad_.get()); // Cannot be NULL here.
1913 vad_->Init();
1914
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001915 // Delete algorithm buffer and create a new one.
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001916 algorithm_buffer_.reset(new AudioMultiVector(channels));
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001917
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001918 // Delete sync buffer and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001919 sync_buffer_.reset(new SyncBuffer(channels, kSyncBufferSize * fs_mult_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001920
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00001921 // Delete BackgroundNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001922 background_noise_.reset(new BackgroundNoise(channels));
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00001923 background_noise_->set_mode(background_noise_mode_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001924
1925 // Reset random vector.
1926 random_vector_.Reset();
1927
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001928 UpdatePlcComponents(fs_hz, channels);
1929
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001930 // Move index so that we create a small set of future samples (all 0).
1931 sync_buffer_->set_next_index(sync_buffer_->next_index() -
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001932 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001933
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001934 normal_.reset(new Normal(fs_hz, decoder_database_.get(), *background_noise_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001935 expand_.get()));
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +00001936 accelerate_.reset(
1937 accelerate_factory_->Create(fs_hz, channels, *background_noise_));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001938 preemptive_expand_.reset(preemptive_expand_factory_->Create(
1939 fs_hz, channels,
1940 *background_noise_,
1941 static_cast<int>(expand_->overlap_length())));
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001942
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001943 // Delete ComfortNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001944 comfort_noise_.reset(new ComfortNoise(fs_hz, decoder_database_.get(),
1945 sync_buffer_.get()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001946
1947 // Verify that |decoded_buffer_| is long enough.
1948 if (decoded_buffer_length_ < kMaxFrameSize * channels) {
1949 // Reallocate to larger size.
1950 decoded_buffer_length_ = kMaxFrameSize * channels;
1951 decoded_buffer_.reset(new int16_t[decoded_buffer_length_]);
1952 }
1953
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001954 // Create DecisionLogic if it is not created yet, then communicate new sample
1955 // rate and output size to DecisionLogic object.
1956 if (!decision_logic_.get()) {
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00001957 CreateDecisionLogic();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001958 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001959 decision_logic_->SetSampleRate(fs_hz_, output_size_samples_);
1960}
1961
1962NetEqOutputType NetEqImpl::LastOutputType() {
1963 assert(vad_.get());
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001964 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001965 if (last_mode_ == kModeCodecInternalCng || last_mode_ == kModeRfc3389Cng) {
1966 return kOutputCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001967 } else if (last_mode_ == kModeExpand && expand_->MuteFactor(0) == 0) {
1968 // Expand mode has faded down to background noise only (very long expand).
1969 return kOutputPLCtoCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001970 } else if (last_mode_ == kModeExpand) {
1971 return kOutputPLC;
wu@webrtc.org24301a62013-12-13 19:17:43 +00001972 } else if (vad_->running() && !vad_->active_speech()) {
1973 return kOutputVADPassive;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001974 } else {
1975 return kOutputNormal;
1976 }
1977}
1978
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00001979void NetEqImpl::CreateDecisionLogic() {
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001980 decision_logic_.reset(DecisionLogic::Create(fs_hz_, output_size_samples_,
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00001981 playout_mode_,
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001982 decoder_database_.get(),
1983 *packet_buffer_.get(),
1984 delay_manager_.get(),
1985 buffer_level_filter_.get()));
1986}
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001987} // namespace webrtc