Home | History | Annotate | Download | only in tests
      1 
      2 /*
      3  * Copyright 2011 Google Inc.
      4  *
      5  * Use of this source code is governed by a BSD-style license that can be
      6  * found in the LICENSE file.
      7  */
      8 #include "Test.h"
      9 #include "TestClassDef.h"
     10 #include "SkBitmap.h"
     11 #include "SkRect.h"
     12 
     13 static const char* boolStr(bool value) {
     14     return value ? "true" : "false";
     15 }
     16 
     17 // these are in the same order as the SkBitmap::Config enum
     18 static const char* gConfigName[] = {
     19     "None", "A8", "Index8", "565", "4444", "8888"
     20 };
     21 
     22 static void report_opaqueness(skiatest::Reporter* reporter, const SkBitmap& src,
     23                               const SkBitmap& dst) {
     24     SkString str;
     25     str.printf("src %s opaque:%d, dst %s opaque:%d",
     26                gConfigName[src.config()], src.isOpaque(),
     27                gConfigName[dst.config()], dst.isOpaque());
     28     reporter->reportFailed(str);
     29 }
     30 
     31 static bool canHaveAlpha(SkBitmap::Config config) {
     32     return config != SkBitmap::kRGB_565_Config;
     33 }
     34 
     35 // copyTo() should preserve isOpaque when it makes sense
     36 static void test_isOpaque(skiatest::Reporter* reporter,
     37                           const SkBitmap& srcOpaque, const SkBitmap& srcPremul,
     38                           SkBitmap::Config dstConfig) {
     39     SkBitmap dst;
     40 
     41     if (canHaveAlpha(srcPremul.config()) && canHaveAlpha(dstConfig)) {
     42         REPORTER_ASSERT(reporter, srcPremul.copyTo(&dst, dstConfig));
     43         REPORTER_ASSERT(reporter, dst.config() == dstConfig);
     44         if (srcPremul.isOpaque() != dst.isOpaque()) {
     45             report_opaqueness(reporter, srcPremul, dst);
     46         }
     47     }
     48 
     49     REPORTER_ASSERT(reporter, srcOpaque.copyTo(&dst, dstConfig));
     50     REPORTER_ASSERT(reporter, dst.config() == dstConfig);
     51     if (srcOpaque.isOpaque() != dst.isOpaque()) {
     52         report_opaqueness(reporter, srcOpaque, dst);
     53     }
     54 }
     55 
     56 static void init_src(const SkBitmap& bitmap) {
     57     SkAutoLockPixels lock(bitmap);
     58     if (bitmap.getPixels()) {
     59         if (bitmap.getColorTable()) {
     60             sk_bzero(bitmap.getPixels(), bitmap.getSize());
     61         } else {
     62             bitmap.eraseColor(SK_ColorWHITE);
     63         }
     64     }
     65 }
     66 
     67 static SkColorTable* init_ctable(SkAlphaType alphaType) {
     68     static const SkColor colors[] = {
     69         SK_ColorBLACK, SK_ColorRED, SK_ColorGREEN, SK_ColorBLUE, SK_ColorWHITE
     70     };
     71     return new SkColorTable(colors, SK_ARRAY_COUNT(colors), alphaType);
     72 }
     73 
     74 struct Pair {
     75     SkBitmap::Config    fConfig;
     76     const char*         fValid;
     77 };
     78 
     79 // Utility functions for copyPixelsTo()/copyPixelsFrom() tests.
     80 // getPixel()
     81 // setPixel()
     82 // getSkConfigName()
     83 // struct Coordinates
     84 // reportCopyVerification()
     85 // writeCoordPixels()
     86 
     87 // Utility function to read the value of a given pixel in bm. All
     88 // values converted to uint32_t for simplification of comparisons.
     89 static uint32_t getPixel(int x, int y, const SkBitmap& bm) {
     90     uint32_t val = 0;
     91     uint16_t val16;
     92     uint8_t val8;
     93     SkAutoLockPixels lock(bm);
     94     const void* rawAddr = bm.getAddr(x,y);
     95 
     96     switch (bm.config()) {
     97         case SkBitmap::kARGB_8888_Config:
     98             memcpy(&val, rawAddr, sizeof(uint32_t));
     99             break;
    100         case SkBitmap::kARGB_4444_Config:
    101         case SkBitmap::kRGB_565_Config:
    102             memcpy(&val16, rawAddr, sizeof(uint16_t));
    103             val = val16;
    104             break;
    105         case SkBitmap::kA8_Config:
    106         case SkBitmap::kIndex8_Config:
    107             memcpy(&val8, rawAddr, sizeof(uint8_t));
    108             val = val8;
    109             break;
    110         default:
    111             break;
    112     }
    113     return val;
    114 }
    115 
    116 // Utility function to set value of any pixel in bm.
    117 // bm.getConfig() specifies what format 'val' must be
    118 // converted to, but at present uint32_t can handle all formats.
    119 static void setPixel(int x, int y, uint32_t val, SkBitmap& bm) {
    120     uint16_t val16;
    121     uint8_t val8;
    122     SkAutoLockPixels lock(bm);
    123     void* rawAddr = bm.getAddr(x,y);
    124 
    125     switch (bm.config()) {
    126         case SkBitmap::kARGB_8888_Config:
    127             memcpy(rawAddr, &val, sizeof(uint32_t));
    128             break;
    129         case SkBitmap::kARGB_4444_Config:
    130         case SkBitmap::kRGB_565_Config:
    131             val16 = val & 0xFFFF;
    132             memcpy(rawAddr, &val16, sizeof(uint16_t));
    133             break;
    134         case SkBitmap::kA8_Config:
    135         case SkBitmap::kIndex8_Config:
    136             val8 = val & 0xFF;
    137             memcpy(rawAddr, &val8, sizeof(uint8_t));
    138             break;
    139         default:
    140             // Ignore.
    141             break;
    142     }
    143 }
    144 
    145 // Utility to return string containing name of each format, to
    146 // simplify diagnostic output.
    147 static const char* getSkConfigName(const SkBitmap& bm) {
    148     switch (bm.config()) {
    149         case SkBitmap::kNo_Config: return "SkBitmap::kNo_Config";
    150         case SkBitmap::kA8_Config: return "SkBitmap::kA8_Config";
    151         case SkBitmap::kIndex8_Config: return "SkBitmap::kIndex8_Config";
    152         case SkBitmap::kRGB_565_Config: return "SkBitmap::kRGB_565_Config";
    153         case SkBitmap::kARGB_4444_Config: return "SkBitmap::kARGB_4444_Config";
    154         case SkBitmap::kARGB_8888_Config: return "SkBitmap::kARGB_8888_Config";
    155         default: return "Unknown SkBitmap configuration.";
    156     }
    157 }
    158 
    159 // Helper struct to contain pixel locations, while avoiding need for STL.
    160 struct Coordinates {
    161 
    162     const int length;
    163     SkIPoint* const data;
    164 
    165     explicit Coordinates(int _length): length(_length)
    166                                      , data(new SkIPoint[length]) { }
    167 
    168     ~Coordinates(){
    169         delete [] data;
    170     }
    171 
    172     SkIPoint* operator[](int i) const {
    173         // Use with care, no bounds checking.
    174         return data + i;
    175     }
    176 };
    177 
    178 // A function to verify that two bitmaps contain the same pixel values
    179 // at all coordinates indicated by coords. Simplifies verification of
    180 // copied bitmaps.
    181 static void reportCopyVerification(const SkBitmap& bm1, const SkBitmap& bm2,
    182                             Coordinates& coords,
    183                             const char* msg,
    184                             skiatest::Reporter* reporter){
    185     bool success = true;
    186 
    187     // Confirm all pixels in the list match.
    188     for (int i = 0; i < coords.length; ++i) {
    189         success = success &&
    190                   (getPixel(coords[i]->fX, coords[i]->fY, bm1) ==
    191                    getPixel(coords[i]->fX, coords[i]->fY, bm2));
    192     }
    193 
    194     if (!success) {
    195         SkString str;
    196         str.printf("%s [config = %s]",
    197                    msg, getSkConfigName(bm1));
    198         reporter->reportFailed(str);
    199     }
    200 }
    201 
    202 // Writes unique pixel values at locations specified by coords.
    203 static void writeCoordPixels(SkBitmap& bm, const Coordinates& coords) {
    204     for (int i = 0; i < coords.length; ++i)
    205         setPixel(coords[i]->fX, coords[i]->fY, i, bm);
    206 }
    207 
    208 DEF_TEST(BitmapCopy, reporter) {
    209     static const Pair gPairs[] = {
    210         { SkBitmap::kNo_Config,         "0000000"  },
    211         { SkBitmap::kA8_Config,         "0101010"  },
    212         { SkBitmap::kIndex8_Config,     "0111010"  },
    213         { SkBitmap::kRGB_565_Config,    "0101010"  },
    214         { SkBitmap::kARGB_4444_Config,  "0101110"  },
    215         { SkBitmap::kARGB_8888_Config,  "0101110"  },
    216     };
    217 
    218     static const bool isExtracted[] = {
    219         false, true
    220     };
    221 
    222     const int W = 20;
    223     const int H = 33;
    224 
    225     for (size_t i = 0; i < SK_ARRAY_COUNT(gPairs); i++) {
    226         for (size_t j = 0; j < SK_ARRAY_COUNT(gPairs); j++) {
    227             SkBitmap srcOpaque, srcPremul, dst;
    228 
    229             {
    230                 SkColorTable* ctOpaque = NULL;
    231                 SkColorTable* ctPremul = NULL;
    232 
    233                 srcOpaque.setConfig(gPairs[i].fConfig, W, H, 0, kOpaque_SkAlphaType);
    234                 srcPremul.setConfig(gPairs[i].fConfig, W, H, 0, kPremul_SkAlphaType);
    235                 if (SkBitmap::kIndex8_Config == gPairs[i].fConfig) {
    236                     ctOpaque = init_ctable(kOpaque_SkAlphaType);
    237                     ctPremul = init_ctable(kPremul_SkAlphaType);
    238                 }
    239                 srcOpaque.allocPixels(ctOpaque);
    240                 srcPremul.allocPixels(ctPremul);
    241                 SkSafeUnref(ctOpaque);
    242                 SkSafeUnref(ctPremul);
    243             }
    244             init_src(srcOpaque);
    245             init_src(srcPremul);
    246 
    247             bool success = srcPremul.copyTo(&dst, gPairs[j].fConfig);
    248             bool expected = gPairs[i].fValid[j] != '0';
    249             if (success != expected) {
    250                 SkString str;
    251                 str.printf("SkBitmap::copyTo from %s to %s. expected %s returned %s",
    252                            gConfigName[i], gConfigName[j], boolStr(expected),
    253                            boolStr(success));
    254                 reporter->reportFailed(str);
    255             }
    256 
    257             bool canSucceed = srcPremul.canCopyTo(gPairs[j].fConfig);
    258             if (success != canSucceed) {
    259                 SkString str;
    260                 str.printf("SkBitmap::copyTo from %s to %s. returned %s canCopyTo %s",
    261                            gConfigName[i], gConfigName[j], boolStr(success),
    262                            boolStr(canSucceed));
    263                 reporter->reportFailed(str);
    264             }
    265 
    266             if (success) {
    267                 REPORTER_ASSERT(reporter, srcPremul.width() == dst.width());
    268                 REPORTER_ASSERT(reporter, srcPremul.height() == dst.height());
    269                 REPORTER_ASSERT(reporter, dst.config() == gPairs[j].fConfig);
    270                 test_isOpaque(reporter, srcOpaque, srcPremul, dst.config());
    271                 if (srcPremul.config() == dst.config()) {
    272                     SkAutoLockPixels srcLock(srcPremul);
    273                     SkAutoLockPixels dstLock(dst);
    274                     REPORTER_ASSERT(reporter, srcPremul.readyToDraw());
    275                     REPORTER_ASSERT(reporter, dst.readyToDraw());
    276                     const char* srcP = (const char*)srcPremul.getAddr(0, 0);
    277                     const char* dstP = (const char*)dst.getAddr(0, 0);
    278                     REPORTER_ASSERT(reporter, srcP != dstP);
    279                     REPORTER_ASSERT(reporter, !memcmp(srcP, dstP,
    280                                                       srcPremul.getSize()));
    281                     REPORTER_ASSERT(reporter, srcPremul.getGenerationID() == dst.getGenerationID());
    282                 } else {
    283                     REPORTER_ASSERT(reporter, srcPremul.getGenerationID() != dst.getGenerationID());
    284                 }
    285                 // test extractSubset
    286                 {
    287                     SkBitmap bitmap(srcOpaque);
    288                     SkBitmap subset;
    289                     SkIRect r;
    290                     r.set(1, 1, 2, 2);
    291                     bitmap.setIsVolatile(true);
    292                     if (bitmap.extractSubset(&subset, r)) {
    293                         REPORTER_ASSERT(reporter, subset.width() == 1);
    294                         REPORTER_ASSERT(reporter, subset.height() == 1);
    295                         REPORTER_ASSERT(reporter,
    296                                         subset.alphaType() == bitmap.alphaType());
    297                         REPORTER_ASSERT(reporter,
    298                                         subset.isVolatile() == true);
    299 
    300                         SkBitmap copy;
    301                         REPORTER_ASSERT(reporter,
    302                                         subset.copyTo(&copy, subset.config()));
    303                         REPORTER_ASSERT(reporter, copy.width() == 1);
    304                         REPORTER_ASSERT(reporter, copy.height() == 1);
    305                         REPORTER_ASSERT(reporter, copy.rowBytes() <= 4);
    306 
    307                         SkAutoLockPixels alp0(subset);
    308                         SkAutoLockPixels alp1(copy);
    309                         // they should both have, or both not-have, a colortable
    310                         bool hasCT = subset.getColorTable() != NULL;
    311                         REPORTER_ASSERT(reporter,
    312                                     (copy.getColorTable() != NULL) == hasCT);
    313                     }
    314                     bitmap = srcPremul;
    315                     bitmap.setIsVolatile(false);
    316                     if (bitmap.extractSubset(&subset, r)) {
    317                         REPORTER_ASSERT(reporter,
    318                                         subset.alphaType() == bitmap.alphaType());
    319                         REPORTER_ASSERT(reporter,
    320                                         subset.isVolatile() == false);
    321                     }
    322                 }
    323             } else {
    324                 // dst should be unchanged from its initial state
    325                 REPORTER_ASSERT(reporter, dst.config() == SkBitmap::kNo_Config);
    326                 REPORTER_ASSERT(reporter, dst.width() == 0);
    327                 REPORTER_ASSERT(reporter, dst.height() == 0);
    328             }
    329         } // for (size_t j = ...
    330 
    331         // Tests for getSafeSize(), getSafeSize64(), copyPixelsTo(),
    332         // copyPixelsFrom().
    333         //
    334         for (size_t copyCase = 0; copyCase < SK_ARRAY_COUNT(isExtracted);
    335              ++copyCase) {
    336             // Test copying to/from external buffer.
    337             // Note: the tests below have hard-coded values ---
    338             //       Please take care if modifying.
    339 
    340             // Tests for getSafeSize64().
    341             // Test with a very large configuration without pixel buffer
    342             // attached.
    343             SkBitmap tstSafeSize;
    344             tstSafeSize.setConfig(gPairs[i].fConfig, 100000000U,
    345                                   100000000U);
    346             Sk64 safeSize = tstSafeSize.getSafeSize64();
    347             if (safeSize.isNeg()) {
    348                 SkString str;
    349                 str.printf("getSafeSize64() negative: %s",
    350                     getSkConfigName(tstSafeSize));
    351                 reporter->reportFailed(str);
    352             }
    353             bool sizeFail = false;
    354             // Compare against hand-computed values.
    355             switch (gPairs[i].fConfig) {
    356                 case SkBitmap::kNo_Config:
    357                     break;
    358 
    359                 case SkBitmap::kA8_Config:
    360                 case SkBitmap::kIndex8_Config:
    361                     if (safeSize.fHi != 0x2386F2 ||
    362                         safeSize.fLo != 0x6FC10000)
    363                         sizeFail = true;
    364                     break;
    365 
    366                 case SkBitmap::kRGB_565_Config:
    367                 case SkBitmap::kARGB_4444_Config:
    368                     if (safeSize.fHi != 0x470DE4 ||
    369                         safeSize.fLo != 0xDF820000)
    370                         sizeFail = true;
    371                     break;
    372 
    373                 case SkBitmap::kARGB_8888_Config:
    374                     if (safeSize.fHi != 0x8E1BC9 ||
    375                         safeSize.fLo != 0xBF040000)
    376                         sizeFail = true;
    377                     break;
    378 
    379                 default:
    380                     break;
    381             }
    382             if (sizeFail) {
    383                 SkString str;
    384                 str.printf("getSafeSize64() wrong size: %s",
    385                     getSkConfigName(tstSafeSize));
    386                 reporter->reportFailed(str);
    387             }
    388 
    389             int subW = 2;
    390             int subH = 2;
    391 
    392             // Create bitmap to act as source for copies and subsets.
    393             SkBitmap src, subset;
    394             SkColorTable* ct = NULL;
    395             if (isExtracted[copyCase]) { // A larger image to extract from.
    396                 src.setConfig(gPairs[i].fConfig, 2 * subW + 1, subH);
    397             } else { // Tests expect a 2x2 bitmap, so make smaller.
    398                 src.setConfig(gPairs[i].fConfig, subW, subH);
    399             }
    400             if (SkBitmap::kIndex8_Config == src.config()) {
    401                 ct = init_ctable(kPremul_SkAlphaType);
    402             }
    403 
    404             src.allocPixels(ct);
    405             SkSafeUnref(ct);
    406 
    407             // Either copy src or extract into 'subset', which is used
    408             // for subsequent calls to copyPixelsTo/From.
    409             bool srcReady = false;
    410             if (isExtracted[copyCase]) {
    411                 // The extractedSubset() test case allows us to test copy-
    412                 // ing when src and dst mave possibly different strides.
    413                 SkIRect r;
    414                 r.set(1, 0, 1 + subW, subH); // 2x2 extracted bitmap
    415 
    416                 srcReady = src.extractSubset(&subset, r);
    417             } else {
    418                 srcReady = src.copyTo(&subset, src.config());
    419             }
    420 
    421             // Not all configurations will generate a valid 'subset'.
    422             if (srcReady) {
    423 
    424                 // Allocate our target buffer 'buf' for all copies.
    425                 // To simplify verifying correctness of copies attach
    426                 // buf to a SkBitmap, but copies are done using the
    427                 // raw buffer pointer.
    428                 const size_t bufSize = subH *
    429                     SkBitmap::ComputeRowBytes(src.config(), subW) * 2;
    430                 SkAutoMalloc autoBuf (bufSize);
    431                 uint8_t* buf = static_cast<uint8_t*>(autoBuf.get());
    432 
    433                 SkBitmap bufBm; // Attach buf to this bitmap.
    434                 bool successExpected;
    435 
    436                 // Set up values for each pixel being copied.
    437                 Coordinates coords(subW * subH);
    438                 for (int x = 0; x < subW; ++x)
    439                     for (int y = 0; y < subH; ++y)
    440                     {
    441                         int index = y * subW + x;
    442                         SkASSERT(index < coords.length);
    443                         coords[index]->fX = x;
    444                         coords[index]->fY = y;
    445                     }
    446 
    447                 writeCoordPixels(subset, coords);
    448 
    449                 // Test #1 ////////////////////////////////////////////
    450 
    451                 // Before/after comparisons easier if we attach buf
    452                 // to an appropriately configured SkBitmap.
    453                 memset(buf, 0xFF, bufSize);
    454                 // Config with stride greater than src but that fits in buf.
    455                 bufBm.setConfig(gPairs[i].fConfig, subW, subH,
    456                     SkBitmap::ComputeRowBytes(subset.config(), subW) * 2);
    457                 bufBm.setPixels(buf);
    458                 successExpected = false;
    459                 // Then attempt to copy with a stride that is too large
    460                 // to fit in the buffer.
    461                 REPORTER_ASSERT(reporter,
    462                     subset.copyPixelsTo(buf, bufSize, bufBm.rowBytes() * 3)
    463                     == successExpected);
    464 
    465                 if (successExpected)
    466                     reportCopyVerification(subset, bufBm, coords,
    467                         "copyPixelsTo(buf, bufSize, 1.5*maxRowBytes)",
    468                         reporter);
    469 
    470                 // Test #2 ////////////////////////////////////////////
    471                 // This test should always succeed, but in the case
    472                 // of extracted bitmaps only because we handle the
    473                 // issue of getSafeSize(). Without getSafeSize()
    474                 // buffer overrun/read would occur.
    475                 memset(buf, 0xFF, bufSize);
    476                 bufBm.setConfig(gPairs[i].fConfig, subW, subH,
    477                                 subset.rowBytes());
    478                 bufBm.setPixels(buf);
    479                 successExpected = subset.getSafeSize() <= bufSize;
    480                 REPORTER_ASSERT(reporter,
    481                     subset.copyPixelsTo(buf, bufSize) ==
    482                         successExpected);
    483                 if (successExpected)
    484                     reportCopyVerification(subset, bufBm, coords,
    485                     "copyPixelsTo(buf, bufSize)", reporter);
    486 
    487                 // Test #3 ////////////////////////////////////////////
    488                 // Copy with different stride between src and dst.
    489                 memset(buf, 0xFF, bufSize);
    490                 bufBm.setConfig(gPairs[i].fConfig, subW, subH,
    491                                 subset.rowBytes()+1);
    492                 bufBm.setPixels(buf);
    493                 successExpected = true; // Should always work.
    494                 REPORTER_ASSERT(reporter,
    495                         subset.copyPixelsTo(buf, bufSize,
    496                             subset.rowBytes()+1) == successExpected);
    497                 if (successExpected)
    498                     reportCopyVerification(subset, bufBm, coords,
    499                     "copyPixelsTo(buf, bufSize, rowBytes+1)", reporter);
    500 
    501                 // Test #4 ////////////////////////////////////////////
    502                 // Test copy with stride too small.
    503                 memset(buf, 0xFF, bufSize);
    504                 bufBm.setConfig(gPairs[i].fConfig, subW, subH);
    505                 bufBm.setPixels(buf);
    506                 successExpected = false;
    507                 // Request copy with stride too small.
    508                 REPORTER_ASSERT(reporter,
    509                     subset.copyPixelsTo(buf, bufSize, bufBm.rowBytes()-1)
    510                         == successExpected);
    511                 if (successExpected)
    512                     reportCopyVerification(subset, bufBm, coords,
    513                     "copyPixelsTo(buf, bufSize, rowBytes()-1)", reporter);
    514 
    515 #if 0   // copyPixelsFrom is gone
    516                 // Test #5 ////////////////////////////////////////////
    517                 // Tests the case where the source stride is too small
    518                 // for the source configuration.
    519                 memset(buf, 0xFF, bufSize);
    520                 bufBm.setConfig(gPairs[i].fConfig, subW, subH);
    521                 bufBm.setPixels(buf);
    522                 writeCoordPixels(bufBm, coords);
    523                 REPORTER_ASSERT(reporter,
    524                     subset.copyPixelsFrom(buf, bufSize, 1) == false);
    525 
    526                 // Test #6 ///////////////////////////////////////////
    527                 // Tests basic copy from an external buffer to the bitmap.
    528                 // If the bitmap is "extracted", this also tests the case
    529                 // where the source stride is different from the dest.
    530                 // stride.
    531                 // We've made the buffer large enough to always succeed.
    532                 bufBm.setConfig(gPairs[i].fConfig, subW, subH);
    533                 bufBm.setPixels(buf);
    534                 writeCoordPixels(bufBm, coords);
    535                 REPORTER_ASSERT(reporter,
    536                     subset.copyPixelsFrom(buf, bufSize, bufBm.rowBytes()) ==
    537                         true);
    538                 reportCopyVerification(bufBm, subset, coords,
    539                     "copyPixelsFrom(buf, bufSize)",
    540                     reporter);
    541 
    542                 // Test #7 ////////////////////////////////////////////
    543                 // Tests the case where the source buffer is too small
    544                 // for the transfer.
    545                 REPORTER_ASSERT(reporter,
    546                     subset.copyPixelsFrom(buf, 1, subset.rowBytes()) ==
    547                         false);
    548 
    549 #endif
    550             }
    551         } // for (size_t copyCase ...
    552     }
    553 }
    554