GameApi 28
Library used by GameApi Builder tool
Loading...
Searching...
No Matches
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
63const int kGifTransIndex = 0;
64
65typedef struct
66{
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];
79
80// max, min, and abs functions
81int GifIMax(int l, int r) { return l>r?l:r; }
82int GifIMin(int l, int r) { return l<r?l:r; }
83int 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.
89void 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
137void 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
161int GifPartition(uint8_t* image, const int left, const int right, const int elt, int pivotIndex)
162{
163 const int pivotValue = image[(pivotIndex)*4+elt];
164 GifSwapPixels(image, pivotIndex, right-1);
165 int storeIndex = left;
166 bool split = 0;
167 for(int ii=left; ii<right-1; ++ii)
168 {
169 int arrayVal = image[ii*4+elt];
170 if( arrayVal < pivotValue )
171 {
172 GifSwapPixels(image, ii, storeIndex);
173 ++storeIndex;
174 }
175 else if( arrayVal == pivotValue )
176 {
177 if(split)
178 {
179 GifSwapPixels(image, ii, storeIndex);
180 ++storeIndex;
181 }
182 split = !split;
183 }
184 }
185 GifSwapPixels(image, storeIndex, right-1);
186 return storeIndex;
187}
188
189// Perform an incomplete sort, finding all elements above and below the desired median
190void GifPartitionByMedian(uint8_t* image, int left, int right, int com, int neededCenter)
191{
192 if(left < right-1)
193 {
194 int pivotIndex = left + (right-left)/2;
195
196 pivotIndex = GifPartition(image, left, right, com, pivotIndex);
197
198 // Only "sort" the section of the array that contains the median
199 if(pivotIndex > neededCenter)
200 GifPartitionByMedian(image, left, pivotIndex, com, neededCenter);
201
202 if(pivotIndex < neededCenter)
203 GifPartitionByMedian(image, pivotIndex+1, right, com, neededCenter);
204 }
205}
206
207// Builds a palette by creating a balanced k-d tree of all pixels in the image
208void GifSplitPalette(uint8_t* image, int numPixels, int firstElt, int lastElt, int splitElt, int splitDist, int treeNode, bool buildForDither, GifPalette* pal)
209{
210 if(lastElt <= firstElt || numPixels == 0)
211 return;
212
213 // base case, bottom of the tree
214 if(lastElt == firstElt+1)
215 {
216 if(buildForDither)
217 {
218 // Dithering needs at least one color as dark as anything
219 // in the image and at least one brightest color -
220 // otherwise it builds up error and produces strange artifacts
221 if( firstElt == 1 )
222 {
223 // special case: the darkest color in the image
224 uint32_t r=255, g=255, b=255;
225 for(int ii=0; ii<numPixels; ++ii)
226 {
227 r = (uint32_t)GifIMin((int32_t)r, image[ii * 4 + 0]);
228 g = (uint32_t)GifIMin((int32_t)g, image[ii * 4 + 1]);
229 b = (uint32_t)GifIMin((int32_t)b, image[ii * 4 + 2]);
230 }
231
232 pal->r[firstElt] = (uint8_t)r;
233 pal->g[firstElt] = (uint8_t)g;
234 pal->b[firstElt] = (uint8_t)b;
235
236 return;
237 }
238
239 if( firstElt == (1 << pal->bitDepth)-1 )
240 {
241 // special case: the lightest color in the image
242 uint32_t r=0, g=0, b=0;
243 for(int ii=0; ii<numPixels; ++ii)
244 {
245 r = (uint32_t)GifIMax((int32_t)r, image[ii * 4 + 0]);
246 g = (uint32_t)GifIMax((int32_t)g, image[ii * 4 + 1]);
247 b = (uint32_t)GifIMax((int32_t)b, image[ii * 4 + 2]);
248 }
249
250 pal->r[firstElt] = (uint8_t)r;
251 pal->g[firstElt] = (uint8_t)g;
252 pal->b[firstElt] = (uint8_t)b;
253
254 return;
255 }
256 }
257
258 // otherwise, take the average of all colors in this subcube
259 uint64_t r=0, g=0, b=0;
260 for(int ii=0; ii<numPixels; ++ii)
261 {
262 r += image[ii*4+0];
263 g += image[ii*4+1];
264 b += image[ii*4+2];
265 }
266
267 r += (uint64_t)numPixels / 2; // round to nearest
268 g += (uint64_t)numPixels / 2;
269 b += (uint64_t)numPixels / 2;
270
271 r /= (uint64_t)numPixels;
272 g /= (uint64_t)numPixels;
273 b /= (uint64_t)numPixels;
274
275 pal->r[firstElt] = (uint8_t)r;
276 pal->g[firstElt] = (uint8_t)g;
277 pal->b[firstElt] = (uint8_t)b;
278
279 return;
280 }
281
282 // Find the axis with the largest range
283 int minR = 255, maxR = 0;
284 int minG = 255, maxG = 0;
285 int minB = 255, maxB = 0;
286 for(int ii=0; ii<numPixels; ++ii)
287 {
288 int r = image[ii*4+0];
289 int g = image[ii*4+1];
290 int b = image[ii*4+2];
291
292 if(r > maxR) maxR = r;
293 if(r < minR) minR = r;
294
295 if(g > maxG) maxG = g;
296 if(g < minG) minG = g;
297
298 if(b > maxB) maxB = b;
299 if(b < minB) minB = b;
300 }
301
302 int rRange = maxR - minR;
303 int gRange = maxG - minG;
304 int bRange = maxB - minB;
305
306 // 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)
307 int splitCom = 1;
308 if(bRange > gRange) splitCom = 2;
309 if(rRange > bRange && rRange > gRange) splitCom = 0;
310
311 int subPixelsA = numPixels * (splitElt - firstElt) / (lastElt - firstElt);
312 int subPixelsB = numPixels-subPixelsA;
313
314 GifPartitionByMedian(image, 0, numPixels, splitCom, subPixelsA);
315
316 pal->treeSplitElt[treeNode] = (uint8_t)splitCom;
317 pal->treeSplit[treeNode] = image[subPixelsA*4+splitCom];
318
319 GifSplitPalette(image, subPixelsA, firstElt, splitElt, splitElt-splitDist, splitDist/2, treeNode*2, buildForDither, pal);
320 GifSplitPalette(image+subPixelsA*4, subPixelsB, splitElt, lastElt, splitElt+splitDist, splitDist/2, treeNode*2+1, buildForDither, pal);
321}
322
323// Finds all pixels that have changed from the previous image and
324// moves them to the fromt of th buffer.
325// This allows us to build a palette optimized for the colors of the
326// changed pixels only.
327int GifPickChangedPixels( const uint8_t* lastFrame, uint8_t* frame, int numPixels )
328{
329 int numChanged = 0;
330 uint8_t* writeIter = frame;
331
332 for (int ii=0; ii<numPixels; ++ii)
333 {
334 if(lastFrame[0] != frame[0] ||
335 lastFrame[1] != frame[1] ||
336 lastFrame[2] != frame[2])
337 {
338 writeIter[0] = frame[0];
339 writeIter[1] = frame[1];
340 writeIter[2] = frame[2];
341 ++numChanged;
342 writeIter += 4;
343 }
344 lastFrame += 4;
345 frame += 4;
346 }
347
348 return numChanged;
349}
350
351// Creates a palette by placing all the image pixels in a k-d tree and then averaging the blocks at the bottom.
352// This is known as the "modified median split" technique
353void GifMakePalette( const uint8_t* lastFrame, const uint8_t* nextFrame, uint32_t width, uint32_t height, int bitDepth, bool buildForDither, GifPalette* pPal )
354{
355 pPal->bitDepth = bitDepth;
356
357 // SplitPalette is destructive (it sorts the pixels by color) so
358 // we must create a copy of the image for it to destroy
359 size_t imageSize = (size_t)(width * height * 4 * sizeof(uint8_t));
360 uint8_t* destroyableImage = (uint8_t*)GIF_TEMP_MALLOC(imageSize);
361 memcpy(destroyableImage, nextFrame, imageSize);
362
363 int numPixels = (int)(width * height);
364 if(lastFrame)
365 numPixels = GifPickChangedPixels(lastFrame, destroyableImage, numPixels);
366
367 const int lastElt = 1 << bitDepth;
368 const int splitElt = lastElt/2;
369 const int splitDist = splitElt/2;
370
371 GifSplitPalette(destroyableImage, numPixels, 1, lastElt, splitElt, splitDist, 1, buildForDither, pPal);
372
373 GIF_TEMP_FREE(destroyableImage);
374
375 // add the bottom node for the transparency index
376 pPal->treeSplit[1 << (bitDepth-1)] = 0;
377 pPal->treeSplitElt[1 << (bitDepth-1)] = 0;
378
379 pPal->r[0] = pPal->g[0] = pPal->b[0] = 0;
380}
381
382// Implements Floyd-Steinberg dithering, writes palette value to alpha
383void GifDitherImage( const uint8_t* lastFrame, const uint8_t* nextFrame, uint8_t* outFrame, uint32_t width, uint32_t height, GifPalette* pPal )
384{
385 int numPixels = (int)(width * height);
386
387 // quantPixels initially holds color*256 for all pixels
388 // The extra 8 bits of precision allow for sub-single-color error values
389 // to be propagated
390 int32_t *quantPixels = (int32_t *)GIF_TEMP_MALLOC(sizeof(int32_t) * (size_t)numPixels * 4);
391
392 for( int ii=0; ii<numPixels*4; ++ii )
393 {
394 uint8_t pix = nextFrame[ii];
395 int32_t pix16 = (int32_t)(pix) * 256;
396 quantPixels[ii] = pix16;
397 }
398
399 for( uint32_t yy=0; yy<height; ++yy )
400 {
401 for( uint32_t xx=0; xx<width; ++xx )
402 {
403 int32_t* nextPix = quantPixels + 4*(yy*width+xx);
404 const uint8_t* lastPix = lastFrame? lastFrame + 4*(yy*width+xx) : NULL;
405
406 // Compute the colors we want (rounding to nearest)
407 int32_t rr = (nextPix[0] + 127) / 256;
408 int32_t gg = (nextPix[1] + 127) / 256;
409 int32_t bb = (nextPix[2] + 127) / 256;
410
411 // if it happens that we want the color from last frame, then just write out
412 // a transparent pixel
413 if( lastFrame &&
414 lastPix[0] == rr &&
415 lastPix[1] == gg &&
416 lastPix[2] == bb )
417 {
418 nextPix[0] = rr;
419 nextPix[1] = gg;
420 nextPix[2] = bb;
421 nextPix[3] = kGifTransIndex;
422 continue;
423 }
424
425 int32_t bestDiff = 1000000;
426 int32_t bestInd = kGifTransIndex;
427
428 // Search the palete
429 GifGetClosestPaletteColor(pPal, rr, gg, bb, &bestInd, &bestDiff, 1);
430
431 // Write the result to the temp buffer
432 int32_t r_err = nextPix[0] - (int32_t)(pPal->r[bestInd]) * 256;
433 int32_t g_err = nextPix[1] - (int32_t)(pPal->g[bestInd]) * 256;
434 int32_t b_err = nextPix[2] - (int32_t)(pPal->b[bestInd]) * 256;
435
436 nextPix[0] = pPal->r[bestInd];
437 nextPix[1] = pPal->g[bestInd];
438 nextPix[2] = pPal->b[bestInd];
439 nextPix[3] = bestInd;
440
441 // Propagate the error to the four adjacent locations
442 // that we haven't touched yet
443 int quantloc_7 = (int)(yy * width + xx + 1);
444 int quantloc_3 = (int)(yy * width + width + xx - 1);
445 int quantloc_5 = (int)(yy * width + width + xx);
446 int quantloc_1 = (int)(yy * width + width + xx + 1);
447
448 if(quantloc_7 < numPixels)
449 {
450 int32_t* pix7 = quantPixels+4*quantloc_7;
451 pix7[0] += GifIMax( -pix7[0], r_err * 7 / 16 );
452 pix7[1] += GifIMax( -pix7[1], g_err * 7 / 16 );
453 pix7[2] += GifIMax( -pix7[2], b_err * 7 / 16 );
454 }
455
456 if(quantloc_3 < numPixels)
457 {
458 int32_t* pix3 = quantPixels+4*quantloc_3;
459 pix3[0] += GifIMax( -pix3[0], r_err * 3 / 16 );
460 pix3[1] += GifIMax( -pix3[1], g_err * 3 / 16 );
461 pix3[2] += GifIMax( -pix3[2], b_err * 3 / 16 );
462 }
463
464 if(quantloc_5 < numPixels)
465 {
466 int32_t* pix5 = quantPixels+4*quantloc_5;
467 pix5[0] += GifIMax( -pix5[0], r_err * 5 / 16 );
468 pix5[1] += GifIMax( -pix5[1], g_err * 5 / 16 );
469 pix5[2] += GifIMax( -pix5[2], b_err * 5 / 16 );
470 }
471
472 if(quantloc_1 < numPixels)
473 {
474 int32_t* pix1 = quantPixels+4*quantloc_1;
475 pix1[0] += GifIMax( -pix1[0], r_err / 16 );
476 pix1[1] += GifIMax( -pix1[1], g_err / 16 );
477 pix1[2] += GifIMax( -pix1[2], b_err / 16 );
478 }
479 }
480 }
481
482 // Copy the palettized result to the output buffer
483 for( int ii=0; ii<numPixels*4; ++ii )
484 {
485 outFrame[ii] = (uint8_t)quantPixels[ii];
486 }
487
488 GIF_TEMP_FREE(quantPixels);
489}
490
491// Picks palette colors for the image using simple thresholding, no dithering
492void GifThresholdImage( const uint8_t* lastFrame, const uint8_t* nextFrame, uint8_t* outFrame, uint32_t width, uint32_t height, GifPalette* pPal )
493{
494 uint32_t numPixels = width*height;
495 for( uint32_t ii=0; ii<numPixels; ++ii )
496 {
497 // if a previous color is available, and it matches the current color,
498 // set the pixel to transparent
499 if(lastFrame &&
500 lastFrame[0] == nextFrame[0] &&
501 lastFrame[1] == nextFrame[1] &&
502 lastFrame[2] == nextFrame[2])
503 {
504 outFrame[0] = lastFrame[0];
505 outFrame[1] = lastFrame[1];
506 outFrame[2] = lastFrame[2];
507 outFrame[3] = kGifTransIndex;
508 }
509 else
510 {
511 // palettize the pixel
512 int32_t bestDiff = 1000000;
513 int32_t bestInd = 1;
514 GifGetClosestPaletteColor(pPal, nextFrame[0], nextFrame[1], nextFrame[2], &bestInd, &bestDiff, 1);
515
516 // Write the resulting color to the output buffer
517 outFrame[0] = pPal->r[bestInd];
518 outFrame[1] = pPal->g[bestInd];
519 outFrame[2] = pPal->b[bestInd];
520 outFrame[3] = (uint8_t)bestInd;
521 }
522
523 if(lastFrame) lastFrame += 4;
524 outFrame += 4;
525 nextFrame += 4;
526 }
527}
528
529// Simple structure to write out the LZW-compressed portion of the image
530// one bit at a time
531typedef struct
532{
533 uint8_t bitIndex; // how many bits in the partial byte written so far
534 uint8_t byte; // current partial byte
535
536 uint32_t chunkIndex;
537 uint8_t chunk[256]; // bytes are written in here until we have 256 of them, then written to the file
539
540// insert a single bit
541void GifWriteBit( GifBitStatus* stat, uint32_t bit )
542{
543 bit = bit & 1;
544 bit = bit << stat->bitIndex;
545 stat->byte |= bit;
546
547 ++stat->bitIndex;
548 if( stat->bitIndex > 7 )
549 {
550 // move the newly-finished byte to the chunk buffer
551 stat->chunk[stat->chunkIndex++] = stat->byte;
552 // and start a new byte
553 stat->bitIndex = 0;
554 stat->byte = 0;
555 }
556}
557
558// write all bytes so far to the file
559void GifWriteChunk( FILE* f, GifBitStatus* stat )
560{
561 fputc((int)stat->chunkIndex, f);
562 fwrite(stat->chunk, 1, stat->chunkIndex, f);
563
564 stat->bitIndex = 0;
565 stat->byte = 0;
566 stat->chunkIndex = 0;
567}
568
569void GifWriteCode( FILE* f, GifBitStatus* stat, uint32_t code, uint32_t length )
570{
571 for( uint32_t ii=0; ii<length; ++ii )
572 {
573 GifWriteBit(stat, code);
574 code = code >> 1;
575
576 if( stat->chunkIndex == 255 )
577 {
578 GifWriteChunk(f, stat);
579 }
580 }
581}
582
583// The LZW dictionary is a 256-ary tree constructed as the file is encoded,
584// this is one node
585typedef struct
586{
587 uint16_t m_next[256];
588} GifLzwNode;
589
590// write a 256-color (8-bit) image palette to the file
591void GifWritePalette( const GifPalette* pPal, FILE* f )
592{
593 fputc(0, f); // first color: transparency
594 fputc(0, f);
595 fputc(0, f);
596
597 for(int ii=1; ii<(1 << pPal->bitDepth); ++ii)
598 {
599 uint32_t r = pPal->r[ii];
600 uint32_t g = pPal->g[ii];
601 uint32_t b = pPal->b[ii];
602
603 fputc((int)r, f);
604 fputc((int)g, f);
605 fputc((int)b, f);
606 }
607}
608
609// write the image header, LZW-compress and write out the image
610void GifWriteLzwImage(FILE* f, uint8_t* image, uint32_t left, uint32_t top, uint32_t width, uint32_t height, uint32_t delay, GifPalette* pPal)
611{
612 // graphics control extension
613 fputc(0x21, f);
614 fputc(0xf9, f);
615 fputc(0x04, f);
616 fputc(0x05, f); // leave prev frame in place, this frame has transparency
617 fputc(delay & 0xff, f);
618 fputc((delay >> 8) & 0xff, f);
619 fputc(kGifTransIndex, f); // transparent color index
620 fputc(0, f);
621
622 fputc(0x2c, f); // image descriptor block
623
624 fputc(left & 0xff, f); // corner of image in canvas space
625 fputc((left >> 8) & 0xff, f);
626 fputc(top & 0xff, f);
627 fputc((top >> 8) & 0xff, f);
628
629 fputc(width & 0xff, f); // width and height of image
630 fputc((width >> 8) & 0xff, f);
631 fputc(height & 0xff, f);
632 fputc((height >> 8) & 0xff, f);
633
634 //fputc(0, f); // no local color table, no transparency
635 //fputc(0x80, f); // no local color table, but transparency
636
637 fputc(0x80 + pPal->bitDepth-1, f); // local color table present, 2 ^ bitDepth entries
638 GifWritePalette(pPal, f);
639
640 const int minCodeSize = pPal->bitDepth;
641 const uint32_t clearCode = 1 << pPal->bitDepth;
642
643 fputc(minCodeSize, f); // min code size 8 bits
644
645 GifLzwNode* codetree = (GifLzwNode*)GIF_TEMP_MALLOC(sizeof(GifLzwNode)*4096);
646
647 memset(codetree, 0, sizeof(GifLzwNode)*4096);
648 int32_t curCode = -1;
649 uint32_t codeSize = (uint32_t)minCodeSize + 1;
650 uint32_t maxCode = clearCode+1;
651
652 GifBitStatus stat;
653 stat.byte = 0;
654 stat.bitIndex = 0;
655 stat.chunkIndex = 0;
656
657 GifWriteCode(f, &stat, clearCode, codeSize); // start with a fresh LZW dictionary
658
659 for(uint32_t yy=0; yy<height; ++yy)
660 {
661 for(uint32_t xx=0; xx<width; ++xx)
662 {
663 #ifdef GIF_FLIP_VERT
664 // bottom-left origin image (such as an OpenGL capture)
665 uint8_t nextValue = image[((height-1-yy)*width+xx)*4+3];
666 #else
667 // top-left origin
668 uint8_t nextValue = image[(yy*width+xx)*4+3];
669 #endif
670
671 // "loser mode" - no compression, every single code is followed immediately by a clear
672 //WriteCode( f, stat, nextValue, codeSize );
673 //WriteCode( f, stat, 256, codeSize );
674
675 if( curCode < 0 )
676 {
677 // first value in a new run
678 curCode = nextValue;
679 }
680 else if( codetree[curCode].m_next[nextValue] )
681 {
682 // current run already in the dictionary
683 curCode = codetree[curCode].m_next[nextValue];
684 }
685 else
686 {
687 // finish the current run, write a code
688 GifWriteCode(f, &stat, (uint32_t)curCode, codeSize);
689
690 // insert the new run into the dictionary
691 codetree[curCode].m_next[nextValue] = (uint16_t)++maxCode;
692
693 if( maxCode >= (1ul << codeSize) )
694 {
695 // dictionary entry count has broken a size barrier,
696 // we need more bits for codes
697 codeSize++;
698 }
699 if( maxCode == 4095 )
700 {
701 // the dictionary is full, clear it out and begin anew
702 GifWriteCode(f, &stat, clearCode, codeSize); // clear tree
703
704 memset(codetree, 0, sizeof(GifLzwNode)*4096);
705 codeSize = (uint32_t)(minCodeSize + 1);
706 maxCode = clearCode+1;
707 }
708
709 curCode = nextValue;
710 }
711 }
712 }
713
714 // compression footer
715 GifWriteCode(f, &stat, (uint32_t)curCode, codeSize);
716 GifWriteCode(f, &stat, clearCode, codeSize);
717 GifWriteCode(f, &stat, clearCode + 1, (uint32_t)minCodeSize + 1);
718
719 // write out the last partial chunk
720 while( stat.bitIndex ) GifWriteBit(&stat, 0);
721 if( stat.chunkIndex ) GifWriteChunk(f, &stat);
722
723 fputc(0, f); // image block terminator
724
725 GIF_TEMP_FREE(codetree);
726}
727
728typedef struct
729{
730 FILE* f;
731 uint8_t* oldImage;
733} GifWriter;
734
735// Creates a gif file.
736// The input GIFWriter is assumed to be uninitialized.
737// The delay value is the time between frames in hundredths of a second - note that not all viewers pay much attention to this value.
738bool GifBegin( GifWriter* writer, const char* filename, uint32_t width, uint32_t height, uint32_t delay, int32_t bitDepth = 8, bool dither = false )
739{
740 (void)bitDepth; (void)dither; // Mute "Unused argument" warnings
741#if defined(_MSC_VER) && (_MSC_VER >= 1400)
742 writer->f = 0;
743 fopen_s(&writer->f, filename, "wb");
744#else
745 writer->f = fopen(filename, "wb");
746#endif
747 if(!writer->f) return false;
748
749 writer->firstFrame = true;
750
751 // allocate
752 writer->oldImage = (uint8_t*)GIF_MALLOC(width*height*4);
753
754 fputs("GIF89a", writer->f);
755
756 // screen descriptor
757 fputc(width & 0xff, writer->f);
758 fputc((width >> 8) & 0xff, writer->f);
759 fputc(height & 0xff, writer->f);
760 fputc((height >> 8) & 0xff, writer->f);
761
762 fputc(0xf0, writer->f); // there is an unsorted global color table of 2 entries
763 fputc(0, writer->f); // background color
764 fputc(0, writer->f); // pixels are square (we need to specify this because it's 1989)
765
766 // now the "global" palette (really just a dummy palette)
767 // color 0: black
768 fputc(0, writer->f);
769 fputc(0, writer->f);
770 fputc(0, writer->f);
771 // color 1: also black
772 fputc(0, writer->f);
773 fputc(0, writer->f);
774 fputc(0, writer->f);
775
776 if( delay != 0 )
777 {
778 // animation header
779 fputc(0x21, writer->f); // extension
780 fputc(0xff, writer->f); // application specific
781 fputc(11, writer->f); // length 11
782 fputs("NETSCAPE2.0", writer->f); // yes, really
783 fputc(3, writer->f); // 3 bytes of NETSCAPE2.0 data
784
785 fputc(1, writer->f); // JUST BECAUSE
786 fputc(0, writer->f); // loop infinitely (byte 0)
787 fputc(0, writer->f); // loop infinitely (byte 1)
788
789 fputc(0, writer->f); // block terminator
790 }
791
792 return true;
793}
794
795// Writes out a new frame to a GIF in progress.
796// The GIFWriter should have been created by GIFBegin.
797// AFAIK, it is legal to use different bit depths for different frames of an image -
798// this may be handy to save bits in animations that don't change much.
799bool GifWriteFrame( GifWriter* writer, const uint8_t* image, uint32_t width, uint32_t height, uint32_t delay, int bitDepth = 8, bool dither = false )
800{
801 if(!writer->f) return false;
802
803 const uint8_t* oldImage = writer->firstFrame? NULL : writer->oldImage;
804 writer->firstFrame = false;
805
806 GifPalette pal;
807 GifMakePalette((dither? NULL : oldImage), image, width, height, bitDepth, dither, &pal);
808
809 if(dither)
810 GifDitherImage(oldImage, image, writer->oldImage, width, height, &pal);
811 else
812 GifThresholdImage(oldImage, image, writer->oldImage, width, height, &pal);
813
814 GifWriteLzwImage(writer->f, writer->oldImage, 0, 0, width, height, delay, &pal);
815
816 return true;
817}
818
819// Writes the EOF code, closes the file handle, and frees temp memory used by a GIF.
820// Many if not most viewers will still display a GIF properly if the EOF code is missing,
821// but it's still a good idea to write it out.
822bool GifEnd( GifWriter* writer )
823{
824 if(!writer->f) return false;
825
826 fputc(0x3b, writer->f); // end of file
827 fclose(writer->f);
828 GIF_FREE(writer->oldImage);
829
830 writer->f = NULL;
831 writer->oldImage = NULL;
832
833 return true;
834}
835
836#endif
void split(std::vector< FontInterfaceImpl::Bezier2d > &vec, FontInterfaceImpl::Bezier2d orig, float t, bool emit_left, bool emit_right)
Definition FreeType2.cc:134
std::string code
Definition test.cpp:145
frame( $arr, $width, $height, $data, $i, $homepage, $noheaders, $seamless, $transparent)
Definition emscripten_frame.php:18
#define GIF_MALLOC
Definition gif.h:55
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:610
void GifWritePalette(const GifPalette *pPal, FILE *f)
Definition gif.h:591
void GifGetClosestPaletteColor(GifPalette *pPal, int r, int g, int b, int *bestInd, int *bestDiff, int treeRoot)
Definition gif.h:89
void GifWriteBit(GifBitStatus *stat, uint32_t bit)
Definition gif.h:541
#define GIF_TEMP_FREE
Definition gif.h:50
void GifThresholdImage(const uint8_t *lastFrame, const uint8_t *nextFrame, uint8_t *outFrame, uint32_t width, uint32_t height, GifPalette *pPal)
Definition gif.h:492
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:799
void GifDitherImage(const uint8_t *lastFrame, const uint8_t *nextFrame, uint8_t *outFrame, uint32_t width, uint32_t height, GifPalette *pPal)
Definition gif.h:383
const int kGifTransIndex
Definition gif.h:63
#define GIF_FREE
Definition gif.h:60
int GifIAbs(int i)
Definition gif.h:83
void GifWriteChunk(FILE *f, GifBitStatus *stat)
Definition gif.h:559
bool GifEnd(GifWriter *writer)
Definition gif.h:822
int GifPartition(uint8_t *image, const int left, const int right, const int elt, int pivotIndex)
Definition gif.h:161
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:738
void GifSwapPixels(uint8_t *image, int pixA, int pixB)
Definition gif.h:137
void GifWriteCode(FILE *f, GifBitStatus *stat, uint32_t code, uint32_t length)
Definition gif.h:569
#define GIF_TEMP_MALLOC
Definition gif.h:45
void GifPartitionByMedian(uint8_t *image, int left, int right, int com, int neededCenter)
Definition gif.h:190
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:353
int GifIMin(int l, int r)
Definition gif.h:82
int GifPickChangedPixels(const uint8_t *lastFrame, uint8_t *frame, int numPixels)
Definition gif.h:327
int GifIMax(int l, int r)
Definition gif.h:81
void GifSplitPalette(uint8_t *image, int numPixels, int firstElt, int lastElt, int splitElt, int splitDist, int treeNode, bool buildForDither, GifPalette *pal)
Definition gif.h:208
line height
Definition meshpage.php:3536
background image
Definition meshpage_bootstrap.php:1723
double f(const std::string &, double, bool) noexcept
Definition profile_cpp_calls_2.cpp:4
Definition gif.h:532
uint32_t chunkIndex
Definition gif.h:536
uint8_t chunk[256]
Definition gif.h:537
uint8_t byte
Definition gif.h:534
uint8_t bitIndex
Definition gif.h:533
Definition gif.h:586
uint16_t m_next[256]
Definition gif.h:587
Definition gif.h:66
uint8_t b[256]
Definition gif.h:71
uint8_t treeSplitElt[256]
Definition gif.h:76
uint8_t r[256]
Definition gif.h:69
int bitDepth
Definition gif.h:67
uint8_t g[256]
Definition gif.h:70
uint8_t treeSplit[256]
Definition gif.h:77
Definition gif.h:729
FILE * f
Definition gif.h:730
uint8_t * oldImage
Definition gif.h:731
bool firstFrame
Definition gif.h:732