gif.h 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835
  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. #ifndef gif_h
  29. #define gif_h
  30. #include <stdio.h> // for FILE*
  31. #include <string.h> // for memcpy and bzero
  32. #include <stdint.h> // for integer typedefs
  33. // Define these macros to hook into a custom memory allocator.
  34. // TEMP_MALLOC and TEMP_FREE will only be called in stack fashion - frees in the reverse order of mallocs
  35. // and any temp memory allocated by a function will be freed before it exits.
  36. // MALLOC and FREE are used only by GifBegin and GifEnd respectively (to allocate a buffer the size of the image, which
  37. // is used to find changed pixels for delta-encoding.)
  38. #ifndef GIF_TEMP_MALLOC
  39. #include <stdlib.h>
  40. #define GIF_TEMP_MALLOC malloc
  41. #endif
  42. #ifndef GIF_TEMP_FREE
  43. #include <stdlib.h>
  44. #define GIF_TEMP_FREE free
  45. #endif
  46. #ifndef GIF_MALLOC
  47. #include <stdlib.h>
  48. #define GIF_MALLOC malloc
  49. #endif
  50. #ifndef GIF_FREE
  51. #include <stdlib.h>
  52. #define GIF_FREE free
  53. #endif
  54. const int kGifTransIndex = 0;
  55. struct GifPalette
  56. {
  57. int bitDepth;
  58. uint8_t r[256];
  59. uint8_t g[256];
  60. uint8_t b[256];
  61. // k-d tree over RGB space, organized in heap fashion
  62. // i.e. left child of node i is node i*2, right child is node i*2+1
  63. // nodes 256-511 are implicitly the leaves, containing a color
  64. uint8_t treeSplitElt[255];
  65. uint8_t treeSplit[255];
  66. };
  67. // max, min, and abs functions
  68. int GifIMax(int l, int r) { return l>r?l:r; }
  69. int GifIMin(int l, int r) { return l<r?l:r; }
  70. int GifIAbs(int i) { return i<0?-i:i; }
  71. // walks the k-d tree to pick the palette entry for a desired color.
  72. // Takes as in/out parameters the current best color and its error -
  73. // only changes them if it finds a better color in its subtree.
  74. // this is the major hotspot in the code at the moment.
  75. void GifGetClosestPaletteColor(GifPalette* pPal, int r, int g, int b, int& bestInd, int& bestDiff, int treeRoot = 1)
  76. {
  77. // base case, reached the bottom of the tree
  78. if(treeRoot > (1<<pPal->bitDepth)-1)
  79. {
  80. int ind = treeRoot-(1<<pPal->bitDepth);
  81. if(ind == kGifTransIndex) return;
  82. // check whether this color is better than the current winner
  83. int r_err = r - ((int32_t)pPal->r[ind]);
  84. int g_err = g - ((int32_t)pPal->g[ind]);
  85. int b_err = b - ((int32_t)pPal->b[ind]);
  86. int diff = GifIAbs(r_err)+GifIAbs(g_err)+GifIAbs(b_err);
  87. if(diff < bestDiff)
  88. {
  89. bestInd = ind;
  90. bestDiff = diff;
  91. }
  92. return;
  93. }
  94. // take the appropriate color (r, g, or b) for this node of the k-d tree
  95. int comps[3]; comps[0] = r; comps[1] = g; comps[2] = b;
  96. int splitComp = comps[pPal->treeSplitElt[treeRoot]];
  97. int splitPos = pPal->treeSplit[treeRoot];
  98. if(splitPos > splitComp)
  99. {
  100. // check the left subtree
  101. GifGetClosestPaletteColor(pPal, r, g, b, bestInd, bestDiff, treeRoot*2);
  102. if( bestDiff > splitPos - splitComp )
  103. {
  104. // cannot prove there's not a better value in the right subtree, check that too
  105. GifGetClosestPaletteColor(pPal, r, g, b, bestInd, bestDiff, treeRoot*2+1);
  106. }
  107. }
  108. else
  109. {
  110. GifGetClosestPaletteColor(pPal, r, g, b, bestInd, bestDiff, treeRoot*2+1);
  111. if( bestDiff > splitComp - splitPos )
  112. {
  113. GifGetClosestPaletteColor(pPal, r, g, b, bestInd, bestDiff, treeRoot*2);
  114. }
  115. }
  116. }
  117. void GifSwapPixels(uint8_t* image, int pixA, int pixB)
  118. {
  119. uint8_t rA = image[pixA*4];
  120. uint8_t gA = image[pixA*4+1];
  121. uint8_t bA = image[pixA*4+2];
  122. uint8_t aA = image[pixA*4+3];
  123. uint8_t rB = image[pixB*4];
  124. uint8_t gB = image[pixB*4+1];
  125. uint8_t bB = image[pixB*4+2];
  126. uint8_t aB = image[pixA*4+3];
  127. image[pixA*4] = rB;
  128. image[pixA*4+1] = gB;
  129. image[pixA*4+2] = bB;
  130. image[pixA*4+3] = aB;
  131. image[pixB*4] = rA;
  132. image[pixB*4+1] = gA;
  133. image[pixB*4+2] = bA;
  134. image[pixB*4+3] = aA;
  135. }
  136. // just the partition operation from quicksort
  137. int GifPartition(uint8_t* image, const int left, const int right, const int elt, int pivotIndex)
  138. {
  139. const int pivotValue = image[(pivotIndex)*4+elt];
  140. GifSwapPixels(image, pivotIndex, right-1);
  141. int storeIndex = left;
  142. bool split = 0;
  143. for(int ii=left; ii<right-1; ++ii)
  144. {
  145. int arrayVal = image[ii*4+elt];
  146. if( arrayVal < pivotValue )
  147. {
  148. GifSwapPixels(image, ii, storeIndex);
  149. ++storeIndex;
  150. }
  151. else if( arrayVal == pivotValue )
  152. {
  153. if(split)
  154. {
  155. GifSwapPixels(image, ii, storeIndex);
  156. ++storeIndex;
  157. }
  158. split = !split;
  159. }
  160. }
  161. GifSwapPixels(image, storeIndex, right-1);
  162. return storeIndex;
  163. }
  164. // Perform an incomplete sort, finding all elements above and below the desired median
  165. void GifPartitionByMedian(uint8_t* image, int left, int right, int com, int neededCenter)
  166. {
  167. if(left < right-1)
  168. {
  169. int pivotIndex = left + (right-left)/2;
  170. pivotIndex = GifPartition(image, left, right, com, pivotIndex);
  171. // Only "sort" the section of the array that contains the median
  172. if(pivotIndex > neededCenter)
  173. GifPartitionByMedian(image, left, pivotIndex, com, neededCenter);
  174. if(pivotIndex < neededCenter)
  175. GifPartitionByMedian(image, pivotIndex+1, right, com, neededCenter);
  176. }
  177. }
  178. // Builds a palette by creating a balanced k-d tree of all pixels in the image
  179. void GifSplitPalette(uint8_t* image, int numPixels, int firstElt, int lastElt, int splitElt, int splitDist, int treeNode, bool buildForDither, GifPalette* pal)
  180. {
  181. if(lastElt <= firstElt || numPixels == 0)
  182. return;
  183. // base case, bottom of the tree
  184. if(lastElt == firstElt+1)
  185. {
  186. if(buildForDither)
  187. {
  188. // Dithering needs at least one color as dark as anything
  189. // in the image and at least one brightest color -
  190. // otherwise it builds up error and produces strange artifacts
  191. if( firstElt == 1 )
  192. {
  193. // special case: the darkest color in the image
  194. uint32_t r=255, g=255, b=255;
  195. for(int ii=0; ii<numPixels; ++ii)
  196. {
  197. r = (uint32_t)GifIMin((int32_t)r, image[ii * 4 + 0]);
  198. g = (uint32_t)GifIMin((int32_t)g, image[ii * 4 + 1]);
  199. b = (uint32_t)GifIMin((int32_t)b, image[ii * 4 + 2]);
  200. }
  201. pal->r[firstElt] = (uint8_t)r;
  202. pal->g[firstElt] = (uint8_t)g;
  203. pal->b[firstElt] = (uint8_t)b;
  204. return;
  205. }
  206. if( firstElt == (1 << pal->bitDepth)-1 )
  207. {
  208. // special case: the lightest color in the image
  209. uint32_t r=0, g=0, b=0;
  210. for(int ii=0; ii<numPixels; ++ii)
  211. {
  212. r = (uint32_t)GifIMax((int32_t)r, image[ii * 4 + 0]);
  213. g = (uint32_t)GifIMax((int32_t)g, image[ii * 4 + 1]);
  214. b = (uint32_t)GifIMax((int32_t)b, image[ii * 4 + 2]);
  215. }
  216. pal->r[firstElt] = (uint8_t)r;
  217. pal->g[firstElt] = (uint8_t)g;
  218. pal->b[firstElt] = (uint8_t)b;
  219. return;
  220. }
  221. }
  222. // otherwise, take the average of all colors in this subcube
  223. uint64_t r=0, g=0, b=0;
  224. for(int ii=0; ii<numPixels; ++ii)
  225. {
  226. r += image[ii*4+0];
  227. g += image[ii*4+1];
  228. b += image[ii*4+2];
  229. }
  230. r += (uint64_t)numPixels / 2; // round to nearest
  231. g += (uint64_t)numPixels / 2;
  232. b += (uint64_t)numPixels / 2;
  233. r /= (uint64_t)numPixels;
  234. g /= (uint64_t)numPixels;
  235. b /= (uint64_t)numPixels;
  236. pal->r[firstElt] = (uint8_t)r;
  237. pal->g[firstElt] = (uint8_t)g;
  238. pal->b[firstElt] = (uint8_t)b;
  239. return;
  240. }
  241. // Find the axis with the largest range
  242. int minR = 255, maxR = 0;
  243. int minG = 255, maxG = 0;
  244. int minB = 255, maxB = 0;
  245. for(int ii=0; ii<numPixels; ++ii)
  246. {
  247. int r = image[ii*4+0];
  248. int g = image[ii*4+1];
  249. int b = image[ii*4+2];
  250. if(r > maxR) maxR = r;
  251. if(r < minR) minR = r;
  252. if(g > maxG) maxG = g;
  253. if(g < minG) minG = g;
  254. if(b > maxB) maxB = b;
  255. if(b < minB) minB = b;
  256. }
  257. int rRange = maxR - minR;
  258. int gRange = maxG - minG;
  259. int bRange = maxB - minB;
  260. // 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)
  261. int splitCom = 1;
  262. if(bRange > gRange) splitCom = 2;
  263. if(rRange > bRange && rRange > gRange) splitCom = 0;
  264. int subPixelsA = numPixels * (splitElt - firstElt) / (lastElt - firstElt);
  265. int subPixelsB = numPixels-subPixelsA;
  266. GifPartitionByMedian(image, 0, numPixels, splitCom, subPixelsA);
  267. pal->treeSplitElt[treeNode] = (uint8_t)splitCom;
  268. pal->treeSplit[treeNode] = image[subPixelsA*4+splitCom];
  269. GifSplitPalette(image, subPixelsA, firstElt, splitElt, splitElt-splitDist, splitDist/2, treeNode*2, buildForDither, pal);
  270. GifSplitPalette(image+subPixelsA*4, subPixelsB, splitElt, lastElt, splitElt+splitDist, splitDist/2, treeNode*2+1, buildForDither, pal);
  271. }
  272. // Finds all pixels that have changed from the previous image and
  273. // moves them to the fromt of th buffer.
  274. // This allows us to build a palette optimized for the colors of the
  275. // changed pixels only.
  276. int GifPickChangedPixels( const uint8_t* lastFrame, uint8_t* frame, int numPixels )
  277. {
  278. int numChanged = 0;
  279. uint8_t* writeIter = frame;
  280. for (int ii=0; ii<numPixels; ++ii)
  281. {
  282. if(lastFrame[0] != frame[0] ||
  283. lastFrame[1] != frame[1] ||
  284. lastFrame[2] != frame[2])
  285. {
  286. writeIter[0] = frame[0];
  287. writeIter[1] = frame[1];
  288. writeIter[2] = frame[2];
  289. ++numChanged;
  290. writeIter += 4;
  291. }
  292. lastFrame += 4;
  293. frame += 4;
  294. }
  295. return numChanged;
  296. }
  297. // Creates a palette by placing all the image pixels in a k-d tree and then averaging the blocks at the bottom.
  298. // This is known as the "modified median split" technique
  299. void GifMakePalette( const uint8_t* lastFrame, const uint8_t* nextFrame, uint32_t width, uint32_t height, int bitDepth, bool buildForDither, GifPalette* pPal )
  300. {
  301. pPal->bitDepth = bitDepth;
  302. // SplitPalette is destructive (it sorts the pixels by color) so
  303. // we must create a copy of the image for it to destroy
  304. size_t imageSize = (size_t)(width * height * 4 * sizeof(uint8_t));
  305. uint8_t* destroyableImage = (uint8_t*)GIF_TEMP_MALLOC(imageSize);
  306. memcpy(destroyableImage, nextFrame, imageSize);
  307. int numPixels = (int)(width * height);
  308. if(lastFrame)
  309. numPixels = GifPickChangedPixels(lastFrame, destroyableImage, numPixels);
  310. const int lastElt = 1 << bitDepth;
  311. const int splitElt = lastElt/2;
  312. const int splitDist = splitElt/2;
  313. GifSplitPalette(destroyableImage, numPixels, 1, lastElt, splitElt, splitDist, 1, buildForDither, pPal);
  314. GIF_TEMP_FREE(destroyableImage);
  315. // add the bottom node for the transparency index
  316. pPal->treeSplit[1 << (bitDepth-1)] = 0;
  317. pPal->treeSplitElt[1 << (bitDepth-1)] = 0;
  318. pPal->r[0] = pPal->g[0] = pPal->b[0] = 0;
  319. }
  320. // Implements Floyd-Steinberg dithering, writes palette value to alpha
  321. void GifDitherImage( const uint8_t* lastFrame, const uint8_t* nextFrame, uint8_t* outFrame, uint32_t width, uint32_t height, GifPalette* pPal )
  322. {
  323. int numPixels = (int)(width * height);
  324. // quantPixels initially holds color*256 for all pixels
  325. // The extra 8 bits of precision allow for sub-single-color error values
  326. // to be propagated
  327. int32_t *quantPixels = (int32_t *)GIF_TEMP_MALLOC(sizeof(int32_t) * (size_t)numPixels * 4);
  328. for( int ii=0; ii<numPixels*4; ++ii )
  329. {
  330. uint8_t pix = nextFrame[ii];
  331. int32_t pix16 = int32_t(pix) * 256;
  332. quantPixels[ii] = pix16;
  333. }
  334. for( uint32_t yy=0; yy<height; ++yy )
  335. {
  336. for( uint32_t xx=0; xx<width; ++xx )
  337. {
  338. int32_t* nextPix = quantPixels + 4*(yy*width+xx);
  339. const uint8_t* lastPix = lastFrame? lastFrame + 4*(yy*width+xx) : NULL;
  340. // Compute the colors we want (rounding to nearest)
  341. int32_t rr = (nextPix[0] + 127) / 256;
  342. int32_t gg = (nextPix[1] + 127) / 256;
  343. int32_t bb = (nextPix[2] + 127) / 256;
  344. // if it happens that we want the color from last frame, then just write out
  345. // a transparent pixel
  346. if( lastFrame &&
  347. lastPix[0] == rr &&
  348. lastPix[1] == gg &&
  349. lastPix[2] == bb )
  350. {
  351. nextPix[0] = rr;
  352. nextPix[1] = gg;
  353. nextPix[2] = bb;
  354. nextPix[3] = kGifTransIndex;
  355. continue;
  356. }
  357. int32_t bestDiff = 1000000;
  358. int32_t bestInd = kGifTransIndex;
  359. // Search the palete
  360. GifGetClosestPaletteColor(pPal, rr, gg, bb, bestInd, bestDiff);
  361. // Write the result to the temp buffer
  362. int32_t r_err = nextPix[0] - int32_t(pPal->r[bestInd]) * 256;
  363. int32_t g_err = nextPix[1] - int32_t(pPal->g[bestInd]) * 256;
  364. int32_t b_err = nextPix[2] - int32_t(pPal->b[bestInd]) * 256;
  365. nextPix[0] = pPal->r[bestInd];
  366. nextPix[1] = pPal->g[bestInd];
  367. nextPix[2] = pPal->b[bestInd];
  368. nextPix[3] = bestInd;
  369. // Propagate the error to the four adjacent locations
  370. // that we haven't touched yet
  371. int quantloc_7 = (int)(yy * width + xx + 1);
  372. int quantloc_3 = (int)(yy * width + width + xx - 1);
  373. int quantloc_5 = (int)(yy * width + width + xx);
  374. int quantloc_1 = (int)(yy * width + width + xx + 1);
  375. if(quantloc_7 < numPixels)
  376. {
  377. int32_t* pix7 = quantPixels+4*quantloc_7;
  378. pix7[0] += GifIMax( -pix7[0], r_err * 7 / 16 );
  379. pix7[1] += GifIMax( -pix7[1], g_err * 7 / 16 );
  380. pix7[2] += GifIMax( -pix7[2], b_err * 7 / 16 );
  381. }
  382. if(quantloc_3 < numPixels)
  383. {
  384. int32_t* pix3 = quantPixels+4*quantloc_3;
  385. pix3[0] += GifIMax( -pix3[0], r_err * 3 / 16 );
  386. pix3[1] += GifIMax( -pix3[1], g_err * 3 / 16 );
  387. pix3[2] += GifIMax( -pix3[2], b_err * 3 / 16 );
  388. }
  389. if(quantloc_5 < numPixels)
  390. {
  391. int32_t* pix5 = quantPixels+4*quantloc_5;
  392. pix5[0] += GifIMax( -pix5[0], r_err * 5 / 16 );
  393. pix5[1] += GifIMax( -pix5[1], g_err * 5 / 16 );
  394. pix5[2] += GifIMax( -pix5[2], b_err * 5 / 16 );
  395. }
  396. if(quantloc_1 < numPixels)
  397. {
  398. int32_t* pix1 = quantPixels+4*quantloc_1;
  399. pix1[0] += GifIMax( -pix1[0], r_err / 16 );
  400. pix1[1] += GifIMax( -pix1[1], g_err / 16 );
  401. pix1[2] += GifIMax( -pix1[2], b_err / 16 );
  402. }
  403. }
  404. }
  405. // Copy the palettized result to the output buffer
  406. for( int ii=0; ii<numPixels*4; ++ii )
  407. {
  408. outFrame[ii] = (uint8_t)quantPixels[ii];
  409. }
  410. GIF_TEMP_FREE(quantPixels);
  411. }
  412. // Picks palette colors for the image using simple thresholding, no dithering
  413. void GifThresholdImage( const uint8_t* lastFrame, const uint8_t* nextFrame, uint8_t* outFrame, uint32_t width, uint32_t height, GifPalette* pPal )
  414. {
  415. uint32_t numPixels = width*height;
  416. for( uint32_t ii=0; ii<numPixels; ++ii )
  417. {
  418. // if a previous color is available, and it matches the current color,
  419. // set the pixel to transparent
  420. if(lastFrame &&
  421. lastFrame[0] == nextFrame[0] &&
  422. lastFrame[1] == nextFrame[1] &&
  423. lastFrame[2] == nextFrame[2])
  424. {
  425. outFrame[0] = lastFrame[0];
  426. outFrame[1] = lastFrame[1];
  427. outFrame[2] = lastFrame[2];
  428. outFrame[3] = kGifTransIndex;
  429. }
  430. else
  431. {
  432. // palettize the pixel
  433. int32_t bestDiff = 1000000;
  434. int32_t bestInd = 1;
  435. GifGetClosestPaletteColor(pPal, nextFrame[0], nextFrame[1], nextFrame[2], bestInd, bestDiff);
  436. // Write the resulting color to the output buffer
  437. outFrame[0] = pPal->r[bestInd];
  438. outFrame[1] = pPal->g[bestInd];
  439. outFrame[2] = pPal->b[bestInd];
  440. outFrame[3] = (uint8_t)bestInd;
  441. }
  442. if(lastFrame) lastFrame += 4;
  443. outFrame += 4;
  444. nextFrame += 4;
  445. }
  446. }
  447. // Simple structure to write out the LZW-compressed portion of the image
  448. // one bit at a time
  449. struct GifBitStatus
  450. {
  451. uint8_t bitIndex; // how many bits in the partial byte written so far
  452. uint8_t byte; // current partial byte
  453. uint32_t chunkIndex;
  454. uint8_t chunk[256]; // bytes are written in here until we have 256 of them, then written to the file
  455. };
  456. // insert a single bit
  457. void GifWriteBit( GifBitStatus& stat, uint32_t bit )
  458. {
  459. bit = bit & 1;
  460. bit = bit << stat.bitIndex;
  461. stat.byte |= bit;
  462. ++stat.bitIndex;
  463. if( stat.bitIndex > 7 )
  464. {
  465. // move the newly-finished byte to the chunk buffer
  466. stat.chunk[stat.chunkIndex++] = stat.byte;
  467. // and start a new byte
  468. stat.bitIndex = 0;
  469. stat.byte = 0;
  470. }
  471. }
  472. // write all bytes so far to the file
  473. void GifWriteChunk( FILE* f, GifBitStatus& stat )
  474. {
  475. fputc((int)stat.chunkIndex, f);
  476. fwrite(stat.chunk, 1, stat.chunkIndex, f);
  477. stat.bitIndex = 0;
  478. stat.byte = 0;
  479. stat.chunkIndex = 0;
  480. }
  481. void GifWriteCode( FILE* f, GifBitStatus& stat, uint32_t code, uint32_t length )
  482. {
  483. for( uint32_t ii=0; ii<length; ++ii )
  484. {
  485. GifWriteBit(stat, code);
  486. code = code >> 1;
  487. if( stat.chunkIndex == 255 )
  488. {
  489. GifWriteChunk(f, stat);
  490. }
  491. }
  492. }
  493. // The LZW dictionary is a 256-ary tree constructed as the file is encoded,
  494. // this is one node
  495. struct GifLzwNode
  496. {
  497. uint16_t m_next[256];
  498. };
  499. // write a 256-color (8-bit) image palette to the file
  500. void GifWritePalette( const GifPalette* pPal, FILE* f )
  501. {
  502. fputc(0, f); // first color: transparency
  503. fputc(0, f);
  504. fputc(0, f);
  505. for(int ii=1; ii<(1 << pPal->bitDepth); ++ii)
  506. {
  507. uint32_t r = pPal->r[ii];
  508. uint32_t g = pPal->g[ii];
  509. uint32_t b = pPal->b[ii];
  510. fputc((int)r, f);
  511. fputc((int)g, f);
  512. fputc((int)b, f);
  513. }
  514. }
  515. // write the image header, LZW-compress and write out the image
  516. void GifWriteLzwImage(FILE* f, uint8_t* image, uint32_t left, uint32_t top, uint32_t width, uint32_t height, uint32_t delay, GifPalette* pPal)
  517. {
  518. // graphics control extension
  519. fputc(0x21, f);
  520. fputc(0xf9, f);
  521. fputc(0x04, f);
  522. fputc(0x05, f); // leave prev frame in place, this frame has transparency
  523. fputc(delay & 0xff, f);
  524. fputc((delay >> 8) & 0xff, f);
  525. fputc(kGifTransIndex, f); // transparent color index
  526. fputc(0, f);
  527. fputc(0x2c, f); // image descriptor block
  528. fputc(left & 0xff, f); // corner of image in canvas space
  529. fputc((left >> 8) & 0xff, f);
  530. fputc(top & 0xff, f);
  531. fputc((top >> 8) & 0xff, f);
  532. fputc(width & 0xff, f); // width and height of image
  533. fputc((width >> 8) & 0xff, f);
  534. fputc(height & 0xff, f);
  535. fputc((height >> 8) & 0xff, f);
  536. //fputc(0, f); // no local color table, no transparency
  537. //fputc(0x80, f); // no local color table, but transparency
  538. fputc(0x80 + pPal->bitDepth-1, f); // local color table present, 2 ^ bitDepth entries
  539. GifWritePalette(pPal, f);
  540. const int minCodeSize = pPal->bitDepth;
  541. const uint32_t clearCode = 1 << pPal->bitDepth;
  542. fputc(minCodeSize, f); // min code size 8 bits
  543. GifLzwNode* codetree = (GifLzwNode*)GIF_TEMP_MALLOC(sizeof(GifLzwNode)*4096);
  544. memset(codetree, 0, sizeof(GifLzwNode)*4096);
  545. int32_t curCode = -1;
  546. uint32_t codeSize = (uint32_t)minCodeSize + 1;
  547. uint32_t maxCode = clearCode+1;
  548. GifBitStatus stat;
  549. stat.byte = 0;
  550. stat.bitIndex = 0;
  551. stat.chunkIndex = 0;
  552. GifWriteCode(f, stat, clearCode, codeSize); // start with a fresh LZW dictionary
  553. for(uint32_t yy=0; yy<height; ++yy)
  554. {
  555. for(uint32_t xx=0; xx<width; ++xx)
  556. {
  557. #ifdef GIF_FLIP_VERT
  558. // bottom-left origin image (such as an OpenGL capture)
  559. uint8_t nextValue = image[((height-1-yy)*width+xx)*4+3];
  560. #else
  561. // top-left origin
  562. uint8_t nextValue = image[(yy*width+xx)*4+3];
  563. #endif
  564. // "loser mode" - no compression, every single code is followed immediately by a clear
  565. //WriteCode( f, stat, nextValue, codeSize );
  566. //WriteCode( f, stat, 256, codeSize );
  567. if( curCode < 0 )
  568. {
  569. // first value in a new run
  570. curCode = nextValue;
  571. }
  572. else if( codetree[curCode].m_next[nextValue] )
  573. {
  574. // current run already in the dictionary
  575. curCode = codetree[curCode].m_next[nextValue];
  576. }
  577. else
  578. {
  579. // finish the current run, write a code
  580. GifWriteCode(f, stat, (uint32_t)curCode, codeSize);
  581. // insert the new run into the dictionary
  582. codetree[curCode].m_next[nextValue] = (uint16_t)++maxCode;
  583. if( maxCode >= (1ul << codeSize) )
  584. {
  585. // dictionary entry count has broken a size barrier,
  586. // we need more bits for codes
  587. codeSize++;
  588. }
  589. if( maxCode == 4095 )
  590. {
  591. // the dictionary is full, clear it out and begin anew
  592. GifWriteCode(f, stat, clearCode, codeSize); // clear tree
  593. memset(codetree, 0, sizeof(GifLzwNode)*4096);
  594. codeSize = (uint32_t)(minCodeSize + 1);
  595. maxCode = clearCode+1;
  596. }
  597. curCode = nextValue;
  598. }
  599. }
  600. }
  601. // compression footer
  602. GifWriteCode(f, stat, (uint32_t)curCode, codeSize);
  603. GifWriteCode(f, stat, clearCode, codeSize);
  604. GifWriteCode(f, stat, clearCode + 1, (uint32_t)minCodeSize + 1);
  605. // write out the last partial chunk
  606. while( stat.bitIndex ) GifWriteBit(stat, 0);
  607. if( stat.chunkIndex ) GifWriteChunk(f, stat);
  608. fputc(0, f); // image block terminator
  609. GIF_TEMP_FREE(codetree);
  610. }
  611. struct GifWriter
  612. {
  613. FILE* f;
  614. uint8_t* oldImage;
  615. bool firstFrame;
  616. };
  617. // Creates a gif file.
  618. // The input GIFWriter is assumed to be uninitialized.
  619. // The delay value is the time between frames in hundredths of a second - note that not all viewers pay much attention to this value.
  620. bool GifBegin( GifWriter* writer, const char* filename, uint32_t width, uint32_t height, uint32_t delay, int32_t bitDepth = 8, bool dither = false )
  621. {
  622. (void)bitDepth; (void)dither; // Mute "Unused argument" warnings
  623. #if defined(_MSC_VER) && (_MSC_VER >= 1400)
  624. writer->f = 0;
  625. fopen_s(&writer->f, filename, "wb");
  626. #else
  627. writer->f = fopen(filename, "wb");
  628. #endif
  629. if(!writer->f) return false;
  630. writer->firstFrame = true;
  631. // allocate
  632. writer->oldImage = (uint8_t*)GIF_MALLOC(width*height*4);
  633. fputs("GIF89a", writer->f);
  634. // screen descriptor
  635. fputc(width & 0xff, writer->f);
  636. fputc((width >> 8) & 0xff, writer->f);
  637. fputc(height & 0xff, writer->f);
  638. fputc((height >> 8) & 0xff, writer->f);
  639. fputc(0xf0, writer->f); // there is an unsorted global color table of 2 entries
  640. fputc(0, writer->f); // background color
  641. fputc(0, writer->f); // pixels are square (we need to specify this because it's 1989)
  642. // now the "global" palette (really just a dummy palette)
  643. // color 0: black
  644. fputc(0, writer->f);
  645. fputc(0, writer->f);
  646. fputc(0, writer->f);
  647. // color 1: also black
  648. fputc(0, writer->f);
  649. fputc(0, writer->f);
  650. fputc(0, writer->f);
  651. if( delay != 0 )
  652. {
  653. // animation header
  654. fputc(0x21, writer->f); // extension
  655. fputc(0xff, writer->f); // application specific
  656. fputc(11, writer->f); // length 11
  657. fputs("NETSCAPE2.0", writer->f); // yes, really
  658. fputc(3, writer->f); // 3 bytes of NETSCAPE2.0 data
  659. fputc(1, writer->f); // JUST BECAUSE
  660. fputc(0, writer->f); // loop infinitely (byte 0)
  661. fputc(0, writer->f); // loop infinitely (byte 1)
  662. fputc(0, writer->f); // block terminator
  663. }
  664. return true;
  665. }
  666. // Writes out a new frame to a GIF in progress.
  667. // The GIFWriter should have been created by GIFBegin.
  668. // AFAIK, it is legal to use different bit depths for different frames of an image -
  669. // this may be handy to save bits in animations that don't change much.
  670. bool GifWriteFrame( GifWriter* writer, const uint8_t* image, uint32_t width, uint32_t height, uint32_t delay, int bitDepth = 8, bool dither = false )
  671. {
  672. if(!writer->f) return false;
  673. const uint8_t* oldImage = writer->firstFrame? NULL : writer->oldImage;
  674. writer->firstFrame = false;
  675. GifPalette pal;
  676. GifMakePalette((dither? NULL : oldImage), image, width, height, bitDepth, dither, &pal);
  677. if(dither)
  678. GifDitherImage(oldImage, image, writer->oldImage, width, height, &pal);
  679. else
  680. GifThresholdImage(oldImage, image, writer->oldImage, width, height, &pal);
  681. GifWriteLzwImage(writer->f, writer->oldImage, 0, 0, width, height, delay, &pal);
  682. return true;
  683. }
  684. // Writes the EOF code, closes the file handle, and frees temp memory used by a GIF.
  685. // Many if not most viewers will still display a GIF properly if the EOF code is missing,
  686. // but it's still a good idea to write it out.
  687. bool GifEnd( GifWriter* writer )
  688. {
  689. if(!writer->f) return false;
  690. fputc(0x3b, writer->f); // end of file
  691. fclose(writer->f);
  692. GIF_FREE(writer->oldImage);
  693. writer->f = NULL;
  694. writer->oldImage = NULL;
  695. return true;
  696. }
  697. #endif