| 1 |
#define _XOPEN_SOURCE /* Make sure unistd.h contains swab() */ |
| 2 |
#include <unistd.h> |
| 3 |
|
| 4 |
#include "netpbm/pm.h" |
| 5 |
#include "netpbm/mallocvar.h" |
| 6 |
|
| 7 |
#include "global_variables.h" |
| 8 |
#include "util.h" |
| 9 |
#include "stdio_nofail.h" |
| 10 |
|
| 11 |
#ifndef LONG_BITS |
| 12 |
#define LONG_BITS (8 * sizeof(long)) |
| 13 |
#endif |
| 14 |
/* |
| 15 |
Get a 2-byte integer, making no assumptions about CPU byte order. |
| 16 |
Nor should we assume that the compiler evaluates left-to-right. |
| 17 |
*/ |
| 18 |
unsigned short |
| 19 |
get2(FILE * const ifp) |
| 20 |
{ |
| 21 |
unsigned char a, b; |
| 22 |
|
| 23 |
a = fgetc_nofail(ifp); b = fgetc_nofail(ifp); |
| 24 |
|
| 25 |
if (order == 0x4949) /* "II" means little-endian */ |
| 26 |
return a | b << 8; |
| 27 |
else /* "MM" means big-endian */ |
| 28 |
return a << 8 | b; |
| 29 |
} |
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
/* |
| 34 |
Same for a 4-byte integer. |
| 35 |
*/ |
| 36 |
int |
| 37 |
get4(FILE * const ifp) |
| 38 |
{ |
| 39 |
unsigned char a, b, c, d; |
| 40 |
|
| 41 |
a = fgetc_nofail(ifp); b = fgetc_nofail(ifp); |
| 42 |
c = fgetc_nofail(ifp); d = fgetc_nofail(ifp); |
| 43 |
|
| 44 |
if (order == 0x4949) |
| 45 |
return a | b << 8 | c << 16 | d << 24; |
| 46 |
else |
| 47 |
return a << 24 | b << 16 | c << 8 | d; |
| 48 |
} |
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
/* |
| 53 |
Faster than calling get2() multiple times. |
| 54 |
*/ |
| 55 |
void |
| 56 |
read_shorts (FILE * const ifp, unsigned short *pixel, int count) |
| 57 |
{ |
| 58 |
unsigned short * buffer; |
| 59 |
|
| 60 |
MALLOCARRAY(buffer, count); |
| 61 |
|
| 62 |
if (!buffer) |
| 63 |
pm_error("Failed to allocate a buffer for reading %u short " |
| 64 |
"integers from file", count); |
| 65 |
else { |
| 66 |
fread_nofail(buffer, 2, count, ifp); |
| 67 |
|
| 68 |
if ((order == 0x4949) == (BYTE_ORDER == BIG_ENDIAN)) |
| 69 |
swab(buffer, pixel, count*2); |
| 70 |
|
| 71 |
free(buffer); |
| 72 |
} |
| 73 |
} |
| 74 |
|
| 75 |
|
| 76 |
|
| 77 |
/* |
| 78 |
getbits(-1) initializes the buffer |
| 79 |
getbits(n) where 0 <= n <= 25 returns an n-bit integer |
| 80 |
*/ |
| 81 |
unsigned |
| 82 |
getbits (FILE * const ifp, int nbits) |
| 83 |
{ |
| 84 |
static unsigned long bitbuf=0; |
| 85 |
static int vbits=0; |
| 86 |
unsigned c, ret; |
| 87 |
|
| 88 |
if (nbits == 0) return 0; |
| 89 |
if (nbits == -1) |
| 90 |
ret = bitbuf = vbits = 0; |
| 91 |
else { |
| 92 |
ret = bitbuf << (LONG_BITS - vbits) >> (LONG_BITS - nbits); |
| 93 |
vbits -= nbits; |
| 94 |
} |
| 95 |
while (vbits < LONG_BITS - 7) { |
| 96 |
c = fgetc_nofail(ifp); |
| 97 |
bitbuf = (bitbuf << 8) + c; |
| 98 |
if (c == 0xff && zero_after_ff) |
| 99 |
fgetc_nofail(ifp); |
| 100 |
vbits += 8; |
| 101 |
} |
| 102 |
return ret; |
| 103 |
} |
| 104 |
|
| 105 |
|
| 106 |
|