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.

380 lines
17 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/merge.h"
  11. #include <assert.h>
  12. #include <string.h> // memmove, memcpy, memset, size_t
  13. #include <algorithm> // min, max
  14. #include <memory>
  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/cross_correlation.h"
  18. #include "modules/audio_coding/neteq/dsp_helper.h"
  19. #include "modules/audio_coding/neteq/expand.h"
  20. #include "modules/audio_coding/neteq/sync_buffer.h"
  21. #include "rtc_base/numerics/safe_conversions.h"
  22. #include "rtc_base/numerics/safe_minmax.h"
  23. namespace webrtc {
  24. Merge::Merge(int fs_hz,
  25. size_t num_channels,
  26. Expand* expand,
  27. SyncBuffer* sync_buffer)
  28. : fs_hz_(fs_hz),
  29. num_channels_(num_channels),
  30. fs_mult_(fs_hz_ / 8000),
  31. timestamps_per_call_(static_cast<size_t>(fs_hz_ / 100)),
  32. expand_(expand),
  33. sync_buffer_(sync_buffer),
  34. expanded_(num_channels_) {
  35. assert(num_channels_ > 0);
  36. }
  37. Merge::~Merge() = default;
  38. size_t Merge::Process(int16_t* input,
  39. size_t input_length,
  40. AudioMultiVector* output) {
  41. // TODO(hlundin): Change to an enumerator and skip assert.
  42. assert(fs_hz_ == 8000 || fs_hz_ == 16000 || fs_hz_ == 32000 ||
  43. fs_hz_ == 48000);
  44. assert(fs_hz_ <= kMaxSampleRate); // Should not be possible.
  45. size_t old_length;
  46. size_t expand_period;
  47. // Get expansion data to overlap and mix with.
  48. size_t expanded_length = GetExpandedSignal(&old_length, &expand_period);
  49. // Transfer input signal to an AudioMultiVector.
  50. AudioMultiVector input_vector(num_channels_);
  51. input_vector.PushBackInterleaved(
  52. rtc::ArrayView<const int16_t>(input, input_length));
  53. size_t input_length_per_channel = input_vector.Size();
  54. assert(input_length_per_channel == input_length / num_channels_);
  55. size_t best_correlation_index = 0;
  56. size_t output_length = 0;
  57. std::unique_ptr<int16_t[]> input_channel(
  58. new int16_t[input_length_per_channel]);
  59. std::unique_ptr<int16_t[]> expanded_channel(new int16_t[expanded_length]);
  60. for (size_t channel = 0; channel < num_channels_; ++channel) {
  61. input_vector[channel].CopyTo(input_length_per_channel, 0,
  62. input_channel.get());
  63. expanded_[channel].CopyTo(expanded_length, 0, expanded_channel.get());
  64. const int16_t new_mute_factor = std::min<int16_t>(
  65. 16384, SignalScaling(input_channel.get(), input_length_per_channel,
  66. expanded_channel.get()));
  67. if (channel == 0) {
  68. // Downsample, correlate, and find strongest correlation period for the
  69. // master (i.e., first) channel only.
  70. // Downsample to 4kHz sample rate.
  71. Downsample(input_channel.get(), input_length_per_channel,
  72. expanded_channel.get(), expanded_length);
  73. // Calculate the lag of the strongest correlation period.
  74. best_correlation_index = CorrelateAndPeakSearch(
  75. old_length, input_length_per_channel, expand_period);
  76. }
  77. temp_data_.resize(input_length_per_channel + best_correlation_index);
  78. int16_t* decoded_output = temp_data_.data() + best_correlation_index;
  79. // Mute the new decoded data if needed (and unmute it linearly).
  80. // This is the overlapping part of expanded_signal.
  81. size_t interpolation_length =
  82. std::min(kMaxCorrelationLength * fs_mult_,
  83. expanded_length - best_correlation_index);
  84. interpolation_length =
  85. std::min(interpolation_length, input_length_per_channel);
  86. RTC_DCHECK_LE(new_mute_factor, 16384);
  87. int16_t mute_factor =
  88. std::max(expand_->MuteFactor(channel), new_mute_factor);
  89. RTC_DCHECK_GE(mute_factor, 0);
  90. if (mute_factor < 16384) {
  91. // Set a suitable muting slope (Q20). 0.004 for NB, 0.002 for WB,
  92. // and so on, or as fast as it takes to come back to full gain within the
  93. // frame length.
  94. const int back_to_fullscale_inc = static_cast<int>(
  95. ((16384 - mute_factor) << 6) / input_length_per_channel);
  96. const int increment = std::max(4194 / fs_mult_, back_to_fullscale_inc);
  97. mute_factor = static_cast<int16_t>(DspHelper::RampSignal(
  98. input_channel.get(), interpolation_length, mute_factor, increment));
  99. DspHelper::UnmuteSignal(&input_channel[interpolation_length],
  100. input_length_per_channel - interpolation_length,
  101. &mute_factor, increment,
  102. &decoded_output[interpolation_length]);
  103. } else {
  104. // No muting needed.
  105. memmove(
  106. &decoded_output[interpolation_length],
  107. &input_channel[interpolation_length],
  108. sizeof(int16_t) * (input_length_per_channel - interpolation_length));
  109. }
  110. // Do overlap and mix linearly.
  111. int16_t increment =
  112. static_cast<int16_t>(16384 / (interpolation_length + 1)); // In Q14.
  113. int16_t local_mute_factor = 16384 - increment;
  114. memmove(temp_data_.data(), expanded_channel.get(),
  115. sizeof(int16_t) * best_correlation_index);
  116. DspHelper::CrossFade(&expanded_channel[best_correlation_index],
  117. input_channel.get(), interpolation_length,
  118. &local_mute_factor, increment, decoded_output);
  119. output_length = best_correlation_index + input_length_per_channel;
  120. if (channel == 0) {
  121. assert(output->Empty()); // Output should be empty at this point.
  122. output->AssertSize(output_length);
  123. } else {
  124. assert(output->Size() == output_length);
  125. }
  126. (*output)[channel].OverwriteAt(temp_data_.data(), output_length, 0);
  127. }
  128. // Copy back the first part of the data to |sync_buffer_| and remove it from
  129. // |output|.
  130. sync_buffer_->ReplaceAtIndex(*output, old_length, sync_buffer_->next_index());
  131. output->PopFront(old_length);
  132. // Return new added length. |old_length| samples were borrowed from
  133. // |sync_buffer_|.
  134. RTC_DCHECK_GE(output_length, old_length);
  135. return output_length - old_length;
  136. }
  137. size_t Merge::GetExpandedSignal(size_t* old_length, size_t* expand_period) {
  138. // Check how much data that is left since earlier.
  139. *old_length = sync_buffer_->FutureLength();
  140. // Should never be less than overlap_length.
  141. assert(*old_length >= expand_->overlap_length());
  142. // Generate data to merge the overlap with using expand.
  143. expand_->SetParametersForMergeAfterExpand();
  144. if (*old_length >= 210 * kMaxSampleRate / 8000) {
  145. // TODO(hlundin): Write test case for this.
  146. // The number of samples available in the sync buffer is more than what fits
  147. // in expanded_signal. Keep the first 210 * kMaxSampleRate / 8000 samples,
  148. // but shift them towards the end of the buffer. This is ok, since all of
  149. // the buffer will be expand data anyway, so as long as the beginning is
  150. // left untouched, we're fine.
  151. size_t length_diff = *old_length - 210 * kMaxSampleRate / 8000;
  152. sync_buffer_->InsertZerosAtIndex(length_diff, sync_buffer_->next_index());
  153. *old_length = 210 * kMaxSampleRate / 8000;
  154. // This is the truncated length.
  155. }
  156. // This assert should always be true thanks to the if statement above.
  157. assert(210 * kMaxSampleRate / 8000 >= *old_length);
  158. AudioMultiVector expanded_temp(num_channels_);
  159. expand_->Process(&expanded_temp);
  160. *expand_period = expanded_temp.Size(); // Samples per channel.
  161. expanded_.Clear();
  162. // Copy what is left since earlier into the expanded vector.
  163. expanded_.PushBackFromIndex(*sync_buffer_, sync_buffer_->next_index());
  164. assert(expanded_.Size() == *old_length);
  165. assert(expanded_temp.Size() > 0);
  166. // Do "ugly" copy and paste from the expanded in order to generate more data
  167. // to correlate (but not interpolate) with.
  168. const size_t required_length = static_cast<size_t>((120 + 80 + 2) * fs_mult_);
  169. if (expanded_.Size() < required_length) {
  170. while (expanded_.Size() < required_length) {
  171. // Append one more pitch period each time.
  172. expanded_.PushBack(expanded_temp);
  173. }
  174. // Trim the length to exactly |required_length|.
  175. expanded_.PopBack(expanded_.Size() - required_length);
  176. }
  177. assert(expanded_.Size() >= required_length);
  178. return required_length;
  179. }
  180. int16_t Merge::SignalScaling(const int16_t* input,
  181. size_t input_length,
  182. const int16_t* expanded_signal) const {
  183. // Adjust muting factor if new vector is more or less of the BGN energy.
  184. const auto mod_input_length = rtc::SafeMin<size_t>(
  185. 64 * rtc::dchecked_cast<size_t>(fs_mult_), input_length);
  186. const int16_t expanded_max =
  187. WebRtcSpl_MaxAbsValueW16(expanded_signal, mod_input_length);
  188. int32_t factor =
  189. (expanded_max * expanded_max) / (std::numeric_limits<int32_t>::max() /
  190. static_cast<int32_t>(mod_input_length));
  191. const int expanded_shift = factor == 0 ? 0 : 31 - WebRtcSpl_NormW32(factor);
  192. int32_t energy_expanded = WebRtcSpl_DotProductWithScale(
  193. expanded_signal, expanded_signal, mod_input_length, expanded_shift);
  194. // Calculate energy of input signal.
  195. const int16_t input_max = WebRtcSpl_MaxAbsValueW16(input, mod_input_length);
  196. factor = (input_max * input_max) / (std::numeric_limits<int32_t>::max() /
  197. static_cast<int32_t>(mod_input_length));
  198. const int input_shift = factor == 0 ? 0 : 31 - WebRtcSpl_NormW32(factor);
  199. int32_t energy_input = WebRtcSpl_DotProductWithScale(
  200. input, input, mod_input_length, input_shift);
  201. // Align to the same Q-domain.
  202. if (input_shift > expanded_shift) {
  203. energy_expanded = energy_expanded >> (input_shift - expanded_shift);
  204. } else {
  205. energy_input = energy_input >> (expanded_shift - input_shift);
  206. }
  207. // Calculate muting factor to use for new frame.
  208. int16_t mute_factor;
  209. if (energy_input > energy_expanded) {
  210. // Normalize |energy_input| to 14 bits.
  211. int16_t temp_shift = WebRtcSpl_NormW32(energy_input) - 17;
  212. energy_input = WEBRTC_SPL_SHIFT_W32(energy_input, temp_shift);
  213. // Put |energy_expanded| in a domain 14 higher, so that
  214. // energy_expanded / energy_input is in Q14.
  215. energy_expanded = WEBRTC_SPL_SHIFT_W32(energy_expanded, temp_shift + 14);
  216. // Calculate sqrt(energy_expanded / energy_input) in Q14.
  217. mute_factor = static_cast<int16_t>(
  218. WebRtcSpl_SqrtFloor((energy_expanded / energy_input) << 14));
  219. } else {
  220. // Set to 1 (in Q14) when |expanded| has higher energy than |input|.
  221. mute_factor = 16384;
  222. }
  223. return mute_factor;
  224. }
  225. // TODO(hlundin): There are some parameter values in this method that seem
  226. // strange. Compare with Expand::Correlation.
  227. void Merge::Downsample(const int16_t* input,
  228. size_t input_length,
  229. const int16_t* expanded_signal,
  230. size_t expanded_length) {
  231. const int16_t* filter_coefficients;
  232. size_t num_coefficients;
  233. int decimation_factor = fs_hz_ / 4000;
  234. static const size_t kCompensateDelay = 0;
  235. size_t length_limit = static_cast<size_t>(fs_hz_ / 100); // 10 ms in samples.
  236. if (fs_hz_ == 8000) {
  237. filter_coefficients = DspHelper::kDownsample8kHzTbl;
  238. num_coefficients = 3;
  239. } else if (fs_hz_ == 16000) {
  240. filter_coefficients = DspHelper::kDownsample16kHzTbl;
  241. num_coefficients = 5;
  242. } else if (fs_hz_ == 32000) {
  243. filter_coefficients = DspHelper::kDownsample32kHzTbl;
  244. num_coefficients = 7;
  245. } else { // fs_hz_ == 48000
  246. filter_coefficients = DspHelper::kDownsample48kHzTbl;
  247. num_coefficients = 7;
  248. }
  249. size_t signal_offset = num_coefficients - 1;
  250. WebRtcSpl_DownsampleFast(
  251. &expanded_signal[signal_offset], expanded_length - signal_offset,
  252. expanded_downsampled_, kExpandDownsampLength, filter_coefficients,
  253. num_coefficients, decimation_factor, kCompensateDelay);
  254. if (input_length <= length_limit) {
  255. // Not quite long enough, so we have to cheat a bit.
  256. // If the input is really short, we'll just use the input length as is, and
  257. // won't bother with correcting for the offset. This is clearly a
  258. // pathological case, and the signal quality will suffer.
  259. const size_t temp_len = input_length > signal_offset
  260. ? input_length - signal_offset
  261. : input_length;
  262. // TODO(hlundin): Should |downsamp_temp_len| be corrected for round-off
  263. // errors? I.e., (temp_len + decimation_factor - 1) / decimation_factor?
  264. size_t downsamp_temp_len = temp_len / decimation_factor;
  265. WebRtcSpl_DownsampleFast(&input[signal_offset], temp_len,
  266. input_downsampled_, downsamp_temp_len,
  267. filter_coefficients, num_coefficients,
  268. decimation_factor, kCompensateDelay);
  269. memset(&input_downsampled_[downsamp_temp_len], 0,
  270. sizeof(int16_t) * (kInputDownsampLength - downsamp_temp_len));
  271. } else {
  272. WebRtcSpl_DownsampleFast(
  273. &input[signal_offset], input_length - signal_offset, input_downsampled_,
  274. kInputDownsampLength, filter_coefficients, num_coefficients,
  275. decimation_factor, kCompensateDelay);
  276. }
  277. }
  278. size_t Merge::CorrelateAndPeakSearch(size_t start_position,
  279. size_t input_length,
  280. size_t expand_period) const {
  281. // Calculate correlation without any normalization.
  282. const size_t max_corr_length = kMaxCorrelationLength;
  283. size_t stop_position_downsamp =
  284. std::min(max_corr_length, expand_->max_lag() / (fs_mult_ * 2) + 1);
  285. int32_t correlation[kMaxCorrelationLength];
  286. CrossCorrelationWithAutoShift(input_downsampled_, expanded_downsampled_,
  287. kInputDownsampLength, stop_position_downsamp, 1,
  288. correlation);
  289. // Normalize correlation to 14 bits and copy to a 16-bit array.
  290. const size_t pad_length = expand_->overlap_length() - 1;
  291. const size_t correlation_buffer_size = 2 * pad_length + kMaxCorrelationLength;
  292. std::unique_ptr<int16_t[]> correlation16(
  293. new int16_t[correlation_buffer_size]);
  294. memset(correlation16.get(), 0, correlation_buffer_size * sizeof(int16_t));
  295. int16_t* correlation_ptr = &correlation16[pad_length];
  296. int32_t max_correlation =
  297. WebRtcSpl_MaxAbsValueW32(correlation, stop_position_downsamp);
  298. int norm_shift = std::max(0, 17 - WebRtcSpl_NormW32(max_correlation));
  299. WebRtcSpl_VectorBitShiftW32ToW16(correlation_ptr, stop_position_downsamp,
  300. correlation, norm_shift);
  301. // Calculate allowed starting point for peak finding.
  302. // The peak location bestIndex must fulfill two criteria:
  303. // (1) w16_bestIndex + input_length <
  304. // timestamps_per_call_ + expand_->overlap_length();
  305. // (2) w16_bestIndex + input_length < start_position.
  306. size_t start_index = timestamps_per_call_ + expand_->overlap_length();
  307. start_index = std::max(start_position, start_index);
  308. start_index = (input_length > start_index) ? 0 : (start_index - input_length);
  309. // Downscale starting index to 4kHz domain. (fs_mult_ * 2 = fs_hz_ / 4000.)
  310. size_t start_index_downsamp = start_index / (fs_mult_ * 2);
  311. // Calculate a modified |stop_position_downsamp| to account for the increased
  312. // start index |start_index_downsamp| and the effective array length.
  313. size_t modified_stop_pos =
  314. std::min(stop_position_downsamp,
  315. kMaxCorrelationLength + pad_length - start_index_downsamp);
  316. size_t best_correlation_index;
  317. int16_t best_correlation;
  318. static const size_t kNumCorrelationCandidates = 1;
  319. DspHelper::PeakDetection(&correlation_ptr[start_index_downsamp],
  320. modified_stop_pos, kNumCorrelationCandidates,
  321. fs_mult_, &best_correlation_index,
  322. &best_correlation);
  323. // Compensate for modified start index.
  324. best_correlation_index += start_index;
  325. // Ensure that underrun does not occur for 10ms case => we have to get at
  326. // least 10ms + overlap . (This should never happen thanks to the above
  327. // modification of peak-finding starting point.)
  328. while (((best_correlation_index + input_length) <
  329. (timestamps_per_call_ + expand_->overlap_length())) ||
  330. ((best_correlation_index + input_length) < start_position)) {
  331. assert(false); // Should never happen.
  332. best_correlation_index += expand_period; // Jump one lag ahead.
  333. }
  334. return best_correlation_index;
  335. }
  336. size_t Merge::RequiredFutureSamples() {
  337. return fs_hz_ / 100 * num_channels_; // 10 ms.
  338. }
  339. } // namespace webrtc