blob: 09130a6b76602e4755830e6fd78b7ad8d38de5e4 [file] [log] [blame]
reed85d91782015-09-10 14:33:38 -07001/*
2 * Copyright 2015 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 "SkImage_Base.h"
reed85d91782015-09-10 14:33:38 -07009#include "SkImageCacherator.h"
Brian Osmandf7e0752017-04-26 16:20:28 -040010
11#include "SkBitmap.h"
12#include "SkBitmapCache.h"
13#include "SkColorSpace_Base.h"
14#include "SkData.h"
15#include "SkImageGenerator.h"
reed85d91782015-09-10 14:33:38 -070016#include "SkImagePriv.h"
Brian Osmandf7e0752017-04-26 16:20:28 -040017#include "SkNextID.h"
reed85d91782015-09-10 14:33:38 -070018#include "SkPixelRef.h"
reed85d91782015-09-10 14:33:38 -070019
Brian Osmandf7e0752017-04-26 16:20:28 -040020#if SK_SUPPORT_GPU
21#include "GrContext.h"
22#include "GrContextPriv.h"
23#include "GrGpuResourcePriv.h"
24#include "GrImageTextureMaker.h"
25#include "GrResourceKey.h"
26#include "GrResourceProvider.h"
27#include "GrSamplerParams.h"
28#include "GrYUVProvider.h"
29#include "SkGr.h"
30#endif
reed85d91782015-09-10 14:33:38 -070031
Brian Osmandf7e0752017-04-26 16:20:28 -040032// Ref-counted tuple(SkImageGenerator, SkMutex) which allows sharing one generator among N images
33class SharedGenerator final : public SkNVRefCnt<SharedGenerator> {
34public:
35 static sk_sp<SharedGenerator> Make(std::unique_ptr<SkImageGenerator> gen) {
36 return gen ? sk_sp<SharedGenerator>(new SharedGenerator(std::move(gen))) : nullptr;
37 }
38
Matt Sarettb2004f72017-05-18 09:26:50 -040039 // This is thread safe. It is a const field set in the constructor.
40 const SkImageInfo& getInfo() { return fGenerator->getInfo(); }
41
Brian Osmandf7e0752017-04-26 16:20:28 -040042private:
43 explicit SharedGenerator(std::unique_ptr<SkImageGenerator> gen)
44 : fGenerator(std::move(gen)) {
45 SkASSERT(fGenerator);
46 }
47
48 friend class ScopedGenerator;
49 friend class SkImage_Lazy;
50
51 std::unique_ptr<SkImageGenerator> fGenerator;
52 SkMutex fMutex;
53};
54
55class SkImage_Lazy : public SkImage_Base, public SkImageCacherator {
56public:
57 struct Validator {
Christopher Cameron77e96662017-07-08 01:47:47 -070058 Validator(sk_sp<SharedGenerator>, const SkIRect* subset, sk_sp<SkColorSpace> colorSpace);
Brian Osmandf7e0752017-04-26 16:20:28 -040059
60 operator bool() const { return fSharedGenerator.get(); }
61
62 sk_sp<SharedGenerator> fSharedGenerator;
63 SkImageInfo fInfo;
64 SkIPoint fOrigin;
Christopher Cameron77e96662017-07-08 01:47:47 -070065 sk_sp<SkColorSpace> fColorSpace;
Brian Osmandf7e0752017-04-26 16:20:28 -040066 uint32_t fUniqueID;
67 };
68
69 SkImage_Lazy(Validator* validator);
70
71 SkImageInfo onImageInfo() const override {
72 return fInfo;
herba7c9d632016-04-19 12:30:22 -070073 }
brianosman69c166d2016-08-17 14:01:05 -070074 SkAlphaType onAlphaType() const override {
Brian Osmandf7e0752017-04-26 16:20:28 -040075 return fInfo.alphaType();
brianosman69c166d2016-08-17 14:01:05 -070076 }
herba7c9d632016-04-19 12:30:22 -070077
Robert Phillipsb726d582017-03-09 16:36:32 -050078 bool onReadPixels(const SkImageInfo&, void*, size_t, int srcX, int srcY,
79 CachingHint) const override;
80#if SK_SUPPORT_GPU
81 sk_sp<GrTextureProxy> asTextureProxyRef(GrContext*, const GrSamplerParams&,
82 SkColorSpace*, sk_sp<SkColorSpace>*,
83 SkScalar scaleAdjust[2]) const override;
84#endif
Brian Osman47858972017-04-25 10:02:12 -040085 SkData* onRefEncoded() const override;
reed7fb4f8b2016-03-11 04:33:52 -080086 sk_sp<SkImage> onMakeSubset(const SkIRect&) const override;
Brian Osman61624f02016-12-09 14:51:59 -050087 bool getROPixels(SkBitmap*, SkColorSpace* dstColorSpace, CachingHint) const override;
reed85d91782015-09-10 14:33:38 -070088 bool onIsLazyGenerated() const override { return true; }
Mike Reed7f1d0202017-05-08 16:13:39 -040089 bool onCanLazyGenerateOnGPU() const override;
Matt Sarett9f3dcb32017-05-04 08:53:32 -040090 sk_sp<SkImage> onMakeColorSpace(sk_sp<SkColorSpace>, SkColorType,
91 SkTransferFunctionBehavior) const override;
reed85d91782015-09-10 14:33:38 -070092
Brian Osman5bbd0762017-05-08 11:07:42 -040093 bool onIsValid(GrContext*) const override;
94
Brian Osmandf7e0752017-04-26 16:20:28 -040095 SkImageCacherator* peekCacherator() const override {
96 return const_cast<SkImage_Lazy*>(this);
97 }
98
99 // Only return true if the generate has already been cached.
100 bool lockAsBitmapOnlyIfAlreadyCached(SkBitmap*, CachedFormat) const;
101 // Call the underlying generator directly
102 bool directGeneratePixels(const SkImageInfo& dstInfo, void* dstPixels, size_t dstRB,
103 int srcX, int srcY, SkTransferFunctionBehavior behavior) const;
104
105 // SkImageCacherator interface
106#if SK_SUPPORT_GPU
107 // Returns the texture proxy. If the cacherator is generating the texture and wants to cache it,
108 // it should use the passed in key (if the key is valid).
109 sk_sp<GrTextureProxy> lockTextureProxy(GrContext*,
110 const GrUniqueKey& key,
111 SkImage::CachingHint,
112 bool willBeMipped,
Stan Ilievba81af22017-06-08 15:16:53 -0400113 SkColorSpace* dstColorSpace,
114 GrTextureMaker::AllowedTexGenType genType) override;
Brian Osmandf7e0752017-04-26 16:20:28 -0400115
116 // Returns the color space of the texture that would be returned if you called lockTexture.
117 // Separate code path to allow querying of the color space for textures that cached (even
118 // externally).
119 sk_sp<SkColorSpace> getColorSpace(GrContext*, SkColorSpace* dstColorSpace) override;
120 void makeCacheKeyFromOrigKey(const GrUniqueKey& origKey, CachedFormat,
121 GrUniqueKey* cacheKey) override;
122#endif
123
124 CachedFormat chooseCacheFormat(SkColorSpace* dstColorSpace,
125 const GrCaps* = nullptr) const override;
126 SkImageInfo buildCacheInfo(CachedFormat) const override;
127
reed85d91782015-09-10 14:33:38 -0700128private:
Brian Osmandf7e0752017-04-26 16:20:28 -0400129 class ScopedGenerator;
130
131 /**
132 * On success (true), bitmap will point to the pixels for this generator. If this returns
133 * false, the bitmap will be reset to empty.
134 */
Christopher Cameron77e96662017-07-08 01:47:47 -0700135 bool lockAsBitmap(SkBitmap*, SkImage::CachingHint, CachedFormat, const SkImageInfo&,
136 SkTransferFunctionBehavior) const;
137
138 /**
139 * Populates parameters to pass to the generator for reading pixels or generating a texture.
140 * For image generators, legacy versus true color blending is indicated using a
141 * SkTransferFunctionBehavior, and the target color space is specified on the SkImageInfo.
142 * If generatorImageInfo has no color space set, set its color space to this SkImage's color
143 * space, and return "ignore" behavior, indicating legacy mode. If generatorImageInfo has a
144 * color space set, return "respect" behavior, indicating linear blending mode.
145 */
146 SkTransferFunctionBehavior getGeneratorBehaviorAndInfo(SkImageInfo* generatorImageInfo) const;
Brian Osmandf7e0752017-04-26 16:20:28 -0400147
148 sk_sp<SharedGenerator> fSharedGenerator;
Christopher Cameron77e96662017-07-08 01:47:47 -0700149 // Note that fInfo is not necessarily the info from the generator. It may be cropped by
150 // onMakeSubset and its color space may be changed by onMakeColorSpace.
Brian Osmandf7e0752017-04-26 16:20:28 -0400151 const SkImageInfo fInfo;
152 const SkIPoint fOrigin;
153
154 struct IDRec {
155 SkOnce fOnce;
156 uint32_t fUniqueID;
157 };
158 mutable IDRec fIDRecs[kNumCachedFormats];
159
160 uint32_t getUniqueID(CachedFormat) const;
reed85d91782015-09-10 14:33:38 -0700161
162 typedef SkImage_Base INHERITED;
163};
164
165///////////////////////////////////////////////////////////////////////////////
166
Christopher Cameron77e96662017-07-08 01:47:47 -0700167SkImage_Lazy::Validator::Validator(sk_sp<SharedGenerator> gen, const SkIRect* subset,
168 sk_sp<SkColorSpace> colorSpace)
Brian Osmandf7e0752017-04-26 16:20:28 -0400169 : fSharedGenerator(std::move(gen)) {
Brian Osmandf7e0752017-04-26 16:20:28 -0400170 if (!fSharedGenerator) {
171 return;
172 }
173
174 // The following generator accessors are safe without acquiring the mutex (const getters).
175 // TODO: refactor to use a ScopedGenerator instead, for clarity.
176 const SkImageInfo& info = fSharedGenerator->fGenerator->getInfo();
177 if (info.isEmpty()) {
178 fSharedGenerator.reset();
179 return;
180 }
181
182 fUniqueID = fSharedGenerator->fGenerator->uniqueID();
183 const SkIRect bounds = SkIRect::MakeWH(info.width(), info.height());
184 if (subset) {
185 if (!bounds.contains(*subset)) {
186 fSharedGenerator.reset();
187 return;
188 }
189 if (*subset != bounds) {
190 // we need a different uniqueID since we really are a subset of the raw generator
191 fUniqueID = SkNextID::ImageID();
192 }
193 } else {
194 subset = &bounds;
195 }
196
197 fInfo = info.makeWH(subset->width(), subset->height());
198 fOrigin = SkIPoint::Make(subset->x(), subset->y());
Christopher Cameron77e96662017-07-08 01:47:47 -0700199 if (colorSpace) {
200 fInfo = fInfo.makeColorSpace(colorSpace);
201 fUniqueID = SkNextID::ImageID();
202 }
Brian Osmandf7e0752017-04-26 16:20:28 -0400203
204 // colortables are poorly to not-at-all supported in our resourcecache, so we
205 // bully them into N32 (the generator will perform the up-sample)
206 if (fInfo.colorType() == kIndex_8_SkColorType) {
207 fInfo = fInfo.makeColorType(kN32_SkColorType);
208 }
209}
210
211///////////////////////////////////////////////////////////////////////////////
212
213// Helper for exclusive access to a shared generator.
214class SkImage_Lazy::ScopedGenerator {
215public:
216 ScopedGenerator(const sk_sp<SharedGenerator>& gen)
217 : fSharedGenerator(gen)
218 , fAutoAquire(gen->fMutex) {}
219
220 SkImageGenerator* operator->() const {
221 fSharedGenerator->fMutex.assertHeld();
222 return fSharedGenerator->fGenerator.get();
223 }
224
225 operator SkImageGenerator*() const {
226 fSharedGenerator->fMutex.assertHeld();
227 return fSharedGenerator->fGenerator.get();
228 }
229
230private:
231 const sk_sp<SharedGenerator>& fSharedGenerator;
232 SkAutoExclusive fAutoAquire;
233};
234
235///////////////////////////////////////////////////////////////////////////////
236
237SkImage_Lazy::SkImage_Lazy(Validator* validator)
238 : INHERITED(validator->fInfo.width(), validator->fInfo.height(), validator->fUniqueID)
239 , fSharedGenerator(std::move(validator->fSharedGenerator))
240 , fInfo(validator->fInfo)
241 , fOrigin(validator->fOrigin) {
242 SkASSERT(fSharedGenerator);
243 SkASSERT(kIndex_8_SkColorType != fInfo.colorType());
244 // We explicit set the legacy format slot, but leave the others uninitialized (via SkOnce)
245 // and only resolove them to IDs as needed (by calling getUniqueID()).
246 fIDRecs[kLegacy_CachedFormat].fOnce([this, validator] {
247 fIDRecs[kLegacy_CachedFormat].fUniqueID = validator->fUniqueID;
248 });
249}
250
251uint32_t SkImage_Lazy::getUniqueID(CachedFormat format) const {
252 IDRec* rec = &fIDRecs[format];
253 rec->fOnce([rec] {
254 rec->fUniqueID = SkNextID::ImageID();
255 });
256 return rec->fUniqueID;
257}
258
259//////////////////////////////////////////////////////////////////////////////////////////////////
260
261// Abstraction of GrCaps that handles the cases where we don't have a caps pointer (because
262// we're in raster mode), or where GPU support is entirely missing. In theory, we only need the
263// chosen format to be texturable, but that lets us choose F16 on GLES implemenations where we
264// won't be able to read the texture back. We'd like to ensure that SkImake::makeNonTextureImage
265// works, so we require that the formats we choose are renderable (as a proxy for being readable).
266struct CacheCaps {
267 CacheCaps(const GrCaps* caps) : fCaps(caps) {}
268
269#if SK_SUPPORT_GPU
270 bool supportsHalfFloat() const {
271 return !fCaps ||
272 (fCaps->isConfigTexturable(kRGBA_half_GrPixelConfig) &&
273 fCaps->isConfigRenderable(kRGBA_half_GrPixelConfig, false));
274 }
275
276 bool supportsSRGB() const {
277 return !fCaps ||
278 (fCaps->srgbSupport() && fCaps->isConfigTexturable(kSRGBA_8888_GrPixelConfig));
279 }
280
281 bool supportsSBGR() const {
282 return !fCaps || fCaps->srgbSupport();
283 }
284#else
285 bool supportsHalfFloat() const { return true; }
286 bool supportsSRGB() const { return true; }
287 bool supportsSBGR() const { return true; }
288#endif
289
290 const GrCaps* fCaps;
291};
292
293SkImageCacherator::CachedFormat SkImage_Lazy::chooseCacheFormat(SkColorSpace* dstColorSpace,
294 const GrCaps* grCaps) const {
295 SkColorSpace* cs = fInfo.colorSpace();
296 if (!cs || !dstColorSpace) {
297 return kLegacy_CachedFormat;
298 }
299
300 CacheCaps caps(grCaps);
301 switch (fInfo.colorType()) {
302 case kUnknown_SkColorType:
303 case kAlpha_8_SkColorType:
304 case kRGB_565_SkColorType:
305 case kARGB_4444_SkColorType:
306 // We don't support color space on these formats, so always decode in legacy mode:
307 // TODO: Ask the codec to decode these to something else (at least sRGB 8888)?
308 return kLegacy_CachedFormat;
309
310 case kIndex_8_SkColorType:
311 SkDEBUGFAIL("Index_8 should have been remapped at construction time.");
312 return kLegacy_CachedFormat;
313
314 case kGray_8_SkColorType:
315 // TODO: What do we do with grayscale sources that have strange color spaces attached?
316 // The codecs and color space xform don't handle this correctly (yet), so drop it on
317 // the floor. (Also, inflating by a factor of 8 is going to be unfortunate).
318 // As it is, we don't directly support sRGB grayscale, so ask the codec to convert
319 // it for us. This bypasses some really sketchy code GrUploadPixmapToTexture.
320 if (cs->gammaCloseToSRGB() && caps.supportsSRGB()) {
321 return kSRGB8888_CachedFormat;
322 } else {
323 return kLegacy_CachedFormat;
324 }
325
326 case kRGBA_8888_SkColorType:
327 if (cs->gammaCloseToSRGB()) {
328 if (caps.supportsSRGB()) {
329 return kSRGB8888_CachedFormat;
330 } else if (caps.supportsHalfFloat()) {
331 return kLinearF16_CachedFormat;
332 } else {
333 return kLegacy_CachedFormat;
334 }
335 } else {
336 if (caps.supportsHalfFloat()) {
337 return kLinearF16_CachedFormat;
338 } else if (caps.supportsSRGB()) {
339 return kSRGB8888_CachedFormat;
340 } else {
341 return kLegacy_CachedFormat;
342 }
343 }
344
345 case kBGRA_8888_SkColorType:
346 // Odd case. sBGRA isn't a real thing, so we may not have this texturable.
347 if (caps.supportsSBGR()) {
348 if (cs->gammaCloseToSRGB()) {
349 return kSBGR8888_CachedFormat;
350 } else if (caps.supportsHalfFloat()) {
351 return kLinearF16_CachedFormat;
352 } else if (caps.supportsSRGB()) {
353 return kSRGB8888_CachedFormat;
354 } else {
355 // sBGRA support without sRGBA is highly unlikely (impossible?) Nevertheless.
356 return kLegacy_CachedFormat;
357 }
358 } else {
359 if (cs->gammaCloseToSRGB()) {
360 if (caps.supportsSRGB()) {
361 return kSRGB8888_CachedFormat;
362 } else if (caps.supportsHalfFloat()) {
363 return kLinearF16_CachedFormat;
364 } else {
365 return kLegacy_CachedFormat;
366 }
367 } else {
368 if (caps.supportsHalfFloat()) {
369 return kLinearF16_CachedFormat;
370 } else if (caps.supportsSRGB()) {
371 return kSRGB8888_CachedFormat;
372 } else {
373 return kLegacy_CachedFormat;
374 }
375 }
376 }
377
378 case kRGBA_F16_SkColorType:
379 if (caps.supportsHalfFloat()) {
380 return kLinearF16_CachedFormat;
381 } else if (caps.supportsSRGB()) {
382 return kSRGB8888_CachedFormat;
383 } else {
384 return kLegacy_CachedFormat;
385 }
386 }
387 SkDEBUGFAIL("Unreachable");
388 return kLegacy_CachedFormat;
389}
390
391SkImageInfo SkImage_Lazy::buildCacheInfo(CachedFormat format) const {
392 switch (format) {
393 case kLegacy_CachedFormat:
394 return fInfo.makeColorSpace(nullptr);
395 case kLinearF16_CachedFormat:
396 return fInfo.makeColorType(kRGBA_F16_SkColorType)
397 .makeColorSpace(as_CSB(fInfo.colorSpace())->makeLinearGamma());
398 case kSRGB8888_CachedFormat:
399 // If the transfer function is nearly (but not exactly) sRGB, we don't want the codec
400 // to bother trans-coding. It would be slow, and do more harm than good visually,
401 // so we make sure to leave the colorspace as-is.
402 if (fInfo.colorSpace()->gammaCloseToSRGB()) {
403 return fInfo.makeColorType(kRGBA_8888_SkColorType);
404 } else {
405 return fInfo.makeColorType(kRGBA_8888_SkColorType)
406 .makeColorSpace(as_CSB(fInfo.colorSpace())->makeSRGBGamma());
407 }
408 case kSBGR8888_CachedFormat:
409 // See note above about not-quite-sRGB transfer functions.
410 if (fInfo.colorSpace()->gammaCloseToSRGB()) {
411 return fInfo.makeColorType(kBGRA_8888_SkColorType);
412 } else {
413 return fInfo.makeColorType(kBGRA_8888_SkColorType)
414 .makeColorSpace(as_CSB(fInfo.colorSpace())->makeSRGBGamma());
415 }
416 default:
417 SkDEBUGFAIL("Invalid cached format");
418 return fInfo;
419 }
420}
421
422//////////////////////////////////////////////////////////////////////////////////////////////////
423
424static bool check_output_bitmap(const SkBitmap& bitmap, uint32_t expectedID) {
425 SkASSERT(bitmap.getGenerationID() == expectedID);
426 SkASSERT(bitmap.isImmutable());
427 SkASSERT(bitmap.getPixels());
428 return true;
429}
430
431bool SkImage_Lazy::directGeneratePixels(const SkImageInfo& info, void* pixels, size_t rb,
432 int srcX, int srcY,
433 SkTransferFunctionBehavior behavior) const {
434 ScopedGenerator generator(fSharedGenerator);
435 const SkImageInfo& genInfo = generator->getInfo();
436 // Currently generators do not natively handle subsets, so check that first.
437 if (srcX || srcY || genInfo.width() != info.width() || genInfo.height() != info.height()) {
438 return false;
439 }
440
441 SkImageGenerator::Options opts;
Christopher Cameron77e96662017-07-08 01:47:47 -0700442 // TODO: This should respect the behavior argument.
443 opts.fBehavior = SkTransferFunctionBehavior::kIgnore;
Brian Osmandf7e0752017-04-26 16:20:28 -0400444 return generator->getPixels(info, pixels, rb, &opts);
445}
446
447//////////////////////////////////////////////////////////////////////////////////////////////////
448
449bool SkImage_Lazy::lockAsBitmapOnlyIfAlreadyCached(SkBitmap* bitmap, CachedFormat format) const {
450 uint32_t uniqueID = this->getUniqueID(format);
451 return SkBitmapCache::Find(SkBitmapCacheDesc::Make(uniqueID,
452 fInfo.width(), fInfo.height()), bitmap) &&
453 check_output_bitmap(*bitmap, uniqueID);
454}
455
Christopher Cameron77e96662017-07-08 01:47:47 -0700456static bool generate_pixels(SkImageGenerator* gen, const SkPixmap& pmap, int originX, int originY,
457 SkTransferFunctionBehavior behavior) {
Brian Osmandf7e0752017-04-26 16:20:28 -0400458 const int genW = gen->getInfo().width();
459 const int genH = gen->getInfo().height();
460 const SkIRect srcR = SkIRect::MakeWH(genW, genH);
461 const SkIRect dstR = SkIRect::MakeXYWH(originX, originY, pmap.width(), pmap.height());
462 if (!srcR.contains(dstR)) {
463 return false;
464 }
465
466 // If they are requesting a subset, we have to have a temp allocation for full image, and
467 // then copy the subset into their allocation
468 SkBitmap full;
469 SkPixmap fullPM;
470 const SkPixmap* dstPM = &pmap;
471 if (srcR != dstR) {
472 if (!full.tryAllocPixels(pmap.info().makeWH(genW, genH))) {
473 return false;
474 }
475 if (!full.peekPixels(&fullPM)) {
476 return false;
477 }
478 dstPM = &fullPM;
479 }
480
Christopher Cameron77e96662017-07-08 01:47:47 -0700481 SkImageGenerator::Options opts;
482 opts.fBehavior = behavior;
483 if (!gen->getPixels(dstPM->info(), dstPM->writable_addr(), dstPM->rowBytes(), &opts)) {
Brian Osmandf7e0752017-04-26 16:20:28 -0400484 return false;
485 }
486
487 if (srcR != dstR) {
488 if (!full.readPixels(pmap, originX, originY)) {
489 return false;
490 }
491 }
492 return true;
493}
494
Christopher Cameron77e96662017-07-08 01:47:47 -0700495bool SkImage_Lazy::lockAsBitmap(SkBitmap* bitmap, SkImage::CachingHint chint, CachedFormat format,
496 const SkImageInfo& info,
497 SkTransferFunctionBehavior behavior) const {
Brian Osmandf7e0752017-04-26 16:20:28 -0400498 if (this->lockAsBitmapOnlyIfAlreadyCached(bitmap, format)) {
499 return true;
500 }
501
502 uint32_t uniqueID = this->getUniqueID(format);
503
504 SkBitmap tmpBitmap;
505 SkBitmapCache::RecPtr cacheRec;
506 SkPixmap pmap;
507 if (SkImage::kAllow_CachingHint == chint) {
508 auto desc = SkBitmapCacheDesc::Make(uniqueID, info.width(), info.height());
509 cacheRec = SkBitmapCache::Alloc(desc, info, &pmap);
510 if (!cacheRec) {
511 return false;
512 }
513 } else {
514 if (!tmpBitmap.tryAllocPixels(info)) {
515 return false;
516 }
517 if (!tmpBitmap.peekPixels(&pmap)) {
518 return false;
519 }
520 }
521
522 ScopedGenerator generator(fSharedGenerator);
Christopher Cameron77e96662017-07-08 01:47:47 -0700523 if (!generate_pixels(generator, pmap, fOrigin.x(), fOrigin.y(), behavior)) {
Brian Osmandf7e0752017-04-26 16:20:28 -0400524 return false;
525 }
526
527 if (cacheRec) {
528 SkBitmapCache::Add(std::move(cacheRec), bitmap);
529 SkASSERT(bitmap->getPixels()); // we're locked
530 SkASSERT(bitmap->isImmutable());
531 SkASSERT(bitmap->getGenerationID() == uniqueID);
532 this->notifyAddedToCache();
533 } else {
534 *bitmap = tmpBitmap;
535 bitmap->pixelRef()->setImmutableWithID(uniqueID);
536 }
537
538 check_output_bitmap(*bitmap, uniqueID);
539 return true;
540}
541
542//////////////////////////////////////////////////////////////////////////////////////////////////
543
Brian Osmanf1b43822017-04-20 13:43:23 -0400544bool SkImage_Lazy::onReadPixels(const SkImageInfo& dstInfo, void* dstPixels, size_t dstRB,
545 int srcX, int srcY, CachingHint chint) const {
Brian Osman61624f02016-12-09 14:51:59 -0500546 SkColorSpace* dstColorSpace = dstInfo.colorSpace();
reed85d91782015-09-10 14:33:38 -0700547 SkBitmap bm;
reed6868c3f2015-11-24 11:44:47 -0800548 if (kDisallow_CachingHint == chint) {
Brian Osmandf7e0752017-04-26 16:20:28 -0400549 CachedFormat cacheFormat = this->chooseCacheFormat(dstColorSpace);
Christopher Cameron77e96662017-07-08 01:47:47 -0700550 SkImageInfo genPixelsInfo = dstInfo;
551 SkTransferFunctionBehavior behavior = getGeneratorBehaviorAndInfo(&genPixelsInfo);
Brian Osmandf7e0752017-04-26 16:20:28 -0400552 if (this->lockAsBitmapOnlyIfAlreadyCached(&bm, cacheFormat)) {
reed6868c3f2015-11-24 11:44:47 -0800553 return bm.readPixels(dstInfo, dstPixels, dstRB, srcX, srcY);
554 } else {
555 // Try passing the caller's buffer directly down to the generator. If this fails we
556 // may still succeed in the general case, as the generator may prefer some other
557 // config, which we could then convert via SkBitmap::readPixels.
Christopher Cameron77e96662017-07-08 01:47:47 -0700558 if (this->directGeneratePixels(genPixelsInfo, dstPixels, dstRB, srcX, srcY, behavior)) {
reed6868c3f2015-11-24 11:44:47 -0800559 return true;
560 }
561 // else fall through
562 }
563 }
564
Brian Osman61624f02016-12-09 14:51:59 -0500565 if (this->getROPixels(&bm, dstColorSpace, chint)) {
reed85d91782015-09-10 14:33:38 -0700566 return bm.readPixels(dstInfo, dstPixels, dstRB, srcX, srcY);
567 }
568 return false;
569}
570
Brian Osman47858972017-04-25 10:02:12 -0400571SkData* SkImage_Lazy::onRefEncoded() const {
Brian Osmandf7e0752017-04-26 16:20:28 -0400572 ScopedGenerator generator(fSharedGenerator);
573 return generator->refEncodedData();
reed85d91782015-09-10 14:33:38 -0700574}
575
Brian Osmanf1b43822017-04-20 13:43:23 -0400576bool SkImage_Lazy::getROPixels(SkBitmap* bitmap, SkColorSpace* dstColorSpace,
577 CachingHint chint) const {
Brian Osmandf7e0752017-04-26 16:20:28 -0400578 CachedFormat cacheFormat = this->chooseCacheFormat(dstColorSpace);
Christopher Cameron77e96662017-07-08 01:47:47 -0700579 const SkImageInfo cacheInfo = this->buildCacheInfo(cacheFormat);
580 SkImageInfo genPixelsInfo = cacheInfo;
581 SkTransferFunctionBehavior behavior = getGeneratorBehaviorAndInfo(&genPixelsInfo);
582 return this->lockAsBitmap(bitmap, chint, cacheFormat, genPixelsInfo, behavior);
reed85d91782015-09-10 14:33:38 -0700583}
584
Brian Osman5bbd0762017-05-08 11:07:42 -0400585bool SkImage_Lazy::onIsValid(GrContext* context) const {
586 ScopedGenerator generator(fSharedGenerator);
587 return generator->isValid(context);
588}
589
Mike Reed7f1d0202017-05-08 16:13:39 -0400590bool SkImage_Lazy::onCanLazyGenerateOnGPU() const {
591#if SK_SUPPORT_GPU
592 ScopedGenerator generator(fSharedGenerator);
Stan Ilievba81af22017-06-08 15:16:53 -0400593 return SkImageGenerator::TexGenType::kNone != generator->onCanGenerateTexture();
Mike Reed7f1d0202017-05-08 16:13:39 -0400594#else
595 return false;
596#endif
597}
598
Christopher Cameron77e96662017-07-08 01:47:47 -0700599SkTransferFunctionBehavior SkImage_Lazy::getGeneratorBehaviorAndInfo(SkImageInfo* generatorImageInfo) const {
600 if (generatorImageInfo->colorSpace()) {
601 return SkTransferFunctionBehavior::kRespect;
602 }
603 // Only specify an output color space if color conversion can be done on the color type.
604 switch (generatorImageInfo->colorType()) {
605 case kRGBA_8888_SkColorType:
606 case kBGRA_8888_SkColorType:
607 case kRGBA_F16_SkColorType:
608 case kRGB_565_SkColorType:
609 *generatorImageInfo = generatorImageInfo->makeColorSpace(fInfo.refColorSpace());
610 break;
611 default:
612 break;
613 }
614 return SkTransferFunctionBehavior::kIgnore;
615}
616
Brian Osmandf7e0752017-04-26 16:20:28 -0400617///////////////////////////////////////////////////////////////////////////////////////////////////
618
Robert Phillipsb726d582017-03-09 16:36:32 -0500619#if SK_SUPPORT_GPU
Brian Osmanf1b43822017-04-20 13:43:23 -0400620sk_sp<GrTextureProxy> SkImage_Lazy::asTextureProxyRef(GrContext* context,
621 const GrSamplerParams& params,
622 SkColorSpace* dstColorSpace,
623 sk_sp<SkColorSpace>* texColorSpace,
624 SkScalar scaleAdjust[2]) const {
Brian Osmandf7e0752017-04-26 16:20:28 -0400625 if (!context) {
626 return nullptr;
627 }
628
629 GrImageTextureMaker textureMaker(context, this, kAllow_CachingHint);
630 return textureMaker.refTextureProxyForParams(params, dstColorSpace, texColorSpace, scaleAdjust);
Robert Phillipsb726d582017-03-09 16:36:32 -0500631}
632#endif
633
Brian Osmanf1b43822017-04-20 13:43:23 -0400634sk_sp<SkImage> SkImage_Lazy::onMakeSubset(const SkIRect& subset) const {
Brian Osmandf7e0752017-04-26 16:20:28 -0400635 SkASSERT(fInfo.bounds().contains(subset));
636 SkASSERT(fInfo.bounds() != subset);
reed7b6945b2015-09-24 00:50:58 -0700637
Brian Osmandf7e0752017-04-26 16:20:28 -0400638 const SkIRect generatorSubset = subset.makeOffset(fOrigin.x(), fOrigin.y());
Christopher Cameron77e96662017-07-08 01:47:47 -0700639 Validator validator(fSharedGenerator, &generatorSubset, fInfo.refColorSpace());
Brian Osmanf1b43822017-04-20 13:43:23 -0400640 return validator ? sk_sp<SkImage>(new SkImage_Lazy(&validator)) : nullptr;
reed7b6945b2015-09-24 00:50:58 -0700641}
642
Matt Sarett9f3dcb32017-05-04 08:53:32 -0400643sk_sp<SkImage> SkImage_Lazy::onMakeColorSpace(sk_sp<SkColorSpace> target,
644 SkColorType targetColorType,
645 SkTransferFunctionBehavior premulBehavior) const {
Christopher Cameron77e96662017-07-08 01:47:47 -0700646 const SkIRect generatorSubset =
647 SkIRect::MakeXYWH(fOrigin.x(), fOrigin.y(), fInfo.width(), fInfo.height());
648 Validator validator(fSharedGenerator, &generatorSubset, target);
649 return validator ? sk_sp<SkImage>(new SkImage_Lazy(&validator)) : nullptr;
Matt Sarett6de13102017-03-14 14:10:48 -0400650}
651
Mike Reed185130c2017-02-15 15:14:16 -0500652sk_sp<SkImage> SkImage::MakeFromGenerator(std::unique_ptr<SkImageGenerator> generator,
653 const SkIRect* subset) {
Christopher Cameron77e96662017-07-08 01:47:47 -0700654 SkImage_Lazy::Validator validator(SharedGenerator::Make(std::move(generator)), subset, nullptr);
fmalita7929e3a2016-10-27 08:15:44 -0700655
Brian Osmanf1b43822017-04-20 13:43:23 -0400656 return validator ? sk_make_sp<SkImage_Lazy>(&validator) : nullptr;
reed85d91782015-09-10 14:33:38 -0700657}
Brian Osmandf7e0752017-04-26 16:20:28 -0400658
659//////////////////////////////////////////////////////////////////////////////////////////////////
660
661/**
662 * Implementation of SkImageCacherator interface, as needed by GrImageTextureMaker
663 */
664
665#if SK_SUPPORT_GPU
666
667void SkImage_Lazy::makeCacheKeyFromOrigKey(const GrUniqueKey& origKey, CachedFormat format,
668 GrUniqueKey* cacheKey) {
669 SkASSERT(!cacheKey->isValid());
670 if (origKey.isValid()) {
671 static const GrUniqueKey::Domain kDomain = GrUniqueKey::GenerateDomain();
672 GrUniqueKey::Builder builder(cacheKey, origKey, kDomain, 1);
673 builder[0] = format;
674 }
675}
676
677class Generator_GrYUVProvider : public GrYUVProvider {
678 SkImageGenerator* fGen;
679
680public:
681 Generator_GrYUVProvider(SkImageGenerator* gen) : fGen(gen) {}
682
683 uint32_t onGetID() override { return fGen->uniqueID(); }
684 bool onQueryYUV8(SkYUVSizeInfo* sizeInfo, SkYUVColorSpace* colorSpace) const override {
685 return fGen->queryYUV8(sizeInfo, colorSpace);
686 }
687 bool onGetYUV8Planes(const SkYUVSizeInfo& sizeInfo, void* planes[3]) override {
688 return fGen->getYUV8Planes(sizeInfo, planes);
689 }
690};
691
692static void set_key_on_proxy(GrResourceProvider* resourceProvider,
693 GrTextureProxy* proxy, const GrUniqueKey& key) {
694 if (key.isValid()) {
695 resourceProvider->assignUniqueKeyToProxy(key, proxy);
696 }
697}
698
699sk_sp<SkColorSpace> SkImage_Lazy::getColorSpace(GrContext* ctx, SkColorSpace* dstColorSpace) {
700 // TODO: This isn't always correct. Picture generator currently produces textures in N32,
701 // and will (soon) emit them in an arbitrary (destination) space. We will need to stash that
702 // information in/on the key so we can return the correct space in case #1 of lockTexture.
703 CachedFormat format = this->chooseCacheFormat(dstColorSpace, ctx->caps());
704 SkImageInfo cacheInfo = this->buildCacheInfo(format);
705 return sk_ref_sp(cacheInfo.colorSpace());
706}
707
708/*
709 * We have 4 ways to try to return a texture (in sorted order)
710 *
711 * 1. Check the cache for a pre-existing one
712 * 2. Ask the generator to natively create one
713 * 3. Ask the generator to return YUV planes, which the GPU can convert
714 * 4. Ask the generator to return RGB(A) data, which the GPU can convert
715 */
716sk_sp<GrTextureProxy> SkImage_Lazy::lockTextureProxy(GrContext* ctx,
717 const GrUniqueKey& origKey,
718 SkImage::CachingHint chint,
719 bool willBeMipped,
Stan Ilievba81af22017-06-08 15:16:53 -0400720 SkColorSpace* dstColorSpace,
721 GrTextureMaker::AllowedTexGenType genType) {
Brian Osmandf7e0752017-04-26 16:20:28 -0400722 // Values representing the various texture lock paths we can take. Used for logging the path
723 // taken to a histogram.
724 enum LockTexturePath {
725 kFailure_LockTexturePath,
726 kPreExisting_LockTexturePath,
727 kNative_LockTexturePath,
728 kCompressed_LockTexturePath, // Deprecated
729 kYUV_LockTexturePath,
730 kRGBA_LockTexturePath,
731 };
732
733 enum { kLockTexturePathCount = kRGBA_LockTexturePath + 1 };
734
735 // Determine which cached format we're going to use (which may involve decoding to a different
736 // info than the generator provides).
737 CachedFormat format = this->chooseCacheFormat(dstColorSpace, ctx->caps());
738
739 // Fold the cache format into our texture key
740 GrUniqueKey key;
741 this->makeCacheKeyFromOrigKey(origKey, format, &key);
742
743 // 1. Check the cache for a pre-existing one
744 if (key.isValid()) {
745 if (sk_sp<GrTextureProxy> proxy = ctx->resourceProvider()->findProxyByUniqueKey(key)) {
746 SK_HISTOGRAM_ENUMERATION("LockTexturePath", kPreExisting_LockTexturePath,
747 kLockTexturePathCount);
748 return proxy;
749 }
750 }
751
752 // The CachedFormat is both an index for which cache "slot" we'll use to store this particular
753 // decoded variant of the encoded data, and also a recipe for how to transform the original
754 // info to get the one that we're going to decode to.
Christopher Cameron77e96662017-07-08 01:47:47 -0700755 const SkImageInfo cacheInfo = this->buildCacheInfo(format);
756 SkImageInfo genPixelsInfo = cacheInfo;
757 SkTransferFunctionBehavior behavior = getGeneratorBehaviorAndInfo(&genPixelsInfo);
Brian Osmandf7e0752017-04-26 16:20:28 -0400758
759 // 2. Ask the generator to natively create one
760 {
761 ScopedGenerator generator(fSharedGenerator);
Stan Ilievba81af22017-06-08 15:16:53 -0400762 if (GrTextureMaker::AllowedTexGenType::kCheap == genType &&
763 SkImageGenerator::TexGenType::kCheap != generator->onCanGenerateTexture()) {
764 return nullptr;
765 }
Christopher Cameron77e96662017-07-08 01:47:47 -0700766 if (sk_sp<GrTextureProxy> proxy =
767 generator->generateTexture(ctx, genPixelsInfo, fOrigin, behavior)) {
Brian Osmandf7e0752017-04-26 16:20:28 -0400768 SK_HISTOGRAM_ENUMERATION("LockTexturePath", kNative_LockTexturePath,
769 kLockTexturePathCount);
770 set_key_on_proxy(ctx->resourceProvider(), proxy.get(), key);
771 return proxy;
772 }
773 }
774
775 // 3. Ask the generator to return YUV planes, which the GPU can convert
776 if (!ctx->contextPriv().disableGpuYUVConversion()) {
777 const GrSurfaceDesc desc = GrImageInfoToSurfaceDesc(cacheInfo, *ctx->caps());
778 ScopedGenerator generator(fSharedGenerator);
779 Generator_GrYUVProvider provider(generator);
Christopher Cameron77e96662017-07-08 01:47:47 -0700780
781 // The pixels in the texture will be in the generator's color space. If onMakeColorSpace
782 // has been called then this will not match this image's color space. To correct this, apply
783 // a color space conversion from the generator's color space to this image's color space.
784 const SkColorSpace* generatorColorSpace =
785 fSharedGenerator->fGenerator->getInfo().colorSpace();
786 const SkColorSpace* thisColorSpace = fInfo.colorSpace();
787
788 sk_sp<GrTextureProxy> proxy =
789 provider.refAsTextureProxy(ctx, desc, true, generatorColorSpace, thisColorSpace);
790 if (proxy) {
Brian Osmandf7e0752017-04-26 16:20:28 -0400791 SK_HISTOGRAM_ENUMERATION("LockTexturePath", kYUV_LockTexturePath,
792 kLockTexturePathCount);
793 set_key_on_proxy(ctx->resourceProvider(), proxy.get(), key);
794 return proxy;
795 }
796 }
797
798 // 4. Ask the generator to return RGB(A) data, which the GPU can convert
799 SkBitmap bitmap;
Christopher Cameron77e96662017-07-08 01:47:47 -0700800 if (this->lockAsBitmap(&bitmap, chint, format, genPixelsInfo, behavior)) {
Brian Osmandf7e0752017-04-26 16:20:28 -0400801 sk_sp<GrTextureProxy> proxy;
802 if (willBeMipped) {
803 proxy = GrGenerateMipMapsAndUploadToTextureProxy(ctx, bitmap, dstColorSpace);
804 }
805 if (!proxy) {
Matt Sarettdedac852017-05-12 10:56:49 -0400806 proxy = GrUploadBitmapToTextureProxy(ctx->resourceProvider(), bitmap, dstColorSpace);
Brian Osmandf7e0752017-04-26 16:20:28 -0400807 }
808 if (proxy) {
809 SK_HISTOGRAM_ENUMERATION("LockTexturePath", kRGBA_LockTexturePath,
810 kLockTexturePathCount);
811 set_key_on_proxy(ctx->resourceProvider(), proxy.get(), key);
812 return proxy;
813 }
814 }
815 SK_HISTOGRAM_ENUMERATION("LockTexturePath", kFailure_LockTexturePath,
816 kLockTexturePathCount);
817 return nullptr;
818}
819
820///////////////////////////////////////////////////////////////////////////////////////////////////
821
822#endif