SkBitmap.cpp revision c7ec7c9cabf5c8ad08beb617b99831ece25dacdd
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_8888_SkColorType:
539            case kBGRA_8888_SkColorType:
540                base += x << 2;
541                break;
542            case kARGB_4444_SkColorType:
543            case kRGB_565_SkColorType:
544                base += x << 1;
545                break;
546            case kAlpha_8_SkColorType:
547            case kIndex_8_SkColorType:
548            case kGray_8_SkColorType:
549                base += x;
550                break;
551            default:
552                SkDEBUGFAIL("Can't return addr for config");
553                base = nullptr;
554                break;
555        }
556    }
557    return base;
558}
559
560#include "SkHalf.h"
561
562SkColor SkBitmap::getColor(int x, int y) const {
563    SkASSERT((unsigned)x < (unsigned)this->width());
564    SkASSERT((unsigned)y < (unsigned)this->height());
565
566    switch (this->colorType()) {
567        case kGray_8_SkColorType: {
568            uint8_t* addr = this->getAddr8(x, y);
569            return SkColorSetRGB(*addr, *addr, *addr);
570        }
571        case kAlpha_8_SkColorType: {
572            uint8_t* addr = this->getAddr8(x, y);
573            return SkColorSetA(0, addr[0]);
574        }
575        case kIndex_8_SkColorType: {
576            SkPMColor c = this->getIndex8Color(x, y);
577            return SkUnPreMultiply::PMColorToColor(c);
578        }
579        case kRGB_565_SkColorType: {
580            uint16_t* addr = this->getAddr16(x, y);
581            return SkPixel16ToColor(addr[0]);
582        }
583        case kARGB_4444_SkColorType: {
584            uint16_t* addr = this->getAddr16(x, y);
585            SkPMColor c = SkPixel4444ToPixel32(addr[0]);
586            return SkUnPreMultiply::PMColorToColor(c);
587        }
588        case kBGRA_8888_SkColorType: {
589            uint32_t* addr = this->getAddr32(x, y);
590            SkPMColor c = SkSwizzle_BGRA_to_PMColor(addr[0]);
591            return SkUnPreMultiply::PMColorToColor(c);
592        }
593        case kRGBA_8888_SkColorType: {
594            uint32_t* addr = this->getAddr32(x, y);
595            SkPMColor c = SkSwizzle_RGBA_to_PMColor(addr[0]);
596            return SkUnPreMultiply::PMColorToColor(c);
597        }
598        case kRGBA_F16_SkColorType: {
599            const uint64_t* addr = (const uint64_t*)fPixels + y * (fRowBytes >> 3) + x;
600            Sk4f p4 = SkHalfToFloat_finite(addr[0]);
601            if (p4[3]) {
602                float inva = 1 / p4[3];
603                p4 = p4 * Sk4f(inva, inva, inva, 1);
604            }
605            SkColor c;
606            SkNx_cast<uint8_t>(p4 * Sk4f(255) + Sk4f(0.5f)).store(&c);
607            // p4 is RGBA, but we want BGRA, so we need to swap next
608            return SkSwizzle_RB(c);
609        }
610        default:
611            SkASSERT(false);
612            return 0;
613    }
614    SkASSERT(false);  // Not reached.
615    return 0;
616}
617
618static bool compute_is_opaque(const SkPixmap& pmap) {
619    const int height = pmap.height();
620    const int width = pmap.width();
621
622    switch (pmap.colorType()) {
623        case kAlpha_8_SkColorType: {
624            unsigned a = 0xFF;
625            for (int y = 0; y < height; ++y) {
626                const uint8_t* row = pmap.addr8(0, y);
627                for (int x = 0; x < width; ++x) {
628                    a &= row[x];
629                }
630                if (0xFF != a) {
631                    return false;
632                }
633            }
634            return true;
635        } break;
636        case kIndex_8_SkColorType: {
637            const SkColorTable* ctable = pmap.ctable();
638            if (nullptr == ctable) {
639                return false;
640            }
641            const SkPMColor* table = ctable->readColors();
642            SkPMColor c = (SkPMColor)~0;
643            for (int i = ctable->count() - 1; i >= 0; --i) {
644                c &= table[i];
645            }
646            return 0xFF == SkGetPackedA32(c);
647        } break;
648        case kRGB_565_SkColorType:
649        case kGray_8_SkColorType:
650            return true;
651            break;
652        case kARGB_4444_SkColorType: {
653            unsigned c = 0xFFFF;
654            for (int y = 0; y < height; ++y) {
655                const SkPMColor16* row = pmap.addr16(0, y);
656                for (int x = 0; x < width; ++x) {
657                    c &= row[x];
658                }
659                if (0xF != SkGetPackedA4444(c)) {
660                    return false;
661                }
662            }
663            return true;
664        } break;
665        case kBGRA_8888_SkColorType:
666        case kRGBA_8888_SkColorType: {
667            SkPMColor c = (SkPMColor)~0;
668            for (int y = 0; y < height; ++y) {
669                const SkPMColor* row = pmap.addr32(0, y);
670                for (int x = 0; x < width; ++x) {
671                    c &= row[x];
672                }
673                if (0xFF != SkGetPackedA32(c)) {
674                    return false;
675                }
676            }
677            return true;
678        }
679        default:
680            break;
681    }
682    return false;
683}
684
685bool SkBitmap::ComputeIsOpaque(const SkBitmap& bm) {
686    SkAutoPixmapUnlock result;
687    if (!bm.requestLock(&result)) {
688        return false;
689    }
690    return compute_is_opaque(result.pixmap());
691}
692
693
694///////////////////////////////////////////////////////////////////////////////
695///////////////////////////////////////////////////////////////////////////////
696
697void SkBitmap::erase(SkColor c, const SkIRect& area) const {
698    SkDEBUGCODE(this->validate();)
699
700    switch (fInfo.colorType()) {
701        case kUnknown_SkColorType:
702        case kIndex_8_SkColorType:
703            // TODO: can we ASSERT that we never get here?
704            return; // can't erase. Should we bzero so the memory is not uninitialized?
705        default:
706            break;
707    }
708
709    SkAutoPixmapUnlock result;
710    if (!this->requestLock(&result)) {
711        return;
712    }
713
714    if (result.pixmap().erase(c, area)) {
715        this->notifyPixelsChanged();
716    }
717}
718
719void SkBitmap::eraseColor(SkColor c) const {
720    this->erase(c, SkIRect::MakeWH(this->width(), this->height()));
721}
722
723//////////////////////////////////////////////////////////////////////////////////////
724//////////////////////////////////////////////////////////////////////////////////////
725
726bool SkBitmap::extractSubset(SkBitmap* result, const SkIRect& subset) const {
727    SkDEBUGCODE(this->validate();)
728
729    if (nullptr == result || nullptr == fPixelRef) {
730        return false;   // no src pixels
731    }
732
733    SkIRect srcRect, r;
734    srcRect.set(0, 0, this->width(), this->height());
735    if (!r.intersect(srcRect, subset)) {
736        return false;   // r is empty (i.e. no intersection)
737    }
738
739    // If the upper left of the rectangle was outside the bounds of this SkBitmap, we should have
740    // exited above.
741    SkASSERT(static_cast<unsigned>(r.fLeft) < static_cast<unsigned>(this->width()));
742    SkASSERT(static_cast<unsigned>(r.fTop) < static_cast<unsigned>(this->height()));
743
744    SkBitmap dst;
745    dst.setInfo(this->info().makeWH(r.width(), r.height()), this->rowBytes());
746    dst.setIsVolatile(this->isVolatile());
747
748    if (fPixelRef) {
749        SkIPoint origin = fPixelRefOrigin;
750        origin.fX += r.fLeft;
751        origin.fY += r.fTop;
752        // share the pixelref with a custom offset
753        dst.setPixelRef(fPixelRef, origin);
754    }
755    SkDEBUGCODE(dst.validate();)
756
757    // we know we're good, so commit to result
758    result->swap(dst);
759    return true;
760}
761
762///////////////////////////////////////////////////////////////////////////////
763
764bool SkBitmap::canCopyTo(SkColorType dstColorType) const {
765    const SkColorType srcCT = this->colorType();
766
767    if (srcCT == kUnknown_SkColorType) {
768        return false;
769    }
770
771    bool sameConfigs = (srcCT == dstColorType);
772    switch (dstColorType) {
773        case kAlpha_8_SkColorType:
774        case kRGB_565_SkColorType:
775        case kRGBA_8888_SkColorType:
776        case kBGRA_8888_SkColorType:
777            break;
778        case kIndex_8_SkColorType:
779            if (!sameConfigs) {
780                return false;
781            }
782            break;
783        case kARGB_4444_SkColorType:
784            return sameConfigs || kN32_SkColorType == srcCT || kIndex_8_SkColorType == srcCT;
785        case kGray_8_SkColorType:
786            switch (srcCT) {
787                case kGray_8_SkColorType:
788                case kRGBA_8888_SkColorType:
789                case kBGRA_8888_SkColorType:
790                    return true;
791                default:
792                    break;
793            }
794            return false;
795        default:
796            return false;
797    }
798    return true;
799}
800
801bool SkBitmap::readPixels(const SkImageInfo& requestedDstInfo, void* dstPixels, size_t dstRB,
802                          int x, int y) const {
803    SkAutoPixmapUnlock src;
804    if (!this->requestLock(&src)) {
805        return false;
806    }
807    return src.pixmap().readPixels(requestedDstInfo, dstPixels, dstRB, x, y);
808}
809
810bool SkBitmap::copyTo(SkBitmap* dst, SkColorType dstColorType, Allocator* alloc) const {
811    if (!this->canCopyTo(dstColorType)) {
812        return false;
813    }
814
815    // if we have a texture, first get those pixels
816    SkBitmap tmpSrc;
817    const SkBitmap* src = this;
818
819    if (fPixelRef) {
820        SkIRect subset;
821        subset.setXYWH(fPixelRefOrigin.fX, fPixelRefOrigin.fY,
822                       fInfo.width(), fInfo.height());
823        if (fPixelRef->readPixels(&tmpSrc, dstColorType, &subset)) {
824            if (fPixelRef->info().alphaType() == kUnpremul_SkAlphaType) {
825                // FIXME: The only meaningful implementation of readPixels
826                // (GrPixelRef) assumes premultiplied pixels.
827                return false;
828            }
829            SkASSERT(tmpSrc.width() == this->width());
830            SkASSERT(tmpSrc.height() == this->height());
831
832            // did we get lucky and we can just return tmpSrc?
833            if (tmpSrc.colorType() == dstColorType && nullptr == alloc) {
834                dst->swap(tmpSrc);
835                // If the result is an exact copy, clone the gen ID.
836                if (dst->pixelRef() && dst->pixelRef()->info() == fPixelRef->info()) {
837                    dst->pixelRef()->cloneGenID(*fPixelRef);
838                }
839                return true;
840            }
841
842            // fall through to the raster case
843            src = &tmpSrc;
844        }
845    }
846
847    SkAutoPixmapUnlock srcUnlocker;
848    if (!src->requestLock(&srcUnlocker)) {
849        return false;
850    }
851    const SkPixmap& srcPM = srcUnlocker.pixmap();
852
853    const SkImageInfo dstInfo = srcPM.info().makeColorType(dstColorType);
854    SkBitmap tmpDst;
855    if (!tmpDst.setInfo(dstInfo)) {
856        return false;
857    }
858
859    // allocate colortable if srcConfig == kIndex8_Config
860    SkAutoTUnref<SkColorTable> ctable;
861    if (dstColorType == kIndex_8_SkColorType) {
862        ctable.reset(SkRef(srcPM.ctable()));
863    }
864    if (!tmpDst.tryAllocPixels(alloc, ctable)) {
865        return false;
866    }
867
868    SkAutoPixmapUnlock dstUnlocker;
869    if (!tmpDst.requestLock(&dstUnlocker)) {
870        return false;
871    }
872
873    if (!srcPM.readPixels(dstUnlocker.pixmap())) {
874        return false;
875    }
876
877    //  (for BitmapHeap) Clone the pixelref genID even though we have a new pixelref.
878    //  The old copyTo impl did this, so we continue it for now.
879    //
880    //  TODO: should we ignore rowbytes (i.e. getSize)? Then it could just be
881    //      if (src_pixelref->info == dst_pixelref->info)
882    //
883    if (srcPM.colorType() == dstColorType && tmpDst.getSize() == srcPM.getSize64()) {
884        SkPixelRef* dstPixelRef = tmpDst.pixelRef();
885        if (dstPixelRef->info() == fPixelRef->info()) {
886            dstPixelRef->cloneGenID(*fPixelRef);
887        }
888    }
889
890    dst->swap(tmpDst);
891    return true;
892}
893
894// TODO: can we merge this with copyTo?
895bool SkBitmap::deepCopyTo(SkBitmap* dst) const {
896    const SkColorType dstCT = this->colorType();
897
898    if (!this->canCopyTo(dstCT)) {
899        return false;
900    }
901    return this->copyTo(dst, dstCT, nullptr);
902}
903
904///////////////////////////////////////////////////////////////////////////////
905
906static void rect_memset(uint8_t* array, U8CPU value, SkISize size, size_t rowBytes) {
907    for (int y = 0; y < size.height(); ++y) {
908        memset(array, value, size.width());
909        array += rowBytes;
910    }
911}
912
913static void get_bitmap_alpha(const SkPixmap& pmap, uint8_t* SK_RESTRICT alpha, int alphaRowBytes) {
914    SkColorType colorType = pmap.colorType();
915    int         w = pmap.width();
916    int         h = pmap.height();
917    size_t      rb = pmap.rowBytes();
918
919    if (kAlpha_8_SkColorType == colorType && !pmap.isOpaque()) {
920        const uint8_t* s = pmap.addr8(0, 0);
921        while (--h >= 0) {
922            memcpy(alpha, s, w);
923            s += rb;
924            alpha += alphaRowBytes;
925        }
926    } else if (kN32_SkColorType == colorType && !pmap.isOpaque()) {
927        const SkPMColor* SK_RESTRICT s = pmap.addr32(0, 0);
928        while (--h >= 0) {
929            for (int x = 0; x < w; x++) {
930                alpha[x] = SkGetPackedA32(s[x]);
931            }
932            s = (const SkPMColor*)((const char*)s + rb);
933            alpha += alphaRowBytes;
934        }
935    } else if (kARGB_4444_SkColorType == colorType && !pmap.isOpaque()) {
936        const SkPMColor16* SK_RESTRICT s = pmap.addr16(0, 0);
937        while (--h >= 0) {
938            for (int x = 0; x < w; x++) {
939                alpha[x] = SkPacked4444ToA32(s[x]);
940            }
941            s = (const SkPMColor16*)((const char*)s + rb);
942            alpha += alphaRowBytes;
943        }
944    } else if (kIndex_8_SkColorType == colorType && !pmap.isOpaque()) {
945        const SkColorTable* ct = pmap.ctable();
946        if (ct) {
947            const SkPMColor* SK_RESTRICT table = ct->readColors();
948            const uint8_t* SK_RESTRICT s = pmap.addr8(0, 0);
949            while (--h >= 0) {
950                for (int x = 0; x < w; x++) {
951                    alpha[x] = SkGetPackedA32(table[s[x]]);
952                }
953                s += rb;
954                alpha += alphaRowBytes;
955            }
956        }
957    } else {    // src is opaque, so just fill alpha[] with 0xFF
958        rect_memset(alpha, 0xFF, pmap.info().dimensions(), alphaRowBytes);
959    }
960}
961
962static bool GetBitmapAlpha(const SkBitmap& src, uint8_t* SK_RESTRICT alpha, int alphaRowBytes) {
963    SkASSERT(alpha != nullptr);
964    SkASSERT(alphaRowBytes >= src.width());
965
966    SkAutoPixmapUnlock apl;
967    if (!src.requestLock(&apl)) {
968        rect_memset(alpha, 0, src.info().dimensions(), alphaRowBytes);
969        return false;
970    }
971    get_bitmap_alpha(apl.pixmap(), alpha, alphaRowBytes);
972    return true;
973}
974
975#include "SkPaint.h"
976#include "SkMaskFilter.h"
977#include "SkMatrix.h"
978
979bool SkBitmap::extractAlpha(SkBitmap* dst, const SkPaint* paint,
980                            Allocator *allocator, SkIPoint* offset) const {
981    SkDEBUGCODE(this->validate();)
982
983    SkBitmap    tmpBitmap;
984    SkMatrix    identity;
985    SkMask      srcM, dstM;
986
987    srcM.fBounds.set(0, 0, this->width(), this->height());
988    srcM.fRowBytes = SkAlign4(this->width());
989    srcM.fFormat = SkMask::kA8_Format;
990
991    SkMaskFilter* filter = paint ? paint->getMaskFilter() : nullptr;
992
993    // compute our (larger?) dst bounds if we have a filter
994    if (filter) {
995        identity.reset();
996        if (!filter->filterMask(&dstM, srcM, identity, nullptr)) {
997            goto NO_FILTER_CASE;
998        }
999        dstM.fRowBytes = SkAlign4(dstM.fBounds.width());
1000    } else {
1001    NO_FILTER_CASE:
1002        tmpBitmap.setInfo(SkImageInfo::MakeA8(this->width(), this->height()), srcM.fRowBytes);
1003        if (!tmpBitmap.tryAllocPixels(allocator, nullptr)) {
1004            // Allocation of pixels for alpha bitmap failed.
1005            SkDebugf("extractAlpha failed to allocate (%d,%d) alpha bitmap\n",
1006                    tmpBitmap.width(), tmpBitmap.height());
1007            return false;
1008        }
1009        GetBitmapAlpha(*this, tmpBitmap.getAddr8(0, 0), srcM.fRowBytes);
1010        if (offset) {
1011            offset->set(0, 0);
1012        }
1013        tmpBitmap.swap(*dst);
1014        return true;
1015    }
1016    srcM.fImage = SkMask::AllocImage(srcM.computeImageSize());
1017    SkAutoMaskFreeImage srcCleanup(srcM.fImage);
1018
1019    GetBitmapAlpha(*this, srcM.fImage, srcM.fRowBytes);
1020    if (!filter->filterMask(&dstM, srcM, identity, nullptr)) {
1021        goto NO_FILTER_CASE;
1022    }
1023    SkAutoMaskFreeImage dstCleanup(dstM.fImage);
1024
1025    tmpBitmap.setInfo(SkImageInfo::MakeA8(dstM.fBounds.width(), dstM.fBounds.height()),
1026                      dstM.fRowBytes);
1027    if (!tmpBitmap.tryAllocPixels(allocator, nullptr)) {
1028        // Allocation of pixels for alpha bitmap failed.
1029        SkDebugf("extractAlpha failed to allocate (%d,%d) alpha bitmap\n",
1030                tmpBitmap.width(), tmpBitmap.height());
1031        return false;
1032    }
1033    memcpy(tmpBitmap.getPixels(), dstM.fImage, dstM.computeImageSize());
1034    if (offset) {
1035        offset->set(dstM.fBounds.fLeft, dstM.fBounds.fTop);
1036    }
1037    SkDEBUGCODE(tmpBitmap.validate();)
1038
1039    tmpBitmap.swap(*dst);
1040    return true;
1041}
1042
1043///////////////////////////////////////////////////////////////////////////////
1044
1045static void write_raw_pixels(SkWriteBuffer* buffer, const SkPixmap& pmap) {
1046    const SkImageInfo& info = pmap.info();
1047    const size_t snugRB = info.width() * info.bytesPerPixel();
1048    const char* src = (const char*)pmap.addr();
1049    const size_t ramRB = pmap.rowBytes();
1050
1051    buffer->write32(SkToU32(snugRB));
1052    info.flatten(*buffer);
1053
1054    const size_t size = snugRB * info.height();
1055    SkAutoTMalloc<char> storage(size);
1056    char* dst = storage.get();
1057    for (int y = 0; y < info.height(); ++y) {
1058        memcpy(dst, src, snugRB);
1059        dst += snugRB;
1060        src += ramRB;
1061    }
1062    buffer->writeByteArray(storage.get(), size);
1063
1064    const SkColorTable* ct = pmap.ctable();
1065    if (kIndex_8_SkColorType == info.colorType() && ct) {
1066        buffer->writeBool(true);
1067        ct->writeToBuffer(*buffer);
1068    } else {
1069        buffer->writeBool(false);
1070    }
1071}
1072
1073void SkBitmap::WriteRawPixels(SkWriteBuffer* buffer, const SkBitmap& bitmap) {
1074    const SkImageInfo info = bitmap.info();
1075    if (0 == info.width() || 0 == info.height() || nullptr == bitmap.pixelRef()) {
1076        buffer->writeUInt(0); // instead of snugRB, signaling no pixels
1077        return;
1078    }
1079
1080    SkAutoPixmapUnlock result;
1081    if (!bitmap.requestLock(&result)) {
1082        buffer->writeUInt(0); // instead of snugRB, signaling no pixels
1083        return;
1084    }
1085
1086    write_raw_pixels(buffer, result.pixmap());
1087}
1088
1089bool SkBitmap::ReadRawPixels(SkReadBuffer* buffer, SkBitmap* bitmap) {
1090    const size_t snugRB = buffer->readUInt();
1091    if (0 == snugRB) {  // no pixels
1092        return false;
1093    }
1094
1095    SkImageInfo info;
1096    info.unflatten(*buffer);
1097
1098    // If there was an error reading "info" or if it is bogus,
1099    // don't use it to compute minRowBytes()
1100    if (!buffer->validate(SkColorTypeValidateAlphaType(info.colorType(),
1101                                                       info.alphaType()))) {
1102        return false;
1103    }
1104
1105    const size_t ramRB = info.minRowBytes();
1106    const int height = SkMax32(info.height(), 0);
1107    const uint64_t snugSize = sk_64_mul(snugRB, height);
1108    const uint64_t ramSize = sk_64_mul(ramRB, height);
1109    static const uint64_t max_size_t = (size_t)(-1);
1110    if (!buffer->validate((snugSize <= ramSize) && (ramSize <= max_size_t))) {
1111        return false;
1112    }
1113
1114    sk_sp<SkData> data(SkData::MakeUninitialized(SkToSizeT(ramSize)));
1115    unsigned char* dst = (unsigned char*)data->writable_data();
1116    buffer->readByteArray(dst, SkToSizeT(snugSize));
1117
1118    if (snugSize != ramSize) {
1119        const unsigned char* srcRow = dst + snugRB * (height - 1);
1120        unsigned char* dstRow = dst + ramRB * (height - 1);
1121        for (int y = height - 1; y >= 1; --y) {
1122            memmove(dstRow, srcRow, snugRB);
1123            srcRow -= snugRB;
1124            dstRow -= ramRB;
1125        }
1126        SkASSERT(srcRow == dstRow); // first row does not need to be moved
1127    }
1128
1129    SkAutoTUnref<SkColorTable> ctable;
1130    if (buffer->readBool()) {
1131        ctable.reset(SkColorTable::Create(*buffer));
1132        if (!ctable) {
1133            return false;
1134        }
1135
1136        if (info.isEmpty()) {
1137            // require an empty ctable
1138            if (ctable->count() != 0) {
1139                buffer->validate(false);
1140                return false;
1141            }
1142        } else {
1143            // require a non-empty ctable
1144            if (ctable->count() == 0) {
1145                buffer->validate(false);
1146                return false;
1147            }
1148            unsigned char maxIndex = ctable->count() - 1;
1149            for (uint64_t i = 0; i < ramSize; ++i) {
1150                dst[i] = SkTMin(dst[i], maxIndex);
1151            }
1152        }
1153    }
1154
1155    SkAutoTUnref<SkPixelRef> pr(SkMallocPixelRef::NewWithData(info, info.minRowBytes(),
1156                                                              ctable.get(), data.get()));
1157    if (!pr.get()) {
1158        return false;
1159    }
1160    bitmap->setInfo(pr->info());
1161    bitmap->setPixelRef(pr, 0, 0);
1162    return true;
1163}
1164
1165enum {
1166    SERIALIZE_PIXELTYPE_NONE,
1167    SERIALIZE_PIXELTYPE_REF_DATA
1168};
1169
1170///////////////////////////////////////////////////////////////////////////////
1171
1172SkBitmap::RLEPixels::RLEPixels(int width, int height) {
1173    fHeight = height;
1174    fYPtrs = (uint8_t**)sk_calloc_throw(height * sizeof(uint8_t*));
1175}
1176
1177SkBitmap::RLEPixels::~RLEPixels() {
1178    sk_free(fYPtrs);
1179}
1180
1181///////////////////////////////////////////////////////////////////////////////
1182
1183#ifdef SK_DEBUG
1184void SkBitmap::validate() const {
1185    fInfo.validate();
1186
1187    // ImageInfo may not require this, but Bitmap ensures that opaque-only
1188    // colorTypes report opaque for their alphatype
1189    if (kRGB_565_SkColorType == fInfo.colorType()) {
1190        SkASSERT(kOpaque_SkAlphaType == fInfo.alphaType());
1191    }
1192
1193    SkASSERT(fInfo.validRowBytes(fRowBytes));
1194    uint8_t allFlags = kImageIsVolatile_Flag;
1195#ifdef SK_BUILD_FOR_ANDROID
1196    allFlags |= kHasHardwareMipMap_Flag;
1197#endif
1198    SkASSERT((~allFlags & fFlags) == 0);
1199    SkASSERT(fPixelLockCount >= 0);
1200
1201    if (fPixels) {
1202        SkASSERT(fPixelRef);
1203        SkASSERT(fPixelLockCount > 0);
1204        SkASSERT(fPixelRef->isLocked());
1205        SkASSERT(fPixelRef->rowBytes() == fRowBytes);
1206        SkASSERT(fPixelRefOrigin.fX >= 0);
1207        SkASSERT(fPixelRefOrigin.fY >= 0);
1208        SkASSERT(fPixelRef->info().width() >= (int)this->width() + fPixelRefOrigin.fX);
1209        SkASSERT(fPixelRef->info().height() >= (int)this->height() + fPixelRefOrigin.fY);
1210        SkASSERT(fPixelRef->rowBytes() >= fInfo.minRowBytes());
1211    } else {
1212        SkASSERT(nullptr == fColorTable);
1213    }
1214}
1215#endif
1216
1217#ifndef SK_IGNORE_TO_STRING
1218#include "SkString.h"
1219void SkBitmap::toString(SkString* str) const {
1220
1221    static const char* gColorTypeNames[kLastEnum_SkColorType + 1] = {
1222        "UNKNOWN", "A8", "565", "4444", "RGBA", "BGRA", "INDEX8",
1223    };
1224
1225    str->appendf("bitmap: ((%d, %d) %s", this->width(), this->height(),
1226                 gColorTypeNames[this->colorType()]);
1227
1228    str->append(" (");
1229    if (this->isOpaque()) {
1230        str->append("opaque");
1231    } else {
1232        str->append("transparent");
1233    }
1234    if (this->isImmutable()) {
1235        str->append(", immutable");
1236    } else {
1237        str->append(", not-immutable");
1238    }
1239    str->append(")");
1240
1241    SkPixelRef* pr = this->pixelRef();
1242    if (nullptr == pr) {
1243        // show null or the explicit pixel address (rare)
1244        str->appendf(" pixels:%p", this->getPixels());
1245    } else {
1246        const char* uri = pr->getURI();
1247        if (uri) {
1248            str->appendf(" uri:\"%s\"", uri);
1249        } else {
1250            str->appendf(" pixelref:%p", pr);
1251        }
1252    }
1253
1254    str->append(")");
1255}
1256#endif
1257
1258///////////////////////////////////////////////////////////////////////////////
1259
1260bool SkBitmap::requestLock(SkAutoPixmapUnlock* result) const {
1261    SkASSERT(result);
1262
1263    SkPixelRef* pr = fPixelRef;
1264    if (nullptr == pr) {
1265        return false;
1266    }
1267
1268    // We have to lock the whole thing (using the pixelref's dimensions) until the api supports
1269    // a partial lock (with offset/origin). Hence we can't use our fInfo.
1270    SkPixelRef::LockRequest req = { pr->info().dimensions(), kNone_SkFilterQuality };
1271    SkPixelRef::LockResult res;
1272    if (pr->requestLock(req, &res)) {
1273        SkASSERT(res.fPixels);
1274        // The bitmap may be a subset of the pixelref's dimensions
1275        SkASSERT(fPixelRefOrigin.x() + fInfo.width()  <= res.fSize.width());
1276        SkASSERT(fPixelRefOrigin.y() + fInfo.height() <= res.fSize.height());
1277        const void* addr = (const char*)res.fPixels + SkColorTypeComputeOffset(fInfo.colorType(),
1278                                                                               fPixelRefOrigin.x(),
1279                                                                               fPixelRefOrigin.y(),
1280                                                                               res.fRowBytes);
1281
1282        result->reset(SkPixmap(this->info(), addr, res.fRowBytes, res.fCTable),
1283                      res.fUnlockProc, res.fUnlockContext);
1284        return true;
1285    }
1286    return false;
1287}
1288
1289bool SkBitmap::peekPixels(SkPixmap* pmap) const {
1290    if (fPixels) {
1291        if (pmap) {
1292            pmap->reset(fInfo, fPixels, fRowBytes, fColorTable);
1293        }
1294        return true;
1295    }
1296    return false;
1297}
1298
1299///////////////////////////////////////////////////////////////////////////////
1300
1301#ifdef SK_DEBUG
1302void SkImageInfo::validate() const {
1303    SkASSERT(fWidth >= 0);
1304    SkASSERT(fHeight >= 0);
1305    SkASSERT(SkColorTypeIsValid(fColorType));
1306    SkASSERT(SkAlphaTypeIsValid(fAlphaType));
1307}
1308#endif
1309