You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

880 lines
38 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  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. #include "modules/audio_coding/neteq/expand.h"
  11. #include <assert.h>
  12. #include <string.h> // memset
  13. #include <algorithm> // min, max
  14. #include <limits> // numeric_limits<T>
  15. #include "common_audio/signal_processing/include/signal_processing_library.h"
  16. #include "modules/audio_coding/neteq/audio_multi_vector.h"
  17. #include "modules/audio_coding/neteq/background_noise.h"
  18. #include "modules/audio_coding/neteq/cross_correlation.h"
  19. #include "modules/audio_coding/neteq/dsp_helper.h"
  20. #include "modules/audio_coding/neteq/random_vector.h"
  21. #include "modules/audio_coding/neteq/statistics_calculator.h"
  22. #include "modules/audio_coding/neteq/sync_buffer.h"
  23. #include "rtc_base/numerics/safe_conversions.h"
  24. namespace webrtc {
  25. Expand::Expand(BackgroundNoise* background_noise,
  26. SyncBuffer* sync_buffer,
  27. RandomVector* random_vector,
  28. StatisticsCalculator* statistics,
  29. int fs,
  30. size_t num_channels)
  31. : random_vector_(random_vector),
  32. sync_buffer_(sync_buffer),
  33. first_expand_(true),
  34. fs_hz_(fs),
  35. num_channels_(num_channels),
  36. consecutive_expands_(0),
  37. background_noise_(background_noise),
  38. statistics_(statistics),
  39. overlap_length_(5 * fs / 8000),
  40. lag_index_direction_(0),
  41. current_lag_index_(0),
  42. stop_muting_(false),
  43. expand_duration_samples_(0),
  44. channel_parameters_(new ChannelParameters[num_channels_]) {
  45. assert(fs == 8000 || fs == 16000 || fs == 32000 || fs == 48000);
  46. assert(fs <= static_cast<int>(kMaxSampleRate)); // Should not be possible.
  47. assert(num_channels_ > 0);
  48. memset(expand_lags_, 0, sizeof(expand_lags_));
  49. Reset();
  50. }
  51. Expand::~Expand() = default;
  52. void Expand::Reset() {
  53. first_expand_ = true;
  54. consecutive_expands_ = 0;
  55. max_lag_ = 0;
  56. for (size_t ix = 0; ix < num_channels_; ++ix) {
  57. channel_parameters_[ix].expand_vector0.Clear();
  58. channel_parameters_[ix].expand_vector1.Clear();
  59. }
  60. }
  61. int Expand::Process(AudioMultiVector* output) {
  62. int16_t random_vector[kMaxSampleRate / 8000 * 120 + 30];
  63. int16_t scaled_random_vector[kMaxSampleRate / 8000 * 125];
  64. static const int kTempDataSize = 3600;
  65. int16_t temp_data[kTempDataSize]; // TODO(hlundin) Remove this.
  66. int16_t* voiced_vector_storage = temp_data;
  67. int16_t* voiced_vector = &voiced_vector_storage[overlap_length_];
  68. static const size_t kNoiseLpcOrder = BackgroundNoise::kMaxLpcOrder;
  69. int16_t unvoiced_array_memory[kNoiseLpcOrder + kMaxSampleRate / 8000 * 125];
  70. int16_t* unvoiced_vector = unvoiced_array_memory + kUnvoicedLpcOrder;
  71. int16_t* noise_vector = unvoiced_array_memory + kNoiseLpcOrder;
  72. int fs_mult = fs_hz_ / 8000;
  73. if (first_expand_) {
  74. // Perform initial setup if this is the first expansion since last reset.
  75. AnalyzeSignal(random_vector);
  76. first_expand_ = false;
  77. expand_duration_samples_ = 0;
  78. } else {
  79. // This is not the first expansion, parameters are already estimated.
  80. // Extract a noise segment.
  81. size_t rand_length = max_lag_;
  82. // This only applies to SWB where length could be larger than 256.
  83. assert(rand_length <= kMaxSampleRate / 8000 * 120 + 30);
  84. GenerateRandomVector(2, rand_length, random_vector);
  85. }
  86. // Generate signal.
  87. UpdateLagIndex();
  88. // Voiced part.
  89. // Generate a weighted vector with the current lag.
  90. size_t expansion_vector_length = max_lag_ + overlap_length_;
  91. size_t current_lag = expand_lags_[current_lag_index_];
  92. // Copy lag+overlap data.
  93. size_t expansion_vector_position =
  94. expansion_vector_length - current_lag - overlap_length_;
  95. size_t temp_length = current_lag + overlap_length_;
  96. for (size_t channel_ix = 0; channel_ix < num_channels_; ++channel_ix) {
  97. ChannelParameters& parameters = channel_parameters_[channel_ix];
  98. if (current_lag_index_ == 0) {
  99. // Use only expand_vector0.
  100. assert(expansion_vector_position + temp_length <=
  101. parameters.expand_vector0.Size());
  102. parameters.expand_vector0.CopyTo(temp_length, expansion_vector_position,
  103. voiced_vector_storage);
  104. } else if (current_lag_index_ == 1) {
  105. std::unique_ptr<int16_t[]> temp_0(new int16_t[temp_length]);
  106. parameters.expand_vector0.CopyTo(temp_length, expansion_vector_position,
  107. temp_0.get());
  108. std::unique_ptr<int16_t[]> temp_1(new int16_t[temp_length]);
  109. parameters.expand_vector1.CopyTo(temp_length, expansion_vector_position,
  110. temp_1.get());
  111. // Mix 3/4 of expand_vector0 with 1/4 of expand_vector1.
  112. WebRtcSpl_ScaleAndAddVectorsWithRound(temp_0.get(), 3, temp_1.get(), 1, 2,
  113. voiced_vector_storage, temp_length);
  114. } else if (current_lag_index_ == 2) {
  115. // Mix 1/2 of expand_vector0 with 1/2 of expand_vector1.
  116. assert(expansion_vector_position + temp_length <=
  117. parameters.expand_vector0.Size());
  118. assert(expansion_vector_position + temp_length <=
  119. parameters.expand_vector1.Size());
  120. std::unique_ptr<int16_t[]> temp_0(new int16_t[temp_length]);
  121. parameters.expand_vector0.CopyTo(temp_length, expansion_vector_position,
  122. temp_0.get());
  123. std::unique_ptr<int16_t[]> temp_1(new int16_t[temp_length]);
  124. parameters.expand_vector1.CopyTo(temp_length, expansion_vector_position,
  125. temp_1.get());
  126. WebRtcSpl_ScaleAndAddVectorsWithRound(temp_0.get(), 1, temp_1.get(), 1, 1,
  127. voiced_vector_storage, temp_length);
  128. }
  129. // Get tapering window parameters. Values are in Q15.
  130. int16_t muting_window, muting_window_increment;
  131. int16_t unmuting_window, unmuting_window_increment;
  132. if (fs_hz_ == 8000) {
  133. muting_window = DspHelper::kMuteFactorStart8kHz;
  134. muting_window_increment = DspHelper::kMuteFactorIncrement8kHz;
  135. unmuting_window = DspHelper::kUnmuteFactorStart8kHz;
  136. unmuting_window_increment = DspHelper::kUnmuteFactorIncrement8kHz;
  137. } else if (fs_hz_ == 16000) {
  138. muting_window = DspHelper::kMuteFactorStart16kHz;
  139. muting_window_increment = DspHelper::kMuteFactorIncrement16kHz;
  140. unmuting_window = DspHelper::kUnmuteFactorStart16kHz;
  141. unmuting_window_increment = DspHelper::kUnmuteFactorIncrement16kHz;
  142. } else if (fs_hz_ == 32000) {
  143. muting_window = DspHelper::kMuteFactorStart32kHz;
  144. muting_window_increment = DspHelper::kMuteFactorIncrement32kHz;
  145. unmuting_window = DspHelper::kUnmuteFactorStart32kHz;
  146. unmuting_window_increment = DspHelper::kUnmuteFactorIncrement32kHz;
  147. } else { // fs_ == 48000
  148. muting_window = DspHelper::kMuteFactorStart48kHz;
  149. muting_window_increment = DspHelper::kMuteFactorIncrement48kHz;
  150. unmuting_window = DspHelper::kUnmuteFactorStart48kHz;
  151. unmuting_window_increment = DspHelper::kUnmuteFactorIncrement48kHz;
  152. }
  153. // Smooth the expanded if it has not been muted to a low amplitude and
  154. // |current_voice_mix_factor| is larger than 0.5.
  155. if ((parameters.mute_factor > 819) &&
  156. (parameters.current_voice_mix_factor > 8192)) {
  157. size_t start_ix = sync_buffer_->Size() - overlap_length_;
  158. for (size_t i = 0; i < overlap_length_; i++) {
  159. // Do overlap add between new vector and overlap.
  160. (*sync_buffer_)[channel_ix][start_ix + i] =
  161. (((*sync_buffer_)[channel_ix][start_ix + i] * muting_window) +
  162. (((parameters.mute_factor * voiced_vector_storage[i]) >> 14) *
  163. unmuting_window) +
  164. 16384) >>
  165. 15;
  166. muting_window += muting_window_increment;
  167. unmuting_window += unmuting_window_increment;
  168. }
  169. } else if (parameters.mute_factor == 0) {
  170. // The expanded signal will consist of only comfort noise if
  171. // mute_factor = 0. Set the output length to 15 ms for best noise
  172. // production.
  173. // TODO(hlundin): This has been disabled since the length of
  174. // parameters.expand_vector0 and parameters.expand_vector1 no longer
  175. // match with expand_lags_, causing invalid reads and writes. Is it a good
  176. // idea to enable this again, and solve the vector size problem?
  177. // max_lag_ = fs_mult * 120;
  178. // expand_lags_[0] = fs_mult * 120;
  179. // expand_lags_[1] = fs_mult * 120;
  180. // expand_lags_[2] = fs_mult * 120;
  181. }
  182. // Unvoiced part.
  183. // Filter |scaled_random_vector| through |ar_filter_|.
  184. memcpy(unvoiced_vector - kUnvoicedLpcOrder, parameters.ar_filter_state,
  185. sizeof(int16_t) * kUnvoicedLpcOrder);
  186. int32_t add_constant = 0;
  187. if (parameters.ar_gain_scale > 0) {
  188. add_constant = 1 << (parameters.ar_gain_scale - 1);
  189. }
  190. WebRtcSpl_AffineTransformVector(scaled_random_vector, random_vector,
  191. parameters.ar_gain, add_constant,
  192. parameters.ar_gain_scale, current_lag);
  193. WebRtcSpl_FilterARFastQ12(scaled_random_vector, unvoiced_vector,
  194. parameters.ar_filter, kUnvoicedLpcOrder + 1,
  195. current_lag);
  196. memcpy(parameters.ar_filter_state,
  197. &(unvoiced_vector[current_lag - kUnvoicedLpcOrder]),
  198. sizeof(int16_t) * kUnvoicedLpcOrder);
  199. // Combine voiced and unvoiced contributions.
  200. // Set a suitable cross-fading slope.
  201. // For lag =
  202. // <= 31 * fs_mult => go from 1 to 0 in about 8 ms;
  203. // (>= 31 .. <= 63) * fs_mult => go from 1 to 0 in about 16 ms;
  204. // >= 64 * fs_mult => go from 1 to 0 in about 32 ms.
  205. // temp_shift = getbits(max_lag_) - 5.
  206. int temp_shift =
  207. (31 - WebRtcSpl_NormW32(rtc::dchecked_cast<int32_t>(max_lag_))) - 5;
  208. int16_t mix_factor_increment = 256 >> temp_shift;
  209. if (stop_muting_) {
  210. mix_factor_increment = 0;
  211. }
  212. // Create combined signal by shifting in more and more of unvoiced part.
  213. temp_shift = 8 - temp_shift; // = getbits(mix_factor_increment).
  214. size_t temp_length =
  215. (parameters.current_voice_mix_factor - parameters.voice_mix_factor) >>
  216. temp_shift;
  217. temp_length = std::min(temp_length, current_lag);
  218. DspHelper::CrossFade(voiced_vector, unvoiced_vector, temp_length,
  219. &parameters.current_voice_mix_factor,
  220. mix_factor_increment, temp_data);
  221. // End of cross-fading period was reached before end of expanded signal
  222. // path. Mix the rest with a fixed mixing factor.
  223. if (temp_length < current_lag) {
  224. if (mix_factor_increment != 0) {
  225. parameters.current_voice_mix_factor = parameters.voice_mix_factor;
  226. }
  227. int16_t temp_scale = 16384 - parameters.current_voice_mix_factor;
  228. WebRtcSpl_ScaleAndAddVectorsWithRound(
  229. voiced_vector + temp_length, parameters.current_voice_mix_factor,
  230. unvoiced_vector + temp_length, temp_scale, 14,
  231. temp_data + temp_length, current_lag - temp_length);
  232. }
  233. // Select muting slope depending on how many consecutive expands we have
  234. // done.
  235. if (consecutive_expands_ == 3) {
  236. // Let the mute factor decrease from 1.0 to 0.95 in 6.25 ms.
  237. // mute_slope = 0.0010 / fs_mult in Q20.
  238. parameters.mute_slope = std::max(parameters.mute_slope, 1049 / fs_mult);
  239. }
  240. if (consecutive_expands_ == 7) {
  241. // Let the mute factor decrease from 1.0 to 0.90 in 6.25 ms.
  242. // mute_slope = 0.0020 / fs_mult in Q20.
  243. parameters.mute_slope = std::max(parameters.mute_slope, 2097 / fs_mult);
  244. }
  245. // Mute segment according to slope value.
  246. if ((consecutive_expands_ != 0) || !parameters.onset) {
  247. // Mute to the previous level, then continue with the muting.
  248. WebRtcSpl_AffineTransformVector(
  249. temp_data, temp_data, parameters.mute_factor, 8192, 14, current_lag);
  250. if (!stop_muting_) {
  251. DspHelper::MuteSignal(temp_data, parameters.mute_slope, current_lag);
  252. // Shift by 6 to go from Q20 to Q14.
  253. // TODO(hlundin): Adding 8192 before shifting 6 steps seems wrong.
  254. // Legacy.
  255. int16_t gain = static_cast<int16_t>(
  256. 16384 - (((current_lag * parameters.mute_slope) + 8192) >> 6));
  257. gain = ((gain * parameters.mute_factor) + 8192) >> 14;
  258. // Guard against getting stuck with very small (but sometimes audible)
  259. // gain.
  260. if ((consecutive_expands_ > 3) && (gain >= parameters.mute_factor)) {
  261. parameters.mute_factor = 0;
  262. } else {
  263. parameters.mute_factor = gain;
  264. }
  265. }
  266. }
  267. // Background noise part.
  268. background_noise_->GenerateBackgroundNoise(
  269. random_vector, channel_ix, channel_parameters_[channel_ix].mute_slope,
  270. TooManyExpands(), current_lag, unvoiced_array_memory);
  271. // Add background noise to the combined voiced-unvoiced signal.
  272. for (size_t i = 0; i < current_lag; i++) {
  273. temp_data[i] = temp_data[i] + noise_vector[i];
  274. }
  275. if (channel_ix == 0) {
  276. output->AssertSize(current_lag);
  277. } else {
  278. assert(output->Size() == current_lag);
  279. }
  280. (*output)[channel_ix].OverwriteAt(temp_data, current_lag, 0);
  281. }
  282. // Increase call number and cap it.
  283. consecutive_expands_ = consecutive_expands_ >= kMaxConsecutiveExpands
  284. ? kMaxConsecutiveExpands
  285. : consecutive_expands_ + 1;
  286. expand_duration_samples_ += output->Size();
  287. // Clamp the duration counter at 2 seconds.
  288. expand_duration_samples_ = std::min(expand_duration_samples_,
  289. rtc::dchecked_cast<size_t>(fs_hz_ * 2));
  290. return 0;
  291. }
  292. void Expand::SetParametersForNormalAfterExpand() {
  293. current_lag_index_ = 0;
  294. lag_index_direction_ = 0;
  295. stop_muting_ = true; // Do not mute signal any more.
  296. statistics_->LogDelayedPacketOutageEvent(expand_duration_samples_, fs_hz_);
  297. statistics_->EndExpandEvent(fs_hz_);
  298. }
  299. void Expand::SetParametersForMergeAfterExpand() {
  300. current_lag_index_ = -1; /* out of the 3 possible ones */
  301. lag_index_direction_ = 1; /* make sure we get the "optimal" lag */
  302. stop_muting_ = true;
  303. statistics_->EndExpandEvent(fs_hz_);
  304. }
  305. bool Expand::Muted() const {
  306. if (first_expand_ || stop_muting_)
  307. return false;
  308. RTC_DCHECK(channel_parameters_);
  309. for (size_t ch = 0; ch < num_channels_; ++ch) {
  310. if (channel_parameters_[ch].mute_factor != 0)
  311. return false;
  312. }
  313. return true;
  314. }
  315. size_t Expand::overlap_length() const {
  316. return overlap_length_;
  317. }
  318. void Expand::InitializeForAnExpandPeriod() {
  319. lag_index_direction_ = 1;
  320. current_lag_index_ = -1;
  321. stop_muting_ = false;
  322. random_vector_->set_seed_increment(1);
  323. consecutive_expands_ = 0;
  324. for (size_t ix = 0; ix < num_channels_; ++ix) {
  325. channel_parameters_[ix].current_voice_mix_factor = 16384; // 1.0 in Q14.
  326. channel_parameters_[ix].mute_factor = 16384; // 1.0 in Q14.
  327. // Start with 0 gain for background noise.
  328. background_noise_->SetMuteFactor(ix, 0);
  329. }
  330. }
  331. bool Expand::TooManyExpands() {
  332. return consecutive_expands_ >= kMaxConsecutiveExpands;
  333. }
  334. void Expand::AnalyzeSignal(int16_t* random_vector) {
  335. int32_t auto_correlation[kUnvoicedLpcOrder + 1];
  336. int16_t reflection_coeff[kUnvoicedLpcOrder];
  337. int16_t correlation_vector[kMaxSampleRate / 8000 * 102];
  338. size_t best_correlation_index[kNumCorrelationCandidates];
  339. int16_t best_correlation[kNumCorrelationCandidates];
  340. size_t best_distortion_index[kNumCorrelationCandidates];
  341. int16_t best_distortion[kNumCorrelationCandidates];
  342. int32_t correlation_vector2[(99 * kMaxSampleRate / 8000) + 1];
  343. int32_t best_distortion_w32[kNumCorrelationCandidates];
  344. static const size_t kNoiseLpcOrder = BackgroundNoise::kMaxLpcOrder;
  345. int16_t unvoiced_array_memory[kNoiseLpcOrder + kMaxSampleRate / 8000 * 125];
  346. int16_t* unvoiced_vector = unvoiced_array_memory + kUnvoicedLpcOrder;
  347. int fs_mult = fs_hz_ / 8000;
  348. // Pre-calculate common multiplications with fs_mult.
  349. size_t fs_mult_4 = static_cast<size_t>(fs_mult * 4);
  350. size_t fs_mult_20 = static_cast<size_t>(fs_mult * 20);
  351. size_t fs_mult_120 = static_cast<size_t>(fs_mult * 120);
  352. size_t fs_mult_dist_len = fs_mult * kDistortionLength;
  353. size_t fs_mult_lpc_analysis_len = fs_mult * kLpcAnalysisLength;
  354. const size_t signal_length = static_cast<size_t>(256 * fs_mult);
  355. const size_t audio_history_position = sync_buffer_->Size() - signal_length;
  356. std::unique_ptr<int16_t[]> audio_history(new int16_t[signal_length]);
  357. (*sync_buffer_)[0].CopyTo(signal_length, audio_history_position,
  358. audio_history.get());
  359. // Initialize.
  360. InitializeForAnExpandPeriod();
  361. // Calculate correlation in downsampled domain (4 kHz sample rate).
  362. size_t correlation_length = 51; // TODO(hlundin): Legacy bit-exactness.
  363. // If it is decided to break bit-exactness |correlation_length| should be
  364. // initialized to the return value of Correlation().
  365. Correlation(audio_history.get(), signal_length, correlation_vector);
  366. // Find peaks in correlation vector.
  367. DspHelper::PeakDetection(correlation_vector, correlation_length,
  368. kNumCorrelationCandidates, fs_mult,
  369. best_correlation_index, best_correlation);
  370. // Adjust peak locations; cross-correlation lags start at 2.5 ms
  371. // (20 * fs_mult samples).
  372. best_correlation_index[0] += fs_mult_20;
  373. best_correlation_index[1] += fs_mult_20;
  374. best_correlation_index[2] += fs_mult_20;
  375. // Calculate distortion around the |kNumCorrelationCandidates| best lags.
  376. int distortion_scale = 0;
  377. for (size_t i = 0; i < kNumCorrelationCandidates; i++) {
  378. size_t min_index =
  379. std::max(fs_mult_20, best_correlation_index[i] - fs_mult_4);
  380. size_t max_index =
  381. std::min(fs_mult_120 - 1, best_correlation_index[i] + fs_mult_4);
  382. best_distortion_index[i] = DspHelper::MinDistortion(
  383. &(audio_history[signal_length - fs_mult_dist_len]), min_index,
  384. max_index, fs_mult_dist_len, &best_distortion_w32[i]);
  385. distortion_scale = std::max(16 - WebRtcSpl_NormW32(best_distortion_w32[i]),
  386. distortion_scale);
  387. }
  388. // Shift the distortion values to fit in 16 bits.
  389. WebRtcSpl_VectorBitShiftW32ToW16(best_distortion, kNumCorrelationCandidates,
  390. best_distortion_w32, distortion_scale);
  391. // Find the maximizing index |i| of the cost function
  392. // f[i] = best_correlation[i] / best_distortion[i].
  393. int32_t best_ratio = std::numeric_limits<int32_t>::min();
  394. size_t best_index = std::numeric_limits<size_t>::max();
  395. for (size_t i = 0; i < kNumCorrelationCandidates; ++i) {
  396. int32_t ratio;
  397. if (best_distortion[i] > 0) {
  398. ratio = (best_correlation[i] * (1 << 16)) / best_distortion[i];
  399. } else if (best_correlation[i] == 0) {
  400. ratio = 0; // No correlation set result to zero.
  401. } else {
  402. ratio = std::numeric_limits<int32_t>::max(); // Denominator is zero.
  403. }
  404. if (ratio > best_ratio) {
  405. best_index = i;
  406. best_ratio = ratio;
  407. }
  408. }
  409. size_t distortion_lag = best_distortion_index[best_index];
  410. size_t correlation_lag = best_correlation_index[best_index];
  411. max_lag_ = std::max(distortion_lag, correlation_lag);
  412. // Calculate the exact best correlation in the range between
  413. // |correlation_lag| and |distortion_lag|.
  414. correlation_length = std::max(std::min(distortion_lag + 10, fs_mult_120),
  415. static_cast<size_t>(60 * fs_mult));
  416. size_t start_index = std::min(distortion_lag, correlation_lag);
  417. size_t correlation_lags = static_cast<size_t>(
  418. WEBRTC_SPL_ABS_W16((distortion_lag - correlation_lag)) + 1);
  419. assert(correlation_lags <= static_cast<size_t>(99 * fs_mult + 1));
  420. for (size_t channel_ix = 0; channel_ix < num_channels_; ++channel_ix) {
  421. ChannelParameters& parameters = channel_parameters_[channel_ix];
  422. // Calculate suitable scaling.
  423. int16_t signal_max = WebRtcSpl_MaxAbsValueW16(
  424. &audio_history[signal_length - correlation_length - start_index -
  425. correlation_lags],
  426. correlation_length + start_index + correlation_lags - 1);
  427. int correlation_scale =
  428. (31 - WebRtcSpl_NormW32(signal_max * signal_max)) +
  429. (31 - WebRtcSpl_NormW32(static_cast<int32_t>(correlation_length))) - 31;
  430. correlation_scale = std::max(0, correlation_scale);
  431. // Calculate the correlation, store in |correlation_vector2|.
  432. WebRtcSpl_CrossCorrelation(
  433. correlation_vector2,
  434. &(audio_history[signal_length - correlation_length]),
  435. &(audio_history[signal_length - correlation_length - start_index]),
  436. correlation_length, correlation_lags, correlation_scale, -1);
  437. // Find maximizing index.
  438. best_index = WebRtcSpl_MaxIndexW32(correlation_vector2, correlation_lags);
  439. int32_t max_correlation = correlation_vector2[best_index];
  440. // Compensate index with start offset.
  441. best_index = best_index + start_index;
  442. // Calculate energies.
  443. int32_t energy1 = WebRtcSpl_DotProductWithScale(
  444. &(audio_history[signal_length - correlation_length]),
  445. &(audio_history[signal_length - correlation_length]),
  446. correlation_length, correlation_scale);
  447. int32_t energy2 = WebRtcSpl_DotProductWithScale(
  448. &(audio_history[signal_length - correlation_length - best_index]),
  449. &(audio_history[signal_length - correlation_length - best_index]),
  450. correlation_length, correlation_scale);
  451. // Calculate the correlation coefficient between the two portions of the
  452. // signal.
  453. int32_t corr_coefficient;
  454. if ((energy1 > 0) && (energy2 > 0)) {
  455. int energy1_scale = std::max(16 - WebRtcSpl_NormW32(energy1), 0);
  456. int energy2_scale = std::max(16 - WebRtcSpl_NormW32(energy2), 0);
  457. // Make sure total scaling is even (to simplify scale factor after sqrt).
  458. if ((energy1_scale + energy2_scale) & 1) {
  459. // If sum is odd, add 1 to make it even.
  460. energy1_scale += 1;
  461. }
  462. int32_t scaled_energy1 = energy1 >> energy1_scale;
  463. int32_t scaled_energy2 = energy2 >> energy2_scale;
  464. int16_t sqrt_energy_product = static_cast<int16_t>(
  465. WebRtcSpl_SqrtFloor(scaled_energy1 * scaled_energy2));
  466. // Calculate max_correlation / sqrt(energy1 * energy2) in Q14.
  467. int cc_shift = 14 - (energy1_scale + energy2_scale) / 2;
  468. max_correlation = WEBRTC_SPL_SHIFT_W32(max_correlation, cc_shift);
  469. corr_coefficient =
  470. WebRtcSpl_DivW32W16(max_correlation, sqrt_energy_product);
  471. // Cap at 1.0 in Q14.
  472. corr_coefficient = std::min(16384, corr_coefficient);
  473. } else {
  474. corr_coefficient = 0;
  475. }
  476. // Extract the two vectors expand_vector0 and expand_vector1 from
  477. // |audio_history|.
  478. size_t expansion_length = max_lag_ + overlap_length_;
  479. const int16_t* vector1 = &(audio_history[signal_length - expansion_length]);
  480. const int16_t* vector2 = vector1 - distortion_lag;
  481. // Normalize the second vector to the same energy as the first.
  482. energy1 = WebRtcSpl_DotProductWithScale(vector1, vector1, expansion_length,
  483. correlation_scale);
  484. energy2 = WebRtcSpl_DotProductWithScale(vector2, vector2, expansion_length,
  485. correlation_scale);
  486. // Confirm that amplitude ratio sqrt(energy1 / energy2) is within 0.5 - 2.0,
  487. // i.e., energy1 / energy2 is within 0.25 - 4.
  488. int16_t amplitude_ratio;
  489. if ((energy1 / 4 < energy2) && (energy1 > energy2 / 4)) {
  490. // Energy constraint fulfilled. Use both vectors and scale them
  491. // accordingly.
  492. int32_t scaled_energy2 = std::max(16 - WebRtcSpl_NormW32(energy2), 0);
  493. int32_t scaled_energy1 = scaled_energy2 - 13;
  494. // Calculate scaled_energy1 / scaled_energy2 in Q13.
  495. int32_t energy_ratio =
  496. WebRtcSpl_DivW32W16(WEBRTC_SPL_SHIFT_W32(energy1, -scaled_energy1),
  497. static_cast<int16_t>(energy2 >> scaled_energy2));
  498. // Calculate sqrt ratio in Q13 (sqrt of en1/en2 in Q26).
  499. amplitude_ratio =
  500. static_cast<int16_t>(WebRtcSpl_SqrtFloor(energy_ratio << 13));
  501. // Copy the two vectors and give them the same energy.
  502. parameters.expand_vector0.Clear();
  503. parameters.expand_vector0.PushBack(vector1, expansion_length);
  504. parameters.expand_vector1.Clear();
  505. if (parameters.expand_vector1.Size() < expansion_length) {
  506. parameters.expand_vector1.Extend(expansion_length -
  507. parameters.expand_vector1.Size());
  508. }
  509. std::unique_ptr<int16_t[]> temp_1(new int16_t[expansion_length]);
  510. WebRtcSpl_AffineTransformVector(
  511. temp_1.get(), const_cast<int16_t*>(vector2), amplitude_ratio, 4096,
  512. 13, expansion_length);
  513. parameters.expand_vector1.OverwriteAt(temp_1.get(), expansion_length, 0);
  514. } else {
  515. // Energy change constraint not fulfilled. Only use last vector.
  516. parameters.expand_vector0.Clear();
  517. parameters.expand_vector0.PushBack(vector1, expansion_length);
  518. // Copy from expand_vector0 to expand_vector1.
  519. parameters.expand_vector0.CopyTo(&parameters.expand_vector1);
  520. // Set the energy_ratio since it is used by muting slope.
  521. if ((energy1 / 4 < energy2) || (energy2 == 0)) {
  522. amplitude_ratio = 4096; // 0.5 in Q13.
  523. } else {
  524. amplitude_ratio = 16384; // 2.0 in Q13.
  525. }
  526. }
  527. // Set the 3 lag values.
  528. if (distortion_lag == correlation_lag) {
  529. expand_lags_[0] = distortion_lag;
  530. expand_lags_[1] = distortion_lag;
  531. expand_lags_[2] = distortion_lag;
  532. } else {
  533. // |distortion_lag| and |correlation_lag| are not equal; use different
  534. // combinations of the two.
  535. // First lag is |distortion_lag| only.
  536. expand_lags_[0] = distortion_lag;
  537. // Second lag is the average of the two.
  538. expand_lags_[1] = (distortion_lag + correlation_lag) / 2;
  539. // Third lag is the average again, but rounding towards |correlation_lag|.
  540. if (distortion_lag > correlation_lag) {
  541. expand_lags_[2] = (distortion_lag + correlation_lag - 1) / 2;
  542. } else {
  543. expand_lags_[2] = (distortion_lag + correlation_lag + 1) / 2;
  544. }
  545. }
  546. // Calculate the LPC and the gain of the filters.
  547. // Calculate kUnvoicedLpcOrder + 1 lags of the auto-correlation function.
  548. size_t temp_index =
  549. signal_length - fs_mult_lpc_analysis_len - kUnvoicedLpcOrder;
  550. // Copy signal to temporary vector to be able to pad with leading zeros.
  551. int16_t* temp_signal =
  552. new int16_t[fs_mult_lpc_analysis_len + kUnvoicedLpcOrder];
  553. memset(temp_signal, 0,
  554. sizeof(int16_t) * (fs_mult_lpc_analysis_len + kUnvoicedLpcOrder));
  555. memcpy(&temp_signal[kUnvoicedLpcOrder],
  556. &audio_history[temp_index + kUnvoicedLpcOrder],
  557. sizeof(int16_t) * fs_mult_lpc_analysis_len);
  558. CrossCorrelationWithAutoShift(
  559. &temp_signal[kUnvoicedLpcOrder], &temp_signal[kUnvoicedLpcOrder],
  560. fs_mult_lpc_analysis_len, kUnvoicedLpcOrder + 1, -1, auto_correlation);
  561. delete[] temp_signal;
  562. // Verify that variance is positive.
  563. if (auto_correlation[0] > 0) {
  564. // Estimate AR filter parameters using Levinson-Durbin algorithm;
  565. // kUnvoicedLpcOrder + 1 filter coefficients.
  566. int16_t stability =
  567. WebRtcSpl_LevinsonDurbin(auto_correlation, parameters.ar_filter,
  568. reflection_coeff, kUnvoicedLpcOrder);
  569. // Keep filter parameters only if filter is stable.
  570. if (stability != 1) {
  571. // Set first coefficient to 4096 (1.0 in Q12).
  572. parameters.ar_filter[0] = 4096;
  573. // Set remaining |kUnvoicedLpcOrder| coefficients to zero.
  574. WebRtcSpl_MemSetW16(parameters.ar_filter + 1, 0, kUnvoicedLpcOrder);
  575. }
  576. }
  577. if (channel_ix == 0) {
  578. // Extract a noise segment.
  579. size_t noise_length;
  580. if (distortion_lag < 40) {
  581. noise_length = 2 * distortion_lag + 30;
  582. } else {
  583. noise_length = distortion_lag + 30;
  584. }
  585. if (noise_length <= RandomVector::kRandomTableSize) {
  586. memcpy(random_vector, RandomVector::kRandomTable,
  587. sizeof(int16_t) * noise_length);
  588. } else {
  589. // Only applies to SWB where length could be larger than
  590. // |kRandomTableSize|.
  591. memcpy(random_vector, RandomVector::kRandomTable,
  592. sizeof(int16_t) * RandomVector::kRandomTableSize);
  593. assert(noise_length <= kMaxSampleRate / 8000 * 120 + 30);
  594. random_vector_->IncreaseSeedIncrement(2);
  595. random_vector_->Generate(
  596. noise_length - RandomVector::kRandomTableSize,
  597. &random_vector[RandomVector::kRandomTableSize]);
  598. }
  599. }
  600. // Set up state vector and calculate scale factor for unvoiced filtering.
  601. memcpy(parameters.ar_filter_state,
  602. &(audio_history[signal_length - kUnvoicedLpcOrder]),
  603. sizeof(int16_t) * kUnvoicedLpcOrder);
  604. memcpy(unvoiced_vector - kUnvoicedLpcOrder,
  605. &(audio_history[signal_length - 128 - kUnvoicedLpcOrder]),
  606. sizeof(int16_t) * kUnvoicedLpcOrder);
  607. WebRtcSpl_FilterMAFastQ12(&audio_history[signal_length - 128],
  608. unvoiced_vector, parameters.ar_filter,
  609. kUnvoicedLpcOrder + 1, 128);
  610. const int unvoiced_max_abs = [&] {
  611. const int16_t max_abs = WebRtcSpl_MaxAbsValueW16(unvoiced_vector, 128);
  612. // Since WebRtcSpl_MaxAbsValueW16 returns 2^15 - 1 when the input contains
  613. // -2^15, we have to conservatively bump the return value by 1
  614. // if it is 2^15 - 1.
  615. return max_abs == WEBRTC_SPL_WORD16_MAX ? max_abs + 1 : max_abs;
  616. }();
  617. // Pick the smallest n such that 2^n > unvoiced_max_abs; then the maximum
  618. // value of the dot product is less than 2^7 * 2^(2*n) = 2^(2*n + 7), so to
  619. // prevent overflows we want 2n + 7 <= 31, which means we should shift by
  620. // 2n + 7 - 31 bits, if this value is greater than zero.
  621. int unvoiced_prescale =
  622. std::max(0, 2 * WebRtcSpl_GetSizeInBits(unvoiced_max_abs) - 24);
  623. int32_t unvoiced_energy = WebRtcSpl_DotProductWithScale(
  624. unvoiced_vector, unvoiced_vector, 128, unvoiced_prescale);
  625. // Normalize |unvoiced_energy| to 28 or 29 bits to preserve sqrt() accuracy.
  626. int16_t unvoiced_scale = WebRtcSpl_NormW32(unvoiced_energy) - 3;
  627. // Make sure we do an odd number of shifts since we already have 7 shifts
  628. // from dividing with 128 earlier. This will make the total scale factor
  629. // even, which is suitable for the sqrt.
  630. unvoiced_scale += ((unvoiced_scale & 0x1) ^ 0x1);
  631. unvoiced_energy = WEBRTC_SPL_SHIFT_W32(unvoiced_energy, unvoiced_scale);
  632. int16_t unvoiced_gain =
  633. static_cast<int16_t>(WebRtcSpl_SqrtFloor(unvoiced_energy));
  634. parameters.ar_gain_scale =
  635. 13 + (unvoiced_scale + 7 - unvoiced_prescale) / 2;
  636. parameters.ar_gain = unvoiced_gain;
  637. // Calculate voice_mix_factor from corr_coefficient.
  638. // Let x = corr_coefficient. Then, we compute:
  639. // if (x > 0.48)
  640. // voice_mix_factor = (-5179 + 19931x - 16422x^2 + 5776x^3) / 4096;
  641. // else
  642. // voice_mix_factor = 0;
  643. if (corr_coefficient > 7875) {
  644. int16_t x1, x2, x3;
  645. // |corr_coefficient| is in Q14.
  646. x1 = static_cast<int16_t>(corr_coefficient);
  647. x2 = (x1 * x1) >> 14; // Shift 14 to keep result in Q14.
  648. x3 = (x1 * x2) >> 14;
  649. static const int kCoefficients[4] = {-5179, 19931, -16422, 5776};
  650. int32_t temp_sum = kCoefficients[0] * 16384;
  651. temp_sum += kCoefficients[1] * x1;
  652. temp_sum += kCoefficients[2] * x2;
  653. temp_sum += kCoefficients[3] * x3;
  654. parameters.voice_mix_factor =
  655. static_cast<int16_t>(std::min(temp_sum / 4096, 16384));
  656. parameters.voice_mix_factor =
  657. std::max(parameters.voice_mix_factor, static_cast<int16_t>(0));
  658. } else {
  659. parameters.voice_mix_factor = 0;
  660. }
  661. // Calculate muting slope. Reuse value from earlier scaling of
  662. // |expand_vector0| and |expand_vector1|.
  663. int16_t slope = amplitude_ratio;
  664. if (slope > 12288) {
  665. // slope > 1.5.
  666. // Calculate (1 - (1 / slope)) / distortion_lag =
  667. // (slope - 1) / (distortion_lag * slope).
  668. // |slope| is in Q13, so 1 corresponds to 8192. Shift up to Q25 before
  669. // the division.
  670. // Shift the denominator from Q13 to Q5 before the division. The result of
  671. // the division will then be in Q20.
  672. int16_t denom =
  673. rtc::saturated_cast<int16_t>((distortion_lag * slope) >> 8);
  674. int temp_ratio = WebRtcSpl_DivW32W16((slope - 8192) << 12, denom);
  675. if (slope > 14746) {
  676. // slope > 1.8.
  677. // Divide by 2, with proper rounding.
  678. parameters.mute_slope = (temp_ratio + 1) / 2;
  679. } else {
  680. // Divide by 8, with proper rounding.
  681. parameters.mute_slope = (temp_ratio + 4) / 8;
  682. }
  683. parameters.onset = true;
  684. } else {
  685. // Calculate (1 - slope) / distortion_lag.
  686. // Shift |slope| by 7 to Q20 before the division. The result is in Q20.
  687. parameters.mute_slope = WebRtcSpl_DivW32W16(
  688. (8192 - slope) * 128, static_cast<int16_t>(distortion_lag));
  689. if (parameters.voice_mix_factor <= 13107) {
  690. // Make sure the mute factor decreases from 1.0 to 0.9 in no more than
  691. // 6.25 ms.
  692. // mute_slope >= 0.005 / fs_mult in Q20.
  693. parameters.mute_slope = std::max(5243 / fs_mult, parameters.mute_slope);
  694. } else if (slope > 8028) {
  695. parameters.mute_slope = 0;
  696. }
  697. parameters.onset = false;
  698. }
  699. }
  700. }
  701. Expand::ChannelParameters::ChannelParameters()
  702. : mute_factor(16384),
  703. ar_gain(0),
  704. ar_gain_scale(0),
  705. voice_mix_factor(0),
  706. current_voice_mix_factor(0),
  707. onset(false),
  708. mute_slope(0) {
  709. memset(ar_filter, 0, sizeof(ar_filter));
  710. memset(ar_filter_state, 0, sizeof(ar_filter_state));
  711. }
  712. void Expand::Correlation(const int16_t* input,
  713. size_t input_length,
  714. int16_t* output) const {
  715. // Set parameters depending on sample rate.
  716. const int16_t* filter_coefficients;
  717. size_t num_coefficients;
  718. int16_t downsampling_factor;
  719. if (fs_hz_ == 8000) {
  720. num_coefficients = 3;
  721. downsampling_factor = 2;
  722. filter_coefficients = DspHelper::kDownsample8kHzTbl;
  723. } else if (fs_hz_ == 16000) {
  724. num_coefficients = 5;
  725. downsampling_factor = 4;
  726. filter_coefficients = DspHelper::kDownsample16kHzTbl;
  727. } else if (fs_hz_ == 32000) {
  728. num_coefficients = 7;
  729. downsampling_factor = 8;
  730. filter_coefficients = DspHelper::kDownsample32kHzTbl;
  731. } else { // fs_hz_ == 48000.
  732. num_coefficients = 7;
  733. downsampling_factor = 12;
  734. filter_coefficients = DspHelper::kDownsample48kHzTbl;
  735. }
  736. // Correlate from lag 10 to lag 60 in downsampled domain.
  737. // (Corresponds to 20-120 for narrow-band, 40-240 for wide-band, and so on.)
  738. static const size_t kCorrelationStartLag = 10;
  739. static const size_t kNumCorrelationLags = 54;
  740. static const size_t kCorrelationLength = 60;
  741. // Downsample to 4 kHz sample rate.
  742. static const size_t kDownsampledLength =
  743. kCorrelationStartLag + kNumCorrelationLags + kCorrelationLength;
  744. int16_t downsampled_input[kDownsampledLength];
  745. static const size_t kFilterDelay = 0;
  746. WebRtcSpl_DownsampleFast(
  747. input + input_length - kDownsampledLength * downsampling_factor,
  748. kDownsampledLength * downsampling_factor, downsampled_input,
  749. kDownsampledLength, filter_coefficients, num_coefficients,
  750. downsampling_factor, kFilterDelay);
  751. // Normalize |downsampled_input| to using all 16 bits.
  752. int16_t max_value =
  753. WebRtcSpl_MaxAbsValueW16(downsampled_input, kDownsampledLength);
  754. int16_t norm_shift = 16 - WebRtcSpl_NormW32(max_value);
  755. WebRtcSpl_VectorBitShiftW16(downsampled_input, kDownsampledLength,
  756. downsampled_input, norm_shift);
  757. int32_t correlation[kNumCorrelationLags];
  758. CrossCorrelationWithAutoShift(
  759. &downsampled_input[kDownsampledLength - kCorrelationLength],
  760. &downsampled_input[kDownsampledLength - kCorrelationLength -
  761. kCorrelationStartLag],
  762. kCorrelationLength, kNumCorrelationLags, -1, correlation);
  763. // Normalize and move data from 32-bit to 16-bit vector.
  764. int32_t max_correlation =
  765. WebRtcSpl_MaxAbsValueW32(correlation, kNumCorrelationLags);
  766. int16_t norm_shift2 = static_cast<int16_t>(
  767. std::max(18 - WebRtcSpl_NormW32(max_correlation), 0));
  768. WebRtcSpl_VectorBitShiftW32ToW16(output, kNumCorrelationLags, correlation,
  769. norm_shift2);
  770. }
  771. void Expand::UpdateLagIndex() {
  772. current_lag_index_ = current_lag_index_ + lag_index_direction_;
  773. // Change direction if needed.
  774. if (current_lag_index_ <= 0) {
  775. lag_index_direction_ = 1;
  776. }
  777. if (current_lag_index_ >= kNumLags - 1) {
  778. lag_index_direction_ = -1;
  779. }
  780. }
  781. Expand* ExpandFactory::Create(BackgroundNoise* background_noise,
  782. SyncBuffer* sync_buffer,
  783. RandomVector* random_vector,
  784. StatisticsCalculator* statistics,
  785. int fs,
  786. size_t num_channels) const {
  787. return new Expand(background_noise, sync_buffer, random_vector, statistics,
  788. fs, num_channels);
  789. }
  790. void Expand::GenerateRandomVector(int16_t seed_increment,
  791. size_t length,
  792. int16_t* random_vector) {
  793. // TODO(turajs): According to hlundin The loop should not be needed. Should be
  794. // just as good to generate all of the vector in one call.
  795. size_t samples_generated = 0;
  796. const size_t kMaxRandSamples = RandomVector::kRandomTableSize;
  797. while (samples_generated < length) {
  798. size_t rand_length = std::min(length - samples_generated, kMaxRandSamples);
  799. random_vector_->IncreaseSeedIncrement(seed_increment);
  800. random_vector_->Generate(rand_length, &random_vector[samples_generated]);
  801. samples_generated += rand_length;
  802. }
  803. }
  804. } // namespace webrtc