GIFDECOD.C 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. /****************************************************************************
  2. * gifdecod.c
  3. *
  4. * GIF-style LZW decoder.
  5. *
  6. * NOTE: Portions of this module were written by Steve Bennett and are used
  7. * here with his permission.
  8. *
  9. * from Persistence of Vision(tm) Ray Tracer
  10. * Copyright 1996,1999 Persistence of Vision Team
  11. *---------------------------------------------------------------------------
  12. * NOTICE: This source code file is provided so that users may experiment
  13. * with enhancements to POV-Ray and to port the software to platforms other
  14. * than those supported by the POV-Ray Team. There are strict rules under
  15. * which you are permitted to use this file. The rules are in the file
  16. * named POVLEGAL.DOC which should be distributed with this file.
  17. * If POVLEGAL.DOC is not available or for more info please contact the POV-Ray
  18. * Team Coordinator by email to team-coord@povray.org or visit us on the web at
  19. * http://www.povray.org. The latest version of POV-Ray may be found at this site.
  20. *
  21. * This program is based on the popular DKB raytracer version 2.12.
  22. * DKBTrace was originally written by David K. Buck.
  23. * DKBTrace Ver 2.0-2.12 were written by David K. Buck & Aaron A. Collins.
  24. *
  25. *****************************************************************************/
  26. /*
  27. This module was freely borrowed from FRACTINT, so here is their entire
  28. copyright to keep them happy:
  29. */
  30. /* DECODER.C - An LZW decoder for GIF
  31. * Copyright (C) 1987, by Steven A. Bennett
  32. *
  33. * Permission is given by the author to freely redistribute and include
  34. * this code in any program as long as this credit is given where due.
  35. *
  36. * In accordance with the above, I want to credit Steve Wilhite who wrote
  37. * the code which this is heavily inspired by...
  38. *
  39. * GIF and 'Graphics Interchange Format' are trademarks (tm) of
  40. * Compuserve, Incorporated, an H&R Block Company.
  41. *
  42. * Release Notes: This file contains a decoder routine for GIF images
  43. * which is similar, structurally, to the original routine by Steve Wilhite.
  44. * It is, however, somewhat noticably faster in most cases.
  45. *
  46. == This routine was modified for use in FRACTINT in two ways.
  47. ==
  48. == 1) The original #includes were folded into the routine strictly to hold
  49. == down the number of files we were dealing with.
  50. ==
  51. == 2) The 'stack', 'suffix', 'prefix', and 'buf' arrays were changed from
  52. == static and 'malloc()'ed to external only so that the assembler
  53. == program could use the same array space for several independent
  54. == chunks of code. Also, 'stack' was renamed to 'dstack' for TASM
  55. == compatibility.
  56. ==
  57. == 3) The 'out_line()' external function has been changed to reference
  58. == '*outln()' for flexibility (in particular, 3D transformations)
  59. ==
  60. == 4) A call to 'keypressed()' has been added after the 'outln()' calls
  61. == to check for the presenc of a key-press as a bail-out signal
  62. ==
  63. == (Bert Tyler and Timothy Wegner)
  64. */
  65. /*
  66. This routine was modified for Persistence of Vision(tm) Ray Tracer in the following ways:
  67. 1) Removed calls to buzzer() and keypressed() to get rid of ASM files.
  68. 2) The dstack, suffix, and prefix arrays were made STATIC once again.
  69. 3) Added the usual ANSI function prototypes, etc. in the Persistence of Vision(tm) Ray Tracer headers.
  70. */
  71. #include "frame.h"
  72. #include "povproto.h"
  73. #include "gif.h"
  74. #include "gifdecod.h"
  75. #define LOCAL static
  76. #define IMPORT extern
  77. #define FAST register
  78. /* typedef short WORD; */
  79. typedef unsigned short UWORD;
  80. typedef unsigned char UTINY;
  81. typedef long LONG;
  82. typedef unsigned long ULONG;
  83. typedef int INT;
  84. /* Various error codes used by decoder
  85. * and my own routines... It's okay
  86. * for you to define whatever you want,
  87. * as long as it's negative... It will be
  88. * returned intact up the various subroutine
  89. * levels...
  90. */
  91. #define OUT_OF_MEMORY -10
  92. #define BAD_CODE_SIZE -20
  93. #define READ_ERROR -1
  94. #define WRITE_ERROR -2
  95. #define OPEN_ERROR -3
  96. #define CREATE_ERROR -4
  97. /* IMPORT INT gif_get_byte()
  98. *
  99. * - This external (machine specific) function is expected to return
  100. * either the next byte from the GIF file, or a negative number, as
  101. * defined in ERRS.H.
  102. */
  103. /*
  104. IMPORT INT gif_get_byte();
  105. */
  106. /* IMPORT INT out_line(pixels, linelen)
  107. * UBYTE pixels[];
  108. * INT linelen;
  109. *
  110. * - This function takes a full line of pixels (one byte per pixel) and
  111. * displays them (or does whatever your program wants with them...). It
  112. * should return zero, or negative if an error or some other event occurs
  113. * which would require aborting the decode process... Note that the length
  114. * passed will almost always be equal to the line length passed to the
  115. * decoder function, with the sole exception occurring when an ending code
  116. * occurs in an odd place in the GIF file... In any case, linelen will be
  117. * equal to the number of pixels passed...
  118. */
  119. /*
  120. IMPORT INT out_line();
  121. */
  122. /* IMPORT INT bad_code_count;
  123. *
  124. * This value is the only other global required by the using program, and
  125. * is incremented each time an out of range code is read by the decoder.
  126. * When this value is non-zero after a decode, your GIF file is probably
  127. * corrupt in some way...
  128. */
  129. static INT bad_code_count;
  130. #define MAX_CODES 4095
  131. /* Static variables */
  132. LOCAL WORD curr_size; /* The current code size */
  133. LOCAL WORD clear_code; /* Value for a clear code */
  134. LOCAL WORD ending; /* Value for a ending code */
  135. LOCAL WORD newcodes; /* First available code */
  136. LOCAL WORD top_slot; /* Highest code for current size */
  137. LOCAL WORD slot; /* Last read code */
  138. /* The following static variables are used
  139. * for seperating out codes
  140. */
  141. LOCAL WORD navail_bytes = 0; /* # bytes left in block */
  142. LOCAL WORD nbits_left = 0; /* # bits left in current byte */
  143. LOCAL UTINY b1; /* Current byte */
  144. LOCAL UTINY byte_buff[257]; /* Current block */
  145. LOCAL UTINY *pbytes; /* Pointer to next byte in block */
  146. LOCAL LONG code_mask[13] = {
  147. 0,
  148. 0x0001, 0x0003,
  149. 0x0007, 0x000F,
  150. 0x001F, 0x003F,
  151. 0x007F, 0x00FF,
  152. 0x01FF, 0x03FF,
  153. 0x07FF, 0x0FFF
  154. };
  155. static void cleanup_gif_decoder (void);
  156. /* changed param to int to avoid problems with 32bit int ANSI compilers. */
  157. static WORD init_exp (int i_size);
  158. static WORD get_next_code (void);
  159. /* This function initializes the decoder for reading a new image.
  160. */
  161. static WORD init_exp (int i_size)
  162. {
  163. WORD size;
  164. size = (WORD)i_size;
  165. curr_size = size + 1;
  166. top_slot = 1 << curr_size;
  167. clear_code = 1 << size;
  168. ending = clear_code + 1;
  169. slot = newcodes = ending + 1;
  170. navail_bytes = nbits_left = 0;
  171. return(0);
  172. }
  173. /* get_next_code()
  174. * - gets the next code from the GIF file. Returns the code, or else
  175. * a negative number in case of file errors...
  176. */
  177. static WORD get_next_code()
  178. {
  179. WORD i, x;
  180. ULONG ret;
  181. if (nbits_left == 0)
  182. {
  183. if (navail_bytes <= 0)
  184. {
  185. /* Out of bytes in current block, so read next block
  186. */
  187. pbytes = byte_buff;
  188. if ((navail_bytes = gif_get_byte()) < 0)
  189. return(navail_bytes);
  190. else if (navail_bytes)
  191. {
  192. for (i = 0; i < navail_bytes; ++i)
  193. {
  194. if ((x = gif_get_byte()) < 0)
  195. return(x);
  196. byte_buff[i] = (UTINY) x;
  197. }
  198. }
  199. }
  200. b1 = *pbytes++;
  201. nbits_left = 8;
  202. --navail_bytes;
  203. }
  204. ret = b1 >> (8 - nbits_left);
  205. while (curr_size > nbits_left)
  206. {
  207. if (navail_bytes <= 0)
  208. {
  209. /* Out of bytes in current block, so read next block
  210. */
  211. pbytes = byte_buff;
  212. if ((navail_bytes = gif_get_byte()) < 0)
  213. return(navail_bytes);
  214. else if (navail_bytes)
  215. {
  216. for (i = 0; i < navail_bytes; ++i)
  217. {
  218. if ((x = gif_get_byte()) < 0)
  219. return(x);
  220. byte_buff[i] = (UTINY) x;
  221. }
  222. }
  223. }
  224. b1 = *pbytes++;
  225. ret |= b1 << nbits_left;
  226. nbits_left += 8;
  227. --navail_bytes;
  228. }
  229. nbits_left -= curr_size;
  230. ret &= code_mask[curr_size];
  231. return((WORD)(ret));
  232. }
  233. /* The reason we have these seperated like this instead of using
  234. * a structure like the original Wilhite code did, is because this
  235. * stuff generally produces significantly faster code when compiled...
  236. * This code is full of similar speedups... (For a good book on writing
  237. * C for speed or for space optomisation, see Efficient C by Tom Plum,
  238. * published by Plum-Hall Associates...)
  239. */
  240. /*
  241. I removed the LOCAL identifiers in the arrays below and replaced them
  242. with 'extern's so as to declare (and re-use) the space elsewhere.
  243. The arrays are actually declared in the assembler source.
  244. Bert Tyler
  245. */
  246. LOCAL UTINY *dstack; /* Stack for storing pixels */
  247. LOCAL UTINY *suffix; /* Suffix table */
  248. LOCAL UWORD *prefix; /* Prefix linked list */
  249. extern UTINY *decoderline; /* decoded line goes here */
  250. /* WORD decoder(linewidth)
  251. * WORD linewidth; * Pixels per line of image *
  252. *
  253. * - This function decodes an LZW image, according to the method used
  254. * in the GIF spec. Every *linewidth* "characters" (ie. pixels) decoded
  255. * will generate a call to out_line(), which is a user specific function
  256. * to display a line of pixels. The function gets its codes from
  257. * get_next_code() which is responsible for reading blocks of data and
  258. * seperating them into the proper size codes. Finally, gif_get_byte() is
  259. * the global routine to read the next byte from the GIF file.
  260. *
  261. * It is generally a good idea to have linewidth correspond to the actual
  262. * width of a line (as specified in the Image header) to make your own
  263. * code a bit simpler, but it isn't absolutely necessary.
  264. *
  265. * Returns: 0 if successful, else negative. (See ERRS.H)
  266. *
  267. */
  268. static void cleanup_gif_decoder ()
  269. {
  270. POV_FREE (dstack);
  271. POV_FREE (suffix);
  272. POV_FREE (prefix);
  273. dstack = NULL;
  274. suffix = NULL;
  275. prefix = NULL;
  276. }
  277. WORD decoder (int i_linewidth)
  278. {
  279. WORD linewidth;
  280. FAST UTINY *sp, *bufptr;
  281. UTINY *buf;
  282. FAST WORD code, fc, oc, bufcnt;
  283. WORD c, size, ret;
  284. linewidth = (WORD)i_linewidth;
  285. /* Initialize for decoding a new image...
  286. */
  287. if ((size = gif_get_byte()) < 0)
  288. return(size);
  289. if (size < 2 || 9 < size)
  290. return(BAD_CODE_SIZE);
  291. init_exp((int)size); /* changed param to int */
  292. dstack = (UTINY *)POV_MALLOC((MAX_CODES + 1)*sizeof(UTINY), "GIF dstack");
  293. suffix = (UTINY *)POV_MALLOC((MAX_CODES + 1)*sizeof(UTINY), "GIF suffix");
  294. prefix = (UWORD *)POV_MALLOC((MAX_CODES + 1)*sizeof(UWORD), "GIF prefix");
  295. /* Initialize in case they forgot to put in a clear code.
  296. * (This shouldn't happen, but we'll try and decode it anyway...)
  297. */
  298. oc = fc = 0;
  299. buf = decoderline;
  300. bad_code_count = 0;
  301. /* Set up the stack pointer and decode buffer pointer
  302. */
  303. sp = dstack;
  304. bufptr = buf;
  305. bufcnt = linewidth;
  306. /* This is the main loop. For each code we get we pass through the
  307. * linked list of prefix codes, pushing the corresponding "character" for
  308. * each code onto the stack. When the list reaches a single "character"
  309. * we push that on the stack too, and then start unstacking each
  310. * character for output in the correct order. Special handling is
  311. * included for the clear code, and the whole thing ends when we get
  312. * an ending code.
  313. */
  314. while ((c = get_next_code()) != ending)
  315. {
  316. COOPERATE_0
  317. /* If we had a file error, return without completing the decode
  318. */
  319. if (c < 0)
  320. {
  321. cleanup_gif_decoder();
  322. return(0);
  323. }
  324. /* If the code is a clear code, reinitialize all necessary items.
  325. */
  326. if (c == clear_code)
  327. {
  328. curr_size = size + 1;
  329. slot = newcodes;
  330. top_slot = 1 << curr_size;
  331. /* Continue reading codes until we get a non-clear code
  332. * (Another unlikely, but possible case...)
  333. */
  334. while ((c = get_next_code()) == clear_code)
  335. ;
  336. /* If we get an ending code immediately after a clear code
  337. * (Yet another unlikely case), then break out of the loop.
  338. */
  339. if (c == ending)
  340. break;
  341. /* Finally, if the code is beyond the range of already set codes,
  342. * (This one had better NOT happen... I have no idea what will
  343. * result from this, but I doubt it will look good...) then set it
  344. * to color zero.
  345. */
  346. if (c >= slot)
  347. c = 0;
  348. oc = fc = c;
  349. /* And let us not forget to put the char into the buffer... And
  350. * if, on the off chance, we were exactly one pixel from the end
  351. * of the line, we have to send the buffer to the out_line()
  352. * routine...
  353. */
  354. *bufptr++ = (UTINY) c;
  355. if (--bufcnt == 0)
  356. {
  357. COOPERATE_1
  358. if ((ret = out_line(buf, linewidth)) < 0)
  359. {
  360. cleanup_gif_decoder();
  361. return(ret);
  362. }
  363. bufptr = buf;
  364. bufcnt = linewidth;
  365. }
  366. }
  367. else
  368. {
  369. /* In this case, it's not a clear code or an ending code, so
  370. * it must be a code code... So we can now decode the code into
  371. * a stack of character codes. (Clear as mud, right?)
  372. */
  373. code = c;
  374. /* Here we go again with one of those off chances... If, on the
  375. * off chance, the code we got is beyond the range of those already
  376. * set up (Another thing which had better NOT happen...) we trick
  377. * the decoder into thinking it actually got the last code read.
  378. * (Hmmn... I'm not sure why this works... But it does...)
  379. */
  380. if (code >= slot)
  381. {
  382. if (code > slot)
  383. ++bad_code_count;
  384. code = oc;
  385. *sp++ = (UTINY) fc;
  386. }
  387. /* Here we scan back along the linked list of prefixes, pushing
  388. * helpless characters (ie. suffixes) onto the stack as we do so.
  389. */
  390. while (code >= newcodes)
  391. {
  392. *sp++ = suffix[code];
  393. code = prefix[code];
  394. }
  395. /* Push the last character on the stack, and set up the new
  396. * prefix and suffix, and if the required slot number is greater
  397. * than that allowed by the current bit size, increase the bit
  398. * size. (NOTE - If we are all full, we *don't* save the new
  399. * suffix and prefix... I'm not certain if this is correct...
  400. * it might be more proper to overwrite the last code...
  401. */
  402. *sp++ = (UTINY) code;
  403. if (slot < top_slot)
  404. {
  405. fc = code;
  406. suffix[slot] = (UTINY) fc;
  407. prefix[slot++] = oc;
  408. oc = c;
  409. }
  410. if (slot >= top_slot)
  411. if (curr_size < 12)
  412. {
  413. top_slot <<= 1;
  414. ++curr_size;
  415. }
  416. /* Now that we've pushed the decoded string (in reverse order)
  417. * onto the stack, lets pop it off and put it into our decode
  418. * buffer... And when the decode buffer is full, write another
  419. * line...
  420. */
  421. while (sp > dstack)
  422. {
  423. *bufptr++ = *(--sp);
  424. if (--bufcnt == 0)
  425. {
  426. COOPERATE_1
  427. if ((ret = out_line(buf, linewidth)) < 0)
  428. {
  429. cleanup_gif_decoder();
  430. return(ret);
  431. }
  432. bufptr = buf;
  433. bufcnt = linewidth;
  434. }
  435. }
  436. }
  437. }
  438. ret = 0;
  439. if (bufcnt != linewidth)
  440. ret = out_line(buf, (linewidth - bufcnt));
  441. cleanup_gif_decoder();
  442. return(ret);
  443. }