~ubuntu-branches/ubuntu/raring/qtwebkit-source/raring-proposed

« back to all changes in this revision

Viewing changes to Source/WebCore/platform/image-decoders/gif/GIFImageReader.cpp

  • Committer: Package Import Robot
  • Author(s): Jonathan Riddell
  • Date: 2013-02-18 14:24:18 UTC
  • Revision ID: package-import@ubuntu.com-20130218142418-eon0jmjg3nj438uy
Tags: upstream-2.3
ImportĀ upstreamĀ versionĀ 2.3

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/* -*- Mode: C; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 
2
/* ***** BEGIN LICENSE BLOCK *****
 
3
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 
4
 *
 
5
 * The contents of this file are subject to the Mozilla Public License Version
 
6
 * 1.1 (the "License"); you may not use this file except in compliance with
 
7
 * the License. You may obtain a copy of the License at
 
8
 * http://www.mozilla.org/MPL/
 
9
 *
 
10
 * Software distributed under the License is distributed on an "AS IS" basis,
 
11
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 
12
 * for the specific language governing rights and limitations under the
 
13
 * License.
 
14
 *
 
15
 * The Original Code is mozilla.org code.
 
16
 *
 
17
 * The Initial Developer of the Original Code is
 
18
 * Netscape Communications Corporation.
 
19
 * Portions created by the Initial Developer are Copyright (C) 1998
 
20
 * the Initial Developer. All Rights Reserved.
 
21
 *
 
22
 * Contributor(s):
 
23
 *   Chris Saari <saari@netscape.com>
 
24
 *   Apple Computer
 
25
 *
 
26
 * Alternatively, the contents of this file may be used under the terms of
 
27
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 
28
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 
29
 * in which case the provisions of the GPL or the LGPL are applicable instead
 
30
 * of those above. If you wish to allow use of your version of this file only
 
31
 * under the terms of either the GPL or the LGPL, and not to allow others to
 
32
 * use your version of this file under the terms of the MPL, indicate your
 
33
 * decision by deleting the provisions above and replace them with the notice
 
34
 * and other provisions required by the GPL or the LGPL. If you do not delete
 
35
 * the provisions above, a recipient may use your version of this file under
 
36
 * the terms of any one of the MPL, the GPL or the LGPL.
 
37
 *
 
38
 * ***** END LICENSE BLOCK ***** */
 
39
 
 
40
/*
 
41
The Graphics Interchange Format(c) is the copyright property of CompuServe
 
42
Incorporated. Only CompuServe Incorporated is authorized to define, redefine,
 
43
enhance, alter, modify or change in any way the definition of the format.
 
44
 
 
45
CompuServe Incorporated hereby grants a limited, non-exclusive, royalty-free
 
46
license for the use of the Graphics Interchange Format(sm) in computer
 
47
software; computer software utilizing GIF(sm) must acknowledge ownership of the
 
48
Graphics Interchange Format and its Service Mark by CompuServe Incorporated, in
 
49
User and Technical Documentation. Computer software utilizing GIF, which is
 
50
distributed or may be distributed without User or Technical Documentation must
 
51
display to the screen or printer a message acknowledging ownership of the
 
52
Graphics Interchange Format and the Service Mark by CompuServe Incorporated; in
 
53
this case, the acknowledgement may be displayed in an opening screen or leading
 
54
banner, or a closing screen or trailing banner. A message such as the following
 
55
may be used:
 
56
 
 
57
    "The Graphics Interchange Format(c) is the Copyright property of
 
58
    CompuServe Incorporated. GIF(sm) is a Service Mark property of
 
59
    CompuServe Incorporated."
 
60
 
 
61
For further information, please contact :
 
62
 
 
63
    CompuServe Incorporated
 
64
    Graphics Technology Department
 
65
    5000 Arlington Center Boulevard
 
66
    Columbus, Ohio  43220
 
67
    U. S. A.
 
68
 
 
69
CompuServe Incorporated maintains a mailing list with all those individuals and
 
70
organizations who wish to receive copies of this document when it is corrected
 
71
or revised. This service is offered free of charge; please provide us with your
 
72
mailing address.
 
73
*/
 
74
 
 
75
#include "config.h"
 
76
#include "GIFImageReader.h"
 
77
 
 
78
#include <string.h>
 
79
#include "GIFImageDecoder.h"
 
80
#include "ImageSource.h"
 
81
 
 
82
using WebCore::GIFImageDecoder;
 
83
 
 
84
// Define the Mozilla macro setup so that we can leave the macros alone.
 
85
#define PR_BEGIN_MACRO  do {
 
86
#define PR_END_MACRO    } while (0)
 
