1
0

quantize.c 13 KB

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