sample_tests.cpp 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*
  2. * Copyright (C) 2018 The Android Open Source Project
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include <array>
  17. #include <climits>
  18. #include <math.h>
  19. #include <audio_utils/sample.h>
  20. #include <gtest/gtest.h>
  21. static_assert(sizeof(sample_minifloat_t) == sizeof(uint16_t),
  22. "sizeof(sample_minifloat_t != sizeof(uint16_t");
  23. static constexpr int signum(float f)
  24. {
  25. return (f > 0) - (f < 0);
  26. }
  27. TEST(audio_utils_sample, Convert)
  28. {
  29. std::vector<float> fvec;
  30. // verify minifloat <-> float is a bijection, and monotonic as float
  31. for (int i = 0; i <= 0xFFFF; i++) {
  32. // construct floats in order
  33. const int val = i < 0x8000 ? 0xFFFF - i : i ^ 0x8000;
  34. // TODO shouldn't depend on representation in order to skip negative zero
  35. if (val == 0x8000) {
  36. // This is an undefined value and so we won't test its behavior
  37. continue;
  38. }
  39. // TODO reinterpret_cast<sample_minifloat_t>(val) fails
  40. const sample_minifloat_t in = (sample_minifloat_t) val;
  41. const float f = float_from_sample(in);
  42. const sample_minifloat_t out = sample_from_float(f);
  43. ASSERT_EQ(in, out);
  44. fvec.push_back(f);
  45. }
  46. // no longer needed since we construct floats in order
  47. // #include <algorithm>
  48. // std::sort(fvec.begin(), fvec.end());
  49. float prev = -2.0f;
  50. for (auto curr : fvec) {
  51. // LT instead of LE because no negative zero
  52. ASSERT_LT(prev, curr);
  53. int signum_prev = signum(prev);
  54. int signum_curr = signum(curr);
  55. ASSERT_LE(signum_prev, signum_curr);
  56. if (signum_prev == signum_curr) {
  57. // confirm ratio between adjacent values (3:45 of "Will it float?" video)
  58. float ratio = curr / prev;
  59. float lower, upper;
  60. // normal
  61. if (fabsf(curr) >= 0.001f) {
  62. upper = 1.005f;
  63. lower = 0.995f;
  64. // denormal
  65. } else {
  66. upper = 2.0f;
  67. lower = 0.5f;
  68. }
  69. ASSERT_GE(ratio, lower) << "prev " << prev << " curr " << curr;
  70. ASSERT_LE(ratio, upper) << "prev " << prev << " curr " << curr;
  71. }
  72. prev = curr;
  73. }
  74. ASSERT_LT(prev, 2.0f);
  75. }