Debian Codegraph @

converter/other/pnmtotiffcmyk.c

raw
1 /*
2
3 CMYKTiff - pnmtotiffcmyk - conversion from a pnm file to a CMYK
4 encoded tiff file.
5
6 Copyright (C) 1999 Andrew Cooke (Jara Software)
7
8 Comments to [email protected]
9
10 This program is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 2 of the License, or (at
13 your option) any later version.
14
15 This program is distributed in the hope that it will be useful, but
16 WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 General Public License for more details.
19
20 You should have received a copy of the GNU General Public License
21 along with this program; if not, write to the Free Software
22 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
23 USA
24
25 These conditions also apply to any other files distributed with the
26 program that describe / document the CMYKTiff package.
27
28
29 Much of the code uses ideas from other pnm programs, written by Jef
30 Poskanzer (thanks go to him and libtiff maintainer Sam Leffler). A
31 small section of the code - some of the tiff tag settings - is derived
32 directly from pnmtotiff, by Jef Poskanzer, which, in turn,
33 acknowledges Patrick Naughton with the following text:
34
35 ** Derived by Jef Poskanzer from ras2tif.c, which is:
36 **
37 ** Copyright (c) 1990 by Sun Microsystems, Inc.
38 **
39 ** Author: Patrick J. Naughton
40 ** [email protected]
41 **
42 ** Permission to use, copy, modify, and distribute this software and its
43 ** documentation for any purpose and without fee is hereby granted,
44 ** provided that the above copyright notice appear in all copies and that
45 ** both that copyright notice and this permission notice appear in
46 ** supporting documentation.
47 **
48 ** This file is provided AS IS with no warranties of any kind. The author
49 ** shall have no liability with respect to the infringement of copyrights,
50 ** trade secrets or any patents by this file or any part thereof. In no
51 ** event will the author be liable for any lost revenue or profits or
52 ** other special, indirect and consequential damages.
53
54 Software copyrights will soon need family trees... :-)
55
56 */
57
58 #define _XOPEN_SOURCE
59
60 #include <string.h>
61 #include <math.h>
62 /* float.h used to be included only if __osf__ was defined. On some
63 platforms, float.h is also included automatically by math.h. But at
64 least on Solaris, it isn't. 00.04.25.
65 */
66 #include <float.h>
67 #include <limits.h>
68 #include <fcntl.h>
69 /* See warning about tiffio.h in pamtotiff.c */
70 #include <tiffio.h>
71
72 #include "pm_c_util.h"
73 #include "nstring.h"
74 #include "pnm.h"
75
76 /* first release after testing */
77 /* second release after testing - small mods to netpbm package */
78 #define VERSION 1.01
79
80 /* only support 8 bit values */
81 #define MAXTIFFBITS 8
82 #define MAXTIFFVAL 255
83
84
85 /* definitions for error values */
86
87 typedef int Err ;
88
89 #define ERR_OK 0 /* no error */
90 #define ERR_PNM 1 /* thrown by pnm library */
91 #define ERR_MEMORY 2 /* could not allocate memory */
92 #define ERR_ARG 3 /* unexpected argument */
93 #define ERR_TIFF 4 /* failure in tiff library */
94 #define ERR_HELP 5 /* terminate with -help */
95
96 /* definitions for command line options */
97
98 #define UNSET 2 /* Simple->remove value when gammap not set */
99 #define K_NORMAL 0
100 #define K_REMOVE 1
101 #define K_ONLY 2
102
103
104 /* definitions for conversion calculations */
105
106 /* catch rounding errors to outside 0-1 range */
107 #define LIMIT01(x) MAX( 0.0, MIN( 1.0, (x) ) )
108 /* convert from 0-1 to 0-maxOut */
109 #define TOMAX(x) MAX( 0, MIN( rt->maxOut, (int)(rt->maxOut * (x)) ) )
110 #define TINY FLT_EPSILON
111 #ifndef PI
112 #define PI 3.1415926
113 #endif
114 #define ONETWENTY ( 2.0 * PI / 3.0 )
115 #define TWOFORTY ( 4.0 * PI / 3.0 )
116 #define THREESIXTY ( 2.0 * PI )
117 /* expand from 0-90 to 0-120 degrees */
118 #define EXPAND(x) ( 4.0 * ( x ) / 3.0 )
119 /* contract from 0-120 to 0-90 degrees */
120 #define CONTRACT(x) ( 3.0 * ( x ) / 4.0 )
121
122
123
124 /* --- main structure for the process ----------------- */
125
126 struct tagIn ;
127 struct tagConv ;
128 struct tagOut ;
129
130 typedef struct {
131 struct tagIn *in ;
132 struct tagConv *conv ;
133 struct tagOut *out ;
134 int nCols ;
135 int nRows ;
136 int maxOut ;
137 const char *name ;
138 } Root ;
139
140
141
142 /* --- utils ------------------------------------------ */
143
144
145 /* parse an arg with a float value. name should be the full key name,
146 preceded by '-' */
147 static Err
148 floatArg( float *arg, const char *name, int size, float lo, float hi,
149 int *argn, int argc, char **argv ) {
150
151 char extra ;
152 int count ;
153
154 if ( pm_keymatch( argv[*argn], name, size ) ) {
155 if ( ++(*argn) == argc ) {
156 fprintf( stderr, "no value for %s\n", name ) ;
157 return ERR_ARG ;
158 }
159 if ( ! (count = sscanf( argv[*argn], "%f%1c", arg, &extra )) ) {
160 fprintf( stderr, "cannot parse %s for %s\n", argv[*argn], name ) ;
161 return ERR_ARG ;
162 }
163 if ( count > 1 ) {
164 fprintf( stderr, "warning: ignored %c... in value for %s\n",
165 extra, name ) ;
166 }
167 if ( *arg > hi || *arg < lo ) {
168 fprintf( stderr, "%s (%f) must be in range %f to %f\n",
169 name, *arg, lo, hi ) ;
170 return ERR_ARG ;
171 }
172 ++(*argn) ;
173 }
174
175 return ERR_OK ;
176 }
177
178
179
180 /* parse an arg with a long value. name should be the full key name,
181 preceded by '-' */
182 static Err
183 longArg( long *arg, const char *name, int size, long lo, long hi,
184 int *argn, int argc, char **argv ) {
185
186 char extra ;
187 int count ;
188
189 if ( pm_keymatch( argv[*argn], name, size ) ) {
190 if ( ++(*argn) == argc ) {
191 fprintf( stderr, "no value for %s\n", name ) ;
192 return ERR_ARG ;
193 }
194 if ( ! (count = sscanf( argv[*argn], "%ld%1c", arg, &extra )) ) {
195 fprintf( stderr, "cannot parse %s for %s\n", argv[*argn], name ) ;
196 return ERR_ARG ;
197 }
198 if ( count > 1 ) {
199 fprintf( stderr, "warning: ignored %c... in value for %s\n",
200 extra, name ) ;
201 }
202 if ( *arg > hi || *arg < lo ) {
203 fprintf( stderr, "%s (%ld) must be in range %ld to %ld\n",
204 name, *arg, lo, hi ) ;
205 return ERR_ARG ;
206 }
207 ++(*argn) ;
208 }
209
210 return ERR_OK ;
211 }
212
213
214
215 /* print usage. for simplicity this routine is *not* split amongst
216 the various components - when you add a component (eg a new
217 conversion algorithm, or maybe new input or output code), you must
218 also change this routine. by keeping all the options in one place
219 it is also easier to calculate the minimum key name length (passed
220 to pnm_keymatch) */
221 static void
222 printUsage( ) {
223 fprintf( stderr, "\nusage: pnmtocmyk [Compargs] [Tiffargs] [Convargs] [pnmfile]\n" ) ;
224 fprintf( stderr, " Compargs: [-none|-packbits|-lzw [-predictor 1|-predictor 2]]\n" ) ;
225 fprintf( stderr, " Tiffargs: [-msb2lsb|-lsb2msb] [-rowsperstrip n]\n" ) ;
226 fprintf( stderr, " [-lowdotrange lo] [-highdotrange hi] [-knormal|-konly|-kremove]\n" ) ;
227 fprintf( stderr, " Convargs: [[-default] [Defargs]|-negative]\n" ) ;
228 fprintf( stderr, " Defargs: [-theta deg] [-gamma g] [-gammap -1|-gammap g]\n" ) ;
229 fprintf( stderr, "where 0 <= lo < hi <= 255; -360 < deg < 360; 0.1 < g < 10; 0 < n < INT_MAX\n\n" ) ;
230 fprintf( stderr, "returns: 0 OK; 1 pnm library error ; 2 memory error ; 3 unexpected arg ;\n" ) ;
231 fprintf( stderr, " 4 tiff library error ; 5 -help key used\n\n" ) ;
232 fprintf( stderr, "Convert a pnm file to a CMYK tiff file. Version %5.2f\n", VERSION ) ;
233 fprintf( stderr, "CMY under K will be removed unless -gammap -1 is used.\n" ) ;
234 fprintf( stderr, "(c) 1999 Andrew Cooke - Beta version, not for public use.\n" ) ;
235 fprintf( stderr, "No warranty.\n\n" ) ;
236 }
237
238
239
240 /* list of key args and number of significant letters required
241 -default 2
242 -gamma 6
243 -gammap 7
244 -highdotrange 2
245 -knormal 3
246 -konly 3
247 -kremove 3
248 -lowdotrange 3
249 -lsb2msb 3
250 -lzw 3
251 -msb2lsb 2
252 -negative 3
253 -none 3
254 -packbits 3
255 -predictor 3
256 -rowsperstrip 2
257 -theta 2
258 */
259
260
261
262 /* --- reading the input ------------------------------ */
263
264
265 /* encapsulate the file reader - uses pnm library at the moment, but
266 could be changed if we move to libtiff */
267
268 typedef Err OptIn( struct tagIn *conv, Root *r,
269 int *argn, int argc, char **argv ) ;
270 typedef int HasMore( struct tagIn *in ) ;
271 typedef Err Next( struct tagIn *in, float *r, float *g, float *b ) ;
272 typedef Err OpenIn( struct tagIn *in, Root *r ) ;
273 typedef void CloseIn( struct tagIn *in ) ;
274
275 typedef struct tagIn {
276 OptIn *opt ;
277 HasMore *hasMore ;
278 Next *next ;
279 OpenIn *open ;
280 CloseIn *close ;
281 void *private ;
282 } In ;
283
284
285 /* implementation for pnm files */
286
287 typedef struct {
288 FILE *in ;
289 int type ;
290 xelval maxVal ;
291 int maxPix ;
292 int iPix ;
293 xel *row ;
294 int maxRow ;
295 int iRow ;
296 } PnmIn ;
297
298
299 /* the only output option is the filename, which will be the last
300 argument, if it doesn't start with '-' */
301 static Err
302 pnmOpt( In *in, Root *r, int *argn, int argc, char **argv ) {
303 PnmIn *p = (PnmIn*)in->private ;
304 if ( *argn + 1 == argc && argv[*argn][0] != '\0' &&
305 argv[*argn][0] != '-' ) {
306 r->name = argv[(*argn)++] ;
307 p->in = pm_openr( r->name ) ;
308 }
309 return ERR_OK ;
310 }
311
312
313
314 /* free the row buffer when closing the input */
315 static void
316 pnmClose( In *in ) {
317 if ( in ) {
318 PnmIn *p = (PnmIn*)in->private ;
319 if ( p ) {
320 if ( p->row ) pnm_freerow( p->row ) ;
321 if ( p->in ) pm_close( p->in ) ;
322 free( p ) ;
323 }
324 }
325 }
326
327
328
329 /* open the file, storing dimensions both locally and in the global
330 root structure */
331 static Err
332 pnmOpen( In *in, Root *r ) {
333
334 PnmIn *p = (PnmIn*)in->private ;
335
336 if ( ! p->in ) p->in = stdin ;
337
338 pnm_readpnminit( p->in, &(r->nCols), &(r->nRows), &(p->maxVal),
339 &(p->type) ) ;
340 p->maxPix = r->nCols * r->nRows ;
341 p->iPix = 0 ;
342 p->maxRow = r->nCols ;
343 p->iRow = 0 ;
344 p->row = pnm_allocrow( p->maxRow ) ;
345
346 return ERR_OK ;
347 }
348
349
350
351 /* more data available? */
352 static int
353 pnmHasMore( In *in ) {
354 PnmIn *p = (PnmIn*)in->private ;
355 return p->iPix < p->maxPix ;
356 }
357
358
359
360 /* read next pixel - buffered by row. return values in range 0 to 1 */
361 static Err
362 pnmNext( In *in, float *r, float *g, float *b ) {
363
364 PnmIn *p = (PnmIn*)in->private ;
365 float m = (float)p->maxVal ;
366
367 if ( p->iPix == 0 || p->iRow == p->maxRow ) {
368 p->iRow = 0 ;
369 pnm_readpnmrow( p->in, p->row, p->maxRow, p->maxVal, p->type ) ;
370 }
371 if ( PNM_FORMAT_TYPE( p->type ) == PPM_TYPE ) {
372 *r = (float)PPM_GETR( p->row[p->iRow] ) / m ;
373 *g = (float)PPM_GETG( p->row[p->iRow] ) / m ;
374 *b = (float)PPM_GETB( p->row[p->iRow] ) / m ;
375 } else {
376 *r = *g = *b = (float)PNM_GET1( p->row[p->iRow] ) / m ;
377 }
378 ++(p->iRow) ;
379 ++(p->iPix) ;
380
381 return ERR_OK ;
382 }
383
384
385
386 /* build the input struct */
387 static Err
388 newPnmInput( In **in ) {
389 if ( ! (*in = (In*)calloc( 1, sizeof( In ) )) ) {
390 fprintf( stderr, "cannot allocate memory\n" ) ;
391 return ERR_MEMORY ;
392 }
393 (*in)->private = calloc( 1, sizeof( PnmIn ) ) ;
394 (*in)->opt = pnmOpt ;
395 (*in)->open = pnmOpen ;
396 (*in)->hasMore = pnmHasMore ;
397 (*in)->next = pnmNext ;
398 (*in)->close = pnmClose ;
399 return ERR_OK ;
400 }
401
402
403
404 /* --- writing the output ----------------------------- */
405
406
407 /* encapsulate file writing (will probably always use libtiff, but may
408 as well be consistent) */
409
410 typedef Err OptOut( struct tagOut *conv, Root *r,
411 int *argn, int argc, char **argv ) ;
412 typedef Err Write( struct tagOut *out, int c, int m, int y, int k ) ;
413 typedef Err OpenOut( struct tagOut *out, Root *r ) ;
414 typedef void CloseOut( struct tagOut *out ) ;
415
416 typedef struct tagOut {
417 OptOut *opt ;
418 Write *write ;
419 OpenOut *open ;
420 CloseOut *close ;
421 void *private ;
422 } Out ;
423
424
425 /* implementation for tiff files */
426
427 typedef struct {
428 tdata_t buffer;
429 tsize_t maxBuffer;
430 tsize_t iBuffer;
431 uint32_t iRow;
432 TIFF * tiff;
433 uint32_t rowsperstrip;
434 uint16_t compression;
435 uint16_t fillorder;
436 uint16_t predictor;
437 uint16_t lowdotrange;
438 uint16_t highdotrange;
439 int kFlag;
440 } TiffOut;
441
442
443 /* these options come from either the tiff 6.0 spec or the pnmtotiff
444 code */
445 static Err
446 tiffOpt( Out *out, Root* rt, int *argn, int argc, char **argv ) {
447
448 Err err ;
449 int oldn ;
450 long lVal ;
451 TiffOut *t = (TiffOut*)out->private ;
452
453 if ( pm_keymatch( argv[*argn], "-none", 3 ) ) {
454 t->compression = COMPRESSION_NONE ;
455 ++(*argn) ;
456 } else if ( pm_keymatch( argv[*argn], "-packbits", 3 ) ) {
457 t->compression = COMPRESSION_PACKBITS ;
458 ++(*argn) ;
459 } else if ( pm_keymatch( argv[*argn], "-lzw", 3 ) ) {
460 t->compression = COMPRESSION_LZW ;
461 ++(*argn) ;
462 } else if ( pm_keymatch( argv[*argn], "-msb2lsb", 2 ) ) {
463 t->fillorder = FILLORDER_MSB2LSB ;
464 ++(*argn) ;
465 } else if ( pm_keymatch( argv[*argn], "-lsb2msb", 3 ) ) {
466 t->fillorder = FILLORDER_LSB2MSB ;
467 ++(*argn) ;
468 } else if ( pm_keymatch( argv[*argn], "-knormal", 3 ) ) {
469 t->kFlag = K_NORMAL ;
470 ++(*argn) ;
471 } else if ( pm_keymatch( argv[*argn], "-kremove", 3 ) ) {
472 t->kFlag = K_REMOVE ;
473 ++(*argn) ;
474 } else if ( pm_keymatch( argv[*argn], "-konly", 3 ) ) {
475 t->kFlag = K_ONLY ;
476 ++(*argn) ;
477 } else {
478 oldn = *argn ;
479 if ( (err = longArg( &lVal, "-predictor", 3, 1, 2,
480 argn, argc, argv )) ) return err ;
481 if ( oldn != *argn ) {
482 t->predictor = (uint16_t)lVal ;
483 } else {
484 if ( (err = longArg( &lVal, "-rowsperstrip", 2, 1, INT_MAX,
485 argn, argc, argv )) ) return err ;
486 }
487 if ( oldn != *argn ) {
488 t->rowsperstrip = (uint32_t)lVal ;
489 } else {
490 if ( (err = longArg( &lVal, "-lowdotrange", 3, 0,
491 (int)(t->highdotrange - 1),
492 argn, argc, argv )) ) return err ;
493 }
494 if ( oldn != *argn ) {
495 t->lowdotrange = (uint16_t)lVal ;
496 } else {
497 if ( (err = longArg( &lVal, "-highdotrange", 2,
498 (int)(t->lowdotrange + 1), MAXTIFFVAL,
499 argn, argc, argv )) ) return err ;
500 }
501 if ( oldn != *argn ) {
502 t->highdotrange = (uint16_t)lVal ;
503 }
504 }
505
506 return ERR_OK ;
507 }
508
509
510
511 /* helper routine - writes individual bytes */
512 static Err
513 tiffWriteByte( TiffOut *t, int b ) {
514 ((unsigned char*)(t->buffer))[t->iBuffer] = (unsigned char)b ;
515 if ( ++(t->iBuffer) == t->maxBuffer ) {
516 if ( TIFFWriteScanline( t->tiff, t->buffer, t->iRow, 0 ) == -1 ) {
517 return ERR_TIFF ;
518 }
519 ++(t->iRow) ;
520 t->iBuffer = 0 ;
521 }
522 return ERR_OK ;
523 }
524
525
526
527 /* write the pixel to the tiff file */
528 static Err
529 tiffWrite( Out *out, int c, int m, int y, int k ) {
530 Err err ;
531 TiffOut *t = (TiffOut*)out->private ;
532 if ( t->kFlag == K_ONLY ) {
533 c = m = y = k ;
534 } else if ( t->kFlag == K_REMOVE ) {
535 k = 0 ;
536 }
537 if ( (err = tiffWriteByte( t, c )) ) return err ;
538 if ( (err = tiffWriteByte( t, m )) ) return err ;
539 if ( (err = tiffWriteByte( t, y )) ) return err ;
540 if ( (err = tiffWriteByte( t, k )) ) return err ;
541 return ERR_OK ;
542 }
543
544
545
546 /* open output to stdout - see warning below */
547 static Err
548 tiffOpen( Out* out, Root *r ) {
549
550 TiffOut *t = (TiffOut*)out->private ;
551
552 short samplesperpixel = 4 ; /* cmyk has four values */
553 uint16_t bitspersample = MAXTIFFBITS ;
554 short photometric = PHOTOMETRIC_SEPARATED ; /* ie cmyk */
555
556 t->tiff = TIFFFdOpen( 1, "Standard Output", "w" ) ;
557 if ( ! t->tiff ) {
558 fprintf( stderr, "cannot open tiff stream to standard output\n" ) ;
559 return ERR_TIFF ;
560 }
561
562 TIFFSetField( t->tiff, TIFFTAG_DOTRANGE, t->lowdotrange, t->highdotrange ) ;
563 TIFFSetField( t->tiff, TIFFTAG_IMAGEWIDTH, (uint32_t)r->nCols ) ;
564 TIFFSetField( t->tiff, TIFFTAG_IMAGELENGTH, (uint32_t)r->nRows ) ;
565 TIFFSetField( t->tiff, TIFFTAG_BITSPERSAMPLE, bitspersample ) ;
566 TIFFSetField( t->tiff, TIFFTAG_ORIENTATION, ORIENTATION_TOPLEFT ) ;
567 TIFFSetField( t->tiff, TIFFTAG_COMPRESSION, t->compression ) ;
568 if ( t->compression == COMPRESSION_LZW && t->predictor ) {
569 TIFFSetField( t->tiff, TIFFTAG_PREDICTOR, t->predictor ) ;
570 }
571 TIFFSetField( t->tiff, TIFFTAG_PHOTOMETRIC, photometric ) ;
572 TIFFSetField( t->tiff, TIFFTAG_FILLORDER, t->fillorder ) ;
573 TIFFSetField( t->tiff, TIFFTAG_DOCUMENTNAME, r->name ) ;
574 TIFFSetField( t->tiff, TIFFTAG_IMAGEDESCRIPTION, "PNM -> CMYK tiff" ) ;
575 TIFFSetField( t->tiff, TIFFTAG_SAMPLESPERPIXEL, samplesperpixel ) ;
576 if ( t->rowsperstrip == 0) {
577 t->rowsperstrip = TIFFDefaultStripSize(t->tiff, 0) ;
578 }
579 TIFFSetField( t->tiff, TIFFTAG_ROWSPERSTRIP, t->rowsperstrip ) ;
580 TIFFSetField( t->tiff, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG ) ;
581
582 t->maxBuffer = TIFFScanlineSize( t->tiff ) ;
583 t->buffer = _TIFFmalloc( t->maxBuffer ) ;
584 t->iBuffer = 0 ;
585 t->iRow = 0 ;
586 if ( ! t->buffer ) {
587 fprintf( stderr, "cannot allocate memory\n" ) ;
588 return ERR_MEMORY ;
589 }
590
591 return ERR_OK ;
592 }
593
594
595
596 /* close file and tidy memory */
597 static void
598 tiffClose( Out *out ) {
599 if ( out ) {
600 TiffOut *t = (TiffOut*)out->private ;
601 if ( t ) {
602 if ( t->buffer ) _TIFFfree( t->buffer ) ;
603 if ( t->tiff ) TIFFClose( t->tiff ) ;
604 free( t ) ;
605 }
606 free( out ) ;
607 }
608 }
609
610
611
612 /* assemble the routines above into a single struct/object */
613 static Err
614 newTiffOutput( Out **out ) {
615
616 TiffOut *t ;
617
618 if ( ! (*out = (Out*)calloc( 1, sizeof( Out ) )) ) goto error ;
619 if ( ! (t = (TiffOut*)calloc( 1, sizeof( TiffOut ) )) ) goto error ;
620 t->compression = COMPRESSION_LZW ;
621 t->fillorder = FILLORDER_MSB2LSB ;
622 t->predictor = 0 ;
623 t->rowsperstrip = 0 ;
624 t->lowdotrange = 0 ;
625 t->highdotrange = MAXTIFFVAL ;
626 t->kFlag = K_NORMAL ;
627 (*out)->private = t ;
628 (*out)->opt = tiffOpt ;
629 (*out)->open = tiffOpen ;
630 (*out)->write = tiffWrite ;
631 (*out)->close = tiffClose ;
632 return ERR_OK ;
633
634 error:
635 fprintf( stderr, "cannot allocate memory\n" ) ;
636 return ERR_MEMORY ;
637 }
638
639
640
641 /* --- conversion ------------------------------------- */
642
643
644 /* encapsulate conversion - allow easy extension with other conversion
645 algorithms. if selection of conversion routine is by command line
646 flag then that flag must precede conversion parameters (for
647 simplicity in argument parsing) */
648
649 typedef Err Opt( struct tagConv *conv, Root *r,
650 int *argn, int argc, char **argv ) ;
651 typedef Err Convert( struct tagConv *conv, Root *rt,
652 float r, float g, float b,
653 int *c, int *m, int *y, int *k ) ;
654 typedef void Close( struct tagConv *conv ) ;
655
656 typedef struct tagConv {
657 Opt *opt ;
658 Convert *convert ;
659 Close *close ;
660 void *private ;
661 } Conv ;
662
663
664 /* include two conversion routines to show how the code can be
665 extended. first, the standard converter, as outlined in the
666 proposal, then a simple replacement that produces colour
667 negatives */
668
669
670 /* implementation with hue rotation, black gamma correction and
671 removal of cmy under k */
672
673 typedef struct {
674 int initialized ;
675 float theta ;
676 float gamma ;
677 float gammap ;
678 int remove ;
679 } Standard ;
680
681
682 /* represent an rgb colour as a hue (angle), white level and colour
683 strength */
684 static void
685 rgbToHueWhiteColour( float r, float g, float b,
686 double *phi, float *white, float *colour ) {
687 *white = MIN( r, MIN( g, b ) ) ;
688 r -= *white ;
689 g -= *white ;
690 b -= *white ;
691 *colour = sqrt( r * r + g * g + b * b ) ;
692 if ( r > TINY || g > TINY || b > TINY ) {
693 if ( b < r && b <= g ) {
694 *phi = EXPAND( atan2( g, r ) ) ;
695 } else if ( r < g && r <= b ) {
696 *phi = ONETWENTY + EXPAND( atan2( b, g ) ) ;
697 } else {
698 *phi = TWOFORTY + EXPAND( atan2( r, b ) ) ;
699 }
700 }
701 }
702
703
704
705 /* represent hue, white and colour values as rgb */
706 static void
707 hueWhiteColourToRgb( double phi, float white, float colour,
708 float *r, float *g, float *b ) {
709 while ( phi < 0 ) { phi += THREESIXTY ; }
710 while ( phi > THREESIXTY ) { phi -= THREESIXTY ; }
711 if ( phi < ONETWENTY ) {
712 phi = CONTRACT( phi ) ;
713 *r = colour * cos( phi ) ;
714 *g = colour * sin( phi ) ;
715 *b = 0.0 ;
716 } else if ( phi < TWOFORTY ) {
717 phi = CONTRACT( phi - ONETWENTY ) ;
718 *r = 0.0 ;
719 *g = colour * cos( phi ) ;
720 *b = colour * sin( phi ) ;
721 } else {
722 phi = CONTRACT( phi - TWOFORTY ) ;
723 *r = colour * sin( phi ) ;
724 *g = 0.0 ;
725 *b = colour * cos( phi ) ;
726 }
727 *r += white ;
728 *g += white ;
729 *b += white ;
730 }
731
732
733
734 /* for details, see the proposal. it's pretty simple - a rotation
735 before conversion, with colour removal */
736 static Err
737 standardConvert( Conv *conv, Root *rt, float r, float g, float b,
738 int *c, int *m, int *y, int *k ) {
739
740 float c0, m0, y0, k0 ; /* CMYK before colour removal */
741 float gray, white, colour ;
742 double phi ;
743
744 Standard *s ; /* private conversion data */
745
746 s = (Standard*)(conv->private) ;
747
748 if ( ! s->initialized ) {
749 s->theta *= 2.0 * PI / 360.0 ; /* to radians */
750 /* if gammap never specified in options, set to gamma now */
751 if ( s->remove == UNSET ) {
752 s->remove = 1 ;
753 s->gammap = s->gamma ;
754 }
755 s->initialized = 1 ;
756 }
757
758 /* rotate in rgb */
759 if ( fabs( s->theta ) > TINY ) {
760 rgbToHueWhiteColour( r, g, b, &phi, &white, &colour ) ;
761 hueWhiteColourToRgb( phi + s->theta, white, colour, &r, &g, &b ) ;
762 }
763
764 c0 = LIMIT01( 1.0 - r ) ;
765 m0 = LIMIT01( 1.0 - g ) ;
766 y0 = LIMIT01( 1.0 - b ) ;
767 k0 = MIN( c0, MIN( y0, m0 ) ) ;
768
769 /* apply gamma corrections to modify black levels */
770 *k = TOMAX( pow( k0, s->gamma ) ) ;
771
772 /* remove colour under black and convert to integer range 0 - rt->maxOut */
773 if ( s->remove ) {
774 gray = pow( k0, s->gammap ) ;
775 } else {
776 gray = 0.0 ;
777 }
778 *c = TOMAX( c0 - gray ) ;
779 *m = TOMAX( m0 - gray ) ;
780 *y = TOMAX( y0 - gray ) ;
781
782 return ERR_OK ;
783 }
784
785
786
787 /* parse options for this conversion - note the ugly use of -1 for
788 gammap to indicate no removal of cmy under k */
789 static Err
790 standardOpt( Conv *conv, Root *r, int *argn, int argc, char **argv ) {
791
792 Err err ;
793 int oldn ;
794 Standard *p = (Standard*)conv->private ;
795
796 oldn = *argn ;
797 if ( (err = floatArg( &(p->theta), "-theta", 2, -360.0, 360.0,
798 argn, argc, argv )) ) return err ;
799 if ( oldn == *argn ) {
800 if ( (err = floatArg( &(p->gamma), "-gamma", 6, 0.1, 10.0,
801 argn, argc, argv )) ) return err ;
802 /* gammap traces gamma unless set separately */
803 if ( oldn != *argn && p->remove == UNSET ) p->gammap = p->gamma ;
804 }
805 /* handle the special case of -1 (no removal) */
806 if ( oldn == *argn && pm_keymatch( argv[*argn], "-gammap", 7 ) &&
807 *argn + 1 < argc && streq(argv[*argn + 1], "-1") ) {
808 p->remove = 0 ;
809 *argn = (*argn) + 2 ;
810 }
811 if ( oldn == *argn ) {
812 if ( (err = floatArg( &(p->gammap), "-gammap", 7, 0.1, 10.0,
813 argn, argc, argv )) ) return err ;
814 if ( oldn != *argn ) p->remove = 1 ;
815 }
816
817 return ERR_OK ;
818 }
819
820
821
822 /* free conversion structure */
823 static void
824 standardClose( Conv *conv ) {
825 if ( conv ) {
826 if ( conv->private ) { free( conv->private ) ; }
827 free( conv ) ;
828 }
829 }
830
831
832
833 /* build new conversion structure */
834 static Err
835 newStandardMap( Conv **conv ) {
836
837 Standard *s ;
838
839 if ( ! (*conv = (Conv*)calloc( 1, sizeof( Conv ) )) ) goto error ;
840 if ( ! (s = (Standard*)calloc( 1, sizeof( Standard ) )) ) goto error ;
841 s->initialized = 0 ;
842 s->remove = UNSET ; /* gammap unset */
843 s->gamma = 1.0 ;
844 (*conv)->private = s ;
845 (*conv)->opt = standardOpt ;
846 (*conv)->convert = standardConvert ;
847 (*conv)->close = standardClose ;
848
849 return ERR_OK ;
850
851 error:
852 fprintf( stderr, "cannot allocate memory\n" ) ;
853 return ERR_MEMORY ;
854 }
855
856
857
858 /* next a simple demonstration of how to implement other conversion
859 algorithms - in this case, something that produces a "colour
860 negative" (just to be different) */
861
862
863 /* the conversion routine must match the Convert typedef */
864 static Err
865 negativeConvert( Conv *conv, Root *rt, float r, float g, float b,
866 int *c, int *m, int *y, int *k ) {
867
868 /* the simple conversion is c=1-r, but for negatives we will use
869 c=r, so only need to convert from rgb 0-1 floats to cmyk
870 0-MAXTIFFVAL ints */
871 *c = TOMAX( r ) ;
872 *m = TOMAX( g ) ;
873 *y = TOMAX( b ) ;
874 *k = MIN( *c, MIN( *m, *y ) ) ;
875
876 return ERR_OK ;
877 }
878
879
880
881 /* since this simple conversion takes no parameters, we don't need to
882 parse them - this routine must match the Opt typedef */
883 static Err
884 negativeOpt( Conv *conv, Root *r, int *argn, int argc, char **argv ) {
885 return ERR_OK ;
886 }
887
888
889
890 /* with no parameters we haven't needed the private data structure, so
891 closing is trivial - this routine must match the Close typedef */
892 static void
893 negativeClose( Conv *conv ) { }
894
895
896 /* and that's it, apart from assembling the routines above into a
897 single struct/object (and adding code in parseOpts to select the
898 algorithm and printUsage to help the user) */
899 static Err
900 newNegativeMap( Conv **conv ) {
901
902 if ( ! (*conv = (Conv*)calloc( 1, sizeof( Conv ) )) ) goto error ;
903 (*conv)->opt = negativeOpt ;
904 (*conv)->convert = negativeConvert ;
905 (*conv)->close = negativeClose ;
906
907 return ERR_OK ;
908
909 error:
910 fprintf( stderr, "cannot allocate memory\n" ) ;
911 return ERR_MEMORY ;
912 }
913
914
915
916 /* --- general routines ------------------------------- */
917
918
919 /* run through args, passing to sub components */
920 static Err
921 parseOpts( int argc, char **argv, Root *r ) {
922
923 int argn = 1 ;
924 int oldn ;
925 Err err ;
926
927 /* set default reader, writer and converter */
928 if ( (err = newPnmInput( &(r->in) )) ) return err ;
929 if ( (err = newTiffOutput( &(r->out) )) ) return err ;
930 if ( (err = newStandardMap( &(r->conv) )) ) return err ;
931
932 /* minimum number of chars from inspection - this is standard netpbm
933 approach - so must check when adding more options */
934 while ( argn < argc ) {
935
936 /* first, high-level options that select components - currently
937 just the default or negative converter */
938 if ( pm_keymatch( argv[argn], "-default", 2 ) ) {
939 if ( r->conv ) { r->conv->close( r->conv ) ; }
940 if ( (err = newStandardMap( &(r->conv) )) ) return err ;
941 ++argn ;
942 } else if ( pm_keymatch( argv[argn], "-negative", 3 ) ) {
943 if ( r->conv ) { r->conv->close( r->conv ) ; }
944 if ( (err = newNegativeMap( &(r->conv) )) ) return err ;
945 ++argn ;
946 } else if ( pm_keymatch( argv[argn], "-help", 2 ) ) {
947 printUsage( ) ;
948 return ERR_HELP ;
949 } else {
950 /* next, try passing the option to each subcomponent */
951 oldn = argn ;
952 if ( (err = r->in->opt( r->in, r, &argn, argc, argv )) ) {
953 return err ;
954 } else if ( oldn == argn &&
955 (err = r->out->opt( r->out, r, &argn, argc, argv )) ) {
956 return err ;
957 } else if ( oldn == argn &&
958 (err = r->conv->opt( r->conv, r, &argn, argc, argv )) ) {
959 return err ;
960 } else if ( oldn == argn ) {
961 fprintf( stderr, "unexpected arg: %s\n", argv[argn] ) ;
962 return ERR_ARG ;
963 }
964 }
965 }
966
967 return ERR_OK ;
968 }
969
970
971
972 /* drive the reading, conversion, and writing */
973 int main( int argc, char **argv ) {
974
975 Root *rt ;
976 float r, g, b ;
977 int c, m, y, k ;
978 Err err = ERR_OK ;
979
980 pnm_init(&argc, argv);
981
982 if ( ! (rt = (Root*)calloc( 1, sizeof( Root ) )) ) {
983 err = ERR_MEMORY ;
984 fprintf( stderr, "cannot allocate memory\n" ) ;
985 goto exit ;
986 }
987 rt->name = "Standard input" ;
988 rt->maxOut = MAXTIFFVAL ;
989
990 if ( (err = parseOpts( argc, argv, rt )) ) goto exit ;
991
992 if ( (err = rt->in->open( rt->in, rt )) ) goto exit ;
993 if ( (err = rt->out->open( rt->out, rt )) ) goto exit ;
994
995 while ( rt->in->hasMore( rt->in ) ) {
996 if ( (err = rt->in->next( rt->in, &r, &g, &b )) ) goto exit ;
997 if ( (err = rt->conv->convert( rt->conv, rt, r, g, b, &c, &m, &y, &k )) )
998 goto exit ;
999 if ( (err = rt->out->write( rt->out, c, m, y, k )) ) goto exit ;
1000 }
1001
1002 exit:
1003
1004 if ( rt && rt->out && rt->out->close ) rt->out->close( rt->out ) ;
1005 if ( rt && rt->conv && rt->conv->close ) rt->conv->close( rt->conv ) ;
1006 if ( rt && rt->in && rt->in->close ) rt->in->close( rt->in ) ;
1007 if ( rt ) free( rt ) ;
1008
1009 if ( err == ERR_ARG ) printUsage( ) ;
1010
1011 return err ;
1012 }
1013
1014
1015