forked from soiaf/C-Sharp-WavPack-Decoder
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBitsUtils.cs
More file actions
145 lines (120 loc) · 2.22 KB
/
BitsUtils.cs
File metadata and controls
145 lines (120 loc) · 2.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
/*
** BitsUtils.cs
**
** Copyright (c) 2010-2016 Peter McQuillan
**
** All Rights Reserved.
**
** Distributed under the BSD Software License (see license.txt)
***/
namespace WavPack
{
class BitsUtils
{
internal static bool getbit(Bitstream bs)
{
if (bs.bc > 0)
bs.bc--;
else
{
bs.ptr++;
bs.buf_index++;
bs.bc = 7;
if (bs.ptr == bs.end)
// wrap call here
bs = bs_read(bs);
bs.sr = bs.buf[bs.buf_index];
}
bool result = (bs.sr & 1) > 0;
bs.sr >>= 1;
return result;
}
internal static long getbits(int nbits, Bitstream bs)
{
long retval;
while (nbits > bs.bc)
{
bs.ptr++;
bs.buf_index++;
if (bs.ptr == bs.end)
bs = bs_read(bs);
bs.sr |= (uint)(bs.buf[bs.buf_index] << bs.bc);
bs.bc += 8;
}
retval = bs.sr;
if (bs.bc > 32)
{
bs.bc -= nbits;
bs.sr = (uint)(bs.buf[bs.buf_index] >> (8 - bs.bc));
}
else
{
bs.bc -= nbits;
bs.sr >>= nbits;
}
return retval;
}
internal static Bitstream bs_open_read(byte[] stream, int buffer_start, int buffer_end, System.IO.BinaryReader file, int file_bytes, int passed)
{
Bitstream bs = new Bitstream();
bs.buf = stream;
bs.buf_index = buffer_start;
bs.end = buffer_end;
bs.sr = 0;
bs.bc = 0;
if (passed != 0)
{
bs.ptr = bs.end - 1/*passed???*/;
bs.file_bytes = file_bytes;
bs.file = file;
}
else
bs.ptr = bs.buf_index = -1;
return bs;
}
internal static Bitstream bs_read(Bitstream bs)
{
if (bs.file_bytes > 0)
{
int bytes_read;
var bytes_to_read = bs.buf.Length;
if (bytes_to_read > bs.file_bytes)
bytes_to_read = bs.file_bytes;
try
{
bytes_read = bs.file.BaseStream.Read(bs.buf, 0, bytes_to_read);
bs.buf_index = 0;
}
catch (System.Exception e)
{
System.Console.Error.WriteLine("Big error while reading file: " + e);
bytes_read = 0;
}
if (bytes_read > 0)
{
bs.end = bytes_read;
bs.file_bytes -= bytes_read;
}
else
{
for (int i = 0; i < bs.buf.Length; i++)
{
bs.buf[i] = unchecked((byte)-1);
}
bs.error = 1;
}
}
else
{
bs.error = 1;
for (int i = 0; i < bs.buf.Length; i++)
{
bs.buf[i] = unchecked((byte)-1);
}
}
bs.ptr = 0;
bs.buf_index = 0;
return bs;
}
}
}