SkGifImageReader.cpp 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958
  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. The Graphics Interchange Format(c) is the copyright property of CompuServe
  41. Incorporated. Only CompuServe Incorporated is authorized to define, redefine,
  42. enhance, alter, modify or change in any way the definition of the format.
  43. CompuServe Incorporated hereby grants a limited, non-exclusive, royalty-free
  44. license for the use of the Graphics Interchange Format(sm) in computer
  45. software; computer software utilizing GIF(sm) must acknowledge ownership of the
  46. Graphics Interchange Format and its Service Mark by CompuServe Incorporated, in
  47. User and Technical Documentation. Computer software utilizing GIF, which is
  48. distributed or may be distributed without User or Technical Documentation must
  49. display to the screen or printer a message acknowledging ownership of the
  50. Graphics Interchange Format and the Service Mark by CompuServe Incorporated; in
  51. this case, the acknowledgement may be displayed in an opening screen or leading
  52. banner, or a closing screen or trailing banner. A message such as the following
  53. may be used:
  54. "The Graphics Interchange Format(c) is the Copyright property of
  55. CompuServe Incorporated. GIF(sm) is a Service Mark property of
  56. CompuServe Incorporated."
  57. For further information, please contact :
  58. CompuServe Incorporated
  59. Graphics Technology Department
  60. 5000 Arlington Center Boulevard
  61. Columbus, Ohio 43220
  62. U. S. A.
  63. CompuServe Incorporated maintains a mailing list with all those individuals and
  64. organizations who wish to receive copies of this document when it is corrected
  65. or revised. This service is offered free of charge; please provide us with your
  66. mailing address.
  67. */
  68. #include "include/core/SkColorPriv.h"
  69. #include "src/codec/SkGifCodec.h"
  70. #include "third_party/gif/SkGifImageReader.h"
  71. #include <algorithm>
  72. #include <string.h>
  73. // GETN(n, s) requests at least 'n' bytes available from 'q', at start of state 's'.
  74. //
  75. // Note, the hold will never need to be bigger than 256 bytes to gather up in the hold,
  76. // as each GIF block (except colormaps) can never be bigger than 256 bytes.
  77. // Colormaps are directly copied in the resp. global_colormap or dynamically allocated local_colormap.
  78. // So a fixed buffer in SkGifImageReader is good enough.
  79. // This buffer is only needed to copy left-over data from one GifWrite call to the next
  80. #define GETN(n, s) \
  81. do { \
  82. m_bytesToConsume = (n); \
  83. m_state = (s); \
  84. } while (0)
  85. // Get a 16-bit value stored in little-endian format.
  86. #define GETINT16(p) ((p)[1]<<8|(p)[0])
  87. namespace {
  88. bool is_palette_index_valid(int transparentIndex) {
  89. // -1 is a signal that there is no transparent index.
  90. // Otherwise, it is encoded in 8 bits, and all 256 values are considered
  91. // valid since a GIF may use an index outside of the palette to be
  92. // transparent.
  93. return transparentIndex >= 0;
  94. }
  95. } // anonymous namespace
  96. // Send the data to the display front-end.
  97. void SkGIFLZWContext::outputRow(const unsigned char* rowBegin)
  98. {
  99. int drowStart = irow;
  100. int drowEnd = irow;
  101. // Haeberli-inspired hack for interlaced GIFs: Replicate lines while
  102. // displaying to diminish the "venetian-blind" effect as the image is
  103. // loaded. Adjust pixel vertical positions to avoid the appearance of the
  104. // image crawling up the screen as successive passes are drawn.
  105. if (m_frameContext->progressiveDisplay() && m_frameContext->interlaced() && ipass < 4) {
  106. unsigned rowDup = 0;
  107. unsigned rowShift = 0;
  108. switch (ipass) {
  109. case 1:
  110. rowDup = 7;
  111. rowShift = 3;
  112. break;
  113. case 2:
  114. rowDup = 3;
  115. rowShift = 1;
  116. break;
  117. case 3:
  118. rowDup = 1;
  119. rowShift = 0;
  120. break;
  121. default:
  122. break;
  123. }
  124. drowStart -= rowShift;
  125. drowEnd = drowStart + rowDup;
  126. // Extend if bottom edge isn't covered because of the shift upward.
  127. if ((unsigned)((m_frameContext->height() - 1) - drowEnd) <= rowShift)
  128. drowEnd = m_frameContext->height() - 1;
  129. // Clamp first and last rows to upper and lower edge of image.
  130. if (drowStart < 0)
  131. drowStart = 0;
  132. if (drowEnd >= m_frameContext->height())
  133. drowEnd = m_frameContext->height() - 1;
  134. }
  135. // Protect against too much image data.
  136. if (drowStart >= m_frameContext->height())
  137. return;
  138. // CALLBACK: Let the client know we have decoded a row.
  139. const bool writeTransparentPixels =
  140. SkCodec::kNoFrame == m_frameContext->getRequiredFrame();
  141. m_client->haveDecodedRow(m_frameContext->frameId(), rowBegin,
  142. drowStart, drowEnd - drowStart + 1, writeTransparentPixels);
  143. if (!m_frameContext->interlaced())
  144. irow++;
  145. else {
  146. do {
  147. switch (ipass) {
  148. case 1:
  149. irow += 8;
  150. if (irow >= (unsigned) m_frameContext->height()) {
  151. ipass++;
  152. irow = 4;
  153. }
  154. break;
  155. case 2:
  156. irow += 8;
  157. if (irow >= (unsigned) m_frameContext->height()) {
  158. ipass++;
  159. irow = 2;
  160. }
  161. break;
  162. case 3:
  163. irow += 4;
  164. if (irow >= (unsigned) m_frameContext->height()) {
  165. ipass++;
  166. irow = 1;
  167. }
  168. break;
  169. case 4:
  170. irow += 2;
  171. if (irow >= (unsigned) m_frameContext->height()) {
  172. ipass++;
  173. irow = 0;
  174. }
  175. break;
  176. default:
  177. break;
  178. }
  179. } while (irow > (unsigned) (m_frameContext->height() - 1));
  180. }
  181. }
  182. // Perform Lempel-Ziv-Welch decoding.
  183. // Returns true if decoding was successful. In this case the block will have been completely consumed and/or rowsRemaining will be 0.
  184. // Otherwise, decoding failed; returns false in this case, which will always cause the SkGifImageReader to set the "decode failed" flag.
  185. bool SkGIFLZWContext::doLZW(const unsigned char* block, size_t bytesInBlock)
  186. {
  187. if (rowIter == rowBuffer.end())
  188. return true;
  189. const int width = m_frameContext->width();
  190. for (const unsigned char* ch = block; bytesInBlock-- > 0; ch++) {
  191. // Feed the next byte into the decoder's 32-bit input buffer.
  192. datum += ((int) *ch) << bits;
  193. bits += 8;
  194. // Check for underflow of decoder's 32-bit input buffer.
  195. while (bits >= codesize) {
  196. // Get the leading variable-length symbol from the data stream.
  197. int code = datum & codemask;
  198. datum >>= codesize;
  199. bits -= codesize;
  200. // Reset the dictionary to its original state, if requested.
  201. if (code == clearCode) {
  202. codesize = m_frameContext->dataSize() + 1;
  203. codemask = (1 << codesize) - 1;
  204. avail = clearCode + 2;
  205. oldcode = -1;
  206. continue;
  207. }
  208. // Check for explicit end-of-stream code.
  209. if (code == (clearCode + 1)) {
  210. // end-of-stream should only appear after all image data.
  211. if (!rowsRemaining)
  212. return true;
  213. return false;
  214. }
  215. const int tempCode = code;
  216. if (code > avail) {
  217. // This is an invalid code. The dictionary is just initialized
  218. // and the code is incomplete. We don't know how to handle
  219. // this case.
  220. return false;
  221. }
  222. if (code == avail) {
  223. if (oldcode != -1) {
  224. // This is a new code just being added to the dictionary.
  225. // It must encode the contents of the previous code, plus
  226. // the first character of the previous code again.
  227. // Now we know avail is the new code we can use oldcode
  228. // value to get the code related to that.
  229. code = oldcode;
  230. } else {
  231. // This is an invalid code. The dictionary is just initialized
  232. // and the code is incomplete. We don't know how to handle
  233. // this case.
  234. return false;
  235. }
  236. }
  237. // code length of the oldcode for new code which is
  238. // avail = oldcode + firstchar of the oldcode
  239. int remaining = suffixLength[code];
  240. // Round remaining up to multiple of SK_DICTIONARY_WORD_SIZE, because that's
  241. // the granularity of the chunks we copy. The last chunk may contain
  242. // some garbage but it'll be overwritten by the next code or left unused.
  243. // The working buffer is padded to account for this.
  244. remaining += -remaining & (SK_DICTIONARY_WORD_SIZE - 1) ;
  245. unsigned char* p = rowIter + remaining;
  246. // Place rowIter so that after writing pixels rowIter can be set to firstchar, thereby
  247. // completing the code.
  248. rowIter += suffixLength[code];
  249. while (remaining > 0) {
  250. p -= SK_DICTIONARY_WORD_SIZE;
  251. std::copy_n(suffix[code].begin(), SK_DICTIONARY_WORD_SIZE, p);
  252. code = prefix[code];
  253. remaining -= SK_DICTIONARY_WORD_SIZE;
  254. }
  255. const int firstchar = static_cast<unsigned char>(code); // (strictly `suffix[code][0]`)
  256. // This completes the new code avail and writing the corresponding
  257. // pixels on target.
  258. if (tempCode == avail) {
  259. *rowIter++ = firstchar;
  260. }
  261. // Define a new codeword in the dictionary as long as we've read
  262. // more than one value from the stream.
  263. if (avail < SK_MAX_DICTIONARY_ENTRIES && oldcode != -1) {
  264. // now add avail to the dictionary for future reference
  265. unsigned short codeLength = suffixLength[oldcode] + 1;
  266. int l = (codeLength - 1) & (SK_DICTIONARY_WORD_SIZE - 1);
  267. // If the suffix buffer is full (l == 0) then oldcode becomes the new
  268. // prefix, otherwise copy and extend oldcode's buffer and use the same
  269. // prefix as oldcode used.
  270. prefix[avail] = (l == 0) ? oldcode : prefix[oldcode];
  271. suffix[avail] = suffix[oldcode];
  272. suffix[avail][l] = firstchar;
  273. suffixLength[avail] = codeLength;
  274. ++avail;
  275. // If we've used up all the codewords of a given length
  276. // increase the length of codewords by one bit, but don't
  277. // exceed the specified maximum codeword size.
  278. if (!(avail & codemask) && avail < SK_MAX_DICTIONARY_ENTRIES) {
  279. ++codesize;
  280. codemask += avail;
  281. }
  282. }
  283. oldcode = tempCode;
  284. // Output as many rows as possible.
  285. unsigned char* rowBegin = rowBuffer.begin();
  286. for (; rowBegin + width <= rowIter; rowBegin += width) {
  287. outputRow(rowBegin);
  288. rowsRemaining--;
  289. if (!rowsRemaining)
  290. return true;
  291. }
  292. if (rowBegin != rowBuffer.begin()) {
  293. // Move the remaining bytes to the beginning of the buffer.
  294. const size_t bytesToCopy = rowIter - rowBegin;
  295. memcpy(&rowBuffer.front(), rowBegin, bytesToCopy);
  296. rowIter = rowBuffer.begin() + bytesToCopy;
  297. }
  298. }
  299. }
  300. return true;
  301. }
  302. sk_sp<SkColorTable> SkGIFColorMap::buildTable(SkStreamBuffer* streamBuffer, SkColorType colorType,
  303. int transparentPixel) const
  304. {
  305. if (!m_isDefined)
  306. return nullptr;
  307. const PackColorProc proc = choose_pack_color_proc(false, colorType);
  308. if (m_table && proc == m_packColorProc && m_transPixel == transparentPixel) {
  309. SkASSERT(transparentPixel == kNotFound || transparentPixel > m_table->count()
  310. || m_table->operator[](transparentPixel) == SK_ColorTRANSPARENT);
  311. // This SkColorTable has already been built with the same transparent color and
  312. // packing proc. Reuse it.
  313. return m_table;
  314. }
  315. m_packColorProc = proc;
  316. m_transPixel = transparentPixel;
  317. const size_t bytes = m_colors * SK_BYTES_PER_COLORMAP_ENTRY;
  318. sk_sp<SkData> rawData(streamBuffer->getDataAtPosition(m_position, bytes));
  319. if (!rawData) {
  320. return nullptr;
  321. }
  322. SkASSERT(m_colors <= SK_MAX_COLORS);
  323. const uint8_t* srcColormap = rawData->bytes();
  324. SkPMColor colorStorage[SK_MAX_COLORS];
  325. for (int i = 0; i < m_colors; i++) {
  326. if (i == transparentPixel) {
  327. colorStorage[i] = SK_ColorTRANSPARENT;
  328. } else {
  329. colorStorage[i] = proc(255, srcColormap[0], srcColormap[1], srcColormap[2]);
  330. }
  331. srcColormap += SK_BYTES_PER_COLORMAP_ENTRY;
  332. }
  333. for (int i = m_colors; i < SK_MAX_COLORS; i++) {
  334. colorStorage[i] = SK_ColorTRANSPARENT;
  335. }
  336. m_table = sk_sp<SkColorTable>(new SkColorTable(colorStorage, SK_MAX_COLORS));
  337. return m_table;
  338. }
  339. sk_sp<SkColorTable> SkGifImageReader::getColorTable(SkColorType colorType, int index) {
  340. if (index < 0 || index >= m_frames.count()) {
  341. return nullptr;
  342. }
  343. const SkGIFFrameContext* frameContext = m_frames[index].get();
  344. const SkGIFColorMap& localColorMap = frameContext->localColorMap();
  345. const int transPix = frameContext->transparentPixel();
  346. if (localColorMap.isDefined()) {
  347. return localColorMap.buildTable(&m_streamBuffer, colorType, transPix);
  348. }
  349. if (m_globalColorMap.isDefined()) {
  350. return m_globalColorMap.buildTable(&m_streamBuffer, colorType, transPix);
  351. }
  352. return nullptr;
  353. }
  354. // Perform decoding for this frame. frameComplete will be true if the entire frame is decoded.
  355. // Returns false if a decoding error occurred. This is a fatal error and causes the SkGifImageReader to set the "decode failed" flag.
  356. // 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.
  357. bool SkGIFFrameContext::decode(SkStreamBuffer* streamBuffer, SkGifCodec* client,
  358. bool* frameComplete)
  359. {
  360. *frameComplete = false;
  361. if (!m_lzwContext) {
  362. // Wait for more data to properly initialize SkGIFLZWContext.
  363. if (!isDataSizeDefined() || !isHeaderDefined())
  364. return true;
  365. m_lzwContext.reset(new SkGIFLZWContext(client, this));
  366. if (!m_lzwContext->prepareToDecode()) {
  367. m_lzwContext.reset();
  368. return false;
  369. }
  370. m_currentLzwBlock = 0;
  371. }
  372. // Some bad GIFs have extra blocks beyond the last row, which we don't want to decode.
  373. while (m_currentLzwBlock < m_lzwBlocks.count() && m_lzwContext->hasRemainingRows()) {
  374. const auto& block = m_lzwBlocks[m_currentLzwBlock];
  375. const size_t len = block.blockSize;
  376. sk_sp<SkData> data(streamBuffer->getDataAtPosition(block.blockPosition, len));
  377. if (!data) {
  378. return false;
  379. }
  380. if (!m_lzwContext->doLZW(reinterpret_cast<const unsigned char*>(data->data()), len)) {
  381. return false;
  382. }
  383. ++m_currentLzwBlock;
  384. }
  385. // If this frame is data complete then the previous loop must have completely decoded all LZW blocks.
  386. // There will be no more decoding for this frame so it's time to cleanup.
  387. if (isComplete()) {
  388. *frameComplete = true;
  389. m_lzwContext.reset();
  390. }
  391. return true;
  392. }
  393. // Decode a frame.
  394. // This method uses SkGIFFrameContext:decode() to decode the frame; decoding error is reported to client as a critical failure.
  395. // Return true if decoding has progressed. Return false if an error has occurred.
  396. bool SkGifImageReader::decode(int frameIndex, bool* frameComplete)
  397. {
  398. SkGIFFrameContext* currentFrame = m_frames[frameIndex].get();
  399. return currentFrame->decode(&m_streamBuffer, m_client, frameComplete);
  400. }
  401. // Parse incoming GIF data stream into internal data structures.
  402. SkCodec::Result SkGifImageReader::parse(SkGifImageReader::SkGIFParseQuery query)
  403. {
  404. if (m_parseCompleted) {
  405. return SkCodec::kSuccess;
  406. }
  407. if (SkGIFLoopCountQuery == query && m_loopCount != cLoopCountNotSeen) {
  408. // Loop count has already been parsed.
  409. return SkCodec::kSuccess;
  410. }
  411. // SkGIFSizeQuery and SkGIFFrameCountQuery are negative, so this is only meaningful when >= 0.
  412. const int lastFrameToParse = (int) query;
  413. if (lastFrameToParse >= 0 && m_frames.count() > lastFrameToParse
  414. && m_frames[lastFrameToParse]->isComplete()) {
  415. // We have already parsed this frame.
  416. return SkCodec::kSuccess;
  417. }
  418. while (true) {
  419. if (!m_streamBuffer.buffer(m_bytesToConsume)) {
  420. // The stream does not yet have enough data.
  421. return SkCodec::kIncompleteInput;
  422. }
  423. switch (m_state) {
  424. case SkGIFLZW: {
  425. SkASSERT(!m_frames.empty());
  426. auto* frame = m_frames.back().get();
  427. frame->addLzwBlock(m_streamBuffer.markPosition(), m_bytesToConsume);
  428. GETN(1, SkGIFSubBlock);
  429. break;
  430. }
  431. case SkGIFLZWStart: {
  432. SkASSERT(!m_frames.empty());
  433. auto* currentFrame = m_frames.back().get();
  434. currentFrame->setDataSize(this->getOneByte());
  435. GETN(1, SkGIFSubBlock);
  436. break;
  437. }
  438. case SkGIFType: {
  439. const char* currentComponent = m_streamBuffer.get();
  440. // All GIF files begin with "GIF87a" or "GIF89a".
  441. if (!memcmp(currentComponent, "GIF89a", 6))
  442. m_version = 89;
  443. else if (!memcmp(currentComponent, "GIF87a", 6))
  444. m_version = 87;
  445. else {
  446. // This prevents attempting to continue reading this invalid stream.
  447. GETN(0, SkGIFDone);
  448. return SkCodec::kInvalidInput;
  449. }
  450. GETN(7, SkGIFGlobalHeader);
  451. break;
  452. }
  453. case SkGIFGlobalHeader: {
  454. const unsigned char* currentComponent =
  455. reinterpret_cast<const unsigned char*>(m_streamBuffer.get());
  456. // This is the height and width of the "screen" or frame into which
  457. // images are rendered. The individual images can be smaller than
  458. // the screen size and located with an origin anywhere within the
  459. // screen.
  460. // Note that we don't inform the client of the size yet, as it might
  461. // change after we read the first frame's image header.
  462. fScreenWidth = GETINT16(currentComponent);
  463. fScreenHeight = GETINT16(currentComponent + 2);
  464. const int globalColorMapColors = 2 << (currentComponent[4] & 0x07);
  465. if ((currentComponent[4] & 0x80) && globalColorMapColors > 0) { /* global map */
  466. m_globalColorMap.setNumColors(globalColorMapColors);
  467. GETN(SK_BYTES_PER_COLORMAP_ENTRY * globalColorMapColors, SkGIFGlobalColormap);
  468. break;
  469. }
  470. GETN(1, SkGIFImageStart);
  471. break;
  472. }
  473. case SkGIFGlobalColormap: {
  474. m_globalColorMap.setTablePosition(m_streamBuffer.markPosition());
  475. GETN(1, SkGIFImageStart);
  476. break;
  477. }
  478. case SkGIFImageStart: {
  479. const char currentComponent = m_streamBuffer.get()[0];
  480. if (currentComponent == '!') { // extension.
  481. GETN(2, SkGIFExtension);
  482. break;
  483. }
  484. if (currentComponent == ',') { // image separator.
  485. GETN(9, SkGIFImageHeader);
  486. break;
  487. }
  488. // If we get anything other than ',' (image separator), '!'
  489. // (extension), or ';' (trailer), there is extraneous data
  490. // between blocks. The GIF87a spec tells us to keep reading
  491. // until we find an image separator, but GIF89a says such
  492. // a file is corrupt. We follow Mozilla's implementation and
  493. // proceed as if the file were correctly terminated, so the
  494. // GIF will display.
  495. GETN(0, SkGIFDone);
  496. break;
  497. }
  498. case SkGIFExtension: {
  499. const unsigned char* currentComponent =
  500. reinterpret_cast<const unsigned char*>(m_streamBuffer.get());
  501. size_t bytesInBlock = currentComponent[1];
  502. SkGIFState exceptionState = SkGIFSkipBlock;
  503. switch (*currentComponent) {
  504. case 0xf9:
  505. // The GIF spec mandates that the GIFControlExtension header block length is 4 bytes,
  506. exceptionState = SkGIFControlExtension;
  507. // and the parser for this block reads 4 bytes, so we must enforce that the buffer
  508. // contains at least this many bytes. If the GIF specifies a different length, we
  509. // allow that, so long as it's larger; the additional data will simply be ignored.
  510. bytesInBlock = std::max(bytesInBlock, static_cast<size_t>(4));
  511. break;
  512. // The GIF spec also specifies the lengths of the following two extensions' headers
  513. // (as 12 and 11 bytes, respectively). Because we ignore the plain text extension entirely
  514. // and sanity-check the actual length of the application extension header before reading it,
  515. // we allow GIFs to deviate from these values in either direction. This is important for
  516. // real-world compatibility, as GIFs in the wild exist with application extension headers
  517. // that are both shorter and longer than 11 bytes.
  518. case 0x01:
  519. // ignoring plain text extension
  520. break;
  521. case 0xff:
  522. exceptionState = SkGIFApplicationExtension;
  523. break;
  524. case 0xfe:
  525. exceptionState = SkGIFConsumeComment;
  526. break;
  527. }
  528. if (bytesInBlock)
  529. GETN(bytesInBlock, exceptionState);
  530. else
  531. GETN(1, SkGIFImageStart);
  532. break;
  533. }
  534. case SkGIFConsumeBlock: {
  535. const unsigned char currentComponent = this->getOneByte();
  536. if (!currentComponent)
  537. GETN(1, SkGIFImageStart);
  538. else
  539. GETN(currentComponent, SkGIFSkipBlock);
  540. break;
  541. }
  542. case SkGIFSkipBlock: {
  543. GETN(1, SkGIFConsumeBlock);
  544. break;
  545. }
  546. case SkGIFControlExtension: {
  547. const unsigned char* currentComponent =
  548. reinterpret_cast<const unsigned char*>(m_streamBuffer.get());
  549. addFrameIfNecessary();
  550. SkGIFFrameContext* currentFrame = m_frames.back().get();
  551. if (*currentComponent & 0x1)
  552. currentFrame->setTransparentPixel(currentComponent[3]);
  553. // We ignore the "user input" bit.
  554. // NOTE: This relies on the values in the FrameDisposalMethod enum
  555. // matching those in the GIF spec!
  556. int rawDisposalMethod = ((*currentComponent) >> 2) & 0x7;
  557. switch (rawDisposalMethod) {
  558. case 1:
  559. case 2:
  560. case 3:
  561. currentFrame->setDisposalMethod((SkCodecAnimation::DisposalMethod) rawDisposalMethod);
  562. break;
  563. case 4:
  564. // Some specs say that disposal method 3 is "overwrite previous", others that setting
  565. // the third bit of the field (i.e. method 4) is. We map both to the same value.
  566. currentFrame->setDisposalMethod(SkCodecAnimation::DisposalMethod::kRestorePrevious);
  567. break;
  568. default:
  569. // Other values use the default.
  570. currentFrame->setDisposalMethod(SkCodecAnimation::DisposalMethod::kKeep);
  571. break;
  572. }
  573. currentFrame->setDuration(GETINT16(currentComponent + 1) * 10);
  574. GETN(1, SkGIFConsumeBlock);
  575. break;
  576. }
  577. case SkGIFCommentExtension: {
  578. const unsigned char currentComponent = this->getOneByte();
  579. if (currentComponent)
  580. GETN(currentComponent, SkGIFConsumeComment);
  581. else
  582. GETN(1, SkGIFImageStart);
  583. break;
  584. }
  585. case SkGIFConsumeComment: {
  586. GETN(1, SkGIFCommentExtension);
  587. break;
  588. }
  589. case SkGIFApplicationExtension: {
  590. // Check for netscape application extension.
  591. if (m_bytesToConsume == 11) {
  592. const unsigned char* currentComponent =
  593. reinterpret_cast<const unsigned char*>(m_streamBuffer.get());
  594. if (!memcmp(currentComponent, "NETSCAPE2.0", 11) || !memcmp(currentComponent, "ANIMEXTS1.0", 11))
  595. GETN(1, SkGIFNetscapeExtensionBlock);
  596. }
  597. if (m_state != SkGIFNetscapeExtensionBlock)
  598. GETN(1, SkGIFConsumeBlock);
  599. break;
  600. }
  601. // Netscape-specific GIF extension: animation looping.
  602. case SkGIFNetscapeExtensionBlock: {
  603. const int currentComponent = this->getOneByte();
  604. // SkGIFConsumeNetscapeExtension always reads 3 bytes from the stream; we should at least wait for this amount.
  605. if (currentComponent)
  606. GETN(std::max(3, currentComponent), SkGIFConsumeNetscapeExtension);
  607. else
  608. GETN(1, SkGIFImageStart);
  609. break;
  610. }
  611. // Parse netscape-specific application extensions
  612. case SkGIFConsumeNetscapeExtension: {
  613. const unsigned char* currentComponent =
  614. reinterpret_cast<const unsigned char*>(m_streamBuffer.get());
  615. int netscapeExtension = currentComponent[0] & 7;
  616. // Loop entire animation specified # of times. Only read the loop count during the first iteration.
  617. if (netscapeExtension == 1) {
  618. m_loopCount = GETINT16(currentComponent + 1);
  619. // Zero loop count is infinite animation loop request.
  620. if (!m_loopCount)
  621. m_loopCount = SkCodec::kRepetitionCountInfinite;
  622. GETN(1, SkGIFNetscapeExtensionBlock);
  623. if (SkGIFLoopCountQuery == query) {
  624. m_streamBuffer.flush();
  625. return SkCodec::kSuccess;
  626. }
  627. } else if (netscapeExtension == 2) {
  628. // Wait for specified # of bytes to enter buffer.
  629. // Don't do this, this extension doesn't exist (isn't used at all)
  630. // and doesn't do anything, as our streaming/buffering takes care of it all...
  631. // See: http://semmix.pl/color/exgraf/eeg24.htm
  632. GETN(1, SkGIFNetscapeExtensionBlock);
  633. } else {
  634. // 0,3-7 are yet to be defined netscape extension codes
  635. // This prevents attempting to continue reading this invalid stream.
  636. GETN(0, SkGIFDone);
  637. return SkCodec::kInvalidInput;
  638. }
  639. break;
  640. }
  641. case SkGIFImageHeader: {
  642. int height, width, xOffset, yOffset;
  643. const unsigned char* currentComponent =
  644. reinterpret_cast<const unsigned char*>(m_streamBuffer.get());
  645. /* Get image offsets, with respect to the screen origin */
  646. xOffset = GETINT16(currentComponent);
  647. yOffset = GETINT16(currentComponent + 2);
  648. /* Get image width and height. */
  649. width = GETINT16(currentComponent + 4);
  650. height = GETINT16(currentComponent + 6);
  651. // Some GIF files have frames that don't fit in the specified
  652. // overall image size. For the first frame, we can simply enlarge
  653. // the image size to allow the frame to be visible. We can't do
  654. // this on subsequent frames because the rest of the decoding
  655. // infrastructure assumes the image size won't change as we
  656. // continue decoding, so any subsequent frames that are even
  657. // larger will be cropped.
  658. // Luckily, handling just the first frame is sufficient to deal
  659. // with most cases, e.g. ones where the image size is erroneously
  660. // set to zero, since usually the first frame completely fills
  661. // the image.
  662. if (currentFrameIsFirstFrame()) {
  663. fScreenHeight = std::max(fScreenHeight, yOffset + height);
  664. fScreenWidth = std::max(fScreenWidth, xOffset + width);
  665. }
  666. // NOTE: Chromium placed this block after setHeaderDefined, down
  667. // below we returned true when asked for the size. So Chromium
  668. // created an image which would fail. Is this the correct behavior?
  669. // We choose to return false early, so we will not create an
  670. // SkCodec.
  671. // Work around more broken GIF files that have zero image width or
  672. // height.
  673. if (!height || !width) {
  674. height = fScreenHeight;
  675. width = fScreenWidth;
  676. if (!height || !width) {
  677. // This prevents attempting to continue reading this invalid stream.
  678. GETN(0, SkGIFDone);
  679. return SkCodec::kInvalidInput;
  680. }
  681. }
  682. const bool isLocalColormapDefined = SkToBool(currentComponent[8] & 0x80);
  683. // The three low-order bits of currentComponent[8] specify the bits per pixel.
  684. const int numColors = 2 << (currentComponent[8] & 0x7);
  685. if (currentFrameIsFirstFrame()) {
  686. const int transPix = m_frames.empty() ? SkGIFColorMap::kNotFound
  687. : m_frames[0]->transparentPixel();
  688. if (is_palette_index_valid(transPix)) {
  689. m_firstFrameHasAlpha = true;
  690. } else {
  691. const bool frameIsSubset = xOffset > 0 || yOffset > 0
  692. || width < fScreenWidth
  693. || height < fScreenHeight;
  694. m_firstFrameHasAlpha = frameIsSubset;
  695. }
  696. }
  697. addFrameIfNecessary();
  698. SkGIFFrameContext* currentFrame = m_frames.back().get();
  699. currentFrame->setHeaderDefined();
  700. if (query == SkGIFSizeQuery) {
  701. // The decoder needs to stop, so we return here, before
  702. // flushing the buffer. Next time through, we'll be in the same
  703. // state, requiring the same amount in the buffer.
  704. return SkCodec::kSuccess;
  705. }
  706. currentFrame->setXYWH(xOffset, yOffset, width, height);
  707. currentFrame->setInterlaced(SkToBool(currentComponent[8] & 0x40));
  708. // Overlaying interlaced, transparent GIFs over
  709. // existing image data using the Haeberli display hack
  710. // requires saving the underlying image in order to
  711. // avoid jaggies at the transparency edges. We are
  712. // unprepared to deal with that, so don't display such
  713. // images progressively. Which means only the first
  714. // frame can be progressively displayed.
  715. // FIXME: It is possible that a non-transparent frame
  716. // can be interlaced and progressively displayed.
  717. currentFrame->setProgressiveDisplay(currentFrameIsFirstFrame());
  718. if (isLocalColormapDefined) {
  719. currentFrame->localColorMap().setNumColors(numColors);
  720. GETN(SK_BYTES_PER_COLORMAP_ENTRY * numColors, SkGIFImageColormap);
  721. break;
  722. }
  723. setAlphaAndRequiredFrame(currentFrame);
  724. GETN(1, SkGIFLZWStart);
  725. break;
  726. }
  727. case SkGIFImageColormap: {
  728. SkASSERT(!m_frames.empty());
  729. auto* currentFrame = m_frames.back().get();
  730. auto& cmap = currentFrame->localColorMap();
  731. cmap.setTablePosition(m_streamBuffer.markPosition());
  732. setAlphaAndRequiredFrame(currentFrame);
  733. GETN(1, SkGIFLZWStart);
  734. break;
  735. }
  736. case SkGIFSubBlock: {
  737. const size_t bytesInBlock = this->getOneByte();
  738. if (bytesInBlock)
  739. GETN(bytesInBlock, SkGIFLZW);
  740. else {
  741. // Finished parsing one frame; Process next frame.
  742. SkASSERT(!m_frames.empty());
  743. // Note that some broken GIF files do not have enough LZW blocks to fully
  744. // decode all rows but we treat it as frame complete.
  745. m_frames.back()->setComplete();
  746. GETN(1, SkGIFImageStart);
  747. if (lastFrameToParse >= 0 && m_frames.count() > lastFrameToParse) {
  748. m_streamBuffer.flush();
  749. return SkCodec::kSuccess;
  750. }
  751. }
  752. break;
  753. }
  754. case SkGIFDone: {
  755. m_parseCompleted = true;
  756. return SkCodec::kSuccess;
  757. }
  758. default:
  759. // We shouldn't ever get here.
  760. // This prevents attempting to continue reading this invalid stream.
  761. GETN(0, SkGIFDone);
  762. return SkCodec::kInvalidInput;
  763. break;
  764. } // switch
  765. m_streamBuffer.flush();
  766. }
  767. }
  768. void SkGifImageReader::addFrameIfNecessary()
  769. {
  770. if (m_frames.empty() || m_frames.back()->isComplete()) {
  771. const int i = m_frames.count();
  772. m_frames.emplace_back(new SkGIFFrameContext(i));
  773. }
  774. }
  775. SkEncodedInfo::Alpha SkGIFFrameContext::onReportedAlpha() const {
  776. // Note: We could correct these after decoding - i.e. some frames may turn out to be
  777. // independent and opaque if they do not use the transparent pixel, but that would require
  778. // checking whether each pixel used the transparent index.
  779. return is_palette_index_valid(this->transparentPixel()) ? SkEncodedInfo::kBinary_Alpha
  780. : SkEncodedInfo::kOpaque_Alpha;
  781. }
  782. // FIXME: Move this method to close to doLZW().
  783. bool SkGIFLZWContext::prepareToDecode()
  784. {
  785. SkASSERT(m_frameContext->isDataSizeDefined() && m_frameContext->isHeaderDefined());
  786. // Since we use a codesize of 1 more than the datasize, we need to ensure
  787. // that our datasize is strictly less than the SK_MAX_DICTIONARY_ENTRY_BITS.
  788. if (m_frameContext->dataSize() >= SK_MAX_DICTIONARY_ENTRY_BITS)
  789. return false;
  790. clearCode = 1 << m_frameContext->dataSize();
  791. avail = clearCode + 2;
  792. oldcode = -1;
  793. codesize = m_frameContext->dataSize() + 1;
  794. codemask = (1 << codesize) - 1;
  795. datum = bits = 0;
  796. ipass = m_frameContext->interlaced() ? 1 : 0;
  797. irow = 0;
  798. // We want to know the longest sequence encodable by a dictionary with
  799. // SK_MAX_DICTIONARY_ENTRIES entries. If we ignore the need to encode the base
  800. // values themselves at the beginning of the dictionary, as well as the need
  801. // for a clear code or a termination code, we could use every entry to
  802. // encode a series of multiple values. If the input value stream looked
  803. // like "AAAAA..." (a long string of just one value), the first dictionary
  804. // entry would encode AA, the next AAA, the next AAAA, and so forth. Thus
  805. // the longest sequence would be SK_MAX_DICTIONARY_ENTRIES + 1 values.
  806. //
  807. // However, we have to account for reserved entries. The first |datasize|
  808. // bits are reserved for the base values, and the next two entries are
  809. // reserved for the clear code and termination code. In theory a GIF can
  810. // set the datasize to 0, meaning we have just two reserved entries, making
  811. // the longest sequence (SK_MAX_DICTIONARY_ENTIRES + 1) - 2 values long. Since
  812. // each value is a byte, this is also the number of bytes in the longest
  813. // encodable sequence.
  814. constexpr size_t kMaxSequence = SK_MAX_DICTIONARY_ENTRIES - 1;
  815. constexpr size_t kMaxBytes = (kMaxSequence + SK_DICTIONARY_WORD_SIZE - 1)
  816. & ~(SK_DICTIONARY_WORD_SIZE - 1);
  817. // Now allocate the output buffer. We decode directly into this buffer
  818. // until we have at least one row worth of data, then call outputRow().
  819. // This means worst case we may have (row width - 1) bytes in the buffer
  820. // and then decode a sequence |kMaxBytes| long to append.
  821. rowBuffer.reset(m_frameContext->width() - 1 + kMaxBytes);
  822. rowIter = rowBuffer.begin();
  823. rowsRemaining = m_frameContext->height();
  824. // Clearing the whole suffix table lets us be more tolerant of bad data.
  825. for (int i = 0; i < clearCode; ++i) {
  826. std::fill_n(suffix[i].begin(), SK_DICTIONARY_WORD_SIZE, 0);
  827. suffix[i][0] = i;
  828. suffixLength[i] = 1;
  829. prefix[i] = i; // ensure that we have a place to find firstchar
  830. }
  831. return true;
  832. }