66 Commits
1.7.4 ... main

Author SHA1 Message Date
Rupert
e7910ac36b add bmpread_image_type() API call 2025-06-22 02:05:35 +02:00
Rupert
7ece494541 Docs update 2025-06-21 16:18:45 +02:00
Rupert
c8ead48e33 add icon/pointer settings-sanity check 2025-06-21 13:24:54 +02:00
Rupert
8b38742ea3 icons/pointers: allow only BMP_UNDEFINED_LEAVE as undefined mode 2025-06-21 09:32:50 +02:00
Rupert
3a673da403 icons/pointers/arrays: minor changes to error handling 2025-06-21 09:32:19 +02:00
Rupert
fabbe4f8af arrays: bmpread_load_info() didn't set rp->getinfo_return
also icons/pointers: minor changes, comments
2025-06-06 16:24:14 +02:00
Rupert
22ef9d73aa Add BA and icon/pointer documentation 2025-06-04 00:03:26 +02:00
Rupert
abd3ea2db2 remove long deprecated symbols, bump version to 1.8.0 2025-06-03 23:16:10 +02:00
Rupert
3c5723b740 OS/2 icons/pointers: require INT result format 2025-06-03 23:21:32 +02:00
Rupert
8dd7182bf1 refuse 64bit for icons/pointers 2025-06-03 23:21:32 +02:00
Rupert
07d3bf6086 OS/2 icons/pointers: refactor boolean flags
one icon flag and and mono flag instead of two color-icon/mono-icon
flags
2025-06-03 23:21:32 +02:00
Rupert
5cd33b22ca Add support for OS/2 BA bitmap arrays 2025-06-03 23:21:32 +02:00
Rupert
10657851d1 Add support for OS/2 icons and pointers (IC/PT/CI/CP)
Still somewhat crude, but it works.

Limitations:
- max size 512x512
- no RLE
- no support yet to load index values, result is
  always returned as RGBA
2025-06-03 23:21:32 +02:00
Rupert
044fa148ed bmp-write: remove duplicate code 2025-05-30 22:22:24 +02:00
Rupert
b9244c0766 embrace C11 VLA syntax 2025-05-30 17:01:10 +02:00
Rupert
84a0f0f49d struct Bmpread - reorder some fields wrt alignment 2025-05-30 16:50:16 +02:00
Rupert
1b67440d29 docs: add section numbering 2025-05-27 15:08:47 +02:00
Rupert
5166bdb1e7 bmplib.h: some houskeeping and preparation for OS/2 icon/pointers 2025-05-14 23:36:08 +02:00
Rupert
c02804cdbf asserts
- use static_assert macro instead of _Static_assert
- make assertion in bmpwrite_set_iccprofile static
2025-05-09 08:12:07 +02:00
Rupert
fd8583d568 unit tests: add libreoffice spreadsheet to help construct test data 2025-05-08 15:14:32 +02:00
Rupert
845223bf62 add unit test for s_imgrgb_to_outbytes() 2025-05-08 13:20:47 +02:00
Rupert
952c10324f bmp-write: update float_to_s2_13() to version from bmp-read
should obviously eventually go into a header file instead of
duplicating it.
2025-05-07 20:56:56 +02:00
Rupert
668cc352e3 add unit tests for write_<xnn>_le() functions 2025-05-07 17:55:07 +02:00
Rupert
1bba98e395 refactor cm_align4size() macro 2025-05-03 18:41:08 +02:00
Rupert
0815eb3a7b remove unused function cm_align2padding() 2025-05-03 14:55:40 +02:00
Rupert
94dceb5812 read_u<nn>_le(): eliminate implementation defined behavior
relatively pointless but fun ;o)

- while not making any assumptions about the host's bit representation
  or the implementation defined behavior of assigning an unsigned int
  > INT_MAX to a signed int, the lack of range (INT_MIN) would
  still break it on non-two's complement unless larger int types were
  used.
- both gcc and clang recognize the pattern and generate the same code as
  for the simple assignment, so doing it this way doesn't cost any
  performance.
2025-05-03 13:25:21 +02:00
Rupert
c733595aed add unit test for read_s32_le() 2025-05-03 11:40:31 +02:00
Rupert
920ba8ea7e add unit test for read_u32_le() 2025-05-03 11:32:51 +02:00
Rupert
0882f1796a add unit test for read_s16_le() 2025-05-03 11:32:51 +02:00
Rupert
da95bcb0ae add unit test for read_u16_le() 2025-05-03 11:32:51 +02:00
Rupert
e5584c3b0f s_buffer32_bits(): make assert more precise 2025-05-01 12:13:32 +02:00
Rupert
3af484b238 update copyright notice dates 2025-05-01 12:11:32 +02:00
Rupert
6c33d975b5 add unit test for s_read_rgb_pixel() 2025-05-01 12:04:27 +02:00
Rupert
0ab592c357 add unit test for s_buffer_32_bits() 2025-04-30 13:23:55 +02:00
Rupert
e9b047b857 add unit test for s_buffer32_fill() 2025-04-30 13:23:55 +02:00
Rupert
71b3853327 s_buffer32_fill(): allow partial fill
this can make sense if the very last (padding) bytes of an indexed
file are truncated.
2025-04-30 13:23:55 +02:00
Rupert
5ce902ce1b add unit test for s_int8_to_result_format() 2025-04-30 13:23:55 +02:00
Rupert
abf93c1a77 reafactor s_int_to_result_format()
the in-place conversion made me feel a bit queezy; also, it's only ever
called for rgb conversion of indexed images, meaning always with
8-bit integers.

- Changed the name to s_int8_to_result_format()
- made it 8-bit only
- source values are now supplied as separate int array 'frombits' and
  stored into the result buffer 'px'.
2025-04-30 13:23:55 +02:00
Rupert
bc7dd1423c add unit test for s_srgb_gamma_float(), rename test source file 2025-04-29 00:59:13 +02:00
Rupert
100715fe9d add unit tests for s2.13 conversion 2025-04-28 22:59:12 +02:00
Rupert
e195d1d918 bmpread: use conversion functions
instead of manual conversions,
- use new s_float_to_s2_13()
- use s_int_to_float() in s_int_to_result_format()
2025-04-28 22:59:12 +02:00
Rupert
3989e07e05 fix rounding error in s2.13 conversion, eliminate impl.defined behavior
also eliminate some duplicate code while we're at it
2025-04-28 22:56:34 +02:00
Rupert
df8d9e44ca read state, minor changes 2025-04-28 22:56:34 +02:00
Rupert
7d2ff7fca5 C23 doesn't define __bool_true_false_are_defined anymore
this is still very kludgy, but seems to work for any c std
2025-04-28 22:56:34 +02:00
Rupert
2ba0910acc static assert of 32bit requirement
be more specific, requiring 32bits, not necessarily 4 bytes
2025-04-28 19:41:02 +02:00
Rupert
7494855af6 cleanup insane handling
- fix: setting a new insanity limit can cause previously ok result to
  be insane
- refactor for simpler expressions / more symmetry
2025-04-19 19:23:46 +02:00
Rupert
1d9a3faad4 icc profile error handling, minor changes 2025-04-19 12:53:52 +02:00
Rupert
3d31aa93cd minor fixes:
- require integer format when loading palette
- don't auto-load info in bmpread_is_64bit, as we cannot return result
2025-04-19 01:30:41 +02:00
Rupert
91d93cba9b refactor read state
instead of several bools, have one enum to keep track of where in the
reading process we are
2025-04-19 01:27:22 +02:00
Rupert
b43fd940e6 bump version to 1.7.7 2025-04-18 15:53:08 +02:00
Rupert
61a4caf6ef fix line-by-line writing bug, refactor write state
bug introduced by 142427e17: line-by-line writing of RLE files resulted
in corrupted files.
Found while refactoring write state
2025-04-18 15:51:09 +02:00
Rupert
4942795e14 don't require explicitly calling load_info() before reading ICC profile 2025-04-17 23:48:19 +02:00
Rupert
52801cd5d5 cleanup s_decide_outformat() 2025-04-17 23:47:24 +02:00
Rupert
0e4e611955 add semicolons in doc for consistent syntax highlighter 2025-04-16 23:50:00 +02:00
Rupert
58ebfc8dc7 doc update, bump version to v1.7.6 2025-04-16 23:43:45 +02:00
Rupert
1e3f4abe16 add support for setting rendering intent
new function: bmpwrite_set_rendering_intent()
2025-04-16 23:08:14 +02:00
Rupert
be9882e04f documentation update
- add documentation for ICC profile functions
- add 'c' to code snippets to enable syntax highlighting
- minor corrections
2025-04-16 13:11:37 +02:00
Rupert
3218cd6e65 small fix in RLE24 preconditions 2025-04-15 22:13:26 +02:00
Rupert
142427e179 add ICC profile writing support
new function bmpwrite_set_iccprofile()
2025-04-15 22:13:26 +02:00
Rupert
0580565bf3 add ICC profile reading support
- new functions:
 - bmpread_iccprofile_size()
 - bmpread_load_iccprofile()
- only pass on profile as is, profile is not interpreted or applied
2025-04-15 22:10:13 +02:00
Rupert
7523138fbb bump version to 1.7.5 2025-04-10 18:29:17 +02:00
Rupert
592605e06f add sanitize meson option 2025-04-10 18:29:17 +02:00
Rupert
eeae2205c5 eliminate all -Wextra warnings
revert height back to int and make INT_MIN an invalid height. Having
a possible height value that's only valid for top-down but not bottom-up
BMPs just creates headaches down the way.
2025-04-10 18:29:17 +02:00
Rupert
2d7763de7f refactor huffman bit-flipping for readability 2025-04-10 11:57:12 +02:00
Rupert
7513352a7b add bmp_set_huffman_t4black_value()
ITU-T T.4 defines 'black' and 'white' (referring to fore- and back-
ground, respectively) pixel sequences, but it doesn't prescribe which
of those is represented by 0 or 1. That would have to be defined by the
BMP specification, but documentation on Huffman BMPs is close to
non-existent.

Current consensus seems to be that 'black' is 1, i.e. indexing the
second color in the palette, and 'white' is 0, i.e. indexing the first
color.

In case that's wrong (in fact it's not even clear if there is a right
and a wrong), bmp_set_huffman_t4black_value() can be used to set the
pixel value of 'black' to either 0 or 1 (and white to the respective
opposite).

Can be used both for reading and writing BMPs.

Changing this value will invert the image colors.
2025-04-09 23:11:58 +02:00
Rupert
ea7b93ce64 read/write handles: move shared portion into struct Bmpcommon
make the generic handle a union of common/read/write
2025-04-09 18:40:06 +02:00
28 changed files with 3409 additions and 849 deletions

View File

