Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / third_party / skia / src / core / SkBitmap.cpp
1
2 /*
3  * Copyright 2008 The Android Open Source Project
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
9
10 #include "SkBitmap.h"
11 #include "SkColorPriv.h"
12 #include "SkDither.h"
13 #include "SkFlattenable.h"
14 #include "SkImagePriv.h"
15 #include "SkMallocPixelRef.h"
16 #include "SkMask.h"
17 #include "SkReadBuffer.h"
18 #include "SkWriteBuffer.h"
19 #include "SkPixelRef.h"
20 #include "SkThread.h"
21 #include "SkUnPreMultiply.h"
22 #include "SkUtils.h"
23 #include "SkValidationUtils.h"
24 #include "SkPackBits.h"
25 #include <new>
26
27 static bool reset_return_false(SkBitmap* bm) {
28     bm->reset();
29     return false;
30 }
31
32 struct MipLevel {
33     void*       fPixels;
34     uint32_t    fRowBytes;
35     uint32_t    fWidth, fHeight;
36 };
37
38 struct SkBitmap::MipMap : SkNoncopyable {
39     int32_t fRefCnt;
40     int     fLevelCount;
41 //  MipLevel    fLevel[fLevelCount];
42 //  Pixels[]
43
44     static MipMap* Alloc(int levelCount, size_t pixelSize) {
45         if (levelCount < 0) {
46             return NULL;
47         }
48         int64_t size = (levelCount + 1) * sizeof(MipLevel);
49         size += sizeof(MipMap) + pixelSize;
50         if (!sk_64_isS32(size)) {
51             return NULL;
52         }
53         MipMap* mm = (MipMap*)sk_malloc_throw(sk_64_asS32(size));
54         mm->fRefCnt = 1;
55         mm->fLevelCount = levelCount;
56         return mm;
57     }
58
59     const MipLevel* levels() const { return (const MipLevel*)(this + 1); }
60     MipLevel* levels() { return (MipLevel*)(this + 1); }
61
62     const void* pixels() const { return levels() + fLevelCount; }
63     void* pixels() { return levels() + fLevelCount; }
64
65     void ref() {
66         if (SK_MaxS32 == sk_atomic_inc(&fRefCnt)) {
67             sk_throw();
68         }
69     }
70     void unref() {
71         SkASSERT(fRefCnt > 0);
72         if (sk_atomic_dec(&fRefCnt) == 1) {
73             sk_free(this);
74         }
75     }
76 };
77
78 ///////////////////////////////////////////////////////////////////////////////
79 ///////////////////////////////////////////////////////////////////////////////
80
81 SkBitmap::SkBitmap() {
82     sk_bzero(this, sizeof(*this));
83 }
84
85 SkBitmap::SkBitmap(const SkBitmap& src) {
86     SkDEBUGCODE(src.validate();)
87     sk_bzero(this, sizeof(*this));
88     *this = src;
89     SkDEBUGCODE(this->validate();)
90 }
91
92 SkBitmap::~SkBitmap() {
93     SkDEBUGCODE(this->validate();)
94     this->freePixels();
95 }
96
97 SkBitmap& SkBitmap::operator=(const SkBitmap& src) {
98     if (this != &src) {
99         this->freePixels();
100         memcpy(this, &src, sizeof(src));
101
102         // inc src reference counts
103         SkSafeRef(src.fPixelRef);
104         SkSafeRef(src.fMipMap);
105
106         // we reset our locks if we get blown away
107         fPixelLockCount = 0;
108
109         if (fPixelRef) {
110             // ignore the values from the memcpy
111             fPixels = NULL;
112             fColorTable = NULL;
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
116             // setPixels.
117             // Just leave the memcpy'ed one but they'll get out of sync
118             // as soon either is modified.
119         }
120     }
121
122     SkDEBUGCODE(this->validate();)
123     return *this;
124 }
125
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);
136
137     SkDEBUGCODE(this->validate();)
138 }
139
140 void SkBitmap::reset() {
141     this->freePixels();
142     sk_bzero(this, sizeof(*this));
143 }
144
145 SkBitmap::Config SkBitmap::config() const {
146     return SkColorTypeToBitmapConfig(fInfo.colorType());
147 }
148
149 int SkBitmap::ComputeBytesPerPixel(SkBitmap::Config config) {
150     int bpp;
151     switch (config) {
152         case kNo_Config:
153             bpp = 0;   // not applicable
154             break;
155         case kA8_Config:
156         case kIndex8_Config:
157             bpp = 1;
158             break;
159         case kRGB_565_Config:
160         case kARGB_4444_Config:
161             bpp = 2;
162             break;
163         case kARGB_8888_Config:
164             bpp = 4;
165             break;
166         default:
167             SkDEBUGFAIL("unknown config");
168             bpp = 0;   // error
169             break;
170     }
171     return bpp;
172 }
173
174 size_t SkBitmap::ComputeRowBytes(Config c, int width) {
175     return SkColorTypeMinRowBytes(SkBitmapConfigToColorType(c), width);
176 }
177
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;
182 }
183
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;
187 }
188
189 int64_t SkBitmap::ComputeSafeSize64(Config config,
190                                     uint32_t width,
191                                     uint32_t height,
192                                     size_t rowBytes) {
193     SkImageInfo info = SkImageInfo::Make(width, height,
194                                          SkBitmapConfigToColorType(config),
195                                          kPremul_SkAlphaType);
196     return info.getSafeSize64(rowBytes);
197 }
198
199 size_t SkBitmap::ComputeSafeSize(Config config,
200                                  uint32_t width,
201                                  uint32_t height,
202                                  size_t rowBytes) {
203     int64_t safeSize = ComputeSafeSize64(config, width, height, rowBytes);
204     int32_t safeSize32 = (int32_t)safeSize;
205
206     if (safeSize32 != safeSize) {
207         safeSize32 = 0;
208     }
209     return safeSize32;
210 }
211
212 void SkBitmap::getBounds(SkRect* bounds) const {
213     SkASSERT(bounds);
214     bounds->set(0, 0,
215                 SkIntToScalar(fInfo.fWidth), SkIntToScalar(fInfo.fHeight));
216 }
217
218 void SkBitmap::getBounds(SkIRect* bounds) const {
219     SkASSERT(bounds);
220     bounds->set(0, 0, fInfo.fWidth, fInfo.fHeight);
221 }
222
223 ///////////////////////////////////////////////////////////////////////////////
224
225 static bool validate_alphaType(SkColorType colorType, SkAlphaType alphaType,
226                                SkAlphaType* canonical = NULL) {
227     switch (colorType) {
228         case kUnknown_SkColorType:
229             alphaType = kIgnore_SkAlphaType;
230             break;
231         case kAlpha_8_SkColorType:
232             if (kUnpremul_SkAlphaType == alphaType) {
233                 alphaType = kPremul_SkAlphaType;
234             }
235             // fall-through
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) {
241                 return false;
242             }
243             break;
244         case kRGB_565_SkColorType:
245             alphaType = kOpaque_SkAlphaType;
246             break;
247         default:
248             return false;
249     }
250     if (canonical) {
251         *canonical = alphaType;
252     }
253     return true;
254 }
255
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);
261     }
262     if ((int64_t)rowBytes != (int32_t)rowBytes) {
263         return reset_return_false(this);
264     }
265
266     if (info.width() < 0 || info.height() < 0) {
267         return reset_return_false(this);
268     }
269
270     if (kUnknown_SkColorType == info.colorType()) {
271         rowBytes = 0;
272     } else if (0 == rowBytes) {
273         rowBytes = (size_t)mrb;
274     } else if (rowBytes < info.minRowBytes()) {
275         return reset_return_false(this);
276     }
277
278     this->freePixels();
279
280     fInfo = info;
281     fRowBytes = SkToU32(rowBytes);
282     return true;
283 }
284
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),
289                            rowBytes);
290 }
291
292 bool SkBitmap::setAlphaType(SkAlphaType alphaType) {
293     if (!validate_alphaType(fInfo.fColorType, alphaType, &alphaType)) {
294         return false;
295     }
296     if (fInfo.fAlphaType != alphaType) {
297         fInfo.fAlphaType = alphaType;
298         if (fPixelRef) {
299             fPixelRef->changeAlphaType(alphaType);
300         }
301     }
302     return true;
303 }
304
305 void SkBitmap::updatePixelsFromRef() const {
306     if (NULL != fPixelRef) {
307         if (fPixelLockCount > 0) {
308             SkASSERT(fPixelRef->isLocked());
309
310             void* p = fPixelRef->pixels();
311             if (NULL != p) {
312                 p = (char*)p
313                     + fPixelRefOrigin.fY * fRowBytes
314                     + fPixelRefOrigin.fX * fInfo.bytesPerPixel();
315             }
316             fPixels = p;
317             fColorTable = fPixelRef->colorTable();
318         } else {
319             SkASSERT(0 == fPixelLockCount);
320             fPixels = NULL;
321             fColorTable = NULL;
322         }
323     }
324 }
325
326 static bool config_to_colorType(SkBitmap::Config config, SkColorType* ctOut) {
327     SkColorType ct;
328     switch (config) {
329         case SkBitmap::kA8_Config:
330             ct = kAlpha_8_SkColorType;
331             break;
332         case SkBitmap::kIndex8_Config:
333             ct = kIndex_8_SkColorType;
334             break;
335         case SkBitmap::kRGB_565_Config:
336             ct = kRGB_565_SkColorType;
337             break;
338         case SkBitmap::kARGB_4444_Config:
339             ct = kARGB_4444_SkColorType;
340             break;
341         case SkBitmap::kARGB_8888_Config:
342             ct = kPMColor_SkColorType;
343             break;
344         case SkBitmap::kNo_Config:
345         default:
346             return false;
347     }
348     if (ctOut) {
349         *ctOut = ct;
350     }
351     return true;
352 }
353
354 SkPixelRef* SkBitmap::setPixelRef(SkPixelRef* pr, int dx, int dy) {
355 #ifdef SK_DEBUG
356     if (pr) {
357         SkImageInfo info;
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);
366                     break;
367                 case kOpaque_SkAlphaType:
368                 case kPremul_SkAlphaType:
369                     SkASSERT(info.fAlphaType == kOpaque_SkAlphaType ||
370                              info.fAlphaType == kPremul_SkAlphaType);
371                     break;
372                 case kUnpremul_SkAlphaType:
373                     SkASSERT(info.fAlphaType == kOpaque_SkAlphaType ||
374                              info.fAlphaType == kUnpremul_SkAlphaType);
375                     break;
376             }
377         }
378     }
379 #endif
380
381     if (pr) {
382         const SkImageInfo& info = pr->info();
383         fPixelRefOrigin.set(SkPin32(dx, 0, info.fWidth),
384                             SkPin32(dy, 0, info.fHeight));
385     } else {
386         // ignore dx,dy if there is no pixelref
387         fPixelRefOrigin.setZero();
388     }
389
390     if (fPixelRef != pr) {
391         if (fPixelRef != pr) {
392             this->freePixels();
393             SkASSERT(NULL == fPixelRef);
394
395             SkSafeRef(pr);
396             fPixelRef = pr;
397         }
398         this->updatePixelsFromRef();
399     }
400
401     SkDEBUGCODE(this->validate();)
402     return pr;
403 }
404
405 void SkBitmap::lockPixels() const {
406     if (NULL != fPixelRef && 0 == sk_atomic_inc(&fPixelLockCount)) {
407         fPixelRef->lockPixels();
408         this->updatePixelsFromRef();
409     }
410     SkDEBUGCODE(this->validate();)
411 }
412
413 void SkBitmap::unlockPixels() const {
414     SkASSERT(NULL == fPixelRef || fPixelLockCount > 0);
415
416     if (NULL != fPixelRef && 1 == sk_atomic_dec(&fPixelLockCount)) {
417         fPixelRef->unlockPixels();
418         this->updatePixelsFromRef();
419     }
420     SkDEBUGCODE(this->validate();)
421 }
422
423 bool SkBitmap::lockPixelsAreWritable() const {
424     return (fPixelRef) ? fPixelRef->lockPixelsAreWritable() : false;
425 }
426
427 void SkBitmap::setPixels(void* p, SkColorTable* ctable) {
428     if (NULL == p) {
429         this->setPixelRef(NULL);
430         return;
431     }
432
433     SkImageInfo info;
434     if (!this->asImageInfo(&info)) {
435         this->setPixelRef(NULL);
436         return;
437     }
438
439     SkPixelRef* pr = SkMallocPixelRef::NewDirect(info, p, fRowBytes, ctable);
440     if (NULL == pr) {
441         this->setPixelRef(NULL);
442         return;
443     }
444
445     this->setPixelRef(pr)->unref();
446
447     // since we're already allocated, we lockPixels right away
448     this->lockPixels();
449     SkDEBUGCODE(this->validate();)
450 }
451
452 bool SkBitmap::allocPixels(Allocator* allocator, SkColorTable* ctable) {
453     HeapAllocator stdalloc;
454
455     if (NULL == allocator) {
456         allocator = &stdalloc;
457     }
458     return allocator->allocPixelRef(this, ctable);
459 }
460
461 ///////////////////////////////////////////////////////////////////////////////
462
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);
467     }
468     if (!this->setConfig(info)) {
469         return reset_return_false(this);
470     }
471
472     SkMallocPixelRef::PRFactory defaultFactory;
473     if (NULL == factory) {
474         factory = &defaultFactory;
475     }
476
477     SkPixelRef* pr = factory->create(info, ctable);
478     if (NULL == pr) {
479         return reset_return_false(this);
480     }
481     this->setPixelRef(pr)->unref();
482
483     // TODO: lockPixels could/should return bool or void*/NULL
484     this->lockPixels();
485     if (NULL == this->getPixels()) {
486         return reset_return_false(this);
487     }
488     return true;
489 }
490
491 bool SkBitmap::installPixels(const SkImageInfo& info, void* pixels, size_t rb,
492                              void (*releaseProc)(void* addr, void* context),
493                              void* context) {
494     if (!this->setConfig(info, rb)) {
495         this->reset();
496         return false;
497     }
498
499     SkPixelRef* pr = SkMallocPixelRef::NewWithProc(info, rb, NULL, pixels,
500                                                    releaseProc, context);
501     if (!pr) {
502         this->reset();
503         return false;
504     }
505
506     this->setPixelRef(pr)->unref();
507     return true;
508 }
509
510 bool SkBitmap::allocConfigPixels(Config config, int width, int height,
511                                  bool isOpaque) {
512     SkColorType ct;
513     if (!config_to_colorType(config, &ct)) {
514         return false;
515     }
516
517     SkAlphaType at = isOpaque ? kOpaque_SkAlphaType : kPremul_SkAlphaType;
518     return this->allocPixels(SkImageInfo::Make(width, height, ct, at));
519 }
520
521 ///////////////////////////////////////////////////////////////////////////////
522
523 void SkBitmap::freePixels() {
524     // if we're gonna free the pixels, we certainly need to free the mipmap
525     this->freeMipMap();
526
527     if (NULL != fPixelRef) {
528         if (fPixelLockCount > 0) {
529             fPixelRef->unlockPixels();
530         }
531         fPixelRef->unref();
532         fPixelRef = NULL;
533         fPixelRefOrigin.setZero();
534     }
535     fPixelLockCount = 0;
536     fPixels = NULL;
537     fColorTable = NULL;
538 }
539
540 void SkBitmap::freeMipMap() {
541     if (fMipMap) {
542         fMipMap->unref();
543         fMipMap = NULL;
544     }
545 }
546
547 uint32_t SkBitmap::getGenerationID() const {
548     return (fPixelRef) ? fPixelRef->getGenerationID() : 0;
549 }
550
551 void SkBitmap::notifyPixelsChanged() const {
552     SkASSERT(!this->isImmutable());
553     if (fPixelRef) {
554         fPixelRef->notifyPixelsChanged();
555     }
556 }
557
558 GrTexture* SkBitmap::getTexture() const {
559     return fPixelRef ? fPixelRef->getTexture() : NULL;
560 }
561
562 ///////////////////////////////////////////////////////////////////////////////
563
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.
566  */
567 bool SkBitmap::HeapAllocator::allocPixelRef(SkBitmap* dst,
568                                             SkColorTable* ctable) {
569     SkImageInfo info;
570     if (!dst->asImageInfo(&info)) {
571 //        SkDebugf("unsupported config for info %d\n", dst->config());
572         return false;
573     }
574
575     SkPixelRef* pr = SkMallocPixelRef::NewAllocate(info, dst->rowBytes(),
576                                                    ctable);
577     if (NULL == pr) {
578         return false;
579     }
580
581     dst->setPixelRef(pr)->unref();
582     // since we're already allocated, we lockPixels right away
583     dst->lockPixels();
584     return true;
585 }
586
587 ///////////////////////////////////////////////////////////////////////////////
588
589 bool SkBitmap::copyPixelsTo(void* const dst, size_t dstSize,
590                             size_t dstRowBytes, bool preserveDstPad) const {
591
592     if (0 == dstRowBytes) {
593         dstRowBytes = fRowBytes;
594     }
595
596     if (dstRowBytes < fInfo.minRowBytes() ||
597         dst == NULL || (getPixels() == NULL && pixelRef() == NULL)) {
598         return false;
599     }
600
601     if (!preserveDstPad && static_cast<uint32_t>(dstRowBytes) == fRowBytes) {
602         size_t safeSize = this->getSafeSize();
603         if (safeSize > dstSize || safeSize == 0)
604             return false;
605         else {
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);
611
612             return true;
613         }
614     } else {
615         // If destination has different stride than us, then copy line by line.
616         if (fInfo.getSafeSize(dstRowBytes) > dstSize) {
617             return false;
618         } else {
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);
627             }
628
629             return true;
630         }
631     }
632 }
633
634 ///////////////////////////////////////////////////////////////////////////////
635
636 bool SkBitmap::isImmutable() const {
637     return fPixelRef ? fPixelRef->isImmutable() :
638         fFlags & kImageIsImmutable_Flag;
639 }
640
641 void SkBitmap::setImmutable() {
642     if (fPixelRef) {
643         fPixelRef->setImmutable();
644     } else {
645         fFlags |= kImageIsImmutable_Flag;
646     }
647 }
648
649 bool SkBitmap::isVolatile() const {
650     return (fFlags & kImageIsVolatile_Flag) != 0;
651 }
652
653 void SkBitmap::setIsVolatile(bool isVolatile) {
654     if (isVolatile) {
655         fFlags |= kImageIsVolatile_Flag;
656     } else {
657         fFlags &= ~kImageIsVolatile_Flag;
658     }
659 }
660
661 void* SkBitmap::getAddr(int x, int y) const {
662     SkASSERT((unsigned)x < (unsigned)this->width());
663     SkASSERT((unsigned)y < (unsigned)this->height());
664
665     char* base = (char*)this->getPixels();
666     if (base) {
667         base += y * this->rowBytes();
668         switch (this->colorType()) {
669             case kRGBA_8888_SkColorType:
670             case kBGRA_8888_SkColorType:
671                 base += x << 2;
672                 break;
673             case kARGB_4444_SkColorType:
674             case kRGB_565_SkColorType:
675                 base += x << 1;
676                 break;
677             case kAlpha_8_SkColorType:
678             case kIndex_8_SkColorType:
679                 base += x;
680                 break;
681             default:
682                 SkDEBUGFAIL("Can't return addr for config");
683                 base = NULL;
684                 break;
685         }
686     }
687     return base;
688 }
689
690 SkColor SkBitmap::getColor(int x, int y) const {
691     SkASSERT((unsigned)x < (unsigned)this->width());
692     SkASSERT((unsigned)y < (unsigned)this->height());
693
694     switch (this->config()) {
695         case SkBitmap::kA8_Config: {
696             uint8_t* addr = this->getAddr8(x, y);
697             return SkColorSetA(0, addr[0]);
698         }
699         case SkBitmap::kIndex8_Config: {
700             SkPMColor c = this->getIndex8Color(x, y);
701             return SkUnPreMultiply::PMColorToColor(c);
702         }
703         case SkBitmap::kRGB_565_Config: {
704             uint16_t* addr = this->getAddr16(x, y);
705             return SkPixel16ToColor(addr[0]);
706         }
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);
711         }
712         case SkBitmap::kARGB_8888_Config: {
713             uint32_t* addr = this->getAddr32(x, y);
714             return SkUnPreMultiply::PMColorToColor(addr[0]);
715         }
716         case kNo_Config:
717         default:
718             SkASSERT(false);
719             return 0;
720     }
721     SkASSERT(false);  // Not reached.
722     return 0;
723 }
724
725 bool SkBitmap::ComputeIsOpaque(const SkBitmap& bm) {
726     SkAutoLockPixels alp(bm);
727     if (!bm.getPixels()) {
728         return false;
729     }
730
731     const int height = bm.height();
732     const int width = bm.width();
733
734     switch (bm.config()) {
735         case SkBitmap::kA8_Config: {
736             unsigned a = 0xFF;
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) {
740                     a &= row[x];
741                 }
742                 if (0xFF != a) {
743                     return false;
744                 }
745             }
746             return true;
747         } break;
748         case SkBitmap::kIndex8_Config: {
749             SkAutoLockColors alc(bm);
750             const SkPMColor* table = alc.colors();
751             if (!table) {
752                 return false;
753             }
754             SkPMColor c = (SkPMColor)~0;
755             for (int i = bm.getColorTable()->count() - 1; i >= 0; --i) {
756                 c &= table[i];
757             }
758             return 0xFF == SkGetPackedA32(c);
759         } break;
760         case SkBitmap::kRGB_565_Config:
761             return true;
762             break;
763         case SkBitmap::kARGB_4444_Config: {
764             unsigned c = 0xFFFF;
765             for (int y = 0; y < height; ++y) {
766                 const SkPMColor16* row = bm.getAddr16(0, y);
767                 for (int x = 0; x < width; ++x) {
768                     c &= row[x];
769                 }
770                 if (0xF != SkGetPackedA4444(c)) {
771                     return false;
772                 }
773             }
774             return true;
775         } break;
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) {
781                     c &= row[x];
782                 }
783                 if (0xFF != SkGetPackedA32(c)) {
784                     return false;
785                 }
786             }
787             return true;
788         }
789         default:
790             break;
791     }
792     return false;
793 }
794
795
796 ///////////////////////////////////////////////////////////////////////////////
797 ///////////////////////////////////////////////////////////////////////////////
798
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);
805 }
806
807 void SkBitmap::internalErase(const SkIRect& area,
808                              U8CPU a, U8CPU r, U8CPU g, U8CPU b) const {
809 #ifdef SK_DEBUG
810     SkDEBUGCODE(this->validate();)
811     SkASSERT(!area.isEmpty());
812     {
813         SkIRect total = { 0, 0, this->width(), this->height() };
814         SkASSERT(total.contains(area));
815     }
816 #endif
817
818     switch (fInfo.colorType()) {
819         case kUnknown_SkColorType:
820         case kIndex_8_SkColorType:
821             return; // can't erase
822         default:
823             break;
824     }
825
826     SkAutoLockPixels alp(*this);
827     // perform this check after the lock call
828     if (!this->readyToDraw()) {
829         return;
830     }
831
832     int height = area.height();
833     const int width = area.width();
834     const int rowBytes = fRowBytes;
835
836     // make rgb premultiplied
837     if (255 != a) {
838         r = SkAlphaMul(r, a);
839         g = SkAlphaMul(g, a);
840         b = SkAlphaMul(b, a);
841     }
842
843     switch (this->colorType()) {
844         case kAlpha_8_SkColorType: {
845             uint8_t* p = this->getAddr8(area.fLeft, area.fTop);
846             while (--height >= 0) {
847                 memset(p, a, width);
848                 p += rowBytes;
849             }
850             break;
851         }
852         case kARGB_4444_SkColorType:
853         case kRGB_565_SkColorType: {
854             uint16_t* p = this->getAddr16(area.fLeft, area.fTop);;
855             uint16_t v;
856
857             if (kARGB_4444_SkColorType == this->colorType()) {
858                 v = pack_8888_to_4444(a, r, g, b);
859             } else {
860                 v = SkPackRGB16(r >> (8 - SK_R16_BITS),
861                                 g >> (8 - SK_G16_BITS),
862                                 b >> (8 - SK_B16_BITS));
863             }
864             while (--height >= 0) {
865                 sk_memset16(p, v, width);
866                 p = (uint16_t*)((char*)p + rowBytes);
867             }
868             break;
869         }
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);
875
876             while (--height >= 0) {
877                 sk_memset32(p, v, width);
878                 p = (uint32_t*)((char*)p + rowBytes);
879             }
880             break;
881         }
882         default:
883             return; // no change, so don't call notifyPixelsChanged()
884     }
885
886     this->notifyPixelsChanged();
887 }
888
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);
893     }
894 }
895
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));
901     }
902 }
903
904 //////////////////////////////////////////////////////////////////////////////////////
905 //////////////////////////////////////////////////////////////////////////////////////
906
907 bool SkBitmap::extractSubset(SkBitmap* result, const SkIRect& subset) const {
908     SkDEBUGCODE(this->validate();)
909
910     if (NULL == result || NULL == fPixelRef) {
911         return false;   // no src pixels
912     }
913
914     SkIRect srcRect, r;
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)
918     }
919
920     if (fPixelRef->getTexture() != NULL) {
921         // Do a deep copy
922         SkPixelRef* pixelRef = fPixelRef->deepCopy(this->config(), &subset);
923         if (pixelRef != NULL) {
924             SkBitmap dst;
925             dst.setConfig(this->config(), subset.width(), subset.height(), 0,
926                           this->alphaType());
927             dst.setIsVolatile(this->isVolatile());
928             dst.setPixelRef(pixelRef)->unref();
929             SkDEBUGCODE(dst.validate());
930             result->swap(dst);
931             return true;
932         }
933     }
934
935     // If the upper left of the rectangle was outside the bounds of this SkBitmap, we should have
936     // exited above.
937     SkASSERT(static_cast<unsigned>(r.fLeft) < static_cast<unsigned>(this->width()));
938     SkASSERT(static_cast<unsigned>(r.fTop) < static_cast<unsigned>(this->height()));
939
940     SkBitmap dst;
941     dst.setConfig(this->config(), r.width(), r.height(), this->rowBytes(),
942                   this->alphaType());
943     dst.setIsVolatile(this->isVolatile());
944
945     if (fPixelRef) {
946         SkIPoint origin = fPixelRefOrigin;
947         origin.fX += r.fLeft;
948         origin.fY += r.fTop;
949         // share the pixelref with a custom offset
950         dst.setPixelRef(fPixelRef, origin);
951     }
952     SkDEBUGCODE(dst.validate();)
953
954     // we know we're good, so commit to result
955     result->swap(dst);
956     return true;
957 }
958
959 ///////////////////////////////////////////////////////////////////////////////
960
961 #include "SkCanvas.h"
962 #include "SkPaint.h"
963
964 bool SkBitmap::canCopyTo(Config dstConfig) const {
965     if (this->config() == kNo_Config) {
966         return false;
967     }
968
969     bool sameConfigs = (this->config() == dstConfig);
970     switch (dstConfig) {
971         case kA8_Config:
972         case kRGB_565_Config:
973         case kARGB_8888_Config:
974             break;
975         case kIndex8_Config:
976             if (!sameConfigs) {
977                 return false;
978             }
979             break;
980         case kARGB_4444_Config:
981             return sameConfigs || kARGB_8888_Config == this->config();
982         default:
983             return false;
984     }
985     return true;
986 }
987
988 bool SkBitmap::copyTo(SkBitmap* dst, Config dstConfig, Allocator* alloc) const {
989     if (!this->canCopyTo(dstConfig)) {
990         return false;
991     }
992
993     // if we have a texture, first get those pixels
994     SkBitmap tmpSrc;
995     const SkBitmap* src = this;
996
997     if (fPixelRef) {
998         SkIRect subset;
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());
1004
1005             // did we get lucky and we can just return tmpSrc?
1006             if (tmpSrc.config() == dstConfig && NULL == alloc) {
1007                 dst->swap(tmpSrc);
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);
1011                 }
1012                 return true;
1013             }
1014
1015             // fall through to the raster case
1016             src = &tmpSrc;
1017         }
1018     }
1019
1020     // we lock this now, since we may need its colortable
1021     SkAutoLockPixels srclock(*src);
1022     if (!src->readyToDraw()) {
1023         return false;
1024     }
1025
1026     // The only way to be readyToDraw is if fPixelRef is non NULL.
1027     SkASSERT(fPixelRef != NULL);
1028
1029     SkBitmap tmpDst;
1030     tmpDst.setConfig(dstConfig, src->width(), src->height(), 0,
1031                      src->alphaType());
1032
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)) {
1038         return false;
1039     }
1040
1041     if (!tmpDst.readyToDraw()) {
1042         // allocator/lock failed
1043         return false;
1044     }
1045
1046     // pixelRef must be non NULL or tmpDst.readyToDraw() would have
1047     // returned false.
1048     SkASSERT(tmpDst.pixelRef() != NULL);
1049
1050     /* do memcpy for the same configs cases, else use drawing
1051     */
1052     if (src->config() == dstConfig) {
1053         if (tmpDst.getSize() == src->getSize()) {
1054             memcpy(tmpDst.getPixels(), src->getPixels(), src->getSafeSize());
1055             SkPixelRef* pixelRef = tmpDst.pixelRef();
1056
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
1062             // the genID.
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);
1072             }
1073         } else {
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();
1082             }
1083         }
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],
1094                                                  DITHER_VALUE(x));
1095             }
1096         }
1097     } else {
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);
1101
1102         SkCanvas canvas(tmpDst);
1103         SkPaint  paint;
1104
1105         paint.setDither(true);
1106         canvas.drawBitmap(*src, 0, 0, &paint);
1107     }
1108
1109     dst->swap(tmpDst);
1110     return true;
1111 }
1112
1113 bool SkBitmap::deepCopyTo(SkBitmap* dst, Config dstConfig) const {
1114     const SkColorType dstCT = SkBitmapConfigToColorType(dstConfig);
1115
1116     if (!this->canCopyTo(dstConfig)) {
1117         return false;
1118     }
1119
1120     // If we have a PixelRef, and it supports deep copy, use it.
1121     // Currently supported only by texture-backed bitmaps.
1122     if (fPixelRef) {
1123         SkPixelRef* pixelRef = fPixelRef->deepCopy(dstConfig);
1124         if (pixelRef) {
1125             uint32_t rowBytes;
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;
1133             } else {
1134                 // With the new config, an appropriate fRowBytes will be computed by setConfig.
1135                 rowBytes = 0;
1136             }
1137
1138             SkImageInfo info = fInfo;
1139             info.fColorType = dstCT;
1140             if (!dst->setConfig(info, rowBytes)) {
1141                 return false;
1142             }
1143             dst->setPixelRef(pixelRef, fPixelRefOrigin)->unref();
1144             return true;
1145         }
1146     }
1147
1148     if (this->getTexture()) {
1149         return false;
1150     } else {
1151         return this->copyTo(dst, dstConfig, NULL);
1152     }
1153 }
1154
1155 ///////////////////////////////////////////////////////////////////////////////
1156 ///////////////////////////////////////////////////////////////////////////////
1157
1158 static void downsampleby2_proc32(SkBitmap* dst, int x, int y,
1159                                  const SkBitmap& src) {
1160     x <<= 1;
1161     y <<= 1;
1162     const SkPMColor* p = src.getAddr32(x, y);
1163     const SkPMColor* baseP = p;
1164     SkPMColor c, ag, rb;
1165
1166     c = *p; ag = (c >> 8) & 0xFF00FF; rb = c & 0xFF00FF;
1167     if (x < src.width() - 1) {
1168         p += 1;
1169     }
1170     c = *p; ag += (c >> 8) & 0xFF00FF; rb += c & 0xFF00FF;
1171
1172     p = baseP;
1173     if (y < src.height() - 1) {
1174         p += src.rowBytes() >> 2;
1175     }
1176     c = *p; ag += (c >> 8) & 0xFF00FF; rb += c & 0xFF00FF;
1177     if (x < src.width() - 1) {
1178         p += 1;
1179     }
1180     c = *p; ag += (c >> 8) & 0xFF00FF; rb += c & 0xFF00FF;
1181
1182     *dst->getAddr32(x >> 1, y >> 1) =
1183         ((rb >> 2) & 0xFF00FF) | ((ag << 6) & 0xFF00FF00);
1184 }
1185
1186 static inline uint32_t expand16(U16CPU c) {
1187     return (c & ~SK_G16_MASK_IN_PLACE) | ((c & SK_G16_MASK_IN_PLACE) << 16);
1188 }
1189
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);
1194 }
1195
1196 static void downsampleby2_proc16(SkBitmap* dst, int x, int y,
1197                                  const SkBitmap& src) {
1198     x <<= 1;
1199     y <<= 1;
1200     const uint16_t* p = src.getAddr16(x, y);
1201     const uint16_t* baseP = p;
1202     SkPMColor       c;
1203
1204     c = expand16(*p);
1205     if (x < src.width() - 1) {
1206         p += 1;
1207     }
1208     c += expand16(*p);
1209
1210     p = baseP;
1211     if (y < src.height() - 1) {
1212         p += src.rowBytes() >> 1;
1213     }
1214     c += expand16(*p);
1215     if (x < src.width() - 1) {
1216         p += 1;
1217     }
1218     c += expand16(*p);
1219
1220     *dst->getAddr16(x >> 1, y >> 1) = (uint16_t)pack16(c >> 2);
1221 }
1222
1223 static uint32_t expand4444(U16CPU c) {
1224     return (c & 0xF0F) | ((c & ~0xF0F) << 12);
1225 }
1226
1227 static U16CPU collaps4444(uint32_t c) {
1228     return (c & 0xF0F) | ((c >> 12) & ~0xF0F);
1229 }
1230
1231 static void downsampleby2_proc4444(SkBitmap* dst, int x, int y,
1232                                    const SkBitmap& src) {
1233     x <<= 1;
1234     y <<= 1;
1235     const uint16_t* p = src.getAddr16(x, y);
1236     const uint16_t* baseP = p;
1237     uint32_t        c;
1238
1239     c = expand4444(*p);
1240     if (x < src.width() - 1) {
1241         p += 1;
1242     }
1243     c += expand4444(*p);
1244
1245     p = baseP;
1246     if (y < src.height() - 1) {
1247         p += src.rowBytes() >> 1;
1248     }
1249     c += expand4444(*p);
1250     if (x < src.width() - 1) {
1251         p += 1;
1252     }
1253     c += expand4444(*p);
1254
1255     *dst->getAddr16(x >> 1, y >> 1) = (uint16_t)collaps4444(c >> 2);
1256 }
1257
1258 void SkBitmap::buildMipMap(bool forceRebuild) {
1259     if (forceRebuild)
1260         this->freeMipMap();
1261     else if (fMipMap)
1262         return; // we're already built
1263
1264     SkASSERT(NULL == fMipMap);
1265
1266     void (*proc)(SkBitmap* dst, int x, int y, const SkBitmap& src);
1267
1268     const SkBitmap::Config config = this->config();
1269
1270     switch (config) {
1271         case kARGB_8888_Config:
1272             proc = downsampleby2_proc32;
1273             break;
1274         case kRGB_565_Config:
1275             proc = downsampleby2_proc16;
1276             break;
1277         case kARGB_4444_Config:
1278             proc = downsampleby2_proc4444;
1279             break;
1280         case kIndex8_Config:
1281         case kA8_Config:
1282         default:
1283             return; // don't build mipmaps for these configs
1284     }
1285
1286     SkAutoLockPixels alp(*this);
1287     if (!this->readyToDraw()) {
1288         return;
1289     }
1290
1291     // whip through our loop to compute the exact size needed
1292     size_t  size = 0;
1293     int     maxLevels = 0;
1294     {
1295         int width = this->width();
1296         int height = this->height();
1297         for (;;) {
1298             width >>= 1;
1299             height >>= 1;
1300             if (0 == width || 0 == height) {
1301                 break;
1302             }
1303             size += ComputeRowBytes(config, width) * height;
1304             maxLevels += 1;
1305         }
1306     }
1307
1308     // nothing to build
1309     if (0 == maxLevels) {
1310         return;
1311     }
1312
1313     SkBitmap srcBM(*this);
1314     srcBM.lockPixels();
1315     if (!srcBM.readyToDraw()) {
1316         return;
1317     }
1318
1319     MipMap* mm = MipMap::Alloc(maxLevels, size);
1320     if (NULL == mm) {
1321         return;
1322     }
1323
1324     MipLevel*   level = mm->levels();
1325     uint8_t*    addr = (uint8_t*)mm->pixels();
1326     int         width = this->width();
1327     int         height = this->height();
1328     uint32_t    rowBytes;
1329     SkBitmap    dstBM;
1330
1331     for (int i = 0; i < maxLevels; i++) {
1332         width >>= 1;
1333         height >>= 1;
1334         rowBytes = SkToU32(ComputeRowBytes(config, width));
1335
1336         level[i].fPixels   = addr;
1337         level[i].fWidth    = width;
1338         level[i].fHeight   = height;
1339         level[i].fRowBytes = rowBytes;
1340
1341         dstBM.setConfig(config, width, height, rowBytes);
1342         dstBM.setPixels(addr);
1343
1344         srcBM.lockPixels();
1345         for (int y = 0; y < height; y++) {
1346             for (int x = 0; x < width; x++) {
1347                 proc(&dstBM, x, y, srcBM);
1348             }
1349         }
1350         srcBM.unlockPixels();
1351
1352         srcBM = dstBM;
1353         addr += height * rowBytes;
1354     }
1355     SkASSERT(addr == (uint8_t*)mm->pixels() + size);
1356     fMipMap = mm;
1357 }
1358
1359 bool SkBitmap::hasMipMap() const {
1360     return fMipMap != NULL;
1361 }
1362
1363 int SkBitmap::extractMipLevel(SkBitmap* dst, SkFixed sx, SkFixed sy) {
1364     if (NULL == fMipMap) {
1365         return 0;
1366     }
1367
1368     int level = ComputeMipLevel(sx, sy) >> 16;
1369     SkASSERT(level >= 0);
1370     if (level <= 0) {
1371         return 0;
1372     }
1373
1374     if (level >= fMipMap->fLevelCount) {
1375         level = fMipMap->fLevelCount - 1;
1376     }
1377     if (dst) {
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);
1382     }
1383     return level;
1384 }
1385
1386 SkFixed SkBitmap::ComputeMipLevel(SkFixed sx, SkFixed sy) {
1387     sx = SkAbs32(sx);
1388     sy = SkAbs32(sy);
1389     if (sx < sy) {
1390         sx = sy;
1391     }
1392     if (sx < SK_Fixed1) {
1393         return 0;
1394     }
1395     int clz = SkCLZ(sx);
1396     SkASSERT(clz >= 1 && clz <= 15);
1397     return SkIntToFixed(15 - clz) + ((unsigned)(sx << (clz + 1)) >> 16);
1398 }
1399
1400 ///////////////////////////////////////////////////////////////////////////////
1401
1402 static bool GetBitmapAlpha(const SkBitmap& src, uint8_t* SK_RESTRICT alpha,
1403                            int alphaRowBytes) {
1404     SkASSERT(alpha != NULL);
1405     SkASSERT(alphaRowBytes >= src.width());
1406
1407     SkBitmap::Config config = src.config();
1408     int              w = src.width();
1409     int              h = src.height();
1410     size_t           rb = src.rowBytes();
1411
1412     SkAutoLockPixels alp(src);
1413     if (!src.readyToDraw()) {
1414         // zero out the alpha buffer and return
1415         while (--h >= 0) {
1416             memset(alpha, 0, w);
1417             alpha += alphaRowBytes;
1418         }
1419         return false;
1420     }
1421
1422     if (SkBitmap::kA8_Config == config && !src.isOpaque()) {
1423         const uint8_t* s = src.getAddr8(0, 0);
1424         while (--h >= 0) {
1425             memcpy(alpha, s, w);
1426             s += rb;
1427             alpha += alphaRowBytes;
1428         }
1429     } else if (SkBitmap::kARGB_8888_Config == config && !src.isOpaque()) {
1430         const SkPMColor* SK_RESTRICT s = src.getAddr32(0, 0);
1431         while (--h >= 0) {
1432             for (int x = 0; x < w; x++) {
1433                 alpha[x] = SkGetPackedA32(s[x]);
1434             }
1435             s = (const SkPMColor*)((const char*)s + rb);
1436             alpha += alphaRowBytes;
1437         }
1438     } else if (SkBitmap::kARGB_4444_Config == config && !src.isOpaque()) {
1439         const SkPMColor16* SK_RESTRICT s = src.getAddr16(0, 0);
1440         while (--h >= 0) {
1441             for (int x = 0; x < w; x++) {
1442                 alpha[x] = SkPacked4444ToA32(s[x]);
1443             }
1444             s = (const SkPMColor16*)((const char*)s + rb);
1445             alpha += alphaRowBytes;
1446         }
1447     } else if (SkBitmap::kIndex8_Config == config && !src.isOpaque()) {
1448         SkColorTable* ct = src.getColorTable();
1449         if (ct) {
1450             const SkPMColor* SK_RESTRICT table = ct->lockColors();
1451             const uint8_t* SK_RESTRICT s = src.getAddr8(0, 0);
1452             while (--h >= 0) {
1453                 for (int x = 0; x < w; x++) {
1454                     alpha[x] = SkGetPackedA32(table[s[x]]);
1455                 }
1456                 s += rb;
1457                 alpha += alphaRowBytes;
1458             }
1459             ct->unlockColors();
1460         }
1461     } else {    // src is opaque, so just fill alpha[] with 0xFF
1462         memset(alpha, 0xFF, h * alphaRowBytes);
1463     }
1464     return true;
1465 }
1466
1467 #include "SkPaint.h"
1468 #include "SkMaskFilter.h"
1469 #include "SkMatrix.h"
1470
1471 bool SkBitmap::extractAlpha(SkBitmap* dst, const SkPaint* paint,
1472                             Allocator *allocator, SkIPoint* offset) const {
1473     SkDEBUGCODE(this->validate();)
1474
1475     SkBitmap    tmpBitmap;
1476     SkMatrix    identity;
1477     SkMask      srcM, dstM;
1478
1479     srcM.fBounds.set(0, 0, this->width(), this->height());
1480     srcM.fRowBytes = SkAlign4(this->width());
1481     srcM.fFormat = SkMask::kA8_Format;
1482
1483     SkMaskFilter* filter = paint ? paint->getMaskFilter() : NULL;
1484
1485     // compute our (larger?) dst bounds if we have a filter
1486     if (NULL != filter) {
1487         identity.reset();
1488         srcM.fImage = NULL;
1489         if (!filter->filterMask(&dstM, srcM, identity, NULL)) {
1490             goto NO_FILTER_CASE;
1491         }
1492         dstM.fRowBytes = SkAlign4(dstM.fBounds.width());
1493     } else {
1494     NO_FILTER_CASE:
1495         tmpBitmap.setConfig(SkBitmap::kA8_Config, this->width(), this->height(),
1496                        srcM.fRowBytes);
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());
1501             return false;
1502         }
1503         GetBitmapAlpha(*this, tmpBitmap.getAddr8(0, 0), srcM.fRowBytes);
1504         if (offset) {
1505             offset->set(0, 0);
1506         }
1507         tmpBitmap.swap(*dst);
1508         return true;
1509     }
1510     srcM.fImage = SkMask::AllocImage(srcM.computeImageSize());
1511     SkAutoMaskFreeImage srcCleanup(srcM.fImage);
1512
1513     GetBitmapAlpha(*this, srcM.fImage, srcM.fRowBytes);
1514     if (!filter->filterMask(&dstM, srcM, identity, NULL)) {
1515         goto NO_FILTER_CASE;
1516     }
1517     SkAutoMaskFreeImage dstCleanup(dstM.fImage);
1518
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());
1525         return false;
1526     }
1527     memcpy(tmpBitmap.getPixels(), dstM.fImage, dstM.computeImageSize());
1528     if (offset) {
1529         offset->set(dstM.fBounds.fLeft, dstM.fBounds.fTop);
1530     }
1531     SkDEBUGCODE(tmpBitmap.validate();)
1532
1533     tmpBitmap.swap(*dst);
1534     return true;
1535 }
1536
1537 ///////////////////////////////////////////////////////////////////////////////
1538
1539 enum {
1540     SERIALIZE_PIXELTYPE_NONE,
1541     SERIALIZE_PIXELTYPE_REF_DATA
1542 };
1543
1544 void SkBitmap::flatten(SkWriteBuffer& buffer) const {
1545     fInfo.flatten(buffer);
1546     buffer.writeInt(fRowBytes);
1547
1548     if (fPixelRef) {
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);
1554             return;
1555         }
1556         // if we get here, we can't record the pixels
1557         buffer.writeInt(SERIALIZE_PIXELTYPE_NONE);
1558     } else {
1559         buffer.writeInt(SERIALIZE_PIXELTYPE_NONE);
1560     }
1561 }
1562
1563 void SkBitmap::unflatten(SkReadBuffer& buffer) {
1564     this->reset();
1565
1566     SkImageInfo info;
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))) {
1574         return;
1575     }
1576
1577     bool configIsValid = this->setConfig(info, rowBytes);
1578     buffer.validate(configIsValid);
1579
1580     int reftype = buffer.readInt();
1581     if (buffer.validate((SERIALIZE_PIXELTYPE_REF_DATA == reftype) ||
1582                         (SERIALIZE_PIXELTYPE_NONE == reftype))) {
1583         switch (reftype) {
1584             case SERIALIZE_PIXELTYPE_REF_DATA: {
1585                 SkIPoint origin;
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())))) {
1592                     origin.setZero();
1593                 }
1594                 SkSafeUnref(this->setPixelRef(pr, origin));
1595                 break;
1596             }
1597             case SERIALIZE_PIXELTYPE_NONE:
1598                 break;
1599             default:
1600                 SkDEBUGFAIL("unrecognized pixeltype in serialized data");
1601                 sk_throw();
1602         }
1603     }
1604 }
1605
1606 ///////////////////////////////////////////////////////////////////////////////
1607
1608 SkBitmap::RLEPixels::RLEPixels(int width, int height) {
1609     fHeight = height;
1610     fYPtrs = (uint8_t**)sk_calloc_throw(height * sizeof(uint8_t*));
1611 }
1612
1613 SkBitmap::RLEPixels::~RLEPixels() {
1614     sk_free(fYPtrs);
1615 }
1616
1617 ///////////////////////////////////////////////////////////////////////////////
1618
1619 #ifdef SK_DEBUG
1620 void SkBitmap::validate() const {
1621     fInfo.validate();
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;
1626 #endif
1627     SkASSERT(fFlags <= allFlags);
1628     SkASSERT(fPixelLockCount >= 0);
1629
1630     if (fPixels) {
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());
1640     } else {
1641         SkASSERT(NULL == fColorTable);
1642     }
1643 }
1644 #endif
1645
1646 #ifdef SK_DEVELOPER
1647 void SkBitmap::toString(SkString* str) const {
1648
1649     static const char* gConfigNames[kConfigCount] = {
1650         "NONE", "A8", "INDEX8", "565", "4444", "8888"
1651     };
1652
1653     str->appendf("bitmap: ((%d, %d) %s", this->width(), this->height(),
1654                  gConfigNames[this->config()]);
1655
1656     str->append(" (");
1657     if (this->isOpaque()) {
1658         str->append("opaque");
1659     } else {
1660         str->append("transparent");
1661     }
1662     if (this->isImmutable()) {
1663         str->append(", immutable");
1664     } else {
1665         str->append(", not-immutable");
1666     }
1667     str->append(")");
1668
1669     SkPixelRef* pr = this->pixelRef();
1670     if (NULL == pr) {
1671         // show null or the explicit pixel address (rare)
1672         str->appendf(" pixels:%p", this->getPixels());
1673     } else {
1674         const char* uri = pr->getURI();
1675         if (NULL != uri) {
1676             str->appendf(" uri:\"%s\"", uri);
1677         } else {
1678             str->appendf(" pixelref:%p", pr);
1679         }
1680     }
1681
1682     str->append(")");
1683 }
1684 #endif
1685
1686 ///////////////////////////////////////////////////////////////////////////////
1687
1688 #ifdef SK_DEBUG
1689 void SkImageInfo::validate() const {
1690     SkASSERT(fWidth >= 0);
1691     SkASSERT(fHeight >= 0);
1692     SkASSERT(SkColorTypeIsValid(fColorType));
1693     SkASSERT(SkAlphaTypeIsValid(fAlphaType));
1694 }
1695 #endif