blob: 4dd8a6afcb06f9441464cd59aa7f882158601353 [file] [log] [blame]
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001/*
2 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000011#include "webrtc/modules/audio_coding/neteq/neteq_impl.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000012
13#include <assert.h>
14#include <memory.h> // memset
15
16#include <algorithm>
17
18#include "webrtc/common_audio/signal_processing/include/signal_processing_library.h"
kwiberg@webrtc.orge04a93b2014-12-09 10:12:53 +000019#include "webrtc/modules/audio_coding/codecs/audio_decoder.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000020#include "webrtc/modules/audio_coding/neteq/accelerate.h"
21#include "webrtc/modules/audio_coding/neteq/background_noise.h"
22#include "webrtc/modules/audio_coding/neteq/buffer_level_filter.h"
23#include "webrtc/modules/audio_coding/neteq/comfort_noise.h"
24#include "webrtc/modules/audio_coding/neteq/decision_logic.h"
25#include "webrtc/modules/audio_coding/neteq/decoder_database.h"
26#include "webrtc/modules/audio_coding/neteq/defines.h"
27#include "webrtc/modules/audio_coding/neteq/delay_manager.h"
28#include "webrtc/modules/audio_coding/neteq/delay_peak_detector.h"
29#include "webrtc/modules/audio_coding/neteq/dtmf_buffer.h"
30#include "webrtc/modules/audio_coding/neteq/dtmf_tone_generator.h"
31#include "webrtc/modules/audio_coding/neteq/expand.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000032#include "webrtc/modules/audio_coding/neteq/merge.h"
33#include "webrtc/modules/audio_coding/neteq/normal.h"
34#include "webrtc/modules/audio_coding/neteq/packet_buffer.h"
35#include "webrtc/modules/audio_coding/neteq/packet.h"
36#include "webrtc/modules/audio_coding/neteq/payload_splitter.h"
37#include "webrtc/modules/audio_coding/neteq/post_decode_vad.h"
38#include "webrtc/modules/audio_coding/neteq/preemptive_expand.h"
39#include "webrtc/modules/audio_coding/neteq/sync_buffer.h"
40#include "webrtc/modules/audio_coding/neteq/timestamp_scaler.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000041#include "webrtc/modules/interface/module_common_types.h"
42#include "webrtc/system_wrappers/interface/critical_section_wrapper.h"
43#include "webrtc/system_wrappers/interface/logging.h"
44
45// Modify the code to obtain backwards bit-exactness. Once bit-exactness is no
46// longer required, this #define should be removed (and the code that it
47// enables).
48#define LEGACY_BITEXACT
49
50namespace webrtc {
51
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +000052NetEqImpl::NetEqImpl(const NetEq::Config& config,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000053 BufferLevelFilter* buffer_level_filter,
54 DecoderDatabase* decoder_database,
55 DelayManager* delay_manager,
56 DelayPeakDetector* delay_peak_detector,
57 DtmfBuffer* dtmf_buffer,
58 DtmfToneGenerator* dtmf_tone_generator,
59 PacketBuffer* packet_buffer,
60 PayloadSplitter* payload_splitter,
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +000061 TimestampScaler* timestamp_scaler,
62 AccelerateFactory* accelerate_factory,
63 ExpandFactory* expand_factory,
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +000064 PreemptiveExpandFactory* preemptive_expand_factory,
65 bool create_components)
henrik.lundin@webrtc.org2f816bb2014-06-05 10:37:13 +000066 : crit_sect_(CriticalSectionWrapper::CreateCriticalSection()),
67 buffer_level_filter_(buffer_level_filter),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000068 decoder_database_(decoder_database),
69 delay_manager_(delay_manager),
70 delay_peak_detector_(delay_peak_detector),
71 dtmf_buffer_(dtmf_buffer),
72 dtmf_tone_generator_(dtmf_tone_generator),
73 packet_buffer_(packet_buffer),
74 payload_splitter_(payload_splitter),
75 timestamp_scaler_(timestamp_scaler),
76 vad_(new PostDecodeVad()),
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +000077 expand_factory_(expand_factory),
78 accelerate_factory_(accelerate_factory),
79 preemptive_expand_factory_(preemptive_expand_factory),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000080 last_mode_(kModeNormal),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000081 decoded_buffer_length_(kMaxFrameSize),
82 decoded_buffer_(new int16_t[decoded_buffer_length_]),
83 playout_timestamp_(0),
84 new_codec_(false),
85 timestamp_(0),
86 reset_decoder_(false),
87 current_rtp_payload_type_(0xFF), // Invalid RTP payload type.
88 current_cng_rtp_payload_type_(0xFF), // Invalid RTP payload type.
89 ssrc_(0),
90 first_packet_(true),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000091 error_code_(0),
92 decoder_error_code_(0),
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +000093 background_noise_mode_(config.background_noise_mode),
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +000094 playout_mode_(config.playout_mode),
minyue@webrtc.orgd7301772013-08-29 00:58:14 +000095 decoded_packet_sequence_number_(-1),
96 decoded_packet_timestamp_(0) {
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +000097 int fs = config.sample_rate_hz;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000098 if (fs != 8000 && fs != 16000 && fs != 32000 && fs != 48000) {
99 LOG(LS_ERROR) << "Sample rate " << fs << " Hz not supported. " <<
100 "Changing to 8000 Hz.";
101 fs = 8000;
102 }
andrew@webrtc.org0569d932014-04-09 17:48:48 +0000103 LOG(LS_VERBOSE) << "Create NetEqImpl object with fs = " << fs << ".";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000104 fs_hz_ = fs;
105 fs_mult_ = fs / 8000;
106 output_size_samples_ = kOutputSizeMs * 8 * fs_mult_;
107 decoder_frame_length_ = 3 * output_size_samples_;
108 WebRtcSpl_Init();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000109 if (create_components) {
110 SetSampleRateAndChannels(fs, 1); // Default is 1 channel.
111 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000112}
113
114NetEqImpl::~NetEqImpl() {
115 LOG(LS_INFO) << "Deleting NetEqImpl object.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000116}
117
118int NetEqImpl::InsertPacket(const WebRtcRTPHeader& rtp_header,
119 const uint8_t* payload,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000120 size_t length_bytes,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000121 uint32_t receive_timestamp) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000122 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000123 LOG(LS_VERBOSE) << "InsertPacket: ts=" << rtp_header.header.timestamp <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000124 ", sn=" << rtp_header.header.sequenceNumber <<
125 ", pt=" << static_cast<int>(rtp_header.header.payloadType) <<
126 ", ssrc=" << rtp_header.header.ssrc <<
127 ", len=" << length_bytes;
128 int error = InsertPacketInternal(rtp_header, payload, length_bytes,
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000129 receive_timestamp, false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000130 if (error != 0) {
131 LOG_FERR1(LS_WARNING, InsertPacketInternal, error);
132 error_code_ = error;
133 return kFail;
134 }
135 return kOK;
136}
137
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000138int NetEqImpl::InsertSyncPacket(const WebRtcRTPHeader& rtp_header,
139 uint32_t receive_timestamp) {
140 CriticalSectionScoped lock(crit_sect_.get());
141 LOG(LS_VERBOSE) << "InsertPacket-Sync: ts="
142 << rtp_header.header.timestamp <<
143 ", sn=" << rtp_header.header.sequenceNumber <<
144 ", pt=" << static_cast<int>(rtp_header.header.payloadType) <<
145 ", ssrc=" << rtp_header.header.ssrc;
146
147 const uint8_t kSyncPayload[] = { 's', 'y', 'n', 'c' };
148 int error = InsertPacketInternal(
149 rtp_header, kSyncPayload, sizeof(kSyncPayload), receive_timestamp, true);
150
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000151 if (error != 0) {
152 LOG_FERR1(LS_WARNING, InsertPacketInternal, error);
153 error_code_ = error;
154 return kFail;
155 }
156 return kOK;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000157}
158
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000159int NetEqImpl::GetAudio(size_t max_length, int16_t* output_audio,
160 int* samples_per_channel, int* num_channels,
161 NetEqOutputType* type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000162 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000163 LOG(LS_VERBOSE) << "GetAudio";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000164 int error = GetAudioInternal(max_length, output_audio, samples_per_channel,
165 num_channels);
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000166 LOG(LS_VERBOSE) << "Produced " << *samples_per_channel <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000167 " samples/channel for " << *num_channels << " channel(s)";
168 if (error != 0) {
169 LOG_FERR1(LS_WARNING, GetAudioInternal, error);
170 error_code_ = error;
171 return kFail;
172 }
173 if (type) {
174 *type = LastOutputType();
175 }
176 return kOK;
177}
178
179int NetEqImpl::RegisterPayloadType(enum NetEqDecoder codec,
180 uint8_t rtp_payload_type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000181 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000182 LOG_API2(static_cast<int>(rtp_payload_type), codec);
183 int ret = decoder_database_->RegisterPayload(rtp_payload_type, codec);
184 if (ret != DecoderDatabase::kOK) {
185 LOG_FERR2(LS_WARNING, RegisterPayload, rtp_payload_type, codec);
186 switch (ret) {
187 case DecoderDatabase::kInvalidRtpPayloadType:
188 error_code_ = kInvalidRtpPayloadType;
189 break;
190 case DecoderDatabase::kCodecNotSupported:
191 error_code_ = kCodecNotSupported;
192 break;
193 case DecoderDatabase::kDecoderExists:
194 error_code_ = kDecoderExists;
195 break;
196 default:
197 error_code_ = kOtherError;
198 }
199 return kFail;
200 }
201 return kOK;
202}
203
204int NetEqImpl::RegisterExternalDecoder(AudioDecoder* decoder,
205 enum NetEqDecoder codec,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000206 uint8_t rtp_payload_type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000207 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000208 LOG_API2(static_cast<int>(rtp_payload_type), codec);
209 if (!decoder) {
210 LOG(LS_ERROR) << "Cannot register external decoder with NULL pointer";
211 assert(false);
212 return kFail;
213 }
kwiberg@webrtc.orge04a93b2014-12-09 10:12:53 +0000214 const int sample_rate_hz = CodecSampleRateHz(codec);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000215 int ret = decoder_database_->InsertExternal(rtp_payload_type, codec,
216 sample_rate_hz, decoder);
217 if (ret != DecoderDatabase::kOK) {
218 LOG_FERR2(LS_WARNING, InsertExternal, rtp_payload_type, codec);
219 switch (ret) {
220 case DecoderDatabase::kInvalidRtpPayloadType:
221 error_code_ = kInvalidRtpPayloadType;
222 break;
223 case DecoderDatabase::kCodecNotSupported:
224 error_code_ = kCodecNotSupported;
225 break;
226 case DecoderDatabase::kDecoderExists:
227 error_code_ = kDecoderExists;
228 break;
229 case DecoderDatabase::kInvalidSampleRate:
230 error_code_ = kInvalidSampleRate;
231 break;
232 case DecoderDatabase::kInvalidPointer:
233 error_code_ = kInvalidPointer;
234 break;
235 default:
236 error_code_ = kOtherError;
237 }
238 return kFail;
239 }
240 return kOK;
241}
242
243int NetEqImpl::RemovePayloadType(uint8_t rtp_payload_type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000244 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000245 LOG_API1(static_cast<int>(rtp_payload_type));
246 int ret = decoder_database_->Remove(rtp_payload_type);
247 if (ret == DecoderDatabase::kOK) {
248 return kOK;
249 } else if (ret == DecoderDatabase::kDecoderNotFound) {
250 error_code_ = kDecoderNotFound;
251 } else {
252 error_code_ = kOtherError;
253 }
254 LOG_FERR1(LS_WARNING, Remove, rtp_payload_type);
255 return kFail;
256}
257
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000258bool NetEqImpl::SetMinimumDelay(int delay_ms) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000259 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000260 if (delay_ms >= 0 && delay_ms < 10000) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000261 assert(delay_manager_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000262 return delay_manager_->SetMinimumDelay(delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000263 }
264 return false;
265}
266
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000267bool NetEqImpl::SetMaximumDelay(int delay_ms) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000268 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000269 if (delay_ms >= 0 && delay_ms < 10000) {
270 assert(delay_manager_.get());
271 return delay_manager_->SetMaximumDelay(delay_ms);
272 }
273 return false;
274}
275
276int NetEqImpl::LeastRequiredDelayMs() const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000277 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000278 assert(delay_manager_.get());
279 return delay_manager_->least_required_delay_ms();
280}
281
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000282// Deprecated.
283// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000284void NetEqImpl::SetPlayoutMode(NetEqPlayoutMode mode) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000285 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000286 if (mode != playout_mode_) {
287 playout_mode_ = mode;
288 CreateDecisionLogic();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000289 }
290}
291
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000292// Deprecated.
293// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000294NetEqPlayoutMode NetEqImpl::PlayoutMode() const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000295 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000296 return playout_mode_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000297}
298
299int NetEqImpl::NetworkStatistics(NetEqNetworkStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000300 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000301 assert(decoder_database_.get());
302 const int total_samples_in_buffers = packet_buffer_->NumSamplesInBuffer(
303 decoder_database_.get(), decoder_frame_length_) +
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000304 static_cast<int>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000305 assert(delay_manager_.get());
306 assert(decision_logic_.get());
307 stats_.GetNetworkStatistics(fs_hz_, total_samples_in_buffers,
308 decoder_frame_length_, *delay_manager_.get(),
309 *decision_logic_.get(), stats);
310 return 0;
311}
312
313void NetEqImpl::WaitingTimes(std::vector<int>* waiting_times) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000314 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000315 stats_.WaitingTimes(waiting_times);
316}
317
318void NetEqImpl::GetRtcpStatistics(RtcpStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000319 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000320 if (stats) {
321 rtcp_.GetStatistics(false, stats);
322 }
323}
324
325void NetEqImpl::GetRtcpStatisticsNoReset(RtcpStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000326 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000327 if (stats) {
328 rtcp_.GetStatistics(true, stats);
329 }
330}
331
332void NetEqImpl::EnableVad() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000333 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000334 assert(vad_.get());
335 vad_->Enable();
336}
337
338void NetEqImpl::DisableVad() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000339 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000340 assert(vad_.get());
341 vad_->Disable();
342}
343
wu@webrtc.org94454b72014-06-05 20:34:08 +0000344bool NetEqImpl::GetPlayoutTimestamp(uint32_t* timestamp) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000345 CriticalSectionScoped lock(crit_sect_.get());
wu@webrtc.org94454b72014-06-05 20:34:08 +0000346 if (first_packet_) {
347 // We don't have a valid RTP timestamp until we have decoded our first
348 // RTP packet.
349 return false;
350 }
351 *timestamp = timestamp_scaler_->ToExternal(playout_timestamp_);
352 return true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000353}
354
henrik.lundin@webrtc.orgb0f4b3d2014-11-04 08:53:10 +0000355int NetEqImpl::LastError() const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000356 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000357 return error_code_;
358}
359
360int NetEqImpl::LastDecoderError() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000361 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000362 return decoder_error_code_;
363}
364
365void NetEqImpl::FlushBuffers() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000366 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000367 LOG_API0();
368 packet_buffer_->Flush();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000369 assert(sync_buffer_.get());
370 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000371 sync_buffer_->Flush();
372 sync_buffer_->set_next_index(sync_buffer_->next_index() -
373 expand_->overlap_length());
374 // Set to wait for new codec.
375 first_packet_ = true;
376}
377
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000378void NetEqImpl::PacketBufferStatistics(int* current_num_packets,
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000379 int* max_num_packets) const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000380 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000381 packet_buffer_->BufferStat(current_num_packets, max_num_packets);
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000382}
383
turaj@webrtc.orgff43c852013-09-25 00:07:27 +0000384int NetEqImpl::DecodedRtpInfo(int* sequence_number, uint32_t* timestamp) const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000385 CriticalSectionScoped lock(crit_sect_.get());
minyue@webrtc.orgd7301772013-08-29 00:58:14 +0000386 if (decoded_packet_sequence_number_ < 0)
387 return -1;
388 *sequence_number = decoded_packet_sequence_number_;
389 *timestamp = decoded_packet_timestamp_;
390 return 0;
391}
392
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000393const SyncBuffer* NetEqImpl::sync_buffer_for_test() const {
394 CriticalSectionScoped lock(crit_sect_.get());
395 return sync_buffer_.get();
396}
397
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000398// Methods below this line are private.
399
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000400int NetEqImpl::InsertPacketInternal(const WebRtcRTPHeader& rtp_header,
401 const uint8_t* payload,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000402 size_t length_bytes,
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000403 uint32_t receive_timestamp,
404 bool is_sync_packet) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000405 if (!payload) {
406 LOG_F(LS_ERROR) << "payload == NULL";
407 return kInvalidPointer;
408 }
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000409 // Sanity checks for sync-packets.
410 if (is_sync_packet) {
411 if (decoder_database_->IsDtmf(rtp_header.header.payloadType) ||
412 decoder_database_->IsRed(rtp_header.header.payloadType) ||
413 decoder_database_->IsComfortNoise(rtp_header.header.payloadType)) {
414 LOG_F(LS_ERROR) << "Sync-packet with an unacceptable payload type "
415 << rtp_header.header.payloadType;
416 return kSyncPacketNotAccepted;
417 }
418 if (first_packet_ ||
419 rtp_header.header.payloadType != current_rtp_payload_type_ ||
420 rtp_header.header.ssrc != ssrc_) {
421 // Even if |current_rtp_payload_type_| is 0xFF, sync-packet isn't
422 // accepted.
423 LOG_F(LS_ERROR) << "Changing codec, SSRC or first packet "
424 "with sync-packet.";
425 return kSyncPacketNotAccepted;
426 }
427 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000428 PacketList packet_list;
429 RTPHeader main_header;
430 {
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000431 // Convert to Packet.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000432 // Create |packet| within this separate scope, since it should not be used
433 // directly once it's been inserted in the packet list. This way, |packet|
434 // is not defined outside of this block.
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000435 Packet* packet = new Packet;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000436 packet->header.markerBit = false;
437 packet->header.payloadType = rtp_header.header.payloadType;
438 packet->header.sequenceNumber = rtp_header.header.sequenceNumber;
439 packet->header.timestamp = rtp_header.header.timestamp;
440 packet->header.ssrc = rtp_header.header.ssrc;
441 packet->header.numCSRCs = 0;
442 packet->payload_length = length_bytes;
443 packet->primary = true;
444 packet->waiting_time = 0;
445 packet->payload = new uint8_t[packet->payload_length];
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000446 packet->sync_packet = is_sync_packet;
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +0000447 if (!packet->payload) {
448 LOG_F(LS_ERROR) << "Payload pointer is NULL.";
449 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000450 assert(payload); // Already checked above.
451 memcpy(packet->payload, payload, packet->payload_length);
452 // Insert packet in a packet list.
453 packet_list.push_back(packet);
454 // Save main payloads header for later.
455 memcpy(&main_header, &packet->header, sizeof(main_header));
456 }
457
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000458 bool update_sample_rate_and_channels = false;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000459 // Reinitialize NetEq if it's needed (changed SSRC or first call).
460 if ((main_header.ssrc != ssrc_) || first_packet_) {
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000461 // Note: |first_packet_| will be cleared further down in this method, once
462 // the packet has been successfully inserted into the packet buffer.
463
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000464 rtcp_.Init(main_header.sequenceNumber);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000465
466 // Flush the packet buffer and DTMF buffer.
467 packet_buffer_->Flush();
468 dtmf_buffer_->Flush();
469
470 // Store new SSRC.
471 ssrc_ = main_header.ssrc;
472
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000473 // Update audio buffer timestamp.
474 sync_buffer_->IncreaseEndTimestamp(main_header.timestamp - timestamp_);
475
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000476 // Update codecs.
477 timestamp_ = main_header.timestamp;
478 current_rtp_payload_type_ = main_header.payloadType;
479
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000480 // Reset timestamp scaling.
481 timestamp_scaler_->Reset();
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000482
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000483 // Trigger an update of sampling rate and the number of channels.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000484 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000485 }
486
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000487 // Update RTCP statistics, only for regular packets.
488 if (!is_sync_packet)
489 rtcp_.Update(main_header, receive_timestamp);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000490
491 // Check for RED payload type, and separate payloads into several packets.
492 if (decoder_database_->IsRed(main_header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000493 assert(!is_sync_packet); // We had a sanity check for this.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000494 if (payload_splitter_->SplitRed(&packet_list) != PayloadSplitter::kOK) {
495 LOG_FERR1(LS_WARNING, SplitRed, packet_list.size());
496 PacketBuffer::DeleteAllPackets(&packet_list);
497 return kRedundancySplitError;
498 }
499 // Only accept a few RED payloads of the same type as the main data,
500 // DTMF events and CNG.
501 payload_splitter_->CheckRedPayloads(&packet_list, *decoder_database_);
502 // Update the stored main payload header since the main payload has now
503 // changed.
504 memcpy(&main_header, &packet_list.front()->header, sizeof(main_header));
505 }
506
507 // Check payload types.
508 if (decoder_database_->CheckPayloadTypes(packet_list) ==
509 DecoderDatabase::kDecoderNotFound) {
510 LOG_FERR1(LS_WARNING, CheckPayloadTypes, packet_list.size());
511 PacketBuffer::DeleteAllPackets(&packet_list);
512 return kUnknownRtpPayloadType;
513 }
514
515 // Scale timestamp to internal domain (only for some codecs).
516 timestamp_scaler_->ToInternal(&packet_list);
517
518 // Process DTMF payloads. Cycle through the list of packets, and pick out any
519 // DTMF payloads found.
520 PacketList::iterator it = packet_list.begin();
521 while (it != packet_list.end()) {
522 Packet* current_packet = (*it);
523 assert(current_packet);
524 assert(current_packet->payload);
525 if (decoder_database_->IsDtmf(current_packet->header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000526 assert(!current_packet->sync_packet); // We had a sanity check for this.
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000527 DtmfEvent event;
528 int ret = DtmfBuffer::ParseEvent(
529 current_packet->header.timestamp,
530 current_packet->payload,
531 current_packet->payload_length,
532 &event);
533 if (ret != DtmfBuffer::kOK) {
534 LOG_FERR2(LS_WARNING, ParseEvent, ret,
535 current_packet->payload_length);
536 PacketBuffer::DeleteAllPackets(&packet_list);
537 return kDtmfParsingError;
538 }
539 if (dtmf_buffer_->InsertEvent(event) != DtmfBuffer::kOK) {
540 LOG_FERR0(LS_WARNING, InsertEvent);
541 PacketBuffer::DeleteAllPackets(&packet_list);
542 return kDtmfInsertError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000543 }
544 // TODO(hlundin): Let the destructor of Packet handle the payload.
545 delete [] current_packet->payload;
546 delete current_packet;
547 it = packet_list.erase(it);
548 } else {
549 ++it;
550 }
551 }
552
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000553 // Check for FEC in packets, and separate payloads into several packets.
554 int ret = payload_splitter_->SplitFec(&packet_list, decoder_database_.get());
555 if (ret != PayloadSplitter::kOK) {
556 LOG_FERR1(LS_WARNING, SplitFec, packet_list.size());
557 PacketBuffer::DeleteAllPackets(&packet_list);
558 switch (ret) {
559 case PayloadSplitter::kUnknownPayloadType:
560 return kUnknownRtpPayloadType;
561 default:
562 return kOtherError;
563 }
564 }
565
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000566 // Split payloads into smaller chunks. This also verifies that all payloads
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000567 // are of a known payload type. SplitAudio() method is protected against
568 // sync-packets.
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +0000569 ret = payload_splitter_->SplitAudio(&packet_list, *decoder_database_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000570 if (ret != PayloadSplitter::kOK) {
571 LOG_FERR1(LS_WARNING, SplitAudio, packet_list.size());
572 PacketBuffer::DeleteAllPackets(&packet_list);
573 switch (ret) {
574 case PayloadSplitter::kUnknownPayloadType:
575 return kUnknownRtpPayloadType;
576 case PayloadSplitter::kFrameSplitError:
577 return kFrameSplitError;
578 default:
579 return kOtherError;
580 }
581 }
582
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000583 // Update bandwidth estimate, if the packet is not sync-packet.
584 if (!packet_list.empty() && !packet_list.front()->sync_packet) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000585 // The list can be empty here if we got nothing but DTMF payloads.
586 AudioDecoder* decoder =
587 decoder_database_->GetDecoder(main_header.payloadType);
588 assert(decoder); // Should always get a valid object, since we have
589 // already checked that the payload types are known.
590 decoder->IncomingPacket(packet_list.front()->payload,
591 packet_list.front()->payload_length,
592 packet_list.front()->header.sequenceNumber,
593 packet_list.front()->header.timestamp,
594 receive_timestamp);
595 }
596
597 // Insert packets in buffer.
598 int temp_bufsize = packet_buffer_->NumPacketsInBuffer();
599 ret = packet_buffer_->InsertPacketList(
600 &packet_list,
601 *decoder_database_,
602 &current_rtp_payload_type_,
603 &current_cng_rtp_payload_type_);
604 if (ret == PacketBuffer::kFlushed) {
605 // Reset DSP timestamp etc. if packet buffer flushed.
606 new_codec_ = true;
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000607 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000608 LOG_F(LS_WARNING) << "Packet buffer flushed";
609 } else if (ret != PacketBuffer::kOK) {
610 LOG_FERR1(LS_WARNING, InsertPacketList, packet_list.size());
611 PacketBuffer::DeleteAllPackets(&packet_list);
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000612 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000613 }
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000614
615 if (first_packet_) {
616 first_packet_ = false;
617 // Update the codec on the next GetAudio call.
618 new_codec_ = true;
619 }
620
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000621 if (current_rtp_payload_type_ != 0xFF) {
622 const DecoderDatabase::DecoderInfo* dec_info =
623 decoder_database_->GetDecoderInfo(current_rtp_payload_type_);
624 if (!dec_info) {
625 assert(false); // Already checked that the payload type is known.
626 }
627 }
628
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000629 if (update_sample_rate_and_channels && !packet_buffer_->Empty()) {
630 // We do not use |current_rtp_payload_type_| to |set payload_type|, but
631 // get the next RTP header from |packet_buffer_| to obtain the payload type.
632 // The reason for it is the following corner case. If NetEq receives a
633 // CNG packet with a sample rate different than the current CNG then it
634 // flushes its buffer, assuming send codec must have been changed. However,
635 // payload type of the hypothetically new send codec is not known.
636 const RTPHeader* rtp_header = packet_buffer_->NextRtpHeader();
637 assert(rtp_header);
638 int payload_type = rtp_header->payloadType;
639 AudioDecoder* decoder = decoder_database_->GetDecoder(payload_type);
640 assert(decoder); // Payloads are already checked to be valid.
641 const DecoderDatabase::DecoderInfo* decoder_info =
642 decoder_database_->GetDecoderInfo(payload_type);
643 assert(decoder_info);
644 if (decoder_info->fs_hz != fs_hz_ ||
645 decoder->channels() != algorithm_buffer_->Channels())
646 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->channels());
647 }
648
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000649 // TODO(hlundin): Move this code to DelayManager class.
650 const DecoderDatabase::DecoderInfo* dec_info =
651 decoder_database_->GetDecoderInfo(main_header.payloadType);
652 assert(dec_info); // Already checked that the payload type is known.
653 delay_manager_->LastDecoderType(dec_info->codec_type);
654 if (delay_manager_->last_pack_cng_or_dtmf() == 0) {
655 // Calculate the total speech length carried in each packet.
656 temp_bufsize = packet_buffer_->NumPacketsInBuffer() - temp_bufsize;
657 temp_bufsize *= decoder_frame_length_;
658
659 if ((temp_bufsize > 0) &&
660 (temp_bufsize != decision_logic_->packet_length_samples())) {
661 decision_logic_->set_packet_length_samples(temp_bufsize);
662 delay_manager_->SetPacketAudioLength((1000 * temp_bufsize) / fs_hz_);
663 }
664
665 // Update statistics.
pbos@webrtc.org0946a562013-04-09 00:28:06 +0000666 if ((int32_t) (main_header.timestamp - timestamp_) >= 0 &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000667 !new_codec_) {
668 // Only update statistics if incoming packet is not older than last played
669 // out packet, and if new codec flag is not set.
670 delay_manager_->Update(main_header.sequenceNumber, main_header.timestamp,
671 fs_hz_);
672 }
673 } else if (delay_manager_->last_pack_cng_or_dtmf() == -1) {
674 // This is first "normal" packet after CNG or DTMF.
675 // Reset packet time counter and measure time until next packet,
676 // but don't update statistics.
677 delay_manager_->set_last_pack_cng_or_dtmf(0);
678 delay_manager_->ResetPacketIatCount();
679 }
680 return 0;
681}
682
683int NetEqImpl::GetAudioInternal(size_t max_length, int16_t* output,
684 int* samples_per_channel, int* num_channels) {
685 PacketList packet_list;
686 DtmfEvent dtmf_event;
687 Operations operation;
688 bool play_dtmf;
689 int return_value = GetDecision(&operation, &packet_list, &dtmf_event,
690 &play_dtmf);
691 if (return_value != 0) {
692 LOG_FERR1(LS_WARNING, GetDecision, return_value);
693 assert(false);
694 last_mode_ = kModeError;
695 return return_value;
696 }
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000697 LOG(LS_VERBOSE) << "GetDecision returned operation=" << operation <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000698 " and " << packet_list.size() << " packet(s)";
699
700 AudioDecoder::SpeechType speech_type;
701 int length = 0;
702 int decode_return_value = Decode(&packet_list, &operation,
703 &length, &speech_type);
704
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000705 assert(vad_.get());
706 bool sid_frame_available =
707 (operation == kRfc3389Cng && !packet_list.empty());
708 vad_->Update(decoded_buffer_.get(), length, speech_type,
709 sid_frame_available, fs_hz_);
710
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000711 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000712 switch (operation) {
713 case kNormal: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000714 DoNormal(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000715 break;
716 }
717 case kMerge: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000718 DoMerge(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000719 break;
720 }
721 case kExpand: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000722 return_value = DoExpand(play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000723 break;
724 }
725 case kAccelerate: {
726 return_value = DoAccelerate(decoded_buffer_.get(), length, speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000727 play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000728 break;
729 }
730 case kPreemptiveExpand: {
731 return_value = DoPreemptiveExpand(decoded_buffer_.get(), length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000732 speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000733 break;
734 }
735 case kRfc3389Cng:
736 case kRfc3389CngNoPacket: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000737 return_value = DoRfc3389Cng(&packet_list, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000738 break;
739 }
740 case kCodecInternalCng: {
741 // This handles the case when there is no transmission and the decoder
742 // should produce internal comfort noise.
743 // TODO(hlundin): Write test for codec-internal CNG.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000744 DoCodecInternalCng();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000745 break;
746 }
747 case kDtmf: {
748 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000749 return_value = DoDtmf(dtmf_event, &play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000750 break;
751 }
752 case kAlternativePlc: {
753 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000754 DoAlternativePlc(false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000755 break;
756 }
757 case kAlternativePlcIncreaseTimestamp: {
758 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000759 DoAlternativePlc(true);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000760 break;
761 }
762 case kAudioRepetitionIncreaseTimestamp: {
763 // TODO(hlundin): Write test for this.
764 sync_buffer_->IncreaseEndTimestamp(output_size_samples_);
765 // Skipping break on purpose. Execution should move on into the
766 // next case.
kjellander@webrtc.org7d2b6a92015-01-28 18:37:58 +0000767 FALLTHROUGH();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000768 }
769 case kAudioRepetition: {
770 // TODO(hlundin): Write test for this.
771 // Copy last |output_size_samples_| from |sync_buffer_| to
772 // |algorithm_buffer|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000773 algorithm_buffer_->PushBackFromIndex(
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000774 *sync_buffer_, sync_buffer_->Size() - output_size_samples_);
775 expand_->Reset();
776 break;
777 }
778 case kUndefined: {
779 LOG_F(LS_ERROR) << "Invalid operation kUndefined.";
780 assert(false); // This should not happen.
781 last_mode_ = kModeError;
782 return kInvalidOperation;
783 }
784 } // End of switch.
785 if (return_value < 0) {
786 return return_value;
787 }
788
789 if (last_mode_ != kModeRfc3389Cng) {
790 comfort_noise_->Reset();
791 }
792
793 // Copy from |algorithm_buffer| to |sync_buffer_|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000794 sync_buffer_->PushBack(*algorithm_buffer_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000795
796 // Extract data from |sync_buffer_| to |output|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000797 size_t num_output_samples_per_channel = output_size_samples_;
798 size_t num_output_samples = output_size_samples_ * sync_buffer_->Channels();
799 if (num_output_samples > max_length) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000800 LOG(LS_WARNING) << "Output array is too short. " << max_length << " < " <<
801 output_size_samples_ << " * " << sync_buffer_->Channels();
802 num_output_samples = max_length;
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000803 num_output_samples_per_channel = static_cast<int>(
804 max_length / sync_buffer_->Channels());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000805 }
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000806 int samples_from_sync = static_cast<int>(
807 sync_buffer_->GetNextAudioInterleaved(num_output_samples_per_channel,
808 output));
809 *num_channels = static_cast<int>(sync_buffer_->Channels());
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000810 LOG(LS_VERBOSE) << "Sync buffer (" << *num_channels << " channel(s)):" <<
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000811 " insert " << algorithm_buffer_->Size() << " samples, extract " <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000812 samples_from_sync << " samples";
813 if (samples_from_sync != output_size_samples_) {
814 LOG_F(LS_ERROR) << "samples_from_sync != output_size_samples_";
minyue@webrtc.orgdb1cefc2013-08-13 01:39:21 +0000815 // TODO(minyue): treatment of under-run, filling zeros
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000816 memset(output, 0, num_output_samples * sizeof(int16_t));
817 *samples_per_channel = output_size_samples_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000818 return kSampleUnderrun;
819 }
820 *samples_per_channel = output_size_samples_;
821
822 // Should always have overlap samples left in the |sync_buffer_|.
823 assert(sync_buffer_->FutureLength() >= expand_->overlap_length());
824
825 if (play_dtmf) {
826 return_value = DtmfOverdub(dtmf_event, sync_buffer_->Channels(), output);
827 }
828
829 // Update the background noise parameters if last operation wrote data
830 // straight from the decoder to the |sync_buffer_|. That is, none of the
831 // operations that modify the signal can be followed by a parameter update.
832 if ((last_mode_ == kModeNormal) ||
833 (last_mode_ == kModeAccelerateFail) ||
834 (last_mode_ == kModePreemptiveExpandFail) ||
835 (last_mode_ == kModeRfc3389Cng) ||
836 (last_mode_ == kModeCodecInternalCng)) {
837 background_noise_->Update(*sync_buffer_, *vad_.get());
838 }
839
840 if (operation == kDtmf) {
841 // DTMF data was written the end of |sync_buffer_|.
842 // Update index to end of DTMF data in |sync_buffer_|.
843 sync_buffer_->set_dtmf_index(sync_buffer_->Size());
844 }
845
henrik.lundin@webrtc.orged865b52014-03-06 10:28:07 +0000846 if (last_mode_ != kModeExpand) {
847 // If last operation was not expand, calculate the |playout_timestamp_| from
848 // the |sync_buffer_|. However, do not update the |playout_timestamp_| if it
849 // would be moved "backwards".
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000850 uint32_t temp_timestamp = sync_buffer_->end_timestamp() -
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000851 static_cast<uint32_t>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000852 if (static_cast<int32_t>(temp_timestamp - playout_timestamp_) > 0) {
853 playout_timestamp_ = temp_timestamp;
854 }
855 } else {
856 // Use dead reckoning to estimate the |playout_timestamp_|.
857 playout_timestamp_ += output_size_samples_;
858 }
859
860 if (decode_return_value) return decode_return_value;
861 return return_value;
862}
863
864int NetEqImpl::GetDecision(Operations* operation,
865 PacketList* packet_list,
866 DtmfEvent* dtmf_event,
867 bool* play_dtmf) {
868 // Initialize output variables.
869 *play_dtmf = false;
870 *operation = kUndefined;
871
872 // Increment time counters.
873 packet_buffer_->IncrementWaitingTimes();
874 stats_.IncreaseCounter(output_size_samples_, fs_hz_);
875
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000876 assert(sync_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000877 uint32_t end_timestamp = sync_buffer_->end_timestamp();
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +0000878 if (!new_codec_) {
879 const uint32_t five_seconds_samples = 5 * fs_hz_;
880 packet_buffer_->DiscardOldPackets(end_timestamp, five_seconds_samples);
881 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000882 const RTPHeader* header = packet_buffer_->NextRtpHeader();
883
henrik.lundin@webrtc.orgca8cb952014-03-12 10:26:52 +0000884 if (decision_logic_->CngRfc3389On() || last_mode_ == kModeRfc3389Cng) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000885 // Because of timestamp peculiarities, we have to "manually" disallow using
886 // a CNG packet with the same timestamp as the one that was last played.
887 // This can happen when using redundancy and will cause the timing to shift.
henrik.lundin@webrtc.org24779fe2014-03-14 12:40:05 +0000888 while (header && decoder_database_->IsComfortNoise(header->payloadType) &&
889 (end_timestamp >= header->timestamp ||
890 end_timestamp + decision_logic_->generated_noise_samples() >
891 header->timestamp)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000892 // Don't use this packet, discard it.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000893 if (packet_buffer_->DiscardNextPacket() != PacketBuffer::kOK) {
894 assert(false); // Must be ok by design.
895 }
896 // Check buffer again.
897 if (!new_codec_) {
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +0000898 packet_buffer_->DiscardOldPackets(end_timestamp, 5 * fs_hz_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000899 }
900 header = packet_buffer_->NextRtpHeader();
901 }
902 }
903
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000904 assert(expand_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000905 const int samples_left = static_cast<int>(sync_buffer_->FutureLength() -
906 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000907 if (last_mode_ == kModeAccelerateSuccess ||
908 last_mode_ == kModeAccelerateLowEnergy ||
909 last_mode_ == kModePreemptiveExpandSuccess ||
910 last_mode_ == kModePreemptiveExpandLowEnergy) {
911 // Subtract (samples_left + output_size_samples_) from sampleMemory.
912 decision_logic_->AddSampleMemory(-(samples_left + output_size_samples_));
913 }
914
915 // Check if it is time to play a DTMF event.
916 if (dtmf_buffer_->GetEvent(end_timestamp +
917 decision_logic_->generated_noise_samples(),
918 dtmf_event)) {
919 *play_dtmf = true;
920 }
921
922 // Get instruction.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000923 assert(sync_buffer_.get());
924 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000925 *operation = decision_logic_->GetDecision(*sync_buffer_,
926 *expand_,
927 decoder_frame_length_,
928 header,
929 last_mode_,
930 *play_dtmf,
931 &reset_decoder_);
932
933 // Check if we already have enough samples in the |sync_buffer_|. If so,
934 // change decision to normal, unless the decision was merge, accelerate, or
935 // preemptive expand.
936 if (samples_left >= output_size_samples_ &&
937 *operation != kMerge &&
938 *operation != kAccelerate &&
939 *operation != kPreemptiveExpand) {
940 *operation = kNormal;
941 return 0;
942 }
943
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000944 decision_logic_->ExpandDecision(*operation);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000945
946 // Check conditions for reset.
947 if (new_codec_ || *operation == kUndefined) {
948 // The only valid reason to get kUndefined is that new_codec_ is set.
949 assert(new_codec_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000950 if (*play_dtmf && !header) {
951 timestamp_ = dtmf_event->timestamp;
952 } else {
953 assert(header);
954 if (!header) {
955 LOG_F(LS_ERROR) << "Packet missing where it shouldn't.";
956 return -1;
957 }
958 timestamp_ = header->timestamp;
959 if (*operation == kRfc3389CngNoPacket
960#ifndef LEGACY_BITEXACT
961 // Without this check, it can happen that a non-CNG packet is sent to
962 // the CNG decoder as if it was a SID frame. This is clearly a bug,
963 // but is kept for now to maintain bit-exactness with the test
964 // vectors.
965 && decoder_database_->IsComfortNoise(header->payloadType)
966#endif
967 ) {
968 // Change decision to CNG packet, since we do have a CNG packet, but it
969 // was considered too early to use. Now, use it anyway.
970 *operation = kRfc3389Cng;
971 } else if (*operation != kRfc3389Cng) {
972 *operation = kNormal;
973 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000974 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000975 // Adjust |sync_buffer_| timestamp before setting |end_timestamp| to the
976 // new value.
977 sync_buffer_->IncreaseEndTimestamp(timestamp_ - end_timestamp);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000978 end_timestamp = timestamp_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000979 new_codec_ = false;
980 decision_logic_->SoftReset();
981 buffer_level_filter_->Reset();
982 delay_manager_->Reset();
983 stats_.ResetMcu();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000984 }
985
986 int required_samples = output_size_samples_;
987 const int samples_10_ms = 80 * fs_mult_;
988 const int samples_20_ms = 2 * samples_10_ms;
989 const int samples_30_ms = 3 * samples_10_ms;
990
991 switch (*operation) {
992 case kExpand: {
993 timestamp_ = end_timestamp;
994 return 0;
995 }
996 case kRfc3389CngNoPacket:
997 case kCodecInternalCng: {
998 return 0;
999 }
1000 case kDtmf: {
1001 // TODO(hlundin): Write test for this.
1002 // Update timestamp.
1003 timestamp_ = end_timestamp;
1004 if (decision_logic_->generated_noise_samples() > 0 &&
1005 last_mode_ != kModeDtmf) {
1006 // Make a jump in timestamp due to the recently played comfort noise.
1007 uint32_t timestamp_jump = decision_logic_->generated_noise_samples();
1008 sync_buffer_->IncreaseEndTimestamp(timestamp_jump);
1009 timestamp_ += timestamp_jump;
1010 }
1011 decision_logic_->set_generated_noise_samples(0);
1012 return 0;
1013 }
1014 case kAccelerate: {
1015 // In order to do a accelerate we need at least 30 ms of audio data.
1016 if (samples_left >= samples_30_ms) {
1017 // Already have enough data, so we do not need to extract any more.
1018 decision_logic_->set_sample_memory(samples_left);
1019 decision_logic_->set_prev_time_scale(true);
1020 return 0;
1021 } else if (samples_left >= samples_10_ms &&
1022 decoder_frame_length_ >= samples_30_ms) {
1023 // Avoid decoding more data as it might overflow the playout buffer.
1024 *operation = kNormal;
1025 return 0;
1026 } else if (samples_left < samples_20_ms &&
1027 decoder_frame_length_ < samples_30_ms) {
1028 // Build up decoded data by decoding at least 20 ms of audio data. Do
1029 // not perform accelerate yet, but wait until we only need to do one
1030 // decoding.
1031 required_samples = 2 * output_size_samples_;
1032 *operation = kNormal;
1033 }
1034 // If none of the above is true, we have one of two possible situations:
1035 // (1) 20 ms <= samples_left < 30 ms and decoder_frame_length_ < 30 ms; or
1036 // (2) samples_left < 10 ms and decoder_frame_length_ >= 30 ms.
1037 // In either case, we move on with the accelerate decision, and decode one
1038 // frame now.
1039 break;
1040 }
1041 case kPreemptiveExpand: {
1042 // In order to do a preemptive expand we need at least 30 ms of decoded
1043 // audio data.
1044 if ((samples_left >= samples_30_ms) ||
1045 (samples_left >= samples_10_ms &&
1046 decoder_frame_length_ >= samples_30_ms)) {
1047 // Already have enough data, so we do not need to extract any more.
1048 // Or, avoid decoding more data as it might overflow the playout buffer.
1049 // Still try preemptive expand, though.
1050 decision_logic_->set_sample_memory(samples_left);
1051 decision_logic_->set_prev_time_scale(true);
1052 return 0;
1053 }
1054 if (samples_left < samples_20_ms &&
1055 decoder_frame_length_ < samples_30_ms) {
1056 // Build up decoded data by decoding at least 20 ms of audio data.
1057 // Still try to perform preemptive expand.
1058 required_samples = 2 * output_size_samples_;
1059 }
1060 // Move on with the preemptive expand decision.
1061 break;
1062 }
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001063 case kMerge: {
1064 required_samples =
1065 std::max(merge_->RequiredFutureSamples(), required_samples);
1066 break;
1067 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001068 default: {
1069 // Do nothing.
1070 }
1071 }
1072
1073 // Get packets from buffer.
1074 int extracted_samples = 0;
1075 if (header &&
1076 *operation != kAlternativePlc &&
1077 *operation != kAlternativePlcIncreaseTimestamp &&
1078 *operation != kAudioRepetition &&
1079 *operation != kAudioRepetitionIncreaseTimestamp) {
1080 sync_buffer_->IncreaseEndTimestamp(header->timestamp - end_timestamp);
1081 if (decision_logic_->CngOff()) {
1082 // Adjustment of timestamp only corresponds to an actual packet loss
1083 // if comfort noise is not played. If comfort noise was just played,
1084 // this adjustment of timestamp is only done to get back in sync with the
1085 // stream timestamp; no loss to report.
1086 stats_.LostSamples(header->timestamp - end_timestamp);
1087 }
1088
1089 if (*operation != kRfc3389Cng) {
1090 // We are about to decode and use a non-CNG packet.
1091 decision_logic_->SetCngOff();
1092 }
1093 // Reset CNG timestamp as a new packet will be delivered.
1094 // (Also if this is a CNG packet, since playedOutTS is updated.)
1095 decision_logic_->set_generated_noise_samples(0);
1096
1097 extracted_samples = ExtractPackets(required_samples, packet_list);
1098 if (extracted_samples < 0) {
1099 LOG_F(LS_WARNING) << "Failed to extract packets from buffer.";
1100 return kPacketBufferCorruption;
1101 }
1102 }
1103
1104 if (*operation == kAccelerate ||
1105 *operation == kPreemptiveExpand) {
1106 decision_logic_->set_sample_memory(samples_left + extracted_samples);
1107 decision_logic_->set_prev_time_scale(true);
1108 }
1109
1110 if (*operation == kAccelerate) {
1111 // Check that we have enough data (30ms) to do accelerate.
1112 if (extracted_samples + samples_left < samples_30_ms) {
1113 // TODO(hlundin): Write test for this.
1114 // Not enough, do normal operation instead.
1115 *operation = kNormal;
1116 }
1117 }
1118
1119 timestamp_ = end_timestamp;
1120 return 0;
1121}
1122
1123int NetEqImpl::Decode(PacketList* packet_list, Operations* operation,
1124 int* decoded_length,
1125 AudioDecoder::SpeechType* speech_type) {
1126 *speech_type = AudioDecoder::kSpeech;
1127 AudioDecoder* decoder = NULL;
1128 if (!packet_list->empty()) {
1129 const Packet* packet = packet_list->front();
1130 int payload_type = packet->header.payloadType;
1131 if (!decoder_database_->IsComfortNoise(payload_type)) {
1132 decoder = decoder_database_->GetDecoder(payload_type);
1133 assert(decoder);
1134 if (!decoder) {
1135 LOG_FERR1(LS_WARNING, GetDecoder, payload_type);
1136 PacketBuffer::DeleteAllPackets(packet_list);
1137 return kDecoderNotFound;
1138 }
1139 bool decoder_changed;
1140 decoder_database_->SetActiveDecoder(payload_type, &decoder_changed);
1141 if (decoder_changed) {
1142 // We have a new decoder. Re-init some values.
1143 const DecoderDatabase::DecoderInfo* decoder_info = decoder_database_
1144 ->GetDecoderInfo(payload_type);
1145 assert(decoder_info);
1146 if (!decoder_info) {
1147 LOG_FERR1(LS_WARNING, GetDecoderInfo, payload_type);
1148 PacketBuffer::DeleteAllPackets(packet_list);
1149 return kDecoderNotFound;
1150 }
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001151 // If sampling rate or number of channels has changed, we need to make
1152 // a reset.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001153 if (decoder_info->fs_hz != fs_hz_ ||
1154 decoder->channels() != algorithm_buffer_->Channels()) {
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001155 // TODO(tlegrand): Add unittest to cover this event.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001156 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->channels());
1157 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001158 sync_buffer_->set_end_timestamp(timestamp_);
1159 playout_timestamp_ = timestamp_;
1160 }
1161 }
1162 }
1163
1164 if (reset_decoder_) {
1165 // TODO(hlundin): Write test for this.
1166 // Reset decoder.
1167 if (decoder) {
1168 decoder->Init();
1169 }
1170 // Reset comfort noise decoder.
1171 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
1172 if (cng_decoder) {
1173 cng_decoder->Init();
1174 }
1175 reset_decoder_ = false;
1176 }
1177
1178#ifdef LEGACY_BITEXACT
1179 // Due to a bug in old SignalMCU, it could happen that CNG operation was
1180 // decided, but a speech packet was provided. The speech packet will be used
1181 // to update the comfort noise decoder, as if it was a SID frame, which is
1182 // clearly wrong.
1183 if (*operation == kRfc3389Cng) {
1184 return 0;
1185 }
1186#endif
1187
1188 *decoded_length = 0;
1189 // Update codec-internal PLC state.
1190 if ((*operation == kMerge) && decoder && decoder->HasDecodePlc()) {
1191 decoder->DecodePlc(1, &decoded_buffer_[*decoded_length]);
1192 }
1193
1194 int return_value = DecodeLoop(packet_list, operation, decoder,
1195 decoded_length, speech_type);
1196
1197 if (*decoded_length < 0) {
1198 // Error returned from the decoder.
1199 *decoded_length = 0;
1200 sync_buffer_->IncreaseEndTimestamp(decoder_frame_length_);
1201 int error_code = 0;
1202 if (decoder)
1203 error_code = decoder->ErrorCode();
1204 if (error_code != 0) {
1205 // Got some error code from the decoder.
1206 decoder_error_code_ = error_code;
1207 return_value = kDecoderErrorCode;
1208 } else {
1209 // Decoder does not implement error codes. Return generic error.
1210 return_value = kOtherDecoderError;
1211 }
1212 LOG_FERR2(LS_WARNING, DecodeLoop, error_code, packet_list->size());
1213 *operation = kExpand; // Do expansion to get data instead.
1214 }
1215 if (*speech_type != AudioDecoder::kComfortNoise) {
1216 // Don't increment timestamp if codec returned CNG speech type
1217 // since in this case, the we will increment the CNGplayedTS counter.
1218 // Increase with number of samples per channel.
1219 assert(*decoded_length == 0 ||
1220 (decoder && decoder->channels() == sync_buffer_->Channels()));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001221 sync_buffer_->IncreaseEndTimestamp(
1222 *decoded_length / static_cast<int>(sync_buffer_->Channels()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001223 }
1224 return return_value;
1225}
1226
1227int NetEqImpl::DecodeLoop(PacketList* packet_list, Operations* operation,
1228 AudioDecoder* decoder, int* decoded_length,
1229 AudioDecoder::SpeechType* speech_type) {
1230 Packet* packet = NULL;
1231 if (!packet_list->empty()) {
1232 packet = packet_list->front();
1233 }
1234 // Do decoding.
1235 while (packet &&
1236 !decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1237 assert(decoder); // At this point, we must have a decoder object.
1238 // The number of channels in the |sync_buffer_| should be the same as the
1239 // number decoder channels.
1240 assert(sync_buffer_->Channels() == decoder->channels());
1241 assert(decoded_buffer_length_ >= kMaxFrameSize * decoder->channels());
1242 assert(*operation == kNormal || *operation == kAccelerate ||
1243 *operation == kMerge || *operation == kPreemptiveExpand);
1244 packet_list->pop_front();
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001245 size_t payload_length = packet->payload_length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001246 int16_t decode_length;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +00001247 if (packet->sync_packet) {
1248 // Decode to silence with the same frame size as the last decode.
1249 LOG(LS_VERBOSE) << "Decoding sync-packet: " <<
1250 " ts=" << packet->header.timestamp <<
1251 ", sn=" << packet->header.sequenceNumber <<
1252 ", pt=" << static_cast<int>(packet->header.payloadType) <<
1253 ", ssrc=" << packet->header.ssrc <<
1254 ", len=" << packet->payload_length;
1255 memset(&decoded_buffer_[*decoded_length], 0, decoder_frame_length_ *
1256 decoder->channels() * sizeof(decoded_buffer_[0]));
1257 decode_length = decoder_frame_length_;
1258 } else if (!packet->primary) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001259 // This is a redundant payload; call the special decoder method.
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +00001260 LOG(LS_VERBOSE) << "Decoding packet (redundant):" <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001261 " ts=" << packet->header.timestamp <<
1262 ", sn=" << packet->header.sequenceNumber <<
1263 ", pt=" << static_cast<int>(packet->header.payloadType) <<
1264 ", ssrc=" << packet->header.ssrc <<
1265 ", len=" << packet->payload_length;
1266 decode_length = decoder->DecodeRedundant(
1267 packet->payload, packet->payload_length,
1268 &decoded_buffer_[*decoded_length], speech_type);
1269 } else {
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +00001270 LOG(LS_VERBOSE) << "Decoding packet: ts=" << packet->header.timestamp <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001271 ", sn=" << packet->header.sequenceNumber <<
1272 ", pt=" << static_cast<int>(packet->header.payloadType) <<
1273 ", ssrc=" << packet->header.ssrc <<
1274 ", len=" << packet->payload_length;
1275 decode_length = decoder->Decode(packet->payload,
1276 packet->payload_length,
1277 &decoded_buffer_[*decoded_length],
1278 speech_type);
1279 }
1280
1281 delete[] packet->payload;
1282 delete packet;
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001283 packet = NULL;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001284 if (decode_length > 0) {
1285 *decoded_length += decode_length;
1286 // Update |decoder_frame_length_| with number of samples per channel.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001287 decoder_frame_length_ = decode_length /
1288 static_cast<int>(decoder->channels());
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +00001289 LOG(LS_VERBOSE) << "Decoded " << decode_length << " samples (" <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001290 decoder->channels() << " channel(s) -> " << decoder_frame_length_ <<
1291 " samples per channel)";
1292 } else if (decode_length < 0) {
1293 // Error.
henrik.lundin@webrtc.org63464a92013-01-30 09:41:56 +00001294 LOG_FERR2(LS_WARNING, Decode, decode_length, payload_length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001295 *decoded_length = -1;
1296 PacketBuffer::DeleteAllPackets(packet_list);
1297 break;
1298 }
1299 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1300 // Guard against overflow.
1301 LOG_F(LS_WARNING) << "Decoded too much.";
1302 PacketBuffer::DeleteAllPackets(packet_list);
1303 return kDecodedTooMuch;
1304 }
1305 if (!packet_list->empty()) {
1306 packet = packet_list->front();
1307 } else {
1308 packet = NULL;
1309 }
1310 } // End of decode loop.
1311
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001312 // If the list is not empty at this point, either a decoding error terminated
1313 // the while-loop, or list must hold exactly one CNG packet.
1314 assert(packet_list->empty() || *decoded_length < 0 ||
1315 (packet_list->size() == 1 && packet &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001316 decoder_database_->IsComfortNoise(packet->header.payloadType)));
1317 return 0;
1318}
1319
1320void NetEqImpl::DoNormal(const int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001321 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001322 assert(normal_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001323 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001324 normal_->Process(decoded_buffer, decoded_length, last_mode_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001325 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001326 if (decoded_length != 0) {
1327 last_mode_ = kModeNormal;
1328 }
1329
1330 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1331 if ((speech_type == AudioDecoder::kComfortNoise)
1332 || ((last_mode_ == kModeCodecInternalCng)
1333 && (decoded_length == 0))) {
1334 // TODO(hlundin): Remove second part of || statement above.
1335 last_mode_ = kModeCodecInternalCng;
1336 }
1337
1338 if (!play_dtmf) {
1339 dtmf_tone_generator_->Reset();
1340 }
1341}
1342
1343void NetEqImpl::DoMerge(int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001344 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001345 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001346 assert(merge_.get());
1347 int new_length = merge_->Process(decoded_buffer, decoded_length,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001348 mute_factor_array_.get(),
1349 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001350
1351 // Update in-call and post-call statistics.
1352 if (expand_->MuteFactor(0) == 0) {
1353 // Expand generates only noise.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001354 stats_.ExpandedNoiseSamples(new_length - static_cast<int>(decoded_length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001355 } else {
1356 // Expansion generates more than only noise.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001357 stats_.ExpandedVoiceSamples(new_length - static_cast<int>(decoded_length));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001358 }
1359
1360 last_mode_ = kModeMerge;
1361 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1362 if (speech_type == AudioDecoder::kComfortNoise) {
1363 last_mode_ = kModeCodecInternalCng;
1364 }
1365 expand_->Reset();
1366 if (!play_dtmf) {
1367 dtmf_tone_generator_->Reset();
1368 }
1369}
1370
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001371int NetEqImpl::DoExpand(bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001372 while ((sync_buffer_->FutureLength() - expand_->overlap_length()) <
1373 static_cast<size_t>(output_size_samples_)) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001374 algorithm_buffer_->Clear();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001375 int return_value = expand_->Process(algorithm_buffer_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001376 int length = static_cast<int>(algorithm_buffer_->Size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001377
1378 // Update in-call and post-call statistics.
1379 if (expand_->MuteFactor(0) == 0) {
1380 // Expand operation generates only noise.
1381 stats_.ExpandedNoiseSamples(length);
1382 } else {
1383 // Expand operation generates more than only noise.
1384 stats_.ExpandedVoiceSamples(length);
1385 }
1386
1387 last_mode_ = kModeExpand;
1388
1389 if (return_value < 0) {
1390 return return_value;
1391 }
1392
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001393 sync_buffer_->PushBack(*algorithm_buffer_);
1394 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001395 }
1396 if (!play_dtmf) {
1397 dtmf_tone_generator_->Reset();
1398 }
1399 return 0;
1400}
1401
1402int NetEqImpl::DoAccelerate(int16_t* decoded_buffer, size_t decoded_length,
1403 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001404 bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001405 const size_t required_samples = 240 * fs_mult_; // Must have 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001406 size_t borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001407 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001408 size_t decoded_length_per_channel = decoded_length / num_channels;
1409 if (decoded_length_per_channel < required_samples) {
1410 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001411 borrowed_samples_per_channel = static_cast<int>(required_samples -
1412 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001413 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1414 decoded_buffer,
1415 sizeof(int16_t) * decoded_length);
1416 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1417 decoded_buffer);
1418 decoded_length = required_samples * num_channels;
1419 }
1420
1421 int16_t samples_removed;
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001422 Accelerate::ReturnCodes return_code = accelerate_->Process(
1423 decoded_buffer, decoded_length, algorithm_buffer_.get(),
1424 &samples_removed);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001425 stats_.AcceleratedSamples(samples_removed);
1426 switch (return_code) {
1427 case Accelerate::kSuccess:
1428 last_mode_ = kModeAccelerateSuccess;
1429 break;
1430 case Accelerate::kSuccessLowEnergy:
1431 last_mode_ = kModeAccelerateLowEnergy;
1432 break;
1433 case Accelerate::kNoStretch:
1434 last_mode_ = kModeAccelerateFail;
1435 break;
1436 case Accelerate::kError:
1437 // TODO(hlundin): Map to kModeError instead?
1438 last_mode_ = kModeAccelerateFail;
1439 return kAccelerateError;
1440 }
1441
1442 if (borrowed_samples_per_channel > 0) {
1443 // Copy borrowed samples back to the |sync_buffer_|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001444 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001445 if (length < borrowed_samples_per_channel) {
1446 // This destroys the beginning of the buffer, but will not cause any
1447 // problems.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001448 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001449 sync_buffer_->Size() -
1450 borrowed_samples_per_channel);
1451 sync_buffer_->PushFrontZeros(borrowed_samples_per_channel - length);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001452 algorithm_buffer_->PopFront(length);
1453 assert(algorithm_buffer_->Empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001454 } else {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001455 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001456 borrowed_samples_per_channel,
1457 sync_buffer_->Size() -
1458 borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001459 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001460 }
1461 }
1462
1463 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1464 if (speech_type == AudioDecoder::kComfortNoise) {
1465 last_mode_ = kModeCodecInternalCng;
1466 }
1467 if (!play_dtmf) {
1468 dtmf_tone_generator_->Reset();
1469 }
1470 expand_->Reset();
1471 return 0;
1472}
1473
1474int NetEqImpl::DoPreemptiveExpand(int16_t* decoded_buffer,
1475 size_t decoded_length,
1476 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001477 bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001478 const size_t required_samples = 240 * fs_mult_; // Must have 30 ms.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001479 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001480 int borrowed_samples_per_channel = 0;
1481 int old_borrowed_samples_per_channel = 0;
1482 size_t decoded_length_per_channel = decoded_length / num_channels;
1483 if (decoded_length_per_channel < required_samples) {
1484 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001485 borrowed_samples_per_channel = static_cast<int>(required_samples -
1486 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001487 // Calculate how many of these were already played out.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001488 old_borrowed_samples_per_channel = static_cast<int>(
1489 borrowed_samples_per_channel - sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001490 old_borrowed_samples_per_channel = std::max(
1491 0, old_borrowed_samples_per_channel);
1492 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1493 decoded_buffer,
1494 sizeof(int16_t) * decoded_length);
1495 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1496 decoded_buffer);
1497 decoded_length = required_samples * num_channels;
1498 }
1499
1500 int16_t samples_added;
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001501 PreemptiveExpand::ReturnCodes return_code = preemptive_expand_->Process(
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001502 decoded_buffer, static_cast<int>(decoded_length),
1503 old_borrowed_samples_per_channel,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001504 algorithm_buffer_.get(), &samples_added);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001505 stats_.PreemptiveExpandedSamples(samples_added);
1506 switch (return_code) {
1507 case PreemptiveExpand::kSuccess:
1508 last_mode_ = kModePreemptiveExpandSuccess;
1509 break;
1510 case PreemptiveExpand::kSuccessLowEnergy:
1511 last_mode_ = kModePreemptiveExpandLowEnergy;
1512 break;
1513 case PreemptiveExpand::kNoStretch:
1514 last_mode_ = kModePreemptiveExpandFail;
1515 break;
1516 case PreemptiveExpand::kError:
1517 // TODO(hlundin): Map to kModeError instead?
1518 last_mode_ = kModePreemptiveExpandFail;
1519 return kPreemptiveExpandError;
1520 }
1521
1522 if (borrowed_samples_per_channel > 0) {
1523 // Copy borrowed samples back to the |sync_buffer_|.
1524 sync_buffer_->ReplaceAtIndex(
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001525 *algorithm_buffer_, borrowed_samples_per_channel,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001526 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001527 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001528 }
1529
1530 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1531 if (speech_type == AudioDecoder::kComfortNoise) {
1532 last_mode_ = kModeCodecInternalCng;
1533 }
1534 if (!play_dtmf) {
1535 dtmf_tone_generator_->Reset();
1536 }
1537 expand_->Reset();
1538 return 0;
1539}
1540
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001541int NetEqImpl::DoRfc3389Cng(PacketList* packet_list, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001542 if (!packet_list->empty()) {
1543 // Must have exactly one SID frame at this point.
1544 assert(packet_list->size() == 1);
1545 Packet* packet = packet_list->front();
1546 packet_list->pop_front();
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001547 if (!decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1548#ifdef LEGACY_BITEXACT
1549 // This can happen due to a bug in GetDecision. Change the payload type
1550 // to a CNG type, and move on. Note that this means that we are in fact
1551 // sending a non-CNG payload to the comfort noise decoder for decoding.
1552 // Clearly wrong, but will maintain bit-exactness with legacy.
1553 if (fs_hz_ == 8000) {
1554 packet->header.payloadType =
1555 decoder_database_->GetRtpPayloadType(kDecoderCNGnb);
1556 } else if (fs_hz_ == 16000) {
1557 packet->header.payloadType =
1558 decoder_database_->GetRtpPayloadType(kDecoderCNGwb);
1559 } else if (fs_hz_ == 32000) {
1560 packet->header.payloadType =
1561 decoder_database_->GetRtpPayloadType(kDecoderCNGswb32kHz);
1562 } else if (fs_hz_ == 48000) {
1563 packet->header.payloadType =
1564 decoder_database_->GetRtpPayloadType(kDecoderCNGswb48kHz);
1565 }
1566 assert(decoder_database_->IsComfortNoise(packet->header.payloadType));
1567#else
1568 LOG(LS_ERROR) << "Trying to decode non-CNG payload as CNG.";
1569 return kOtherError;
1570#endif
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001571 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001572 // UpdateParameters() deletes |packet|.
1573 if (comfort_noise_->UpdateParameters(packet) ==
1574 ComfortNoise::kInternalError) {
1575 LOG_FERR0(LS_WARNING, UpdateParameters);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001576 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001577 return -comfort_noise_->internal_error_code();
1578 }
1579 }
1580 int cn_return = comfort_noise_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001581 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001582 expand_->Reset();
1583 last_mode_ = kModeRfc3389Cng;
1584 if (!play_dtmf) {
1585 dtmf_tone_generator_->Reset();
1586 }
1587 if (cn_return == ComfortNoise::kInternalError) {
1588 LOG_FERR1(LS_WARNING, comfort_noise_->Generate, cn_return);
1589 decoder_error_code_ = comfort_noise_->internal_error_code();
1590 return kComfortNoiseErrorCode;
1591 } else if (cn_return == ComfortNoise::kUnknownPayloadType) {
1592 LOG_FERR1(LS_WARNING, comfort_noise_->Generate, cn_return);
1593 return kUnknownRtpPayloadType;
1594 }
1595 return 0;
1596}
1597
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001598void NetEqImpl::DoCodecInternalCng() {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001599 int length = 0;
1600 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1601 int16_t decoded_buffer[kMaxFrameSize];
1602 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1603 if (decoder) {
1604 const uint8_t* dummy_payload = NULL;
1605 AudioDecoder::SpeechType speech_type;
1606 length = decoder->Decode(dummy_payload, 0, decoded_buffer, &speech_type);
1607 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001608 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001609 normal_->Process(decoded_buffer, length, last_mode_, mute_factor_array_.get(),
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001610 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001611 last_mode_ = kModeCodecInternalCng;
1612 expand_->Reset();
1613}
1614
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001615int NetEqImpl::DoDtmf(const DtmfEvent& dtmf_event, bool* play_dtmf) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001616 // This block of the code and the block further down, handling |dtmf_switch|
1617 // are commented out. Otherwise playing out-of-band DTMF would fail in VoE
1618 // test, DtmfTest.ManualSuccessfullySendsOutOfBandTelephoneEvents. This is
1619 // equivalent to |dtmf_switch| always be false.
1620 //
1621 // See http://webrtc-codereview.appspot.com/1195004/ for discussion
1622 // On this issue. This change might cause some glitches at the point of
1623 // switch from audio to DTMF. Issue 1545 is filed to track this.
1624 //
1625 // bool dtmf_switch = false;
1626 // if ((last_mode_ != kModeDtmf) && dtmf_tone_generator_->initialized()) {
1627 // // Special case; see below.
1628 // // We must catch this before calling Generate, since |initialized| is
1629 // // modified in that call.
1630 // dtmf_switch = true;
1631 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001632
1633 int dtmf_return_value = 0;
1634 if (!dtmf_tone_generator_->initialized()) {
1635 // Initialize if not already done.
1636 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1637 dtmf_event.volume);
1638 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001639
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001640 if (dtmf_return_value == 0) {
1641 // Generate DTMF signal.
1642 dtmf_return_value = dtmf_tone_generator_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001643 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001644 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001645
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001646 if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001647 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001648 return dtmf_return_value;
1649 }
1650
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001651 // if (dtmf_switch) {
1652 // // This is the special case where the previous operation was DTMF
1653 // // overdub, but the current instruction is "regular" DTMF. We must make
1654 // // sure that the DTMF does not have any discontinuities. The first DTMF
1655 // // sample that we generate now must be played out immediately, therefore
1656 // // it must be copied to the speech buffer.
1657 // // TODO(hlundin): This code seems incorrect. (Legacy.) Write test and
1658 // // verify correct operation.
1659 // assert(false);
1660 // // Must generate enough data to replace all of the |sync_buffer_|
1661 // // "future".
1662 // int required_length = sync_buffer_->FutureLength();
1663 // assert(dtmf_tone_generator_->initialized());
1664 // dtmf_return_value = dtmf_tone_generator_->Generate(required_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001665 // algorithm_buffer_);
1666 // assert((size_t) required_length == algorithm_buffer_->Size());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001667 // if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001668 // algorithm_buffer_->Zeros(output_size_samples_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001669 // return dtmf_return_value;
1670 // }
1671 //
1672 // // Overwrite the "future" part of the speech buffer with the new DTMF
1673 // // data.
1674 // // TODO(hlundin): It seems that this overwriting has gone lost.
1675 // // Not adapted for multi-channel yet.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001676 // assert(algorithm_buffer_->Channels() == 1);
1677 // if (algorithm_buffer_->Channels() != 1) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001678 // LOG(LS_WARNING) << "DTMF not supported for more than one channel";
1679 // return kStereoNotSupported;
1680 // }
1681 // // Shuffle the remaining data to the beginning of algorithm buffer.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001682 // algorithm_buffer_->PopFront(sync_buffer_->FutureLength());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001683 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001684
1685 sync_buffer_->IncreaseEndTimestamp(output_size_samples_);
1686 expand_->Reset();
1687 last_mode_ = kModeDtmf;
1688
1689 // Set to false because the DTMF is already in the algorithm buffer.
1690 *play_dtmf = false;
1691 return 0;
1692}
1693
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001694void NetEqImpl::DoAlternativePlc(bool increase_timestamp) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001695 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1696 int length;
1697 if (decoder && decoder->HasDecodePlc()) {
1698 // Use the decoder's packet-loss concealment.
1699 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1700 int16_t decoded_buffer[kMaxFrameSize];
1701 length = decoder->DecodePlc(1, decoded_buffer);
1702 if (length > 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001703 algorithm_buffer_->PushBackInterleaved(decoded_buffer, length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001704 } else {
1705 length = 0;
1706 }
1707 } else {
1708 // Do simple zero-stuffing.
1709 length = output_size_samples_;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001710 algorithm_buffer_->Zeros(length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001711 // By not advancing the timestamp, NetEq inserts samples.
1712 stats_.AddZeros(length);
1713 }
1714 if (increase_timestamp) {
1715 sync_buffer_->IncreaseEndTimestamp(length);
1716 }
1717 expand_->Reset();
1718}
1719
1720int NetEqImpl::DtmfOverdub(const DtmfEvent& dtmf_event, size_t num_channels,
1721 int16_t* output) const {
1722 size_t out_index = 0;
1723 int overdub_length = output_size_samples_; // Default value.
1724
1725 if (sync_buffer_->dtmf_index() > sync_buffer_->next_index()) {
1726 // Special operation for transition from "DTMF only" to "DTMF overdub".
1727 out_index = std::min(
1728 sync_buffer_->dtmf_index() - sync_buffer_->next_index(),
1729 static_cast<size_t>(output_size_samples_));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001730 overdub_length = output_size_samples_ - static_cast<int>(out_index);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001731 }
1732
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001733 AudioMultiVector dtmf_output(num_channels);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001734 int dtmf_return_value = 0;
1735 if (!dtmf_tone_generator_->initialized()) {
1736 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1737 dtmf_event.volume);
1738 }
1739 if (dtmf_return_value == 0) {
1740 dtmf_return_value = dtmf_tone_generator_->Generate(overdub_length,
1741 &dtmf_output);
1742 assert((size_t) overdub_length == dtmf_output.Size());
1743 }
1744 dtmf_output.ReadInterleaved(overdub_length, &output[out_index]);
1745 return dtmf_return_value < 0 ? dtmf_return_value : 0;
1746}
1747
1748int NetEqImpl::ExtractPackets(int required_samples, PacketList* packet_list) {
1749 bool first_packet = true;
1750 uint8_t prev_payload_type = 0;
1751 uint32_t prev_timestamp = 0;
1752 uint16_t prev_sequence_number = 0;
1753 bool next_packet_available = false;
1754
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001755 const RTPHeader* header = packet_buffer_->NextRtpHeader();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001756 assert(header);
1757 if (!header) {
1758 return -1;
1759 }
turaj@webrtc.org7df97062013-08-02 18:07:13 +00001760 uint32_t first_timestamp = header->timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001761 int extracted_samples = 0;
1762
1763 // Packet extraction loop.
1764 do {
1765 timestamp_ = header->timestamp;
1766 int discard_count = 0;
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001767 Packet* packet = packet_buffer_->GetNextPacket(&discard_count);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001768 // |header| may be invalid after the |packet_buffer_| operation.
1769 header = NULL;
1770 if (!packet) {
1771 LOG_FERR1(LS_ERROR, GetNextPacket, discard_count) <<
1772 "Should always be able to extract a packet here";
1773 assert(false); // Should always be able to extract a packet here.
1774 return -1;
1775 }
1776 stats_.PacketsDiscarded(discard_count);
1777 // Store waiting time in ms; packets->waiting_time is in "output blocks".
1778 stats_.StoreWaitingTime(packet->waiting_time * kOutputSizeMs);
1779 assert(packet->payload_length > 0);
1780 packet_list->push_back(packet); // Store packet in list.
1781
1782 if (first_packet) {
1783 first_packet = false;
minyue@webrtc.orgd7301772013-08-29 00:58:14 +00001784 decoded_packet_sequence_number_ = prev_sequence_number =
1785 packet->header.sequenceNumber;
1786 decoded_packet_timestamp_ = prev_timestamp = packet->header.timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001787 prev_payload_type = packet->header.payloadType;
1788 }
1789
1790 // Store number of extracted samples.
1791 int packet_duration = 0;
1792 AudioDecoder* decoder = decoder_database_->GetDecoder(
1793 packet->header.payloadType);
1794 if (decoder) {
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001795 if (packet->sync_packet) {
1796 packet_duration = decoder_frame_length_;
1797 } else {
1798 packet_duration = packet->primary ?
1799 decoder->PacketDuration(packet->payload, packet->payload_length) :
1800 decoder->PacketDurationRedundant(packet->payload,
1801 packet->payload_length);
1802 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001803 } else {
1804 LOG_FERR1(LS_WARNING, GetDecoder, packet->header.payloadType) <<
1805 "Could not find a decoder for a packet about to be extracted.";
1806 assert(false);
1807 }
1808 if (packet_duration <= 0) {
1809 // Decoder did not return a packet duration. Assume that the packet
1810 // contains the same number of samples as the previous one.
1811 packet_duration = decoder_frame_length_;
1812 }
1813 extracted_samples = packet->header.timestamp - first_timestamp +
1814 packet_duration;
1815
1816 // Check what packet is available next.
1817 header = packet_buffer_->NextRtpHeader();
1818 next_packet_available = false;
1819 if (header && prev_payload_type == header->payloadType) {
1820 int16_t seq_no_diff = header->sequenceNumber - prev_sequence_number;
1821 int32_t ts_diff = header->timestamp - prev_timestamp;
1822 if (seq_no_diff == 1 ||
1823 (seq_no_diff == 0 && ts_diff == decoder_frame_length_)) {
1824 // The next sequence number is available, or the next part of a packet
1825 // that was split into pieces upon insertion.
1826 next_packet_available = true;
1827 }
1828 prev_sequence_number = header->sequenceNumber;
1829 }
1830 } while (extracted_samples < required_samples && next_packet_available);
1831
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00001832 if (extracted_samples > 0) {
1833 // Delete old packets only when we are going to decode something. Otherwise,
1834 // we could end up in the situation where we never decode anything, since
1835 // all incoming packets are considered too old but the buffer will also
1836 // never be flooded and flushed.
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001837 packet_buffer_->DiscardAllOldPackets(timestamp_);
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00001838 }
1839
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001840 return extracted_samples;
1841}
1842
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001843void NetEqImpl::UpdatePlcComponents(int fs_hz, size_t channels) {
1844 // Delete objects and create new ones.
1845 expand_.reset(expand_factory_->Create(background_noise_.get(),
1846 sync_buffer_.get(), &random_vector_,
1847 fs_hz, channels));
1848 merge_.reset(new Merge(fs_hz, channels, expand_.get(), sync_buffer_.get()));
1849}
1850
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001851void NetEqImpl::SetSampleRateAndChannels(int fs_hz, size_t channels) {
1852 LOG_API2(fs_hz, channels);
1853 // TODO(hlundin): Change to an enumerator and skip assert.
1854 assert(fs_hz == 8000 || fs_hz == 16000 || fs_hz == 32000 || fs_hz == 48000);
1855 assert(channels > 0);
1856
1857 fs_hz_ = fs_hz;
1858 fs_mult_ = fs_hz / 8000;
1859 output_size_samples_ = kOutputSizeMs * 8 * fs_mult_;
1860 decoder_frame_length_ = 3 * output_size_samples_; // Initialize to 30ms.
1861
1862 last_mode_ = kModeNormal;
1863
1864 // Create a new array of mute factors and set all to 1.
1865 mute_factor_array_.reset(new int16_t[channels]);
1866 for (size_t i = 0; i < channels; ++i) {
1867 mute_factor_array_[i] = 16384; // 1.0 in Q14.
1868 }
1869
1870 // Reset comfort noise decoder, if there is one active.
1871 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
1872 if (cng_decoder) {
1873 cng_decoder->Init();
1874 }
1875
1876 // Reinit post-decode VAD with new sample rate.
1877 assert(vad_.get()); // Cannot be NULL here.
1878 vad_->Init();
1879
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001880 // Delete algorithm buffer and create a new one.
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001881 algorithm_buffer_.reset(new AudioMultiVector(channels));
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001882
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001883 // Delete sync buffer and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001884 sync_buffer_.reset(new SyncBuffer(channels, kSyncBufferSize * fs_mult_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001885
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00001886 // Delete BackgroundNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001887 background_noise_.reset(new BackgroundNoise(channels));
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00001888 background_noise_->set_mode(background_noise_mode_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001889
1890 // Reset random vector.
1891 random_vector_.Reset();
1892
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001893 UpdatePlcComponents(fs_hz, channels);
1894
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001895 // Move index so that we create a small set of future samples (all 0).
1896 sync_buffer_->set_next_index(sync_buffer_->next_index() -
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001897 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001898
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001899 normal_.reset(new Normal(fs_hz, decoder_database_.get(), *background_noise_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001900 expand_.get()));
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +00001901 accelerate_.reset(
1902 accelerate_factory_->Create(fs_hz, channels, *background_noise_));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001903 preemptive_expand_.reset(preemptive_expand_factory_->Create(
1904 fs_hz, channels,
1905 *background_noise_,
1906 static_cast<int>(expand_->overlap_length())));
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001907
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001908 // Delete ComfortNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001909 comfort_noise_.reset(new ComfortNoise(fs_hz, decoder_database_.get(),
1910 sync_buffer_.get()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001911
1912 // Verify that |decoded_buffer_| is long enough.
1913 if (decoded_buffer_length_ < kMaxFrameSize * channels) {
1914 // Reallocate to larger size.
1915 decoded_buffer_length_ = kMaxFrameSize * channels;
1916 decoded_buffer_.reset(new int16_t[decoded_buffer_length_]);
1917 }
1918
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001919 // Create DecisionLogic if it is not created yet, then communicate new sample
1920 // rate and output size to DecisionLogic object.
1921 if (!decision_logic_.get()) {
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00001922 CreateDecisionLogic();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001923 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001924 decision_logic_->SetSampleRate(fs_hz_, output_size_samples_);
1925}
1926
1927NetEqOutputType NetEqImpl::LastOutputType() {
1928 assert(vad_.get());
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001929 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001930 if (last_mode_ == kModeCodecInternalCng || last_mode_ == kModeRfc3389Cng) {
1931 return kOutputCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001932 } else if (last_mode_ == kModeExpand && expand_->MuteFactor(0) == 0) {
1933 // Expand mode has faded down to background noise only (very long expand).
1934 return kOutputPLCtoCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001935 } else if (last_mode_ == kModeExpand) {
1936 return kOutputPLC;
wu@webrtc.org24301a62013-12-13 19:17:43 +00001937 } else if (vad_->running() && !vad_->active_speech()) {
1938 return kOutputVADPassive;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001939 } else {
1940 return kOutputNormal;
1941 }
1942}
1943
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00001944void NetEqImpl::CreateDecisionLogic() {
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001945 decision_logic_.reset(DecisionLogic::Create(fs_hz_, output_size_samples_,
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00001946 playout_mode_,
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001947 decoder_database_.get(),
1948 *packet_buffer_.get(),
1949 delay_manager_.get(),
1950 buffer_level_filter_.get()));
1951}
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001952} // namespace webrtc