@@ -1,12 +1,12 @@
# Rupert's bmplib -- Full API Description (v1.7.1)
# Rupert's bmplib -- Full API Description (v1.8.0)
Refer to the *Quick Start Guide* (API-quick-start.md) for a quick intro to bmplib which describes only the minimal set of functions needed to read/write BMP files.
## 1. Functions for reading BMP files
### Get a handle
### 1.2 Get a handle
```
```c
BMPHANDLE bmpread_new(FILE *file)
```
@@ -16,9 +16,9 @@ handle.
The handle cannot be reused to read multiple files.
### Read the file header
### 1.3 Read the file header
```
```c
BMPRESULT bmpread_load_info(BMPHANDLE h)
```
@@ -31,7 +31,7 @@ bmplib reads the file header and checks validity. Possible return values are:
`bmpread_set_insanity_limit()` to increase the allowed file size.
Otherwise, `bmpread_load_image()` will refuse to load the image. (You can
build the library with a different default limit, using the meson
option '-Dinsanity_limit_mb=nnn')
option `-Dinsanity_limit_mb=nnn`)
- `BMP_RESULT_PNG` / `BMP_RESULT_JPEG`: It's not really a BMP file, but a
wrapped PNG or JPEG. The file pointer is left in the correct state to be
passed on to e.g. libpng or libjpeg.
@@ -42,15 +42,15 @@ bmplib reads the file header and checks validity. Possible return values are:
Calling `bmpread_load_info()` is optional when you use `bmpread_dimensions()`
(see below).
### Get image dimensions
### 1.4 Get image dimensions
```
```c
BMPRESULT bmpread_dimensions(BMPHANDLE h,
int *width,
int *height,
int *channels,
int *bitsperchannel,
BMPORIENT *orientation)
BMPORIENT *orientation);
```
Use `bmpread_dimensions()` to get all dimensions with one call. It is not
@@ -68,18 +68,18 @@ Note, in order to use these functions, -- unlike with `bmpread_dimensions
()` -- you must first (successfully) call `bmpread_load_info()`, otherwise
they will all return 0!
```
int bmpread_width(BMPHANDLE h)
int bmpread_height(BMPHANDLE h)
int bmpread_channels(BMPHANDLE h)
int bmpread_bitsperchannel(BMPHANDLE h)
BMPORIENT bmpread_orientation(BMPHANDLE h)
```c
int bmpread_width(BMPHANDLE h);
int bmpread_height(BMPHANDLE h);
int bmpread_channels(BMPHANDLE h);
int bmpread_bitsperchannel(BMPHANDLE h);
BMPORIENT bmpread_orientation(BMPHANDLE h);
int bmpread_resolution_xdpi(BMPHANDLE h)
int bmpread_resolution_ydpi(BMPHANDLE h)
int bmpread_resolution_xdpi(BMPHANDLE h);
int bmpread_resolution_ydpi(BMPHANDLE h);
```
#### top-down / bottom-up
#### 1.4.1. top-down / bottom-up
`*orientation` is one of:
@@ -96,15 +96,38 @@ other hand, when the whole image is loaded at once (using `bmpread_load_image
the BMP file is oriented. The `orientation` value will still indicate the
orientation of the original BMP.
#### Required size for buffer to receive image
#### 1.4.2. Required size for buffer to receive image
```
size_t bmpread_buffersize(BMPHANDLE h)
```c
size_t bmpread_buffersize(BMPHANDLE h);
```
Returns the buffer size you have to allocate for the whole image.
### Indexed BMPs
### 1.5. Image type
```c
BMPIMAGETYPE bmpread_image_type(BMPHANDLE h);
```
Returns one of
- `BMP_IMAGETYPE_NONE` type hasn't been determined (yet). Either
`bmpread_load_info()` hasn't been called yet, or the file is not a valid
BMP file.
- `BMP_IMAGETYPE_BM` bitmap (normal image)
- `BMP_IMAGETYPE_BA` bitmap array
- `BMP_IMAGETYPE_CI` color icon
- `BMP_IMAGETYPE_CP` color pointer
- `BMP_IMAGETYPE_IC` icon (monochrome)
- `BMP_IMAGETYPE_PT` pointer (monochrome)
Other than bitmap arrays (in which case `bmpread_load_info()` will have
returned `BMP_RESULT_ARRAY`) and the limitations that apply to icon and
pointer files (see below) the returned type is purely informational and no
special actions need to be taken.
### 1.6. Indexed BMPs
By default, bmplib will interpret indexed (color palette) BMPs and return the
image as 24-bit RGB data, same as non-indexed (RGB) BMPs.
@@ -112,9 +135,9 @@ image as 24-bit RGB data, same as non-indexed (RGB) BMPs.
If instead you want to keep the image as indexed, you have the option do so
with these two functions:
```
int bmpread_num_palette_colors(BMPHANDLE h)
BMPRESULT bmpread_load_palette(BMPHANDLE h, unsigned char **palette)
```c
int bmpread_num_palette_colors(BMPHANDLE h);
BMPRESULT bmpread_load_palette(BMPHANDLE h, unsigned char **palette);
```
`bmpread_num_palette_colors()` will return 0 for non-indexed images, otherwise
@@ -130,7 +153,7 @@ the palette buffer will contain "rgb0rgb0rgb0...".
As with the main image buffer, you can either provide one for the palette or
let bmplib allocate it for you (and then `free()` it, once you are done):
```
```c
unsigned char *palette;
int numcolors;
@@ -153,7 +176,7 @@ RGB data. After you loaded the palette, calls to `bmpread_dimensions
`bmpread_set_undefined()` will have no effect, as indexed images cannot have
an alpha channel (see below).
#### Undefined pixels
#### 1.6.1. Undefined pixels
RLE-encoded BMP files may have undefined pixels, either by using early
end-of-line or end-of-file codes, or by using delta codes to skip part of the
@@ -171,8 +194,8 @@ untouched by undefined pixels. (Note: if you let bmplib allocate the image
buffer, it will always be initialized to zero before loading the image). This
function has no effect on non-RLE BMPs.
```
void bmpread_set_undefined(BMPHANDLE h, BMPUNDEFINED mode)
```c
void bmpread_set_undefined(BMPHANDLE h, BMPUNDEFINED mode);
```
`mode` can be one of:
@@ -184,11 +207,37 @@ Note: If you use `bmpread_load_palette()` to switch to loading the index data
instead of RGB data, this setting will have no effect and undefined pixels
will always be left alone! (see above)
### Optional settings for 64bit BMPs
### 1.7. ICC color profiles
```c
size_t bmpread_iccprofile_size(BMPHANDLE h);
BMPRESULT bmpread_load_iccprofile(BMPHANDLE h, unsigned char **pprofile);
```
int bmpread_is_64bit(BMPHANDLE h)
BMPRESULT bmpread_set_64bit_conv(BMPHANDLE h, BMPCONV64 conv)
Use `bmpread_iccprofile_size()` to query the size (or existence) of an
embedded color profile. If the BMP file doesn't contain a profile, the return
value is 0.
bmplib does not interpret or apply embedded ICC color profiles. The profile is
simply returned 'as is', image data is not affected in any way.
`bmpread_load_iccprofile()` loads the profile into the buffer pointed to by
`*pprofile`. As with loading image and palette data, you can either allocate
the buffer yourself or pass a pointer to a NULL-pointer and let bmplib
allocate an appropriate buffer, e.g.:
```c
unsigned char *profile = NULL;
if (bmpread_iccprofile_size(h) > 0)
bmpread_load_iccprofile(h, &profile);
```
### 1.8. Optional settings for 64bit BMPs
```c
int bmpread_is_64bit(BMPHANDLE h);
BMPRESULT bmpread_set_64bit_conv(BMPHANDLE h, BMPCONV64 conv);
```
If you don't do anything, 64bit BMPs will be read like any other BMP and the
@@ -196,7 +245,11 @@ data will be returned as 16bit/channel sRGB RGBA.
But if you want to access the original s2.13 fixed-point components, or you
don't want the linear-to-sRGB conversion, you can use `bmpread_set_64bit_conv
()` and `bmp_set_number_format()` to control how the image is returned:
()` and `bmp_set_number_format()` to control how the image is returned.
64bit BMP pixel values are in the [-4...4) range, beyond the usual
[0...1]. Unless you load the image as `BMP_FORMAT_S2_13` or `BMP_FORMAT_FLOAT`,
the values will be clipped to [0...1].
Options for `bmpread_set_64bit()` are:
@@ -204,38 +257,102 @@ Options for `bmpread_set_64bit()` are:
fixed-point linear and converted to sRGB-gamma.
- `BMP_CONV64_LINEAR`: no gamma-conversion is applied to the image data.
- `BMP_CONV64_NONE`: this option is just a shorthand for setting
BMP_CONV64_LINEAR *and* BMP_FORMAT_S2_13. Image values are returned exactly
as they are in the BMP file, without any conversion or attempt at
interpretation.
`BMP_CONV64_LINEAR` *and also* calling `bmp_set_number_format()` with
`BMP_FORMAT_S2_13`. Image values are returned exactly as they are in the BMP
file, without any conversion or attempt at interpretation.
### Setting a number format
### 1.9. Setting a number format
By default, bmplib will always return the image data as 8-,16-, or 32-bit integer values. You can instead set the number format to floating point or fixed using:
By default, bmplib will always return the image data as 8-,16-, or 32-bit
integer values. You can instead set the number format to floating point or
fixed using:
```
BMPRESULT bmp_set_number_format(BMPHANDLE h, BMPFORMAT format)
```c
BMPRESULT bmp_set_number_format(BMPHANDLE h, BMPFORMAT format);
```
(see below, *3. General functions for both reading/writing BMPs*)
### Huge files: bmpread_set_insanity_limit()
### 1.10. Huge files: bmpread_set_insanity_limit()
bmplib will refuse to load images beyond a certain size (default 500MB) and
instead return BMP_RESULT_INSANE. If you want to load the image anyway, call
`bmpread_set_insanity_limit()` at any time before calling `bmpread_load_image
()`. `limit` is the new allowed size in bytes. (not MB!)
instead return `BMP_RESULT_INSANE`. If you want to load the image anyway, call
`bmpread_set_insanity_limit()` at any time before calling `bmpread_load_image()`.
`limit` is the new allowed size in bytes (not MB!).
```
void
bmpread_set_insanity_limit(BMPHANDLE h, size_t limit)
```c
void bmpread_set_insanity_limit(BMPHANDLE h, size_t limit);
```
### Load the image
### 1.11. OS/2 bitmap arrays (type 'BA')
#### bmpread_load_image()
Bitmap arrays are meant to contain several versions (with different
resolutions and color depths) of the same image. They are not meant to
contain different images like e.g. several scanned pages.
If a BMP file is of type 'BA', `bmpread_load_info()` will return
`BMP_RESULT_ARRAY`. Use the following functions to to query the number and
type of contained images and get a new `BMPHANDLE` for any of the contained
images:
```c
int bmpread_array_num(BMPHANDLE h);
BMPRESULT bmpread_array_info(BMPHANDLE h, struct BmpArrayInfo *ai, int idx);
struct BmpArrayInfo {
BMPHANDLE handle;
BMPIMAGETYPE type;
int width, height;
int ncolors; /* 0 = RGB */
int screenwidth, screenheight; /* typically 0, or 1024x768 for 'hi-res' */
};
```
BMPRESULT bmpread_load_image(BMPHANDLE h, unsigned char **pbuffer)
`bmpread_array_num()` returns the number of images contained in the array.
`bmpread_array_info()` fills the supplied `struct BmpArrayInfo` with
information about any of the contained images:
- `handle`: A handle that can be used with all the usual bmpread_* functions
to read the respective image. These handles for array images don't have to
be freed individually, it is sufficient to call `bmp_free()` on the
main array handle once the images have been loaded.
- `type`: Image type, one of
- `BMP_IMAGETYPE_BM` bitmap (normal image)
- `BMP_IMAGETYPE_CI` color icon
- `BMP_IMAGETYPE_CP` color pointer
- `BMP_IMAGETYPE_IC` icon (monochrome)
- `BMP_IMAGETYPE_PT` pointer (monochrome)
- `width, height`: Width and height of the image
- `ncolors`: number of colors (2/16/256) for indexed images, or 0 for RGB
images
- `screenwidth, screenheight`: The screen size the image was intended for.
Typically 0, or 1024x768 for 'hi-res'.
NOTE: You must not interleave calls to `bmpread_load_line()` for several array
images or simultanously call `bmpread_load_image()` from different threads.
First completely read one image before proceeding to the next one.
#### 1.10.1 OS/2 icons and pointers
OS/2 icons and pointers are often contained in bitmap arrays.
Some limitations apply for loading icons and pointers:
- The image is always returned as 8 bit per channel RGBA, loading index values
and palette is not supported.
- Maximum supported size is 512x512. This shouldn't be limiting for actual
legacy icons and pointers.
- For RLE images, undefined mode is always assumed to be
`BMP_UNDEFINED_LEAVE`, regardless of what `bmpread_set_undefined()` was set
to. (Because icons and pointers have their own mask-based transparency
scheme.)
### 1.12. Load the image
#### 1.12.1. bmpread_load_image()
```c
BMPRESULT bmpread_load_image(BMPHANDLE h, unsigned char **pbuffer);
```
Loads the complete image from the BMP file into the buffer pointed to by
@@ -247,7 +364,7 @@ with it.
If you allocate the buffer yourself, the buffer must be at least as large as
the size returned by `bmpread_buffersize()`.
```
```c
unsigned char *buffer;
/* either: */
@@ -265,14 +382,14 @@ order R-G-B or R-G-B-A. The returned image is always top-down, i.e. data
starts in the top left corner. Unlike BMPs which are (almost always)
bottom-up. (See above, "Getting information...")
If `bmpread_load_image()` returns BMP_RESULT_TRUNCATED or BMP_RESULT_INVALID,
If `bmpread_load_image()` returns `BMP_RESULT_TRUNCATED` or `BMP_RESULT_INVALID`,
the file may have been damaged or simply contains invalid image data. Image
data is loaded anyway as far as possible and may be partially usable.
#### bmpread_load_line()
#### 1.12.2. bmpread_load_line()
```
BMPRESULT bmpread_load_line(BMPHANDLE h, unsigned char **pbuffer)
```c
BMPRESULT bmpread_load_line(BMPHANDLE h, unsigned char **pbuffer);
```
Loads a single scan line from the BMP file into the buffer pointed to by
@@ -286,7 +403,7 @@ To determine the required buffer size, either divide the value from
calculate from the image dimensions returned by bmplib as width * channels *
bitsperchannel / 8.
```
```c
single_line_buffersize = bmpread_buffersize(h) / bmpread_height(h);
/* or */
single_line_buffersize = bmpread_width(h) * bmpread_channels(h) * bmpread_bitsperchannel(h) / 8;
@@ -301,7 +418,7 @@ returned in whichever order they are stored in the BMP. Use the value
returned by `bmpread_orientation()` to determine if it is top-down or
bottom-up. Almost all BMPs will be bottom-up. (see above)
### Invalid pixels
### 1.13. Invalid pixels
Invalid pixels may occur in indexed BMPs, both RLE and non-RLE. Invalid pixels
either point beyond the given color palette, or they try to set pixels
@@ -310,56 +427,56 @@ be set to the maximum allowed value, and attempts to point outside the image
will be ignored.
In both cases, `bmpread_load_image()` and `bmpread_load_line()` will return
BMP_RESULT_INVALID, unless the image is also truncated, then
BMP_RESULT_TRUNCATED is returned.
`BMP_RESULT_INVALID`, unless the image is also truncated, then
`BMP_RESULT_TRUNCATED` is returned.
### Query info about the BMP file
### 1.14. Query info about the BMP file
Note: these functions return information about the original BMP file being
read. They do *not* describe the format of the returned image data, which may
be different!
```
BMPINFOVER bmpread_info_header_version(BMPHANDLE h)
int bmpread_info_header_size(BMPHANDLE h)
int bmpread_info_compression(BMPHANDLE h)
int bmpread_info_bitcount(BMPHANDLE h)
const char* bmpread_info_header_name(BMPHANDLE h)
const char* bmpread_info_compression_name(BMPHANDLE h)
BMPRESULT bmpread_info_channel_bits(BMPHANDLE h, int *r, int *g, int *b, int *a)
```c
BMPINFOVER bmpread_info_header_version(BMPHANDLE h);
int bmpread_info_header_size(BMPHANDLE h);
int bmpread_info_compression(BMPHANDLE h);
int bmpread_info_bitcount(BMPHANDLE h);
const char* bmpread_info_header_name(BMPHANDLE h);
const char* bmpread_info_compression_name(BMPHANDLE h);
BMPRESULT bmpread_info_channel_bits(BMPHANDLE h, int *r, int *g, int *b, int *a);
```
### Release the handle
### 1.15. Release the handle
```
void bmp_free(BMPHANDLE h)
```c
void bmp_free(BMPHANDLE h);
```
Frees all resources associated with the handle `h`. **Image data is not
affected**, so you can call bmp_free() immediately after `bmpread_load_image
()` and still use the returned image data.
affected**, so you can call `bmp_free()` immediately after `bmpread_load_image()`
and still use the returned image data.
Note: Any error message strings returned by `bmp_errmsg()` are invalidated by
`bmp_free()` and must not be used anymore!
## 2. Functions for writing BMP files
### Get a handle
### 2.1. Get a handle
```
BMPHANDLE bmpwrite_new(FILE *file)
```c
BMPHANDLE bmpwrite_new(FILE *file);
```
### Set image dimensions
### 2.2. Set image dimensions
```
```c
BMPRESULT bmpwrite_set_dimensions(BMPHANDLE h,
unsigned width,
unsigned height,
unsigned channels,
unsigned bitsperchannel)
unsigned bitsperchannel);
BMPRESULT bmpwrite_set_resolution(BMPHANDLE h, int xdpi, int ydpi)
BMPRESULT bmpwrite_set_resolution(BMPHANDLE h, int xdpi, int ydpi);
```
Note: the dimensions set with `bmpwrite_set_dimensions()` describe the source
@@ -367,22 +484,22 @@ data that you pass to bmplib, *not* the output BMP format. Use
`bmpwrite_set_output_bits()`, `bmpwrite_set_palette()`, and
`bmpwrite_set_64bit()` to modify the format written to the BMP file.
### Set the output format
### 2.3. Set the output format
Optional: set the bit-depth for each output channel. bmplib will otherwise
choose appropriate bit-depths for your image. The bit-depth per channel can
be anywhere between 0 and 32, inclusive. In sum, the bits must be at least 1
and must not exceed 32.
```
BMPRESULT bmpwrite_set_output_bits(BMPHANDLE h, int red, int green, int blue, int alpha)
```c
BMPRESULT bmpwrite_set_output_bits(BMPHANDLE h, int red, int green, int blue, int alpha);
```
### Indexed images
### 2.4. Indexed images
```
BMPRESULT bmpwrite_set_palette(BMPHANDLE h, int numcolors, unsigned char *palette)
BMPRESULT bmpwrite_allow_2bit(BMPHANDLE h)
```c
BMPRESULT bmpwrite_set_palette(BMPHANDLE h, int numcolors, unsigned char *palette);
BMPRESULT bmpwrite_allow_2bit(BMPHANDLE h);
```
You can write 1/2/4/8-bit indexed images by providing a color palette with
@@ -402,15 +519,15 @@ relict), as many readers will refuse to open these. If you do want a 2-bit
BMP for 3- or 4-color images, call `bmpwrite_allow_2bit()` before calling
`bmpwrite_save_image()`.
#### RLE
#### 2.4.1. RLE
```
BMPRESULT bmpwrite_set_rle(BMPHANDLE h, BMPRLETYPE type)
BMPRESULT bmpwrite_allow_huffman(BMPHANDLE h)
BMPRESULT bmpwrite_set_huffman_img_fg_idx(BMPHANDLE h, int idx)
```c
BMPRESULT bmpwrite_set_rle(BMPHANDLE h, BMPRLETYPE type);
BMPRESULT bmpwrite_allow_huffman(BMPHANDLE h);
BMPRESULT bmpwrite_set_huffman_img_fg_idx(BMPHANDLE h, int idx);
```
Indexed images may optionally be written run-lenght-encoded (RLE) bitmaps.
Indexed images may optionally be written as run-length-encoded (RLE) bitmaps.
Images with 16 or fewer colors can be written as either RLE4 or RLE8
(default is RLE4), images with more than 16 colors only as RLE8.
@@ -428,7 +545,7 @@ of the following values:
- `BMP_RLE_RLE8` use RLE8, regardless of number of colors in palette
#### 1-D Huffman encoding
#### 2.4.2. 1-D Huffman encoding
In order to write 1-D Huffman encoded bitmpas,
- the provided palette must have 2 colors,
@@ -440,12 +557,12 @@ Be aware that *very* few programs will be able to read Huffman encoded BMPs!
In order to get the best compression result, you should also call
`bmpwrite_set_huffman_img_fg_idx()` to specify which color index (0 or 1) in
the image corresponds to the foreground color. Huffman compression is
optimized for scanned text, meaning short runs of foreground color and long
(er) runs of background color. This will not change the appearance of the
optimized for scanned text, meaning short runs of foreground color and long(er)
runs of background color. This will not change the appearance of the
image, but setting it correctly will result in better compression.
#### RLE24
#### 2.4.3. RLE24
RLE24 is an old OS/2 compression method. As the name suggests, it's 24-bit RLE
for non-indexed images. Like Huffman encoding, it's very uncommon and only
@@ -456,7 +573,8 @@ In order to save an image as RLE24, the data must be provided as 8 bits per
channel RGB (no alpha channel). Call `bmpwrite_set_rle()` with type set to
`BMP_RLE_AUTO` and also call `bmpwrite_allow_rle24()` (in any order).
### top-down / bottom-up
### 2.5. top-down / bottom-up
By default, bmplib will write BMP files bottom-up, which is how BMP files are
usually orientated.
@@ -464,8 +582,8 @@ usually orientated.
For non-RLE files, you have the option to change the orientation to top-down.
(RLE files always have to be written in the default bottom-up orientation.)
```
BMPRESULT bmpwrite_set_orientation(BMPHANDLE h, BMPORIENT orientation)
```c
BMPRESULT bmpwrite_set_orientation(BMPHANDLE h, BMPORIENT orientation);
```
with `orientation` set to one of the following values:
@@ -481,26 +599,58 @@ When writing the image line-by-line using `bmpwrite_save_line()`, you must
provide the image lines in the order according to the orientation you have
chosen for the BMP file.
### 64-bit RGBA BMPs
By default, bmplib will not write 64-bit BMPs because they are rather exotic and hardly any
software can open them.
### 2.6. ICC color profiles
```c
BMPRESULT bmpwrite_set_iccprofile(BMPHANDLE h, size_t size,
const unsigned char *iccprofile);
BMPRESULT bmpwrite_set_rendering_intent(BMPHANDLE h, BMPINTENT intent);
```
Use `bmpwrite_set_iccprofile()` to write an embedded ICC color profile to the
BMP file.
bmplib will not interpret or validate the supplied profile in any way.
Setting a color profile or rendering intent will disable Huffman and RLE24 encodings.
(color profiles require a BITMAPV5HEADER, but those encodings would require
an older OS/2 info header, instead.)
You can optionally specify a rendering intent with `bmpwrite_set_rendering_intent()`,
where `intent` is one of:
- `BMP_INTENT_NONE`
- `BMP_INTENT_BUSINESS` (= saturation)
- `BMP_INTENT_GRAPHICS` (= relative colorimetric)
- `BMP_INTENT_IMAGES` (= perceptive)
- `BMP_INTENT_ABS_COLORIMETRIC` (= absolute colorimetric)
### 2.7. 64-bit RGBA BMPs
By default, bmplib will not write 64-bit BMPs because they are rather exotic
and hardly any software can open them.
If you do want to write 64-bit BMPs, call
```
BMPRESULT bmpwrite_set_64bit(BMPHANDLE h)
```c
BMPRESULT bmpwrite_set_64bit(BMPHANDLE h);
```
In order to make use of the extended range available in 64-bit BMPs (-4.0 to +3.999...), you will probably want to provide the image buffer either as 32-bit float or as 16-bit s2.13 (and call `bmp_set_number_format()` accordingly).
In order to make use of the extended range available in 64-bit BMPs
(-4.0 to +3.999...), you will probably want to provide the image buffer
either as 32-bit float or as 16-bit s2.13 (and call `bmp_set_number_format()`
accordingly).
Note: 64-bit BMPs store pixel values in *linear light*. Unlike when *reading* 64-bit BMPs, bmplib will not make any gamma/linear conversion while writing BMPs. You have to provide the proper linear values in the image buffer.
Note: 64-bit BMPs store pixel values in *linear light*. Unlike when *reading*
64-bit BMPs, bmplib will not make any gamma/linear conversion while writing
BMPs. You have to provide the proper linear values in the image buffer.
### Write the image
### 2.8. Write the image
```
BMPRESULT bmpwrite_save_image(BMPHANDLE h, const unsigned char *image)
BMPRESULT bmpwrite_save_line(BMPHANDLE h, const unsigned char *line)
```c
BMPRESULT bmpwrite_save_image(BMPHANDLE h, const unsigned char *image);
BMPRESULT bmpwrite_save_line(BMPHANDLE h, const unsigned char *line);
```
Write either the whole image at once with `bmpwrite_save_image()` or one line
@@ -512,65 +662,104 @@ in host byte order, the channels in the order R-G-B-(A). Indexed data must be
supplied as 8 bit per pixel, even when writing lower bit (1/2/4) BMPs
(see above).
Important: When writing the whole image at once using `bmpwrite_save_image
()`, the image data must be provided top-down (same as is returned by
Important: When writing the whole image at once using `bmpwrite_save_image()`,
the image data must be provided top-down (same as is returned by
`bmpread_load_image()`). When using `bmpwrite_save_line()` to write the image
line-by-line, the image data must be provided according to the orientation
set with `bmpwrite_set_orientation()` (see above).
## 3. General functions for both reading/writing BMPs
### bmp_free()
### 3.1. bmp_free()
```
void bmp_free(BMPHANDLE h)
```c
void bmp_free(BMPHANDLE h);
```
Frees all resources associated with the handle `h`. Image data is not
affected, so you can call bmp_free() immediately after bmpread_load_image
() and still use the returned image data. Note: Any error messages returned
affected, so you can call `bmp_free()` immediately after `bmpread_load_image()`
and still use the returned image data. Note: Any error messages returned
by `bmp_errmsg()` are invalidated by `bmp_free()` and cannot be used
anymore.
anymore!
### bmp_errmsg()
### 3.2. bmp_errmsg()
```
const char* bmp_errmsg(BMPHANDLE h)
```c
const char* bmp_errmsg(BMPHANDLE h);
```
Returns a zero-terminated character string containing the last error
description(s). The returned string is safe to use until any other
bmplib-function is called with the same handle.
bmplib-function is called with the same handle or the handle is freed with
`bmp_free()`.
### bmp_set_number_format()
### 3.3. bmp_set_number_format()
```
BMPRESULT bmp_set_number_format(BMPHANDLE h, BMPFORMAT format)
```c
BMPRESULT bmp_set_number_format(BMPHANDLE h, BMPFORMAT format);
```
sets the number format of the image buffer received from / passed to bmplib. `format` can be one of
- `BMP_FORMAT_INT` image buffer values are expected/returned as 8-, 16-, or 32-bit integers. (this is the default)
- `BMP_FORMAT_INT` image buffer values are expected/returned as 8-, 16-, or
32-bit integers. (this is the default)
- `BMP_FORMAT_FLOAT` image buffer values are expected/returned as 32-bit floating point numbers (C `float`).
- `BMP_FORMAT_S2_13` image buffer values are expected/returned as s2.13 fixed point numbers. s2.13 is a 16-bit format with one sign bit, 2 integer bits, and 13 bits for the fractional part. Range is from -4.0 to +3.999...
- `BMP_FORMAT_S2_13` image buffer values are expected/returned as s2.13 fixed
point numbers. s2.13 is a 16-bit format with one sign bit, 2 integer bits,
and 13 bits for the fractional part. Range is from -4.0 to +3.999...
For indexed images, `BMP_FORMAT_INT` is the only valid format.
### bmp_version()
### 3.4. bmp_version()
```
const char* bmp_version(void)
```c
const char* bmp_version(void);
```
Returns a zero-terminated character string containing the version of bmplib.
### 3.5. bmp_set_huffman_t4black_value()
```c
BMPRESULT bmp_set_huffman_t4black_value(BMPHANDLE h, int blackidx);
```
(not to be confused with `bmpwrite_set_huffman_img_fg_idx()`, which serves an
entirely different purpose, see above.)
ITU-T T.4 defines 'black' and 'white' pixel sequences (referring to fore- and
background, respectively), but it doesn't prescribe which of those is
represented by 0 or 1. That would have to be defined by a BMP specification,
but documentation on Huffman BMPs is close to non-existent.
Current consensus seems to be that 'black' is 1, i.e. indexing the second
color in the palette, and 'white' is 0, i.e. indexing the first color. This
is the default for bmplib.
In case that's wrong (in fact it's not even clear if there is a right and a
wrong), `bmp_set_huffman_t4black_value()` can be used to set the pixel value
of 'black' to either 0 or 1 (and white to the respective opposite).
Can be used both for reading and writing BMPs.
Changing this value will invert the image colors!
Reasons to use this function:
- You know that bmplib's default assumption of 'black'=1 is wrong, and you
want to set it to 0. (In that case, please also drop a note on github.)
- You don't care either way, but you want to be sure to get consistent
behaviour, in case bmplib's default is ever changed in light of new
information/documentation.
- You need to interface with other software that you know assumes 'black'=0.
## 4. Data types and constants
#### `BMPHANDLE`
Returned by `bmpread_new()` and `bmpwrite_new()`.
Identifies the current operation for all subsequent
calls to bmplib-functions.
Returned by `bmpread_new()` and `bmpwrite_new()`. Identifies the current
operation for all subsequent calls to bmplib-functions.
#### `BMPRESULT`
@@ -603,7 +792,7 @@ else {
Returned by `bmpread_info_header_version()`. Possible values are:
- `BMPINFO_CORE_OS21` BITMAPCOREHEADER aka OS21XBITMAPHEADER (12 bytes)
- `BMPINFO_OS22` OS22XBITMAPHEADER (16/40/64 bytes)
- `BMPINFO_OS22` OS22XBITMAPHEADER (16-64 bytes)
- `BMPINFO_V3` BITMAPINFOHEADER (40 bytes)
- `BMPINFO_V3_ADOBE1` BITMAPINFOHEADER with additional RGB masks (52 bytes)
- `BMPINFO_V3_ADOBE2` BITMAPINFOHEADER with additional RGBA masks (56 bytes)
@@ -629,7 +818,7 @@ Can safely be cast from/to int.
Used in `bmpread_set_undefined()`. Possible values are:
- `BMP_UNDEFINED_TO_ALPHA` (default)
- `BMP_UNDEFINED_TO_ZERO`
- `BMP_UNDEFINED_LEAVE`
Can safely be cast from/to int.
@@ -653,9 +842,9 @@ Used in `bmp_set_number_format()`. Possible values are:
## 5. Sample code
### Reading BMPs
### 5.1. Reading BMPs
```
```c
/* (all error checking left out for clarity) */
BMPHANDLE h;
@@ -705,9 +894,9 @@ Used in `bmp_set_number_format()`. Possible values are:
*/
```
### Writing BMPs
### 5.2. Writing BMPs
```
```c
/* (all error checking left out for clarity) */
BMPHANDLE h;

