UltraGrid
UltraGrid Low-Latency High-Resolution Transmission System
Loading...
Searching...
No Matches
bitstream.c
Go to the documentation of this file.
1/*
2 * FILE: bitstream.c
3 * PROGRAM: RAT
4 * AUTHOR: Orion Hodson
5 *
6 * Copyright (c) 2003 University of Southern California
7 * Copyright (c) 1998-2001 University College London
8 * All rights reserved.
9 *
10 * $Revision: 1.1 $
11 * $Date: 2007/11/08 09:48:59 $
12 */
13
14#include "bitstream.h"
15
16typedef struct s_bitstream {
17 u_char *buf; /* head of bitstream */
18 u_char *pos; /* current byte in bitstream */
19 unsigned int remain; /* bits remaining */
20 unsigned int len; /* length of bitstream in bytes */
22
24{
25 bs *pb;
26 pb = (bs *) malloc(sizeof(bs));
27 if (pb) {
28 memset(pb, 0, sizeof(bs));
29 *ppb = pb;
30 return TRUE;
31 }
32 return FALSE;
33}
34
36{
37 free(*ppb);
38 return TRUE;
39}
40
41int bs_attach(bitstream_t * b, u_char * buf, int blen)
42{
43 b->buf = b->pos = buf;
44 b->remain = 8;
45 b->len = blen;
46 memset(b->buf, 0, b->len);
47 return TRUE;
48}
49
50int bs_put(bitstream_t * b, u_char bits, uint8_t nbits)
51{
52 assert(nbits != 0 && nbits <= 8);
53
54 if (b->remain == 0) {
55 b->pos++;
56 b->remain = 8;
57 }
58
59 if (nbits > b->remain) {
60 unsigned int over = nbits - b->remain;
61 (*b->pos) |= (bits >> over);
62 b->pos++;
63 b->remain = 8 - over;
64 (*b->pos) = (bits << b->remain);
65 } else {
66 (*b->pos) |= bits << (b->remain - nbits);
67 b->remain -= nbits;
68 }
69
70 assert((unsigned int)(b->pos - b->buf) <= b->len);
71 return TRUE;
72}
73
74u_char bs_get(bitstream_t * b, uint8_t nbits)
75{
76 u_char out;
77
78 if (b->remain == 0) {
79 b->pos++;
80 b->remain = 8;
81 }
82
83 if (nbits > b->remain) {
84 /* Get high bits */
85 out = *b->pos;
86 out <<= (8 - b->remain);
87 out >>= (8 - nbits);
88 b->pos++;
89 b->remain += 8 - nbits;
90 out |= (*b->pos) >> b->remain;
91 } else {
92 out = *b->pos;
93 out <<= (8 - b->remain);
94 out >>= (8 - nbits);
95 b->remain -= nbits;
96 }
97
98 assert((unsigned int)(b->pos - b->buf) <= b->len);
99 return out;
100}
101
103{
104 unsigned int used = (unsigned int)(b->pos - b->buf);
105 if (b->remain != 8) {
106 used++;
107 }
108 return used;
109}
u_char bs_get(bitstream_t *b, uint8_t nbits)
Definition bitstream.c:74
int bs_put(bitstream_t *b, u_char bits, uint8_t nbits)
Definition bitstream.c:50
int bs_attach(bitstream_t *b, u_char *buf, int blen)
Definition bitstream.c:41
struct s_bitstream bs
int bs_create(bitstream_t **ppb)
Definition bitstream.c:23
int bs_destroy(bitstream_t **ppb)
Definition bitstream.c:35
int bs_bytes_used(bitstream_t *b)
Definition bitstream.c:102
#define TRUE
#define FALSE
u_char * pos
Definition bitstream.c:18
u_char * buf
Definition bitstream.c:17
unsigned int remain
Definition bitstream.c:19
unsigned int len
Definition bitstream.c:20