dyadic_decimator.h 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*
  2. * Copyright (c) 2013 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. #ifndef MODULES_AUDIO_PROCESSING_TRANSIENT_DYADIC_DECIMATOR_H_
  11. #define MODULES_AUDIO_PROCESSING_TRANSIENT_DYADIC_DECIMATOR_H_
  12. #include <cstdlib>
  13. // Provides a set of static methods to perform dyadic decimations.
  14. namespace webrtc {
  15. // Returns the proper length of the output buffer that you should use for the
  16. // given |in_length| and decimation |odd_sequence|.
  17. // Return -1 on error.
  18. inline size_t GetOutLengthToDyadicDecimate(size_t in_length,
  19. bool odd_sequence) {
  20. size_t out_length = in_length / 2;
  21. if (in_length % 2 == 1 && !odd_sequence) {
  22. ++out_length;
  23. }
  24. return out_length;
  25. }
  26. // Performs a dyadic decimation: removes every odd/even member of a sequence
  27. // halving its overall length.
  28. // Arguments:
  29. // in: array of |in_length|.
  30. // odd_sequence: If false, the odd members will be removed (1, 3, 5, ...);
  31. // if true, the even members will be removed (0, 2, 4, ...).
  32. // out: array of |out_length|. |out_length| must be large enough to
  33. // hold the decimated output. The necessary length can be provided by
  34. // GetOutLengthToDyadicDecimate().
  35. // Must be previously allocated.
  36. // Returns the number of output samples, -1 on error.
  37. template <typename T>
  38. static size_t DyadicDecimate(const T* in,
  39. size_t in_length,
  40. bool odd_sequence,
  41. T* out,
  42. size_t out_length) {
  43. size_t half_length = GetOutLengthToDyadicDecimate(in_length, odd_sequence);
  44. if (!in || !out || in_length <= 0 || out_length < half_length) {
  45. return 0;
  46. }
  47. size_t output_samples = 0;
  48. size_t index_adjustment = odd_sequence ? 1 : 0;
  49. for (output_samples = 0; output_samples < half_length; ++output_samples) {
  50. out[output_samples] = in[output_samples * 2 + index_adjustment];
  51. }
  52. return output_samples;
  53. }
  54. } // namespace webrtc
  55. #endif // MODULES_AUDIO_PROCESSING_TRANSIENT_DYADIC_DECIMATOR_H_