xref: /aosp_15_r20/external/libvpx/vpx_dsp/bitwriter_buffer.c (revision fb1b10ab9aebc7c7068eedab379b749d7e3900be)
1 /*
2  *  Copyright (c) 2013 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 
11 #include <assert.h>
12 #include <limits.h>
13 #include <stdlib.h>
14 
15 #include "./vpx_config.h"
16 #include "./bitwriter_buffer.h"
17 
vpx_wb_init(struct vpx_write_bit_buffer * wb,uint8_t * bit_buffer,size_t size)18 void vpx_wb_init(struct vpx_write_bit_buffer *wb, uint8_t *bit_buffer,
19                  size_t size) {
20   wb->error = 0;
21   wb->bit_offset = 0;
22   wb->size = size;
23   wb->bit_buffer = bit_buffer;
24 }
25 
vpx_wb_has_error(const struct vpx_write_bit_buffer * wb)26 int vpx_wb_has_error(const struct vpx_write_bit_buffer *wb) {
27   return wb->error;
28 }
29 
vpx_wb_bytes_written(const struct vpx_write_bit_buffer * wb)30 size_t vpx_wb_bytes_written(const struct vpx_write_bit_buffer *wb) {
31   assert(!wb->error);
32   return wb->bit_offset / CHAR_BIT + (wb->bit_offset % CHAR_BIT > 0);
33 }
34 
vpx_wb_write_bit(struct vpx_write_bit_buffer * wb,int bit)35 void vpx_wb_write_bit(struct vpx_write_bit_buffer *wb, int bit) {
36   if (wb->error) return;
37   const int off = (int)wb->bit_offset;
38   const int p = off / CHAR_BIT;
39   const int q = CHAR_BIT - 1 - off % CHAR_BIT;
40   if ((size_t)p >= wb->size) {
41     wb->error = 1;
42     return;
43   }
44   if (q == CHAR_BIT - 1) {
45     wb->bit_buffer[p] = bit << q;
46   } else {
47     assert((wb->bit_buffer[p] & (1 << q)) == 0);
48     wb->bit_buffer[p] |= bit << q;
49   }
50   wb->bit_offset = off + 1;
51 }
52 
vpx_wb_write_literal(struct vpx_write_bit_buffer * wb,int data,int bits)53 void vpx_wb_write_literal(struct vpx_write_bit_buffer *wb, int data, int bits) {
54   int bit;
55   for (bit = bits - 1; bit >= 0; bit--) vpx_wb_write_bit(wb, (data >> bit) & 1);
56 }
57 
vpx_wb_write_inv_signed_literal(struct vpx_write_bit_buffer * wb,int data,int bits)58 void vpx_wb_write_inv_signed_literal(struct vpx_write_bit_buffer *wb, int data,
59                                      int bits) {
60   vpx_wb_write_literal(wb, abs(data), bits);
61   vpx_wb_write_bit(wb, data < 0);
62 }
63