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