Coverage Report

Created: 2026-08-14 06:29

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/giflib-code/quantize.c
Line
Count
Source
1
/*****************************************************************************
2
3
 quantize.c - quantize a high resolution image into lower one
4
5
 Based on: "Color Image Quantization for frame buffer Display", by
6
 Paul Heckbert SIGGRAPH 1982 page 297-307.
7
8
 This doesn't really belong in the core library, was undocumented,
9
 and was removed in 4.2.  Then it turned out some client apps were
10
 actually using it, so it was restored in 5.0.
11
12
******************************************************************************/
13
// SPDX-License-Identifier: MIT
14
// SPDX-FileCopyrightText: Copyright (C) Eric S. Raymond <esr@thyrsus.com>
15
16
#include <stdio.h>
17
#include <stdlib.h>
18
19
#include "gif_lib.h"
20
#include "gif_lib_private.h"
21
22
22.9M
#define ABS(x) ((x) > 0 ? (x) : (-(x)))
23
24
24.8M
#define COLOR_ARRAY_SIZE 32768
25
101M
#define BITS_PER_PRIM_COLOR 5
26
24.8M
#define MAX_PRIM_COLOR 0x1f
27
28
static int SortRGBAxis;
29
30
typedef struct QuantizedColorType {
31
  GifByteType RGB[3];
32
  GifByteType NewColorIndex;
33
  long Count;
34
  struct QuantizedColorType *Pnext;
35
} QuantizedColorType;
36
37
typedef struct NewColorMapType {
38
  GifByteType RGBMin[3], RGBWidth[3];
39
  unsigned int
40
      NumEntries;      /* # of QuantizedColorType in linked list below */
41
  unsigned long Count; /* Total number of pixels in all the entries */
42
  QuantizedColorType *QuantizedColors;
43
} NewColorMapType;
44
45
static int SubdivColorMap(NewColorMapType *NewColorSubdiv,
46
                          unsigned int ColorMapSize,
47
                          unsigned int *NewColorMapSize);
