blob: be934ab95e6c791f7a3de8248efe41e78074e2c2 [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
11#include "webrtc/modules/audio_coding/neteq4/neteq_impl.h"
12
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"
19#include "webrtc/modules/audio_coding/neteq4/accelerate.h"
20#include "webrtc/modules/audio_coding/neteq4/background_noise.h"
21#include "webrtc/modules/audio_coding/neteq4/buffer_level_filter.h"
22#include "webrtc/modules/audio_coding/neteq4/comfort_noise.h"
23#include "webrtc/modules/audio_coding/neteq4/decision_logic.h"
24#include "webrtc/modules/audio_coding/neteq4/decoder_database.h"
25#include "webrtc/modules/audio_coding/neteq4/defines.h"
26#include "webrtc/modules/audio_coding/neteq4/delay_manager.h"
27#include "webrtc/modules/audio_coding/neteq4/delay_peak_detector.h"
28#include "webrtc/modules/audio_coding/neteq4/dtmf_buffer.h"
29#include "webrtc/modules/audio_coding/neteq4/dtmf_tone_generator.h"
30#include "webrtc/modules/audio_coding/neteq4/expand.h"
31#include "webrtc/modules/audio_coding/neteq4/interface/audio_decoder.h"
32#include "webrtc/modules/audio_coding/neteq4/merge.h"
33#include "webrtc/modules/audio_coding/neteq4/normal.h"
34#include "webrtc/modules/audio_coding/neteq4/packet_buffer.h"
35#include "webrtc/modules/audio_coding/neteq4/packet.h"
36#include "webrtc/modules/audio_coding/neteq4/payload_splitter.h"
37#include "webrtc/modules/audio_coding/neteq4/post_decode_vad.h"
38#include "webrtc/modules/audio_coding/neteq4/preemptive_expand.h"
39#include "webrtc/modules/audio_coding/neteq4/sync_buffer.h"
40#include "webrtc/modules/audio_coding/neteq4/timestamp_scaler.h"
41#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
52NetEqImpl::NetEqImpl(int fs,
53 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,
61 TimestampScaler* timestamp_scaler)
62 : background_noise_(NULL),
63 buffer_level_filter_(buffer_level_filter),
64 decoder_database_(decoder_database),
65 delay_manager_(delay_manager),
66 delay_peak_detector_(delay_peak_detector),
67 dtmf_buffer_(dtmf_buffer),
68 dtmf_tone_generator_(dtmf_tone_generator),
69 packet_buffer_(packet_buffer),
70 payload_splitter_(payload_splitter),
71 timestamp_scaler_(timestamp_scaler),
72 vad_(new PostDecodeVad()),
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +000073 algorithm_buffer_(NULL),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000074 sync_buffer_(NULL),
75 expand_(NULL),
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +000076 normal_(NULL),
77 merge_(NULL),
78 accelerate_(NULL),
79 preemptive_expand_(NULL),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000080 comfort_noise_(NULL),
81 last_mode_(kModeNormal),
82 mute_factor_array_(NULL),
83 decoded_buffer_length_(kMaxFrameSize),
84 decoded_buffer_(new int16_t[decoded_buffer_length_]),
85 playout_timestamp_(0),
86 new_codec_(false),
87 timestamp_(0),
88 reset_decoder_(false),
89 current_rtp_payload_type_(0xFF), // Invalid RTP payload type.
90 current_cng_rtp_payload_type_(0xFF), // Invalid RTP payload type.
91 ssrc_(0),
92 first_packet_(true),
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +000093 error_code_(0),
94 decoder_error_code_(0),
minyue@webrtc.orgd7301772013-08-29 00:58:14 +000095 crit_sect_(CriticalSectionWrapper::CreateCriticalSection()),
96 decoded_packet_sequence_number_(-1),
97 decoded_packet_timestamp_(0) {
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 }
103 LOG(LS_INFO) << "Create NetEqImpl object with fs = " << fs << ".";
104 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();
109 decision_logic_.reset(DecisionLogic::Create(fs_hz_, output_size_samples_,
110 kPlayoutOn,
111 decoder_database_.get(),
112 *packet_buffer_.get(),
113 delay_manager_.get(),
114 buffer_level_filter_.get()));
115 SetSampleRateAndChannels(fs, 1); // Default is 1 channel.
116}
117
118NetEqImpl::~NetEqImpl() {
119 LOG(LS_INFO) << "Deleting NetEqImpl object.";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000120}
121
122int NetEqImpl::InsertPacket(const WebRtcRTPHeader& rtp_header,
123 const uint8_t* payload,
124 int length_bytes,
125 uint32_t receive_timestamp) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000126 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgb3e905c2013-09-02 09:41:06 +0000127 NETEQ_LOG_VERBOSE << "InsertPacket: ts=" << rtp_header.header.timestamp <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000128 ", sn=" << rtp_header.header.sequenceNumber <<
129 ", pt=" << static_cast<int>(rtp_header.header.payloadType) <<
130 ", ssrc=" << rtp_header.header.ssrc <<
131 ", len=" << length_bytes;
132 int error = InsertPacketInternal(rtp_header, payload, length_bytes,
133 receive_timestamp);
134 if (error != 0) {
135 LOG_FERR1(LS_WARNING, InsertPacketInternal, error);
136 error_code_ = error;
137 return kFail;
138 }
139 return kOK;
140}
141
142int NetEqImpl::GetAudio(size_t max_length, int16_t* output_audio,
143 int* samples_per_channel, int* num_channels,
144 NetEqOutputType* type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000145 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgb3e905c2013-09-02 09:41:06 +0000146 NETEQ_LOG_VERBOSE << "GetAudio";
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000147 int error = GetAudioInternal(max_length, output_audio, samples_per_channel,
148 num_channels);
henrik.lundin@webrtc.orgb3e905c2013-09-02 09:41:06 +0000149 NETEQ_LOG_VERBOSE << "Produced " << *samples_per_channel <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000150 " samples/channel for " << *num_channels << " channel(s)";
151 if (error != 0) {
152 LOG_FERR1(LS_WARNING, GetAudioInternal, error);
153 error_code_ = error;
154 return kFail;
155 }
156 if (type) {
157 *type = LastOutputType();
158 }
159 return kOK;
160}
161
162int NetEqImpl::RegisterPayloadType(enum NetEqDecoder codec,
163 uint8_t rtp_payload_type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000164 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000165 LOG_API2(static_cast<int>(rtp_payload_type), codec);
166 int ret = decoder_database_->RegisterPayload(rtp_payload_type, codec);
167 if (ret != DecoderDatabase::kOK) {
168 LOG_FERR2(LS_WARNING, RegisterPayload, rtp_payload_type, codec);
169 switch (ret) {
170 case DecoderDatabase::kInvalidRtpPayloadType:
171 error_code_ = kInvalidRtpPayloadType;
172 break;
173 case DecoderDatabase::kCodecNotSupported:
174 error_code_ = kCodecNotSupported;
175 break;
176 case DecoderDatabase::kDecoderExists:
177 error_code_ = kDecoderExists;
178 break;
179 default:
180 error_code_ = kOtherError;
181 }
182 return kFail;
183 }
184 return kOK;
185}
186
187int NetEqImpl::RegisterExternalDecoder(AudioDecoder* decoder,
188 enum NetEqDecoder codec,
189 int sample_rate_hz,
190 uint8_t rtp_payload_type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000191 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000192 LOG_API2(static_cast<int>(rtp_payload_type), codec);
193 if (!decoder) {
194 LOG(LS_ERROR) << "Cannot register external decoder with NULL pointer";
195 assert(false);
196 return kFail;
197 }
198 int ret = decoder_database_->InsertExternal(rtp_payload_type, codec,
199 sample_rate_hz, decoder);
200 if (ret != DecoderDatabase::kOK) {
201 LOG_FERR2(LS_WARNING, InsertExternal, rtp_payload_type, codec);
202 switch (ret) {
203 case DecoderDatabase::kInvalidRtpPayloadType:
204 error_code_ = kInvalidRtpPayloadType;
205 break;
206 case DecoderDatabase::kCodecNotSupported:
207 error_code_ = kCodecNotSupported;
208 break;
209 case DecoderDatabase::kDecoderExists:
210 error_code_ = kDecoderExists;
211 break;
212 case DecoderDatabase::kInvalidSampleRate:
213 error_code_ = kInvalidSampleRate;
214 break;
215 case DecoderDatabase::kInvalidPointer:
216 error_code_ = kInvalidPointer;
217 break;
218 default:
219 error_code_ = kOtherError;
220 }
221 return kFail;
222 }
223 return kOK;
224}
225
226int NetEqImpl::RemovePayloadType(uint8_t rtp_payload_type) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000227 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000228 LOG_API1(static_cast<int>(rtp_payload_type));
229 int ret = decoder_database_->Remove(rtp_payload_type);
230 if (ret == DecoderDatabase::kOK) {
231 return kOK;
232 } else if (ret == DecoderDatabase::kDecoderNotFound) {
233 error_code_ = kDecoderNotFound;
234 } else {
235 error_code_ = kOtherError;
236 }
237 LOG_FERR1(LS_WARNING, Remove, rtp_payload_type);
238 return kFail;
239}
240
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000241bool NetEqImpl::SetMinimumDelay(int delay_ms) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000242 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000243 if (delay_ms >= 0 && delay_ms < 10000) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000244 assert(delay_manager_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000245 return delay_manager_->SetMinimumDelay(delay_ms);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000246 }
247 return false;
248}
249
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000250bool NetEqImpl::SetMaximumDelay(int delay_ms) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000251 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000252 if (delay_ms >= 0 && delay_ms < 10000) {
253 assert(delay_manager_.get());
254 return delay_manager_->SetMaximumDelay(delay_ms);
255 }
256 return false;
257}
258
259int NetEqImpl::LeastRequiredDelayMs() const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000260 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.orgf1efc572013-08-16 23:44:24 +0000261 assert(delay_manager_.get());
262 return delay_manager_->least_required_delay_ms();
263}
264
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000265void NetEqImpl::SetPlayoutMode(NetEqPlayoutMode mode) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000266 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000267 if (!decision_logic_.get() || mode != decision_logic_->playout_mode()) {
268 // The reset() method calls delete for the old object.
269 decision_logic_.reset(DecisionLogic::Create(fs_hz_, output_size_samples_,
270 mode,
271 decoder_database_.get(),
272 *packet_buffer_.get(),
273 delay_manager_.get(),
274 buffer_level_filter_.get()));
275 }
276}
277
278NetEqPlayoutMode NetEqImpl::PlayoutMode() const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000279 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000280 assert(decision_logic_.get());
281 return decision_logic_->playout_mode();
282}
283
284int NetEqImpl::NetworkStatistics(NetEqNetworkStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000285 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000286 assert(decoder_database_.get());
287 const int total_samples_in_buffers = packet_buffer_->NumSamplesInBuffer(
288 decoder_database_.get(), decoder_frame_length_) +
289 sync_buffer_->FutureLength();
290 assert(delay_manager_.get());
291 assert(decision_logic_.get());
292 stats_.GetNetworkStatistics(fs_hz_, total_samples_in_buffers,
293 decoder_frame_length_, *delay_manager_.get(),
294 *decision_logic_.get(), stats);
295 return 0;
296}
297
298void NetEqImpl::WaitingTimes(std::vector<int>* waiting_times) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000299 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000300 stats_.WaitingTimes(waiting_times);
301}
302
303void NetEqImpl::GetRtcpStatistics(RtcpStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000304 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000305 if (stats) {
306 rtcp_.GetStatistics(false, stats);
307 }
308}
309
310void NetEqImpl::GetRtcpStatisticsNoReset(RtcpStatistics* stats) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000311 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000312 if (stats) {
313 rtcp_.GetStatistics(true, stats);
314 }
315}
316
317void NetEqImpl::EnableVad() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000318 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000319 assert(vad_.get());
320 vad_->Enable();
321}
322
323void NetEqImpl::DisableVad() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000324 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000325 assert(vad_.get());
326 vad_->Disable();
327}
328
329uint32_t NetEqImpl::PlayoutTimestamp() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000330 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000331 return timestamp_scaler_->ToExternal(playout_timestamp_);
332}
333
334int NetEqImpl::LastError() {
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 return error_code_;
337}
338
339int NetEqImpl::LastDecoderError() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000340 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000341 return decoder_error_code_;
342}
343
344void NetEqImpl::FlushBuffers() {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000345 CriticalSectionScoped lock(crit_sect_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000346 LOG_API0();
347 packet_buffer_->Flush();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000348 assert(sync_buffer_.get());
349 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000350 sync_buffer_->Flush();
351 sync_buffer_->set_next_index(sync_buffer_->next_index() -
352 expand_->overlap_length());
353 // Set to wait for new codec.
354 first_packet_ = true;
355}
356
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000357void NetEqImpl::PacketBufferStatistics(int* current_num_packets,
358 int* max_num_packets,
359 int* current_memory_size_bytes,
360 int* max_memory_size_bytes) const {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000361 CriticalSectionScoped lock(crit_sect_.get());
turaj@webrtc.org3170b572013-08-30 15:36:53 +0000362 packet_buffer_->BufferStat(current_num_packets, max_num_packets,
363 current_memory_size_bytes, max_memory_size_bytes);
364}
365
minyue@webrtc.orgd7301772013-08-29 00:58:14 +0000366int NetEqImpl::DecodedRtpInfo(int* sequence_number, uint32_t* timestamp) {
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000367 CriticalSectionScoped lock(crit_sect_.get());
minyue@webrtc.orgd7301772013-08-29 00:58:14 +0000368 if (decoded_packet_sequence_number_ < 0)
369 return -1;
370 *sequence_number = decoded_packet_sequence_number_;
371 *timestamp = decoded_packet_timestamp_;
372 return 0;
373}
374
turaj@webrtc.org036b7432013-09-11 18:45:02 +0000375int NetEqImpl::InsertSyncPacket(const WebRtcRTPHeader& /* rtp_header */,
376 uint32_t /* receive_timestamp */) {
377 return kNotImplemented;
378}
379
380void NetEqImpl::SetBackgroundNoiseMode(NetEqBackgroundNoiseMode /* mode */) {}
381
382NetEqBackgroundNoiseMode NetEqImpl::BackgroundNoiseMode() const {
383 return kBgnOn;
384}
385
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000386// Methods below this line are private.
387
388
389int NetEqImpl::InsertPacketInternal(const WebRtcRTPHeader& rtp_header,
390 const uint8_t* payload,
391 int length_bytes,
392 uint32_t receive_timestamp) {
393 if (!payload) {
394 LOG_F(LS_ERROR) << "payload == NULL";
395 return kInvalidPointer;
396 }
397 PacketList packet_list;
398 RTPHeader main_header;
399 {
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000400 // Convert to Packet.
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000401 // Create |packet| within this separate scope, since it should not be used
402 // directly once it's been inserted in the packet list. This way, |packet|
403 // is not defined outside of this block.
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +0000404 Packet* packet = new Packet;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000405 packet->header.markerBit = false;
406 packet->header.payloadType = rtp_header.header.payloadType;
407 packet->header.sequenceNumber = rtp_header.header.sequenceNumber;
408 packet->header.timestamp = rtp_header.header.timestamp;
409 packet->header.ssrc = rtp_header.header.ssrc;
410 packet->header.numCSRCs = 0;
411 packet->payload_length = length_bytes;
412 packet->primary = true;
413 packet->waiting_time = 0;
414 packet->payload = new uint8_t[packet->payload_length];
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +0000415 if (!packet->payload) {
416 LOG_F(LS_ERROR) << "Payload pointer is NULL.";
417 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000418 assert(payload); // Already checked above.
419 memcpy(packet->payload, payload, packet->payload_length);
420 // Insert packet in a packet list.
421 packet_list.push_back(packet);
422 // Save main payloads header for later.
423 memcpy(&main_header, &packet->header, sizeof(main_header));
424 }
425
426 // Reinitialize NetEq if it's needed (changed SSRC or first call).
427 if ((main_header.ssrc != ssrc_) || first_packet_) {
428 rtcp_.Init(main_header.sequenceNumber);
429 first_packet_ = false;
430
431 // Flush the packet buffer and DTMF buffer.
432 packet_buffer_->Flush();
433 dtmf_buffer_->Flush();
434
435 // Store new SSRC.
436 ssrc_ = main_header.ssrc;
437
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000438 // Update audio buffer timestamp.
439 sync_buffer_->IncreaseEndTimestamp(main_header.timestamp - timestamp_);
440
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000441 // Update codecs.
442 timestamp_ = main_header.timestamp;
443 current_rtp_payload_type_ = main_header.payloadType;
444
445 // Set MCU to update codec on next SignalMCU call.
446 new_codec_ = true;
447
448 // Reset timestamp scaling.
449 timestamp_scaler_->Reset();
450 }
451
452 // Update RTCP statistics.
453 rtcp_.Update(main_header, receive_timestamp);
454
455 // Check for RED payload type, and separate payloads into several packets.
456 if (decoder_database_->IsRed(main_header.payloadType)) {
457 if (payload_splitter_->SplitRed(&packet_list) != PayloadSplitter::kOK) {
458 LOG_FERR1(LS_WARNING, SplitRed, packet_list.size());
459 PacketBuffer::DeleteAllPackets(&packet_list);
460 return kRedundancySplitError;
461 }
462 // Only accept a few RED payloads of the same type as the main data,
463 // DTMF events and CNG.
464 payload_splitter_->CheckRedPayloads(&packet_list, *decoder_database_);
465 // Update the stored main payload header since the main payload has now
466 // changed.
467 memcpy(&main_header, &packet_list.front()->header, sizeof(main_header));
468 }
469
470 // Check payload types.
471 if (decoder_database_->CheckPayloadTypes(packet_list) ==
472 DecoderDatabase::kDecoderNotFound) {
473 LOG_FERR1(LS_WARNING, CheckPayloadTypes, packet_list.size());
474 PacketBuffer::DeleteAllPackets(&packet_list);
475 return kUnknownRtpPayloadType;
476 }
477
478 // Scale timestamp to internal domain (only for some codecs).
479 timestamp_scaler_->ToInternal(&packet_list);
480
481 // Process DTMF payloads. Cycle through the list of packets, and pick out any
482 // DTMF payloads found.
483 PacketList::iterator it = packet_list.begin();
484 while (it != packet_list.end()) {
485 Packet* current_packet = (*it);
486 assert(current_packet);
487 assert(current_packet->payload);
488 if (decoder_database_->IsDtmf(current_packet->header.payloadType)) {
minyue@webrtc.org9721db72013-08-06 05:36:26 +0000489 DtmfEvent event;
490 int ret = DtmfBuffer::ParseEvent(
491 current_packet->header.timestamp,
492 current_packet->payload,
493 current_packet->payload_length,
494 &event);
495 if (ret != DtmfBuffer::kOK) {
496 LOG_FERR2(LS_WARNING, ParseEvent, ret,
497 current_packet->payload_length);
498 PacketBuffer::DeleteAllPackets(&packet_list);
499 return kDtmfParsingError;
500 }
501 if (dtmf_buffer_->InsertEvent(event) != DtmfBuffer::kOK) {
502 LOG_FERR0(LS_WARNING, InsertEvent);
503 PacketBuffer::DeleteAllPackets(&packet_list);
504 return kDtmfInsertError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000505 }
506 // TODO(hlundin): Let the destructor of Packet handle the payload.
507 delete [] current_packet->payload;
508 delete current_packet;
509 it = packet_list.erase(it);
510 } else {
511 ++it;
512 }
513 }
514
515 // Split payloads into smaller chunks. This also verifies that all payloads
516 // are of a known payload type.
517 int ret = payload_splitter_->SplitAudio(&packet_list, *decoder_database_);
518 if (ret != PayloadSplitter::kOK) {
519 LOG_FERR1(LS_WARNING, SplitAudio, packet_list.size());
520 PacketBuffer::DeleteAllPackets(&packet_list);
521 switch (ret) {
522 case PayloadSplitter::kUnknownPayloadType:
523 return kUnknownRtpPayloadType;
524 case PayloadSplitter::kFrameSplitError:
525 return kFrameSplitError;
526 default:
527 return kOtherError;
528 }
529 }
530
531 // Update bandwidth estimate.
532 if (!packet_list.empty()) {
533 // The list can be empty here if we got nothing but DTMF payloads.
534 AudioDecoder* decoder =
535 decoder_database_->GetDecoder(main_header.payloadType);
536 assert(decoder); // Should always get a valid object, since we have
537 // already checked that the payload types are known.
538 decoder->IncomingPacket(packet_list.front()->payload,
539 packet_list.front()->payload_length,
540 packet_list.front()->header.sequenceNumber,
541 packet_list.front()->header.timestamp,
542 receive_timestamp);
543 }
544
545 // Insert packets in buffer.
546 int temp_bufsize = packet_buffer_->NumPacketsInBuffer();
547 ret = packet_buffer_->InsertPacketList(
548 &packet_list,
549 *decoder_database_,
550 &current_rtp_payload_type_,
551 &current_cng_rtp_payload_type_);
552 if (ret == PacketBuffer::kFlushed) {
553 // Reset DSP timestamp etc. if packet buffer flushed.
554 new_codec_ = true;
555 LOG_F(LS_WARNING) << "Packet buffer flushed";
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000556 } else if (ret == PacketBuffer::kOversizePacket) {
557 LOG_F(LS_WARNING) << "Packet larger than packet buffer";
558 return kOversizePacket;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000559 } else if (ret != PacketBuffer::kOK) {
560 LOG_FERR1(LS_WARNING, InsertPacketList, packet_list.size());
561 PacketBuffer::DeleteAllPackets(&packet_list);
minyue@webrtc.org7bb54362013-08-06 05:40:57 +0000562 return kOtherError;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000563 }
564 if (current_rtp_payload_type_ != 0xFF) {
565 const DecoderDatabase::DecoderInfo* dec_info =
566 decoder_database_->GetDecoderInfo(current_rtp_payload_type_);
567 if (!dec_info) {
568 assert(false); // Already checked that the payload type is known.
569 }
570 }
571
572 // TODO(hlundin): Move this code to DelayManager class.
573 const DecoderDatabase::DecoderInfo* dec_info =
574 decoder_database_->GetDecoderInfo(main_header.payloadType);
575 assert(dec_info); // Already checked that the payload type is known.
576 delay_manager_->LastDecoderType(dec_info->codec_type);
577 if (delay_manager_->last_pack_cng_or_dtmf() == 0) {
578 // Calculate the total speech length carried in each packet.
579 temp_bufsize = packet_buffer_->NumPacketsInBuffer() - temp_bufsize;
580 temp_bufsize *= decoder_frame_length_;
581
582 if ((temp_bufsize > 0) &&
583 (temp_bufsize != decision_logic_->packet_length_samples())) {
584 decision_logic_->set_packet_length_samples(temp_bufsize);
585 delay_manager_->SetPacketAudioLength((1000 * temp_bufsize) / fs_hz_);
586 }
587
588 // Update statistics.
pbos@webrtc.org0946a562013-04-09 00:28:06 +0000589 if ((int32_t) (main_header.timestamp - timestamp_) >= 0 &&
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000590 !new_codec_) {
591 // Only update statistics if incoming packet is not older than last played
592 // out packet, and if new codec flag is not set.
593 delay_manager_->Update(main_header.sequenceNumber, main_header.timestamp,
594 fs_hz_);
595 }
596 } else if (delay_manager_->last_pack_cng_or_dtmf() == -1) {
597 // This is first "normal" packet after CNG or DTMF.
598 // Reset packet time counter and measure time until next packet,
599 // but don't update statistics.
600 delay_manager_->set_last_pack_cng_or_dtmf(0);
601 delay_manager_->ResetPacketIatCount();
602 }
603 return 0;
604}
605
606int NetEqImpl::GetAudioInternal(size_t max_length, int16_t* output,
607 int* samples_per_channel, int* num_channels) {
608 PacketList packet_list;
609 DtmfEvent dtmf_event;
610 Operations operation;
611 bool play_dtmf;
612 int return_value = GetDecision(&operation, &packet_list, &dtmf_event,
613 &play_dtmf);
614 if (return_value != 0) {
615 LOG_FERR1(LS_WARNING, GetDecision, return_value);
616 assert(false);
617 last_mode_ = kModeError;
618 return return_value;
619 }
henrik.lundin@webrtc.orgb3e905c2013-09-02 09:41:06 +0000620 NETEQ_LOG_VERBOSE << "GetDecision returned operation=" << operation <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000621 " and " << packet_list.size() << " packet(s)";
622
623 AudioDecoder::SpeechType speech_type;
624 int length = 0;
625 int decode_return_value = Decode(&packet_list, &operation,
626 &length, &speech_type);
627
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000628 assert(vad_.get());
629 bool sid_frame_available =
630 (operation == kRfc3389Cng && !packet_list.empty());
631 vad_->Update(decoded_buffer_.get(), length, speech_type,
632 sid_frame_available, fs_hz_);
633
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000634 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000635 switch (operation) {
636 case kNormal: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000637 DoNormal(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000638 break;
639 }
640 case kMerge: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000641 DoMerge(decoded_buffer_.get(), length, speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000642 break;
643 }
644 case kExpand: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000645 return_value = DoExpand(play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000646 break;
647 }
648 case kAccelerate: {
649 return_value = DoAccelerate(decoded_buffer_.get(), length, speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000650 play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000651 break;
652 }
653 case kPreemptiveExpand: {
654 return_value = DoPreemptiveExpand(decoded_buffer_.get(), length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000655 speech_type, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000656 break;
657 }
658 case kRfc3389Cng:
659 case kRfc3389CngNoPacket: {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000660 return_value = DoRfc3389Cng(&packet_list, play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000661 break;
662 }
663 case kCodecInternalCng: {
664 // This handles the case when there is no transmission and the decoder
665 // should produce internal comfort noise.
666 // TODO(hlundin): Write test for codec-internal CNG.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000667 DoCodecInternalCng();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000668 break;
669 }
670 case kDtmf: {
671 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000672 return_value = DoDtmf(dtmf_event, &play_dtmf);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000673 break;
674 }
675 case kAlternativePlc: {
676 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000677 DoAlternativePlc(false);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000678 break;
679 }
680 case kAlternativePlcIncreaseTimestamp: {
681 // TODO(hlundin): Write test for this.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000682 DoAlternativePlc(true);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000683 break;
684 }
685 case kAudioRepetitionIncreaseTimestamp: {
686 // TODO(hlundin): Write test for this.
687 sync_buffer_->IncreaseEndTimestamp(output_size_samples_);
688 // Skipping break on purpose. Execution should move on into the
689 // next case.
690 }
691 case kAudioRepetition: {
692 // TODO(hlundin): Write test for this.
693 // Copy last |output_size_samples_| from |sync_buffer_| to
694 // |algorithm_buffer|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000695 algorithm_buffer_->PushBackFromIndex(
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000696 *sync_buffer_, sync_buffer_->Size() - output_size_samples_);
697 expand_->Reset();
698 break;
699 }
700 case kUndefined: {
701 LOG_F(LS_ERROR) << "Invalid operation kUndefined.";
702 assert(false); // This should not happen.
703 last_mode_ = kModeError;
704 return kInvalidOperation;
705 }
706 } // End of switch.
707 if (return_value < 0) {
708 return return_value;
709 }
710
711 if (last_mode_ != kModeRfc3389Cng) {
712 comfort_noise_->Reset();
713 }
714
715 // Copy from |algorithm_buffer| to |sync_buffer_|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000716 sync_buffer_->PushBack(*algorithm_buffer_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000717
718 // Extract data from |sync_buffer_| to |output|.
719 int num_output_samples_per_channel = output_size_samples_;
720 int num_output_samples = output_size_samples_ * sync_buffer_->Channels();
721 if (num_output_samples > static_cast<int>(max_length)) {
722 LOG(LS_WARNING) << "Output array is too short. " << max_length << " < " <<
723 output_size_samples_ << " * " << sync_buffer_->Channels();
724 num_output_samples = max_length;
725 num_output_samples_per_channel = max_length / sync_buffer_->Channels();
726 }
727 int samples_from_sync = sync_buffer_->GetNextAudioInterleaved(
728 num_output_samples_per_channel, output);
729 *num_channels = sync_buffer_->Channels();
henrik.lundin@webrtc.orgb3e905c2013-09-02 09:41:06 +0000730 NETEQ_LOG_VERBOSE << "Sync buffer (" << *num_channels << " channel(s)):" <<
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +0000731 " insert " << algorithm_buffer_->Size() << " samples, extract " <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000732 samples_from_sync << " samples";
733 if (samples_from_sync != output_size_samples_) {
734 LOG_F(LS_ERROR) << "samples_from_sync != output_size_samples_";
minyue@webrtc.orgdb1cefc2013-08-13 01:39:21 +0000735 // TODO(minyue): treatment of under-run, filling zeros
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000736 memset(output, 0, num_output_samples * sizeof(int16_t));
737 *samples_per_channel = output_size_samples_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000738 return kSampleUnderrun;
739 }
740 *samples_per_channel = output_size_samples_;
741
742 // Should always have overlap samples left in the |sync_buffer_|.
743 assert(sync_buffer_->FutureLength() >= expand_->overlap_length());
744
745 if (play_dtmf) {
746 return_value = DtmfOverdub(dtmf_event, sync_buffer_->Channels(), output);
747 }
748
749 // Update the background noise parameters if last operation wrote data
750 // straight from the decoder to the |sync_buffer_|. That is, none of the
751 // operations that modify the signal can be followed by a parameter update.
752 if ((last_mode_ == kModeNormal) ||
753 (last_mode_ == kModeAccelerateFail) ||
754 (last_mode_ == kModePreemptiveExpandFail) ||
755 (last_mode_ == kModeRfc3389Cng) ||
756 (last_mode_ == kModeCodecInternalCng)) {
757 background_noise_->Update(*sync_buffer_, *vad_.get());
758 }
759
760 if (operation == kDtmf) {
761 // DTMF data was written the end of |sync_buffer_|.
762 // Update index to end of DTMF data in |sync_buffer_|.
763 sync_buffer_->set_dtmf_index(sync_buffer_->Size());
764 }
765
766 if ((last_mode_ != kModeExpand) && (last_mode_ != kModeRfc3389Cng)) {
767 // If last operation was neither expand, nor comfort noise, calculate the
768 // |playout_timestamp_| from the |sync_buffer_|. However, do not update the
769 // |playout_timestamp_| if it would be moved "backwards".
770 uint32_t temp_timestamp = sync_buffer_->end_timestamp() -
771 sync_buffer_->FutureLength();
772 if (static_cast<int32_t>(temp_timestamp - playout_timestamp_) > 0) {
773 playout_timestamp_ = temp_timestamp;
774 }
775 } else {
776 // Use dead reckoning to estimate the |playout_timestamp_|.
777 playout_timestamp_ += output_size_samples_;
778 }
779
780 if (decode_return_value) return decode_return_value;
781 return return_value;
782}
783
784int NetEqImpl::GetDecision(Operations* operation,
785 PacketList* packet_list,
786 DtmfEvent* dtmf_event,
787 bool* play_dtmf) {
788 // Initialize output variables.
789 *play_dtmf = false;
790 *operation = kUndefined;
791
792 // Increment time counters.
793 packet_buffer_->IncrementWaitingTimes();
794 stats_.IncreaseCounter(output_size_samples_, fs_hz_);
795
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000796 assert(sync_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000797 uint32_t end_timestamp = sync_buffer_->end_timestamp();
798 if (!new_codec_) {
799 packet_buffer_->DiscardOldPackets(end_timestamp);
800 }
801 const RTPHeader* header = packet_buffer_->NextRtpHeader();
802
803 if (decision_logic_->CngRfc3389On()) {
804 // Because of timestamp peculiarities, we have to "manually" disallow using
805 // a CNG packet with the same timestamp as the one that was last played.
806 // This can happen when using redundancy and will cause the timing to shift.
807 while (header &&
808 decoder_database_->IsComfortNoise(header->payloadType) &&
809 end_timestamp >= header->timestamp) {
810 // Don't use this packet, discard it.
811 // TODO(hlundin): Write test for this case.
812 if (packet_buffer_->DiscardNextPacket() != PacketBuffer::kOK) {
813 assert(false); // Must be ok by design.
814 }
815 // Check buffer again.
816 if (!new_codec_) {
817 packet_buffer_->DiscardOldPackets(end_timestamp);
818 }
819 header = packet_buffer_->NextRtpHeader();
820 }
821 }
822
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000823 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000824 const int samples_left = sync_buffer_->FutureLength() -
825 expand_->overlap_length();
826 if (last_mode_ == kModeAccelerateSuccess ||
827 last_mode_ == kModeAccelerateLowEnergy ||
828 last_mode_ == kModePreemptiveExpandSuccess ||
829 last_mode_ == kModePreemptiveExpandLowEnergy) {
830 // Subtract (samples_left + output_size_samples_) from sampleMemory.
831 decision_logic_->AddSampleMemory(-(samples_left + output_size_samples_));
832 }
833
834 // Check if it is time to play a DTMF event.
835 if (dtmf_buffer_->GetEvent(end_timestamp +
836 decision_logic_->generated_noise_samples(),
837 dtmf_event)) {
838 *play_dtmf = true;
839 }
840
841 // Get instruction.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +0000842 assert(sync_buffer_.get());
843 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000844 *operation = decision_logic_->GetDecision(*sync_buffer_,
845 *expand_,
846 decoder_frame_length_,
847 header,
848 last_mode_,
849 *play_dtmf,
850 &reset_decoder_);
851
852 // Check if we already have enough samples in the |sync_buffer_|. If so,
853 // change decision to normal, unless the decision was merge, accelerate, or
854 // preemptive expand.
855 if (samples_left >= output_size_samples_ &&
856 *operation != kMerge &&
857 *operation != kAccelerate &&
858 *operation != kPreemptiveExpand) {
859 *operation = kNormal;
860 return 0;
861 }
862
863 decision_logic_->ExpandDecision(*operation == kExpand);
864
865 // Check conditions for reset.
866 if (new_codec_ || *operation == kUndefined) {
867 // The only valid reason to get kUndefined is that new_codec_ is set.
868 assert(new_codec_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000869 if (*play_dtmf && !header) {
870 timestamp_ = dtmf_event->timestamp;
871 } else {
872 assert(header);
873 if (!header) {
874 LOG_F(LS_ERROR) << "Packet missing where it shouldn't.";
875 return -1;
876 }
877 timestamp_ = header->timestamp;
878 if (*operation == kRfc3389CngNoPacket
879#ifndef LEGACY_BITEXACT
880 // Without this check, it can happen that a non-CNG packet is sent to
881 // the CNG decoder as if it was a SID frame. This is clearly a bug,
882 // but is kept for now to maintain bit-exactness with the test
883 // vectors.
884 && decoder_database_->IsComfortNoise(header->payloadType)
885#endif
886 ) {
887 // Change decision to CNG packet, since we do have a CNG packet, but it
888 // was considered too early to use. Now, use it anyway.
889 *operation = kRfc3389Cng;
890 } else if (*operation != kRfc3389Cng) {
891 *operation = kNormal;
892 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000893 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000894 // Adjust |sync_buffer_| timestamp before setting |end_timestamp| to the
895 // new value.
896 sync_buffer_->IncreaseEndTimestamp(timestamp_ - end_timestamp);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +0000897 end_timestamp = timestamp_;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000898 new_codec_ = false;
899 decision_logic_->SoftReset();
900 buffer_level_filter_->Reset();
901 delay_manager_->Reset();
902 stats_.ResetMcu();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +0000903 }
904
905 int required_samples = output_size_samples_;
906 const int samples_10_ms = 80 * fs_mult_;
907 const int samples_20_ms = 2 * samples_10_ms;
908 const int samples_30_ms = 3 * samples_10_ms;
909
910 switch (*operation) {
911 case kExpand: {
912 timestamp_ = end_timestamp;
913 return 0;
914 }
915 case kRfc3389CngNoPacket:
916 case kCodecInternalCng: {
917 return 0;
918 }
919 case kDtmf: {
920 // TODO(hlundin): Write test for this.
921 // Update timestamp.
922 timestamp_ = end_timestamp;
923 if (decision_logic_->generated_noise_samples() > 0 &&
924 last_mode_ != kModeDtmf) {
925 // Make a jump in timestamp due to the recently played comfort noise.
926 uint32_t timestamp_jump = decision_logic_->generated_noise_samples();
927 sync_buffer_->IncreaseEndTimestamp(timestamp_jump);
928 timestamp_ += timestamp_jump;
929 }
930 decision_logic_->set_generated_noise_samples(0);
931 return 0;
932 }
933 case kAccelerate: {
934 // In order to do a accelerate we need at least 30 ms of audio data.
935 if (samples_left >= samples_30_ms) {
936 // Already have enough data, so we do not need to extract any more.
937 decision_logic_->set_sample_memory(samples_left);
938 decision_logic_->set_prev_time_scale(true);
939 return 0;
940 } else if (samples_left >= samples_10_ms &&
941 decoder_frame_length_ >= samples_30_ms) {
942 // Avoid decoding more data as it might overflow the playout buffer.
943 *operation = kNormal;
944 return 0;
945 } else if (samples_left < samples_20_ms &&
946 decoder_frame_length_ < samples_30_ms) {
947 // Build up decoded data by decoding at least 20 ms of audio data. Do
948 // not perform accelerate yet, but wait until we only need to do one
949 // decoding.
950 required_samples = 2 * output_size_samples_;
951 *operation = kNormal;
952 }
953 // If none of the above is true, we have one of two possible situations:
954 // (1) 20 ms <= samples_left < 30 ms and decoder_frame_length_ < 30 ms; or
955 // (2) samples_left < 10 ms and decoder_frame_length_ >= 30 ms.
956 // In either case, we move on with the accelerate decision, and decode one
957 // frame now.
958 break;
959 }
960 case kPreemptiveExpand: {
961 // In order to do a preemptive expand we need at least 30 ms of decoded
962 // audio data.
963 if ((samples_left >= samples_30_ms) ||
964 (samples_left >= samples_10_ms &&
965 decoder_frame_length_ >= samples_30_ms)) {
966 // Already have enough data, so we do not need to extract any more.
967 // Or, avoid decoding more data as it might overflow the playout buffer.
968 // Still try preemptive expand, though.
969 decision_logic_->set_sample_memory(samples_left);
970 decision_logic_->set_prev_time_scale(true);
971 return 0;
972 }
973 if (samples_left < samples_20_ms &&
974 decoder_frame_length_ < samples_30_ms) {
975 // Build up decoded data by decoding at least 20 ms of audio data.
976 // Still try to perform preemptive expand.
977 required_samples = 2 * output_size_samples_;
978 }
979 // Move on with the preemptive expand decision.
980 break;
981 }
982 default: {
983 // Do nothing.
984 }
985 }
986
987 // Get packets from buffer.
988 int extracted_samples = 0;
989 if (header &&
990 *operation != kAlternativePlc &&
991 *operation != kAlternativePlcIncreaseTimestamp &&
992 *operation != kAudioRepetition &&
993 *operation != kAudioRepetitionIncreaseTimestamp) {
994 sync_buffer_->IncreaseEndTimestamp(header->timestamp - end_timestamp);
995 if (decision_logic_->CngOff()) {
996 // Adjustment of timestamp only corresponds to an actual packet loss
997 // if comfort noise is not played. If comfort noise was just played,
998 // this adjustment of timestamp is only done to get back in sync with the
999 // stream timestamp; no loss to report.
1000 stats_.LostSamples(header->timestamp - end_timestamp);
1001 }
1002
1003 if (*operation != kRfc3389Cng) {
1004 // We are about to decode and use a non-CNG packet.
1005 decision_logic_->SetCngOff();
1006 }
1007 // Reset CNG timestamp as a new packet will be delivered.
1008 // (Also if this is a CNG packet, since playedOutTS is updated.)
1009 decision_logic_->set_generated_noise_samples(0);
1010
1011 extracted_samples = ExtractPackets(required_samples, packet_list);
1012 if (extracted_samples < 0) {
1013 LOG_F(LS_WARNING) << "Failed to extract packets from buffer.";
1014 return kPacketBufferCorruption;
1015 }
1016 }
1017
1018 if (*operation == kAccelerate ||
1019 *operation == kPreemptiveExpand) {
1020 decision_logic_->set_sample_memory(samples_left + extracted_samples);
1021 decision_logic_->set_prev_time_scale(true);
1022 }
1023
1024 if (*operation == kAccelerate) {
1025 // Check that we have enough data (30ms) to do accelerate.
1026 if (extracted_samples + samples_left < samples_30_ms) {
1027 // TODO(hlundin): Write test for this.
1028 // Not enough, do normal operation instead.
1029 *operation = kNormal;
1030 }
1031 }
1032
1033 timestamp_ = end_timestamp;
1034 return 0;
1035}
1036
1037int NetEqImpl::Decode(PacketList* packet_list, Operations* operation,
1038 int* decoded_length,
1039 AudioDecoder::SpeechType* speech_type) {
1040 *speech_type = AudioDecoder::kSpeech;
1041 AudioDecoder* decoder = NULL;
1042 if (!packet_list->empty()) {
1043 const Packet* packet = packet_list->front();
1044 int payload_type = packet->header.payloadType;
1045 if (!decoder_database_->IsComfortNoise(payload_type)) {
1046 decoder = decoder_database_->GetDecoder(payload_type);
1047 assert(decoder);
1048 if (!decoder) {
1049 LOG_FERR1(LS_WARNING, GetDecoder, payload_type);
1050 PacketBuffer::DeleteAllPackets(packet_list);
1051 return kDecoderNotFound;
1052 }
1053 bool decoder_changed;
1054 decoder_database_->SetActiveDecoder(payload_type, &decoder_changed);
1055 if (decoder_changed) {
1056 // We have a new decoder. Re-init some values.
1057 const DecoderDatabase::DecoderInfo* decoder_info = decoder_database_
1058 ->GetDecoderInfo(payload_type);
1059 assert(decoder_info);
1060 if (!decoder_info) {
1061 LOG_FERR1(LS_WARNING, GetDecoderInfo, payload_type);
1062 PacketBuffer::DeleteAllPackets(packet_list);
1063 return kDecoderNotFound;
1064 }
1065 SetSampleRateAndChannels(decoder_info->fs_hz, decoder->channels());
1066 sync_buffer_->set_end_timestamp(timestamp_);
1067 playout_timestamp_ = timestamp_;
1068 }
1069 }
1070 }
1071
1072 if (reset_decoder_) {
1073 // TODO(hlundin): Write test for this.
1074 // Reset decoder.
1075 if (decoder) {
1076 decoder->Init();
1077 }
1078 // Reset comfort noise decoder.
1079 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
1080 if (cng_decoder) {
1081 cng_decoder->Init();
1082 }
1083 reset_decoder_ = false;
1084 }
1085
1086#ifdef LEGACY_BITEXACT
1087 // Due to a bug in old SignalMCU, it could happen that CNG operation was
1088 // decided, but a speech packet was provided. The speech packet will be used
1089 // to update the comfort noise decoder, as if it was a SID frame, which is
1090 // clearly wrong.
1091 if (*operation == kRfc3389Cng) {
1092 return 0;
1093 }
1094#endif
1095
1096 *decoded_length = 0;
1097 // Update codec-internal PLC state.
1098 if ((*operation == kMerge) && decoder && decoder->HasDecodePlc()) {
1099 decoder->DecodePlc(1, &decoded_buffer_[*decoded_length]);
1100 }
1101
1102 int return_value = DecodeLoop(packet_list, operation, decoder,
1103 decoded_length, speech_type);
1104
1105 if (*decoded_length < 0) {
1106 // Error returned from the decoder.
1107 *decoded_length = 0;
1108 sync_buffer_->IncreaseEndTimestamp(decoder_frame_length_);
1109 int error_code = 0;
1110 if (decoder)
1111 error_code = decoder->ErrorCode();
1112 if (error_code != 0) {
1113 // Got some error code from the decoder.
1114 decoder_error_code_ = error_code;
1115 return_value = kDecoderErrorCode;
1116 } else {
1117 // Decoder does not implement error codes. Return generic error.
1118 return_value = kOtherDecoderError;
1119 }
1120 LOG_FERR2(LS_WARNING, DecodeLoop, error_code, packet_list->size());
1121 *operation = kExpand; // Do expansion to get data instead.
1122 }
1123 if (*speech_type != AudioDecoder::kComfortNoise) {
1124 // Don't increment timestamp if codec returned CNG speech type
1125 // since in this case, the we will increment the CNGplayedTS counter.
1126 // Increase with number of samples per channel.
1127 assert(*decoded_length == 0 ||
1128 (decoder && decoder->channels() == sync_buffer_->Channels()));
1129 sync_buffer_->IncreaseEndTimestamp(*decoded_length /
1130 sync_buffer_->Channels());
1131 }
1132 return return_value;
1133}
1134
1135int NetEqImpl::DecodeLoop(PacketList* packet_list, Operations* operation,
1136 AudioDecoder* decoder, int* decoded_length,
1137 AudioDecoder::SpeechType* speech_type) {
1138 Packet* packet = NULL;
1139 if (!packet_list->empty()) {
1140 packet = packet_list->front();
1141 }
1142 // Do decoding.
1143 while (packet &&
1144 !decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1145 assert(decoder); // At this point, we must have a decoder object.
1146 // The number of channels in the |sync_buffer_| should be the same as the
1147 // number decoder channels.
1148 assert(sync_buffer_->Channels() == decoder->channels());
1149 assert(decoded_buffer_length_ >= kMaxFrameSize * decoder->channels());
1150 assert(*operation == kNormal || *operation == kAccelerate ||
1151 *operation == kMerge || *operation == kPreemptiveExpand);
1152 packet_list->pop_front();
henrik.lundin@webrtc.org63464a92013-01-30 09:41:56 +00001153 int payload_length = packet->payload_length;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001154 int16_t decode_length;
1155 if (!packet->primary) {
1156 // This is a redundant payload; call the special decoder method.
henrik.lundin@webrtc.orgb3e905c2013-09-02 09:41:06 +00001157 NETEQ_LOG_VERBOSE << "Decoding packet (redundant):" <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001158 " ts=" << packet->header.timestamp <<
1159 ", sn=" << packet->header.sequenceNumber <<
1160 ", pt=" << static_cast<int>(packet->header.payloadType) <<
1161 ", ssrc=" << packet->header.ssrc <<
1162 ", len=" << packet->payload_length;
1163 decode_length = decoder->DecodeRedundant(
1164 packet->payload, packet->payload_length,
1165 &decoded_buffer_[*decoded_length], speech_type);
1166 } else {
henrik.lundin@webrtc.orgb3e905c2013-09-02 09:41:06 +00001167 NETEQ_LOG_VERBOSE << "Decoding packet: ts=" << packet->header.timestamp <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001168 ", sn=" << packet->header.sequenceNumber <<
1169 ", pt=" << static_cast<int>(packet->header.payloadType) <<
1170 ", ssrc=" << packet->header.ssrc <<
1171 ", len=" << packet->payload_length;
1172 decode_length = decoder->Decode(packet->payload,
1173 packet->payload_length,
1174 &decoded_buffer_[*decoded_length],
1175 speech_type);
1176 }
1177
1178 delete[] packet->payload;
1179 delete packet;
1180 if (decode_length > 0) {
1181 *decoded_length += decode_length;
1182 // Update |decoder_frame_length_| with number of samples per channel.
1183 decoder_frame_length_ = decode_length / decoder->channels();
henrik.lundin@webrtc.orgb3e905c2013-09-02 09:41:06 +00001184 NETEQ_LOG_VERBOSE << "Decoded " << decode_length << " samples (" <<
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001185 decoder->channels() << " channel(s) -> " << decoder_frame_length_ <<
1186 " samples per channel)";
1187 } else if (decode_length < 0) {
1188 // Error.
henrik.lundin@webrtc.org63464a92013-01-30 09:41:56 +00001189 LOG_FERR2(LS_WARNING, Decode, decode_length, payload_length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001190 *decoded_length = -1;
1191 PacketBuffer::DeleteAllPackets(packet_list);
1192 break;
1193 }
1194 if (*decoded_length > static_cast<int>(decoded_buffer_length_)) {
1195 // Guard against overflow.
1196 LOG_F(LS_WARNING) << "Decoded too much.";
1197 PacketBuffer::DeleteAllPackets(packet_list);
1198 return kDecodedTooMuch;
1199 }
1200 if (!packet_list->empty()) {
1201 packet = packet_list->front();
1202 } else {
1203 packet = NULL;
1204 }
1205 } // End of decode loop.
1206
1207 // If the list is not empty at this point, it must hold exactly one CNG
1208 // packet.
1209 assert(packet_list->empty() ||
1210 (packet_list->size() == 1 &&
1211 decoder_database_->IsComfortNoise(packet->header.payloadType)));
1212 return 0;
1213}
1214
1215void NetEqImpl::DoNormal(const int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001216 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001217 assert(normal_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001218 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001219 normal_->Process(decoded_buffer, decoded_length, last_mode_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001220 mute_factor_array_.get(), algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001221 if (decoded_length != 0) {
1222 last_mode_ = kModeNormal;
1223 }
1224
1225 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1226 if ((speech_type == AudioDecoder::kComfortNoise)
1227 || ((last_mode_ == kModeCodecInternalCng)
1228 && (decoded_length == 0))) {
1229 // TODO(hlundin): Remove second part of || statement above.
1230 last_mode_ = kModeCodecInternalCng;
1231 }
1232
1233 if (!play_dtmf) {
1234 dtmf_tone_generator_->Reset();
1235 }
1236}
1237
1238void NetEqImpl::DoMerge(int16_t* decoded_buffer, size_t decoded_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001239 AudioDecoder::SpeechType speech_type, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001240 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001241 assert(merge_.get());
1242 int new_length = merge_->Process(decoded_buffer, decoded_length,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001243 mute_factor_array_.get(),
1244 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001245
1246 // Update in-call and post-call statistics.
1247 if (expand_->MuteFactor(0) == 0) {
1248 // Expand generates only noise.
1249 stats_.ExpandedNoiseSamples(new_length - decoded_length);
1250 } else {
1251 // Expansion generates more than only noise.
1252 stats_.ExpandedVoiceSamples(new_length - decoded_length);
1253 }
1254
1255 last_mode_ = kModeMerge;
1256 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1257 if (speech_type == AudioDecoder::kComfortNoise) {
1258 last_mode_ = kModeCodecInternalCng;
1259 }
1260 expand_->Reset();
1261 if (!play_dtmf) {
1262 dtmf_tone_generator_->Reset();
1263 }
1264}
1265
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001266int NetEqImpl::DoExpand(bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001267 while ((sync_buffer_->FutureLength() - expand_->overlap_length()) <
1268 static_cast<size_t>(output_size_samples_)) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001269 algorithm_buffer_->Clear();
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001270 int return_value = expand_->Process(algorithm_buffer_.get());
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001271 int length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001272
1273 // Update in-call and post-call statistics.
1274 if (expand_->MuteFactor(0) == 0) {
1275 // Expand operation generates only noise.
1276 stats_.ExpandedNoiseSamples(length);
1277 } else {
1278 // Expand operation generates more than only noise.
1279 stats_.ExpandedVoiceSamples(length);
1280 }
1281
1282 last_mode_ = kModeExpand;
1283
1284 if (return_value < 0) {
1285 return return_value;
1286 }
1287
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001288 sync_buffer_->PushBack(*algorithm_buffer_);
1289 algorithm_buffer_->Clear();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001290 }
1291 if (!play_dtmf) {
1292 dtmf_tone_generator_->Reset();
1293 }
1294 return 0;
1295}
1296
1297int NetEqImpl::DoAccelerate(int16_t* decoded_buffer, size_t decoded_length,
1298 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001299 bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001300 const size_t required_samples = 240 * fs_mult_; // Must have 30 ms.
1301 int borrowed_samples_per_channel = 0;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001302 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001303 size_t decoded_length_per_channel = decoded_length / num_channels;
1304 if (decoded_length_per_channel < required_samples) {
1305 // Must move data from the |sync_buffer_| in order to get 30 ms.
1306 borrowed_samples_per_channel = required_samples -
1307 decoded_length_per_channel;
1308 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1309 decoded_buffer,
1310 sizeof(int16_t) * decoded_length);
1311 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1312 decoded_buffer);
1313 decoded_length = required_samples * num_channels;
1314 }
1315
1316 int16_t samples_removed;
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001317 Accelerate::ReturnCodes return_code = accelerate_->Process(
1318 decoded_buffer, decoded_length, algorithm_buffer_.get(),
1319 &samples_removed);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001320 stats_.AcceleratedSamples(samples_removed);
1321 switch (return_code) {
1322 case Accelerate::kSuccess:
1323 last_mode_ = kModeAccelerateSuccess;
1324 break;
1325 case Accelerate::kSuccessLowEnergy:
1326 last_mode_ = kModeAccelerateLowEnergy;
1327 break;
1328 case Accelerate::kNoStretch:
1329 last_mode_ = kModeAccelerateFail;
1330 break;
1331 case Accelerate::kError:
1332 // TODO(hlundin): Map to kModeError instead?
1333 last_mode_ = kModeAccelerateFail;
1334 return kAccelerateError;
1335 }
1336
1337 if (borrowed_samples_per_channel > 0) {
1338 // Copy borrowed samples back to the |sync_buffer_|.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001339 int length = algorithm_buffer_->Size();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001340 if (length < borrowed_samples_per_channel) {
1341 // This destroys the beginning of the buffer, but will not cause any
1342 // problems.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001343 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001344 sync_buffer_->Size() -
1345 borrowed_samples_per_channel);
1346 sync_buffer_->PushFrontZeros(borrowed_samples_per_channel - length);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001347 algorithm_buffer_->PopFront(length);
1348 assert(algorithm_buffer_->Empty());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001349 } else {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001350 sync_buffer_->ReplaceAtIndex(*algorithm_buffer_,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001351 borrowed_samples_per_channel,
1352 sync_buffer_->Size() -
1353 borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001354 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001355 }
1356 }
1357
1358 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1359 if (speech_type == AudioDecoder::kComfortNoise) {
1360 last_mode_ = kModeCodecInternalCng;
1361 }
1362 if (!play_dtmf) {
1363 dtmf_tone_generator_->Reset();
1364 }
1365 expand_->Reset();
1366 return 0;
1367}
1368
1369int NetEqImpl::DoPreemptiveExpand(int16_t* decoded_buffer,
1370 size_t decoded_length,
1371 AudioDecoder::SpeechType speech_type,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001372 bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001373 const size_t required_samples = 240 * fs_mult_; // Must have 30 ms.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001374 size_t num_channels = algorithm_buffer_->Channels();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001375 int borrowed_samples_per_channel = 0;
1376 int old_borrowed_samples_per_channel = 0;
1377 size_t decoded_length_per_channel = decoded_length / num_channels;
1378 if (decoded_length_per_channel < required_samples) {
1379 // Must move data from the |sync_buffer_| in order to get 30 ms.
1380 borrowed_samples_per_channel = required_samples -
1381 decoded_length_per_channel;
1382 // Calculate how many of these were already played out.
1383 old_borrowed_samples_per_channel = borrowed_samples_per_channel -
1384 sync_buffer_->FutureLength();
1385 old_borrowed_samples_per_channel = std::max(
1386 0, old_borrowed_samples_per_channel);
1387 memmove(&decoded_buffer[borrowed_samples_per_channel * num_channels],
1388 decoded_buffer,
1389 sizeof(int16_t) * decoded_length);
1390 sync_buffer_->ReadInterleavedFromEnd(borrowed_samples_per_channel,
1391 decoded_buffer);
1392 decoded_length = required_samples * num_channels;
1393 }
1394
1395 int16_t samples_added;
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001396 PreemptiveExpand::ReturnCodes return_code = preemptive_expand_->Process(
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001397 decoded_buffer, decoded_length, old_borrowed_samples_per_channel,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001398 algorithm_buffer_.get(), &samples_added);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001399 stats_.PreemptiveExpandedSamples(samples_added);
1400 switch (return_code) {
1401 case PreemptiveExpand::kSuccess:
1402 last_mode_ = kModePreemptiveExpandSuccess;
1403 break;
1404 case PreemptiveExpand::kSuccessLowEnergy:
1405 last_mode_ = kModePreemptiveExpandLowEnergy;
1406 break;
1407 case PreemptiveExpand::kNoStretch:
1408 last_mode_ = kModePreemptiveExpandFail;
1409 break;
1410 case PreemptiveExpand::kError:
1411 // TODO(hlundin): Map to kModeError instead?
1412 last_mode_ = kModePreemptiveExpandFail;
1413 return kPreemptiveExpandError;
1414 }
1415
1416 if (borrowed_samples_per_channel > 0) {
1417 // Copy borrowed samples back to the |sync_buffer_|.
1418 sync_buffer_->ReplaceAtIndex(
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001419 *algorithm_buffer_, borrowed_samples_per_channel,
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001420 sync_buffer_->Size() - borrowed_samples_per_channel);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001421 algorithm_buffer_->PopFront(borrowed_samples_per_channel);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001422 }
1423
1424 // If last packet was decoded as an inband CNG, set mode to CNG instead.
1425 if (speech_type == AudioDecoder::kComfortNoise) {
1426 last_mode_ = kModeCodecInternalCng;
1427 }
1428 if (!play_dtmf) {
1429 dtmf_tone_generator_->Reset();
1430 }
1431 expand_->Reset();
1432 return 0;
1433}
1434
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001435int NetEqImpl::DoRfc3389Cng(PacketList* packet_list, bool play_dtmf) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001436 if (!packet_list->empty()) {
1437 // Must have exactly one SID frame at this point.
1438 assert(packet_list->size() == 1);
1439 Packet* packet = packet_list->front();
1440 packet_list->pop_front();
henrik.lundin@webrtc.org73deaad2013-01-31 13:32:51 +00001441 if (!decoder_database_->IsComfortNoise(packet->header.payloadType)) {
1442#ifdef LEGACY_BITEXACT
1443 // This can happen due to a bug in GetDecision. Change the payload type
1444 // to a CNG type, and move on. Note that this means that we are in fact
1445 // sending a non-CNG payload to the comfort noise decoder for decoding.
1446 // Clearly wrong, but will maintain bit-exactness with legacy.
1447 if (fs_hz_ == 8000) {
1448 packet->header.payloadType =
1449 decoder_database_->GetRtpPayloadType(kDecoderCNGnb);
1450 } else if (fs_hz_ == 16000) {
1451 packet->header.payloadType =
1452 decoder_database_->GetRtpPayloadType(kDecoderCNGwb);
1453 } else if (fs_hz_ == 32000) {
1454 packet->header.payloadType =
1455 decoder_database_->GetRtpPayloadType(kDecoderCNGswb32kHz);
1456 } else if (fs_hz_ == 48000) {
1457 packet->header.payloadType =
1458 decoder_database_->GetRtpPayloadType(kDecoderCNGswb48kHz);
1459 }
1460 assert(decoder_database_->IsComfortNoise(packet->header.payloadType));
1461#else
1462 LOG(LS_ERROR) << "Trying to decode non-CNG payload as CNG.";
1463 return kOtherError;
1464#endif
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001465 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001466 // UpdateParameters() deletes |packet|.
1467 if (comfort_noise_->UpdateParameters(packet) ==
1468 ComfortNoise::kInternalError) {
1469 LOG_FERR0(LS_WARNING, UpdateParameters);
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001470 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001471 return -comfort_noise_->internal_error_code();
1472 }
1473 }
1474 int cn_return = comfort_noise_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001475 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001476 expand_->Reset();
1477 last_mode_ = kModeRfc3389Cng;
1478 if (!play_dtmf) {
1479 dtmf_tone_generator_->Reset();
1480 }
1481 if (cn_return == ComfortNoise::kInternalError) {
1482 LOG_FERR1(LS_WARNING, comfort_noise_->Generate, cn_return);
1483 decoder_error_code_ = comfort_noise_->internal_error_code();
1484 return kComfortNoiseErrorCode;
1485 } else if (cn_return == ComfortNoise::kUnknownPayloadType) {
1486 LOG_FERR1(LS_WARNING, comfort_noise_->Generate, cn_return);
1487 return kUnknownRtpPayloadType;
1488 }
1489 return 0;
1490}
1491
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001492void NetEqImpl::DoCodecInternalCng() {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001493 int length = 0;
1494 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1495 int16_t decoded_buffer[kMaxFrameSize];
1496 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1497 if (decoder) {
1498 const uint8_t* dummy_payload = NULL;
1499 AudioDecoder::SpeechType speech_type;
1500 length = decoder->Decode(dummy_payload, 0, decoded_buffer, &speech_type);
1501 }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001502 assert(mute_factor_array_.get());
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001503 normal_->Process(decoded_buffer, length, last_mode_, mute_factor_array_.get(),
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001504 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001505 last_mode_ = kModeCodecInternalCng;
1506 expand_->Reset();
1507}
1508
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001509int NetEqImpl::DoDtmf(const DtmfEvent& dtmf_event, bool* play_dtmf) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001510 // This block of the code and the block further down, handling |dtmf_switch|
1511 // are commented out. Otherwise playing out-of-band DTMF would fail in VoE
1512 // test, DtmfTest.ManualSuccessfullySendsOutOfBandTelephoneEvents. This is
1513 // equivalent to |dtmf_switch| always be false.
1514 //
1515 // See http://webrtc-codereview.appspot.com/1195004/ for discussion
1516 // On this issue. This change might cause some glitches at the point of
1517 // switch from audio to DTMF. Issue 1545 is filed to track this.
1518 //
1519 // bool dtmf_switch = false;
1520 // if ((last_mode_ != kModeDtmf) && dtmf_tone_generator_->initialized()) {
1521 // // Special case; see below.
1522 // // We must catch this before calling Generate, since |initialized| is
1523 // // modified in that call.
1524 // dtmf_switch = true;
1525 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001526
1527 int dtmf_return_value = 0;
1528 if (!dtmf_tone_generator_->initialized()) {
1529 // Initialize if not already done.
1530 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1531 dtmf_event.volume);
1532 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001533
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001534 if (dtmf_return_value == 0) {
1535 // Generate DTMF signal.
1536 dtmf_return_value = dtmf_tone_generator_->Generate(output_size_samples_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001537 algorithm_buffer_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001538 }
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001539
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001540 if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001541 algorithm_buffer_->Zeros(output_size_samples_);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001542 return dtmf_return_value;
1543 }
1544
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001545 // if (dtmf_switch) {
1546 // // This is the special case where the previous operation was DTMF
1547 // // overdub, but the current instruction is "regular" DTMF. We must make
1548 // // sure that the DTMF does not have any discontinuities. The first DTMF
1549 // // sample that we generate now must be played out immediately, therefore
1550 // // it must be copied to the speech buffer.
1551 // // TODO(hlundin): This code seems incorrect. (Legacy.) Write test and
1552 // // verify correct operation.
1553 // assert(false);
1554 // // Must generate enough data to replace all of the |sync_buffer_|
1555 // // "future".
1556 // int required_length = sync_buffer_->FutureLength();
1557 // assert(dtmf_tone_generator_->initialized());
1558 // dtmf_return_value = dtmf_tone_generator_->Generate(required_length,
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001559 // algorithm_buffer_);
1560 // assert((size_t) required_length == algorithm_buffer_->Size());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001561 // if (dtmf_return_value < 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001562 // algorithm_buffer_->Zeros(output_size_samples_);
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001563 // return dtmf_return_value;
1564 // }
1565 //
1566 // // Overwrite the "future" part of the speech buffer with the new DTMF
1567 // // data.
1568 // // TODO(hlundin): It seems that this overwriting has gone lost.
1569 // // Not adapted for multi-channel yet.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001570 // assert(algorithm_buffer_->Channels() == 1);
1571 // if (algorithm_buffer_->Channels() != 1) {
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001572 // LOG(LS_WARNING) << "DTMF not supported for more than one channel";
1573 // return kStereoNotSupported;
1574 // }
1575 // // Shuffle the remaining data to the beginning of algorithm buffer.
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001576 // algorithm_buffer_->PopFront(sync_buffer_->FutureLength());
turaj@webrtc.org4d06db52013-03-27 18:31:42 +00001577 // }
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001578
1579 sync_buffer_->IncreaseEndTimestamp(output_size_samples_);
1580 expand_->Reset();
1581 last_mode_ = kModeDtmf;
1582
1583 // Set to false because the DTMF is already in the algorithm buffer.
1584 *play_dtmf = false;
1585 return 0;
1586}
1587
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001588void NetEqImpl::DoAlternativePlc(bool increase_timestamp) {
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001589 AudioDecoder* decoder = decoder_database_->GetActiveDecoder();
1590 int length;
1591 if (decoder && decoder->HasDecodePlc()) {
1592 // Use the decoder's packet-loss concealment.
1593 // TODO(hlundin): Will probably need a longer buffer for multi-channel.
1594 int16_t decoded_buffer[kMaxFrameSize];
1595 length = decoder->DecodePlc(1, decoded_buffer);
1596 if (length > 0) {
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001597 algorithm_buffer_->PushBackInterleaved(decoded_buffer, length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001598 } else {
1599 length = 0;
1600 }
1601 } else {
1602 // Do simple zero-stuffing.
1603 length = output_size_samples_;
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001604 algorithm_buffer_->Zeros(length);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001605 // By not advancing the timestamp, NetEq inserts samples.
1606 stats_.AddZeros(length);
1607 }
1608 if (increase_timestamp) {
1609 sync_buffer_->IncreaseEndTimestamp(length);
1610 }
1611 expand_->Reset();
1612}
1613
1614int NetEqImpl::DtmfOverdub(const DtmfEvent& dtmf_event, size_t num_channels,
1615 int16_t* output) const {
1616 size_t out_index = 0;
1617 int overdub_length = output_size_samples_; // Default value.
1618
1619 if (sync_buffer_->dtmf_index() > sync_buffer_->next_index()) {
1620 // Special operation for transition from "DTMF only" to "DTMF overdub".
1621 out_index = std::min(
1622 sync_buffer_->dtmf_index() - sync_buffer_->next_index(),
1623 static_cast<size_t>(output_size_samples_));
1624 overdub_length = output_size_samples_ - out_index;
1625 }
1626
1627 AudioMultiVector<int16_t> dtmf_output(num_channels);
1628 int dtmf_return_value = 0;
1629 if (!dtmf_tone_generator_->initialized()) {
1630 dtmf_return_value = dtmf_tone_generator_->Init(fs_hz_, dtmf_event.event_no,
1631 dtmf_event.volume);
1632 }
1633 if (dtmf_return_value == 0) {
1634 dtmf_return_value = dtmf_tone_generator_->Generate(overdub_length,
1635 &dtmf_output);
1636 assert((size_t) overdub_length == dtmf_output.Size());
1637 }
1638 dtmf_output.ReadInterleaved(overdub_length, &output[out_index]);
1639 return dtmf_return_value < 0 ? dtmf_return_value : 0;
1640}
1641
1642int NetEqImpl::ExtractPackets(int required_samples, PacketList* packet_list) {
1643 bool first_packet = true;
1644 uint8_t prev_payload_type = 0;
1645 uint32_t prev_timestamp = 0;
1646 uint16_t prev_sequence_number = 0;
1647 bool next_packet_available = false;
1648
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001649 const RTPHeader* header = packet_buffer_->NextRtpHeader();
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001650 assert(header);
1651 if (!header) {
1652 return -1;
1653 }
turaj@webrtc.org7df97062013-08-02 18:07:13 +00001654 uint32_t first_timestamp = header->timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001655 int extracted_samples = 0;
1656
1657 // Packet extraction loop.
1658 do {
1659 timestamp_ = header->timestamp;
1660 int discard_count = 0;
henrik.lundin@webrtc.orge1d468c2013-01-30 07:37:20 +00001661 Packet* packet = packet_buffer_->GetNextPacket(&discard_count);
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001662 // |header| may be invalid after the |packet_buffer_| operation.
1663 header = NULL;
1664 if (!packet) {
1665 LOG_FERR1(LS_ERROR, GetNextPacket, discard_count) <<
1666 "Should always be able to extract a packet here";
1667 assert(false); // Should always be able to extract a packet here.
1668 return -1;
1669 }
1670 stats_.PacketsDiscarded(discard_count);
1671 // Store waiting time in ms; packets->waiting_time is in "output blocks".
1672 stats_.StoreWaitingTime(packet->waiting_time * kOutputSizeMs);
1673 assert(packet->payload_length > 0);
1674 packet_list->push_back(packet); // Store packet in list.
1675
1676 if (first_packet) {
1677 first_packet = false;
minyue@webrtc.orgd7301772013-08-29 00:58:14 +00001678 decoded_packet_sequence_number_ = prev_sequence_number =
1679 packet->header.sequenceNumber;
1680 decoded_packet_timestamp_ = prev_timestamp = packet->header.timestamp;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001681 prev_payload_type = packet->header.payloadType;
1682 }
1683
1684 // Store number of extracted samples.
1685 int packet_duration = 0;
1686 AudioDecoder* decoder = decoder_database_->GetDecoder(
1687 packet->header.payloadType);
1688 if (decoder) {
1689 packet_duration = decoder->PacketDuration(packet->payload,
1690 packet->payload_length);
1691 } else {
1692 LOG_FERR1(LS_WARNING, GetDecoder, packet->header.payloadType) <<
1693 "Could not find a decoder for a packet about to be extracted.";
1694 assert(false);
1695 }
1696 if (packet_duration <= 0) {
1697 // Decoder did not return a packet duration. Assume that the packet
1698 // contains the same number of samples as the previous one.
1699 packet_duration = decoder_frame_length_;
1700 }
1701 extracted_samples = packet->header.timestamp - first_timestamp +
1702 packet_duration;
1703
1704 // Check what packet is available next.
1705 header = packet_buffer_->NextRtpHeader();
1706 next_packet_available = false;
1707 if (header && prev_payload_type == header->payloadType) {
1708 int16_t seq_no_diff = header->sequenceNumber - prev_sequence_number;
1709 int32_t ts_diff = header->timestamp - prev_timestamp;
1710 if (seq_no_diff == 1 ||
1711 (seq_no_diff == 0 && ts_diff == decoder_frame_length_)) {
1712 // The next sequence number is available, or the next part of a packet
1713 // that was split into pieces upon insertion.
1714 next_packet_available = true;
1715 }
1716 prev_sequence_number = header->sequenceNumber;
1717 }
1718 } while (extracted_samples < required_samples && next_packet_available);
1719
1720 return extracted_samples;
1721}
1722
1723void NetEqImpl::SetSampleRateAndChannels(int fs_hz, size_t channels) {
1724 LOG_API2(fs_hz, channels);
1725 // TODO(hlundin): Change to an enumerator and skip assert.
1726 assert(fs_hz == 8000 || fs_hz == 16000 || fs_hz == 32000 || fs_hz == 48000);
1727 assert(channels > 0);
1728
1729 fs_hz_ = fs_hz;
1730 fs_mult_ = fs_hz / 8000;
1731 output_size_samples_ = kOutputSizeMs * 8 * fs_mult_;
1732 decoder_frame_length_ = 3 * output_size_samples_; // Initialize to 30ms.
1733
1734 last_mode_ = kModeNormal;
1735
1736 // Create a new array of mute factors and set all to 1.
1737 mute_factor_array_.reset(new int16_t[channels]);
1738 for (size_t i = 0; i < channels; ++i) {
1739 mute_factor_array_[i] = 16384; // 1.0 in Q14.
1740 }
1741
1742 // Reset comfort noise decoder, if there is one active.
1743 AudioDecoder* cng_decoder = decoder_database_->GetActiveCngDecoder();
1744 if (cng_decoder) {
1745 cng_decoder->Init();
1746 }
1747
1748 // Reinit post-decode VAD with new sample rate.
1749 assert(vad_.get()); // Cannot be NULL here.
1750 vad_->Init();
1751
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001752 // Delete algorithm buffer and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001753 algorithm_buffer_.reset(new AudioMultiVector<int16_t>(channels));
henrik.lundin@webrtc.orgc487c6a2013-09-02 07:59:30 +00001754
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001755 // Delete sync buffer and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001756 sync_buffer_.reset(new SyncBuffer(channels, kSyncBufferSize * fs_mult_));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001757
1758 // Delete BackgroundNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001759 background_noise_.reset(new BackgroundNoise(channels));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001760
1761 // Reset random vector.
1762 random_vector_.Reset();
1763
1764 // Delete Expand object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001765 expand_.reset(new Expand(background_noise_.get(), sync_buffer_.get(),
1766 &random_vector_, fs_hz, channels));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001767 // Move index so that we create a small set of future samples (all 0).
1768 sync_buffer_->set_next_index(sync_buffer_->next_index() -
1769 expand_->overlap_length());
1770
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001771 normal_.reset(new Normal(fs_hz, decoder_database_.get(), *background_noise_,
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001772 expand_.get()));
1773 merge_.reset(new Merge(fs_hz, channels, expand_.get(), sync_buffer_.get()));
henrik.lundin@webrtc.org40d3fc62013-09-18 12:19:50 +00001774 accelerate_.reset(new Accelerate(fs_hz, channels, *background_noise_));
1775 preemptive_expand_.reset(new PreemptiveExpand(fs_hz, channels,
1776 *background_noise_));
1777
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001778 // Delete ComfortNoise object and create a new one.
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001779 comfort_noise_.reset(new ComfortNoise(fs_hz, decoder_database_.get(),
1780 sync_buffer_.get()));
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001781
1782 // Verify that |decoded_buffer_| is long enough.
1783 if (decoded_buffer_length_ < kMaxFrameSize * channels) {
1784 // Reallocate to larger size.
1785 decoded_buffer_length_ = kMaxFrameSize * channels;
1786 decoded_buffer_.reset(new int16_t[decoded_buffer_length_]);
1787 }
1788
1789 // Communicate new sample rate and output size to DecisionLogic object.
1790 assert(decision_logic_.get());
1791 decision_logic_->SetSampleRate(fs_hz_, output_size_samples_);
1792}
1793
1794NetEqOutputType NetEqImpl::LastOutputType() {
1795 assert(vad_.get());
henrik.lundin@webrtc.org0d5da252013-09-18 21:12:38 +00001796 assert(expand_.get());
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001797 if (last_mode_ == kModeCodecInternalCng || last_mode_ == kModeRfc3389Cng) {
1798 return kOutputCNG;
1799 } else if (vad_->running() && !vad_->active_speech()) {
1800 return kOutputVADPassive;
1801 } else if (last_mode_ == kModeExpand && expand_->MuteFactor(0) == 0) {
1802 // Expand mode has faded down to background noise only (very long expand).
1803 return kOutputPLCtoCNG;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001804 } else if (last_mode_ == kModeExpand) {
1805 return kOutputPLC;
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001806 } else {
1807 return kOutputNormal;
1808 }
1809}
1810
henrik.lundin@webrtc.orgd94659d2013-01-29 12:09:21 +00001811} // namespace webrtc