Debian Codegraph @

converter/ppm/ilbmtoppm.c

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 /* ilbmtoppm.c - read an IFF ILBM file and produce a PPM
2 **
3 ** Copyright (C) 1989 by Jef Poskanzer.
4 **
5 ** Permission to use, copy, modify, and distribute this software and its
6 ** documentation for any purpose and without fee is hereby granted, provided
7 ** that the above copyright notice appear in all copies and that both that
8 ** copyright notice and this permission notice appear in supporting
9 ** documentation. This software is provided "as is" without express or
10 ** implied warranty.
11 **
12 ** Modified by Mark Thompson on 10/4/90 to accommodate 24-bit IFF files
13 ** as used by ASDG, NewTek, etc.
14 **
15 ** Modified by Ingo Wilken ([email protected])
16 ** 20/Jun/93:
17 ** - row-by-row operation
18 ** - better de-interleave algorithm
19 ** - colormap files
20 ** - direct color
21 ** 04/Oct/93:
22 ** - multipalette capability (PCHG chunk)
23 ** - options -ignore, -isham, -isehb and -adjustcolors
24 ** 22/May/94:
25 ** - minor change: check first for 24 planes, then for HAM
26 ** 21/Sep/94:
27 ** - write mask plane to a file if -maskfile option used
28 ** - write colormap file
29 ** - added sliced HAM/dynamic HAM/dynamic Hires multipalette formats (SHAM, CTBL chunk)
30 ** - added color lookup tables (CLUT chunk)
31 ** - major rework of colormap/multipalette handling
32 ** - now uses numeric IFF IDs
33 ** 24/Oct/94:
34 ** - transparentColor capability
35 ** - added RGBN/RGB8 image types
36 ** - 24-bit & direct color modified to n-bit deep ILBM
37 ** 22/Feb/95:
38 ** - direct color (DCOL) reimplemented
39 ** 29/Mar/95
40 ** - added IFF-PBM format
41 */
42
43 #include <string.h>
44
45 #include "pm_c_util.h"
46 #include "mallocvar.h"
47 #include "intcode.h"
48 #include "ilbm.h"
49 #include "ppm.h"
50
51 typedef struct {
52 int reg; /* color register to change */
53 pixval r, g, b; /* new colors for register */
54 } PaletteChange;
55
56 typedef struct {
57 pixel *color;
58 int ncolors;
59 /* lookup tables */
60 unsigned char *redlut;
61 unsigned char *greenlut;
62 unsigned char *bluelut;
63 unsigned char *monolut;
64 /* multipalette stuff */
65 PaletteChange *mp_init;
66 PaletteChange **mp_change;
67 int mp_rows; /* # of rows in change array */
68 int mp_type; /* see below, higher types preferred */
69 int mp_flags;
70 IFF_ID mp_id;
71 } ColorMap;
72
73 #define HAS_COLORMAP(cmap) ((cmap) && (cmap)->color)
74 #define HAS_COLORLUT(cmap) ((cmap) && ((cmap)->redlut || (cmap)->greenlut || (cmap)->bluelut))
75 #define HAS_MONOLUT(cmap) ((cmap) && (cmap)->monolut)
76 #define HAS_MULTIPALETTE(cmap) (HAS_COLORMAP(cmap) && (cmap)->mp_type)
77 #define MP_TYPE_SHAM 1
78 #define MP_TYPE_CTBL 2
79 #define MP_TYPE_PCHG 3
80 #define MP_REG_IGNORE -1
81 #define MP_REG_END -2
82 #define MP_FLAGS_SKIPLACED (1<<0)
83
84 #define FACTOR_4BIT 17 /* scale factor maxval 15 -> maxval 255 */
85
86 static short verbose = 0;
87 static short adjustcolors = 0;
88 static unsigned char *ilbmrow;
89 static pixel *pixelrow;
90 static FILE *maskfile = NULL;
91 static bit *maskrow = NULL;
92 static bool wrotemask;
93 static IFF_ID typeid; /* ID_ILBM, ID_RGBN, ID_RGB8 */
94
95 static char *transpName = NULL; /* -transparent option value */
96
97 static bool debug = FALSE;
98
99
100
101 static char *
102 ID2string(IFF_ID const id) {
103
104 static char str[4];
105
106 str[0] = (char)(id >> 24 & 0xff);
107 str[1] = (char)(id >> 16 & 0xff);
108 str[2] = (char)(id >> 8 & 0xff);
109 str[3] = (char)(id >> 0 & 0xff);
110
111 return str;
112 }
113
114
115
116 /****************************************************************************
117 Memory allocation
118 ****************************************************************************/
119 static ColorMap *
120 alloc_cmap(void) {
121
122 ColorMap * cmap;
123
124 MALLOCVAR_NOFAIL(cmap);
125
126 cmap->color = NULL;
127 cmap->ncolors = 0;
128 cmap->monolut = NULL;
129 cmap->redlut = NULL;
130 cmap->greenlut = NULL;
131 cmap->bluelut = NULL;
132 cmap->mp_init = NULL;
133 cmap->mp_change = NULL;
134 cmap->mp_rows = 0;
135 cmap->mp_type = 0;
136 cmap->mp_flags = 0;
137
138 return cmap;
139 }
140
141
142
143 static rawtype *
144 alloc_rawrow(unsigned int const cols) {
145
146 rawtype * r;
147 unsigned int col;
148
149 MALLOCARRAY_NOFAIL(r, cols);
150
151 for (col = 0; col < cols; ++col)
152 r[col] = 0;
153
154 return r;
155 }
156
157
158
159 /****************************************************************************
160 Basic I/O functions
161 ****************************************************************************/
162
163 static void
164 readerr(FILE * const fP,
165 IFF_ID const iffId) {
166
167 if (ferror(fP))
168 pm_error("read error");
169 else
170 pm_error("premature EOF in %s chunk", ID2string(iffId));
171 }
172
173
174
175 static void
176 read_bytes(FILE * const ifP,
177 int const bytes,
178 unsigned char * const buffer,
179 IFF_ID const iffid,
180 unsigned long * const counterP) {
181
182 if (counterP) {
183 if (*counterP < bytes)
184 pm_error("insufficient data in %s chunk", ID2string(iffid));
185 *counterP -= bytes;
186 }
187 if (fread(buffer, 1, bytes, ifP) != bytes)
188 readerr(ifP, iffid);
189 }
190
191
192
193 static unsigned char
194 get_byte(FILE * const ifP,
195 IFF_ID const iffId,
196 unsigned long * const counterP) {
197
198 int i;
199
200 if (counterP) {
201 if (*counterP == 0 )
202 pm_error("insufficient data in %s chunk", ID2string(iffId));
203 --(*counterP);
204 }
205 i = getc(ifP);
206 if (i == EOF)
207 readerr(ifP, iffId);
208
209 return (unsigned char) i;
210 }
211
212
213
214 static long
215 get_big_long(FILE * const ifP,
216 IFF_ID const iffid,
217 unsigned long * const counterP) {
218
219 long l;
220
221 if (counterP) {
222 if (*counterP < 4)
223 pm_error("insufficient data in %s chunk", ID2string(iffid));
224 *counterP -= 4;
225 }
226 if (pm_readbiglong(ifP, &l) == -1)
227 readerr(ifP, iffid);
228
229 return l;
230 }
231
232
233
234 static short
235 get_big_short(FILE * const ifP,
236 IFF_ID const iffid,
237 unsigned long * const counterP) {
238
239 short s;
240
241 if (counterP) {
242 if (*counterP < 2)
243 pm_error("insufficient data in %s chunk", ID2string(iffid));
244 *counterP -= 2;
245 }
246 if (pm_readbigshort(ifP, &s) == -1)
247 readerr(ifP, iffid);
248
249 return s;
250 }
251
252
253
254 /****************************************************************************
255 Chunk reader
256 ****************************************************************************/
257
258 static void
259 chunk_end(FILE * const ifP,
260 IFF_ID const iffid,
261 unsigned long const chunksize) {
262
263 if (chunksize > 0) {
264 unsigned long remainingChunksize;
265 pm_message("warning - %ld extraneous byte%s in %s chunk",
266 chunksize, (chunksize == 1 ? "" : "s"), ID2string(iffid));
267 remainingChunksize = chunksize; /* initial value */
268 while (remainingChunksize > 0)
269 get_byte(ifP, iffid, &remainingChunksize);
270 }
271 }
272
273
274
275 static void
276 skip_chunk(FILE * const ifP,
277 IFF_ID const iffId,
278 unsigned long const chunkSize) {
279
280 unsigned long remainingChunkSize;
281
282 for (remainingChunkSize = chunkSize; remainingChunkSize > 0; )
283 get_byte(ifP, iffId, &remainingChunkSize);
284 }
285
286
287
288 static void
289 display_chunk(FILE * const ifP,
290 IFF_ID const iffId,
291 unsigned long const chunkSize) {
292
293 int byte;
294 unsigned long remainingChunkSize;
295
296 pm_message("contents of %s chunk:", ID2string(iffId));
297
298 for (remainingChunkSize = chunkSize, byte = '\0';
299 remainingChunkSize > 0; ) {
300
301 byte = get_byte(ifP, iffId, &remainingChunkSize);
302 if (fputc(byte, stderr) == EOF)
303 pm_error("write error");
304 }
305 if (byte != '\n') {
306 int rc;
307 rc = fputc('\n', stderr);
308 if (rc == EOF)
309 pm_error("write error");
310 }
311 }
312
313
314
315 static void
316 read_cmap(FILE * const ifP,
317 IFF_ID const iffId,
318 unsigned long const chunkSize,
319 ColorMap * const cmapP) {
320
321 unsigned long const colorCt = chunkSize / 3;
322
323 if (colorCt == 0) {
324 pm_error("warning - empty %s colormap", ID2string(iffId));
325 skip_chunk(ifP, iffId, chunkSize);
326 } else {
327 unsigned int i;
328 unsigned long remainingChunkSize;
329
330 if (cmapP->color) /* prefer CMAP-chunk over CMYK-chunk */
331 ppm_freerow(cmapP->color);
332 cmapP->color = ppm_allocrow(colorCt);
333 cmapP->ncolors = colorCt;
334
335 for (i = 0, remainingChunkSize = chunkSize; i < colorCt; ++i ) {
336 int const r = get_byte(ifP, iffId, &remainingChunkSize);
337 int const g = get_byte(ifP, iffId, &remainingChunkSize);
338 int const b = get_byte(ifP, iffId, &remainingChunkSize);
339 PPM_ASSIGN(cmapP->color[i], r, g, b);
340 }
341 chunk_end(ifP, iffId, remainingChunkSize);
342 }
343 }
344
345
346
347 static void
348 read_cmyk(FILE * const ifP,
349 IFF_ID const iffId,
350 unsigned long const chunkSize,
351 ColorMap * const cmapP) {
352
353 if (HAS_COLORMAP(cmapP)) { /* prefer RGB color map */
354 skip_chunk(ifP, iffId, chunkSize);
355 } else {
356 unsigned long const colorCt = chunkSize / 4;
357 if (colorCt == 0 ) {
358 pm_error("warning - empty %s colormap", ID2string(iffId));
359 skip_chunk(ifP, iffId, chunkSize);
360 } else {
361 unsigned int i;
362 unsigned long remainingChunkSize;
363
364 cmapP->color = ppm_allocrow(colorCt);
365 cmapP->ncolors = colorCt;
366
367 for (i = 0, remainingChunkSize = chunkSize; i < colorCt; ++i) {
368 int const c = get_byte(ifP, iffId, &remainingChunkSize);
369 int const m = get_byte(ifP, iffId, &remainingChunkSize);
370 int const y = get_byte(ifP, iffId, &remainingChunkSize);
371 int const k = get_byte(ifP, iffId, &remainingChunkSize);
372
373 {
374 pixval const red =
375 MAXCOLVAL - MIN(MAXCOLVAL,
376 c * (MAXCOLVAL-k) / MAXCOLVAL+k);
377 pixval const green =
378 MAXCOLVAL - MIN(MAXCOLVAL,
379 m * (MAXCOLVAL-k) / MAXCOLVAL+k);
380 pixval const blue =
381 MAXCOLVAL - MIN(MAXCOLVAL,
382 y * (MAXCOLVAL-k) / MAXCOLVAL+k);
383
384 PPM_ASSIGN(cmapP->color[i], red, green, blue);
385 }
386 }
387 chunk_end(ifP, iffId, remainingChunkSize);
388 }
389 }
390 }
391
392
393
394 static void
395 read_clut(FILE * const ifP,
396 IFF_ID const iffId,
397 unsigned long const chunkSize,
398 ColorMap * const cmapP) {
399
400 if (chunkSize != CLUTSize) {
401 pm_message("invalid size for %s chunk - skipping it",
402 ID2string(iffId));
403 skip_chunk(ifP, iffId, chunkSize);
404 } else {
405 long type;
406 unsigned char * lut;
407 unsigned long remainingChunkSize;
408 unsigned int i;
409
410 remainingChunkSize = chunkSize; /* initial value */
411
412 type = get_big_long(ifP, iffId, &remainingChunkSize);
413 get_big_long(ifP, iffId, &remainingChunkSize); /* skip reserved fld */
414
415 MALLOCARRAY_NOFAIL(lut, 256);
416 for( i = 0; i < 256; ++i )
417 lut[i] = get_byte(ifP, iffId, &remainingChunkSize);
418
419 switch( type ) {
420 case CLUT_MONO:
421 cmapP->monolut = lut;
422 break;
423 case CLUT_RED:
424 cmapP->redlut = lut;
425 break;
426 case CLUT_GREEN:
427 cmapP->greenlut = lut;
428 break;
429 case CLUT_BLUE:
430 cmapP->bluelut = lut;
431 break;
432 default:
433 pm_message("warning - %s type %ld not recognized",
434 ID2string(iffId), type);
435 free(lut);
436 }
437 }
438 }
439
440
441
442 static void
443 warnNonsquarePixels(uint8_t const xAspect,
444 uint8_t const yAspect) {
445
446 if (xAspect != yAspect) {
447 const char * const baseMsg = "warning - non-square pixels";
448
449 if (pm_have_float_format())
450 pm_message("%s; to fix do a 'pamscale -%cscale %g'",
451 baseMsg,
452 xAspect > yAspect ? 'x' : 'y',
453 xAspect > yAspect ?
454 (float)xAspect/yAspect :
455 (float)yAspect/xAspect);
456 else
457 pm_message("%s", baseMsg);
458 }
459 }
460
461
462
463 static BitMapHeader *
464 read_bmhd(FILE * const ifP,
465 IFF_ID const iffid,
466 unsigned long const chunksize) {
467
468 BitMapHeader * bmhdP;
469
470 if (chunksize != BitMapHeaderSize) {
471 pm_message("invalid size for %s chunk - skipping it",
472 ID2string(iffid));
473 skip_chunk(ifP, iffid, chunksize);
474 bmhdP = NULL;
475 } else {
476 unsigned long remainingChunksize;
477
478 MALLOCVAR_NOFAIL(bmhdP);
479
480 remainingChunksize = chunksize; /* initial value */
481
482 bmhdP->w = get_big_short(ifP, iffid, &remainingChunksize);
483 bmhdP->h = get_big_short(ifP, iffid, &remainingChunksize);
484 bmhdP->x = get_big_short(ifP, iffid, &remainingChunksize);
485 bmhdP->y = get_big_short(ifP, iffid, &remainingChunksize);
486 bmhdP->nPlanes = get_byte(ifP, iffid, &remainingChunksize);
487 bmhdP->masking = get_byte(ifP, iffid, &remainingChunksize);
488 bmhdP->compression = get_byte(ifP, iffid, &remainingChunksize);
489 bmhdP->flags = get_byte(ifP, iffid, &remainingChunksize);
490 bmhdP->transparentColor =
491 get_big_short(ifP, iffid, &remainingChunksize);
492 bmhdP->xAspect = get_byte(ifP, iffid, &remainingChunksize);
493 bmhdP->yAspect = get_byte(ifP, iffid, &remainingChunksize);
494 bmhdP->pageWidth = get_big_short(ifP, iffid, &remainingChunksize);
495 bmhdP->pageHeight = get_big_short(ifP, iffid, &remainingChunksize);
496
497 if (verbose) {
498 if (typeid == ID_ILBM)
499 pm_message("dimensions: %dx%d, %d planes",
500 bmhdP->w, bmhdP->h, bmhdP->nPlanes);
501 else
502 pm_message("dimensions: %dx%d", bmhdP->w, bmhdP->h);
503
504 if (typeid == ID_ILBM || typeid == ID_PBM) {
505 pm_message("compression: %s",
506 bmhdP->compression <= cmpMAXKNOWN ?
507 cmpNAME[bmhdP->compression] : "unknown");
508
509 switch(bmhdP->masking) {
510 case mskNone:
511 break;
512 case mskHasMask:
513 case mskHasTransparentColor:
514 if (!maskfile)
515 pm_message("use '-maskfile <filename>' "
516 "to generate a PBM mask file from %s",
517 mskNAME[bmhdP->masking]);
518 break;
519 case mskLasso:
520 pm_message("warning - masking type '%s' not recognized",
521 mskNAME[bmhdP->masking]);
522 break;
523 default:
524 pm_error("unknown masking type %d", bmhdP->masking);
525 }
526 }
527 else /* RGBN/RGB8 */
528 if (!maskfile)
529 pm_message("use '-maskfile <filename>' "
530 "to generate a PBM mask file "
531 "from genlock bits");
532 }
533
534 /* fix aspect ratio */
535 if (bmhdP->xAspect == 0 || bmhdP->yAspect == 0) {
536 pm_message("warning - illegal aspect ratio %d:%d, using 1:1",
537 bmhdP->xAspect, bmhdP->yAspect);
538 bmhdP->xAspect = bmhdP->yAspect = 1;
539 }
540
541 warnNonsquarePixels(bmhdP->xAspect, bmhdP->yAspect);
542 }
543 return bmhdP;
544 }
545
546
547
548 /****************************************************************************
549 ILBM functions
550 ****************************************************************************/
551
552
553 static void
554 read_ilbm_plane(FILE * const ifP,
555 unsigned long * const remainingChunksizeP,
556 int const bytes,
557 int const compression) {
558
559 unsigned char *ubp;
560 int j, byte;
561 int bytesRemaining;
562
563 bytesRemaining = bytes; /* initial value */
564
565 switch(compression) {
566 case cmpNone:
567 read_bytes(ifP, bytesRemaining, ilbmrow,
568 ID_BODY, remainingChunksizeP);
569 break;
570 case cmpByteRun1:
571 ubp = ilbmrow;
572 do {
573 byte = (int)get_byte(ifP, ID_BODY, remainingChunksizeP);
574 if( byte <= 127 ) {
575 j = byte;
576 bytesRemaining -= (j+1);
577 if( bytesRemaining < 0 )
578 pm_error("error doing ByteRun1 decompression");
579 for( ; j >= 0; j-- )
580 *ubp++ = get_byte(ifP, ID_BODY, remainingChunksizeP);
581 }
582 else
583 if ( byte != 128 ) {
584 j = 256 - byte;
585 bytesRemaining -= (j+1);
586 if( bytesRemaining < 0 )
587 pm_error("error doing ByteRun1 decompression");
588 byte = (int)get_byte(ifP, ID_BODY, remainingChunksizeP);
589 for( ; j >= 0; j-- )
590 *ubp++ = (unsigned char)byte;
591 }
592 /* 128 is a NOP */
593 }
594 while( bytesRemaining > 0 );
595 break;
596 default:
597 pm_error("unknown compression type %d", compression);
598 }
599 }
600
601
602
603 static const unsigned char bit_mask[] = {1, 2, 4, 8, 16, 32, 64, 128};
604
605 static void
606 decodeRow(FILE * const ifP,
607 unsigned long * const remainingChunksizeP,
608 rawtype * const chunkyrow,
609 int const nPlanes,
610 BitMapHeader * const bmhdP) {
611
612 int plane;
613 int col;
614 int cols;
615 int bytes;
616 unsigned char * ilP;
617 rawtype * chP;
618
619 cols = bmhdP->w;
•620 overflow_add(cols, 15);
621 bytes = ilbm_rowByteCt(cols);
622
623 for (plane = 0; plane < nPlanes; ++plane) {
624 int mask;
625 int cbit;
626
627 mask = 1 << plane;
628 read_ilbm_plane(ifP, remainingChunksizeP, bytes, bmhdP->compression);
629
630 ilP = ilbmrow;
631 chP = chunkyrow;
632
633 for (col = 0, cbit = 7; col < cols; col++, cbit--, chP++ ) {
634 if (cbit < 0) {
635 cbit = 7;
636 ++ilP;
637 }
638 if (*ilP & bit_mask[cbit])
639 *chP |= mask;
640 else
641 *chP &= ~mask;
642 }
643 }
644 }
645
646
647
648 static void
649 decodeMask(FILE * const ifP,
650 unsigned long * const remainingChunksizeP,
651 rawtype * const chunkyrow,
652 BitMapHeader * const bmhdP) {
653
654 int cols;
655 unsigned char * ilP;
656
657 cols = bmhdP->w;
658 switch (bmhdP->masking) {
659 case mskNone:
660 break;
661 case mskHasMask: /* mask plane */
662 read_ilbm_plane(ifP, remainingChunksizeP, ilbm_rowByteCt(cols),
663 bmhdP->compression);
664 if (maskfile) {
665 int col;
666 int cbit;
667
668 ilP = ilbmrow;
669 for (col = 0, cbit = 7; col < cols; ++col, --cbit) {
670 if (cbit < 0) {
671 cbit = 7;
672 ++ilP;
673 }
674 if (*ilP & bit_mask[cbit])
675 maskrow[col] = PBM_BLACK;
676 else
677 maskrow[col] = PBM_WHITE;
678 }
679 pbm_writepbmrow(maskfile, maskrow, cols, 0);
680 wrotemask = true;
681 }
682 break;
683 case mskHasTransparentColor:
684 if (!chunkyrow)
685 pm_error("decodeMask(): chunkyrow == NULL - can't happen");
686
687 if (maskfile) {
688 unsigned int col;
689
690 for (col = 0; col < cols; ++col) {
691 if (chunkyrow[col] == bmhdP->transparentColor)
692 maskrow[col] = PBM_WHITE;
693 else
694 maskrow[col] = PBM_BLACK;
695 }
696 pbm_writepbmrow(maskfile, maskrow, cols, 0);
697 wrotemask = true;
698 }
699 break;
700 case mskLasso:
701 pm_error("This program does not know how to process Lasso masking");
702 break;
703 default:
704 pm_error("decodeMask(): unknown masking type %d - can't happen",
705 bmhdP->masking);
706 }
707 }
708
709
710
711 /****************************************************************************
712 Multipalette handling
713 ****************************************************************************/
714
•715 static void *
716 xmalloc2(x, y)
717 int x;
718 int y;
719 {
720 void *mem;
721
722 overflow2(x,y);
723 if( x * y == 0 )
724 return NULL;
725
726 mem = malloc2(x,y);
727 if( mem == NULL )
728 pm_error("out of memory allocating %d bytes", x * y);
729 return mem;
730 }
731
732
733 static void
734 multi_adjust(ColorMap * const cmapP,
735 unsigned int const row,
736 const PaletteChange * const palchange) {
737
738 unsigned int i;
739
740 for (i = 0; palchange[i].reg != MP_REG_END; ++i) {
741 int const reg = palchange[i].reg;
742 if (reg >= cmapP->ncolors) {
743 pm_message("warning - palette change register out of range");
744 pm_message(" row %u change structure %d reg=%d (max %d)",
745 row, i, reg, cmapP->ncolors-1);
746 pm_message(" ignoring it... "
747 "colors might get messed up from here");
748 } else {
749 if (reg != MP_REG_IGNORE) {
750 PPM_ASSIGN(cmapP->color[reg],
751 palchange[i].r, palchange[i].g, palchange[i].b);
752 }
753 }
754 }
755 }
756
757
758
759 static void
760 multi_init(ColorMap * const cmapP,
761 long const viewportmodes) {
762
763 if (cmapP->mp_init)
764 multi_adjust(cmapP, -1, cmapP->mp_init);
765 if (!(viewportmodes & vmLACE) )
766 cmapP->mp_flags &= ~(MP_FLAGS_SKIPLACED);
767 }
768
769
770
771 static void
772 multi_update(ColorMap * const cmapP,
773 unsigned int const row) {
774
775 if (cmapP->mp_flags & MP_FLAGS_SKIPLACED) {
776 if (ODD(row))
777 return;
778 if (row/2 < cmapP->mp_rows && cmapP->mp_change[row/2])
779 multi_adjust(cmapP, row, cmapP->mp_change[row/2]);
780 } else {
781 if (row < cmapP->mp_rows && cmapP->mp_change[row])
782 multi_adjust(cmapP, row, cmapP->mp_change[row]);
783 }
784 }
785
786
787
788 static void
789 multi_free(ColorMap * const cmapP) {
790
791 if (cmapP->mp_init) {
792 free(cmapP->mp_init);
793 cmapP->mp_init = NULL;
794 }
795
796 if (cmapP->mp_change) {
797 unsigned int i;
798
799 for (i = 0; i < cmapP->mp_rows; ++i) {
800 if (cmapP->mp_change[i])
801 free(cmapP->mp_change[i]);
802 }
803 free(cmapP->mp_change);
804 cmapP->mp_change = NULL;
805 }
806
807 cmapP->mp_rows = 0;
808 cmapP->mp_type = 0;
809 cmapP->mp_flags = 0;
810 }
811
812
813
814 /****************************************************************************
815 Colormap handling
816 ****************************************************************************/
817
818
819
820 static void
821 analyzeCmapSamples(const ColorMap * const cmapP,
822 pixval * const maxSampleP,
823 bool * const shiftedP) {
824
825 pixval maxSample;
826 bool shifted;
827 unsigned int i;
828
829 for (i = 0, maxSample = 0, shifted = true; i < cmapP->ncolors; ++i) {
830 pixval const r = PPM_GETR(cmapP->color[i]);
831 pixval const g = PPM_GETG(cmapP->color[i]);
832 pixval const b = PPM_GETB(cmapP->color[i]);
833
834 maxSample = MAX(maxSample, MAX(r, MAX(g, b)));
835
836 if (r & 0x0f || g & 0x0f || b & 0x0f)
837 shifted = false;
838 }
839 *shiftedP = shifted;
840 *maxSampleP = maxSample;
841 }
842
843
844
845 static void
846 transformCmap(ColorMap * const cmapP) {
847
848 pixval maxSample;
849 /* The maximum sample value in *cmapP input */
850 bool shifted;
851 /* Samples in the *cmapP input appear to be 4 bit (maxval 15) original
852 values shifted left 4 places to make 8 bit (maxval 255) samples.
853 */
854
855 analyzeCmapSamples(cmapP, &maxSample, &shifted);
856
857 if (maxSample == 0)
858 pm_message("warning - black colormap");
859 else if (shifted || maxSample <= 15) {
860 if (!adjustcolors) {
861 pm_message("warning - probably %s4-bit colormap",
862 shifted ? "shifted " : "");
863 pm_message("Use '-adjustcolors' to scale colormap to 8 bits");
864 } else {
865 unsigned int i;
866 pm_message("scaling colormap to 8 bits");
867 for (i = 0; i < cmapP->ncolors; ++i) {
868 pixval r, g, b;
869 r = PPM_GETR(cmapP->color[i]);
870 g = PPM_GETG(cmapP->color[i]);
871 b = PPM_GETB(cmapP->color[i]);
872 if (shifted) {
873 r >>= 4;
874 g >>= 4;
875 b >>= 4;
876 }
877 r *= FACTOR_4BIT;
878 g *= FACTOR_4BIT;
879 b *= FACTOR_4BIT;
880 PPM_ASSIGN(cmapP->color[i], r, g, b);
881 }
882 }
883 }
884 }
885
886
887
888 static pixel *
889 transpColor(const BitMapHeader * const bmhdP,
890 ColorMap * const cmapP,
891 const char * const transpName,
892 pixval const maxval) {
893
894 pixel * transpColorP;
895
896 if (bmhdP) {
897 if (bmhdP->masking == mskHasTransparentColor ||
898 bmhdP->masking == mskLasso) {
899 MALLOCVAR_NOFAIL(transpColorP);
900
901 if (transpName)
902 *transpColorP = ppm_parsecolor(transpName, maxval);
903 else {
904 unsigned short const transpIdx = bmhdP->transparentColor;
905 if (HAS_COLORMAP(cmapP)) {
906 if (transpIdx >= cmapP->ncolors) {
907 pm_message("using default transparent color (black)");
908 PPM_ASSIGN(*transpColorP, 0, 0, 0);
909 } else
910 *transpColorP = cmapP->color[transpIdx];
911 } else {
912 /* The color index is just a direct gray level */
913 PPM_ASSIGN(*transpColorP, transpIdx, transpIdx, transpIdx);
914 }
915 }
916 } else
917 transpColorP = NULL;
918 } else
919 transpColorP = NULL;
920
921 return transpColorP;
922 }
923
924
925
926 static void
927 prepareCmap(const BitMapHeader * const bmhdP,
928 ColorMap * const cmapP) {
929 /*----------------------------------------------------------------------------
930 This is a really ugly subroutine that 1) analyzes a colormap and its
931 context (returning the analysis in global variables); and 2) modifies that
932 color map, because it's really one type of data structure as input and
933 another as output.
934 -----------------------------------------------------------------------------*/
935 bool bmhdCmapOk;
936
937 if (bmhdP)
938 bmhdCmapOk = (bmhdP->flags & BMHD_FLAGS_CMAPOK);
939 else
940 bmhdCmapOk = false;
941
942 if (HAS_COLORMAP(cmapP) && !bmhdCmapOk)
943 transformCmap(cmapP);
944 }
945
946
947
948 static pixval
949 lookup_red(ColorMap * const cmapP,
950 unsigned int const oldval) {
951
952 if (cmapP && cmapP->redlut && oldval < 256)
953 return cmapP->redlut[oldval];
954 else
955 return oldval;
956 }
957
958
959
960 static pixval
961 lookup_green(ColorMap * const cmapP,
962 unsigned int const oldval) {
963
964 if (cmapP && cmapP->greenlut && oldval < 256)
965 return cmapP->greenlut[oldval];
966 else
967 return oldval;
968 }
969
970
971
972 static pixval
973 lookup_blue(ColorMap * const cmapP,
974 unsigned int const oldval) {
975
976 if (cmapP && cmapP->bluelut && oldval < 256)
977 return cmapP->bluelut[oldval];
978 else
979 return oldval;
980 }
981
982
983
984 static pixval
985 lookup_mono(ColorMap * const cmapP,
986 unsigned int const oldval) {
987
988 if (cmapP && cmapP->monolut && oldval < 256)
989 return cmapP->monolut[oldval];
990 else
991 return oldval;
992 }
993
994
995
996 static ColorMap *
997 ehbcmap(ColorMap * const cmapP) {
998
999 pixel * tempcolor;
1000 unsigned int i;
1001
1002 tempcolor = ppm_allocrow(cmapP->ncolors * 2);
1003
1004 for (i = 0; i < cmapP->ncolors; ++i) {
1005 tempcolor[i] = cmapP->color[i];
1006 PPM_ASSIGN(tempcolor[cmapP->ncolors + i],
1007 PPM_GETR(cmapP->color[i]) / 2,
1008 PPM_GETG(cmapP->color[i]) / 2,
1009 PPM_GETB(cmapP->color[i]) / 2);
1010 }
1011 ppm_freerow(cmapP->color);
1012 cmapP->color = tempcolor;
1013 cmapP->ncolors *= 2;
1014
1015 return cmapP;
1016 }
1017
1018
1019
1020 static pixval
1021 lut_maxval(ColorMap * const cmap,
1022 pixval const maxval) {
1023
1024 pixval retval;
1025
1026 if (maxval >= 255)
1027 retval = maxval;
1028 else {
1029 if (!HAS_COLORLUT(cmap))
1030 retval = maxval;
1031 else {
1032 unsigned int i;
1033 unsigned char maxlut;
1034 maxlut = maxval;
1035 for( i = 0; i < maxval; i++ ) {
1036 if( cmap->redlut && cmap->redlut[i] > maxlut )
1037 maxlut = cmap->redlut[i];
1038 if( cmap->greenlut && cmap->greenlut[i] > maxlut )
1039 maxlut = cmap->greenlut[i];
1040 if( cmap->bluelut && cmap->bluelut[i] > maxlut )
1041 maxlut = cmap->bluelut[i];
1042 }
1043 pm_message("warning - "
1044 "%d-bit index into 8-bit color lookup table, "
1045 "table maxval=%d",
1046 pm_maxvaltobits(maxval), maxlut);
1047 if( maxlut != maxval )
1048 retval = 255;
1049 else
1050 retval = maxval;
1051 pm_message(" assuming image maxval=%d", retval);
1052 }
1053 }
1054 return retval;
1055 }
1056
1057
1058
1059 static void
1060 get_color(ColorMap * const cmapP,
1061 unsigned int const idx,
1062 pixval * const redP,
1063 pixval * const greenP,
1064 pixval * const blueP) {
1065
1066 if (HAS_COLORMAP(cmapP)) {
1067 if (idx >= cmapP->ncolors)
1068 pm_error("color index out of range: %u (max %u)",
1069 idx, cmapP->ncolors);
1070 else {
1071 pixval const r = PPM_GETR(cmapP->color[idx]);
1072 pixval const g = PPM_GETG(cmapP->color[idx]);
1073 pixval const b = PPM_GETB(cmapP->color[idx]);
1074
1075 *redP = lookup_red (cmapP, r);
1076 *greenP = lookup_green (cmapP, g);
1077 *blueP = lookup_blue (cmapP, b);
1078 }
1079 } else
1080 *redP = *greenP = *blueP = lookup_mono(cmapP, idx);
1081 }
1082
1083
1084
1085 /****************************************************************************
1086 Conversion functions
1087 ****************************************************************************/
1088
1089 static void
1090 std_to_ppm(FILE * const ifP,
1091 long const chunksize,
1092 BitMapHeader * const bmhdP,
1093 ColorMap * const cmap,
1094 long const viewportmodes);
1095
1096
1097
1098 static void
1099 ham_to_ppm(FILE * const ifP,
1100 long const chunksize,
1101 BitMapHeader * const bmhdP,
1102 ColorMap * const cmap,
1103 long const viewportmodes) {
1104
1105 int cols, rows, hambits, hammask, hamshift, hammask2, col, row;
1106 pixval maxval;
1107 rawtype *rawrow;
1108 unsigned char hamlut[256];
1109
1110 cols = bmhdP->w;
1111 rows = bmhdP->h;
1112 hambits = bmhdP->nPlanes - 2;
1113 hammask = (1 << hambits) - 1;
1114 hamshift = 8 - hambits;
1115 hammask2 = (1 << hamshift) - 1;
1116
1117 if( hambits > 8 || hambits < 1 ) {
1118 int const assumed_viewportmodes = viewportmodes & ~(vmHAM);
1119
1120 pm_message("%d-plane HAM?? - interpreting image as a normal ILBM",
1121 bmhdP->nPlanes);
1122 std_to_ppm(ifP, chunksize, bmhdP, cmap, assumed_viewportmodes);
1123 return;
1124 } else {
1125 unsigned long remainingChunksize;
1126 pixel * transpColorP;
1127
1128 pm_message("input is a %sHAM%d file",
1129 HAS_MULTIPALETTE(cmap) ? "multipalette " : "",
1130 bmhdP->nPlanes);
1131
1132 if( HAS_COLORLUT(cmap) || HAS_MONOLUT(cmap) ) {
1133 pm_message("warning - color lookup tables ignored in HAM");
1134 if( cmap->redlut ) free(cmap->redlut);
1135 if( cmap->greenlut ) free(cmap->greenlut);
1136 if( cmap->bluelut ) free(cmap->bluelut);
1137 if( cmap->monolut ) free(cmap->monolut);
1138 cmap->redlut = cmap->greenlut = cmap->bluelut =
1139 cmap->monolut = NULL;
1140 }
1141 if( !HAS_COLORMAP(cmap) ) {
1142 pm_message("no colormap - interpreting values as grayscale");
1143 maxval = pm_bitstomaxval(hambits);
1144 for( col = 0; col <= maxval; col++ )
1145 hamlut[col] = col * MAXCOLVAL / maxval;
1146 cmap->monolut = hamlut;
1147 }
1148
1149 transpColorP = transpColor(bmhdP, cmap, transpName, MAXCOLVAL);
1150
1151 if( HAS_MULTIPALETTE(cmap) )
1152 multi_init(cmap, viewportmodes);
1153
1154 rawrow = alloc_rawrow(cols);
1155
1156 ppm_writeppminit(stdout, cols, rows, MAXCOLVAL, 0);
1157
1158 remainingChunksize = chunksize; /* initial value */
1159
1160 for (row = 0; row < rows; ++row) {
1161 pixval r, g, b;
1162
1163 if( HAS_MULTIPALETTE(cmap) )
1164 multi_update(cmap, row);
1165
1166 decodeRow(ifP, &remainingChunksize, rawrow, bmhdP->nPlanes, bmhdP);
1167 decodeMask(ifP, &remainingChunksize, rawrow, bmhdP);
1168
1169 r = g = b = 0;
1170 for( col = 0; col < cols; col++ ) {
1171 int idx = rawrow[col] & hammask;
1172
1173 if( transpColorP && maskrow && maskrow[col] == PBM_WHITE )
1174 pixelrow[col] = *transpColorP;
1175 else {
1176 switch((rawrow[col] >> hambits) & 0x03) {
1177 case HAMCODE_CMAP:
1178 get_color(cmap, idx, &r, &g, &b);
1179 break;
1180 case HAMCODE_BLUE:
1181 b = ((b & hammask2) | (idx << hamshift));
1182 /*b = hamlut[idx];*/
1183 break;
1184 case HAMCODE_RED:
1185 r = ((r & hammask2) | (idx << hamshift));
1186 /*r = hamlut[idx];*/
1187 break;
1188 case HAMCODE_GREEN:
1189 g = ((g & hammask2) | (idx << hamshift));
1190 /*g = hamlut[idx];*/
1191 break;
1192 default:
1193 pm_error("ham_to_ppm(): "
1194 "impossible HAM code - can't happen");
1195 }
1196 PPM_ASSIGN(pixelrow[col], r, g, b);
1197 }
1198 }
1199 ppm_writeppmrow(stdout, pixelrow, cols, MAXCOLVAL, 0);
1200 }
1201 chunk_end(ifP, ID_BODY, remainingChunksize);
1202 }
1203 }
1204
1205
1206
1207 static void
1208 std_to_ppm(FILE * const ifP,
1209 long const chunksize,
1210 BitMapHeader * const bmhdP,
1211 ColorMap * const cmap,
1212 long const viewportmodes) {
1213
1214 if (viewportmodes & vmHAM) {
1215 ham_to_ppm(ifP, chunksize, bmhdP, cmap, viewportmodes);
1216 } else {
1217 unsigned int const cols = bmhdP->w;
1218 unsigned int const rows = bmhdP->h;
1219
1220 rawtype *rawrow;
1221 unsigned int row, col;
1222 pixval maxval;
1223 unsigned long remainingChunksize;
1224 pixel * transpColorP;
1225
1226 pm_message("input is a %d-plane %s%sILBM", bmhdP->nPlanes,
1227 HAS_MULTIPALETTE(cmap) ? "multipalette " : "",
1228 viewportmodes & vmEXTRA_HALFBRITE ? "EHB " : ""
1229 );
1230
1231 if( bmhdP->nPlanes > MAXPLANES )
1232 pm_error("too many planes (max %d)", MAXPLANES);
1233
1234 if( HAS_COLORMAP(cmap) ) {
1235 if( viewportmodes & vmEXTRA_HALFBRITE )
1236 ehbcmap(cmap); /* Modifies *cmap */
1237 maxval = MAXCOLVAL;
1238 }
1239 else {
1240 pm_message("no colormap - interpreting values as grayscale");
1241 maxval = lut_maxval(cmap, pm_bitstomaxval(bmhdP->nPlanes));
1242 if( maxval > PPM_OVERALLMAXVAL )
1243 pm_error("nPlanes is too large");
1244 }
1245
1246 transpColorP = transpColor(bmhdP, cmap, transpName, maxval);
1247
1248 rawrow = alloc_rawrow(cols);
1249
1250 if( HAS_MULTIPALETTE(cmap) )
1251 multi_init(cmap, viewportmodes);
1252
1253 ppm_writeppminit( stdout, cols, rows, maxval, 0 );
1254
1255 remainingChunksize = chunksize; /* initial value */
1256
1257 for (row = 0; row < rows; ++row) {
1258
1259 if( HAS_MULTIPALETTE(cmap) )
1260 multi_update(cmap, row);
1261
1262 decodeRow(ifP, &remainingChunksize, rawrow, bmhdP->nPlanes, bmhdP);
1263 decodeMask(ifP, &remainingChunksize, rawrow, bmhdP);
1264
1265 for( col = 0; col < cols; col++ ) {
1266 pixval r, g, b;
1267 if( transpColorP && maskrow && maskrow[col] == PBM_WHITE )
1268 pixelrow[col] = *transpColorP;
1269 else {
1270 get_color(cmap, rawrow[col], &r, &g, &b);
1271 PPM_ASSIGN(pixelrow[col], r, g, b);
1272 }
1273 }
1274 ppm_writeppmrow(stdout, pixelrow, cols, maxval, 0);
1275 }
1276 chunk_end(ifP, ID_BODY, remainingChunksize);
1277 }
1278 }
1279
1280
1281
1282 static void
1283 deep_to_ppm(FILE * const ifP,
1284 long const chunksize,
1285 BitMapHeader * const bmhdP,
1286 ColorMap * const cmap) {
1287
1288 unsigned int const cols = bmhdP->w;
1289 unsigned int const rows = bmhdP->h;
1290 unsigned int const planespercolor = bmhdP->nPlanes / 3;
1291
1292 unsigned int row;
1293 rawtype * Rrow;
1294 rawtype * Grow;
1295 rawtype * Brow;
1296 pixval maxval;
1297 unsigned long remainingChunksize;
1298 pixel * transpColorP;
1299
1300 pm_message("input is a deep (%d-bit) ILBM", bmhdP->nPlanes);
1301 if (planespercolor > MAXPLANES)
1302 pm_error("too many planes (max %d)", MAXPLANES * 3);
1303
1304 if (bmhdP->masking == mskHasTransparentColor ||
1305 bmhdP->masking == mskLasso) {
1306 pm_message("masking type '%s' in a deep ILBM?? - ignoring it",
1307 mskNAME[bmhdP->masking]);
1308 bmhdP->masking = mskNone;
1309 }
1310
1311 maxval = lut_maxval(cmap, pm_bitstomaxval(planespercolor));
1312 if (maxval > PPM_OVERALLMAXVAL)
1313 pm_error("nPlanes is too large");
1314
1315 transpColorP = transpColor(bmhdP, cmap, transpName, maxval);
1316
1317 Rrow = alloc_rawrow(cols);
1318 Grow = alloc_rawrow(cols);
1319 Brow = alloc_rawrow(cols);
1320
1321 ppm_writeppminit(stdout, cols, rows, maxval, 0);
1322
1323 remainingChunksize = chunksize; /* initial value */
1324
1325 for (row = 0; row < rows; ++row) {
1326 unsigned int col;
1327
1328 decodeRow(ifP, &remainingChunksize, Rrow, planespercolor, bmhdP);
1329 decodeRow(ifP, &remainingChunksize, Grow, planespercolor, bmhdP);
1330 decodeRow(ifP, &remainingChunksize, Brow, planespercolor, bmhdP);
1331 decodeMask(ifP, &remainingChunksize, NULL, bmhdP);
1332
1333 for (col = 0; col < cols; ++col) {
1334 if (transpColorP && maskrow && maskrow[col] == PBM_WHITE)
1335 pixelrow[col] = *transpColorP;
1336 else
1337 PPM_ASSIGN(pixelrow[col], lookup_red(cmap, Rrow[col]),
1338 lookup_green(cmap, Grow[col]),
1339 lookup_blue(cmap, Brow[col]));
1340 }
1341 ppm_writeppmrow(stdout, pixelrow, cols, maxval, 0);
1342 }
1343 chunk_end(ifP, ID_BODY, remainingChunksize);
1344 }
1345
1346
1347
1348 static void
1349 dcol_to_ppm(FILE * const ifP,
1350 long const chunksize,
1351 BitMapHeader * const bmhdP,
1352 ColorMap * const cmap,
1353 DirectColor * const dcol) {
1354
1355 unsigned int const cols = bmhdP->w;
1356 unsigned int const rows = bmhdP->h;
1357 unsigned int const redplanes = dcol->r;
1358 unsigned int const greenplanes = dcol->g;
1359 unsigned int const blueplanes = dcol->b;
1360
1361 int row;
1362 rawtype * Rrow;
1363 rawtype * Grow;
1364 rawtype * Brow;
1365 pixval maxval, redmaxval, greenmaxval, bluemaxval;
1366 pixval *redtable, *greentable, *bluetable;
1367 unsigned long remainingChunksize;
1368 pixel * transpColorP;
1369
1370 pm_message("input is a %d:%d:%d direct color ILBM",
1371 redplanes, greenplanes, blueplanes);
1372
1373 if (redplanes > MAXPLANES ||
1374 blueplanes > MAXPLANES ||
1375 greenplanes > MAXPLANES)
1376 pm_error("too many planes (max %d per color component)", MAXPLANES);
1377
1378 if (bmhdP->nPlanes != (redplanes + greenplanes + blueplanes))
1379 pm_error("%s/%s plane number mismatch",
1380 ID2string(ID_BMHD), ID2string(ID_DCOL));
1381
1382 if (bmhdP->masking == mskHasTransparentColor ||
1383 bmhdP->masking == mskLasso) {
1384 pm_message("masking type '%s' in a direct color ILBM?? - ignoring it",
1385 mskNAME[bmhdP->masking]);
1386 bmhdP->masking = mskNone;
1387 }
1388
1389 if (HAS_COLORLUT(cmap)) {
1390 pm_error("This program does not know how to process a %s chunk "
1391 "in direct color", ID2string(ID_CLUT));
1392 cmap->redlut = cmap->greenlut = cmap->bluelut = NULL;
1393 }
1394
1395 redmaxval = pm_bitstomaxval(redplanes);
1396 greenmaxval = pm_bitstomaxval(greenplanes);
1397 bluemaxval = pm_bitstomaxval(blueplanes);
1398 maxval = MAX(redmaxval, MAX(greenmaxval, bluemaxval));
1399
1400 if (maxval > PPM_OVERALLMAXVAL)
1401 pm_error("too many planes");
1402
1403 if (redmaxval != maxval || greenmaxval != maxval || bluemaxval != maxval)
1404 pm_message("scaling colors to %u bits", pm_maxvaltobits(maxval));
1405
•1406 overflow_add(redmaxval, 1);
1407 overflow_add(greenmaxval, 1);
1408 overflow_add(bluemaxval, 1);
1409 MALLOCARRAY_NOFAIL(redtable, redmaxval + 1);
1410 MALLOCARRAY_NOFAIL(greentable, greenmaxval + 1);
1411 MALLOCARRAY_NOFAIL(bluetable, bluemaxval + 1);
1412
1413 {
1414 unsigned int i;
1415 for (i = 0; i <= redmaxval; ++i)
1416 redtable[i] = ROUNDDIV(i * maxval, redmaxval);
1417 for (i = 0; i <= greenmaxval; ++i)
1418 greentable[i] = ROUNDDIV(i * maxval, greenmaxval);
1419 for (i = 0; i <= bluemaxval; ++i)
1420 bluetable[i] = ROUNDDIV(i * maxval, bluemaxval);
1421 }
1422 transpColorP = transpColor(bmhdP, cmap, transpName, maxval);
1423
1424 Rrow = alloc_rawrow(cols);
1425 Grow = alloc_rawrow(cols);
1426 Brow = alloc_rawrow(cols);
1427
1428 ppm_writeppminit(stdout, cols, rows, maxval, 0);
1429
1430 remainingChunksize = chunksize; /* initial value */
1431
1432 for (row = 0; row < rows; ++row) {
1433 unsigned int col;
1434
1435 decodeRow(ifP, &remainingChunksize, Rrow, redplanes, bmhdP);
1436 decodeRow(ifP, &remainingChunksize, Grow, greenplanes, bmhdP);
1437 decodeRow(ifP, &remainingChunksize, Brow, blueplanes, bmhdP);
1438 decodeMask(ifP, &remainingChunksize, NULL, bmhdP);
1439
1440 for (col = 0; col < cols; ++col) {
1441 if (transpColorP && maskrow && maskrow[col] == PBM_WHITE)
1442 pixelrow[col] = *transpColorP;
1443 else
1444 PPM_ASSIGN(pixelrow[col], redtable[Rrow[col]],
1445 greentable[Grow[col]],
1446 bluetable[Brow[col]]);
1447 }
1448 ppm_writeppmrow(stdout, pixelrow, cols, maxval, 0);
1449 }
1450 chunk_end(ifP, ID_BODY, remainingChunksize);
1451 }
1452
1453
1454
1455 static void
1456 cmapToPpm(FILE * const ofP,
1457 ColorMap * const cmapP) {
1458
1459 ppm_colorrowtomapfile(ofP, cmapP->color, cmapP->ncolors, MAXCOLVAL);
1460 }
1461
1462
1463
1464 static void
1465 ipbm_to_ppm(FILE * const ifP,
1466 long const chunksize,
1467 BitMapHeader * const bmhdP,
1468 ColorMap * const cmap,
1469 long const viewportmodes) {
1470
1471 unsigned int const cols = bmhdP->w;
1472 unsigned int const rows = bmhdP->h;
1473
1474 int col, row;
1475 pixval maxval;
1476 unsigned long remainingChunksize;
1477 pixel * transpColorP;
1478
1479 pm_message("input is a %sPBM ",
1480 HAS_MULTIPALETTE(cmap) ? "multipalette " : "");
1481
1482 if( bmhdP->nPlanes != 8 )
1483 pm_error("invalid number of planes for IFF-PBM: %d (must be 8)",
1484 bmhdP->nPlanes);
1485
1486 if( bmhdP->masking == mskHasMask )
1487 pm_error("Image has a maskplane, which is invalid in IFF-PBM");
1488
1489 if( HAS_COLORMAP(cmap) )
1490 maxval = MAXCOLVAL;
1491 else {
1492 pm_message("no colormap - interpreting values as grayscale");
1493 maxval = lut_maxval(cmap, pm_bitstomaxval(bmhdP->nPlanes));
1494 }
1495
1496 transpColorP = transpColor(bmhdP, cmap, transpName, maxval);
1497
1498 if( HAS_MULTIPALETTE(cmap) )
1499 multi_init(cmap, viewportmodes);
1500
1501 MALLOCARRAY_NOFAIL(ilbmrow, cols);
1502
1503 ppm_writeppminit(stdout, cols, rows, maxval, 0);
1504
1505 remainingChunksize = chunksize; /* initial value */
1506
1507 for( row = 0; row < rows; row++ ) {
1508 if( HAS_MULTIPALETTE(cmap) )
1509 multi_update(cmap, row);
1510
1511 read_ilbm_plane(ifP, &remainingChunksize, cols, bmhdP->compression);
1512
1513 for( col = 0; col < cols; col++ ) {
1514 pixval r, g, b;
1515 if( transpColorP && maskrow && maskrow[col] == PBM_WHITE )
1516 pixelrow[col] = *transpColorP;
1517 else {
1518 get_color(cmap, ilbmrow[col], &r, &g, &b);
1519 PPM_ASSIGN(pixelrow[col], r, g, b);
1520 }
1521 }
1522 ppm_writeppmrow(stdout, pixelrow, cols, maxval, 0);
1523 }
1524 chunk_end(ifP, ID_BODY, remainingChunksize);
1525 }
1526
1527
1528
1529 static void
1530 rgbn_to_ppm(FILE * const ifP,
1531 long const chunksize,
1532 BitMapHeader * const bmhdP,
1533 ColorMap * const cmap /* for CLUTs */
1534 ) {
1535
1536 unsigned int const rows = bmhdP->h;
1537 unsigned int const cols = bmhdP->w;
1538
1539 unsigned int row;
1540 unsigned int count;
1541 pixval maxval;
1542 unsigned long remainingChunksize;
1543 pixel * transpColorP;
1544
1545 pm_message("input is a %d-bit RGB image", (typeid == ID_RGB8 ? 8 : 4));
1546
1547 if (bmhdP->compression != 4)
1548 pm_error("invalid compression mode for %s: %d (must be 4)",
1549 ID2string(typeid), bmhdP->compression);
1550
1551 switch (typeid) {
1552 case ID_RGBN:
1553 if (bmhdP->nPlanes != 13)
1554 pm_error("invalid number of planes for %s: %d (must be 13)",
1555 ID2string(typeid), bmhdP->nPlanes);
1556 maxval = lut_maxval(cmap, 15);
1557 break;
1558 case ID_RGB8:
1559 if (bmhdP->nPlanes != 25)
1560 pm_error("invalid number of planes for %s: %d (must be 25)",
1561 ID2string(typeid), bmhdP->nPlanes);
1562 maxval = 255;
1563 break;
1564 default:
1565 pm_error("rgbn_to_ppm(): invalid IFF ID %s - can't happen",
1566 ID2string(typeid));
1567 }
1568
1569 transpColorP = transpColor(bmhdP, cmap, transpName, maxval);
1570
1571 ppm_writeppminit(stdout, cols, rows, maxval, 0);
1572
1573 for (row = 0, count = 0, remainingChunksize = chunksize;
1574 row < rows;
1575 ++row) {
1576
1577 unsigned int col;
1578
1579 for (col = 0; col < cols; ++col) {
1580 unsigned int tries;
1581 unsigned int genlock;
1582 pixval r, g, b;
1583
1584 tries = 0;
1585 while (count == 0) {
1586 if (typeid == ID_RGB8) {
1587 r = lookup_red(cmap, get_byte(ifP, ID_BODY,
1588 &remainingChunksize));
1589 g = lookup_green(cmap, get_byte(ifP, ID_BODY,
1590 &remainingChunksize));
1591 b = lookup_blue(cmap, get_byte(ifP, ID_BODY,
1592 &remainingChunksize));
1593 count = get_byte(ifP, ID_BODY, &remainingChunksize);
1594 genlock = count & 0x80;
1595 count &= 0x7f;
1596 } else {
1597 unsigned int const word =
1598 get_big_short(ifP, ID_BODY, &remainingChunksize);
1599 r = lookup_red(cmap, (word & 0xf000) >> 12);
1600 g = lookup_green(cmap, (word & 0x0f00) >> 8);
1601 b = lookup_blue(cmap, (word & 0x00f0) >> 4);
1602 genlock = word & 0x0008;
1603 count = word & 0x0007;
1604 }
1605 if (!count) {
1606 count = get_byte(ifP, ID_BODY, &remainingChunksize);
1607 if (count == 0)
1608 count =
1609 get_big_short(ifP, ID_BODY, &remainingChunksize);
1610 if (count == 0)
1611 ++tries;
1612 }
1613 }
1614 if (tries > 0) {
1615 pm_message("warning - repeat count 0 at col %u row %u: "
1616 "skipped %u RGB entr%s",
1617 col, row, tries, (tries == 1 ? "y" : "ies"));
1618 }
1619 if (maskfile) {
1620 /* genlock bit set -> transparent */
1621 if (genlock)
1622 maskrow[col] = PBM_WHITE;
1623 else
1624 maskrow[col] = PBM_BLACK;
1625 }
1626 if (transpColorP && maskrow && maskrow[col] == PBM_WHITE)
1627 pixelrow[col] = *transpColorP;
1628 else
1629 PPM_ASSIGN(pixelrow[col], r, g, b);
1630 --count;
1631 }
1632 ppm_writeppmrow(stdout, pixelrow, cols, maxval, 0);
1633 if (maskfile) {
1634 pbm_writepbmrow(maskfile, maskrow, cols, 0);
1635 wrotemask = true;
1636 }
1637 }
1638 chunk_end(ifP, ID_BODY, remainingChunksize);
1639 }
1640
1641
1642
1643 /****************************************************************************
1644 Multipalette chunk reader
1645
1646 Currently there are three multipalette formats:
1647 SHAM - sliced HAM (obsolete)
1648 CTBL - dynamic HAM/Hires (obsolete)
1649 PCHG - palette change
1650 There is no official documentation available for SHAM and CTBL, so
1651 this is mostly guesswork from other sources and hexdumps of pictures...
1652
1653 CTBL format (dynamic HAM/Hires):
1654 16 bigendian words per row (16 bit: 0000rrrrggggbbbb)
1655 This is simply an entire 4-bit colormap per row.
1656 I have no idea what the DYCP chunk is for.
1657
1658 SHAM format (sliced HAM):
1659 1 word - version info (?) - always 0
1660 16 bigendian words per row (16 bit: 0000rrrrggggbbbb)
1661 If the picture is laced, then there are only rows/2 changes, don't change
1662 palette on odd lines.
1663
1664 PCHG format: A detailed description of this format is available
1665 from AmiNet as PCHGLib12.lha.
1666
1667 ****************************************************************************/
1668
1669 /* Turn big-endian 4-byte long and 2-byte short stored at x (unsigned char *)
1670 * into the native format of the CPU
1671 */
1672 #define BIG_LONG(x) ( ((unsigned long)((x)[0]) << 24) + \
1673 ((unsigned long)((x)[1]) << 16) + \
1674 ((unsigned long)((x)[2]) << 8) + \
1675 ((unsigned long)((x)[3]) << 0) )
1676 #define BIG_WORD(x) ( ((unsigned short)((x)[0]) << 8) + \
1677 ((unsigned short)((x)[1]) << 0) )
1678
1679
1680
1681 static void
1682 read_4bit_mp(FILE * const ifP,
1683 IFF_ID const iffid,
1684 long const chunksize,
1685 ColorMap * const cmap) {
1686
1687 int row, rows, i, type;
1688 short data;
1689 unsigned long remainingChunksize;
1690
1691 type = (iffid == ID_SHAM ? MP_TYPE_SHAM : MP_TYPE_CTBL);
1692
1693 if( cmap->mp_type >= type ) {
1694 skip_chunk(ifP, iffid, chunksize);
1695 } else {
1696 if( cmap->mp_type )
1697 multi_free(cmap);
1698 cmap->mp_type = type;
1699
1700 remainingChunksize = chunksize; /* initial value */
1701
1702 if( type == MP_TYPE_SHAM ) {
1703 cmap->mp_flags = MP_FLAGS_SKIPLACED;
1704 get_big_short(ifP, iffid, &remainingChunksize); /* skip first wd */
1705 }
1706
1707 cmap->mp_rows = rows = remainingChunksize/32; /* sizeof(word) * 16 */
1708 MALLOCARRAY_NOFAIL(cmap->mp_change, rows);
1709
1710 for( row = 0; row < rows; row++ ) {
1711 MALLOCARRAY_NOFAIL(cmap->mp_change[row], 17); /* 16 + sentinel */
1712 for( i = 0; i < 16; i++ ) {
1713 data = get_big_short(ifP, iffid, &remainingChunksize);
1714 cmap->mp_change[row][i].reg = i;
1715 cmap->mp_change[row][i].r =
1716 ((data & 0x0f00) >> 8) * FACTOR_4BIT;
1717 cmap->mp_change[row][i].g =
1718 ((data & 0x00f0) >> 4) * FACTOR_4BIT;
1719 cmap->mp_change[row][i].b =
1720 ((data & 0x000f) >> 0) * FACTOR_4BIT;
1721 }
1722 cmap->mp_change[row][16].reg = MP_REG_END; /* sentinel */
1723 }
1724 chunk_end(ifP, iffid, remainingChunksize);
1725 }
1726 }
1727
1728
1729
1730 static void
1731 PCHG_DecompHuff(const unsigned char * const src,
1732 unsigned char * const dst,
1733 short * const tree,
1734 unsigned long const origsize) {
1735
1736 const unsigned char * srcCursor;
1737 unsigned char * dstCursor;
1738 unsigned long i;
1739 unsigned long bits;
1740 unsigned char thisbyte;
1741 short * p;
1742
1743 srcCursor = &src[0]; /* initial value */
1744 dstCursor = &dst[0]; /* initial value */
1745 i = 0; /* initial value */
1746 bits = 0; /* initial value */
1747 p = tree; /* initial value */
1748
1749 while (i < origsize) {
1750 if (bits == 0) {
1751 thisbyte = *srcCursor++;
1752 bits = 8;
1753 }
1754 if (thisbyte & (1 << 7)) {
1755 if (*p >= 0) {
1756 *dstCursor++ = (unsigned char)*p;
1757 ++i;
1758 p = tree;
1759 } else
1760 p += (*p / 2);
1761 } else {
1762 --p;
1763 if (*p > 0 && (*p & 0x100)) {
1764 *dstCursor++ = (unsigned char )*p;
1765 ++i;
1766 p = tree;
1767 }
1768 }
1769 thisbyte <<= 1;
1770 --bits;
1771 }
1772 }
1773
1774
1775
1776 static void
1777 PCHG_Decompress(PCHGHeader * const PCHG,
1778 PCHGCompHeader * const CompHdr,
1779 unsigned char * const compdata,
1780 unsigned long const compsize,
1781 unsigned char * const comptree,
1782 unsigned char * const data) {
1783
1784 switch(PCHG->Compression) {
1785 case PCHG_COMP_HUFFMAN: {
1786 unsigned long const treesize = CompHdr->CompInfoSize;
1787 unsigned long const huffsize = treesize / 2;
1788 const bigend16 * const bigendComptree = (const void *)comptree;
1789
1790 short * hufftree;
1791 unsigned long i;
1792
1793 /* Convert big-endian 2-byte shorts to C shorts */
1794
1795 MALLOCARRAY(hufftree, huffsize);
1796
1797 if (!hufftree)
1798 pm_error("Couldn't get memory for %lu-byte Huffman tree",
1799 huffsize);
1800
1801 for (i = 0; i < huffsize; ++i)
1802 hufftree[i] = pm_uintFromBigend16(bigendComptree[i]);
1803
1804 /* decompress the change structure data */
1805 PCHG_DecompHuff(compdata, data, &hufftree[huffsize-1],
1806 CompHdr->OriginalDataSize);
1807
1808 free(hufftree);
1809 } break;
1810 default:
1811 pm_error("unknown PCHG compression type %d", PCHG->Compression);
1812 }
1813 }
1814
1815
1816
1817 static void
1818 PCHG_ConvertSmall(PCHGHeader * const pchgP,
1819 ColorMap * const cmapP,
1820 unsigned char * const mask,
1821 unsigned long const dataSize) {
1822
1823 unsigned char * dataCursor;
1824 unsigned long remDataSize;
1825 unsigned char thismask;
1826 int bits, row, masklen, reg;
1827 unsigned int totalChangeCt;
1828 unsigned int changedLineCt;
1829 unsigned char * maskCursor;
1830
1831 totalChangeCt = 0; /* initial value */
1832 changedLineCt = pchgP->ChangedLines; /* initial value */
1833 masklen = 4 * MaskLongWords(pchgP->LineCount);
1834 maskCursor = mask;
1835 dataCursor = maskCursor + masklen;
1836 remDataSize = dataSize - masklen;
1837 bits = 0;
1838
1839 for (row = pchgP->StartLine; changedLineCt > 0 && row < 0; ++row) {
1840 if (bits == 0) {
1841 if (masklen == 0) goto fail2;
1842 thismask = *maskCursor++;
1843 --masklen;
1844 bits = 8;
1845 }
1846 if (thismask & (1<<7)) {
1847 if (remDataSize < 2) goto fail;
1848 else {
1849 unsigned int const changeCt16 = *dataCursor++;
1850 unsigned int const changeCt32 = *dataCursor++;
1851 unsigned int const changeCt = changeCt16 + changeCt32;
1852
1853 unsigned int i;
1854
1855 remDataSize -= 2;
1856
1857 for (i = 0; i < changeCt; ++i) {
1858 if (totalChangeCt >= pchgP->TotalChanges) goto fail;
1859 if (remDataSize < 2) goto fail;
1860 else {
1861 unsigned short const smallChange =
1862 BIG_WORD(dataCursor);
1863
1864 dataCursor += 2; remDataSize -= 2;
1865
1866 reg = ((smallChange & 0xf000) >> 12) +
1867 (i >= changeCt ? 16 : 0);
1868 cmapP->mp_init[reg - pchgP->MinReg].reg = reg;
1869 cmapP->mp_init[reg - pchgP->MinReg].r =
1870 ((smallChange & 0x0f00) >> 8) * FACTOR_4BIT;
1871 cmapP->mp_init[reg - pchgP->MinReg].g =
1872 ((smallChange & 0x00f0) >> 4) * FACTOR_4BIT;
1873 cmapP->mp_init[reg - pchgP->MinReg].b =
1874 ((smallChange & 0x000f) >> 0) * FACTOR_4BIT;
1875 ++totalChangeCt;
1876 }
1877 }
1878 --changedLineCt;
1879 }
1880 }
1881 thismask <<= 1;
1882 --bits;
1883 }
1884
1885 for (row = pchgP->StartLine;
1886 changedLineCt > 0 && row < cmapP->mp_rows;
1887 ++row) {
1888 if (bits == 0) {
1889 if (masklen == 0) goto fail2;
1890 thismask = *maskCursor++;
1891 --masklen;
1892 bits = 8;
1893 }
1894 if (thismask & (1<<7)) {
1895 if (remDataSize < 2) goto fail;
1896 else {
1897 unsigned int const changeCt16 = *dataCursor++;
1898 unsigned int const changeCt32 = *dataCursor++;
1899 unsigned int const changeCt = changeCt16 + changeCt32;
1900
1901 unsigned int i;
1902
1903 remDataSize -= 2;
1904
1905 MALLOCARRAY_NOFAIL(cmapP->mp_change[row], changeCt + 1);
1906 for (i = 0; i < changeCt; ++i) {
1907 if (totalChangeCt >= pchgP->TotalChanges) goto fail;
1908 if (remDataSize < 2) goto fail;
1909 else {
1910 unsigned short const smallChange =
1911 BIG_WORD(dataCursor);
1912
1913 dataCursor += 2; remDataSize -= 2;
1914 reg = ((smallChange & 0xf000) >> 12) +
1915 (i >= changeCt16 ? 16 : 0);
1916 cmapP->mp_change[row][i].reg = reg;
1917 cmapP->mp_change[row][i].r =
1918 ((smallChange & 0x0f00) >> 8) * FACTOR_4BIT;
1919 cmapP->mp_change[row][i].g =
1920 ((smallChange & 0x00f0) >> 4) * FACTOR_4BIT;
1921 cmapP->mp_change[row][i].b =
1922 ((smallChange & 0x000f) >> 0) * FACTOR_4BIT;
1923 ++totalChangeCt;
1924 }
1925 }
1926 cmapP->mp_change[row][changeCt].reg = MP_REG_END;
1927 --changedLineCt;
1928 }
1929 }
1930 thismask <<= 1;
1931 --bits;
1932 }
1933 if (totalChangeCt != pchgP->TotalChanges)
1934 pm_message("warning - got %u change structures, "
1935 "chunk header reports %ld",
1936 totalChangeCt, pchgP->TotalChanges);
1937 return;
1938 fail:
1939 pm_error("insufficient data in SmallLineChanges structures");
1940 fail2:
1941 pm_error("insufficient data in line mask");
1942 }
1943
1944
1945
1946 static void
1947 PCHG_ConvertBig(PCHGHeader * const PCHG,
1948 ColorMap * const cmap,
1949 unsigned char * const maskStart,
1950 unsigned long const datasize) {
1951
1952 unsigned char * data;
1953 unsigned char thismask;
1954 int bits;
1955 unsigned int row;
1956 int changes;
1957 int masklen;
1958 int reg;
1959 unsigned long totalchanges;
1960 int changedlines;
1961 unsigned long remDataSize;
1962 unsigned char * mask;
1963
1964 mask = maskStart; /* initial value */
1965 remDataSize = datasize; /* initial value */
1966 changedlines = PCHG->ChangedLines; /* initial value */
1967 totalchanges = 0; /* initial value */
1968
1969 masklen = 4 * MaskLongWords(PCHG->LineCount);
1970 data = mask + masklen; remDataSize -= masklen;
1971
1972 for (row = PCHG->StartLine, bits = 0; changedlines && row < 0; ++row) {
1973 if (bits == 0) {
1974 if (masklen == 0)
1975 pm_error("insufficient data in line mask");
1976 thismask = *mask++;
1977 --masklen;
1978 bits = 8;
1979 }
1980 if (thismask & (1<<7)) {
1981 unsigned int i;
1982
1983 if (remDataSize < 2)
1984 pm_error("insufficient data in BigLineChanges structures");
1985
1986 changes = BIG_WORD(data); data += 2; remDataSize -= 2;
1987
1988 for (i = 0; i < changes; ++i) {
1989 if (totalchanges >= PCHG->TotalChanges)
1990 pm_error("insufficient data in BigLineChanges structures");
1991
1992 if (remDataSize < 6)
1993 pm_error("insufficient data in BigLineChanges structures");
1994
1995 reg = BIG_WORD(data); data += 2;
1996 cmap->mp_init[reg - PCHG->MinReg].reg = reg;
1997 ++data; /* skip alpha */
1998 cmap->mp_init[reg - PCHG->MinReg].r = *data++;
1999 cmap->mp_init[reg - PCHG->MinReg].b = *data++; /* yes, RBG */
2000 cmap->mp_init[reg - PCHG->MinReg].g = *data++;
2001 remDataSize -= 6;
2002 ++totalchanges;
2003 }
2004 --changedlines;
2005 }
2006 thismask <<= 1;
2007 --bits;
2008 }
2009
2010 for (row = PCHG->StartLine; changedlines && row < cmap->mp_rows; ++row) {
2011 if (bits == 0) {
2012 if (masklen == 0)
2013 pm_error("insufficient data in line mask");
2014
2015 thismask = *mask++;
2016 --masklen;
2017 bits = 8;
2018 }
2019 if (thismask & (1<<7)) {
2020 unsigned int i;
2021
2022 if (remDataSize < 2)
2023 pm_error("insufficient data in BigLineChanges structures");
2024
2025 changes = BIG_WORD(data); data += 2; remDataSize -= 2;
2026
2027 MALLOCARRAY_NOFAIL(cmap->mp_change[row], changes + 1);
2028 for (i = 0; i < changes; ++i) {
2029 if (totalchanges >= PCHG->TotalChanges)
2030 pm_error("insufficient data in BigLineChanges structures");
2031
2032 if (remDataSize < 6)
2033 pm_error("insufficient data in BigLineChanges structures");
2034
2035 reg = BIG_WORD(data); data += 2;
2036 cmap->mp_change[row][i].reg = reg;
2037 ++data; /* skip alpha */
2038 cmap->mp_change[row][i].r = *data++;
2039 cmap->mp_change[row][i].b = *data++; /* yes, RBG */
2040 cmap->mp_change[row][i].g = *data++;
2041 remDataSize -= 6;
2042 ++totalchanges;
2043 }
2044 cmap->mp_change[row][changes].reg = MP_REG_END;
2045 --changedlines;
2046 }
2047 thismask <<= 1;
2048 --bits;
2049 }
2050 if (totalchanges != PCHG->TotalChanges)
2051 pm_message("warning - got %ld change structures, "
2052 "chunk header reports %ld",
2053 totalchanges, PCHG->TotalChanges);
2054 }
2055
2056
2057
2058 static void
2059 read_pchg(FILE * const ifP,
2060 IFF_ID const iffid,
2061 long const chunksize,
2062 ColorMap * const cmapP) {
2063
2064 if (cmapP->mp_type >= MP_TYPE_PCHG ) {
2065 skip_chunk(ifP, iffid, chunksize);
2066 } else {
2067 PCHGHeader PCHG;
2068 unsigned char * data;
2069 unsigned long datasize;
2070 unsigned long remainingChunksize;
2071 int i;
2072
2073 if (cmapP->mp_type)
2074 multi_free(cmapP);
2075 cmapP->mp_type = MP_TYPE_PCHG;
2076
2077 remainingChunksize = chunksize; /* initial value */
2078
2079 PCHG.Compression = get_big_short(ifP, iffid, &remainingChunksize);
2080 PCHG.Flags = get_big_short(ifP, iffid, &remainingChunksize);
2081 PCHG.StartLine = get_big_short(ifP, iffid, &remainingChunksize);
2082 PCHG.LineCount = get_big_short(ifP, iffid, &remainingChunksize);
2083 PCHG.ChangedLines= get_big_short(ifP, iffid, &remainingChunksize);
2084 PCHG.MinReg = get_big_short(ifP, iffid, &remainingChunksize);
2085 PCHG.MaxReg = get_big_short(ifP, iffid, &remainingChunksize);
2086 PCHG.MaxChanges = get_big_short(ifP, iffid, &remainingChunksize);
2087 PCHG.TotalChanges= get_big_long (ifP, iffid, &remainingChunksize);
2088
2089 #ifdef DEBUG
2090 pm_message("PCHG StartLine : %d", PCHG.StartLine);
2091 pm_message("PCHG LineCount : %d", PCHG.LineCount);
2092 pm_message("PCHG ChangedLines: %d", PCHG.ChangedLines);
2093 pm_message("PCHG TotalChanges: %d", PCHG.TotalChanges);
2094 #endif
2095
2096 if (PCHG.Compression != PCHG_COMP_NONE) {
2097 PCHGCompHeader CompHdr;
2098 unsigned char * compdata;
2099 unsigned char * comptree;
2100 long treesize, compsize;
2101
2102 CompHdr.CompInfoSize =
2103 get_big_long(ifP, iffid, &remainingChunksize);
2104 CompHdr.OriginalDataSize =
2105 get_big_long(ifP, iffid, &remainingChunksize);
2106
2107 treesize = CompHdr.CompInfoSize;
2108 MALLOCARRAY_NOFAIL(comptree, treesize);
2109 read_bytes(ifP, treesize, comptree, iffid, &remainingChunksize);
2110
2111 compsize = remainingChunksize;
2112 MALLOCARRAY_NOFAIL(compdata, compsize);
2113 read_bytes(ifP, compsize, compdata, iffid, &remainingChunksize);
2114
2115 datasize = CompHdr.OriginalDataSize;
2116 MALLOCARRAY_NOFAIL(data, datasize);
2117 PCHG_Decompress(&PCHG, &CompHdr, compdata,
2118 compsize, comptree, data);
2119
2120 free(comptree);
2121 free(compdata);
2122 } else {
2123 #ifdef DEBUG
2124 pm_message("uncompressed PCHG");
2125 #endif
2126 datasize = remainingChunksize;
2127 MALLOCARRAY_NOFAIL(data, datasize);
2128 read_bytes(ifP, datasize, data, iffid, &remainingChunksize);
2129 }
2130
2131 if (PCHG.Flags & PCHGF_USE_ALPHA)
2132 pm_message("warning - ignoring PCHG alpha channel because "
2133 "this program doesn't know what to do with it");
2134
2135 cmapP->mp_rows = PCHG.StartLine + PCHG.LineCount;
2136 MALLOCARRAY_NOFAIL(cmapP->mp_change, cmapP->mp_rows);
2137 for (i = 0; i < cmapP->mp_rows; ++i)
2138 cmapP->mp_change[i] = NULL;
2139
2140 if (PCHG.StartLine < 0) {
2141 if (PCHG.MaxReg < PCHG.MinReg)
2142 pm_error("PCHG chunk says maxreg (%u) "
2143 "is less than minreg (%u)",
2144 PCHG.MaxReg, PCHG.MinReg);
2145 else {
2146 unsigned int const nch = PCHG.MaxReg - PCHG.MinReg + 1;
2147
2148 unsigned int i;
2149
2150 MALLOCARRAY_NOFAIL(cmapP->mp_init, nch + 1);
2151
2152 for (i = 0; i < nch; ++i)
2153 cmapP->mp_init[i].reg = MP_REG_IGNORE;
2154
2155 cmapP->mp_init[nch].reg = MP_REG_END;
2156 }
2157 }
2158
2159 if (PCHG.Flags & PCHGF_12BIT) {
2160 #ifdef DEBUG
2161 pm_message("SmallLineChanges");
2162 #endif
2163 PCHG_ConvertSmall(&PCHG, cmapP, data, datasize);
2164 }
2165 else {
2166 if (PCHG.Flags & PCHGF_32BIT) {
2167 #ifdef DEBUG
2168 pm_message("BigLineChanges");
2169 #endif
2170 PCHG_ConvertBig(&PCHG, cmapP, data, datasize);
2171 } else
2172 pm_error("unknown palette changes structure "
2173 "format in %s chunk",
2174 ID2string(iffid));
2175 }
2176 free(data);
2177 chunk_end(ifP, iffid, remainingChunksize);
2178 }
2179 }
2180
2181
2182
2183 static bool
2184 ignored_iffid(IFF_ID const iffid,
2185 IFF_ID const ignorelist[],
2186 unsigned int const ignorecount) {
2187
2188 bool ignore;
2189
2190 unsigned int i;
2191 ignore = FALSE; /* initial assumption */
2192 for( i = 0; i < ignorecount && !ignore; i++ ) {
2193 if( iffid == ignorelist[i] )
2194 ignore = TRUE;
2195 }
2196 return ignore;
2197 }
2198
2199
2200
2201 static void
2202 process_body( FILE * const ifP,
2203 long const chunksize,
2204 BitMapHeader * const bmhdP,
2205 ColorMap * const cmap,
2206 FILE * const maskfile,
2207 int const fakeviewport,
2208 int const isdeepopt,
2209 DirectColor * const dcol,
2210 int * const viewportmodesP) {
2211
2212 if (bmhdP == NULL)
2213 pm_error("%s chunk without %s chunk",
2214 ID2string(ID_BODY), ID2string(ID_BMHD));
2215
2216 prepareCmap(bmhdP, cmap);
2217
2218 pixelrow = ppm_allocrow(bmhdP->w);
2219 if (maskfile) {
2220 maskrow = pbm_allocrow(bmhdP->w);
2221 pbm_writepbminit(maskfile, bmhdP->w, bmhdP->h, 0);
2222 }
2223
2224 if (typeid == ID_ILBM) {
2225 int isdeep;
2226
2227 MALLOCARRAY_NOFAIL(ilbmrow, ilbm_rowByteCt(bmhdP->w));
2228 *viewportmodesP |= fakeviewport; /* -isham/-isehb */
2229
2230 if( isdeepopt > 0 && (bmhdP->nPlanes % 3 != 0) ) {
2231 pm_message("cannot interpret %d-plane image as 'deep' "
2232 "(# of planes must be divisible by 3)",
2233 bmhdP->nPlanes);
2234 isdeep = 0;
2235 } else
2236 isdeep = isdeepopt;
2237
2238 if (isdeep > 0)
2239 deep_to_ppm(ifP, chunksize, bmhdP, cmap);
2240 else if (dcol)
2241 dcol_to_ppm(ifP, chunksize, bmhdP, cmap, dcol);
2242 else if (bmhdP->nPlanes > 8) {
2243 if (bmhdP->nPlanes <= 16 && HAS_COLORMAP(cmap))
2244 std_to_ppm(ifP, chunksize, bmhdP, cmap, *viewportmodesP);
2245 else if (isdeep >= 0 && (bmhdP->nPlanes % 3 == 0))
2246 deep_to_ppm(ifP, chunksize, bmhdP, cmap);
2247 else if (bmhdP->nPlanes <= 16)
2248 /* will be interpreted as grayscale */
2249 std_to_ppm(ifP, chunksize, bmhdP, cmap, *viewportmodesP);
2250 else
2251 pm_error("don't know how to interpret %d-plane image",
2252 bmhdP->nPlanes);
2253 } else
2254 std_to_ppm(ifP, chunksize, bmhdP, cmap, *viewportmodesP);
2255 } else if( typeid == ID_PBM )
2256 ipbm_to_ppm(ifP, chunksize, bmhdP, cmap, *viewportmodesP);
2257 else /* RGBN or RGB8 */
2258 rgbn_to_ppm(ifP, chunksize, bmhdP, cmap);
2259 }
2260
2261
2262
2263 static void
2264 processChunk(FILE * const ifP,
2265 long const formsize,
2266 IFF_ID const ignorelist[],
2267 unsigned int const ignorecount,
2268 int const fakeviewport,
2269 int const viewportmask,
2270 int const isdeepopt,
2271 bool const cmaponly,
2272 bool * const bodyChunkProcessedP,
2273 bool * const endchunkP,
2274 BitMapHeader ** const bmhdP,
2275 ColorMap * const cmap,
2276 DirectColor ** const dcolP,
2277 int * const viewportmodesP,
2278 long * const bytesReadP
2279 ) {
2280
2281 IFF_ID iffid;
2282 long chunksize;
2283 long bytesread;
2284
2285 bytesread = 0;
2286
2287 iffid = get_big_long(ifP, ID_FORM, NULL);
2288 chunksize = get_big_long(ifP, iffid, NULL);
2289 bytesread += 8;
2290
2291 if (debug)
2292 pm_message("reading %s chunk: %ld bytes", ID2string(iffid), chunksize);
2293
2294 if (ignored_iffid(iffid, ignorelist, ignorecount)) {
2295 pm_message("ignoring %s chunk", ID2string(iffid));
2296 skip_chunk(ifP, iffid, chunksize);
2297 } else if (iffid == ID_END) {
2298 /* END chunks are not officially valid in IFF, but
2299 suggested as a future expansion for stream-writing,
2300 see Amiga RKM Devices, 3rd Ed, page 376
2301 */
2302 if (chunksize != 0 ) {
2303 pm_message("warning - non-0 %s chunk", ID2string(iffid));
2304 skip_chunk(ifP, iffid, chunksize);
2305 }
2306 if (formsize != 0xffffffff)
2307 pm_message("warning - %s chunk with FORM size 0x%08lx "
2308 "(should be 0x%08x)",
2309 ID2string(iffid), formsize, 0xffffffff);
2310 *endchunkP = 1;
2311 } else if (*bodyChunkProcessedP) {
2312 pm_message("%s chunk found after %s chunk - skipping",
2313 ID2string(iffid), ID2string(ID_BODY));
2314 skip_chunk(ifP, iffid, chunksize);
2315 } else
2316 switch (iffid) {
2317 case ID_BMHD:
2318 *bmhdP = read_bmhd(ifP, iffid, chunksize);
2319 break;
2320 case ID_CMAP:
2321 read_cmap(ifP, iffid, chunksize, cmap);
2322 break;
2323 case ID_CMYK:
2324 read_cmyk(ifP, iffid, chunksize, cmap);
2325 break;
2326 case ID_CLUT:
2327 read_clut(ifP, iffid, chunksize, cmap);
2328 break;
2329 case ID_CAMG:
2330 if (chunksize != CAMGChunkSize)
2331 pm_error("%s chunk size mismatch", ID2string(iffid));
2332 *viewportmodesP = get_big_long(ifP, ID_CAMG, NULL);
2333 *viewportmodesP &= viewportmask; /* -isnotham/-isnotehb */
2334 break;
2335 case ID_PCHG:
2336 read_pchg(ifP, iffid, chunksize, cmap);
2337 break;
2338 case ID_CTBL:
2339 case ID_SHAM:
2340 read_4bit_mp(ifP, iffid, chunksize, cmap);
2341 break;
2342 case ID_DCOL:
2343 if (chunksize != DirectColorSize)
2344 pm_error("%s chunk size mismatch", ID2string(iffid));
2345 MALLOCVAR_NOFAIL(*dcolP);
2346 (*dcolP)->r = get_byte(ifP, iffid, NULL);
2347 (*dcolP)->g = get_byte(ifP, iffid, NULL);
2348 (*dcolP)->b = get_byte(ifP, iffid, NULL);
2349 get_byte(ifP, iffid, NULL); /* skip pad byte */
2350 break;
2351 case ID_BODY:
2352 if (cmaponly || (*bmhdP && (*bmhdP)->nPlanes == 0))
2353 skip_chunk(ifP, ID_BODY, chunksize);
2354 else {
2355 process_body(ifP, chunksize, *bmhdP, cmap,
2356 maskfile, fakeviewport, isdeepopt, *dcolP,
2357 viewportmodesP);
2358
2359 *bodyChunkProcessedP = TRUE;
2360 } break;
2361 case ID_GRAB: case ID_DEST: case ID_SPRT: case ID_CRNG:
2362 case ID_CCRT: case ID_DYCP: case ID_DPPV: case ID_DRNG:
2363 case ID_EPSF: case ID_JUNK: case ID_CNAM: case ID_PRVW:
2364 case ID_TINY: case ID_DPPS:
2365 skip_chunk(ifP, iffid, chunksize);
2366 break;
2367 case ID_copy: case ID_AUTH: case ID_NAME: case ID_ANNO:
2368 case ID_TEXT: case ID_FVER:
2369 if (verbose)
2370 display_chunk(ifP, iffid, chunksize);
2371 else
2372 skip_chunk(ifP, iffid, chunksize);
2373 break;
2374 case ID_DPI: {
2375 int x, y;
2376
2377 x = get_big_short(ifP, ID_DPI, NULL);
2378 y = get_big_short(ifP, ID_DPI, NULL);
2379 if (verbose)
2380 pm_message("%s chunk: dpi_x = %d dpi_y = %d",
2381 ID2string(ID_DPI), x, y);
2382 } break;
2383 default:
2384 pm_message("unknown chunk type %s - skipping",
2385 ID2string(iffid));
2386 skip_chunk(ifP, iffid, chunksize);
2387 break;
2388 }
2389
2390 bytesread += chunksize;
2391
2392 if (ODD(chunksize)) {
2393 get_byte(ifP, iffid, NULL);
2394 bytesread += 1;
2395 }
2396 *bytesReadP = bytesread;
2397 }
2398
2399
2400
2401 static void
2402 maybeWriteColorMap(FILE * const ofP,
2403 const BitMapHeader * const bmhdP,
2404 ColorMap * const cmapP,
2405 bool const bodyChunkProcessed,
2406 bool const cmaponly) {
2407 /*----------------------------------------------------------------------------
2408 Write to file *ofP the color map *cmapP as a PPM, if appropriate.
2409
2410 The logic (not just here -- in the program as a whole) for deciding whether
2411 to write the image or the colormap is quite twisted. If I thought anyone
2412 was actually using this program, I would take the time to straighten it
2413 out.
2414
2415 What's really sick about this subroutine is that in choosing to write
2416 a color map, it has to know that Caller hasn't already written
2417 the image. Huge modularity violation.
2418 -----------------------------------------------------------------------------*/
2419 if (cmaponly) {
2420 if (HAS_COLORMAP(cmapP)) {
2421 prepareCmap(bmhdP, cmapP);
2422 cmapToPpm(ofP, cmapP);
2423 } else
2424 pm_error("You specified -cmaponly, but the ILBM "
2425 "has no colormap");
2426 } else if (bmhdP && bmhdP->nPlanes == 0) {
2427 if (HAS_COLORMAP(cmapP)) {
2428 prepareCmap(bmhdP, cmapP);
2429 cmapToPpm(ofP, cmapP);
2430 } else
2431 pm_error("ILBM has neither a color map nor color planes");
2432 } else if (!bodyChunkProcessed) {
2433 if (HAS_COLORMAP(cmapP)) {
2434 pm_message("input is a colormap file");
2435 prepareCmap(bmhdP, cmapP);
2436 cmapToPpm(ofP, cmapP);
2437 } else
2438 pm_error("ILBM has neither %s or %s chunk",
2439 ID2string(ID_BODY), ID2string(ID_CMAP));
2440 }
2441 }
2442
2443
2444
2445 int
2446 main(int argc, char *argv[]) {
2447
2448 FILE * ifP;
2449 int argn;
2450 short cmaponly = 0, isdeepopt = 0;
2451 bool endchunk;
2452 bool bodyChunkProcessed;
2453 long formsize, bytesread;
2454 int viewportmodes = 0, fakeviewport = 0, viewportmask;
2455 IFF_ID firstIffid;
2456 BitMapHeader *bmhdP = NULL;
2457 ColorMap * cmap;
2458 DirectColor *dcol = NULL;
2459 #define MAX_IGNORE 16
2460 IFF_ID ignorelist[MAX_IGNORE];
2461 int ignorecount = 0;
2462 char *maskname;
2463 const char * const usage =
2464 "[-verbose] [-ignore <chunkID> [-ignore <chunkID>] ...] "
2465 "[-isham|-isehb|-isdeep|-isnotham|-isnotehb|-isnotdeep] "
2466 "[-cmaponly] [-adjustcolors] "
2467 "[-transparent <color>] [-maskfile <filename>] [ilbmfile]";
2468 ppm_init(&argc, argv);
2469
2470 viewportmask = 0xffffffff;
2471
2472 argn = 1;
2473 while( argn < argc && argv[argn][0] == '-' && argv[argn][1] != '\0' ) {
2474 if( pm_keymatch(argv[argn], "-verbose", 2) )
2475 verbose = 1;
2476 else if( pm_keymatch(argv[argn], "-noverbose", 4) )
2477 verbose = 0;
2478 else if( pm_keymatch(argv[argn], "-isham", 4) )
2479 fakeviewport |= vmHAM;
2480 else if( pm_keymatch(argv[argn], "-isehb", 4) )
2481 fakeviewport |= vmEXTRA_HALFBRITE;
2482 else if( pm_keymatch(argv[argn], "-isdeep", 4) )
2483 isdeepopt = 1;
2484 else if( pm_keymatch(argv[argn], "-isnotham", 7) )
2485 viewportmask &= ~(vmHAM);
2486 else if( pm_keymatch(argv[argn], "-isnotehb", 7) )
2487 viewportmask &= ~(vmEXTRA_HALFBRITE);
2488 else if( pm_keymatch(argv[argn], "-isnotdeep", 7) )
2489 isdeepopt = -1;
2490 else if( pm_keymatch(argv[argn], "-cmaponly", 2) )
2491 cmaponly = 1;
2492 else if( pm_keymatch(argv[argn], "-adjustcolors", 2) )
2493 adjustcolors = 1;
2494 else if( pm_keymatch(argv[argn], "-noadjustcolors", 4) )
2495 adjustcolors = 0;
2496 else if( pm_keymatch(argv[argn], "-transparent", 2) ) {
2497 if( ++argn >= argc )
2498 pm_usage(usage);
2499 transpName = argv[argn];
2500 } else if( pm_keymatch(argv[argn], "-maskfile", 2) ) {
2501 if( ++argn >= argc )
2502 pm_usage(usage);
2503 maskname = argv[argn];
2504 maskfile = pm_openw(maskname);
2505 } else if( pm_keymatch(argv[argn], "-ignore", 2) ) {
2506 if( ++argn >= argc )
2507 pm_usage(usage);
2508 if( strlen(argv[argn]) != 4 )
2509 pm_error("'-ignore' option needs a 4 byte chunk ID string "
2510 "as argument");
2511 if( ignorecount >= MAX_IGNORE )
2512 pm_error("max %d chunk IDs to ignore", MAX_IGNORE);
2513 ignorelist[ignorecount++] =
2514 MAKE_ID(argv[argn][0], argv[argn][1], argv[argn][2],
2515 argv[argn][3]);
2516 } else
2517 pm_usage(usage);
2518 ++argn;
2519 }
2520
2521 if( argn < argc ) {
2522 ifP = pm_openr( argv[argn] );
2523 argn++;
2524 } else
2525 ifP = stdin;
2526
2527 if( argn != argc )
2528 pm_usage(usage);
2529
2530 wrotemask = false; /* initial value */
2531
2532 /* Read in the ILBM file. */
2533
2534 firstIffid = get_big_long(ifP, ID_FORM, NULL);
2535 if (firstIffid != ID_FORM)
2536 pm_error("input is not a FORM type IFF file");
2537 formsize = get_big_long(ifP, ID_FORM, NULL);
2538 typeid = get_big_long(ifP, ID_FORM, NULL);
2539 if (typeid != ID_ILBM && typeid != ID_RGBN && typeid != ID_RGB8 &&
2540 typeid != ID_PBM)
2541 pm_error("input is not an ILBM, RGBN, RGB8 or PBM "
2542 "type FORM IFF file");
2543 bytesread = 4; /* FORM and formsize do not count */
2544
2545 cmap = alloc_cmap();
2546
2547 /* Main loop, parsing the IFF FORM. */
2548 bodyChunkProcessed = FALSE;
2549 endchunk = FALSE;
2550 while (!endchunk && formsize-bytesread >= 8) {
2551 long bytesReadForChunk;
2552
2553 processChunk(ifP, formsize, ignorelist, ignorecount,
2554 fakeviewport, viewportmask,
2555 isdeepopt, cmaponly,
2556 &bodyChunkProcessed,
2557 &endchunk, &bmhdP, cmap, &dcol,
2558 &viewportmodes, &bytesReadForChunk);
2559
2560 bytesread += bytesReadForChunk;
2561 }
2562
2563 if (maskfile) {
2564 pm_close(maskfile);
2565 if (!wrotemask)
2566 remove(maskname);
2567 pbm_freerow(maskrow);
2568 }
2569
2570 maybeWriteColorMap(stdout, bmhdP, cmap, bodyChunkProcessed, cmaponly);
2571
2572 {
2573 unsigned int skipped;
2574
2575 for (skipped = 0; fgetc(ifP) != EOF; ++skipped)
2576 ++bytesread;
2577
2578 if (skipped > 0)
2579 pm_message("skipped %u extraneous byte%s after last chunk",
2580 skipped, (skipped == 1 ? "" : "s"));
2581 }
2582 pm_close(ifP);
2583
2584 if (!endchunk && bytesread != formsize) {
2585 pm_message("warning - file length/FORM size field mismatch "
2586 "(%ld != %ld+8)",
2587 bytesread+8 /* FORM+size */, formsize);
2588 }
2589
2590 return 0;
2591 }
2592
2593
2594