gif.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. /* gif.c - Handles output to gif file */
  2. /*
  3. libzint - the open source barcode library
  4. Copyright (C) 2009-2024 Robin Stuart <rstuart114@gmail.com>
  5. Redistribution and use in source and binary forms, with or without
  6. modification, are permitted provided that the following conditions
  7. are met:
  8. 1. Redistributions of source code must retain the above copyright
  9. notice, this list of conditions and the following disclaimer.
  10. 2. Redistributions in binary form must reproduce the above copyright
  11. notice, this list of conditions and the following disclaimer in the
  12. documentation and/or other materials provided with the distribution.
  13. 3. Neither the name of the project nor the names of its contributors
  14. may be used to endorse or promote products derived from this software
  15. without specific prior written permission.
  16. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  17. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  18. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  19. ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
  20. FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  21. DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  22. OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  23. HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  24. LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  25. OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  26. SUCH DAMAGE.
  27. */
  28. /* SPDX-License-Identifier: BSD-3-Clause */
  29. #include <errno.h>
  30. #include <stdio.h>
  31. #include "common.h"
  32. #include "filemem.h"
  33. #include "output.h"
  34. /* Set LZW buffer paging size to this in expectation that compressed data will fit for typical scalings */
  35. #define GIF_LZW_PAGE_SIZE 0x100000 /* Megabyte */
  36. struct gif_state {
  37. struct filemem *fmp;
  38. unsigned char *pOut;
  39. const unsigned char *pIn;
  40. const unsigned char *pInEnd;
  41. size_t OutLength;
  42. size_t OutPosCur;
  43. size_t OutByteCountPos;
  44. unsigned short ClearCode;
  45. unsigned short FreeCode;
  46. char fByteCountByteSet;
  47. char fOutPaged;
  48. unsigned char OutBitsFree;
  49. unsigned short NodeAxon[4096];
  50. unsigned short NodeNext[4096];
  51. unsigned char NodePix[4096];
  52. unsigned char map[256];
  53. };
  54. static void gif_BufferNextByte(struct gif_state *pState) {
  55. (pState->OutPosCur)++;
  56. if (pState->fOutPaged && pState->OutPosCur + 2 >= pState->OutLength) {
  57. /* Keep last 256 bytes so `OutByteCountPos` within range */
  58. fm_write(pState->pOut, 1, pState->OutPosCur - 256, pState->fmp);
  59. memmove(pState->pOut, pState->pOut + pState->OutPosCur - 256, 256);
  60. pState->OutByteCountPos -= pState->OutPosCur - 256;
  61. pState->OutPosCur = 256;
  62. }
  63. /* Check if this position is a byte count position
  64. * `fByteCountByteSet` indicates, if byte count position bytes should be
  65. * inserted in general.
  66. * If this is true, and the distance to the last byte count position is 256
  67. * (e.g. 255 bytes in between), a byte count byte is inserted, and the value
  68. * of the last one is set to 255.
  69. * */
  70. if (pState->fByteCountByteSet && (pState->OutByteCountPos + 256 == pState->OutPosCur)) {
  71. (pState->pOut)[pState->OutByteCountPos] = 255;
  72. pState->OutByteCountPos = pState->OutPosCur;
  73. (pState->OutPosCur)++;
  74. }
  75. (pState->pOut)[pState->OutPosCur] = 0x00;
  76. }
  77. static void gif_AddCodeToBuffer(struct gif_state *pState, unsigned short CodeIn, unsigned char CodeBits) {
  78. /* Check, if we may fill up the current byte completely */
  79. if (CodeBits >= pState->OutBitsFree) {
  80. (pState->pOut)[pState->OutPosCur] |= (unsigned char) (CodeIn << (8 - pState->OutBitsFree));
  81. gif_BufferNextByte(pState);
  82. CodeIn = (unsigned short) (CodeIn >> pState->OutBitsFree);
  83. CodeBits -= pState->OutBitsFree;
  84. pState->OutBitsFree = 8;
  85. /* Write a full byte if there are at least 8 code bits left */
  86. if (CodeBits >= pState->OutBitsFree) {
  87. (pState->pOut)[pState->OutPosCur] = (unsigned char) CodeIn;
  88. gif_BufferNextByte(pState);
  89. CodeIn = (unsigned short) (CodeIn >> 8);
  90. CodeBits -= 8;
  91. }
  92. }
  93. /* The remaining bits of CodeIn fit in the current byte. */
  94. if (CodeBits > 0) {
  95. (pState->pOut)[pState->OutPosCur] |= (unsigned char) (CodeIn << (8 - pState->OutBitsFree));
  96. pState->OutBitsFree -= CodeBits;
  97. }
  98. }
  99. static void gif_FlushStringTable(struct gif_state *pState) {
  100. unsigned short Pos;
  101. for (Pos = 0; Pos < pState->ClearCode; Pos++) {
  102. (pState->NodeAxon)[Pos] = 0;
  103. }
  104. }
  105. static unsigned short gif_FindPixelOutlet(struct gif_state *pState, unsigned short HeadNode, unsigned char Byte) {
  106. unsigned short Outlet;
  107. Outlet = (pState->NodeAxon)[HeadNode];
  108. while (Outlet) {
  109. if ((pState->NodePix)[Outlet] == Byte)
  110. return Outlet;
  111. Outlet = (pState->NodeNext)[Outlet];
  112. }
  113. return 0;
  114. }
  115. static int gif_NextCode(struct gif_state *pState, unsigned char *pPixelValueCur, unsigned char CodeBits) {
  116. unsigned short UpNode;
  117. unsigned short DownNode;
  118. /* start with the root node for last pixel chain */
  119. UpNode = *pPixelValueCur;
  120. if (pState->pIn == pState->pInEnd) {
  121. gif_AddCodeToBuffer(pState, UpNode, CodeBits);
  122. return 0;
  123. }
  124. *pPixelValueCur = pState->map[*pState->pIn++];
  125. /* Follow the string table and the data stream to the end of the longest string that has a code */
  126. while (0 != (DownNode = gif_FindPixelOutlet(pState, UpNode, *pPixelValueCur))) {
  127. UpNode = DownNode;
  128. if (pState->pIn == pState->pInEnd) {
  129. gif_AddCodeToBuffer(pState, UpNode, CodeBits);
  130. return 0;
  131. }
  132. *pPixelValueCur = pState->map[*pState->pIn++];
  133. }
  134. /* Submit 'UpNode' which is the code of the longest string */
  135. gif_AddCodeToBuffer(pState, UpNode, CodeBits);
  136. /* ... and extend the string by appending 'PixelValueCur' */
  137. /* Create a successor node for 'PixelValueCur' whose code is 'freecode' */
  138. (pState->NodePix)[pState->FreeCode] = *pPixelValueCur;
  139. (pState->NodeAxon)[pState->FreeCode] = (pState->NodeNext)[pState->FreeCode] = 0;
  140. /* ...and link it to the end of the chain emanating from fg_axon[UpNode]. */
  141. DownNode = (pState->NodeAxon)[UpNode];
  142. if (!DownNode) {
  143. (pState->NodeAxon)[UpNode] = pState->FreeCode;
  144. } else {
  145. while ((pState->NodeNext)[DownNode]) {
  146. DownNode = (pState->NodeNext)[DownNode];
  147. }
  148. (pState->NodeNext)[DownNode] = pState->FreeCode;
  149. }
  150. return 1;
  151. }
  152. static int gif_lzw(struct gif_state *pState, int paletteBitSize) {
  153. unsigned char PixelValueCur;
  154. unsigned char CodeBits;
  155. unsigned short Pos;
  156. /* > Get first data byte */
  157. if (pState->pIn == pState->pInEnd)
  158. return 0;
  159. PixelValueCur = pState->map[*pState->pIn++];
  160. /* Number of bits per data item (=pixel)
  161. * We need at least a value of 2, otherwise the cc and eoi code consumes
  162. * the whole string table
  163. */
  164. if (paletteBitSize == 1)
  165. paletteBitSize = 2;
  166. /* initial size of compression codes */
  167. CodeBits = paletteBitSize + 1;
  168. pState->ClearCode = (1 << paletteBitSize);
  169. pState->FreeCode = pState->ClearCode + 2;
  170. pState->OutBitsFree = 8;
  171. pState->OutPosCur = 0;
  172. pState->fByteCountByteSet = 0;
  173. for (Pos = 0; Pos < pState->ClearCode; Pos++)
  174. (pState->NodePix)[Pos] = (unsigned char) Pos;
  175. gif_FlushStringTable(pState);
  176. /* Write what the GIF specification calls the "code size". */
  177. (pState->pOut)[pState->OutPosCur] = paletteBitSize;
  178. /* Reserve first bytecount byte */
  179. gif_BufferNextByte(pState);
  180. pState->OutByteCountPos = pState->OutPosCur;
  181. gif_BufferNextByte(pState);
  182. pState->fByteCountByteSet = 1;
  183. /* Submit one 'ClearCode' as the first code */
  184. gif_AddCodeToBuffer(pState, pState->ClearCode, CodeBits);
  185. for (;;) {
  186. /* generate and save the next code, which may consist of multiple input pixels. */
  187. if (!gif_NextCode(pState, &PixelValueCur, CodeBits)) { /* Check for end of data stream */
  188. /* submit 'eoi' as the last item of the code stream */
  189. gif_AddCodeToBuffer(pState, (unsigned short) (pState->ClearCode + 1), CodeBits);
  190. pState->fByteCountByteSet = 0;
  191. if (pState->OutBitsFree < 8) {
  192. gif_BufferNextByte(pState);
  193. }
  194. /* > Update last bytecount byte; */
  195. if (pState->OutByteCountPos < pState->OutPosCur) {
  196. (pState->pOut)[pState->OutByteCountPos]
  197. = (unsigned char) (pState->OutPosCur - pState->OutByteCountPos - 1);
  198. }
  199. pState->OutPosCur++;
  200. return 1;
  201. }
  202. /* Check for currently last code */
  203. if (pState->FreeCode == (1U << CodeBits))
  204. CodeBits++;
  205. pState->FreeCode++;
  206. /* Check for full stringtable - for widest compatibility with gif decoders, empty when 0xfff, not 0x1000 */
  207. if (pState->FreeCode == 0xfff) {
  208. gif_FlushStringTable(pState);
  209. gif_AddCodeToBuffer(pState, pState->ClearCode, CodeBits);
  210. CodeBits = (unsigned char) (1 + paletteBitSize);
  211. pState->FreeCode = (unsigned short) (pState->ClearCode + 2);
  212. }
  213. }
  214. }
  215. /*
  216. * Called function to save in gif format
  217. */
  218. INTERNAL int gif_pixel_plot(struct zint_symbol *symbol, unsigned char *pixelbuf) {
  219. struct filemem fm;
  220. unsigned char outbuf[10];
  221. unsigned char paletteRGB[10][3];
  222. int paletteCount, i;
  223. int paletteBitSize;
  224. int paletteSize;
  225. struct gif_state State;
  226. int transparent_index;
  227. int bgindex = -1, fgindex = -1;
  228. static const unsigned char RGBUnused[3] = {0,0,0};
  229. unsigned char RGBfg[3];
  230. unsigned char RGBbg[3];
  231. unsigned char fgalpha;
  232. unsigned char bgalpha;
  233. const size_t bitmapSize = (size_t) symbol->bitmap_height * symbol->bitmap_width;
  234. (void) out_colour_get_rgb(symbol->fgcolour, &RGBfg[0], &RGBfg[1], &RGBfg[2], &fgalpha);
  235. (void) out_colour_get_rgb(symbol->bgcolour, &RGBbg[0], &RGBbg[1], &RGBbg[2], &bgalpha);
  236. /* prepare state array */
  237. State.pIn = pixelbuf;
  238. State.pInEnd = pixelbuf + bitmapSize;
  239. /* Allow for overhead of 4 == code size + byte count + overflow byte + zero terminator */
  240. State.OutLength = bitmapSize + 4;
  241. State.fOutPaged = State.OutLength > GIF_LZW_PAGE_SIZE;
  242. if (State.fOutPaged) {
  243. State.OutLength = GIF_LZW_PAGE_SIZE;
  244. }
  245. if (!(State.pOut = (unsigned char *) malloc(State.OutLength))) {
  246. return errtxt(ZINT_ERROR_MEMORY, symbol, 614, "Insufficient memory for GIF LZW buffer");
  247. }
  248. State.fmp = &fm;
  249. /* Open output file in binary mode */
  250. if (!fm_open(State.fmp, symbol, "wb")) {
  251. errtxtf(0, symbol, 611, "Could not open GIF output file (%1$d: %2$s)", State.fmp->err,
  252. strerror(State.fmp->err));
  253. free(State.pOut);
  254. return ZINT_ERROR_FILE_ACCESS;
  255. }
  256. /*
  257. * Build a table of the used palette items.
  258. * Currently, there are the following 10 colour codes:
  259. * '0': standard background
  260. * '1': standard foreground
  261. * 'W': white
  262. * 'C': cyan
  263. * 'B': blue
  264. * 'M': magenta
  265. * 'R': red
  266. * 'Y': yellow
  267. * 'G': green
  268. * 'K': black
  269. * '0' and '1' may be identical to one of the other values
  270. */
  271. memset(State.map, 0, sizeof(State.map));
  272. if (symbol->symbology == BARCODE_ULTRA) {
  273. static const unsigned char ultra_chars[8] = { 'W', 'C', 'B', 'M', 'R', 'Y', 'G', 'K' };
  274. for (i = 0; i < 8; i++) {
  275. State.map[ultra_chars[i]] = i;
  276. out_colour_char_to_rgb(ultra_chars[i], &paletteRGB[i][0], &paletteRGB[i][1], &paletteRGB[i][2]);
  277. }
  278. paletteCount = 8;
  279. paletteBitSize = 3;
  280. /* For Ultracode, have foreground only if have bind/box */
  281. if (symbol->border_width > 0 && (symbol->output_options & (BARCODE_BIND | BARCODE_BOX | BARCODE_BIND_TOP))) {
  282. /* Check whether can re-use black */
  283. if (RGBfg[0] == 0 && RGBfg[1] == 0 && RGBfg[2] == 0) {
  284. State.map['1'] = fgindex = 7; /* Re-use black */
  285. } else {
  286. State.map['1'] = fgindex = paletteCount;
  287. memcpy(paletteRGB[paletteCount++], RGBfg, 3);
  288. paletteBitSize = 4;
  289. }
  290. }
  291. /* For Ultracode, have background only if have whitespace/quiet zones */
  292. if (symbol->whitespace_width > 0 || symbol->whitespace_height > 0
  293. || ((symbol->output_options & BARCODE_QUIET_ZONES)
  294. && !(symbol->output_options & BARCODE_NO_QUIET_ZONES))) {
  295. /* Check whether can re-use white */
  296. if (RGBbg[0] == 0xff && RGBbg[1] == 0xff && RGBbg[2] == 0xff && bgalpha == fgalpha) {
  297. State.map['0'] = bgindex = 0; /* Re-use white */
  298. } else {
  299. State.map['0'] = bgindex = paletteCount;
  300. memcpy(paletteRGB[paletteCount++], RGBbg, 3);
  301. paletteBitSize = 4;
  302. }
  303. }
  304. } else {
  305. State.map['0'] = bgindex = 0;
  306. memcpy(paletteRGB[bgindex], RGBbg, 3);
  307. State.map['1'] = fgindex = 1;
  308. memcpy(paletteRGB[fgindex], RGBfg, 3);
  309. paletteCount = 2;
  310. paletteBitSize = 1;
  311. }
  312. /* Set transparency */
  313. /* Note: does not allow both transparent foreground and background -
  314. * background takes priority */
  315. transparent_index = -1;
  316. if (bgalpha == 0 && bgindex != -1) {
  317. /* Transparent background */
  318. transparent_index = bgindex;
  319. } else if (fgalpha == 0 && fgindex != -1) {
  320. /* Transparent foreground */
  321. transparent_index = fgindex;
  322. }
  323. /* palette size 2 ^ bit size */
  324. paletteSize = 1 << paletteBitSize;
  325. /* GIF signature (6) */
  326. fm_write(transparent_index == -1 ? "GIF87a" : "GIF89a", 1, 6, State.fmp);
  327. /* Screen Descriptor (7) */
  328. /* Screen Width */
  329. outbuf[0] = (unsigned char) (0xff & symbol->bitmap_width);
  330. outbuf[1] = (unsigned char) (0xff & (symbol->bitmap_width >> 8));
  331. /* Screen Height */
  332. outbuf[2] = (unsigned char) (0xff & symbol->bitmap_height);
  333. outbuf[3] = (unsigned char) (0xff & (symbol->bitmap_height >> 8));
  334. /* write ImageBits-1 to the three least significant bits of byte 5 of
  335. * the Screen Descriptor
  336. * Bits 76543210
  337. * 1 : Global colour map
  338. * 111 : 8 bit colour depth of the palette
  339. * 0 : Not ordered in decreasing importance
  340. * xxx : palette bit size - 1
  341. */
  342. outbuf[4] = (unsigned char) (0xf0 | (0x7 & (paletteBitSize - 1)));
  343. /*
  344. * Background colour index
  345. * Default to 0. If colour code 0 or K is present, it is used as index
  346. */
  347. outbuf[5] = bgindex == -1 ? 0 : bgindex;
  348. /* Byte 7 must be 0x00 */
  349. outbuf[6] = 0x00;
  350. fm_write(outbuf, 1, 7, State.fmp);
  351. /* Global Color Table (paletteSize*3) */
  352. fm_write(paletteRGB, 1, 3*paletteCount, State.fmp);
  353. /* add unused palette items to fill palette size */
  354. for (i = paletteCount; i < paletteSize; i++) {
  355. fm_write(RGBUnused, 1, 3, State.fmp);
  356. }
  357. /* Graphic control extension (8) */
  358. /* A graphic control extension block is used for overlay gifs.
  359. * This is necessary to define a transparent color.
  360. */
  361. if (transparent_index != -1) {
  362. /* Extension Introducer = '!' */
  363. outbuf[0] = '!';
  364. /* Graphic Control Label */
  365. outbuf[1] = 0xf9;
  366. /* Block Size */
  367. outbuf[2] = 4;
  368. /* Packet fields:
  369. * 3 Reserved
  370. * 3 Disposal Method: 0 No Action, 1 No Dispose, 2: Background, 3: Prev.
  371. * 1 User Input Flag: 0: no user input, 1: user input
  372. * 1 Transparent Color Flag: 0: No Transparency, 1: Transparency index
  373. */
  374. outbuf[3] = 1;
  375. /* Delay Time */
  376. outbuf[4] = 0;
  377. outbuf[5] = 0;
  378. /* Transparent Color Index */
  379. outbuf[6] = (unsigned char) transparent_index;
  380. /* Block Terminator */
  381. outbuf[7] = 0;
  382. fm_write(outbuf, 1, 8, State.fmp);
  383. }
  384. /* Image Descriptor */
  385. /* Image separator character = ',' */
  386. outbuf[0] = ',';
  387. /* "Image Left" */
  388. outbuf[1] = 0x00;
  389. outbuf[2] = 0x00;
  390. /* "Image Top" */
  391. outbuf[3] = 0x00;
  392. outbuf[4] = 0x00;
  393. /* Image Width (low byte first) */
  394. outbuf[5] = (unsigned char) (0xff & symbol->bitmap_width);
  395. outbuf[6] = (unsigned char) (0xff & (symbol->bitmap_width >> 8));
  396. /* Image Height */
  397. outbuf[7] = (unsigned char) (0xff & symbol->bitmap_height);
  398. outbuf[8] = (unsigned char) (0xff & (symbol->bitmap_height >> 8));
  399. /* Byte 10 contains the interlaced flag and
  400. * information on the local color table.
  401. * There is no local color table if its most significant bit is reset.
  402. */
  403. outbuf[9] = 0x00;
  404. fm_write(outbuf, 1, 10, State.fmp);
  405. /* call lzw encoding */
  406. if (!gif_lzw(&State, paletteBitSize)) {
  407. free(State.pOut);
  408. (void) fm_close(State.fmp, symbol);
  409. return errtxt(ZINT_ERROR_MEMORY, symbol, 613, "Insufficient memory for GIF LZW buffer");
  410. }
  411. fm_write(State.pOut, 1, State.OutPosCur, State.fmp);
  412. free(State.pOut);
  413. /* GIF terminator */
  414. fm_putc(';', State.fmp);
  415. if (fm_error(State.fmp)) {
  416. errtxtf(0, symbol, 615, "Incomplete write of GIF output (%1$d: %2$s)", State.fmp->err,
  417. strerror(State.fmp->err));
  418. (void) fm_close(State.fmp, symbol);
  419. return ZINT_ERROR_FILE_WRITE;
  420. }
  421. if (!fm_close(State.fmp, symbol)) {
  422. return errtxtf(ZINT_ERROR_FILE_WRITE, symbol, 617, "Failure on closing GIF output file (%1$d: %2$s)",
  423. State.fmp->err, strerror(State.fmp->err));
  424. }
  425. return 0;
  426. }
  427. /* vim: set ts=4 sw=4 et : */