bitwriter.h 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /*
  2. * Copyright (c) 2010 The WebM project authors. All Rights Reserved.
  3. *
  4. * Use of this source code is governed by a BSD-style license
  5. * that can be found in the LICENSE file in the root of the source
  6. * tree. An additional intellectual property rights grant can be found
  7. * in the file PATENTS. All contributing project authors may
  8. * be found in the AUTHORS file in the root of the source tree.
  9. */
  10. #ifndef VPX_DSP_BITWRITER_H_
  11. #define VPX_DSP_BITWRITER_H_
  12. #include "vpx_ports/mem.h"
  13. #include "vpx_dsp/prob.h"
  14. #ifdef __cplusplus
  15. extern "C" {
  16. #endif
  17. typedef struct vpx_writer {
  18. unsigned int lowvalue;
  19. unsigned int range;
  20. int count;
  21. unsigned int pos;
  22. uint8_t *buffer;
  23. } vpx_writer;
  24. void vpx_start_encode(vpx_writer *bc, uint8_t *buffer);
  25. void vpx_stop_encode(vpx_writer *bc);
  26. static INLINE void vpx_write(vpx_writer *br, int bit, int probability) {
  27. unsigned int split;
  28. int count = br->count;
  29. unsigned int range = br->range;
  30. unsigned int lowvalue = br->lowvalue;
  31. register int shift;
  32. split = 1 + (((range - 1) * probability) >> 8);
  33. range = split;
  34. if (bit) {
  35. lowvalue += split;
  36. range = br->range - split;
  37. }
  38. shift = vpx_norm[range];
  39. range <<= shift;
  40. count += shift;
  41. if (count >= 0) {
  42. int offset = shift - count;
  43. if ((lowvalue << (offset - 1)) & 0x80000000) {
  44. int x = br->pos - 1;
  45. while (x >= 0 && br->buffer[x] == 0xff) {
  46. br->buffer[x] = 0;
  47. x--;
  48. }
  49. br->buffer[x] += 1;
  50. }
  51. br->buffer[br->pos++] = (lowvalue >> (24 - offset));
  52. lowvalue <<= offset;
  53. shift = count;
  54. lowvalue &= 0xffffff;
  55. count -= 8;
  56. }
  57. lowvalue <<= shift;
  58. br->count = count;
  59. br->lowvalue = lowvalue;
  60. br->range = range;
  61. }
  62. static INLINE void vpx_write_bit(vpx_writer *w, int bit) {
  63. vpx_write(w, bit, 128); // vpx_prob_half
  64. }
  65. static INLINE void vpx_write_literal(vpx_writer *w, int data, int bits) {
  66. int bit;
  67. for (bit = bits - 1; bit >= 0; bit--) vpx_write_bit(w, 1 & (data >> bit));
  68. }
  69. #define vpx_write_prob(w, v) vpx_write_literal((w), (v), 8)
  70. #ifdef __cplusplus
  71. } // extern "C"
  72. #endif
  73. #endif // VPX_DSP_BITWRITER_H_