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