about summary refs log tree commit diff
path: root/converter/other/pamtodjvurle.c
blob: ae35e81d47a940f8a197dde7c1f55e0b43b67a28 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
/*****************************************************************************
                               pamtodjvurle
******************************************************************************
  This program converts a PAM image to DjVu Color RLE format.
  
  By Bryan Henderson, San Jose, CA April 2004.

  Contributed to the public domain by its author.

  This work is inspired by Ppmtodjvurle, written by Scott Pakin
  <scott+pbm@pakin.org> in March 2004.  Bryan took the requirements of
  the DjVu Color RLE format and the technique for generating the format
  (but not code) from that program.

*****************************************************************************/
#include <stdio.h>
#include <assert.h>

#include "pam.h"
#include "pammap.h"
#include "shhopt.h"


struct cmdlineInfo {
    const char * inputFilespec;
    const char * transparent;
    unsigned int showcolormap;
};



static void 
parseCommandLine(int argc, 
                 char ** argv, 
                 struct cmdlineInfo  * const cmdlineP) {
/* --------------------------------------------------------------------------
   Parse program command line described in Unix standard form by argc
   and argv.  Return the information in the options as *cmdlineP.  

   If command line is internally inconsistent (invalid options, etc.),
   issue error message to stderr and abort program.

   Note that the strings we return are stored in the storage that
   was passed to us as the argv array.  We also trash *argv.
--------------------------------------------------------------------------*/
    optEntry *option_def = malloc( 100*sizeof( optEntry ) );
    /* Instructions to optParseOptions3 on how to parse our options. */
    optStruct3 opt;
  
    unsigned int option_def_index;
    unsigned int transparentSpec;

    option_def_index = 0;   /* incremented by OPTENTRY */
    OPTENT3(0, "transparent",   OPT_STRING, &cmdlineP->transparent, 
            &transparentSpec,        0);
    OPTENT3(0, "showcolormap",  OPT_FLAG, NULL,
            &cmdlineP->showcolormap,        0);
  
    opt.opt_table = option_def;
    opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
    opt.allowNegNum = FALSE;   /* We have no parms that are negative numbers */

    optParseOptions3( &argc, argv, opt, sizeof(opt), 0 );
    /* Uses and sets argc, argv, and some of *cmdline_p and others. */

    if (!transparentSpec)
        cmdlineP->transparent = "white";

    /* Get the program parameters */

    if (argc-1 >= 1)
        cmdlineP->inputFilespec = argv[1];
    else
        cmdlineP->inputFilespec = "-";
    
    if (argc-1 > 1)
        pm_error("Program takes at most one argument:  the file name.  "
                 "You specified %d", argc-1);
}



static void
computeColorMap(struct pam *   const pamP,
                tuple **       const tupleArray,
                unsigned int * const numColorsP,
                tupletable *   const colormapP,
                tuplehash *    const colorhashP,
                bool           const show) {

    unsigned int numColors;
    tupletable colormap;

    colormap = pnm_computetuplefreqtable(pamP, tupleArray, 0, &numColors);
    if (numColors > 0xFF0)
        pm_error("too many colors; "
                 "use pnmquant to reduce to no more than %u colors", 0xFF0);
    
    if (show) {
        unsigned int colorIndex;
        fprintf(stderr, "Color map:\n");
        fprintf(stderr, "    Index Color\n");
        for (colorIndex = 0; colorIndex < numColors; ++colorIndex) {
            unsigned int plane;
            fprintf(stderr, "    %5u   ", colorIndex);
            for (plane = 0; plane < pamP->depth; ++plane)
                fprintf(stderr, "%3lu ", colormap[colorIndex]->tuple[plane]);
            fprintf(stderr, "\n");
        }
    }

    *colorhashP = pnm_computetupletablehash(pamP, colormap, numColors);

    *numColorsP = numColors;
    *colormapP  = colormap;
}



static void
makeDjvurleHeader(FILE *       const ofP,
                  struct pam * const pamP,
                  unsigned int const numColors,
                  tupletable   const colormap) {
    
    unsigned int colorIndex;

    fprintf(ofP, "R6\n");
    fprintf(ofP, "%d %d %d\n", pamP->width, pamP->height, numColors);

    for (colorIndex = 0; colorIndex < numColors; ++colorIndex) {
        sample red, grn, blu;

        if (pamP->depth >= 3) {
            red = colormap[colorIndex]->tuple[PAM_RED_PLANE];
            grn = colormap[colorIndex]->tuple[PAM_GRN_PLANE];
            blu = colormap[colorIndex]->tuple[PAM_BLU_PLANE];
        } else
            red = grn = blu = colormap[colorIndex]->tuple[0];
        
        fputc(pnm_scalesample(red, pamP->maxval, 255), ofP);
        fputc(pnm_scalesample(grn, pamP->maxval, 255), ofP);
        fputc(pnm_scalesample(blu, pamP->maxval, 255), ofP);
    }
}



