3 * Copyright 2008 The Android Open Source Project
5 * Use of this source code is governed by a BSD-style license that can be
6 * found in the LICENSE file.
11 #include "SkColorPriv.h"
13 #include "SkFlattenable.h"
14 #include "SkImagePriv.h"
15 #include "SkMallocPixelRef.h"
17 #include "SkReadBuffer.h"
18 #include "SkWriteBuffer.h"
19 #include "SkPixelRef.h"
21 #include "SkUnPreMultiply.h"
23 #include "SkValidationUtils.h"
24 #include "SkPackBits.h"
27 static bool reset_return_false(SkBitmap* bm) {
35 uint32_t fWidth, fHeight;
38 struct SkBitmap::MipMap : SkNoncopyable {
41 // MipLevel fLevel[fLevelCount];
44 static MipMap* Alloc(int levelCount, size_t pixelSize) {
48 int64_t size = (levelCount + 1) * sizeof(MipLevel);
49 size += sizeof(MipMap) + pixelSize;
50 if (!sk_64_isS32(size)) {
53 MipMap* mm = (MipMap*)sk_malloc_throw(sk_64_asS32(size));
55 mm->fLevelCount = levelCount;
59 const MipLevel* levels() const { return (const MipLevel*)(this + 1); }
60 MipLevel* levels() { return (MipLevel*)(this + 1); }
62 const void* pixels() const { return levels() + fLevelCount; }
63 void* pixels() { return levels() + fLevelCount; }
66 if (SK_MaxS32 == sk_atomic_inc(&fRefCnt)) {
71 SkASSERT(fRefCnt > 0);
72 if (sk_atomic_dec(&fRefCnt) == 1) {
78 ///////////////////////////////////////////////////////////////////////////////
79 ///////////////////////////////////////////////////////////////////////////////
81 SkBitmap::SkBitmap() {
82 sk_bzero(this, sizeof(*this));
85 SkBitmap::SkBitmap(const SkBitmap& src) {
86 SkDEBUGCODE(src.validate();)
87 sk_bzero(this, sizeof(*this));
89 SkDEBUGCODE(this->validate();)
92 SkBitmap::~SkBitmap() {
93 SkDEBUGCODE(this->validate();)
97 SkBitmap& SkBitmap::operator=(const SkBitmap& src) {
100 memcpy(this, &src, sizeof(src));
102 // inc src reference counts
103 SkSafeRef(src.fPixelRef);
104 SkSafeRef(src.fMipMap);
106 // we reset our locks if we get blown away
110 // ignore the values from the memcpy
113 // Note that what to for genID is somewhat arbitrary. We have no
114 // way to track changes to raw pixels across multiple SkBitmaps.
115 // Would benefit from an SkRawPixelRef type created by
117 // Just leave the memcpy'ed one but they'll get out of sync
118 // as soon either is modified.
122 SkDEBUGCODE(this->validate();)
126 void SkBitmap::swap(SkBitmap& other) {
127 SkTSwap(fColorTable, other.fColorTable);
128 SkTSwap(fPixelRef, other.fPixelRef);
129 SkTSwap(fPixelRefOrigin, other.fPixelRefOrigin);
130 SkTSwap(fPixelLockCount, other.fPixelLockCount);
131 SkTSwap(fMipMap, other.fMipMap);
132 SkTSwap(fPixels, other.fPixels);
133 SkTSwap(fInfo, other.fInfo);
134 SkTSwap(fRowBytes, other.fRowBytes);
135 SkTSwap(fFlags, other.fFlags);
137 SkDEBUGCODE(this->validate();)
140 void SkBitmap::reset() {
142 sk_bzero(this, sizeof(*this));
145 SkBitmap::Config SkBitmap::config() const {
146 return SkColorTypeToBitmapConfig(fInfo.colorType());
149 int SkBitmap::ComputeBytesPerPixel(SkBitmap::Config config) {
153 bpp = 0; // not applicable
159 case kRGB_565_Config:
160 case kARGB_4444_Config:
163 case kARGB_8888_Config:
167 SkDEBUGFAIL("unknown config");
174 size_t SkBitmap::ComputeRowBytes(Config c, int width) {
175 return SkColorTypeMinRowBytes(SkBitmapConfigToColorType(c), width);
178 int64_t SkBitmap::ComputeSize64(Config config, int width, int height) {
179 SkColorType ct = SkBitmapConfigToColorType(config);
180 int64_t rowBytes = sk_64_mul(SkColorTypeBytesPerPixel(ct), width);
181 return rowBytes * height;
184 size_t SkBitmap::ComputeSize(Config c, int width, int height) {
185 int64_t size = SkBitmap::ComputeSize64(c, width, height);
186 return sk_64_isS32(size) ? sk_64_asS32(size) : 0;
189 int64_t SkBitmap::ComputeSafeSize64(Config config,
193 SkImageInfo info = SkImageInfo::Make(width, height,
194 SkBitmapConfigToColorType(config),
195 kPremul_SkAlphaType);
196 return info.getSafeSize64(rowBytes);
199 size_t SkBitmap::ComputeSafeSize(Config config,
203 int64_t safeSize = ComputeSafeSize64(config, width, height, rowBytes);
204 int32_t safeSize32 = (int32_t)safeSize;
206 if (safeSize32 != safeSize) {
212 void SkBitmap::getBounds(SkRect* bounds) const {
215 SkIntToScalar(fInfo.fWidth), SkIntToScalar(fInfo.fHeight));
218 void SkBitmap::getBounds(SkIRect* bounds) const {
220 bounds->set(0, 0, fInfo.fWidth, fInfo.fHeight);
223 ///////////////////////////////////////////////////////////////////////////////
225 static bool validate_alphaType(SkColorType colorType, SkAlphaType alphaType,
226 SkAlphaType* canonical = NULL) {
228 case kUnknown_SkColorType:
229 alphaType = kIgnore_SkAlphaType;
231 case kAlpha_8_SkColorType:
232 if (kUnpremul_SkAlphaType == alphaType) {
233 alphaType = kPremul_SkAlphaType;
236 case kIndex_8_SkColorType:
237 case kARGB_4444_SkColorType:
238 case kRGBA_8888_SkColorType:
239 case kBGRA_8888_SkColorType:
240 if (kIgnore_SkAlphaType == alphaType) {
244 case kRGB_565_SkColorType:
245 alphaType = kOpaque_SkAlphaType;
251 *canonical = alphaType;
256 bool SkBitmap::setConfig(const SkImageInfo& info, size_t rowBytes) {
257 // require that rowBytes fit in 31bits
258 int64_t mrb = info.minRowBytes64();
259 if ((int32_t)mrb != mrb) {
260 return reset_return_false(this);
262 if ((int64_t)rowBytes != (int32_t)rowBytes) {
263 return reset_return_false(this);
266 if (info.width() < 0 || info.height() < 0) {
267 return reset_return_false(this);
270 if (kUnknown_SkColorType == info.colorType()) {
272 } else if (0 == rowBytes) {
273 rowBytes = (size_t)mrb;
274 } else if (rowBytes < info.minRowBytes()) {
275 return reset_return_false(this);
281 fRowBytes = SkToU32(rowBytes);
285 bool SkBitmap::setConfig(Config config, int width, int height, size_t rowBytes,
286 SkAlphaType alphaType) {
287 SkColorType ct = SkBitmapConfigToColorType(config);
288 return this->setConfig(SkImageInfo::Make(width, height, ct, alphaType),
292 bool SkBitmap::setAlphaType(SkAlphaType alphaType) {
293 if (!validate_alphaType(fInfo.fColorType, alphaType, &alphaType)) {
296 if (fInfo.fAlphaType != alphaType) {
297 fInfo.fAlphaType = alphaType;
299 fPixelRef->changeAlphaType(alphaType);
305 void SkBitmap::updatePixelsFromRef() const {
306 if (NULL != fPixelRef) {
307 if (fPixelLockCount > 0) {
308 SkASSERT(fPixelRef->isLocked());
310 void* p = fPixelRef->pixels();
313 + fPixelRefOrigin.fY * fRowBytes
314 + fPixelRefOrigin.fX * fInfo.bytesPerPixel();
317 fColorTable = fPixelRef->colorTable();
319 SkASSERT(0 == fPixelLockCount);
326 static bool config_to_colorType(SkBitmap::Config config, SkColorType* ctOut) {
329 case SkBitmap::kA8_Config:
330 ct = kAlpha_8_SkColorType;
332 case SkBitmap::kIndex8_Config:
333 ct = kIndex_8_SkColorType;
335 case SkBitmap::kRGB_565_Config:
336 ct = kRGB_565_SkColorType;
338 case SkBitmap::kARGB_4444_Config:
339 ct = kARGB_4444_SkColorType;
341 case SkBitmap::kARGB_8888_Config:
342 ct = kPMColor_SkColorType;
344 case SkBitmap::kNo_Config:
354 SkPixelRef* SkBitmap::setPixelRef(SkPixelRef* pr, int dx, int dy) {
358 if (this->asImageInfo(&info)) {
359 const SkImageInfo& prInfo = pr->info();
360 SkASSERT(info.fWidth <= prInfo.fWidth);
361 SkASSERT(info.fHeight <= prInfo.fHeight);
362 SkASSERT(info.fColorType == prInfo.fColorType);
363 switch (prInfo.fAlphaType) {
364 case kIgnore_SkAlphaType:
365 SkASSERT(fInfo.fAlphaType == kIgnore_SkAlphaType);
367 case kOpaque_SkAlphaType:
368 case kPremul_SkAlphaType:
369 SkASSERT(info.fAlphaType == kOpaque_SkAlphaType ||
370 info.fAlphaType == kPremul_SkAlphaType);
372 case kUnpremul_SkAlphaType:
373 SkASSERT(info.fAlphaType == kOpaque_SkAlphaType ||
374 info.fAlphaType == kUnpremul_SkAlphaType);
382 const SkImageInfo& info = pr->info();
383 fPixelRefOrigin.set(SkPin32(dx, 0, info.fWidth),
384 SkPin32(dy, 0, info.fHeight));
386 // ignore dx,dy if there is no pixelref
387 fPixelRefOrigin.setZero();
390 if (fPixelRef != pr) {
391 if (fPixelRef != pr) {
393 SkASSERT(NULL == fPixelRef);
398 this->updatePixelsFromRef();
401 SkDEBUGCODE(this->validate();)
405 void SkBitmap::lockPixels() const {
406 if (NULL != fPixelRef && 0 == sk_atomic_inc(&fPixelLockCount)) {
407 fPixelRef->lockPixels();
408 this->updatePixelsFromRef();
410 SkDEBUGCODE(this->validate();)
413 void SkBitmap::unlockPixels() const {
414 SkASSERT(NULL == fPixelRef || fPixelLockCount > 0);
416 if (NULL != fPixelRef && 1 == sk_atomic_dec(&fPixelLockCount)) {
417 fPixelRef->unlockPixels();
418 this->updatePixelsFromRef();
420 SkDEBUGCODE(this->validate();)
423 bool SkBitmap::lockPixelsAreWritable() const {
424 return (fPixelRef) ? fPixelRef->lockPixelsAreWritable() : false;
427 void SkBitmap::setPixels(void* p, SkColorTable* ctable) {
429 this->setPixelRef(NULL);
434 if (!this->asImageInfo(&info)) {
435 this->setPixelRef(NULL);
439 SkPixelRef* pr = SkMallocPixelRef::NewDirect(info, p, fRowBytes, ctable);
441 this->setPixelRef(NULL);
445 this->setPixelRef(pr)->unref();
447 // since we're already allocated, we lockPixels right away
449 SkDEBUGCODE(this->validate();)
452 bool SkBitmap::allocPixels(Allocator* allocator, SkColorTable* ctable) {
453 HeapAllocator stdalloc;
455 if (NULL == allocator) {
456 allocator = &stdalloc;
458 return allocator->allocPixelRef(this, ctable);
461 ///////////////////////////////////////////////////////////////////////////////
463 bool SkBitmap::allocPixels(const SkImageInfo& info, SkPixelRefFactory* factory,
464 SkColorTable* ctable) {
465 if (kIndex_8_SkColorType == info.fColorType && NULL == ctable) {
466 return reset_return_false(this);
468 if (!this->setConfig(info)) {
469 return reset_return_false(this);
472 SkMallocPixelRef::PRFactory defaultFactory;
473 if (NULL == factory) {
474 factory = &defaultFactory;
477 SkPixelRef* pr = factory->create(info, ctable);
479 return reset_return_false(this);
481 this->setPixelRef(pr)->unref();
483 // TODO: lockPixels could/should return bool or void*/NULL
485 if (NULL == this->getPixels()) {
486 return reset_return_false(this);
491 bool SkBitmap::installPixels(const SkImageInfo& info, void* pixels, size_t rb,
492 void (*releaseProc)(void* addr, void* context),
494 if (!this->setConfig(info, rb)) {
499 SkPixelRef* pr = SkMallocPixelRef::NewWithProc(info, rb, NULL, pixels,
500 releaseProc, context);
506 this->setPixelRef(pr)->unref();
510 bool SkBitmap::allocConfigPixels(Config config, int width, int height,
513 if (!config_to_colorType(config, &ct)) {
517 SkAlphaType at = isOpaque ? kOpaque_SkAlphaType : kPremul_SkAlphaType;
518 return this->allocPixels(SkImageInfo::Make(width, height, ct, at));
521 ///////////////////////////////////////////////////////////////////////////////
523 void SkBitmap::freePixels() {
524 // if we're gonna free the pixels, we certainly need to free the mipmap
527 if (NULL != fPixelRef) {
528 if (fPixelLockCount > 0) {
529 fPixelRef->unlockPixels();
533 fPixelRefOrigin.setZero();
540 void SkBitmap::freeMipMap() {
547 uint32_t SkBitmap::getGenerationID() const {
548 return (fPixelRef) ? fPixelRef->getGenerationID() : 0;
551 void SkBitmap::notifyPixelsChanged() const {
552 SkASSERT(!this->isImmutable());
554 fPixelRef->notifyPixelsChanged();
558 GrTexture* SkBitmap::getTexture() const {
559 return fPixelRef ? fPixelRef->getTexture() : NULL;
562 ///////////////////////////////////////////////////////////////////////////////
564 /** We explicitly use the same allocator for our pixels that SkMask does,
565 so that we can freely assign memory allocated by one class to the other.
567 bool SkBitmap::HeapAllocator::allocPixelRef(SkBitmap* dst,
568 SkColorTable* ctable) {
570 if (!dst->asImageInfo(&info)) {
571 // SkDebugf("unsupported config for info %d\n", dst->config());
575 SkPixelRef* pr = SkMallocPixelRef::NewAllocate(info, dst->rowBytes(),
581 dst->setPixelRef(pr)->unref();
582 // since we're already allocated, we lockPixels right away
587 ///////////////////////////////////////////////////////////////////////////////
589 bool SkBitmap::copyPixelsTo(void* const dst, size_t dstSize,
590 size_t dstRowBytes, bool preserveDstPad) const {
592 if (0 == dstRowBytes) {
593 dstRowBytes = fRowBytes;
596 if (dstRowBytes < fInfo.minRowBytes() ||
597 dst == NULL || (getPixels() == NULL && pixelRef() == NULL)) {
601 if (!preserveDstPad && static_cast<uint32_t>(dstRowBytes) == fRowBytes) {
602 size_t safeSize = this->getSafeSize();
603 if (safeSize > dstSize || safeSize == 0)
606 SkAutoLockPixels lock(*this);
607 // This implementation will write bytes beyond the end of each row,
608 // excluding the last row, if the bitmap's stride is greater than
609 // strictly required by the current config.
610 memcpy(dst, getPixels(), safeSize);
615 // If destination has different stride than us, then copy line by line.
616 if (fInfo.getSafeSize(dstRowBytes) > dstSize) {
619 // Just copy what we need on each line.
620 size_t rowBytes = fInfo.minRowBytes();
621 SkAutoLockPixels lock(*this);
622 const uint8_t* srcP = reinterpret_cast<const uint8_t*>(getPixels());
623 uint8_t* dstP = reinterpret_cast<uint8_t*>(dst);
624 for (int row = 0; row < fInfo.fHeight;
625 row++, srcP += fRowBytes, dstP += dstRowBytes) {
626 memcpy(dstP, srcP, rowBytes);
634 ///////////////////////////////////////////////////////////////////////////////
636 bool SkBitmap::isImmutable() const {
637 return fPixelRef ? fPixelRef->isImmutable() :
638 fFlags & kImageIsImmutable_Flag;
641 void SkBitmap::setImmutable() {
643 fPixelRef->setImmutable();
645 fFlags |= kImageIsImmutable_Flag;
649 bool SkBitmap::isVolatile() const {
650 return (fFlags & kImageIsVolatile_Flag) != 0;
653 void SkBitmap::setIsVolatile(bool isVolatile) {
655 fFlags |= kImageIsVolatile_Flag;
657 fFlags &= ~kImageIsVolatile_Flag;
661 void* SkBitmap::getAddr(int x, int y) const {
662 SkASSERT((unsigned)x < (unsigned)this->width());
663 SkASSERT((unsigned)y < (unsigned)this->height());
665 char* base = (char*)this->getPixels();
667 base += y * this->rowBytes();
668 switch (this->colorType()) {
669 case kRGBA_8888_SkColorType:
670 case kBGRA_8888_SkColorType:
673 case kARGB_4444_SkColorType:
674 case kRGB_565_SkColorType:
677 case kAlpha_8_SkColorType:
678 case kIndex_8_SkColorType:
682 SkDEBUGFAIL("Can't return addr for config");
690 SkColor SkBitmap::getColor(int x, int y) const {
691 SkASSERT((unsigned)x < (unsigned)this->width());
692 SkASSERT((unsigned)y < (unsigned)this->height());
694 switch (this->config()) {
695 case SkBitmap::kA8_Config: {
696 uint8_t* addr = this->getAddr8(x, y);
697 return SkColorSetA(0, addr[0]);
699 case SkBitmap::kIndex8_Config: {
700 SkPMColor c = this->getIndex8Color(x, y);
701 return SkUnPreMultiply::PMColorToColor(c);
703 case SkBitmap::kRGB_565_Config: {
704 uint16_t* addr = this->getAddr16(x, y);
705 return SkPixel16ToColor(addr[0]);
707 case SkBitmap::kARGB_4444_Config: {
708 uint16_t* addr = this->getAddr16(x, y);
709 SkPMColor c = SkPixel4444ToPixel32(addr[0]);
710 return SkUnPreMultiply::PMColorToColor(c);
712 case SkBitmap::kARGB_8888_Config: {
713 uint32_t* addr = this->getAddr32(x, y);
714 return SkUnPreMultiply::PMColorToColor(addr[0]);
721 SkASSERT(false); // Not reached.
725 bool SkBitmap::ComputeIsOpaque(const SkBitmap& bm) {
726 SkAutoLockPixels alp(bm);
727 if (!bm.getPixels()) {
731 const int height = bm.height();
732 const int width = bm.width();
734 switch (bm.config()) {
735 case SkBitmap::kA8_Config: {
737 for (int y = 0; y < height; ++y) {
738 const uint8_t* row = bm.getAddr8(0, y);
739 for (int x = 0; x < width; ++x) {
748 case SkBitmap::kIndex8_Config: {
749 SkAutoLockColors alc(bm);
750 const SkPMColor* table = alc.colors();
754 SkPMColor c = (SkPMColor)~0;
755 for (int i = bm.getColorTable()->count() - 1; i >= 0; --i) {
758 return 0xFF == SkGetPackedA32(c);
760 case SkBitmap::kRGB_565_Config:
763 case SkBitmap::kARGB_4444_Config: {
765 for (int y = 0; y < height; ++y) {
766 const SkPMColor16* row = bm.getAddr16(0, y);
767 for (int x = 0; x < width; ++x) {
770 if (0xF != SkGetPackedA4444(c)) {
776 case SkBitmap::kARGB_8888_Config: {
777 SkPMColor c = (SkPMColor)~0;
778 for (int y = 0; y < height; ++y) {
779 const SkPMColor* row = bm.getAddr32(0, y);
780 for (int x = 0; x < width; ++x) {
783 if (0xFF != SkGetPackedA32(c)) {
796 ///////////////////////////////////////////////////////////////////////////////
797 ///////////////////////////////////////////////////////////////////////////////
799 static uint16_t pack_8888_to_4444(unsigned a, unsigned r, unsigned g, unsigned b) {
800 unsigned pixel = (SkA32To4444(a) << SK_A4444_SHIFT) |
801 (SkR32To4444(r) << SK_R4444_SHIFT) |
802 (SkG32To4444(g) << SK_G4444_SHIFT) |
803 (SkB32To4444(b) << SK_B4444_SHIFT);
804 return SkToU16(pixel);
807 void SkBitmap::internalErase(const SkIRect& area,
808 U8CPU a, U8CPU r, U8CPU g, U8CPU b) const {
810 SkDEBUGCODE(this->validate();)
811 SkASSERT(!area.isEmpty());
813 SkIRect total = { 0, 0, this->width(), this->height() };
814 SkASSERT(total.contains(area));
818 switch (fInfo.colorType()) {
819 case kUnknown_SkColorType:
820 case kIndex_8_SkColorType:
821 return; // can't erase
826 SkAutoLockPixels alp(*this);
827 // perform this check after the lock call
828 if (!this->readyToDraw()) {
832 int height = area.height();
833 const int width = area.width();
834 const int rowBytes = fRowBytes;
836 // make rgb premultiplied
838 r = SkAlphaMul(r, a);
839 g = SkAlphaMul(g, a);
840 b = SkAlphaMul(b, a);
843 switch (this->colorType()) {
844 case kAlpha_8_SkColorType: {
845 uint8_t* p = this->getAddr8(area.fLeft, area.fTop);
846 while (--height >= 0) {
852 case kARGB_4444_SkColorType:
853 case kRGB_565_SkColorType: {
854 uint16_t* p = this->getAddr16(area.fLeft, area.fTop);;
857 if (kARGB_4444_SkColorType == this->colorType()) {
858 v = pack_8888_to_4444(a, r, g, b);
860 v = SkPackRGB16(r >> (8 - SK_R16_BITS),
861 g >> (8 - SK_G16_BITS),
862 b >> (8 - SK_B16_BITS));
864 while (--height >= 0) {
865 sk_memset16(p, v, width);
866 p = (uint16_t*)((char*)p + rowBytes);
870 case kPMColor_SkColorType: {
871 // what to do about BGRA or RGBA (which ever is != PMColor ?
872 // for now we don't support them.
873 uint32_t* p = this->getAddr32(area.fLeft, area.fTop);
874 uint32_t v = SkPackARGB32(a, r, g, b);
876 while (--height >= 0) {
877 sk_memset32(p, v, width);
878 p = (uint32_t*)((char*)p + rowBytes);
883 return; // no change, so don't call notifyPixelsChanged()
886 this->notifyPixelsChanged();
889 void SkBitmap::eraseARGB(U8CPU a, U8CPU r, U8CPU g, U8CPU b) const {
890 SkIRect area = { 0, 0, this->width(), this->height() };
891 if (!area.isEmpty()) {
892 this->internalErase(area, a, r, g, b);
896 void SkBitmap::eraseArea(const SkIRect& rect, SkColor c) const {
897 SkIRect area = { 0, 0, this->width(), this->height() };
898 if (area.intersect(rect)) {
899 this->internalErase(area, SkColorGetA(c), SkColorGetR(c),
900 SkColorGetG(c), SkColorGetB(c));
904 //////////////////////////////////////////////////////////////////////////////////////
905 //////////////////////////////////////////////////////////////////////////////////////
907 bool SkBitmap::extractSubset(SkBitmap* result, const SkIRect& subset) const {
908 SkDEBUGCODE(this->validate();)
910 if (NULL == result || NULL == fPixelRef) {
911 return false; // no src pixels
915 srcRect.set(0, 0, this->width(), this->height());
916 if (!r.intersect(srcRect, subset)) {
917 return false; // r is empty (i.e. no intersection)
920 if (fPixelRef->getTexture() != NULL) {
922 SkPixelRef* pixelRef = fPixelRef->deepCopy(this->config(), &subset);
923 if (pixelRef != NULL) {
925 dst.setConfig(this->config(), subset.width(), subset.height(), 0,
927 dst.setIsVolatile(this->isVolatile());
928 dst.setPixelRef(pixelRef)->unref();
929 SkDEBUGCODE(dst.validate());
935 // If the upper left of the rectangle was outside the bounds of this SkBitmap, we should have
937 SkASSERT(static_cast<unsigned>(r.fLeft) < static_cast<unsigned>(this->width()));
938 SkASSERT(static_cast<unsigned>(r.fTop) < static_cast<unsigned>(this->height()));
941 dst.setConfig(this->config(), r.width(), r.height(), this->rowBytes(),
943 dst.setIsVolatile(this->isVolatile());
946 SkIPoint origin = fPixelRefOrigin;
947 origin.fX += r.fLeft;
949 // share the pixelref with a custom offset
950 dst.setPixelRef(fPixelRef, origin);
952 SkDEBUGCODE(dst.validate();)
954 // we know we're good, so commit to result
959 ///////////////////////////////////////////////////////////////////////////////
961 #include "SkCanvas.h"
964 bool SkBitmap::canCopyTo(Config dstConfig) const {
965 if (this->config() == kNo_Config) {
969 bool sameConfigs = (this->config() == dstConfig);
972 case kRGB_565_Config:
973 case kARGB_8888_Config:
980 case kARGB_4444_Config:
981 return sameConfigs || kARGB_8888_Config == this->config();
988 bool SkBitmap::copyTo(SkBitmap* dst, Config dstConfig, Allocator* alloc) const {
989 if (!this->canCopyTo(dstConfig)) {
993 // if we have a texture, first get those pixels
995 const SkBitmap* src = this;
999 subset.setXYWH(fPixelRefOrigin.fX, fPixelRefOrigin.fY,
1000 fInfo.width(), fInfo.height());
1001 if (fPixelRef->readPixels(&tmpSrc, &subset)) {
1002 SkASSERT(tmpSrc.width() == this->width());
1003 SkASSERT(tmpSrc.height() == this->height());
1005 // did we get lucky and we can just return tmpSrc?
1006 if (tmpSrc.config() == dstConfig && NULL == alloc) {
1008 // If the result is an exact copy, clone the gen ID.
1009 if (dst->pixelRef() && dst->pixelRef()->info() == fPixelRef->info()) {
1010 dst->pixelRef()->cloneGenID(*fPixelRef);
1015 // fall through to the raster case
1020 // we lock this now, since we may need its colortable
1021 SkAutoLockPixels srclock(*src);
1022 if (!src->readyToDraw()) {
1026 // The only way to be readyToDraw is if fPixelRef is non NULL.
1027 SkASSERT(fPixelRef != NULL);
1030 tmpDst.setConfig(dstConfig, src->width(), src->height(), 0,
1033 // allocate colortable if srcConfig == kIndex8_Config
1034 SkColorTable* ctable = (dstConfig == kIndex8_Config) ?
1035 new SkColorTable(*src->getColorTable()) : NULL;
1036 SkAutoUnref au(ctable);
1037 if (!tmpDst.allocPixels(alloc, ctable)) {
1041 if (!tmpDst.readyToDraw()) {
1042 // allocator/lock failed
1046 // pixelRef must be non NULL or tmpDst.readyToDraw() would have
1048 SkASSERT(tmpDst.pixelRef() != NULL);
1050 /* do memcpy for the same configs cases, else use drawing
1052 if (src->config() == dstConfig) {
1053 if (tmpDst.getSize() == src->getSize()) {
1054 memcpy(tmpDst.getPixels(), src->getPixels(), src->getSafeSize());
1055 SkPixelRef* pixelRef = tmpDst.pixelRef();
1057 // In order to reach this point, we know that the width, config and
1058 // rowbytes of the SkPixelRefs are the same, but it is possible for
1059 // the heights to differ, if this SkBitmap's height is a subset of
1060 // fPixelRef. Only if the SkPixelRefs' heights match are we
1061 // guaranteed that this is an exact copy, meaning we should clone
1063 if (pixelRef->info().fHeight == fPixelRef->info().fHeight) {
1064 // TODO: what to do if the two infos match, BUT
1065 // fPixelRef is premul and pixelRef is opaque?
1066 // skipping assert for now
1067 // https://code.google.com/p/skia/issues/detail?id=2012
1068 // SkASSERT(pixelRef->info() == fPixelRef->info());
1069 SkASSERT(pixelRef->info().fWidth == fPixelRef->info().fWidth);
1070 SkASSERT(pixelRef->info().fColorType == fPixelRef->info().fColorType);
1071 pixelRef->cloneGenID(*fPixelRef);
1074 const char* srcP = reinterpret_cast<const char*>(src->getPixels());
1075 char* dstP = reinterpret_cast<char*>(tmpDst.getPixels());
1076 // to be sure we don't read too much, only copy our logical pixels
1077 size_t bytesToCopy = tmpDst.width() * tmpDst.bytesPerPixel();
1078 for (int y = 0; y < tmpDst.height(); y++) {
1079 memcpy(dstP, srcP, bytesToCopy);
1080 srcP += src->rowBytes();
1081 dstP += tmpDst.rowBytes();
1084 } else if (SkBitmap::kARGB_4444_Config == dstConfig
1085 && SkBitmap::kARGB_8888_Config == src->config()) {
1086 SkASSERT(src->height() == tmpDst.height());
1087 SkASSERT(src->width() == tmpDst.width());
1088 for (int y = 0; y < src->height(); ++y) {
1089 SkPMColor16* SK_RESTRICT dstRow = (SkPMColor16*) tmpDst.getAddr16(0, y);
1090 SkPMColor* SK_RESTRICT srcRow = (SkPMColor*) src->getAddr32(0, y);
1091 DITHER_4444_SCAN(y);
1092 for (int x = 0; x < src->width(); ++x) {
1093 dstRow[x] = SkDitherARGB32To4444(srcRow[x],
1098 // Always clear the dest in case one of the blitters accesses it
1099 // TODO: switch the allocation of tmpDst to call sk_calloc_throw
1100 tmpDst.eraseColor(SK_ColorTRANSPARENT);
1102 SkCanvas canvas(tmpDst);
1105 paint.setDither(true);
1106 canvas.drawBitmap(*src, 0, 0, &paint);
1113 bool SkBitmap::deepCopyTo(SkBitmap* dst, Config dstConfig) const {
1114 const SkColorType dstCT = SkBitmapConfigToColorType(dstConfig);
1116 if (!this->canCopyTo(dstConfig)) {
1120 // If we have a PixelRef, and it supports deep copy, use it.
1121 // Currently supported only by texture-backed bitmaps.
1123 SkPixelRef* pixelRef = fPixelRef->deepCopy(dstConfig);
1126 if (this->colorType() == dstCT) {
1127 // Since there is no subset to pass to deepCopy, and deepCopy
1128 // succeeded, the new pixel ref must be identical.
1129 SkASSERT(fPixelRef->info() == pixelRef->info());
1130 pixelRef->cloneGenID(*fPixelRef);
1131 // Use the same rowBytes as the original.
1132 rowBytes = fRowBytes;
1134 // With the new config, an appropriate fRowBytes will be computed by setConfig.
1138 SkImageInfo info = fInfo;
1139 info.fColorType = dstCT;
1140 if (!dst->setConfig(info, rowBytes)) {
1143 dst->setPixelRef(pixelRef, fPixelRefOrigin)->unref();
1148 if (this->getTexture()) {
1151 return this->copyTo(dst, dstConfig, NULL);
1155 ///////////////////////////////////////////////////////////////////////////////
1156 ///////////////////////////////////////////////////////////////////////////////
1158 static void downsampleby2_proc32(SkBitmap* dst, int x, int y,
1159 const SkBitmap& src) {
1162 const SkPMColor* p = src.getAddr32(x, y);
1163 const SkPMColor* baseP = p;
1164 SkPMColor c, ag, rb;
1166 c = *p; ag = (c >> 8) & 0xFF00FF; rb = c & 0xFF00FF;
1167 if (x < src.width() - 1) {
1170 c = *p; ag += (c >> 8) & 0xFF00FF; rb += c & 0xFF00FF;
1173 if (y < src.height() - 1) {
1174 p += src.rowBytes() >> 2;
1176 c = *p; ag += (c >> 8) & 0xFF00FF; rb += c & 0xFF00FF;
1177 if (x < src.width() - 1) {
1180 c = *p; ag += (c >> 8) & 0xFF00FF; rb += c & 0xFF00FF;
1182 *dst->getAddr32(x >> 1, y >> 1) =
1183 ((rb >> 2) & 0xFF00FF) | ((ag << 6) & 0xFF00FF00);
1186 static inline uint32_t expand16(U16CPU c) {
1187 return (c & ~SK_G16_MASK_IN_PLACE) | ((c & SK_G16_MASK_IN_PLACE) << 16);
1190 // returns dirt in the top 16bits, but we don't care, since we only
1191 // store the low 16bits.
1192 static inline U16CPU pack16(uint32_t c) {
1193 return (c & ~SK_G16_MASK_IN_PLACE) | ((c >> 16) & SK_G16_MASK_IN_PLACE);
1196 static void downsampleby2_proc16(SkBitmap* dst, int x, int y,
1197 const SkBitmap& src) {
1200 const uint16_t* p = src.getAddr16(x, y);
1201 const uint16_t* baseP = p;
1205 if (x < src.width() - 1) {
1211 if (y < src.height() - 1) {
1212 p += src.rowBytes() >> 1;
1215 if (x < src.width() - 1) {
1220 *dst->getAddr16(x >> 1, y >> 1) = (uint16_t)pack16(c >> 2);
1223 static uint32_t expand4444(U16CPU c) {
1224 return (c & 0xF0F) | ((c & ~0xF0F) << 12);
1227 static U16CPU collaps4444(uint32_t c) {
1228 return (c & 0xF0F) | ((c >> 12) & ~0xF0F);
1231 static void downsampleby2_proc4444(SkBitmap* dst, int x, int y,
1232 const SkBitmap& src) {
1235 const uint16_t* p = src.getAddr16(x, y);
1236 const uint16_t* baseP = p;
1240 if (x < src.width() - 1) {
1243 c += expand4444(*p);
1246 if (y < src.height() - 1) {
1247 p += src.rowBytes() >> 1;
1249 c += expand4444(*p);
1250 if (x < src.width() - 1) {
1253 c += expand4444(*p);
1255 *dst->getAddr16(x >> 1, y >> 1) = (uint16_t)collaps4444(c >> 2);
1258 void SkBitmap::buildMipMap(bool forceRebuild) {
1262 return; // we're already built
1264 SkASSERT(NULL == fMipMap);
1266 void (*proc)(SkBitmap* dst, int x, int y, const SkBitmap& src);
1268 const SkBitmap::Config config = this->config();
1271 case kARGB_8888_Config:
1272 proc = downsampleby2_proc32;
1274 case kRGB_565_Config:
1275 proc = downsampleby2_proc16;
1277 case kARGB_4444_Config:
1278 proc = downsampleby2_proc4444;
1280 case kIndex8_Config:
1283 return; // don't build mipmaps for these configs
1286 SkAutoLockPixels alp(*this);
1287 if (!this->readyToDraw()) {
1291 // whip through our loop to compute the exact size needed
1295 int width = this->width();
1296 int height = this->height();
1300 if (0 == width || 0 == height) {
1303 size += ComputeRowBytes(config, width) * height;
1309 if (0 == maxLevels) {
1313 SkBitmap srcBM(*this);
1315 if (!srcBM.readyToDraw()) {
1319 MipMap* mm = MipMap::Alloc(maxLevels, size);
1324 MipLevel* level = mm->levels();
1325 uint8_t* addr = (uint8_t*)mm->pixels();
1326 int width = this->width();
1327 int height = this->height();
1331 for (int i = 0; i < maxLevels; i++) {
1334 rowBytes = SkToU32(ComputeRowBytes(config, width));
1336 level[i].fPixels = addr;
1337 level[i].fWidth = width;
1338 level[i].fHeight = height;
1339 level[i].fRowBytes = rowBytes;
1341 dstBM.setConfig(config, width, height, rowBytes);
1342 dstBM.setPixels(addr);
1345 for (int y = 0; y < height; y++) {
1346 for (int x = 0; x < width; x++) {
1347 proc(&dstBM, x, y, srcBM);
1350 srcBM.unlockPixels();
1353 addr += height * rowBytes;
1355 SkASSERT(addr == (uint8_t*)mm->pixels() + size);
1359 bool SkBitmap::hasMipMap() const {
1360 return fMipMap != NULL;
1363 int SkBitmap::extractMipLevel(SkBitmap* dst, SkFixed sx, SkFixed sy) {
1364 if (NULL == fMipMap) {
1368 int level = ComputeMipLevel(sx, sy) >> 16;
1369 SkASSERT(level >= 0);
1374 if (level >= fMipMap->fLevelCount) {
1375 level = fMipMap->fLevelCount - 1;
1378 const MipLevel& mip = fMipMap->levels()[level - 1];
1379 dst->setConfig((SkBitmap::Config)this->config(),
1380 mip.fWidth, mip.fHeight, mip.fRowBytes);
1381 dst->setPixels(mip.fPixels);
1386 SkFixed SkBitmap::ComputeMipLevel(SkFixed sx, SkFixed sy) {
1392 if (sx < SK_Fixed1) {
1395 int clz = SkCLZ(sx);
1396 SkASSERT(clz >= 1 && clz <= 15);
1397 return SkIntToFixed(15 - clz) + ((unsigned)(sx << (clz + 1)) >> 16);
1400 ///////////////////////////////////////////////////////////////////////////////
1402 static bool GetBitmapAlpha(const SkBitmap& src, uint8_t* SK_RESTRICT alpha,
1403 int alphaRowBytes) {
1404 SkASSERT(alpha != NULL);
1405 SkASSERT(alphaRowBytes >= src.width());
1407 SkBitmap::Config config = src.config();
1408 int w = src.width();
1409 int h = src.height();
1410 size_t rb = src.rowBytes();
1412 SkAutoLockPixels alp(src);
1413 if (!src.readyToDraw()) {
1414 // zero out the alpha buffer and return
1416 memset(alpha, 0, w);
1417 alpha += alphaRowBytes;
1422 if (SkBitmap::kA8_Config == config && !src.isOpaque()) {
1423 const uint8_t* s = src.getAddr8(0, 0);
1425 memcpy(alpha, s, w);
1427 alpha += alphaRowBytes;
1429 } else if (SkBitmap::kARGB_8888_Config == config && !src.isOpaque()) {
1430 const SkPMColor* SK_RESTRICT s = src.getAddr32(0, 0);
1432 for (int x = 0; x < w; x++) {
1433 alpha[x] = SkGetPackedA32(s[x]);
1435 s = (const SkPMColor*)((const char*)s + rb);
1436 alpha += alphaRowBytes;
1438 } else if (SkBitmap::kARGB_4444_Config == config && !src.isOpaque()) {
1439 const SkPMColor16* SK_RESTRICT s = src.getAddr16(0, 0);
1441 for (int x = 0; x < w; x++) {
1442 alpha[x] = SkPacked4444ToA32(s[x]);
1444 s = (const SkPMColor16*)((const char*)s + rb);
1445 alpha += alphaRowBytes;
1447 } else if (SkBitmap::kIndex8_Config == config && !src.isOpaque()) {
1448 SkColorTable* ct = src.getColorTable();
1450 const SkPMColor* SK_RESTRICT table = ct->lockColors();
1451 const uint8_t* SK_RESTRICT s = src.getAddr8(0, 0);
1453 for (int x = 0; x < w; x++) {
1454 alpha[x] = SkGetPackedA32(table[s[x]]);
1457 alpha += alphaRowBytes;
1461 } else { // src is opaque, so just fill alpha[] with 0xFF
1462 memset(alpha, 0xFF, h * alphaRowBytes);
1467 #include "SkPaint.h"
1468 #include "SkMaskFilter.h"
1469 #include "SkMatrix.h"
1471 bool SkBitmap::extractAlpha(SkBitmap* dst, const SkPaint* paint,
1472 Allocator *allocator, SkIPoint* offset) const {
1473 SkDEBUGCODE(this->validate();)
1479 srcM.fBounds.set(0, 0, this->width(), this->height());
1480 srcM.fRowBytes = SkAlign4(this->width());
1481 srcM.fFormat = SkMask::kA8_Format;
1483 SkMaskFilter* filter = paint ? paint->getMaskFilter() : NULL;
1485 // compute our (larger?) dst bounds if we have a filter
1486 if (NULL != filter) {
1489 if (!filter->filterMask(&dstM, srcM, identity, NULL)) {
1490 goto NO_FILTER_CASE;
1492 dstM.fRowBytes = SkAlign4(dstM.fBounds.width());
1495 tmpBitmap.setConfig(SkBitmap::kA8_Config, this->width(), this->height(),
1497 if (!tmpBitmap.allocPixels(allocator, NULL)) {
1498 // Allocation of pixels for alpha bitmap failed.
1499 SkDebugf("extractAlpha failed to allocate (%d,%d) alpha bitmap\n",
1500 tmpBitmap.width(), tmpBitmap.height());
1503 GetBitmapAlpha(*this, tmpBitmap.getAddr8(0, 0), srcM.fRowBytes);
1507 tmpBitmap.swap(*dst);
1510 srcM.fImage = SkMask::AllocImage(srcM.computeImageSize());
1511 SkAutoMaskFreeImage srcCleanup(srcM.fImage);
1513 GetBitmapAlpha(*this, srcM.fImage, srcM.fRowBytes);
1514 if (!filter->filterMask(&dstM, srcM, identity, NULL)) {
1515 goto NO_FILTER_CASE;
1517 SkAutoMaskFreeImage dstCleanup(dstM.fImage);
1519 tmpBitmap.setConfig(SkBitmap::kA8_Config, dstM.fBounds.width(),
1520 dstM.fBounds.height(), dstM.fRowBytes);
1521 if (!tmpBitmap.allocPixels(allocator, NULL)) {
1522 // Allocation of pixels for alpha bitmap failed.
1523 SkDebugf("extractAlpha failed to allocate (%d,%d) alpha bitmap\n",
1524 tmpBitmap.width(), tmpBitmap.height());
1527 memcpy(tmpBitmap.getPixels(), dstM.fImage, dstM.computeImageSize());
1529 offset->set(dstM.fBounds.fLeft, dstM.fBounds.fTop);
1531 SkDEBUGCODE(tmpBitmap.validate();)
1533 tmpBitmap.swap(*dst);
1537 ///////////////////////////////////////////////////////////////////////////////
1540 SERIALIZE_PIXELTYPE_NONE,
1541 SERIALIZE_PIXELTYPE_REF_DATA
1544 void SkBitmap::flatten(SkWriteBuffer& buffer) const {
1545 fInfo.flatten(buffer);
1546 buffer.writeInt(fRowBytes);
1549 if (fPixelRef->getFactory()) {
1550 buffer.writeInt(SERIALIZE_PIXELTYPE_REF_DATA);
1551 buffer.writeInt(fPixelRefOrigin.fX);
1552 buffer.writeInt(fPixelRefOrigin.fY);
1553 buffer.writeFlattenable(fPixelRef);
1556 // if we get here, we can't record the pixels
1557 buffer.writeInt(SERIALIZE_PIXELTYPE_NONE);
1559 buffer.writeInt(SERIALIZE_PIXELTYPE_NONE);
1563 void SkBitmap::unflatten(SkReadBuffer& buffer) {
1567 info.unflatten(buffer);
1568 size_t rowBytes = buffer.readInt();
1569 if (!buffer.validate((info.width() >= 0) && (info.height() >= 0) &&
1570 SkColorTypeIsValid(info.fColorType) &&
1571 SkAlphaTypeIsValid(info.fAlphaType) &&
1572 validate_alphaType(info.fColorType, info.fAlphaType) &&
1573 info.validRowBytes(rowBytes))) {
1577 bool configIsValid = this->setConfig(info, rowBytes);
1578 buffer.validate(configIsValid);
1580 int reftype = buffer.readInt();
1581 if (buffer.validate((SERIALIZE_PIXELTYPE_REF_DATA == reftype) ||
1582 (SERIALIZE_PIXELTYPE_NONE == reftype))) {
1584 case SERIALIZE_PIXELTYPE_REF_DATA: {
1586 origin.fX = buffer.readInt();
1587 origin.fY = buffer.readInt();
1588 size_t offset = origin.fY * rowBytes + origin.fX * info.bytesPerPixel();
1589 SkPixelRef* pr = buffer.readPixelRef();
1590 if (!buffer.validate((NULL == pr) ||
1591 (pr->getAllocatedSizeInBytes() >= (offset + this->getSafeSize())))) {
1594 SkSafeUnref(this->setPixelRef(pr, origin));
1597 case SERIALIZE_PIXELTYPE_NONE:
1600 SkDEBUGFAIL("unrecognized pixeltype in serialized data");
1606 ///////////////////////////////////////////////////////////////////////////////
1608 SkBitmap::RLEPixels::RLEPixels(int width, int height) {
1610 fYPtrs = (uint8_t**)sk_calloc_throw(height * sizeof(uint8_t*));
1613 SkBitmap::RLEPixels::~RLEPixels() {
1617 ///////////////////////////////////////////////////////////////////////////////
1620 void SkBitmap::validate() const {
1622 SkASSERT(fInfo.validRowBytes(fRowBytes));
1623 uint8_t allFlags = kImageIsOpaque_Flag | kImageIsVolatile_Flag | kImageIsImmutable_Flag;
1624 #ifdef SK_BUILD_FOR_ANDROID
1625 allFlags |= kHasHardwareMipMap_Flag;
1627 SkASSERT(fFlags <= allFlags);
1628 SkASSERT(fPixelLockCount >= 0);
1631 SkASSERT(fPixelRef);
1632 SkASSERT(fPixelLockCount > 0);
1633 SkASSERT(fPixelRef->isLocked());
1634 SkASSERT(fPixelRef->rowBytes() == fRowBytes);
1635 SkASSERT(fPixelRefOrigin.fX >= 0);
1636 SkASSERT(fPixelRefOrigin.fY >= 0);
1637 SkASSERT(fPixelRef->info().width() >= (int)this->width() + fPixelRefOrigin.fX);
1638 SkASSERT(fPixelRef->info().fHeight >= (int)this->height() + fPixelRefOrigin.fY);
1639 SkASSERT(fPixelRef->rowBytes() >= fInfo.minRowBytes());
1641 SkASSERT(NULL == fColorTable);
1647 void SkBitmap::toString(SkString* str) const {
1649 static const char* gConfigNames[kConfigCount] = {
1650 "NONE", "A8", "INDEX8", "565", "4444", "8888"
1653 str->appendf("bitmap: ((%d, %d) %s", this->width(), this->height(),
1654 gConfigNames[this->config()]);
1657 if (this->isOpaque()) {
1658 str->append("opaque");
1660 str->append("transparent");
1662 if (this->isImmutable()) {
1663 str->append(", immutable");
1665 str->append(", not-immutable");
1669 SkPixelRef* pr = this->pixelRef();
1671 // show null or the explicit pixel address (rare)
1672 str->appendf(" pixels:%p", this->getPixels());
1674 const char* uri = pr->getURI();
1676 str->appendf(" uri:\"%s\"", uri);
1678 str->appendf(" pixelref:%p", pr);
1686 ///////////////////////////////////////////////////////////////////////////////
1689 void SkImageInfo::validate() const {
1690 SkASSERT(fWidth >= 0);
1691 SkASSERT(fHeight >= 0);
1692 SkASSERT(SkColorTypeIsValid(fColorType));
1693 SkASSERT(SkAlphaTypeIsValid(fAlphaType));