SkBmpStandardCodec.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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/SkBmpStandardCodec.h"
  10. #include "src/codec/SkCodecPriv.h"
  11. #include "src/core/SkMathPriv.h"
  12. /*
  13. * Creates an instance of the decoder
  14. * Called only by NewFromStream
  15. */
  16. SkBmpStandardCodec::SkBmpStandardCodec(SkEncodedInfo&& info, std::unique_ptr<SkStream> stream,
  17. uint16_t bitsPerPixel, uint32_t numColors,
  18. uint32_t bytesPerColor, uint32_t offset,
  19. SkCodec::SkScanlineOrder rowOrder,
  20. bool isOpaque, bool inIco)
  21. : INHERITED(std::move(info), std::move(stream), bitsPerPixel, rowOrder)
  22. , fColorTable(nullptr)
  23. , fNumColors(numColors)
  24. , fBytesPerColor(bytesPerColor)
  25. , fOffset(offset)
  26. , fSwizzler(nullptr)
  27. , fIsOpaque(isOpaque)
  28. , fInIco(inIco)
  29. , fAndMaskRowBytes(fInIco ? SkAlign4(compute_row_bytes(this->dimensions().width(), 1)) : 0)
  30. {}
  31. /*
  32. * Initiates the bitmap decode
  33. */
  34. SkCodec::Result SkBmpStandardCodec::onGetPixels(const SkImageInfo& dstInfo,
  35. void* dst, size_t dstRowBytes,
  36. const Options& opts,
  37. int* rowsDecoded) {
  38. if (opts.fSubset) {
  39. // Subsets are not supported.
  40. return kUnimplemented;
  41. }
  42. if (dstInfo.dimensions() != this->dimensions()) {
  43. SkCodecPrintf("Error: scaling not supported.\n");
  44. return kInvalidScale;
  45. }
  46. Result result = this->prepareToDecode(dstInfo, opts);
  47. if (kSuccess != result) {
  48. return result;
  49. }
  50. int rows = this->decodeRows(dstInfo, dst, dstRowBytes, opts);
  51. if (rows != dstInfo.height()) {
  52. *rowsDecoded = rows;
  53. return kIncompleteInput;
  54. }
  55. return kSuccess;
  56. }
  57. /*
  58. * Process the color table for the bmp input
  59. */
  60. bool SkBmpStandardCodec::createColorTable(SkColorType dstColorType, SkAlphaType dstAlphaType) {
  61. // Allocate memory for color table
  62. uint32_t colorBytes = 0;
  63. SkPMColor colorTable[256];
  64. if (this->bitsPerPixel() <= 8) {
  65. // Inform the caller of the number of colors
  66. uint32_t maxColors = 1 << this->bitsPerPixel();
  67. // Don't bother reading more than maxColors.
  68. const uint32_t numColorsToRead =
  69. fNumColors == 0 ? maxColors : SkTMin(fNumColors, maxColors);
  70. // Read the color table from the stream
  71. colorBytes = numColorsToRead * fBytesPerColor;
  72. std::unique_ptr<uint8_t[]> cBuffer(new uint8_t[colorBytes]);
  73. if (stream()->read(cBuffer.get(), colorBytes) != colorBytes) {
  74. SkCodecPrintf("Error: unable to read color table.\n");
  75. return false;
  76. }
  77. SkColorType packColorType = dstColorType;
  78. SkAlphaType packAlphaType = dstAlphaType;
  79. if (this->colorXform()) {
  80. packColorType = kBGRA_8888_SkColorType;
  81. packAlphaType = kUnpremul_SkAlphaType;
  82. }
  83. // Choose the proper packing function
  84. bool isPremul = (kPremul_SkAlphaType == packAlphaType) && !fIsOpaque;
  85. PackColorProc packARGB = choose_pack_color_proc(isPremul, packColorType);
  86. // Fill in the color table
  87. uint32_t i = 0;
  88. for (; i < numColorsToRead; i++) {
  89. uint8_t blue = get_byte(cBuffer.get(), i*fBytesPerColor);
  90. uint8_t green = get_byte(cBuffer.get(), i*fBytesPerColor + 1);
  91. uint8_t red = get_byte(cBuffer.get(), i*fBytesPerColor + 2);
  92. uint8_t alpha;
  93. if (fIsOpaque) {
  94. alpha = 0xFF;
  95. } else {
  96. alpha = get_byte(cBuffer.get(), i*fBytesPerColor + 3);
  97. }
  98. colorTable[i] = packARGB(alpha, red, green, blue);
  99. }
  100. // To avoid segmentation faults on bad pixel data, fill the end of the
  101. // color table with black. This is the same the behavior as the
  102. // chromium decoder.
  103. for (; i < maxColors; i++) {
  104. colorTable[i] = SkPackARGB32NoCheck(0xFF, 0, 0, 0);
  105. }
  106. if (this->colorXform() && !this->xformOnDecode()) {
  107. this->applyColorXform(colorTable, colorTable, maxColors);
  108. }
  109. // Set the color table
  110. fColorTable.reset(new SkColorTable(colorTable, maxColors));
  111. }
  112. // Bmp-in-Ico files do not use an offset to indicate where the pixel data
  113. // begins. Pixel data always begins immediately after the color table.
  114. if (!fInIco) {
  115. // Check that we have not read past the pixel array offset
  116. if(fOffset < colorBytes) {
  117. // This may occur on OS 2.1 and other old versions where the color
  118. // table defaults to max size, and the bmp tries to use a smaller
  119. // color table. This is invalid, and our decision is to indicate
  120. // an error, rather than try to guess the intended size of the
  121. // color table.
  122. SkCodecPrintf("Error: pixel data offset less than color table size.\n");
  123. return false;
  124. }
  125. // After reading the color table, skip to the start of the pixel array
  126. if (stream()->skip(fOffset - colorBytes) != fOffset - colorBytes) {
  127. SkCodecPrintf("Error: unable to skip to image data.\n");
  128. return false;
  129. }
  130. }
  131. // Return true on success
  132. return true;
  133. }
  134. static SkEncodedInfo make_info(SkEncodedInfo::Color color,
  135. SkEncodedInfo::Alpha alpha, int bitsPerPixel) {
  136. // This is just used for the swizzler, which does not need the width or height.
  137. return SkEncodedInfo::Make(0, 0, color, alpha, bitsPerPixel);
  138. }
  139. SkEncodedInfo SkBmpStandardCodec::swizzlerInfo() const {
  140. const auto& info = this->getEncodedInfo();
  141. if (fInIco) {
  142. if (this->bitsPerPixel() <= 8) {
  143. return make_info(SkEncodedInfo::kPalette_Color,
  144. info.alpha(), this->bitsPerPixel());
  145. }
  146. if (this->bitsPerPixel() == 24) {
  147. return make_info(SkEncodedInfo::kBGR_Color,
  148. SkEncodedInfo::kOpaque_Alpha, 8);
  149. }
  150. }
  151. return make_info(info.color(), info.alpha(), info.bitsPerComponent());
  152. }
  153. void SkBmpStandardCodec::initializeSwizzler(const SkImageInfo& dstInfo, const Options& opts) {
  154. // In the case of bmp-in-icos, we will report BGRA to the client,
  155. // since we may be required to apply an alpha mask after the decode.
  156. // However, the swizzler needs to know the actual format of the bmp.
  157. SkEncodedInfo encodedInfo = this->swizzlerInfo();
  158. // Get a pointer to the color table if it exists
  159. const SkPMColor* colorPtr = get_color_ptr(fColorTable.get());
  160. SkImageInfo swizzlerInfo = dstInfo;
  161. SkCodec::Options swizzlerOptions = opts;
  162. if (this->colorXform()) {
  163. swizzlerInfo = swizzlerInfo.makeColorType(kXformSrcColorType);
  164. if (kPremul_SkAlphaType == dstInfo.alphaType()) {
  165. swizzlerInfo = swizzlerInfo.makeAlphaType(kUnpremul_SkAlphaType);
  166. }
  167. swizzlerOptions.fZeroInitialized = kNo_ZeroInitialized;
  168. }
  169. fSwizzler = SkSwizzler::Make(encodedInfo, colorPtr, swizzlerInfo, swizzlerOptions);
  170. SkASSERT(fSwizzler);
  171. }
  172. SkCodec::Result SkBmpStandardCodec::onPrepareToDecode(const SkImageInfo& dstInfo,
  173. const SkCodec::Options& options) {
  174. if (this->xformOnDecode()) {
  175. this->resetXformBuffer(dstInfo.width());
  176. }
  177. // Create the color table if necessary and prepare the stream for decode
  178. // Note that if it is non-NULL, inputColorCount will be modified
  179. if (!this->createColorTable(dstInfo.colorType(), dstInfo.alphaType())) {
  180. SkCodecPrintf("Error: could not create color table.\n");
  181. return SkCodec::kInvalidInput;
  182. }
  183. // Initialize a swizzler
  184. this->initializeSwizzler(dstInfo, options);
  185. return SkCodec::kSuccess;
  186. }
  187. /*
  188. * Performs the bitmap decoding for standard input format
  189. */
  190. int SkBmpStandardCodec::decodeRows(const SkImageInfo& dstInfo, void* dst, size_t dstRowBytes,
  191. const Options& opts) {
  192. // Iterate over rows of the image
  193. const int height = dstInfo.height();
  194. for (int y = 0; y < height; y++) {
  195. // Read a row of the input
  196. if (this->stream()->read(this->srcBuffer(), this->srcRowBytes()) != this->srcRowBytes()) {
  197. SkCodecPrintf("Warning: incomplete input stream.\n");
  198. return y;
  199. }
  200. // Decode the row in destination format
  201. uint32_t row = this->getDstRow(y, dstInfo.height());
  202. void* dstRow = SkTAddOffset<void>(dst, row * dstRowBytes);
  203. if (this->xformOnDecode()) {
  204. SkASSERT(this->colorXform());
  205. fSwizzler->swizzle(this->xformBuffer(), this->srcBuffer());
  206. this->applyColorXform(dstRow, this->xformBuffer(), fSwizzler->swizzleWidth());
  207. } else {
  208. fSwizzler->swizzle(dstRow, this->srcBuffer());
  209. }
  210. }
  211. if (fInIco && fIsOpaque) {
  212. const int startScanline = this->currScanline();
  213. if (startScanline < 0) {
  214. // We are not performing a scanline decode.
  215. // Just decode the entire ICO mask and return.
  216. decodeIcoMask(this->stream(), dstInfo, dst, dstRowBytes);
  217. return height;
  218. }
  219. // In order to perform a scanline ICO decode, we must be able
  220. // to skip ahead in the stream in order to apply the AND mask
  221. // to the requested scanlines.
  222. // We will do this by taking advantage of the fact that
  223. // SkIcoCodec always uses a SkMemoryStream as its underlying
  224. // representation of the stream.
  225. const void* memoryBase = this->stream()->getMemoryBase();
  226. SkASSERT(nullptr != memoryBase);
  227. SkASSERT(this->stream()->hasLength());
  228. SkASSERT(this->stream()->hasPosition());
  229. const size_t length = this->stream()->getLength();
  230. const size_t currPosition = this->stream()->getPosition();
  231. // Calculate how many bytes we must skip to reach the AND mask.
  232. const int remainingScanlines = this->dimensions().height() - startScanline - height;
  233. const size_t bytesToSkip = remainingScanlines * this->srcRowBytes() +
  234. startScanline * fAndMaskRowBytes;
  235. const size_t subStreamStartPosition = currPosition + bytesToSkip;
  236. if (subStreamStartPosition >= length) {
  237. // FIXME: How can we indicate that this decode was actually incomplete?
  238. return height;
  239. }
  240. // Create a subStream to pass to decodeIcoMask(). It is useful to encapsulate
  241. // the memory base into a stream in order to safely handle incomplete images
  242. // without reading out of bounds memory.
  243. const void* subStreamMemoryBase = SkTAddOffset<const void>(memoryBase,
  244. subStreamStartPosition);
  245. const size_t subStreamLength = length - subStreamStartPosition;
  246. // This call does not transfer ownership of the subStreamMemoryBase.
  247. SkMemoryStream subStream(subStreamMemoryBase, subStreamLength, false);
  248. // FIXME: If decodeIcoMask does not succeed, is there a way that we can
  249. // indicate the decode was incomplete?
  250. decodeIcoMask(&subStream, dstInfo, dst, dstRowBytes);
  251. }
  252. return height;
  253. }
  254. void SkBmpStandardCodec::decodeIcoMask(SkStream* stream, const SkImageInfo& dstInfo,
  255. void* dst, size_t dstRowBytes) {
  256. // BMP in ICO have transparency, so this cannot be 565. The below code depends
  257. // on the output being an SkPMColor.
  258. SkASSERT(kRGBA_8888_SkColorType == dstInfo.colorType() ||
  259. kBGRA_8888_SkColorType == dstInfo.colorType() ||
  260. kRGBA_F16_SkColorType == dstInfo.colorType());
  261. // If we are sampling, make sure that we only mask the sampled pixels.
  262. // We do not need to worry about sampling in the y-dimension because that
  263. // should be handled by SkSampledCodec.
  264. const int sampleX = fSwizzler->sampleX();
  265. const int sampledWidth = get_scaled_dimension(this->dimensions().width(), sampleX);
  266. const int srcStartX = get_start_coord(sampleX);
  267. SkPMColor* dstPtr = (SkPMColor*) dst;
  268. for (int y = 0; y < dstInfo.height(); y++) {
  269. // The srcBuffer will at least be large enough
  270. if (stream->read(this->srcBuffer(), fAndMaskRowBytes) != fAndMaskRowBytes) {
  271. SkCodecPrintf("Warning: incomplete AND mask for bmp-in-ico.\n");
  272. return;
  273. }
  274. auto applyMask = [dstInfo](void* dstRow, int x, uint64_t bit) {
  275. if (kRGBA_F16_SkColorType == dstInfo.colorType()) {
  276. uint64_t* dst64 = (uint64_t*) dstRow;
  277. dst64[x] &= bit - 1;
  278. } else {
  279. uint32_t* dst32 = (uint32_t*) dstRow;
  280. dst32[x] &= bit - 1;
  281. }
  282. };
  283. int row = this->getDstRow(y, dstInfo.height());
  284. void* dstRow = SkTAddOffset<SkPMColor>(dstPtr, row * dstRowBytes);
  285. int srcX = srcStartX;
  286. for (int dstX = 0; dstX < sampledWidth; dstX++) {
  287. int quotient;
  288. int modulus;
  289. SkTDivMod(srcX, 8, &quotient, &modulus);
  290. uint32_t shift = 7 - modulus;
  291. uint64_t alphaBit = (this->srcBuffer()[quotient] >> shift) & 0x1;
  292. applyMask(dstRow, dstX, alphaBit);
  293. srcX += sampleX;
  294. }
  295. }
  296. }