half_float_maker_unittest.cc 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // Copyright 2017 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include <math.h>
  5. #include "media/video/half_float_maker.h"
  6. #include "testing/gtest/include/gtest/gtest.h"
  7. namespace media {
  8. class HalfFloatMakerTest : public testing::Test {};
  9. // Convert an IEEE 754 half-float to a double value
  10. // that we can do math on.
  11. double FromHalfFloat(uint16_t half_float) {
  12. if (!half_float)
  13. return 0.0;
  14. int sign = (half_float & 0x8000) ? -1 : 1;
  15. int exponent = (half_float >> 10) & 0x1F;
  16. int fraction = half_float & 0x3FF;
  17. if (exponent == 0) {
  18. return pow(2.0, -24.0) * fraction;
  19. } else if (exponent == 0x1F) {
  20. return sign * 1000000000000.0;
  21. } else {
  22. return pow(2.0, exponent - 25) * (0x400 + fraction);
  23. }
  24. }
  25. TEST_F(HalfFloatMakerTest, MakeHalfFloatTest) {
  26. unsigned short integers[1 << 16];
  27. unsigned short half_floats[1 << 16];
  28. for (int bits = 9; bits <= 16; bits++) {
  29. std::unique_ptr<media::HalfFloatMaker> half_float_maker;
  30. half_float_maker = media::HalfFloatMaker::NewHalfFloatMaker(bits);
  31. int num_values = 1 << bits;
  32. for (int i = 0; i < num_values; i++)
  33. integers[i] = i;
  34. half_float_maker->MakeHalfFloats(integers, num_values, half_floats);
  35. // Multiplier to converting integers to 0.0..1.0 range.
  36. double multiplier = 1.0 / (num_values - 1);
  37. for (int i = 0; i < num_values; i++) {
  38. // This value is in range 0..1
  39. float value = integers[i] * multiplier;
  40. // Reverse the effect of offset and multiplier to get the expected
  41. // output value from the half-float converter.
  42. float expected_value =
  43. value / half_float_maker->Multiplier() + half_float_maker->Offset();
  44. EXPECT_EQ(integers[i], i);
  45. // We expect the result to be within +/- one least-significant bit.
  46. // Within the range we care about, half-floats values and
  47. // their representation both sort in the same order, so we
  48. // can just add one to get the next bigger half-float.
  49. float expected_precision =
  50. FromHalfFloat(half_floats[i] + 1) - FromHalfFloat(half_floats[i]);
  51. EXPECT_NEAR(FromHalfFloat(half_floats[i]), expected_value,
  52. expected_precision)
  53. << "i = " << i << " bits = " << bits;
  54. }
  55. }
  56. }
  57. } // namespace media