bit_cost.h 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /* Copyright 2013 Google Inc. All Rights Reserved.
  2. Distributed under MIT license.
  3. See file LICENSE for detail or copy at https://opensource.org/licenses/MIT
  4. */
  5. /* Functions to estimate the bit cost of Huffman trees. */
  6. #ifndef BROTLI_ENC_BIT_COST_H_
  7. #define BROTLI_ENC_BIT_COST_H_
  8. #include "../common/platform.h"
  9. #include <brotli/types.h>
  10. #include "./fast_log.h"
  11. #include "./histogram.h"
  12. #if defined(__cplusplus) || defined(c_plusplus)
  13. extern "C" {
  14. #endif
  15. static BROTLI_INLINE double ShannonEntropy(
  16. const uint32_t* population, size_t size, size_t* total) {
  17. size_t sum = 0;
  18. double retval = 0;
  19. const uint32_t* population_end = population + size;
  20. size_t p;
  21. if (size & 1) {
  22. goto odd_number_of_elements_left;
  23. }
  24. while (population < population_end) {
  25. p = *population++;
  26. sum += p;
  27. retval -= (double)p * FastLog2(p);
  28. odd_number_of_elements_left:
  29. p = *population++;
  30. sum += p;
  31. retval -= (double)p * FastLog2(p);
  32. }
  33. if (sum) retval += (double)sum * FastLog2(sum);
  34. *total = sum;
  35. return retval;
  36. }
  37. static BROTLI_INLINE double BitsEntropy(
  38. const uint32_t* population, size_t size) {
  39. size_t sum;
  40. double retval = ShannonEntropy(population, size, &sum);
  41. if (retval < sum) {
  42. /* At least one bit per literal is needed. */
  43. retval = (double)sum;
  44. }
  45. return retval;
  46. }
  47. BROTLI_INTERNAL double BrotliPopulationCostLiteral(const HistogramLiteral*);
  48. BROTLI_INTERNAL double BrotliPopulationCostCommand(const HistogramCommand*);
  49. BROTLI_INTERNAL double BrotliPopulationCostDistance(const HistogramDistance*);
  50. #if defined(__cplusplus) || defined(c_plusplus)
  51. } /* extern "C" */
  52. #endif
  53. #endif /* BROTLI_ENC_BIT_COST_H_ */