1 /*
2  * Copyright (C) 2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "VkInteropFunctorDrawable.h"
18 
19 #include <EGL/egl.h>
20 #include <EGL/eglext.h>
21 #include <GLES2/gl2.h>
22 #include <GLES2/gl2ext.h>
23 #include <GLES3/gl3.h>
24 #include <gui/TraceUtils.h>
25 #include <private/hwui/DrawGlInfo.h>
26 #include <utils/Color.h>
27 #include <utils/GLUtils.h>
28 #include <utils/Trace.h>
29 
30 #include <thread>
31 
32 #include "renderthread/EglManager.h"
33 #include "thread/ThreadBase.h"
34 #include "utils/TimeUtils.h"
35 #include "effects/GainmapRenderer.h"
36 
37 #include <SkBlendMode.h>
38 
39 namespace android {
40 namespace uirenderer {
41 namespace skiapipeline {
42 
43 static renderthread::EglManager sEglManager;
44 
45 // ScopedDrawRequest makes sure a GL thread is started and EGL context is initialized on it.
46 class ScopedDrawRequest {
47 public:
ScopedDrawRequest()48     ScopedDrawRequest() { beginDraw(); }
49 
50 private:
beginDraw()51     void beginDraw() {
52         if (!sEglManager.hasEglContext()) {
53             sEglManager.initialize();
54         }
55     }
56 };
57 
vkInvokeFunctor(Functor * functor)58 void VkInteropFunctorDrawable::vkInvokeFunctor(Functor* functor) {
59     ScopedDrawRequest _drawRequest{};
60     EGLDisplay display = sEglManager.eglDisplay();
61     DrawGlInfo::Mode mode = DrawGlInfo::kModeProcessNoContext;
62     if (display != EGL_NO_DISPLAY) {
63         mode = DrawGlInfo::kModeProcess;
64     }
65     (*functor)(mode, nullptr);
66 }
67 
68 #define FENCE_TIMEOUT 2000000000
69 
onDraw(SkCanvas * canvas)70 void VkInteropFunctorDrawable::onDraw(SkCanvas* canvas) {
71     ATRACE_CALL();
72 
73     if (canvas->recordingContext() == nullptr) {
74         ALOGD("Attempting to draw VkInteropFunctor into an unsupported surface");
75         return;
76     }
77 
78     ScopedDrawRequest _drawRequest{};
79 
80     SkImageInfo surfaceInfo = canvas->imageInfo();
81 
82     if (mFrameBuffer == nullptr || mFBInfo != surfaceInfo) {
83         // Buffer will be used as an OpenGL ES render target.
84         AHardwareBuffer_Desc desc = {
85                 .width = static_cast<uint32_t>(surfaceInfo.width()),
86                 .height = static_cast<uint32_t>(surfaceInfo.height()),
87                 .layers = 1,
88                 .format = ColorTypeToBufferFormat(surfaceInfo.colorType()),
89                 .usage = AHARDWAREBUFFER_USAGE_CPU_READ_NEVER |
90                          AHARDWAREBUFFER_USAGE_CPU_WRITE_NEVER |
91                          AHARDWAREBUFFER_USAGE_GPU_SAMPLED_IMAGE |
92                          AHARDWAREBUFFER_USAGE_GPU_FRAMEBUFFER,
93         };
94 
95         mFrameBuffer = allocateAHardwareBuffer(desc);
96 
97         if (!mFrameBuffer) {
98             ALOGW("VkInteropFunctorDrawable::onDraw() failed in AHardwareBuffer_allocate()");
99             return;
100         }
101 
102         mFBInfo = surfaceInfo;
103     }
104 
105     // TODO: Synchronization is needed on mFrameBuffer to guarantee that the previous Vulkan
106     // TODO: draw command has completed.
107     // TODO: A simple but inefficient way is to flush and issue a QueueWaitIdle call. See
108     // TODO: GrVkGpu::destroyResources() for example.
109     {
110         ATRACE_FORMAT("WebViewDraw_%dx%d", mFBInfo.width(), mFBInfo.height());
111         EGLDisplay display = sEglManager.eglDisplay();
112         LOG_ALWAYS_FATAL_IF(display == EGL_NO_DISPLAY, "Failed to get EGL_DEFAULT_DISPLAY! err=%s",
113                             uirenderer::renderthread::EglManager::eglErrorString());
114         // We use an EGLImage to access the content of the GraphicBuffer
115         // The EGL image is later bound to a 2D texture
116         const EGLClientBuffer clientBuffer = eglGetNativeClientBufferANDROID(mFrameBuffer.get());
117         AutoEglImage autoImage(display, clientBuffer);
118         if (autoImage.image == EGL_NO_IMAGE_KHR) {
119             ALOGW("Could not create EGL image, err =%s",
120                   uirenderer::renderthread::EglManager::eglErrorString());
121             return;
122         }
123 
124         AutoSkiaGlTexture glTexture;
125         glEGLImageTargetTexture2DOES(GL_TEXTURE_2D, autoImage.image);
126         GL_CHECKPOINT(MODERATE);
127 
128         glBindTexture(GL_TEXTURE_2D, 0);
129 
130         DrawGlInfo info;
131         SkM44 mat4(canvas->getLocalToDevice());
132         SkIRect clipBounds = canvas->getDeviceClipBounds();
133 
134         info.clipLeft = clipBounds.fLeft;
135         info.clipTop = clipBounds.fTop;
136         info.clipRight = clipBounds.fRight;
137         info.clipBottom = clipBounds.fBottom;
138         info.isLayer = true;
139         info.width = mFBInfo.width();
140         info.height = mFBInfo.height();
141         mat4.getColMajor(&info.transform[0]);
142         info.color_space_ptr = canvas->imageInfo().colorSpace();
143         info.currentHdrSdrRatio = getTargetHdrSdrRatio(info.color_space_ptr);
144 
145         glViewport(0, 0, info.width, info.height);
146 
147         AutoGLFramebuffer glFb;
148         // Bind texture to the frame buffer.
149         glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
150                                glTexture.mTexture, 0);
151         if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
152             ALOGE("Failed framebuffer check for created target buffer: %s",
153                   GLUtils::getGLFramebufferError());
154             return;
155         }
156 
157         glDisable(GL_STENCIL_TEST);
158         glDisable(GL_SCISSOR_TEST);
159         glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
160         glClear(GL_COLOR_BUFFER_BIT);
161 
162         mWebViewHandle->drawGl(info);
163 
164         EGLSyncKHR glDrawFinishedFence =
165                 eglCreateSyncKHR(eglGetCurrentDisplay(), EGL_SYNC_FENCE_KHR, NULL);
166         LOG_ALWAYS_FATAL_IF(glDrawFinishedFence == EGL_NO_SYNC_KHR,
167                             "Could not create sync fence %#x", eglGetError());
168         glFlush();
169         // TODO: export EGLSyncKHR in file descr
170         // TODO: import file desc in Vulkan Semaphore
171         // TODO: instead block the GPU: probably by using external Vulkan semaphore.
172         // Block the CPU until the glFlush finish.
173         EGLint waitStatus = eglClientWaitSyncKHR(display, glDrawFinishedFence, 0, FENCE_TIMEOUT);
174         LOG_ALWAYS_FATAL_IF(waitStatus != EGL_CONDITION_SATISFIED_KHR,
175                             "Failed to wait for the fence %#x", eglGetError());
176         eglDestroySyncKHR(display, glDrawFinishedFence);
177     }
178 
179     SkPaint paint;
180     paint.setBlendMode(SkBlendMode::kSrcOver);
181     canvas->save();
182     // The size of the image matches the size of the canvas. We've used the matrix already, while
183     // drawing into the offscreen surface, so we need to reset it here.
184     canvas->resetMatrix();
185 
186     auto functorImage = SkImage::MakeFromAHardwareBuffer(mFrameBuffer.get(), kPremul_SkAlphaType,
187                                                          canvas->imageInfo().refColorSpace(),
188                                                          kBottomLeft_GrSurfaceOrigin);
189     canvas->drawImage(functorImage, 0, 0, SkSamplingOptions(), &paint);
190     canvas->restore();
191 }
192 
syncFunctor(const WebViewSyncData & data) const193 void VkInteropFunctorDrawable::syncFunctor(const WebViewSyncData& data) const {
194     ScopedDrawRequest _drawRequest{};
195     FunctorDrawable::syncFunctor(data);
196 }
197 
198 }  // namespace skiapipeline
199 }  // namespace uirenderer
200 }  // namespace android
201