blob: 73708256f10453b939864d89874e78eb23d78df4 [file] [log] [blame]
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001/*
2 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000011#include "webrtc/modules/audio_coding/neteq/neteq_impl.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000012
13#include <assert.h>
14#include <memory.h> // memset
15
16#include <algorithm>
17
18#include "webrtc/common_audio/signal_processing/include/signal_processing_library.h"
kwiberg@webrtc.orge04a93b2014-12-09 10:12:53 +000019#include "webrtc/modules/audio_coding/codecs/audio_decoder.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000020#include "webrtc/modules/audio_coding/neteq/accelerate.h"
21#include "webrtc/modules/audio_coding/neteq/background_noise.h"
22#include "webrtc/modules/audio_coding/neteq/buffer_level_filter.h"
23#include "webrtc/modules/audio_coding/neteq/comfort_noise.h"
24#include "webrtc/modules/audio_coding/neteq/decision_logic.h"
25#include "webrtc/modules/audio_coding/neteq/decoder_database.h"
26#include "webrtc/modules/audio_coding/neteq/defines.h"
27#include "webrtc/modules/audio_coding/neteq/delay_manager.h"
28#include "webrtc/modules/audio_coding/neteq/delay_peak_detector.h"
29#include "webrtc/modules/audio_coding/neteq/dtmf_buffer.h"
30#include "webrtc/modules/audio_coding/neteq/dtmf_tone_generator.h"
31#include "webrtc/modules/audio_coding/neteq/expand.h"
henrik.lundin@webrtc.org9c55f0f2014-06-09 08:10:28 +000032#include "webrtc/modules/audio_coding/neteq/merge.h"
33#include "webrtc/modules/audio_coding/neteq/normal.h"
34#include "webrtc/modules/audio_coding/neteq/packet_buffer.h"
35#include "webrtc/modules/audio_coding/neteq/packet.h"
36#include "webrtc/modules/audio_coding/neteq/payload_splitter.h"
37#include "webrtc/modules/audio_coding/neteq/post_decode_vad.h"
38#include "webrtc/modules/audio_coding/neteq/preemptive_expand.h"
39#include "webrtc/modules/audio_coding/neteq/sync_buffer.h"
40#include "webrtc/modules/audio_coding/neteq/timestamp_scaler.h"
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000041#include "webrtc/modules/interface/module_common_types.h"
42#include "webrtc/system_wrappers/interface/critical_section_wrapper.h"
43#include "webrtc/system_wrappers/interface/logging.h"
44
45// Modify the code to obtain backwards bit-exactness. Once bit-exactness is no
46// longer required, this #define should be removed (and the code that it
47// enables).
48#define LEGACY_BITEXACT
49
50namespace webrtc {
51
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +000052NetEqImpl::NetEqImpl(const NetEq::Config& config,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000053 BufferLevelFilter* buffer_level_filter,
54 DecoderDatabase* decoder_database,
55 DelayManager* delay_manager,
56 DelayPeakDetector* delay_peak_detector,
57 DtmfBuffer* dtmf_buffer,
58 DtmfToneGenerator* dtmf_tone_generator,
59 PacketBuffer* packet_buffer,
60 PayloadSplitter* payload_splitter,
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +000061 TimestampScaler* timestamp_scaler,
62 AccelerateFactory* accelerate_factory,
63 ExpandFactory* expand_factory,
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +000064 PreemptiveExpandFactory* preemptive_expand_factory,
65 bool create_components)
henrik.lundin@webrtc.org2f816bb2014-06-05 10:37:13 +000066 : crit_sect_(CriticalSectionWrapper::CreateCriticalSection()),
67 buffer_level_filter_(buffer_level_filter),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000068 decoder_database_(decoder_database),
69 delay_manager_(delay_manager),
70 delay_peak_detector_(delay_peak_detector),
71 dtmf_buffer_(dtmf_buffer),
72 dtmf_tone_generator_(dtmf_tone_generator),
73 packet_buffer_(packet_buffer),
74 payload_splitter_(payload_splitter),
75 timestamp_scaler_(timestamp_scaler),
76 vad_(new PostDecodeVad()),
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +000077 expand_factory_(expand_factory),
78 accelerate_factory_(accelerate_factory),
79 preemptive_expand_factory_(preemptive_expand_factory),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000080 last_mode_(kModeNormal),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000081 decoded_buffer_length_(kMaxFrameSize),
82 decoded_buffer_(new int16_t[decoded_buffer_length_]),
83 playout_timestamp_(0),
84 new_codec_(false),
85 timestamp_(0),
86 reset_decoder_(false),
87 current_rtp_payload_type_(0xFF), // Invalid RTP payload type.
88 current_cng_rtp_payload_type_(0xFF), // Invalid RTP payload type.
89 ssrc_(0),
90 first_packet_(true),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000091 error_code_(0),
92 decoder_error_code_(0),
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +000093 background_noise_mode_(config.background_noise_mode),
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +000094 playout_mode_(config.playout_mode),
minyue@webrtc.orgd7301772013-08-29 00:58:14 +000095 decoded_packet_sequence_number_(-1),
96 decoded_packet_timestamp_(0) {
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +000097 int fs = config.sample_rate_hz;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000098 if (fs != 8000 && fs != 16000 && fs != 32000 && fs != 48000) {
99 LOG(LS_ERROR) << "Sample rate " << fs << " Hz not supported. " <<
100 "Changing to 8000 Hz.";
101 fs = 8000;
102 }
andrew@webrtc.org0569d932014-04-09 17:48:48 +0000103 LOG(LS_VERBOSE) << "Create NetEqImpl object with fs = " << fs << ".";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000104 fs_hz_ = fs;
105 fs_mult_ = fs / 8000;
106 output_size_samples_ = kOutputSizeMs * 8 * fs_mult_;
107 decoder_frame_length_ = 3 * output_size_samples_;
108 WebRtcSpl_Init();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000109 if (create_components) {
110 SetSampleRateAndChannels(fs, 1); // Default is 1 channel.
111 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000112}
113
114NetEqImpl::~NetEqImpl() {
115 LOG(LS_INFO) << "Deleting NetEqImpl object.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000116}
117
118int NetEqImpl::InsertPacket(const WebRtcRTPHeader& rtp_header,
119 const uint8_t* payload,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000120 size_t length_bytes,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000121 uint32_t receive_timestamp) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000122 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000123 LOG(LS_VERBOSE) << "InsertPacket: ts=" << rtp_header.header.timestamp <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000124 ", sn=" << rtp_header.header.sequenceNumber <<
125 ", pt=" << static_cast<int>(rtp_header.header.payloadType) <<
126 ", ssrc=" << rtp_header.header.ssrc <<
127 ", len=" << length_bytes;
128 int error = InsertPacketInternal(rtp_header, payload, length_bytes,
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000129 receive_timestamp, false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000130 if (error != 0) {
131 LOG_FERR1(LS_WARNING, InsertPacketInternal, error);
132 error_code_ = error;
133 return kFail;
134 }
135 return kOK;
136}
137
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000138int NetEqImpl::InsertSyncPacket(const WebRtcRTPHeader& rtp_header,
139 uint32_t receive_timestamp) {
140 CriticalSectionScoped lock(crit_sect_.get());
141 LOG(LS_VERBOSE) << "InsertPacket-Sync: ts="
142 << rtp_header.header.timestamp <<
143 ", sn=" << rtp_header.header.sequenceNumber <<
144 ", pt=" << static_cast<int>(rtp_header.header.payloadType) <<
145 ", ssrc=" << rtp_header.header.ssrc;
146
147 const uint8_t kSyncPayload[] = { 's', 'y', 'n', 'c' };
148 int error = InsertPacketInternal(
149 rtp_header, kSyncPayload, sizeof(kSyncPayload), receive_timestamp, true);
150
henrik.lundin@webrtc.orge7ce4372014-01-09 14:01:55 +0000151 if (error != 0) {
152 LOG_FERR1(LS_WARNING, InsertPacketInternal, error);
153 error_code_ = error;
154 return kFail;
155 }
156 return kOK;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000157}
158
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000159int NetEqImpl::GetAudio(size_t max_length, int16_t* output_audio,
160 int* samples_per_channel, int* num_channels,
161 NetEqOutputType* type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000162 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000163 LOG(LS_VERBOSE) << "GetAudio";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000164 int error = GetAudioInternal(max_length, output_audio, samples_per_channel,
165 num_channels);
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000166 LOG(LS_VERBOSE) << "Produced " << *samples_per_channel <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000167 " samples/channel for " << *num_channels << " channel(s)";
168 if (error != 0) {
169 LOG_FERR1(LS_WARNING, GetAudioInternal, error);
170 error_code_ = error;
171 return kFail;
172 }
173 if (type) {
174 *type = LastOutputType();
175 }
176 return kOK;
177}
178
179int NetEqImpl::RegisterPayloadType(enum NetEqDecoder codec,
180 uint8_t rtp_payload_type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000181 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000182 LOG_API2(static_cast<int>(rtp_payload_type), codec);
183 int ret = decoder_database_->RegisterPayload(rtp_payload_type, codec);
184 if (ret != DecoderDatabase::kOK) {
pkasting@chromium.org026b8922015-01-30 19:53:42 +0000185 LOG_FERR2(LS_WARNING, RegisterPayload, static_cast<int>(rtp_payload_type),
186 codec);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000187 switch (ret) {
188 case DecoderDatabase::kInvalidRtpPayloadType:
189 error_code_ = kInvalidRtpPayloadType;
190 break;
191 case DecoderDatabase::kCodecNotSupported:
192 error_code_ = kCodecNotSupported;
193 break;
194 case DecoderDatabase::kDecoderExists:
195 error_code_ = kDecoderExists;
196 break;
197 default:
198 error_code_ = kOtherError;
199 }
200 return kFail;
201 }
202 return kOK;
203}
204
205int NetEqImpl::RegisterExternalDecoder(AudioDecoder* decoder,
206 enum NetEqDecoder codec,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000207 uint8_t rtp_payload_type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000208 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000209 LOG_API2(static_cast<int>(rtp_payload_type), codec);
210 if (!decoder) {
211 LOG(LS_ERROR) << "Cannot register external decoder with NULL pointer";
212 assert(false);
213 return kFail;
214 }
kwiberg@webrtc.orge04a93b2014-12-09 10:12:53 +0000215 const int sample_rate_hz = CodecSampleRateHz(codec);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000216 int ret = decoder_database_->InsertExternal(rtp_payload_type, codec,
217 sample_rate_hz, decoder);
218 if (ret != DecoderDatabase::kOK) {
pkasting@chromium.org026b8922015-01-30 19:53:42 +0000219 LOG_FERR2(LS_WARNING, InsertExternal, static_cast<int>(rtp_payload_type),
220 codec);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000221 switch (ret) {
222 case DecoderDatabase::kInvalidRtpPayloadType:
223 error_code_ = kInvalidRtpPayloadType;
224 break;
225 case DecoderDatabase::kCodecNotSupported:
226 error_code_ = kCodecNotSupported;
227 break;
228 case DecoderDatabase::kDecoderExists:
229 error_code_ = kDecoderExists;
230 break;
231 case DecoderDatabase::kInvalidSampleRate:
232 error_code_ = kInvalidSampleRate;
233 break;
234 case DecoderDatabase::kInvalidPointer:
235 error_code_ = kInvalidPointer;
236 break;
237 default:
238 error_code_ = kOtherError;
239 }
240 return kFail;
241 }
242 return kOK;
243}
244
245int NetEqImpl::RemovePayloadType(uint8_t rtp_payload_type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000246 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000247 LOG_API1(static_cast<int>(rtp_payload_type));
248 int ret = decoder_database_->Remove(rtp_payload_type);
249 if (ret == DecoderDatabase::kOK) {
250 return kOK;
251 } else if (ret == DecoderDatabase::kDecoderNotFound) {
252 error_code_ = kDecoderNotFound;
253 } else {
254 error_code_ = kOtherError;
255 }
pkasting@chromium.org026b8922015-01-30 19:53:42 +0000256 LOG_FERR1(LS_WARNING, Remove, static_cast<int>(rtp_payload_type));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000257 return kFail;
258}
259
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000260bool NetEqImpl::SetMinimumDelay(int delay_ms) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000261 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000262 if (delay_ms >= 0 && delay_ms < 10000) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000263 assert(delay_manager_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000264 return delay_manager_->SetMinimumDelay(delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000265 }
266 return false;
267}
268
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000269bool NetEqImpl::SetMaximumDelay(int delay_ms) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000270 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000271 if (delay_ms >= 0 && delay_ms < 10000) {
272 assert(delay_manager_.get());
273 return delay_manager_->SetMaximumDelay(delay_ms);
274 }
275 return false;
276}
277
278int NetEqImpl::LeastRequiredDelayMs() const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000279 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000280 assert(delay_manager_.get());
281 return delay_manager_->least_required_delay_ms();
282}
283
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000284// Deprecated.
285// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000286void NetEqImpl::SetPlayoutMode(NetEqPlayoutMode mode) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000287 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000288 if (mode != playout_mode_) {
289 playout_mode_ = mode;
290 CreateDecisionLogic();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000291 }
292}
293
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000294// Deprecated.
295// TODO(henrik.lundin) Delete.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000296NetEqPlayoutMode NetEqImpl::PlayoutMode() const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000297 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +0000298 return playout_mode_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000299}
300
301int NetEqImpl::NetworkStatistics(NetEqNetworkStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000302 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000303 assert(decoder_database_.get());
304 const int total_samples_in_buffers = packet_buffer_->NumSamplesInBuffer(
305 decoder_database_.get(), decoder_frame_length_) +
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000306 static_cast<int>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000307 assert(delay_manager_.get());
308 assert(decision_logic_.get());
309 stats_.GetNetworkStatistics(fs_hz_, total_samples_in_buffers,
310 decoder_frame_length_, *delay_manager_.get(),
311 *decision_logic_.get(), stats);
312 return 0;
313}
314
315void NetEqImpl::WaitingTimes(std::vector<int>* waiting_times) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000316 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000317 stats_.WaitingTimes(waiting_times);
318}
319
320void NetEqImpl::GetRtcpStatistics(RtcpStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000321 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000322 if (stats) {
323 rtcp_.GetStatistics(false, stats);
324 }
325}
326
327void NetEqImpl::GetRtcpStatisticsNoReset(RtcpStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000328 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000329 if (stats) {
330 rtcp_.GetStatistics(true, stats);
331 }
332}
333
334void NetEqImpl::EnableVad() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000335 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000336 assert(vad_.get());
337 vad_->Enable();
338}
339
340void NetEqImpl::DisableVad() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000341 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000342 assert(vad_.get());
343 vad_->Disable();
344}
345
wu@webrtc.org94454b72014-06-05 20:34:08 +0000346bool NetEqImpl::GetPlayoutTimestamp(uint32_t* timestamp) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000347 CriticalSectionScoped lock(crit_sect_.get());
wu@webrtc.org94454b72014-06-05 20:34:08 +0000348 if (first_packet_) {
349 // We don't have a valid RTP timestamp until we have decoded our first
350 // RTP packet.
351 return false;
352 }
353 *timestamp = timestamp_scaler_->ToExternal(playout_timestamp_);
354 return true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000355}
356
henrik.lundin@webrtc.orgb0f4b3d2014-11-04 08:53:10 +0000357int NetEqImpl::LastError() const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000358 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000359 return error_code_;
360}
361
362int NetEqImpl::LastDecoderError() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000363 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000364 return decoder_error_code_;
365}
366
367void NetEqImpl::FlushBuffers() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000368 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000369 LOG_API0();
370 packet_buffer_->Flush();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000371 assert(sync_buffer_.get());
372 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000373 sync_buffer_->Flush();
374 sync_buffer_->set_next_index(sync_buffer_->next_index() -
375 expand_->overlap_length());
376 // Set to wait for new codec.
377 first_packet_ = true;
378}
379
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000380void NetEqImpl::PacketBufferStatistics(int* current_num_packets,
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000381 int* max_num_packets) const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000382 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.org116ed1d2014-04-28 08:20:04 +0000383 packet_buffer_->BufferStat(current_num_packets, max_num_packets);
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000384}
385
turaj@webrtc.orgff43c852013-09-25 00:07:27 +0000386int NetEqImpl::DecodedRtpInfo(int* sequence_number, uint32_t* timestamp) const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000387 CriticalSectionScoped lock(crit_sect_.get());
minyue@webrtc.orgd7301772013-08-29 00:58:14 +0000388 if (decoded_packet_sequence_number_ < 0)
389 return -1;
390 *sequence_number = decoded_packet_sequence_number_;
391 *timestamp = decoded_packet_timestamp_;
392 return 0;
393}
394
henrik.lundin@webrtc.orgb287d962014-04-07 21:21:45 +0000395const SyncBuffer* NetEqImpl::sync_buffer_for_test() const {
396 CriticalSectionScoped lock(crit_sect_.get());
397 return sync_buffer_.get();
398}
399
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000400// Methods below this line are private.
401
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000402int NetEqImpl::InsertPacketInternal(const WebRtcRTPHeader& rtp_header,
403 const uint8_t* payload,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000404 size_t length_bytes,
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000405 uint32_t receive_timestamp,
406 bool is_sync_packet) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000407 if (!payload) {
408 LOG_F(LS_ERROR) << "payload == NULL";
409 return kInvalidPointer;
410 }
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000411 // Sanity checks for sync-packets.
412 if (is_sync_packet) {
413 if (decoder_database_->IsDtmf(rtp_header.header.payloadType) ||
414 decoder_database_->IsRed(rtp_header.header.payloadType) ||
415 decoder_database_->IsComfortNoise(rtp_header.header.payloadType)) {
416 LOG_F(LS_ERROR) << "Sync-packet with an unacceptable payload type "
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000417 << static_cast<int>(rtp_header.header.payloadType);
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000418 return kSyncPacketNotAccepted;
419 }
420 if (first_packet_ ||
421 rtp_header.header.payloadType != current_rtp_payload_type_ ||
422 rtp_header.header.ssrc != ssrc_) {
423 // Even if |current_rtp_payload_type_| is 0xFF, sync-packet isn't
424 // accepted.
pkasting@chromium.orgd3245462015-02-23 21:28:22 +0000425 LOG_F(LS_ERROR)
426 << "Changing codec, SSRC or first packet with sync-packet.";
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000427 return kSyncPacketNotAccepted;
428 }
429 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000430 PacketList packet_list;
431 RTPHeader main_header;
432 {
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000433 // Convert to Packet.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000434 // Create |packet| within this separate scope, since it should not be used
435 // directly once it's been inserted in the packet list. This way, |packet|
436 // is not defined outside of this block.
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000437 Packet* packet = new Packet;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000438 packet->header.markerBit = false;
439 packet->header.payloadType = rtp_header.header.payloadType;
440 packet->header.sequenceNumber = rtp_header.header.sequenceNumber;
441 packet->header.timestamp = rtp_header.header.timestamp;
442 packet->header.ssrc = rtp_header.header.ssrc;
443 packet->header.numCSRCs = 0;
444 packet->payload_length = length_bytes;
445 packet->primary = true;
446 packet->waiting_time = 0;
447 packet->payload = new uint8_t[packet->payload_length];
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000448 packet->sync_packet = is_sync_packet;
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +0000449 if (!packet->payload) {
450 LOG_F(LS_ERROR) << "Payload pointer is NULL.";
451 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000452 assert(payload); // Already checked above.
453 memcpy(packet->payload, payload, packet->payload_length);
454 // Insert packet in a packet list.
455 packet_list.push_back(packet);
456 // Save main payloads header for later.
457 memcpy(&main_header, &packet->header, sizeof(main_header));
458 }
459
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000460 bool update_sample_rate_and_channels = false;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000461 // Reinitialize NetEq if it's needed (changed SSRC or first call).
462 if ((main_header.ssrc != ssrc_) || first_packet_) {
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000463 // Note: |first_packet_| will be cleared further down in this method, once
464 // the packet has been successfully inserted into the packet buffer.
465
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000466 rtcp_.Init(main_header.sequenceNumber);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000467
468 // Flush the packet buffer and DTMF buffer.
469 packet_buffer_->Flush();
470 dtmf_buffer_->Flush();
471
472 // Store new SSRC.
473 ssrc_ = main_header.ssrc;
474
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000475 // Update audio buffer timestamp.
476 sync_buffer_->IncreaseEndTimestamp(main_header.timestamp - timestamp_);
477
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000478 // Update codecs.
479 timestamp_ = main_header.timestamp;
480 current_rtp_payload_type_ = main_header.payloadType;
481
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000482 // Reset timestamp scaling.
483 timestamp_scaler_->Reset();
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000484
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000485 // Trigger an update of sampling rate and the number of channels.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000486 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000487 }
488
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000489 // Update RTCP statistics, only for regular packets.
490 if (!is_sync_packet)
491 rtcp_.Update(main_header, receive_timestamp);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000492
493 // Check for RED payload type, and separate payloads into several packets.
494 if (decoder_database_->IsRed(main_header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000495 assert(!is_sync_packet); // We had a sanity check for this.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000496 if (payload_splitter_->SplitRed(&packet_list) != PayloadSplitter::kOK) {
497 LOG_FERR1(LS_WARNING, SplitRed, packet_list.size());
498 PacketBuffer::DeleteAllPackets(&packet_list);
499 return kRedundancySplitError;
500 }
501 // Only accept a few RED payloads of the same type as the main data,
502 // DTMF events and CNG.
503 payload_splitter_->CheckRedPayloads(&packet_list, *decoder_database_);
504 // Update the stored main payload header since the main payload has now
505 // changed.
506 memcpy(&main_header, &packet_list.front()->header, sizeof(main_header));
507 }
508
509 // Check payload types.
510 if (decoder_database_->CheckPayloadTypes(packet_list) ==
511 DecoderDatabase::kDecoderNotFound) {
512 LOG_FERR1(LS_WARNING, CheckPayloadTypes, packet_list.size());
513 PacketBuffer::DeleteAllPackets(&packet_list);
514 return kUnknownRtpPayloadType;
515 }
516
517 // Scale timestamp to internal domain (only for some codecs).
518 timestamp_scaler_->ToInternal(&packet_list);
519
520 // Process DTMF payloads. Cycle through the list of packets, and pick out any
521 // DTMF payloads found.
522 PacketList::iterator it = packet_list.begin();
523 while (it != packet_list.end()) {
524 Packet* current_packet = (*it);
525 assert(current_packet);
526 assert(current_packet->payload);
527 if (decoder_database_->IsDtmf(current_packet->header.payloadType)) {
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000528 assert(!current_packet->sync_packet); // We had a sanity check for this.
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000529 DtmfEvent event;
530 int ret = DtmfBuffer::ParseEvent(
531 current_packet->header.timestamp,
532 current_packet->payload,
533 current_packet->payload_length,
534 &event);
535 if (ret != DtmfBuffer::kOK) {
536 LOG_FERR2(LS_WARNING, ParseEvent, ret,
537 current_packet->payload_length);
538 PacketBuffer::DeleteAllPackets(&packet_list);
539 return kDtmfParsingError;
540 }
541 if (dtmf_buffer_->InsertEvent(event) != DtmfBuffer::kOK) {
542 LOG_FERR0(LS_WARNING, InsertEvent);
543 PacketBuffer::DeleteAllPackets(&packet_list);
544 return kDtmfInsertError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000545 }
546 // TODO(hlundin): Let the destructor of Packet handle the payload.
547 delete [] current_packet->payload;
548 delete current_packet;
549 it = packet_list.erase(it);
550 } else {
551 ++it;
552 }
553 }
554
minyue@webrtc.org7549ff42014-04-02 15:03:01 +0000555 // Check for FEC in packets, and separate payloads into several packets.
556 int ret = payload_splitter_->SplitFec(&packet_list, decoder_database_.get());
557 if (ret != PayloadSplitter::kOK) {
558 LOG_FERR1(LS_WARNING, SplitFec, packet_list.size());
559 PacketBuffer::DeleteAllPackets(&packet_list);
560 switch (ret) {
561 case PayloadSplitter::kUnknownPayloadType:
562 return kUnknownRtpPayloadType;
563 default:
564 return kOtherError;
565 }
566 }
567
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000568 // Split payloads into smaller chunks. This also verifies that all payloads
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000569 // are of a known payload type. SplitAudio() method is protected against
570 // sync-packets.
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +0000571 ret = payload_splitter_->SplitAudio(&packet_list, *decoder_database_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000572 if (ret != PayloadSplitter::kOK) {
573 LOG_FERR1(LS_WARNING, SplitAudio, packet_list.size());
574 PacketBuffer::DeleteAllPackets(&packet_list);
575 switch (ret) {
576 case PayloadSplitter::kUnknownPayloadType:
577 return kUnknownRtpPayloadType;
578 case PayloadSplitter::kFrameSplitError:
579 return kFrameSplitError;
580 default:
581 return kOtherError;
582 }
583 }
584
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +0000585 // Update bandwidth estimate, if the packet is not sync-packet.
586 if (!packet_list.empty() && !packet_list.front()->sync_packet) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000587 // The list can be empty here if we got nothing but DTMF payloads.
588 AudioDecoder* decoder =
589 decoder_database_->GetDecoder(main_header.payloadType);
590 assert(decoder); // Should always get a valid object, since we have
591 // already checked that the payload types are known.
592 decoder->IncomingPacket(packet_list.front()->payload,
593 packet_list.front()->payload_length,
594 packet_list.front()->header.sequenceNumber,
595 packet_list.front()->header.timestamp,
596 receive_timestamp);
597 }
598
599 // Insert packets in buffer.
600 int temp_bufsize = packet_buffer_->NumPacketsInBuffer();
601 ret = packet_buffer_->InsertPacketList(
602 &packet_list,
603 *decoder_database_,
604 &current_rtp_payload_type_,
605 &current_cng_rtp_payload_type_);
606 if (ret == PacketBuffer::kFlushed) {
607 // Reset DSP timestamp etc. if packet buffer flushed.
608 new_codec_ = true;
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000609 update_sample_rate_and_channels = true;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000610 LOG_F(LS_WARNING) << "Packet buffer flushed";
611 } else if (ret != PacketBuffer::kOK) {
612 LOG_FERR1(LS_WARNING, InsertPacketList, packet_list.size());
613 PacketBuffer::DeleteAllPackets(&packet_list);
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000614 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000615 }
henrik.lundin@webrtc.org6ff3ac12014-11-20 14:14:49 +0000616
617 if (first_packet_) {
618 first_packet_ = false;
619 // Update the codec on the next GetAudio call.
620 new_codec_ = true;
621 }
622
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000623 if (current_rtp_payload_type_ != 0xFF) {
624 const DecoderDatabase::DecoderInfo* dec_info =
625 decoder_database_->GetDecoderInfo(current_rtp_payload_type_);
626 if (!dec_info) {
627 assert(false); // Already checked that the payload type is known.
628 }
629 }
630
turaj@webrtc.orga6101d72013-10-01 22:01:09 +0000631 if (update_sample_rate_and_channels && !packet_buffer_->Empty()) {
632 // We do not use |current_rtp_payload_type_| to |set payload_type|, but
633 // get the next RTP header from |packet_buffer_| to obtain the payload type.
634 // The reason for it is the following corner case. If NetEq receives a
635 // CNG packet with a sample rate different than the current CNG then it
636 // flushes its buffer, assuming send codec must have been changed. However,
637 // payload type of the hypothetically new send codec is not known.
638 const RTPHeader* rtp_header = packet_buffer_->NextRtpHeader();
639 assert(rtp_header);
640 int payload_type = rtp_header->payloadType;
641 AudioDecoder* decoder = decoder_database_->GetDecoder(payload_type);
642 assert(decoder); // Payloads are already checked to be valid.
643 const DecoderDatabase::DecoderInfo* decoder_info =
644 decoder_database_->GetDecoderInfo(payload_type);
645 assert(decoder_info);
646 if (decoder_info->fs_hz != fs_hz_ ||
647 decoder->channels() != algorithm_buffer_->Channels())
648 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->channels());
649 }
650
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000651 // TODO(hlundin): Move this code to DelayManager class.
652 const DecoderDatabase::DecoderInfo* dec_info =
653 decoder_database_->GetDecoderInfo(main_header.payloadType);
654 assert(dec_info); // Already checked that the payload type is known.
655 delay_manager_->LastDecoderType(dec_info->codec_type);
656 if (delay_manager_->last_pack_cng_or_dtmf() == 0) {
657 // Calculate the total speech length carried in each packet.
658 temp_bufsize = packet_buffer_->NumPacketsInBuffer() - temp_bufsize;
659 temp_bufsize *= decoder_frame_length_;
660
661 if ((temp_bufsize > 0) &&
662 (temp_bufsize != decision_logic_->packet_length_samples())) {
663 decision_logic_->set_packet_length_samples(temp_bufsize);
664 delay_manager_->SetPacketAudioLength((1000 * temp_bufsize) / fs_hz_);
665 }
666
667 // Update statistics.
pbos@webrtc.org0946a562013-04-09 00:28:06 +0000668 if ((int32_t) (main_header.timestamp - timestamp_) >= 0 &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000669 !new_codec_) {
670 // Only update statistics if incoming packet is not older than last played
671 // out packet, and if new codec flag is not set.
672 delay_manager_->Update(main_header.sequenceNumber, main_header.timestamp,
673 fs_hz_);
674 }
675 } else if (delay_manager_->last_pack_cng_or_dtmf() == -1) {
676 // This is first "normal" packet after CNG or DTMF.
677 // Reset packet time counter and measure time until next packet,
678 // but don't update statistics.
679 delay_manager_->set_last_pack_cng_or_dtmf(0);
680 delay_manager_->ResetPacketIatCount();
681 }
682 return 0;
683}
684
685int NetEqImpl::GetAudioInternal(size_t max_length, int16_t* output,
686 int* samples_per_channel, int* num_channels) {
687 PacketList packet_list;
688 DtmfEvent dtmf_event;
689 Operations operation;
690 bool play_dtmf;
691 int return_value = GetDecision(&operation, &packet_list, &dtmf_event,
692 &play_dtmf);
693 if (return_value != 0) {
694 LOG_FERR1(LS_WARNING, GetDecision, return_value);
695 assert(false);
696 last_mode_ = kModeError;
697 return return_value;
698 }
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000699 LOG(LS_VERBOSE) << "GetDecision returned operation=" << operation <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000700 " and " << packet_list.size() << " packet(s)";
701
702 AudioDecoder::SpeechType speech_type;
703 int length = 0;
704 int decode_return_value = Decode(&packet_list, &operation,
705 &length, &speech_type);
706
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000707 assert(vad_.get());
708 bool sid_frame_available =
709 (operation == kRfc3389Cng && !packet_list.empty());
710 vad_->Update(decoded_buffer_.get(), length, speech_type,
711 sid_frame_available, fs_hz_);
712
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000713 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000714 switch (operation) {
715 case kNormal: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000716 DoNormal(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000717 break;
718 }
719 case kMerge: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000720 DoMerge(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000721 break;
722 }
723 case kExpand: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000724 return_value = DoExpand(play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000725 break;
726 }
727 case kAccelerate: {
728 return_value = DoAccelerate(decoded_buffer_.get(), length, speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000729 play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000730 break;
731 }
732 case kPreemptiveExpand: {
733 return_value = DoPreemptiveExpand(decoded_buffer_.get(), length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000734 speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000735 break;
736 }
737 case kRfc3389Cng:
738 case kRfc3389CngNoPacket: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000739 return_value = DoRfc3389Cng(&packet_list, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000740 break;
741 }
742 case kCodecInternalCng: {
743 // This handles the case when there is no transmission and the decoder
744 // should produce internal comfort noise.
745 // TODO(hlundin): Write test for codec-internal CNG.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000746 DoCodecInternalCng();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000747 break;
748 }
749 case kDtmf: {
750 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000751 return_value = DoDtmf(dtmf_event, &play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000752 break;
753 }
754 case kAlternativePlc: {
755 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000756 DoAlternativePlc(false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000757 break;
758 }
759 case kAlternativePlcIncreaseTimestamp: {
760 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000761 DoAlternativePlc(true);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000762 break;
763 }
764 case kAudioRepetitionIncreaseTimestamp: {
765 // TODO(hlundin): Write test for this.
766 sync_buffer_->IncreaseEndTimestamp(output_size_samples_);
767 // Skipping break on purpose. Execution should move on into the
768 // next case.
kjellander@webrtc.org7d2b6a92015-01-28 18:37:58 +0000769 FALLTHROUGH();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000770 }
771 case kAudioRepetition: {
772 // TODO(hlundin): Write test for this.
773 // Copy last |output_size_samples_| from |sync_buffer_| to
774 // |algorithm_buffer|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000775 algorithm_buffer_->PushBackFromIndex(
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000776 *sync_buffer_, sync_buffer_->Size() - output_size_samples_);
777 expand_->Reset();
778 break;
779 }
780 case kUndefined: {
781 LOG_F(LS_ERROR) << "Invalid operation kUndefined.";
782 assert(false); // This should not happen.
783 last_mode_ = kModeError;
784 return kInvalidOperation;
785 }
786 } // End of switch.
787 if (return_value < 0) {
788 return return_value;
789 }
790
791 if (last_mode_ != kModeRfc3389Cng) {
792 comfort_noise_->Reset();
793 }
794
795 // Copy from |algorithm_buffer| to |sync_buffer_|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000796 sync_buffer_->PushBack(*algorithm_buffer_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000797
798 // Extract data from |sync_buffer_| to |output|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000799 size_t num_output_samples_per_channel = output_size_samples_;
800 size_t num_output_samples = output_size_samples_ * sync_buffer_->Channels();
801 if (num_output_samples > max_length) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000802 LOG(LS_WARNING) << "Output array is too short. " << max_length << " < " <<
803 output_size_samples_ << " * " << sync_buffer_->Channels();
804 num_output_samples = max_length;
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000805 num_output_samples_per_channel = static_cast<int>(
806 max_length / sync_buffer_->Channels());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000807 }
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000808 int samples_from_sync = static_cast<int>(
809 sync_buffer_->GetNextAudioInterleaved(num_output_samples_per_channel,
810 output));
811 *num_channels = static_cast<int>(sync_buffer_->Channels());
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +0000812 LOG(LS_VERBOSE) << "Sync buffer (" << *num_channels << " channel(s)):" <<
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000813 " insert " << algorithm_buffer_->Size() << " samples, extract " <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000814 samples_from_sync << " samples";
815 if (samples_from_sync != output_size_samples_) {
816 LOG_F(LS_ERROR) << "samples_from_sync != output_size_samples_";
minyue@webrtc.orgdb1cefc2013-08-13 01:39:21 +0000817 // TODO(minyue): treatment of under-run, filling zeros
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000818 memset(output, 0, num_output_samples * sizeof(int16_t));
819 *samples_per_channel = output_size_samples_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000820 return kSampleUnderrun;
821 }
822 *samples_per_channel = output_size_samples_;
823
824 // Should always have overlap samples left in the |sync_buffer_|.
825 assert(sync_buffer_->FutureLength() >= expand_->overlap_length());
826
827 if (play_dtmf) {
828 return_value = DtmfOverdub(dtmf_event, sync_buffer_->Channels(), output);
829 }
830
831 // Update the background noise parameters if last operation wrote data
832 // straight from the decoder to the |sync_buffer_|. That is, none of the
833 // operations that modify the signal can be followed by a parameter update.
834 if ((last_mode_ == kModeNormal) ||
835 (last_mode_ == kModeAccelerateFail) ||
836 (last_mode_ == kModePreemptiveExpandFail) ||
837 (last_mode_ == kModeRfc3389Cng) ||
838 (last_mode_ == kModeCodecInternalCng)) {
839 background_noise_->Update(*sync_buffer_, *vad_.get());
840 }
841
842 if (operation == kDtmf) {
843 // DTMF data was written the end of |sync_buffer_|.
844 // Update index to end of DTMF data in |sync_buffer_|.
845 sync_buffer_->set_dtmf_index(sync_buffer_->Size());
846 }
847
henrik.lundin@webrtc.orged865b52014-03-06 10:28:07 +0000848 if (last_mode_ != kModeExpand) {
849 // If last operation was not expand, calculate the |playout_timestamp_| from
850 // the |sync_buffer_|. However, do not update the |playout_timestamp_| if it
851 // would be moved "backwards".
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000852 uint32_t temp_timestamp = sync_buffer_->end_timestamp() -
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000853 static_cast<uint32_t>(sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000854 if (static_cast<int32_t>(temp_timestamp - playout_timestamp_) > 0) {
855 playout_timestamp_ = temp_timestamp;
856 }
857 } else {
858 // Use dead reckoning to estimate the |playout_timestamp_|.
859 playout_timestamp_ += output_size_samples_;
860 }
861
862 if (decode_return_value) return decode_return_value;
863 return return_value;
864}
865
866int NetEqImpl::GetDecision(Operations* operation,
867 PacketList* packet_list,
868 DtmfEvent* dtmf_event,
869 bool* play_dtmf) {
870 // Initialize output variables.
871 *play_dtmf = false;
872 *operation = kUndefined;
873
874 // Increment time counters.
875 packet_buffer_->IncrementWaitingTimes();
876 stats_.IncreaseCounter(output_size_samples_, fs_hz_);
877
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000878 assert(sync_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000879 uint32_t end_timestamp = sync_buffer_->end_timestamp();
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +0000880 if (!new_codec_) {
881 const uint32_t five_seconds_samples = 5 * fs_hz_;
882 packet_buffer_->DiscardOldPackets(end_timestamp, five_seconds_samples);
883 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000884 const RTPHeader* header = packet_buffer_->NextRtpHeader();
885
henrik.lundin@webrtc.orgca8cb952014-03-12 10:26:52 +0000886 if (decision_logic_->CngRfc3389On() || last_mode_ == kModeRfc3389Cng) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000887 // Because of timestamp peculiarities, we have to "manually" disallow using
888 // a CNG packet with the same timestamp as the one that was last played.
889 // This can happen when using redundancy and will cause the timing to shift.
henrik.lundin@webrtc.org24779fe2014-03-14 12:40:05 +0000890 while (header && decoder_database_->IsComfortNoise(header->payloadType) &&
891 (end_timestamp >= header->timestamp ||
892 end_timestamp + decision_logic_->generated_noise_samples() >
893 header->timestamp)) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000894 // Don't use this packet, discard it.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000895 if (packet_buffer_->DiscardNextPacket() != PacketBuffer::kOK) {
896 assert(false); // Must be ok by design.
897 }
898 // Check buffer again.
899 if (!new_codec_) {
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +0000900 packet_buffer_->DiscardOldPackets(end_timestamp, 5 * fs_hz_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000901 }
902 header = packet_buffer_->NextRtpHeader();
903 }
904 }
905
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000906 assert(expand_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +0000907 const int samples_left = static_cast<int>(sync_buffer_->FutureLength() -
908 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000909 if (last_mode_ == kModeAccelerateSuccess ||
910 last_mode_ == kModeAccelerateLowEnergy ||
911 last_mode_ == kModePreemptiveExpandSuccess ||
912 last_mode_ == kModePreemptiveExpandLowEnergy) {
913 // Subtract (samples_left + output_size_samples_) from sampleMemory.
914 decision_logic_->AddSampleMemory(-(samples_left + output_size_samples_));
915 }
916
917 // Check if it is time to play a DTMF event.
918 if (dtmf_buffer_->GetEvent(end_timestamp +
919 decision_logic_->generated_noise_samples(),
920 dtmf_event)) {
921 *play_dtmf = true;
922 }
923
924 // Get instruction.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000925 assert(sync_buffer_.get());
926 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000927 *operation = decision_logic_->GetDecision(*sync_buffer_,
928 *expand_,
929 decoder_frame_length_,
930 header,
931 last_mode_,
932 *play_dtmf,
933 &reset_decoder_);
934
935 // Check if we already have enough samples in the |sync_buffer_|. If so,
936 // change decision to normal, unless the decision was merge, accelerate, or
937 // preemptive expand.
938 if (samples_left >= output_size_samples_ &&
939 *operation != kMerge &&
940 *operation != kAccelerate &&
941 *operation != kPreemptiveExpand) {
942 *operation = kNormal;
943 return 0;
944 }
945
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +0000946 decision_logic_->ExpandDecision(*operation);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000947
948 // Check conditions for reset.
949 if (new_codec_ || *operation == kUndefined) {
950 // The only valid reason to get kUndefined is that new_codec_ is set.
951 assert(new_codec_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000952 if (*play_dtmf && !header) {
953 timestamp_ = dtmf_event->timestamp;
954 } else {
955 assert(header);
956 if (!header) {
957 LOG_F(LS_ERROR) << "Packet missing where it shouldn't.";
958 return -1;
959 }
960 timestamp_ = header->timestamp;
961 if (*operation == kRfc3389CngNoPacket
962#ifndef LEGACY_BITEXACT
963 // Without this check, it can happen that a non-CNG packet is sent to
964 // the CNG decoder as if it was a SID frame. This is clearly a bug,
965 // but is kept for now to maintain bit-exactness with the test
966 // vectors.
967 && decoder_database_->IsComfortNoise(header->payloadType)
968#endif
969 ) {
970 // Change decision to CNG packet, since we do have a CNG packet, but it
971 // was considered too early to use. Now, use it anyway.
972 *operation = kRfc3389Cng;
973 } else if (*operation != kRfc3389Cng) {
974 *operation = kNormal;
975 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000976 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000977 // Adjust |sync_buffer_| timestamp before setting |end_timestamp| to the
978 // new value.
979 sync_buffer_->IncreaseEndTimestamp(timestamp_ - end_timestamp);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000980 end_timestamp = timestamp_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000981 new_codec_ = false;
982 decision_logic_->SoftReset();
983 buffer_level_filter_->Reset();
984 delay_manager_->Reset();
985 stats_.ResetMcu();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000986 }
987
988 int required_samples = output_size_samples_;
989 const int samples_10_ms = 80 * fs_mult_;
990 const int samples_20_ms = 2 * samples_10_ms;
991 const int samples_30_ms = 3 * samples_10_ms;
992
993 switch (*operation) {
994 case kExpand: {
995 timestamp_ = end_timestamp;
996 return 0;
997 }
998 case kRfc3389CngNoPacket:
999 case kCodecInternalCng: {
1000 return 0;
1001 }
1002 case kDtmf: {
1003 // TODO(hlundin): Write test for this.
1004 // Update timestamp.
1005 timestamp_ = end_timestamp;
1006 if (decision_logic_->generated_noise_samples() > 0 &&
1007 last_mode_ != kModeDtmf) {
1008 // Make a jump in timestamp due to the recently played comfort noise.
1009 uint32_t timestamp_jump = decision_logic_->generated_noise_samples();
1010 sync_buffer_->IncreaseEndTimestamp(timestamp_jump);
1011 timestamp_ += timestamp_jump;
1012 }
1013 decision_logic_->set_generated_noise_samples(0);
1014 return 0;
1015 }
1016 case kAccelerate: {
1017 // In order to do a accelerate we need at least 30 ms of audio data.
1018 if (samples_left >= samples_30_ms) {
1019 // Already have enough data, so we do not need to extract any more.
1020 decision_logic_->set_sample_memory(samples_left);
1021 decision_logic_->set_prev_time_scale(true);
1022 return 0;
1023 } else if (samples_left >= samples_10_ms &&
1024 decoder_frame_length_ >= samples_30_ms) {
1025 // Avoid decoding more data as it might overflow the playout buffer.
1026 *operation = kNormal;
1027 return 0;
1028 } else if (samples_left < samples_20_ms &&
1029 decoder_frame_length_ < samples_30_ms) {
1030 // Build up decoded data by decoding at least 20 ms of audio data. Do
1031 // not perform accelerate yet, but wait until we only need to do one
1032 // decoding.
1033 required_samples = 2 * output_size_samples_;
1034 *operation = kNormal;
1035 }
1036 // If none of the above is true, we have one of two possible situations:
1037 // (1) 20 ms <= samples_left < 30 ms and decoder_frame_length_ < 30 ms; or
1038 // (2) samples_left < 10 ms and decoder_frame_length_ >= 30 ms.
1039 // In either case, we move on with the accelerate decision, and decode one
1040 // frame now.
1041 break;
1042 }
1043 case kPreemptiveExpand: {
1044 // In order to do a preemptive expand we need at least 30 ms of decoded
1045 // audio data.
1046 if ((samples_left >= samples_30_ms) ||
1047 (samples_left >= samples_10_ms &&
1048 decoder_frame_length_ >= samples_30_ms)) {
1049 // Already have enough data, so we do not need to extract any more.
1050 // Or, avoid decoding more data as it might overflow the playout buffer.
1051 // Still try preemptive expand, though.
1052 decision_logic_->set_sample_memory(samples_left);
1053 decision_logic_->set_prev_time_scale(true);
1054 return 0;
1055 }
1056 if (samples_left < samples_20_ms &&
1057 decoder_frame_length_ < samples_30_ms) {
1058 // Build up decoded data by decoding at least 20 ms of audio data.
1059 // Still try to perform preemptive expand.
1060 required_samples = 2 * output_size_samples_;
1061 }
1062 // Move on with the preemptive expand decision.
1063 break;
1064 }
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001065 case kMerge: {
1066 required_samples =
1067 std::max(merge_->RequiredFutureSamples(), required_samples);
1068 break;
1069 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001070 default: {
1071 // Do nothing.
1072 }
1073 }
1074
1075 // Get packets from buffer.
1076 int extracted_samples = 0;
1077 if (header &&
1078 *operation != kAlternativePlc &&
1079 *operation != kAlternativePlcIncreaseTimestamp &&
1080 *operation != kAudioRepetition &&
1081 *operation != kAudioRepetitionIncreaseTimestamp) {
1082 sync_buffer_->IncreaseEndTimestamp(header->timestamp - end_timestamp);
1083 if (decision_logic_->CngOff()) {
1084 // Adjustment of timestamp only corresponds to an actual packet loss
1085 // if comfort noise is not played. If comfort noise was just played,
1086 // this adjustment of timestamp is only done to get back in sync with the
1087 // stream timestamp; no loss to report.
1088 stats_.LostSamples(header->timestamp - end_timestamp);
1089 }
1090
1091 if (*operation != kRfc3389Cng) {
1092 // We are about to decode and use a non-CNG packet.
1093 decision_logic_->SetCngOff();
1094 }
1095 // Reset CNG timestamp as a new packet will be delivered.
1096 // (Also if this is a CNG packet, since playedOutTS is updated.)
1097 decision_logic_->set_generated_noise_samples(0);
1098
1099 extracted_samples = ExtractPackets(required_samples, packet_list);
1100 if (extracted_samples < 0) {
1101 LOG_F(LS_WARNING) << "Failed to extract packets from buffer.";
1102 return kPacketBufferCorruption;
1103 }
1104 }
1105
1106 if (*operation == kAccelerate ||
1107 *operation == kPreemptiveExpand) {
1108 decision_logic_->set_sample_memory(samples_left + extracted_samples);
1109 decision_logic_->set_prev_time_scale(true);
1110 }
1111
1112 if (*operation == kAccelerate) {
1113 // Check that we have enough data (30ms) to do accelerate.
1114 if (extracted_samples + samples_left < samples_30_ms) {
1115 // TODO(hlundin): Write test for this.
1116 // Not enough, do normal operation instead.
1117 *operation = kNormal;
1118 }
1119 }
1120
1121 timestamp_ = end_timestamp;
1122 return 0;
1123}
1124
1125int NetEqImpl::Decode(PacketList* packet_list, Operations* operation,
1126 int* decoded_length,
1127 AudioDecoder::SpeechType* speech_type) {
1128 *speech_type = AudioDecoder::kSpeech;
1129 AudioDecoder* decoder = NULL;
1130 if (!packet_list->empty()) {
1131 const Packet* packet = packet_list->front();
pkasting@chromium.org0e81fdf2015-02-02 23:54:03 +00001132 uint8_t payload_type = packet->header.payloadType;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001133 if (!decoder_database_->IsComfortNoise(payload_type)) {
1134 decoder = decoder_database_->GetDecoder(payload_type);
1135 assert(decoder);
1136 if (!decoder) {
pkasting@chromium.org0e81fdf2015-02-02 23:54:03 +00001137 LOG_FERR1(LS_WARNING, GetDecoder, static_cast<int>(payload_type));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001138 PacketBuffer::DeleteAllPackets(packet_list);
1139 return kDecoderNotFound;
1140 }
1141 bool decoder_changed;
1142 decoder_database_->SetActiveDecoder(payload_type, &decoder_changed);
1143 if (decoder_changed) {
1144 // We have a new decoder. Re-init some values.
1145 const DecoderDatabase::DecoderInfo* decoder_info = decoder_database_
1146 ->GetDecoderInfo(payload_type);
1147 assert(decoder_info);
1148 if (!decoder_info) {
pkasting@chromium.org0e81fdf2015-02-02 23:54:03 +00001149 LOG_FERR1(LS_WARNING, GetDecoderInfo, static_cast<int>(payload_type));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001150 PacketBuffer::DeleteAllPackets(packet_list);
1151 return kDecoderNotFound;
1152 }
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001153 // If sampling rate or number of channels has changed, we need to make
1154 // a reset.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001155 if (decoder_info->fs_hz != fs_hz_ ||
1156 decoder->channels() != algorithm_buffer_->Channels()) {
tina.legrand@webrtc.orgba5a6c32014-03-23 09:58:48 +00001157 // TODO(tlegrand): Add unittest to cover this event.
turaj@webrtc.orga6101d72013-10-01 22:01:09 +00001158 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->channels());
1159 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001160 sync_buffer_->set_end_timestamp(timestamp_);
1161 playout_timestamp_ = timestamp_;
1162 }
1163 }
1164 }
1165
1166 if (reset_decoder_) {
1167 // TODO(hlundin): Write test for this.
1168 // Reset decoder.
1169 if (decoder) {
1170 decoder->Init();
1171 }
1172 // Reset comfort noise decoder.
1173 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
1174 if (cng_decoder) {
1175 cng_decoder->Init();
1176 }
1177 reset_decoder_ = false;
1178 }
1179
1180#ifdef LEGACY_BITEXACT
1181 // Due to a bug in old SignalMCU, it could happen that CNG operation was
1182 // decided, but a speech packet was provided. The speech packet will be used
1183 // to update the comfort noise decoder, as if it was a SID frame, which is
1184 // clearly wrong.
1185 if (*operation == kRfc3389Cng) {
1186 return 0;
1187 }
1188#endif
1189
1190 *decoded_length = 0;
1191 // Update codec-internal PLC state.
1192 if ((*operation == kMerge) && decoder && decoder->HasDecodePlc()) {
1193 decoder->DecodePlc(1, &decoded_buffer_[*decoded_length]);
1194 }
1195
1196 int return_value = DecodeLoop(packet_list, operation, decoder,
1197 decoded_length, speech_type);
1198
1199 if (*decoded_length < 0) {
1200 // Error returned from the decoder.
1201 *decoded_length = 0;
1202 sync_buffer_->IncreaseEndTimestamp(decoder_frame_length_);
1203 int error_code = 0;
1204 if (decoder)
1205 error_code = decoder->ErrorCode();
1206 if (error_code != 0) {
1207 // Got some error code from the decoder.
1208 decoder_error_code_ = error_code;
1209 return_value = kDecoderErrorCode;
1210 } else {
1211 // Decoder does not implement error codes. Return generic error.
1212 return_value = kOtherDecoderError;
1213 }
1214 LOG_FERR2(LS_WARNING, DecodeLoop, error_code, packet_list->size());
1215 *operation = kExpand; // Do expansion to get data instead.
1216 }
1217 if (*speech_type != AudioDecoder::kComfortNoise) {
1218 // Don't increment timestamp if codec returned CNG speech type
1219 // since in this case, the we will increment the CNGplayedTS counter.
1220 // Increase with number of samples per channel.
1221 assert(*decoded_length == 0 ||
1222 (decoder && decoder->channels() == sync_buffer_->Channels()));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001223 sync_buffer_->IncreaseEndTimestamp(
1224 *decoded_length / static_cast<int>(sync_buffer_->Channels()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001225 }
1226 return return_value;
1227}
1228
1229int NetEqImpl::DecodeLoop(PacketList* packet_list, Operations* operation,
1230 AudioDecoder* decoder, int* decoded_length,
1231 AudioDecoder::SpeechType* speech_type) {
1232 Packet* packet = NULL;
1233 if (!packet_list->empty()) {
1234 packet = packet_list->front();
1235 }
1236 // Do decoding.
1237 while (packet &&
1238 !decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1239 assert(decoder); // At this point, we must have a decoder object.
1240 // The number of channels in the |sync_buffer_| should be the same as the
1241 // number decoder channels.
1242 assert(sync_buffer_->Channels() == decoder->channels());
1243 assert(decoded_buffer_length_ >= kMaxFrameSize * decoder->channels());
1244 assert(*operation == kNormal || *operation == kAccelerate ||
1245 *operation == kMerge || *operation == kPreemptiveExpand);
1246 packet_list->pop_front();
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +00001247 size_t payload_length = packet->payload_length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001248 int16_t decode_length;
turaj@webrtc.org7b75ac62013-09-26 00:27:56 +00001249 if (packet->sync_packet) {
1250 // Decode to silence with the same frame size as the last decode.
1251 LOG(LS_VERBOSE) << "Decoding sync-packet: " <<
1252 " ts=" << packet->header.timestamp <<
1253 ", sn=" << packet->header.sequenceNumber <<
1254 ", pt=" << static_cast<int>(packet->header.payloadType) <<
1255 ", ssrc=" << packet->header.ssrc <<
1256 ", len=" << packet->payload_length;
1257 memset(&decoded_buffer_[*decoded_length], 0, decoder_frame_length_ *
1258 decoder->channels() * sizeof(decoded_buffer_[0]));
1259 decode_length = decoder_frame_length_;
1260 } else if (!packet->primary) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001261 // This is a redundant payload; call the special decoder method.
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +00001262 LOG(LS_VERBOSE) << "Decoding packet (redundant):" <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001263 " ts=" << packet->header.timestamp <<
1264 ", sn=" << packet->header.sequenceNumber <<
1265 ", pt=" << static_cast<int>(packet->header.payloadType) <<
1266 ", ssrc=" << packet->header.ssrc <<
1267 ", len=" << packet->payload_length;
1268 decode_length = decoder->DecodeRedundant(
henrik.lundin@webrtc.orgb9c18d52015-02-24 15:58:17 +00001269 packet->payload, packet->payload_length, fs_hz_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001270 &decoded_buffer_[*decoded_length], speech_type);
1271 } else {
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +00001272 LOG(LS_VERBOSE) << "Decoding packet: ts=" << packet->header.timestamp <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001273 ", sn=" << packet->header.sequenceNumber <<
1274 ", pt=" << static_cast<int>(packet->header.payloadType) <<
1275 ", ssrc=" << packet->header.ssrc <<
1276 ", len=" << packet->payload_length;
henrik.lundin@webrtc.orgb9c18d52015-02-24 15:58:17 +00001277 decode_length =
1278 decoder->Decode(packet->payload, packet->payload_length, fs_hz_,
1279 &decoded_buffer_[*decoded_length], speech_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001280 }
1281
1282 delete[] packet->payload;
1283 delete packet;
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001284 packet = NULL;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001285 if (decode_length > 0) {
1286 *decoded_length += decode_length;
1287 // Update |decoder_frame_length_| with number of samples per channel.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001288 decoder_frame_length_ = decode_length /
1289 static_cast<int>(decoder->channels());
turaj@webrtc.org0c0fae82013-09-25 17:42:17 +00001290 LOG(LS_VERBOSE) << "Decoded " << decode_length << " samples (" <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001291 decoder->channels() << " channel(s) -> " << decoder_frame_length_ <<
1292 " samples per channel)";
1293 } else if (decode_length < 0) {
1294 // Error.
henrik.lundin@webrtc.org63464a92013-01-30 09:41:56 +00001295 LOG_FERR2(LS_WARNING, Decode, decode_length, payload_length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001296 *decoded_length = -1;
1297 PacketBuffer::DeleteAllPackets(packet_list);
1298 break;
1299 }
1300 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1301 // Guard against overflow.
1302 LOG_F(LS_WARNING) << "Decoded too much.";
1303 PacketBuffer::DeleteAllPackets(packet_list);
1304 return kDecodedTooMuch;
1305 }
1306 if (!packet_list->empty()) {
1307 packet = packet_list->front();
1308 } else {
1309 packet = NULL;
1310 }
1311 } // End of decode loop.
1312
turaj@webrtc.org58cd3162013-10-31 15:15:55 +00001313 // If the list is not empty at this point, either a decoding error terminated
1314 // the while-loop, or list must hold exactly one CNG packet.
1315 assert(packet_list->empty() || *decoded_length < 0 ||
1316 (packet_list->size() == 1 && packet &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001317 decoder_database_->IsComfortNoise(packet->header.payloadType)));
1318 return 0;
1319}
1320
1321void NetEqImpl::DoNormal(const int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001322 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001323 assert(normal_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001324 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001325 normal_->Process(decoded_buffer, decoded_length, last_mode_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001326 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001327 if (decoded_length != 0) {
1328 last_mode_ = kModeNormal;
1329 }
1330
1331 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1332 if ((speech_type == AudioDecoder::kComfortNoise)
1333 || ((last_mode_ == kModeCodecInternalCng)
1334 && (decoded_length == 0))) {
1335 // TODO(hlundin): Remove second part of || statement above.
1336 last_mode_ = kModeCodecInternalCng;
1337 }
1338
1339 if (!play_dtmf) {
1340 dtmf_tone_generator_->Reset();
1341 }
1342}
1343
1344void NetEqImpl::DoMerge(int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001345 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001346 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001347 assert(merge_.get());
1348 int new_length = merge_->Process(decoded_buffer, decoded_length,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001349 mute_factor_array_.get(),
1350 algorithm_buffer_.get());
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001351 int expand_length_correction = new_length -
1352 static_cast<int>(decoded_length / algorithm_buffer_->Channels());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001353
1354 // Update in-call and post-call statistics.
1355 if (expand_->MuteFactor(0) == 0) {
1356 // Expand generates only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001357 stats_.ExpandedNoiseSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001358 } else {
1359 // Expansion generates more than only noise.
minyue@webrtc.orgc11348b2015-02-10 08:35:38 +00001360 stats_.ExpandedVoiceSamples(expand_length_correction);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001361 }
1362
1363 last_mode_ = kModeMerge;
1364 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1365 if (speech_type == AudioDecoder::kComfortNoise) {
1366 last_mode_ = kModeCodecInternalCng;
1367 }
1368 expand_->Reset();
1369 if (!play_dtmf) {
1370 dtmf_tone_generator_->Reset();
1371 }
1372}
1373
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001374int NetEqImpl::DoExpand(bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001375 while ((sync_buffer_->FutureLength() - expand_->overlap_length()) <
1376 static_cast<size_t>(output_size_samples_)) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001377 algorithm_buffer_->Clear();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001378 int return_value = expand_->Process(algorithm_buffer_.get());
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001379 int length = static_cast<int>(algorithm_buffer_->Size());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001380
1381 // Update in-call and post-call statistics.
1382 if (expand_->MuteFactor(0) == 0) {
1383 // Expand operation generates only noise.
1384 stats_.ExpandedNoiseSamples(length);
1385 } else {
1386 // Expand operation generates more than only noise.
1387 stats_.ExpandedVoiceSamples(length);
1388 }
1389
1390 last_mode_ = kModeExpand;
1391
1392 if (return_value < 0) {
1393 return return_value;
1394 }
1395
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001396 sync_buffer_->PushBack(*algorithm_buffer_);
1397 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001398 }
1399 if (!play_dtmf) {
1400 dtmf_tone_generator_->Reset();
1401 }
1402 return 0;
1403}
1404
1405int NetEqImpl::DoAccelerate(int16_t* decoded_buffer, size_t decoded_length,
1406 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001407 bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001408 const size_t required_samples = 240 * fs_mult_; // Must have 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001409 size_t borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001410 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001411 size_t decoded_length_per_channel = decoded_length / num_channels;
1412 if (decoded_length_per_channel < required_samples) {
1413 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001414 borrowed_samples_per_channel = static_cast<int>(required_samples -
1415 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001416 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1417 decoded_buffer,
1418 sizeof(int16_t) * decoded_length);
1419 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1420 decoded_buffer);
1421 decoded_length = required_samples * num_channels;
1422 }
1423
1424 int16_t samples_removed;
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001425 Accelerate::ReturnCodes return_code = accelerate_->Process(
1426 decoded_buffer, decoded_length, algorithm_buffer_.get(),
1427 &samples_removed);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001428 stats_.AcceleratedSamples(samples_removed);
1429 switch (return_code) {
1430 case Accelerate::kSuccess:
1431 last_mode_ = kModeAccelerateSuccess;
1432 break;
1433 case Accelerate::kSuccessLowEnergy:
1434 last_mode_ = kModeAccelerateLowEnergy;
1435 break;
1436 case Accelerate::kNoStretch:
1437 last_mode_ = kModeAccelerateFail;
1438 break;
1439 case Accelerate::kError:
1440 // TODO(hlundin): Map to kModeError instead?
1441 last_mode_ = kModeAccelerateFail;
1442 return kAccelerateError;
1443 }
1444
1445 if (borrowed_samples_per_channel > 0) {
1446 // Copy borrowed samples back to the |sync_buffer_|.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001447 size_t length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001448 if (length < borrowed_samples_per_channel) {
1449 // This destroys the beginning of the buffer, but will not cause any
1450 // problems.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001451 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001452 sync_buffer_->Size() -
1453 borrowed_samples_per_channel);
1454 sync_buffer_->PushFrontZeros(borrowed_samples_per_channel - length);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001455 algorithm_buffer_->PopFront(length);
1456 assert(algorithm_buffer_->Empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001457 } else {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001458 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001459 borrowed_samples_per_channel,
1460 sync_buffer_->Size() -
1461 borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001462 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001463 }
1464 }
1465
1466 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1467 if (speech_type == AudioDecoder::kComfortNoise) {
1468 last_mode_ = kModeCodecInternalCng;
1469 }
1470 if (!play_dtmf) {
1471 dtmf_tone_generator_->Reset();
1472 }
1473 expand_->Reset();
1474 return 0;
1475}
1476
1477int NetEqImpl::DoPreemptiveExpand(int16_t* decoded_buffer,
1478 size_t decoded_length,
1479 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001480 bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001481 const size_t required_samples = 240 * fs_mult_; // Must have 30 ms.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001482 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001483 int borrowed_samples_per_channel = 0;
1484 int old_borrowed_samples_per_channel = 0;
1485 size_t decoded_length_per_channel = decoded_length / num_channels;
1486 if (decoded_length_per_channel < required_samples) {
1487 // Must move data from the |sync_buffer_| in order to get 30 ms.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001488 borrowed_samples_per_channel = static_cast<int>(required_samples -
1489 decoded_length_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001490 // Calculate how many of these were already played out.
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001491 old_borrowed_samples_per_channel = static_cast<int>(
1492 borrowed_samples_per_channel - sync_buffer_->FutureLength());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001493 old_borrowed_samples_per_channel = std::max(
1494 0, old_borrowed_samples_per_channel);
1495 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1496 decoded_buffer,
1497 sizeof(int16_t) * decoded_length);
1498 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1499 decoded_buffer);
1500 decoded_length = required_samples * num_channels;
1501 }
1502
1503 int16_t samples_added;
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001504 PreemptiveExpand::ReturnCodes return_code = preemptive_expand_->Process(
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001505 decoded_buffer, static_cast<int>(decoded_length),
1506 old_borrowed_samples_per_channel,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001507 algorithm_buffer_.get(), &samples_added);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001508 stats_.PreemptiveExpandedSamples(samples_added);
1509 switch (return_code) {
1510 case PreemptiveExpand::kSuccess:
1511 last_mode_ = kModePreemptiveExpandSuccess;
1512 break;
1513 case PreemptiveExpand::kSuccessLowEnergy:
1514 last_mode_ = kModePreemptiveExpandLowEnergy;
1515 break;
1516 case PreemptiveExpand::kNoStretch:
1517 last_mode_ = kModePreemptiveExpandFail;
1518 break;
1519 case PreemptiveExpand::kError:
1520 // TODO(hlundin): Map to kModeError instead?
1521 last_mode_ = kModePreemptiveExpandFail;
1522 return kPreemptiveExpandError;
1523 }
1524
1525 if (borrowed_samples_per_channel > 0) {
1526 // Copy borrowed samples back to the |sync_buffer_|.
1527 sync_buffer_->ReplaceAtIndex(
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001528 *algorithm_buffer_, borrowed_samples_per_channel,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001529 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001530 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001531 }
1532
1533 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1534 if (speech_type == AudioDecoder::kComfortNoise) {
1535 last_mode_ = kModeCodecInternalCng;
1536 }
1537 if (!play_dtmf) {
1538 dtmf_tone_generator_->Reset();
1539 }
1540 expand_->Reset();
1541 return 0;
1542}
1543
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001544int NetEqImpl::DoRfc3389Cng(PacketList* packet_list, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001545 if (!packet_list->empty()) {
1546 // Must have exactly one SID frame at this point.
1547 assert(packet_list->size() == 1);
1548 Packet* packet = packet_list->front();
1549 packet_list->pop_front();
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001550 if (!decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1551#ifdef LEGACY_BITEXACT
1552 // This can happen due to a bug in GetDecision. Change the payload type
1553 // to a CNG type, and move on. Note that this means that we are in fact
1554 // sending a non-CNG payload to the comfort noise decoder for decoding.
1555 // Clearly wrong, but will maintain bit-exactness with legacy.
1556 if (fs_hz_ == 8000) {
1557 packet->header.payloadType =
1558 decoder_database_->GetRtpPayloadType(kDecoderCNGnb);
1559 } else if (fs_hz_ == 16000) {
1560 packet->header.payloadType =
1561 decoder_database_->GetRtpPayloadType(kDecoderCNGwb);
1562 } else if (fs_hz_ == 32000) {
1563 packet->header.payloadType =
1564 decoder_database_->GetRtpPayloadType(kDecoderCNGswb32kHz);
1565 } else if (fs_hz_ == 48000) {
1566 packet->header.payloadType =
1567 decoder_database_->GetRtpPayloadType(kDecoderCNGswb48kHz);
1568 }
1569 assert(decoder_database_->IsComfortNoise(packet->header.payloadType));
1570#else
1571 LOG(LS_ERROR) << "Trying to decode non-CNG payload as CNG.";
1572 return kOtherError;
1573#endif
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001574 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001575 // UpdateParameters() deletes |packet|.
1576 if (comfort_noise_->UpdateParameters(packet) ==
1577 ComfortNoise::kInternalError) {
1578 LOG_FERR0(LS_WARNING, UpdateParameters);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001579 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001580 return -comfort_noise_->internal_error_code();
1581 }
1582 }
1583 int cn_return = comfort_noise_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001584 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001585 expand_->Reset();
1586 last_mode_ = kModeRfc3389Cng;
1587 if (!play_dtmf) {
1588 dtmf_tone_generator_->Reset();
1589 }
1590 if (cn_return == ComfortNoise::kInternalError) {
1591 LOG_FERR1(LS_WARNING, comfort_noise_->Generate, cn_return);
1592 decoder_error_code_ = comfort_noise_->internal_error_code();
1593 return kComfortNoiseErrorCode;
1594 } else if (cn_return == ComfortNoise::kUnknownPayloadType) {
1595 LOG_FERR1(LS_WARNING, comfort_noise_->Generate, cn_return);
1596 return kUnknownRtpPayloadType;
1597 }
1598 return 0;
1599}
1600
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001601void NetEqImpl::DoCodecInternalCng() {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001602 int length = 0;
1603 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1604 int16_t decoded_buffer[kMaxFrameSize];
1605 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1606 if (decoder) {
1607 const uint8_t* dummy_payload = NULL;
1608 AudioDecoder::SpeechType speech_type;
henrik.lundin@webrtc.orgb9c18d52015-02-24 15:58:17 +00001609 length =
1610 decoder->Decode(dummy_payload, 0, fs_hz_, decoded_buffer, &speech_type);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001611 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001612 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001613 normal_->Process(decoded_buffer, length, last_mode_, mute_factor_array_.get(),
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001614 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001615 last_mode_ = kModeCodecInternalCng;
1616 expand_->Reset();
1617}
1618
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001619int NetEqImpl::DoDtmf(const DtmfEvent& dtmf_event, bool* play_dtmf) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001620 // This block of the code and the block further down, handling |dtmf_switch|
1621 // are commented out. Otherwise playing out-of-band DTMF would fail in VoE
1622 // test, DtmfTest.ManualSuccessfullySendsOutOfBandTelephoneEvents. This is
1623 // equivalent to |dtmf_switch| always be false.
1624 //
1625 // See http://webrtc-codereview.appspot.com/1195004/ for discussion
1626 // On this issue. This change might cause some glitches at the point of
1627 // switch from audio to DTMF. Issue 1545 is filed to track this.
1628 //
1629 // bool dtmf_switch = false;
1630 // if ((last_mode_ != kModeDtmf) && dtmf_tone_generator_->initialized()) {
1631 // // Special case; see below.
1632 // // We must catch this before calling Generate, since |initialized| is
1633 // // modified in that call.
1634 // dtmf_switch = true;
1635 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001636
1637 int dtmf_return_value = 0;
1638 if (!dtmf_tone_generator_->initialized()) {
1639 // Initialize if not already done.
1640 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1641 dtmf_event.volume);
1642 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001643
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001644 if (dtmf_return_value == 0) {
1645 // Generate DTMF signal.
1646 dtmf_return_value = dtmf_tone_generator_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001647 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001648 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001649
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001650 if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001651 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001652 return dtmf_return_value;
1653 }
1654
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001655 // if (dtmf_switch) {
1656 // // This is the special case where the previous operation was DTMF
1657 // // overdub, but the current instruction is "regular" DTMF. We must make
1658 // // sure that the DTMF does not have any discontinuities. The first DTMF
1659 // // sample that we generate now must be played out immediately, therefore
1660 // // it must be copied to the speech buffer.
1661 // // TODO(hlundin): This code seems incorrect. (Legacy.) Write test and
1662 // // verify correct operation.
1663 // assert(false);
1664 // // Must generate enough data to replace all of the |sync_buffer_|
1665 // // "future".
1666 // int required_length = sync_buffer_->FutureLength();
1667 // assert(dtmf_tone_generator_->initialized());
1668 // dtmf_return_value = dtmf_tone_generator_->Generate(required_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001669 // algorithm_buffer_);
1670 // assert((size_t) required_length == algorithm_buffer_->Size());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001671 // if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001672 // algorithm_buffer_->Zeros(output_size_samples_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001673 // return dtmf_return_value;
1674 // }
1675 //
1676 // // Overwrite the "future" part of the speech buffer with the new DTMF
1677 // // data.
1678 // // TODO(hlundin): It seems that this overwriting has gone lost.
1679 // // Not adapted for multi-channel yet.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001680 // assert(algorithm_buffer_->Channels() == 1);
1681 // if (algorithm_buffer_->Channels() != 1) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001682 // LOG(LS_WARNING) << "DTMF not supported for more than one channel";
1683 // return kStereoNotSupported;
1684 // }
1685 // // Shuffle the remaining data to the beginning of algorithm buffer.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001686 // algorithm_buffer_->PopFront(sync_buffer_->FutureLength());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001687 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001688
1689 sync_buffer_->IncreaseEndTimestamp(output_size_samples_);
1690 expand_->Reset();
1691 last_mode_ = kModeDtmf;
1692
1693 // Set to false because the DTMF is already in the algorithm buffer.
1694 *play_dtmf = false;
1695 return 0;
1696}
1697
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001698void NetEqImpl::DoAlternativePlc(bool increase_timestamp) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001699 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1700 int length;
1701 if (decoder && decoder->HasDecodePlc()) {
1702 // Use the decoder's packet-loss concealment.
1703 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1704 int16_t decoded_buffer[kMaxFrameSize];
1705 length = decoder->DecodePlc(1, decoded_buffer);
1706 if (length > 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001707 algorithm_buffer_->PushBackInterleaved(decoded_buffer, length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001708 } else {
1709 length = 0;
1710 }
1711 } else {
1712 // Do simple zero-stuffing.
1713 length = output_size_samples_;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001714 algorithm_buffer_->Zeros(length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001715 // By not advancing the timestamp, NetEq inserts samples.
1716 stats_.AddZeros(length);
1717 }
1718 if (increase_timestamp) {
1719 sync_buffer_->IncreaseEndTimestamp(length);
1720 }
1721 expand_->Reset();
1722}
1723
1724int NetEqImpl::DtmfOverdub(const DtmfEvent& dtmf_event, size_t num_channels,
1725 int16_t* output) const {
1726 size_t out_index = 0;
1727 int overdub_length = output_size_samples_; // Default value.
1728
1729 if (sync_buffer_->dtmf_index() > sync_buffer_->next_index()) {
1730 // Special operation for transition from "DTMF only" to "DTMF overdub".
1731 out_index = std::min(
1732 sync_buffer_->dtmf_index() - sync_buffer_->next_index(),
1733 static_cast<size_t>(output_size_samples_));
turaj@webrtc.org362a55e2013-09-20 16:25:28 +00001734 overdub_length = output_size_samples_ - static_cast<int>(out_index);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001735 }
1736
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001737 AudioMultiVector dtmf_output(num_channels);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001738 int dtmf_return_value = 0;
1739 if (!dtmf_tone_generator_->initialized()) {
1740 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1741 dtmf_event.volume);
1742 }
1743 if (dtmf_return_value == 0) {
1744 dtmf_return_value = dtmf_tone_generator_->Generate(overdub_length,
1745 &dtmf_output);
1746 assert((size_t) overdub_length == dtmf_output.Size());
1747 }
1748 dtmf_output.ReadInterleaved(overdub_length, &output[out_index]);
1749 return dtmf_return_value < 0 ? dtmf_return_value : 0;
1750}
1751
1752int NetEqImpl::ExtractPackets(int required_samples, PacketList* packet_list) {
1753 bool first_packet = true;
1754 uint8_t prev_payload_type = 0;
1755 uint32_t prev_timestamp = 0;
1756 uint16_t prev_sequence_number = 0;
1757 bool next_packet_available = false;
1758
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001759 const RTPHeader* header = packet_buffer_->NextRtpHeader();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001760 assert(header);
1761 if (!header) {
1762 return -1;
1763 }
turaj@webrtc.org7df97062013-08-02 18:07:13 +00001764 uint32_t first_timestamp = header->timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001765 int extracted_samples = 0;
1766
1767 // Packet extraction loop.
1768 do {
1769 timestamp_ = header->timestamp;
1770 int discard_count = 0;
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001771 Packet* packet = packet_buffer_->GetNextPacket(&discard_count);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001772 // |header| may be invalid after the |packet_buffer_| operation.
1773 header = NULL;
1774 if (!packet) {
1775 LOG_FERR1(LS_ERROR, GetNextPacket, discard_count) <<
1776 "Should always be able to extract a packet here";
1777 assert(false); // Should always be able to extract a packet here.
1778 return -1;
1779 }
1780 stats_.PacketsDiscarded(discard_count);
1781 // Store waiting time in ms; packets->waiting_time is in "output blocks".
1782 stats_.StoreWaitingTime(packet->waiting_time * kOutputSizeMs);
1783 assert(packet->payload_length > 0);
1784 packet_list->push_back(packet); // Store packet in list.
1785
1786 if (first_packet) {
1787 first_packet = false;
minyue@webrtc.orgd7301772013-08-29 00:58:14 +00001788 decoded_packet_sequence_number_ = prev_sequence_number =
1789 packet->header.sequenceNumber;
1790 decoded_packet_timestamp_ = prev_timestamp = packet->header.timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001791 prev_payload_type = packet->header.payloadType;
1792 }
1793
1794 // Store number of extracted samples.
1795 int packet_duration = 0;
1796 AudioDecoder* decoder = decoder_database_->GetDecoder(
1797 packet->header.payloadType);
1798 if (decoder) {
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001799 if (packet->sync_packet) {
1800 packet_duration = decoder_frame_length_;
1801 } else {
minyue@webrtc.org2c1bcf22015-02-17 10:17:09 +00001802 if (packet->primary) {
1803 packet_duration = decoder->PacketDuration(packet->payload,
1804 packet->payload_length);
1805 } else {
1806 packet_duration = decoder->
1807 PacketDurationRedundant(packet->payload, packet->payload_length);
1808 stats_.SecondaryDecodedSamples(packet_duration);
1809 }
minyue@webrtc.orgb28bfa72014-03-21 12:07:40 +00001810 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001811 } else {
pkasting@chromium.org026b8922015-01-30 19:53:42 +00001812 LOG_FERR1(LS_WARNING, GetDecoder,
1813 static_cast<int>(packet->header.payloadType))
1814 << "Could not find a decoder for a packet about to be extracted.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001815 assert(false);
1816 }
1817 if (packet_duration <= 0) {
1818 // Decoder did not return a packet duration. Assume that the packet
1819 // contains the same number of samples as the previous one.
1820 packet_duration = decoder_frame_length_;
1821 }
1822 extracted_samples = packet->header.timestamp - first_timestamp +
1823 packet_duration;
1824
1825 // Check what packet is available next.
1826 header = packet_buffer_->NextRtpHeader();
1827 next_packet_available = false;
1828 if (header && prev_payload_type == header->payloadType) {
1829 int16_t seq_no_diff = header->sequenceNumber - prev_sequence_number;
1830 int32_t ts_diff = header->timestamp - prev_timestamp;
1831 if (seq_no_diff == 1 ||
1832 (seq_no_diff == 0 && ts_diff == decoder_frame_length_)) {
1833 // The next sequence number is available, or the next part of a packet
1834 // that was split into pieces upon insertion.
1835 next_packet_available = true;
1836 }
1837 prev_sequence_number = header->sequenceNumber;
1838 }
1839 } while (extracted_samples < required_samples && next_packet_available);
1840
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00001841 if (extracted_samples > 0) {
1842 // Delete old packets only when we are going to decode something. Otherwise,
1843 // we could end up in the situation where we never decode anything, since
1844 // all incoming packets are considered too old but the buffer will also
1845 // never be flooded and flushed.
henrik.lundin@webrtc.org52b42cb2014-11-04 14:03:58 +00001846 packet_buffer_->DiscardAllOldPackets(timestamp_);
henrik.lundin@webrtc.org61217152014-09-22 08:30:07 +00001847 }
1848
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001849 return extracted_samples;
1850}
1851
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001852void NetEqImpl::UpdatePlcComponents(int fs_hz, size_t channels) {
1853 // Delete objects and create new ones.
1854 expand_.reset(expand_factory_->Create(background_noise_.get(),
1855 sync_buffer_.get(), &random_vector_,
1856 fs_hz, channels));
1857 merge_.reset(new Merge(fs_hz, channels, expand_.get(), sync_buffer_.get()));
1858}
1859
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001860void NetEqImpl::SetSampleRateAndChannels(int fs_hz, size_t channels) {
1861 LOG_API2(fs_hz, channels);
1862 // TODO(hlundin): Change to an enumerator and skip assert.
1863 assert(fs_hz == 8000 || fs_hz == 16000 || fs_hz == 32000 || fs_hz == 48000);
1864 assert(channels > 0);
1865
1866 fs_hz_ = fs_hz;
1867 fs_mult_ = fs_hz / 8000;
1868 output_size_samples_ = kOutputSizeMs * 8 * fs_mult_;
1869 decoder_frame_length_ = 3 * output_size_samples_; // Initialize to 30ms.
1870
1871 last_mode_ = kModeNormal;
1872
1873 // Create a new array of mute factors and set all to 1.
1874 mute_factor_array_.reset(new int16_t[channels]);
1875 for (size_t i = 0; i < channels; ++i) {
1876 mute_factor_array_[i] = 16384; // 1.0 in Q14.
1877 }
1878
1879 // Reset comfort noise decoder, if there is one active.
1880 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
1881 if (cng_decoder) {
1882 cng_decoder->Init();
1883 }
1884
1885 // Reinit post-decode VAD with new sample rate.
1886 assert(vad_.get()); // Cannot be NULL here.
1887 vad_->Init();
1888
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001889 // Delete algorithm buffer and create a new one.
henrik.lundin@webrtc.orgfd11bbf2013-09-30 20:38:44 +00001890 algorithm_buffer_.reset(new AudioMultiVector(channels));
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001891
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001892 // Delete sync buffer and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001893 sync_buffer_.reset(new SyncBuffer(channels, kSyncBufferSize * fs_mult_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001894
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00001895 // Delete BackgroundNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001896 background_noise_.reset(new BackgroundNoise(channels));
henrik.lundin@webrtc.orgea257842014-08-07 12:27:37 +00001897 background_noise_->set_mode(background_noise_mode_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001898
1899 // Reset random vector.
1900 random_vector_.Reset();
1901
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001902 UpdatePlcComponents(fs_hz, channels);
1903
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001904 // Move index so that we create a small set of future samples (all 0).
1905 sync_buffer_->set_next_index(sync_buffer_->next_index() -
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001906 expand_->overlap_length());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001907
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001908 normal_.reset(new Normal(fs_hz, decoder_database_.get(), *background_noise_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001909 expand_.get()));
henrik.lundin@webrtc.orgd9faa462014-01-14 10:18:45 +00001910 accelerate_.reset(
1911 accelerate_factory_->Create(fs_hz, channels, *background_noise_));
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001912 preemptive_expand_.reset(preemptive_expand_factory_->Create(
1913 fs_hz, channels,
1914 *background_noise_,
1915 static_cast<int>(expand_->overlap_length())));
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001916
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001917 // Delete ComfortNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001918 comfort_noise_.reset(new ComfortNoise(fs_hz, decoder_database_.get(),
1919 sync_buffer_.get()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001920
1921 // Verify that |decoded_buffer_| is long enough.
1922 if (decoded_buffer_length_ < kMaxFrameSize * channels) {
1923 // Reallocate to larger size.
1924 decoded_buffer_length_ = kMaxFrameSize * channels;
1925 decoded_buffer_.reset(new int16_t[decoded_buffer_length_]);
1926 }
1927
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001928 // Create DecisionLogic if it is not created yet, then communicate new sample
1929 // rate and output size to DecisionLogic object.
1930 if (!decision_logic_.get()) {
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00001931 CreateDecisionLogic();
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001932 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001933 decision_logic_->SetSampleRate(fs_hz_, output_size_samples_);
1934}
1935
1936NetEqOutputType NetEqImpl::LastOutputType() {
1937 assert(vad_.get());
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001938 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001939 if (last_mode_ == kModeCodecInternalCng || last_mode_ == kModeRfc3389Cng) {
1940 return kOutputCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001941 } else if (last_mode_ == kModeExpand && expand_->MuteFactor(0) == 0) {
1942 // Expand mode has faded down to background noise only (very long expand).
1943 return kOutputPLCtoCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001944 } else if (last_mode_ == kModeExpand) {
1945 return kOutputPLC;
wu@webrtc.org24301a62013-12-13 19:17:43 +00001946 } else if (vad_->running() && !vad_->active_speech()) {
1947 return kOutputVADPassive;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001948 } else {
1949 return kOutputNormal;
1950 }
1951}
1952
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00001953void NetEqImpl::CreateDecisionLogic() {
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001954 decision_logic_.reset(DecisionLogic::Create(fs_hz_, output_size_samples_,
henrik.lundin@webrtc.org7cbc4f92014-10-07 06:37:39 +00001955 playout_mode_,
turaj@webrtc.org8d1cdaa2014-04-11 18:47:55 +00001956 decoder_database_.get(),
1957 *packet_buffer_.get(),
1958 delay_manager_.get(),
1959 buffer_level_filter_.get()));
1960}
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001961} // namespace webrtc