about summary refs log tree commit diff
path: root/converter/other/pnmtosgi.c
blob: 169125b37383e3b1a9ffeda113e11780b4ae7bd0 (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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
/* pnmtosgi.c - convert portable anymap to SGI image
**
** Copyright (C) 1994 by Ingo Wilken (Ingo.Wilken@informatik.uni-oldenburg.de)
**
** Based on the SGI image description v0.9 by Paul Haeberli (paul@sgi.comp)
** Available via ftp from sgi.com:graphics/SGIIMAGESPEC
**
** Permission to use, copy, modify, and distribute this software and its
** documentation for any purpose and without fee is hereby granted, provided
** that the above copyright notice appear in all copies and that both that
** copyright notice and this permission notice appear in supporting
** documentation.  This software is provided "as is" without express or
** implied warranty.
**
** 29Jan94: first version

** Feb 2010 afu
** Added dimension check to prevent short int from overflowing
*/
#include "pnm.h"
#include "sgi.h"
#include "mallocvar.h"



/*#define DEBUG*/

typedef short       ScanElem;
typedef struct {
    ScanElem *  data;
    long        length;
} ScanLine;

/* prototypes */
static void put_big_short ARGS((short s));
static void put_big_long ARGS((long l));
#define put_byte(b)     (void)(putc((unsigned char)(b), stdout))
static void put_short_as_byte ARGS((short s));
static void write_table  ARGS((long *table, int tabsize));
static void write_channels ARGS((int cols, int rows, int channels, void (*put) ARGS((short)) ));
static long * build_channels ARGS((FILE *ifp, int cols, int rows, xelval maxval, int format, int bpc, int channels));
static ScanElem *compress ARGS((ScanElem *temp, int row, int rows, int cols, int chan_no, long *table, int bpc));
static int rle_compress ARGS((ScanElem *inbuf, int cols));

#define WORSTCOMPR(x)   (2*(x) + 2)


#define MAXVAL_BYTE     255
#define MAXVAL_WORD     65535
#define INT16MAX        32767

static char storage = STORAGE_RLE;
static ScanLine * channel[3];
static ScanElem * rletemp;
static xel * pnmrow;


static void
write_header(int const cols, 
             int const rows, 
             xelval const maxval, 
             int const bpc, 
             int const dimensions, 
             int const channels, 
             const char * const imagename)
{
    int i;

#ifdef DEBUG
    pm_message("writing header");
#endif

    put_big_short(SGI_MAGIC);
    put_byte(storage);
    put_byte((char)bpc);
    put_big_short(dimensions);
    put_big_short(cols);
    put_big_short(rows);
    put_big_short(channels);
    put_big_long(0);                /* PIXMIN */
    put_big_long(maxval);           /* PIXMAX */
    for( i = 0; i < 4; i++ )
        put_byte(0);
    for( i = 0; i < 79 && imagename[i] != '\0'; i++ )
        put_byte(imagename[i]);
    for(; i < 80; i++ )
        put_byte(0);
    put_big_long(CMAP_NORMAL);
    for( i = 0; i < 404; i++ )
        put_byte(0);
}



int
main(int argc,char * argv[])
{
    FILE *ifp;
    int argn;
    const char * const usage = "[-verbatim|-rle] [-imagename <name>] [pnmfile]";
    int cols, rows, format;
    xelval maxval, newmaxval;
    const char *imagename = "no name";
    int bpc, dimensions, channels;
    long *table = NULL;

    pnm_init(&argc, argv);

    argn = 1;
    while( argn < argc && argv[argn][0] == '-' && argv[argn][1] != '\0' ) {
        if( pm_keymatch(argv[argn], "-verbatim", 2) )
            storage = STORAGE_VERBATIM;
        else
        if( pm_keymatch(argv[argn], "-rle", 2) )
            storage = STORAGE_RLE;
        else
        if( pm_keymatch(argv[argn], "-imagename", 2) ) {
            if( ++argn >= argc )
                pm_usage(usage);
            imagename = argv[argn];
        }
        else
            pm_usage(usage);
        ++argn;
    }

    if( argn < argc ) {
        ifp = pm_openr( argv[argn] );
        argn++;
    }
    else
        ifp = stdin;

    if( argn != argc )
        pm_usage(usage);

    pnm_readpnminit(ifp, &cols, &rows, &maxval, &format);
    if( rows>INT16MAX || cols>INT16MAX )
      pm_error ("Input image is too large.");

    pnmrow = pnm_allocrow(cols);

    switch( PNM_FORMAT_TYPE(format) ) {
        case PBM_TYPE:
            newmaxval = PGM_MAXMAXVAL;
            pm_message("promoting PBM to PGM");
        case PGM_TYPE:
            newmaxval = maxval;
            dimensions = 2; channels = 1;
            break;
        case PPM_TYPE:
            newmaxval = maxval;
            dimensions = 3; channels = 3;
            break;
        default:
            pm_error("can\'t happen");
    }
    if( newmaxval <= MAXVAL_BYTE )
        bpc = 1;
    else if( newmaxval <= MAXVAL_WORD )
        bpc = 2;
    else
        pm_error("maxval too large - try using \"pnmdepth %d\"", MAXVAL_WORD);

    table = build_channels(ifp, cols, rows, newmaxval, format, bpc, channels);
    pnm_freerow(pnmrow);
    pm_close(ifp);

    write_header(cols, rows, newmaxval, bpc, dimensions, channels, imagename);
    if( table )
        write_table(table, rows * channels);
    if( bpc == 1 )
        write_channels(cols, rows, channels, put_short_as_byte);
    else
        write_channels(cols, rows, channels, put_big_short);

    exit(0);
}


static void
write_table(long * table, int const tabsize)
{
    int i;
    long offset;

#ifdef DEBUG
    pm_message("writing table");
#endif

    offset = HeaderSize + tabsize * 8;
    for( i = 0; i < tabsize; i++ ) {
        put_big_long(offset);
        offset += table[i];
    }
    for( i = 0; i < tabsize; i++ )
        put_big_long(table[i]);
}


static void
write_channels(int const cols,int const rows, int const channels,
               void (*put) (short))
{
    int i, row, col;

#ifdef DEBUG
    pm_message("writing image data");
#endif

    for( i = 0; i < channels; i++ ) {
        for( row = 0; row < rows; row++ ) {
            for( col = 0; col < channel[i][row].length; col++ ) {
                (*put)(channel[i][row].data[col]);
            }
        }
    }
}

static void
put_big_short(short const s)
{
    if ( pm_writebigshort( stdout, s ) == -1 )
        pm_error( "write error" );
}


static void
put_big_long(long const l)
{
    if ( pm_writebiglong( stdout, l ) == -1 )
        pm_error( "write error" );
}


static void
put_short_as_byte(short const s)
{
    put_byte((unsigned char)s);
}


static long *
build_channels(FILE * const ifp, int const cols, int const rows,
               xelval const maxval, int const format,
               int const bpc, int const channels)
{
    int i, row, col, sgirow;
    long *table = NULL;
    ScanElem *temp;

#ifdef DEBUG
    pm_message("building channels");
#endif

    if( storage != STORAGE_VERBATIM ) {
        MALLOCARRAY_NOFAIL(table, channels * rows);
        MALLOCARRAY_NOFAIL(rletemp, WORSTCOMPR(cols));
    }
    MALLOCARRAY_NOFAIL(temp, cols);

    for( i = 0; i < channels; i++ )
        MALLOCARRAY_NOFAIL(channel[i], rows);

    for( row = 0, sgirow = rows-1; row < rows; row++, sgirow-- ) {
        pnm_readpnmrow(ifp, pnmrow, cols, maxval, format);
        if( channels == 1 ) {
            for( col = 0; col < cols; col++ )
                temp[col] = (ScanElem)PNM_GET1(pnmrow[col]);
            temp = compress(temp, sgirow, rows, cols, 0, table, bpc);
        }
        else {
            for( col = 0; col < cols; col++ )
                temp[col] = (ScanElem)PPM_GETR(pnmrow[col]);
            temp = compress(temp, sgirow, rows, cols, 0, table, bpc);
            for( col = 0; col < cols; col++ )
                temp[col] = (ScanElem)PPM_GETG(pnmrow[col]);
            temp = compress(temp, sgirow, rows, cols, 1, table, bpc);
            for( col = 0; col < cols; col++ )
                temp[col] = (ScanElem)PPM_GETB(pnmrow[col]);
            temp = compress(temp, sgirow, rows, cols, 2, table, bpc);
        }
    }

    free(temp);
    if( table )
        free(rletemp);
    return table;
}


static ScanElem *
compress(ScanElem * temp,
         int const row,  int const rows,
         int const cols, int const chan_no,
         long * table, int const bpc)
{
    int len, i, tabrow;
    ScanElem *p;

    switch( storage ) {
        case STORAGE_VERBATIM:
            channel[chan_no][row].length = cols;
            channel[chan_no][row].data = temp;
            MALLOCARRAY_NOFAIL(temp, cols);
            break;
        case STORAGE_RLE:
            tabrow = chan_no * rows + row;
            len = rle_compress(temp, cols);    /* writes result into rletemp */
            channel[chan_no][row].length = len;
            MALLOCARRAY(p, len);
            channel[chan_no][row].data = p;
            for( i = 0; i < len; i++, p++ )
                *p = rletemp[i];
            table[tabrow] = len * bpc;
            break;
        default:
            pm_error("unknown storage type - can\'t happen");
    }
    return temp;
}


/*
slightly modified RLE algorithm from ppmtoilbm.c
written by Robert A. Knop (rknop@mop.caltech.edu)
*/
static int
rle_compress(ScanElem * const inbuf, int const size)
{
    int in, out, hold, count;
    ScanElem *outbuf = rletemp;

    in=out=0;
    while( in<size ) {
        if( (in<size-1) && (inbuf[in]==inbuf[in+1]) ) {     /*Begin replicate run*/
            for( count=0,hold=in; in<size && inbuf[in]==inbuf[hold] && count<127; in++,count++)
                ;
            outbuf[out++]=(ScanElem)(count);
            outbuf[out++]=inbuf[hold];
        }
        else {  /*Do a literal run*/
            hold=out; out++; count=0;
            while( ((in>=size-2)&&(in<size)) || ((in<size-2) && ((inbuf[in]!=inbuf[in+1])||(inbuf[in]!=inbuf[in+2]))) ) {
                outbuf[out++]=inbuf[in++];
                if( ++count>=127 )
                    break;
            }
            outbuf[hold]=(ScanElem)(count | 0x80);
        }
    }
    outbuf[out++] = (ScanElem)0;     /* terminator */
    return(out);
}