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

Side by Side Diff: src/codec/GIFImageReader.cpp

Issue 2045293002: Add support for multiple frames in SkCodec (Closed) Base URL: https://skia.googlesource.com/skia.git@master
Patch Set: Never use background index. Sometimes recommend N32 Created 4 years, 2 months 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
« no previous file with comments | « src/codec/GIFImageReader.h ('k') | src/codec/SkAndroidCodec.cpp » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
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 "GIFImageReader.h"
76 #include "SkColorPriv.h"
77 #include "SkGifCodec.h"
78
79 #include <string.h>
80
81
82 // GETN(n, s) requests at least 'n' bytes available from 'q', at start of state 's'.
83 //
84 // Note, the hold will never need to be bigger than 256 bytes to gather up in th e hold,
85 // as each GIF block (except colormaps) can never be bigger than 256 bytes.
86 // Colormaps are directly copied in the resp. global_colormap or dynamically all ocated local_colormap.
87 // So a fixed buffer in GIFImageReader is good enough.
88 // This buffer is only needed to copy left-over data from one GifWrite call to t he next
89 #define GETN(n, s) \
90 do { \
91 m_bytesToConsume = (n); \
92 m_state = (s); \
93 } while (0)
94
95 // Get a 16-bit value stored in little-endian format.
96 #define GETINT16(p) ((p)[1]<<8|(p)[0])
97
98 // Send the data to the display front-end.
99 bool GIFLZWContext::outputRow(const unsigned char* rowBegin)
100 {
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() && ipass < 4) {
109 unsigned rowDup = 0;
110 unsigned rowShift = 0;
111
112 switch (ipass) {
113 case 1:
114 rowDup = 7;
115 rowShift = 3;
116 break;
117 case 2:
118 rowDup = 3;
119 rowShift = 1;
120 break;
121 case 3:
122 rowDup = 1;
123 rowShift = 0;
124 break;
125 default:
126 break;
127 }
128
129 drowStart -= rowShift;
130 drowEnd = drowStart + rowDup;
131
132 // Extend if bottom edge isn't covered because of the shift upward.
133 if (((m_frameContext->height() - 1) - drowEnd) <= rowShift)
134 drowEnd = m_frameContext->height() - 1;
135
136 // Clamp first and last rows to upper and lower edge of image.
137 if (drowStart < 0)
138 drowStart = 0;
139
140 if ((unsigned)drowEnd >= m_frameContext->height())
141 drowEnd = m_frameContext->height() - 1;
142 }
143
144 // Protect against too much image data.
145 if ((unsigned)drowStart >= m_frameContext->height())
146 return true;
147
148 // CALLBACK: Let the client know we have decoded a row.
149 if (!m_client->haveDecodedRow(m_frameContext->frameId(), rowBegin,
150 drowStart, drowEnd - drowStart + 1, m_frameContext->progressiveDisplay() && m_frameContext->interlaced() && ipass > 1))
151 return false;
152
153 if (!m_frameContext->interlaced())
154 irow++;
155 else {
156 do {
157 switch (ipass) {
158 case 1:
159 irow += 8;
160 if (irow >= m_frameContext->height()) {
161 ipass++;
162 irow = 4;
163 }
164 break;
165
166 case 2:
167 irow += 8;
168 if (irow >= m_frameContext->height()) {
169 ipass++;
170 irow = 2;
171 }
172 break;
173
174 case 3:
175 irow += 4;
176 if (irow >= m_frameContext->height()) {
177 ipass++;
178 irow = 1;
179 }
180 break;
181
182 case 4:
183 irow += 2;
184 if (irow >= m_frameContext->height()) {
185 ipass++;
186 irow = 0;
187 }
188 break;
189
190 default:
191 break;
192 }
193 } while (irow > (m_frameContext->height() - 1));
194 }
195 return true;
196 }
197
198 // Perform Lempel-Ziv-Welch decoding.
199 // Returns true if decoding was successful. In this case the block will have bee n completely consumed and/or rowsRemaining will be 0.
200 // Otherwise, decoding failed; returns false in this case, which will always cau se the GIFImageReader to set the "decode failed" flag.
201 bool GIFLZWContext::doLZW(const unsigned char* block, size_t bytesInBlock)
202 {
203 const size_t width = m_frameContext->width();
204
205 if (rowIter == rowBuffer.end())
206 return true;
207
208 for (const unsigned char* ch = block; bytesInBlock-- > 0; ch++) {
209 // Feed the next byte into the decoder's 32-bit input buffer.
210 datum += ((int) *ch) << bits;
211 bits += 8;
212
213 // Check for underflow of decoder's 32-bit input buffer.
214 while (bits >= codesize) {
215 // Get the leading variable-length symbol from the data stream.
216 int code = datum & codemask;
217 datum >>= codesize;
218 bits -= codesize;
219
220 // Reset the dictionary to its original state, if requested.
221 if (code == clearCode) {
222 codesize = m_frameContext->dataSize() + 1;
223 codemask = (1 << codesize) - 1;
224 avail = clearCode + 2;
225 oldcode = -1;
226 continue;
227 }
228
229 // Check for explicit end-of-stream code.
230 if (code == (clearCode + 1)) {
231 // end-of-stream should only appear after all image data.
232 if (!rowsRemaining)
233 return true;
234 return false;
235 }
236
237 const int tempCode = code;
238 unsigned short codeLength = 0;
239 if (code < avail) {
240 // This is a pre-existing code, so we already know what it
241 // encodes.
242 codeLength = suffixLength[code];
243 rowIter += codeLength;
244 } else if (code == avail && oldcode != -1) {
245 // This is a new code just being added to the dictionary.
246 // It must encode the contents of the previous code, plus
247 // the first character of the previous code again.
248 codeLength = suffixLength[oldcode] + 1;
249 rowIter += codeLength;
250 *--rowIter = firstchar;
251 code = oldcode;
252 } else {
253 // This is an invalid code. The dictionary is just initialized
254 // and the code is incomplete. We don't know how to handle
255 // this case.
256 return false;
257 }
258
259 while (code >= clearCode) {
260 *--rowIter = suffix[code];
261 code = prefix[code];
262 }
263
264 *--rowIter = firstchar = suffix[code];
265
266 // Define a new codeword in the dictionary as long as we've read
267 // more than one value from the stream.
268 if (avail < MAX_DICTIONARY_ENTRIES && oldcode != -1) {
269 prefix[avail] = oldcode;
270 suffix[avail] = firstchar;
271 suffixLength[avail] = suffixLength[oldcode] + 1;
272 ++avail;
273
274 // If we've used up all the codewords of a given length
275 // increase the length of codewords by one bit, but don't
276 // exceed the specified maximum codeword size.
277 if (!(avail & codemask) && avail < MAX_DICTIONARY_ENTRIES) {
278 ++codesize;
279 codemask += avail;
280 }
281 }
282 oldcode = tempCode;
283 rowIter += codeLength;
284
285 // Output as many rows as possible.
286 unsigned char* rowBegin = rowBuffer.begin();
287 for (; rowBegin + width <= rowIter; rowBegin += width) {
288 if (!outputRow(rowBegin))
289 return false;
290 rowsRemaining--;
291 if (!rowsRemaining)
292 return true;
293 }
294
295 if (rowBegin != rowBuffer.begin()) {
296 // Move the remaining bytes to the beginning of the buffer.
297 const size_t bytesToCopy = rowIter - rowBegin;
298 memcpy(&rowBuffer.front(), rowBegin, bytesToCopy);
299 rowIter = rowBuffer.begin() + bytesToCopy;
300 }
301 }
302 }
303 return true;
304 }
305
306 sk_sp<SkColorTable> GIFColorMap::buildTable(SkColorType colorType, size_t transp arentPixel) const
307 {
308 if (!m_isDefined)
309 return nullptr;
310
311 const PackColorProc proc = choose_pack_color_proc(false, colorType);
312 if (m_table) {
313 if (transparentPixel > (unsigned) m_table->count()
314 || m_table->operator[](transparentPixel) == SK_ColorTRANSPARENT) {
315 if (proc == m_packColorProc) {
316 // This SkColorTable has already been built with the same transp arent color and
317 // packing proc. Reuse it.
318 return m_table;
319 }
320 }
321 }
322 m_packColorProc = proc;
323
324 SkASSERT(m_colors <= MAX_COLORS);
325 const uint8_t* srcColormap = m_rawData->bytes();
326 SkPMColor colorStorage[MAX_COLORS];
327 for (size_t i = 0; i < m_colors; i++) {
328 if (i == transparentPixel) {
329 colorStorage[i] = SK_ColorTRANSPARENT;
330 } else {
331 colorStorage[i] = proc(255, srcColormap[0], srcColormap[1], srcColor map[2]);
332 }
333 srcColormap += BYTES_PER_COLORMAP_ENTRY;
334 }
335 for (size_t i = m_colors; i < MAX_COLORS; i++) {
336 colorStorage[i] = SK_ColorTRANSPARENT;
337 }
338 m_table = sk_sp<SkColorTable>(new SkColorTable(colorStorage, MAX_COLORS));
339 return m_table;
340 }
341
342 sk_sp<SkColorTable> GIFImageReader::getColorTable(SkColorType colorType, size_t index) const {
343 if (index >= m_frames.size()) {
344 return nullptr;
345 }
346
347 const GIFFrameContext* frameContext = m_frames[index].get();
348 const GIFColorMap& localColorMap = frameContext->localColorMap();
349 if (localColorMap.isDefined()) {
350 return localColorMap.buildTable(colorType, frameContext->transparentPixe l());
351 }
352 if (m_globalColorMap.isDefined()) {
353 return m_globalColorMap.buildTable(colorType, frameContext->transparentP ixel());
354 }
355 return nullptr;
356 }
357
358 // Perform decoding for this frame. frameComplete will be true if the entire fra me is decoded.
359 // Returns false if a decoding error occurred. This is a fatal error and causes the GIFImageReader to set the "decode failed" flag.
360 // Otherwise, either not enough data is available to decode further than before, or the new data has been decoded successfully; returns true in this case.
361 bool GIFFrameContext::decode(SkGifCodec* client, bool* frameComplete)
362 {
363 *frameComplete = false;
364 if (!m_lzwContext) {
365 // Wait for more data to properly initialize GIFLZWContext.
366 if (!isDataSizeDefined() || !isHeaderDefined())
367 return true;
368
369 m_lzwContext.reset(new GIFLZWContext(client, this));
370 if (!m_lzwContext->prepareToDecode()) {
371 m_lzwContext.reset();
372 return false;
373 }
374
375 m_currentLzwBlock = 0;
376 }
377
378 // Some bad GIFs have extra blocks beyond the last row, which we don't want to decode.
379 while (m_currentLzwBlock < m_lzwBlocks.size() && m_lzwContext->hasRemainingR ows()) {
380 if (!m_lzwContext->doLZW(reinterpret_cast<const unsigned char*>(m_lzwBlo cks[m_currentLzwBlock]->data()),
381 m_lzwBlo cks[m_currentLzwBlock]->size())) {
382 return false;
383 }
384 ++m_currentLzwBlock;
385 }
386
387 // If this frame is data complete then the previous loop must have completel y decoded all LZW blocks.
388 // There will be no more decoding for this frame so it's time to cleanup.
389 if (isComplete()) {
390 *frameComplete = true;
391 m_lzwContext.reset();
392 }
393 return true;
394 }
395
396 // Decode a frame.
397 // This method uses GIFFrameContext:decode() to decode the frame; decoding error is reported to client as a critical failure.
398 // Return true if decoding has progressed. Return false if an error has occurred .
399 bool GIFImageReader::decode(size_t frameIndex, bool* frameComplete)
400 {
401 GIFFrameContext* currentFrame = m_frames[frameIndex].get();
402
403 return currentFrame->decode(m_client, frameComplete);
404 }
405
406 // Parse incoming GIF data stream into internal data structures.
407 // Return true if parsing has progressed or there is not enough data.
408 // Return false if a fatal error is encountered.
409 bool GIFImageReader::parse(GIFImageReader::GIFParseQuery query)
410 {
411 if (m_parseCompleted) {
412 return true;
413 }
414
415 // GIFSizeQuery and GIFFrameCountQuery are negative, so this is only meaning ful when >= 0.
416 const int lastFrameToParse = (int) query;
417 if (lastFrameToParse >= 0 && (int) m_frames.size() > lastFrameToParse
418 && m_frames[lastFrameToParse]->isComplete()) {
419 // We have already parsed this frame.
420 return true;
421 }
422
423 while (true) {
424 const size_t bytesBuffered = m_streamBuffer.buffer(m_bytesToConsume);
425 if (bytesBuffered < m_bytesToConsume) {
426 // The stream does not yet have enough data. Mark that we need less next time around,
427 // and return.
428 m_bytesToConsume -= bytesBuffered;
429 return true;
430 }
431
432 switch (m_state) {
433 case GIFLZW:
434 SkASSERT(!m_frames.empty());
435 // FIXME: All this copying might be wasteful for e.g. SkMemoryStream
436 m_frames.back()->addLzwBlock(m_streamBuffer.get(), m_streamBuffer.by tesBuffered());
437 GETN(1, GIFSubBlock);
438 break;
439
440 case GIFLZWStart: {
441 SkASSERT(!m_frames.empty());
442 m_frames.back()->setDataSize(this->getOneByte());
443 GETN(1, GIFSubBlock);
444 break;
445 }
446
447 case GIFType: {
448 const char* currentComponent = m_streamBuffer.get();
449
450 // All GIF files begin with "GIF87a" or "GIF89a".
451 if (!memcmp(currentComponent, "GIF89a", 6))
452 m_version = 89;
453 else if (!memcmp(currentComponent, "GIF87a", 6))
454 m_version = 87;
455 else {
456 // This prevents attempting to continue reading this invalid str eam.
457 GETN(0, GIFDone);
458 return false;
459 }
460 GETN(7, GIFGlobalHeader);
461 break;
462 }
463
464 case GIFGlobalHeader: {
465 const unsigned char* currentComponent =
466 reinterpret_cast<const unsigned char*>(m_streamBuffer.get());
467
468 // This is the height and width of the "screen" or frame into which
469 // images are rendered. The individual images can be smaller than
470 // the screen size and located with an origin anywhere within the
471 // screen.
472 // Note that we don't inform the client of the size yet, as it might
473 // change after we read the first frame's image header.
474 m_screenWidth = GETINT16(currentComponent);
475 m_screenHeight = GETINT16(currentComponent + 2);
476
477 const size_t globalColorMapColors = 2 << (currentComponent[4] & 0x07 );
478
479 if ((currentComponent[4] & 0x80) && globalColorMapColors > 0) { /* g lobal map */
480 m_globalColorMap.setNumColors(globalColorMapColors);
481 GETN(BYTES_PER_COLORMAP_ENTRY * globalColorMapColors, GIFGlobalC olormap);
482 break;
483 }
484
485 GETN(1, GIFImageStart);
486 break;
487 }
488
489 case GIFGlobalColormap: {
490 m_globalColorMap.setRawData(m_streamBuffer.get(), m_streamBuffer.byt esBuffered());
491 GETN(1, GIFImageStart);
492 break;
493 }
494
495 case GIFImageStart: {
496 const char currentComponent = m_streamBuffer.get()[0];
497
498 if (currentComponent == '!') { // extension.
499 GETN(2, GIFExtension);
500 break;
501 }
502
503 if (currentComponent == ',') { // image separator.
504 GETN(9, GIFImageHeader);
505 break;
506 }
507
508 // If we get anything other than ',' (image separator), '!'
509 // (extension), or ';' (trailer), there is extraneous data
510 // between blocks. The GIF87a spec tells us to keep reading
511 // until we find an image separator, but GIF89a says such
512 // a file is corrupt. We follow Mozilla's implementation and
513 // proceed as if the file were correctly terminated, so the
514 // GIF will display.
515 GETN(0, GIFDone);
516 break;
517 }
518
519 case GIFExtension: {
520 const unsigned char* currentComponent =
521 reinterpret_cast<const unsigned char*>(m_streamBuffer.get());
522
523 size_t bytesInBlock = currentComponent[1];
524 GIFState exceptionState = GIFSkipBlock;
525
526 switch (*currentComponent) {
527 case 0xf9:
528 exceptionState = GIFControlExtension;
529 // The GIF spec mandates that the GIFControlExtension header blo ck length is 4 bytes,
530 // and the parser for this block reads 4 bytes, so we must enfor ce that the buffer
531 // contains at least this many bytes. If the GIF specifies a dif ferent length, we
532 // allow that, so long as it's larger; the additional data will simply be ignored.
533 bytesInBlock = std::max(bytesInBlock, static_cast<size_t>(4));
534 break;
535
536 // The GIF spec also specifies the lengths of the following two exte nsions' headers
537 // (as 12 and 11 bytes, respectively). Because we ignore the plain t ext extension entirely
538 // and sanity-check the actual length of the application extension h eader before reading it,
539 // we allow GIFs to deviate from these values in either direction. T his is important for
540 // real-world compatibility, as GIFs in the wild exist with applicat ion extension headers
541 // that are both shorter and longer than 11 bytes.
542 case 0x01:
543 // ignoring plain text extension
544 break;
545
546 case 0xff:
547 exceptionState = GIFApplicationExtension;
548 break;
549
550 case 0xfe:
551 exceptionState = GIFConsumeComment;
552 break;
553 }
554
555 if (bytesInBlock)
556 GETN(bytesInBlock, exceptionState);
557 else
558 GETN(1, GIFImageStart);
559 break;
560 }
561
562 case GIFConsumeBlock: {
563 const unsigned char currentComponent = this->getOneByte();
564 if (!currentComponent)
565 GETN(1, GIFImageStart);
566 else
567 GETN(currentComponent, GIFSkipBlock);
568 break;
569 }
570
571 case GIFSkipBlock: {
572 GETN(1, GIFConsumeBlock);
573 break;
574 }
575
576 case GIFControlExtension: {
577 const unsigned char* currentComponent =
578 reinterpret_cast<const unsigned char*>(m_streamBuffer.get());
579
580 addFrameIfNecessary();
581 GIFFrameContext* currentFrame = m_frames.back().get();
582 if (*currentComponent & 0x1)
583 currentFrame->setTransparentPixel(currentComponent[3]);
584
585 // We ignore the "user input" bit.
586
587 // NOTE: This relies on the values in the FrameDisposalMethod enum
588 // matching those in the GIF spec!
589 int rawDisposalMethod = ((*currentComponent) >> 2) & 0x7;
590 switch (rawDisposalMethod) {
591 case 1:
592 case 2:
593 case 3:
594 currentFrame->setDisposalMethod((SkCodecAnimation::DisposalMetho d) rawDisposalMethod);
595 break;
596 case 4:
597 // Some specs say that disposal method 3 is "overwrite previous" , others that setting
598 // the third bit of the field (i.e. method 4) is. We map both to the same value.
599 currentFrame->setDisposalMethod(SkCodecAnimation::RestorePreviou s_DisposalMethod);
600 break;
601 default:
602 // Other values use the default.
603 currentFrame->setDisposalMethod(SkCodecAnimation::Keep_DisposalM ethod);
604 break;
605 }
606 currentFrame->setDelayTime(GETINT16(currentComponent + 1) * 10);
607 GETN(1, GIFConsumeBlock);
608 break;
609 }
610
611 case GIFCommentExtension: {
612 const unsigned char currentComponent = this->getOneByte();
613 if (currentComponent)
614 GETN(currentComponent, GIFConsumeComment);
615 else
616 GETN(1, GIFImageStart);
617 break;
618 }
619
620 case GIFConsumeComment: {
621 GETN(1, GIFCommentExtension);
622 break;
623 }
624
625 case GIFApplicationExtension: {
626 // Check for netscape application extension.
627 if (m_streamBuffer.bytesBuffered() == 11) {
628 const unsigned char* currentComponent =
629 reinterpret_cast<const unsigned char*>(m_streamBuffer.get()) ;
630
631 if (!memcmp(currentComponent, "NETSCAPE2.0", 11) || !memcmp(curr entComponent, "ANIMEXTS1.0", 11))
632 GETN(1, GIFNetscapeExtensionBlock);
633 }
634
635 if (m_state != GIFNetscapeExtensionBlock)
636 GETN(1, GIFConsumeBlock);
637 break;
638 }
639
640 // Netscape-specific GIF extension: animation looping.
641 case GIFNetscapeExtensionBlock: {
642 const int currentComponent = this->getOneByte();
643 // GIFConsumeNetscapeExtension always reads 3 bytes from the stream; we should at least wait for this amount.
644 if (currentComponent)
645 GETN(std::max(3, currentComponent), GIFConsumeNetscapeExtension) ;
646 else
647 GETN(1, GIFImageStart);
648 break;
649 }
650
651 // Parse netscape-specific application extensions
652 case GIFConsumeNetscapeExtension: {
653 const unsigned char* currentComponent =
654 reinterpret_cast<const unsigned char*>(m_streamBuffer.get());
655
656 int netscapeExtension = currentComponent[0] & 7;
657
658 // Loop entire animation specified # of times. Only read the loop co unt during the first iteration.
659 if (netscapeExtension == 1) {
660 m_loopCount = GETINT16(currentComponent + 1);
661
662 // Zero loop count is infinite animation loop request.
663 if (!m_loopCount)
664 m_loopCount = SkCodecAnimation::kAnimationLoopInfinite;
665
666 GETN(1, GIFNetscapeExtensionBlock);
667 } else if (netscapeExtension == 2) {
668 // Wait for specified # of bytes to enter buffer.
669
670 // Don't do this, this extension doesn't exist (isn't used at al l)
671 // and doesn't do anything, as our streaming/buffering takes car e of it all...
672 // See: http://semmix.pl/color/exgraf/eeg24.htm
673 GETN(1, GIFNetscapeExtensionBlock);
674 } else {
675 // 0,3-7 are yet to be defined netscape extension codes
676 // This prevents attempting to continue reading this invalid str eam.
677 GETN(0, GIFDone);
678 return false;
679 }
680 break;
681 }
682
683 case GIFImageHeader: {
684 unsigned height, width, xOffset, yOffset;
685 const unsigned char* currentComponent =
686 reinterpret_cast<const unsigned char*>(m_streamBuffer.get());
687
688 /* Get image offsets, with respect to the screen origin */
689 xOffset = GETINT16(currentComponent);
690 yOffset = GETINT16(currentComponent + 2);
691
692 /* Get image width and height. */
693 width = GETINT16(currentComponent + 4);
694 height = GETINT16(currentComponent + 6);
695
696 // Some GIF files have frames that don't fit in the specified
697 // overall image size. For the first frame, we can simply enlarge
698 // the image size to allow the frame to be visible. We can't do
699 // this on subsequent frames because the rest of the decoding
700 // infrastructure assumes the image size won't change as we
701 // continue decoding, so any subsequent frames that are even
702 // larger will be cropped.
703 // Luckily, handling just the first frame is sufficient to deal
704 // with most cases, e.g. ones where the image size is erroneously
705 // set to zero, since usually the first frame completely fills
706 // the image.
707 if (currentFrameIsFirstFrame()) {
708 m_screenHeight = std::max(m_screenHeight, yOffset + height);
709 m_screenWidth = std::max(m_screenWidth, xOffset + width);
710 }
711
712 // NOTE: Chromium placed this block after setHeaderDefined, down
713 // below we returned true when asked for the size. So Chromium
714 // created an image which would fail. Is this the correct behavior?
715 // We choose to return false early, so we will not create an
716 // SkCodec.
717
718 // Work around more broken GIF files that have zero image width or
719 // height.
720 if (!height || !width) {
721 height = m_screenHeight;
722 width = m_screenWidth;
723 if (!height || !width) {
724 // This prevents attempting to continue reading this invalid stream.
725 GETN(0, GIFDone);
726 return false;
727 }
728 }
729
730 const bool isLocalColormapDefined = currentComponent[8] & 0x80;
scroggo_chromium 2016/10/20 17:57:13 msarett@, PTAL at the new changes related to the b
731 // The three low-order bits of currentComponent[8] specify the bits per pixel.
732 const size_t numColors = 2 << (currentComponent[8] & 0x7);
733 if (currentFrameIsFirstFrame()) {
734 bool hasTransparentPixel;
735 if (m_frames.size() == 0) {
736 // We did not see a Graphics Control Extension, so no transp arent
737 // pixel was specified.
738 hasTransparentPixel = false;
739 } else {
740 // This means we did see a Graphics Control Extension, which specifies
741 // the transparent pixel
742 const size_t transparentPixel = m_frames[0]->transparentPixe l();
743 if (isLocalColormapDefined) {
744 hasTransparentPixel = transparentPixel < numColors;
745 } else {
746 const size_t globalColors = m_globalColorMap.numColors() ;
747 if (!globalColors) {
748 // No color table for this frame, so the frame is em pty.
749 // This is technically different from having a trans parent
750 // pixel, but we'll treat it the same - nothing to d raw here.
751 hasTransparentPixel = true;
752 } else {
753 hasTransparentPixel = transparentPixel < globalColor s;
754 }
755 }
756 }
757
758 if (hasTransparentPixel) {
759 m_firstFrameHasAlpha = true;
760 m_firstFrameSupportsIndex8 = true;
761 } else {
762 const bool frameIsSubset = xOffset > 0 || yOffset > 0
763 || xOffset + width < m_screenWidth
764 || yOffset + height < m_screenHeight;
765 m_firstFrameHasAlpha = frameIsSubset;
766 m_firstFrameSupportsIndex8 = !frameIsSubset;
767 }
768 }
769
770 if (query == GIFSizeQuery) {
771 // The decoder needs to stop, so we return here, before
772 // flushing the buffer. Next time through, we'll be in the same
773 // state, requiring the same amount in the buffer.
774 m_bytesToConsume = 0;
775 return true;
776 }
777
778 addFrameIfNecessary();
779 GIFFrameContext* currentFrame = m_frames.back().get();
780
781 currentFrame->setHeaderDefined();
782
783 currentFrame->setRect(xOffset, yOffset, width, height);
784 currentFrame->setInterlaced(currentComponent[8] & 0x40);
785
786 // Overlaying interlaced, transparent GIFs over
787 // existing image data using the Haeberli display hack
788 // requires saving the underlying image in order to
789 // avoid jaggies at the transparency edges. We are
790 // unprepared to deal with that, so don't display such
791 // images progressively. Which means only the first
792 // frame can be progressively displayed.
793 // FIXME: It is possible that a non-transparent frame
794 // can be interlaced and progressively displayed.
795 currentFrame->setProgressiveDisplay(currentFrameIsFirstFrame());
796
797 if (isLocalColormapDefined) {
798 currentFrame->localColorMap().setNumColors(numColors);
799 GETN(BYTES_PER_COLORMAP_ENTRY * numColors, GIFImageColormap);
800 break;
801 }
802
803 GETN(1, GIFLZWStart);
804 break;
805 }
806
807 case GIFImageColormap: {
808 SkASSERT(!m_frames.empty());
809 m_frames.back()->localColorMap().setRawData(m_streamBuffer.get(), m_ streamBuffer.bytesBuffered());
810 GETN(1, GIFLZWStart);
811 break;
812 }
813
814 case GIFSubBlock: {
815 const size_t bytesInBlock = this->getOneByte();
816 if (bytesInBlock)
817 GETN(bytesInBlock, GIFLZW);
818 else {
819 // Finished parsing one frame; Process next frame.
820 SkASSERT(!m_frames.empty());
821 // Note that some broken GIF files do not have enough LZW blocks to fully
822 // decode all rows but we treat it as frame complete.
823 m_frames.back()->setComplete();
824 GETN(1, GIFImageStart);
825 if (lastFrameToParse >= 0 && (int) m_frames.size() > lastFrameTo Parse) {
826 m_streamBuffer.flush();
827 return true;
828 }
829 }
830 break;
831 }
832
833 case GIFDone: {
834 m_parseCompleted = true;
835 return true;
836 }
837
838 default:
839 // We shouldn't ever get here.
840 // This prevents attempting to continue reading this invalid stream.
841 GETN(0, GIFDone);
842 return false;
843 break;
844 } // switch
845 m_streamBuffer.flush();
846 }
847
848 return true;
849 }
850
851 void GIFImageReader::addFrameIfNecessary()
852 {
853 if (m_frames.empty() || m_frames.back()->isComplete()) {
854 const size_t i = m_frames.size();
855 std::unique_ptr<GIFFrameContext> frame(new GIFFrameContext(i));
856 if (0 == i) {
857 frame->setRequiredFrame(SkCodec::kNone);
858 } else {
859 // FIXME: We could correct these after decoding (i.e. some frames ma y turn out to be
860 // independent although we did not determine that here).
861 const GIFFrameContext* prevFrameContext = m_frames[i - 1].get();
862 switch (prevFrameContext->getDisposalMethod()) {
863 case SkCodecAnimation::Keep_DisposalMethod:
864 frame->setRequiredFrame(i - 1);
865 break;
866 case SkCodecAnimation::RestorePrevious_DisposalMethod:
867 frame->setRequiredFrame(prevFrameContext->getRequiredFrame() );
868 break;
869 case SkCodecAnimation::RestoreBGColor_DisposalMethod:
870 // If the prior frame covers the whole image
871 if (prevFrameContext->frameRect() == SkIRect::MakeWH(m_scree nWidth,
872 m_scree nHeight)
873 // Or the prior frame was independent
874 || prevFrameContext->getRequiredFrame() == SkCodec:: kNone)
875 {
876 // This frame is independent, since we clear everything
877 // prior frame to the BG color
878 frame->setRequiredFrame(SkCodec::kNone);
879 } else {
880 frame->setRequiredFrame(i - 1);
881 }
882 break;
883 }
884 }
885 m_frames.push_back(std::move(frame));
886 }
887 }
888
889 // FIXME: Move this method to close to doLZW().
890 bool GIFLZWContext::prepareToDecode()
891 {
892 SkASSERT(m_frameContext->isDataSizeDefined() && m_frameContext->isHeaderDefi ned());
893
894 // Since we use a codesize of 1 more than the datasize, we need to ensure
895 // that our datasize is strictly less than the MAX_DICTIONARY_ENTRY_BITS.
896 if (m_frameContext->dataSize() >= MAX_DICTIONARY_ENTRY_BITS)
897 return false;
898 clearCode = 1 << m_frameContext->dataSize();
899 avail = clearCode + 2;
900 oldcode = -1;
901 codesize = m_frameContext->dataSize() + 1;
902 codemask = (1 << codesize) - 1;
903 datum = bits = 0;
904 ipass = m_frameContext->interlaced() ? 1 : 0;
905 irow = 0;
906
907 // We want to know the longest sequence encodable by a dictionary with
908 // MAX_DICTIONARY_ENTRIES entries. If we ignore the need to encode the base
909 // values themselves at the beginning of the dictionary, as well as the need
910 // for a clear code or a termination code, we could use every entry to
911 // encode a series of multiple values. If the input value stream looked
912 // like "AAAAA..." (a long string of just one value), the first dictionary
913 // entry would encode AA, the next AAA, the next AAAA, and so forth. Thus
914 // the longest sequence would be MAX_DICTIONARY_ENTRIES + 1 values.
915 //
916 // However, we have to account for reserved entries. The first |datasize|
917 // bits are reserved for the base values, and the next two entries are
918 // reserved for the clear code and termination code. In theory a GIF can
919 // set the datasize to 0, meaning we have just two reserved entries, making
920 // the longest sequence (MAX_DICTIONARY_ENTIRES + 1) - 2 values long. Since
921 // each value is a byte, this is also the number of bytes in the longest
922 // encodable sequence.
923 const size_t maxBytes = MAX_DICTIONARY_ENTRIES - 1;
924
925 // Now allocate the output buffer. We decode directly into this buffer
926 // until we have at least one row worth of data, then call outputRow().
927 // This means worst case we may have (row width - 1) bytes in the buffer
928 // and then decode a sequence |maxBytes| long to append.
929 rowBuffer.reset(m_frameContext->width() - 1 + maxBytes);
930 rowIter = rowBuffer.begin();
931 rowsRemaining = m_frameContext->height();
932
933 // Clearing the whole suffix table lets us be more tolerant of bad data.
934 for (int i = 0; i < clearCode; ++i) {
935 suffix[i] = i;
936 suffixLength[i] = 1;
937 }
938 return true;
939 }
940
OLDNEW
« no previous file with comments | « src/codec/GIFImageReader.h ('k') | src/codec/SkAndroidCodec.cpp » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698