summaryrefslogtreecommitdiffstats
path: root/kviewshell/plugins/djvu/libdjvu/DjVuPalette.cpp
blob: 06e6e91179ece8d37c2fbce3032c865b16480499 (plain)
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
//C- -------------------------------------------------------------------
//C- DjVuLibre-3.5
//C- Copyright (c) 2002  Leon Bottou and Yann Le Cun.
//C- Copyright (c) 2001  AT&T
//C-
//C- This software is subject to, and may be distributed under, the
//C- GNU General Public License, Version 2. The license should have
//C- accompanied the software or you may obtain a copy of the license
//C- from the Free Software Foundation at http://www.fsf.org .
//C-
//C- This program is distributed in the hope that it will be useful,
//C- but WITHOUT ANY WARRANTY; without even the implied warranty of
//C- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//C- GNU General Public License for more details.
//C- 
//C- DjVuLibre-3.5 is derived from the DjVu(r) Reference Library
//C- distributed by Lizardtech Software.  On July 19th 2002, Lizardtech 
//C- Software authorized us to replace the original DjVu(r) Reference 
//C- Library notice by the following text (see doc/lizard2002.djvu):
//C-
//C-  ------------------------------------------------------------------
//C- | DjVu (r) Reference Library (v. 3.5)
//C- | Copyright (c) 1999-2001 LizardTech, Inc. All Rights Reserved.
//C- | The DjVu Reference Library is protected by U.S. Pat. No.
//C- | 6,058,214 and patents pending.
//C- |
//C- | This software is subject to, and may be distributed under, the
//C- | GNU General Public License, Version 2. The license should have
//C- | accompanied the software or you may obtain a copy of the license
//C- | from the Free Software Foundation at http://www.fsf.org .
//C- |
//C- | The computer code originally released by LizardTech under this
//C- | license and unmodified by other parties is deemed "the LIZARDTECH
//C- | ORIGINAL CODE."  Subject to any third party intellectual property
//C- | claims, LizardTech grants recipient a worldwide, royalty-free, 
//C- | non-exclusive license to make, use, sell, or otherwise dispose of 
//C- | the LIZARDTECH ORIGINAL CODE or of programs derived from the 
//C- | LIZARDTECH ORIGINAL CODE in compliance with the terms of the GNU 
//C- | General Public License.   This grant only confers the right to 
//C- | infringe patent claims underlying the LIZARDTECH ORIGINAL CODE to 
//C- | the extent such infringement is reasonably necessary to enable 
//C- | recipient to make, have made, practice, sell, or otherwise dispose 
//C- | of the LIZARDTECH ORIGINAL CODE (or portions thereof) and not to 
//C- | any greater extent that may be necessary to utilize further 
//C- | modifications or combinations.
//C- |
//C- | The LIZARDTECH ORIGINAL CODE is provided "AS IS" WITHOUT WARRANTY
//C- | OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
//C- | TO ANY WARRANTY OF NON-INFRINGEMENT, OR ANY IMPLIED WARRANTY OF
//C- | MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
//C- +------------------------------------------------------------------
// 
// $Id: DjVuPalette.cpp,v 1.11 2004/03/18 15:03:50 leonb Exp $
// $Name: release_3_5_15 $

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#if NEED_GNUG_PRAGMAS
# pragma implementation
#endif

#include "GException.h"
#include "ByteStream.h"
#include "BSByteStream.h"
#include "DjVuPalette.h"
#include <stdlib.h>
#include <cmath>


#ifdef HAVE_NAMESPACES
namespace DJVU {
# ifdef NOT_DEFINED // Just to fool emacs c++ mode
}
#endif
#endif


#define CUBEBITS  4
#define CUBESIDE  (1<<CUBEBITS)
#define CUBESIZE  (CUBESIDE*CUBESIDE*CUBESIDE)

#define RMUL 5
#define GMUL 9
#define BMUL 2
#define SMUL (RMUL+GMUL+BMUL)

#define MAXPALETTESIZE 65535 // Limit for a 16 bit unsigned read.


inline unsigned char 
umax(unsigned char a, unsigned char b) 
{ return (a>b) ? a : b; }

inline unsigned char 
umin(unsigned char a, unsigned char b) 
{ return (a>b) ? b : a; }

#if !defined(HAVE_FMIN)
inline float 
fmin(float a, float b) 
{ return (a>b) ? b : a; }
#endif


// ------- DJVUPALETTE


DjVuPalette::DjVuPalette()
  : mask(0), hist(0), pmap(0)
{
}

DjVuPalette::~DjVuPalette()
{
  delete hist;
  delete pmap;
}