static bool
colorEqual(tuple        comparand,
           unsigned int comparandDepth,
           tuple        comparator) {

    /* comparator has depth 3 */

    if (comparandDepth >= 3)
        return (comparand[0] == comparator[0] &&
                comparand[1] == comparator[1] &&
                comparand[2] == comparator[2]);
    else
        return (comparand[0] == comparator[0] &&
                comparand[0] == comparator[1] &&
                comparand[0] == comparator[2]);
}



static void 
writeRleRun(FILE *       const ofP, 
            struct pam * const pamP,
            tuple        const color, 
            int          const count,
            tuplehash    const colorhash,
            tuple        const transcolor) {
/*----------------------------------------------------------------------------
  Write one DjVu Color RLE run to the file 'ofP'.  The run is 
  'count' pixels of color 'color', using the color index given by
  'colorhash' and assuming 'transcolor' is the transparent color.
  
  'transcolor' is a 3-deep tuple with the same maxval as the image.
-----------------------------------------------------------------------------*/
    uint32n rlevalue;         /* RLE-encoded color/valuex */
    int index;

    if (count > 0) {
        if (colorEqual(color, pamP->depth, transcolor))
            index = 0xFFF;
        else {
            int found;
            pnm_lookuptuple(pamP, colorhash, color, &found, &index);
            assert(found);
        }
        rlevalue = (index << 20) | count;
      
        pm_writebiglong(ofP, rlevalue);
    }
}



static void
writeDjvurleRow(FILE *       const ofP,
                struct pam * const pamP,
                tuple *      const tupleRow,
                tuplehash    const colorhash,
                tuple        const transcolor) {

    unsigned int col;
    unsigned int runlength;
    tuple prevpixel;        /* Previous pixel seen */

    prevpixel = tupleRow[0];
    runlength = 0;
    
    for (col = 0; col < pamP->width; ++col) {
        tuple const newpixel = tupleRow[col];      /* Current pixel color */
        
        if (pnm_tupleequal(pamP, newpixel, prevpixel))
            /* This is a continuation of the current run */
            ++runlength;
          else {
              /* The run is over.  Write it out and start a run of the next
                 color.
              */
              writeRleRun(ofP, pamP, prevpixel, runlength, 
                          colorhash, transcolor);
              runlength = 1;
              prevpixel = newpixel;
          }
        if (runlength >= (1<<20)-1) {
            /* Can't make the run any longer.  Write it out and start a
               new run.
            */
            writeRleRun(ofP, pamP, prevpixel, runlength, 
                        colorhash, transcolor);
            runlength = 1;
        }
    }
    /* Write the last run we started */
    writeRleRun(ofP, pamP, prevpixel, runlength, colorhash, transcolor);
}



int 
main(int argc, char *argv[]) {

    FILE * const rlefile = stdout;

    struct cmdlineInfo cmdline;
    FILE *ifP;                 /* Input (Netpbm) file */
    struct pam pam;            /* Description of the image */
    tuple ** tupleArray;       /* The image raster */
    tupletable colormap;       /* List of all of the colors used */
    unsigned int numColors;    /* Number of unique colors in the color map */
    tuplehash colorhash; 
        /* Mapping from color to index into colormap[] */
    tuple transcolor;
        /* Color that should be considered transparent */

    pnm_init (&argc, argv);

    parseCommandLine(argc, argv, &cmdline);

    ifP = pm_openr(cmdline.inputFilespec);

    tupleArray = pnm_readpam(ifP, &pam, PAM_STRUCT_SIZE(tuple_type));

    transcolor = pnm_parsecolor(cmdline.transparent, pam.maxval);
    
    computeColorMap(&pam, tupleArray, &numColors, &colormap, &colorhash,
                    cmdline.showcolormap);
    
    makeDjvurleHeader(rlefile, &pam, numColors, colormap);

    /* Write the raster */

    {
        unsigned int row;
        for (row = 0; row < pam.height; ++row)
            writeDjvurleRow(rlefile, &pam, tupleArray[row], colorhash, 
                            transcolor);
    }
    /* Clean up */
    
    pnm_freepamarray(tupleArray, &pam);
    pnm_freetupletable(&pam, colormap);
    pnm_destroytuplehash(colorhash);
    pnm_freepamtuple(transcolor);
    pm_close(ifP);

    return 0;
}