about summary refs log tree commit diff
path: root/editor/pnmgamma.c
blob: e10e138b7e17307ea5d6c0a2e04195bb3e122aa8 (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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
/* pnmgamma.c - perform gamma correction on a PNM image
**
** Copyright (C) 1991 by Bill Davidson and Jef Poskanzer.
**
** 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.
*/

#include <assert.h>
#include <math.h>
#include <ctype.h>

#include "pm_c_util.h"
#include "mallocvar.h"
#include "shhopt.h"
#include "pnm.h"

enum transferFunction {
    XF_EXP,
    XF_EXP_INVERSE,
    XF_BT709RAMP,
    XF_BT709RAMP_INVERSE,
    XF_SRGBRAMP,
    XF_SRGBRAMP_INVERSE,
    XF_BT709_TO_SRGB,
    XF_SRGB_TO_BT709
};

struct cmdlineInfo {
    /* All the information the user supplied in the command line,
       in a form easy for the program to use.
    */
    const char * filespec;  /* '-' if stdin */
    enum transferFunction transferFunction;
    float rgamma, ggamma, bgamma;
    unsigned int maxval;
    unsigned int makeNewMaxval;
};



static void
interpretOldArguments(int                  const argc,
                      char **              const argv,
                      float                const defaultGamma,
                      struct cmdlineInfo * const cmdlineP) {

    /* Use the old syntax wherein the gamma values come from arguments.
       If there is one argument, it's a gamma value for all three
       components.  If 3 arguments, it's separate gamma values.  If
       2, it's a single gamma value plus a file name.  If 4, it's
       separate gamma values plus a file name.
    */
    if (argc-1 == 0) {
        cmdlineP->rgamma = defaultGamma;
        cmdlineP->ggamma = defaultGamma;
        cmdlineP->bgamma = defaultGamma;
        cmdlineP->filespec = "-";
    } else if (argc-1 == 1) {
        cmdlineP->rgamma = atof(argv[1]);
        cmdlineP->ggamma = atof(argv[1]);
        cmdlineP->bgamma = atof(argv[1]);
        cmdlineP->filespec = "-";
    } else if (argc-1 == 2) {
        cmdlineP->rgamma = atof(argv[1]);
        cmdlineP->ggamma = atof(argv[1]);
        cmdlineP->bgamma = atof(argv[1]);
        cmdlineP->filespec = argv[2];
    } else if (argc-1 == 3) {
        cmdlineP->rgamma = atof(argv[1]);
        cmdlineP->ggamma = atof(argv[2]);
        cmdlineP->bgamma = atof(argv[3]);
        cmdlineP->filespec = "-";
    } else if (argc-1 == 4) {
        cmdlineP->rgamma = atof(argv[1]);
        cmdlineP->ggamma = atof(argv[2]);
        cmdlineP->bgamma = atof(argv[3]);
        cmdlineP->filespec = argv[4];
    } else 
        pm_error("Wrong number of arguments.  "
                 "You may have 0, 1, or 3 gamma values "
                 "plus zero or one filename");
        
    if (cmdlineP->rgamma <= 0.0 || 
        cmdlineP->ggamma <= 0.0 || 
        cmdlineP->bgamma <= 0.0 )
        pm_error("Invalid gamma value.  Must be positive floating point "
                 "number.");
}



static void
getGammaFromOpts(struct cmdlineInfo * const cmdlineP,
                 bool                 const gammaSpec,
                 float                const gammaOpt,
                 bool                 const rgammaSpec,
                 bool                 const ggammaSpec,
                 bool                 const bgammaSpec,
                 float                const defaultGamma) {

    if (gammaSpec)
        if (gammaOpt < 0.0)
            pm_error("Invalid gamma value %f.  Must be positive.", gammaOpt);
    
    if (rgammaSpec) {
        if (cmdlineP->rgamma < 0.0)
            pm_error("Invalid red gamma value %f.  Must be positive.",
                     cmdlineP->rgamma);
    } else {
        if (gammaSpec)
            cmdlineP->rgamma = gammaOpt;
        else 
            cmdlineP->rgamma = defaultGamma;
    }
    if (ggammaSpec) {
        if (cmdlineP->ggamma < 0.0) 
            pm_error("Invalid green gamma value %f.  Must be positive.",
                     cmdlineP->ggamma);
    } else {
        if (gammaSpec)
            cmdlineP->ggamma = gammaOpt;
        else 
            cmdlineP->ggamma = defaultGamma;
    }
    if (bgammaSpec) {
        if (cmdlineP->bgamma < 0.0)
            pm_error("Invalid blue gamma value %f.  Must be positive.",
                     cmdlineP->bgamma);
    } else {
        if (gammaSpec)
            cmdlineP->bgamma = gammaOpt;
        else
            cmdlineP->bgamma = defaultGamma;
    }
}



static void
parseCommandLine(int argc, char ** argv, 
                 struct cmdlineInfo * const cmdlineP) {

    optEntry *option_def;
        /* Instructions to pm_optParseOptions3 on how to parse our options.
         */
    optStruct3 opt;

    unsigned int bt709ramp, srgbramp, ungamma, bt709tosrgb, srgbtobt709;
    unsigned int bt709tolinear, lineartobt709;
    unsigned int gammaSpec, rgammaSpec, ggammaSpec, bgammaSpec;
    float gammaOpt;
    float defaultGamma;
    unsigned int option_def_index;

    MALLOCARRAY_NOFAIL(option_def, 100);

    option_def_index = 0;   /* incremented by OPTENT3 */
    OPTENT3(0, "ungamma",       OPT_FLAG,   NULL,
            &ungamma,                 0);
    OPTENT3(0, "bt709tolinear", OPT_FLAG,   NULL,
            &bt709tolinear,           0);
    OPTENT3(0, "lineartobt709", OPT_FLAG,   NULL,
            &lineartobt709,           0);
    OPTENT3(0, "bt709ramp",     OPT_FLAG,   NULL,
            &bt709ramp,               0);
    OPTENT3(0, "cieramp",       OPT_FLAG,   NULL,
            &bt709ramp,               0);
    OPTENT3(0, "srgbramp",      OPT_FLAG,   NULL,
            &srgbramp,                0);
    OPTENT3(0, "bt709tosrgb",   OPT_FLAG,   NULL,
            &bt709tosrgb,             0);
    OPTENT3(0, "srgbtobt709",   OPT_FLAG,   NULL,
            &srgbtobt709,             0);
    OPTENT3(0, "maxval",        OPT_UINT,   &cmdlineP->maxval,
            &cmdlineP->makeNewMaxval, 0);
    OPTENT3(0, "gamma",         OPT_FLOAT,  &gammaOpt,
            &gammaSpec,               0);
    OPTENT3(0, "rgamma",        OPT_FLOAT,  &cmdlineP->rgamma,
            &rgammaSpec,              0);
    OPTENT3(0, "ggamma",        OPT_FLOAT,  &cmdlineP->ggamma,
            &ggammaSpec,              0);
    OPTENT3(0, "bgamma",        OPT_FLOAT,  &cmdlineP->bgamma,
            &bgammaSpec,              0);

    opt.opt_table = option_def;
    opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
    opt.allowNegNum = TRUE; 

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

    if (bt709tolinear + lineartobt709 + bt709ramp + srgbramp +
        bt709tosrgb + srgbtobt709 > 1)
        pm_error("You may specify only one function option");
    else {
        if (bt709tolinear) {
            if (ungamma)
                pm_error("You cannot specify -ungamma with -bt709tolinear");
            else
                cmdlineP->transferFunction = XF_BT709RAMP_INVERSE;
        } else if (lineartobt709) {
            if (ungamma)
                pm_error("You cannot specify -ungamma with -lineartobt709");
            else
                cmdlineP->transferFunction = XF_BT709RAMP;
        } else if (bt709tosrgb) {
            if (ungamma)
                pm_error("You cannot specify -ungamma with -bt709tosrgb");
            else
                cmdlineP->transferFunction = XF_BT709_TO_SRGB;
        } else if (srgbtobt709) {
            if (ungamma)
                pm_error("You cannot specify -ungamma with -srgbtobt709");
            else
                cmdlineP->transferFunction = XF_SRGB_TO_BT709;
        } else if (bt709ramp) {
            if (ungamma)
                cmdlineP->transferFunction = XF_BT709RAMP_INVERSE;
            else
                cmdlineP->transferFunction = XF_BT709RAMP;
        } else if (srgbramp) {
            if (ungamma)
                cmdlineP->transferFunction = XF_SRGBRAMP_INVERSE;
            else
                cmdlineP->transferFunction = XF_SRGBRAMP;
        } else {
            if (ungamma)
                cmdlineP->transferFunction = XF_EXP_INVERSE;
            else
                cmdlineP->transferFunction = XF_EXP;
        }
    }

    if (cmdlineP->makeNewMaxval) {
        if (cmdlineP->maxval > PNM_OVERALLMAXVAL)
            pm_error("Largest possible maxval is %u.  You specified %u",
                     PNM_OVERALLMAXVAL, cmdlineP->maxval);
    }

    switch (cmdlineP->transferFunction) {
    case XF_BT709RAMP:
    case XF_BT709RAMP_INVERSE:
    case XF_SRGB_TO_BT709:
        defaultGamma = 1.0/0.45;
        break;
    case XF_SRGBRAMP:
    case XF_SRGBRAMP_INVERSE:
    case XF_BT709_TO_SRGB:
        /* The whole function is often approximated with
           exponent 2.2 and no linear piece.  We do the linear
           piece, so we use the real exponent of 2.4.
        */
        defaultGamma = 2.4;
        break;
    case XF_EXP:
    case XF_EXP_INVERSE:
        defaultGamma = 2.2;
        break;
    }

    if (bt709tolinear || lineartobt709 || bt709tosrgb || srgbtobt709) {
        /* Use the new syntax wherein the gamma values come from options,
           not arguments.  So if there's an argument, it's a file name.
        */
        getGammaFromOpts(cmdlineP, gammaSpec, gammaOpt,
                         rgammaSpec, ggammaSpec, bgammaSpec, defaultGamma);

        if (argc-1 < 1)
            cmdlineP->filespec = "-";
        else {
            cmdlineP->filespec = argv[1];
            if (argc-1 > 1)
                pm_error("Too many arguments (%u).  With this function, there "
                         "is at most one argument:  the file name", argc-1);
        }
    } else {
        if (gammaSpec || rgammaSpec || ggammaSpec || bgammaSpec)
            pm_error("With this function, you specify the gamma values in "
                     "arguments, not with the -gamma, etc.");
        interpretOldArguments(argc, argv, defaultGamma, cmdlineP);
    }
}



static void
buildPowGamma(xelval       table[],
              xelval const maxval,
              xelval const newMaxval,
              double const gamma) {
/*----------------------------------------------------------------------------
   Build a gamma table of size maxval+1 for the given gamma value.
  
   This function depends on pow(3m).  If you don't have it, you can
   simulate it with '#define pow(x,y) exp((y)*log(x))' provided that
   you have the exponential function exp(3m) and the natural logarithm
   function log(3m).  I can't believe I actually remembered my log
   identities.
-----------------------------------------------------------------------------*/
    xelval i;
    double const oneOverGamma = 1.0 / gamma;

    for (i = 0 ; i <= maxval; ++i) {
        double const normalized = ((double) i) / maxval;
            /* Xel sample value normalized to 0..1 */
        double const v = pow(normalized, oneOverGamma);

        table[i] = MIN((xelval)(v * newMaxval + 0.5), newMaxval);  
            /* denormalize, round and clip */
    }
}



static void
buildBt709Gamma(xelval       table[],
                xelval const maxval,
                xelval const newMaxval,
                double const gamma) {
/*----------------------------------------------------------------------------
   Build a gamma table of size maxval+1 for the ITU Recommendation
   BT.709 gamma transfer function.

   'gamma' must be 1/0.45 for true Rec. 709.
-----------------------------------------------------------------------------*/
    double const oneOverGamma = 1.0 / gamma;
    xelval i;

    /* This transfer function is linear for sample values 0
       .. maxval*.018 and an exponential for larger sample values.
       The exponential is slightly stretched and translated, though,
       unlike the popular pure exponential gamma transfer function.
    */
    xelval const linearCutoff = (xelval) (maxval * 0.018 + 0.5);
    double const linearExpansion = 
        (1.099 * pow(0.018, oneOverGamma) - 0.099) / 0.018;
    double const maxvalScaler = (double)newMaxval/maxval;

    for (i = 0; i <= linearCutoff; ++i) 
        table[i] = i * linearExpansion * maxvalScaler + 0.5;
    for (; i <= maxval; ++i) {
        double const normalized = ((double) i) / maxval;
            /* Xel sample value normalized to 0..1 */
        double const v = 1.099 * pow(normalized, oneOverGamma) - 0.099;
        table[i] = MIN((xelval)(v * newMaxval + 0.5), newMaxval);  
            /* denormalize, round, and clip */
    }
}



static void
buildBt709GammaInverse(xelval       table[],
                       xelval const maxval,
                       xelval const newMaxval,
                       double const gamma) {
/*----------------------------------------------------------------------------
   Build a gamma table of size maxval+1 for the Inverse of the ITU
   Rec. BT.709 gamma transfer function.

   'gamma' must be 1/0.45 for true Rec. 709.
-----------------------------------------------------------------------------*/
    double const oneOverGamma = 1.0 / gamma;
    xelval i;

    /* This transfer function is linear for sample values 0
       .. maxval*.018 and an exponential for larger sample values.
       The exponential is slightly stretched and translated, though,
       unlike the popular pure exponential gamma transfer function.
    */

    xelval const linearCutoff = (xelval) (maxval * 0.018 + 0.5);
    double const linearCompression = 
        0.018 / (1.099 * pow(0.018, oneOverGamma) - 0.099);
    double const maxvalScaler = (double)newMaxval/maxval;

    for (i = 0; i <= linearCutoff / linearCompression; ++i) 
        table[i] = i * linearCompression * maxvalScaler + 0.5;

    for (; i <= maxval; ++i) {
        double const normalized = ((double) i) / maxval;
            /* Xel sample value normalized to 0..1 */
        double const v = pow((normalized + 0.099) / 1.099, gamma);
        table[i] = MIN((xelval)(v * newMaxval + 0.5), newMaxval);  
            /* denormalize, round, and clip */
    }
}



static void
buildSrgbGamma(xelval       table[],
               xelval const maxval,
               xelval const newMaxval,
               double const gamma) {
/*----------------------------------------------------------------------------
   Build a gamma table of size maxval+1 for the IEC SRGB gamma
   transfer function (Standard IEC 61966-2-1).

   'gamma' must be 2.4 for true SRGB
-----------------------------------------------------------------------------*/
    double const oneOverGamma = 1.0 / gamma;
    xelval i;

    /* This transfer function is linear for sample values 0
       .. maxval*.040405 and an exponential for larger sample values.
       The exponential is slightly stretched and translated, though,
       unlike the popular pure exponential gamma transfer function.
    */
    xelval const linearCutoff = (xelval) maxval * 0.0031308 + 0.5;
    double const linearExpansion = 
        (1.055 * pow(0.0031308, oneOverGamma) - 0.055) / 0.0031308;
    double const maxvalScaler = (double)newMaxval/maxval;

    for (i = 0; i <= linearCutoff; ++i) 
        table[i] = i * linearExpansion * maxvalScaler + 0.5;
    for (; i <= maxval; ++i) {
        double const normalized = ((double) i) / maxval;
            /* Xel sample value normalized to 0..1 */
        double const v = 1.055 * pow(normalized, oneOverGamma) - 0.055;
        table[i] = MIN((xelval)(v * newMaxval + 0.5), newMaxval);  
            /* denormalize, round, and clip */
    }
}



static void
buildSrgbGammaInverse(xelval       table[],
                      xelval const maxval,
                      xelval const newMaxval,
                      double const gamma) {
/*----------------------------------------------------------------------------
   Build a gamma table of size maxval+1 for the Inverse of the IEC SRGB gamma
   transfer function (Standard IEC 61966-2-1).

   'gamma' must be 2.4 for true SRGB
-----------------------------------------------------------------------------*/
    double const oneOverGamma = 1.0 / gamma;
    xelval i;

    /* This transfer function is linear for sample values 0
       .. maxval*.040405 and an exponential for larger sample values.
       The exponential is slightly stretched and translated, though,
       unlike the popular pure exponential gamma transfer function.
    */
    xelval const linearCutoff = (xelval) maxval * 0.0031308 + 0.5;
    double const linearCompression = 
        0.0031308 / (1.055 * pow(0.0031308, oneOverGamma) - 0.055);
    double const maxvalScaler = (double)newMaxval/maxval;

    for (i = 0; i <= linearCutoff / linearCompression; ++i) 
        table[i] = i * linearCompression * maxvalScaler + 0.5;
    for (; i <= maxval; ++i) {
        double const normalized = ((double) i) / maxval;
            /* Xel sample value normalized to 0..1 */
        double const v = pow((normalized + 0.055) / 1.055, gamma);
        table[i] = MIN((xelval)(v * newMaxval + 0.5), newMaxval);  
            /* denormalize, round, and clip */
    }
}



static void
buildBt709ToSrgbGamma(xelval       table[],
                      xelval const maxval,
                      xelval const newMaxval,
                      double const gammaSrgb) {
/*----------------------------------------------------------------------------
   Build a gamma table of size maxval+1 for the combination of the
   inverse of ITU Rec BT.709 and the forward SRGB gamma transfer
   functions.  I.e. this converts from Rec 709 to SRGB.

   'gammaSrgb' must be 2.4 for true SRGB.
-----------------------------------------------------------------------------*/
    double const oneOverGamma709  = 0.45;
    double const gamma709         = 1.0 / oneOverGamma709;
    double const oneOverGammaSrgb = 1.0 / gammaSrgb;
    double const normalizer       = 1.0 / maxval;

    /* This transfer function is linear for sample values 0
       .. maxval*.018 and an exponential for larger sample values.
       The exponential is slightly stretched and translated, though,
       unlike the popular pure exponential gamma transfer function.
    */

    xelval const linearCutoff709 = (xelval) (maxval * 0.018 + 0.5);
    double const linearCompression709 = 
        0.018 / (1.099 * pow(0.018, oneOverGamma709) - 0.099);

    double const linearCutoffSrgb = 0.0031308;
    double const linearExpansionSrgb = 
        (1.055 * pow(0.0031308, oneOverGammaSrgb) - 0.055) / 0.0031308;

    xelval i;

    for (i = 0; i <= maxval; ++i) {
        double const normalized = i * normalizer;
            /* Xel sample value normalized to 0..1 */
        double radiance;
        double srgb;

        if (i < linearCutoff709 / linearCompression709)
            radiance = normalized * linearCompression709;
        else
            radiance = pow((normalized + 0.099) / 1.099, gamma709);

        assert(radiance <= 1.0);

        if (radiance < linearCutoffSrgb * normalizer)
            srgb = radiance * linearExpansionSrgb;
        else
            srgb = 1.055 * pow(radiance, oneOverGammaSrgb) - 0.055;

        assert(srgb <= 1.0);

        table[i] = srgb * newMaxval + 0.5;
    }
}



static void
buildSrgbToBt709Gamma(xelval       table[],
                      xelval const maxval,
                      xelval const newMaxval,
                      double const gamma709) {
/*----------------------------------------------------------------------------
   Build a gamma table of size maxval+1 for the combination of the
   inverse of SRGB and the forward ITU Rec BT.709 gamma transfer
   functions.  I.e. this converts from SRGB to Rec 709.

   'gamma709' must be 1/0.45 for true Rec. 709.
-----------------------------------------------------------------------------*/
    double const oneOverGamma709  = 1.0 / gamma709;
    double const gammaSrgb        = 2.4;
    double const oneOverGammaSrgb = 1.0 / gammaSrgb;
    double const normalizer       = 1.0 / maxval;

    /* This transfer function is linear for sample values 0
       .. maxval*.040405 and an exponential for larger sample values.
       The exponential is slightly stretched and translated, though,
       unlike the popular pure exponential gamma transfer function.
    */
    xelval const linearCutoffSrgb = (xelval) maxval * 0.0031308 + 0.5;
    double const linearCompressionSrgb = 
        0.0031308 / (1.055 * pow(0.0031308, oneOverGammaSrgb) - 0.055);

    xelval const linearCutoff709 = (xelval) (maxval * 0.018 + 0.5);
    double const linearExpansion709 = 
        (1.099 * pow(0.018, oneOverGamma709) - 0.099) / 0.018;

    xelval i;

    for (i = 0; i <= maxval; ++i) {
        double const normalized = i * normalizer;
            /* Xel sample value normalized to 0..1 */
        double radiance;
        double bt709;

        if (i < linearCutoffSrgb / linearCompressionSrgb)
            radiance = normalized * linearCompressionSrgb;
        else
            radiance = pow((normalized + 0.055) / 1.055, gammaSrgb);

        assert(radiance <= 1.0);

        if (radiance < linearCutoff709 * normalizer)
            bt709 = radiance * linearExpansion709;
        else
            bt709 = 1.099 * pow(radiance, oneOverGamma709) - 0.099;

        assert(bt709 <= 1.0);

        table[i] = bt709 * newMaxval + 0.5;
    }
}



static void
createGammaTables(enum transferFunction const transferFunction,
                  xelval                const maxval,
                  xelval                const newMaxval,
                  double                const rgamma, 
                  double                const ggamma, 
                  double                const bgamma,
                  xelval **             const rtableP,
                  xelval **             const gtableP,
                  xelval **             const btableP) {

    /* Allocate space for the tables. */
    MALLOCARRAY(*rtableP, maxval+1);
    MALLOCARRAY(*gtableP, maxval+1);
    MALLOCARRAY(*btableP, maxval+1);
    if (*rtableP == NULL || *gtableP == NULL || *btableP == NULL)
        pm_error("Can't get memory to make gamma transfer tables");

    /* Build the gamma correction tables. */
    switch (transferFunction) {
    case XF_BT709RAMP: {
        buildBt709Gamma(*rtableP, maxval, newMaxval, rgamma);
        buildBt709Gamma(*gtableP, maxval, newMaxval, ggamma);
        buildBt709Gamma(*btableP, maxval, newMaxval, bgamma);
    } break;

    case XF_BT709RAMP_INVERSE: {
        buildBt709GammaInverse(*rtableP, maxval, newMaxval, rgamma);
        buildBt709GammaInverse(*gtableP, maxval, newMaxval, ggamma);
        buildBt709GammaInverse(*btableP, maxval, newMaxval, bgamma);
    } break;

    case XF_SRGBRAMP: {
        buildSrgbGamma(*rtableP, maxval, newMaxval, rgamma);
        buildSrgbGamma(*gtableP, maxval, newMaxval, ggamma);
        buildSrgbGamma(*btableP, maxval, newMaxval, bgamma);
    } break;

    case XF_SRGBRAMP_INVERSE: {
        buildSrgbGammaInverse(*rtableP, maxval, newMaxval, rgamma);
        buildSrgbGammaInverse(*gtableP, maxval, newMaxval, ggamma);
        buildSrgbGammaInverse(*btableP, maxval, newMaxval, bgamma);
    } break;

    case XF_EXP: {
        buildPowGamma(*rtableP, maxval, newMaxval, rgamma);
        buildPowGamma(*gtableP, maxval, newMaxval, ggamma);
        buildPowGamma(*btableP, maxval, newMaxval, bgamma);
    } break;

    case XF_EXP_INVERSE: {
        buildPowGamma(*rtableP, maxval, newMaxval, 1.0/rgamma);
        buildPowGamma(*gtableP, maxval, newMaxval, 1.0/ggamma);
        buildPowGamma(*btableP, maxval, newMaxval, 1.0/bgamma);
    } break;

    case XF_BT709_TO_SRGB: {
        buildBt709ToSrgbGamma(*rtableP, maxval, newMaxval, rgamma);
        buildBt709ToSrgbGamma(*gtableP, maxval, newMaxval, ggamma);
        buildBt709ToSrgbGamma(*btableP, maxval, newMaxval, bgamma);
    } break;

    case XF_SRGB_TO_BT709: {
        buildSrgbToBt709Gamma(*rtableP, maxval, newMaxval, rgamma);
        buildSrgbToBt709Gamma(*gtableP, maxval, newMaxval, ggamma);
        buildSrgbToBt709Gamma(*btableP, maxval, newMaxval, bgamma);
    } break;
    }
}



static void
convertRaster(FILE *   const ifP,
              FILE *   const ofP,
              int      const cols,
              int      const rows,
              xelval   const maxval,
              int      const format,
              xelval   const outputMaxval,
              int      const outputFormat,
              xelval * const rtable,
              xelval * const gtable,
              xelval * const btable) {

    xel * xelrow;
    unsigned int row;

    xelrow = pnm_allocrow(cols);

    for (row = 0; row < rows; ++row) {
        pnm_readpnmrow(ifP, xelrow, cols, maxval, format);

        pnm_promoteformatrow(xelrow, cols, maxval, format, 
                             maxval, outputFormat);

        switch (PNM_FORMAT_TYPE(outputFormat)) {
        case PPM_TYPE: {
            unsigned int col;
            for (col = 0; col < cols; ++col) {
                xelval const r = PPM_GETR(xelrow[col]);
                xelval const g = PPM_GETG(xelrow[col]);
                xelval const b = PPM_GETB(xelrow[col]);
                PPM_ASSIGN(xelrow[col], rtable[r], gtable[g], btable[b]);
            }
        } break;

        case PGM_TYPE: {
            unsigned int col;
            for (col = 0; col < cols; ++col) {
                xelval const xel = PNM_GET1(xelrow[col]);
                PNM_ASSIGN1(xelrow[col], gtable[xel]);
            }
        } break;
        default:
            pm_error("Internal error.  Impossible format type");
        }
        pnm_writepnmrow(ofP, xelrow, cols, outputMaxval, outputFormat, 0);
    }
    pnm_freerow(xelrow);
}



int
main(int argc, char *argv[]) {
    struct cmdlineInfo cmdline;
    FILE * ifP;
    xelval maxval;
    int rows, cols, format;
    xelval outputMaxval;
    int outputFormat;
    xelval * rtable;
    xelval * gtable;
    xelval * btable;

    pnm_init(&argc, argv);

    parseCommandLine(argc, argv, &cmdline);

    ifP = pm_openr(cmdline.filespec);

    pnm_readpnminit(ifP, &cols, &rows, &maxval, &format);

    if (PNM_FORMAT_TYPE(format) == PPM_TYPE)
        outputFormat = PPM_TYPE;
    else if (cmdline.rgamma != cmdline.ggamma 
             || cmdline.ggamma != cmdline.bgamma) 
        outputFormat = PPM_TYPE;
    else 
        outputFormat = PGM_TYPE;

    if (PNM_FORMAT_TYPE(format) != outputFormat) {
        if (outputFormat == PPM_TYPE)
            pm_message("Promoting to PPM");
        if (outputFormat == PGM_TYPE)
            pm_message("Promoting to PGM");
    }

    outputMaxval = cmdline.makeNewMaxval ? cmdline.maxval : maxval;

    createGammaTables(cmdline.transferFunction, maxval,
                      outputMaxval,
                      cmdline.rgamma, cmdline.ggamma, cmdline.bgamma,
                      &rtable, &gtable, &btable);

    pnm_writepnminit(stdout, cols, rows, outputMaxval, outputFormat, 0);

    convertRaster(ifP, stdout, cols, rows, maxval, format,
                  outputMaxval, outputFormat,
                  rtable, gtable, btable);

    pm_close(ifP);
    pm_close(stdout);

    return 0;
}