about summary refs log tree commit diff
path: root/converter/other/pfmtopam.c
blob: 7e26d9c2781c3f373606439b623c3be1da5f3a58 (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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
/*****************************************************************************
                                  pfmtopam
******************************************************************************
  This program converts a PFM (Portable Float Map) image to PAM.

  By Bryan Henderson, San Jose, CA April 2004.

  Contributed to the public domain by its author.

*****************************************************************************/

#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <assert.h>

#include "pm_c_util.h"
#include "pam.h"
#include "pm_gamma.h"
#include "shhopt.h"
#include "mallocvar.h"


struct cmdlineInfo {
    const char * inputFilespec;
    unsigned int verbose;
    sample maxval;
};



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 pm_optParseOptions3 on how to parse our options. */
    optStruct3 opt;

    unsigned int option_def_index;
    unsigned int maxvalSpec;

    option_def_index = 0;   /* incremented by OPTENTRY */
    OPTENT3(0, "maxval",   OPT_UINT, &cmdlineP->maxval, &maxvalSpec,        0);
    OPTENT3(0, "verbose",  OPT_FLAG, NULL,             &cmdlineP->verbose, 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 */

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

    if (!maxvalSpec)
        cmdlineP->maxval = PNM_MAXMAXVAL;

    if (cmdlineP->maxval > PNM_OVERALLMAXVAL)
        pm_error("Maximum allowed -maxval is %u.  You specified %u",
                 PNM_OVERALLMAXVAL, (unsigned)cmdlineP->maxval);
    else if (cmdlineP->maxval == 0)
        pm_error("-maxval cannot be 0");

    /* 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);
}



enum endian {ENDIAN_BIG, ENDIAN_LITTLE};


static enum endian machineEndianness;



static enum endian
thisMachineEndianness(void) {
/*----------------------------------------------------------------------------
   Endianness is a component of the format in which a machine represents
   a number in memory or a register.  It is the only component of the format
   that varies among typical machines.

   Big endianness is the natural format.  In this format, if an integer is
   4 bytes, to be stored at memory address 100-103, the most significant
   byte goes at 100, the next most significant at 101, and the least
   significant byte at 103.  This is natural because it matches the way
   humans read and write numbers.  I.e. 258 is stored as 0x00000102.

   Little endian is extremely common because it is used by IA32.  In the
   example above, the least significant byte goes first, so 258 would be
   stored as 0x02010000.

   You can extend this concept to floating point numbers, even though the
   bytes of a floating point number differ by more than significance.
-----------------------------------------------------------------------------*/
    short const testNumber = 0x0001;

    unsigned char * const storedNumber = (unsigned char *)&testNumber;
    enum endian endianness;

    if (storedNumber[0] == 0x01)
        endianness = ENDIAN_LITTLE;
    else
        endianness = ENDIAN_BIG;

    return endianness;
}



typedef union {
    unsigned char bytes[4];      /* as read from the file */
    float value;
        /* This is valid only if the pfmSample has the same endianness
           as the machine we're running on.
        */
} pfmSample;



static float
floatFromPfmSample(pfmSample   const sample,
                   enum endian const pfmEndianness) {
/*----------------------------------------------------------------------------
   Type converter
-----------------------------------------------------------------------------*/
    if (machineEndianness == pfmEndianness) {
        return sample.value;
    } else {
        pfmSample rightEndianSample;
        unsigned int i, j;

        for (i = 0, j = sizeof(sample.bytes)-1;
             i < sizeof(sample.bytes);
             ++i, --j)

            rightEndianSample.bytes[i] = sample.bytes[j];

        return rightEndianSample.value;
    }
}



struct pfmHeader {
    unsigned int width;
    unsigned int height;
    bool color;
    float scaleFactor;
    enum endian endian;
};


static void
readPfmHeader(FILE *             const ifP,
              struct pfmHeader * const pfmHeaderP) {

    int firstChar;
    int secondChar;
    float scaleFactorEndian;

    firstChar = fgetc(ifP);
    if (firstChar == EOF)
        pm_error("Error reading first character of PFM file");
    secondChar = fgetc(ifP);
    if (secondChar == EOF)
        pm_error("Error reading second character of PFM file");

    if (firstChar != 'P' || (secondChar != 'F' && secondChar != 'f'))
        pm_error("First two characters of input file are '%c%c', but "
                 "for a valid PFM file, they must be 'PF' or 'Pf'.",
                 firstChar, secondChar);

    {
        int whitespace;

        whitespace = fgetc(ifP);
        if (whitespace == EOF)
            pm_error("Error reading third character of PFM file");

        if (!isspace(whitespace))
            pm_error("The 3rd character of the input file is not whitespace.");
    }
    {
        int rc;
        char whitespace;

        rc = fscanf(ifP, "%u %u%c",
                    &pfmHeaderP->width, &pfmHeaderP->height, &whitespace);

        if (rc == EOF)
            pm_error("Error reading the width and height from input file.");
        else if (rc != 3)
            pm_error("Invalid input file format where width and height "
                     "are supposed to be (should be two positive decimal "
                     "integers separated by a space and followed by "
                     "white space)");

        if (!isspace(whitespace))
            pm_error("Invalid input file format -- '%c' instead of "
                     "white space after height", whitespace);

        if (pfmHeaderP->width == 0)
            pm_error("Invalid input file: image width is zero");
        if (pfmHeaderP->height == 0)
            pm_error("Invalid input file: image height is zero");
    }
    {
        int rc;
        char whitespace;

        rc = fscanf(ifP, "%f%c", &scaleFactorEndian, &whitespace);

        if (rc == EOF)
            pm_error("Error reading the scale factor from input file.");
        else if (rc != 2)
            pm_error("Invalid input file format where scale factor "
                     "is supposed to be (should be a floating point decimal "
                     "number followed by white space");

        if (!isspace(whitespace))
            pm_error("Invalid input file format -- '%c' instead of "
                     "white space after scale factor", whitespace);
    }

    pfmHeaderP->color = (secondChar == 'F');
        /* 'PF' = RGB, 'Pf' = monochrome */

    if (scaleFactorEndian > 0.0) {
        pfmHeaderP->endian = ENDIAN_BIG;
        pfmHeaderP->scaleFactor = scaleFactorEndian;
    } else if (scaleFactorEndian < 0.0) {
        pfmHeaderP->endian = ENDIAN_LITTLE;
        pfmHeaderP->scaleFactor = - scaleFactorEndian;
    } else
        pm_error("Scale factor/endianness in PFM header is 0");
}



static void
dumpPfmHeader(struct pfmHeader const pfmHeader) {

    pm_message("width: %u, height: %u", pfmHeader.width, pfmHeader.height);
    pm_message("color: %s", pfmHeader.color ? "YES" : "NO");
    pm_message("endian: %s",
               pfmHeader.endian == ENDIAN_BIG ? "BIG" : "LITTLE");
    pm_message("scale factor: %f", pfmHeader.scaleFactor);
}



static void
initPam(struct pam * const pamP,
        int          const width,
        int          const height,
        bool         const color,
        sample       const maxval) {

    pamP->size        = sizeof(*pamP);
    pamP->len         = PAM_STRUCT_SIZE(tuple_type);
    pamP->file        = stdout;
    pamP->format      = PAM_FORMAT;
    pamP->plainformat = FALSE;
    pamP->width       = width;
    pamP->height      = height;
    pamP->maxval      = maxval;
    if (color) {
        pamP->depth = 3;
        strcpy(pamP->tuple_type, "RGB");
    } else {
        pamP->depth = 1;
        strcpy(pamP->tuple_type, "GRAYSCALE");
    }
}



static void
makePamRow(struct pam * const pamP,
           FILE *       const ifP,
           unsigned int const pfmRow,
           unsigned int const pfmSamplesPerRow,
           tuplen **    const tuplenArray,
           enum endian  const endian,
           float        const scaleFactor,
           pfmSample *  const pfmRowBuffer) {
/*----------------------------------------------------------------------------
   Make a PAM (tuple) row of the form described by *pamP, from the next
   row in the PFM file identified by 'ifP'.  Place it in the proper location
   in the tuple array 'tuplenArray'.

   'endian' is the endianness of the samples in the PFM file.

   'pfmRowNum' is the sequence number (starting at 0, which is the
   bottommost row of the image) of the row we are converting in the
   PFM file.

   Use 'pfmRowBuffer' as a work space; Caller must ensure this array
   has at least 'pfmSamplesPerRow' elements of space in it.
-----------------------------------------------------------------------------*/
    int      const row       = pamP->height - pfmRow - 1;
    tuplen * const tuplenRow = tuplenArray[row];

    int col;
    int pfmCursor;
    int rc;

    rc = fread(pfmRowBuffer, sizeof(pfmSample), pfmSamplesPerRow, ifP);
    if (rc != pfmSamplesPerRow)
        pm_error("End of file in the middle of row %d", pfmRow);

    pfmCursor = 0;

    for (col = 0; col < pamP->width; ++col) {
        /* The order of planes (R, G, B) is the same in PFM as in PAM. */
        unsigned int plane;
        for (plane = 0; plane < pamP->depth; ++plane) {
            float const val =
                floatFromPfmSample(pfmRowBuffer[pfmCursor++], endian);
            tuplenRow[col][plane] = val / scaleFactor;
        }
    }
    assert(pfmCursor == pfmSamplesPerRow);
}



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

    struct cmdlineInfo cmdline;
    FILE* ifP;
    struct pam pam;
    struct pfmHeader pfmHeader;
    pfmSample * pfmRowBuffer;
    unsigned int pfmSamplesPerRow;
    unsigned pfmRow;
    tuplen ** tuplenArray;

    machineEndianness = thisMachineEndianness();

    pnm_init(&argc, argv);

    parseCommandLine(argc, argv, &cmdline);

    ifP = pm_openr(cmdline.inputFilespec);

    readPfmHeader(ifP, &pfmHeader);

    if (cmdline.verbose)
        dumpPfmHeader(pfmHeader);

    initPam(&pam,
            pfmHeader.width, pfmHeader.height, pfmHeader.color,
            cmdline.maxval);

    tuplenArray = pnm_allocpamarrayn(&pam);

    pfmSamplesPerRow = pam.width * pam.depth;

    MALLOCARRAY_NOFAIL(pfmRowBuffer, pfmSamplesPerRow);

    /* PFMs are upside down like BMPs */
    for (pfmRow = 0; pfmRow < pam.height; ++pfmRow)
        makePamRow(&pam, ifP, pfmRow, pfmSamplesPerRow,
                   tuplenArray, pfmHeader.endian, pfmHeader.scaleFactor,
                   pfmRowBuffer);

    pnm_writepamn(&pam, tuplenArray);

    pnm_freepamarrayn(tuplenArray, &pam);
    free(pfmRowBuffer);

    pm_close(ifP);
    pm_close(pam.file);

    return 0;
}