random.h 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. // Copyright 2013 Google Inc. All Rights Reserved.
  2. //
  3. // Use of this source code is governed by a BSD-style license
  4. // that can be found in the COPYING file in the root of the source
  5. // tree. An additional intellectual property rights grant can be found
  6. // in the file PATENTS. All contributing project authors may
  7. // be found in the AUTHORS file in the root of the source tree.
  8. // -----------------------------------------------------------------------------
  9. //
  10. // Pseudo-random utilities
  11. //
  12. // Author: Skal (pascal.massimino@gmail.com)
  13. #ifndef WEBP_UTILS_RANDOM_H_
  14. #define WEBP_UTILS_RANDOM_H_
  15. #include <assert.h>
  16. #include "../webp/types.h"
  17. #ifdef __cplusplus
  18. extern "C" {
  19. #endif
  20. #define VP8_RANDOM_DITHER_FIX 8 // fixed-point precision for dithering
  21. #define VP8_RANDOM_TABLE_SIZE 55
  22. typedef struct {
  23. int index1_, index2_;
  24. uint32_t tab_[VP8_RANDOM_TABLE_SIZE];
  25. int amp_;
  26. } VP8Random;
  27. // Initializes random generator with an amplitude 'dithering' in range [0..1].
  28. void VP8InitRandom(VP8Random* const rg, float dithering);
  29. // Returns a centered pseudo-random number with 'num_bits' amplitude.
  30. // (uses D.Knuth's Difference-based random generator).
  31. // 'amp' is in VP8_RANDOM_DITHER_FIX fixed-point precision.
  32. static WEBP_INLINE int VP8RandomBits2(VP8Random* const rg, int num_bits,
  33. int amp) {
  34. int diff;
  35. assert(num_bits + VP8_RANDOM_DITHER_FIX <= 31);
  36. diff = rg->tab_[rg->index1_] - rg->tab_[rg->index2_];
  37. if (diff < 0) diff += (1u << 31);
  38. rg->tab_[rg->index1_] = diff;
  39. if (++rg->index1_ == VP8_RANDOM_TABLE_SIZE) rg->index1_ = 0;
  40. if (++rg->index2_ == VP8_RANDOM_TABLE_SIZE) rg->index2_ = 0;
  41. // sign-extend, 0-center
  42. diff = (int)((uint32_t)diff << 1) >> (32 - num_bits);
  43. diff = (diff * amp) >> VP8_RANDOM_DITHER_FIX; // restrict range
  44. diff += 1 << (num_bits - 1); // shift back to 0.5-center
  45. return diff;
  46. }
  47. static WEBP_INLINE int VP8RandomBits(VP8Random* const rg, int num_bits) {
  48. return VP8RandomBits2(rg, num_bits, rg->amp_);
  49. }
  50. #ifdef __cplusplus
  51. } // extern "C"
  52. #endif
  53. #endif /* WEBP_UTILS_RANDOM_H_ */