48
static int SortCmpRtn(const void *Entry1, const void *Entry2);
49
50
/******************************************************************************
51
 Quantize high resolution image into lower one. Input image consists of a
52
 2D array for each of the RGB colors with size Width by Height. There is no
53
 Color map for the input. Output is a quantized image with 2D array of
54
 indexes into the output color map.
55
   Note input image can be 24 bits at the most (8 for red/green/blue) and
56
 the output has 256 colors at the most (256 entries in the color map.).
57
 ColorMapSize specifies size of color map up to 256 and will be updated to
58
 real size before returning.
59
   Also non of the parameter are allocated by this routine.
60
   This function returns GIF_OK if successful, GIF_ERROR otherwise.
61
******************************************************************************/
62
int GifQuantizeBuffer(unsigned int Width, unsigned int Height,
63
                      int *ColorMapSize, const GifByteType *RedInput,
64
                      const GifByteType *GreenInput,
65
                      const GifByteType *BlueInput, GifByteType *OutputBuffer,
66
379
                      GifColorType *OutputColorMap) {
67
68
379
  unsigned int Index, NumOfEntries;
69
379
  int i, j, MaxRGBError[3];
70
379
  unsigned int NewColorMapSize;
71
379
  long Red, Green, Blue;
72
379
  NewColorMapType NewColorSubdiv[256];
73
379
  QuantizedColorType *ColorArrayEntries, *QuantizedColor;
74
379
  size_t k, PixelCount;
75
76
379
  ColorArrayEntries = (QuantizedColorType *)malloc(
77
379
      sizeof(QuantizedColorType) * COLOR_ARRAY_SIZE);
78
379
  if (ColorArrayEntries == NULL) {
79
0
    return GIF_ERROR;
80
0
  }
81
82
379
  PixelCount = (size_t)Width * Height;
83
379
  if (Width != 0 && PixelCount / Width != Height) {
84
0
    free((char *)ColorArrayEntries);
85
0
    return GIF_ERROR;
86
0
  }
87
88
12.4M
  for (i = 0; i < COLOR_ARRAY_SIZE; i++) {
89
12.4M
    ColorArrayEntries[i].RGB[0] = i >> (2 * BITS_PER_PRIM_COLOR);
90
12.4M
    ColorArrayEntries[i].RGB[1] =
91
12.4M
        (i >> BITS_PER_PRIM_COLOR) & MAX_PRIM_COLOR;
92
12.4M
    ColorArrayEntries[i].RGB[2] = i & MAX_PRIM_COLOR;
93
12.4M
    ColorArrayEntries[i].Count = 0;
94
12.4M
  }
95
96
  /* Sample the colors and their distribution: */
97
7.64M
  for (k = 0; k < PixelCount; k++) {
98
7.64M
    Index = ((RedInput[k] >> (8 - BITS_PER_PRIM_COLOR))
99
7.64M
             << (2 * BITS_PER_PRIM_COLOR)) +
100
7.64M
            ((GreenInput[k] >> (8 - BITS_PER_PRIM_COLOR))
101
7.64M
             << BITS_PER_PRIM_COLOR) +
102
7.64M
            (BlueInput[k] >> (8 - BITS_PER_PRIM_COLOR));
103
7.64M
    ColorArrayEntries[Index].Count++;
104
7.64M
  }
105
106
  /* Put all the colors in the first entry of the color map, and call the
107
   * recursive subdivision process.  */
108
97.4k
  for (i = 0; i < 256; i++) {
109
97.0k
    NewColorSubdiv[i].QuantizedColors = NULL;
110
97.0k
    NewColorSubdiv[i].Count = NewColorSubdiv[i].NumEntries = 0;
111
388k
    for (j = 0; j < 3; j++) {
112
291k
      NewColorSubdiv[i].RGBMin[j] = 0;
113
291k
      NewColorSubdiv[i].RGBWidth[j] = 255;
114
291k
    }
115
97.0k
  }
116
117
  /* Find the non empty entries in the color table and chain them: */
118
950k
  for (i = 0; i < COLOR_ARRAY_SIZE; i++) {
119
950k
    if (ColorArrayEntries[i].Count > 0) {
120
379
      break;
121
379
    }
122
950k
  }
123
379
  QuantizedColor = NewColorSubdiv[0].QuantizedColors =
124
379
      &ColorArrayEntries[i];
125
379
  NumOfEntries = 1;
126
11.4M
  while (++i < COLOR_ARRAY_SIZE) {
127
11.4M
    if (ColorArrayEntries[i].Count > 0) {
128
1.60M
      QuantizedColor->Pnext = &ColorArrayEntries[i];
129
1.60M
      QuantizedColor = &ColorArrayEntries[i];
130
1.60M
      NumOfEntries++;
131
1.60M
    }
132
11.4M
  }
133
379
  QuantizedColor->Pnext = NULL;
134
135
379
  NewColorSubdiv[0].NumEntries =
136
379
      NumOfEntries; /* Different sampled colors */
137
379
  NewColorSubdiv[0].Count = (unsigned long)PixelCount; /* Pixels */
138
379
  NewColorMapSize = 1;
139
379
  if (SubdivColorMap(NewColorSubdiv, *ColorMapSize, &NewColorMapSize) !=
140
379
      GIF_OK) {
141
0
    free((char *)ColorArrayEntries);
142
0
    return GIF_ERROR;
143
0
  }
144
379
  if (NewColorMapSize < *ColorMapSize) {
145
    /* And clear rest of color map: */
146
35.4k
    for (i = NewColorMapSize; i < *ColorMapSize; i++) {
147
35.2k
      OutputColorMap[i].Red = OutputColorMap[i].Green =
148
35.2k
          OutputColorMap[i].Blue = 0;
149
35.2k
    }
150
188
  }
151
152
  /* Average the colors in each entry to be the color to be used in the
153
   * output color map, and plug it into the output color map itself. */
154
62.1k
  for (i = 0; i < NewColorMapSize; i++) {
155
61.8k
    if ((j = NewColorSubdiv[i].NumEntries) > 0) {
156
61.8k
      QuantizedColor = NewColorSubdiv[i].QuantizedColors;
157
61.8k
      Red = Green = Blue = 0;
158
1.66M
      while (QuantizedColor) {
159
1.60M
        QuantizedColor->NewColorIndex = i;
160
1.60M
        Red += QuantizedColor->RGB[0];
161
1.60M
        Green += QuantizedColor->RGB[1];
162
1.60M
        Blue += QuantizedColor->RGB[2];
163
1.60M
        QuantizedColor = QuantizedColor->Pnext;
164
1.60M
      }
165
61.8k
      OutputColorMap[i].Red =
166
61.8k
          (Red << (8 - BITS_PER_PRIM_COLOR)) / j;
167
61.8k
      OutputColorMap[i].Green =
168
61.8k
          (Green << (8 - BITS_PER_PRIM_COLOR)) / j;
169
61.8k
      OutputColorMap[i].Blue =
170
61.8k
          (Blue << (8 - BITS_PER_PRIM_COLOR)) / j;
171
61.8k
    }
172
61.8k
  }
173
174
  /* Finally scan the input buffer again and put the mapped index in the
175
   * output buffer.  */
176
379
  MaxRGBError[0] = MaxRGBError[1] = MaxRGBError[2] = 0;
177
7.64M
  for (k = 0; k < PixelCount; k++) {
178
7.64M
    Index = ((RedInput[k] >> (8 - BITS_PER_PRIM_COLOR))
179
7.64M
             << (2 * BITS_PER_PRIM_COLOR)) +
180
7.64M
            ((GreenInput[k] >> (8 - BITS_PER_PRIM_COLOR))
181
7.64M
             << BITS_PER_PRIM_COLOR) +
182
7.64M
            (BlueInput[k] >> (8 - BITS_PER_PRIM_COLOR));
183
7.64M
    Index = ColorArrayEntries[Index].NewColorIndex;
184
7.64M
    OutputBuffer[k] = Index;
185
7.64M
    if (MaxRGBError[0] <
186
7.64M
        ABS(OutputColorMap[Index].Red - RedInput[k])) {
187
1.67k
      MaxRGBError[0] =
188
1.67k
          ABS(OutputColorMap[Index].Red - RedInput[k]);
189
1.67k
    }
190
7.64M
    if (MaxRGBError[1] <
191
7.64M
        ABS(OutputColorMap[Index].Green - GreenInput[k])) {
192
1.79k
      MaxRGBError[1] =
193
1.79k
          ABS(OutputColorMap[Index].Green - GreenInput[k]);
194
1.79k
    }
195
7.64M
    if (MaxRGBError[2] <
196
7.64M
        ABS(OutputColorMap[Index].Blue - BlueInput[k])) {
197
1.76k
      MaxRGBError[2] =
198
1.76k
          ABS(OutputColorMap[Index].Blue - BlueInput[k]);
199
1.76k
    }
200
7.64M
  }
201
202
#ifdef DEBUG
203
  fprintf(stderr,
204
          "Quantization L(0) errors: Red = %d, Green = %d, Blue = %d.\n",
205
          MaxRGBError[0], MaxRGBError[1], MaxRGBError[2]);
206
#endif /* DEBUG */
207
208
379
  free((char *)ColorArrayEntries);
209
210
379
  *ColorMapSize = NewColorMapSize;
211
212
379
  return GIF_OK;
213
379
}
214
215
/******************************************************************************
216
 Routine to subdivide the RGB space recursively using median cut in each
217
 axes alternatingly until ColorMapSize different cubes exists.
218
 The biggest cube in one dimension is subdivide unless it has only one entry.
219
 Returns GIF_ERROR if failed, otherwise GIF_OK.
220
*******************************************************************************/
221
static int SubdivColorMap(NewColorMapType *NewColorSubdiv,
222
                          unsigned int ColorMapSize,
223
379
                          unsigned int *NewColorMapSize) {
224
225
379
  unsigned int i, j, Index = 0;
226
379
  QuantizedColorType *QuantizedColor, **SortArray;
227
228
61.8k
  while (ColorMapSize > *NewColorMapSize) {
229
    /* Find candidate for subdivision: */
230
61.6k
    long Sum, Count;
231
61.6k
    int MaxSize = -1;
232
61.6k
    unsigned int NumEntries, MinColor, MaxColor;
233
7.11M
    for (i = 0; i < *NewColorMapSize; i++) {
234
28.2M
      for (j = 0; j < 3; j++) {
235
21.1M
        if ((((int)NewColorSubdiv[i].RGBWidth[j]) >
236
21.1M
             MaxSize) &&
237
1.78M
            (NewColorSubdiv[i].NumEntries > 1)) {
238
224k
          MaxSize = NewColorSubdiv[i].RGBWidth[j];
239
224k
          Index = i;
240
224k
          SortRGBAxis = j;
241
224k
        }
242
21.1M
      }
243
7.05M
    }
244
245
61.6k
    if (MaxSize == -1) {
246
188
      return GIF_OK;
247
188
    }
248
249
    /* Split the entry Index into two along the axis SortRGBAxis: */
250
251
    /* Sort all elements in that entry along the given axis and
252
     * split at the median.  */
253
61.4k
    SortArray = (QuantizedColorType **)malloc(
254
61.4k
        sizeof(QuantizedColorType *) *
255
61.4k
        NewColorSubdiv[Index].NumEntries);
256
61.4k
    if (SortArray == NULL) {
257
0
      return GIF_ERROR;
258
0
    }
259
61.4k
    for (j = 0,
260
61.4k
        QuantizedColor = NewColorSubdiv[Index].QuantizedColors;
261
34.4M
         j < NewColorSubdiv[Index].NumEntries &&
262
34.3M
         QuantizedColor != NULL;
263
34.3M
         j++, QuantizedColor = QuantizedColor->Pnext) {
264
34.3M
      SortArray[j] = QuantizedColor;
265
34.3M
    }
266
267
    /*
268
     * Because qsort isn't stable, this can produce differing
269
     * results for the order of tuples depending on platform
270
     * details of how qsort() is implemented.
271
     *
272
     * We mitigate this problem by sorting on all three axes rather
273
     * than only the one specied by SortRGBAxis; that way the
274
     * instability can only become an issue if there are multiple
275
     * color indices referring to identical RGB tuples.  Older
276
     * versions of this sorted on only the one axis.
277
     */
278
61.4k
    qsort(SortArray, NewColorSubdiv[Index].NumEntries,
279
61.4k
          sizeof(QuantizedColorType *), SortCmpRtn);
280
281
    /* Relink the sorted list into one: */
282
34.3M
    for (j = 0; j < NewColorSubdiv[Index].NumEntries - 1; j++) {
283
34.3M
      SortArray[j]->Pnext = SortArray[j + 1];
284
34.3M
    }
285
61.4k
    SortArray[NewColorSubdiv[Index].NumEntries - 1]->Pnext = NULL;
286
61.4k
    NewColorSubdiv[Index].QuantizedColors = QuantizedColor =
287
61.4k
        SortArray[0];
288
61.4k
    free((char *)SortArray);
289
290
    /* Now simply add the Counts until we have half of the Count: */
291
61.4k
    Sum = NewColorSubdiv[Index].Count / 2 - QuantizedColor->Count;
292
61.4k
    NumEntries = 1;
293
61.4k
    Count = QuantizedColor->Count;
294
5.73M
    while (QuantizedColor->Pnext != NULL &&
295
5.73M
           (Sum -= QuantizedColor->Pnext->Count) >= 0 &&
296
5.67M
           QuantizedColor->Pnext->Pnext != NULL) {
297
5.67M
      QuantizedColor = QuantizedColor->Pnext;
298
5.67M
      NumEntries++;
299
5.67M
      Count += QuantizedColor->Count;
300
5.67M
    }
301
    /* Save the values of the last color of the first half, and
302
     * first of the second half so we can update the Bounding Boxes
303
     * later. Also as the colors are quantized and the BBoxes are
304
     * full 0..255, they need to be rescaled.
305
     */
306
61.4k
    MaxColor =
307
61.4k
        QuantizedColor->RGB[SortRGBAxis]; /* Max. of first half */
308
    /* coverity[var_deref_op] */
309
61.4k
    MinColor =
310
        // cppcheck-suppress nullPointerRedundantCheck
311
61.4k
        QuantizedColor->Pnext->RGB[SortRGBAxis]; /* of second */
312
61.4k
    MaxColor <<= (8 - BITS_PER_PRIM_COLOR);
313
61.4k
    MinColor <<= (8 - BITS_PER_PRIM_COLOR);
314
315
    /* Partition right here: */
316
61.4k
    NewColorSubdiv[*NewColorMapSize].QuantizedColors =
317
61.4k
        QuantizedColor->Pnext;
318
61.4k
    QuantizedColor->Pnext = NULL;
319
61.4k
    NewColorSubdiv[*NewColorMapSize].Count = Count;
320
61.4k
    NewColorSubdiv[Index].Count -= Count;
321
61.4k
    NewColorSubdiv[*NewColorMapSize].NumEntries =
322
61.4k
        NewColorSubdiv[Index].NumEntries - NumEntries;
323
61.4k
    NewColorSubdiv[Index].NumEntries = NumEntries;
324
245k
    for (j = 0; j < 3; j++) {
325
184k
      NewColorSubdiv[*NewColorMapSize].RGBMin[j] =
326
184k
          NewColorSubdiv[Index].RGBMin[j];
327
184k
      NewColorSubdiv[*NewColorMapSize].RGBWidth[j] =
328
184k
          NewColorSubdiv[Index].RGBWidth[j];
329
184k
    }
330
61.4k
    NewColorSubdiv[*NewColorMapSize].RGBWidth[SortRGBAxis] =
331
61.4k
        NewColorSubdiv[*NewColorMapSize].RGBMin[SortRGBAxis] +
332
61.4k
        NewColorSubdiv[*NewColorMapSize].RGBWidth[SortRGBAxis] -
333
61.4k
        MinColor;
334
61.4k
    NewColorSubdiv[*NewColorMapSize].RGBMin[SortRGBAxis] = MinColor;
335
336
61.4k
    NewColorSubdiv[Index].RGBWidth[SortRGBAxis] =
337
61.4k
        MaxColor - NewColorSubdiv[Index].RGBMin[SortRGBAxis];
338
339
61.4k
    (*NewColorMapSize)++;
340
61.4k
  }
341
342
191
  return GIF_OK;
343
379
}
344
345
/****************************************************************************
346
 Routine called by qsort to compare two entries.
347
 *****************************************************************************/
348
349
233M
static int SortCmpRtn(const void *Entry1, const void *Entry2) {
350
233M
  QuantizedColorType *entry1 = (*((QuantizedColorType **)Entry1));
351
233M
  QuantizedColorType *entry2 = (*((QuantizedColorType **)Entry2));
352
353
  /* sort on all axes of the color space! */
354
233M
  int hash1 = entry1->RGB[SortRGBAxis] * 256 * 256 +
355
233M
              entry1->RGB[(SortRGBAxis + 1) % 3] * 256 +
356
233M
              entry1->RGB[(SortRGBAxis + 2) % 3];
357
233M
  int hash2 = entry2->RGB[SortRGBAxis] * 256 * 256 +
358
233M
              entry2->RGB[(SortRGBAxis + 1) % 3] * 256 +
359
233M
              entry2->RGB[(SortRGBAxis + 2) % 3];
360
361
233M
  return hash1 - hash2;
362
233M
}
363
364
/* end */