87
 
 
88
/*
 
89
 * GETN(n, s) requests at least 'n' bytes available from 'q', at start of state 's'
 
90
 *
 
91
 * Note, the hold will never need to be bigger than 256 bytes to gather up in the hold,
 
92
 * as each GIF block (except colormaps) can never be bigger than 256 bytes.
 
93
 * Colormaps are directly copied in the resp. global_colormap or dynamically allocated local_colormap.
 
94
 * So a fixed buffer in GIFImageReader is good enough.
 
95
 * This buffer is only needed to copy left-over data from one GifWrite call to the next
 
96
 */
 
97
#define GETN(n,s)                    \
 
98
  PR_BEGIN_MACRO                     \
 
99
    bytes_to_consume = (n);      \
 
100
    state = (s);                 \
 
101
  PR_END_MACRO
 
102
 
 
103
/* Get a 16-bit value stored in little-endian format */
 
104
#define GETINT16(p)   ((p)[1]<<8|(p)[0])
 
105
 
 
106
//******************************************************************************
 
107
// Send the data to the display front-end.
 
108
bool GIFImageReader::output_row()
 
109
{
 
110
  GIFFrameReader* gs = frame_reader;
 
111
 
 
112
  int drow_start, drow_end;
 
113
 
 
114
  drow_start = drow_end = gs->irow;
 
115
 
 
116
  /*
 
117
   * Haeberli-inspired hack for interlaced GIFs: Replicate lines while
 
118
   * displaying to diminish the "venetian-blind" effect as the image is
 
119
   * loaded. Adjust pixel vertical positions to avoid the appearance of the
 
120
   * image crawling up the screen as successive passes are drawn.
 
121
   */
 
122
  if (gs->progressive_display && gs->interlaced && gs->ipass < 4) {
 
123
    unsigned row_dup = 0, row_shift = 0;
 
124
 
 
125
    switch (gs->ipass) {
 
126
    case 1:
 
127
      row_dup = 7;
 
128
      row_shift = 3;
 
129
      break;
 
130
    case 2:
 
131
      row_dup = 3;
 
132
      row_shift = 1;
 
133
      break;
 
134
    case 3:
 
135
      row_dup = 1;
 
136
      row_shift = 0;
 
137
      break;
 
138
    default:
 
139
      break;
 
140
    }
 
141
 
 
142
    drow_start -= row_shift;
 
143
    drow_end = drow_start + row_dup;
 
144
 
 
145
    /* Extend if bottom edge isn't covered because of the shift upward. */
 
146
    if (((gs->height - 1) - drow_end) <= row_shift)
 
147
      drow_end = gs->height - 1;
 
148
 
 
149
    /* Clamp first and last rows to upper and lower edge of image. */
 
150
    if (drow_start < 0)
 
151
      drow_start = 0;
 
152
    if ((unsigned)drow_end >= gs->height)
 
153
      drow_end = gs->height - 1;
 
154
  }
 
155
 
 
156
  /* Protect against too much image data */
 
157
  if ((unsigned)drow_start >= gs->height)
 
158
    return true;
 
159
 
 
160
  // CALLBACK: Let the client know we have decoded a row.
 
161
  if (clientptr && frame_reader &&
 
162
      !clientptr->haveDecodedRow(images_count - 1, frame_reader->rowbuf, frame_reader->rowend,
 
163
                                 drow_start, drow_end - drow_start + 1,
 
164
                                 gs->progressive_display && gs->interlaced && gs->ipass > 1))
 
165
    return false;
 
166
 
 
167
  gs->rowp = gs->rowbuf;
 
168
 
 
169
  if (!gs->interlaced)
 
170
    gs->irow++;
 
171
  else {
 
172
    do {
 
173
      switch (gs->ipass)
 
174
      {
 
175
        case 1:
 
176
          gs->irow += 8;
 
177
          if (gs->irow >= gs->height) {
 
178
            gs->ipass++;
 
179
            gs->irow = 4;
 
180
          }
 
181
          break;
 
182
 
 
183
        case 2:
 
184
          gs->irow += 8;
 
185
          if (gs->irow >= gs->height) {
 
186
            gs->ipass++;
 
187
            gs->irow = 2;
 
188
          }
 
189
          break;
 
190
 
 
191
        case 3:
 
192
          gs->irow += 4;
 
193
          if (gs->irow >= gs->height) {
 
194
            gs->ipass++;
 
195
            gs->irow = 1;
 
196
          }
 
197
          break;
 
198
 
 
199
        case 4:
 
200
          gs->irow += 2;
 
201
          if (gs->irow >= gs->height){
 
202
            gs->ipass++;
 
203
            gs->irow = 0;
 
204
          }
 
205
          break;
 
206
 
 
207
        default:
 
208
          break;
 
209
      }
 
210
    } while (gs->irow > (gs->height - 1));
 
211
  }
 
212
 
 
213
  return true;
 
214
}
 
215
 
 
216
//******************************************************************************
 
217
/* Perform Lempel-Ziv-Welch decoding */
 
218
bool GIFImageReader::do_lzw(const unsigned char *q)
 
