Subversion Repositories Kolibri OS

Rev

Go to most recent revision | Blame | Last modification | View Log | Download | RSS feed

  1. /*
  2.  * Copyright 2004 Richard Wilson <richard.wilson@netsurf-browser.org>
  3.  * Copyright 2008 Sean Fox <dyntryx@gmail.com>
  4.  *
  5.  * This file is part of NetSurf's libnsgif, http://www.netsurf-browser.org/
  6.  * Licenced under the MIT License,
  7.  *                http://www.opensource.org/licenses/mit-license.php
  8.  */
  9.  
  10. #include <stdbool.h>
  11. #include <stdio.h>
  12. #include <string.h>
  13. #include <stdlib.h>
  14. #include <assert.h>
  15. #include "libnsgif.h"
  16. #include "utils/log.h"
  17.  
  18. /*      READING GIF FILES
  19.         =================
  20.  
  21.         The functions provided by this file allow for efficient progressive GIF
  22.         decoding. Whilst the initialisation does not ensure that there is
  23.         sufficient image data to complete the entire frame, it does ensure that
  24.         the information provided is valid. Any subsequent attempts to decode an
  25.         initialised GIF are guaranteed to succeed, and any bytes of the image
  26.         not present are assumed to be totally transparent.
  27.  
  28.         To begin decoding a GIF, the 'gif' structure must be initialised with
  29.         the 'gif_data' and 'buffer_size' set to their initial values. The
  30.         'buffer_position' should initially be 0, and will be internally updated
  31.         as the decoding commences. The caller should then repeatedly call
  32.         gif_initialise() with the structure until the function returns 1, or
  33.         no more data is avaliable.
  34.  
  35.         Once the initialisation has begun, the decoder completes the variables
  36.         'frame_count' and 'frame_count_partial'. The former being the total
  37.         number of frames that have been successfully initialised, and the
  38.         latter being the number of frames that a partial amount of data is
  39.         available for. This assists the caller in managing the animation whilst
  40.         decoding is continuing.
  41.  
  42.         To decode a frame, the caller must use gif_decode_frame() which updates
  43.         the current 'frame_image' to reflect the desired frame. The required
  44.         'disposal_method' is also updated to reflect how the frame should be
  45.         plotted. The caller must not assume that the current 'frame_image' will
  46.         be valid between calls if initialisation is still occuring, and should
  47.         either always request that the frame is decoded (no processing will
  48.         occur if the 'decoded_frame' has not been invalidated by initialisation)
  49.         or perform the check itself.
  50.  
  51.         It should be noted that gif_finalise() should always be called, even if
  52.         no frames were initialised.  Additionally, it is the responsibility of
  53.         the caller to free 'gif_data'.
  54.  
  55.         [rjw] - Fri 2nd April 2004
  56. */
  57.  
  58. /*      TO-DO LIST
  59.         =================
  60.  
  61.         + Plain text and comment extensions could be implemented if there is any
  62.         interest in doing so.
  63. */
  64.  
  65.  
  66.  
  67.  
  68. /*      Maximum colour table size
  69. */
  70. #define GIF_MAX_COLOURS 256
  71.  
  72. /*      Internal flag that the colour table needs to be processed
  73. */
  74. #define GIF_PROCESS_COLOURS 0xaa000000
  75.  
  76. /*      Internal flag that a frame is invalid/unprocessed
  77. */
  78. #define GIF_INVALID_FRAME -1
  79.  
  80. /*      Maximum LZW bits available
  81. */
  82. #define GIF_MAX_LZW 12
  83.  
  84. /* Transparent colour
  85. */
  86. #define GIF_TRANSPARENT_COLOUR 0x00
  87.  
  88. /*      GIF Flags
  89. */
  90. #define GIF_FRAME_COMBINE 1
  91. #define GIF_FRAME_CLEAR 2
  92. #define GIF_FRAME_RESTORE 3
  93. #define GIF_FRAME_QUIRKS_RESTORE 4
  94. #define GIF_IMAGE_SEPARATOR 0x2c
  95. #define GIF_INTERLACE_MASK 0x40
  96. #define GIF_COLOUR_TABLE_MASK 0x80
  97. #define GIF_COLOUR_TABLE_SIZE_MASK 0x07
  98. #define GIF_EXTENSION_INTRODUCER 0x21
  99. #define GIF_EXTENSION_GRAPHIC_CONTROL 0xf9
  100. #define GIF_DISPOSAL_MASK 0x1c
  101. #define GIF_TRANSPARENCY_MASK 0x01
  102. #define GIF_EXTENSION_COMMENT 0xfe
  103. #define GIF_EXTENSION_PLAIN_TEXT 0x01
  104. #define GIF_EXTENSION_APPLICATION 0xff
  105. #define GIF_BLOCK_TERMINATOR 0x00
  106. #define GIF_TRAILER 0x3b
  107.  
  108. /*      Internal GIF routines
  109. */
  110. static gif_result gif_initialise_sprite(gif_animation *gif, unsigned int width, unsigned int height);
  111. static gif_result gif_initialise_frame(gif_animation *gif);
  112. static gif_result gif_initialise_frame_extensions(gif_animation *gif, const int frame);
  113. static gif_result gif_skip_frame_extensions(gif_animation *gif);
  114. static unsigned int gif_interlaced_line(int height, int y);
  115.  
  116.  
  117.  
  118. /*      Internal LZW routines
  119. */
  120. static void gif_init_LZW(gif_animation *gif);
  121. static bool gif_next_LZW(gif_animation *gif);
  122. static int gif_next_code(gif_animation *gif, int code_size);
  123.  
  124. /*      General LZW values. They are shared for all GIFs being decoded, and
  125.         thus we can't handle progressive decoding efficiently without having
  126.         the data for each image which would use an extra 10Kb or so per GIF.
  127. */
  128. static unsigned char buf[4];
  129. static unsigned char *direct;
  130. static int maskTbl[16] = {0x0000, 0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f,
  131.                           0x00ff, 0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff};
  132. static int table[2][(1 << GIF_MAX_LZW)];
  133. static unsigned char stack[(1 << GIF_MAX_LZW) * 2];
  134. static unsigned char *stack_pointer;
  135. static int code_size, set_code_size;
  136. static int max_code, max_code_size;
  137. static int clear_code, end_code;
  138. static int curbit, lastbit, last_byte;
  139. static int firstcode, oldcode;
  140. static bool zero_data_block = false;
  141. static bool get_done;
  142.  
  143. /*      Whether to clear the decoded image rather than plot
  144. */
  145. static bool clear_image = false;
  146.  
  147.  
  148.  
  149. /**     Initialises necessary gif_animation members.
  150. */
  151. void gif_create(gif_animation *gif, gif_bitmap_callback_vt *bitmap_callbacks) {
  152.         memset(gif, 0, sizeof(gif_animation));
  153.         gif->bitmap_callbacks = *bitmap_callbacks;
  154.         gif->decoded_frame = GIF_INVALID_FRAME;
  155. }
  156.  
  157.  
  158. /**     Initialises any workspace held by the animation and attempts to decode
  159.         any information that hasn't already been decoded.
  160.         If an error occurs, all previously decoded frames are retained.
  161.  
  162.         @return GIF_FRAME_DATA_ERROR for GIF frame data error
  163.                 GIF_INSUFFICIENT_FRAME_DATA for insufficient data to process
  164.                           any more frames
  165.                 GIF_INSUFFICIENT_MEMORY for memory error
  166.                 GIF_DATA_ERROR for GIF error
  167.                 GIF_INSUFFICIENT_DATA for insufficient data to do anything
  168.                 GIF_OK for successful decoding
  169.                 GIF_WORKING for successful decoding if more frames are expected
  170. */
  171. gif_result gif_initialise(gif_animation *gif, size_t size, unsigned char *data) {
  172.         unsigned char *gif_data;
  173.         unsigned int index;
  174.         gif_result return_value;
  175.  
  176.         /*      The GIF format is thoroughly documented; a full description
  177.          *      can be found at http://www.w3.org/Graphics/GIF/spec-gif89a.txt
  178.         */
  179.  
  180.         /*      Initialize values
  181.         */
  182.         gif->buffer_size = size;
  183.         gif->gif_data = data;
  184.        
  185.         /*      Check for sufficient data to be a GIF (6-byte header + 7-byte logical screen descriptor)
  186.         */
  187.         if (gif->buffer_size < 13) return GIF_INSUFFICIENT_DATA;
  188.  
  189.         /*      Get our current processing position
  190.         */
  191.         gif_data = gif->gif_data + gif->buffer_position;
  192.  
  193.         /*      See if we should initialise the GIF
  194.         */
  195.         if (gif->buffer_position == 0) {
  196.  
  197.                 /*      We want everything to be NULL before we start so we've no chance
  198.                         of freeing bad pointers (paranoia)
  199.                 */
  200.                 gif->frame_image = NULL;
  201.                 gif->frames = NULL;
  202.                 gif->local_colour_table = NULL;
  203.                 gif->global_colour_table = NULL;
  204.  
  205.                 /*      The caller may have been lazy and not reset any values
  206.                 */
  207.                 gif->frame_count = 0;
  208.                 gif->frame_count_partial = 0;
  209.                 gif->decoded_frame = GIF_INVALID_FRAME;
  210.  
  211.                 /* 6-byte GIF file header is:
  212.                  *
  213.                  *      +0      3CHARS  Signature ('GIF')
  214.                  *      +3      3CHARS  Version ('87a' or '89a')
  215.                  */
  216.                 if (strncmp((const char *) gif_data, "GIF", 3) != 0)
  217.                         return GIF_DATA_ERROR;
  218.                 gif_data += 3;
  219.  
  220.                 /*      Ensure GIF reports version 87a or 89a
  221.                 */
  222. /*              if ((strncmp(gif_data, "87a", 3) != 0) &&
  223.                                 (strncmp(gif_data, "89a", 3) != 0))
  224.                         LOG(("Unknown GIF format - proceeding anyway"));
  225. */              gif_data += 3;
  226.  
  227.                 /* 7-byte Logical Screen Descriptor is:
  228.                  *
  229.                  *      +0      SHORT   Logical Screen Width
  230.                  *      +2      SHORT   Logical Screen Height
  231.                  *      +4      CHAR    __Packed Fields__
  232.                  *                      1BIT    Global Colour Table Flag
  233.                  *                      3BITS   Colour Resolution
  234.                  *                      1BIT    Sort Flag
  235.                  *                      3BITS   Size of Global Colour Table
  236.                  *      +5      CHAR    Background Colour Index
  237.                  *      +6      CHAR    Pixel Aspect Ratio
  238.                  */
  239.                 gif->width = gif_data[0] | (gif_data[1] << 8);
  240.                 gif->height = gif_data[2] | (gif_data[3] << 8);
  241.                 gif->global_colours = (gif_data[4] & GIF_COLOUR_TABLE_MASK);
  242.                 gif->colour_table_size = (2 << (gif_data[4] & GIF_COLOUR_TABLE_SIZE_MASK));
  243.                 gif->background_index = gif_data[5];
  244.                 gif->aspect_ratio = gif_data[6];
  245.                 gif->loop_count = 1;
  246.                 gif_data += 7;
  247.  
  248.                 /*      Some broken GIFs report the size as the screen size they were created in. As
  249.                         such, we detect for the common cases and set the sizes as 0 if they are found
  250.                         which results in the GIF being the maximum size of the frames.
  251.                 */
  252.                 if (((gif->width == 640) && (gif->height == 480)) ||
  253.                                 ((gif->width == 640) && (gif->height == 512)) ||
  254.                                 ((gif->width == 800) && (gif->height == 600)) ||
  255.                                 ((gif->width == 1024) && (gif->height == 768)) ||
  256.                                 ((gif->width == 1280) && (gif->height == 1024)) ||
  257.                                 ((gif->width == 1600) && (gif->height == 1200)) ||
  258.                                 ((gif->width == 0) || (gif->height == 0)) ||
  259.                                 ((gif->width > 2048) || (gif->height > 2048))) {
  260.                         gif->width = 1;
  261.                         gif->height = 1;
  262.                 }
  263.  
  264.                 /*      Allocate some data irrespective of whether we've got any colour tables. We
  265.                         always get the maximum size in case a GIF is lying to us. It's far better
  266.                         to give the wrong colours than to trample over some memory somewhere.
  267.                 */
  268.                 gif->global_colour_table = (unsigned int *)calloc(GIF_MAX_COLOURS, sizeof(int));
  269.                 gif->local_colour_table = (unsigned int *)calloc(GIF_MAX_COLOURS, sizeof(int));
  270.                 if ((gif->global_colour_table == NULL) || (gif->local_colour_table == NULL)) {
  271.                         gif_finalise(gif);
  272.                         return GIF_INSUFFICIENT_MEMORY;
  273.                 }
  274.  
  275.                 /*      Set the first colour to a value that will never occur in reality so we
  276.                         know if we've processed it
  277.                 */
  278.                 gif->global_colour_table[0] = GIF_PROCESS_COLOURS;
  279.                
  280.                 /*      Check if the GIF has no frame data (13-byte header + 1-byte termination block)
  281.                  *      Although generally useless, the GIF specification does not expressly prohibit this
  282.                  */
  283.                 if (gif->buffer_size == 14) {
  284.                         if (gif_data[0] == GIF_TRAILER)
  285.                                 return GIF_OK;
  286.                         else
  287.                                 return GIF_INSUFFICIENT_DATA;
  288.                 }
  289.  
  290.                 /*      Initialise enough workspace for 4 frames initially
  291.                 */
  292.                 if ((gif->frames = (gif_frame *)malloc(sizeof(gif_frame))) == NULL) {
  293.                         gif_finalise(gif);
  294.                         return GIF_INSUFFICIENT_MEMORY;
  295.                 }
  296.                 gif->frame_holders = 1;
  297.  
  298.                 /*      Initialise the sprite header
  299.                 */
  300.                 assert(gif->bitmap_callbacks.bitmap_create);
  301.                 if ((gif->frame_image = gif->bitmap_callbacks.bitmap_create(gif->width, gif->height)) == NULL) {
  302.                         gif_finalise(gif);
  303.                         return GIF_INSUFFICIENT_MEMORY;
  304.                 }
  305.  
  306.                 /*      Remember we've done this now
  307.                 */
  308.                 gif->buffer_position = gif_data - gif->gif_data;
  309.         }
  310.  
  311.         /*      Do the colour map if we haven't already. As the top byte is always 0xff or 0x00
  312.                 depending on the transparency we know if it's been filled in.
  313.         */
  314.         if (gif->global_colour_table[0] == GIF_PROCESS_COLOURS) {
  315.                 /*      Check for a global colour map signified by bit 7
  316.                 */
  317.                 if (gif->global_colours) {
  318.                         if (gif->buffer_size < (gif->colour_table_size * 3 + 12)) {
  319.                                 return GIF_INSUFFICIENT_DATA;
  320.                         }
  321.                         for (index = 0; index < gif->colour_table_size; index++) {
  322.                                 /* Gif colour map contents are r,g,b.
  323.                                  *
  324.                                  * We want to pack them bytewise into the
  325.                                  * colour table, such that the red component
  326.                                  * is in byte 0 and the alpha component is in
  327.                                  * byte 3.
  328.                                  */
  329.                                 unsigned char *entry = (unsigned char *) &gif->
  330.                                                 global_colour_table[index];
  331.  
  332.                                 entry[0] = gif_data[0]; /* r */
  333.                                 entry[1] = gif_data[1]; /* g */
  334.                                 entry[2] = gif_data[2]; /* b */
  335.                                 entry[3] = 0xff;        /* a */
  336.  
  337.                                 gif_data += 3;
  338.                         }
  339.                         gif->buffer_position = (gif_data - gif->gif_data);
  340.                 } else {
  341.                         /*      Create a default colour table with the first two colours as black and white
  342.                         */
  343.                         unsigned int *entry = gif->global_colour_table;
  344.  
  345.                         entry[0] = 0x00000000;
  346.                         /* Force Alpha channel to opaque */
  347.                         ((unsigned char *) entry)[3] = 0xff;
  348.  
  349.                         entry[1] = 0xffffffff;
  350.                 }
  351.         }
  352.  
  353.         /*      Repeatedly try to initialise frames
  354.         */
  355.         while ((return_value = gif_initialise_frame(gif)) == GIF_WORKING);
  356.  
  357.         /*      If there was a memory error tell the caller
  358.         */
  359.         if ((return_value == GIF_INSUFFICIENT_MEMORY) ||
  360.                         (return_value == GIF_DATA_ERROR))
  361.                 return return_value;
  362.  
  363.         /*      If we didn't have some frames then a GIF_INSUFFICIENT_DATA becomes a
  364.                 GIF_INSUFFICIENT_FRAME_DATA
  365.         */
  366.         if ((return_value == GIF_INSUFFICIENT_DATA) && (gif->frame_count_partial > 0))
  367.                 return GIF_INSUFFICIENT_FRAME_DATA;
  368.  
  369.         /*      Return how many we got
  370.         */
  371.         return return_value;
  372. }
  373.  
  374.  
  375. /**     Updates the sprite memory size
  376.  
  377.         @return GIF_INSUFFICIENT_MEMORY for a memory error
  378.                 GIF_OK for success
  379. */
  380. static gif_result gif_initialise_sprite(gif_animation *gif, unsigned int width, unsigned int height) {
  381.         unsigned int max_width;
  382.         unsigned int max_height;
  383.         struct bitmap *buffer;
  384.  
  385.         /*      Check if we've changed
  386.         */
  387.         if ((width <= gif->width) && (height <= gif->height))
  388.                 return GIF_OK;
  389.  
  390.         /*      Get our maximum values
  391.         */
  392.         max_width = (width > gif->width) ? width : gif->width;
  393.         max_height = (height > gif->height) ? height : gif->height;
  394.  
  395.         /*      Allocate some more memory
  396.         */
  397.         assert(gif->bitmap_callbacks.bitmap_create);
  398.         if ((buffer = gif->bitmap_callbacks.bitmap_create(max_width, max_height)) == NULL)
  399.                 return GIF_INSUFFICIENT_MEMORY;
  400.         assert(gif->bitmap_callbacks.bitmap_destroy);
  401.         gif->bitmap_callbacks.bitmap_destroy(gif->frame_image);
  402.         gif->frame_image = buffer;
  403.         gif->width = max_width;
  404.         gif->height = max_height;
  405.  
  406.         /*      Invalidate our currently decoded image
  407.         */
  408.         gif->decoded_frame = GIF_INVALID_FRAME;
  409.         return GIF_OK;
  410. }
  411.  
  412.  
  413. /**     Attempts to initialise the next frame
  414.  
  415.         @return GIF_INSUFFICIENT_DATA for insufficient data to do anything
  416.                 GIF_FRAME_DATA_ERROR for GIF frame data error
  417.                 GIF_INSUFFICIENT_MEMORY for insufficient memory to process
  418.                 GIF_INSUFFICIENT_FRAME_DATA for insufficient data to complete the frame
  419.                 GIF_DATA_ERROR for GIF error (invalid frame header)
  420.                 GIF_OK for successful decoding
  421.                 GIF_WORKING for successful decoding if more frames are expected
  422. */
  423. static gif_result gif_initialise_frame(gif_animation *gif) {
  424.         int frame;
  425.         gif_frame *temp_buf;
  426.  
  427.         unsigned char *gif_data, *gif_end;
  428.         int gif_bytes;
  429.         unsigned int flags = 0;
  430.         unsigned int width, height, offset_x, offset_y;
  431.         unsigned int block_size, colour_table_size;
  432.         bool first_image = true;
  433.         gif_result return_value;
  434.  
  435.         /*      Get the frame to decode and our data position
  436.         */
  437.         frame = gif->frame_count;
  438.  
  439.         /*      Get our buffer position etc.
  440.         */
  441.         gif_data = (unsigned char *)(gif->gif_data + gif->buffer_position);
  442.         gif_end = (unsigned char *)(gif->gif_data + gif->buffer_size);
  443.         gif_bytes = (gif_end - gif_data);
  444.  
  445.         /*      Check if we've finished
  446.         */
  447.         if ((gif_bytes > 0) && (gif_data[0] == GIF_TRAILER)) return GIF_OK;
  448.        
  449.         /*      Check if we have enough data
  450.          *      The shortest block of data is a 4-byte comment extension + 1-byte block terminator + 1-byte gif trailer
  451.         */
  452.         if (gif_bytes < 6) return GIF_INSUFFICIENT_DATA;
  453.  
  454.         /*      We could theoretically get some junk data that gives us millions of frames, so
  455.                 we ensure that we don't have a silly number
  456.         */
  457.         if (frame > 4096) return GIF_FRAME_DATA_ERROR;
  458.  
  459.         /*      Get some memory to store our pointers in etc.
  460.         */
  461.         if ((int)gif->frame_holders <= frame) {
  462.                 /*      Allocate more memory
  463.                 */
  464.                 if ((temp_buf = (gif_frame *)realloc(gif->frames,
  465.                                         (frame + 1) * sizeof(gif_frame))) == NULL)
  466.                         return GIF_INSUFFICIENT_MEMORY;
  467.                 gif->frames = temp_buf;
  468.                 gif->frame_holders = frame + 1;
  469.         }
  470.  
  471.         /*      Store our frame pointer. We would do it when allocating except we
  472.                 start off with one frame allocated so we can always use realloc.
  473.         */
  474.         gif->frames[frame].frame_pointer = gif->buffer_position;
  475.         gif->frames[frame].display = false;
  476.         gif->frames[frame].virgin = true;
  477.         gif->frames[frame].disposal_method = 0;
  478.         gif->frames[frame].transparency = false;
  479.         gif->frames[frame].frame_delay = 100;
  480.         gif->frames[frame].redraw_required = false;
  481.  
  482.         /*      Invalidate any previous decoding we have of this frame
  483.         */
  484.         if (gif->decoded_frame == frame)
  485.                 gif->decoded_frame = GIF_INVALID_FRAME;
  486.  
  487.         /*      We pretend to initialise the frames, but really we just skip over all
  488.                 the data contained within. This is all basically a cut down version of
  489.                 gif_decode_frame that doesn't have any of the LZW bits in it.
  490.         */
  491.  
  492.         /*      Initialise any extensions
  493.         */
  494.         gif->buffer_position = gif_data - gif->gif_data;
  495.         if ((return_value = gif_initialise_frame_extensions(gif, frame)) != GIF_OK)
  496.                 return return_value;
  497.         gif_data = (gif->gif_data + gif->buffer_position);
  498.         gif_bytes = (gif_end - gif_data);
  499.  
  500.         /*      Check if we've finished
  501.         */
  502.         if ((gif_bytes = (gif_end - gif_data)) < 1)
  503.                 return GIF_INSUFFICIENT_FRAME_DATA;
  504.         else if (gif_data[0] == GIF_TRAILER) {
  505.                 gif->buffer_position = (gif_data - gif->gif_data);
  506.                 gif->frame_count = frame + 1;
  507.                 return GIF_OK;
  508.         }
  509.  
  510.         /*      If we're not done, there should be an image descriptor
  511.         */
  512.         if (gif_data[0] != GIF_IMAGE_SEPARATOR) return GIF_FRAME_DATA_ERROR;
  513.  
  514.         /*      Do some simple boundary checking
  515.         */
  516.         offset_x = gif_data[1] | (gif_data[2] << 8);
  517.         offset_y = gif_data[3] | (gif_data[4] << 8);
  518.         width = gif_data[5] | (gif_data[6] << 8);
  519.         height = gif_data[7] | (gif_data[8] << 8);
  520.  
  521.         /*      Set up the redraw characteristics. We have to check for extending the area
  522.                 due to multi-image frames.
  523.         */
  524.         if (!first_image) {
  525.                 if (gif->frames[frame].redraw_x > offset_x) {
  526.                         gif->frames[frame].redraw_width += (gif->frames[frame].redraw_x - offset_x);
  527.                         gif->frames[frame].redraw_x = offset_x;
  528.                 }
  529.                 if (gif->frames[frame].redraw_y > offset_y) {
  530.                         gif->frames[frame].redraw_height += (gif->frames[frame].redraw_y - offset_y);
  531.                         gif->frames[frame].redraw_y = offset_y;
  532.                 }
  533.                 if ((offset_x + width) > (gif->frames[frame].redraw_x + gif->frames[frame].redraw_width))
  534.                         gif->frames[frame].redraw_width = (offset_x + width) - gif->frames[frame].redraw_x;
  535.                 if ((offset_y + height) > (gif->frames[frame].redraw_y + gif->frames[frame].redraw_height))
  536.                         gif->frames[frame].redraw_height = (offset_y + height) - gif->frames[frame].redraw_y;
  537.         } else {
  538.                 first_image = false;
  539.                 gif->frames[frame].redraw_x = offset_x;
  540.                 gif->frames[frame].redraw_y = offset_y;
  541.                 gif->frames[frame].redraw_width = width;
  542.                 gif->frames[frame].redraw_height = height;
  543.         }
  544.  
  545.         /*      if we are clearing the background then we need to redraw enough to cover the previous
  546.                 frame too
  547.         */
  548.         gif->frames[frame].redraw_required = ((gif->frames[frame].disposal_method == GIF_FRAME_CLEAR) ||
  549.                                                 (gif->frames[frame].disposal_method == GIF_FRAME_RESTORE));
  550.  
  551.         /*      Boundary checking - shouldn't ever happen except with junk data
  552.         */
  553.         if (gif_initialise_sprite(gif, (offset_x + width), (offset_y + height)))
  554.                 return GIF_INSUFFICIENT_MEMORY;
  555.  
  556.         /*      Decode the flags
  557.         */
  558.         flags = gif_data[9];
  559.         colour_table_size = 2 << (flags & GIF_COLOUR_TABLE_SIZE_MASK);
  560.  
  561.         /*      Move our data onwards and remember we've got a bit of this frame
  562.         */
  563.         gif_data += 10;
  564.         gif_bytes = (gif_end - gif_data);
  565.         gif->frame_count_partial = frame + 1;
  566.  
  567.         /*      Skip the local colour table
  568.         */
  569.         if (flags & GIF_COLOUR_TABLE_MASK) {
  570.                 gif_data += 3 * colour_table_size;
  571.                 if ((gif_bytes = (gif_end - gif_data)) < 0)
  572.                         return GIF_INSUFFICIENT_FRAME_DATA;
  573.         }
  574.  
  575.         /*      Ensure we have a correct code size
  576.         */
  577.         if (gif_data[0] > GIF_MAX_LZW)
  578.                 return GIF_DATA_ERROR;
  579.  
  580.         /*      Move our pointer to the actual image data
  581.         */
  582.         gif_data++;
  583.         if (--gif_bytes < 0)
  584.                 return GIF_INSUFFICIENT_FRAME_DATA;
  585.  
  586.         /*      Repeatedly skip blocks until we get a zero block or run out of data
  587.          *      These blocks of image data are processed later by gif_decode_frame()
  588.         */
  589.         block_size = 0;
  590.         while (block_size != 1) {
  591.                 block_size = gif_data[0] + 1;
  592.                 /*      Check if the frame data runs off the end of the file
  593.                 */
  594.                 if ((int)(gif_bytes - block_size) < 0) {
  595.                         /*      Try to recover by signaling the end of the gif.
  596.                          *      Once we get garbage data, there is no logical
  597.                          *      way to determine where the next frame is.
  598.                          *      It's probably better to partially load the gif
  599.                          *      than not at all.
  600.                         */
  601.                         if (gif_bytes >= 2) {
  602.                                 gif_data[0] = 0;
  603.                                 gif_data[1] = GIF_TRAILER;
  604.                                 gif_bytes = 1;
  605.                                 ++gif_data;
  606.                                 break;
  607.                         } else
  608.                                 return GIF_INSUFFICIENT_FRAME_DATA;
  609.                 } else {
  610.                         gif_bytes -= block_size;
  611.                         gif_data += block_size;
  612.                 }
  613.         }
  614.  
  615.         /*      Add the frame and set the display flag
  616.         */
  617.         gif->buffer_position = gif_data - gif->gif_data;
  618.         gif->frame_count = frame + 1;
  619.         gif->frames[frame].display = true;
  620.  
  621.         /*      Check if we've finished
  622.         */
  623.         if (gif_bytes < 1)
  624.                 return GIF_INSUFFICIENT_FRAME_DATA;
  625.         else
  626.                 if (gif_data[0] == GIF_TRAILER) return GIF_OK;
  627.         return GIF_WORKING;
  628. }
  629.  
  630. /**     Attempts to initialise the frame's extensions
  631.  
  632.         @return GIF_INSUFFICIENT_FRAME_DATA for insufficient data to complete the frame
  633.                 GIF_OK for successful initialisation
  634. */
  635. static gif_result gif_initialise_frame_extensions(gif_animation *gif, const int frame) {
  636.         unsigned char *gif_data, *gif_end;
  637.         int gif_bytes;
  638.         unsigned int block_size;
  639.  
  640.         /*      Get our buffer position etc.
  641.         */
  642.         gif_data = (unsigned char *)(gif->gif_data + gif->buffer_position);
  643.         gif_end = (unsigned char *)(gif->gif_data + gif->buffer_size);
  644.        
  645.         /*      Initialise the extensions
  646.         */
  647.         while (gif_data[0] == GIF_EXTENSION_INTRODUCER) {
  648.                 ++gif_data;
  649.                 gif_bytes = (gif_end - gif_data);
  650.  
  651.                 /*      Switch on extension label
  652.                 */
  653.                 switch(gif_data[0]) {
  654.                         /* 6-byte Graphic Control Extension is:
  655.                          *
  656.                          *      +0      CHAR    Graphic Control Label
  657.                          *      +1      CHAR    Block Size
  658.                          *      +2      CHAR    __Packed Fields__
  659.                          *                      3BITS   Reserved
  660.                          *                      3BITS   Disposal Method
  661.                          *                      1BIT    User Input Flag
  662.                          *                      1BIT    Transparent Color Flag
  663.                          *      +3      SHORT   Delay Time
  664.                          *      +5      CHAR    Transparent Color Index
  665.                         */
  666.                         case GIF_EXTENSION_GRAPHIC_CONTROL:
  667.                                 if (gif_bytes < 6) return GIF_INSUFFICIENT_FRAME_DATA;
  668.                                 gif->frames[frame].frame_delay = gif_data[3] | (gif_data[4] << 8);
  669.                                 if (gif_data[2] & GIF_TRANSPARENCY_MASK) {
  670.                                         gif->frames[frame].transparency = true;
  671.                                         gif->frames[frame].transparency_index = gif_data[5];
  672.                                 }
  673.                                 gif->frames[frame].disposal_method = ((gif_data[2] & GIF_DISPOSAL_MASK) >> 2);
  674.                                 /*      I have encountered documentation and GIFs in the wild that use
  675.                                  *      0x04 to restore the previous frame, rather than the officially
  676.                                  *      documented 0x03.  I believe some (older?) software may even actually
  677.                                  *      export this way.  We handle this as a type of "quirks" mode.
  678.                                 */
  679.                                 if (gif->frames[frame].disposal_method == GIF_FRAME_QUIRKS_RESTORE)
  680.                                         gif->frames[frame].disposal_method = GIF_FRAME_RESTORE;
  681.                                 gif_data += (2 + gif_data[1]);
  682.                                 break;
  683.  
  684.                         /* 14-byte+ Application Extension is:
  685.                          *
  686.                          *      +0      CHAR    Application Extension Label
  687.                          *      +1      CHAR    Block Size
  688.                          *      +2      8CHARS  Application Identifier
  689.                          *      +10     3CHARS  Appl. Authentication Code
  690.                          *      +13     1-256   Application Data (Data sub-blocks)
  691.                         */
  692.                         case GIF_EXTENSION_APPLICATION:
  693.                                 if (gif_bytes < 17) return GIF_INSUFFICIENT_FRAME_DATA;
  694.                                 if ((gif_data[1] == 0x0b) &&
  695.                                         (strncmp((const char *) gif_data + 2,
  696.                                                 "NETSCAPE2.0", 11) == 0) &&
  697.                                         (gif_data[13] == 0x03) &&
  698.                                         (gif_data[14] == 0x01)) {
  699.                                                 gif->loop_count = gif_data[15] | (gif_data[16] << 8);
  700.                                 }
  701.                                 gif_data += (2 + gif_data[1]);
  702.                                 break;
  703.  
  704.                         /*      Move the pointer to the first data sub-block
  705.                          *      Skip 1 byte for the extension label
  706.                         */
  707.                         case GIF_EXTENSION_COMMENT:
  708.                                 ++gif_data;
  709.                                 break;
  710.  
  711.                         /*      Move the pointer to the first data sub-block
  712.                          *      Skip 2 bytes for the extension label and size fields
  713.                          *      Skip the extension size itself
  714.                         */
  715.                         default:
  716.                                 gif_data += (2 + gif_data[1]);
  717.                 }
  718.  
  719.                 /*      Repeatedly skip blocks until we get a zero block or run out of data
  720.                  *      This data is ignored by this gif decoder
  721.                 */
  722.                 gif_bytes = (gif_end - gif_data);
  723.                 block_size = 0;
  724.                 while (gif_data[0] != GIF_BLOCK_TERMINATOR) {
  725.                         block_size = gif_data[0] + 1;
  726.                         if ((gif_bytes -= block_size) < 0)
  727.                                 return GIF_INSUFFICIENT_FRAME_DATA;
  728.                         gif_data += block_size;
  729.                 }
  730.                 ++gif_data;
  731.         }
  732.  
  733.         /*      Set buffer position and return
  734.         */
  735.         gif->buffer_position = (gif_data - gif->gif_data);
  736.         return GIF_OK;
  737. }
  738.  
  739.  
  740. /**     Decodes a GIF frame.
  741.  
  742.         @return GIF_FRAME_DATA_ERROR for GIF frame data error
  743.                 GIF_INSUFFICIENT_FRAME_DATA for insufficient data to complete the frame
  744.                 GIF_DATA_ERROR for GIF error (invalid frame header)
  745.                 GIF_INSUFFICIENT_DATA for insufficient data to do anything
  746.                 GIF_INSUFFICIENT_MEMORY for insufficient memory to process
  747.                 GIF_OK for successful decoding
  748.                 If a frame does not contain any image data, GIF_OK is returned and
  749.                         gif->current_error is set to GIF_FRAME_NO_DISPLAY
  750. */
  751. gif_result gif_decode_frame(gif_animation *gif, unsigned int frame) {
  752.         unsigned int index = 0;
  753.         unsigned char *gif_data, *gif_end;
  754.         int gif_bytes;
  755.         unsigned int width, height, offset_x, offset_y;
  756.         unsigned int flags, colour_table_size, interlace;
  757.         unsigned int *colour_table;
  758.         unsigned int *frame_data = 0;   // Set to 0 for no warnings
  759.         unsigned int *frame_scanline;
  760.         unsigned int save_buffer_position;
  761.         unsigned int return_value = 0;
  762.         unsigned int x, y, decode_y, burst_bytes;
  763.         int last_undisposed_frame = (frame - 1);
  764.         register unsigned char colour;
  765.  
  766.         /*      Ensure this frame is supposed to be decoded
  767.         */
  768.         if (gif->frames[frame].display == false) {
  769.                 gif->current_error = GIF_FRAME_NO_DISPLAY;
  770.                 return GIF_OK;
  771.         }
  772.  
  773.         /*      Ensure we have a frame to decode
  774.         */
  775.         if (frame > gif->frame_count_partial)
  776.                 return GIF_INSUFFICIENT_DATA;
  777.         if ((!clear_image) && ((int)frame == gif->decoded_frame))
  778.                 return GIF_OK;
  779.  
  780.         /*      Get the start of our frame data and the end of the GIF data
  781.         */
  782.         gif_data = gif->gif_data + gif->frames[frame].frame_pointer;
  783.         gif_end = gif->gif_data + gif->buffer_size;
  784.         gif_bytes = (gif_end - gif_data);
  785.  
  786.         /*      Check if we have enough data
  787.          *      The shortest block of data is a 10-byte image descriptor + 1-byte gif trailer
  788.         */
  789.         if (gif_bytes < 12) return GIF_INSUFFICIENT_FRAME_DATA;
  790.  
  791.         /*      Save the buffer position
  792.         */
  793.         save_buffer_position = gif->buffer_position;
  794.         gif->buffer_position = gif_data - gif->gif_data;
  795.  
  796.         /*      Skip any extensions because we all ready processed them
  797.         */
  798.         if ((return_value = gif_skip_frame_extensions(gif)) != GIF_OK)
  799.                 goto gif_decode_frame_exit;
  800.         gif_data = (gif->gif_data + gif->buffer_position);
  801.         gif_bytes = (gif_end - gif_data);
  802.  
  803.         /*      Ensure we have enough data for the 10-byte image descriptor + 1-byte gif trailer
  804.         */
  805.         if (gif_bytes < 12) {
  806.                 return_value = GIF_INSUFFICIENT_FRAME_DATA;
  807.                 goto gif_decode_frame_exit;
  808.         }
  809.  
  810.         /* 10-byte Image Descriptor is:
  811.          *
  812.          *      +0      CHAR    Image Separator (0x2c)
  813.          *      +1      SHORT   Image Left Position
  814.          *      +3      SHORT   Image Top Position
  815.          *      +5      SHORT   Width
  816.          *      +7      SHORT   Height
  817.          *      +9      CHAR    __Packed Fields__
  818.          *                      1BIT    Local Colour Table Flag
  819.          *                      1BIT    Interlace Flag
  820.          *                      1BIT    Sort Flag
  821.          *                      2BITS   Reserved
  822.          *                      3BITS   Size of Local Colour Table
  823.         */
  824.         if (gif_data[0] != GIF_IMAGE_SEPARATOR) {
  825.                 return_value = GIF_DATA_ERROR;
  826.                 goto gif_decode_frame_exit;
  827.         }
  828.         offset_x = gif_data[1] | (gif_data[2] << 8);
  829.         offset_y = gif_data[3] | (gif_data[4] << 8);
  830.         width = gif_data[5] | (gif_data[6] << 8);
  831.         height = gif_data[7] | (gif_data[8] << 8);
  832.  
  833.         /*      Boundary checking - shouldn't ever happen except unless the data has been
  834.                 modified since initialisation.
  835.         */
  836.         if ((offset_x + width > gif->width) || (offset_y + height > gif->height)) {
  837.                 return_value = GIF_DATA_ERROR;
  838.                 goto gif_decode_frame_exit;
  839.         }
  840.  
  841.         /*      Decode the flags
  842.         */
  843.         flags = gif_data[9];
  844.         colour_table_size = 2 << (flags & GIF_COLOUR_TABLE_SIZE_MASK);
  845.         interlace = flags & GIF_INTERLACE_MASK;
  846.  
  847.         /*      Move our pointer to the colour table or image data (if no colour table is given)
  848.         */
  849.         gif_data += 10;
  850.         gif_bytes = (gif_end - gif_data);
  851.  
  852.         /*      Set up the colour table
  853.         */
  854.         if (flags & GIF_COLOUR_TABLE_MASK) {
  855.                 if (gif_bytes < (int)(3 * colour_table_size)) {
  856.                         return_value = GIF_INSUFFICIENT_FRAME_DATA;
  857.                         goto gif_decode_frame_exit;
  858.                 }
  859.                 colour_table = gif->local_colour_table;
  860.                 if (!clear_image) {
  861.                         for (index = 0; index < colour_table_size; index++) {
  862.                                 /* Gif colour map contents are r,g,b.
  863.                                  *
  864.                                  * We want to pack them bytewise into the
  865.                                  * colour table, such that the red component
  866.                                  * is in byte 0 and the alpha component is in
  867.                                  * byte 3.
  868.                                  */
  869.                                 unsigned char *entry =
  870.                                         (unsigned char *) &colour_table[index];
  871.  
  872.                                 entry[0] = gif_data[0]; /* r */
  873.                                 entry[1] = gif_data[1]; /* g */
  874.                                 entry[2] = gif_data[2]; /* b */
  875.                                 entry[3] = 0xff;        /* a */
  876.  
  877.                                 gif_data += 3;
  878.                         }
  879.                 } else {
  880.                         gif_data += 3 * colour_table_size;
  881.                 }
  882.                 gif_bytes = (gif_end - gif_data);
  883.         } else {
  884.                 colour_table = gif->global_colour_table;
  885.         }
  886.  
  887.         /*      Check if we've finished
  888.         */
  889.         if (gif_bytes < 1) {
  890.                 return_value = GIF_INSUFFICIENT_FRAME_DATA;
  891.                 goto gif_decode_frame_exit;
  892.         } else if (gif_data[0] == GIF_TRAILER) {
  893.                 return_value = GIF_OK;
  894.                 goto gif_decode_frame_exit;
  895.         }
  896.  
  897.         /*      Get the frame data
  898.         */
  899.         assert(gif->bitmap_callbacks.bitmap_get_buffer);
  900.         frame_data = (void *)gif->bitmap_callbacks.bitmap_get_buffer(gif->frame_image);
  901.         if (!frame_data)
  902.                 return GIF_INSUFFICIENT_MEMORY;
  903.  
  904.         /*      If we are clearing the image we just clear, if not decode
  905.         */
  906.         if (!clear_image) {
  907.                 /*      Ensure we have enough data for a 1-byte LZW code size + 1-byte gif trailer
  908.                 */
  909.                 if (gif_bytes < 2) {
  910.                         return_value = GIF_INSUFFICIENT_FRAME_DATA;
  911.                         goto gif_decode_frame_exit;
  912.                 /*      If we only have a 1-byte LZW code size + 1-byte gif trailer, we're finished
  913.                 */
  914.                 } else if ((gif_bytes == 2) && (gif_data[1] == GIF_TRAILER)) {
  915.                         return_value = GIF_OK;
  916.                         goto gif_decode_frame_exit;
  917.                 }
  918.  
  919.                 /*      If the previous frame's disposal method requires we restore the background
  920.                  *      colour or this is the first frame, clear the frame data
  921.                 */
  922.                 if ((frame == 0) || (gif->decoded_frame == GIF_INVALID_FRAME)) {
  923.                         memset((char*)frame_data, GIF_TRANSPARENT_COLOUR, gif->width * gif->height * sizeof(int));
  924.                         gif->decoded_frame = frame;
  925.                         /* The line below would fill the image with its background color, but because GIFs support
  926.                          * transparency we likely wouldn't want to do that. */
  927.                         /* memset((char*)frame_data, colour_table[gif->background_index], gif->width * gif->height * sizeof(int)); */
  928.                 } else if ((frame != 0) && (gif->frames[frame - 1].disposal_method == GIF_FRAME_CLEAR)) {
  929.                         clear_image = true;
  930.                         if ((return_value = gif_decode_frame(gif, (frame - 1))) != GIF_OK)
  931.                                 goto gif_decode_frame_exit;
  932.                         clear_image = false;
  933.                 /*      If the previous frame's disposal method requires we restore the previous
  934.                  *      image, find the last image set to "do not dispose" and get that frame data
  935.                 */
  936.                 } else if ((frame != 0) && (gif->frames[frame - 1].disposal_method == GIF_FRAME_RESTORE)) {
  937.                         while ((last_undisposed_frame != -1) && (gif->frames[--last_undisposed_frame].disposal_method == GIF_FRAME_RESTORE));
  938.                                 /*      If we don't find one, clear the frame data
  939.                                 */
  940.                                 if (last_undisposed_frame == -1) {
  941.                                         /* see notes above on transparency vs. background color */
  942.                                         memset((char*)frame_data, GIF_TRANSPARENT_COLOUR, gif->width * gif->height * sizeof(int));
  943.                                 } else {
  944.                                         if ((return_value = gif_decode_frame(gif, last_undisposed_frame)) != GIF_OK)
  945.                                                 goto gif_decode_frame_exit;
  946.                                         /*      Get this frame's data
  947.                                         */
  948.                                         assert(gif->bitmap_callbacks.bitmap_get_buffer);
  949.                                         frame_data = (void *)gif->bitmap_callbacks.bitmap_get_buffer(gif->frame_image);
  950.                                         if (!frame_data)
  951.                                                 return GIF_INSUFFICIENT_MEMORY;
  952.                                 }
  953.                 }
  954.                 gif->decoded_frame = frame;
  955.  
  956.                 /*      Initialise the LZW decoding
  957.                 */
  958.                 set_code_size = gif_data[0];
  959.                 gif->buffer_position = (gif_data - gif->gif_data) + 1;
  960.  
  961.                 /*      Set our code variables
  962.                 */
  963.                 code_size = set_code_size + 1;
  964.                 clear_code = (1 << set_code_size);
  965.                 end_code = clear_code + 1;
  966.                 max_code_size = clear_code << 1;
  967.                 max_code = clear_code + 2;
  968.                 curbit = lastbit = 0;
  969.                 last_byte = 2;
  970.                 get_done = false;
  971.                 direct = buf;
  972.                 gif_init_LZW(gif);
  973.  
  974.                 /*      Decompress the data
  975.                 */
  976.                 for (y = 0; y < height; y++) {
  977.                         if (interlace)
  978.                                 decode_y = gif_interlaced_line(height, y) + offset_y;
  979.                         else
  980.                                 decode_y = y + offset_y;
  981.                         frame_scanline = frame_data + offset_x + (decode_y * gif->width);
  982.  
  983.                         /*      Rather than decoding pixel by pixel, we try to burst out streams
  984.                                 of data to remove the need for end-of data checks every pixel.
  985.                         */
  986.                         x = width;
  987.                         while (x > 0) {
  988.                                 burst_bytes = (stack_pointer - stack);
  989.                                 if (burst_bytes > 0) {
  990.                                         if (burst_bytes > x)
  991.                                                 burst_bytes = x;
  992.                                         x -= burst_bytes;
  993.                                         while (burst_bytes-- > 0) {
  994.                                                 colour = *--stack_pointer;
  995.                                                 if (((gif->frames[frame].transparency) &&
  996.                                                         (colour != gif->frames[frame].transparency_index)) ||
  997.                                                         (!gif->frames[frame].transparency))
  998.                                                                 *frame_scanline = colour_table[colour];
  999.                                                 frame_scanline++;
  1000.                                         }
  1001.                                 } else {
  1002.                                         if (!gif_next_LZW(gif)) {
  1003.                                                 /*      Unexpected end of frame, try to recover
  1004.                                                 */
  1005.                                                 if (gif->current_error == GIF_END_OF_FRAME)
  1006.                                                         return_value = GIF_OK;
  1007.                                                 else
  1008.                                                         return_value = gif->current_error;
  1009.                                                 goto gif_decode_frame_exit;
  1010.                                         }
  1011.                                 }
  1012.                         }
  1013.                 }
  1014.         } else {
  1015.                 /*      Clear our frame
  1016.                 */
  1017.                 if (gif->frames[frame].disposal_method == GIF_FRAME_CLEAR) {
  1018.                         for (y = 0; y < height; y++) {
  1019.                                 frame_scanline = frame_data + offset_x + ((offset_y + y) * gif->width);
  1020.                                 if (gif->frames[frame].transparency)
  1021.                                         memset(frame_scanline, GIF_TRANSPARENT_COLOUR, width * 4);
  1022.                                 else
  1023.                                         memset(frame_scanline, colour_table[gif->background_index], width * 4);
  1024.                         }
  1025.                 }
  1026.         }
  1027. gif_decode_frame_exit:
  1028.  
  1029.         /*      Check if we should test for optimisation
  1030.         */
  1031.         if (gif->frames[frame].virgin) {
  1032.                 if (gif->bitmap_callbacks.bitmap_test_opaque)
  1033.                         gif->frames[frame].opaque = gif->bitmap_callbacks.bitmap_test_opaque(gif->frame_image);
  1034.                 else
  1035.                         gif->frames[frame].opaque = false;
  1036.                 gif->frames[frame].virgin = false;
  1037.         }
  1038.         if (gif->bitmap_callbacks.bitmap_set_opaque)
  1039.                 gif->bitmap_callbacks.bitmap_set_opaque(gif->frame_image, gif->frames[frame].opaque);
  1040.         if (gif->bitmap_callbacks.bitmap_modified)
  1041.                 gif->bitmap_callbacks.bitmap_modified(gif->frame_image);
  1042.  
  1043.         /*      Restore the buffer position
  1044.         */
  1045.         gif->buffer_position = save_buffer_position;
  1046.  
  1047.         /*      Success!
  1048.         */
  1049.         return return_value;
  1050.  
  1051. }
  1052.  
  1053. /**     Skips the frame's extensions (which have been previously initialised)
  1054.  
  1055.         @return GIF_INSUFFICIENT_FRAME_DATA for insufficient data to complete the frame
  1056.                 GIF_OK for successful decoding
  1057. */
  1058. static gif_result gif_skip_frame_extensions(gif_animation *gif) {
  1059.         unsigned char *gif_data, *gif_end;
  1060.         int gif_bytes;
  1061.         unsigned int block_size;
  1062.  
  1063.         /*      Get our buffer position etc.
  1064.         */
  1065.         gif_data = (unsigned char *)(gif->gif_data + gif->buffer_position);
  1066.         gif_end = (unsigned char *)(gif->gif_data + gif->buffer_size);
  1067.         gif_bytes = (gif_end - gif_data);
  1068.  
  1069.         /*      Skip the extensions
  1070.         */
  1071.         while (gif_data[0] == GIF_EXTENSION_INTRODUCER) {
  1072.                 ++gif_data;
  1073.  
  1074.                 /*      Switch on extension label
  1075.                 */
  1076.                 switch(gif_data[0]) {
  1077.                         /*      Move the pointer to the first data sub-block
  1078.                          *      1 byte for the extension label
  1079.                         */
  1080.                         case GIF_EXTENSION_COMMENT:
  1081.                                 ++gif_data;
  1082.                                 break;
  1083.  
  1084.                         /*      Move the pointer to the first data sub-block
  1085.                          *      2 bytes for the extension label and size fields
  1086.                          *      Skip the extension size itself
  1087.                         */
  1088.                         default:
  1089.                                 gif_data += (2 + gif_data[1]);
  1090.                 }
  1091.  
  1092.                 /*      Repeatedly skip blocks until we get a zero block or run out of data
  1093.                  *      This data is ignored by this gif decoder
  1094.                 */
  1095.                 gif_bytes = (gif_end - gif_data);
  1096.                 block_size = 0;
  1097.                 while (gif_data[0] != GIF_BLOCK_TERMINATOR) {
  1098.                         block_size = gif_data[0] + 1;
  1099.                         if ((gif_bytes -= block_size) < 0)
  1100.                                 return GIF_INSUFFICIENT_FRAME_DATA;
  1101.                         gif_data += block_size;
  1102.                 }
  1103.                 ++gif_data;
  1104.         }
  1105.  
  1106.         /*      Set buffer position and return
  1107.         */
  1108.         gif->buffer_position = (gif_data - gif->gif_data);
  1109.         return GIF_OK;
  1110. }
  1111.  
  1112. static unsigned int gif_interlaced_line(int height, int y) {
  1113.         if ((y << 3) < height) return (y << 3);
  1114.         y -= ((height + 7) >> 3);
  1115.         if ((y << 3) < (height - 4)) return (y << 3) + 4;
  1116.         y -= ((height + 3) >> 3);
  1117.         if ((y << 2) < (height - 2)) return (y << 2) + 2;
  1118.         y -= ((height + 1) >> 2);
  1119.         return (y << 1) + 1;
  1120. }
  1121.  
  1122. /*      Releases any workspace held by the animation
  1123. */
  1124. void gif_finalise(gif_animation *gif) {
  1125.         /*      Release all our memory blocks
  1126.         */
  1127.         if (gif->frame_image) {
  1128.                 assert(gif->bitmap_callbacks.bitmap_destroy);
  1129.                 gif->bitmap_callbacks.bitmap_destroy(gif->frame_image);
  1130.         }
  1131.         gif->frame_image = NULL;
  1132.         free(gif->frames);
  1133.         gif->frames = NULL;
  1134.         free(gif->local_colour_table);
  1135.         gif->local_colour_table = NULL;
  1136.         free(gif->global_colour_table);
  1137.         gif->global_colour_table = NULL;
  1138. }
  1139.  
  1140. /**
  1141.  * Initialise LZW decoding
  1142.  */
  1143. void gif_init_LZW(gif_animation *gif) {
  1144.         int i;
  1145.  
  1146.         gif->current_error = 0;
  1147.         if (clear_code >= (1 << GIF_MAX_LZW)) {
  1148.                 stack_pointer = stack;
  1149.                 gif->current_error = GIF_FRAME_DATA_ERROR;
  1150.                 return;
  1151.         }
  1152.  
  1153.         /* initialise our table */
  1154.         memset(table, 0x00, (1 << GIF_MAX_LZW) * 8);
  1155.         for (i = 0; i < clear_code; ++i)
  1156.                 table[1][i] = i;
  1157.  
  1158.         /* update our LZW parameters */
  1159.         code_size = set_code_size + 1;
  1160.         max_code_size = clear_code << 1;
  1161.         max_code = clear_code + 2;
  1162.         stack_pointer = stack;
  1163.         do {
  1164.                 firstcode = oldcode = gif_next_code(gif, code_size);
  1165.         } while (firstcode == clear_code);
  1166.         *stack_pointer++ =firstcode;
  1167. }
  1168.  
  1169.  
  1170. static bool gif_next_LZW(gif_animation *gif) {
  1171.         int code, incode;
  1172.         int block_size;
  1173.         int new_code;
  1174.  
  1175.         code = gif_next_code(gif, code_size);
  1176.         if (code < 0) {
  1177.                 gif->current_error = code;
  1178.                 return false;
  1179.         } else if (code == clear_code) {
  1180.                 gif_init_LZW(gif);
  1181.                 return true;
  1182.         } else if (code == end_code) {
  1183.                 /* skip to the end of our data so multi-image GIFs work */
  1184.                 if (zero_data_block) {
  1185.                         gif->current_error = GIF_FRAME_DATA_ERROR;
  1186.                         return false;
  1187.                 }
  1188.                 block_size = 0;
  1189.                 while (block_size != 1) {
  1190.                         block_size = gif->gif_data[gif->buffer_position] + 1;
  1191.                         gif->buffer_position += block_size;
  1192.                 }
  1193.                 gif->current_error = GIF_FRAME_DATA_ERROR;
  1194.                 return false;
  1195.         }
  1196.  
  1197.         incode = code;
  1198.         if (code >= max_code) {
  1199.                 *stack_pointer++ = firstcode;
  1200.                 code = oldcode;
  1201.         }
  1202.  
  1203.         /* The following loop is the most important in the GIF decoding cycle as every
  1204.          * single pixel passes through it.
  1205.          *
  1206.          * Note: our stack is always big enough to hold a complete decompressed chunk. */
  1207.         while (code >= clear_code) {
  1208.                 *stack_pointer++ = table[1][code];
  1209.                 new_code = table[0][code];
  1210.                 if (new_code < clear_code) {
  1211.                         code = new_code;
  1212.                         break;
  1213.                 }
  1214.                 *stack_pointer++ = table[1][new_code];
  1215.                 code = table[0][new_code];
  1216.                 if (code == new_code) {
  1217.                         gif->current_error = GIF_FRAME_DATA_ERROR;
  1218.                         return false;
  1219.                 }
  1220.         }
  1221.  
  1222.         *stack_pointer++ = firstcode = table[1][code];
  1223.  
  1224.         if ((code = max_code) < (1 << GIF_MAX_LZW)) {
  1225.                 table[0][code] = oldcode;
  1226.                 table[1][code] = firstcode;
  1227.                 ++max_code;
  1228.                 if ((max_code >= max_code_size) && (max_code_size < (1 << GIF_MAX_LZW))) {
  1229.                         max_code_size = max_code_size << 1;
  1230.                         ++code_size;
  1231.                 }
  1232.         }
  1233.         oldcode = incode;
  1234.         return true;
  1235. }
  1236.  
  1237. static int gif_next_code(gif_animation *gif, int code_size) {
  1238.         int i, j, end, count, ret;
  1239.         unsigned char *b;
  1240.  
  1241.         end = curbit + code_size;
  1242.         if (end >= lastbit) {
  1243.                 if (get_done)
  1244.                         return GIF_END_OF_FRAME;
  1245.                 buf[0] = direct[last_byte - 2];
  1246.                 buf[1] = direct[last_byte - 1];
  1247.  
  1248.                 /* get the next block */
  1249.                 direct = gif->gif_data + gif->buffer_position;
  1250.                 zero_data_block = ((count = direct[0]) == 0);
  1251.                 if ((gif->buffer_position + count) >= gif->buffer_size)
  1252.                         return GIF_INSUFFICIENT_FRAME_DATA;
  1253.                 if (count == 0)
  1254.                         get_done = true;
  1255.                 else {
  1256.                         direct -= 1;
  1257.                         buf[2] = direct[2];
  1258.                         buf[3] = direct[3];
  1259.                 }
  1260.                 gif->buffer_position += count + 1;
  1261.  
  1262.                 /* update our variables */
  1263.                 last_byte = 2 + count;
  1264.                 curbit = (curbit - lastbit) + 16;
  1265.                 lastbit = (2 + count) << 3;
  1266.                 end = curbit + code_size;
  1267.         }
  1268.  
  1269.         i = curbit >> 3;
  1270.         if (i < 2)
  1271.                 b = buf;
  1272.         else
  1273.                 b = direct;
  1274.  
  1275.         ret = b[i];
  1276.         j = (end >> 3) - 1;
  1277.         if (i <= j) {
  1278.                 ret |= (b[i + 1] << 8);
  1279.                 if (i < j)
  1280.                         ret |= (b[i + 2] << 16);
  1281.         }
  1282.         ret = (ret >> (curbit % 8)) & maskTbl[code_size];
  1283.         curbit += code_size;
  1284.         return ret;
  1285. }
  1286.