1 /*
2  * Copyright 2017 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 #ifndef GrAHardwareBufferImageGenerator_DEFINED
8 #define GrAHardwareBufferImageGenerator_DEFINED
9 
10 #include "SkImageGenerator.h"
11 
12 #include "GrTypesPriv.h"
13 
14 class GrGpuResource;
15 
16 extern "C" {
17     typedef struct AHardwareBuffer AHardwareBuffer;
18 }
19 
20 /**
21  *  GrAHardwareBufferImageGenerator allows to create an SkImage attached to
22  *  an existing android native hardware buffer. A hardware buffer has to be
23  *  created with AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE usage, because it is
24  *  bound to an external texture using an EGLImage. The image generator will
25  *  keep a reference to the hardware buffer for its lifetime. A hardware buffer
26  *  can be shared between processes and same buffer can be used in multiple GPU
27  *  contexts.
28  *  To implement certain features like tiling, Skia may copy the texture to
29  *  avoid OpenGL API limitations.
30  */
31 class GrAHardwareBufferImageGenerator : public SkImageGenerator {
32 public:
33     static std::unique_ptr<SkImageGenerator> Make(AHardwareBuffer*, SkAlphaType,
34                                                   sk_sp<SkColorSpace>, GrSurfaceOrigin);
35 
36     ~GrAHardwareBufferImageGenerator() override;
37 
38     typedef void* DeleteImageCtx;
39     typedef void (*DeleteImageProc)(DeleteImageCtx);
40 
41     static void DeleteGLTexture(void* ctx);
42 
43 #ifdef SK_VULKAN
44     static void DeleteVkImage(void* ctx);
45 #endif
46 
47 protected:
48 
49     bool onIsValid(GrContext*) const override;
50 
51     TexGenType onCanGenerateTexture() const override { return TexGenType::kCheap; }
52     sk_sp<GrTextureProxy> onGenerateTexture(GrContext*, const SkImageInfo&, const SkIPoint&,
53                                             bool willNeedMipMaps) override;
54 
55 private:
56     GrAHardwareBufferImageGenerator(const SkImageInfo&, AHardwareBuffer*, SkAlphaType,
57                                     bool isProtectedContent, uint32_t bufferFormat,
58                                     GrSurfaceOrigin surfaceOrigin);
59     sk_sp<GrTextureProxy> makeProxy(GrContext* context);
60 
61     void releaseTextureRef();
62 
63     static void ReleaseRefHelper_TextureReleaseProc(void* ctx);
64 
65     AHardwareBuffer* fHardwareBuffer;
66     uint32_t         fBufferFormat;
67     const bool       fIsProtectedContent;
68     GrSurfaceOrigin  fSurfaceOrigin;
69 
70     typedef SkImageGenerator INHERITED;
71 };
72 #endif  // GrAHardwareBufferImageGenerator_DEFINED
73