DjVuPalette& 
DjVuPalette::operator=(const DjVuPalette &ref)
{
  if (this != &ref)
    {
      delete hist;
      delete pmap;
      mask = 0;
      palette = ref.palette;
      colordata = ref.colordata;
    }
  return *this;
}

DjVuPalette::DjVuPalette(const DjVuPalette &ref)
  : mask(0), hist(0), pmap(0)
{
  this->operator=(ref);
}



// -------- HISTOGRAM ALLOCATION

void
DjVuPalette::allocate_hist()
{
  if (! hist)
    {
      hist = new GMap<int,int>;
      mask = 0;
    }
  else
    {
      GMap<int,int> *old = hist;
      hist = new GMap<int,int>;
      mask = (mask<<1)|(0x010101);
      for (GPosition p = *old; p; ++p)
        {
          int k = old->key(p);
          int w = (*old)[p];
          (*hist)[k | mask] += w;
        }
      delete old;
    }
}


// -------- PALETTE COMPUTATION


#ifndef NEED_DECODER_ONLY

struct PData
{
  unsigned char p[3];
  int w;
};

struct PBox 
{
  PData *data;
  int colors;
  int boxsize;
  int sum;
};
int
DjVuPalette::bcomp (const void *a, const void *b)
{
  return ((PData*)a)->p[0] - ((PData*)b)->p[0];
}

int

DjVuPalette::gcomp (const void *a, const void *b)
{
  return ((PData*)a)->p[1] - ((PData*)b)->p[1];
}

int
DjVuPalette::rcomp (const void *a, const void *b)
{
  return ((PData*)a)->p[2] - ((PData*)b)->p[2];
}

int
DjVuPalette::lcomp (const void *a, const void *b)
{
  unsigned char *aa = ((PColor*)a)->p;
  unsigned char *bb = ((PColor*)b)->p;
  if (aa[3] != bb[3])
    return aa[3]-bb[3];
  else if (aa[2] != bb[2])
    return aa[2]-bb[2];
  else if (aa[1] != bb[1])
    return aa[1]=bb[1];
  else
    return aa[0]-bb[0];
}

