blob: aff19f8d791e637c55c7ecc5960e2264529ea356 [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
Christopher Camerond4b67872017-07-13 15:18:08 -0700162 // Repeated calls to onMakeColorSpace will result in a proliferation of unique IDs and
163 // SkImage_Lazy instances. Cache the result of the last successful onMakeColorSpace call.
164 mutable SkMutex fOnMakeColorSpaceMutex;
165 mutable sk_sp<SkColorSpace> fOnMakeColorSpaceTarget;
166 mutable sk_sp<SkImage> fOnMakeColorSpaceResult;
167
reed85d91782015-09-10 14:33:38 -0700168 typedef SkImage_Base INHERITED;
169};
170
171///////////////////////////////////////////////////////////////////////////////
172
Christopher Cameron77e96662017-07-08 01:47:47 -0700173SkImage_Lazy::Validator::Validator(sk_sp<SharedGenerator> gen, const SkIRect* subset,
174 sk_sp<SkColorSpace> colorSpace)
Brian Osmandf7e0752017-04-26 16:20:28 -0400175 : fSharedGenerator(std::move(gen)) {
Brian Osmandf7e0752017-04-26 16:20:28 -0400176 if (!fSharedGenerator) {
177 return;
178 }
179
180 // The following generator accessors are safe without acquiring the mutex (const getters).
181 // TODO: refactor to use a ScopedGenerator instead, for clarity.
182 const SkImageInfo& info = fSharedGenerator->fGenerator->getInfo();
183 if (info.isEmpty()) {
184 fSharedGenerator.reset();
185 return;
186 }
187
188 fUniqueID = fSharedGenerator->fGenerator->uniqueID();
189 const SkIRect bounds = SkIRect::MakeWH(info.width(), info.height());
190 if (subset) {
191 if (!bounds.contains(*subset)) {
192 fSharedGenerator.reset();
193 return;
194 }
195 if (*subset != bounds) {
196 // we need a different uniqueID since we really are a subset of the raw generator
197 fUniqueID = SkNextID::ImageID();
198 }
199 } else {
200 subset = &bounds;
201 }
202
203 fInfo = info.makeWH(subset->width(), subset->height());
204 fOrigin = SkIPoint::Make(subset->x(), subset->y());
Christopher Cameron77e96662017-07-08 01:47:47 -0700205 if (colorSpace) {
206 fInfo = fInfo.makeColorSpace(colorSpace);
207 fUniqueID = SkNextID::ImageID();
208 }
Brian Osmandf7e0752017-04-26 16:20:28 -0400209}
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);
Brian Osmandf7e0752017-04-26 16:20:28 -0400243 // We explicit set the legacy format slot, but leave the others uninitialized (via SkOnce)
244 // and only resolove them to IDs as needed (by calling getUniqueID()).
245 fIDRecs[kLegacy_CachedFormat].fOnce([this, validator] {
246 fIDRecs[kLegacy_CachedFormat].fUniqueID = validator->fUniqueID;
247 });
248}
249
250uint32_t SkImage_Lazy::getUniqueID(CachedFormat format) const {
251 IDRec* rec = &fIDRecs[format];
252 rec->fOnce([rec] {
253 rec->fUniqueID = SkNextID::ImageID();
254 });
255 return rec->fUniqueID;
256}
257
258//////////////////////////////////////////////////////////////////////////////////////////////////
259
260// Abstraction of GrCaps that handles the cases where we don't have a caps pointer (because
261// we're in raster mode), or where GPU support is entirely missing. In theory, we only need the
262// chosen format to be texturable, but that lets us choose F16 on GLES implemenations where we
263// won't be able to read the texture back. We'd like to ensure that SkImake::makeNonTextureImage
264// works, so we require that the formats we choose are renderable (as a proxy for being readable).
265struct CacheCaps {
266 CacheCaps(const GrCaps* caps) : fCaps(caps) {}
267
268#if SK_SUPPORT_GPU
269 bool supportsHalfFloat() const {
270 return !fCaps ||
271 (fCaps->isConfigTexturable(kRGBA_half_GrPixelConfig) &&
272 fCaps->isConfigRenderable(kRGBA_half_GrPixelConfig, false));
273 }
274
275 bool supportsSRGB() const {
276 return !fCaps ||
277 (fCaps->srgbSupport() && fCaps->isConfigTexturable(kSRGBA_8888_GrPixelConfig));
278 }
279
280 bool supportsSBGR() const {
281 return !fCaps || fCaps->srgbSupport();
282 }
283#else
284 bool supportsHalfFloat() const { return true; }
285 bool supportsSRGB() const { return true; }
286 bool supportsSBGR() const { return true; }
287#endif
288
289 const GrCaps* fCaps;
290};
291
292SkImageCacherator::CachedFormat SkImage_Lazy::chooseCacheFormat(SkColorSpace* dstColorSpace,
293 const GrCaps* grCaps) const {
294 SkColorSpace* cs = fInfo.colorSpace();
295 if (!cs || !dstColorSpace) {
296 return kLegacy_CachedFormat;
297 }
298
299 CacheCaps caps(grCaps);
300 switch (fInfo.colorType()) {
301 case kUnknown_SkColorType:
302 case kAlpha_8_SkColorType:
303 case kRGB_565_SkColorType:
304 case kARGB_4444_SkColorType:
305 // We don't support color space on these formats, so always decode in legacy mode:
306 // TODO: Ask the codec to decode these to something else (at least sRGB 8888)?
307 return kLegacy_CachedFormat;
308
Brian Osmandf7e0752017-04-26 16:20:28 -0400309 case kGray_8_SkColorType:
310 // TODO: What do we do with grayscale sources that have strange color spaces attached?
311 // The codecs and color space xform don't handle this correctly (yet), so drop it on
312 // the floor. (Also, inflating by a factor of 8 is going to be unfortunate).
313 // As it is, we don't directly support sRGB grayscale, so ask the codec to convert
314 // it for us. This bypasses some really sketchy code GrUploadPixmapToTexture.
315 if (cs->gammaCloseToSRGB() && caps.supportsSRGB()) {
316 return kSRGB8888_CachedFormat;
317 } else {
318 return kLegacy_CachedFormat;
319 }
320
321 case kRGBA_8888_SkColorType:
322 if (cs->gammaCloseToSRGB()) {
323 if (caps.supportsSRGB()) {
324 return kSRGB8888_CachedFormat;
325 } else if (caps.supportsHalfFloat()) {
326 return kLinearF16_CachedFormat;
327 } else {
328 return kLegacy_CachedFormat;
329 }
330 } else {
331 if (caps.supportsHalfFloat()) {
332 return kLinearF16_CachedFormat;
333 } else if (caps.supportsSRGB()) {
334 return kSRGB8888_CachedFormat;
335 } else {
336 return kLegacy_CachedFormat;
337 }
338 }
339
340 case kBGRA_8888_SkColorType:
341 // Odd case. sBGRA isn't a real thing, so we may not have this texturable.
342 if (caps.supportsSBGR()) {
343 if (cs->gammaCloseToSRGB()) {
344 return kSBGR8888_CachedFormat;
345 } else if (caps.supportsHalfFloat()) {
346 return kLinearF16_CachedFormat;
347 } else if (caps.supportsSRGB()) {
348 return kSRGB8888_CachedFormat;
349 } else {
350 // sBGRA support without sRGBA is highly unlikely (impossible?) Nevertheless.
351 return kLegacy_CachedFormat;
352 }
353 } else {
354 if (cs->gammaCloseToSRGB()) {
355 if (caps.supportsSRGB()) {
356 return kSRGB8888_CachedFormat;
357 } else if (caps.supportsHalfFloat()) {
358 return kLinearF16_CachedFormat;
359 } else {
360 return kLegacy_CachedFormat;
361 }
362 } else {
363 if (caps.supportsHalfFloat()) {
364 return kLinearF16_CachedFormat;
365 } else if (caps.supportsSRGB()) {
366 return kSRGB8888_CachedFormat;
367 } else {
368 return kLegacy_CachedFormat;
369 }
370 }
371 }
372
373 case kRGBA_F16_SkColorType:
374 if (caps.supportsHalfFloat()) {
375 return kLinearF16_CachedFormat;
376 } else if (caps.supportsSRGB()) {
377 return kSRGB8888_CachedFormat;
378 } else {
379 return kLegacy_CachedFormat;
380 }
381 }
382 SkDEBUGFAIL("Unreachable");
383 return kLegacy_CachedFormat;
384}
385
386SkImageInfo SkImage_Lazy::buildCacheInfo(CachedFormat format) const {
387 switch (format) {
388 case kLegacy_CachedFormat:
389 return fInfo.makeColorSpace(nullptr);
390 case kLinearF16_CachedFormat:
391 return fInfo.makeColorType(kRGBA_F16_SkColorType)
392 .makeColorSpace(as_CSB(fInfo.colorSpace())->makeLinearGamma());
393 case kSRGB8888_CachedFormat:
394 // If the transfer function is nearly (but not exactly) sRGB, we don't want the codec
395 // to bother trans-coding. It would be slow, and do more harm than good visually,
396 // so we make sure to leave the colorspace as-is.
397 if (fInfo.colorSpace()->gammaCloseToSRGB()) {
398 return fInfo.makeColorType(kRGBA_8888_SkColorType);
399 } else {
400 return fInfo.makeColorType(kRGBA_8888_SkColorType)
401 .makeColorSpace(as_CSB(fInfo.colorSpace())->makeSRGBGamma());
402 }
403 case kSBGR8888_CachedFormat:
404 // See note above about not-quite-sRGB transfer functions.
405 if (fInfo.colorSpace()->gammaCloseToSRGB()) {
406 return fInfo.makeColorType(kBGRA_8888_SkColorType);
407 } else {
408 return fInfo.makeColorType(kBGRA_8888_SkColorType)
409 .makeColorSpace(as_CSB(fInfo.colorSpace())->makeSRGBGamma());
410 }
411 default:
412 SkDEBUGFAIL("Invalid cached format");
413 return fInfo;
414 }
415}
416
417//////////////////////////////////////////////////////////////////////////////////////////////////
418
419static bool check_output_bitmap(const SkBitmap& bitmap, uint32_t expectedID) {
420 SkASSERT(bitmap.getGenerationID() == expectedID);
421 SkASSERT(bitmap.isImmutable());
422 SkASSERT(bitmap.getPixels());
423 return true;
424}
425
426bool SkImage_Lazy::directGeneratePixels(const SkImageInfo& info, void* pixels, size_t rb,
427 int srcX, int srcY,
428 SkTransferFunctionBehavior behavior) const {
429 ScopedGenerator generator(fSharedGenerator);
430 const SkImageInfo& genInfo = generator->getInfo();
431 // Currently generators do not natively handle subsets, so check that first.
432 if (srcX || srcY || genInfo.width() != info.width() || genInfo.height() != info.height()) {
433 return false;
434 }
435
436 SkImageGenerator::Options opts;
Christopher Cameron77e96662017-07-08 01:47:47 -0700437 // TODO: This should respect the behavior argument.
438 opts.fBehavior = SkTransferFunctionBehavior::kIgnore;
Brian Osmandf7e0752017-04-26 16:20:28 -0400439 return generator->getPixels(info, pixels, rb, &opts);
440}
441
442//////////////////////////////////////////////////////////////////////////////////////////////////
443
444bool SkImage_Lazy::lockAsBitmapOnlyIfAlreadyCached(SkBitmap* bitmap, CachedFormat format) const {
445 uint32_t uniqueID = this->getUniqueID(format);
446 return SkBitmapCache::Find(SkBitmapCacheDesc::Make(uniqueID,
447 fInfo.width(), fInfo.height()), bitmap) &&
448 check_output_bitmap(*bitmap, uniqueID);
449}
450
Christopher Cameron77e96662017-07-08 01:47:47 -0700451static bool generate_pixels(SkImageGenerator* gen, const SkPixmap& pmap, int originX, int originY,
452 SkTransferFunctionBehavior behavior) {
Brian Osmandf7e0752017-04-26 16:20:28 -0400453 const int genW = gen->getInfo().width();
454 const int genH = gen->getInfo().height();
455 const SkIRect srcR = SkIRect::MakeWH(genW, genH);
456 const SkIRect dstR = SkIRect::MakeXYWH(originX, originY, pmap.width(), pmap.height());
457 if (!srcR.contains(dstR)) {
458 return false;
459 }
460
461 // If they are requesting a subset, we have to have a temp allocation for full image, and
462 // then copy the subset into their allocation
463 SkBitmap full;
464 SkPixmap fullPM;
465 const SkPixmap* dstPM = &pmap;
466 if (srcR != dstR) {
467 if (!full.tryAllocPixels(pmap.info().makeWH(genW, genH))) {
468 return false;
469 }
470 if (!full.peekPixels(&fullPM)) {
471 return false;
472 }
473 dstPM = &fullPM;
474 }
475
Christopher Cameron77e96662017-07-08 01:47:47 -0700476 SkImageGenerator::Options opts;
477 opts.fBehavior = behavior;
478 if (!gen->getPixels(dstPM->info(), dstPM->writable_addr(), dstPM->rowBytes(), &opts)) {
Brian Osmandf7e0752017-04-26 16:20:28 -0400479 return false;
480 }
481
482 if (srcR != dstR) {
483 if (!full.readPixels(pmap, originX, originY)) {
484 return false;
485 }
486 }
487 return true;
488}
489
Christopher Cameron77e96662017-07-08 01:47:47 -0700490bool SkImage_Lazy::lockAsBitmap(SkBitmap* bitmap, SkImage::CachingHint chint, CachedFormat format,
491 const SkImageInfo& info,
492 SkTransferFunctionBehavior behavior) const {
Brian Osmandf7e0752017-04-26 16:20:28 -0400493 if (this->lockAsBitmapOnlyIfAlreadyCached(bitmap, format)) {
494 return true;
495 }
496
497 uint32_t uniqueID = this->getUniqueID(format);
498
499 SkBitmap tmpBitmap;
500 SkBitmapCache::RecPtr cacheRec;
501 SkPixmap pmap;
502 if (SkImage::kAllow_CachingHint == chint) {
503 auto desc = SkBitmapCacheDesc::Make(uniqueID, info.width(), info.height());
504 cacheRec = SkBitmapCache::Alloc(desc, info, &pmap);
505 if (!cacheRec) {
506 return false;
507 }
508 } else {
509 if (!tmpBitmap.tryAllocPixels(info)) {
510 return false;
511 }
512 if (!tmpBitmap.peekPixels(&pmap)) {
513 return false;
514 }
515 }
516
517 ScopedGenerator generator(fSharedGenerator);
Christopher Cameron77e96662017-07-08 01:47:47 -0700518 if (!generate_pixels(generator, pmap, fOrigin.x(), fOrigin.y(), behavior)) {
Brian Osmandf7e0752017-04-26 16:20:28 -0400519 return false;
520 }
521
522 if (cacheRec) {
523 SkBitmapCache::Add(std::move(cacheRec), bitmap);
524 SkASSERT(bitmap->getPixels()); // we're locked
525 SkASSERT(bitmap->isImmutable());
526 SkASSERT(bitmap->getGenerationID() == uniqueID);
527 this->notifyAddedToCache();
528 } else {
529 *bitmap = tmpBitmap;
530 bitmap->pixelRef()->setImmutableWithID(uniqueID);
531 }
532
533 check_output_bitmap(*bitmap, uniqueID);
534 return true;
535}
536
537//////////////////////////////////////////////////////////////////////////////////////////////////
538
Brian Osmanf1b43822017-04-20 13:43:23 -0400539bool SkImage_Lazy::onReadPixels(const SkImageInfo& dstInfo, void* dstPixels, size_t dstRB,
540 int srcX, int srcY, CachingHint chint) const {
Brian Osman61624f02016-12-09 14:51:59 -0500541 SkColorSpace* dstColorSpace = dstInfo.colorSpace();
reed85d91782015-09-10 14:33:38 -0700542 SkBitmap bm;
reed6868c3f2015-11-24 11:44:47 -0800543 if (kDisallow_CachingHint == chint) {
Brian Osmandf7e0752017-04-26 16:20:28 -0400544 CachedFormat cacheFormat = this->chooseCacheFormat(dstColorSpace);
Christopher Cameron77e96662017-07-08 01:47:47 -0700545 SkImageInfo genPixelsInfo = dstInfo;
546 SkTransferFunctionBehavior behavior = getGeneratorBehaviorAndInfo(&genPixelsInfo);
Brian Osmandf7e0752017-04-26 16:20:28 -0400547 if (this->lockAsBitmapOnlyIfAlreadyCached(&bm, cacheFormat)) {
reed6868c3f2015-11-24 11:44:47 -0800548 return bm.readPixels(dstInfo, dstPixels, dstRB, srcX, srcY);
549 } else {
550 // Try passing the caller's buffer directly down to the generator. If this fails we
551 // may still succeed in the general case, as the generator may prefer some other
552 // config, which we could then convert via SkBitmap::readPixels.
Christopher Cameron77e96662017-07-08 01:47:47 -0700553 if (this->directGeneratePixels(genPixelsInfo, dstPixels, dstRB, srcX, srcY, behavior)) {
reed6868c3f2015-11-24 11:44:47 -0800554 return true;
555 }
556 // else fall through
557 }
558 }
559
Brian Osman61624f02016-12-09 14:51:59 -0500560 if (this->getROPixels(&bm, dstColorSpace, chint)) {
reed85d91782015-09-10 14:33:38 -0700561 return bm.readPixels(dstInfo, dstPixels, dstRB, srcX, srcY);
562 }
563 return false;
564}
565
Brian Osman47858972017-04-25 10:02:12 -0400566SkData* SkImage_Lazy::onRefEncoded() const {
Brian Osmandf7e0752017-04-26 16:20:28 -0400567 ScopedGenerator generator(fSharedGenerator);
568 return generator->refEncodedData();
reed85d91782015-09-10 14:33:38 -0700569}
570
Brian Osmanf1b43822017-04-20 13:43:23 -0400571bool SkImage_Lazy::getROPixels(SkBitmap* bitmap, SkColorSpace* dstColorSpace,
572 CachingHint chint) const {
Brian Osmandf7e0752017-04-26 16:20:28 -0400573 CachedFormat cacheFormat = this->chooseCacheFormat(dstColorSpace);
Christopher Cameron77e96662017-07-08 01:47:47 -0700574 const SkImageInfo cacheInfo = this->buildCacheInfo(cacheFormat);
575 SkImageInfo genPixelsInfo = cacheInfo;
576 SkTransferFunctionBehavior behavior = getGeneratorBehaviorAndInfo(&genPixelsInfo);
577 return this->lockAsBitmap(bitmap, chint, cacheFormat, genPixelsInfo, behavior);
reed85d91782015-09-10 14:33:38 -0700578}
579
Brian Osman5bbd0762017-05-08 11:07:42 -0400580bool SkImage_Lazy::onIsValid(GrContext* context) const {
581 ScopedGenerator generator(fSharedGenerator);
582 return generator->isValid(context);
583}
584
Mike Reed7f1d0202017-05-08 16:13:39 -0400585bool SkImage_Lazy::onCanLazyGenerateOnGPU() const {
586#if SK_SUPPORT_GPU
587 ScopedGenerator generator(fSharedGenerator);
Stan Ilievba81af22017-06-08 15:16:53 -0400588 return SkImageGenerator::TexGenType::kNone != generator->onCanGenerateTexture();
Mike Reed7f1d0202017-05-08 16:13:39 -0400589#else
590 return false;
591#endif
592}
593
Christopher Cameron77e96662017-07-08 01:47:47 -0700594SkTransferFunctionBehavior SkImage_Lazy::getGeneratorBehaviorAndInfo(SkImageInfo* generatorImageInfo) const {
595 if (generatorImageInfo->colorSpace()) {
596 return SkTransferFunctionBehavior::kRespect;
597 }
598 // Only specify an output color space if color conversion can be done on the color type.
599 switch (generatorImageInfo->colorType()) {
600 case kRGBA_8888_SkColorType:
601 case kBGRA_8888_SkColorType:
602 case kRGBA_F16_SkColorType:
603 case kRGB_565_SkColorType:
604 *generatorImageInfo = generatorImageInfo->makeColorSpace(fInfo.refColorSpace());
605 break;
606 default:
607 break;
608 }
609 return SkTransferFunctionBehavior::kIgnore;
610}
611
Brian Osmandf7e0752017-04-26 16:20:28 -0400612///////////////////////////////////////////////////////////////////////////////////////////////////
613
Robert Phillipsb726d582017-03-09 16:36:32 -0500614#if SK_SUPPORT_GPU
Brian Osmanf1b43822017-04-20 13:43:23 -0400615sk_sp<GrTextureProxy> SkImage_Lazy::asTextureProxyRef(GrContext* context,
616 const GrSamplerParams& params,
617 SkColorSpace* dstColorSpace,
618 sk_sp<SkColorSpace>* texColorSpace,
619 SkScalar scaleAdjust[2]) const {
Brian Osmandf7e0752017-04-26 16:20:28 -0400620 if (!context) {
621 return nullptr;
622 }
623
624 GrImageTextureMaker textureMaker(context, this, kAllow_CachingHint);
625 return textureMaker.refTextureProxyForParams(params, dstColorSpace, texColorSpace, scaleAdjust);
Robert Phillipsb726d582017-03-09 16:36:32 -0500626}
627#endif
628
Brian Osmanf1b43822017-04-20 13:43:23 -0400629sk_sp<SkImage> SkImage_Lazy::onMakeSubset(const SkIRect& subset) const {
Brian Osmandf7e0752017-04-26 16:20:28 -0400630 SkASSERT(fInfo.bounds().contains(subset));
631 SkASSERT(fInfo.bounds() != subset);
reed7b6945b2015-09-24 00:50:58 -0700632
Brian Osmandf7e0752017-04-26 16:20:28 -0400633 const SkIRect generatorSubset = subset.makeOffset(fOrigin.x(), fOrigin.y());
Christopher Cameron77e96662017-07-08 01:47:47 -0700634 Validator validator(fSharedGenerator, &generatorSubset, fInfo.refColorSpace());
Brian Osmanf1b43822017-04-20 13:43:23 -0400635 return validator ? sk_sp<SkImage>(new SkImage_Lazy(&validator)) : nullptr;
reed7b6945b2015-09-24 00:50:58 -0700636}
637
Matt Sarett9f3dcb32017-05-04 08:53:32 -0400638sk_sp<SkImage> SkImage_Lazy::onMakeColorSpace(sk_sp<SkColorSpace> target,
639 SkColorType targetColorType,
640 SkTransferFunctionBehavior premulBehavior) const {
Christopher Camerond4b67872017-07-13 15:18:08 -0700641 SkAutoExclusive autoAquire(fOnMakeColorSpaceMutex);
642 if (target && fOnMakeColorSpaceTarget &&
643 SkColorSpace::Equals(target.get(), fOnMakeColorSpaceTarget.get())) {
644 return fOnMakeColorSpaceResult;
645 }
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);
Christopher Camerond4b67872017-07-13 15:18:08 -0700649 sk_sp<SkImage> result = validator ? sk_sp<SkImage>(new SkImage_Lazy(&validator)) : nullptr;
650 if (result) {
651 fOnMakeColorSpaceTarget = target;
652 fOnMakeColorSpaceResult = result;
653 }
654 return result;
Matt Sarett6de13102017-03-14 14:10:48 -0400655}
656
Mike Reed185130c2017-02-15 15:14:16 -0500657sk_sp<SkImage> SkImage::MakeFromGenerator(std::unique_ptr<SkImageGenerator> generator,
658 const SkIRect* subset) {
Christopher Cameron77e96662017-07-08 01:47:47 -0700659 SkImage_Lazy::Validator validator(SharedGenerator::Make(std::move(generator)), subset, nullptr);
fmalita7929e3a2016-10-27 08:15:44 -0700660
Brian Osmanf1b43822017-04-20 13:43:23 -0400661 return validator ? sk_make_sp<SkImage_Lazy>(&validator) : nullptr;
reed85d91782015-09-10 14:33:38 -0700662}
Brian Osmandf7e0752017-04-26 16:20:28 -0400663
664//////////////////////////////////////////////////////////////////////////////////////////////////
665
666/**
667 * Implementation of SkImageCacherator interface, as needed by GrImageTextureMaker
668 */
669
670#if SK_SUPPORT_GPU
671
672void SkImage_Lazy::makeCacheKeyFromOrigKey(const GrUniqueKey& origKey, CachedFormat format,
673 GrUniqueKey* cacheKey) {
674 SkASSERT(!cacheKey->isValid());
675 if (origKey.isValid()) {
676 static const GrUniqueKey::Domain kDomain = GrUniqueKey::GenerateDomain();
677 GrUniqueKey::Builder builder(cacheKey, origKey, kDomain, 1);
678 builder[0] = format;
679 }
680}
681
682class Generator_GrYUVProvider : public GrYUVProvider {
683 SkImageGenerator* fGen;
684
685public:
686 Generator_GrYUVProvider(SkImageGenerator* gen) : fGen(gen) {}
687
688 uint32_t onGetID() override { return fGen->uniqueID(); }
689 bool onQueryYUV8(SkYUVSizeInfo* sizeInfo, SkYUVColorSpace* colorSpace) const override {
690 return fGen->queryYUV8(sizeInfo, colorSpace);
691 }
692 bool onGetYUV8Planes(const SkYUVSizeInfo& sizeInfo, void* planes[3]) override {
693 return fGen->getYUV8Planes(sizeInfo, planes);
694 }
695};
696
697static void set_key_on_proxy(GrResourceProvider* resourceProvider,
698 GrTextureProxy* proxy, const GrUniqueKey& key) {
699 if (key.isValid()) {
Robert Phillips8a90f502017-07-24 15:09:56 -0400700 SkASSERT(proxy->origin() == kTopLeft_GrSurfaceOrigin);
Brian Osmandf7e0752017-04-26 16:20:28 -0400701 resourceProvider->assignUniqueKeyToProxy(key, proxy);
702 }
703}
704
705sk_sp<SkColorSpace> SkImage_Lazy::getColorSpace(GrContext* ctx, SkColorSpace* dstColorSpace) {
706 // TODO: This isn't always correct. Picture generator currently produces textures in N32,
707 // and will (soon) emit them in an arbitrary (destination) space. We will need to stash that
708 // information in/on the key so we can return the correct space in case #1 of lockTexture.
709 CachedFormat format = this->chooseCacheFormat(dstColorSpace, ctx->caps());
710 SkImageInfo cacheInfo = this->buildCacheInfo(format);
711 return sk_ref_sp(cacheInfo.colorSpace());
712}
713
714/*
715 * We have 4 ways to try to return a texture (in sorted order)
716 *
717 * 1. Check the cache for a pre-existing one
718 * 2. Ask the generator to natively create one
719 * 3. Ask the generator to return YUV planes, which the GPU can convert
720 * 4. Ask the generator to return RGB(A) data, which the GPU can convert
721 */
722sk_sp<GrTextureProxy> SkImage_Lazy::lockTextureProxy(GrContext* ctx,
723 const GrUniqueKey& origKey,
724 SkImage::CachingHint chint,
725 bool willBeMipped,
Stan Ilievba81af22017-06-08 15:16:53 -0400726 SkColorSpace* dstColorSpace,
727 GrTextureMaker::AllowedTexGenType genType) {
Brian Osmandf7e0752017-04-26 16:20:28 -0400728 // Values representing the various texture lock paths we can take. Used for logging the path
729 // taken to a histogram.
730 enum LockTexturePath {
731 kFailure_LockTexturePath,
732 kPreExisting_LockTexturePath,
733 kNative_LockTexturePath,
734 kCompressed_LockTexturePath, // Deprecated
735 kYUV_LockTexturePath,
736 kRGBA_LockTexturePath,
737 };
738
739 enum { kLockTexturePathCount = kRGBA_LockTexturePath + 1 };
740
741 // Determine which cached format we're going to use (which may involve decoding to a different
742 // info than the generator provides).
743 CachedFormat format = this->chooseCacheFormat(dstColorSpace, ctx->caps());
744
745 // Fold the cache format into our texture key
746 GrUniqueKey key;
747 this->makeCacheKeyFromOrigKey(origKey, format, &key);
748
749 // 1. Check the cache for a pre-existing one
750 if (key.isValid()) {
Robert Phillips066f0202017-07-25 10:16:35 -0400751 if (sk_sp<GrTextureProxy> proxy = ctx->resourceProvider()->findProxyByUniqueKey(
752 key, kTopLeft_GrSurfaceOrigin)) {
Brian Osmandf7e0752017-04-26 16:20:28 -0400753 SK_HISTOGRAM_ENUMERATION("LockTexturePath", kPreExisting_LockTexturePath,
754 kLockTexturePathCount);
755 return proxy;
756 }
757 }
758
759 // The CachedFormat is both an index for which cache "slot" we'll use to store this particular
760 // decoded variant of the encoded data, and also a recipe for how to transform the original
761 // info to get the one that we're going to decode to.
Christopher Cameron77e96662017-07-08 01:47:47 -0700762 const SkImageInfo cacheInfo = this->buildCacheInfo(format);
763 SkImageInfo genPixelsInfo = cacheInfo;
764 SkTransferFunctionBehavior behavior = getGeneratorBehaviorAndInfo(&genPixelsInfo);
Brian Osmandf7e0752017-04-26 16:20:28 -0400765
766 // 2. Ask the generator to natively create one
767 {
768 ScopedGenerator generator(fSharedGenerator);
Stan Ilievba81af22017-06-08 15:16:53 -0400769 if (GrTextureMaker::AllowedTexGenType::kCheap == genType &&
770 SkImageGenerator::TexGenType::kCheap != generator->onCanGenerateTexture()) {
771 return nullptr;
772 }
Christopher Cameron77e96662017-07-08 01:47:47 -0700773 if (sk_sp<GrTextureProxy> proxy =
774 generator->generateTexture(ctx, genPixelsInfo, fOrigin, behavior)) {
Brian Osmandf7e0752017-04-26 16:20:28 -0400775 SK_HISTOGRAM_ENUMERATION("LockTexturePath", kNative_LockTexturePath,
776 kLockTexturePathCount);
777 set_key_on_proxy(ctx->resourceProvider(), proxy.get(), key);
778 return proxy;
779 }
780 }
781
782 // 3. Ask the generator to return YUV planes, which the GPU can convert
783 if (!ctx->contextPriv().disableGpuYUVConversion()) {
784 const GrSurfaceDesc desc = GrImageInfoToSurfaceDesc(cacheInfo, *ctx->caps());
785 ScopedGenerator generator(fSharedGenerator);
786 Generator_GrYUVProvider provider(generator);
Christopher Cameron77e96662017-07-08 01:47:47 -0700787
788 // The pixels in the texture will be in the generator's color space. If onMakeColorSpace
789 // has been called then this will not match this image's color space. To correct this, apply
790 // a color space conversion from the generator's color space to this image's color space.
791 const SkColorSpace* generatorColorSpace =
792 fSharedGenerator->fGenerator->getInfo().colorSpace();
793 const SkColorSpace* thisColorSpace = fInfo.colorSpace();
794
795 sk_sp<GrTextureProxy> proxy =
796 provider.refAsTextureProxy(ctx, desc, true, generatorColorSpace, thisColorSpace);
797 if (proxy) {
Brian Osmandf7e0752017-04-26 16:20:28 -0400798 SK_HISTOGRAM_ENUMERATION("LockTexturePath", kYUV_LockTexturePath,
799 kLockTexturePathCount);
800 set_key_on_proxy(ctx->resourceProvider(), proxy.get(), key);
801 return proxy;
802 }
803 }
804
805 // 4. Ask the generator to return RGB(A) data, which the GPU can convert
806 SkBitmap bitmap;
Christopher Cameron77e96662017-07-08 01:47:47 -0700807 if (this->lockAsBitmap(&bitmap, chint, format, genPixelsInfo, behavior)) {
Brian Osmandf7e0752017-04-26 16:20:28 -0400808 sk_sp<GrTextureProxy> proxy;
809 if (willBeMipped) {
810 proxy = GrGenerateMipMapsAndUploadToTextureProxy(ctx, bitmap, dstColorSpace);
811 }
812 if (!proxy) {
Matt Sarettdedac852017-05-12 10:56:49 -0400813 proxy = GrUploadBitmapToTextureProxy(ctx->resourceProvider(), bitmap, dstColorSpace);
Brian Osmandf7e0752017-04-26 16:20:28 -0400814 }
815 if (proxy) {
816 SK_HISTOGRAM_ENUMERATION("LockTexturePath", kRGBA_LockTexturePath,
817 kLockTexturePathCount);
818 set_key_on_proxy(ctx->resourceProvider(), proxy.get(), key);
819 return proxy;
820 }
821 }
822 SK_HISTOGRAM_ENUMERATION("LockTexturePath", kFailure_LockTexturePath,
823 kLockTexturePathCount);
824 return nullptr;
825}
826
827///////////////////////////////////////////////////////////////////////////////////////////////////
828
829#endif