status = gif_clear_screen(gs); if (status < 0) return status;
il_gif_write(il_container *ic, const PRUint8 *buf, int32 len){  int status;  gif_struct *gs = (gif_struct *)ic->ds;  NI_PixmapHeader *src_header = ic->src_header;  NI_ColorMap *cmap = &src_header->color_space->cmap;  const PRUint8 *q, *p=buf,*ep=buf+len;    /* If this assert fires, chances are the netlib flubbed and       continued to send data after the image stream was closed. */    PR_ASSERT(gs);    if (!gs) {#ifdef DEBUG        ILTRACE(1,("Netlib Error - imagelib image stream is closed\n"));#endif        return MK_IMAGE_LOSSAGE;    }    /* If this assert fires, some upstream data provider ignored the       zero return value from il_gif_write_ready() which says not to       send any more data to this stream until the delay timeout fires. */  //  PR_ASSERT ((len == 0) || (gs->gathered < MAX_READ_AHEAD));    if (!((len == 0) || (gs->gathered < MAX_READ_AHEAD)))        return MK_INTERRUPTED;        q = NULL;                   /* Initialize to shut up gcc warnings */        while (p <= ep)    {        ILTRACE(9,("il:gif: state %d len %d buf %u p %u q %u ep %u",                   gs->state,len,buf,p,q,ep));        switch(gs->state)        {        case gif_lzw:            if (do_lzw(gs, q) < 0)            {                gs->state=gif_error;                break;            }                       GETN(1,gif_sub_block);            break;                case gif_lzw_start:        {            int i;            cmap->map = gs->is_local_colormap_defined ?                gs->local_colormap : gs->global_colormap;            PR_ASSERT(cmap->map);            if (!cmap->map)                return MK_IMAGE_LOSSAGE;            /* Now we know how many colors are in our colormap. */            if (gs->is_local_colormap_defined || (gs->images_decoded == 0)){                if(ic->imgdcb){                nsresult rv = ic->imgdcb->ImgDCBSetupColorspaceConverter();                 if(NS_FAILED(rv))                    return MK_IMAGE_LOSSAGE;                }            }            /* Initialize LZW parser/decoder */            gs->datasize = *q;            if(gs->datasize > MAX_LZW_BITS)            {                gs->state=gif_error;                break;            }            gs->clear_code = 1 << gs->datasize;            gs->avail = gs->clear_code + 2;            gs->oldcode = -1;            gs->codesize = gs->datasize + 1;            gs->codemask = (1 << gs->codesize) - 1;            gs->datum = gs->bits = 0;            if (!gs->prefix)                        gs->prefix = (PRUint16 *)PR_Calloc(sizeof(PRUint16), MAX_BITS);            if (!gs->suffix)                gs->suffix = ( PRUint8 *)PR_Calloc(sizeof(PRUint8),  MAX_BITS);            if (!gs->stack)                gs->stack  = ( PRUint8 *)PR_Calloc(sizeof(PRUint8),  MAX_BITS);                                if( !gs->prefix || !gs->suffix || !gs->stack)            {                /* complete from abort will free prefix & suffix */                ILTRACE(0,("il:gif: MEM stack"));                gs->state=gif_oom;                break;            }            if(gs->clear_code >= MAX_BITS)            {                gs->state=gif_error;                break;            }            /* init the tables */            for (i=0; i < gs->clear_code; i++)                 gs->suffix[i] = i;            gs->stackp = gs->stack;            GETN(1,gif_sub_block);        }        break;        /* We're positioned at the very start of the file. */        case gif_init:        {            GETN(3,gif_type);            break;        }        /* All GIF files begin with "GIF87a" or "GIF89a" */        case gif_type:        {            if (strncmp((char*)q,"GIF",3))            {                ILTRACE(2,("il:gif: not a GIF file"));                gs->state=gif_error;                break;            }            GETN(3,gif_version);        }        break;        case gif_version:        {            if(!strncmp((char*)q,"89a",3))            {                gs->version=89;            }            else            {                if(!strncmp((char*)q,"87a",3))                {                    gs->version=87;                }                else                {                    ILTRACE(2,("il:gif: unrecognized GIF version number"));                    gs->state=gif_error;                    break;                }            }            ILTRACE(2,("il:gif: %d gif", gs->version));            GETN(7,gif_global_header);        }        break;        case gif_global_header:        {            /* This is the height and width of the "screen" or             * frame into which images are rendered.  The             * individual images can be smaller than the             * screen size and located with an origin anywhere             * within the screen.             */                                gs->screen_width = GETINT16(q);             gs->screen_height = GETINT16(q+2);            gs->screen_bgcolor = q[5];            gs->global_colormap_size = 2<<(q[4]&0x07);            /* A -ve value for cmap->num_colors indicates that the colors may               be non-unique.*/            cmap->num_colors = -gs->global_colormap_size;            cmap->map = NULL;            if(q[6])            {                /* should assert gif89 */                if(q[6] != 49)                {#ifdef DEBUG                    float aspect = (float)((q[6] + 15) / 64.0);                    ILTRACE(2, ("il:gif: %f aspect ratio", aspect));#endif                }            }            if( q[4] & 0x80 ) /* global map */            {                GETN(gs->global_colormap_size*3, gif_global_colormap);            }            else            {                GETN(1, gif_image_start);            }        }        break;        case gif_global_colormap:        {            IL_RGB* map;            int i;            if(!(map = (IL_RGB*)PR_Calloc(gs->global_colormap_size,                                          sizeof(IL_RGB))))            {                ILTRACE(0,("il:gif: MEM map"));                gs->state=gif_oom;                break;            }                       if(ic->imgdcb)               ic->imgdcb->ImgDCBResetPalette();            gs->global_colormap = map;#ifndef M12N                    /* Fix me. */#ifdef XP_MAC            im->hasUniqueColormap = 1;#endif#endif /* M12N */            for (i=0; i < gs->global_colormap_size; i++, map++)             {                map->red = *q++;                map->green = *q++;                map->blue = *q++;            }            GETN(1,gif_image_start);        }        break;        case gif_image_start:        {            if(*q==';') /* terminator */            {                gs->state = gif_done;                break;            }            if(*q=='!') /* extension */            {                GETN(2,gif_extension);                break;            }                                    if(*q!=',') /* invalid start character */            {                ILTRACE(2,("il:gif: bogus start character 0x%02x",                           (int)*q));                gs->state=gif_error;                break;            }            else            {                /* If this is a multi-part GIF, flush the last image */                if (gs->images_decoded) {                    ic->multi++;    /* Avoid progressive display */                }                            GETN(9, gif_image_header);            }        }        break;        case gif_extension:        {            int len = gs->count = q[1];            gstate es = gif_skip_block;            ILTRACE(2,("il:gif: %d byte extension %x", len, (int)*q));            switch(*q)            {            case 0xf9:                es = gif_control_extension;                break;            case 0x01:                ILTRACE(2,("il:gif: ignoring plain text extension"));                break;                                        case 0xff:                es = gif_application_extension;                break;            case 0xfe:                es = gif_consume_comment;                break;            }                        if (len)                GETN(len, es);            else                GETN(1, gif_image_start);        }        break;        case gif_consume_block:        {            if(!*q)            {                GETN(1, gif_image_start);            }            else            {                GETN(*q, gif_skip_block);            }        }        break;                    case gif_skip_block:            GETN(1, gif_consume_block);            break;        case gif_control_extension:        {            if(*q & 0x1)            {                gs->tpixel = *(q+3);                ILTRACE(2,("il:gif: transparent pixel %d", gs->tpixel));                if (!il_gif_init_transparency(ic, gs->tpixel))                    return MK_OUT_OF_MEMORY;                gs->is_transparent = TRUE;            }            else            {                ILTRACE(2,("il:gif: ignoring gfx control extension"));            }            gs->control_extension = TRUE;            gs->disposal_method = (gdispose)(((*q) >> 2) & 0x7);            gs->delay_time = GETINT16(q + 1) * 10;            GETN(1,gif_consume_block);        }        break;        case gif_comment_extension:        {            gs->count = *q;            if (gs->count)                 GETN(gs->count, gif_consume_comment);            else                GETN(1, gif_image_start);        }        break;        case gif_consume_comment:        {                       BlockAllocCat(ic->comment, ic->comment_length, (char*)q, gs->count);                      ic->comment_length += gs->count;            BlockAllocCat(ic->comment, ic->comment_length, "", 1);            ic->comment_length++;            GETN(1, gif_comment_extension);        }        break;        case gif_application_extension:            /* Check for netscape application extension */            if (!strncmp((char*)q, "NETSCAPE2.0", 11) ||                !strncmp((char*)q, "ANIMEXTS1.0", 11))                GETN(1, gif_netscape_extension_block);            else                GETN(1, gif_consume_block);            break;        /* Netscape-specific GIF extension: animation looping */        case gif_netscape_extension_block:            if (*q)                GETN(*q, gif_consume_netscape_extension);            else                GETN(1, gif_image_start);            break;        /* Parse netscape-specific application extensions */        case gif_consume_netscape_extension:        {            int netscape_extension = q[0] & 7;            /* Loop entire animation specified # of times.  Only read the               loop count during the first iteration. */            if (netscape_extension == 1) {                if (!ic->is_looping) {                    ic->loop_count = GETINT16(q + 1);                    /* Zero loop count is infinite animation loop request */                    if (ic->loop_count == 0)                        ic->loop_count = -1;                    /* Tell the front end that the stop state might have changed */                    /* because of the looping GIF.                               */#ifndef M12N                    /* XXXM12N Fix me. */                    if (ic->net_cx)                      FE_UpdateStopState(ic->net_cx);#endif /* M12N */                }                GETN(1, gif_netscape_extension_block);            }            /* Wait for specified # of bytes to enter buffer */            else if (netscape_extension == 2)            {                gs->requested_buffer_fullness = GETINT32(q + 1);                GETN(gs->requested_buffer_fullness, gif_wait_for_buffer_full);            }            break;        }        case gif_wait_for_buffer_full:            gs->gathered = gs->requested_buffer_fullness;            GETN(1, gif_netscape_extension_block);            break;        case gif_image_header:        {            PRUintn height, width;                                                                                                                                                /* Get image offsets, with respect to the screen origin */            gs->x_offset = GETINT16(q);            gs->y_offset = GETINT16(q + 2);            /* Get image width and height. */            width  = GETINT16(q + 4);                        height = GETINT16(q + 6);            ILTRACE(2,("il:gif: screen %dx%d, image %dx%d",                        gs->screen_width, gs->screen_height, width, height));            /* Work around broken GIF files where the logical screen             * size has weird width or height.  We assume that GIF87a             * files don't contain animations.             */         if ((gs->images_decoded == 0) &&                ((gs->screen_height < height) || (gs->screen_width < width) ||                 (gs->version == 87))){                           gs->screen_height = height;                gs->screen_width = width;                gs->x_offset = 0;                gs->y_offset = 0;            }            /* Work around more broken GIF files that have zero image               width or height */            if (!height || !width)             {                height = gs->screen_height;                width = gs->screen_width;            }            gs->height = height;            gs->width = width;            /* This case will never be taken if this is the first image */            /* being decoded. If any of the later images are larger     */            /* than the screen size, we need to reallocate buffers.     */            if (gs->screen_width < width) {                gs->rgbrow = (PRUint8*)PR_REALLOC(gs->rgbrow, 3 * width);                gs->rowbuf = (PRUint8*)PR_REALLOC(gs->rowbuf, width);                if((!gs->rgbrow)||(!gs->rowbuf)){                  gs->state = gif_oom;                  break;                }                            gs->screen_width = width;                if(gs->screen_height < gs->height )                    gs->screen_height = gs->height;                ic->src_header->width = gs->width;                ic->src_header->height = gs->height;                ic->image->header.width = gs->width;                ic->image->header.height = gs->height;                ic->image->header.widthBytes = (ic->image->header.width * ic->image->header.color_space->pixmap_depth + 7)/8;                 ic->image->header.widthBytes = ROUNDUP(ic->image->header.widthBytes, 4);                if(ic->imgdcb){                  nsresult rv = ic->imgdcb->ImgDCBImageSize();                                   if(NS_FAILED(rv)){                      gs->state = gif_error;                      break;                  }                }                else{    //no callback is an error too.                    gs->state = gif_error;                    break;                }                ic->img_cx->img_cb->NewPixmap(ic->img_cx->dpy_cx, ic->dest_width,                            ic->dest_height, ic->image, ic->mask);                    if((!ic->scalerow)||(!ic->image->bits)||(ic->mask && !ic->mask->bits)){                    gs->state=gif_oom;                    break;                }        }        else{            if (!gs->rgbrow)                gs->rgbrow = (PRUint8*)PR_MALLOC(3 * gs->screen_width);            if (!gs->rowbuf)                gs->rowbuf = (PRUint8*)PR_MALLOC(gs->screen_width);        }            if (!gs->rowbuf || !gs->rgbrow)            {                    ILTRACE(0,("il:gif: MEM row"));                    gs->state=gif_oom;                    break;            }                                /* Free transparency from earlier image in multi-image sequence. */            if (!gs->is_transparent && src_header->transparent_pixel) {                 il_gif_destroy_transparency(ic);            }            if (gs->images_decoded == 0) {                src_header->width = gs->screen_width;                src_header->height = gs->screen_height;                if(ic->imgdcb){                    nsresult rv = ic->imgdcb->ImgDCBImageSize();                                     if(NS_FAILED(rv)){                        gs->state = gif_error;                        break;                    }                }                else{    //no callback is an error too.                    gs->state = gif_error;                    break;                }            }            if ( *(q+8) & 0x40 )            {                ILTRACE(2,("il:gif: interlaced"));                gs->interlaced = TRUE;                gs->ipass = 1;            } else {                gs->interlaced = FALSE;                gs->ipass = 0;            }                        if (gs->images_decoded == 0)            {                gs->progressive_display = ic->img_cx->progressive_display;            } else {                /* Overlaying interlaced, transparent GIFs over                   existing image data using the Haeberli display hack                   requires saving the underlying image in order to                   avoid jaggies at the transparency edges.  We are                   unprepared to deal with that, so don't display such                   images progressively */                gs->progressive_display = ic->img_cx->progressive_display &&                    !(gs->interlaced && gs->is_transparent);            }             status = gif_clear_screen(gs);                          if (status < 0)                return status;            /* Clear state from last image */            gs->requested_buffer_fullness = 0;            gs->control_extension = FALSE;            gs->is_transparent = FALSE;            gs->irow = 0;            gs->rows_remaining = gs->height;            gs->rowend = gs->rowbuf + gs->width;            gs->rowp = gs->rowbuf;            /* bits per pixel is 1<<((q[8]&0x07)+1); */            if ( *(q+8) & 0x80 )             {                int num_colors = 2 << (*(q + 8) & 0x7);                                if ((num_colors > gs->local_colormap_size) &&                    gs->local_colormap)                {                    PR_FREEIF(gs->local_colormap);                    gs->local_colormap = NULL;                }                gs->local_colormap_size = num_colors;                /* A -ve value for cmap->num_colors indicates that the colors                   may be non-unique. */                cmap->num_colors = -num_colors;                /* Switch to the new local palette after it loads */                if(ic->imgdcb)                   ic->imgdcb->ImgDCBResetPalette();                gs->is_local_colormap_defined = TRUE;                GETN(gs->local_colormap_size * 3, gif_image_colormap);            }            else            {                /* Switch back to the global palette */                if (gs->is_local_colormap_defined)                  if(ic->imgdcb)                    ic->imgdcb->ImgDCBResetPalette();                gs->is_local_colormap_defined = FALSE;                GETN(1, gif_lzw_start);            }        }        break;        case gif_image_colormap:        {            IL_RGB* map;            int i;            ILTRACE(2,("il:gif: local colormap"));                                map = gs->local_colormap;            if (!map)             {                map = gs->local_colormap = (IL_RGB*)PR_Calloc(                    gs->local_colormap_size, sizeof(IL_RGB));                if(!map)                {                    ILTRACE(0,("il:gif: MEM map"));                    gs->state=gif_oom;                    break;                }            }#ifndef M12N                    /* Fix me */#ifdef XP_MAC            im->hasUniqueColormap = 1;#endif#endif /* M12N */            for (i=0; i < gs->local_colormap_size; i++, map++)             {                map->red   = *q++;                map->green = *q++;                map->blue  = *q++;            }            GETN(1,gif_lzw_start);        }        break;        case gif_sub_block:        {            if ((gs->count = *q) != 0)            /* Still working on the same image: Process next LZW data block */            {                /* Make sure there are still rows left. If the GIF data */                /* is corrupt, we may not get an explicit terminator.   */                if (gs->rows_remaining == 0) {                    ILTRACE(3,("il:gif: missing image terminator, continuing"));                    /* This is an illegal GIF, but we remain tolerant. */#ifdef DONT_TOLERATE_BROKEN_GIFS                    gs->state=gif_error;                    break;#else                    GETN(1,gif_sub_block);#endif                }                GETN(gs->count, gif_lzw);            }            else            /* See if there are any more images in this sequence. */                            {                /* Flush the image data unconditionally, so that we can                   notify observers that the current frame has completed. */                if(ic->imgdcb){                     ic->imgdcb->ImgDCBFlushImage();                     ic->imgdcb->ImgDCBHaveImageFrame();                }                        gs->images_decoded++;                                if(ic->animate_request == eImageAnimation_None){                    /* This is not really an error, but a mechanism                    to stop decoding of subsequent frames. Only the                    first frame is displayed for eImageAnimation_None.                    */                    gs->state = gif_stop_animating;                       break;                }                /* An image can specify a delay time before which to display                   subsequent images.  Block until the appointed time. */                if(gs->delay_time < MINIMUM_DELAY_TIME )                    gs->delay_time = MINIMUM_DELAY_TIME;                if (gs->delay_time){                    if(ic->imgdcb){                          gs->delay_timeout = (void *)                                ic->imgdcb->ImgDCBSetTimeout(gif_delay_time_callback, gs->ic, gs->delay_time);                     }                    /* Essentially, tell the decoder state machine to wait                       forever.  The timeout callback routine will wake up the                       state machine and force it to decode the next image. */                    GETN(1L<<30, gif_image_start);                    gs->state = gif_delay;                } else {                    GETN(1, gif_image_start);                }            }        }        break;        case gif_done:                            return 0;            break;        case gif_delay:        case gif_gather:            {            int32 gather_remaining;            int32 request_size = gs->gather_request_size;                        {                gather_remaining = request_size - gs->gathered;                /* Do we already have enough data in the accumulation                   buffer to satisfy the request ?  (This can happen                   after we transition from the gif_delay state.) */                if (gather_remaining <= 0)                {                    gs->gathered -= request_size;                    q = gs->gather_head;                    gs->gather_head += request_size;                    gs->state = gs->post_gather_state;                    break;                }                /* Shift remaining data to the head of the buffer */                if (gs->gathered && (gs->gather_head != gs->hold)) {                    nsCRT::memmove(gs->hold, gs->gather_head, gs->gathered);                    gs->gather_head = gs->hold;                }                                 /* If we add the data just handed to us by the netlib                   to what we've already gathered, is there enough to satisfy                    the current request ? */                if ((ep - p) >= gather_remaining)                {                    if(gs->gathered)                    { /* finish a prior gather */                        char *hold = (char*)gs->hold;                        BlockAllocCat(hold, gs->gathered, (char*)p, gather_remaining);                        gs->hold = (PRUint8*)hold;                        q = gs->gather_head = gs->hold;                        gs->gathered = 0;                    }                    else                    {                        q = p;                    }                    p += gather_remaining;                    gs->state = gs->post_gather_state;                }                else                {                     char *hold = (char*)gs->hold;                    BlockAllocCat(hold, gs->gathered, (char*)p, ep - p);                    gs->hold = (PRUint8*)hold;                    gs->gather_head = gs->hold;                    gs->gathered += ep-p;                    return 0;                }            }        }        break;        case gif_oom:             ILTRACE(1,("il:gif: reached oom state"));            return MK_OUT_OF_MEMORY;            break;        case gif_error:             ILTRACE(2,("il:gif: reached error state"));            return MK_IMAGE_LOSSAGE;            break;        case gif_stop_animating:            return 0;            break;        default:             ILTRACE(0,("il:gif: unknown state"));            PR_ASSERT(0);            break;        }    }    return 0;}