about summary refs log tree commit diff
path: root/editor/pamaltsat.c
blob: 3bff55bd5f02c9bacf82dd376220c4d8a060ad32 (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
#include <stdbool.h>
#include <assert.h>
#include <string.h>

#include <pam.h>
#include <pm_gamma.h>
#include <nstring.h>

#include "shhopt.h"
#include "mallocvar.h"

typedef unsigned int  uint;
typedef unsigned char uchar;

typedef enum {MLog,  MSpectrum } Method; /* method identifiers */

typedef struct {
    Method       method;
    const char * name;
} MethodTableEntry;

MethodTableEntry methodTable[] = {
    {MLog,      "log"},
    {MSpectrum, "spectrum"}
};

/* Command-line arguments parsed: */
typedef struct {
    const char * inputFileName;
        /* name of the input file. "-" for stdin */
    float        strength;
    uint         linear;
    Method       method;
} CmdlineInfo;




static Method
methodFmNm(const char * const methodNm) {
/*----------------------------------------------------------------------------
   The method of saturation whose name is 'methodNm'
-----------------------------------------------------------------------------*/
    uint  i;
    bool found;
    Method method;

    for (i = 0, found = false; i < ARRAY_SIZE(methodTable) && !found; ++i) {
        if (streq(methodNm, methodTable[i].name)) {
            found = true;
            method = methodTable[i].method;
        }
    }

    if (!found) {
        /* Issue error message and abort */
        char * methodList;
        uint   methodListLen;
        uint   i;

        /* Allocate a buffer to store the list of known saturation methods: */
        for (i = 0, methodListLen = 0; i < ARRAY_SIZE(methodTable); ++i)
            methodListLen += strlen(methodTable[i].name) + 2;

        MALLOCARRAY(methodList, methodListLen);

        if (!methodList)
            pm_error("Failed to allocate memory for %lu saturation "
                     "method names", (unsigned long)ARRAY_SIZE(methodTable));

        /* Fill the list of methods: */
        for (i = 0, methodList[0] = '\0'; i < ARRAY_SIZE(methodTable); ++i) {
            if (i > 0)
                strcat(methodList, ", ");
            strcat(methodList, methodTable[i].name);
        }

        pm_error("Unknown saturation method: '%s'. Known methods are: %s",
                 methodNm, methodList);

        free(methodList);
    }
    return method;
}



static CmdlineInfo
parsedCommandLine(int argc, const char ** argv) {

    CmdlineInfo cmdline;
    optStruct3 opt;

    uint option_def_index;
    uint methodSpec, strengthSpec, linearSpec;
    const char * method;

    optEntry * option_def;
    MALLOCARRAY_NOFAIL(option_def, 100);

    option_def_index = 0;   /* incremented by OPTENT3 */
    OPTENT3(0, "method",   OPT_STRING, &method,            &methodSpec,   0);
    OPTENT3(0, "strength", OPT_FLOAT,  &cmdline.strength,  &strengthSpec, 0);
    OPTENT3(0, "linear",   OPT_FLAG,   &cmdline.linear,    &linearSpec,   0);

    opt.opt_table     = option_def;
    opt.short_allowed = 0;
    opt.allowNegNum   = 0;

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

    if (methodSpec)
        cmdline.method = methodFmNm(method);
    else
        cmdline.method = MSpectrum;

    if (!strengthSpec)
        pm_error("You must specify -strength");

    if (!linearSpec)
        cmdline.linear = 0;

    if (argc-1 < 1)
        cmdline.inputFileName = "-";
    else {
        cmdline.inputFileName = argv[1];
        if (argc-1 > 1)
            pm_error("Program takes at most one argument:  file name");
    }

    free(option_def);

    return cmdline;
}



typedef struct {
    double _[3];
} TupleD;

typedef struct {
/*----------------------------------------------------------------------------
  Information about a color sample in linear format
-----------------------------------------------------------------------------*/
    TupleD sample;    /* layer intensities                        */
    double maxval;    /* the highest layer intensity              */
    uint   maxl;      /* index of that layer                      */
    uint   minl;      /* index of the layer with lowest intensity */
    double intensity; /* total sample intensity                   */
} LinSampleInfo;

/* ---------------------------- Binary search ------------------------------ */
/*                    ( a minimal drop-in implementation )                   */

/* Function to search, where <data> is an arbitrary user-supplied parameter */
typedef double (binsearchFunc)(double       const x,
                               const void * const data);

/* The binary-search function. Returns such <x> from [<min>, <max>] that
   monotonically increasing function func(x, data) equals <value> within
   precision <prec>. <dataP> is an arbitrary parameter to <func>. */
static double
binsearch(binsearchFunc       func,
          const void  * const dataP,
          double        const prec,
          double        const minArg,
          double        const maxArg,
          double        const value
         ) {
    double x;
    double min, max;
    bool found;

    for (min = minArg, max = maxArg, found = false; !found;) {

        x = (min + max) / 2;
        {
            double const f = func(x, dataP);

            if ((fabs(f - value)) < prec)
                found = true;
            else {
                assert(f != value);

                if (f > value) max = x;
                else           min = x;
            }
        }
    }
    return x;
}

/* ------------- Utilities not specific to saturation methods -------------- */

/* Y chromaticities in Rec.709: R       G       B  */
static double const yCoeffs[3]  = {0.3333, 0.6061, 0.0606};

static void
applyRatio(TupleD * const tupP,
           double   const ratio) {
/*----------------------------------------------------------------------------
  Multiply the components of tuple *tupP by coefficient 'ratio'.
-----------------------------------------------------------------------------*/
    uint c;

    for (c = 0; c < 3; ++c)
        tupP->_[c] = tupP->_[c] * ratio;
}



static void
getTupInfo(tuplen          const tup,
           bool            const linear,
           LinSampleInfo * const siP) {
/*----------------------------------------------------------------------------
  Convert PBM tuple <tup> into linear form with double precision siP->sample
  and obtain also additional information required for further processing.
  Return the result as *siP.
-----------------------------------------------------------------------------*/
    uint i;
    double minval;

    minval         = 1.1;
    siP->intensity = 0;
    siP->maxval    = 0.0;
    siP->maxl      = 0;

    for (i = 0; i < 3; ++i) {
        double linval;
        if (!linear)
            linval = pm_ungamma709(tup[i]);
        else
            linval = tup[i];

        siP->sample._[i] = linval;

        if (linval > siP->maxval) {
            siP->maxval = linval;
            siP->maxl   = i;
        }
        if (linval < minval) {
           siP->minl = i;
           minval    = linval;
        }
        siP->intensity += linval * yCoeffs[i];
    }
}

/* ------------------------ Logarithmic saturation ------------------------- */

/* Method and algorithm by Anton Shepelev.  */

static void
tryLogSat(double          const sat,
          LinSampleInfo * const siP,
          TupleD *        const tupsatP,
          double *        const intRatioP,
          double *        const highestP) {
/*----------------------------------------------------------------------------
  Try to increase the saturation of siP->sample by a factor 'sat' and return
  the result as *tupsatP.

  Also return as *intRatioP the ratio of intensities of 'tupin' and
  siP->sample.

  Return as *highestP the highest component the saturated color would have if
  normalized to intensity siP->intensity.

  If the return value exceeds unity saturation cannot be properly increased by
  the required factor.
-----------------------------------------------------------------------------*/
    uint   c;
    double intSat;

    for (c = 0, intSat = 0.0; c < 3; ++c) {
        tupsatP->_[c] = pow(siP->sample._[c], sat);
        intSat       = intSat + tupsatP->_[c] * yCoeffs[c];
    }

    {
        double const intRatio = siP->intensity / intSat;

        double const maxComp = tupsatP->_[siP->maxl] * intRatio;

        *intRatioP = intRatio;
        *highestP = maxComp;
    }
}



/* Structure for the binary search of maximum saturation: */
typedef struct {
    LinSampleInfo * siP;
        /* original color with precalculated information  */
    TupleD *        tupsatP;
        /* saturated color                            */
    double *        intRatioP;
        /* ratio of original and saturated intensities */
} MaxLogSatInfo;



static binsearchFunc binsearchMaxLogSat;

static double
binsearchMaxLogSat(double       const x,
                   const void * const dataP) {
/*----------------------------------------------------------------------------
  Target function for the generic binary search routine, for the finding
  of the maximum possible saturation of a given color. 'dataP' shall point
  to a MaxSatInfo structure.
-----------------------------------------------------------------------------*/
    const MaxLogSatInfo * const infoP = dataP;

    double highest;

    tryLogSat(x, infoP->siP, infoP->tupsatP, infoP->intRatioP, &highest);

    return highest;
}



static void
getMaxLogSat(LinSampleInfo * const siP,
             TupleD        * const tupsatP,
             double        * const intRatioP,
             double          const upperLimit
          ) {
/*  Saturates the color <siP->sample> as much as possible and stores the result
    in <tupsatP>, which must be multiplied by <*intRatioP> in order to restore
    the intensity of the original color. The range of saturation search is
    [1.0..<upperlimit>]. */
    const double PREC = 0.00001; /* precision of binary search */

    MaxLogSatInfo info;

    info.siP       = siP;
    info.tupsatP   = tupsatP;
    info.intRatioP = intRatioP;

/*  Discarding return value (maximum saturation) because upon completion of
    binsearch() info.tupsatP will contain the saturated color. The target value
    of maximum channel intensity is decreased by PREC in order to avoid
    overflow. */
    binsearch(binsearchMaxLogSat, &info, PREC, 1.0, upperLimit, 1.0 - PREC);
}



static void
saturateLog(LinSampleInfo* const siP,
            double         const sat,
            TupleD*        const tupsatP) {
/*----------------------------------------------------------------------------
  Saturate linear tuple *siP using the logarithmic saturation method.
-----------------------------------------------------------------------------*/
    double intRatio;
        /* ratio of original and saturated intensities */
    double maxlValSat;
        /* maximum component intensity in the saturated sample */

    tryLogSat(sat, siP, tupsatP, &intRatio, &maxlValSat);

    /* if we cannot saturate siP->sample by 'sat', use the maximum possible
       saturation
    */
    if (maxlValSat > 1.0)
        getMaxLogSat(siP, tupsatP, &intRatio, sat);

    /* restore the original intensity: */
    applyRatio(tupsatP, intRatio);
}



/* ------------------------- Spectrum saturation --------------------------- */

/* Method and algorithm by Anton Shepelev.  */

static void
saturateSpectrum(LinSampleInfo * const siP,
                 double          const sat,
                 TupleD *        const tupsatP) {
/*----------------------------------------------------------------------------
  Saturate linear tuple *siP using the Spectrum saturation method.
-----------------------------------------------------------------------------*/
    double k;
    double * sample;

    sample = siP->sample._; /* short-cut to the input sample data */

    if (sample[siP->minl] == sample[siP->maxl])
        k = 1.0; /* Cannot saturate a neutral sample */
    else {
        double const km1 =
            (1.0 - siP->intensity)/(siP->maxval - siP->intensity);
            /* Maximum saturation factor that keeps maximum layer intensity
               within range
            */
        double const km2 = siP->intensity/(siP->intensity - sample[siP->minl]);
            /* Maximum saturation factor  that keeps minimum layer intensity
               within range
            */

        /* To satisfy both constraints, choose the strictest: */
        double const km = km1 > km2 ? km2 : km1;

        /* Ensure the saturation factor does not exceed the maximum
           possible value:
        */
        k = sat < km ? sat : km;
    }

    {
        /* Initialize the resulting sample with the input value */
        uint i;
        for (i = 0; i < 3; ++i)
            tupsatP->_[i] = sample[i];
    }

    applyRatio(tupsatP, k); /* apply the saturation factor */

    {
         /* restore the original intensity */
        uint i;
        for (i = 0; i < 3; ++i)
            tupsatP->_[i] = tupsatP->_[i] - siP->intensity * (k - 1.0);
    }
}



/* --------------------- General saturation algorithm ---------------------- */

static void
saturateTup(Method const method,
            double const sat,
            bool   const linear,
            tuplen const tup) {
/*----------------------------------------------------------------------------
  Saturate black and white tuple 'tup'
-----------------------------------------------------------------------------*/
    LinSampleInfo si;

    getTupInfo(tup, linear, &si);

    if (sat < 1.0 ||  /* saturation can always be decresed */
        si.maxval < 1.0 ) { /* there is room for increase        */

        TupleD tupsat;

        /* Dispatch saturation methods:
           (There seems too little benefit in using a table of
           function pointers, so a manual switch should suffice)
        */
        switch (method) {
            case MLog:      saturateLog     (&si, sat, &tupsat); break;
            case MSpectrum: saturateSpectrum(&si, sat, &tupsat); break;
        }

        /* Put the processed tuple back in the tuple row, gamma-adjusting it
           if required.
        */
        {
            uint i;

            for (i = 0; i < 3; ++i)
                tup[i] = linear ? tupsat._[i] : pm_gamma709(tupsat._[i]);
        }
    }
}



static void
pamaltsat(CmdlineInfo const cmdline,
          FILE *      const ofP) {

    struct pam inPam, outPam;
    tuplen *   tuplerown;
    FILE *     ifP;
    uint       row;

    ifP = pm_openr(cmdline.inputFileName);

    pnm_readpaminit(ifP, &inPam, PAM_STRUCT_SIZE(tuple_type));

    outPam = inPam;
    outPam.file = ofP;

    tuplerown = pnm_allocpamrown(&inPam);

    pnm_writepaminit(&outPam);

    for (row = 0; row < inPam.height; ++row) {
        pnm_readpamrown(&inPam, tuplerown);

        if (inPam.depth >= 3) {
            uint col;

            for (col = 0; col < inPam.width; ++col)
                saturateTup(cmdline.method, cmdline.strength, cmdline.linear,
                            tuplerown[col]);
        }

        pnm_writepamrown(&outPam, tuplerown);
    }

    pnm_freepamrown(tuplerown);
    pm_close(ifP);
}



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

    CmdlineInfo cmdline;

    pm_proginit(&argc, argv);

    cmdline = parsedCommandLine(argc, argv);

    pamaltsat(cmdline, stdout);

    return 0;
}