minifloat.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /*
  2. * Copyright (C) 2014 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 <cmath>
  17. #include "audio/android/audio_utils/include/audio_utils/minifloat.h"
  18. #define EXPONENT_BITS 3
  19. #define EXPONENT_MAX ((1 << EXPONENT_BITS) - 1)
  20. #define EXCESS ((1 << EXPONENT_BITS) - 2)
  21. #define MANTISSA_BITS 13
  22. #define MANTISSA_MAX ((1 << MANTISSA_BITS) - 1)
  23. #define HIDDEN_BIT (1 << MANTISSA_BITS)
  24. #define ONE_FLOAT ((float) (1 << (MANTISSA_BITS + 1)))
  25. #define MINIFLOAT_MAX ((EXPONENT_MAX << MANTISSA_BITS) | MANTISSA_MAX)
  26. #if EXPONENT_BITS + MANTISSA_BITS != 16
  27. #error EXPONENT_BITS and MANTISSA_BITS must sum to 16
  28. #endif
  29. extern "C" {
  30. gain_minifloat_t gain_from_float(float v)
  31. {
  32. if (std::isnan(v) || v <= 0.0f)
  33. {
  34. return 0;
  35. }
  36. if (v >= 2.0f)
  37. {
  38. return MINIFLOAT_MAX;
  39. }
  40. int exp;
  41. float r = frexpf(v, &exp);
  42. if ((exp += EXCESS) > EXPONENT_MAX)
  43. {
  44. return MINIFLOAT_MAX;
  45. }
  46. if (-exp >= MANTISSA_BITS)
  47. {
  48. return 0;
  49. }
  50. int mantissa = (int) (r * ONE_FLOAT);
  51. return exp > 0 ? (exp << MANTISSA_BITS) | (mantissa & ~HIDDEN_BIT) :
  52. (mantissa >> (1 - exp)) & MANTISSA_MAX;
  53. }
  54. float float_from_gain(gain_minifloat_t a)
  55. {
  56. int mantissa = a & MANTISSA_MAX;
  57. int exponent = (a >> MANTISSA_BITS) & EXPONENT_MAX;
  58. return ldexpf((exponent > 0 ? HIDDEN_BIT | mantissa : mantissa << 1) / ONE_FLOAT,
  59. exponent - EXCESS);
  60. }
  61. } // extern "C" {