219
{
 
220
  GIFFrameReader* gs = frame_reader;
 
221
  if (!gs)
 
222
    return true;
 
223
 
 
224
  int code;
 
225
  int incode;
 
226
  const unsigned char *ch;
 
227
  
 
228
  /* Copy all the decoder state variables into locals so the compiler
 
229
   * won't worry about them being aliased.  The locals will be homed
 
230
   * back into the GIF decoder structure when we exit.
 
231
   */
 
232
  int avail       = gs->avail;
 
233
  int bits        = gs->bits;
 
234
  int cnt         = count;
 
235
  int codesize    = gs->codesize;
 
236
  int codemask    = gs->codemask;
 
237
  int oldcode     = gs->oldcode;
 
238
  int clear_code  = gs->clear_code;
 
239
  unsigned char firstchar = gs->firstchar;
 
240
  int datum     = gs->datum;
 
241
 
 
242
  if (!gs->prefix) {
 
243
    gs->prefix = new unsigned short[MAX_BITS];
 
244
    memset(gs->prefix, 0, MAX_BITS * sizeof(short));
 
245
  }
 
246
 
 
247
  unsigned short *prefix  = gs->prefix;
 
248
  unsigned char *stackp   = gs->stackp;
 
249
  unsigned char *suffix   = gs->suffix;
 
250
  unsigned char *stack    = gs->stack;
 
251
  unsigned char *rowp     = gs->rowp;
 
252
  unsigned char *rowend   = gs->rowend;
 
253
  unsigned rows_remaining = gs->rows_remaining;
 
254
 
 
255
  if (rowp == rowend)
 
256
    return true;
 
257
 
 
258
#define OUTPUT_ROW                                                  \
 
259
  PR_BEGIN_MACRO                                                        \
 
260
    if (!output_row())                                                     \
 
261
      return false;                                                        \
 
262
    rows_remaining--;                                                   \
 
263
    rowp = frame_reader->rowp;                                                    \
 
264
    if (!rows_remaining)                                                \
 
265
      goto END;                                                         \
 
266
  PR_END_MACRO
 
267
 
 
268
  for (ch = q; cnt-- > 0; ch++)
 
269
  {
 
270
    /* Feed the next byte into the decoder's 32-bit input buffer. */
 
271
    datum += ((int) *ch) << bits;
 
272
    bits += 8;
 
273
 
 
274
    /* Check for underflow of decoder's 32-bit input buffer. */
 
275
    while (bits >= codesize)
 
276
    {
 
277
      /* Get the leading variable-length symbol from the data stream */
 
278
      code = datum & codemask;
 
279
      datum >>= codesize;
 
280
      bits -= codesize;
 
281
 
 
282
      /* Reset the dictionary to its original state, if requested */
 
283
      if (code == clear_code) {
 
284
        codesize = gs->datasize + 1;
 
285
        codemask = (1 << codesize) - 1;
 
286
        avail = clear_code + 2;
 
287
        oldcode = -1;
 
288
        continue;
 
289
      }
 
290
 
 
291
      /* Check for explicit end-of-stream code */
 
292
      if (code == (clear_code + 1)) {
 
293
        /* end-of-stream should only appear after all image data */
 
294
        if (!rows_remaining)
 
295
          return true;
 
296
        return clientptr ? clientptr->setFailed() : false;
 
297
      }
 
298
 
 
299
      if (oldcode == -1) {
 
300
        *rowp++ = suffix[code];
 
301
        if (rowp == rowend)
 
302
          OUTPUT_ROW;
 
303
 
 
304
        firstchar = oldcode = code;
 
305
        continue;
 
306
      }
 
307
 
 
308
      incode = code;
 
309
      if (code >= avail) {
 
310
        *stackp++ = firstchar;
 
311
        code = oldcode;
 
312
 
 
313
        if (stackp == stack + MAX_BITS)
 
314
          return clientptr ? clientptr->setFailed() : false;
 
315
      }
 
316
 
 
317
      while (code >= clear_code)
 
318
      {
 
319
        if (code >= MAX_BITS || code == prefix[code])
 
320
          return clientptr ? clientptr->setFailed() : false;
 
321
 
 
322
        // Even though suffix[] only holds characters through suffix[avail - 1],
 
323
        // allowing code >= avail here lets us be more tolerant of malformed
 
324
        // data. As long as code < MAX_BITS, the only risk is a garbled image,
 
325
        // which is no worse than refusing to display it.
 
326
        *stackp++ = suffix[code];
 
327
        code = prefix[code];
 
328
 
 
329
        if (stackp == stack + MAX_BITS)
 
330
          return clientptr ? clientptr->setFailed() : false;
 
331
      }
 
332
 
 
333
      *stackp++ = firstchar = suffix[code];
 
334
 
 
335
      /* Define a new codeword in the dictionary. */
 
336
      if (avail < 4096) {
 
337
        prefix[avail] = oldcode;
 
338
        suffix[avail] = firstchar;
 
339
        avail++;
 
340
 
 
341
        /* If we've used up all the codewords of a given length
 
342
         * increase the length of codewords by one bit, but don't
 
343
         * exceed the specified maximum codeword size of 12 bits.
 
344
         */
 
345
        if (((avail & codemask) == 0) && (avail < 4096)) {
 
346
          codesize++;
 
347
          codemask += avail;
 
348
        }
 
349
      }
 
350
      oldcode = incode;
 
351
 
 
352
        /* Copy the decoded data out to the scanline buffer. */
 
353
      do {
 
354
        *rowp++ = *--stackp;
 
355
        if (rowp == rowend) {
 
356
          OUTPUT_ROW;
 
357
        }
 
358
      } while (stackp > stack);
 
359
    }
 
360
  }
 
361
 
 
362
  END:
 
363
 
 
364
  /* Home the local copies of the GIF decoder state variables */
 
365
  gs->avail = avail;
 
366
  gs->bits = bits;
 
367
  gs->codesize = codesize;
 
368
  gs->codemask = codemask;
 
369
  count = cnt;
 
370
  gs->oldcode = oldcode;
 
371
  gs->firstchar = firstchar;
 
372
  gs->datum = datum;
 
373
  gs->stackp = stackp;
 
374
  gs->rowp = rowp;
 
375
  gs->rows_remaining = rows_remaining;
 
376
 
 
377
  return true;
 
378
}
 