int
DjVuPalette::compute_palette(int maxcolors, int minboxsize)
{
  if (!hist)
    G_THROW( ERR_MSG("DjVuPalette.no_color") );
  if (maxcolors<1 || maxcolors>MAXPALETTESIZE)
    G_THROW( ERR_MSG("DjVuPalette.many_colors") );
  
  // Paul Heckbert: "Color Image Quantization for Frame Buffer Display", 
  // SIGGRAPH '82 Proceedings, page 297.  (also in ppmquant)
  
  // Collect histogram colors
  int sum = 0;
  int ncolors = 0;
  GTArray<PData> pdata;
  for (GPosition p = *hist; p; ++p)
    {
      pdata.touch(ncolors);
      PData &data = pdata[ncolors++];
      int k = hist->key(p);
      data.p[0] = (k>>16) & 0xff;
      data.p[1] = (k>>8) & 0xff;
      data.p[2] = (k) & 0xff;
      data.w = (*hist)[p];
      sum += data.w;
    }
  // Create first box
  GList<PBox> boxes;
  PBox newbox;
  newbox.data = pdata;
  newbox.colors = ncolors;
  newbox.boxsize = 256;
  newbox.sum = sum;
  boxes.append(newbox);
  // Repeat spliting boxes
  while (boxes.size() < maxcolors)
    {
      // Find suitable box
      GPosition p;
      for (p=boxes; p; ++p)
        if (boxes[p].colors>=2 && boxes[p].boxsize>minboxsize) 
          break;
      if (! p)
        break;
      // Find box boundaries
      PBox &splitbox = boxes[p];
      unsigned char pmax[3];
      unsigned char pmin[3];
      pmax[0] = pmin[0] = splitbox.data->p[0];
      pmax[1] = pmin[1] = splitbox.data->p[1];
      pmax[2] = pmin[2] = splitbox.data->p[2];
      for (int j=1; j<splitbox.colors; j++)
        {
          pmax[0] = umax(pmax[0], splitbox.data[j].p[0]);
          pmax[1] = umax(pmax[1], splitbox.data[j].p[1]);
          pmax[2] = umax(pmax[2], splitbox.data[j].p[2]);
          pmin[0] = umin(pmin[0], splitbox.data[j].p[0]);
          pmin[1] = umin(pmin[1], splitbox.data[j].p[1]);
          pmin[2] = umin(pmin[2], splitbox.data[j].p[2]);
        }
      // Determine split direction and sort
      int bl = pmax[0]-pmin[0]; 
      int gl = pmax[1]-pmin[1];
      int rl = pmax[2]-pmin[2];
      splitbox.boxsize = (bl>gl ? (rl>bl ? rl : bl) : (rl>gl ? rl : gl));
      if (splitbox.boxsize <= minboxsize)
        continue;
      if (gl == splitbox.boxsize)
        qsort(splitbox.data, splitbox.colors, sizeof(PData), gcomp);
      else if (rl == splitbox.boxsize)
        qsort(splitbox.data, splitbox.colors, sizeof(PData), rcomp);
      else
        qsort(splitbox.data, splitbox.colors, sizeof(PData), bcomp);
      // Find median
      int lowercolors = 0;
      int lowersum = 0;
      while (lowercolors<splitbox.colors-1 && lowersum+lowersum<splitbox.sum)
        lowersum += splitbox.data[lowercolors++].w;
      // Compute new boxes
      newbox.data = splitbox.data + lowercolors;
      newbox.colors = splitbox.colors - lowercolors;
      newbox.sum = splitbox.sum - lowersum;
      splitbox.colors = lowercolors;
      splitbox.sum = lowersum;
      // Insert boxes at proper location
      GPosition q;
      for (q=p; q; ++q)
        if (boxes[q].sum < newbox.sum)
          break;
      boxes.insert_before(q, newbox);
      for (q=p; q; ++q)
        if (boxes[q].sum < splitbox.sum)
          break;
      boxes.insert_before(q, boxes, p);
    }
  // Fill palette array
  ncolors = 0;
  palette.empty();
  palette.resize(0,boxes.size()-1);
  for (GPosition p=boxes; p; ++p)
    {
      PBox &box = boxes[p];
      // Compute box representative color
      float bsum = 0;
      float gsum = 0;
      float rsum = 0;
      for (int j=0; j<box.colors; j++)
        {
          float w = (float)box.data[j].w;
          bsum += box.data[j].p[0] * w;
          gsum += box.data[j].p[1] * w;
          rsum += box.data[j].p[2] * w;
        }
      PColor &color = palette[ncolors++];
      color.p[0] = (unsigned char) fmin(255, bsum/box.sum);
      color.p[1] = (unsigned char) fmin(255, gsum/box.sum);
      color.p[2] = (unsigned char) fmin(255, rsum/box.sum);
      color.p[3] = ( color.p[0]*BMUL + color.p[1]*GMUL + color.p[2]*RMUL) / SMUL;
    }
  // Save dominant color
  PColor dcolor = palette[0];
  // Sort palette colors in luminance order
  qsort((PColor*)palette, ncolors, sizeof(PColor), lcomp);
  // Clear invalid data
  colordata.empty();
  delete pmap;
  pmap = 0;
  // Return dominant color
  return color_to_index_slow(dcolor.p);
}



int 
DjVuPalette::compute_pixmap_palette(const GPixmap &pm, int ncolors, int minboxsize)
{
  // Prepare histogram
  histogram_clear();
  for (int j=0; j<(int)pm.rows(); j++)
    {
      const GPixel *p = pm[j];
      for (int i=0; i<(int)pm.columns(); i++)
        histogram_add(p[i], 1);
    }
  // Compute palette
  return compute_palette(ncolors, minboxsize);
}


#endif




// -------- QUANTIZATION


void
DjVuPalette::allocate_pmap()
{
  if (! pmap)
    pmap = new GMap<int,int>;
}

int 
DjVuPalette::color_to_index_slow(const unsigned char *bgr)
{
  PColor *pal = palette;
  const int ncolors = palette.size();
  if (! ncolors)
    G_THROW( ERR_MSG("DjVuPalette.not_init") );
  // Should be able to do better
  int found = 0;
  int founddist = 3*256*256;
  for (int i=0; i<ncolors; i++)
    {
      int bd = bgr[0] - pal[i].p[0];
      int gd = bgr[1] - pal[i].p[1];
      int rd = bgr[2] - pal[i].p[2];
      int dist = (bd*bd)+(gd*gd)+(rd*rd);
      if (dist < founddist)
        {
          found = i;
          founddist = dist;
        }
    }
  // Store in pmap
  if (pmap && pmap->size()<0x8000)
    {
      int key = (bgr[0]<<16)|(bgr[1]<<8)|(bgr[2]);
      (*pmap)[key] = found;
    }
  // Return
  return found;
}


#ifndef NEED_DECODER_ONLY

void 
DjVuPalette::quantize(GPixmap &pm)
{
  for (int j=0; j<(int)pm.rows(); j++)
    {
      GPixel *p = pm[j];
      for (int i=0; i<(int)pm.columns(); i++)
        index_to_color(color_to_index(p[i]), p[i]);
    }
}

