1/*
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 "GrYUVProvider.h"
9#include "GrClip.h"
10#include "GrContext.h"
11#include "GrContextPriv.h"
12#include "GrRenderTargetContext.h"
13#include "GrTextureProxy.h"
14#include "SkAutoMalloc.h"
15#include "SkCachedData.h"
16#include "SkRefCnt.h"
17#include "SkResourceCache.h"
18#include "SkYUVPlanesCache.h"
19#include "effects/GrSRGBEffect.h"
20#include "effects/GrYUVEffect.h"
21
22namespace {
23/**
24 *  Helper class to manage the resources used for storing the YUV planar data. Depending on the
25 *  useCache option, we may find (and lock) the data in our ResourceCache, or we may have allocated
26 *  it in scratch storage.
27 */
28class YUVScoper {
29public:
30    bool init(GrYUVProvider*, SkYUVPlanesCache::Info*, void* planes[3], bool useCache);
31
32private:
33    // we only use one or the other of these
34    sk_sp<SkCachedData>  fCachedData;
35    SkAutoMalloc         fStorage;
36};
37}
38
39bool YUVScoper::init(GrYUVProvider* provider, SkYUVPlanesCache::Info* yuvInfo, void* planes[3],
40                     bool useCache) {
41    if (useCache) {
42        fCachedData.reset(SkYUVPlanesCache::FindAndRef(provider->onGetID(), yuvInfo));
43    }
44
45    if (fCachedData.get()) {
46        planes[0] = (void*)fCachedData->data();
47        planes[1] = (uint8_t*)planes[0] + (yuvInfo->fSizeInfo.fWidthBytes[SkYUVSizeInfo::kY] *
48                                           yuvInfo->fSizeInfo.fSizes[SkYUVSizeInfo::kY].fHeight);
49        planes[2] = (uint8_t*)planes[1] + (yuvInfo->fSizeInfo.fWidthBytes[SkYUVSizeInfo::kU] *
50                                           yuvInfo->fSizeInfo.fSizes[SkYUVSizeInfo::kU].fHeight);
51    } else {
52        // Fetch yuv plane sizes for memory allocation.
53        if (!provider->onQueryYUV8(&yuvInfo->fSizeInfo, &yuvInfo->fColorSpace)) {
54            return false;
55        }
56
57        // Allocate the memory for YUV
58        size_t totalSize(0);
59        for (int i = 0; i < 3; i++) {
60            totalSize += yuvInfo->fSizeInfo.fWidthBytes[i] * yuvInfo->fSizeInfo.fSizes[i].fHeight;
61        }
62        if (useCache) {
63            fCachedData.reset(SkResourceCache::NewCachedData(totalSize));
64            planes[0] = fCachedData->writable_data();
65        } else {
66            fStorage.reset(totalSize);
67            planes[0] = fStorage.get();
68        }
69        planes[1] = (uint8_t*)planes[0] + (yuvInfo->fSizeInfo.fWidthBytes[SkYUVSizeInfo::kY] *
70                                           yuvInfo->fSizeInfo.fSizes[SkYUVSizeInfo::kY].fHeight);
71        planes[2] = (uint8_t*)planes[1] + (yuvInfo->fSizeInfo.fWidthBytes[SkYUVSizeInfo::kU] *
72                                           yuvInfo->fSizeInfo.fSizes[SkYUVSizeInfo::kU].fHeight);
73
74        // Get the YUV planes.
75        if (!provider->onGetYUV8Planes(yuvInfo->fSizeInfo, planes)) {
76            return false;
77        }
78
79        if (useCache) {
80            // Decoding is done, cache the resulting YUV planes
81            SkYUVPlanesCache::Add(provider->onGetID(), fCachedData.get(), yuvInfo);
82        }
83    }
84    return true;
85}
86
87sk_sp<GrTextureProxy> GrYUVProvider::refAsTextureProxy(GrContext* ctx,
88                                                       const GrSurfaceDesc& desc,
89                                                       bool useCache) {
90    SkYUVPlanesCache::Info yuvInfo;
91    void* planes[3];
92    YUVScoper scoper;
93    if (!scoper.init(this, &yuvInfo, planes, useCache)) {
94        return nullptr;
95    }
96
97    GrSurfaceDesc yuvDesc;
98    yuvDesc.fOrigin = kTopLeft_GrSurfaceOrigin;
99    yuvDesc.fConfig = kAlpha_8_GrPixelConfig;
100    sk_sp<GrSurfaceContext> yuvTextureContexts[3];
101    for (int i = 0; i < 3; i++) {
102        yuvDesc.fWidth  = yuvInfo.fSizeInfo.fSizes[i].fWidth;
103        yuvDesc.fHeight = yuvInfo.fSizeInfo.fSizes[i].fHeight;
104        // TODO: why do we need this check?
105        SkBackingFit fit =
106                (yuvDesc.fWidth  != yuvInfo.fSizeInfo.fSizes[SkYUVSizeInfo::kY].fWidth) ||
107                (yuvDesc.fHeight != yuvInfo.fSizeInfo.fSizes[SkYUVSizeInfo::kY].fHeight)
108                    ? SkBackingFit::kExact : SkBackingFit::kApprox;
109
110        yuvTextureContexts[i] = ctx->contextPriv().makeDeferredSurfaceContext(yuvDesc, fit,
111                                                                              SkBudgeted::kYes);
112        if (!yuvTextureContexts[i]) {
113            return nullptr;
114        }
115
116        const SkImageInfo ii = SkImageInfo::MakeA8(yuvDesc.fWidth, yuvDesc.fHeight);
117        if (!yuvTextureContexts[i]->writePixels(ii, planes[i],
118                                                yuvInfo.fSizeInfo.fWidthBytes[i], 0, 0)) {
119            return nullptr;
120        }
121    }
122
123    // We never want to perform color-space conversion during the decode
124    sk_sp<GrRenderTargetContext> renderTargetContext(ctx->makeRenderTargetContext(
125                                                                          SkBackingFit::kExact,
126                                                                          desc.fWidth, desc.fHeight,
127                                                                          desc.fConfig, nullptr,
128                                                                          desc.fSampleCnt));
129    if (!renderTargetContext) {
130        return nullptr;
131    }
132
133    GrPaint paint;
134    sk_sp<GrFragmentProcessor> yuvToRgbProcessor(
135        GrYUVEffect::MakeYUVToRGB(ctx->resourceProvider(),
136                                  yuvTextureContexts[0]->asTextureProxyRef(),
137                                  yuvTextureContexts[1]->asTextureProxyRef(),
138                                  yuvTextureContexts[2]->asTextureProxyRef(),
139                                  yuvInfo.fSizeInfo.fSizes, yuvInfo.fColorSpace, false));
140    paint.addColorFragmentProcessor(std::move(yuvToRgbProcessor));
141
142    // If we're decoding an sRGB image, the result of our linear math on the YUV planes is already
143    // in sRGB. (The encoding is just math on bytes, with no concept of color spaces.) So, we need
144    // to output the results of that math directly to the buffer that we will then consider sRGB.
145    // If we have sRGB write control, we can just tell the HW not to do the Linear -> sRGB step.
146    // Otherwise, we do our shader math to go from YUV -> sRGB, manually convert sRGB -> Linear,
147    // then let the HW convert Linear -> sRGB.
148    if (GrPixelConfigIsSRGB(desc.fConfig)) {
149        if (ctx->caps()->srgbWriteControl()) {
150            paint.setDisableOutputConversionToSRGB(true);
151        } else {
152            paint.addColorFragmentProcessor(GrSRGBEffect::Make(GrSRGBEffect::Mode::kSRGBToLinear));
153        }
154    }
155
156    paint.setPorterDuffXPFactory(SkBlendMode::kSrc);
157    const SkRect r = SkRect::MakeIWH(yuvInfo.fSizeInfo.fSizes[SkYUVSizeInfo::kY].fWidth,
158                                     yuvInfo.fSizeInfo.fSizes[SkYUVSizeInfo::kY].fHeight);
159
160    renderTargetContext->drawRect(GrNoClip(), std::move(paint), GrAA::kNo, SkMatrix::I(), r);
161
162    return renderTargetContext->asTextureProxyRef();
163}
164