379
 
 
380
 
 
381
/******************************************************************************/
 
382
/*
 
383
 * process data arriving from the stream for the gif decoder
 
384
 */
 
385
 
 
386
bool GIFImageReader::read(const unsigned char *buf, unsigned len, 
 
387
                     GIFImageDecoder::GIFQuery query, unsigned haltAtFrame)
 
388
{
 
389
  if (!len) {
 
390
    // No new data has come in since the last call, just ignore this call.
 
391
    return true;
 
392
  }
 
393
 
 
394
  const unsigned char *q = buf;
 
395
 
 
396
  // Add what we have so far to the block
 
397
  // If previous call to me left something in the hold first complete current block
 
398
  // Or if we are filling the colormaps, first complete the colormap
 
399
  unsigned char* p = 0;
 
400
  if (state == gif_global_colormap)
 
401
    p = global_colormap;
 
402
  else if (state == gif_image_colormap)
 
403
    p = frame_reader ? frame_reader->local_colormap : 0;
 
404
  else if (bytes_in_hold)
 
405
    p = hold;
 
406
  else
 
407
    p = 0;
 
408
 
 
409
  if (p || (state == gif_global_colormap) || (state == gif_image_colormap)) {
 
410
    // Add what we have sofar to the block
 
411
    unsigned l = len < bytes_to_consume ? len : bytes_to_consume;
 
412
    if (p)
 
413
        memcpy(p + bytes_in_hold, buf, l);
 
414
 
 
415
    if (l < bytes_to_consume) {
 
416
      // Not enough in 'buf' to complete current block, get more
 
417
      bytes_in_hold += l;
 
418
      bytes_to_consume -= l;
 
419
      if (clientptr)
 
420
        clientptr->decodingHalted(0);
 
421
      return false;
 
422
    }
 
423
    // Reset hold buffer count
 
424
    bytes_in_hold = 0;
 
425
    // Point 'q' to complete block in hold (or in colormap)
 
426
    q = p;
 
427
  }
 
428
 
 
429
  // Invariant:
 
430
  //    'q' is start of current to be processed block (hold, colormap or buf)
 
431
  //    'bytes_to_consume' is number of bytes to consume from 'buf'
 
432
  //    'buf' points to the bytes to be consumed from the input buffer
 
433
  //    'len' is number of bytes left in input buffer from position 'buf'.
 
434
  //    At entrance of the for loop will 'buf' will be moved 'bytes_to_consume'
 
435
  //    to point to next buffer, 'len' is adjusted accordingly.
 
436
  //    So that next round in for loop, q gets pointed to the next buffer.
 
437
 
 
438
  for (;len >= bytes_to_consume; q=buf) {
 
439
    // Eat the current block from the buffer, q keeps pointed at current block
 
440
    buf += bytes_to_consume;
 
441
    len -= bytes_to_consume;
 
442
 
 
443
    switch (state)
 
444
    {
 
445
    case gif_lzw:
 
446
      if (!do_lzw(q))
 
447
        return false; // If do_lzw() encountered an error, it has already called
 
448
                      // clientptr->setFailed().
 
449
      GETN(1, gif_sub_block);
 
450
      break;
 
451
 
 
452
    case gif_lzw_start:
 
453
    {
 
454
      /* Initialize LZW parser/decoder */
 
455
      int datasize = *q;
 
456
      // Since we use a codesize of 1 more than the datasize, we need to ensure
 
457
      // that our datasize is strictly less than the MAX_LZW_BITS value (12).
 
458
      // This sets the largest possible codemask correctly at 4095.
 
459
      if (datasize >= MAX_LZW_BITS)
 
460
        return clientptr ? clientptr->setFailed() : false;
 
461
      int clear_code = 1 << datasize;
 
462
      if (clear_code >= MAX_BITS)
 
463
        return clientptr ? clientptr->setFailed() : false;
 
464
 
 
465
      if (frame_reader) {
 
466
        frame_reader->datasize = datasize;
 
467
        frame_reader->clear_code = clear_code;
 
468
        frame_reader->avail = frame_reader->clear_code + 2;
 
469
        frame_reader->oldcode = -1;
 
470
        frame_reader->codesize = frame_reader->datasize + 1;
 
471
        frame_reader->codemask = (1 << frame_reader->codesize) - 1;
 
472
 
 
473
        frame_reader->datum = frame_reader->bits = 0;
 
474
 
 
475
        /* init the tables */
 
476
        if (!frame_reader->suffix)
 
477
          frame_reader->suffix = new unsigned char[MAX_BITS];
 
478
        // Clearing the whole suffix table lets us be more tolerant of bad data.
 
479
        memset(frame_reader->suffix, 0, MAX_BITS);
 
480
        for (int i = 0; i < frame_reader->clear_code; i++)
 
481
          frame_reader->suffix[i] = i;
 
482
 
 
483
        if (!frame_reader->stack)
 
484
          frame_reader->stack = new unsigned char[MAX_BITS];
 
485
        frame_reader->stackp = frame_reader->stack;
 
486
      }
 
487
 
 
488
      GETN(1, gif_sub_block);
 
489
    }
 
490
    break;
 
491
 
 
492
    /* All GIF files begin with "GIF87a" or "GIF89a" */
 
493
    case gif_type:
 
494
    {
 
495
      if (!strncmp((char*)q, "GIF89a", 6))
 
496
        version = 89;
 
497
      else if (!strncmp((char*)q, "GIF87a", 6))
 
498
        version = 87;
 
499
      else
 
500
        return clientptr ? clientptr->setFailed() : false;
 
501
      GETN(7, gif_global_header);
 
502
    }
 
503
    break;
 
504
 
 
505
    case gif_global_header:
 
506
    {
 
507
      /* This is the height and width of the "screen" or
 
508
       * frame into which images are rendered.  The
 
509
       * individual images can be smaller than the
 
510
       * screen size and located with an origin anywhere
 
511
       * within the screen.
 
512
       */
 
513
 
 
514
      screen_width = GETINT16(q);
 
515
      screen_height = GETINT16(q + 2);
 
516
 
 
517
      // CALLBACK: Inform the decoderplugin of our size.
 
518
      if (clientptr && !clientptr->setSize(screen_width, screen_height))
 
519
        return false;
 
520
      
 
521
      screen_bgcolor = q[5];
 
522
      global_colormap_size = 2<<(q[4]&0x07);
 
523
 
 
524
      if ((q[4] & 0x80) && global_colormap_size > 0) { /* global map */
 
525
        // Get the global colormap
 
526
        const unsigned size = 3*global_colormap_size;
 
527
        
 
528
        // Malloc the color map, but only if we're not just counting frames.
 
529
        if (query != GIFImageDecoder::GIFFrameCountQuery)
 
530
          global_colormap = new unsigned char[size];
 
531
 
 
532
        if (len < size) {
 
533
          // Use 'hold' pattern to get the global colormap
 
534
          GETN(size, gif_global_colormap);
 
535
          break;
 
536
        }
 
537
        
 
538
        // Copy everything and go directly to gif_image_start.
 
539
        if (global_colormap)
 
540
            memcpy(global_colormap, buf, size);
 
541
        buf += size;
 
542
        len -= size;
 
543
      }
 
544
 
 
545
      GETN(1, gif_image_start);
 
546
 
 
547
      // q[6] = Pixel Aspect Ratio
 
548
      //   Not used
 
549
      //   float aspect = (float)((q[6] + 15) / 64.0);
 
550
    }
 
551
    break;
 
552
 
 
553
    case gif_global_colormap:
 
554
      // Everything is already copied into global_colormap
 
555
      GETN(1, gif_image_start);
 
556
    break;
 
557
 
 
558
    case gif_image_start:
 
559
    {
 
560
      if (*q == ';') { /* terminator */
 
561
        GETN(0, gif_done);
 
562
        break;
 
563
      }
 
564
 
 
565
      if (*q == '!') { /* extension */
 
566
        GETN(2, gif_extension);
 
567
        break;
 
568
      }
 
569
 
 
570
      /* If we get anything other than ',' (image separator), '!'
 
571
       * (extension), or ';' (trailer), there is extraneous data
 
572
       * between blocks. The GIF87a spec tells us to keep reading
 
573
       * until we find an image separator, but GIF89a says such
 
574
       * a file is corrupt. We follow GIF89a and bail out. */
 
575
      if (*q != ',')
 
576
        return clientptr ? clientptr->setFailed() : false;
 
577
 
 
578
      GETN(9, gif_image_header);
 
579
    }
 
580
    break;
 
581
 
 
582
    case gif_extension:
 
583
    {
 
584
      count = q[1];
 
585
      gstate es = gif_skip_block;
 
586
 
 
587
      // The GIF spec mandates lengths for three of the extensions below.
 
588
      // However, it's possible for GIFs in the wild to deviate. For example,
 
589
      // some GIFs that embed ICC color profiles using gif_application_extension
 
590
      // violate the spec and treat this extension block like a sort of
 
591
      // "extension + data" block, giving a size greater than 11 and filling the
 
592
      // remaining bytes with data (then following with more data blocks as
 
593
      // needed), instead of placing a true data block just after the 11 byte
 
594
      // extension block.
 
595
      //
 
596
      // Accordingly, if the specified length is larger than the required value,
 
597
      // we use it. If it's smaller, then we enforce the spec value, because the
 
598
      // parsers for these extensions expect to have the specified number of
 
599
      // bytes available, and if we don't ensure that, they could read off the
 
600
      // end of the heap buffer. (In this case, it's likely the GIF is corrupt
 
601
      // and we'll soon fail to decode anyway.)
 
602
      switch (*q)
 
603
      {
 
604
      case 0xf9:
 
605
        es = gif_control_extension;
 
606
        count = std::max(count, 4);
 
607
        break;
 
608
 
 
609
      case 0x01:
 
610
        // ignoring plain text extension
 
611
        count = std::max(count, 12);
 
612
        break;
 
613
 
 
614
      case 0xff:
 
615
        es = gif_application_extension;
 
616
        count = std::max(count, 11);
 
617
        break;
 
618
 
 
619
      case 0xfe:
 
620
        es = gif_consume_comment;
 
621
        break;
 
622
      }
 
623
 
 
624
      if (count)
 
625
        GETN(count, es);
 
626
      else
 
627
        GETN(1, gif_image_start);
 
628
    }
 
629
    break;
 
630
 
 
631
    case gif_consume_block:
 
632
      if (!*q)
 
633
        GETN(1, gif_image_start);
 
634
      else
 
635
        GETN(*q, gif_skip_block);
 
636
    break;
 
637
 
 
638
    case gif_skip_block:
 
639
      GETN(1, gif_consume_block);
 
640
      break;
 
641
 
 
642
    case gif_control_extension:
 
643
    {
 
644
      if (query != GIFImageDecoder::GIFFrameCountQuery) {
 
645
          if (!frame_reader)
 
646
            frame_reader = new GIFFrameReader();
 
647
      }
 
648
 
 
649
      if (frame_reader) {
 
650
        if (*q & 0x1) {
 
651
          frame_reader->tpixel = q[3];
 
652
          frame_reader->is_transparent = true;
 
653
        } else {
 
654
          frame_reader->is_transparent = false;
 
655
          // ignoring gfx control extension
 
656
        }
 
657
        // NOTE: This relies on the values in the FrameDisposalMethod enum
 
658
        // matching those in the GIF spec!
 
659
        int disposal_method = ((*q) >> 2) & 0x7;
 
660
        frame_reader->disposal_method = (WebCore::ImageFrame::FrameDisposalMethod)disposal_method;
 
661
        // Some specs say 3rd bit (value 4), other specs say value 3
 
662
        // Let's choose 3 (the more popular)
 
663
        if (disposal_method == 4)
 
664
          frame_reader->disposal_method = WebCore::ImageFrame::DisposeOverwritePrevious;
 
665
        frame_reader->delay_time = GETINT16(q + 1) * 10;
 
666
      }
 
667
      GETN(1, gif_consume_block);
 
668
    }
 
669
    break;
 
670
 
 
671
    case gif_comment_extension:
 
672
    {
 
673
      if (*q)
 
674
        GETN(*q, gif_consume_comment);
 
675
      else
 
676
        GETN(1, gif_image_start);
 
677
    }
 
678
    break;
 
679
 
 
680
    case gif_consume_comment:
 
681
      GETN(1, gif_comment_extension);
 
682
    break;
 
683
 
 
684
    case gif_application_extension:
 
685
      /* Check for netscape application extension */
 
686
      if (!strncmp((char*)q, "NETSCAPE2.0", 11) ||
 
687
        !strncmp((char*)q, "ANIMEXTS1.0", 11))
 
688
        GETN(1, gif_netscape_extension_block);
 
689
      else
 
690
        GETN(1, gif_consume_block);
 
691
    break;
 
692
 
 
693
    /* Netscape-specific GIF extension: animation looping */
 
694
    case gif_netscape_extension_block:
 
695
      if (*q)
 
696
        GETN(*q, gif_consume_netscape_extension);
 
697
      else
 
698
        GETN(1, gif_image_start);
 
699
    break;
 
700
 
 
701
    /* Parse netscape-specific application extensions */
 
702
    case gif_consume_netscape_extension:
 
703
    {
 
704
      int netscape_extension = q[0] & 7;
 
705
 
 
706
      /* Loop entire animation specified # of times.  Only read the
 
707
         loop count during the first iteration. */
 
708
      if (netscape_extension == 1) {
 
709
        loop_count = GETINT16(q + 1);
 
710
 
 
711
        /* Zero loop count is infinite animation loop request */
 
712
        if (loop_count == 0)
 
713
          loop_count = WebCore::cAnimationLoopInfinite;
 
714
 
 
715
        GETN(1, gif_netscape_extension_block);
 
716
      }
 
717
      /* Wait for specified # of bytes to enter buffer */
 
718
      else if (netscape_extension == 2) {
 
719
        // Don't do this, this extension doesn't exist (isn't used at all) 
 
720
        // and doesn't do anything, as our streaming/buffering takes care of it all...
 
721
        // See: http://semmix.pl/color/exgraf/eeg24.htm
 
722
        GETN(1, gif_netscape_extension_block);
 
723
      } else {
 
724
        // 0,3-7 are yet to be defined netscape extension codes
 
725
        return clientptr ? clientptr->setFailed() : false;
 
726
      }
 
727
 
 
728
      break;
 
729
    }
 
730
 
 
731
    case gif_image_header:
 
732
    {
 
733
      unsigned height, width, x_offset, y_offset;
 
734
      
 
735
      /* Get image offsets, with respect to the screen origin */
 
736
      x_offset = GETINT16(q);
 
737
      y_offset = GETINT16(q + 2);
 
738
 
 
739
      /* Get image width and height. */
 
740
      width  = GETINT16(q + 4);
 
741
      height = GETINT16(q + 6);
 
742
 
 
743
      /* Work around broken GIF files where the logical screen
 
744
       * size has weird width or height.  We assume that GIF87a
 
745
       * files don't contain animations.
 
746
       */
 
747
      if ((images_decoded == 0) &&
 
748
          ((screen_height < height) || (screen_width < width) ||
 
749
           (version == 87)))
 
750
      {
 
751
        screen_height = height;
 
752
        screen_width = width;
 
753
        x_offset = 0;
 
754
        y_offset = 0;
 
755
 
 
756
        // CALLBACK: Inform the decoderplugin of our size.
 
757
        if (clientptr && !clientptr->setSize(screen_width, screen_height))
 
758
          return false;
 
759
      }
 
760
 
 
761
      /* Work around more broken GIF files that have zero image
 
762
         width or height */
 
763
      if (!height || !width) {
 
764
        height = screen_height;
 
765
        width = screen_width;
 
766
        if (!height || !width)
 
767
          return clientptr ? clientptr->setFailed() : false;
 
768
      }
 
769
 
 
770
      if (query == GIFImageDecoder::GIFSizeQuery || haltAtFrame == images_decoded) {
 
771
        // The decoder needs to stop.  Hand back the number of bytes we consumed from
 
772
        // buffer minus 9 (the amount we consumed to read the header).
 
773
        if (clientptr)
 
774
            clientptr->decodingHalted(len + 9);
 
775
        GETN(9, gif_image_header);
 
776
        return true;
 
777
      }
 
778
      
 
779
      images_count = images_decoded + 1;
 
780
 
 
781
      if (query == GIFImageDecoder::GIFFullQuery && !frame_reader)
 
782
        frame_reader = new GIFFrameReader();
 
783
 
 
784
      if (frame_reader) {
 
785
        frame_reader->x_offset = x_offset;
 
786
        frame_reader->y_offset = y_offset;
 
787
        frame_reader->height = height;
 
788
        frame_reader->width = width;
 
789
 
 
790
        /* This case will never be taken if this is the first image */
 
791
        /* being decoded. If any of the later images are larger     */
 
792
        /* than the screen size, we need to reallocate buffers.     */
 
793
        if (screen_width < width) {
 
794
          /* XXX Deviant! */
 
795
 
 
796
          delete []frame_reader->rowbuf;
 
797
          screen_width = width;
 
798
          frame_reader->rowbuf = new unsigned char[screen_width];
 
799
        } else if (!frame_reader->rowbuf) {
 
800
          frame_reader->rowbuf = new unsigned char[screen_width];
 
801
        }
 
802
 
 
803
        if (!frame_reader->rowbuf)
 
804
          return clientptr ? clientptr->setFailed() : false;
 
805
        if (screen_height < height)
 
806
          screen_height = height;
 
807
 
 
808
        if (q[8] & 0x40) {
 
809
          frame_reader->interlaced = true;
 
810
          frame_reader->ipass = 1;
 
811
        } else {
 
812
          frame_reader->interlaced = false;
 
813
          frame_reader->ipass = 0;
 
814
        }
 
815
 
 
816
        if (images_decoded == 0) {
 
817
          frame_reader->progressive_display = true;
 
818
        } else {
 
819
          /* Overlaying interlaced, transparent GIFs over
 
820
             existing image data using the Haeberli display hack
 
821
             requires saving the underlying image in order to
 
822
             avoid jaggies at the transparency edges.  We are
 
823
             unprepared to deal with that, so don't display such
 
824
             images progressively */
 
825
          frame_reader->progressive_display = false;
 
826
        }
 
827
 
 
828
        /* Clear state from last image */
 
829
        frame_reader->irow = 0;
 
830
        frame_reader->rows_remaining = frame_reader->height;
 
831
        frame_reader->rowend = frame_reader->rowbuf + frame_reader->width;
 
832
        frame_reader->rowp = frame_reader->rowbuf;
 
833
 
 
834
        /* bits per pixel is q[8]&0x07 */
 
835
      }
 
836
      
 
837
      if (q[8] & 0x80) /* has a local colormap? */
 
838
      {
 
839
        int num_colors = 2 << (q[8] & 0x7);
 
840
        const unsigned size = 3*num_colors;
 
841
        unsigned char *map = frame_reader ? frame_reader->local_colormap : 0;
 
842
        if (frame_reader && (!map || (num_colors > frame_reader->local_colormap_size))) {
 
843
          delete []map;
 
844
          map = new unsigned char[size];
 
845
          if (!map)
 
846
            return clientptr ? clientptr->setFailed() : false;
 
847
        }
 
848
 
 
849
        /* Switch to the new local palette after it loads */
 
850
        if (frame_reader) {
 
851
          frame_reader->local_colormap = map;
 
852
          frame_reader->local_colormap_size = num_colors;
 
853
          frame_reader->is_local_colormap_defined = true;
 
854
        }
 
855
 
 
856
        if (len < size) {
 
857
          // Use 'hold' pattern to get the image colormap
 
858
          GETN(size, gif_image_colormap);
 
859
          break;
 
860
        }
 
861
        // Copy everything and directly go to gif_lzw_start
 
862
        if (frame_reader)
 
863
          memcpy(frame_reader->local_colormap, buf, size);
 
864
        buf += size;
 
865
        len -= size;
 
866
      } else if (frame_reader) {
 
867
        /* Switch back to the global palette */
 
868
        frame_reader->is_local_colormap_defined = false;
 
869
      }
 
870
      GETN(1, gif_lzw_start);
 
871
    }
 
872
    break;
 
873
 
 
874
    case gif_image_colormap:
 
875
      // Everything is already copied into local_colormap
 
876
      GETN(1, gif_lzw_start);
 
877
    break;
 
878
 
 
879
    case gif_sub_block:
 
880
    {
 
881
      if ((count = *q) != 0)
 
882
      /* Still working on the same image: Process next LZW data block */
 
883
      {
 
884
        /* Make sure there are still rows left. If the GIF data */
 
885
        /* is corrupt, we may not get an explicit terminator.   */
 
886
        if (frame_reader && frame_reader->rows_remaining == 0) {
 
887
          /* This is an illegal GIF, but we remain tolerant. */
 
888
          GETN(1, gif_sub_block);
 
889
        }
 
890
        GETN(count, gif_lzw);
 
891
      }
 
892
      else
 
893
      /* See if there are any more images in this sequence. */
 
894
      {
 
895
        images_decoded++;
 
896
 
 
897
        // CALLBACK: The frame is now complete.
 
898
        if (clientptr && frame_reader && !clientptr->frameComplete(images_decoded - 1, frame_reader->delay_time, frame_reader->disposal_method))
 
899
          return false; // frameComplete() has already called
 
900
                        // clientptr->setFailed().
 
901
 
 
902
        /* Clear state from this image */
 
903
        if (frame_reader) {
 
904
            frame_reader->is_local_colormap_defined = false;
 
905
            frame_reader->is_transparent = false;
 
906
        }
 
907
 
 
908
        GETN(1, gif_image_start);
 
909
      }
 
910
    }
 
911
    break;
 
912
 
 
913
    case gif_done:
 
914
      // When the GIF is done, we can stop.
 
915
      if (clientptr)
 
916
        clientptr->gifComplete();
 
917
      return true;
 
918
 
 
919
    // We shouldn't ever get here.
 
920
    default:
 
921
      break;
 
922
    }
 
923
  }
 
924
 
 
925
  // Copy the leftover into gs->hold
 
926
  bytes_in_hold = len;
 
927
  if (len) {
 
928
    // Add what we have sofar to the block
 
929
    unsigned char* p;
 
930
    if (state == gif_global_colormap)
 
931
      p = global_colormap;
 
932
    else if (state == gif_image_colormap)
 
933
      p = frame_reader ? frame_reader->local_colormap : 0;
 
934
    else
 
935
      p = hold;
 
936
    if (p)
 
937
      memcpy(p, buf, len);
 
938
    bytes_to_consume -= len;
 
939
  }
 
940
 
 
941
  if (clientptr)
 
942
    clientptr->decodingHalted(0);
 
943
  return false;
 
944
}