Debian Codegraph @

converter/ppm/ilbmtoppm.c

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
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 bytes = ilbm_rowByteCt(cols);
621
622 for (plane = 0; plane < nPlanes; ++plane) {
623 int mask;
624 int cbit;
625
626 mask = 1 << plane;
627 read_ilbm_plane(ifP, remainingChunksizeP, bytes, bmhdP->compression);
628
629 ilP = ilbmrow;
630 chP = chunkyrow;
631
632 for (col = 0, cbit = 7; col < cols; col++, cbit--, chP++ ) {
633 if (cbit < 0) {
634 cbit = 7;
635 ++ilP;
636 }
637 if (*ilP & bit_mask[cbit])
638 *chP |= mask;
639 else
640 *chP &= ~mask;
641 }
642 }
643 }
644
645
646
647 static void
648 decodeMask(FILE * const ifP,
649 unsigned long * const remainingChunksizeP,
650 rawtype * const chunkyrow,
651 BitMapHeader * const bmhdP) {
652
653 int cols;
654 unsigned char * ilP;
655
656 cols = bmhdP->w;
657 switch (bmhdP->masking) {
658 case mskNone:
659 break;
660 case mskHasMask: /* mask plane */
661 read_ilbm_plane(ifP, remainingChunksizeP, ilbm_rowByteCt(cols),
662 bmhdP->compression);
663 if (maskfile) {
664 int col;
665 int cbit;
666
667 ilP = ilbmrow;
668 for (col = 0, cbit = 7; col < cols; ++col, --cbit) {
669 if (cbit < 0) {
670 cbit = 7;
671 ++ilP;
672 }
673 if (*ilP & bit_mask[cbit])
674 maskrow[col] = PBM_BLACK;
675 else
676 maskrow[col] = PBM_WHITE;
677 }
678 pbm_writepbmrow(maskfile, maskrow, cols, 0);
679 wrotemask = true;
680 }
681 break;
682 case mskHasTransparentColor:
683 if (!chunkyrow)
684 pm_error("decodeMask(): chunkyrow == NULL - can't happen");
685
686 if (maskfile) {
687 unsigned int col;
688
689 for (col = 0; col < cols; ++col) {
690 if (chunkyrow[col] == bmhdP->transparentColor)
691 maskrow[col] = PBM_WHITE;
692 else
693 maskrow[col] = PBM_BLACK;
694 }
695 pbm_writepbmrow(maskfile, maskrow, cols, 0);
696 wrotemask = true;
697 }
698 break;
699 case mskLasso:
700 pm_error("This program does not know how to process Lasso masking");
701 break;
702 default:
703 pm_error("decodeMask(): unknown masking type %d - can't happen",
704 bmhdP->masking);
705 }
706 }
707
708
709
710 /****************************************************************************
711 Multipalette handling
712 ****************************************************************************/
713
714
715 static void
716 multi_adjust(ColorMap * const cmapP,
717 unsigned int const row,
718 const PaletteChange * const palchange) {
719
720 unsigned int i;
721
722 for (i = 0; palchange[i].reg != MP_REG_END; ++i) {
723 int const reg = palchange[i].reg;
724 if (reg >= cmapP->ncolors) {
725 pm_message("warning - palette change register out of range");
726 pm_message(" row %u change structure %d reg=%d (max %d)",
727 row, i, reg, cmapP->ncolors-1);
728 pm_message(" ignoring it... "
729 "colors might get messed up from here");
730 } else {
731 if (reg != MP_REG_IGNORE) {
732 PPM_ASSIGN(cmapP->color[reg],
733 palchange[i].r, palchange[i].g, palchange[i].b);
734 }
735 }
736 }
737 }
738
739
740
741 static void
742 multi_init(ColorMap * const cmapP,
743 long const viewportmodes) {
744
745 if (cmapP->mp_init)
746 multi_adjust(cmapP, -1, cmapP->mp_init);
747 if (!(viewportmodes & vmLACE) )
748 cmapP->mp_flags &= ~(MP_FLAGS_SKIPLACED);
749 }
750
751
752
753 static void
754 multi_update(ColorMap * const cmapP,
755 unsigned int const row) {
756
757 if (cmapP->mp_flags & MP_FLAGS_SKIPLACED) {
758 if (ODD(row))
759 return;
760 if (row/2 < cmapP->mp_rows && cmapP->mp_change[row/2])
761 multi_adjust(cmapP, row, cmapP->mp_change[row/2]);
762 } else {
763 if (row < cmapP->mp_rows && cmapP->mp_change[row])
764 multi_adjust(cmapP, row, cmapP->mp_change[row]);
765 }
766 }
767
768
769
770 static void
771 multi_free(ColorMap * const cmapP) {
772
773 if (cmapP->mp_init) {
774 free(cmapP->mp_init);
775 cmapP->mp_init = NULL;
776 }
777
778 if (cmapP->mp_change) {
779 unsigned int i;
780
781 for (i = 0; i < cmapP->mp_rows; ++i) {
782 if (cmapP->mp_change[i])
783 free(cmapP->mp_change[i]);
784 }
785 free(cmapP->mp_change);
786 cmapP->mp_change = NULL;
787 }
788
789 cmapP->mp_rows = 0;
790 cmapP->mp_type = 0;
791 cmapP->mp_flags = 0;
792 }
793
794
795
796 /****************************************************************************
797 Colormap handling
798 ****************************************************************************/
799
800
801
802 static void
803 analyzeCmapSamples(const ColorMap * const cmapP,
804 pixval * const maxSampleP,
805 bool * const shiftedP) {
806
807 pixval maxSample;
808 bool shifted;
809 unsigned int i;
810
811 for (i = 0, maxSample = 0, shifted = true; i < cmapP->ncolors; ++i) {
812 pixval const r = PPM_GETR(cmapP->color[i]);
813 pixval const g = PPM_GETG(cmapP->color[i]);
814 pixval const b = PPM_GETB(cmapP->color[i]);
815
816 maxSample = MAX(maxSample, MAX(r, MAX(g, b)));
817
818 if (r & 0x0f || g & 0x0f || b & 0x0f)
819 shifted = false;
820 }
821 *shiftedP = shifted;
822 *maxSampleP = maxSample;
823 }
824
825
826
827 static void
828 transformCmap(ColorMap * const cmapP) {
829
830 pixval maxSample;
831 /* The maximum sample value in *cmapP input */
832 bool shifted;
833 /* Samples in the *cmapP input appear to be 4 bit (maxval 15) original
834 values shifted left 4 places to make 8 bit (maxval 255) samples.
835 */
836
837 analyzeCmapSamples(cmapP, &maxSample, &shifted);
838
839 if (maxSample == 0)
840 pm_message("warning - black colormap");
841 else if (shifted || maxSample <= 15) {
842 if (!adjustcolors) {
843 pm_message("warning - probably %s4-bit colormap",
844 shifted ? "shifted " : "");
845 pm_message("Use '-adjustcolors' to scale colormap to 8 bits");
846 } else {
847 unsigned int i;
848 pm_message("scaling colormap to 8 bits");
849 for (i = 0; i < cmapP->ncolors; ++i) {
850 pixval r, g, b;
851 r = PPM_GETR(cmapP->color[i]);
852 g = PPM_GETG(cmapP->color[i]);
853 b = PPM_GETB(cmapP->color[i]);
854 if (shifted) {
855 r >>= 4;
856 g >>= 4;
857 b >>= 4;
858 }
859 r *= FACTOR_4BIT;
860 g *= FACTOR_4BIT;
861 b *= FACTOR_4BIT;
862 PPM_ASSIGN(cmapP->color[i], r, g, b);
863 }
864 }
865 }
866 }
867
868
869
870 static pixel *
871 transpColor(const BitMapHeader * const bmhdP,
872 ColorMap * const cmapP,
873 const char * const transpName,
874 pixval const maxval) {
875
876 pixel * transpColorP;
877
878 if (bmhdP) {
879 if (bmhdP->masking == mskHasTransparentColor ||
880 bmhdP->masking == mskLasso) {
881 MALLOCVAR_NOFAIL(transpColorP);
882
883 if (transpName)
884 *transpColorP = ppm_parsecolor(transpName, maxval);
885 else {
886 unsigned short const transpIdx = bmhdP->transparentColor;
887 if (HAS_COLORMAP(cmapP)) {
888 if (transpIdx >= cmapP->ncolors) {
889 pm_message("using default transparent color (black)");
890 PPM_ASSIGN(*transpColorP, 0, 0, 0);
891 } else
892 *transpColorP = cmapP->color[transpIdx];
893 } else {
894 /* The color index is just a direct gray level */
895 PPM_ASSIGN(*transpColorP, transpIdx, transpIdx, transpIdx);
896 }
897 }
898 } else
899 transpColorP = NULL;
900 } else
901 transpColorP = NULL;
902
903 return transpColorP;
904 }
905
906
907
908 static void
909 prepareCmap(const BitMapHeader * const bmhdP,
910 ColorMap * const cmapP) {
911 /*----------------------------------------------------------------------------
912 This is a really ugly subroutine that 1) analyzes a colormap and its
913 context (returning the analysis in global variables); and 2) modifies that
914 color map, because it's really one type of data structure as input and
915 another as output.
916 -----------------------------------------------------------------------------*/
917 bool bmhdCmapOk;
918
919 if (bmhdP)
920 bmhdCmapOk = (bmhdP->flags & BMHD_FLAGS_CMAPOK);
921 else
922 bmhdCmapOk = false;
923
924 if (HAS_COLORMAP(cmapP) && !bmhdCmapOk)
925 transformCmap(cmapP);
926 }
927
928
929
930 static pixval
931 lookup_red(ColorMap * const cmapP,
932 unsigned int const oldval) {
933
934 if (cmapP && cmapP->redlut && oldval < 256)
935 return cmapP->redlut[oldval];
936 else
937 return oldval;
938 }
939
940
941
942 static pixval
943 lookup_green(ColorMap * const cmapP,
944 unsigned int const oldval) {
945
946 if (cmapP && cmapP->greenlut && oldval < 256)
947 return cmapP->greenlut[oldval];
948 else
949 return oldval;
950 }
951
952
953
954 static pixval
955 lookup_blue(ColorMap * const cmapP,
956 unsigned int const oldval) {
957
958 if (cmapP && cmapP->bluelut && oldval < 256)
959 return cmapP->bluelut[oldval];
960 else
961 return oldval;
962 }
963
964
965
966 static pixval
967 lookup_mono(ColorMap * const cmapP,
968 unsigned int const oldval) {
969
970 if (cmapP && cmapP->monolut && oldval < 256)
971 return cmapP->monolut[oldval];
972 else
973 return oldval;
974 }
975
976
977
978 static ColorMap *
979 ehbcmap(ColorMap * const cmapP) {
980
981 pixel * tempcolor;
982 unsigned int i;
983
984 tempcolor = ppm_allocrow(cmapP->ncolors * 2);
985
986 for (i = 0; i < cmapP->ncolors; ++i) {
987 tempcolor[i] = cmapP->color[i];
988 PPM_ASSIGN(tempcolor[cmapP->ncolors + i],
989 PPM_GETR(cmapP->color[i]) / 2,
990 PPM_GETG(cmapP->color[i]) / 2,
991 PPM_GETB(cmapP->color[i]) / 2);
992 }
993 ppm_freerow(cmapP->color);
994 cmapP->color = tempcolor;
995 cmapP->ncolors *= 2;
996
997 return cmapP;
998 }
999
1000
1001
1002 static pixval
1003 lut_maxval(ColorMap * const cmap,
1004 pixval const maxval) {
1005
1006 pixval retval;
1007
1008 if (maxval >= 255)
1009 retval = maxval;
1010 else {
1011 if (!HAS_COLORLUT(cmap))
1012 retval = maxval;
1013 else {
1014 unsigned int i;
1015 unsigned char maxlut;
1016 maxlut = maxval;
1017 for( i = 0; i < maxval; i++ ) {
1018 if( cmap->redlut && cmap->redlut[i] > maxlut )
1019 maxlut = cmap->redlut[i];
1020 if( cmap->greenlut && cmap->greenlut[i] > maxlut )
1021 maxlut = cmap->greenlut[i];
1022 if( cmap->bluelut && cmap->bluelut[i] > maxlut )
1023 maxlut = cmap->bluelut[i];
1024 }
1025 pm_message("warning - "
1026 "%d-bit index into 8-bit color lookup table, "
1027 "table maxval=%d",
1028 pm_maxvaltobits(maxval), maxlut);
1029 if( maxlut != maxval )
1030 retval = 255;
1031 else
1032 retval = maxval;
1033 pm_message(" assuming image maxval=%d", retval);
1034 }
1035 }
1036 return retval;
1037 }
1038
1039
1040
1041 static void
1042 get_color(ColorMap * const cmapP,
1043 unsigned int const idx,
1044 pixval * const redP,
1045 pixval * const greenP,
1046 pixval * const blueP) {
1047
1048 if (HAS_COLORMAP(cmapP)) {
1049 if (idx >= cmapP->ncolors)
1050 pm_error("color index out of range: %u (max %u)",
1051 idx, cmapP->ncolors);
1052 else {
1053 pixval const r = PPM_GETR(cmapP->color[idx]);
1054 pixval const g = PPM_GETG(cmapP->color[idx]);
1055 pixval const b = PPM_GETB(cmapP->color[idx]);
1056
1057 *redP = lookup_red (cmapP, r);
1058 *greenP = lookup_green (cmapP, g);
1059 *blueP = lookup_blue (cmapP, b);
1060 }
1061 } else
1062 *redP = *greenP = *blueP = lookup_mono(cmapP, idx);
1063 }
1064
1065
1066
1067 /****************************************************************************
1068 Conversion functions
1069 ****************************************************************************/
1070
1071 static void
1072 std_to_ppm(FILE * const ifP,
1073 long const chunksize,
1074 BitMapHeader * const bmhdP,
1075 ColorMap * const cmap,
1076 long const viewportmodes);
1077
1078
1079
1080 static void
1081 ham_to_ppm(FILE * const ifP,
1082 long const chunksize,
1083 BitMapHeader * const bmhdP,
1084 ColorMap * const cmap,
1085 long const viewportmodes) {
1086
1087 int cols, rows, hambits, hammask, hamshift, hammask2, col, row;
1088 pixval maxval;
1089 rawtype *rawrow;
1090 unsigned char hamlut[256];
1091
1092 cols = bmhdP->w;
1093 rows = bmhdP->h;
1094 hambits = bmhdP->nPlanes - 2;
1095 hammask = (1 << hambits) - 1;
1096 hamshift = 8 - hambits;
1097 hammask2 = (1 << hamshift) - 1;
1098
1099 if( hambits > 8 || hambits < 1 ) {
1100 int const assumed_viewportmodes = viewportmodes & ~(vmHAM);
1101
1102 pm_message("%d-plane HAM?? - interpreting image as a normal ILBM",
1103 bmhdP->nPlanes);
1104 std_to_ppm(ifP, chunksize, bmhdP, cmap, assumed_viewportmodes);
1105 return;
1106 } else {
1107 unsigned long remainingChunksize;
1108 pixel * transpColorP;
1109
1110 pm_message("input is a %sHAM%d file",
1111 HAS_MULTIPALETTE(cmap) ? "multipalette " : "",
1112 bmhdP->nPlanes);
1113
1114 if( HAS_COLORLUT(cmap) || HAS_MONOLUT(cmap) ) {
1115 pm_message("warning - color lookup tables ignored in HAM");
1116 if( cmap->redlut ) free(cmap->redlut);
1117 if( cmap->greenlut ) free(cmap->greenlut);
1118 if( cmap->bluelut ) free(cmap->bluelut);
1119 if( cmap->monolut ) free(cmap->monolut);
1120 cmap->redlut = cmap->greenlut = cmap->bluelut =
1121 cmap->monolut = NULL;
1122 }
1123 if( !HAS_COLORMAP(cmap) ) {
1124 pm_message("no colormap - interpreting values as grayscale");
1125 maxval = pm_bitstomaxval(hambits);
1126 for( col = 0; col <= maxval; col++ )
1127 hamlut[col] = col * MAXCOLVAL / maxval;
1128 cmap->monolut = hamlut;
1129 }
1130
1131 transpColorP = transpColor(bmhdP, cmap, transpName, MAXCOLVAL);
1132
1133 if( HAS_MULTIPALETTE(cmap) )
1134 multi_init(cmap, viewportmodes);
1135
1136 rawrow = alloc_rawrow(cols);
1137
1138 ppm_writeppminit(stdout, cols, rows, MAXCOLVAL, 0);
1139
1140 remainingChunksize = chunksize; /* initial value */
1141
1142 for (row = 0; row < rows; ++row) {
1143 pixval r, g, b;
1144
1145 if( HAS_MULTIPALETTE(cmap) )
1146 multi_update(cmap, row);
1147
1148 decodeRow(ifP, &remainingChunksize, rawrow, bmhdP->nPlanes, bmhdP);
1149 decodeMask(ifP, &remainingChunksize, rawrow, bmhdP);
1150
1151 r = g = b = 0;
1152 for( col = 0; col < cols; col++ ) {
1153 int idx = rawrow[col] & hammask;
1154
1155 if( transpColorP && maskrow && maskrow[col] == PBM_WHITE )
1156 pixelrow[col] = *transpColorP;
1157 else {
1158 switch((rawrow[col] >> hambits) & 0x03) {
1159 case HAMCODE_CMAP:
1160 get_color(cmap, idx, &r, &g, &b);
1161 break;
1162 case HAMCODE_BLUE:
1163 b = ((b & hammask2) | (idx << hamshift));
1164 /*b = hamlut[idx];*/
1165 break;
1166 case HAMCODE_RED:
1167 r = ((r & hammask2) | (idx << hamshift));
1168 /*r = hamlut[idx];*/
1169 break;
1170 case HAMCODE_GREEN:
1171 g = ((g & hammask2) | (idx << hamshift));
1172 /*g = hamlut[idx];*/
1173 break;
1174 default:
1175 pm_error("ham_to_ppm(): "
1176 "impossible HAM code - can't happen");
1177 }
1178 PPM_ASSIGN(pixelrow[col], r, g, b);
1179 }
1180 }
1181 ppm_writeppmrow(stdout, pixelrow, cols, MAXCOLVAL, 0);
1182 }
1183 chunk_end(ifP, ID_BODY, remainingChunksize);
1184 }
1185 }
1186
1187
1188
1189 static void
1190 std_to_ppm(FILE * const ifP,
1191 long const chunksize,
1192 BitMapHeader * const bmhdP,
1193 ColorMap * const cmap,
1194 long const viewportmodes) {
1195
1196 if (viewportmodes & vmHAM) {
1197 ham_to_ppm(ifP, chunksize, bmhdP, cmap, viewportmodes);
1198 } else {
1199 unsigned int const cols = bmhdP->w;
1200 unsigned int const rows = bmhdP->h;
1201
1202 rawtype *rawrow;
1203 unsigned int row, col;
1204 pixval maxval;
1205 unsigned long remainingChunksize;
1206 pixel * transpColorP;
1207
1208 pm_message("input is a %d-plane %s%sILBM", bmhdP->nPlanes,
1209 HAS_MULTIPALETTE(cmap) ? "multipalette " : "",
1210 viewportmodes & vmEXTRA_HALFBRITE ? "EHB " : ""
1211 );
1212
1213 if( bmhdP->nPlanes > MAXPLANES )
1214 pm_error("too many planes (max %d)", MAXPLANES);
1215
1216 if( HAS_COLORMAP(cmap) ) {
1217 if( viewportmodes & vmEXTRA_HALFBRITE )
1218 ehbcmap(cmap); /* Modifies *cmap */
1219 maxval = MAXCOLVAL;
1220 }
1221 else {
1222 pm_message("no colormap - interpreting values as grayscale");
1223 maxval = lut_maxval(cmap, pm_bitstomaxval(bmhdP->nPlanes));
1224 if( maxval > PPM_OVERALLMAXVAL )
1225 pm_error("nPlanes is too large");
1226 }
1227
1228 transpColorP = transpColor(bmhdP, cmap, transpName, maxval);
1229
1230 rawrow = alloc_rawrow(cols);
1231
1232 if( HAS_MULTIPALETTE(cmap) )
1233 multi_init(cmap, viewportmodes);
1234
1235 ppm_writeppminit( stdout, cols, rows, maxval, 0 );
1236
1237 remainingChunksize = chunksize; /* initial value */
1238
1239 for (row = 0; row < rows; ++row) {
1240
1241 if( HAS_MULTIPALETTE(cmap) )
1242 multi_update(cmap, row);
1243
1244 decodeRow(ifP, &remainingChunksize, rawrow, bmhdP->nPlanes, bmhdP);
1245 decodeMask(ifP, &remainingChunksize, rawrow, bmhdP);
1246
1247 for( col = 0; col < cols; col++ ) {
1248 pixval r, g, b;
1249 if( transpColorP && maskrow && maskrow[col] == PBM_WHITE )
1250 pixelrow[col] = *transpColorP;
1251 else {
1252 get_color(cmap, rawrow[col], &r, &g, &b);
1253 PPM_ASSIGN(pixelrow[col], r, g, b);
1254 }
1255 }
1256 ppm_writeppmrow(stdout, pixelrow, cols, maxval, 0);
1257 }
1258 chunk_end(ifP, ID_BODY, remainingChunksize);
1259 }
1260 }
1261
1262
1263
1264 static void
1265 deep_to_ppm(FILE * const ifP,
1266 long const chunksize,
1267 BitMapHeader * const bmhdP,
1268 ColorMap * const cmap) {
1269
1270 unsigned int const cols = bmhdP->w;
1271 unsigned int const rows = bmhdP->h;
1272 unsigned int const planespercolor = bmhdP->nPlanes / 3;
1273
1274 unsigned int row;
1275 rawtype * Rrow;
1276 rawtype * Grow;
1277 rawtype * Brow;
1278 pixval maxval;
1279 unsigned long remainingChunksize;
1280 pixel * transpColorP;
1281
1282 pm_message("input is a deep (%d-bit) ILBM", bmhdP->nPlanes);
1283 if (planespercolor > MAXPLANES)
1284 pm_error("too many planes (max %d)", MAXPLANES * 3);
1285
1286 if (bmhdP->masking == mskHasTransparentColor ||
1287 bmhdP->masking == mskLasso) {
1288 pm_message("masking type '%s' in a deep ILBM?? - ignoring it",
1289 mskNAME[bmhdP->masking]);
1290 bmhdP->masking = mskNone;
1291 }
1292
1293 maxval = lut_maxval(cmap, pm_bitstomaxval(planespercolor));
1294 if (maxval > PPM_OVERALLMAXVAL)
1295 pm_error("nPlanes is too large");
1296
1297 transpColorP = transpColor(bmhdP, cmap, transpName, maxval);
1298
1299 Rrow = alloc_rawrow(cols);
1300 Grow = alloc_rawrow(cols);
1301 Brow = alloc_rawrow(cols);
1302
1303 ppm_writeppminit(stdout, cols, rows, maxval, 0);
1304
1305 remainingChunksize = chunksize; /* initial value */
1306
1307 for (row = 0; row < rows; ++row) {
1308 unsigned int col;
1309
1310 decodeRow(ifP, &remainingChunksize, Rrow, planespercolor, bmhdP);
1311 decodeRow(ifP, &remainingChunksize, Grow, planespercolor, bmhdP);
1312 decodeRow(ifP, &remainingChunksize, Brow, planespercolor, bmhdP);
1313 decodeMask(ifP, &remainingChunksize, NULL, bmhdP);
1314
1315 for (col = 0; col < cols; ++col) {
1316 if (transpColorP && maskrow && maskrow[col] == PBM_WHITE)
1317 pixelrow[col] = *transpColorP;
1318 else
1319 PPM_ASSIGN(pixelrow[col], lookup_red(cmap, Rrow[col]),
1320 lookup_green(cmap, Grow[col]),
1321 lookup_blue(cmap, Brow[col]));
1322 }
1323 ppm_writeppmrow(stdout, pixelrow, cols, maxval, 0);
1324 }
1325 chunk_end(ifP, ID_BODY, remainingChunksize);
1326 }
1327
1328
1329
1330 static void
1331 dcol_to_ppm(FILE * const ifP,
1332 long const chunksize,
1333 BitMapHeader * const bmhdP,
1334 ColorMap * const cmap,
1335 DirectColor * const dcol) {
1336
1337 unsigned int const cols = bmhdP->w;
1338 unsigned int const rows = bmhdP->h;
1339 unsigned int const redplanes = dcol->r;
1340 unsigned int const greenplanes = dcol->g;
1341 unsigned int const blueplanes = dcol->b;
1342
1343 int row;
1344 rawtype * Rrow;
1345 rawtype * Grow;
1346 rawtype * Brow;
1347 pixval maxval, redmaxval, greenmaxval, bluemaxval;
1348 pixval *redtable, *greentable, *bluetable;
1349 unsigned long remainingChunksize;
1350 pixel * transpColorP;
1351
1352 pm_message("input is a %d:%d:%d direct color ILBM",
1353 redplanes, greenplanes, blueplanes);
1354
1355 if (redplanes > MAXPLANES ||
1356 blueplanes > MAXPLANES ||
1357 greenplanes > MAXPLANES)
1358 pm_error("too many planes (max %d per color component)", MAXPLANES);
1359
1360 if (bmhdP->nPlanes != (redplanes + greenplanes + blueplanes))
1361 pm_error("%s/%s plane number mismatch",
1362 ID2string(ID_BMHD), ID2string(ID_DCOL));
1363
1364 if (bmhdP->masking == mskHasTransparentColor ||
1365 bmhdP->masking == mskLasso) {
1366 pm_message("masking type '%s' in a direct color ILBM?? - ignoring it",
1367 mskNAME[bmhdP->masking]);
1368 bmhdP->masking = mskNone;
1369 }
1370
1371 if (HAS_COLORLUT(cmap)) {
1372 pm_error("This program does not know how to process a %s chunk "
1373 "in direct color", ID2string(ID_CLUT));
1374 cmap->redlut = cmap->greenlut = cmap->bluelut = NULL;
1375 }
1376
1377 redmaxval = pm_bitstomaxval(redplanes);
1378 greenmaxval = pm_bitstomaxval(greenplanes);
1379 bluemaxval = pm_bitstomaxval(blueplanes);
1380 maxval = MAX(redmaxval, MAX(greenmaxval, bluemaxval));
1381
1382 if (maxval > PPM_OVERALLMAXVAL)
1383 pm_error("too many planes");
1384
1385 if (redmaxval != maxval || greenmaxval != maxval || bluemaxval != maxval)
1386 pm_message("scaling colors to %u bits", pm_maxvaltobits(maxval));
1387
1388 MALLOCARRAY_NOFAIL(redtable, redmaxval + 1);
1389 MALLOCARRAY_NOFAIL(greentable, greenmaxval + 1);
1390 MALLOCARRAY_NOFAIL(bluetable, bluemaxval + 1);
1391
1392 {
1393 unsigned int i;
1394 for (i = 0; i <= redmaxval; ++i)
1395 redtable[i] = ROUNDDIV(i * maxval, redmaxval);
1396 for (i = 0; i <= greenmaxval; ++i)
1397 greentable[i] = ROUNDDIV(i * maxval, greenmaxval);
1398 for (i = 0; i <= bluemaxval; ++i)
1399 bluetable[i] = ROUNDDIV(i * maxval, bluemaxval);
1400 }
1401 transpColorP = transpColor(bmhdP, cmap, transpName, maxval);
1402
1403 Rrow = alloc_rawrow(cols);
1404 Grow = alloc_rawrow(cols);
1405 Brow = alloc_rawrow(cols);
1406
1407 ppm_writeppminit(stdout, cols, rows, maxval, 0);
1408
1409 remainingChunksize = chunksize; /* initial value */
1410
1411 for (row = 0; row < rows; ++row) {
1412 unsigned int col;
1413
1414 decodeRow(ifP, &remainingChunksize, Rrow, redplanes, bmhdP);
1415 decodeRow(ifP, &remainingChunksize, Grow, greenplanes, bmhdP);
1416 decodeRow(ifP, &remainingChunksize, Brow, blueplanes, bmhdP);
1417 decodeMask(ifP, &remainingChunksize, NULL, bmhdP);
1418
1419 for (col = 0; col < cols; ++col) {
1420 if (transpColorP && maskrow && maskrow[col] == PBM_WHITE)
1421 pixelrow[col] = *transpColorP;
1422 else
1423 PPM_ASSIGN(pixelrow[col], redtable[Rrow[col]],
1424 greentable[Grow[col]],
1425 bluetable[Brow[col]]);
1426 }
1427 ppm_writeppmrow(stdout, pixelrow, cols, maxval, 0);
1428 }
1429 chunk_end(ifP, ID_BODY, remainingChunksize);
1430 }
1431
1432
1433
1434 static void
1435 cmapToPpm(FILE * const ofP,
1436 ColorMap * const cmapP) {
1437
1438 ppm_colorrowtomapfile(ofP, cmapP->color, cmapP->ncolors, MAXCOLVAL);
1439 }
1440
1441
1442
1443 static void
1444 ipbm_to_ppm(FILE * const ifP,
1445 long const chunksize,
1446 BitMapHeader * const bmhdP,
1447 ColorMap * const cmap,
1448 long const viewportmodes) {
1449
1450 unsigned int const cols = bmhdP->w;
1451 unsigned int const rows = bmhdP->h;
1452
1453 int col, row;
1454 pixval maxval;
1455 unsigned long remainingChunksize;
1456 pixel * transpColorP;
1457
1458 pm_message("input is a %sPBM ",
1459 HAS_MULTIPALETTE(cmap) ? "multipalette " : "");
1460
1461 if( bmhdP->nPlanes != 8 )
1462 pm_error("invalid number of planes for IFF-PBM: %d (must be 8)",
1463 bmhdP->nPlanes);
1464
1465 if( bmhdP->masking == mskHasMask )
1466 pm_error("Image has a maskplane, which is invalid in IFF-PBM");
1467
1468 if( HAS_COLORMAP(cmap) )
1469 maxval = MAXCOLVAL;
1470 else {
1471 pm_message("no colormap - interpreting values as grayscale");
1472 maxval = lut_maxval(cmap, pm_bitstomaxval(bmhdP->nPlanes));
1473 }
1474
1475 transpColorP = transpColor(bmhdP, cmap, transpName, maxval);
1476
1477 if( HAS_MULTIPALETTE(cmap) )
1478 multi_init(cmap, viewportmodes);
1479
1480 MALLOCARRAY_NOFAIL(ilbmrow, cols);
1481
1482 ppm_writeppminit(stdout, cols, rows, maxval, 0);
1483
1484 remainingChunksize = chunksize; /* initial value */
1485
1486 for( row = 0; row < rows; row++ ) {
1487 if( HAS_MULTIPALETTE(cmap) )
1488 multi_update(cmap, row);
1489
1490 read_ilbm_plane(ifP, &remainingChunksize, cols, bmhdP->compression);
1491
1492 for( col = 0; col < cols; col++ ) {
1493 pixval r, g, b;
1494 if( transpColorP && maskrow && maskrow[col] == PBM_WHITE )
1495 pixelrow[col] = *transpColorP;
1496 else {
1497 get_color(cmap, ilbmrow[col], &r, &g, &b);
1498 PPM_ASSIGN(pixelrow[col], r, g, b);
1499 }
1500 }
1501 ppm_writeppmrow(stdout, pixelrow, cols, maxval, 0);
1502 }
1503 chunk_end(ifP, ID_BODY, remainingChunksize);
1504 }
1505
1506
1507
1508 static void
1509 rgbn_to_ppm(FILE * const ifP,
1510 long const chunksize,
1511 BitMapHeader * const bmhdP,
1512 ColorMap * const cmap /* for CLUTs */
1513 ) {
1514
1515 unsigned int const rows = bmhdP->h;
1516 unsigned int const cols = bmhdP->w;
1517
1518 unsigned int row;
1519 unsigned int count;
1520 pixval maxval;
1521 unsigned long remainingChunksize;
1522 pixel * transpColorP;
1523
1524 pm_message("input is a %d-bit RGB image", (typeid == ID_RGB8 ? 8 : 4));
1525
1526 if (bmhdP->compression != 4)
1527 pm_error("invalid compression mode for %s: %d (must be 4)",
1528 ID2string(typeid), bmhdP->compression);
1529
1530 switch (typeid) {
1531 case ID_RGBN:
1532 if (bmhdP->nPlanes != 13)
1533 pm_error("invalid number of planes for %s: %d (must be 13)",
1534 ID2string(typeid), bmhdP->nPlanes);
1535 maxval = lut_maxval(cmap, 15);
1536 break;
1537 case ID_RGB8:
1538 if (bmhdP->nPlanes != 25)
1539 pm_error("invalid number of planes for %s: %d (must be 25)",
1540 ID2string(typeid), bmhdP->nPlanes);
1541 maxval = 255;
1542 break;
1543 default:
1544 pm_error("rgbn_to_ppm(): invalid IFF ID %s - can't happen",
1545 ID2string(typeid));
1546 }
1547
1548 transpColorP = transpColor(bmhdP, cmap, transpName, maxval);
1549
1550 ppm_writeppminit(stdout, cols, rows, maxval, 0);
1551
1552 for (row = 0, count = 0, remainingChunksize = chunksize;
1553 row < rows;
1554 ++row) {
1555
1556 unsigned int col;
1557
1558 for (col = 0; col < cols; ++col) {
1559 unsigned int tries;
1560 unsigned int genlock;
1561 pixval r, g, b;
1562
1563 tries = 0;
1564 while (count == 0) {
1565 if (typeid == ID_RGB8) {
1566 r = lookup_red(cmap, get_byte(ifP, ID_BODY,
1567 &remainingChunksize));
1568 g = lookup_green(cmap, get_byte(ifP, ID_BODY,
1569 &remainingChunksize));
1570 b = lookup_blue(cmap, get_byte(ifP, ID_BODY,
1571 &remainingChunksize));
1572 count = get_byte(ifP, ID_BODY, &remainingChunksize);
1573 genlock = count & 0x80;
1574 count &= 0x7f;
1575 } else {
1576 unsigned int const word =
1577 get_big_short(ifP, ID_BODY, &remainingChunksize);
1578 r = lookup_red(cmap, (word & 0xf000) >> 12);
1579 g = lookup_green(cmap, (word & 0x0f00) >> 8);
1580 b = lookup_blue(cmap, (word & 0x00f0) >> 4);
1581 genlock = word & 0x0008;
1582 count = word & 0x0007;
1583 }
1584 if (!count) {
1585 count = get_byte(ifP, ID_BODY, &remainingChunksize);
1586 if (count == 0)
1587 count =
1588 get_big_short(ifP, ID_BODY, &remainingChunksize);
1589 if (count == 0)
1590 ++tries;
1591 }
1592 }
1593 if (tries > 0) {
1594 pm_message("warning - repeat count 0 at col %u row %u: "
1595 "skipped %u RGB entr%s",
1596 col, row, tries, (tries == 1 ? "y" : "ies"));
1597 }
1598 if (maskfile) {
1599 /* genlock bit set -> transparent */
1600 if (genlock)
1601 maskrow[col] = PBM_WHITE;
1602 else
1603 maskrow[col] = PBM_BLACK;
1604 }
1605 if (transpColorP && maskrow && maskrow[col] == PBM_WHITE)
1606 pixelrow[col] = *transpColorP;
1607 else
1608 PPM_ASSIGN(pixelrow[col], r, g, b);
1609 --count;
1610 }
1611 ppm_writeppmrow(stdout, pixelrow, cols, maxval, 0);
1612 if (maskfile) {
1613 pbm_writepbmrow(maskfile, maskrow, cols, 0);
1614 wrotemask = true;
1615 }
1616 }
1617 chunk_end(ifP, ID_BODY, remainingChunksize);
1618 }
1619
1620
1621
1622 /****************************************************************************
1623 Multipalette chunk reader
1624
1625 Currently there are three multipalette formats:
1626 SHAM - sliced HAM (obsolete)
1627 CTBL - dynamic HAM/Hires (obsolete)
1628 PCHG - palette change
1629 There is no official documentation available for SHAM and CTBL, so
1630 this is mostly guesswork from other sources and hexdumps of pictures...
1631
1632 CTBL format (dynamic HAM/Hires):
1633 16 bigendian words per row (16 bit: 0000rrrrggggbbbb)
1634 This is simply an entire 4-bit colormap per row.
1635 I have no idea what the DYCP chunk is for.
1636
1637 SHAM format (sliced HAM):
1638 1 word - version info (?) - always 0
1639 16 bigendian words per row (16 bit: 0000rrrrggggbbbb)
1640 If the picture is laced, then there are only rows/2 changes, don't change
1641 palette on odd lines.
1642
1643 PCHG format: A detailed description of this format is available
1644 from AmiNet as PCHGLib12.lha.
1645
1646 ****************************************************************************/
1647
1648 /* Turn big-endian 4-byte long and 2-byte short stored at x (unsigned char *)
1649 * into the native format of the CPU
1650 */
1651 #define BIG_LONG(x) ( ((unsigned long)((x)[0]) << 24) + \
1652 ((unsigned long)((x)[1]) << 16) + \
1653 ((unsigned long)((x)[2]) << 8) + \
1654 ((unsigned long)((x)[3]) << 0) )
1655 #define BIG_WORD(x) ( ((unsigned short)((x)[0]) << 8) + \
1656 ((unsigned short)((x)[1]) << 0) )
1657
1658
1659
1660 static void
1661 read_4bit_mp(FILE * const ifP,
1662 IFF_ID const iffid,
1663 long const chunksize,
1664 ColorMap * const cmap) {
1665
1666 int row, rows, i, type;
1667 short data;
1668 unsigned long remainingChunksize;
1669
1670 type = (iffid == ID_SHAM ? MP_TYPE_SHAM : MP_TYPE_CTBL);
1671
1672 if( cmap->mp_type >= type ) {
1673 skip_chunk(ifP, iffid, chunksize);
1674 } else {
1675 if( cmap->mp_type )
1676 multi_free(cmap);
1677 cmap->mp_type = type;
1678
1679 remainingChunksize = chunksize; /* initial value */
1680
1681 if( type == MP_TYPE_SHAM ) {
1682 cmap->mp_flags = MP_FLAGS_SKIPLACED;
1683 get_big_short(ifP, iffid, &remainingChunksize); /* skip first wd */
1684 }
1685
1686 cmap->mp_rows = rows = remainingChunksize/32; /* sizeof(word) * 16 */
1687 MALLOCARRAY_NOFAIL(cmap->mp_change, rows);
1688
1689 for( row = 0; row < rows; row++ ) {
1690 MALLOCARRAY_NOFAIL(cmap->mp_change[row], 17); /* 16 + sentinel */
1691 for( i = 0; i < 16; i++ ) {
1692 data = get_big_short(ifP, iffid, &remainingChunksize);
1693 cmap->mp_change[row][i].reg = i;
1694 cmap->mp_change[row][i].r =
1695 ((data & 0x0f00) >> 8) * FACTOR_4BIT;
1696 cmap->mp_change[row][i].g =
1697 ((data & 0x00f0) >> 4) * FACTOR_4BIT;
1698 cmap->mp_change[row][i].b =
1699 ((data & 0x000f) >> 0) * FACTOR_4BIT;
1700 }
1701 cmap->mp_change[row][16].reg = MP_REG_END; /* sentinel */
1702 }
1703 chunk_end(ifP, iffid, remainingChunksize);
1704 }
1705 }
1706
1707
1708
1709 static void
1710 PCHG_DecompHuff(const unsigned char * const src,
1711 unsigned char * const dst,
1712 short * const tree,
1713 unsigned long const origsize) {
1714
1715 const unsigned char * srcCursor;
1716 unsigned char * dstCursor;
1717 unsigned long i;
1718 unsigned long bits;
1719 unsigned char thisbyte;
1720 short * p;
1721
1722 srcCursor = &src[0]; /* initial value */
1723 dstCursor = &dst[0]; /* initial value */
1724 i = 0; /* initial value */
1725 bits = 0; /* initial value */
1726 p = tree; /* initial value */
1727
1728 while (i < origsize) {
1729 if (bits == 0) {
1730 thisbyte = *srcCursor++;
1731 bits = 8;
1732 }
1733 if (thisbyte & (1 << 7)) {
1734 if (*p >= 0) {
1735 *dstCursor++ = (unsigned char)*p;
1736 ++i;
1737 p = tree;
1738 } else
1739 p += (*p / 2);
1740 } else {
1741 --p;
1742 if (*p > 0 && (*p & 0x100)) {
1743 *dstCursor++ = (unsigned char )*p;
1744 ++i;
1745 p = tree;
1746 }
1747 }
1748 thisbyte <<= 1;
1749 --bits;
1750 }
1751 }
1752
1753
1754
1755 static void
1756 PCHG_Decompress(PCHGHeader * const PCHG,
1757 PCHGCompHeader * const CompHdr,
1758 unsigned char * const compdata,
1759 unsigned long const compsize,
1760 unsigned char * const comptree,
1761 unsigned char * const data) {
1762
1763 switch(PCHG->Compression) {
1764 case PCHG_COMP_HUFFMAN: {
1765 unsigned long const treesize = CompHdr->CompInfoSize;
1766 unsigned long const huffsize = treesize / 2;
1767 const bigend16 * const bigendComptree = (const void *)comptree;
1768
1769 short * hufftree;
1770 unsigned long i;
1771
1772 /* Convert big-endian 2-byte shorts to C shorts */
1773
1774 MALLOCARRAY(hufftree, huffsize);
1775
1776 if (!hufftree)
1777 pm_error("Couldn't get memory for %lu-byte Huffman tree",
1778 huffsize);
1779
1780 for (i = 0; i < huffsize; ++i)
1781 hufftree[i] = pm_uintFromBigend16(bigendComptree[i]);
1782
1783 /* decompress the change structure data */
1784 PCHG_DecompHuff(compdata, data, &hufftree[huffsize-1],
1785 CompHdr->OriginalDataSize);
1786
1787 free(hufftree);
1788 } break;
1789 default:
1790 pm_error("unknown PCHG compression type %d", PCHG->Compression);
1791 }
1792 }
1793
1794
1795
1796 static void
1797 PCHG_ConvertSmall(PCHGHeader * const pchgP,
1798 ColorMap * const cmapP,
1799 unsigned char * const mask,
1800 unsigned long const dataSize) {
1801
1802 unsigned char * dataCursor;
1803 unsigned long remDataSize;
1804 unsigned char thismask;
1805 int bits, row, masklen, reg;
1806 unsigned int totalChangeCt;
1807 unsigned int changedLineCt;
1808 unsigned char * maskCursor;
1809
1810 totalChangeCt = 0; /* initial value */
1811 changedLineCt = pchgP->ChangedLines; /* initial value */
1812 masklen = 4 * MaskLongWords(pchgP->LineCount);
1813 maskCursor = mask;
1814 dataCursor = maskCursor + masklen;
1815 remDataSize = dataSize - masklen;
1816 bits = 0;
1817
1818 for (row = pchgP->StartLine; changedLineCt > 0 && row < 0; ++row) {
1819 if (bits == 0) {
1820 if (masklen == 0) goto fail2;
1821 thismask = *maskCursor++;
1822 --masklen;
1823 bits = 8;
1824 }
1825 if (thismask & (1<<7)) {
1826 if (remDataSize < 2) goto fail;
1827 else {
1828 unsigned int const changeCt16 = *dataCursor++;
1829 unsigned int const changeCt32 = *dataCursor++;
1830 unsigned int const changeCt = changeCt16 + changeCt32;
1831
1832 unsigned int i;
1833
1834 remDataSize -= 2;
1835
1836 for (i = 0; i < changeCt; ++i) {
1837 if (totalChangeCt >= pchgP->TotalChanges) goto fail;
1838 if (remDataSize < 2) goto fail;
1839 else {
1840 unsigned short const smallChange =
1841 BIG_WORD(dataCursor);
1842
1843 dataCursor += 2; remDataSize -= 2;
1844
1845 reg = ((smallChange & 0xf000) >> 12) +
1846 (i >= changeCt ? 16 : 0);
1847 cmapP->mp_init[reg - pchgP->MinReg].reg = reg;
1848 cmapP->mp_init[reg - pchgP->MinReg].r =
1849 ((smallChange & 0x0f00) >> 8) * FACTOR_4BIT;
1850 cmapP->mp_init[reg - pchgP->MinReg].g =
1851 ((smallChange & 0x00f0) >> 4) * FACTOR_4BIT;
1852 cmapP->mp_init[reg - pchgP->MinReg].b =
1853 ((smallChange & 0x000f) >> 0) * FACTOR_4BIT;
1854 ++totalChangeCt;
1855 }
1856 }
1857 --changedLineCt;
1858 }
1859 }
1860 thismask <<= 1;
1861 --bits;
1862 }
1863
1864 for (row = pchgP->StartLine;
1865 changedLineCt > 0 && row < cmapP->mp_rows;
1866 ++row) {
1867 if (bits == 0) {
1868 if (masklen == 0) goto fail2;
1869 thismask = *maskCursor++;
1870 --masklen;
1871 bits = 8;
1872 }
1873 if (thismask & (1<<7)) {
1874 if (remDataSize < 2) goto fail;
1875 else {
1876 unsigned int const changeCt16 = *dataCursor++;
1877 unsigned int const changeCt32 = *dataCursor++;
1878 unsigned int const changeCt = changeCt16 + changeCt32;
1879
1880 unsigned int i;
1881
1882 remDataSize -= 2;
1883
1884 MALLOCARRAY_NOFAIL(cmapP->mp_change[row], changeCt + 1);
1885 for (i = 0; i < changeCt; ++i) {
1886 if (totalChangeCt >= pchgP->TotalChanges) goto fail;
1887 if (remDataSize < 2) goto fail;
1888 else {
1889 unsigned short const smallChange =
1890 BIG_WORD(dataCursor);
1891
1892 dataCursor += 2; remDataSize -= 2;
1893 reg = ((smallChange & 0xf000) >> 12) +
1894 (i >= changeCt16 ? 16 : 0);
1895 cmapP->mp_change[row][i].reg = reg;
1896 cmapP->mp_change[row][i].r =
1897 ((smallChange & 0x0f00) >> 8) * FACTOR_4BIT;
1898 cmapP->mp_change[row][i].g =
1899 ((smallChange & 0x00f0) >> 4) * FACTOR_4BIT;
1900 cmapP->mp_change[row][i].b =
1901 ((smallChange & 0x000f) >> 0) * FACTOR_4BIT;
1902 ++totalChangeCt;
1903 }
1904 }
1905 cmapP->mp_change[row][changeCt].reg = MP_REG_END;
1906 --changedLineCt;
1907 }
1908 }
1909 thismask <<= 1;
1910 --bits;
1911 }
1912 if (totalChangeCt != pchgP->TotalChanges)
1913 pm_message("warning - got %u change structures, "
1914 "chunk header reports %ld",
1915 totalChangeCt, pchgP->TotalChanges);
1916 return;
1917 fail:
1918 pm_error("insufficient data in SmallLineChanges structures");
1919 fail2:
1920 pm_error("insufficient data in line mask");
1921 }
1922
1923
1924
1925 static void
1926 PCHG_ConvertBig(PCHGHeader * const PCHG,
1927 ColorMap * const cmap,
1928 unsigned char * const maskStart,
1929 unsigned long const datasize) {
1930
1931 unsigned char * data;
1932 unsigned char thismask;
1933 int bits;
1934 unsigned int row;
1935 int changes;
1936 int masklen;
1937 int reg;
1938 unsigned long totalchanges;
1939 int changedlines;
1940 unsigned long remDataSize;
1941 unsigned char * mask;
1942
1943 mask = maskStart; /* initial value */
1944 remDataSize = datasize; /* initial value */
1945 changedlines = PCHG->ChangedLines; /* initial value */
1946 totalchanges = 0; /* initial value */
1947
1948 masklen = 4 * MaskLongWords(PCHG->LineCount);
1949 data = mask + masklen; remDataSize -= masklen;
1950
1951 for (row = PCHG->StartLine, bits = 0; changedlines && row < 0; ++row) {
1952 if (bits == 0) {
1953 if (masklen == 0)
1954 pm_error("insufficient data in line mask");
1955 thismask = *mask++;
1956 --masklen;
1957 bits = 8;
1958 }
1959 if (thismask & (1<<7)) {
1960 unsigned int i;
1961
1962 if (remDataSize < 2)
1963 pm_error("insufficient data in BigLineChanges structures");
1964
1965 changes = BIG_WORD(data); data += 2; remDataSize -= 2;
1966
1967 for (i = 0; i < changes; ++i) {
1968 if (totalchanges >= PCHG->TotalChanges)
1969 pm_error("insufficient data in BigLineChanges structures");
1970
1971 if (remDataSize < 6)
1972 pm_error("insufficient data in BigLineChanges structures");
1973
1974 reg = BIG_WORD(data); data += 2;
1975 cmap->mp_init[reg - PCHG->MinReg].reg = reg;
1976 ++data; /* skip alpha */
1977 cmap->mp_init[reg - PCHG->MinReg].r = *data++;
1978 cmap->mp_init[reg - PCHG->MinReg].b = *data++; /* yes, RBG */
1979 cmap->mp_init[reg - PCHG->MinReg].g = *data++;
1980 remDataSize -= 6;
1981 ++totalchanges;
1982 }
1983 --changedlines;
1984 }
1985 thismask <<= 1;
1986 --bits;
1987 }
1988
1989 for (row = PCHG->StartLine; changedlines && row < cmap->mp_rows; ++row) {
1990 if (bits == 0) {
1991 if (masklen == 0)
1992 pm_error("insufficient data in line mask");
1993
1994 thismask = *mask++;
1995 --masklen;
1996 bits = 8;
1997 }
1998 if (thismask & (1<<7)) {
1999 unsigned int i;
2000
2001 if (remDataSize < 2)
2002 pm_error("insufficient data in BigLineChanges structures");
2003
2004 changes = BIG_WORD(data); data += 2; remDataSize -= 2;
2005
2006 MALLOCARRAY_NOFAIL(cmap->mp_change[row], changes + 1);
2007 for (i = 0; i < changes; ++i) {
2008 if (totalchanges >= PCHG->TotalChanges)
2009 pm_error("insufficient data in BigLineChanges structures");
2010
2011 if (remDataSize < 6)
2012 pm_error("insufficient data in BigLineChanges structures");
2013
2014 reg = BIG_WORD(data); data += 2;
2015 cmap->mp_change[row][i].reg = reg;
2016 ++data; /* skip alpha */
2017 cmap->mp_change[row][i].r = *data++;
2018 cmap->mp_change[row][i].b = *data++; /* yes, RBG */
2019 cmap->mp_change[row][i].g = *data++;
2020 remDataSize -= 6;
2021 ++totalchanges;
2022 }
2023 cmap->mp_change[row][changes].reg = MP_REG_END;
2024 --changedlines;
2025 }
2026 thismask <<= 1;
2027 --bits;
2028 }
2029 if (totalchanges != PCHG->TotalChanges)
2030 pm_message("warning - got %ld change structures, "
2031 "chunk header reports %ld",
2032 totalchanges, PCHG->TotalChanges);
2033 }
2034
2035
2036
2037 static void
2038 read_pchg(FILE * const ifP,
2039 IFF_ID const iffid,
2040 long const chunksize,
2041 ColorMap * const cmapP) {
2042
2043 if (cmapP->mp_type >= MP_TYPE_PCHG ) {
2044 skip_chunk(ifP, iffid, chunksize);
2045 } else {
2046 PCHGHeader PCHG;
2047 unsigned char * data;
2048 unsigned long datasize;
2049 unsigned long remainingChunksize;
2050 int i;
2051
2052 if (cmapP->mp_type)
2053 multi_free(cmapP);
2054 cmapP->mp_type = MP_TYPE_PCHG;
2055
2056 remainingChunksize = chunksize; /* initial value */
2057
2058 PCHG.Compression = get_big_short(ifP, iffid, &remainingChunksize);
2059 PCHG.Flags = get_big_short(ifP, iffid, &remainingChunksize);
2060 PCHG.StartLine = get_big_short(ifP, iffid, &remainingChunksize);
2061 PCHG.LineCount = get_big_short(ifP, iffid, &remainingChunksize);
2062 PCHG.ChangedLines= get_big_short(ifP, iffid, &remainingChunksize);
2063 PCHG.MinReg = get_big_short(ifP, iffid, &remainingChunksize);
2064 PCHG.MaxReg = get_big_short(ifP, iffid, &remainingChunksize);
2065 PCHG.MaxChanges = get_big_short(ifP, iffid, &remainingChunksize);
2066 PCHG.TotalChanges= get_big_long (ifP, iffid, &remainingChunksize);
2067
2068 #ifdef DEBUG
2069 pm_message("PCHG StartLine : %d", PCHG.StartLine);
2070 pm_message("PCHG LineCount : %d", PCHG.LineCount);
2071 pm_message("PCHG ChangedLines: %d", PCHG.ChangedLines);
2072 pm_message("PCHG TotalChanges: %d", PCHG.TotalChanges);
2073 #endif
2074
2075 if (PCHG.Compression != PCHG_COMP_NONE) {
2076 PCHGCompHeader CompHdr;
2077 unsigned char * compdata;
2078 unsigned char * comptree;
2079 long treesize, compsize;
2080
2081 CompHdr.CompInfoSize =
2082 get_big_long(ifP, iffid, &remainingChunksize);
2083 CompHdr.OriginalDataSize =
2084 get_big_long(ifP, iffid, &remainingChunksize);
2085
2086 treesize = CompHdr.CompInfoSize;
2087 MALLOCARRAY_NOFAIL(comptree, treesize);
2088 read_bytes(ifP, treesize, comptree, iffid, &remainingChunksize);
2089
2090 compsize = remainingChunksize;
2091 MALLOCARRAY_NOFAIL(compdata, compsize);
2092 read_bytes(ifP, compsize, compdata, iffid, &remainingChunksize);
2093
2094 datasize = CompHdr.OriginalDataSize;
2095 MALLOCARRAY_NOFAIL(data, datasize);
2096 PCHG_Decompress(&PCHG, &CompHdr, compdata,
2097 compsize, comptree, data);
2098
2099 free(comptree);
2100 free(compdata);
2101 } else {
2102 #ifdef DEBUG
2103 pm_message("uncompressed PCHG");
2104 #endif
2105 datasize = remainingChunksize;
2106 MALLOCARRAY_NOFAIL(data, datasize);
2107 read_bytes(ifP, datasize, data, iffid, &remainingChunksize);
2108 }
2109
2110 if (PCHG.Flags & PCHGF_USE_ALPHA)
2111 pm_message("warning - ignoring PCHG alpha channel because "
2112 "this program doesn't know what to do with it");
2113
2114 cmapP->mp_rows = PCHG.StartLine + PCHG.LineCount;
2115 MALLOCARRAY_NOFAIL(cmapP->mp_change, cmapP->mp_rows);
2116 for (i = 0; i < cmapP->mp_rows; ++i)
2117 cmapP->mp_change[i] = NULL;
2118
2119 if (PCHG.StartLine < 0) {
2120 if (PCHG.MaxReg < PCHG.MinReg)
2121 pm_error("PCHG chunk says maxreg (%u) "
2122 "is less than minreg (%u)",
2123 PCHG.MaxReg, PCHG.MinReg);
2124 else {
2125 unsigned int const nch = PCHG.MaxReg - PCHG.MinReg + 1;
2126
2127 unsigned int i;
2128
2129 MALLOCARRAY_NOFAIL(cmapP->mp_init, nch + 1);
2130
2131 for (i = 0; i < nch; ++i)
2132 cmapP->mp_init[i].reg = MP_REG_IGNORE;
2133
2134 cmapP->mp_init[nch].reg = MP_REG_END;
2135 }
2136 }
2137
2138 if (PCHG.Flags & PCHGF_12BIT) {
2139 #ifdef DEBUG
2140 pm_message("SmallLineChanges");
2141 #endif
2142 PCHG_ConvertSmall(&PCHG, cmapP, data, datasize);
2143 }
2144 else {
2145 if (PCHG.Flags & PCHGF_32BIT) {
2146 #ifdef DEBUG
2147 pm_message("BigLineChanges");
2148 #endif
2149 PCHG_ConvertBig(&PCHG, cmapP, data, datasize);
2150 } else
2151 pm_error("unknown palette changes structure "
2152 "format in %s chunk",
2153 ID2string(iffid));
2154 }
2155 free(data);
2156 chunk_end(ifP, iffid, remainingChunksize);
2157 }
2158 }
2159
2160
2161
2162 static bool
2163 ignored_iffid(IFF_ID const iffid,
2164 IFF_ID const ignorelist[],
2165 unsigned int const ignorecount) {
2166
2167 bool ignore;
2168
2169 unsigned int i;
2170 ignore = FALSE; /* initial assumption */
2171 for( i = 0; i < ignorecount && !ignore; i++ ) {
2172 if( iffid == ignorelist[i] )
2173 ignore = TRUE;
2174 }
2175 return ignore;
2176 }
2177
2178
2179
2180 static void
2181 process_body( FILE * const ifP,
2182 long const chunksize,
2183 BitMapHeader * const bmhdP,
2184 ColorMap * const cmap,
2185 FILE * const maskfile,
2186 int const fakeviewport,
2187 int const isdeepopt,
2188 DirectColor * const dcol,
2189 int * const viewportmodesP) {
2190
2191 if (bmhdP == NULL)
2192 pm_error("%s chunk without %s chunk",
2193 ID2string(ID_BODY), ID2string(ID_BMHD));
2194
2195 prepareCmap(bmhdP, cmap);
2196
2197 pixelrow = ppm_allocrow(bmhdP->w);
2198 if (maskfile) {
2199 maskrow = pbm_allocrow(bmhdP->w);
2200 pbm_writepbminit(maskfile, bmhdP->w, bmhdP->h, 0);
2201 }
2202
2203 if (typeid == ID_ILBM) {
2204 int isdeep;
2205
2206 MALLOCARRAY_NOFAIL(ilbmrow, ilbm_rowByteCt(bmhdP->w));
2207 *viewportmodesP |= fakeviewport; /* -isham/-isehb */
2208
2209 if( isdeepopt > 0 && (bmhdP->nPlanes % 3 != 0) ) {
2210 pm_message("cannot interpret %d-plane image as 'deep' "
2211 "(# of planes must be divisible by 3)",
2212 bmhdP->nPlanes);
2213 isdeep = 0;
2214 } else
2215 isdeep = isdeepopt;
2216
2217 if (isdeep > 0)
2218 deep_to_ppm(ifP, chunksize, bmhdP, cmap);
2219 else if (dcol)
2220 dcol_to_ppm(ifP, chunksize, bmhdP, cmap, dcol);
2221 else if (bmhdP->nPlanes > 8) {
2222 if (bmhdP->nPlanes <= 16 && HAS_COLORMAP(cmap))
2223 std_to_ppm(ifP, chunksize, bmhdP, cmap, *viewportmodesP);
2224 else if (isdeep >= 0 && (bmhdP->nPlanes % 3 == 0))
2225 deep_to_ppm(ifP, chunksize, bmhdP, cmap);
2226 else if (bmhdP->nPlanes <= 16)
2227 /* will be interpreted as grayscale */
2228 std_to_ppm(ifP, chunksize, bmhdP, cmap, *viewportmodesP);
2229 else
2230 pm_error("don't know how to interpret %d-plane image",
2231 bmhdP->nPlanes);
2232 } else
2233 std_to_ppm(ifP, chunksize, bmhdP, cmap, *viewportmodesP);
2234 } else if( typeid == ID_PBM )
2235 ipbm_to_ppm(ifP, chunksize, bmhdP, cmap, *viewportmodesP);
2236 else /* RGBN or RGB8 */
2237 rgbn_to_ppm(ifP, chunksize, bmhdP, cmap);
2238 }
2239
2240
2241
2242 static void
2243 processChunk(FILE * const ifP,
2244 long const formsize,
2245 IFF_ID const ignorelist[],
2246 unsigned int const ignorecount,
2247 int const fakeviewport,
2248 int const viewportmask,
2249 int const isdeepopt,
2250 bool const cmaponly,
2251 bool * const bodyChunkProcessedP,
2252 bool * const endchunkP,
2253 BitMapHeader ** const bmhdP,
2254 ColorMap * const cmap,
2255 DirectColor ** const dcolP,
2256 int * const viewportmodesP,
2257 long * const bytesReadP
2258 ) {
2259
2260 IFF_ID iffid;
2261 long chunksize;
2262 long bytesread;
2263
2264 bytesread = 0;
2265
2266 iffid = get_big_long(ifP, ID_FORM, NULL);
2267 chunksize = get_big_long(ifP, iffid, NULL);
2268 bytesread += 8;
2269
2270 if (debug)
2271 pm_message("reading %s chunk: %ld bytes", ID2string(iffid), chunksize);
2272
2273 if (ignored_iffid(iffid, ignorelist, ignorecount)) {
2274 pm_message("ignoring %s chunk", ID2string(iffid));
2275 skip_chunk(ifP, iffid, chunksize);
2276 } else if (iffid == ID_END) {
2277 /* END chunks are not officially valid in IFF, but
2278 suggested as a future expansion for stream-writing,
2279 see Amiga RKM Devices, 3rd Ed, page 376
2280 */
2281 if (chunksize != 0 ) {
2282 pm_message("warning - non-0 %s chunk", ID2string(iffid));
2283 skip_chunk(ifP, iffid, chunksize);
2284 }
2285 if (formsize != 0xffffffff)
2286 pm_message("warning - %s chunk with FORM size 0x%08lx "
2287 "(should be 0x%08x)",
2288 ID2string(iffid), formsize, 0xffffffff);
2289 *endchunkP = 1;
2290 } else if (*bodyChunkProcessedP) {
2291 pm_message("%s chunk found after %s chunk - skipping",
2292 ID2string(iffid), ID2string(ID_BODY));
2293 skip_chunk(ifP, iffid, chunksize);
2294 } else
2295 switch (iffid) {
2296 case ID_BMHD:
2297 *bmhdP = read_bmhd(ifP, iffid, chunksize);
2298 break;
2299 case ID_CMAP:
2300 read_cmap(ifP, iffid, chunksize, cmap);
2301 break;
2302 case ID_CMYK:
2303 read_cmyk(ifP, iffid, chunksize, cmap);
2304 break;
2305 case ID_CLUT:
2306 read_clut(ifP, iffid, chunksize, cmap);
2307 break;
2308 case ID_CAMG:
2309 if (chunksize != CAMGChunkSize)
2310 pm_error("%s chunk size mismatch", ID2string(iffid));
2311 *viewportmodesP = get_big_long(ifP, ID_CAMG, NULL);
2312 *viewportmodesP &= viewportmask; /* -isnotham/-isnotehb */
2313 break;
2314 case ID_PCHG:
2315 read_pchg(ifP, iffid, chunksize, cmap);
2316 break;
2317 case ID_CTBL:
2318 case ID_SHAM:
2319 read_4bit_mp(ifP, iffid, chunksize, cmap);
2320 break;
2321 case ID_DCOL:
2322 if (chunksize != DirectColorSize)
2323 pm_error("%s chunk size mismatch", ID2string(iffid));
2324 MALLOCVAR_NOFAIL(*dcolP);
2325 (*dcolP)->r = get_byte(ifP, iffid, NULL);
2326 (*dcolP)->g = get_byte(ifP, iffid, NULL);
2327 (*dcolP)->b = get_byte(ifP, iffid, NULL);
2328 get_byte(ifP, iffid, NULL); /* skip pad byte */
2329 break;
2330 case ID_BODY:
2331 if (cmaponly || (*bmhdP && (*bmhdP)->nPlanes == 0))
2332 skip_chunk(ifP, ID_BODY, chunksize);
2333 else {
2334 process_body(ifP, chunksize, *bmhdP, cmap,
2335 maskfile, fakeviewport, isdeepopt, *dcolP,
2336 viewportmodesP);
2337
2338 *bodyChunkProcessedP = TRUE;
2339 } break;
2340 case ID_GRAB: case ID_DEST: case ID_SPRT: case ID_CRNG:
2341 case ID_CCRT: case ID_DYCP: case ID_DPPV: case ID_DRNG:
2342 case ID_EPSF: case ID_JUNK: case ID_CNAM: case ID_PRVW:
2343 case ID_TINY: case ID_DPPS:
2344 skip_chunk(ifP, iffid, chunksize);
2345 break;
2346 case ID_copy: case ID_AUTH: case ID_NAME: case ID_ANNO:
2347 case ID_TEXT: case ID_FVER:
2348 if (verbose)
2349 display_chunk(ifP, iffid, chunksize);
2350 else
2351 skip_chunk(ifP, iffid, chunksize);
2352 break;
2353 case ID_DPI: {
2354 int x, y;
2355
2356 x = get_big_short(ifP, ID_DPI, NULL);
2357 y = get_big_short(ifP, ID_DPI, NULL);
2358 if (verbose)
2359 pm_message("%s chunk: dpi_x = %d dpi_y = %d",
2360 ID2string(ID_DPI), x, y);
2361 } break;
2362 default:
2363 pm_message("unknown chunk type %s - skipping",
2364 ID2string(iffid));
2365 skip_chunk(ifP, iffid, chunksize);
2366 break;
2367 }
2368
2369 bytesread += chunksize;
2370
2371 if (ODD(chunksize)) {
2372 get_byte(ifP, iffid, NULL);
2373 bytesread += 1;
2374 }
2375 *bytesReadP = bytesread;
2376 }
2377
2378
2379
2380 static void
2381 maybeWriteColorMap(FILE * const ofP,
2382 const BitMapHeader * const bmhdP,
2383 ColorMap * const cmapP,
2384 bool const bodyChunkProcessed,
2385 bool const cmaponly) {
2386 /*----------------------------------------------------------------------------
2387 Write to file *ofP the color map *cmapP as a PPM, if appropriate.
2388
2389 The logic (not just here -- in the program as a whole) for deciding whether
2390 to write the image or the colormap is quite twisted. If I thought anyone
2391 was actually using this program, I would take the time to straighten it
2392 out.
2393
2394 What's really sick about this subroutine is that in choosing to write
2395 a color map, it has to know that Caller hasn't already written
2396 the image. Huge modularity violation.
2397 -----------------------------------------------------------------------------*/
2398 if (cmaponly) {
2399 if (HAS_COLORMAP(cmapP)) {
2400 prepareCmap(bmhdP, cmapP);
2401 cmapToPpm(ofP, cmapP);
2402 } else
2403 pm_error("You specified -cmaponly, but the ILBM "
2404 "has no colormap");
2405 } else if (bmhdP && bmhdP->nPlanes == 0) {
2406 if (HAS_COLORMAP(cmapP)) {
2407 prepareCmap(bmhdP, cmapP);
2408 cmapToPpm(ofP, cmapP);
2409 } else
2410 pm_error("ILBM has neither a color map nor color planes");
2411 } else if (!bodyChunkProcessed) {
2412 if (HAS_COLORMAP(cmapP)) {
2413 pm_message("input is a colormap file");
2414 prepareCmap(bmhdP, cmapP);
2415 cmapToPpm(ofP, cmapP);
2416 } else
2417 pm_error("ILBM has neither %s or %s chunk",
2418 ID2string(ID_BODY), ID2string(ID_CMAP));
2419 }
2420 }
2421
2422
2423
2424 int
2425 main(int argc, char *argv[]) {
2426
2427 FILE * ifP;
2428 int argn;
2429 short cmaponly = 0, isdeepopt = 0;
2430 bool endchunk;
2431 bool bodyChunkProcessed;
2432 long formsize, bytesread;
2433 int viewportmodes = 0, fakeviewport = 0, viewportmask;
2434 IFF_ID firstIffid;
2435 BitMapHeader *bmhdP = NULL;
2436 ColorMap * cmap;
2437 DirectColor *dcol = NULL;
2438 #define MAX_IGNORE 16
2439 IFF_ID ignorelist[MAX_IGNORE];
2440 int ignorecount = 0;
2441 char *maskname;
2442 const char * const usage =
2443 "[-verbose] [-ignore <chunkID> [-ignore <chunkID>] ...] "
2444 "[-isham|-isehb|-isdeep|-isnotham|-isnotehb|-isnotdeep] "
2445 "[-cmaponly] [-adjustcolors] "
2446 "[-transparent <color>] [-maskfile <filename>] [ilbmfile]";
2447 ppm_init(&argc, argv);
2448
2449 viewportmask = 0xffffffff;
2450
2451 argn = 1;
2452 while( argn < argc && argv[argn][0] == '-' && argv[argn][1] != '\0' ) {
2453 if( pm_keymatch(argv[argn], "-verbose", 2) )
2454 verbose = 1;
2455 else if( pm_keymatch(argv[argn], "-noverbose", 4) )
2456 verbose = 0;
2457 else if( pm_keymatch(argv[argn], "-isham", 4) )
2458 fakeviewport |= vmHAM;
2459 else if( pm_keymatch(argv[argn], "-isehb", 4) )
2460 fakeviewport |= vmEXTRA_HALFBRITE;
2461 else if( pm_keymatch(argv[argn], "-isdeep", 4) )
2462 isdeepopt = 1;
2463 else if( pm_keymatch(argv[argn], "-isnotham", 7) )
2464 viewportmask &= ~(vmHAM);
2465 else if( pm_keymatch(argv[argn], "-isnotehb", 7) )
2466 viewportmask &= ~(vmEXTRA_HALFBRITE);
2467 else if( pm_keymatch(argv[argn], "-isnotdeep", 7) )
2468 isdeepopt = -1;
2469 else if( pm_keymatch(argv[argn], "-cmaponly", 2) )
2470 cmaponly = 1;
2471 else if( pm_keymatch(argv[argn], "-adjustcolors", 2) )
2472 adjustcolors = 1;
2473 else if( pm_keymatch(argv[argn], "-noadjustcolors", 4) )
2474 adjustcolors = 0;
2475 else if( pm_keymatch(argv[argn], "-transparent", 2) ) {
2476 if( ++argn >= argc )
2477 pm_usage(usage);
2478 transpName = argv[argn];
2479 } else if( pm_keymatch(argv[argn], "-maskfile", 2) ) {
2480 if( ++argn >= argc )
2481 pm_usage(usage);
2482 maskname = argv[argn];
2483 maskfile = pm_openw(maskname);
2484 } else if( pm_keymatch(argv[argn], "-ignore", 2) ) {
2485 if( ++argn >= argc )
2486 pm_usage(usage);
2487 if( strlen(argv[argn]) != 4 )
2488 pm_error("'-ignore' option needs a 4 byte chunk ID string "
2489 "as argument");
2490 if( ignorecount >= MAX_IGNORE )
2491 pm_error("max %d chunk IDs to ignore", MAX_IGNORE);
2492 ignorelist[ignorecount++] =
2493 MAKE_ID(argv[argn][0], argv[argn][1], argv[argn][2],
2494 argv[argn][3]);
2495 } else
2496 pm_usage(usage);
2497 ++argn;
2498 }
2499
2500 if( argn < argc ) {
2501 ifP = pm_openr( argv[argn] );
2502 argn++;
2503 } else
2504 ifP = stdin;
2505
2506 if( argn != argc )
2507 pm_usage(usage);
2508
2509 wrotemask = false; /* initial value */
2510
2511 /* Read in the ILBM file. */
2512
2513 firstIffid = get_big_long(ifP, ID_FORM, NULL);
2514 if (firstIffid != ID_FORM)
2515 pm_error("input is not a FORM type IFF file");
2516 formsize = get_big_long(ifP, ID_FORM, NULL);
2517 typeid = get_big_long(ifP, ID_FORM, NULL);
2518 if (typeid != ID_ILBM && typeid != ID_RGBN && typeid != ID_RGB8 &&
2519 typeid != ID_PBM)
2520 pm_error("input is not an ILBM, RGBN, RGB8 or PBM "
2521 "type FORM IFF file");
2522 bytesread = 4; /* FORM and formsize do not count */
2523
2524 cmap = alloc_cmap();
2525
2526 /* Main loop, parsing the IFF FORM. */
2527 bodyChunkProcessed = FALSE;
2528 endchunk = FALSE;
2529 while (!endchunk && formsize-bytesread >= 8) {
2530 long bytesReadForChunk;
2531
2532 processChunk(ifP, formsize, ignorelist, ignorecount,
2533 fakeviewport, viewportmask,
2534 isdeepopt, cmaponly,
2535 &bodyChunkProcessed,
2536 &endchunk, &bmhdP, cmap, &dcol,
2537 &viewportmodes, &bytesReadForChunk);
2538
2539 bytesread += bytesReadForChunk;
2540 }
2541
2542 if (maskfile) {
2543 pm_close(maskfile);
2544 if (!wrotemask)
2545 remove(maskname);
2546 pbm_freerow(maskrow);
2547 }
2548
2549 maybeWriteColorMap(stdout, bmhdP, cmap, bodyChunkProcessed, cmaponly);
2550
2551 {
2552 unsigned int skipped;
2553
2554 for (skipped = 0; fgetc(ifP) != EOF; ++skipped)
2555 ++bytesread;
2556
2557 if (skipped > 0)
2558 pm_message("skipped %u extraneous byte%s after last chunk",
2559 skipped, (skipped == 1 ? "" : "s"));
2560 }
2561 pm_close(ifP);
2562
2563 if (!endchunk && bytesread != formsize) {
2564 pm_message("warning - file length/FORM size field mismatch "
2565 "(%ld != %ld+8)",
2566 bytesread+8 /* FORM+size */, formsize);
2567 }
2568
2569 return 0;
2570 }
2571
2572
2573