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