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