SkBmpRLECodec.cpp 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  1. /*
  2. * Copyright 2015 Google Inc.
  3. *
  4. * Use of this source code is governed by a BSD-style license that can be
  5. * found in the LICENSE file.
  6. */
  7. #include "include/core/SkStream.h"
  8. #include "include/private/SkColorData.h"
  9. #include "src/codec/SkBmpRLECodec.h"
  10. #include "src/codec/SkCodecPriv.h"
  11. /*
  12. * Creates an instance of the decoder
  13. * Called only by NewFromStream
  14. */
  15. SkBmpRLECodec::SkBmpRLECodec(SkEncodedInfo&& info,
  16. std::unique_ptr<SkStream> stream,
  17. uint16_t bitsPerPixel, uint32_t numColors,
  18. uint32_t bytesPerColor, uint32_t offset,
  19. SkCodec::SkScanlineOrder rowOrder)
  20. : INHERITED(std::move(info), std::move(stream), bitsPerPixel, rowOrder)
  21. , fColorTable(nullptr)
  22. , fNumColors(numColors)
  23. , fBytesPerColor(bytesPerColor)
  24. , fOffset(offset)
  25. , fBytesBuffered(0)
  26. , fCurrRLEByte(0)
  27. , fSampleX(1)
  28. {}
  29. /*
  30. * Initiates the bitmap decode
  31. */
  32. SkCodec::Result SkBmpRLECodec::onGetPixels(const SkImageInfo& dstInfo,
  33. void* dst, size_t dstRowBytes,
  34. const Options& opts,
  35. int* rowsDecoded) {
  36. if (opts.fSubset) {
  37. // Subsets are not supported.
  38. return kUnimplemented;
  39. }
  40. Result result = this->prepareToDecode(dstInfo, opts);
  41. if (kSuccess != result) {
  42. return result;
  43. }
  44. // Perform the decode
  45. int rows = this->decodeRows(dstInfo, dst, dstRowBytes, opts);
  46. if (rows != dstInfo.height()) {
  47. // We set rowsDecoded equal to the height because the background has already
  48. // been filled. RLE encodings sometimes skip pixels, so we always start by
  49. // filling the background.
  50. *rowsDecoded = dstInfo.height();
  51. return kIncompleteInput;
  52. }
  53. return kSuccess;
  54. }
  55. /*
  56. * Process the color table for the bmp input
  57. */
  58. bool SkBmpRLECodec::createColorTable(SkColorType dstColorType) {
  59. // Allocate memory for color table
  60. uint32_t colorBytes = 0;
  61. SkPMColor colorTable[256];
  62. if (this->bitsPerPixel() <= 8) {
  63. // Inform the caller of the number of colors
  64. uint32_t maxColors = 1 << this->bitsPerPixel();
  65. // Don't bother reading more than maxColors.
  66. const uint32_t numColorsToRead =
  67. fNumColors == 0 ? maxColors : SkTMin(fNumColors, maxColors);
  68. // Read the color table from the stream
  69. colorBytes = numColorsToRead * fBytesPerColor;
  70. std::unique_ptr<uint8_t[]> cBuffer(new uint8_t[colorBytes]);
  71. if (stream()->read(cBuffer.get(), colorBytes) != colorBytes) {
  72. SkCodecPrintf("Error: unable to read color table.\n");
  73. return false;
  74. }
  75. // Fill in the color table
  76. PackColorProc packARGB = choose_pack_color_proc(false, dstColorType);
  77. uint32_t i = 0;
  78. for (; i < numColorsToRead; i++) {
  79. uint8_t blue = get_byte(cBuffer.get(), i*fBytesPerColor);
  80. uint8_t green = get_byte(cBuffer.get(), i*fBytesPerColor + 1);
  81. uint8_t red = get_byte(cBuffer.get(), i*fBytesPerColor + 2);
  82. colorTable[i] = packARGB(0xFF, red, green, blue);
  83. }
  84. // To avoid segmentation faults on bad pixel data, fill the end of the
  85. // color table with black. This is the same the behavior as the
  86. // chromium decoder.
  87. for (; i < maxColors; i++) {
  88. colorTable[i] = SkPackARGB32NoCheck(0xFF, 0, 0, 0);
  89. }
  90. // Set the color table
  91. fColorTable.reset(new SkColorTable(colorTable, maxColors));
  92. }
  93. // Check that we have not read past the pixel array offset
  94. if(fOffset < colorBytes) {
  95. // This may occur on OS 2.1 and other old versions where the color
  96. // table defaults to max size, and the bmp tries to use a smaller
  97. // color table. This is invalid, and our decision is to indicate
  98. // an error, rather than try to guess the intended size of the
  99. // color table.
  100. SkCodecPrintf("Error: pixel data offset less than color table size.\n");
  101. return false;
  102. }
  103. // After reading the color table, skip to the start of the pixel array
  104. if (stream()->skip(fOffset - colorBytes) != fOffset - colorBytes) {
  105. SkCodecPrintf("Error: unable to skip to image data.\n");
  106. return false;
  107. }
  108. // Return true on success
  109. return true;
  110. }
  111. bool SkBmpRLECodec::initializeStreamBuffer() {
  112. fBytesBuffered = this->stream()->read(fStreamBuffer, kBufferSize);
  113. if (fBytesBuffered == 0) {
  114. SkCodecPrintf("Error: could not read RLE image data.\n");
  115. return false;
  116. }
  117. fCurrRLEByte = 0;
  118. return true;
  119. }
  120. /*
  121. * @return the number of bytes remaining in the stream buffer after
  122. * attempting to read more bytes from the stream
  123. */
  124. size_t SkBmpRLECodec::checkForMoreData() {
  125. const size_t remainingBytes = fBytesBuffered - fCurrRLEByte;
  126. uint8_t* buffer = fStreamBuffer;
  127. // We will be reusing the same buffer, starting over from the beginning.
  128. // Move any remaining bytes to the start of the buffer.
  129. // We use memmove() instead of memcpy() because there is risk that the dst
  130. // and src memory will overlap in corrupt images.
  131. memmove(buffer, SkTAddOffset<uint8_t>(buffer, fCurrRLEByte), remainingBytes);
  132. // Adjust the buffer ptr to the start of the unfilled data.
  133. buffer += remainingBytes;
  134. // Try to read additional bytes from the stream. There are fCurrRLEByte
  135. // bytes of additional space remaining in the buffer, assuming that we
  136. // have already copied remainingBytes to the start of the buffer.
  137. size_t additionalBytes = this->stream()->read(buffer, fCurrRLEByte);
  138. // Update counters and return the number of bytes we currently have
  139. // available. We are at the start of the buffer again.
  140. fCurrRLEByte = 0;
  141. fBytesBuffered = remainingBytes + additionalBytes;
  142. return fBytesBuffered;
  143. }
  144. /*
  145. * Set an RLE pixel using the color table
  146. */
  147. void SkBmpRLECodec::setPixel(void* dst, size_t dstRowBytes,
  148. const SkImageInfo& dstInfo, uint32_t x, uint32_t y,
  149. uint8_t index) {
  150. if (dst && is_coord_necessary(x, fSampleX, dstInfo.width())) {
  151. // Set the row
  152. uint32_t row = this->getDstRow(y, dstInfo.height());
  153. // Set the pixel based on destination color type
  154. const int dstX = get_dst_coord(x, fSampleX);
  155. switch (dstInfo.colorType()) {
  156. case kRGBA_8888_SkColorType:
  157. case kBGRA_8888_SkColorType: {
  158. SkPMColor* dstRow = SkTAddOffset<SkPMColor>(dst, row * (int) dstRowBytes);
  159. dstRow[dstX] = fColorTable->operator[](index);
  160. break;
  161. }
  162. case kRGB_565_SkColorType: {
  163. uint16_t* dstRow = SkTAddOffset<uint16_t>(dst, row * (int) dstRowBytes);
  164. dstRow[dstX] = SkPixel32ToPixel16(fColorTable->operator[](index));
  165. break;
  166. }
  167. default:
  168. // This case should not be reached. We should catch an invalid
  169. // color type when we check that the conversion is possible.
  170. SkASSERT(false);
  171. break;
  172. }
  173. }
  174. }
  175. /*
  176. * Set an RLE pixel from R, G, B values
  177. */
  178. void SkBmpRLECodec::setRGBPixel(void* dst, size_t dstRowBytes,
  179. const SkImageInfo& dstInfo, uint32_t x,
  180. uint32_t y, uint8_t red, uint8_t green,
  181. uint8_t blue) {
  182. if (dst && is_coord_necessary(x, fSampleX, dstInfo.width())) {
  183. // Set the row
  184. uint32_t row = this->getDstRow(y, dstInfo.height());
  185. // Set the pixel based on destination color type
  186. const int dstX = get_dst_coord(x, fSampleX);
  187. switch (dstInfo.colorType()) {
  188. case kRGBA_8888_SkColorType: {
  189. SkPMColor* dstRow = SkTAddOffset<SkPMColor>(dst, row * (int) dstRowBytes);
  190. dstRow[dstX] = SkPackARGB_as_RGBA(0xFF, red, green, blue);
  191. break;
  192. }
  193. case kBGRA_8888_SkColorType: {
  194. SkPMColor* dstRow = SkTAddOffset<SkPMColor>(dst, row * (int) dstRowBytes);
  195. dstRow[dstX] = SkPackARGB_as_BGRA(0xFF, red, green, blue);
  196. break;
  197. }
  198. case kRGB_565_SkColorType: {
  199. uint16_t* dstRow = SkTAddOffset<uint16_t>(dst, row * (int) dstRowBytes);
  200. dstRow[dstX] = SkPack888ToRGB16(red, green, blue);
  201. break;
  202. }
  203. default:
  204. // This case should not be reached. We should catch an invalid
  205. // color type when we check that the conversion is possible.
  206. SkASSERT(false);
  207. break;
  208. }
  209. }
  210. }
  211. SkCodec::Result SkBmpRLECodec::onPrepareToDecode(const SkImageInfo& dstInfo,
  212. const SkCodec::Options& options) {
  213. // FIXME: Support subsets for scanline decodes.
  214. if (options.fSubset) {
  215. // Subsets are not supported.
  216. return kUnimplemented;
  217. }
  218. // Reset fSampleX. If it needs to be a value other than 1, it will get modified by
  219. // the sampler.
  220. fSampleX = 1;
  221. fLinesToSkip = 0;
  222. SkColorType colorTableColorType = dstInfo.colorType();
  223. if (this->colorXform()) {
  224. // Just set a known colorType for the colorTable. No need to actually transform
  225. // the colors in the colorTable.
  226. colorTableColorType = kBGRA_8888_SkColorType;
  227. }
  228. // Create the color table if necessary and prepare the stream for decode
  229. // Note that if it is non-NULL, inputColorCount will be modified
  230. if (!this->createColorTable(colorTableColorType)) {
  231. SkCodecPrintf("Error: could not create color table.\n");
  232. return SkCodec::kInvalidInput;
  233. }
  234. // Initialize a buffer for encoded RLE data
  235. if (!this->initializeStreamBuffer()) {
  236. SkCodecPrintf("Error: cannot initialize stream buffer.\n");
  237. return SkCodec::kInvalidInput;
  238. }
  239. return SkCodec::kSuccess;
  240. }
  241. /*
  242. * Performs the bitmap decoding for RLE input format
  243. * RLE decoding is performed all at once, rather than a one row at a time
  244. */
  245. int SkBmpRLECodec::decodeRows(const SkImageInfo& info, void* dst, size_t dstRowBytes,
  246. const Options& opts) {
  247. int height = info.height();
  248. // Account for sampling.
  249. SkImageInfo dstInfo = info.makeWH(this->fillWidth(), height);
  250. // Set the background as transparent. Then, if the RLE code skips pixels,
  251. // the skipped pixels will be transparent.
  252. if (dst) {
  253. SkSampler::Fill(dstInfo, dst, dstRowBytes, opts.fZeroInitialized);
  254. }
  255. // Adjust the height and the dst if the previous call to decodeRows() left us
  256. // with lines that need to be skipped.
  257. if (height > fLinesToSkip) {
  258. height -= fLinesToSkip;
  259. if (dst) {
  260. dst = SkTAddOffset<void>(dst, fLinesToSkip * dstRowBytes);
  261. }
  262. fLinesToSkip = 0;
  263. dstInfo = dstInfo.makeWH(dstInfo.width(), height);
  264. } else {
  265. fLinesToSkip -= height;
  266. return height;
  267. }
  268. void* decodeDst = dst;
  269. size_t decodeRowBytes = dstRowBytes;
  270. SkImageInfo decodeInfo = dstInfo;
  271. if (decodeDst) {
  272. if (this->colorXform()) {
  273. decodeInfo = decodeInfo.makeColorType(kXformSrcColorType);
  274. if (kRGBA_F16_SkColorType == dstInfo.colorType()) {
  275. int count = height * dstInfo.width();
  276. this->resetXformBuffer(count);
  277. sk_bzero(this->xformBuffer(), count * sizeof(uint32_t));
  278. decodeDst = this->xformBuffer();
  279. decodeRowBytes = dstInfo.width() * sizeof(uint32_t);
  280. }
  281. }
  282. }
  283. int decodedHeight = this->decodeRLE(decodeInfo, decodeDst, decodeRowBytes);
  284. if (this->colorXform() && decodeDst) {
  285. for (int y = 0; y < decodedHeight; y++) {
  286. this->applyColorXform(dst, decodeDst, dstInfo.width());
  287. decodeDst = SkTAddOffset<void>(decodeDst, decodeRowBytes);
  288. dst = SkTAddOffset<void>(dst, dstRowBytes);
  289. }
  290. }
  291. return decodedHeight;
  292. }
  293. int SkBmpRLECodec::decodeRLE(const SkImageInfo& dstInfo, void* dst, size_t dstRowBytes) {
  294. // Use the original width to count the number of pixels in each row.
  295. const int width = this->dimensions().width();
  296. // This tells us the number of rows that we are meant to decode.
  297. const int height = dstInfo.height();
  298. // Set RLE flags
  299. constexpr uint8_t RLE_ESCAPE = 0;
  300. constexpr uint8_t RLE_EOL = 0;
  301. constexpr uint8_t RLE_EOF = 1;
  302. constexpr uint8_t RLE_DELTA = 2;
  303. // Destination parameters
  304. int x = 0;
  305. int y = 0;
  306. while (true) {
  307. // If we have reached a row that is beyond the requested height, we have
  308. // succeeded.
  309. if (y >= height) {
  310. // It would be better to check for the EOF marker before indicating
  311. // success, but we may be performing a scanline decode, which
  312. // would require us to stop before decoding the full height.
  313. return height;
  314. }
  315. // Every entry takes at least two bytes
  316. if ((int) fBytesBuffered - fCurrRLEByte < 2) {
  317. if (this->checkForMoreData() < 2) {
  318. return y;
  319. }
  320. }
  321. // Read the next two bytes. These bytes have different meanings
  322. // depending on their values. In the first interpretation, the first
  323. // byte is an escape flag and the second byte indicates what special
  324. // task to perform.
  325. const uint8_t flag = fStreamBuffer[fCurrRLEByte++];
  326. const uint8_t task = fStreamBuffer[fCurrRLEByte++];
  327. // Perform decoding
  328. if (RLE_ESCAPE == flag) {
  329. switch (task) {
  330. case RLE_EOL:
  331. x = 0;
  332. y++;
  333. break;
  334. case RLE_EOF:
  335. return height;
  336. case RLE_DELTA: {
  337. // Two bytes are needed to specify delta
  338. if ((int) fBytesBuffered - fCurrRLEByte < 2) {
  339. if (this->checkForMoreData() < 2) {
  340. return y;
  341. }
  342. }
  343. // Modify x and y
  344. const uint8_t dx = fStreamBuffer[fCurrRLEByte++];
  345. const uint8_t dy = fStreamBuffer[fCurrRLEByte++];
  346. x += dx;
  347. y += dy;
  348. if (x > width) {
  349. SkCodecPrintf("Warning: invalid RLE input.\n");
  350. return y - dy;
  351. } else if (y > height) {
  352. fLinesToSkip = y - height;
  353. return height;
  354. }
  355. break;
  356. }
  357. default: {
  358. // If task does not match any of the above signals, it
  359. // indicates that we have a sequence of non-RLE pixels.
  360. // Furthermore, the value of task is equal to the number
  361. // of pixels to interpret.
  362. uint8_t numPixels = task;
  363. const size_t rowBytes = compute_row_bytes(numPixels,
  364. this->bitsPerPixel());
  365. // Abort if setting numPixels moves us off the edge of the
  366. // image.
  367. if (x + numPixels > width) {
  368. SkCodecPrintf("Warning: invalid RLE input.\n");
  369. return y;
  370. }
  371. // Also abort if there are not enough bytes
  372. // remaining in the stream to set numPixels.
  373. // At most, alignedRowBytes can be 255 (max uint8_t) *
  374. // 3 (max bytes per pixel) + 1 (aligned) = 766. If
  375. // fStreamBuffer was smaller than this,
  376. // checkForMoreData would never succeed for some bmps.
  377. static_assert(255 * 3 + 1 < kBufferSize,
  378. "kBufferSize needs to be larger!");
  379. const size_t alignedRowBytes = SkAlign2(rowBytes);
  380. if ((int) fBytesBuffered - fCurrRLEByte < alignedRowBytes) {
  381. SkASSERT(alignedRowBytes < kBufferSize);
  382. if (this->checkForMoreData() < alignedRowBytes) {
  383. return y;
  384. }
  385. }
  386. // Set numPixels number of pixels
  387. while (numPixels > 0) {
  388. switch(this->bitsPerPixel()) {
  389. case 4: {
  390. SkASSERT(fCurrRLEByte < fBytesBuffered);
  391. uint8_t val = fStreamBuffer[fCurrRLEByte++];
  392. setPixel(dst, dstRowBytes, dstInfo, x++,
  393. y, val >> 4);
  394. numPixels--;
  395. if (numPixels != 0) {
  396. setPixel(dst, dstRowBytes, dstInfo,
  397. x++, y, val & 0xF);
  398. numPixels--;
  399. }
  400. break;
  401. }
  402. case 8:
  403. SkASSERT(fCurrRLEByte < fBytesBuffered);
  404. setPixel(dst, dstRowBytes, dstInfo, x++,
  405. y, fStreamBuffer[fCurrRLEByte++]);
  406. numPixels--;
  407. break;
  408. case 24: {
  409. SkASSERT(fCurrRLEByte + 2 < fBytesBuffered);
  410. uint8_t blue = fStreamBuffer[fCurrRLEByte++];
  411. uint8_t green = fStreamBuffer[fCurrRLEByte++];
  412. uint8_t red = fStreamBuffer[fCurrRLEByte++];
  413. setRGBPixel(dst, dstRowBytes, dstInfo,
  414. x++, y, red, green, blue);
  415. numPixels--;
  416. break;
  417. }
  418. default:
  419. SkASSERT(false);
  420. return y;
  421. }
  422. }
  423. // Skip a byte if necessary to maintain alignment
  424. if (!SkIsAlign2(rowBytes)) {
  425. fCurrRLEByte++;
  426. }
  427. break;
  428. }
  429. }
  430. } else {
  431. // If the first byte read is not a flag, it indicates the number of
  432. // pixels to set in RLE mode.
  433. const uint8_t numPixels = flag;
  434. const int endX = SkTMin<int>(x + numPixels, width);
  435. if (24 == this->bitsPerPixel()) {
  436. // In RLE24, the second byte read is part of the pixel color.
  437. // There are two more required bytes to finish encoding the
  438. // color.
  439. if ((int) fBytesBuffered - fCurrRLEByte < 2) {
  440. if (this->checkForMoreData() < 2) {
  441. return y;
  442. }
  443. }
  444. // Fill the pixels up to endX with the specified color
  445. uint8_t blue = task;
  446. uint8_t green = fStreamBuffer[fCurrRLEByte++];
  447. uint8_t red = fStreamBuffer[fCurrRLEByte++];
  448. while (x < endX) {
  449. setRGBPixel(dst, dstRowBytes, dstInfo, x++, y, red, green, blue);
  450. }
  451. } else {
  452. // In RLE8 or RLE4, the second byte read gives the index in the
  453. // color table to look up the pixel color.
  454. // RLE8 has one color index that gets repeated
  455. // RLE4 has two color indexes in the upper and lower 4 bits of
  456. // the bytes, which are alternated
  457. uint8_t indices[2] = { task, task };
  458. if (4 == this->bitsPerPixel()) {
  459. indices[0] >>= 4;
  460. indices[1] &= 0xf;
  461. }
  462. // Set the indicated number of pixels
  463. for (int which = 0; x < endX; x++) {
  464. setPixel(dst, dstRowBytes, dstInfo, x, y, indices[which]);
  465. which = !which;
  466. }
  467. }
  468. }
  469. }
  470. }
  471. bool SkBmpRLECodec::skipRows(int count) {
  472. const SkImageInfo rowInfo = SkImageInfo::Make(this->dimensions().width(), count,
  473. kN32_SkColorType, kUnpremul_SkAlphaType);
  474. return count == this->decodeRows(rowInfo, nullptr, 0, this->options());
  475. }
  476. // FIXME: Make SkBmpRLECodec have no knowledge of sampling.
  477. // Or it should do all sampling natively.
  478. // It currently is a hybrid that needs to know what SkScaledCodec is doing.
  479. class SkBmpRLESampler : public SkSampler {
  480. public:
  481. SkBmpRLESampler(SkBmpRLECodec* codec)
  482. : fCodec(codec)
  483. {
  484. SkASSERT(fCodec);
  485. }
  486. int fillWidth() const override {
  487. return fCodec->fillWidth();
  488. }
  489. private:
  490. int onSetSampleX(int sampleX) override {
  491. return fCodec->setSampleX(sampleX);
  492. }
  493. // Unowned pointer. fCodec will delete this class in its destructor.
  494. SkBmpRLECodec* fCodec;
  495. };
  496. SkSampler* SkBmpRLECodec::getSampler(bool createIfNecessary) {
  497. if (!fSampler && createIfNecessary) {
  498. fSampler.reset(new SkBmpRLESampler(this));
  499. }
  500. return fSampler.get();
  501. }
  502. int SkBmpRLECodec::setSampleX(int sampleX) {
  503. fSampleX = sampleX;
  504. return this->fillWidth();
  505. }
  506. int SkBmpRLECodec::fillWidth() const {
  507. return get_scaled_dimension(this->dimensions().width(), fSampleX);
  508. }