Debian Codegraph @

converter/other/winicontopam.c

raw
1 /*=============================================================================
2 winicontopam
3 ===============================================================================
4 Convert from Windows icon format to PAM
5 =============================================================================*/
6
7 /*
8 Here are some references for the Windows icon format:
9
10 ICO (file format) - Wikipedia
11 https://en.wikipedia.org/wiki/ICO_(file_format)
12
13 ICO - Just Solve the File Format Problem
14 http://fileformats.archiveteam.org/wiki/ICO
15 (Has links to example icon file collections)
16
17 GFF Format Summary: Microsoft Windows Cursor and Icon
18 https://web.archive.org/web/20050421161512/http:/www.oreilly.com/www/centers/gff/formats/miccur/index.htm
19
20
21 */
22
23 #include <assert.h>
24 #include <stdio.h>
25 #include <string.h>
26
27 #include "netpbm/pm_config.h"
28 #include "netpbm/pm_c_util.h"
29 #include "netpbm/mallocvar.h"
30 #include "netpbm/nstring.h"
31 #include "netpbm/shhopt.h"
32 #include "netpbm/pam.h"
33 #include "netpbm/pm_system.h"
34
35 #include "winicon.h"
36
37 #define RED 0
38 #define GRN 1
39 #define BLU 2
40 #define ALPHA 3
41 #define CHANNEL_CHARS "RGBA"
42
43
44
45 static bool verbose;
46
47
48
49 struct CmdlineInfo {
50
51 const char * inputFileName;
52 unsigned int allimages;
53 unsigned int imageSpec;
54 unsigned int image;
55 unsigned int andmasks;
56 unsigned int headerdump;
57 unsigned int verbose;
58 };
59
60
61
62 static void
63 parseCommandLine(int argc, const char **argv,
64 struct CmdlineInfo * const cmdlineP) {
65
66 optEntry * option_def;
67 unsigned int option_def_index;
68 optStruct3 opt3;
69
70 MALLOCARRAY_NOFAIL(option_def, 100);
71
72 option_def_index = 0;
73
74 OPTENT3(0, "allimages", OPT_FLAG, NULL,
75 &cmdlineP->allimages, 0);
76 OPTENT3(0, "image", OPT_UINT, &cmdlineP->image,
77 &cmdlineP->imageSpec, 0);
78 OPTENT3(0, "andmasks", OPT_FLAG, NULL,
79 &cmdlineP->andmasks, 0);
80 OPTENT3(0, "headerdump", OPT_FLAG, NULL,
81 &cmdlineP->headerdump, 0);
82 OPTENT3(0, "verbose", OPT_FLAG, NULL,
83 &cmdlineP->verbose, 0);
84
85 opt3.opt_table = option_def;
86 opt3.short_allowed = false;
87 opt3.allowNegNum = false;
88
89 pm_optParseOptions4(&argc, argv, opt3, sizeof(opt3), 0);
90
91 if (cmdlineP->allimages && cmdlineP->imageSpec)
92 pm_error("You cannot specify both -allimages and -image");
93
94 if (argc-1 < 1)
95 cmdlineP->inputFileName = "-";
96 else {
97 cmdlineP->inputFileName = argv[1];
98
99 if (argc-1 > 1)
100 pm_error("Too many arguments. The only possible "
101 "non-option argument is the input file name");
102 }
103
104 free(option_def);
105 }
106
107
108
109 static unsigned char const pngSignature[] = PNG_SIGNATURE;
110
111
112
113 struct File {
114
115 FILE * fileP;
116 const char * name;
117 pm_filepos pos;
118
119 };
120
121
122
123 static uint32_t
124 u8_le(const unsigned char * const buf,
125 size_t const offset) {
126
127 return buf[offset + 0];
128 }
129
130
131
132 static uint32_t
133 u16_le(const unsigned char * const buf,
134 size_t const offset) {
135
136 return
137 ((uint32_t)buf[offset + 0] << 0) +
138 ((uint32_t)buf[offset + 1] << 8);
139 }
140
141
142
143 static uint32_t
144 u32_le(const unsigned char * const buf,
145 size_t const offset) {
146
147 return
148 ((uint32_t)buf[offset + 0] << 0) +
149 ((uint32_t)buf[offset + 1] << 8) +
150 ((uint32_t)buf[offset + 2] << 16) +
151 ((uint32_t)buf[offset + 3] << 24);
152 }
153
154
155
156 static uint32_t
157 s32_le(const unsigned char * const buf,
158 size_t const offset) {
159
160 return
161 ((uint32_t)buf[offset + 0] << 0) +
162 ((uint32_t)buf[offset + 1] << 8) +
163 ((uint32_t)buf[offset + 2] << 16) +
164 ((uint32_t)buf[offset + 3] << 24);
165 }
166
167
168
169 static uint32_t
170 u8_be(const unsigned char * const buf,
171 size_t const offset) {
172
173 return buf[offset + 0];
174 }
175
176
177
178 static uint32_t
179 u32_be(const unsigned char * const buf,
180 size_t const offset) {
181
182 return
183 ((uint32_t)buf[offset + 0] << 24) +
184 ((uint32_t)buf[offset + 1] << 16) +
185 ((uint32_t)buf[offset + 2] << 8) +
186 ((uint32_t)buf[offset + 3] << 0);
187 }
188
189
190
191 static uint32_t
192 u32_xx(const unsigned char * const buf,
193 size_t const offset) {
194
195 uint32_t u32;
196
197 ((uint8_t*) &u32)[0] = buf[offset + 0];
198 ((uint8_t*) &u32)[1] = buf[offset + 1];
199 ((uint8_t*) &u32)[2] = buf[offset + 2];
200 ((uint8_t*) &u32)[3] = buf[offset + 3];
201
202 return (u32);
203 }
204
205
206
207 #ifndef LITERAL_FN_DEF_MATCH
208 static qsort_comparison_fn cmpfn;
209 #endif
210
211 static int
212 cmpfn(const void * const aP,
213 const void * const bP) {
214
215 const struct IconDirEntry * const dirEntryAP = aP;
216 const struct IconDirEntry * const dirEntryBP = bP;
217
218 if (dirEntryAP->offset < dirEntryBP->offset)
219 return -1;
220 else if (dirEntryAP->offset > dirEntryBP->offset)
221 return +1;
222 else
223 return 0;
224 }
225
226
227
228 static void
229 dumpIconDir(const struct IconDir * const dirP) {
230
231 unsigned int i;
232
233 pm_message("Type: %u", dirP->type);
234 pm_message("Icon directory has %u images:", dirP->count);
235
236 for (i = 0; i < dirP->count; ++i) {
237 const struct IconDirEntry * const dirEntryP = &dirP->entries[i];
238
239 pm_message("width: %u", dirEntryP->width);
240 pm_message("height: %u", dirEntryP->height);
241 pm_message("color count: %u", dirEntryP->color_count);
242 pm_message("# color planes: %u", dirEntryP->color_planes);
243 pm_message("bits per pixel: %u", dirEntryP->bits_per_pixel);
244 pm_message("offset in file of image: %u", dirEntryP->offset);
245 pm_message("size of image: %u", dirEntryP->size);
246 pm_message("zero field: %u", dirEntryP->zero);
247 }
248 }
249
250
251
252 static struct IconDir *
253 readIconDir(struct File * const fP,
254 bool const needHeaderDump) {
255
256 struct IconDir head;
257 struct IconDir * dirP;
258 uint32_t imageIndex; /* more bits than dir.count */
259
260 pm_readlittleshortu(fP->fileP, &head.zero);
261 pm_readlittleshortu(fP->fileP, &head.type);
262 pm_readlittleshortu(fP->fileP, &head.count);
263 fP->pos += 6;
264
265 if (head.zero != 0 || head.type != ICONDIR_TYPE_ICO)
266 pm_error("Not a valid windows icon file");
267
268 MALLOCVAR(dirP);
269
270 if (dirP == NULL)
271 pm_error("Couldn't allocate memory for Icon directory");
272
273 MALLOCARRAY(dirP->entries, head.count);
274
275 if (dirP->entries == NULL)
276 pm_error("Could not allocate memory for %u entries in icon directory",
277 head.count);
278
279 dirP->zero = head.zero;
280 dirP->type = head.type;
281 dirP->count = head.count;
282 dirP->entriesAllocCt = head.count;
283
284 for (imageIndex = 0; imageIndex < head.count; ++imageIndex) {
285 struct IconDirEntry * const dirEntryP = &dirP->entries[imageIndex];
286
287 unsigned char widthField, heightField;
288
289 unsigned long ul;
290
291 pm_readcharu(fP->fileP, &widthField);
292 dirEntryP->width = (widthField == 0 ? 256 : widthField);
293
294 pm_readcharu(fP->fileP, &heightField);
295 dirEntryP->height = (heightField == 0 ? 256 : heightField);
296
297 pm_readcharu(fP->fileP, &dirEntryP->color_count);
298
299 pm_readcharu(fP->fileP, &dirEntryP->zero);
300
301 pm_readlittleshortu(fP->fileP, &dirEntryP->color_planes);
302
303 pm_readlittleshortu(fP->fileP, &dirEntryP->bits_per_pixel);
304
305 pm_readlittlelongu(fP->fileP, &ul); dirEntryP->size = ul;
306
307 pm_readlittlelongu(fP->fileP, &ul); dirEntryP->offset = ul;
308
309 fP->pos += 16;
310
311 dirEntryP->index = imageIndex;
312 }
313
314 /* The following is paranoia code only:
315
316 I've never seen a windows icon file in the wild with having the entries
317 in the directory stored in a different order than the images
318 themselves. However, the file format allows for it ...
319 */
320 qsort(dirP->entries, dirP->count, sizeof(struct IconDirEntry), cmpfn);
321
322 if (verbose) {
323 pm_message("%s icon directory (%u image%s):",
324 fP->name,
325 dirP->count, dirP->count == 1 ? "" : "s");
326
327 for (imageIndex = 0; imageIndex < dirP->count; ++imageIndex) {
328 const struct IconDirEntry * const dirEntryP =
329 &dirP->entries[imageIndex];
330
331 uint32_t colorCt;
332
333 if (dirEntryP->bits_per_pixel == 0)
334 colorCt = 0;
335 else if (dirEntryP->bits_per_pixel >= 32)
336 colorCt = 1u << 24;
337 else
338 colorCt = 1u << dirEntryP->bits_per_pixel;
339
340 if (dirEntryP->color_count != 0 &&
341 colorCt > dirEntryP->color_count) {
342 colorCt = dirEntryP->color_count;
343 }
344 pm_message ("%5u: %3u x %3u, %8u colors, %5u bytes",
345 dirEntryP->index,
346 dirEntryP->width,
347 dirEntryP->height,
348 colorCt,
349 dirEntryP->size);
350 }
351 }
352
353 if (needHeaderDump)
354 dumpIconDir(dirP);
355
356 return dirP;
357 }
358
359
360
361 static void
362 freeIconDir(struct IconDir * const dirP) {
363
364 free(dirP->entries);
365 free(dirP);
366 }
367
368
369
370 static const unsigned char *
371 readImage(struct File * const fP,
372 struct IconDirEntry * const dirEntryP) {
373
374 size_t rc;
375 unsigned char * image;
376 uint32_t skippedCt;
377
378 /* Don't try to read an image that is smaller than the
379 BITMAPINFOHEADER of BMP images (40 bytes).
380
381 PNG compressed images can't be smaller than that either, as the
382 PNG header plus the mandantory IHDR and IEND chunks already take
383 8 + 25 + 12 = 35 bytes, and there is to be a IDAT chunk too.
384 */
385 if (dirEntryP->size < 40) {
386 pm_error("image %2u: format violation: too small as an image.",
387 dirEntryP->index);
388 }
389 if ((pm_filepos) dirEntryP->offset < fP->pos)
390 pm_error("image %2u: format violation: invalid offset.",
391 dirEntryP->index);
392
393 /* The following is paranoia code only:
394
395 I've never seen a windows icon file in the wild with gaps between
396 the images, but the file format allows for it, and Microsoft
397 expects the user to fseek() to the start of each image.
398 */
399 skippedCt = 0;
400
401 while ((pm_filepos) dirEntryP->offset > fP->pos) {
402 if (getc(fP->fileP) == EOF) {
403 pm_error("seeking to image %u: unexpected EOF", dirEntryP->index);
404 }
405 ++fP->pos;
406 ++skippedCt;
407 }
408
409 /* The additional four bytes are for purify and friends, as the
410 routines reading BMP XOR and AND masks might read (but not
411 evaluate) some bytes beyond the image data.
412 */
413 image = malloc(dirEntryP->size + sizeof(uint32_t));
414 if (image == NULL)
415 pm_error("out of memory.");
416
417 rc = fread (image, 1, dirEntryP->size, fP->fileP);
418 if (rc != dirEntryP->size) {
419 pm_error("reading image %2u: unexpected EOF", dirEntryP->index);
420 }
421 fP->pos += dirEntryP->size;
422
423 return image;
424 }
425
426
427
428 static uint8_t
429 getIdx1(const unsigned char * const bitmap,
430 uint32_t const offset,
431 int16_t const col) {
432
433 return u8_le(bitmap, offset + (col >> 3)) >> (7 - (col & 0x07)) & 0x1;
434 }
435
436
437
438 static uint8_t
439 getIdx4(const unsigned char * const bitmap,
440 uint32_t const offset,
441 int16_t const col) {
442
443 if ((col & 1) == 0x0000)
444 return u8_le(bitmap, offset + (col >> 1)) >> 4 & 0x0F;
445 else
446 return u8_le(bitmap, offset + (col >> 1)) >> 0 & 0x0F;
447 }
448
449
450
451 static uint8_t
452 getIdx8(const unsigned char * const bitmap,
453 uint32_t const offset,
454 int16_t const col) {
455
456 return u8_le(bitmap, offset + col);
457 }
458
459
460
461 typedef unsigned char PaletteEntry[4];
462
463
464
465 static void
466 dumpPalette(const PaletteEntry * const palette,
467 unsigned int const colorCt) {
468
469 unsigned int i;
470
471 for (i = 0; i < colorCt; ++i) {
472 pm_message("Color %u: (%u, %u, %u)",
473 i, palette[i][2], palette[i][1], palette[i][0]);
474 }
475 }
476
477
478
479 static void
480 readXorPalette(struct BitmapInfoHeader * const hdrP,
481 const unsigned char * const bitmap,
482 uint32_t const maxSize,
483 tuple ** const tuples,
484 uint16_t const index,
485 bool const needHeaderDump,
486 uint32_t * const bytesConsumedP) {
487
488 uint32_t paletteSize;
489
490 int16_t row;
491 const PaletteEntry * palette;
492 uint32_t truncatedXorSize;
493 uint32_t bytesConsumed;
494 uint32_t bytesPerRow;
495 const unsigned char * bitmapCursor;
496 uint32_t sizeRemaining;
497
498 uint8_t (*getIdx) (const unsigned char * bitmap,
499 uint32_t rowOffset,
500 int16_t col);
501
502 if (hdrP->compression_method != BI_RGB)
503 pm_error("image %2u: invalid compression method %u.",
504 index, hdrP->compression_method);
505
506 assert(hdrP->bits_per_pixel < 16);
507
508 switch (hdrP->bits_per_pixel) {
509 case 1:
510 if (hdrP->colors_in_palette == 0)
511 hdrP->colors_in_palette = 2;
512 getIdx = getIdx1;
513 break;
514
515 case 4:
516 if (hdrP->colors_in_palette == 0)
517 hdrP->colors_in_palette = 16;
518 getIdx = getIdx4;
519 break;
520
521 case 8:
522 if (hdrP->colors_in_palette == 0)
523 hdrP->colors_in_palette = 256;
524 getIdx = getIdx8;
525 break;
526
527 default:
528 pm_error("image %2u: "
529 "bits per pixel is a value we don't understand: %u",
530 index, hdrP->bits_per_pixel);
531 getIdx = NULL;
532 }
533
534 bitmapCursor = &bitmap[0]; /* initial value */
535 sizeRemaining = maxSize; /* initial value */
536 bytesConsumed = 0; /* initial value */
537
538 paletteSize = hdrP->colors_in_palette * 4;
539
540 if (sizeRemaining < paletteSize)
541 pm_error("image %2u: "
542 "reading palette: image truncated.", index);
543
544 palette = (const PaletteEntry *) bitmapCursor;
545
546 if (needHeaderDump)
547 dumpPalette(palette, hdrP->colors_in_palette);
548
549 bitmapCursor += paletteSize;
550 sizeRemaining -= paletteSize;
551 bytesConsumed += paletteSize;
552
553 {
554 uint32_t const xorSize = (uint32_t)
555 (((hdrP->bits_per_pixel * hdrP->bm_width + 31) / 32)
556 * 4 * hdrP->bm_height / 2);
557
558 if (sizeRemaining < xorSize) {
559 pm_message("image %2u: "
560 "reading XOR mask: image truncated.", index);
561 truncatedXorSize = sizeRemaining;
562 } else
563 truncatedXorSize = xorSize;
564 }
565
566 bytesPerRow = ((hdrP->bits_per_pixel * hdrP->bm_width + 31) / 32) * 4;
567
568 for (row = 0; hdrP->bm_height / 2 > row; ++row) {
569 uint32_t rowOffset;
570
571 if (hdrP->top_down)
572 rowOffset = row * bytesPerRow;
573 else
574 rowOffset = (hdrP->bm_height / 2 - row - 1) * bytesPerRow;
575
576 if (rowOffset + bytesPerRow <= truncatedXorSize) {
577 int16_t col;
578 for (col = 0; hdrP->bm_width > col; ++col) {
579 uint8_t const idx = getIdx(bitmapCursor, rowOffset, col);
580
581 if (idx > hdrP->colors_in_palette)
582 pm_error("invalid palette index in row %u, column %u.",
583 row, col);
584
585 /* The palette is an array of little-endian 32-bit values,
586 where the RGB value is encoded as follows:
587
588 red: bits 2^16..2^23
589 green: bits 2^8 ..2^15
590 blue: bits 2^0 ..2^7
591 */
592 tuples[row][col][PAM_RED_PLANE] = palette[idx][2];
593 tuples[row][col][PAM_GRN_PLANE] = palette[idx][1];
594 tuples[row][col][PAM_BLU_PLANE] = palette[idx][0];
595 }
596 }
597 }
598
599 bitmapCursor += truncatedXorSize;
600 sizeRemaining -= truncatedXorSize;
601 bytesConsumed += truncatedXorSize;
602
603 *bytesConsumedP = bytesConsumed;
604 }
605
606
607
608 static void
609 readXorBitfields(struct BitmapInfoHeader * const hdrP,
610 const unsigned char * const bitmap,
611 uint32_t const maxSize,
612 tuple ** const tuples,
613 uint16_t const index,
614 bool * const haveAlphaP,
615 uint32_t * const bytesConsumedP) {
616 /*----------------------------------------------------------------------------
617 Return as *haveAlphaP whether the Xor mask indicates the pixels are
618 anything but fully opaque.
619 -----------------------------------------------------------------------------*/
620 uint32_t bitfields[4];
621 uint8_t shift [4];
622 sample maxval [4];
623
624 int16_t row;
625 uint32_t bytesConsumed;
626 uint32_t bytesPerSample;
627 uint32_t bytesPerRow;
628 const unsigned char * bitmapCursor;
629 uint32_t sizeRemaining;
630 uint32_t truncatedXorSize;
631
632 static uint8_t alphas [256];
633 bool allOpaque;
634 bool allTransparent;
635
636 bytesConsumed = 0;
637
638 if (hdrP->compression_method != BI_RGB
639 && hdrP->compression_method != BI_BITFIELDS)
640 pm_error("image %2u: invalid compression method %u.",
641 index, hdrP->compression_method);
642
643 assert(hdrP->bits_per_pixel >= 16);
644
645 switch (hdrP->bits_per_pixel) {
646 case 16:
647 bytesPerSample = 2;
648 bitfields[RED] = 0x7C00;
649 bitfields[GRN] = 0x03E0;
650 bitfields[BLU] = 0x001F;
651 bitfields[ALPHA] = 0x0000;
652 break;
653
654 case 24:
655 bytesPerSample = 3;
656 bitfields[RED] = 0xFF0000;
657 bitfields[GRN] = 0x00FF00;
658 bitfields[BLU] = 0x0000FF;
659 bitfields[ALPHA] = 0x000000;
660 break;
661
662 case 32:
663 bytesPerSample = 4;
664 bitfields[RED] = 0x00FF0000;
665 bitfields[GRN] = 0x0000FF00;
666 bitfields[BLU] = 0x000000FF;
667 bitfields[ALPHA] = 0xFF000000;
668 break;
669
670 default:
671 pm_error("image %2u: bits per pixel is one we don't understand: %u.",
672 index, hdrP->bits_per_pixel);
673 bytesPerSample = 0;
674 }
675
676 bitmapCursor = &bitmap[0]; /* initial value */
677 sizeRemaining = maxSize; /* initial value */
678
679 /* read bit fields from image data */
680 if (hdrP->compression_method == BI_BITFIELDS) {
681 if (sizeRemaining < 12)
682 pm_error("image %2u: "
683 "reading bit fields: image truncated.", index);
684
685 bitfields[RED] = u32_le(bitmapCursor, 0);
686 bitfields[GRN] = u32_le(bitmapCursor, 4);
687 bitfields[BLU] = u32_le(bitmapCursor, 8);
688 bitfields[ALPHA] = 0;
689
690 bitmapCursor += 12;
691 sizeRemaining -= 12;
692 bytesConsumed += 12;
693 }
694
695 /* determine shift and maxval from bit field for each channel */
696 {
697 unsigned int i;
698
699 for (i = 0; 4 > i; ++i) {
700 if (bitfields[i] == 0) {
701 maxval[i] = 1;
702 shift [i] = 0;
703 } else {
704 unsigned int j;
705
706 maxval[i] = bitfields[i];
707
708 for (j = 0; 32 > j; ++j) {
709 if ((maxval[i] & 0x1) != 0)
710 break;
711 maxval[i] >>= 1;
712 }
713 shift[i] = j;
714 }
715
716 }
717 }
718
719 /* read the XOR mask */
720 {
721 uint32_t const xorSize = (uint32_t)
722 (((hdrP->bits_per_pixel * hdrP->bm_width + 31) / 32)
723 * 4 * hdrP->bm_height / 2);
724
725 if (sizeRemaining < xorSize) {
726 pm_message("image %2u: "
727 "reading XOR mask: image truncated.", index);
728 truncatedXorSize = sizeRemaining;
729 } else
730 truncatedXorSize = xorSize;
731 }
732
733 bytesPerRow = ((hdrP->bits_per_pixel * hdrP->bm_width + 31) / 32) * 4;
734 MEMSZERO(alphas);
735
736 for (row = 0, allOpaque = true, allTransparent = true;
737 hdrP->bm_height / 2 > row;
738 ++row) {
739
740 uint32_t offset;
741
742 if (hdrP->top_down)
743 offset = row * bytesPerRow;
744 else
745 offset = (hdrP->bm_height / 2 - row - 1) * bytesPerRow;
746
747 if (offset + bytesPerRow <= truncatedXorSize) {
748 unsigned int col;
749 for (col = 0; col < hdrP->bm_width; ++col) {
750 uint32_t const pixel = u32_le(bitmapCursor, offset);
751 offset += bytesPerSample;
752
753 tuples[row][col][PAM_RED_PLANE] =
754 pnm_scalesample((pixel & bitfields[RED]) >> shift[RED],
755 maxval[RED], 255);
756 tuples[row][col][PAM_GRN_PLANE] =
757 pnm_scalesample((pixel & bitfields[GRN]) >> shift[GRN],
758 maxval[GRN], 255);
759 tuples [row][col][PAM_BLU_PLANE]
760 = pnm_scalesample((pixel & bitfields[BLU]) >> shift[BLU],
761 maxval[BLU], 255);
762
763 if (bitfields [ALPHA] != 0) {
764 tuples[row][col][PAM_TRN_PLANE]
765 = pnm_scalesample(
766 (pixel & bitfields[ALPHA]) >> shift[ALPHA],
767 maxval[ALPHA], 255);
768
769 if (tuples[row][col][PAM_TRN_PLANE] != 0)
770 allTransparent = false;
771
772 if (tuples [row][col][PAM_TRN_PLANE] != 255)
773 allOpaque = false;
774
775 alphas[tuples[row][col][PAM_TRN_PLANE]] = !0;
776 }
777 }
778 }
779 }
780
781 bitmapCursor += truncatedXorSize;
782 sizeRemaining -= truncatedXorSize;
783 bytesConsumed += truncatedXorSize;
784
785 /* A fully transparent alpha channel (all zero) in XOR mask is
786 defined to be void by Microsoft.
787 */
788 if (verbose) {
789 if (allTransparent)
790 pm_message("image %2u: All pixels are nominally coded in the "
791 "transparency map as fully transparent, "
792 "which is defined by the format to mean they "
793 "are all opaque", index);
794 if (allOpaque)
795 pm_message("image %2u: All pixels are fully opaque "
796 "in the transparency map", index);
797 }
798 *haveAlphaP = !allTransparent && !allOpaque;
799
800 if (!allTransparent && ! allOpaque && verbose) {
801 unsigned int i;
802 unsigned int c;
803
804 for (i = 0, c = 0; 256 > i; ++i) {
805 if (alphas[i] != 0)
806 ++c;
807 }
808 pm_message("image %2u: %u distinct transparency value%s",
809 index, c, (c == 1) ? "": "s");
810 }
811 *bytesConsumedP = bytesConsumed;
812 }
813
814
815
816 static void
817 readAnd(struct BitmapInfoHeader * const hdrP,
818 const unsigned char * const bitmap,
819 uint32_t const maxSize,
820 tuple ** const tuples,
821 uint16_t const index,
822 unsigned int const plane,
823 sample const maxval) {
824 /*----------------------------------------------------------------------------
825 Fill in plane 'plane' of the tuple array 'tuples' according to the and
826 mask of a Windows icon. Where the and mask for a pixel is 1, set the
827 plane to 'maxval'; where it is zero, set it to zero.
828
829 'bitmap' is the and mask, in a format describe dby *hdrP.
830
831 'index' is the position of the icon in question in the Windows icon file --
832 the first image in the file is 0, second is 1, etc.
833 -----------------------------------------------------------------------------*/
834 int16_t row;
835 uint32_t bytesConsumed;
836 uint32_t bytesPerRow;
837 uint32_t sizeRemaining;
838 uint32_t truncatedAndSize;
839
840 sizeRemaining = maxSize; /* initial value */
841 bytesConsumed = 0; /* initial value */
842
843 {
844 uint32_t const andSize = (uint32_t)
845 (((1 * hdrP->bm_width + 31) / 32) * 4 * hdrP->bm_height / 2);
846
847 if (sizeRemaining < andSize) {
848 pm_message ("image %2u: "
849 "Input image ends %u bytes into the %u-byte "
850 "AND mask. Implying remainder of mask",
851 index, sizeRemaining, andSize);
852 truncatedAndSize = sizeRemaining;
853 } else
854 truncatedAndSize = andSize;
855 }
856
857 bytesPerRow = ((1 * hdrP->bm_width + 31) / 32) * 4;
858
859 for (row = 0; row < hdrP->bm_height / 2; ++row) {
860 uint32_t offset;
861
862 if (hdrP->top_down)
863 offset = row * bytesPerRow;
864 else
865 offset = (hdrP->bm_height / 2 - row - 1) * bytesPerRow;
866
867 if (offset + bytesPerRow <= sizeRemaining) {
868 unsigned int col;
869
870 for (col = 0; col < hdrP->bm_width; ++col) {
871 tuples[row][col][plane] =
872 ((u8_le(bitmap, offset + col/8)
873 & (1 << (7 - (col & 0x7)))) == 0x00) ?
874 maxval : 0
875 ;
876 }
877 }
878 }
879 sizeRemaining -= truncatedAndSize;
880 bytesConsumed += truncatedAndSize;
881 }
882
883
884
885 static void
886 dumpBmpHeader(struct BitmapInfoHeader const hdr,
887 unsigned int const imageIndex) {
888
889 pm_message("BMP header for Image %u:", imageIndex);
890
891 pm_message("header size: %u", hdr.header_size);
892 pm_message("bitmap width: %u", hdr.bm_width);
893 pm_message("bitmap height * 2: %u", hdr.bm_height);
894 pm_message("row order: %s", hdr.top_down ? "top down" : "bottom up");
895 pm_message("# color planes: %u", hdr.color_planes);
896 pm_message("bits per pixel: %u", hdr.bits_per_pixel);
897 pm_message("image size: %u", hdr.image_size);
898 pm_message("horizontal resolution: %u", hdr.horizontal_resolution);
899 pm_message("vertical resolution: %u", hdr.vertical_resolution);
900 pm_message("# colors in palette: %u", hdr.colors_in_palette);
901 pm_message("# important colors: %u", hdr.important_colors);
902 }
903
904
905
906 static void
907 readBmpHeader(const unsigned char * const image,
908 uint32_t const size,
909 unsigned int const imageIndex,
910 bool const needHeaderDump,
911 struct BitmapInfoHeader * const hdrP) {
912
913 /* BITMAPINFOHEADER structure */
914
915 if (size < 40)
916 pm_error("image %2u: reading BITMAPINFOHEADER: not enough data.",
917 imageIndex);
918
919 hdrP->header_size = u32_le(image, 0);
920 hdrP->bm_width = s32_le(image, 4);
921 hdrP->bm_height = s32_le(image, 8);
922 hdrP->color_planes = u16_le(image, 12);
923 hdrP->bits_per_pixel = u16_le(image, 14);
924 hdrP->compression_method = u32_le(image, 16);
925 hdrP->image_size = u32_le(image, 20);
926 hdrP->horizontal_resolution = s32_le(image, 24);
927 hdrP->vertical_resolution = s32_le(image, 28);
928 hdrP->colors_in_palette = u32_le(image, 32);
929 hdrP->important_colors = u32_le(image, 36);
930
931 if (hdrP->bm_height > 0) {
932 hdrP->top_down = false;
933 } else {
934 hdrP->top_down = true;
935 hdrP->bm_height *= -1;
936 }
937
938 if (hdrP->header_size < 36
939 || hdrP->bm_width == 0 || hdrP->bm_height == 0
940 || (hdrP->bm_height & 1) != 0x0000) {
941 pm_error("image %2u: format violation: invalid BMP header.",
942 imageIndex);
943 }
944
945 if (needHeaderDump)
946 dumpBmpHeader(*hdrP, imageIndex);
947 }
948
949
950
951 static void
952 readXorMask(struct BitmapInfoHeader * const hdrP,
953 const unsigned char * const imageCursor,
954 uint32_t const imageSize,
955 tuple ** const tuples,
956 uint16_t const index,
957 bool const needHeaderDump,
958 bool * const haveAlphaP,
959 uint32_t * const bytesConsumedP) {
960 /*----------------------------------------------------------------------------
961 Read the so-called XOR mask (for non-monochrome images, this is the
962 color pixmap, which may include transparency).
963
964 Return the pixels as 'tuples', an array whose width and height are
965 given by *hdrP and depth is 4.
966
967 Return as *haveAlphaP whether the Xor mask indicates the pixels are
968 anything but fully opaque.
969 -----------------------------------------------------------------------------*/
970 /* preset the PAM with fully opaque black (just in case the image
971 is truncated and not all pixels are filled in below).
972 */
973 {
974 unsigned int row;
975
976 for (row = 0; row < hdrP->bm_height / 2; ++row) {
977 unsigned int col;
978 for (col = 0; col < hdrP->bm_width; ++col) {
979 tuples[row][col][PAM_RED_PLANE] = 0;
980 tuples[row][col][PAM_GRN_PLANE] = 0;
981 tuples[row][col][PAM_BLU_PLANE] = 0;
982 tuples[row][col][PAM_TRN_PLANE] = 255;
983 }
984 }
985 }
986
987 if (hdrP->bits_per_pixel < 16) {
988 readXorPalette(hdrP, imageCursor, imageSize, tuples, index,
989 needHeaderDump,
990 bytesConsumedP);
991 *haveAlphaP = false;
992 } else
993 readXorBitfields(hdrP, imageCursor, imageSize, tuples, index,
994 haveAlphaP, bytesConsumedP);
995 }
996
997
998
999 static void
1000 reportImage(unsigned int const imageIndex,
1001 struct BitmapInfoHeader const hdr,
1002 bool const haveAlpha) {
1003
1004 const char * const style =
1005 haveAlpha ? "RGB +alpha" :
1006 hdr.bits_per_pixel < 16 ? "RGB/palette" :
1007 "RGB"
1008 ;
1009
1010 pm_message("image %2u: "
1011 "BMP %3u x %3u x %2u (%s)",
1012 imageIndex,
1013 hdr.bm_width, hdr.bm_height / 2, hdr.bits_per_pixel,
1014 style);
1015 }
1016
1017
1018
1019 static void
1020 convertBmp(const unsigned char * const image,
1021 FILE * const ofP,
1022 struct IconDirEntry * const dirEntryP,
1023 bool const needHeaderDump,
1024 bool const wantAndMaskPlane) {
1025
1026 struct BitmapInfoHeader hdr;
1027 uint32_t offset;
1028 bool haveAlpha;
1029 uint32_t xorByteCt;
1030
1031 struct pam outpam;
1032 tuple ** tuples;
1033
1034 readBmpHeader(image, dirEntryP->size, dirEntryP->index, needHeaderDump,
1035 &hdr);
1036
1037 offset = hdr.header_size; /* Start after header */
1038
1039 if ((dirEntryP->width != hdr.bm_width)
1040 || (dirEntryP->height != hdr.bm_height / 2)) {
1041 pm_message("image %2u: "
1042 "mismatch in header and image dimensions "
1043 "(%u x %u vs. %u x %u)",
1044 dirEntryP->index,
1045 dirEntryP->width,
1046 dirEntryP->height,
1047 hdr.bm_width,
1048 hdr.bm_height / 2);
1049 }
1050
1051 if ((dirEntryP->bits_per_pixel != 0)
1052 && (dirEntryP->bits_per_pixel != hdr.bits_per_pixel)) {
1053 pm_message("image %2u "
1054 "mismatch in header and image bpp value"
1055 "(%u vs. %u)",
1056 dirEntryP->index,
1057 dirEntryP->bits_per_pixel,
1058 hdr.bits_per_pixel);
1059 }
1060
1061 outpam.size = sizeof(struct pam);
1062 outpam.len = PAM_STRUCT_SIZE(allocation_depth);
1063 outpam.file = ofP;
1064 outpam.format = PAM_FORMAT;
1065 outpam.width = hdr.bm_width;
1066 outpam.height = hdr.bm_height / 2;
1067 outpam.maxval = 255;
1068 outpam.allocation_depth = 5;
1069 outpam.depth = 0;
1070 /* Just for tuple array allocation; we set the value for the actual
1071 output image below.
1072 */
1073
1074 tuples = pnm_allocpamarray(&outpam);
1075
1076 readXorMask(&hdr, &image[offset],
1077 dirEntryP->size - offset,
1078 tuples, dirEntryP->index, needHeaderDump,
1079 &haveAlpha, &xorByteCt);
1080
1081 offset += xorByteCt;
1082
1083 {
1084 /* If there is no alpha channel in the XOR mask, use the AND mask as
1085 the transparency plane. Else, there are two transparency
1086 maps. If requested, return the AND mask as a fifth PAM plane.
1087 */
1088 bool haveAnd;
1089 unsigned int andPlane;
1090
1091 if (!haveAlpha) {
1092 haveAnd = true;
1093 andPlane = PAM_TRN_PLANE;
1094 strcpy (outpam.tuple_type, "RGB_ALPHA");
1095 outpam.depth = 4;
1096 } else if (wantAndMaskPlane) {
1097 haveAnd = true;
1098 andPlane = PAM_TRN_PLANE + 1;
1099 outpam.depth = 5;
1100 strcpy(outpam.tuple_type, "RGB_ALPHA_ANDMASK");
1101 } else {
1102 haveAnd = false;
1103 strcpy (outpam.tuple_type, "RGB_ALPHA");
1104 outpam.depth = 4;
1105 }
1106 if (haveAnd) {
1107 readAnd(&hdr, &image[offset], dirEntryP->size - offset,
1108 tuples, dirEntryP->index, andPlane, outpam.maxval);
1109 }
1110 }
1111 pnm_writepam(&outpam, tuples);
1112 pnm_freepamarray(tuples, &outpam);
1113
1114 reportImage(dirEntryP->index, hdr, haveAlpha);
1115 }
1116
1117
1118
1119 static void
1120 reportPngInfo(const unsigned char * const image,
1121 struct IconDirEntry * const dirEntryP) {
1122
1123 struct PngIhdr ihdr;
1124
1125 ihdr.length = u32_be (image, sizeof(pngSignature) +0);
1126 ihdr.signature = u32_xx (image, sizeof(pngSignature) +4);
1127 ihdr.width = u32_be (image, sizeof(pngSignature) +8);
1128 ihdr.height = u32_be (image, sizeof(pngSignature) +12);
1129 ihdr.bit_depth = u8_be (image, sizeof(pngSignature) +16);
1130 ihdr.color_type = u8_be (image, sizeof(pngSignature) +17);
1131 ihdr.compression = u8_be (image, sizeof(pngSignature) +18);
1132 ihdr.filter = u8_be (image, sizeof(pngSignature) +19);
1133 ihdr.interlace = u8_be (image, sizeof(pngSignature) +20);
1134
1135 if ((ihdr.length != 13)
1136 || ihdr.signature != *(uint32_t*)"IHDR") {
1137 pm_message("image %2u: PNG (uncommonly formatted)",
1138 dirEntryP->index);
1139 } else {
1140 uint32_t depth;
1141 const char * colorType;
1142
1143 switch (ihdr.color_type) {
1144 case 0:
1145 colorType = "grayscale";
1146 depth = ihdr.bit_depth;
1147 break;
1148
1149 case 2:
1150 colorType = "RGB";
1151 depth = ihdr.bit_depth * 3;
1152 break;
1153
1154 case 3:
1155 colorType = "RGB/palette";
1156 depth = 8;
1157 break;
1158
1159 case 4:
1160 colorType = "grayscale + alpha";
1161 depth = ihdr.bit_depth * 2;
1162 break;
1163
1164 case 6:
1165 colorType = "RGB + alpha";
1166 depth = ihdr.bit_depth * 4;
1167 break;
1168
1169 default:
1170 colorType = "unknown color system";
1171 depth = 0;
1172 break;
1173 }
1174 pm_message("image %2u: PNG %3u x %3u x %2u (%s)",
1175 dirEntryP->index,
1176 ihdr.width, ihdr.height, depth, colorType);
1177
1178 if ((dirEntryP->width != ihdr.width)
1179 || (dirEntryP->height != ihdr.height)) {
1180 pm_message("image %2u:"
1181 " mismatch in header and image dimensions"
1182 " (%u x %u vs %u x %u)",
1183 dirEntryP->index, dirEntryP->width, dirEntryP->height,
1184 ihdr.width, ihdr.height);
1185 }
1186 /* Mismatch between dirEntryP->bits_per_pixel and 'depth' is
1187 normal, because the creator of the winicon file doesn't necessarily
1188 know the true color resolution.
1189 */
1190 }
1191 }
1192
1193
1194
1195 static void
1196 convertPng(const unsigned char * const image,
1197 FILE * const ofP,
1198 struct IconDirEntry * const dirEntryP) {
1199
1200 pm_bufferDesc imageBuffer;
1201
1202 reportPngInfo(image, dirEntryP);
1203
1204 imageBuffer.size = dirEntryP->size;
1205 imageBuffer.buffer = (unsigned char *)image;
1206 imageBuffer.bytesTransferredP = NULL;
1207
1208 fflush(stdout);
1209
1210 pm_system_lp("pngtopam", pm_feed_from_memory, &imageBuffer,
1211 NULL /* stdout accepter */, NULL,
1212 "pngtopam", "-alphapam", NULL);
1213 }
1214
1215
1216
1217 static uint32_t
1218 bestImage(struct IconDir * const dirP) {
1219
1220 uint32_t imageIndex;
1221 uint32_t bestPixelCt;
1222 uint32_t bestColorCt;
1223 uint16_t best;
1224
1225 bestPixelCt = 0; /* initial value */
1226 bestColorCt = 0; /* initial value */
1227 best = 0; /* initial value */
1228
1229 for (imageIndex = 0; dirP->count > imageIndex; ++imageIndex) {
1230 struct IconDirEntry * const dirEntryP = &dirP->entries[imageIndex];
1231
1232 uint32_t const pixelCt = dirEntryP->width * dirEntryP->height;
1233
1234 uint32_t colorCt;
1235
1236 /* 32-bit icons have 24 bit color information only.
1237
1238 Since NT 5.1 (aka WinXP), it is allowed to place 8-bit
1239 transparency information in the remaining bits (to check,
1240 you have to read all these bits in the image!), so I prefer
1241 32-bit images over 24-bit images (which violate the
1242 spec. anyway).
1243 */
1244 if (dirEntryP->bits_per_pixel > 24)
1245 colorCt = 1u << 25;
1246 else
1247 colorCt = 1u << dirEntryP->bits_per_pixel;
1248
1249 if (dirEntryP->color_count != 0 && colorCt > dirEntryP->color_count)
1250 colorCt = dirEntryP->color_count;
1251
1252 if ((pixelCt > bestPixelCt)
1253 || ((pixelCt == bestPixelCt) && (colorCt > bestColorCt))) {
1254 /* This is a new best */
1255 bestPixelCt = pixelCt;
1256 bestColorCt = colorCt;
1257 best = imageIndex;
1258 }
1259 }
1260 return best;
1261 }
1262
1263
1264
1265 static void
1266 convertImage(struct File * const icoP,
1267 struct IconDirEntry * const dirEntryP,
1268 FILE * const ofP,
1269 bool const needHeaderDump,
1270 bool const wantAndMaskPlane) {
1271
1272 const unsigned char * image; /* malloced */
1273
1274 image = readImage(icoP, dirEntryP);
1275
1276 if (memeq(image, pngSignature, sizeof (pngSignature)))
1277 convertPng(image, ofP, dirEntryP);
1278 else
1279 convertBmp(image, ofP, dirEntryP, needHeaderDump, wantAndMaskPlane);
1280
1281 free((void *)image);
1282 }
1283
1284
1285
1286 int
1287 main (int argc, const char *argv []) {
1288
1289 struct File ico;
1290 struct IconDir * dirP;
1291 struct CmdlineInfo cmdline;
1292
1293 pm_proginit (&argc, argv);
1294
1295 parseCommandLine(argc, argv, &cmdline);
1296
1297 verbose = cmdline.verbose;
1298
1299 ico.name =
1300 streq(cmdline.inputFileName, "-") ? "<stdin>" : cmdline.inputFileName;
1301 ico.pos = 0;
1302 ico.fileP = pm_openr(cmdline.inputFileName);
1303
1304 dirP = readIconDir(&ico, cmdline.headerdump);
1305
1306 if (cmdline.allimages) {
1307 unsigned int i;
1308 for (i = 0; i < dirP->count; ++i)
1309 convertImage(&ico, &dirP->entries[i], stdout,
1310 cmdline.headerdump, cmdline.andmasks);
1311 } else if (cmdline.imageSpec) {
1312 unsigned int i;
1313 bool found;
1314 for (i = 0, found = false; i < dirP->count; ++i) {
1315 if (dirP->entries[i].index == cmdline.image) {
1316 found = true;
1317 convertImage(&ico, &dirP->entries[i], stdout,
1318 cmdline.headerdump, cmdline.andmasks);
1319 }
1320 }
1321 if (!found)
1322 pm_error("no image index %u in.input", cmdline.image);
1323 } else {
1324 convertImage(&ico, &dirP->entries[bestImage(dirP)], stdout,
1325 cmdline.headerdump, cmdline.andmasks);
1326 }
1327
1328 freeIconDir(dirP);
1329
1330 if (ico.fileP != stdin)
1331 pm_close(ico.fileP);
1332
1333 return 0;
1334 }
1335
1336
1337