00001
00020 #include "mfcpch.h"
00021 #ifdef __MSW32__
00022 #include <io.h>
00023 #else
00024 #include <unistd.h>
00025 #endif
00026 #include "fileerr.h"
00027 #include "bitstrm.h"
00028
00030 const UINT16 R_BITSTREAM::bitmasks[17] = {
00031 0, 1, 3, 7, 15, 31, 63, 127, 255,
00032 511, 1023, 2047, 4095, 8191, 16383, 32767, 65535
00033 };
00034
00038 UINT16 R_BITSTREAM::open(
00039 int fd
00040 ) {
00041 bitfd = fd;
00042 bufsize = read (fd, (char *) bitbuf, BITBUFSIZE * sizeof (UINT8));
00043
00044 if (bufsize < 0) {
00045 READFAILED.error ("R_BITSTREAM::open", LOG, NULL);
00046 return 0;
00047 }
00048 bitword = bitbuf[0] | (bitbuf[1] << 8);
00049 bitindex = 2;
00050 bitbit = 16;
00051 return (UINT16) bitword;
00052 }
00053
00054
00058 UINT16 R_BITSTREAM::read_code(
00059 UINT8 length
00060 ) {
00061 bitbit -= length;
00062 bitword >>= length;
00063 while (bitbit < 16) {
00064
00065 bitword |= bitbuf[bitindex++] << bitbit;
00066 bitbit += 8;
00067 if (bitindex >= bufsize) {
00068 bufsize =
00069 read (bitfd, (char *) bitbuf, BITBUFSIZE * sizeof (UINT8));
00070 if (bufsize < 0) {
00071 READFAILED.error ("R_BITSTREAM::read_code", LOG, NULL);
00072 return 0;
00073 }
00074 bitindex = 0;
00075 }
00076 }
00077 return (UINT16) bitword;
00078 }
00079
00080
00084 UINT16 R_BITSTREAM::masks(
00085 INT32 index
00086 ) {
00087 return bitmasks[index];
00088 }
00089
00090
00094 void W_BITSTREAM::open(
00095 int fd
00096 ) {
00097 bitfd = fd;
00098 bitindex = 0;
00099 bitword = 0;
00100 bitbit = 0;
00101 }
00102
00103
00107 INT8 W_BITSTREAM::write_code(
00108 UINT16 code,
00109 UINT8 length
00110 ) {
00111 if (length == 0) {
00112
00113 if (bitbit > 0)
00114
00115 bitbuf[bitindex++] = (UINT8) bitword;
00116 if ((bitindex > 0) &&
00117 (write (bitfd, (char *) bitbuf, bitindex * sizeof (UINT8)) !=
00118 (INT32) (bitindex * sizeof (UINT8)))) {
00119 WRITEFAILED.error ("W_BITSTREAM::write_code", LOG, "Flushing");
00120 return -1;
00121 }
00122 }
00123 else {
00124 bitword |= code << bitbit;
00125 bitbit += length;
00126 while (bitbit >= 8) {
00127
00128 bitbuf[bitindex++] = (UINT8) bitword;
00129 bitbit -= 8;
00130 bitword >>= 8;
00131 if (bitindex >= BITBUFSIZE) {
00132 if (write (bitfd, (char *) bitbuf, bitindex * sizeof (UINT8))
00133 != (INT32) (bitindex * sizeof (UINT8))) {
00134 WRITEFAILED.error ("W_BITSTREAM::write_code", LOG, NULL);
00135 return -1;
00136 }
00137 bitindex = 0;
00138 }
00139 }
00140 }
00141 return 0;
00142 }