SkBitmap.cpp revision 8ae991e433d2c0814ea5579613f00173805ff057
1/*
2 * Copyright 2008 The Android Open Source Project
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8#include "SkAtomics.h"
9#include "SkBitmap.h"
10#include "SkColorPriv.h"
11#include "SkData.h"
12#include "SkFilterQuality.h"
13#include "SkMallocPixelRef.h"
14#include "SkMask.h"
15#include "SkMath.h"
16#include "SkPixelRef.h"
17#include "SkReadBuffer.h"
18#include "SkRect.h"
19#include "SkScalar.h"
20#include "SkTemplates.h"
21#include "SkUnPreMultiply.h"
22#include "SkWriteBuffer.h"
23
24#include <string.h>
25
26static bool reset_return_false(SkBitmap* bm) {
27    bm->reset();
28    return false;
29}
30
31SkBitmap::SkBitmap() {
32    sk_bzero(this, sizeof(*this));
33}
34
35SkBitmap::SkBitmap(const SkBitmap& src) {
36    SkDEBUGCODE(src.validate();)
37    sk_bzero(this, sizeof(*this));
38    *this = src;
39    SkDEBUGCODE(this->validate();)
40}
41
42SkBitmap::SkBitmap(SkBitmap&& other) : SkBitmap() { this->swap(other); }
43
44SkBitmap::~SkBitmap() {
45    SkDEBUGCODE(this->validate();)
46    this->freePixels();
47}
48
49SkBitmap& SkBitmap::operator=(const SkBitmap& src) {
50    if (this != &src) {
51        this->freePixels();
52        this->fPixelRef = SkSafeRef(src.fPixelRef);
53        if (this->fPixelRef) {
54            // ignore the values if we have a pixelRef
55            this->fPixels = nullptr;
56            this->fColorTable = nullptr;
57        } else {
58            this->fPixels = src.fPixels;
59            this->fColorTable = src.fColorTable;
60        }
61        // we reset our locks if we get blown away
62        this->fPixelLockCount = 0;
63
64        this->fPixelRefOrigin = src.fPixelRefOrigin;
65        this->fInfo = src.fInfo;
66        this->fRowBytes = src.fRowBytes;
67        this->fFlags = src.fFlags;
68    }
69
70    SkDEBUGCODE(this->validate();)
71    return *this;
72}
73
74SkBitmap& SkBitmap::operator=(SkBitmap&& other) {
75    if (this != &other) {
76        this->swap(other);
77        other.reset();
78    }
79    return *this;
80}
81
82void SkBitmap::swap(SkBitmap& other) {
83    SkTSwap(fColorTable, other.fColorTable);
84    SkTSwap(fPixelRef, other.fPixelRef);
85    SkTSwap(fPixelRefOrigin, other.fPixelRefOrigin);
86    SkTSwap(fPixelLockCount, other.fPixelLockCount);
87    SkTSwap(fPixels, other.fPixels);
88    SkTSwap(fInfo, other.fInfo);
89    SkTSwap(fRowBytes, other.fRowBytes);
90    SkTSwap(fFlags, other.fFlags);
91
92    SkDEBUGCODE(this->validate();)
93}
94
95void SkBitmap::reset() {
96    this->freePixels();
97    this->fInfo.reset();
98    sk_bzero(this, sizeof(*this));
99}
100
101void SkBitmap::getBounds(SkRect* bounds) const {
102    SkASSERT(bounds);
103    bounds->set(0, 0,
104                SkIntToScalar(fInfo.width()), SkIntToScalar(fInfo.height()));
105}
106
107void SkBitmap::getBounds(SkIRect* bounds) const {
108    SkASSERT(bounds);
109    bounds->set(0, 0, fInfo.width(), fInfo.height());
110}
111
112///////////////////////////////////////////////////////////////////////////////
113
114bool SkBitmap::setInfo(const SkImageInfo& info, size_t rowBytes) {
115    SkAlphaType newAT = info.alphaType();
116    if (!SkColorTypeValidateAlphaType(info.colorType(), info.alphaType(), &newAT)) {
117        return reset_return_false(this);
118    }
119    // don't look at info.alphaType(), since newAT is the real value...
120
121    // require that rowBytes fit in 31bits
122    int64_t mrb = info.minRowBytes64();
123    if ((int32_t)mrb != mrb) {
124        return reset_return_false(this);
125    }
126    if ((int64_t)rowBytes != (int32_t)rowBytes) {
127        return reset_return_false(this);
128    }
129
130    if (info.width() < 0 || info.height() < 0) {
131        return reset_return_false(this);
132    }
133
134    if (kUnknown_SkColorType == info.colorType()) {
135        rowBytes = 0;
136    } else if (0 == rowBytes) {
137        rowBytes = (size_t)mrb;
138    } else if (!info.validRowBytes(rowBytes)) {
139        return reset_return_false(this);
140    }
141
142    this->freePixels();
143
144    fInfo = info.makeAlphaType(newAT);
145    fRowBytes = SkToU32(rowBytes);
146    return true;
147}
148
149bool SkBitmap::setAlphaType(SkAlphaType newAlphaType) {
150    if (!SkColorTypeValidateAlphaType(fInfo.colorType(), newAlphaType, &newAlphaType)) {
151        return false;
152    }
153    if (fInfo.alphaType() != newAlphaType) {
154        fInfo = fInfo.makeAlphaType(newAlphaType);
155        if (fPixelRef) {
156            fPixelRef->changeAlphaType(newAlphaType);
157        }
158    }
159    return true;
160}
161
162void SkBitmap::updatePixelsFromRef() const {
163    if (fPixelRef) {
164        if (fPixelLockCount > 0) {
165            SkASSERT(fPixelRef->isLocked());
166
167            void* p = fPixelRef->pixels();
168            if (p) {
169                p = (char*)p
170                    + fPixelRefOrigin.fY * fRowBytes
171                    + fPixelRefOrigin.fX * fInfo.bytesPerPixel();
172            }
173            fPixels = p;
174            fColorTable = fPixelRef->colorTable();
175        } else {
176            SkASSERT(0 == fPixelLockCount);
177            fPixels = nullptr;
178            fColorTable = nullptr;
179        }
180    }
181}
182
183SkPixelRef* SkBitmap::setPixelRef(SkPixelRef* pr, int dx, int dy) {
184#ifdef SK_DEBUG
185    if (pr) {
186        if (kUnknown_SkColorType != fInfo.colorType()) {
187            const SkImageInfo& prInfo = pr->info();
188            SkASSERT(fInfo.width() <= prInfo.width());
189            SkASSERT(fInfo.height() <= prInfo.height());
190            SkASSERT(fInfo.colorType() == prInfo.colorType());
191            switch (prInfo.alphaType()) {
192                case kUnknown_SkAlphaType:
193                    SkASSERT(fInfo.alphaType() == kUnknown_SkAlphaType);
194                    break;
195                case kOpaque_SkAlphaType:
196                case kPremul_SkAlphaType:
197                    SkASSERT(fInfo.alphaType() == kOpaque_SkAlphaType ||
198                             fInfo.alphaType() == kPremul_SkAlphaType);
199                    break;
200                case kUnpremul_SkAlphaType:
201                    SkASSERT(fInfo.alphaType() == kOpaque_SkAlphaType ||
202                             fInfo.alphaType() == kUnpremul_SkAlphaType);
203                    break;
204            }
205        }
206    }
207#endif
208
209    if (pr) {
210        const SkImageInfo& info = pr->info();
211        fPixelRefOrigin.set(SkTPin(dx, 0, info.width()), SkTPin(dy, 0, info.height()));
212    } else {
213        // ignore dx,dy if there is no pixelref
214        fPixelRefOrigin.setZero();
215    }
216
217    if (fPixelRef != pr) {
218        this->freePixels();
219        SkASSERT(nullptr == fPixelRef);
220
221        SkSafeRef(pr);
222        fPixelRef = pr;
223        this->updatePixelsFromRef();
224    }
225
226    SkDEBUGCODE(this->validate();)
227    return pr;
228}
229
230void SkBitmap::lockPixels() const {
231    if (fPixelRef && 0 == sk_atomic_inc(&fPixelLockCount)) {
232        fPixelRef->lockPixels();
233        this->updatePixelsFromRef();
234    }
235    SkDEBUGCODE(this->validate();)
236}
237
238void SkBitmap::unlockPixels() const {
239    SkASSERT(nullptr == fPixelRef || fPixelLockCount > 0);
240
241    if (fPixelRef && 1 == sk_atomic_dec(&fPixelLockCount)) {
242        fPixelRef->unlockPixels();
243        this->updatePixelsFromRef();
244    }
245    SkDEBUGCODE(this->validate();)
246}
247
248bool SkBitmap::lockPixelsAreWritable() const {
249    return (fPixelRef) ? fPixelRef->lockPixelsAreWritable() : false;
250}
251
252void SkBitmap::setPixels(void* p, SkColorTable* ctable) {
253    if (nullptr == p) {
254        this->setPixelRef(nullptr);
255        return;
256    }
257
258    if (kUnknown_SkColorType == fInfo.colorType()) {
259        this->setPixelRef(nullptr);
260        return;
261    }
262
263    SkPixelRef* pr = SkMallocPixelRef::NewDirect(fInfo, p, fRowBytes, ctable);
264    if (nullptr == pr) {
265        this->setPixelRef(nullptr);
266        return;
267    }
268
269    this->setPixelRef(pr)->unref();
270
271    // since we're already allocated, we lockPixels right away
272    this->lockPixels();
273    SkDEBUGCODE(this->validate();)
274}
275
276bool SkBitmap::tryAllocPixels(Allocator* allocator, SkColorTable* ctable) {
277    HeapAllocator stdalloc;
278
279    if (nullptr == allocator) {
280        allocator = &stdalloc;
281    }
282    return allocator->allocPixelRef(this, ctable);
283}
284
285///////////////////////////////////////////////////////////////////////////////
286
287bool SkBitmap::tryAllocPixels(const SkImageInfo& requestedInfo, size_t rowBytes) {
288    if (kIndex_8_SkColorType == requestedInfo.colorType()) {
289        return reset_return_false(this);
290    }
291    if (!this->setInfo(requestedInfo, rowBytes)) {
292        return reset_return_false(this);
293    }
294
295    // setInfo may have corrected info (e.g. 565 is always opaque).
296    const SkImageInfo& correctedInfo = this->info();
297    // setInfo may have computed a valid rowbytes if 0 were passed in
298    rowBytes = this->rowBytes();
299
300    SkMallocPixelRef::PRFactory defaultFactory;
301
302    SkPixelRef* pr = defaultFactory.create(correctedInfo, rowBytes, nullptr);
303    if (nullptr == pr) {
304        return reset_return_false(this);
305    }
306    this->setPixelRef(pr)->unref();
307
308    // TODO: lockPixels could/should return bool or void*/nullptr
309    this->lockPixels();
310    if (nullptr == this->getPixels()) {
311        return reset_return_false(this);
312    }
313    return true;
314}
315
316bool SkBitmap::tryAllocPixels(const SkImageInfo& requestedInfo, SkPixelRefFactory* factory,
317                                SkColorTable* ctable) {
318    if (kIndex_8_SkColorType == requestedInfo.colorType() && nullptr == ctable) {
319        return reset_return_false(this);
320    }
321    if (!this->setInfo(requestedInfo)) {
322        return reset_return_false(this);
323    }
324
325    // setInfo may have corrected info (e.g. 565 is always opaque).
326    const SkImageInfo& correctedInfo = this->info();
327
328    SkMallocPixelRef::PRFactory defaultFactory;
329    if (nullptr == factory) {
330        factory = &defaultFactory;
331    }
332
333    SkPixelRef* pr = factory->create(correctedInfo, correctedInfo.minRowBytes(), ctable);
334    if (nullptr == pr) {
335        return reset_return_false(this);
336    }
337    this->setPixelRef(pr)->unref();
338
339    // TODO: lockPixels could/should return bool or void*/nullptr
340    this->lockPixels();
341    if (nullptr == this->getPixels()) {
342        return reset_return_false(this);
343    }
344    return true;
345}
346
347static void invoke_release_proc(void (*proc)(void* pixels, void* ctx), void* pixels, void* ctx) {
348    if (proc) {
349        proc(pixels, ctx);
350    }
351}
352
353bool SkBitmap::installPixels(const SkImageInfo& requestedInfo, void* pixels, size_t rb,
354                             SkColorTable* ct, void (*releaseProc)(void* addr, void* context),
355                             void* context) {
356    if (!this->setInfo(requestedInfo, rb)) {
357        invoke_release_proc(releaseProc, pixels, context);
358        this->reset();
359        return false;
360    }
361    if (nullptr == pixels) {
362        invoke_release_proc(releaseProc, pixels, context);
363        return true;    // we behaved as if they called setInfo()
364    }
365
366    // setInfo may have corrected info (e.g. 565 is always opaque).
367    const SkImageInfo& correctedInfo = this->info();
368
369    SkPixelRef* pr = SkMallocPixelRef::NewWithProc(correctedInfo, rb, ct, pixels, releaseProc,
370                                                   context);
371    if (!pr) {
372        this->reset();
373        return false;
374    }
375
376    this->setPixelRef(pr)->unref();
377
378    // since we're already allocated, we lockPixels right away
379    this->lockPixels();
380    SkDEBUGCODE(this->validate();)
381    return true;
382}
383
384bool SkBitmap::installPixels(const SkPixmap& pixmap) {
385    return this->installPixels(pixmap.info(), pixmap.writable_addr(),
386                               pixmap.rowBytes(), pixmap.ctable(),
387                               nullptr, nullptr);
388}
389
390bool SkBitmap::installMaskPixels(const SkMask& mask) {
391    if (SkMask::kA8_Format != mask.fFormat) {
392        this->reset();
393        return false;
394    }
395    return this->installPixels(SkImageInfo::MakeA8(mask.fBounds.width(),
396                                                   mask.fBounds.height()),
397                               mask.fImage, mask.fRowBytes);
398}
399
400///////////////////////////////////////////////////////////////////////////////
401
402void SkBitmap::freePixels() {
403    if (fPixelRef) {
404        if (fPixelLockCount > 0) {
405            fPixelRef->unlockPixels();
406        }
407        fPixelRef->unref();
408        fPixelRef = nullptr;
409        fPixelRefOrigin.setZero();
410    }
411    fPixelLockCount = 0;
412    fPixels = nullptr;
413    fColorTable = nullptr;
414}
415
416uint32_t SkBitmap::getGenerationID() const {
417    return (fPixelRef) ? fPixelRef->getGenerationID() : 0;
418}
419
420void SkBitmap::notifyPixelsChanged() const {
421    SkASSERT(!this->isImmutable());
422    if (fPixelRef) {
423        fPixelRef->notifyPixelsChanged();
424    }
425}
426
427///////////////////////////////////////////////////////////////////////////////
428
429/** We explicitly use the same allocator for our pixels that SkMask does,
430 so that we can freely assign memory allocated by one class to the other.
431 */
432bool SkBitmap::HeapAllocator::allocPixelRef(SkBitmap* dst,
433                                            SkColorTable* ctable) {
434    const SkImageInfo info = dst->info();
435    if (kUnknown_SkColorType == info.colorType()) {
436//        SkDebugf("unsupported config for info %d\n", dst->config());
437        return false;
438    }
439
440    SkPixelRef* pr = SkMallocPixelRef::NewAllocate(info, dst->rowBytes(), ctable);
441    if (nullptr == pr) {
442        return false;
443    }
444
445    dst->setPixelRef(pr)->unref();
446    // since we're already allocated, we lockPixels right away
447    dst->lockPixels();
448    return true;
449}
450
451///////////////////////////////////////////////////////////////////////////////
452
453static bool copy_pixels_to(const SkPixmap& src, void* const dst, size_t dstSize,
454                           size_t dstRowBytes, bool preserveDstPad) {
455    const SkImageInfo& info = src.info();
456
457    if (0 == dstRowBytes) {
458        dstRowBytes = src.rowBytes();
459    }
460    if (dstRowBytes < info.minRowBytes()) {
461        return false;
462    }
463
464    if (!preserveDstPad && static_cast<uint32_t>(dstRowBytes) == src.rowBytes()) {
465        size_t safeSize = src.getSafeSize();
466        if (safeSize > dstSize || safeSize == 0)
467            return false;
468        else {
469            // This implementation will write bytes beyond the end of each row,
470            // excluding the last row, if the bitmap's stride is greater than
471            // strictly required by the current config.
472            memcpy(dst, src.addr(), safeSize);
473            return true;
474        }
475    } else {
476        // If destination has different stride than us, then copy line by line.
477        if (info.getSafeSize(dstRowBytes) > dstSize) {
478            return false;
479        } else {
480            // Just copy what we need on each line.
481            size_t rowBytes = info.minRowBytes();
482            const uint8_t* srcP = reinterpret_cast<const uint8_t*>(src.addr());
483            uint8_t* dstP = reinterpret_cast<uint8_t*>(dst);
484            for (int row = 0; row < info.height(); ++row) {
485                memcpy(dstP, srcP, rowBytes);
486                srcP += src.rowBytes();
487                dstP += dstRowBytes;
488            }
489
490            return true;
491        }
492    }
493}
494
495bool SkBitmap::copyPixelsTo(void* dst, size_t dstSize, size_t dstRB, bool preserveDstPad) const {
496    if (nullptr == dst) {
497        return false;
498    }
499    SkAutoPixmapUnlock result;
500    if (!this->requestLock(&result)) {
501        return false;
502    }
503    return copy_pixels_to(result.pixmap(), dst, dstSize, dstRB, preserveDstPad);
504}
505
506///////////////////////////////////////////////////////////////////////////////
507
508bool SkBitmap::isImmutable() const {
509    return fPixelRef ? fPixelRef->isImmutable() : false;
510}
511
512void SkBitmap::setImmutable() {
513    if (fPixelRef) {
514        fPixelRef->setImmutable();
515    }
516}
517
518bool SkBitmap::isVolatile() const {
519    return (fFlags & kImageIsVolatile_Flag) != 0;
520}
521
522void SkBitmap::setIsVolatile(bool isVolatile) {
523    if (isVolatile) {
524        fFlags |= kImageIsVolatile_Flag;
525    } else {
526        fFlags &= ~kImageIsVolatile_Flag;
527    }
528}
529
530void* SkBitmap::getAddr(int x, int y) const {
531    SkASSERT((unsigned)x < (unsigned)this->width());
532    SkASSERT((unsigned)y < (unsigned)this->height());
533
534    char* base = (char*)this->getPixels();
535    if (base) {
536        base += y * this->rowBytes();
537        switch (this->colorType()) {
538            case kRGBA_F16_SkColorType:
539                base += x << 3;
540                break;
541            case kRGBA_8888_SkColorType:
542            case kBGRA_8888_SkColorType:
543                base += x << 2;
544                break;
545            case kARGB_4444_SkColorType:
546            case kRGB_565_SkColorType:
547                base += x << 1;
548                break;
549            case kAlpha_8_SkColorType:
550            case kIndex_8_SkColorType:
551            case kGray_8_SkColorType:
552                base += x;
553                break;
554            default:
555                SkDEBUGFAIL("Can't return addr for config");
556                base = nullptr;
557                break;
558        }
559    }
560    return base;
561}
562
563#include "SkHalf.h"
564
565SkColor SkBitmap::getColor(int x, int y) const {
566    SkASSERT((unsigned)x < (unsigned)this->width());
567    SkASSERT((unsigned)y < (unsigned)this->height());
568
569    switch (this->colorType()) {
570        case kGray_8_SkColorType: {
571            uint8_t* addr = this->getAddr8(x, y);
572            return SkColorSetRGB(*addr, *addr, *addr);
573        }
574        case kAlpha_8_SkColorType: {
575            uint8_t* addr = this->getAddr8(x, y);
576            return SkColorSetA(0, addr[0]);
577        }
578        case kIndex_8_SkColorType: {
579            SkPMColor c = this->getIndex8Color(x, y);
580            return SkUnPreMultiply::PMColorToColor(c);
581        }
582        case kRGB_565_SkColorType: {
583            uint16_t* addr = this->getAddr16(x, y);
584            return SkPixel16ToColor(addr[0]);
585        }
586        case kARGB_4444_SkColorType: {
587            uint16_t* addr = this->getAddr16(x, y);
588            SkPMColor c = SkPixel4444ToPixel32(addr[0]);
589            return SkUnPreMultiply::PMColorToColor(c);
590        }
591        case kBGRA_8888_SkColorType: {
592            uint32_t* addr = this->getAddr32(x, y);
593            SkPMColor c = SkSwizzle_BGRA_to_PMColor(addr[0]);
594            return SkUnPreMultiply::PMColorToColor(c);
595        }
596        case kRGBA_8888_SkColorType: {
597            uint32_t* addr = this->getAddr32(x, y);
598            SkPMColor c = SkSwizzle_RGBA_to_PMColor(addr[0]);
599            return SkUnPreMultiply::PMColorToColor(c);
600        }
601        case kRGBA_F16_SkColorType: {
602            const uint64_t* addr = (const uint64_t*)fPixels + y * (fRowBytes >> 3) + x;
603            Sk4f p4 = SkHalfToFloat_finite_ftz(addr[0]);
604            if (p4[3]) {
605                float inva = 1 / p4[3];
606                p4 = p4 * Sk4f(inva, inva, inva, 1);
607            }
608            SkColor c;
609            SkNx_cast<uint8_t>(p4 * Sk4f(255) + Sk4f(0.5f)).store(&c);
610            // p4 is RGBA, but we want BGRA, so we need to swap next
611            return SkSwizzle_RB(c);
612        }
613        default:
614            SkASSERT(false);
615            return 0;
616    }
617    SkASSERT(false);  // Not reached.
618    return 0;
619}
620
621static bool compute_is_opaque(const SkPixmap& pmap) {
622    const int height = pmap.height();
623    const int width = pmap.width();
624
625    switch (pmap.colorType()) {
626        case kAlpha_8_SkColorType: {
627            unsigned a = 0xFF;
628            for (int y = 0; y < height; ++y) {
629                const uint8_t* row = pmap.addr8(0, y);
630                for (int x = 0; x < width; ++x) {
631                    a &= row[x];
632                }
633                if (0xFF != a) {
634                    return false;
635                }
636            }
637            return true;
638        } break;
639        case kIndex_8_SkColorType: {
640            const SkColorTable* ctable = pmap.ctable();
641            if (nullptr == ctable) {
642                return false;
643            }
644            const SkPMColor* table = ctable->readColors();
645            SkPMColor c = (SkPMColor)~0;
646            for (int i = ctable->count() - 1; i >= 0; --i) {
647                c &= table[i];
648            }
649            return 0xFF == SkGetPackedA32(c);
650        } break;
651        case kRGB_565_SkColorType:
652        case kGray_8_SkColorType:
653            return true;
654            break;
655        case kARGB_4444_SkColorType: {
656            unsigned c = 0xFFFF;
657            for (int y = 0; y < height; ++y) {
658                const SkPMColor16* row = pmap.addr16(0, y);
659                for (int x = 0; x < width; ++x) {
660                    c &= row[x];
661                }
662                if (0xF != SkGetPackedA4444(c)) {
663                    return false;
664                }
665            }
666            return true;
667        } break;
668        case kBGRA_8888_SkColorType:
669        case kRGBA_8888_SkColorType: {
670            SkPMColor c = (SkPMColor)~0;
671            for (int y = 0; y < height; ++y) {
672                const SkPMColor* row = pmap.addr32(0, y);
673                for (int x = 0; x < width; ++x) {
674                    c &= row[x];
675                }
676                if (0xFF != SkGetPackedA32(c)) {
677                    return false;
678                }
679            }
680            return true;
681        }
682        default:
683            break;
684    }
685    return false;
686}
687
688bool SkBitmap::ComputeIsOpaque(const SkBitmap& bm) {
689    SkAutoPixmapUnlock result;
690    if (!bm.requestLock(&result)) {
691        return false;
692    }
693    return compute_is_opaque(result.pixmap());
694}
695
696
697///////////////////////////////////////////////////////////////////////////////
698///////////////////////////////////////////////////////////////////////////////
699
700void SkBitmap::erase(SkColor c, const SkIRect& area) const {
701    SkDEBUGCODE(this->validate();)
702
703    switch (fInfo.colorType()) {
704        case kUnknown_SkColorType:
705        case kIndex_8_SkColorType:
706            // TODO: can we ASSERT that we never get here?
707            return; // can't erase. Should we bzero so the memory is not uninitialized?
708        default:
709            break;
710    }
711
712    SkAutoPixmapUnlock result;
713    if (!this->requestLock(&result)) {
714        return;
715    }
716
717    if (result.pixmap().erase(c, area)) {
718        this->notifyPixelsChanged();
719    }
720}
721
722void SkBitmap::eraseColor(SkColor c) const {
723    this->erase(c, SkIRect::MakeWH(this->width(), this->height()));
724}
725
726//////////////////////////////////////////////////////////////////////////////////////
727//////////////////////////////////////////////////////////////////////////////////////
728
729bool SkBitmap::extractSubset(SkBitmap* result, const SkIRect& subset) const {
730    SkDEBUGCODE(this->validate();)
731
732    if (nullptr == result || nullptr == fPixelRef) {
733        return false;   // no src pixels
734    }
735
736    SkIRect srcRect, r;
737    srcRect.set(0, 0, this->width(), this->height());
738    if (!r.intersect(srcRect, subset)) {
739        return false;   // r is empty (i.e. no intersection)
740    }
741
742    // If the upper left of the rectangle was outside the bounds of this SkBitmap, we should have
743    // exited above.
744    SkASSERT(static_cast<unsigned>(r.fLeft) < static_cast<unsigned>(this->width()));
745    SkASSERT(static_cast<unsigned>(r.fTop) < static_cast<unsigned>(this->height()));
746
747    SkBitmap dst;
748    dst.setInfo(this->info().makeWH(r.width(), r.height()), this->rowBytes());
749    dst.setIsVolatile(this->isVolatile());
750
751    if (fPixelRef) {
752        SkIPoint origin = fPixelRefOrigin;
753        origin.fX += r.fLeft;
754        origin.fY += r.fTop;
755        // share the pixelref with a custom offset
756        dst.setPixelRef(fPixelRef, origin);
757    }
758    SkDEBUGCODE(dst.validate();)
759
760    // we know we're good, so commit to result
761    result->swap(dst);
762    return true;
763}
764
765///////////////////////////////////////////////////////////////////////////////
766
767bool SkBitmap::canCopyTo(SkColorType dstColorType) const {
768    const SkColorType srcCT = this->colorType();
769
770    if (srcCT == kUnknown_SkColorType) {
771        return false;
772    }
773
774    bool sameConfigs = (srcCT == dstColorType);
775    switch (dstColorType) {
776        case kAlpha_8_SkColorType:
777        case kRGB_565_SkColorType:
778        case kRGBA_8888_SkColorType:
779        case kBGRA_8888_SkColorType:
780            break;
781        case kIndex_8_SkColorType:
782            if (!sameConfigs) {
783                return false;
784            }
785            break;
786        case kARGB_4444_SkColorType:
787            return sameConfigs || kN32_SkColorType == srcCT || kIndex_8_SkColorType == srcCT;
788        case kGray_8_SkColorType:
789            switch (srcCT) {
790                case kGray_8_SkColorType:
791                case kRGBA_8888_SkColorType:
792                case kBGRA_8888_SkColorType:
793                    return true;
794                default:
795                    break;
796            }
797            return false;
798        default:
799            return false;
800    }
801    return true;
802}
803
804bool SkBitmap::readPixels(const SkImageInfo& requestedDstInfo, void* dstPixels, size_t dstRB,
805                          int x, int y) const {
806    SkAutoPixmapUnlock src;
807    if (!this->requestLock(&src)) {
808        return false;
809    }
810    return src.pixmap().readPixels(requestedDstInfo, dstPixels, dstRB, x, y);
811}
812
813bool SkBitmap::copyTo(SkBitmap* dst, SkColorType dstColorType, Allocator* alloc) const {
814    if (!this->canCopyTo(dstColorType)) {
815        return false;
816    }
817
818    // if we have a texture, first get those pixels
819    SkBitmap tmpSrc;
820    const SkBitmap* src = this;
821
822    if (fPixelRef) {
823        SkIRect subset;
824        subset.setXYWH(fPixelRefOrigin.fX, fPixelRefOrigin.fY,
825                       fInfo.width(), fInfo.height());
826        if (fPixelRef->readPixels(&tmpSrc, dstColorType, &subset)) {
827            if (fPixelRef->info().alphaType() == kUnpremul_SkAlphaType) {
828                // FIXME: The only meaningful implementation of readPixels
829                // (GrPixelRef) assumes premultiplied pixels.
830                return false;
831            }
832            SkASSERT(tmpSrc.width() == this->width());
833            SkASSERT(tmpSrc.height() == this->height());
834
835            // did we get lucky and we can just return tmpSrc?
836            if (tmpSrc.colorType() == dstColorType && nullptr == alloc) {
837                dst->swap(tmpSrc);
838                // If the result is an exact copy, clone the gen ID.
839                if (dst->pixelRef() && dst->pixelRef()->info() == fPixelRef->info()) {
840                    dst->pixelRef()->cloneGenID(*fPixelRef);
841                }
842                return true;
843            }
844
845            // fall through to the raster case
846            src = &tmpSrc;
847        }
848    }
849
850    SkAutoPixmapUnlock srcUnlocker;
851    if (!src->requestLock(&srcUnlocker)) {
852        return false;
853    }
854    const SkPixmap& srcPM = srcUnlocker.pixmap();
855
856    const SkImageInfo dstInfo = srcPM.info().makeColorType(dstColorType);
857    SkBitmap tmpDst;
858    if (!tmpDst.setInfo(dstInfo)) {
859        return false;
860    }
861
862    // allocate colortable if srcConfig == kIndex8_Config
863    SkAutoTUnref<SkColorTable> ctable;
864    if (dstColorType == kIndex_8_SkColorType) {
865        ctable.reset(SkRef(srcPM.ctable()));
866    }
867    if (!tmpDst.tryAllocPixels(alloc, ctable)) {
868        return false;
869    }
870
871    SkAutoPixmapUnlock dstUnlocker;
872    if (!tmpDst.requestLock(&dstUnlocker)) {
873        return false;
874    }
875
876    if (!srcPM.readPixels(dstUnlocker.pixmap())) {
877        return false;
878    }
879
880    //  (for BitmapHeap) Clone the pixelref genID even though we have a new pixelref.
881    //  The old copyTo impl did this, so we continue it for now.
882    //
883    //  TODO: should we ignore rowbytes (i.e. getSize)? Then it could just be
884    //      if (src_pixelref->info == dst_pixelref->info)
885    //
886    if (srcPM.colorType() == dstColorType && tmpDst.getSize() == srcPM.getSize64()) {
887        SkPixelRef* dstPixelRef = tmpDst.pixelRef();
888        if (dstPixelRef->info() == fPixelRef->info()) {
889            dstPixelRef->cloneGenID(*fPixelRef);
890        }
891    }
892
893    dst->swap(tmpDst);
894    return true;
895}
896
897// TODO: can we merge this with copyTo?
898bool SkBitmap::deepCopyTo(SkBitmap* dst) const {
899    const SkColorType dstCT = this->colorType();
900
901    if (!this->canCopyTo(dstCT)) {
902        return false;
903    }
904    return this->copyTo(dst, dstCT, nullptr);
905}
906
907///////////////////////////////////////////////////////////////////////////////
908
909static void rect_memset(uint8_t* array, U8CPU value, SkISize size, size_t rowBytes) {
910    for (int y = 0; y < size.height(); ++y) {
911        memset(array, value, size.width());
912        array += rowBytes;
913    }
914}
915
916static void get_bitmap_alpha(const SkPixmap& pmap, uint8_t* SK_RESTRICT alpha, int alphaRowBytes) {
917    SkColorType colorType = pmap.colorType();
918    int         w = pmap.width();
919    int         h = pmap.height();
920    size_t      rb = pmap.rowBytes();
921
922    if (kAlpha_8_SkColorType == colorType && !pmap.isOpaque()) {
923        const uint8_t* s = pmap.addr8(0, 0);
924        while (--h >= 0) {
925            memcpy(alpha, s, w);
926            s += rb;
927            alpha += alphaRowBytes;
928        }
929    } else if (kN32_SkColorType == colorType && !pmap.isOpaque()) {
930        const SkPMColor* SK_RESTRICT s = pmap.addr32(0, 0);
931        while (--h >= 0) {
932            for (int x = 0; x < w; x++) {
933                alpha[x] = SkGetPackedA32(s[x]);
934            }
935            s = (const SkPMColor*)((const char*)s + rb);
936            alpha += alphaRowBytes;
937        }
938    } else if (kARGB_4444_SkColorType == colorType && !pmap.isOpaque()) {
939        const SkPMColor16* SK_RESTRICT s = pmap.addr16(0, 0);
940        while (--h >= 0) {
941            for (int x = 0; x < w; x++) {
942                alpha[x] = SkPacked4444ToA32(s[x]);
943            }
944            s = (const SkPMColor16*)((const char*)s + rb);
945            alpha += alphaRowBytes;
946        }
947    } else if (kIndex_8_SkColorType == colorType && !pmap.isOpaque()) {
948        const SkColorTable* ct = pmap.ctable();
949        if (ct) {
950            const SkPMColor* SK_RESTRICT table = ct->readColors();
951            const uint8_t* SK_RESTRICT s = pmap.addr8(0, 0);
952            while (--h >= 0) {
953                for (int x = 0; x < w; x++) {
954                    alpha[x] = SkGetPackedA32(table[s[x]]);
955                }
956                s += rb;
957                alpha += alphaRowBytes;
958            }
959        }
960    } else {    // src is opaque, so just fill alpha[] with 0xFF
961        rect_memset(alpha, 0xFF, pmap.info().dimensions(), alphaRowBytes);
962    }
963}
964
965static bool GetBitmapAlpha(const SkBitmap& src, uint8_t* SK_RESTRICT alpha, int alphaRowBytes) {
966    SkASSERT(alpha != nullptr);
967    SkASSERT(alphaRowBytes >= src.width());
968
969    SkAutoPixmapUnlock apl;
970    if (!src.requestLock(&apl)) {
971        rect_memset(alpha, 0, src.info().dimensions(), alphaRowBytes);
972        return false;
973    }
974    get_bitmap_alpha(apl.pixmap(), alpha, alphaRowBytes);
975    return true;
976}
977
978#include "SkPaint.h"
979#include "SkMaskFilter.h"
980#include "SkMatrix.h"
981
982bool SkBitmap::extractAlpha(SkBitmap* dst, const SkPaint* paint,
983                            Allocator *allocator, SkIPoint* offset) const {
984    SkDEBUGCODE(this->validate();)
985
986    SkBitmap    tmpBitmap;
987    SkMatrix    identity;
988    SkMask      srcM, dstM;
989
990    srcM.fBounds.set(0, 0, this->width(), this->height());
991    srcM.fRowBytes = SkAlign4(this->width());
992    srcM.fFormat = SkMask::kA8_Format;
993
994    SkMaskFilter* filter = paint ? paint->getMaskFilter() : nullptr;
995
996    // compute our (larger?) dst bounds if we have a filter
997    if (filter) {
998        identity.reset();
999        if (!filter->filterMask(&dstM, srcM, identity, nullptr)) {
1000            goto NO_FILTER_CASE;
1001        }
1002        dstM.fRowBytes = SkAlign4(dstM.fBounds.width());
1003    } else {
1004    NO_FILTER_CASE:
1005        tmpBitmap.setInfo(SkImageInfo::MakeA8(this->width(), this->height()), srcM.fRowBytes);
1006        if (!tmpBitmap.tryAllocPixels(allocator, nullptr)) {
1007            // Allocation of pixels for alpha bitmap failed.
1008            SkDebugf("extractAlpha failed to allocate (%d,%d) alpha bitmap\n",
1009                    tmpBitmap.width(), tmpBitmap.height());
1010            return false;
1011        }
1012        GetBitmapAlpha(*this, tmpBitmap.getAddr8(0, 0), srcM.fRowBytes);
1013        if (offset) {
1014            offset->set(0, 0);
1015        }
1016        tmpBitmap.swap(*dst);
1017        return true;
1018    }
1019    srcM.fImage = SkMask::AllocImage(srcM.computeImageSize());
1020    SkAutoMaskFreeImage srcCleanup(srcM.fImage);
1021
1022    GetBitmapAlpha(*this, srcM.fImage, srcM.fRowBytes);
1023    if (!filter->filterMask(&dstM, srcM, identity, nullptr)) {
1024        goto NO_FILTER_CASE;
1025    }
1026    SkAutoMaskFreeImage dstCleanup(dstM.fImage);
1027
1028    tmpBitmap.setInfo(SkImageInfo::MakeA8(dstM.fBounds.width(), dstM.fBounds.height()),
1029                      dstM.fRowBytes);
1030    if (!tmpBitmap.tryAllocPixels(allocator, nullptr)) {
1031        // Allocation of pixels for alpha bitmap failed.
1032        SkDebugf("extractAlpha failed to allocate (%d,%d) alpha bitmap\n",
1033                tmpBitmap.width(), tmpBitmap.height());
1034        return false;
1035    }
1036    memcpy(tmpBitmap.getPixels(), dstM.fImage, dstM.computeImageSize());
1037    if (offset) {
1038        offset->set(dstM.fBounds.fLeft, dstM.fBounds.fTop);
1039    }
1040    SkDEBUGCODE(tmpBitmap.validate();)
1041
1042    tmpBitmap.swap(*dst);
1043    return true;
1044}
1045
1046///////////////////////////////////////////////////////////////////////////////
1047
1048static void write_raw_pixels(SkWriteBuffer* buffer, const SkPixmap& pmap) {
1049    const SkImageInfo& info = pmap.info();
1050    const size_t snugRB = info.width() * info.bytesPerPixel();
1051    const char* src = (const char*)pmap.addr();
1052    const size_t ramRB = pmap.rowBytes();
1053
1054    buffer->write32(SkToU32(snugRB));
1055    info.flatten(*buffer);
1056
1057    const size_t size = snugRB * info.height();
1058    SkAutoTMalloc<char> storage(size);
1059    char* dst = storage.get();
1060    for (int y = 0; y < info.height(); ++y) {
1061        memcpy(dst, src, snugRB);
1062        dst += snugRB;
1063        src += ramRB;
1064    }
1065    buffer->writeByteArray(storage.get(), size);
1066
1067    const SkColorTable* ct = pmap.ctable();
1068    if (kIndex_8_SkColorType == info.colorType() && ct) {
1069        buffer->writeBool(true);
1070        ct->writeToBuffer(*buffer);
1071    } else {
1072        buffer->writeBool(false);
1073    }
1074}
1075
1076void SkBitmap::WriteRawPixels(SkWriteBuffer* buffer, const SkBitmap& bitmap) {
1077    const SkImageInfo info = bitmap.info();
1078    if (0 == info.width() || 0 == info.height() || nullptr == bitmap.pixelRef()) {
1079        buffer->writeUInt(0); // instead of snugRB, signaling no pixels
1080        return;
1081    }
1082
1083    SkAutoPixmapUnlock result;
1084    if (!bitmap.requestLock(&result)) {
1085        buffer->writeUInt(0); // instead of snugRB, signaling no pixels
1086        return;
1087    }
1088
1089    write_raw_pixels(buffer, result.pixmap());
1090}
1091
1092bool SkBitmap::ReadRawPixels(SkReadBuffer* buffer, SkBitmap* bitmap) {
1093    const size_t snugRB = buffer->readUInt();
1094    if (0 == snugRB) {  // no pixels
1095        return false;
1096    }
1097
1098    SkImageInfo info;
1099    info.unflatten(*buffer);
1100
1101    // If there was an error reading "info" or if it is bogus,
1102    // don't use it to compute minRowBytes()
1103    if (!buffer->validate(SkColorTypeValidateAlphaType(info.colorType(),
1104                                                       info.alphaType()))) {
1105        return false;
1106    }
1107
1108    const size_t ramRB = info.minRowBytes();
1109    const int height = SkMax32(info.height(), 0);
1110    const uint64_t snugSize = sk_64_mul(snugRB, height);
1111    const uint64_t ramSize = sk_64_mul(ramRB, height);
1112    static const uint64_t max_size_t = (size_t)(-1);
1113    if (!buffer->validate((snugSize <= ramSize) && (ramSize <= max_size_t))) {
1114        return false;
1115    }
1116
1117    sk_sp<SkData> data(SkData::MakeUninitialized(SkToSizeT(ramSize)));
1118    unsigned char* dst = (unsigned char*)data->writable_data();
1119    buffer->readByteArray(dst, SkToSizeT(snugSize));
1120
1121    if (snugSize != ramSize) {
1122        const unsigned char* srcRow = dst + snugRB * (height - 1);
1123        unsigned char* dstRow = dst + ramRB * (height - 1);
1124        for (int y = height - 1; y >= 1; --y) {
1125            memmove(dstRow, srcRow, snugRB);
1126            srcRow -= snugRB;
1127            dstRow -= ramRB;
1128        }
1129        SkASSERT(srcRow == dstRow); // first row does not need to be moved
1130    }
1131
1132    SkAutoTUnref<SkColorTable> ctable;
1133    if (buffer->readBool()) {
1134        ctable.reset(SkColorTable::Create(*buffer));
1135        if (!ctable) {
1136            return false;
1137        }
1138
1139        if (info.isEmpty()) {
1140            // require an empty ctable
1141            if (ctable->count() != 0) {
1142                buffer->validate(false);
1143                return false;
1144            }
1145        } else {
1146            // require a non-empty ctable
1147            if (ctable->count() == 0) {
1148                buffer->validate(false);
1149                return false;
1150            }
1151            unsigned char maxIndex = ctable->count() - 1;
1152            for (uint64_t i = 0; i < ramSize; ++i) {
1153                dst[i] = SkTMin(dst[i], maxIndex);
1154            }
1155        }
1156    }
1157
1158    SkAutoTUnref<SkPixelRef> pr(SkMallocPixelRef::NewWithData(info, info.minRowBytes(),
1159                                                              ctable.get(), data.get()));
1160    if (!pr.get()) {
1161        return false;
1162    }
1163    bitmap->setInfo(pr->info());
1164    bitmap->setPixelRef(pr, 0, 0);
1165    return true;
1166}
1167
1168enum {
1169    SERIALIZE_PIXELTYPE_NONE,
1170    SERIALIZE_PIXELTYPE_REF_DATA
1171};
1172
1173///////////////////////////////////////////////////////////////////////////////
1174
1175SkBitmap::RLEPixels::RLEPixels(int width, int height) {
1176    fHeight = height;
1177    fYPtrs = (uint8_t**)sk_calloc_throw(height * sizeof(uint8_t*));
1178}
1179
1180SkBitmap::RLEPixels::~RLEPixels() {
1181    sk_free(fYPtrs);
1182}
1183
1184///////////////////////////////////////////////////////////////////////////////
1185
1186#ifdef SK_DEBUG
1187void SkBitmap::validate() const {
1188    fInfo.validate();
1189
1190    // ImageInfo may not require this, but Bitmap ensures that opaque-only
1191    // colorTypes report opaque for their alphatype
1192    if (kRGB_565_SkColorType == fInfo.colorType()) {
1193        SkASSERT(kOpaque_SkAlphaType == fInfo.alphaType());
1194    }
1195
1196    SkASSERT(fInfo.validRowBytes(fRowBytes));
1197    uint8_t allFlags = kImageIsVolatile_Flag;
1198#ifdef SK_BUILD_FOR_ANDROID
1199    allFlags |= kHasHardwareMipMap_Flag;
1200#endif
1201    SkASSERT((~allFlags & fFlags) == 0);
1202    SkASSERT(fPixelLockCount >= 0);
1203
1204    if (fPixels) {
1205        SkASSERT(fPixelRef);
1206        SkASSERT(fPixelLockCount > 0);
1207        SkASSERT(fPixelRef->isLocked());
1208        SkASSERT(fPixelRef->rowBytes() == fRowBytes);
1209        SkASSERT(fPixelRefOrigin.fX >= 0);
1210        SkASSERT(fPixelRefOrigin.fY >= 0);
1211        SkASSERT(fPixelRef->info().width() >= (int)this->width() + fPixelRefOrigin.fX);
1212        SkASSERT(fPixelRef->info().height() >= (int)this->height() + fPixelRefOrigin.fY);
1213        SkASSERT(fPixelRef->rowBytes() >= fInfo.minRowBytes());
1214    } else {
1215        SkASSERT(nullptr == fColorTable);
1216    }
1217}
1218#endif
1219
1220#ifndef SK_IGNORE_TO_STRING
1221#include "SkString.h"
1222void SkBitmap::toString(SkString* str) const {
1223
1224    static const char* gColorTypeNames[kLastEnum_SkColorType + 1] = {
1225        "UNKNOWN", "A8", "565", "4444", "RGBA", "BGRA", "INDEX8",
1226    };
1227
1228    str->appendf("bitmap: ((%d, %d) %s", this->width(), this->height(),
1229                 gColorTypeNames[this->colorType()]);
1230
1231    str->append(" (");
1232    if (this->isOpaque()) {
1233        str->append("opaque");
1234    } else {
1235        str->append("transparent");
1236    }
1237    if (this->isImmutable()) {
1238        str->append(", immutable");
1239    } else {
1240        str->append(", not-immutable");
1241    }
1242    str->append(")");
1243
1244    SkPixelRef* pr = this->pixelRef();
1245    if (nullptr == pr) {
1246        // show null or the explicit pixel address (rare)
1247        str->appendf(" pixels:%p", this->getPixels());
1248    } else {
1249        const char* uri = pr->getURI();
1250        if (uri) {
1251            str->appendf(" uri:\"%s\"", uri);
1252        } else {
1253            str->appendf(" pixelref:%p", pr);
1254        }
1255    }
1256
1257    str->append(")");
1258}
1259#endif
1260
1261///////////////////////////////////////////////////////////////////////////////
1262
1263bool SkBitmap::requestLock(SkAutoPixmapUnlock* result) const {
1264    SkASSERT(result);
1265
1266    SkPixelRef* pr = fPixelRef;
1267    if (nullptr == pr) {
1268        return false;
1269    }
1270
1271    // We have to lock the whole thing (using the pixelref's dimensions) until the api supports
1272    // a partial lock (with offset/origin). Hence we can't use our fInfo.
1273    SkPixelRef::LockRequest req = { pr->info().dimensions(), kNone_SkFilterQuality };
1274    SkPixelRef::LockResult res;
1275    if (pr->requestLock(req, &res)) {
1276        SkASSERT(res.fPixels);
1277        // The bitmap may be a subset of the pixelref's dimensions
1278        SkASSERT(fPixelRefOrigin.x() + fInfo.width()  <= res.fSize.width());
1279        SkASSERT(fPixelRefOrigin.y() + fInfo.height() <= res.fSize.height());
1280        const void* addr = (const char*)res.fPixels + SkColorTypeComputeOffset(fInfo.colorType(),
1281                                                                               fPixelRefOrigin.x(),
1282                                                                               fPixelRefOrigin.y(),
1283                                                                               res.fRowBytes);
1284
1285        result->reset(SkPixmap(this->info(), addr, res.fRowBytes, res.fCTable),
1286                      res.fUnlockProc, res.fUnlockContext);
1287        return true;
1288    }
1289    return false;
1290}
1291
1292bool SkBitmap::peekPixels(SkPixmap* pmap) const {
1293    if (fPixels) {
1294        if (pmap) {
1295            pmap->reset(fInfo, fPixels, fRowBytes, fColorTable);
1296        }
1297        return true;
1298    }
1299    return false;
1300}
1301
1302///////////////////////////////////////////////////////////////////////////////
1303
1304#ifdef SK_DEBUG
1305void SkImageInfo::validate() const {
1306    SkASSERT(fWidth >= 0);
1307    SkASSERT(fHeight >= 0);
1308    SkASSERT(SkColorTypeIsValid(fColorType));
1309    SkASSERT(SkAlphaTypeIsValid(fAlphaType));
1310}
1311#endif
1312