Elaztek Developer Hub
Blamite Game Engine - blam!  00423.10.27.24.0533.blamite
The core library for the Blamite Game Engine.
gif.h
Go to the documentation of this file.
1 //
2 // gif.h
3 // by Charlie Tangora
4 // Public domain.
5 // Email me : ctangora -at- gmail -dot- com
6 //
7 // This file offers a simple, very limited way to create animated GIFs directly in code.
8 //
9 // Those looking for particular cleverness are likely to be disappointed; it's pretty
10 // much a straight-ahead implementation of the GIF format with optional Floyd-Steinberg
11 // dithering. (It does at least use delta encoding - only the changed portions of each
12 // frame are saved.)
13 //
14 // So resulting files are often quite large. The hope is that it will be handy nonetheless
15 // as a quick and easily-integrated way for programs to spit out animations.
16 //
17 // Only RGBA8 is currently supported as an input format. (The alpha is ignored.)
18 //
19 // If capturing a buffer with a bottom-left origin (such as OpenGL), define GIF_FLIP_VERT
20 // to automatically flip the buffer data when writing the image (the buffer itself is
21 // unchanged.
22 //
23 // USAGE:
24 // Create a GifWriter struct. Pass it to GifBegin() to initialize and write the header.
25 // Pass subsequent frames to GifWriteFrame().
26 // Finally, call GifEnd() to close the file handle and free memory.
27 //
28 
29 #ifndef gif_h
30 #define gif_h
31 
32 #include <stdio.h> // for FILE*
33 #include <string.h> // for memcpy and bzero
34 #include <stdint.h> // for integer typedefs
35 #include <stdbool.h> // for bool macros
36 
37 // Define these macros to hook into a custom memory allocator.
38 // TEMP_MALLOC and TEMP_FREE will only be called in stack fashion - frees in the reverse order of mallocs
39 // and any temp memory allocated by a function will be freed before it exits.
40 // MALLOC and FREE are used only by GifBegin and GifEnd respectively (to allocate a buffer the size of the image, which
41 // is used to find changed pixels for delta-encoding.)
42 
43 #ifndef GIF_TEMP_MALLOC
44 #include <stdlib.h>
45 #define GIF_TEMP_MALLOC malloc
46 #endif
47 
48 #ifndef GIF_TEMP_FREE
49 #include <stdlib.h>
50 #define GIF_TEMP_FREE free
51 #endif
52 
53 #ifndef GIF_MALLOC
54 #include <stdlib.h>
55 #define GIF_MALLOC malloc
56 #endif
57 
58 #ifndef GIF_FREE
59 #include <stdlib.h>
60 #define GIF_FREE free
61 #endif
62 
63 const int kGifTransIndex = 0;
64 
65 typedef struct
66 {
67  int bitDepth;
68 
69  uint8_t r[256];
70  uint8_t g[256];
71  uint8_t b[256];
72 
73  // k-d tree over RGB space, organized in heap fashion
74  // i.e. left child of node i is node i*2, right child is node i*2+1
75  // nodes 256-511 are implicitly the leaves, containing a color
76  uint8_t treeSplitElt[256];
77  uint8_t treeSplit[256];
78 } GifPalette;
79 
80 // max, min, and abs functions
81 int GifIMax(int l, int r) { return l > r ? l : r; }
82 int GifIMin(int l, int r) { return l < r ? l : r; }
83 int GifIAbs(int i) { return i < 0 ? -i : i; }
84 
85 // walks the k-d tree to pick the palette entry for a desired color.
86 // Takes as in/out parameters the current best color and its error -
87 // only changes them if it finds a better color in its subtree.
88 // this is the major hotspot in the code at the moment.
89 void GifGetClosestPaletteColor(GifPalette* pPal, int r, int g, int b, int* bestInd, int* bestDiff, int treeRoot)
90 {
91  // base case, reached the bottom of the tree
92  if (treeRoot > (1 << pPal->bitDepth) - 1)
93  {
94  int ind = treeRoot - (1 << pPal->bitDepth);
95  if (ind == kGifTransIndex) return;
96 
97  // check whether this color is better than the current winner
98  int r_err = r - ((int32_t)pPal->r[ind]);
99  int g_err = g - ((int32_t)pPal->g[ind]);
100  int b_err = b - ((int32_t)pPal->b[ind]);
101  int diff = GifIAbs(r_err) + GifIAbs(g_err) + GifIAbs(b_err);
102 
103  if (diff < *bestDiff)
104  {
105  *bestInd = ind;
106  *bestDiff = diff;
107  }
108 
109  return;
110  }
111 
112  // take the appropriate color (r, g, or b) for this node of the k-d tree
113  int comps[3]; comps[0] = r; comps[1] = g; comps[2] = b;
114  int splitComp = comps[pPal->treeSplitElt[treeRoot]];
115 
116  int splitPos = pPal->treeSplit[treeRoot];
117  if (splitPos > splitComp)
118  {
119  // check the left subtree
120  GifGetClosestPaletteColor(pPal, r, g, b, bestInd, bestDiff, treeRoot * 2);
121  if (*bestDiff > splitPos - splitComp)
122  {
123  // cannot prove there's not a better value in the right subtree, check that too
124  GifGetClosestPaletteColor(pPal, r, g, b, bestInd, bestDiff, treeRoot * 2 + 1);
125  }
126  }
127  else
128  {
129  GifGetClosestPaletteColor(pPal, r, g, b, bestInd, bestDiff, treeRoot * 2 + 1);
130  if (*bestDiff > splitComp - splitPos)
131  {
132  GifGetClosestPaletteColor(pPal, r, g, b, bestInd, bestDiff, treeRoot * 2);
133  }
134  }
135 }
136 
137 void GifSwapPixels(uint8_t* image, int pixA, int pixB)
138 {
139  uint8_t rA = image[pixA * 4];
140  uint8_t gA = image[pixA * 4 + 1];
141  uint8_t bA = image[pixA * 4 + 2];
142  uint8_t aA = image[pixA * 4 + 3];
143 
144  uint8_t rB = image[pixB * 4];
145  uint8_t gB = image[pixB * 4 + 1];
146  uint8_t bB = image[pixB * 4 + 2];
147  uint8_t aB = image[pixA * 4 + 3];
148 
149  image[pixA * 4] = rB;
150  image[pixA * 4 + 1] = gB;
151  image[pixA * 4 + 2] = bB;
152  image[pixA * 4 + 3] = aB;
153 
154  image[pixB * 4] = rA;
155  image[pixB * 4 + 1] = gA;
156  image[pixB * 4 + 2] = bA;
157  image[pixB * 4 + 3] = aA;
158 }
159 
160 // just the partition operation from quicksort
161 int GifPartition(uint8_t* image, const int left, const int right, const int elt, int pivotValue)
162 {
163  int storeIndex = left;
164  bool split = 0;
165  for (int ii = left; ii < right; ++ii)
166  {
167  int arrayVal = image[ii * 4 + elt];
168  if (arrayVal < pivotValue)
169  {
170  GifSwapPixels(image, ii, storeIndex);
171  ++storeIndex;
172  }
173  else if (arrayVal == pivotValue)
174  {
175  if (split)
176  {
177  GifSwapPixels(image, ii, storeIndex);
178  ++storeIndex;
179  }
180  split = !split;
181  }
182  }
183  return storeIndex;
184 }
185 
186 // Perform an incomplete sort, finding all elements above and below the desired median
187 void GifPartitionByMedian(uint8_t* image, int left, int right, int com, int neededCenter)
188 {
189  if (left < right - 1)
190  {
191  int pivotValue = image[(neededCenter) * 4 + com];
192  GifSwapPixels(image, neededCenter, right - 1);
193  int pivotIndex = GifPartition(image, left, right - 1, com, pivotValue);
194  GifSwapPixels(image, pivotIndex, right - 1);
195 
196  // Only "sort" the section of the array that contains the median
197  if (pivotIndex > neededCenter)
198  GifPartitionByMedian(image, left, pivotIndex, com, neededCenter);
199 
200  if (pivotIndex < neededCenter)
201  GifPartitionByMedian(image, pivotIndex + 1, right, com, neededCenter);
202  }
203 }
204 
205 // Just partition around a given pivot, returning the split point
206 int GifPartitionByMean(uint8_t* image, int left, int right, int com, int neededMean)
207 {
208  if (left < right - 1)
209  {
210  return GifPartition(image, left, right - 1, com, neededMean);
211  }
212  return left;
213 }
214 
215 // Builds a palette by creating a balanced k-d tree of all pixels in the image
216 void GifSplitPalette(uint8_t* image, int numPixels, int treeNode, int treeLevel, bool buildForDither, GifPalette* pal)
217 {
218  if (numPixels == 0)
219  return;
220 
221  int numColors = (1 << pal->bitDepth);
222 
223  // base case, bottom of the tree
224  if (treeNode >= numColors)
225  {
226  int entry = treeNode - numColors;
227 
228  if (buildForDither)
229  {
230  // Dithering needs at least one color as dark as anything
231  // in the image and at least one brightest color -
232  // otherwise it builds up error and produces strange artifacts
233  if (entry == 1)
234  {
235  // special case: the darkest color in the image
236  uint32_t r = 255, g = 255, b = 255;
237  for (int ii = 0; ii < numPixels; ++ii)
238  {
239  r = (uint32_t)GifIMin((int32_t)r, image[ii * 4 + 0]);
240  g = (uint32_t)GifIMin((int32_t)g, image[ii * 4 + 1]);
241  b = (uint32_t)GifIMin((int32_t)b, image[ii * 4 + 2]);
242  }
243 
244  pal->r[entry] = (uint8_t)r;
245  pal->g[entry] = (uint8_t)g;
246  pal->b[entry] = (uint8_t)b;
247 
248  return;
249  }
250 
251  if (entry == numColors - 1)
252  {
253  // special case: the lightest color in the image
254  uint32_t r = 0, g = 0, b = 0;
255  for (int ii = 0; ii < numPixels; ++ii)
256  {
257  r = (uint32_t)GifIMax((int32_t)r, image[ii * 4 + 0]);
258  g = (uint32_t)GifIMax((int32_t)g, image[ii * 4 + 1]);
259  b = (uint32_t)GifIMax((int32_t)b, image[ii * 4 + 2]);
260  }
261 
262  pal->r[entry] = (uint8_t)r;
263  pal->g[entry] = (uint8_t)g;
264  pal->b[entry] = (uint8_t)b;
265 
266  return;
267  }
268  }
269 
270  // otherwise, take the average of all colors in this subcube
271  uint64_t r = 0, g = 0, b = 0;
272  for (int ii = 0; ii < numPixels; ++ii)
273  {
274  r += image[ii * 4 + 0];
275  g += image[ii * 4 + 1];
276  b += image[ii * 4 + 2];
277  }
278 
279  r += (uint64_t)numPixels / 2; // round to nearest
280  g += (uint64_t)numPixels / 2;
281  b += (uint64_t)numPixels / 2;
282 
283  r /= (uint64_t)numPixels;
284  g /= (uint64_t)numPixels;
285  b /= (uint64_t)numPixels;
286 
287  pal->r[entry] = (uint8_t)r;
288  pal->g[entry] = (uint8_t)g;
289  pal->b[entry] = (uint8_t)b;
290 
291  return;
292  }
293 
294  // Find the axis with the largest range
295  int minR = 255, maxR = 0;
296  int minG = 255, maxG = 0;
297  int minB = 255, maxB = 0;
298  for (int ii = 0; ii < numPixels; ++ii)
299  {
300  int r = image[ii * 4 + 0];
301  int g = image[ii * 4 + 1];
302  int b = image[ii * 4 + 2];
303 
304  if (r > maxR) maxR = r;
305  if (r < minR) minR = r;
306 
307  if (g > maxG) maxG = g;
308  if (g < minG) minG = g;
309 
310  if (b > maxB) maxB = b;
311  if (b < minB) minB = b;
312  }
313 
314  int rRange = maxR - minR;
315  int gRange = maxG - minG;
316  int bRange = maxB - minB;
317 
318  // and split along that axis. (incidentally, this means this isn't a "proper" k-d tree but I don't know what else to call it)
319  int splitCom = 1; int rangeMin = minG; int rangeMax = maxG;
320  if (bRange > gRange) { splitCom = 2; rangeMin = minB; rangeMax = maxB; }
321  if (rRange > bRange && rRange > gRange) { splitCom = 0; rangeMin = minR; rangeMax = maxR; }
322 
323  int subPixelsA = numPixels / 2;
324 
325  GifPartitionByMedian(image, 0, numPixels, splitCom, subPixelsA);
326  int splitValue = image[subPixelsA * 4 + splitCom];
327 
328  // if the split is very unbalanced, split at the mean instead of the median to preserve rare colors
329  int splitUnbalance = GifIAbs((splitValue - rangeMin) - (rangeMax - splitValue));
330  if (splitUnbalance > (1536 >> treeLevel))
331  {
332  splitValue = rangeMin + (rangeMax - rangeMin) / 2;
333  subPixelsA = GifPartitionByMean(image, 0, numPixels, splitCom, splitValue);
334  }
335 
336  // add the bottom node for the transparency index
337  if (treeNode == numColors / 2)
338  {
339  subPixelsA = 0;
340  splitValue = 0;
341  }
342 
343  int subPixelsB = numPixels - subPixelsA;
344  pal->treeSplitElt[treeNode] = (uint8_t)splitCom;
345  pal->treeSplit[treeNode] = (uint8_t)splitValue;
346 
347  GifSplitPalette(image, subPixelsA, treeNode * 2, treeLevel + 1, buildForDither, pal);
348  GifSplitPalette(image + subPixelsA * 4, subPixelsB, treeNode * 2 + 1, treeLevel + 1, buildForDither, pal);
349 }
350 
351 // Finds all pixels that have changed from the previous image and
352 // moves them to the fromt of th buffer.
353 // This allows us to build a palette optimized for the colors of the
354 // changed pixels only.
355 int GifPickChangedPixels(const uint8_t* lastFrame, uint8_t* frame, int numPixels)
356 {
357  int numChanged = 0;
358  uint8_t* writeIter = frame;
359 
360  for (int ii = 0; ii < numPixels; ++ii)
361  {
362  if (lastFrame[0] != frame[0] ||
363  lastFrame[1] != frame[1] ||
364  lastFrame[2] != frame[2])
365  {
366  writeIter[0] = frame[0];
367  writeIter[1] = frame[1];
368  writeIter[2] = frame[2];
369  ++numChanged;
370  writeIter += 4;
371  }
372  lastFrame += 4;
373  frame += 4;
374  }
375 
376  return numChanged;
377 }
378 
379 // Creates a palette by placing all the image pixels in a k-d tree and then averaging the blocks at the bottom.
380 // This is known as the "median split" technique
381 void GifMakePalette(const uint8_t* lastFrame, const uint8_t* nextFrame, uint32_t width, uint32_t height, int bitDepth, bool buildForDither, GifPalette* pPal)
382 {
383  pPal->bitDepth = bitDepth;
384 
385  // SplitPalette is destructive (it sorts the pixels by color) so
386  // we must create a copy of the image for it to destroy
387  size_t imageSize = (size_t)(width * height * 4 * sizeof(uint8_t));
388  uint8_t* destroyableImage = (uint8_t*)GIF_TEMP_MALLOC(imageSize);
389  memcpy(destroyableImage, nextFrame, imageSize);
390 
391  int numPixels = (int)(width * height);
392  if (lastFrame)
393  numPixels = GifPickChangedPixels(lastFrame, destroyableImage, numPixels);
394 
395  GifSplitPalette(destroyableImage, numPixels, 1, 0, buildForDither, pPal);
396 
397  GIF_TEMP_FREE(destroyableImage);
398 
399  // add the bottom node for the transparency index
400  pPal->treeSplit[1 << (bitDepth - 1)] = 0;
401  pPal->treeSplitElt[1 << (bitDepth - 1)] = 0;
402 
403  pPal->r[0] = pPal->g[0] = pPal->b[0] = 0;
404 }
405 
406 // Implements Floyd-Steinberg dithering, writes palette value to alpha
407 void GifDitherImage(const uint8_t* lastFrame, const uint8_t* nextFrame, uint8_t* outFrame, uint32_t width, uint32_t height, GifPalette* pPal)
408 {
409  int numPixels = (int)(width * height);
410 
411  // quantPixels initially holds color*256 for all pixels
412  // The extra 8 bits of precision allow for sub-single-color error values
413  // to be propagated
414  int32_t* quantPixels = (int32_t*)GIF_TEMP_MALLOC(sizeof(int32_t) * (size_t)numPixels * 4);
415 
416  for (int ii = 0; ii < numPixels * 4; ++ii)
417  {
418  uint8_t pix = nextFrame[ii];
419  int32_t pix16 = (int32_t)(pix) * 256;
420  quantPixels[ii] = pix16;
421  }
422 
423  for (uint32_t yy = 0; yy < height; ++yy)
424  {
425  for (uint32_t xx = 0; xx < width; ++xx)
426  {
427  int32_t* nextPix = quantPixels + 4 * (yy * width + xx);
428  const uint8_t* lastPix = lastFrame ? lastFrame + 4 * (yy * width + xx) : NULL;
429 
430  // Compute the colors we want (rounding to nearest)
431  int32_t rr = (nextPix[0] + 127) / 256;
432  int32_t gg = (nextPix[1] + 127) / 256;
433  int32_t bb = (nextPix[2] + 127) / 256;
434 
435  // if it happens that we want the color from last frame, then just write out
436  // a transparent pixel
437  if (lastFrame &&
438  lastPix[0] == rr &&
439  lastPix[1] == gg &&
440  lastPix[2] == bb)
441  {
442  nextPix[0] = rr;
443  nextPix[1] = gg;
444  nextPix[2] = bb;
445  nextPix[3] = kGifTransIndex;
446  continue;
447  }
448 
449  int32_t bestDiff = 1000000;
450  int32_t bestInd = kGifTransIndex;
451 
452  // Search the palete
453  GifGetClosestPaletteColor(pPal, rr, gg, bb, &bestInd, &bestDiff, 1);
454 
455  // Write the result to the temp buffer
456  int32_t r_err = nextPix[0] - (int32_t)(pPal->r[bestInd]) * 256;
457  int32_t g_err = nextPix[1] - (int32_t)(pPal->g[bestInd]) * 256;
458  int32_t b_err = nextPix[2] - (int32_t)(pPal->b[bestInd]) * 256;
459 
460  nextPix[0] = pPal->r[bestInd];
461  nextPix[1] = pPal->g[bestInd];
462  nextPix[2] = pPal->b[bestInd];
463  nextPix[3] = bestInd;
464 
465  // Propagate the error to the four adjacent locations
466  // that we haven't touched yet
467  int quantloc_7 = (int)(yy * width + xx + 1);
468  int quantloc_3 = (int)(yy * width + width + xx - 1);
469  int quantloc_5 = (int)(yy * width + width + xx);
470  int quantloc_1 = (int)(yy * width + width + xx + 1);
471 
472  if (quantloc_7 < numPixels)
473  {
474  int32_t* pix7 = quantPixels + 4 * quantloc_7;
475  pix7[0] += GifIMax(-pix7[0], r_err * 7 / 16);
476  pix7[1] += GifIMax(-pix7[1], g_err * 7 / 16);
477  pix7[2] += GifIMax(-pix7[2], b_err * 7 / 16);
478  }
479 
480  if (quantloc_3 < numPixels)
481  {
482  int32_t* pix3 = quantPixels + 4 * quantloc_3;
483  pix3[0] += GifIMax(-pix3[0], r_err * 3 / 16);
484  pix3[1] += GifIMax(-pix3[1], g_err * 3 / 16);
485  pix3[2] += GifIMax(-pix3[2], b_err * 3 / 16);
486  }
487 
488  if (quantloc_5 < numPixels)
489  {
490  int32_t* pix5 = quantPixels + 4 * quantloc_5;
491  pix5[0] += GifIMax(-pix5[0], r_err * 5 / 16);
492  pix5[1] += GifIMax(-pix5[1], g_err * 5 / 16);
493  pix5[2] += GifIMax(-pix5[2], b_err * 5 / 16);
494  }
495 
496  if (quantloc_1 < numPixels)
497  {
498  int32_t* pix1 = quantPixels + 4 * quantloc_1;
499  pix1[0] += GifIMax(-pix1[0], r_err / 16);
500  pix1[1] += GifIMax(-pix1[1], g_err / 16);
501  pix1[2] += GifIMax(-pix1[2], b_err / 16);
502  }
503  }
504  }
505 
506  // Copy the palettized result to the output buffer
507  for (int ii = 0; ii < numPixels * 4; ++ii)
508  {
509  outFrame[ii] = (uint8_t)quantPixels[ii];
510  }
511 
512  GIF_TEMP_FREE(quantPixels);
513 }
514 
515 // Picks palette colors for the image using simple thresholding, no dithering
516 void GifThresholdImage(const uint8_t* lastFrame, const uint8_t* nextFrame, uint8_t* outFrame, uint32_t width, uint32_t height, GifPalette* pPal)
517 {
518  uint32_t numPixels = width * height;
519  for (uint32_t ii = 0; ii < numPixels; ++ii)
520  {
521  // if a previous color is available, and it matches the current color,
522  // set the pixel to transparent
523  if (lastFrame &&
524  lastFrame[0] == nextFrame[0] &&
525  lastFrame[1] == nextFrame[1] &&
526  lastFrame[2] == nextFrame[2])
527  {
528  outFrame[0] = lastFrame[0];
529  outFrame[1] = lastFrame[1];
530  outFrame[2] = lastFrame[2];
531  outFrame[3] = kGifTransIndex;
532  }
533  else
534  {
535  // palettize the pixel
536  int32_t bestDiff = 1000000;
537  int32_t bestInd = 1;
538  GifGetClosestPaletteColor(pPal, nextFrame[0], nextFrame[1], nextFrame[2], &bestInd, &bestDiff, 1);
539 
540  // Write the resulting color to the output buffer
541  outFrame[0] = pPal->r[bestInd];
542  outFrame[1] = pPal->g[bestInd];
543  outFrame[2] = pPal->b[bestInd];
544  outFrame[3] = (uint8_t)bestInd;
545  }
546 
547  if (lastFrame) lastFrame += 4;
548  outFrame += 4;
549  nextFrame += 4;
550  }
551 }
552 
553 // Simple structure to write out the LZW-compressed portion of the image
554 // one bit at a time
555 typedef struct
556 {
558  uint8_t chunk[256]; // bytes are written in here until we have 256 of them, then written to the file
559 
560  uint8_t bitIndex; // how many bits in the partial byte written so far
561  uint8_t byte; // current partial byte
562 
563  uint8_t padding[2]; // make padding explicit
564 } GifBitStatus;
565 
566 // insert a single bit
568 {
569  bit = bit & 1;
570  bit = bit << stat->bitIndex;
571  stat->byte |= bit;
572 
573  ++stat->bitIndex;
574  if (stat->bitIndex > 7)
575  {
576  // move the newly-finished byte to the chunk buffer
577  stat->chunk[stat->chunkIndex++] = stat->byte;
578  // and start a new byte
579  stat->bitIndex = 0;
580  stat->byte = 0;
581  }
582 }
583 
584 // write all bytes so far to the file
585 void GifWriteChunk(FILE* f, GifBitStatus* stat)
586 {
587  fputc((int)stat->chunkIndex, f);
588  fwrite(stat->chunk, 1, stat->chunkIndex, f);
589 
590  stat->bitIndex = 0;
591  stat->byte = 0;
592  stat->chunkIndex = 0;
593 }
594 
595 void GifWriteCode(FILE* f, GifBitStatus* stat, uint32_t code, uint32_t length)
596 {
597  for (uint32_t ii = 0; ii < length; ++ii)
598  {
599  GifWriteBit(stat, code);
600  code = code >> 1;
601 
602  if (stat->chunkIndex == 255)
603  {
604  GifWriteChunk(f, stat);
605  }
606  }
607 }
608 
609 // The LZW dictionary is a 256-ary tree constructed as the file is encoded,
610 // this is one node
611 typedef struct
612 {
613  uint16_t m_next[256];
614 } GifLzwNode;
615 
616 // write a 256-color (8-bit) image palette to the file
617 void GifWritePalette(const GifPalette* pPal, FILE* f)
618 {
619  fputc(0, f); // first color: transparency
620  fputc(0, f);
621  fputc(0, f);
622 
623  for (int ii = 1; ii < (1 << pPal->bitDepth); ++ii)
624  {
625  uint32_t r = pPal->r[ii];
626  uint32_t g = pPal->g[ii];
627  uint32_t b = pPal->b[ii];
628 
629  fputc((int)r, f);
630  fputc((int)g, f);
631  fputc((int)b, f);
632  }
633 }
634 
635 // write the image header, LZW-compress and write out the image
636 void GifWriteLzwImage(FILE* f, uint8_t* image, uint32_t left, uint32_t top, uint32_t width, uint32_t height, uint32_t delay, GifPalette* pPal)
637 {
638  // graphics control extension
639  fputc(0x21, f);
640  fputc(0xf9, f);
641  fputc(0x04, f);
642  fputc(0x05, f); // leave prev frame in place, this frame has transparency
643  fputc(delay & 0xff, f);
644  fputc((delay >> 8) & 0xff, f);
645  fputc(kGifTransIndex, f); // transparent color index
646  fputc(0, f);
647 
648  fputc(0x2c, f); // image descriptor block
649 
650  fputc(left & 0xff, f); // corner of image in canvas space
651  fputc((left >> 8) & 0xff, f);
652  fputc(top & 0xff, f);
653  fputc((top >> 8) & 0xff, f);
654 
655  fputc(width & 0xff, f); // width and height of image
656  fputc((width >> 8) & 0xff, f);
657  fputc(height & 0xff, f);
658  fputc((height >> 8) & 0xff, f);
659 
660  //fputc(0, f); // no local color table, no transparency
661  //fputc(0x80, f); // no local color table, but transparency
662 
663  fputc(0x80 + pPal->bitDepth - 1, f); // local color table present, 2 ^ bitDepth entries
664  GifWritePalette(pPal, f);
665 
666  const int minCodeSize = pPal->bitDepth;
667  const uint32_t clearCode = 1 << pPal->bitDepth;
668 
669  fputc(minCodeSize, f); // min code size 8 bits
670 
671  GifLzwNode* codetree = (GifLzwNode*)GIF_TEMP_MALLOC(sizeof(GifLzwNode) * 4096);
672 
673  memset(codetree, 0, sizeof(GifLzwNode) * 4096);
674  int32_t curCode = -1;
675  uint32_t codeSize = (uint32_t)minCodeSize + 1;
676  uint32_t maxCode = clearCode + 1;
677 
678  GifBitStatus stat;
679  stat.byte = 0;
680  stat.bitIndex = 0;
681  stat.chunkIndex = 0;
682 
683  GifWriteCode(f, &stat, clearCode, codeSize); // start with a fresh LZW dictionary
684 
685  for (uint32_t yy = 0; yy < height; ++yy)
686  {
687  for (uint32_t xx = 0; xx < width; ++xx)
688  {
689 #ifdef GIF_FLIP_VERT
690  // bottom-left origin image (such as an OpenGL capture)
691  uint8_t nextValue = image[((height - 1 - yy) * width + xx) * 4 + 3];
692 #else
693  // top-left origin
694  uint8_t nextValue = image[(yy * width + xx) * 4 + 3];
695 #endif
696 
697  // "worst possible mode" - no compression, every single code is followed immediately by a clear
698  //WriteCode( f, stat, nextValue, codeSize );
699  //WriteCode( f, stat, 256, codeSize );
700 
701  if (curCode < 0)
702  {
703  // first value in a new run
704  curCode = nextValue;
705  }
706  else if (codetree[curCode].m_next[nextValue])
707  {
708  // current run already in the dictionary
709  curCode = codetree[curCode].m_next[nextValue];
710  }
711  else
712  {
713  // finish the current run, write a code
714  GifWriteCode(f, &stat, (uint32_t)curCode, codeSize);
715 
716  // insert the new run into the dictionary
717  codetree[curCode].m_next[nextValue] = (uint16_t)++maxCode;
718 
719  if (maxCode >= (1ul << codeSize))
720  {
721  // dictionary entry count has broken a size barrier,
722  // we need more bits for codes
723  codeSize++;
724  }
725  if (maxCode == 4095)
726  {
727  // the dictionary is full, clear it out and begin anew
728  GifWriteCode(f, &stat, clearCode, codeSize); // clear tree
729 
730  memset(codetree, 0, sizeof(GifLzwNode) * 4096);
731  codeSize = (uint32_t)(minCodeSize + 1);
732  maxCode = clearCode + 1;
733  }
734 
735  curCode = nextValue;
736  }
737  }
738  }
739 
740  // compression footer
741  GifWriteCode(f, &stat, (uint32_t)curCode, codeSize);
742  GifWriteCode(f, &stat, clearCode, codeSize);
743  GifWriteCode(f, &stat, clearCode + 1, (uint32_t)minCodeSize + 1);
744 
745  // write out the last partial chunk
746  while (stat.bitIndex) GifWriteBit(&stat, 0);
747  if (stat.chunkIndex) GifWriteChunk(f, &stat);
748 
749  fputc(0, f); // image block terminator
750 
751  GIF_TEMP_FREE(codetree);
752 }
753 
754 typedef struct
755 {
756  FILE* f;
759 
760  uint8_t padding[7]; // make padding explicit
761 } GifWriter;
762 
763 // Creates a gif file.
764 // The input GIFWriter is assumed to be uninitialized.
765 // The delay value is the time between frames in hundredths of a second - note that not all viewers pay much attention to this value.
766 bool GifBegin(GifWriter* writer, const char* filename, uint32_t width, uint32_t height, uint32_t delay, int32_t bitDepth = 8, bool dither = false)
767 {
768  (void)bitDepth; (void)dither; // Mute "Unused argument" warnings
769 #if defined(_MSC_VER) && (_MSC_VER >= 1400)
770  writer->f = 0;
771  fopen_s(&writer->f, filename, "wb");
772 #else
773  writer->f = fopen(filename, "wb");
774 #endif
775  if (!writer->f) return false;
776 
777  writer->firstFrame = true;
778 
779  // allocate
780  writer->oldImage = (uint8_t*)GIF_MALLOC(width * height * 4);
781 
782  fputs("GIF89a", writer->f);
783 
784  // screen descriptor
785  fputc(width & 0xff, writer->f);
786  fputc((width >> 8) & 0xff, writer->f);
787  fputc(height & 0xff, writer->f);
788  fputc((height >> 8) & 0xff, writer->f);
789 
790  fputc(0xf0, writer->f); // there is an unsorted global color table of 2 entries
791  fputc(0, writer->f); // background color
792  fputc(0, writer->f); // pixels are square (we need to specify this because it's 1989)
793 
794  // now the "global" palette (really just a dummy palette)
795  // color 0: black
796  fputc(0, writer->f);
797  fputc(0, writer->f);
798  fputc(0, writer->f);
799  // color 1: also black
800  fputc(0, writer->f);
801  fputc(0, writer->f);
802  fputc(0, writer->f);
803 
804  if (delay != 0)
805  {
806  // animation header
807  fputc(0x21, writer->f); // extension
808  fputc(0xff, writer->f); // application specific
809  fputc(11, writer->f); // length 11
810  fputs("NETSCAPE2.0", writer->f); // yes, really
811  fputc(3, writer->f); // 3 bytes of NETSCAPE2.0 data
812 
813  fputc(1, writer->f); // this is the Netscape 2.0 sub-block ID and it must be 1, otherwise some viewers error
814  fputc(0, writer->f); // loop infinitely (byte 0)
815  fputc(0, writer->f); // loop infinitely (byte 1)
816 
817  fputc(0, writer->f); // block terminator
818  }
819 
820  return true;
821 }
822 
823 // Writes out a new frame to a GIF in progress.
824 // The GIFWriter should have been created by GIFBegin.
825 // AFAIK, it is legal to use different bit depths for different frames of an image -
826 // this may be handy to save bits in animations that don't change much.
827 bool GifWriteFrame(GifWriter* writer, const uint8_t* image, uint32_t width, uint32_t height, uint32_t delay, int bitDepth = 8, bool dither = false)
828 {
829  if (!writer->f) return false;
830 
831  const uint8_t* oldImage = writer->firstFrame ? NULL : writer->oldImage;
832  writer->firstFrame = false;
833 
834  GifPalette pal;
835  GifMakePalette((dither ? NULL : oldImage), image, width, height, bitDepth, dither, &pal);
836 
837  if (dither)
838  GifDitherImage(oldImage, image, writer->oldImage, width, height, &pal);
839  else
840  GifThresholdImage(oldImage, image, writer->oldImage, width, height, &pal);
841 
842  GifWriteLzwImage(writer->f, writer->oldImage, 0, 0, width, height, delay, &pal);
843 
844  return true;
845 }
846 
847 // Writes the EOF code, closes the file handle, and frees temp memory used by a GIF.
848 // Many if not most viewers will still display a GIF properly if the EOF code is missing,
849 // but it's still a good idea to write it out.
850 bool GifEnd(GifWriter* writer)
851 {
852  if (!writer->f) return false;
853 
854  fputc(0x3b, writer->f); // end of file
855  fclose(writer->f);
856  GIF_FREE(writer->oldImage);
857 
858  writer->f = NULL;
859  writer->oldImage = NULL;
860 
861  return true;
862 }
863 
864 #endif
variable_type::int
@ int
GifIAbs
int GifIAbs(int i)
Definition: gif.h:83
GifLzwNode::m_next
uint16_t m_next[256]
Definition: gif.h:613
GifBitStatus::bitIndex
uint8_t bitIndex
Definition: gif.h:560
GifSplitPalette
void GifSplitPalette(uint8_t *image, int numPixels, int treeNode, int treeLevel, bool buildForDither, GifPalette *pal)
Definition: gif.h:216
GifWriteBit
void GifWriteBit(GifBitStatus *stat, uint32_t bit)
Definition: gif.h:567
GifPickChangedPixels
int GifPickChangedPixels(const uint8_t *lastFrame, uint8_t *frame, int numPixels)
Definition: gif.h:355
kGifTransIndex
const int kGifTransIndex
Definition: gif.h:63
GIF_TEMP_FREE
#define GIF_TEMP_FREE
Definition: gif.h:50
uint8_t
unsigned char uint8_t
Definition: stdint.h:15
GifMakePalette
void GifMakePalette(const uint8_t *lastFrame, const uint8_t *nextFrame, uint32_t width, uint32_t height, int bitDepth, bool buildForDither, GifPalette *pPal)
Definition: gif.h:381
GifBitStatus::chunkIndex
uint32_t chunkIndex
Definition: gif.h:557
GifGetClosestPaletteColor
void GifGetClosestPaletteColor(GifPalette *pPal, int r, int g, int b, int *bestInd, int *bestDiff, int treeRoot)
Definition: gif.h:89
GifWriter
Definition: gif.h:754
GifPartitionByMean
int GifPartitionByMean(uint8_t *image, int left, int right, int com, int neededMean)
Definition: gif.h:206
GifPalette::treeSplit
uint8_t treeSplit[256]
Definition: gif.h:77
GifPalette::treeSplitElt
uint8_t treeSplitElt[256]
Definition: gif.h:76
GifPartitionByMedian
void GifPartitionByMedian(uint8_t *image, int left, int right, int com, int neededCenter)
Definition: gif.h:187
GifPalette::r
uint8_t r[256]
Definition: gif.h:69
uint64_t
unsigned long long uint64_t
Definition: stdint.h:18
GifPalette::g
uint8_t g[256]
Definition: gif.h:70
GifWriter::oldImage
uint8_t * oldImage
Definition: gif.h:757
GifBegin
bool GifBegin(GifWriter *writer, const char *filename, uint32_t width, uint32_t height, uint32_t delay, int32_t bitDepth=8, bool dither=false)
Definition: gif.h:766
int32_t
int int32_t
Definition: stdint.h:13
GifSwapPixels
void GifSwapPixels(uint8_t *image, int pixA, int pixB)
Definition: gif.h:137
NULL
Add a fourth parameter to bake specific font ranges NULL
Definition: README.txt:57
GifPartition
int GifPartition(uint8_t *image, const int left, const int right, const int elt, int pivotValue)
Definition: gif.h:161
GIF_TEMP_MALLOC
#define GIF_TEMP_MALLOC
Definition: gif.h:45
rr
#define rr
Definition: resource.h:8
GifBitStatus::byte
uint8_t byte
Definition: gif.h:561
GIF_MALLOC
#define GIF_MALLOC
Definition: gif.h:55
uint32_t
unsigned int uint32_t
Definition: stdint.h:17
GifIMax
int GifIMax(int l, int r)
Definition: gif.h:81
GifBitStatus
Definition: gif.h:555
GifThresholdImage
void GifThresholdImage(const uint8_t *lastFrame, const uint8_t *nextFrame, uint8_t *outFrame, uint32_t width, uint32_t height, GifPalette *pPal)
Definition: gif.h:516
GifWriteLzwImage
void GifWriteLzwImage(FILE *f, uint8_t *image, uint32_t left, uint32_t top, uint32_t width, uint32_t height, uint32_t delay, GifPalette *pPal)
Definition: gif.h:636
GifWriteFrame
bool GifWriteFrame(GifWriter *writer, const uint8_t *image, uint32_t width, uint32_t height, uint32_t delay, int bitDepth=8, bool dither=false)
Definition: gif.h:827
GifWriter::f
FILE * f
Definition: gif.h:756
GifPalette::b
uint8_t b[256]
Definition: gif.h:71
GifBitStatus::chunk
uint8_t chunk[256]
Definition: gif.h:558
GifWriter::firstFrame
bool firstFrame
Definition: gif.h:758
GifWritePalette
void GifWritePalette(const GifPalette *pPal, FILE *f)
Definition: gif.h:617
GifLzwNode
Definition: gif.h:611
GIF_FREE
#define GIF_FREE
Definition: gif.h:60
GifWriteCode
void GifWriteCode(FILE *f, GifBitStatus *stat, uint32_t code, uint32_t length)
Definition: gif.h:595
GifDitherImage
void GifDitherImage(const uint8_t *lastFrame, const uint8_t *nextFrame, uint8_t *outFrame, uint32_t width, uint32_t height, GifPalette *pPal)
Definition: gif.h:407
GifWriteChunk
void GifWriteChunk(FILE *f, GifBitStatus *stat)
Definition: gif.h:585
GifIMin
int GifIMin(int l, int r)
Definition: gif.h:82
GifPalette
Definition: gif.h:65
uint16_t
unsigned short uint16_t
Definition: stdint.h:16
GifPalette::bitDepth
int bitDepth
Definition: gif.h:67
GifEnd
bool GifEnd(GifWriter *writer)
Definition: gif.h:850