View File

@@ -12,15 +12,16 @@ For the complete API, refer to the *Full API Description* (API-full.md).
## 1. Reading BMP files:
```
bmpread_new()
bmpread_dimensions()
bmpread_load_image()
bmp_free()
```c
bmpread_new();
bmpread_dimensions();
bmpread_load_image();
bmp_free();
```
### Get a handle
```
```c
BMPHANDLE bmpread_new(FILE *file)
```
@@ -32,13 +33,13 @@ The handle cannot be reused to read multiple files.
### Get image dimensions
```
```c
BMPRESULT bmpread_dimensions(BMPHANDLE h,
int *width,
int *height,
int *channels,
int *bitsperchannel,
BMPORIENT *orientation)
BMPORIENT *orientation);
```
Use `bmpread_dimensions()` to get all dimensions with one call. The return
@@ -54,8 +55,8 @@ line-by-line. Can be set to NULL. (see *Full API Description*)
### Load the image
```
BMPRESULT bmpread_load_image(BMPHANDLE h, unsigned char **pbuffer)
```c
BMPRESULT bmpread_load_image(BMPHANDLE h, unsigned char **pbuffer);
```
Loads the complete image from the BMP file into the buffer pointed to by
@@ -67,7 +68,7 @@ with it.
If you allocate the buffer yourself, the buffer must be at least as large as
the size returned by `bmpread_buffersize()` (see *Full API description*).
```
```c
unsigned char *buffer;
/* either: */
@@ -86,7 +87,7 @@ in the order R-G-B or R-G-B-A. The returned image is always top-down, i.e.
data starts in the top left corner. Unlike BMPs which are (almost always)
bottom-up.
If `bmpread_load_image()` returns BMP_RESULT_TRUNCATED or BMP_RESULT_INVALID,
If `bmpread_load_image()` returns `BMP_RESULT_TRUNCATED` or `BMP_RESULT_INVALID`,
the file may have been damaged or simply contains invalid image data. Image
data is loaded anyway as far as possible and may be partially usable.
@@ -94,13 +95,13 @@ data is loaded anyway as far as possible and may be partially usable.
### Release the handle
```
void bmp_free(BMPHANDLE h)
```c
void bmp_free(BMPHANDLE h);
```
Frees all resources associated with the handle `h`. **Image data is not
affected**, so you can call bmp_free() immediately after `bmpread_load_image
()` and still use the returned image data.
affected**, so you can call `bmp_free()` immediately after `bmpread_load_image()`
and still use the returned image data.
Note: Any error message strings returned by `bmp_errmsg()` are invalidated by
`bmp_free()` and must not be used anymore!
@@ -109,25 +110,27 @@ Note: Any error message strings returned by `bmp_errmsg()` are invalidated by
## 2. Writing BMP files:
```
bmpwrite_new()
bmpwrite_set_dimensions()
bmpwrite_save_image()
bmp_free()
```c
bmpwrite_new();
bmpwrite_set_dimensions();
bmpwrite_save_image();
bmp_free();
```
### Get a handle
```
BMPHANDLE bmpwrite_new(FILE *file)
```c
BMPHANDLE bmpwrite_new(FILE *file);
```
### Set image dimensions
```
```c
BMPRESULT bmpwrite_set_dimensions(BMPHANDLE h,
unsigned width,
unsigned height,
unsigned channels,
unsigned bitsperchannel)
unsigned bitsperchannel);
```
Note: the dimensions set with `bmpwrite_set_dimensions()` describe the source
@@ -140,8 +143,8 @@ API description*)
### Write the image
```
BMPRESULT bmpwrite_save_image(BMPHANDLE h, const unsigned char *image)
```c
BMPRESULT bmpwrite_save_image(BMPHANDLE h, const unsigned char *image);
```
Write the whole image at once with `bmpwrite_save_image()`.
@@ -155,8 +158,8 @@ file will be bottom-up.)
### bmp_free()
```
void bmp_free(BMPHANDLE h)
```c
void bmp_free(BMPHANDLE h);
```
Frees all resources associated with the handle `h`.
@@ -182,7 +185,7 @@ Many bmplib functions return the success/failure of an operation as a
- `BMP_RESULT_JPEG`
- `BMP_RESULT_ERROR`
Can safely be cast from/to int. BMP_RESULT_OK is guaranteed to have the value 0.
Can safely be cast from/to int. `BMP_RESULT_OK` is guaranteed to have the value 0.
@@ -190,7 +193,7 @@ Can safely be cast from/to int. BMP_RESULT_OK is guaranteed to have the value 0.
### Reading BMPs
```
```c
/* (all error checking left out for clarity) */
BMPHANDLE h;
@@ -236,7 +239,7 @@ Can safely be cast from/to int. BMP_RESULT_OK is guaranteed to have the value 0.
### Writing BMPs
```
```c
/* (all error checking left out for clarity) */
BMPHANDLE h;

View File

