SkImage.cpp revision ce02e7175872abde3721df9e5d3ec0ab8384cd8e
1/*
2 * Copyright 2012 Google Inc.
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 "SkBitmap.h"
9#include "SkBitmapCache.h"
10#include "SkCanvas.h"
11#include "SkData.h"
12#include "SkImageEncoder.h"
13#include "SkImageFilter.h"
14#include "SkImageFilterCache.h"
15#include "SkImageGenerator.h"
16#include "SkImagePriv.h"
17#include "SkImageShader.h"
18#include "SkImage_Base.h"
19#include "SkNextID.h"
20#include "SkPicture.h"
21#include "SkPixelRef.h"
22#include "SkPixelSerializer.h"
23#include "SkReadPixelsRec.h"
24#include "SkSpecialImage.h"
25#include "SkString.h"
26#include "SkSurface.h"
27
28#if SK_SUPPORT_GPU
29#include "GrTexture.h"
30#include "GrContext.h"
31#include "SkImage_Gpu.h"
32#endif
33
34SkImage::SkImage(int width, int height, uint32_t uniqueID)
35    : fWidth(width)
36    , fHeight(height)
37    , fUniqueID(kNeedNewImageUniqueID == uniqueID ? SkNextID::ImageID() : uniqueID)
38{
39    SkASSERT(width > 0);
40    SkASSERT(height > 0);
41}
42
43bool SkImage::peekPixels(SkPixmap* pm) const {
44    SkPixmap tmp;
45    if (!pm) {
46        pm = &tmp;
47    }
48    return as_IB(this)->onPeekPixels(pm);
49}
50
51#ifdef SK_SUPPORT_LEGACY_PEEKPIXELS_PARMS
52const void* SkImage::peekPixels(SkImageInfo* info, size_t* rowBytes) const {
53    SkPixmap pm;
54    if (this->peekPixels(&pm)) {
55        if (info) {
56            *info = pm.info();
57        }
58        if (rowBytes) {
59            *rowBytes = pm.rowBytes();
60        }
61        return pm.addr();
62    }
63    return nullptr;
64}
65#endif
66
67bool SkImage::readPixels(const SkImageInfo& dstInfo, void* dstPixels, size_t dstRowBytes,
68                           int srcX, int srcY, CachingHint chint) const {
69    SkReadPixelsRec rec(dstInfo, dstPixels, dstRowBytes, srcX, srcY);
70    if (!rec.trim(this->width(), this->height())) {
71        return false;
72    }
73    return as_IB(this)->onReadPixels(rec.fInfo, rec.fPixels, rec.fRowBytes, rec.fX, rec.fY, chint);
74}
75
76bool SkImage::scalePixels(const SkPixmap& dst, SkFilterQuality quality, CachingHint chint) const {
77    if (this->width() == dst.width() && this->height() == dst.height()) {
78        return this->readPixels(dst, 0, 0, chint);
79    }
80
81    // Idea: If/when SkImageGenerator supports a native-scaling API (where the generator itself
82    //       can scale more efficiently) we should take advantage of it here.
83    //
84    SkBitmap bm;
85    if (as_IB(this)->getROPixels(&bm, chint)) {
86        bm.lockPixels();
87        SkPixmap pmap;
88        // Note: By calling the pixmap scaler, we never cache the final result, so the chint
89        //       is (currently) only being applied to the getROPixels. If we get a request to
90        //       also attempt to cache the final (scaled) result, we would add that logic here.
91        //
92        return bm.peekPixels(&pmap) && pmap.scalePixels(dst, quality);
93    }
94    return false;
95}
96
97void SkImage::preroll(GrContext* ctx) const {
98    // For now, and to maintain parity w/ previous pixelref behavior, we just force the image
99    // to produce a cached raster-bitmap form, so that drawing to a raster canvas should be fast.
100    //
101    SkBitmap bm;
102    if (as_IB(this)->getROPixels(&bm)) {
103        bm.lockPixels();
104        bm.unlockPixels();
105    }
106}
107
108///////////////////////////////////////////////////////////////////////////////////////////////////
109
110SkAlphaType SkImage::alphaType() const {
111    return as_IB(this)->onAlphaType();
112}
113
114sk_sp<SkShader> SkImage::makeShader(SkShader::TileMode tileX, SkShader::TileMode tileY,
115                                    const SkMatrix* localMatrix) const {
116    return SkImageShader::Make(sk_ref_sp(const_cast<SkImage*>(this)), tileX, tileY, localMatrix);
117}
118
119#ifdef SK_SUPPORT_LEGACY_CREATESHADER_PTR
120SkShader* SkImage::newShader(SkShader::TileMode tileX, SkShader::TileMode tileY,
121                             const SkMatrix* localMatrix) const {
122    return this->makeShader(tileX, tileY, localMatrix).release();
123}
124#endif
125
126SkData* SkImage::encode(SkImageEncoder::Type type, int quality) const {
127    SkBitmap bm;
128    if (as_IB(this)->getROPixels(&bm)) {
129        return SkImageEncoder::EncodeData(bm, type, quality);
130    }
131    return nullptr;
132}
133
134SkData* SkImage::encode(SkPixelSerializer* serializer) const {
135    SkAutoTUnref<SkPixelSerializer> defaultSerializer;
136    SkPixelSerializer* effectiveSerializer = serializer;
137    if (!effectiveSerializer) {
138        defaultSerializer.reset(SkImageEncoder::CreatePixelSerializer());
139        SkASSERT(defaultSerializer.get());
140        effectiveSerializer = defaultSerializer.get();
141    }
142    sk_sp<SkData> encoded(this->refEncoded());
143    if (encoded && effectiveSerializer->useEncodedData(encoded->data(), encoded->size())) {
144        return encoded.release();
145    }
146
147    SkBitmap bm;
148    SkAutoPixmapUnlock apu;
149    if (as_IB(this)->getROPixels(&bm) && bm.requestLock(&apu)) {
150        return effectiveSerializer->encode(apu.pixmap());
151    }
152
153    return nullptr;
154}
155
156SkData* SkImage::refEncoded() const {
157    GrContext* ctx = nullptr;   // should we allow the caller to pass in a ctx?
158    return as_IB(this)->onRefEncoded(ctx);
159}
160
161sk_sp<SkImage> SkImage::MakeFromEncoded(sk_sp<SkData> encoded, const SkIRect* subset) {
162    if (nullptr == encoded || 0 == encoded->size()) {
163        return nullptr;
164    }
165    SkImageGenerator* generator = SkImageGenerator::NewFromEncoded(encoded.get());
166    return SkImage::MakeFromGenerator(generator, subset);
167}
168
169const char* SkImage::toString(SkString* str) const {
170    str->appendf("image: (id:%d (%d, %d) %s)", this->uniqueID(), this->width(), this->height(),
171                 this->isOpaque() ? "opaque" : "");
172    return str->c_str();
173}
174
175sk_sp<SkImage> SkImage::makeSubset(const SkIRect& subset) const {
176    if (subset.isEmpty()) {
177        return nullptr;
178    }
179
180    const SkIRect bounds = SkIRect::MakeWH(this->width(), this->height());
181    if (!bounds.contains(subset)) {
182        return nullptr;
183    }
184
185    // optimization : return self if the subset == our bounds
186    if (bounds == subset) {
187        return sk_ref_sp(const_cast<SkImage*>(this));
188    }
189    return as_IB(this)->onMakeSubset(subset);
190}
191
192#if SK_SUPPORT_GPU
193
194GrTexture* SkImage::getTexture() const {
195    return as_IB(this)->peekTexture();
196}
197
198bool SkImage::isTextureBacked() const { return SkToBool(as_IB(this)->peekTexture()); }
199
200GrBackendObject SkImage::getTextureHandle(bool flushPendingGrContextIO) const {
201    GrTexture* texture = as_IB(this)->peekTexture();
202    if (texture) {
203        GrContext* context = texture->getContext();
204        if (context) {
205            if (flushPendingGrContextIO) {
206                context->prepareSurfaceForExternalIO(texture);
207            }
208        }
209        return texture->getTextureHandle();
210    }
211    return 0;
212}
213
214#else
215
216GrTexture* SkImage::getTexture() const { return nullptr; }
217
218bool SkImage::isTextureBacked() const { return false; }
219
220GrBackendObject SkImage::getTextureHandle(bool) const { return 0; }
221
222#endif
223
224///////////////////////////////////////////////////////////////////////////////
225
226static bool raster_canvas_supports(const SkImageInfo& info) {
227    switch (info.colorType()) {
228        case kN32_SkColorType:
229            return kUnpremul_SkAlphaType != info.alphaType();
230        case kRGB_565_SkColorType:
231            return true;
232        case kAlpha_8_SkColorType:
233            return true;
234        default:
235            break;
236    }
237    return false;
238}
239
240SkImage_Base::SkImage_Base(int width, int height, uint32_t uniqueID)
241    : INHERITED(width, height, uniqueID)
242    , fAddedToCache(false)
243{}
244
245SkImage_Base::~SkImage_Base() {
246    if (fAddedToCache.load()) {
247        SkNotifyBitmapGenIDIsStale(this->uniqueID());
248    }
249}
250
251bool SkImage_Base::onReadPixels(const SkImageInfo& dstInfo, void* dstPixels, size_t dstRowBytes,
252                                int srcX, int srcY, CachingHint) const {
253    if (!raster_canvas_supports(dstInfo)) {
254        return false;
255    }
256
257    SkBitmap bm;
258    bm.installPixels(dstInfo, dstPixels, dstRowBytes);
259    SkCanvas canvas(bm);
260
261    SkPaint paint;
262    paint.setXfermodeMode(SkXfermode::kSrc_Mode);
263    canvas.drawImage(this, -SkIntToScalar(srcX), -SkIntToScalar(srcY), &paint);
264
265    return true;
266}
267
268///////////////////////////////////////////////////////////////////////////////////////////////////
269
270bool SkImage::readPixels(const SkPixmap& pmap, int srcX, int srcY, CachingHint chint) const {
271    return this->readPixels(pmap.info(), pmap.writable_addr(), pmap.rowBytes(), srcX, srcY, chint);
272}
273
274#if SK_SUPPORT_GPU
275#include "GrTextureToYUVPlanes.h"
276#endif
277
278#include "SkRGBAToYUV.h"
279
280bool SkImage::readYUV8Planes(const SkISize sizes[3], void* const planes[3],
281                             const size_t rowBytes[3], SkYUVColorSpace colorSpace) const {
282#if SK_SUPPORT_GPU
283    if (GrTexture* texture = as_IB(this)->peekTexture()) {
284        if (GrTextureToYUVPlanes(texture, sizes, planes, rowBytes, colorSpace)) {
285            return true;
286        }
287    }
288#endif
289    return SkRGBAToYUV(this, sizes, planes, rowBytes, colorSpace);
290}
291
292///////////////////////////////////////////////////////////////////////////////////////////////////
293
294sk_sp<SkImage> SkImage::MakeFromBitmap(const SkBitmap& bm) {
295    SkPixelRef* pr = bm.pixelRef();
296    if (nullptr == pr) {
297        return nullptr;
298    }
299
300    return SkMakeImageFromRasterBitmap(bm, kIfMutable_SkCopyPixelsMode);
301}
302
303bool SkImage::asLegacyBitmap(SkBitmap* bitmap, LegacyBitmapMode mode) const {
304    return as_IB(this)->onAsLegacyBitmap(bitmap, mode);
305}
306
307bool SkImage_Base::onAsLegacyBitmap(SkBitmap* bitmap, LegacyBitmapMode mode) const {
308    // As the base-class, all we can do is make a copy (regardless of mode).
309    // Subclasses that want to be more optimal should override.
310    SkImageInfo info = this->onImageInfo().makeColorType(kN32_SkColorType)
311            .makeAlphaType(this->alphaType());
312    if (!bitmap->tryAllocPixels(info)) {
313        return false;
314    }
315    if (!this->readPixels(bitmap->info(), bitmap->getPixels(), bitmap->rowBytes(), 0, 0)) {
316        bitmap->reset();
317        return false;
318    }
319
320    if (kRO_LegacyBitmapMode == mode) {
321        bitmap->setImmutable();
322    }
323    return true;
324}
325
326sk_sp<SkImage> SkImage::MakeFromPicture(sk_sp<SkPicture> picture, const SkISize& dimensions,
327                                        const SkMatrix* matrix, const SkPaint* paint) {
328    if (!picture) {
329        return nullptr;
330    }
331    return MakeFromGenerator(SkImageGenerator::NewFromPicture(dimensions, picture.get(),
332                                                              matrix, paint));
333}
334
335sk_sp<SkImage> SkImage::makeWithFilter(const SkImageFilter* filter, const SkIRect& subset,
336                                       const SkIRect& clipBounds, SkIRect* outSubset,
337                                       SkIPoint* offset) const {
338    if (!filter || !outSubset || !offset || !this->bounds().contains(subset)) {
339        return nullptr;
340    }
341    sk_sp<SkSpecialImage> srcSpecialImage = SkSpecialImage::MakeFromImage(
342        subset, sk_ref_sp(const_cast<SkImage*>(this)));
343    if (!srcSpecialImage) {
344        return nullptr;
345    }
346
347    SkAutoTUnref<SkImageFilterCache> cache(
348        SkImageFilterCache::Create(SkImageFilterCache::kDefaultTransientSize));
349    SkImageFilter::OutputProperties outputProperties(as_IB(this)->onImageInfo().colorSpace());
350    SkImageFilter::Context context(SkMatrix::I(), clipBounds, cache.get(), outputProperties);
351
352    sk_sp<SkSpecialImage> result =
353        filter->filterImage(srcSpecialImage.get(), context, offset);
354
355    if (!result) {
356        return nullptr;
357    }
358
359    SkIRect fullSize = SkIRect::MakeWH(result->width(), result->height());
360#if SK_SUPPORT_GPU
361    if (result->isTextureBacked()) {
362        GrContext* context = result->getContext();
363        sk_sp<GrTexture> texture = result->asTextureRef(context);
364        fullSize = SkIRect::MakeWH(texture->width(), texture->height());
365    }
366#endif
367    *outSubset = SkIRect::MakeWH(result->width(), result->height());
368    if (!outSubset->intersect(clipBounds.makeOffset(-offset->x(), -offset->y()))) {
369        return nullptr;
370    }
371    offset->fX += outSubset->x();
372    offset->fY += outSubset->y();
373    // This isn't really a "tight" subset, but includes any texture padding.
374    return result->makeTightSubset(fullSize);
375}
376
377bool SkImage::isLazyGenerated() const {
378    return as_IB(this)->onIsLazyGenerated();
379}
380
381//////////////////////////////////////////////////////////////////////////////////////
382
383#if !SK_SUPPORT_GPU
384
385sk_sp<SkImage> SkImage::MakeTextureFromPixmap(GrContext*, const SkPixmap&, SkBudgeted budgeted) {
386    return nullptr;
387}
388
389sk_sp<SkImage> MakeTextureFromMipMap(GrContext*, const SkImageInfo&, const GrMipLevel* texels,
390                                     int mipLevelCount, SkBudgeted, SkSourceGammaTreatment) {
391    return nullptr;
392}
393
394sk_sp<SkImage> SkImage::MakeFromTexture(GrContext*, const GrBackendTextureDesc&, SkAlphaType,
395                                        sk_sp<SkColorSpace>, TextureReleaseProc, ReleaseContext) {
396    return nullptr;
397}
398
399size_t SkImage::getDeferredTextureImageData(const GrContextThreadSafeProxy&,
400                                            const DeferredTextureImageUsageParams[],
401                                            int paramCnt, void* buffer,
402                                            SkSourceGammaTreatment treatment) const {
403    return 0;
404}
405
406sk_sp<SkImage> SkImage::MakeFromDeferredTextureImageData(GrContext* context, const void*,
407                                                         SkBudgeted) {
408    return nullptr;
409}
410
411sk_sp<SkImage> SkImage::MakeFromAdoptedTexture(GrContext*, const GrBackendTextureDesc&,
412                                               SkAlphaType, sk_sp<SkColorSpace>) {
413    return nullptr;
414}
415
416sk_sp<SkImage> SkImage::MakeFromYUVTexturesCopy(GrContext* ctx, SkYUVColorSpace space,
417                                                const GrBackendObject yuvTextureHandles[3],
418                                                const SkISize yuvSizes[3],
419                                                GrSurfaceOrigin origin,
420                                                sk_sp<SkColorSpace> imageColorSpace) {
421    return nullptr;
422}
423
424sk_sp<SkImage> SkImage::makeTextureImage(GrContext*) const {
425    return nullptr;
426}
427
428sk_sp<SkImage> SkImage::makeNonTextureImage() const {
429    return sk_ref_sp(const_cast<SkImage*>(this));
430}
431
432#endif
433
434///////////////////////////////////////////////////////////////////////////////////////////////////
435
436#ifdef SK_SUPPORT_LEGACY_IMAGEFACTORY
437SkImage* SkImage::NewRasterCopy(const Info& info, const void* pixels, size_t rowBytes,
438                                SkColorTable* ctable) {
439    return MakeRasterCopy(SkPixmap(info, pixels, rowBytes, ctable)).release();
440}
441
442SkImage* SkImage::NewRasterData(const Info& info, SkData* pixels, size_t rowBytes) {
443    return MakeRasterData(info, sk_ref_sp(pixels), rowBytes).release();
444}
445
446SkImage* SkImage::NewFromRaster(const Info& info, const void* pixels, size_t rowBytes,
447                                RasterReleaseProc proc, ReleaseContext releasectx) {
448    return MakeFromRaster(SkPixmap(info, pixels, rowBytes), proc, releasectx).release();
449}
450
451SkImage* SkImage::NewFromBitmap(const SkBitmap& bm) {
452    return MakeFromBitmap(bm).release();
453}
454
455SkImage* SkImage::NewFromGenerator(SkImageGenerator* gen, const SkIRect* subset) {
456    return MakeFromGenerator(gen, subset).release();
457}
458
459SkImage* SkImage::NewFromEncoded(SkData* encoded, const SkIRect* subset) {
460    return MakeFromEncoded(sk_ref_sp(encoded), subset).release();
461}
462
463SkImage* SkImage::NewFromTexture(GrContext* ctx, const GrBackendTextureDesc& desc, SkAlphaType at,
464                                 TextureReleaseProc proc, ReleaseContext releasectx) {
465    return MakeFromTexture(ctx, desc, at, proc, releasectx).release();
466}
467
468SkImage* SkImage::NewFromAdoptedTexture(GrContext* ctx, const GrBackendTextureDesc& desc,
469                                        SkAlphaType at) {
470    return MakeFromAdoptedTexture(ctx, desc, at).release();
471}
472
473SkImage* SkImage::NewFromYUVTexturesCopy(GrContext* ctx, SkYUVColorSpace space,
474                                         const GrBackendObject yuvTextureHandles[3],
475                                         const SkISize yuvSizes[3],
476                                         GrSurfaceOrigin origin) {
477    return MakeFromYUVTexturesCopy(ctx, space, yuvTextureHandles, yuvSizes, origin).release();
478}
479
480SkImage* SkImage::NewFromPicture(const SkPicture* picture, const SkISize& dimensions,
481                                 const SkMatrix* matrix, const SkPaint* paint) {
482    return MakeFromPicture(sk_ref_sp(const_cast<SkPicture*>(picture)), dimensions,
483                                     matrix, paint).release();
484}
485
486SkImage* SkImage::NewTextureFromPixmap(GrContext* ctx, const SkPixmap& pmap, SkBudgeted budgeted) {
487    return MakeTextureFromPixmap(ctx, pmap, budgeted).release();
488}
489
490SkImage* SkImage::NewFromDeferredTextureImageData(GrContext* ctx, const void* data,
491                                                  SkBudgeted budgeted) {
492    return MakeFromDeferredTextureImageData(ctx, data, budgeted).release();
493}
494#endif
495
496sk_sp<SkImage> MakeTextureFromMipMap(GrContext*, const SkImageInfo&, const GrMipLevel* texels,
497                                     int mipLevelCount, SkBudgeted) {
498    return nullptr;
499}
500
501///////////////////////////////////////////////////////////////////////////////////////////////////
502#include "SkImageDeserializer.h"
503
504sk_sp<SkImage> SkImageDeserializer::makeFromData(SkData* data, const SkIRect* subset) {
505    return SkImage::MakeFromEncoded(sk_ref_sp(data), subset);
506}
507sk_sp<SkImage> SkImageDeserializer::makeFromMemory(const void* data, size_t length,
508                                                   const SkIRect* subset) {
509    return SkImage::MakeFromEncoded(SkData::MakeWithCopy(data, length), subset);
510}
511
512///////////////////////////////////////////////////////////////////////////////////////////////////
513
514void SkImage_pinAsTexture(const SkImage* image, GrContext* ctx) {
515    SkASSERT(image);
516    SkASSERT(ctx);
517    as_IB(image)->onPinAsTexture(ctx);
518}
519
520void SkImage_unpinAsTexture(const SkImage* image, GrContext* ctx) {
521    SkASSERT(image);
522    SkASSERT(ctx);
523    as_IB(image)->onUnpinAsTexture(ctx);
524}
525