int 
DjVuPalette::compute_palette_and_quantize(GPixmap &pm, int maxcolors, int minboxsize)
{
  int result = compute_pixmap_palette(pm, maxcolors, minboxsize);
  quantize(pm);
  return result;
}

void 
DjVuPalette::color_correct(double corr)
{
  const int palettesize = palette.size();
  if (palettesize > 0)
    {
      // Copy colors
      int i;
      GTArray<GPixel> pix(0,palettesize-1);
      GPixel *r = pix;
      PColor *q = palette;
      for (i=0; i<palettesize; i++) 
        {
          r[i].b = q[i].p[0];
          r[i].g = q[i].p[1];
          r[i].r = q[i].p[2];
        }
      // Apply color correction
      GPixmap::color_correct(corr, r, palettesize);
      // Restore colors
      for (i=0; i<palettesize; i++) 
        {
          q[i].p[0] = r[i].b;
          q[i].p[1] = r[i].g;
          q[i].p[2] = r[i].r;
        }
    }
}

#endif


// -------- ENCODE AND DECODE

#define DJVUPALETTEVERSION 0

void
DjVuPalette::encode_rgb_entries(ByteStream &bs) const
{
  const int palettesize = palette.size();
  for (int c=0; c<palettesize; c++)
    {
      unsigned char p[3];
      p[2] = palette[c].p[0];
      p[1] = palette[c].p[1];
      p[0] = palette[c].p[2];
      bs.writall((const void*)p, 3);
    }
}

void 
DjVuPalette::encode(GP<ByteStream> gbs) const
{
  ByteStream &bs=*gbs;
  const int palettesize = palette.size();
  const int datasize = colordata.size();
  // Code version number
  int version = DJVUPALETTEVERSION;
  if (datasize>0) version |= 0x80;
  bs.write8(version);
  // Code palette
  bs.write16(palettesize);
  for (int c=0; c<palettesize; c++)
    {
      unsigned char p[3];
      p[0] = palette[c].p[0];
      p[1] = palette[c].p[1];
      p[2] = palette[c].p[2];
      bs.writall((const void*)p, 3);
    }
  // Code colordata
  if (datasize > 0)
    {
      bs.write24(datasize);
      GP<ByteStream> gbsb=BSByteStream::create(gbs, 50);
      ByteStream &bsb=*gbsb;
      for (int d=0; d<datasize; d++)
        bsb.write16(colordata[d]);
    }
}

void 
DjVuPalette::decode_rgb_entries(ByteStream &bs, const int palettesize)
{
  palette.resize(0,palettesize-1);
  for (int c=0; c<palettesize; c++)
    {
      unsigned char p[3];
      bs.readall((void*)p, 3);
      palette[c].p[0] = p[2];
      palette[c].p[1] = p[1];
      palette[c].p[2] = p[0];
      palette[c].p[3] = (p[0]*BMUL+p[1]*GMUL+p[2]*RMUL)/SMUL;
    }
}

void 
DjVuPalette::decode(GP<ByteStream> gbs)
{
  ByteStream &bs=*gbs;
  // Make sure that everything is clear
  delete hist;
  delete pmap;
  hist = 0;
  pmap = 0;
  mask = 0;
  // Code version
  int version = bs.read8();
  if ( (version & 0x7f) != DJVUPALETTEVERSION)
    G_THROW( ERR_MSG("DjVuPalette.bad_version") );
  // Code palette
  const int palettesize = bs.read16();
  if (palettesize<0 || palettesize>MAXPALETTESIZE)
    G_THROW( ERR_MSG("DjVuPalette.bad_palette") );
  palette.resize(0,palettesize-1);
  for (int c=0; c<palettesize; c++)
    {
      unsigned char p[3];
      bs.readall((void*)p, 3);
      palette[c].p[0] = p[0];
      palette[c].p[1] = p[1];
      palette[c].p[2] = p[2];
      palette[c].p[3] = (p[0]*BMUL+p[1]*GMUL+p[2]*RMUL)/SMUL;
    }
  // Code data
  if (version & 0x80)
    {
      int datasize = bs.read24();
      if (datasize<0)
        G_THROW( ERR_MSG("DjVuPalette.bad_palette") );
      colordata.resize(0,datasize-1);
      GP<ByteStream> gbsb=BSByteStream::create(gbs);
      ByteStream &bsb=*gbsb;
      for (int d=0; d<datasize; d++)
        {
          short s = bsb.read16();
          if (s<0 || s>=palettesize)
            G_THROW( ERR_MSG("DjVuPalette.bad_palette") );        
          colordata[d] = s;
        }
    }
}




#ifdef HAVE_NAMESPACES
}
# ifndef NOT_USING_DJVU_NAMESPACE
using namespace DJVU;
# endif
#endif