@@ -8,7 +8,7 @@
Download [bmplib on github](https://github.com/rupertwh/bmplib).
## Current status (v1.7.1):
## Current status (v1.8.0):
### Reading BMP files:
- 16/24/32 bit RGB(A) with any bits/channel combination
(BI_RGB, BI_BITFIELDS, BI_ALPHABITFIELDS).
@@ -16,6 +16,8 @@ Download [bmplib on github](https://github.com/rupertwh/bmplib).
- 1/2/4/8 bit indexed (palette), including RLE4 and RLE8 compressed.
- RLE24 compressed (OS/2).
- Huffman encoded (OS/2).
- OS/2 bitmap arrays.
- OS/2 icons and pointers.
- optional line-by-line reading of BMPs.
- optionally return image data as float or s2.13 fixed point.
@@ -25,12 +27,12 @@ Download [bmplib on github](https://github.com/rupertwh/bmplib).
- most 'questionable' files (see below)
- some 'bad' files
Questionable files that failed:
Questionable files that fail:
- embedded JPEG and PNG. Not really a fail. We return BMP_RESULT_JPEG or
BMP_RESULT_PNG and leave the file pointer in the correct state to be
passed on to either libpng or libjpeg. Works as designed. Don't want to
create dependency on those libs.
- We currently ignore icc-profiles and chromaticity/gamma values. See TODO.
- We currently ignore chromaticity/gamma values from V4+ headers. See TODO.
### Writing BMP files:
@@ -125,38 +127,23 @@ conversion:
- `bmpread_set_64bit_conv()`
- `bmp_set_number_format()`
As to writing BMPs, by default bmplib will not write 64bit BMPs, as they are so exotic that only few applications will read them (other than native Microsoft tools, the new GIMP 3.0 is the only one I am aware of).
Use `bmpwrite_set_64bit()` in order to write 64bit BMPs.
As to writing BMPs, by default bmplib will not write 64bit BMPs, as they are
so exotic that only few applications will read them (other than native
Microsoft tools, the new GIMP 3.0 is the only one I am aware of). Use
`bmpwrite_set_64bit()` in order to write 64bit BMPs.
## TODOs:
### Definitely:
- [x] write indexed images.
- [x] write RLE-compressed images ~~(RLE4/RLE8 only. No OS/2 v2 BMPs)~~.
- [x] read RLE24-encoded BMPs.
- [x] read Huffman-encoded BMPs. (Still haven't found any real-life examples)
- [x] line-by-line reading/writing. ~~Right now, the image can only be
passed as a whole to/from bmplib.~~
- [ ] read/write icc-profile and chromaticity/gamma values
- [x] sanity checks for size of of image / palette. Require confirmation
above a certain size (~ 500MB?)
- [x] store undefined pixels (RLE delta and early EOL/EOF) as alpha
- [ ] read/write chromaticity/gamma values
### Maybe:
- [x] passing indexed data and palette to user (optionally) instead of
RGB-data.
- [ ] interpret icc-profile, to enable giving at least sRGB/not-sRGB info.
(Like sRGB / probably-sRGB / maybe-sRGB). Torn on that one, would need
dependency on liblcms2.
- [ ] "BA"-files (bitmap-arrays). Either return the first bitmap only
(which is the 'official' default) or let user pick one/multiple/all to
be read in sequence.
- [ ] Add a 'not-a-BMP-file' return type instead of just returning error.
- ~~[ ] icon- and pointer-files ("CI", "CP", "IC", "PT").~~
- [x] 64-bits BMPs. (I changed my mind)
### Unclear:
@@ -165,19 +152,6 @@ Use `bmpwrite_set_64bit()` in order to write 64bit BMPs.
platforms/cpus. And Windows?
### Non-feature (internal):
- [x] complete API description (see API-full.md and API-quick-start.md)
- [x] bmp-read.c is getting too big, split into several files
## Misc:
- [x] License: probably LPGL3? That's what I'm going with for now.
Cheers,
Rupert

View File

@@ -1,6 +1,6 @@
/* bmplib - bmp-common.c
*
* Copyright (c) 2024, Rupert Weber.
* Copyright (c) 2024, 2025, Rupert Weber.
*
* This file is part of bmplib.
* bmplib is free software: you can redistribute it and/or modify
@@ -36,13 +36,6 @@
#include "bmp-write.h"
struct Bmphandle {
struct {
uint32_t magic;
LOG log;
};
};
/********************************************************
@@ -62,10 +55,10 @@ API const char* bmp_version(void)
API const char* bmp_errmsg(BMPHANDLE h)
{
if (!(h && (h->magic == HMAGIC_READ || h->magic == HMAGIC_WRITE)))
if (!(h && (h->common.magic == HMAGIC_READ || h->common.magic == HMAGIC_WRITE)))
return "BMPHANDLE is NULL or invalid";
return logmsg(h->log);
return logmsg(h->common.log);
}
@@ -79,17 +72,17 @@ API BMPRESULT bmp_set_number_format(BMPHANDLE h, enum BmpFormat format)
if (!h)
return BMP_RESULT_ERROR;
switch (h->magic) {
switch (h->common.magic) {
case HMAGIC_READ:
return br_set_number_format((BMPREAD)(void*)h, format);
return br_set_number_format(&h->read, format);
case HMAGIC_WRITE:
return bw_set_number_format((BMPWRITE)(void*)h, format);
return bw_set_number_format(&h->write, format);
default:
#ifdef DEBUG
printf("bmp_set_number_format() called with invalid handle (0x%04x)\n",
(unsigned int) h->magic);
(unsigned int) h->common.magic);
#endif
break;
}
@@ -98,6 +91,25 @@ API BMPRESULT bmp_set_number_format(BMPHANDLE h, enum BmpFormat format)
/********************************************************
* bmp_set_huffman_t4black_value
*******************************************************/
API BMPRESULT bmp_set_huffman_t4black_value(BMPHANDLE h, int blackidx)
{
if (!h)
return BMP_RESULT_ERROR;
if (!(h->common.magic == HMAGIC_READ || h->common.magic == HMAGIC_WRITE))
return BMP_RESULT_ERROR;
h->common.huffman_black_is_zero = !blackidx;
return BMP_RESULT_OK;
}
/********************************************************
* bmp_free
*******************************************************/
@@ -107,18 +119,18 @@ API void bmp_free(BMPHANDLE h)
if (!h)
return;
switch (h->magic) {
switch (h->common.magic) {
case HMAGIC_READ:
br_free((BMPREAD)(void*)h);
br_free(&h->read);
break;
case HMAGIC_WRITE:
bw_free((BMPWRITE)(void*)h);
bw_free(&h->write);
break;
default:
#ifdef DEBUG
printf("bmp_free() called with invalid handle (0x%04x)\n",
(unsigned int) h->magic);
(unsigned int) h->common.magic);
#endif
break;
}
@@ -132,10 +144,8 @@ API void bmp_free(BMPHANDLE h)
BMPREAD cm_read_handle(BMPHANDLE h)
{
BMPREAD rp = (BMPREAD)(void*)h;
if (rp && rp->magic == HMAGIC_READ)
return rp;
if (h && h->common.magic == HMAGIC_READ)
return &h->read;
return NULL;
}
@@ -147,10 +157,8 @@ BMPREAD cm_read_handle(BMPHANDLE h)
BMPWRITE cm_write_handle(BMPHANDLE h)
{
BMPWRITE wp = (BMPWRITE)(void*)h;
if (wp && wp->magic == HMAGIC_WRITE)
return wp;
if (h && h->common.magic == HMAGIC_WRITE)
return &h->write;
return NULL;
}
@@ -168,10 +176,10 @@ bool cm_gobble_up(BMPREAD_R rp, int count)
if (EOF == getc(rp->file)) {
if (feof(rp->file)) {
rp->lasterr = BMP_ERR_TRUNCATED;
logerr(rp->log, "unexpected end of file");
logerr(rp->c.log, "unexpected end of file");
} else {
rp->lasterr = BMP_ERR_FILEIO;
logsyserr(rp->log, "error reading from file");
logsyserr(rp->c.log, "error reading from file");
}
return false;
}
@@ -312,18 +320,11 @@ bool cm_is_one_of(int n, int candidate, ...)
}
int cm_align4padding(unsigned long long a)
{
return (int) (cm_align4size(a) - a);
}
int cm_align2padding(unsigned long long a)
{
return (int) (cm_align2size(a) - a);
}
/*********************************************************
* endianess-agnostic functions to read/write
@@ -394,7 +395,10 @@ bool read_s16_le(FILE *file, int16_t *val)
if (!read_u16_le(file, &u16))
return false;
*val = (int16_t)u16;
if (u16 >= 0x8000U)
*val = (int16_t)(u16 - 0x8000U) - 32767 - 1;
else
*val = (int16_t)u16;
return true;
}
@@ -406,7 +410,10 @@ bool read_s32_le(FILE *file, int32_t *val)
if (!read_u32_le(file, &u32))
return false;
*val = (int32_t)u32;
if (u32 >= 0x80000000UL)
*val = (int32_t)(u32 - 0x80000000UL) - 0x7fffffffL - 1;
else
*val = (int32_t)u32;
return true;
}
@@ -433,3 +440,27 @@ int16_t s16_from_le(const unsigned char *buf)
{
return (int16_t)u16_from_le(buf);
}
/*****************************************************************************
* cm_infoheader_name
*****************************************************************************/
const char* cm_infoheader_name(enum BmpInfoVer infoversion)
{
switch (infoversion) {
case BMPINFO_CORE_OS21 : return "OS21XBITMAPHEADER";
case BMPINFO_OS22 : return "OS22XBITMAPHEADER";
case BMPINFO_V3 : return "BITMAPINFOHEADER";
case BMPINFO_V3_ADOBE1 : return "BITMAPINFOHEADER + RGB mask";
case BMPINFO_V3_ADOBE2 : return "BITMAPINFOHEADER + RGBA mask";
case BMPINFO_V4 : return "BITMAPV4HEADER";
case BMPINFO_V5 : return "BITMAPV5HEADER";
case BMPINFO_FUTURE : return "unknown future version";
default:
return "invalid infoheader version";
}
}

View File

@@ -1,6 +1,6 @@
/* bmplib - bmp-common.h
*
* Copyright (c) 2024, Rupert Weber.
* Copyright (c) 2024, 2025, Rupert Weber.
*
* This file is part of bmplib.
* bmplib is free software: you can redistribute it and/or modify
@@ -82,58 +82,76 @@ struct Colormask {
} maxval;
};
typedef struct Bmpread *BMPREAD;
typedef struct Bmpwrite *BMPWRITE;
typedef struct Bmpread *restrict BMPREAD_R;
typedef struct Bmpwrite *restrict BMPWRITE_R;
struct Palette {
int numcolors;
union Pixel color[1];
};
struct Bmpcommon {
uint32_t magic;
LOG log;
bool huffman_black_is_zero; /* defaults to false */
};
enum ReadState {
RS_INIT,
RS_EXPECT_ICON_MASK,
RS_HEADER_OK,
RS_DIMENSIONS_QUERIED,
RS_LOAD_STARTED,
RS_LOAD_DONE,
RS_ARRAY,
RS_FATAL,
};
struct Bmpread {
struct {
uint32_t magic;
LOG log;
};
struct Bmpcommon c;
FILE *file;
size_t bytes_read; /* number of bytes we have read from the file */
struct Bmpfile *fh;
struct Bmpinfo *ih;
struct Arraylist *arrayimgs;
int narrayimgs;
bool is_arrayimg;
unsigned int insanity_limit;
int width;
unsigned height;
int height;
enum BmpOrient orientation;
bool is_icon;
bool icon_is_mono;
bool has_alpha; /* original BMP has alpha channel */
enum BmpUndefined undefined_mode;
bool we_allocated_buffer;
bool line_by_line;
struct Palette *palette;
struct Colormask cmask;
unsigned char *icon_mono_and;
unsigned char *icon_mono_xor;
int icon_mono_width;
int icon_mono_height;
/* result image dimensions */
enum Bmpconv64 conv64;
bool conv64_explicit;
int result_channels;
bool result_indexed;
int result_bits_per_pixel;
int result_bytes_per_pixel;
int result_bitsperchannel;
enum BmpFormat result_format;
bool result_format_explicit;
size_t result_size;
bool conv64_explicit;
bool result_indexed;
bool result_format_explicit;
/* state */
unsigned long lasterr;
bool getinfo_called;
enum ReadState read_state;
int getinfo_return;
bool jpeg;
bool png;
bool dimensions_queried;
bool dim_queried_width;
bool dim_queried_height;
bool dim_queried_channels;
bool dim_queried_bitsperchannel;
bool image_loaded;
bool iccprofile_size_queried;
bool rle;
bool rle_eol;
bool rle_eof;
@@ -149,15 +167,18 @@ struct Bmpread {
bool file_err;
bool file_eof;
bool panic;
};
enum WriteState {
WS_INIT,
WS_DIMENSIONS_SET,
WS_SAVE_STARTED,
WS_SAVE_DONE,
WS_FATAL,
};
struct Bmpwrite {
struct {
uint32_t magic;
LOG log;
};
struct Bmpcommon c;
FILE *file;
struct Bmpfile *fh;
struct Bmpinfo *ih;
@@ -167,47 +188,57 @@ struct Bmpwrite {
int source_channels;
int source_bitsperchannel;
int source_bytes_per_pixel;
int source_format;
enum BmpFormat source_format;
bool source_has_alpha;
struct Palette *palette;
int palette_size; /* sizeof palette in bytes */
unsigned char *iccprofile;
int iccprofile_size;
/* output */
size_t bytes_written;
uint64_t bytes_written;
size_t bytes_written_before_bitdata;
bool has_alpha;
enum BmpOrient outorientation;
bool huffman_fg_idx;
struct Colormask cmask;
enum BmpRLEtype rle_requested;
int rle; /* 1, 4, or 8 */
bool allow_2bit; /* Windows CE, but many will not read it */
bool allow_huffman;
bool allow_rle24;
int rle; /* 1, 4, 8, or 24 */
bool allow_2bit; /* Windows CE */
bool allow_huffman; /* OS/2 */
bool allow_rle24; /* OS/2 */
bool out64bit;
int outbytes_per_pixel;
int padding;
int *group;
int group_count;
/* state */
enum WriteState write_state;
bool outbits_set;
bool dimensions_set;
bool saveimage_done;
bool line_by_line;
int lbl_y;
uint32_t hufbuf;
int hufbuf_len;
};
union Bmphandle {
struct Bmpcommon common;
struct Bmpread read;
struct Bmpwrite write;
};
typedef struct Bmpread *BMPREAD;
typedef struct Bmpwrite *BMPWRITE;
typedef struct Bmpread *restrict BMPREAD_R;
typedef struct Bmpwrite *restrict BMPWRITE_R;
bool cm_all_lessoreq_int(int limit, int n, ...);
bool cm_all_equal_int(int n, ...);
bool cm_all_positive_int(int n, ...);
bool cm_is_one_of(int n, int candidate, ...);
#define cm_align4size(a) ((((a) + 3) >> 2) << 2)
#define cm_align2size(a) ((((a) + 1) >> 1) << 1)
#define cm_align4size(a) (((a) + 3) & ~3ULL)
int cm_align4padding(unsigned long long a);
int cm_align2padding(unsigned long long a);
int cm_count_bits(unsigned long v);
bool cm_gobble_up(BMPREAD_R rp, int count);
@@ -232,6 +263,8 @@ int32_t s32_from_le(const unsigned char *buf);
uint16_t u16_from_le(const unsigned char *buf);
int16_t s16_from_le(const unsigned char *buf);
const char* cm_infoheader_name(enum BmpInfoVer infoversion);
#define HMAGIC_READ 0x44414552UL
#define HMAGIC_WRITE 0x54495257UL
@@ -248,6 +281,7 @@ int16_t s16_from_le(const unsigned char *buf);
#define BMPIHSIZE_V3 40
#define BMPIHSIZE_V4 108
#define BMPIHSIZE_OS22 64
#define BMPIHSIZE_V5 124
struct Bmpfile {
uint16_t type; /* "BM" */
@@ -307,7 +341,17 @@ struct Bmpinfo {
enum BmpInfoVer version;
};
struct Bmparray {
uint16_t type;
uint32_t size;
uint32_t offsetnext;
uint16_t screenwidth;
uint16_t screenheight;
};
#define IH_PROFILEDATA_OFFSET (14L + 112L)
#define MAX_ICCPROFILE_SIZE (1UL << 20)
#define BI_RGB 0
@@ -334,3 +378,9 @@ struct Bmpinfo {
#define LCS_WINDOWS_COLOR_SPACE 0x57696e20 /* 'Win ' */
#define PROFILE_LINKED 0x4c494e4b /* 'LINK' */
#define PROFILE_EMBEDDED 0x4d424544 /* 'MBED' */
#define LCS_GM_BUSINESS 1
#define LCS_GM_GRAPHICS 2
#define LCS_GM_IMAGES 4
#define LCS_GM_ABS_COLORIMETRIC 8

360
bmp-read-icons.c Normal file
View File

@@ -0,0 +1,360 @@
/* bmplib - bmp-read-icons.c
*
* Copyright (c) 2025, Rupert Weber.
*
* This file is part of bmplib.
* bmplib is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library.
* If not, see <https://www.gnu.org/licenses/>
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <limits.h>
#include <stdbool.h>
#define BMPLIB_LIB
#include "config.h"
#include "bmplib.h"
#include "logging.h"
#include "bmp-common.h"
#include "bmp-read-icons.h"
/********************************************************
* bmpread_array_num
*******************************************************/
API int bmpread_array_num(BMPHANDLE h)
{
BMPREAD rp;
if (!(rp = cm_read_handle(h)))
return BMP_RESULT_ERROR;
if (rp->read_state != RS_ARRAY) {
logerr(rp->c.log, "Not a bitmap array");
return -1;
}
return rp->narrayimgs;
}
/********************************************************
* bmpread_array_info
*******************************************************/
API BMPRESULT bmpread_array_info(BMPHANDLE h, struct BmpArrayInfo *ai, int idx)
{
BMPREAD rp;
if (!(rp = cm_read_handle(h)))
return BMP_RESULT_ERROR;
if (rp->read_state != RS_ARRAY) {
logerr(rp->c.log, "Not a bitmap array");
return BMP_RESULT_ERROR;
}
if (idx < 0 || idx >= rp->narrayimgs) {
logerr(rp->c.log, "Invalid array index %d. Max is %d", idx, rp->narrayimgs - 1);
return BMP_RESULT_ERROR;
}
if (!ai) {
logerr(rp->c.log, "Invalid array info pointer (NULL)");
return BMP_RESULT_ERROR;
}
struct Arraylist *img = &rp->arrayimgs[idx];
BMPREAD imgrp = (BMPREAD)img->handle;
memset(ai, 0, sizeof *ai);
ai->type = imgrp->fh->type;
ai->handle = img->handle;
ai->width = imgrp->width;
ai->height = imgrp->height;
if (imgrp->ih->bitcount <= 8)
ai->ncolors = 1 << imgrp->ih->bitcount;
else
ai->ncolors = 0;
ai->screenwidth = img->ah.screenwidth;
ai->screenheight = img->ah.screenheight;
return BMP_RESULT_OK;
}
/********************************************************
* icon_read_array
*******************************************************/
static bool s_read_array_header(BMPREAD_R rp, struct Bmparray *ah);
static void s_array_header_from_file_header(struct Bmparray *ah, struct Bmpfile *fh);
bool icon_read_array(BMPREAD_R rp)
{
struct Arraylist *imgs = NULL;
struct Bmparray ah = { 0 };
int n = 0;
const int nmax = 16;
bool invalid = false;
if (!(imgs = calloc(nmax, sizeof *imgs))) {
logsyserr(rp->c.log, "Allocating bitmap array list");
rp->lasterr = BMP_ERR_MEMORY;
return false;
}
s_array_header_from_file_header(&ah, rp->fh);
while (n < nmax) {
if (ah.type != BMPFILE_BA) {
logerr(rp->c.log, "Invalid BMP type (0x%04x), expected 'BA'", (unsigned) ah.type);
invalid = true;
rp->lasterr = BMP_ERR_HEADER;
break;
}
memcpy(&imgs[n].ah, &ah, sizeof ah);
imgs[n].handle = bmpread_new(rp->file);
if (imgs[n].handle) {
if (BMP_RESULT_OK == bmpread_load_info(imgs[n].handle)) {
((BMPREAD)imgs[n].handle)->is_arrayimg = true;
n++;
} else {
bmp_free(imgs[n].handle);
invalid = true;
rp->lasterr = BMP_ERR_HEADER;
break;
}
} else {
logerr(rp->c.log, "Failed to create handle for array image");
invalid = true;
rp->lasterr = BMP_ERR_MEMORY;
break;
}
if (!ah.offsetnext)
break;
#if ( LONG_MAX <= 0x7fffffffL )
if (ah.offsetnext > (unsigned long)LONG_MAX) {
logerr(rp->c.log, "Invalid offset to next array image: %lu", (unsigned long)ah.offsetnext);
invalid = true;
rp->lasterr = BMP_ERR_HEADER;
break;
}
#endif
if (fseek(rp->file, ah.offsetnext, SEEK_SET)) {
logsyserr(rp->c.log, "Seeking next array header");
invalid = true;
rp->lasterr = BMP_ERR_FILEIO;
break;
}
if (!s_read_array_header(rp, &ah)) {
invalid = true;
break;
}
}
rp->arrayimgs = imgs;
rp->narrayimgs = n;
return !invalid;
}
/********************************************************
* s_read_array_header
*******************************************************/
static bool s_read_array_header(BMPREAD_R rp, struct Bmparray *ah)
{
if (read_u16_le(rp->file, &ah->type) &&
read_u32_le(rp->file, &ah->size) &&
read_u32_le(rp->file, &ah->offsetnext) &&
read_u16_le(rp->file, &ah->screenwidth) &&
read_u16_le(rp->file, &ah->screenheight)) {
return true;
}
if (feof(rp->file)) {
logerr(rp->c.log, "unexpected end-of-file while reading "
"array header");
rp->lasterr = BMP_ERR_TRUNCATED;
} else {
logsyserr(rp->c.log, "error reading array header");
rp->lasterr = BMP_ERR_FILEIO;
}
return false;
}
/********************************************************
* s_array_header_from_file_header
*******************************************************/
static void s_array_header_from_file_header(struct Bmparray *ah, struct Bmpfile *fh)
{
ah->type = fh->type;
ah->size = fh->size;
ah->offsetnext = (uint32_t)fh->reserved2 << 16 | fh->reserved1;
ah->screenwidth = fh->offbits & 0xffff;
ah->screenheight = (fh->offbits >> 16) & 0xffff;
}
/********************************************************
* icon_load_masks
*******************************************************/
long icon_load_masks(BMPREAD_R rp)
{
/* OS/2 icons and pointers contain 1-bit AND and XOR masks, stacked in a single
* image. For monochrome (IC/PT), that's all the image; for color (CI/CP), these are
* followed by a complete color image (including headers), the masks are only used
* for transparency information.
*/
BMPHANDLE hmono = NULL;
BMPREAD rpmono;
unsigned char *monobuf = NULL;
size_t bufsize;
unsigned bmptype = rp->fh->type;
long posmono = 0, poscolor = 0;
if (fseek(rp->file, -14, SEEK_CUR)) {
logsyserr(rp->c.log, "Seeking to start of icon/pointer");
goto abort;
}
if (-1 == (posmono = ftell(rp->file))) {
logsyserr(rp->c.log, "Saving file position");
goto abort;
}
/* first, load monochrome XOR/AND bitmap. We'll use the
* AND bitmap as alpha channel for the color bitmap
*/
if (!(hmono = bmpread_new(rp->file))) {
logerr(rp->c.log, "Getting handle for monochrome XOR/AND map");
goto abort;
}
rpmono = cm_read_handle(hmono);
rpmono->read_state = RS_EXPECT_ICON_MASK;
if (BMP_RESULT_OK != bmpread_load_info(hmono)) {
logerr(rp->c.log, "%s", bmp_errmsg(hmono));
goto abort;
}
if (rpmono->fh->type != bmptype) {
logerr(rp->c.log, "File type mismatch. Have 0x%04x, expected 0x%04x",
(unsigned)rpmono->fh->type, bmptype);
}
if (rp->fh->type == BMPFILE_CI || rp->fh->type == BMPFILE_CP) {
if (-1 == (poscolor = ftell(rp->file))) {
logsyserr(rp->c.log, "Saving position of color header");
goto abort;
}
}
if (!(rpmono->width > 0 && rpmono->height > 0 && rpmono->width <=512 && rpmono->height <= 512)) {
logerr(rp->c.log, "Invalid icon/pointer dimensions: %dx%d", rpmono->width, rpmono->height);
goto abort;
}
if (rpmono->ih->bitcount != 1) {
logerr(rp->c.log, "Invalid icon/pointer monochrome bitcount: %d", rpmono->ih->bitcount);
goto abort;
}
if (rpmono->height & 1) {
logerr(rp->c.log, "Invalid odd icon/pointer height: %d (must be even)", rpmono->height);
goto abort;
}
int width, height, bitsperchannel, channels;
if (BMP_RESULT_OK != bmpread_dimensions(hmono, &width, &height, &channels, &bitsperchannel, NULL)) {
logerr(rp->c.log, "%s", bmp_errmsg(hmono));
goto abort;
}
height /= 2; /* mochrome contains two stacked bitmaps (AND and XOR) */
if (channels != 3 || bitsperchannel != 8) {
logerr(rp->c.log, "Unexpected result color depth for monochrome image: "
"%d channels, %d bits/channel", channels, bitsperchannel);
goto abort;
}
/* store the AND/XOR bitmaps in the main BMPREAD struct */
bufsize = bmpread_buffersize(hmono);
if (BMP_RESULT_OK != bmpread_load_image(hmono, &monobuf)) {
logerr(rp->c.log, "%s", bmp_errmsg(hmono));
goto abort;
}
if (!(bufsize > 0 && monobuf != NULL)) {
logerr(rp->c.log, "Panic! unkown error while loading monochrome bitmap");
goto abort;
}
if (!(rp->icon_mono_and = malloc(width * height))) {
logsyserr(rp->c.log, "Allocating mono AND bitmap");
goto abort;
}
if (!(rp->icon_mono_xor = malloc(width * height))) {
logsyserr(rp->c.log, "Allocating mono XOR bitmap");
goto abort;
}
for (int i = 0; i < width * height; i++)
rp->icon_mono_and[i] = 255 - monobuf[3 * i];
for (int i = 0; i < width * height; i++)
rp->icon_mono_xor[i] = monobuf[3 * (width * height + i)];
rp->icon_mono_width = width;
rp->icon_mono_height = height;
free(monobuf);
monobuf = NULL;
bmp_free(hmono);
hmono = NULL;
if (rp->fh->type == BMPFILE_CI || rp->fh->type == BMPFILE_CP)
return poscolor;
return posmono;
abort:
if (hmono)
bmp_free(hmono);
if (monobuf)
free(monobuf);
return -1;
}

28
bmp-read-icons.h Normal file
View File

@@ -0,0 +1,28 @@
/* bmplib - bmp-read-icons.h
*
* Copyright (c) 2025, Rupert Weber.
*
* This file is part of bmplib.
* bmplib is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library.
* If not, see <https://www.gnu.org/licenses/>
*/
struct Arraylist {
struct Bmparray ah;
BMPHANDLE handle;
};
long icon_load_masks(BMPREAD_R rp);
bool icon_read_array(BMPREAD_R rp);

View File

@@ -1,6 +1,6 @@
/* bmplib - bmp-read-loadimage.c
*
* Copyright (c) 2024, Rupert Weber.
* Copyright (c) 2024, 2025, Rupert Weber.
*
* This file is part of bmplib.
* bmplib is free software: you can redistribute it and/or modify
@@ -23,6 +23,7 @@
#include <string.h>
#include <stdint.h>
#include <stdbool.h>
#include <limits.h>
#include <assert.h>
#include <math.h>
@@ -65,7 +66,7 @@ static void s_log_error_from_state(BMPREAD_R rp);
static bool s_cont_error(BMPREAD_R rp);
static bool s_stopping_error(BMPREAD_R rp);
static inline int s_read_one_byte(BMPREAD_R rp);
static inline void s_int_to_result_format(BMPREAD_R rp, int frombits, unsigned char *restrict px);
static inline void s_int8_to_result_format(BMPREAD_R rp, const int *restrict fromrgba, unsigned char *restrict px);
static BMPRESULT s_load_image_or_line(BMPREAD_R rp, unsigned char **restrict buffer, bool line_by_line);
static void s_read_rgb_line(BMPREAD_R rp, unsigned char *restrict line);
@@ -73,9 +74,10 @@ static void s_read_indexed_line(BMPREAD_R rp, unsigned char *restrict line);
static void s_read_rle_line(BMPREAD_R rp, unsigned char *restrict line,
int *restrict x, int *restrict yoff);
static void s_read_huffman_line(BMPREAD_R rp, unsigned char *restrict line);
static bool s_are_settings_icon_compatible(BMPREAD_R rp);
_Static_assert(sizeof(float) == 4, "sizeof(float) must be 4. Cannot build bmplib.");
_Static_assert(sizeof(int) >= 4, "int must be at least 32bit. Cannot build bmplib.");
static_assert(sizeof(float) == 4, "sizeof(float) must be 4. Cannot build bmplib.");
static_assert(sizeof(int) * CHAR_BIT >= 32, "int must be at least 32bit. Cannot build bmplib.");
/********************************************************
@@ -105,7 +107,7 @@ API BMPRESULT bmpread_load_line(BMPHANDLE h, unsigned char **restrict buffer)
if (!(rp = cm_read_handle(h)))
return BMP_RESULT_ERROR;
logreset(rp->log); /* otherwise we might accumulate thousands */
logreset(rp->c.log); /* otherwise we might accumulate thousands */
/* of log entries with large corrupt images */
return s_load_image_or_line(rp, buffer, true);
@@ -124,33 +126,48 @@ static BMPRESULT s_load_image_or_line(BMPREAD_R rp, unsigned char **restrict buf
{
size_t buffer_size;
if (!(rp->getinfo_called && (rp->getinfo_return == BMP_RESULT_OK))) {
if (rp->getinfo_return == BMP_RESULT_INSANE) {
logerr(rp->log, "trying to load insanley large image");
return BMP_RESULT_INSANE;
if (rp->read_state == RS_FATAL) {
logerr(rp->c.log, "Cannot load image due to a previous fatal error");
return BMP_RESULT_ERROR;
}
if (rp->read_state >= RS_ARRAY) {
logerr(rp->c.log, "Invalid operation on bitmap array");
return BMP_RESULT_ERROR;
}
if (rp->read_state >= RS_LOAD_DONE) {
logerr(rp->c.log, "Cannot load image more than once!");
return BMP_RESULT_ERROR;
}
if (rp->read_state >= RS_LOAD_STARTED && !line_by_line) {
logerr(rp->c.log, "Image is being loaded line-by-line. "
"Cannot switch to full image.");
return BMP_RESULT_ERROR;
}
if (rp->read_state < RS_DIMENSIONS_QUERIED) {
logerr(rp->c.log, "Must query dimensions before loading image");
return BMP_RESULT_ERROR;
}
if (rp->getinfo_return == BMP_RESULT_INSANE) {
logerr(rp->c.log, "trying to load insanley large image");
return BMP_RESULT_INSANE;
}
if (rp->read_state < RS_LOAD_STARTED && rp->is_icon) {
if (!s_are_settings_icon_compatible(rp)) {
logerr(rp->c.log, "Panic! Trying to load icon/pointer with incompatibele settings.\n");
rp->read_state = RS_FATAL;
rp->lasterr = BMP_ERR_INTERNAL;
return BMP_RESULT_ERROR;
}
logerr(rp->log, "getinfo had failed, cannot load image");
return BMP_RESULT_ERROR;
}
if (rp->image_loaded) {
logerr(rp->log, "Cannot load image more than once!");
return BMP_RESULT_ERROR;
}
if (rp->line_by_line && !line_by_line) {
logerr(rp->log, "Image is being loaded line-by-line. "
"Cannot switch to full image.");
return BMP_RESULT_ERROR;
}
if (!rp->dimensions_queried) {
logerr(rp->log, "must query dimensions before loading image");
return BMP_RESULT_ERROR;
}
if (!buffer) {
logerr(rp->log, "buffer pointer is NULL");
logerr(rp->c.log, "Buffer pointer is NULL. (It may point to a NULL pointer, but must not itself be NULL)");
return BMP_RESULT_ERROR;
}
@@ -160,7 +177,7 @@ static BMPRESULT s_load_image_or_line(BMPREAD_R rp, unsigned char **restrict buf
buffer_size = rp->result_size;
if (!*buffer) { /* no buffer supplied, we will allocate one */
if (!(*buffer = malloc(buffer_size))) {
logsyserr(rp->log, "allocating result buffer");
logsyserr(rp->c.log, "allocating result buffer");
return BMP_RESULT_ERROR;
}
rp->we_allocated_buffer = true;
@@ -171,34 +188,30 @@ static BMPRESULT s_load_image_or_line(BMPREAD_R rp, unsigned char **restrict buf
if (rp->we_allocated_buffer || (rp->rle && (rp->undefined_mode == BMP_UNDEFINED_TO_ALPHA)))
memset(*buffer, 0, buffer_size);
if (!line_by_line)
rp->image_loaded = true; /* point of no return */
if (!rp->line_by_line) { /* either whole image or first line */
if (rp->read_state < RS_LOAD_STARTED) { /* either whole image or first line */
if (rp->bytes_read > rp->fh->offbits) {
logerr(rp->log, "Corrupt file");
logerr(rp->c.log, "Corrupt file, invalid offset to image bitmap data");
goto abort;
}
/* skip to actual bitmap data: */
if (!cm_gobble_up(rp, rp->fh->offbits - rp->bytes_read)) {
logerr(rp->log, "while seeking start of bitmap data");
/*if (!cm_gobble_up(rp, rp->fh->offbits - rp->bytes_read)) {*/
if (fseek(rp->file, (long)rp->fh->offbits, SEEK_SET)) {
logerr(rp->c.log, "while seeking start of bitmap data");
goto abort;
}
rp->bytes_read += rp->fh->offbits - rp->bytes_read;
rp->read_state = RS_LOAD_STARTED;
}
if (line_by_line) {
rp->line_by_line = true; /* don't set this earlier, or we won't */
/* be able to identify first line */
if (line_by_line)
s_read_one_line(rp, *buffer);
} else {
else
s_read_whole_image(rp, *buffer);
}
s_log_error_from_state(rp);
if (s_stopping_error(rp)) {
rp->truncated = true;
rp->image_loaded = true;
rp->read_state = RS_FATAL;
return BMP_RESULT_TRUNCATED;
} else if (s_cont_error(rp))
return BMP_RESULT_INVALID;
@@ -210,10 +223,42 @@ abort:
free(*buffer);
*buffer = NULL;
}
rp->image_loaded = true;
rp->read_state = RS_FATAL;
return BMP_RESULT_ERROR;
}
static bool s_are_settings_icon_compatible(BMPREAD_R rp)
{
/* some catch-all sanity checks for icons/pointers. Strictly, these
* shouldn't be necessary, as they should have been caught already.
* If any of these fail, there is a bug somewhere else.
*/
if (rp->result_channels != 4 || rp->result_bitsperchannel != 8)
return false;
if (rp->result_format != BMP_FORMAT_INT)
return false;
if (rp->rle && (rp->undefined_mode != BMP_UNDEFINED_LEAVE))
return false;
if (!(rp->rle || (rp->ih->compression == BI_RGB)))
return false;
return true;
}
/********************************************************
* apply_icon_alpha
*******************************************************/
static void apply_icon_alpha(BMPREAD_R rp, int y, unsigned char *restrict line)
{
for (int x = 0; x < rp->width; x++) {
line[x * 4 + 3] = rp->icon_mono_and[(rp->height - y - 1) * rp->width + x];
}
}
/********************************************************
@@ -227,7 +272,7 @@ static void s_read_whole_image(BMPREAD_R rp, unsigned char *restrict image)
linesize = (size_t) rp->width * rp->result_bytes_per_pixel;
for (y = 0; y < (int) rp->height; y += yoff) {
for (y = 0; y < rp->height; y += yoff) {
real_y = (rp->orientation == BMP_ORIENT_TOPDOWN) ? y : rp->height-1-y;
s_read_one_line(rp, image + real_y * linesize);
if (rp->rle_eof || s_stopping_error(rp))
@@ -240,6 +285,7 @@ static void s_read_whole_image(BMPREAD_R rp, unsigned char *restrict image)
/********************************************************
* s_read_one_line
*******************************************************/
static void s_read_monoicon_line(BMPREAD_R rp, unsigned char *restrict line, int y);
static void s_read_one_line(BMPREAD_R rp, unsigned char *restrict line)
{
@@ -258,13 +304,15 @@ static void s_read_one_line(BMPREAD_R rp, unsigned char *restrict line)
} else {
if (rp->ih->compression == BI_OS2_HUFFMAN) {
s_read_huffman_line(rp, line);
} else if (rp->is_icon && rp->icon_is_mono) {
s_read_monoicon_line(rp, line, rp->lbl_y);
} else {
s_read_indexed_line(rp, line);
}
}
if (!(rp->rle_eof || s_stopping_error(rp))) {
if (yoff > (int) rp->height - rp->lbl_file_y) {
if (yoff > rp->height - rp->lbl_file_y) {
rp->invalid_delta = true;
}
rp->lbl_file_y += yoff;
@@ -277,13 +325,31 @@ static void s_read_one_line(BMPREAD_R rp, unsigned char *restrict line)
s_read_rgb_line(rp, line);
}
if (rp->is_icon) {
apply_icon_alpha(rp, rp->lbl_y, line);
}
rp->lbl_y++;
if (rp->lbl_y >= (int) rp->height) {
rp->image_loaded = true;
if (rp->lbl_y >= rp->height) {
rp->read_state = RS_LOAD_DONE;
}
}
/********************************************************
* s_read_monoicon_line
*******************************************************/
static void s_read_monoicon_line(BMPREAD_R rp, unsigned char *restrict line, int y)
{
for (int x = 0; x < rp->width; x++) {
for (int c = 0; c < 3; c++) {
line[rp->result_bytes_per_pixel * x + c] =
rp->icon_mono_xor[(rp->height - y - 1) * rp->width + x];
}
}
}
/********************************************************
* s_read_rgb_line
@@ -291,9 +357,10 @@ static void s_read_one_line(BMPREAD_R rp, unsigned char *restrict line)
static inline bool s_read_rgb_pixel(BMPREAD_R rp, union Pixel *restrict px);
static inline double s_s2_13_to_float(uint16_t s2_13);
static inline uint16_t s_float_to_s2_13(double d);
static inline double s_int_to_float(unsigned long ul, int bits);
static inline void s_convert64(uint16_t *val64);
static inline void s_convert64srgb(uint16_t *val64);
static inline void s_convert64(uint16_t val64[static 4]);
static inline void s_convert64srgb(uint16_t val64[static 4]);
static inline double s_srgb_gamma_float(double d);
static inline uint16_t s_srgb_gamma_s2_13(uint16_t s2_13);
@@ -330,7 +397,7 @@ static void s_read_rgb_line(BMPREAD_R rp, unsigned char *restrict line)
((uint32_t*)line)[offs + i] = pxval;
break;
default:
logerr(rp->log, "Waaaaaaaaaaaaaah!");
logerr(rp->c.log, "Waaaaaaaaaaaaaah!");
rp->panic = true;
return;
}
@@ -376,14 +443,13 @@ static void s_read_rgb_line(BMPREAD_R rp, unsigned char *restrict line)
} else {
for (i = 0; i < rp->result_channels; i++) {
d = s_int_to_float(px.value[i], rp->cmask.bits.value[i]);
d = d * 8192.0 + 0.5;
((uint16_t*)line)[offs+i] = (uint16_t) d;
((uint16_t*)line)[offs+i] = s_float_to_s2_13(d);
}
}
break;
default:
logerr(rp->log, "Unknown format");
logerr(rp->c.log, "Unknown format");
rp->panic = true;
return;
}
@@ -399,23 +465,41 @@ static void s_read_rgb_line(BMPREAD_R rp, unsigned char *restrict line)
static inline double s_s2_13_to_float(uint16_t s2_13)
{
return (int16_t)s2_13 / 8192.0;
int16_t s16;
if (s2_13 >= 0x8000)
s16 = (int16_t)(s2_13 - 0x8000) - 0x7fff - 1;
else
s16 = (int16_t)s2_13;
return s16 / 8192.0;
}
static inline uint16_t s_float_to_s2_13(double d)
{
d = MIN(d, 3.99987793);
d = MAX(-4.0, d);
return (uint16_t) ((int)round(d * 8192.0) & 0xffff);
}
static inline double s_int_to_float(unsigned long ul, int bits)
{
return (double) ul / ((1ULL<<bits)-1);
return (double) ul / ((1ULL << bits) - 1);
}
static inline void s_convert64(uint16_t *val64)
static inline void s_convert64(uint16_t val64[static 4])
{
/* convert the s2.13 values of a 64bit BMP to plain old 16bit integers.
* Values are clipped to the representable [0..1] range
*/
double d;
for (int i = 0; i < 4; i++) {
d = (double) (int16_t) val64[i];
d /= 8192.0;
d = s_s2_13_to_float(val64[i]);
d = MAX(0.0, d);
d = MIN(d, 1.0);
val64[i] = (uint16_t) (d * 0xffff + 0.5);
@@ -423,13 +507,14 @@ static inline void s_convert64(uint16_t *val64)
}
static inline void s_convert64srgb(uint16_t *val64)
static inline void s_convert64srgb(uint16_t val64[static 4])
{
/* Same as s_convert64(), but also apply sRGB gamma. */
double d;
for (int i = 0; i < 4; i++) {
d = (double) (int16_t) val64[i];
d /= 8192.0;
d = s_s2_13_to_float(val64[i]);
d = MAX(0.0, d);
d = MIN(d, 1.0);
@@ -455,11 +540,11 @@ static inline double s_srgb_gamma_float(double d)
static inline uint16_t s_srgb_gamma_s2_13(uint16_t s2_13)
{
double d;
double d;
d = (int16_t)s2_13 / 8192.0;
d = s_s2_13_to_float(s2_13);
d = s_srgb_gamma_float(d);
return (uint16_t) (((int)(d * 8192.0 + 0.5)) & 0xffff);
return s_float_to_s2_13(d);
}
@@ -513,14 +598,13 @@ static inline bool s_buffer32_fill(BMPREAD_R rp, struct Buffer32 *restrict buf)
for (int i = 0; i < 4; i++) {
if (EOF == (byte = s_read_one_byte(rp))) {
s_set_file_error(rp);
return false;
break;
}
buf->buffer <<= 8;
buf->buffer |= byte;
buf->buffer |= ((uint32_t)byte) << (8 * (3 - i));
buf->n += 8;
}
buf->n = 32;
return true;
return buf->n > 0;
}
@@ -528,7 +612,8 @@ static inline uint32_t s_buffer32_bits(struct Buffer32 *restrict buf, int nbits)
{
uint32_t result;
assert(nbits < 32);
assert(nbits == 1 || nbits == 2 || nbits == 4 || nbits == 8);
assert(nbits <= buf->n);
result = buf->buffer >> (32 - nbits);
buf->buffer = (buf->buffer << nbits) & 0xffffffffUL;
@@ -540,9 +625,10 @@ static inline uint32_t s_buffer32_bits(struct Buffer32 *restrict buf, int nbits)
static void s_read_indexed_line(BMPREAD_R rp, unsigned char *restrict line)
{
int x = 0, v;
bool done = false;
struct Buffer32 buffer;
size_t offs;
int rgba[4] = { 0 };
bool done = false;
/* the buffer size of 32 bits takes care of padding bytes */
@@ -561,10 +647,10 @@ static void s_read_indexed_line(BMPREAD_R rp, unsigned char *restrict line)
if (rp->result_indexed) {
line[offs] = v;
} else {
line[offs] = rp->palette->color[v].red;
line[offs+1] = rp->palette->color[v].green;
line[offs+2] = rp->palette->color[v].blue;
s_int_to_result_format(rp, 8, line + offs);
rgba[0] = rp->palette->color[v].red;
rgba[1] = rp->palette->color[v].green;
rgba[2] = rp->palette->color[v].blue;
s_int8_to_result_format(rp, rgba, line + offs);
}
if (++x == rp->width) {
@@ -589,6 +675,7 @@ static void s_read_rle_line(BMPREAD_R rp, unsigned char *restrict line,
bool repeat = false, padding = false, odd = false;
int right, up;
int v, r = 0, g = 0, b = 0;
int rgba[4] = { 0, 0, 0, 0xff };
size_t offs;
int bits = rp->ih->bitcount;
@@ -622,14 +709,12 @@ static void s_read_rle_line(BMPREAD_R rp, unsigned char *restrict line,
}
offs = (size_t) *x * rp->result_bytes_per_pixel;
if ((rp->undefined_mode == BMP_UNDEFINED_TO_ALPHA) && !rp->result_indexed)
line[offs+3] = 0xff; /* set alpha to 1.0 for defined pixels */
switch (bits) {
case 24:
line[offs] = r;
line[offs+1] = g;
line[offs+2] = b;
s_int_to_result_format(rp, 8, line + offs);
rgba[0] = r;
rgba[1] = g;
rgba[2] = b;
s_int8_to_result_format(rp, rgba, line + offs);
break;
case 4:
case 8:
@@ -646,10 +731,10 @@ static void s_read_rle_line(BMPREAD_R rp, unsigned char *restrict line,
if (rp->result_indexed) {
line[offs] = v;
} else {
line[offs] = rp->palette->color[v].red;
line[offs+1] = rp->palette->color[v].green;
line[offs+2] = rp->palette->color[v].blue;
s_int_to_result_format(rp, 8, line + offs);
rgba[0] = rp->palette->color[v].red;
rgba[1] = rp->palette->color[v].green;
rgba[2] = rp->palette->color[v].blue;
s_int8_to_result_format(rp, rgba, line + offs);
}
break;
}
@@ -747,7 +832,7 @@ static void s_read_rle_line(BMPREAD_R rp, unsigned char *restrict line,
continue;
}
logerr(rp->log, "Should never get here! (x=%d, byte=%d)", (int) *x, (int) v);
logerr(rp->c.log, "Should never get here! (x=%d, byte=%d)", (int) *x, (int) v);
rp->panic = true;
break;
}
@@ -764,6 +849,7 @@ static void s_read_huffman_line(BMPREAD_R rp, unsigned char *restrict line)
{
size_t offs;
int x = 0, runlen;
int rgba[4] = { 0 };
bool black = false;
while (x < rp->width) {
@@ -800,12 +886,12 @@ static void s_read_huffman_line(BMPREAD_R rp, unsigned char *restrict line)
for (int i = 0; i < runlen; i++, x++) {
offs = (size_t) x * rp->result_bytes_per_pixel;
if (rp->result_indexed) {
line[offs] = black;
line[offs] = black ^ rp->c.huffman_black_is_zero;
} else {
line[offs] = rp->palette->color[black].red;
line[offs+1] = rp->palette->color[black].green;
line[offs+2] = rp->palette->color[black].blue;
s_int_to_result_format(rp, 8, line + offs);
rgba[0] = rp->palette->color[black ^ rp->c.huffman_black_is_zero].red;
rgba[1] = rp->palette->color[black ^ rp->c.huffman_black_is_zero].green;
rgba[2] = rp->palette->color[black ^ rp->c.huffman_black_is_zero].blue;
s_int8_to_result_format(rp, rgba, line + offs);
}
}
black = !black;
@@ -859,55 +945,29 @@ static bool s_huff_find_eol(BMPREAD_R rp)
/********************************************************
* s_int_to_result_format
* convert integer values in image buffer
* s_int8_to_result_format
* convert 8-bit integer values (from indexed images)
* to selected number format.
*******************************************************/
static inline void s_int_to_result_format(BMPREAD_R rp, int frombits, unsigned char *restrict px)
static inline void s_int8_to_result_format(BMPREAD_R rp, const int *restrict fromrgba, unsigned char *restrict px)
{
int c;
uint32_t v;
if (rp->result_format == BMP_FORMAT_INT)
return;
#ifdef DEBUG
if (frombits > rp->result_bitsperchannel) {
printf("This is bad, frombits must be <= result_bitsperchannel");
exit(1);
}
#endif
for (c = rp->result_channels - 1; c >= 0; c--) {
/* going backwards because we are converting in place and
* always growing, never shrinking
*/
switch (frombits) {
case 8:
v = px[c];
break;
case 16:
v = ((uint16_t*)px)[c];
break;
case 32:
v = ((uint32_t*)px)[c];
break;
default:
#ifdef DEBUG
printf("Invalid pixel int size %d!!!", frombits);
exit(1);
#endif
break;
}
for (int c = 0; c < rp->result_channels; c++) {
switch (rp->result_format) {
case BMP_FORMAT_INT:
assert(rp->result_bitsperchannel == 8);
px[c] = fromrgba[c];
break;
case BMP_FORMAT_FLOAT:
((float*)px)[c] = (float) ((double) v / ((1ULL<<frombits)-1));
((float*)px)[c] = s_int_to_float(fromrgba[c], 8);
break;
case BMP_FORMAT_S2_13:
((uint16_t*)px)[c] = (uint16_t) ((double) v / ((1ULL<<frombits)-1) * 8192.0 + 0.5);
((uint16_t*)px)[c] = s_float_to_s2_13(s_int_to_float(fromrgba[c], 8));
break;
default:
#ifdef DEBUG
logerr(rp->log, "Unexpected result format %d", rp->result_format);
logerr(rp->c.log, "Unexpected result format %d", rp->result_format);
exit(1);
#endif
break;
@@ -938,19 +998,19 @@ static void s_set_file_error(BMPREAD_R rp)
static void s_log_error_from_state(BMPREAD_R rp)
{
if (rp->panic)
logerr(rp->log, "An internal error occured.");
logerr(rp->c.log, "An internal error occured.");
if (rp->file_eof)
logerr(rp->log, "Unexpected end of file.");
logerr(rp->c.log, "Unexpected end of file.");
if (rp->file_err)
logsyserr(rp->log, "While reading file");
logsyserr(rp->c.log, "While reading file");
if (rp->invalid_index)
logerr(rp->log, "File contained invalid color index.");
logerr(rp->c.log, "File contained invalid color index.");
if (rp->invalid_delta)
logerr(rp->log, "Invalid delta pointing outside image area.");
logerr(rp->c.log, "Invalid delta pointing outside image area.");
if (rp->invalid_overrun)
logerr(rp->log, "RLE data overrunning image area.");
logerr(rp->c.log, "RLE data overrunning image area.");
if (rp->truncated)
logerr(rp->log, "Image was truncated.");
logerr(rp->c.log, "Image was truncated.");
}

View File

@@ -1,6 +1,6 @@
/* bmplib - bmp-read-loadindexed.c
*
* Copyright (c) 2024, Rupert Weber.
* Copyright (c) 2024, 2025, Rupert Weber.
*
* This file is part of bmplib.
* bmplib is free software: you can redistribute it and/or modify
@@ -77,24 +77,35 @@ API BMPRESULT bmpread_load_palette(BMPHANDLE h, unsigned char **palette)
if (!(rp = cm_read_handle(h)))
return BMP_RESULT_ERROR;
if (!rp->getinfo_called) {
logerr(rp->log, "Must call bmpread_load_info() before loading palette");
if (rp->read_state < RS_HEADER_OK) {
logerr(rp->c.log, "Must call bmpread_load_info() before loading palette");
return BMP_RESULT_ERROR;
}
if (rp->read_state >= RS_LOAD_STARTED) {
logerr(rp->c.log, "Cannot load palette after image data");
return BMP_RESULT_ERROR;
}
if (!rp->palette) {
logerr(rp->log, "Image has no palette");
logerr(rp->c.log, "Image has no palette");
return BMP_RESULT_ERROR;
}
if (!palette) {
logerr(rp->log, "palette is NULL");
logerr(rp->c.log, "palette is NULL");
return BMP_RESULT_ERROR;
}
if (rp->result_format != BMP_FORMAT_INT) {
logerr(rp->c.log, "Palette can only be loaded when number format is BMP_FORMAT_INT");
return BMP_RESULT_ERROR;
}
memsize = rp->palette->numcolors * 4;
if (!*palette) {
if (!(*palette = malloc(memsize))) {
logsyserr(rp->log, "allocating palette");
logsyserr(rp->c.log, "allocating palette");
rp->read_state = RS_FATAL;
return BMP_RESULT_ERROR;
}
}
@@ -103,11 +114,13 @@ API BMPRESULT bmpread_load_palette(BMPHANDLE h, unsigned char **palette)
/* irreversible. image will be returned as indexed pixels */
if (!rp->result_indexed) {
rp->result_indexed = true;
rp->dimensions_queried = false;
rp->read_state = MIN(RS_HEADER_OK, rp->read_state);
rp->dim_queried_channels = false;
rp->result_channels = 1;
if (!br_set_resultbits(rp))
if (!br_set_resultbits(rp)) {
rp->read_state = RS_FATAL;
return BMP_RESULT_ERROR;
}
}
for (i = 0; i < rp->palette->numcolors; i++) {

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
/* bmplib - bmp-read.h
*
* Copyright (c) 2024, Rupert Weber.
* Copyright (c) 2024, 2025, Rupert Weber.
*
* This file is part of bmplib.
* bmplib is free software: you can redistribute it and/or modify

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
/* bmplib - bmp-write.h
*
* Copyright (c) 2024, Rupert Weber.
* Copyright (c) 2024, 2025, Rupert Weber.
*
* This file is part of bmplib.
* bmplib is free software: you can redistribute it and/or modify

104
bmplib.h
View File

@@ -1,6 +1,6 @@
/* bmplib - bmplib.h
*
* Copyright (c) 2024, Rupert Weber.
* Copyright (c) 2024, 2025, Rupert Weber.
*
* This file is part of bmplib.
* bmplib is free software: you can redistribute it and/or modify
@@ -42,7 +42,7 @@
#endif
typedef struct Bmphandle *BMPHANDLE;
typedef union Bmphandle *BMPHANDLE;
/*
@@ -84,6 +84,9 @@ typedef struct Bmphandle *BMPHANDLE;
* the image unless you first call
* bmpread_set_insanity_limit() to set a new
* sufficiently high limit.
*
* BMP_RESULT_ARRAY The BMP file contains an OS/2 bitmap array.
*
*/
enum Bmpresult {
BMP_RESULT_OK = 0,
@@ -93,6 +96,7 @@ enum Bmpresult {
BMP_RESULT_PNG,
BMP_RESULT_JPEG,
BMP_RESULT_ERROR,
BMP_RESULT_ARRAY
};
typedef enum Bmpresult BMPRESULT;
@@ -113,10 +117,8 @@ typedef enum Bmpresult BMPRESULT;
*/
enum Bmpconv64 {
BMP_CONV64_SRGB = 0, /* default */
BMP_CONV64_LINEAR = 1,
BMP_CONV64_16BIT_SRGB DEPR("use BMP_CONV64_SRGB instead") = 0,
BMP_CONV64_16BIT DEPR("use BMP_CONV64_LINEAR instead") = 1,
BMP_CONV64_NONE
BMP_CONV64_LINEAR,
BMP_CONV64_NONE,
};
typedef enum Bmpconv64 BMPCONV64;
@@ -131,7 +133,7 @@ typedef enum Bmpconv64 BMPCONV64;
*/
enum BmpInfoVer {
BMPINFO_CORE_OS21 = 1, /* 12 bytes */
BMPINFO_OS22, /* 16 / 40(!) / 64 bytes */
BMPINFO_OS22, /* 16 / 40(!) / up to 64 bytes */
BMPINFO_V3, /* 40 bytes */
BMPINFO_V3_ADOBE1, /* 52 bytes, unofficial */
BMPINFO_V3_ADOBE2, /* 56 bytes, unofficial */
@@ -164,8 +166,9 @@ typedef enum BmpRLEtype BMPRLETYPE;
/*
* undefined pixels in RLE images
*
* BMP_UNDEFINED_TO_ZERO set undefined pixels to 0 (= first
* entry in color table).
* BMP_UNDEFINED_LEAVE leaves image buffer at whatever pixel value it was
* initialized to. (0, i.e. first entry in color table if
* buffer was allocated by bmplib).
*
* BMP_UNDEFINED_TO_ALPHA (default) make undefined pixels
* transparent. Always adds an alpha
@@ -174,8 +177,7 @@ typedef enum BmpRLEtype BMPRLETYPE;
*/
enum BmpUndefined {
BMP_UNDEFINED_LEAVE,
BMP_UNDEFINED_TO_ZERO DEPR("use BMP_UNDEFINED_LEAVE instead") = 0,
BMP_UNDEFINED_TO_ALPHA /* default */
BMP_UNDEFINED_TO_ALPHA, /* default */
};
typedef enum BmpUndefined BMPUNDEFINED;
@@ -195,6 +197,19 @@ enum BmpOrient {
typedef enum BmpOrient BMPORIENT;
/*
* number format
*
* format of input/output RGB(A) image data. (indexed image data
* is always 8-bit integer).
*
* BMP_FORMAT_INT 8/16/32-bit integer
*
* BMP_FORMAT_FLOAT 32-bit float
*
* BMP_FORMAT_S2_13 16-bit s2.13 fixed point with range from
* -4.0 to +3.999...
*/
enum BmpFormat {
BMP_FORMAT_INT,
BMP_FORMAT_FLOAT,
@@ -203,16 +218,48 @@ enum BmpFormat {
typedef enum BmpFormat BMPFORMAT;
enum BmpIntent {
BMP_INTENT_NONE,
BMP_INTENT_BUSINESS, /* saturation */
BMP_INTENT_GRAPHICS, /* relative colorimetric */
BMP_INTENT_IMAGES, /* perceptive */
BMP_INTENT_ABS_COLORIMETRIC /* absolute colorimetric */
};
typedef enum BmpIntent BMPINTENT;
enum BmpImagetype {
BMP_IMAGETYPE_NONE,
BMP_IMAGETYPE_BM = 0x4d42,
BMP_IMAGETYPE_CI = 0x4943,
BMP_IMAGETYPE_CP = 0x5043,
BMP_IMAGETYPE_IC = 0x4349,
BMP_IMAGETYPE_PT = 0x5450,
BMP_IMAGETYPE_BA = 0x4142
};
typedef enum BmpImagetype BMPIMAGETYPE;
struct BmpArrayInfo {
BMPHANDLE handle;
BMPIMAGETYPE type;
int width, height;
int ncolors; /* 0 = RGB */
int screenwidth, screenheight; /* typically 0, or 1024x768 for 'hi-res' */
};
APIDECL BMPHANDLE bmpread_new(FILE *file);
APIDECL BMPRESULT bmpread_load_info(BMPHANDLE h);
APIDECL BMPIMAGETYPE bmpread_image_type(BMPHANDLE h);
APIDECL BMPRESULT bmpread_dimensions(BMPHANDLE h,
int *width,
int *height,
int *channels,
int *bitsperchannel,
BMPORIENT *orientation);
int *width,
int *height,
int *channels,
int *bitsperchannel,
BMPORIENT *orientation);
APIDECL int bmpread_width(BMPHANDLE h);
APIDECL int bmpread_height(BMPHANDLE h);
@@ -228,17 +275,23 @@ APIDECL size_t bmpread_buffersize(BMPHANDLE h);
APIDECL BMPRESULT bmpread_load_image(BMPHANDLE h, unsigned char **buffer);
APIDECL BMPRESULT bmpread_load_line(BMPHANDLE h, unsigned char **buffer);
APIDECL int bmpread_num_palette_colors(BMPHANDLE h);
APIDECL BMPRESULT bmpread_load_palette(BMPHANDLE h, unsigned char **palette);
APIDECL void bmpread_set_undefined(BMPHANDLE h, BMPUNDEFINED mode);
APIDECL void bmpread_set_insanity_limit(BMPHANDLE h, size_t limit);
APIDECL int bmpread_is_64bit(BMPHANDLE h);
APIDECL BMPRESULT bmpread_set_64bit_conv(BMPHANDLE h, BMPCONV64 conv);
APIDECL size_t bmpread_iccprofile_size(BMPHANDLE h);
APIDECL BMPRESULT bmpread_load_iccprofile(BMPHANDLE h, unsigned char **profile);
APIDECL int bmpread_array_num(BMPHANDLE h);
APIDECL BMPRESULT bmpread_array_info(BMPHANDLE h, struct BmpArrayInfo *ai, int idx);
APIDECL BMPINFOVER bmpread_info_header_version(BMPHANDLE h);
APIDECL const char* bmpread_info_header_name(BMPHANDLE h);
APIDECL int bmpread_info_header_size(BMPHANDLE h);
@@ -268,11 +321,17 @@ APIDECL BMPRESULT bmpwrite_set_orientation(BMPHANDLE h, BMPORIENT orientation);
APIDECL BMPRESULT bmpwrite_set_64bit(BMPHANDLE h);
APIDECL BMPRESULT bmpwrite_set_huffman_img_fg_idx(BMPHANDLE h, int idx);
APIDECL BMPRESULT bmpwrite_set_iccprofile(BMPHANDLE h, size_t size,
const unsigned char *iccprofile);
APIDECL BMPRESULT bmpwrite_set_rendering_intent(BMPHANDLE h, BMPINTENT intent);
APIDECL BMPRESULT bmpwrite_save_image(BMPHANDLE h, const unsigned char *image);
APIDECL BMPRESULT bmpwrite_save_line(BMPHANDLE h, const unsigned char *line);
APIDECL BMPRESULT bmp_set_number_format(BMPHANDLE h, BMPFORMAT format);
APIDECL BMPRESULT bmp_set_huffman_t4black_value(BMPHANDLE h, int blackidx);
APIDECL void bmp_free(BMPHANDLE h);
@@ -311,15 +370,6 @@ APIDECL const char* bmp_version(void);
/* these functions are kept for binary compatibility and will be
* removed from future versions:
*/
APIDECL int DEPR("use bmpread_orientation() instead") bmpread_topdown(BMPHANDLE h);
APIDECL void DEPR("use bmpread_set_undefined() instead") bmpread_set_undefined_to_alpha(BMPHANDLE h, int mode);
APIDECL int DEPR("use bmpread_bitsperchannel() instead") bmpread_bits_per_channel(BMPHANDLE h);
#ifdef __cplusplus
}
#endif

View File

@@ -1,6 +1,6 @@
/* bmplib - gen-huffman-codes.h
*
* Copyright (c) 2024, Rupert Weber.
* Copyright (c) 2024, 2025, Rupert Weber.
*
* This file is part of bmplib.
* bmplib is free software: you can redistribute it and/or modify

View File

@@ -1,6 +1,6 @@
/* bmplib - gen-huffman.c
*
* Copyright (c) 2024, Rupert Weber.
* Copyright (c) 2024, 2025, Rupert Weber.
*
* This file is part of bmplib.
* bmplib is free software: you can redistribute it and/or modify
@@ -26,7 +26,7 @@
#include <string.h>
#if (! __bool_true_false_are_defined)
#if (! __bool_true_false_are_defined && __STDC_VERSION__ < 202000L)
typedef int bool;
#define true 1
#define false 0
@@ -116,14 +116,14 @@ int main(int argc, char *argv[])
fprintf(file, "static const int blackroot = %d;\n", black_tree);
fprintf(file, "static const int whiteroot = %d;\n\n\n", white_tree);
fprintf(file, "static const struct Node nodebuffer[] = {\n");
for (i = 0; i < ARR_SIZE(nodebuffer); i++) {
for (i = 0; i < (int) ARR_SIZE(nodebuffer); i++) {
fprintf(file, "\t{ %3d, %3d, %4d, %d, %d },\n",
n[i].l, n[i].r, n[i].value, n[i].terminal, n[i].makeup);
}
fputs("};\n\n", file);
fputs("static const struct Huffcode huff_term_black[] = {\n\t", file);
for (i = 0; i < ARR_SIZE(huff_term_black); i++) {
for (i = 0; i < (int) ARR_SIZE(huff_term_black); i++) {
fprintf(file, "{ 0x%02hx, %2d },",
str2bits(huff_term_black[i].bits),
(int) strlen(huff_term_black[i].bits));
@@ -135,7 +135,7 @@ int main(int argc, char *argv[])
fputs("\n};\n\n", file);
fputs("static const struct Huffcode huff_term_white[] = {\n\t", file);
for (i = 0; i < ARR_SIZE(huff_term_white); i++) {
for (i = 0; i < (int) ARR_SIZE(huff_term_white); i++) {
fprintf(file, "{ 0x%02hx, %2d },",
str2bits(huff_term_white[i].bits),
(int) strlen(huff_term_white[i].bits));
@@ -147,7 +147,7 @@ int main(int argc, char *argv[])
fputs("\n};\n\n", file);
fputs("static const struct Huffcode huff_makeup_black[] = {\n\t", file);
for (i = 0; i < ARR_SIZE(huff_makeup_black); i++) {
for (i = 0; i < (int) ARR_SIZE(huff_makeup_black); i++) {
fprintf(file, "{ 0x%02hx, %2d },",
str2bits(huff_makeup_black[i].bits),
(int) strlen(huff_makeup_black[i].bits));
@@ -159,7 +159,7 @@ int main(int argc, char *argv[])
fputs("\n};\n\n", file);
fputs("static const struct Huffcode huff_makeup_white[] = {\n\t", file);
for (i = 0; i < ARR_SIZE(huff_makeup_white); i++) {
for (i = 0; i < (int) ARR_SIZE(huff_makeup_white); i++) {
fprintf(file, "{ 0x%02hx, %2d },",
str2bits(huff_makeup_white[i].bits),
(int) strlen(huff_makeup_white[i].bits));
@@ -197,20 +197,20 @@ static void s_buildtree(void)
memset(nodebuffer, 0, sizeof nodebuffer);
for (i = 0; i < ARR_SIZE(huff_term_black); i++) {
for (i = 0; i < (int) ARR_SIZE(huff_term_black); i++) {
add_node(&black_tree, huff_term_black[i].bits,
huff_term_black[i].number, false);
}
for (i = 0; i < ARR_SIZE(huff_makeup_black); i++) {
for (i = 0; i < (int) ARR_SIZE(huff_makeup_black); i++) {
add_node(&black_tree, huff_makeup_black[i].bits,
huff_makeup_black[i].number, true);
}
for (i = 0; i < ARR_SIZE(huff_term_white); i++) {
for (i = 0; i < (int) ARR_SIZE(huff_term_white); i++) {
add_node(&white_tree, huff_term_white[i].bits,
huff_term_white[i].number, false);
}
for (i = 0; i < ARR_SIZE(huff_makeup_white); i++) {
for (i = 0; i < (int) ARR_SIZE(huff_makeup_white); i++) {
add_node(&white_tree, huff_makeup_white[i].bits,
huff_makeup_white[i].number, true);
}
@@ -229,7 +229,7 @@ static void add_node(int *nodeidx, const char *bits, int value, bool makeup)
nodebuffer[*nodeidx].l = -1;
nodebuffer[*nodeidx].r = -1;
}
if (nnodes > ARR_SIZE(nodebuffer)) {
if (nnodes > (int) ARR_SIZE(nodebuffer)) {
printf("too many nodes (have %d, max is %d)\n",
nnodes, (int) ARR_SIZE(nodebuffer));
exit(1);

View File

@@ -1,6 +1,6 @@
/* bmplib - huffman.c
*
* Copyright (c) 2024, Rupert Weber.
* Copyright (c) 2024, 2025, Rupert Weber.
*
* This file is part of bmplib.
* bmplib is free software: you can redistribute it and/or modify
@@ -227,7 +227,7 @@ bool huff_flush(BMPWRITE_R wp)
while (wp->hufbuf_len >= 8) {
byte = 0x00ff & (wp->hufbuf >> (wp->hufbuf_len - 8));
if (EOF == putc(byte, wp->file)) {
logsyserr(wp->log, "writing Huffman bitmap");
logsyserr(wp->c.log, "writing Huffman bitmap");
return false;
}
wp->bytes_written++;

View File

@@ -1,6 +1,6 @@
/* bmplib - huffman.h
*
* Copyright (c) 2024, Rupert Weber.
* Copyright (c) 2024, 2025, Rupert Weber.
*
* This file is part of bmplib.
* bmplib is free software: you can redistribute it and/or modify

View File

@@ -1,6 +1,6 @@
/* bmplib - logging.c
*
* Copyright (c) 2024, Rupert Weber.
* Copyright (c) 2024, 2025, Rupert Weber.
*
* This file is part of bmplib.
* bmplib is free software: you can redistribute it and/or modify
@@ -29,6 +29,12 @@
#include "config.h"
#include "logging.h"
#if defined(__GNUC__)
#define MAY_BE_UNUSED __attribute__((unused))
#else
#define MAY_BE_UNUSED
#endif
struct Log {
int size;
@@ -169,8 +175,9 @@ void logsyserr(LOG log, const char *fmt, ...)
* s_log()
*********************************************************/
static void s_log(LOG log, const char *file, int line, const char *function,
const char *etxt, const char *fmt, va_list args)
static void s_log(LOG log, const char *file MAY_BE_UNUSED, int line MAY_BE_UNUSED,
const char *function MAY_BE_UNUSED,
const char *etxt, const char *fmt, va_list args)
{
va_list argsdup;
int len = 0,addl_len, required_len;

View File

@@ -1,6 +1,6 @@
/* bmplib - logging.h
*
* Copyright (c) 2024, Rupert Weber.
* Copyright (c) 2024, 2025, Rupert Weber.
*
* This file is part of bmplib.
* bmplib is free software: you can redistribute it and/or modify

View File

@@ -1,16 +1,25 @@
project('bmplib', 'c', default_options: ['c_std=c11'], version: '1.7.4')
project('bmplib', 'c', default_options: ['c_std=c11', 'warning_level=3'], version: '1.8.0')
cc = meson.get_compiler('c')
add_project_arguments(['-pedantic','-fvisibility=hidden'], language : 'c')
add_project_arguments('-pedantic', language : 'c')
add_project_arguments('-fvisibility=hidden', language: 'c')
if get_option('buildtype') == 'debug'
add_project_arguments('-DDEBUG', language: 'c')
elif get_option('buildtype') == 'release'
add_project_arguments('-DNDEBUG', language: 'c')
endif
if get_option('sanitize')
sanitize = [
'-fsanitize=signed-integer-overflow',
'-fsanitize=undefined',
'-fsanitize=float-divide-by-zero',
]
add_project_arguments(sanitize, language : 'c')
add_project_link_arguments(sanitize, language: 'c')
endif
m_dep = cc.find_library('m', required : false)
conf_data = configuration_data()
@@ -28,6 +37,7 @@ bmplib_sources = ['bmp-read.c',
'bmp-write.c',
'bmp-read-loadimage.c',
'bmp-read-loadindexed.c',
'bmp-read-icons.c',
'bmp-common.c',
'huffman.c',
'logging.c']
@@ -60,3 +70,64 @@ pkg_mod.generate(libraries: bmplib,
filebase: 'libbmp',
description: 'Library for reading/writing Windows BMP files.',
)
test_read_conversions = executable('test_read_conversions',
'test-read-conversions.c',
'bmp-common.c',
'bmp-read.c',
'bmp-read-icons.c',
'bmp-write.c',
'huffman.c',
'logging.c',
huff_codes[0],
dependencies: m_dep,
)
test_read_io = executable('test_read_io',
'test-read-io.c',
'bmp-common.c',
'bmp-read.c',
'bmp-read-icons.c',
'bmp-write.c',
'huffman.c',
'logging.c',
'test-fileio-pipes.c',
huff_codes[0],
dependencies: m_dep,
)
test_write_io = executable('test_write_io',
'test-write-io.c',
'bmp-common.c',
'bmp-read.c',
'bmp-read-icons.c',
'bmp-read-loadimage.c',
'huffman.c',
'logging.c',
'test-fileio-pipes.c',
huff_codes[0],
dependencies: m_dep,
)
test('read - s_s2_13_to_float', test_read_conversions, args : ['s_s2_13_to_float'])
test('read - s_convert64', test_read_conversions, args : ['s_convert64'])
test('read - s_float_to_s2_13', test_read_conversions, args : ['s_float_to_s2_13'])
test('read - roundtrip_s2.13-float-s2.13', test_read_conversions, args : ['roundtrip_s2.13-float-s2.13'])
test('read - s_srgb_gamma_float', test_read_conversions, args : ['s_srgb_gamma_float'])
test('read - s_int8_to_result_format/float', test_read_conversions, args : ['s_int8_to_result_format', 'float'])
test('read - s_int8_to_result_format/int', test_read_conversions, args : ['s_int8_to_result_format', 'int'])
test('read - s_int8_to_result_format/s2.13', test_read_conversions, args : ['s_int8_to_result_format', 's2.13'])
test('read - s_buffer32_fill', test_read_io, args : ['s_buffer32_fill'])
test('read - s_buffer32_bits', test_read_io, args : ['s_buffer32_bits'])
test('read - s_read_rgb_pixel', test_read_io, args : ['s_read_rgb_pixel'])
test('read - read_u16_le', test_read_io, args : ['read_u16_le'])
test('read - read_s16_le', test_read_io, args : ['read_s16_le'])
test('read - read_u32_le', test_read_io, args : ['read_u32_le'])
test('read - read_s32_le', test_read_io, args : ['read_s32_le'])
test('write - write_u32_le', test_write_io, args : ['write_u32_le'])
test('write - write_s32_le', test_write_io, args : ['write_s32_le'])
test('write - write_u16_le', test_write_io, args : ['write_u16_le'])
test('write - write_s16_le', test_write_io, args : ['write_s16_le'])
test('write - s_imgrgb_to_outbytes/int', test_write_io, args : ['s_imgrgb_to_outbytes', 'int'])
test('write - s_imgrgb_to_outbytes/float', test_write_io, args : ['s_imgrgb_to_outbytes', 'float'])
test('write - s_imgrgb_to_outbytes/s2.13', test_write_io, args : ['s_imgrgb_to_outbytes', 's2.13'])

View File

@@ -1 +1,2 @@
option('insanity_limit_mb', type: 'integer', min: 0, value: 500)
option('sanitize', type: 'boolean', value: false)

145
test-fileio-pipes.c Normal file
View File

@@ -0,0 +1,145 @@
/* bmplib - test-fileio-pipes.c
*
* Copyright (c) 2025, Rupert Weber.
*
* This file is part of bmplib.
* bmplib is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library.
* If not, see <https://www.gnu.org/licenses/>
*/
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <test-fileio-pipes.h>
FILE* provide_as_file(const unsigned char *data, size_t size)
{
int fd[2] = { -1, -1 };
FILE *file_read = NULL, *file_write = NULL;
if (pipe(fd)) {
perror("pipe");
goto abort;
}
if (!(file_read = fdopen(fd[0], "rb"))) {
perror("fdopen read pipe");
goto abort;
}
if (!(file_write = fdopen(fd[1], "w"))) {
perror("fdopen write pipe");
goto abort;
}
if (size != fwrite(data, 1, size, file_write)) {
perror("fwrite to pipe");
goto abort;
}
fclose(file_write);
return file_read;
abort:
if (file_write)
fclose(file_write);
else if (fd[1] != -1)
close(fd[1]);
if (file_read)
fclose(file_read);
else if (fd[0] != -1)
close(fd[0]);
return NULL;
}
FILE* open_write_pipe(struct WritePipe **hwp)
{
int fd[2] = { -1, -1 };
FILE *file_read = NULL, *file_write = NULL;
struct WritePipe *wp = NULL;
if (!hwp)
return NULL;
*hwp = NULL;
if (!(wp = malloc(sizeof *wp))) {
perror(__func__);
goto abort;
}
memset(wp, 0, sizeof *wp);
if (pipe(fd)) {
perror("pipe");
goto abort;
}
if (!(file_read = fdopen(fd[0], "rb"))) {
perror("fdopen read pipe");
goto abort;
}
if (!(file_write = fdopen(fd[1], "w"))) {
perror("fdopen write pipe");
goto abort;
}
wp->file_read = file_read;
*hwp = wp;
return file_write;
abort:
if (file_write)
fclose(file_write);
else if (fd[1] != -1)
close(fd[1]);
if (file_read)
fclose(file_read);
else if (fd[0] != -1)
close(fd[0]);
if (wp)
free(wp);
return NULL;
}
int data_from_write_pipe(struct WritePipe *wp, unsigned char *buffer, int size)
{
int nread;
if (!(wp && buffer)) {
fprintf(stderr, "%s(): invalid NULL argument(s)\n", __func__);
exit(3);
}
if (!wp->file_read) {
fprintf(stderr, "%s(): FILE* is NULL\n", __func__);
exit(3);
}
nread = fread(buffer, 1, size, wp->file_read);
fclose(wp->file_read);
free(wp);
return nread;
}

29
test-fileio-pipes.h Normal file
View File

@@ -0,0 +1,29 @@
/* bmplib - test-fileio-pipes.h
*
* Copyright (c) 2025, Rupert Weber.
*
* This file is part of bmplib.
* bmplib is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library.
* If not, see <https://www.gnu.org/licenses/>
*/
struct WritePipe {
FILE *file_read;
};
FILE* provide_as_file(const unsigned char *data, size_t size);
FILE* open_write_pipe(struct WritePipe **hwp);
int data_from_write_pipe(struct WritePipe *wp, unsigned char *buffer, int size);

247
test-read-conversions.c Normal file
View File

@@ -0,0 +1,247 @@
/* bmplib - test-read-conversions.c
*
* Copyright (c) 2025, Rupert Weber.
*
* This file is part of bmplib.
* bmplib is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library.
* If not, see <https://www.gnu.org/licenses/>
*/
#include "bmp-read-loadimage.c"
#define ARRAY_LEN(a) ((int)(sizeof (a) / sizeof ((a)[0])))
int main(int argc, const char **argv)
{
const char *func, *subtest ="";
if (argc < 2) {
fprintf(stderr, "Invalid invocation\n");
return 2;
}
func = argv[1];
if (argc >= 3)
subtest = argv[2];
if (!strcmp(func, "s_float_to_s2_13")) {
struct {
double d;
uint16_t expected;
} data[] = {
{ .d = -4.0, .expected = 0x8000 },
{ .d = -5.0, .expected = 0x8000 },
{ .d = -1.0, .expected = 0xe000 },
{ .d = 0.0, .expected = 0x0000 },
{ .d = 1.0, .expected = 0x2000 },
{ .d = 3.99987793, .expected = 0x7fff },
{ .d = 4.0, .expected = 0x7fff },
{ .d = 20.0, .expected = 0x7fff },
};
for (int i = 0; i < ARRAY_LEN(data); i++) {
uint16_t s2_13 = s_float_to_s2_13(data[i].d);
if (s2_13 != data[i].expected) {
printf("%s() failed on data set %d: %f\n", func, i, data[i].d);
printf("expected 0x%04x, got 0x%04x\n", data[i].expected, s2_13);
return 1;
}
}
return 0;
}
if (!strcmp(func, "s_s2_13_to_float")) {
struct {
uint16_t s2_13;
double expected;
} data[] = {
{ .s2_13 = 0x2000u, .expected = 1.0},
{ .s2_13 = 0xe000u, .expected = -1.0},
{ .s2_13 = 0, .expected = 0.0},
{ .s2_13 = 0x7fffu, .expected = 3.99987793},
{ .s2_13 = 0x8000u, .expected = -4.0},
};
for (int i = 0; i < ARRAY_LEN(data); i++) {
double d = s_s2_13_to_float(data[i].s2_13);
printf("is %.12f, expected %.12f\n", d, data[i].expected);
if (fabs(d - data[i].expected) > 0.000000001) {
printf("%s() failed on data set %d: 0x%04x\n", func, i, data[i].s2_13);
printf("expected %.12f, got %.12f\n", data[i].expected, d);
return 1;
}
}
return 0;
}
if (!strcmp(func, "roundtrip_s2.13-float-s2.13")) {
for (uint32_t u = 0; u <= 0xffffu; u++) {
double d = s_s2_13_to_float(u);
uint16_t u16 = s_float_to_s2_13(d);
if (u != u16) {
printf("%s for 0x%04x failed:\n", func, (unsigned)u);
printf("expected 0x%04x, got 0x%04x\n", (unsigned)u, (unsigned)u16);
return 1;
}
}
return 0;
}
if (!strcmp(func, "s_convert64")) {
struct {
uint16_t val64[4];
uint16_t expected[4];
} data[] = {
{ .val64 = {0, 0, 0, 0}, .expected = {0, 0, 0, 0} },
{ .val64 = {0x2000, 0xe000, 0x2000, 0xffff}, .expected = {0xffff, 0, 0xffff, 0} },
{ .val64 = {0x4000, 0x1000, 0x4000, 0x1000}, .expected = {0xffff, 0x8000, 0xffff, 0x8000} },
};
for (int i = 0; i < ARRAY_LEN(data); i++) {
s_convert64(data[i].val64);
for (int j = 0; j < 4; j++) {
if (data[i].val64[j] != data[i].expected[j]) {
printf("%s() failed on data set %d\n", func, i);
printf("expected 0x%04x, got 0x%04x\n", (unsigned)data[i].expected[j],
(unsigned)data[i].val64[j]);
return 1;
}
}
}
return 0;
}
if (!strcmp(func, "s_srgb_gamma_float")) {
struct {
double lin;
double expected;
} data[] = {
{ .lin = 0.0, .expected = 0.0},
{ .lin = 1.0, .expected = 1.0},
{ .lin = 0.1, .expected = 0.349190213},
{ .lin = 0.5, .expected = 0.735356983},
{ .lin = 0.9, .expected = 0.954687172},
};
for (int i = 0; i < ARRAY_LEN(data); i++) {
double d = s_srgb_gamma_float(data[i].lin);
printf("is %.12f, expected %.12f\n", d, data[i].expected);
if (fabs(d - data[i].expected) > 0.000000001) {
printf("%s() failed on data set %d: %f\n", func, i, data[i].lin);
printf("expected %.12f, got %.12f\n", data[i].expected, d);
return 1;
}
}
return 0;
}
if (!strcmp(func, "s_int8_to_result_format") && !strcmp(subtest, "float")) {
struct Bmpread br = { .result_format = BMP_FORMAT_FLOAT, .result_bitsperchannel = 32 };
struct {
int channels;
int rgba[4];
float expected[4];
} data[] = {
{ .channels = 3, .rgba = { 0, 0, 0, 0}, .expected = { 0.0, 0.0, 0.0, 0.0 } },
{ .channels = 3, .rgba = { 255, 255, 255, 255}, .expected = { 1.0, 1.0, 1.0, 0.0 } },
{ .channels = 4, .rgba = { 127, 128, 1, 254}, .expected = { 0.4980392, 0.5019608, 0.0039216, 0.9960784 } },
};
float floatbuf[4] = { 0 };
for (int i = 0; i < ARRAY_LEN(data); i++) {
br.result_channels = data[i].channels;
s_int8_to_result_format(&br, data[i].rgba, (unsigned char*) floatbuf);
//printf("is %.12f, expected %.12f\n", d, data[i].expected);
for (int j = 0; j < 4; j++) {
if (fabs(floatbuf[j] - data[i].expected[j]) > 0.0000001) {
printf("%s()/%s - failed on data set %d:\n", func, subtest, i);
printf("expected %.12f, got %.12f\n", data[i].expected[j], floatbuf[j]);
return 1;
}
}
}
return 0;
}
if (!strcmp(func, "s_int8_to_result_format") && !strcmp(subtest, "int")) {
struct Bmpread br = { .result_format = BMP_FORMAT_INT, .result_bitsperchannel = 8 };
struct {
int channels;
int rgba[4];
unsigned expected[4];
} data[] = {
{ .channels = 3, .rgba = { 0, 0, 0, 0}, .expected = { 0, 0, 0, 0 } },
{ .channels = 3, .rgba = { 255, 255, 255, 255}, .expected = { 255, 255, 255, 0 } },
{ .channels = 4, .rgba = { 127, 128, 1, 254}, .expected = { 127, 128, 1, 254 } },
};
uint8_t int8buf[4] = { 0 };
for (int i = 0; i < ARRAY_LEN(data); i++) {
br.result_channels = data[i].channels;
s_int8_to_result_format(&br, data[i].rgba, (unsigned char*) int8buf);
for (int j = 0; j < 4; j++) {
if (int8buf[j] != data[i].expected[j]) {
printf("%s()/%s - failed on data set %d:\n", func, subtest, i);
printf("expected %u, got %u\n", (unsigned)data[i].expected[j], (unsigned)int8buf[j]);
return 1;
}
}
}
return 0;
}
if (!strcmp(func, "s_int8_to_result_format") && !strcmp(subtest, "s2.13")) {
struct Bmpread br = { .result_format = BMP_FORMAT_S2_13, .result_bitsperchannel = 16 };
struct {
int channels;
int rgba[4];
uint16_t expected[4];
} data[] = {
{ .channels = 3, .rgba = { 0, 0, 0, 0}, .expected = { 0, 0, 0, 0 } },
{ .channels = 3, .rgba = { 255, 255, 255, 255}, .expected = { 0x2000, 0x2000, 0x2000, 0 } },
{ .channels = 4, .rgba = { 127, 128, 1, 254}, .expected = { 0x0ff0, 0x1010, 0x0020, 0x1fe0 } },
};
uint16_t s213buf[4] = { 0 };
for (int i = 0; i < ARRAY_LEN(data); i++) {
br.result_channels = data[i].channels;
s_int8_to_result_format(&br, data[i].rgba, (unsigned char*) s213buf);
for (int j = 0; j < 4; j++) {
if (s213buf[j] != data[i].expected[j]) {
printf("%s()/%s - failed on data set %d:\n", func, subtest, i);
printf("expected %u, got %u\n", (unsigned)data[i].expected[j], (unsigned)s213buf[j]);
return 1;
}
}
}
return 0;
}
fprintf(stderr, "Invalid test '%s'\n", func);
return 2;
}

377
test-read-io.c Normal file
View File

@@ -0,0 +1,377 @@
/* bmplib - test-read-io.c
*
* Copyright (c) 2025, Rupert Weber.
*
* This file is part of bmplib.
* bmplib is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library.
* If not, see <https://www.gnu.org/licenses/>
*/
#include "bmp-read-loadimage.c"
#include "test-fileio-pipes.h"
#define ARRAY_LEN(a) ((int)(sizeof (a) / sizeof ((a)[0])))
int main(int argc, const char **argv)
{
const char *func /*, *subtest =""*/;
if (argc < 2) {
fprintf(stderr, "Invalid invocation\n");
return 2;
}
func = argv[1];
/*if (argc >= 3)
subtest = argv[2];*/
if (!strcmp(func, "s_buffer32_fill")) {
struct Bmpread br = { 0 };
struct Buffer32 buf32;
struct {
unsigned char *filedata;
size_t datalen;
uint32_t expected_data;
int expected_n;
bool expected_return;
} data[] = {
{ .filedata = (unsigned char[]){0x00,0x00,0x00,0x00},
.datalen = 4,
.expected_n = 32,
.expected_data = 0,
.expected_return = true },
{ .filedata = (unsigned char[]){0x01,0x02,0x03,0x04},
.datalen = 4,
.expected_n = 32,
.expected_data = 0x01020304UL,
.expected_return = true },
{ .filedata = (unsigned char[]){0x01,0x02,0x03},
.datalen = 3,
.expected_n = 24,
.expected_data = 0x01020300UL,
.expected_return = true },
{ .filedata = (unsigned char[]){ 0 },
.datalen = 0,
.expected_n = 0,
.expected_data = 0x0UL,
.expected_return = false },
};
for (int i = 0; i < ARRAY_LEN(data); i++) {
br.file = provide_as_file(data[i].filedata, data[i].datalen);
if (!br.file)
return 2;
bool result = s_buffer32_fill(&br, &buf32);
if (result != data[i].expected_return || buf32.buffer != data[i].expected_data ||
buf32.n != data[i].expected_n) {
printf("%s() failed on dataset %d:\n", func, i);
printf("expected %s/0x%08lx/%d, got %s/0x%08lx/%d\n", data[i].expected_return ? "true" : "false",
(unsigned long)data[i].expected_data,
data[i].expected_n,
result ? "true" : "false",
(unsigned long)buf32.buffer, buf32.n);
return 1;
fclose(br.file);
}
}
return 0;
}
if (!strcmp(func, "s_buffer32_bits")) {
struct Buffer32 buf32 = { 0 };
struct {
uint32_t buffer;
int n;
int request;
uint32_t expected;
} data[] = {
{ .buffer = 0x0f000000UL, .n = 8, .request = 8, .expected = 0x0f },
{ .buffer = 0x34ffffffUL, .n = 16, .request = 4, .expected = 0x03 },
{ .buffer = 0x1234ffffUL, .n = 32, .request = 8, .expected = 0x12 },
{ .buffer = 0x8234ffffUL, .n = 16, .request = 2, .expected = 0x02 },
{ .buffer = 0x8234ffffUL, .n = 16, .request = 1, .expected = 0x01 },
};
for (int i = 0; i < ARRAY_LEN(data); i++) {
buf32.buffer = data[i].buffer;
buf32.n = data[i].n;
uint32_t result = s_buffer32_bits(&buf32, data[i].request);
if (result != data[i].expected) {
printf("%s() failed on dataset %d:\n", func, i);
printf("expected 0x%08lx, got 0x%08lx\n",
(unsigned long)data[i].expected,
(unsigned long)result);
return 1;
}
}
return 0;
}
if (!strcmp(func, "s_read_rgb_pixel")) {
struct Bmpread br = { 0 };
struct Bmpinfo ih = { 0 };
union Pixel px = { 0 };
br.ih = &ih;
struct {
unsigned char *filedata;
size_t datalen;
int bitcount;
uint64_t mask[4];
int shift[4];
uint32_t expected[4];
bool has_alpha;
int result_bitsperchannel;
} data[] = {
{ .filedata = (unsigned char[]){0x03,0x02,0x01,0x00},
.datalen = 4,
.bitcount = 32,
.mask = { 0xff0000, 0xff00, 0xff, 0 },
.shift = { 16, 8, 0, 0 },
.has_alpha = false,
.expected = { 1, 2, 3, 255 },
.result_bitsperchannel = 8,
},
{ .filedata = (unsigned char[]){0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08},
.datalen = 8,
.bitcount = 64,
.mask = { 0xffffULL, 0xffff0000ULL, 0xffff00000000ULL, 0xffff000000000000ULL },
.shift = { 0, 16, 32, 48 },
.has_alpha = true,
.expected = { 0x0201, 0x0403, 0x0605, 0x0807 },
.result_bitsperchannel = 16,
},
{ .filedata = (unsigned char[]){ 0x12, 0x34 },
.datalen = 2,
.bitcount = 16,
.mask = { 0x0f, 0xf0, 0x0f00, 0xf000 },
.shift = { 0, 4, 8, 12 },
.has_alpha = true,
.expected = { 2, 1, 4, 3 },
.result_bitsperchannel = 8,
},
};
for (int i = 0; i < ARRAY_LEN(data); i++) {
br.file = provide_as_file(data[i].filedata, data[i].datalen);
if (!br.file)
return 2;
br.cmask.mask.red = data[i].mask[0];
br.cmask.mask.green = data[i].mask[1];
br.cmask.mask.blue = data[i].mask[2];
br.cmask.mask.alpha = data[i].mask[3];
br.cmask.shift.red = data[i].shift[0];
br.cmask.shift.green = data[i].shift[1];
br.cmask.shift.blue = data[i].shift[2];
br.cmask.shift.alpha = data[i].shift[3];
br.has_alpha = data[i].has_alpha;
br.result_bitsperchannel = data[i].result_bitsperchannel;
ih.bitcount = data[i].bitcount;
if (!s_read_rgb_pixel(&br, &px)) {
printf("%s(): EOF or file error (.filedata too short?)\n", func);
return 2;
}
for (int j = 0; j < 4; j++) {
if (px.value[j] != data[i].expected[j]) {
printf("%s() failed on dataset %d, val %d:\n", func, i, j);
printf("expected %d, got %d\n",
(int)data[i].expected[j],
(int)px.value[j]);
return 1;
}
}
fclose(br.file);
br.file = NULL;
}
return 0;
}
if (!strcmp(func, "read_u16_le")) {
struct {
unsigned char *filedata;
int datalen;
unsigned expected;
} data[] = {
{ .filedata = (unsigned char[]){0x00,0x00},
.datalen = 2, .expected = 0 },
{ .filedata = (unsigned char[]){0x01,0x00},
.datalen = 2, .expected = 1 },
{ .filedata = (unsigned char[]){0xfe,0xff},
.datalen = 2, .expected = 65534 },
{ .filedata = (unsigned char[]){0xff,0xff},
.datalen = 2, .expected = 65535 },
};
for (int i = 0; i < ARRAY_LEN(data); i++) {
FILE *file = provide_as_file(data[i].filedata, data[i].datalen);
if (!file)
return 2;
uint16_t result = 0;
if (!read_u16_le(file, &result)) {
perror(func);
return 3;
}
if (result != data[i].expected) {
printf("%s() failed on dataset %d:\n", func, i);
printf("expected 0x%04x, got 0x%04x\n",
(unsigned)data[i].expected,
(unsigned)result);
return 1;
}
}
return 0;
}
if (!strcmp(func, "read_s16_le")) {
struct {
unsigned char *filedata;
int datalen;
int expected;
} data[] = {
{ .filedata = (unsigned char[]){0x00,0x00},
.datalen = 2, .expected = 0 },
{ .filedata = (unsigned char[]){0x01,0x00},
.datalen = 2, .expected = 1 },
{ .filedata = (unsigned char[]){0xff,0xff},
.datalen = 2, .expected = -1 },
{ .filedata = (unsigned char[]){0x00,0x80},
.datalen = 2, .expected = -32768 },
{ .filedata = (unsigned char[]){0x01,0x80},
.datalen = 2, .expected = -32767 },
{ .filedata = (unsigned char[]){0xfe,0x7f},
.datalen = 2, .expected = 32766 },
{ .filedata = (unsigned char[]){0xff,0x7f},
.datalen = 2, .expected = 32767 },
};
for (int i = 0; i < ARRAY_LEN(data); i++) {
FILE *file = provide_as_file(data[i].filedata, data[i].datalen);
if (!file)
return 2;
int16_t result = 0;
if (!read_s16_le(file, &result)) {
perror(func);
return 3;
}
if (result != data[i].expected) {
printf("%s() failed on dataset %d:\n", func, i);
printf("expected %d, got %d\n", (int)data[i].expected,
(int)result);
return 1;
}
}
return 0;
}
if (!strcmp(func, "read_u32_le")) {
struct {
unsigned char *filedata;
int datalen;
uint32_t expected;
} data[] = {
{ .filedata = (unsigned char[]){0x00,0x00,0x00,0x00},
.datalen = 4, .expected = 0 },
{ .filedata = (unsigned char[]){0x01,0x00,0x00,0x00},
.datalen = 4, .expected = 1 },
{ .filedata = (unsigned char[]){0xfe,0xff,0xff,0xff},
.datalen = 4, .expected = 0xfffffffeUL },
{ .filedata = (unsigned char[]){0xff,0xff,0xff,0xff},
.datalen = 4, .expected = 0xffffffffUL },
{ .filedata = (unsigned char[]){0x12,0x34,0x56,0x78},
.datalen = 4, .expected = 0x78563412UL },
};
for (int i = 0; i < ARRAY_LEN(data); i++) {
FILE *file = provide_as_file(data[i].filedata, data[i].datalen);
if (!file)
return 2;
uint32_t result = 0;
if (!read_u32_le(file, &result)) {
perror(func);
return 3;
}
if (result != data[i].expected) {
printf("%s() failed on dataset %d:\n", func, i);
printf("expected 0x%08lx, got 0x%08lx\n",
(unsigned long)data[i].expected,
(unsigned long)result);
return 1;
}
}
return 0;
}
if (!strcmp(func, "read_s32_le")) {
struct {
unsigned char *filedata;
int datalen;
long expected;
} data[] = {
{ .filedata = (unsigned char[]){0x00,0x00,0x00,0x00},
.datalen = 4, .expected = 0 },
{ .filedata = (unsigned char[]){0x01,0x00,0x00,0x00},
.datalen = 4, .expected = 1 },
{ .filedata = (unsigned char[]){0xff,0xff,0xff,0xff},
.datalen = 4, .expected = -1 },
{ .filedata = (unsigned char[]){0x00,0x00,0x00,0x80},
.datalen = 4, .expected = -2147483648L },
{ .filedata = (unsigned char[]){0x01,0x00,0x00,0x80},
.datalen = 4, .expected = -2147483647L },
{ .filedata = (unsigned char[]){0xfe,0xff,0xff,0x7f},
.datalen = 4, .expected = 2147483646L },
{ .filedata = (unsigned char[]){0xff,0xff,0xff,0x7f},
.datalen = 4, .expected = 2147483647L },
{ .filedata = (unsigned char[]){0x12,0x34,0x56,0x78},
.datalen = 4, .expected = 2018915346L },
};
for (int i = 0; i < ARRAY_LEN(data); i++) {
FILE *file = provide_as_file(data[i].filedata, data[i].datalen);
if (!file)
return 2;
int32_t result = 0;
if (!read_s32_le(file, &result)) {
perror(func);
return 3;
}
if (result != data[i].expected) {
printf("%s() failed on dataset %d:\n", func, i);
printf("expected %ld, got %ld\n", (long)data[i].expected,
(long)result);
return 1;
}
}
return 0;
}
fprintf(stderr, "Invalid test '%s'\n", func);
return 2;
}

BIN
test-write-helper.ods Normal file

Binary file not shown.

431
test-write-io.c Normal file
View File

@@ -0,0 +1,431 @@
/* bmplib - test-read-io.c
*
* Copyright (c) 2025, Rupert Weber.
*
* This file is part of bmplib.
* bmplib is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library.
* If not, see <https://www.gnu.org/licenses/>
*/
#include "bmp-write.c"
#include "test-fileio-pipes.h"
#define ARRAY_LEN(a) ((int)(sizeof (a) / sizeof ((a)[0])))
int main(int argc, const char **argv)
{
const char *func, *subtest ="";
if (argc < 2) {
fprintf(stderr, "Invalid invocation\n");
return 2;
}
func = argv[1];
if (argc >= 3)
subtest = argv[2];
if (!strcmp(func, "write_u32_le")) {
const int expected_len = 4;
struct {
uint32_t value;
unsigned char *expected;
} data[] = {
{ .expected = (unsigned char[]){0x00,0x00,0x00,0x00}, .value = 0 },
{ .expected = (unsigned char[]){0x01,0x00,0x00,0x00}, .value = 1 },
{ .expected = (unsigned char[]){0xfe,0xff,0xff,0xff}, .value = 0xfffffffeUL },
{ .expected = (unsigned char[]){0xff,0xff,0xff,0xff}, .value = 0xffffffffUL },
{ .expected = (unsigned char[]){0x12,0x34,0x56,0x78}, .value = 0x78563412UL },
};
for (int i = 0; i < ARRAY_LEN(data); i++) {
struct WritePipe *wp = NULL;
unsigned char buf[expected_len];
FILE *file = open_write_pipe(&wp);
if (!file)
return 2;
if (!write_u32_le(file, data[i].value)) {
perror(func);
return 3;
}
fflush(file); /* important, otherwise read will get stuck */
int nbytes = data_from_write_pipe(wp, buf, (int) sizeof buf);
fclose(file);
if (nbytes != expected_len) {
printf("%s() failed on dataset %d (%lu):\n", func, i, (unsigned long)data[i].value);
printf("expected to read %d bytes, got %d bytes\n", expected_len, nbytes);
return 1;
}
if (memcmp(data[i].expected, buf, expected_len) != 0) {
printf("%s() failed on dataset %d (%lu):\n", func, i, (unsigned long)data[i].value);
printf("expected 0x%02x%02x%02x%02x, got 0x%02x%02x%02x%02x\n",
(unsigned)data[i].expected[0], (unsigned)data[i].expected[1],
(unsigned)data[i].expected[2], (unsigned)data[i].expected[3],
(unsigned)buf[0], (unsigned)buf[1], (unsigned)buf[2], (unsigned)buf[3]);
return 1;
}
}
return 0;
}
if (!strcmp(func, "write_s32_le")) {
const int expected_len = 4;
struct {
int32_t value;
unsigned char *expected;
} data[] = {
{ .expected = (unsigned char[]){0x00,0x00,0x00,0x00}, .value = 0 },
{ .expected = (unsigned char[]){0x01,0x00,0x00,0x00}, .value = 1 },
{ .expected = (unsigned char[]){0xff,0xff,0xff,0xff}, .value = -1 },
{ .expected = (unsigned char[]){0x00,0x00,0x00,0x80}, .value = -2147483648L },
{ .expected = (unsigned char[]){0x01,0x00,0x00,0x80}, .value = -2147483647L },
{ .expected = (unsigned char[]){0xfe,0xff,0xff,0x7f}, .value = 2147483646L },
{ .expected = (unsigned char[]){0xff,0xff,0xff,0x7f}, .value = 2147483647L },
{ .expected = (unsigned char[]){0x12,0x34,0x56,0x78}, .value = 2018915346L },
};
for (int i = 0; i < ARRAY_LEN(data); i++) {
struct WritePipe *wp = NULL;
unsigned char buf[expected_len];
FILE *file = open_write_pipe(&wp);
if (!file)
return 2;
if (!write_s32_le(file, data[i].value)) {
perror(func);
return 3;
}
fflush(file); /* important, otherwise read will get stuck */
int nbytes = data_from_write_pipe(wp, buf, (int) sizeof buf);
fclose(file);
if (nbytes != expected_len) {
printf("%s() failed on dataset %d (%ld):\n", func, i, (long)data[i].value);
printf("expected to read %d bytes, got %d bytes\n", expected_len, nbytes);
return 1;
}
if (memcmp(data[i].expected, buf, expected_len) != 0) {
printf("%s() failed on dataset %d (%ld):\n", func, i, (long)data[i].value);
printf("expected 0x%02x%02x%02x%02x, got 0x%02x%02x%02x%02x\n",
(unsigned)data[i].expected[0], (unsigned)data[i].expected[1],
(unsigned)data[i].expected[2], (unsigned)data[i].expected[3],
(unsigned)buf[0], (unsigned)buf[1], (unsigned)buf[2], (unsigned)buf[3]);
return 1;
}
}
return 0;
}
if (!strcmp(func, "write_u16_le")) {
const int expected_len = 2;
struct {
uint16_t value;
unsigned char *expected;
} data[] = {
{ .expected = (unsigned char[]){0x00,0x00}, .value = 0 },
{ .expected = (unsigned char[]){0x01,0x00}, .value = 1 },
{ .expected = (unsigned char[]){0xfe,0xff}, .value = 65534 },
{ .expected = (unsigned char[]){0xff,0xff}, .value = 65535 },
};
for (int i = 0; i < ARRAY_LEN(data); i++) {
struct WritePipe *wp = NULL;
unsigned char buf[expected_len];
FILE *file = open_write_pipe(&wp);
if (!file)
return 2;
if (!write_u16_le(file, data[i].value)) {
perror(func);
return 3;
}
fflush(file); /* important, otherwise read will get stuck */
int nbytes = data_from_write_pipe(wp, buf, (int) sizeof buf);
fclose(file);
if (nbytes != expected_len) {
printf("%s() failed on dataset %d (%u):\n", func, i, (unsigned)data[i].value);
printf("expected to read %d bytes, got %d bytes\n", expected_len, nbytes);
return 1;
}
if (memcmp(data[i].expected, buf, expected_len) != 0) {
printf("%s() failed on dataset %d (%u):\n", func, i, (unsigned)data[i].value);
printf("expected 0x%02x%02x, got 0x%02x%02x\n",
(unsigned)data[i].expected[0], (unsigned)data[i].expected[1],
(unsigned)buf[0], (unsigned)buf[1]);
return 1;
}
}
return 0;
}
if (!strcmp(func, "write_s16_le")) {
const int expected_len = 2;
struct {
int16_t value;
unsigned char *expected;
} data[] = {
{ .expected = (unsigned char[]){0x00,0x00}, .value = 0 },
{ .expected = (unsigned char[]){0x01,0x00}, .value = 1 },
{ .expected = (unsigned char[]){0x00,0x80}, .value = -32768 },
{ .expected = (unsigned char[]){0x01,0x80}, .value = -32767 },
{ .expected = (unsigned char[]){0xfe,0x7f}, .value = 32766 },
{ .expected = (unsigned char[]){0xff,0x7f}, .value = 32767 },
};
for (int i = 0; i < ARRAY_LEN(data); i++) {
struct WritePipe *wp = NULL;
unsigned char buf[expected_len];
FILE *file = open_write_pipe(&wp);
if (!file)
return 2;
if (!write_s16_le(file, data[i].value)) {
perror(func);
return 3;
}
fflush(file); /* important, otherwise read will get stuck */
int nbytes = data_from_write_pipe(wp, buf, (int) sizeof buf);
fclose(file);
if (nbytes != expected_len) {
printf("%s() failed on dataset %d (%d):\n", func, i, (int)data[i].value);
printf("expected to read %d bytes, got %d bytes\n", expected_len, nbytes);
return 1;
}
if (memcmp(data[i].expected, buf, expected_len) != 0) {
printf("%s() failed on dataset %d (%d):\n", func, i, (int)data[i].value);
printf("expected 0x%02x%02x, got 0x%02x%02x\n",
(unsigned)data[i].expected[0], (unsigned)data[i].expected[1],
(unsigned)buf[0], (unsigned)buf[1]);
return 1;
}
}
return 0;
}
if (!strcmp(func, "s_imgrgb_to_outbytes") && !strcmp(subtest, "int")) {
struct Bmpwrite bw = { 0 };
struct {
int src_channels;
bool src_has_alpha;
BMPFORMAT src_format;
int src_bitsperchannel;
bool out_64bit;
struct Colormask masks;
const unsigned char *imgbytes;
unsigned long long expected;
} data[] = {
{ .src_channels = 1, .src_has_alpha = false, .src_format = BMP_FORMAT_INT,
.src_bitsperchannel = 8, .out_64bit = false,
.masks.mask = { .red = 0xff, .green = 0xff, .blue = 0xff },
.masks.shift = { .red = 0, .green = 8, .blue = 16 },
.masks.bits = { .red = 8, .green = 8, .blue = 8},
.masks.maxval = { .red = 255.0, .green = 255.0, .blue = 255.0},
.imgbytes = (unsigned char[]){ 0x45 },
.expected = 0x00454545ULL,
},
{ .src_channels = 3, .src_has_alpha = false, .src_format = BMP_FORMAT_INT,
.src_bitsperchannel = 8, .out_64bit = false,
.masks.mask = { .red = 0xff, .green = 0xff, .blue = 0xff },
.masks.shift = { .red = 0, .green = 8, .blue = 16 },
.masks.bits = { .red = 8, .green = 8, .blue = 8},
.masks.maxval = { .red = 255.0, .green = 255.0, .blue = 255.0},
.imgbytes = (unsigned char[]){ 0x12, 0x34, 0x45 },
.expected = 0x00453412ULL,
},
{ .src_channels = 4, .src_has_alpha = true, .src_format = BMP_FORMAT_INT,
.src_bitsperchannel = 8, .out_64bit = false,
.masks.mask = { .red = 0xff, .green = 0xff, .blue = 0xff, .alpha = 0xff },
.masks.shift = { .red = 0, .green = 8, .blue = 16, .alpha = 24 },
.masks.bits = { .red = 8, .green = 8, .blue = 8, .alpha = 8},
.masks.maxval = { .red = 255.0, .green = 255.0, .blue = 255.0, .alpha = 255.0 },
.imgbytes = (unsigned char[]){ 0x12, 0x34, 0x45, 0x67 },
.expected = 0x67453412ULL,
},
{ .src_channels = 4, .src_has_alpha = true, .src_format = BMP_FORMAT_INT,
.src_bitsperchannel = 8, .out_64bit = false,
.masks.mask = { .red = 0x3ff, .green = 0x3ff, .blue = 0x3ff, .alpha = 0x1 },
.masks.shift = { .red = 0, .green = 10, .blue = 20, .alpha = 30 },
.masks.bits = { .red = 10, .green = 10, .blue = 10, .alpha = 1 },
.masks.maxval = { .red = 1023.0 , .green = 1023.0 , .blue = 1023.0 , .alpha = 1.0 },
.imgbytes = (unsigned char[]){ 0x79, 0x11, 0xe6, 0xff },
.expected = 0x79b111e5ULL,
},
{ .src_channels = 4, .src_has_alpha = true, .src_format = BMP_FORMAT_INT,
.src_bitsperchannel = 16, .out_64bit = false,
.masks.mask = { .red = 0xff, .green = 0x1ff, .blue = 0x3ff, .alpha = 0x1f },
.masks.shift = { .red = 0, .green = 8, .blue = 17, .alpha = 27 },
.masks.bits = { .red = 8, .green = 9, .blue = 10, .alpha = 5 },
.masks.maxval = { .red = 255.0 , .green = 511.0 , .blue = 1023.0 , .alpha = 31.0 },
.imgbytes = (unsigned char[]){ 0x79, 0x00, 0x32, 0x09, 0x45, 0xf5, 0x00, 0x80 },
.expected = 0x87a81200ULL,
},
{ .src_channels = 4, .src_has_alpha = true, .src_format = BMP_FORMAT_INT,
.src_bitsperchannel = 32, .out_64bit = false,
.masks.mask = { .red = 0xff, .green = 0x1ff, .blue = 0x3ff, .alpha = 0x1f },
.masks.shift = { .red = 0, .green = 8, .blue = 17, .alpha = 27 },
.masks.bits = { .red = 8, .green = 9, .blue = 10, .alpha = 5 },
.masks.maxval = { .red = 255.0 , .green = 511.0 , .blue = 1023.0 , .alpha = 31.0 },
.imgbytes = (unsigned char[]){ 0xf8, 0x15, 0xd3, 0x89, 0xcc, 0x15, 0x6f, 0x55,
0x5f, 0xd5, 0xfb, 0x1d, 0x19, 0xc8, 0x60, 0x36 },
.expected = 0x38f0ab89ULL,
},
};
for (int i = 0; i < ARRAY_LEN(data); i++) {
bw.source_channels = data[i].src_channels;
bw.source_has_alpha = data[i].src_has_alpha;
bw.source_format = data[i].src_format;
bw.source_bitsperchannel = data[i].src_bitsperchannel;
bw.out64bit = data[i].out_64bit;
memcpy(&bw.cmask, &data[i].masks, sizeof data[i].masks);
unsigned long long result = s_imgrgb_to_outbytes(&bw, data[i].imgbytes);
if (result != data[i].expected) {
printf("%s() - %s failed on dataset %d:\n", func, subtest, i);
printf("expected 0x%016llx, got 0x%016llx\n",
data[i].expected, result);
return 1;
}
}
return 0;
}
if (!strcmp(func, "s_imgrgb_to_outbytes") && !strcmp(subtest, "float")) {
struct Bmpwrite bw = { 0 };
struct {
int src_channels;
bool src_has_alpha;
BMPFORMAT src_format;
int src_bitsperchannel;
bool out_64bit;
struct Colormask masks;
const float *imgvals;
unsigned long long expected;
} data[] = {
{ .src_channels = 4, .src_has_alpha = true, .src_format = BMP_FORMAT_FLOAT,
.src_bitsperchannel = 32, .out_64bit = false,
.masks.mask = { .red = 0xff, .green = 0x1ff, .blue = 0x3ff, .alpha = 0x1f },
.masks.shift = { .red = 0, .green = 8, .blue = 17, .alpha = 27 },
.masks.bits = { .red = 8, .green = 9, .blue = 10, .alpha = 5 },
.masks.maxval = { .red = 255.0 , .green = 511.0 , .blue = 1023.0 , .alpha = 31.0 },
.imgvals = (float[]){ 0.3, 1.0, 0.78923, 0.6 },
.expected = 0x9e4fff4dULL,
},
{ .src_channels = 4, .src_has_alpha = true, .src_format = BMP_FORMAT_FLOAT,
.src_bitsperchannel = 32, .out_64bit = false,
.masks.mask = { .red = 0xff, .green = 0x1ff, .blue = 0x3ff, .alpha = 0x1f },
.masks.shift = { .red = 0, .green = 8, .blue = 17, .alpha = 27 },
.masks.bits = { .red = 8, .green = 9, .blue = 10, .alpha = 5 },
.masks.maxval = { .red = 255.0 , .green = 511.0 , .blue = 1023.0 , .alpha = 31.0 },
.imgvals = (float[]){ 0.3, 3.2, 0.78923, -1.5 },
.expected = 0x64fff4dULL,
},
};
for (int i = 0; i < ARRAY_LEN(data); i++) {
bw.source_channels = data[i].src_channels;
bw.source_has_alpha = data[i].src_has_alpha;
bw.source_format = data[i].src_format;
bw.source_bitsperchannel = data[i].src_bitsperchannel;
bw.out64bit = data[i].out_64bit;
memcpy(&bw.cmask, &data[i].masks, sizeof data[i].masks);
unsigned long long result = s_imgrgb_to_outbytes(&bw, (unsigned char*)data[i].imgvals);
if (result != data[i].expected) {
printf("%s() - %s failed on dataset %d:\n", func, subtest, i);
printf("expected 0x%016llx, got 0x%016llx\n",
data[i].expected, result);
return 1;
}
}
return 0;
}
if (!strcmp(func, "s_imgrgb_to_outbytes") && !strcmp(subtest, "s2.13")) {
struct Bmpwrite bw = { 0 };
struct {
int src_channels;
bool src_has_alpha;
BMPFORMAT src_format;
int src_bitsperchannel;
bool out_64bit;
struct Colormask masks;
const unsigned char *imgbytes;
unsigned long long expected;
} data[] = {
{ .src_channels = 4, .src_has_alpha = true, .src_format = BMP_FORMAT_S2_13,
.src_bitsperchannel = 16, .out_64bit = false,
.masks.mask = { .red = 0xff, .green = 0x7ff, .blue = 0x3ff, .alpha = 0x7 },
.masks.shift = { .red = 0, .green = 8, .blue = 19, .alpha = 29 },
.masks.bits = { .red = 8, .green = 11, .blue = 10, .alpha = 3 },
.masks.maxval = { .red = 255.0 , .green = 2047.0 , .blue = 1023.0 , .alpha = 7.0 },
.imgbytes = (unsigned char[]){ 0x81, 0x0e, 0x7d, 0x67, 0x41, 0x19, 0x68, 0xb1 },
.expected = 0x193fff74ULL,
},
};
for (int i = 0; i < ARRAY_LEN(data); i++) {
bw.source_channels = data[i].src_channels;
bw.source_has_alpha = data[i].src_has_alpha;
bw.source_format = data[i].src_format;
bw.source_bitsperchannel = data[i].src_bitsperchannel;
bw.out64bit = data[i].out_64bit;
memcpy(&bw.cmask, &data[i].masks, sizeof data[i].masks);
unsigned long long result = s_imgrgb_to_outbytes(&bw, (unsigned char*)data[i].imgbytes);
if (result != data[i].expected) {
printf("%s() - %s failed on dataset %d:\n", func, subtest, i);
printf("expected 0x%016llx, got 0x%016llx\n",
data[i].expected, result);
return 1;
}
}
return 0;
}
fprintf(stderr, "Invalid test '%s'\n", func);
return 2;
}