Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(181)

Side by Side Diff: third_party/WebKit/Source/platform/image-decoders/gif/GIFImageReader.cpp

Issue 2565323003: Move gif image decoder to SkCodec (Closed)
Patch Set: Created 4 years ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
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 "platform/image-decoders/gif/GIFImageReader.h"
76
77 #include "wtf/PtrUtil.h"
78 #include <string.h>
79
80 using blink::GIFImageDecoder;
81
82 // GETN(n, s) requests at least 'n' bytes available from 'q', at start of state
83 // 's'.
84 //
85 // Note: the hold will never need to be bigger than 256 bytes, as each GIF block
86 // (except colormaps) can never be bigger than 256 bytes. Colormaps are directly
87 // copied in the resp. global_colormap or dynamically allocated local_colormap,
88 // so a fixed buffer in GIFImageReader is good enough. This buffer is only
89 // needed to copy left-over data from one GifWrite call to the next.
90 #define GETN(n, s) \
91 do { \
92 m_bytesToConsume = (n); \
93 m_state = (s); \
94 } while (0)
95
96 // Get a 16-bit value stored in little-endian format.
97 #define GETINT16(p) ((p)[1] << 8 | (p)[0])
98
99 // Send the data to the display front-end.
100 bool GIFLZWContext::outputRow(GIFRow::const_iterator rowBegin) {
101 int drowStart = irow;
102 int drowEnd = irow;
103
104 // Haeberli-inspired hack for interlaced GIFs: Replicate lines while
105 // displaying to diminish the "venetian-blind" effect as the image is
106 // loaded. Adjust pixel vertical positions to avoid the appearance of the
107 // image crawling up the screen as successive passes are drawn.
108 if (m_frameContext->progressiveDisplay() && m_frameContext->interlaced() &&
109 ipass < 4) {
110 unsigned rowDup = 0;
111 unsigned rowShift = 0;
112
113 switch (ipass) {
114 case 1:
115 rowDup = 7;
116 rowShift = 3;
117 break;
118 case 2:
119 rowDup = 3;
120 rowShift = 1;
121 break;
122 case 3:
123 rowDup = 1;
124 rowShift = 0;
125 break;
126 default:
127 break;
128 }
129
130 drowStart -= rowShift;
131 drowEnd = drowStart + rowDup;
132
133 // Extend if bottom edge isn't covered because of the shift upward.
134 if (((m_frameContext->height() - 1) - drowEnd) <= rowShift)
135 drowEnd = m_frameContext->height() - 1;
136
137 // Clamp first and last rows to upper and lower edge of image.
138 if (drowStart < 0)
139 drowStart = 0;
140
141 if ((unsigned)drowEnd >= m_frameContext->height())
142 drowEnd = m_frameContext->height() - 1;
143 }
144
145 // Protect against too much image data.
146 if ((unsigned)drowStart >= m_frameContext->height())
147 return true;
148
149 // CALLBACK: Let the client know we have decoded a row.
150 if (!m_client->haveDecodedRow(m_frameContext->frameId(), rowBegin,
151 m_frameContext->width(), drowStart,
152 drowEnd - drowStart + 1,
153 m_frameContext->progressiveDisplay() &&
154 m_frameContext->interlaced() && ipass > 1))
155 return false;
156
157 if (!m_frameContext->interlaced())
158 irow++;
159 else {
160 do {
161 switch (ipass) {
162 case 1:
163 irow += 8;
164 if (irow >= m_frameContext->height()) {
165 ipass++;
166 irow = 4;
167 }
168 break;
169
170 case 2:
171 irow += 8;
172 if (irow >= m_frameContext->height()) {
173 ipass++;
174 irow = 2;
175 }
176 break;
177
178 case 3:
179 irow += 4;
180 if (irow >= m_frameContext->height()) {
181 ipass++;
182 irow = 1;
183 }
184 break;
185
186 case 4:
187 irow += 2;
188 if (irow >= m_frameContext->height()) {
189 ipass++;
190 irow = 0;
191 }
192 break;
193
194 default:
195 break;
196 }
197 } while (irow > (m_frameContext->height() - 1));
198 }
199 return true;
200 }
201
202 // Performs Lempel-Ziv-Welch decoding. Returns whether decoding was successful.
203 // If successful, the block will have been completely consumed and/or
204 // rowsRemaining will be 0.
205 bool GIFLZWContext::doLZW(const unsigned char* block, size_t bytesInBlock) {
206 const size_t width = m_frameContext->width();
207
208 if (rowIter == rowBuffer.end())
209 return true;
210
211 for (const unsigned char* ch = block; bytesInBlock-- > 0; ch++) {
212 // Feed the next byte into the decoder's 32-bit input buffer.
213 datum += ((int)*ch) << bits;
214 bits += 8;
215
216 // Check for underflow of decoder's 32-bit input buffer.
217 while (bits >= codesize) {
218 // Get the leading variable-length symbol from the data stream.
219 int code = datum & codemask;
220 datum >>= codesize;
221 bits -= codesize;
222
223 // Reset the dictionary to its original state, if requested.
224 if (code == clearCode) {
225 codesize = m_frameContext->dataSize() + 1;
226 codemask = (1 << codesize) - 1;
227 avail = clearCode + 2;
228 oldcode = -1;
229 continue;
230 }
231
232 // Check for explicit end-of-stream code.
233 if (code == (clearCode + 1)) {
234 // end-of-stream should only appear after all image data.
235 if (!rowsRemaining)
236 return true;
237 return false;
238 }
239
240 const int tempCode = code;
241 unsigned short codeLength = 0;
242 if (code < avail) {
243 // This is a pre-existing code, so we already know what it
244 // encodes.
245 codeLength = suffixLength[code];
246 rowIter += codeLength;
247 } else if (code == avail && oldcode != -1) {
248 // This is a new code just being added to the dictionary.
249 // It must encode the contents of the previous code, plus
250 // the first character of the previous code again.
251 codeLength = suffixLength[oldcode] + 1;
252 rowIter += codeLength;
253 *--rowIter = firstchar;
254 code = oldcode;
255 } else {
256 // This is an invalid code. The dictionary is just initialized
257 // and the code is incomplete. We don't know how to handle
258 // this case.
259 return false;
260 }
261
262 while (code >= clearCode) {
263 *--rowIter = suffix[code];
264 code = prefix[code];
265 }
266
267 *--rowIter = firstchar = suffix[code];
268
269 // Define a new codeword in the dictionary as long as we've read
270 // more than one value from the stream.
271 if (avail < MAX_DICTIONARY_ENTRIES && oldcode != -1) {
272 prefix[avail] = oldcode;
273 suffix[avail] = firstchar;
274 suffixLength[avail] = suffixLength[oldcode] + 1;
275 ++avail;
276
277 // If we've used up all the codewords of a given length
278 // increase the length of codewords by one bit, but don't
279 // exceed the specified maximum codeword size.
280 if (!(avail & codemask) && avail < MAX_DICTIONARY_ENTRIES) {
281 ++codesize;
282 codemask += avail;
283 }
284 }
285 oldcode = tempCode;
286 rowIter += codeLength;
287
288 // Output as many rows as possible.
289 GIFRow::iterator rowBegin = rowBuffer.begin();
290 for (; rowBegin + width <= rowIter; rowBegin += width) {
291 if (!outputRow(rowBegin))
292 return false;
293 rowsRemaining--;
294 if (!rowsRemaining)
295 return true;
296 }
297
298 if (rowBegin != rowBuffer.begin()) {
299 // Move the remaining bytes to the beginning of the buffer.
300 const size_t bytesToCopy = rowIter - rowBegin;
301 memcpy(rowBuffer.begin(), rowBegin, bytesToCopy);
302 rowIter = rowBuffer.begin() + bytesToCopy;
303 }
304 }
305 }
306 return true;
307 }
308
309 void GIFColorMap::buildTable(blink::FastSharedBufferReader* reader) {
310 if (!m_isDefined || !m_table.isEmpty())
311 return;
312
313 RELEASE_ASSERT(m_position + m_colors * BYTES_PER_COLORMAP_ENTRY <=
314 reader->size());
315 ASSERT(m_colors <= MAX_COLORS);
316 char buffer[MAX_COLORS * BYTES_PER_COLORMAP_ENTRY];
317 const unsigned char* srcColormap =
318 reinterpret_cast<const unsigned char*>(reader->getConsecutiveData(
319 m_position, m_colors * BYTES_PER_COLORMAP_ENTRY, buffer));
320 m_table.resize(m_colors);
321 for (Table::iterator iter = m_table.begin(); iter != m_table.end(); ++iter) {
322 *iter = SkPackARGB32NoCheck(255, srcColormap[0], srcColormap[1],
323 srcColormap[2]);
324 srcColormap += BYTES_PER_COLORMAP_ENTRY;
325 }
326 }
327
328 // Decodes this frame. |frameDecoded| will be set to true if the entire frame is
329 // decoded. Returns true if decoding progressed further than before without
330 // error, or there is insufficient new data to decode further. Otherwise, a
331 // decoding error occurred; returns false in this case.
332 bool GIFFrameContext::decode(blink::FastSharedBufferReader* reader,
333 blink::GIFImageDecoder* client,
334 bool* frameDecoded) {
335 m_localColorMap.buildTable(reader);
336
337 *frameDecoded = false;
338 if (!m_lzwContext) {
339 // Wait for more data to properly initialize GIFLZWContext.
340 if (!isDataSizeDefined() || !isHeaderDefined())
341 return true;
342
343 m_lzwContext = makeUnique<GIFLZWContext>(client, this);
344 if (!m_lzwContext->prepareToDecode()) {
345 m_lzwContext.reset();
346 return false;
347 }
348
349 m_currentLzwBlock = 0;
350 }
351
352 // Some bad GIFs have extra blocks beyond the last row, which we don't want to
353 // decode.
354 while (m_currentLzwBlock < m_lzwBlocks.size() &&
355 m_lzwContext->hasRemainingRows()) {
356 size_t blockPosition = m_lzwBlocks[m_currentLzwBlock].blockPosition;
357 size_t blockSize = m_lzwBlocks[m_currentLzwBlock].blockSize;
358 if (blockPosition + blockSize > reader->size())
359 return false;
360
361 while (blockSize) {
362 const char* segment = 0;
363 size_t segmentLength = reader->getSomeData(segment, blockPosition);
364 size_t decodeSize = std::min(segmentLength, blockSize);
365 if (!m_lzwContext->doLZW(reinterpret_cast<const unsigned char*>(segment),
366 decodeSize))
367 return false;
368 blockPosition += decodeSize;
369 blockSize -= decodeSize;
370 }
371 ++m_currentLzwBlock;
372 }
373
374 // If this frame is data complete then the previous loop must have completely
375 // decoded all LZW blocks.
376 // There will be no more decoding for this frame so it's time to cleanup.
377 if (isComplete()) {
378 *frameDecoded = true;
379 m_lzwContext.reset();
380 }
381 return true;
382 }
383
384 // Decodes a frame using GIFFrameContext:decode(). Returns true if decoding has
385 // progressed, or false if an error has occurred.
386 bool GIFImageReader::decode(size_t frameIndex) {
387 blink::FastSharedBufferReader reader(m_data);
388 m_globalColorMap.buildTable(&reader);
389
390 bool frameDecoded = false;
391 GIFFrameContext* currentFrame = m_frames[frameIndex].get();
392
393 return currentFrame->decode(&reader, m_client, &frameDecoded) &&
394 (!frameDecoded || m_client->frameComplete(frameIndex));
395 }
396
397 bool GIFImageReader::parse(GIFImageDecoder::GIFParseQuery query) {
398 if (m_bytesRead >= m_data->size()) {
399 // This data has already been parsed. For example, in deferred
400 // decoding, a DecodingImageGenerator with more data may have already
401 // used this same ImageDecoder to decode. This can happen if two
402 // SkImages created by a DeferredImageDecoder are drawn/prerolled
403 // out of order (with respect to how much data they had at creation
404 // time).
405 return !m_client->failed();
406 }
407
408 return parseData(m_bytesRead, m_data->size() - m_bytesRead, query);
409 }
410
411 // Parse incoming GIF data stream into internal data structures.
412 // Return true if parsing has progressed or there is not enough data.
413 // Return false if a fatal error is encountered.
414 bool GIFImageReader::parseData(size_t dataPosition,
415 size_t len,
416 GIFImageDecoder::GIFParseQuery query) {
417 if (!len) {
418 // No new data has come in since the last call, just ignore this call.
419 return true;
420 }
421
422 if (len < m_bytesToConsume)
423 return true;
424
425 blink::FastSharedBufferReader reader(m_data);
426
427 // A read buffer of 16 bytes is enough to accomodate all possible reads for
428 // parsing.
429 char readBuffer[16];
430
431 // Read as many components from |m_data| as possible. At the beginning of each
432 // iteration, |dataPosition| is advanced by m_bytesToConsume to point to the
433 // next component. |len| is decremented accordingly.
434 while (len >= m_bytesToConsume) {
435 const size_t currentComponentPosition = dataPosition;
436
437 // Mark the current component as consumed. Note that currentComponent will
438 // remain pointed at this component until the next loop iteration.
439 dataPosition += m_bytesToConsume;
440 len -= m_bytesToConsume;
441
442 switch (m_state) {
443 case GIFLZW:
444 ASSERT(!m_frames.isEmpty());
445 // m_bytesToConsume is the current component size because it hasn't been
446 // updated.
447 m_frames.back()->addLzwBlock(currentComponentPosition,
448 m_bytesToConsume);
449 GETN(1, GIFSubBlock);
450 break;
451
452 case GIFLZWStart: {
453 ASSERT(!m_frames.isEmpty());
454 m_frames.back()->setDataSize(static_cast<unsigned char>(
455 reader.getOneByte(currentComponentPosition)));
456 GETN(1, GIFSubBlock);
457 break;
458 }
459
460 case GIFType: {
461 const char* currentComponent =
462 reader.getConsecutiveData(currentComponentPosition, 6, readBuffer);
463
464 // All GIF files begin with "GIF87a" or "GIF89a".
465 if (!memcmp(currentComponent, "GIF89a", 6))
466 m_version = 89;
467 else if (!memcmp(currentComponent, "GIF87a", 6))
468 m_version = 87;
469 else
470 return false;
471 GETN(7, GIFGlobalHeader);
472 break;
473 }
474
475 case GIFGlobalHeader: {
476 const unsigned char* currentComponent =
477 reinterpret_cast<const unsigned char*>(reader.getConsecutiveData(
478 currentComponentPosition, 5, readBuffer));
479
480 // This is the height and width of the "screen" or frame into which
481 // images are rendered. The individual images can be smaller than
482 // the screen size and located with an origin anywhere within the
483 // screen.
484 // Note that we don't inform the client of the size yet, as it might
485 // change after we read the first frame's image header.
486 m_screenWidth = GETINT16(currentComponent);
487 m_screenHeight = GETINT16(currentComponent + 2);
488
489 const size_t globalColorMapColors = 2 << (currentComponent[4] & 0x07);
490
491 if ((currentComponent[4] & 0x80) &&
492 globalColorMapColors > 0) { /* global map */
493 m_globalColorMap.setTablePositionAndSize(dataPosition,
494 globalColorMapColors);
495 GETN(BYTES_PER_COLORMAP_ENTRY * globalColorMapColors,
496 GIFGlobalColormap);
497 break;
498 }
499
500 GETN(1, GIFImageStart);
501 break;
502 }
503
504 case GIFGlobalColormap: {
505 m_globalColorMap.setDefined();
506 GETN(1, GIFImageStart);
507 break;
508 }
509
510 case GIFImageStart: {
511 const char currentComponent =
512 reader.getOneByte(currentComponentPosition);
513
514 if (currentComponent == '!') { // extension.
515 GETN(2, GIFExtension);
516 break;
517 }
518
519 if (currentComponent == ',') { // image separator.
520 GETN(9, GIFImageHeader);
521 break;
522 }
523
524 // If we get anything other than ',' (image separator), '!'
525 // (extension), or ';' (trailer), there is extraneous data
526 // between blocks. The GIF87a spec tells us to keep reading
527 // until we find an image separator, but GIF89a says such
528 // a file is corrupt. We follow Mozilla's implementation and
529 // proceed as if the file were correctly terminated, so the
530 // GIF will display.
531 GETN(0, GIFDone);
532 break;
533 }
534
535 case GIFExtension: {
536 const unsigned char* currentComponent =
537 reinterpret_cast<const unsigned char*>(reader.getConsecutiveData(
538 currentComponentPosition, 2, readBuffer));
539
540 size_t bytesInBlock = currentComponent[1];
541 GIFState exceptionState = GIFSkipBlock;
542
543 switch (*currentComponent) {
544 case 0xf9:
545 exceptionState = GIFControlExtension;
546 // The GIF spec mandates that the GIFControlExtension header block
547 // length is 4 bytes, and the parser for this block reads 4 bytes,
548 // so we must enforce that the buffer contains at least this many
549 // bytes. If the GIF specifies a different length, we allow that, so
550 // long as it's larger; the additional data will simply be ignored.
551 bytesInBlock = std::max(bytesInBlock, static_cast<size_t>(4));
552 break;
553
554 // The GIF spec also specifies the lengths of the following two
555 // extensions' headers (as 12 and 11 bytes, respectively). Because we
556 // ignore the plain text extension entirely and sanity-check the
557 // actual length of the application extension header before reading
558 // it, we allow GIFs to deviate from these values in either direction.
559 // This is important for real-world compatibility, as GIFs in the wild
560 // exist with application extension headers that are both shorter and
561 // longer than 11 bytes.
562 case 0x01:
563 // ignoring plain text extension
564 break;
565
566 case 0xff:
567 exceptionState = GIFApplicationExtension;
568 break;
569
570 case 0xfe:
571 exceptionState = GIFConsumeComment;
572 break;
573 }
574
575 if (bytesInBlock)
576 GETN(bytesInBlock, exceptionState);
577 else
578 GETN(1, GIFImageStart);
579 break;
580 }
581
582 case GIFConsumeBlock: {
583 const unsigned char currentComponent = static_cast<unsigned char>(
584 reader.getOneByte(currentComponentPosition));
585 if (!currentComponent)
586 GETN(1, GIFImageStart);
587 else
588 GETN(currentComponent, GIFSkipBlock);
589 break;
590 }
591
592 case GIFSkipBlock: {
593 GETN(1, GIFConsumeBlock);
594 break;
595 }
596
597 case GIFControlExtension: {
598 const unsigned char* currentComponent =
599 reinterpret_cast<const unsigned char*>(reader.getConsecutiveData(
600 currentComponentPosition, 4, readBuffer));
601
602 addFrameIfNecessary();
603 GIFFrameContext* currentFrame = m_frames.back().get();
604 if (*currentComponent & 0x1)
605 currentFrame->setTransparentPixel(currentComponent[3]);
606
607 // We ignore the "user input" bit.
608
609 // NOTE: This relies on the values in the FrameDisposalMethod enum
610 // matching those in the GIF spec!
611 int disposalMethod = ((*currentComponent) >> 2) & 0x7;
612 if (disposalMethod < 4) {
613 currentFrame->setDisposalMethod(
614 static_cast<blink::ImageFrame::DisposalMethod>(disposalMethod));
615 } else if (disposalMethod == 4) {
616 // Some specs say that disposal method 3 is "overwrite previous",
617 // others that setting the third bit of the field (i.e. method 4) is.
618 // We map both to the same value.
619 currentFrame->setDisposalMethod(
620 blink::ImageFrame::DisposeOverwritePrevious);
621 }
622 currentFrame->setDelayTime(GETINT16(currentComponent + 1) * 10);
623 GETN(1, GIFConsumeBlock);
624 break;
625 }
626
627 case GIFCommentExtension: {
628 const unsigned char currentComponent = static_cast<unsigned char>(
629 reader.getOneByte(currentComponentPosition));
630 if (currentComponent)
631 GETN(currentComponent, GIFConsumeComment);
632 else
633 GETN(1, GIFImageStart);
634 break;
635 }
636
637 case GIFConsumeComment: {
638 GETN(1, GIFCommentExtension);
639 break;
640 }
641
642 case GIFApplicationExtension: {
643 // Check for netscape application extension.
644 if (m_bytesToConsume == 11) {
645 const unsigned char* currentComponent =
646 reinterpret_cast<const unsigned char*>(reader.getConsecutiveData(
647 currentComponentPosition, 11, readBuffer));
648
649 if (!memcmp(currentComponent, "NETSCAPE2.0", 11) ||
650 !memcmp(currentComponent, "ANIMEXTS1.0", 11))
651 GETN(1, GIFNetscapeExtensionBlock);
652 }
653
654 if (m_state != GIFNetscapeExtensionBlock)
655 GETN(1, GIFConsumeBlock);
656 break;
657 }
658
659 // Netscape-specific GIF extension: animation looping.
660 case GIFNetscapeExtensionBlock: {
661 const int currentComponent = static_cast<unsigned char>(
662 reader.getOneByte(currentComponentPosition));
663 // GIFConsumeNetscapeExtension always reads 3 bytes from the stream; we
664 // should at least wait for this amount.
665 if (currentComponent)
666 GETN(std::max(3, currentComponent), GIFConsumeNetscapeExtension);
667 else
668 GETN(1, GIFImageStart);
669 break;
670 }
671
672 // Parse netscape-specific application extensions
673 case GIFConsumeNetscapeExtension: {
674 const unsigned char* currentComponent =
675 reinterpret_cast<const unsigned char*>(reader.getConsecutiveData(
676 currentComponentPosition, 3, readBuffer));
677
678 int netscapeExtension = currentComponent[0] & 7;
679
680 // Loop entire animation specified # of times. Only read the loop count
681 // during the first iteration.
682 if (netscapeExtension == 1) {
683 m_loopCount = GETINT16(currentComponent + 1);
684
685 // Zero loop count is infinite animation loop request.
686 if (!m_loopCount)
687 m_loopCount = blink::cAnimationLoopInfinite;
688
689 GETN(1, GIFNetscapeExtensionBlock);
690 } else if (netscapeExtension == 2) {
691 // Wait for specified # of bytes to enter buffer.
692
693 // Don't do this, this extension doesn't exist (isn't used at all)
694 // and doesn't do anything, as our streaming/buffering takes care of
695 // it all. See http://semmix.pl/color/exgraf/eeg24.htm .
696 GETN(1, GIFNetscapeExtensionBlock);
697 } else {
698 // 0,3-7 are yet to be defined netscape extension codes
699 return false;
700 }
701 break;
702 }
703
704 case GIFImageHeader: {
705 unsigned height, width, xOffset, yOffset;
706 const unsigned char* currentComponent =
707 reinterpret_cast<const unsigned char*>(reader.getConsecutiveData(
708 currentComponentPosition, 9, readBuffer));
709
710 /* Get image offsets, with respect to the screen origin */
711 xOffset = GETINT16(currentComponent);
712 yOffset = GETINT16(currentComponent + 2);
713
714 /* Get image width and height. */
715 width = GETINT16(currentComponent + 4);
716 height = GETINT16(currentComponent + 6);
717
718 // Some GIF files have frames that don't fit in the specified
719 // overall image size. For the first frame, we can simply enlarge
720 // the image size to allow the frame to be visible. We can't do
721 // this on subsequent frames because the rest of the decoding
722 // infrastructure assumes the image size won't change as we
723 // continue decoding, so any subsequent frames that are even
724 // larger will be cropped.
725 // Luckily, handling just the first frame is sufficient to deal
726 // with most cases, e.g. ones where the image size is erroneously
727 // set to zero, since usually the first frame completely fills
728 // the image.
729 if (currentFrameIsFirstFrame()) {
730 m_screenHeight = std::max(m_screenHeight, yOffset + height);
731 m_screenWidth = std::max(m_screenWidth, xOffset + width);
732 }
733
734 // Inform the client of the final size.
735 if (!m_sentSizeToClient && m_client &&
736 !m_client->setSize(m_screenWidth, m_screenHeight))
737 return false;
738 m_sentSizeToClient = true;
739
740 if (query == GIFImageDecoder::GIFSizeQuery) {
741 // The decoder needs to stop. Hand back the number of bytes we
742 // consumed from the buffer minus 9 (the amount we consumed to read
743 // the header).
744 setRemainingBytes(len + 9);
745 GETN(9, GIFImageHeader);
746 return true;
747 }
748
749 addFrameIfNecessary();
750 GIFFrameContext* currentFrame = m_frames.back().get();
751
752 currentFrame->setHeaderDefined();
753
754 // Work around more broken GIF files that have zero image width or
755 // height.
756 if (!height || !width) {
757 height = m_screenHeight;
758 width = m_screenWidth;
759 if (!height || !width)
760 return false;
761 }
762 currentFrame->setRect(xOffset, yOffset, width, height);
763 currentFrame->setInterlaced(currentComponent[8] & 0x40);
764
765 // Overlaying interlaced, transparent GIFs over
766 // existing image data using the Haeberli display hack
767 // requires saving the underlying image in order to
768 // avoid jaggies at the transparency edges. We are
769 // unprepared to deal with that, so don't display such
770 // images progressively. Which means only the first
771 // frame can be progressively displayed.
772 // FIXME: It is possible that a non-transparent frame
773 // can be interlaced and progressively displayed.
774 currentFrame->setProgressiveDisplay(currentFrameIsFirstFrame());
775
776 const bool isLocalColormapDefined = currentComponent[8] & 0x80;
777 if (isLocalColormapDefined) {
778 // The three low-order bits of currentComponent[8] specify the bits
779 // per pixel.
780 const size_t numColors = 2 << (currentComponent[8] & 0x7);
781 currentFrame->localColorMap().setTablePositionAndSize(dataPosition,
782 numColors);
783 GETN(BYTES_PER_COLORMAP_ENTRY * numColors, GIFImageColormap);
784 break;
785 }
786
787 GETN(1, GIFLZWStart);
788 break;
789 }
790
791 case GIFImageColormap: {
792 ASSERT(!m_frames.isEmpty());
793 m_frames.back()->localColorMap().setDefined();
794 GETN(1, GIFLZWStart);
795 break;
796 }
797
798 case GIFSubBlock: {
799 const size_t bytesInBlock = static_cast<unsigned char>(
800 reader.getOneByte(currentComponentPosition));
801 if (bytesInBlock)
802 GETN(bytesInBlock, GIFLZW);
803 else {
804 // Finished parsing one frame; Process next frame.
805 ASSERT(!m_frames.isEmpty());
806 // Note that some broken GIF files do not have enough LZW blocks to
807 // fully decode all rows; we treat this case as "frame complete".
808 m_frames.back()->setComplete();
809 GETN(1, GIFImageStart);
810 }
811 break;
812 }
813
814 case GIFDone: {
815 m_parseCompleted = true;
816 return true;
817 }
818
819 default:
820 // We shouldn't ever get here.
821 return false;
822 break;
823 }
824 }
825
826 setRemainingBytes(len);
827 return true;
828 }
829
830 void GIFImageReader::setRemainingBytes(size_t remainingBytes) {
831 ASSERT(remainingBytes <= m_data->size());
832 m_bytesRead = m_data->size() - remainingBytes;
833 }
834
835 void GIFImageReader::addFrameIfNecessary() {
836 if (m_frames.isEmpty() || m_frames.back()->isComplete())
837 m_frames.append(wrapUnique(new GIFFrameContext(m_frames.size())));
838 }
839
840 // FIXME: Move this method to close to doLZW().
841 bool GIFLZWContext::prepareToDecode() {
842 ASSERT(m_frameContext->isDataSizeDefined() &&
843 m_frameContext->isHeaderDefined());
844
845 // Since we use a codesize of 1 more than the datasize, we need to ensure
846 // that our datasize is strictly less than the MAX_DICTIONARY_ENTRY_BITS.
847 if (m_frameContext->dataSize() >= MAX_DICTIONARY_ENTRY_BITS)
848 return false;
849 clearCode = 1 << m_frameContext->dataSize();
850 avail = clearCode + 2;
851 oldcode = -1;
852 codesize = m_frameContext->dataSize() + 1;
853 codemask = (1 << codesize) - 1;
854 datum = bits = 0;
855 ipass = m_frameContext->interlaced() ? 1 : 0;
856 irow = 0;
857
858 // We want to know the longest sequence encodable by a dictionary with
859 // MAX_DICTIONARY_ENTRIES entries. If we ignore the need to encode the base
860 // values themselves at the beginning of the dictionary, as well as the need
861 // for a clear code or a termination code, we could use every entry to
862 // encode a series of multiple values. If the input value stream looked
863 // like "AAAAA..." (a long string of just one value), the first dictionary
864 // entry would encode AA, the next AAA, the next AAAA, and so forth. Thus
865 // the longest sequence would be MAX_DICTIONARY_ENTRIES + 1 values.
866 //
867 // However, we have to account for reserved entries. The first |datasize|
868 // bits are reserved for the base values, and the next two entries are
869 // reserved for the clear code and termination code. In theory a GIF can
870 // set the datasize to 0, meaning we have just two reserved entries, making
871 // the longest sequence (MAX_DICTIONARY_ENTIRES + 1) - 2 values long. Since
872 // each value is a byte, this is also the number of bytes in the longest
873 // encodable sequence.
874 const size_t maxBytes = MAX_DICTIONARY_ENTRIES - 1;
875
876 // Now allocate the output buffer. We decode directly into this buffer
877 // until we have at least one row worth of data, then call outputRow().
878 // This means worst case we may have (row width - 1) bytes in the buffer
879 // and then decode a sequence |maxBytes| long to append.
880 rowBuffer.resize(m_frameContext->width() - 1 + maxBytes);
881 rowIter = rowBuffer.begin();
882 rowsRemaining = m_frameContext->height();
883
884 // Clearing the whole suffix table lets us be more tolerant of bad data.
885 for (int i = 0; i < clearCode; ++i) {
886 suffix[i] = i;
887 suffixLength[i] = 1;
888 }
889 return true;
890 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698