• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2016 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 "pipeline/skia/SkiaOpenGLPipeline.h"
18 
19 #include <GrBackendSurface.h>
20 #include <SkBlendMode.h>
21 #include <SkImageInfo.h>
22 #include <cutils/properties.h>
23 #include <gui/TraceUtils.h>
24 #include <include/gpu/ganesh/SkSurfaceGanesh.h>
25 #include <include/gpu/ganesh/gl/GrGLBackendSurface.h>
26 #include <include/gpu/gl/GrGLTypes.h>
27 #include <strings.h>
28 
29 #include "DeferredLayerUpdater.h"
30 #include "FrameInfo.h"
31 #include "LightingInfo.h"
32 #include "hwui/Bitmap.h"
33 #include "pipeline/skia/LayerDrawable.h"
34 #include "pipeline/skia/SkiaGpuPipeline.h"
35 #include "pipeline/skia/SkiaProfileRenderer.h"
36 #include "private/hwui/DrawGlInfo.h"
37 #include "renderstate/RenderState.h"
38 #include "renderthread/EglManager.h"
39 #include "renderthread/Frame.h"
40 #include "renderthread/IRenderPipeline.h"
41 #include "utils/GLUtils.h"
42 
43 using namespace android::uirenderer::renderthread;
44 
45 namespace android {
46 namespace uirenderer {
47 namespace skiapipeline {
48 
SkiaOpenGLPipeline(RenderThread & thread)49 SkiaOpenGLPipeline::SkiaOpenGLPipeline(RenderThread& thread)
50         : SkiaGpuPipeline(thread), mEglManager(thread.eglManager()) {
51     thread.renderState().registerContextCallback(this);
52 }
53 
~SkiaOpenGLPipeline()54 SkiaOpenGLPipeline::~SkiaOpenGLPipeline() {
55     mRenderThread.renderState().removeContextCallback(this);
56 }
57 
makeCurrent()58 MakeCurrentResult SkiaOpenGLPipeline::makeCurrent() {
59     bool wasSurfaceless = mEglManager.isCurrent(EGL_NO_SURFACE);
60 
61     // In case the surface was destroyed (e.g. a previous trimMemory call) we
62     // need to recreate it here.
63     if (mHardwareBuffer) {
64         mRenderThread.requireGlContext();
65     } else if (!isSurfaceReady() && mNativeWindow) {
66         setSurface(mNativeWindow.get(), mSwapBehavior);
67     }
68 
69     EGLint error = 0;
70     if (!mEglManager.makeCurrent(mEglSurface, &error)) {
71         return MakeCurrentResult::AlreadyCurrent;
72     }
73 
74     EGLint majorVersion = 0;
75     eglQueryContext(eglGetCurrentDisplay(), eglGetCurrentContext(), EGL_CONTEXT_CLIENT_VERSION, &majorVersion);
76 
77     // Make sure read/draw buffer state of default framebuffer is GL_BACK for ES 3.X. Vendor implementations
78     // disagree on the draw/read buffer state if the default framebuffer transitions from a surface
79     // to EGL_NO_SURFACE and vice-versa. There was a related discussion within Khronos on this topic.
80     // See https://cvs.khronos.org/bugzilla/show_bug.cgi?id=13534.
81     // The discussion was not resolved with a clear consensus
82     if (error == 0 && (majorVersion > 2) && wasSurfaceless && mEglSurface != EGL_NO_SURFACE) {
83         GLint curReadFB = 0;
84         GLint curDrawFB = 0;
85         glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &curReadFB);
86         glGetIntegerv(GL_DRAW_FRAMEBUFFER_BINDING, &curDrawFB);
87 
88         GLint buffer = GL_NONE;
89         glBindFramebuffer(GL_FRAMEBUFFER, 0);
90         glGetIntegerv(GL_DRAW_BUFFER0, &buffer);
91         if (buffer == GL_NONE) {
92             const GLenum drawBuffer = GL_BACK;
93             glDrawBuffers(1, &drawBuffer);
94         }
95 
96         glGetIntegerv(GL_READ_BUFFER, &buffer);
97         if (buffer == GL_NONE) {
98             glReadBuffer(GL_BACK);
99         }
100 
101         glBindFramebuffer(GL_READ_FRAMEBUFFER, curReadFB);
102         glBindFramebuffer(GL_DRAW_FRAMEBUFFER, curDrawFB);
103 
104         GL_CHECKPOINT(LOW);
105     }
106 
107     return error ? MakeCurrentResult::Failed : MakeCurrentResult::Succeeded;
108 }
109 
getFrame()110 Frame SkiaOpenGLPipeline::getFrame() {
111     LOG_ALWAYS_FATAL_IF(mEglSurface == EGL_NO_SURFACE,
112                         "drawRenderNode called on a context with no surface!");
113     return mEglManager.beginFrame(mEglSurface);
114 }
115 
draw(const Frame & frame,const SkRect & screenDirty,const SkRect & dirty,const LightGeometry & lightGeometry,LayerUpdateQueue * layerUpdateQueue,const Rect & contentDrawBounds,bool opaque,const LightInfo & lightInfo,const std::vector<sp<RenderNode>> & renderNodes,FrameInfoVisualizer * profiler,const HardwareBufferRenderParams & bufferParams,std::mutex & profilerLock)116 IRenderPipeline::DrawResult SkiaOpenGLPipeline::draw(
117         const Frame& frame, const SkRect& screenDirty, const SkRect& dirty,
118         const LightGeometry& lightGeometry, LayerUpdateQueue* layerUpdateQueue,
119         const Rect& contentDrawBounds, bool opaque, const LightInfo& lightInfo,
120         const std::vector<sp<RenderNode>>& renderNodes, FrameInfoVisualizer* profiler,
121         const HardwareBufferRenderParams& bufferParams, std::mutex& profilerLock) {
122     if (!isCapturingSkp() && !mHardwareBuffer) {
123         mEglManager.damageFrame(frame, dirty);
124     }
125 
126     SkColorType colorType = getSurfaceColorType();
127     // setup surface for fbo0
128     GrGLFramebufferInfo fboInfo;
129     fboInfo.fFBOID = 0;
130     if (colorType == kRGBA_F16_SkColorType) {
131         fboInfo.fFormat = GL_RGBA16F;
132     } else if (colorType == kN32_SkColorType) {
133         // Note: The default preference of pixel format is RGBA_8888, when other
134         // pixel format is available, we should branch out and do more check.
135         fboInfo.fFormat = GL_RGBA8;
136     } else if (colorType == kRGBA_1010102_SkColorType) {
137         fboInfo.fFormat = GL_RGB10_A2;
138     } else if (colorType == kAlpha_8_SkColorType) {
139         fboInfo.fFormat = GL_R8;
140     } else {
141         LOG_ALWAYS_FATAL("Unsupported color type.");
142     }
143 
144     auto backendRT = GrBackendRenderTargets::MakeGL(frame.width(), frame.height(), 0,
145                                                     STENCIL_BUFFER_SIZE, fboInfo);
146 
147     SkSurfaceProps props(mColorMode == ColorMode::Default ? 0 : SkSurfaceProps::kAlwaysDither_Flag,
148                          kUnknown_SkPixelGeometry);
149 
150     SkASSERT(mRenderThread.getGrContext() != nullptr);
151     sk_sp<SkSurface> surface;
152     SkMatrix preTransform;
153     if (mHardwareBuffer) {
154         surface = getBufferSkSurface(bufferParams);
155         preTransform = bufferParams.getTransform();
156     } else {
157         surface = SkSurfaces::WrapBackendRenderTarget(mRenderThread.getGrContext(), backendRT,
158                                                       getSurfaceOrigin(), colorType,
159                                                       mSurfaceColorSpace, &props);
160         preTransform = SkMatrix::I();
161     }
162 
163     SkPoint lightCenter = preTransform.mapXY(lightGeometry.center.x, lightGeometry.center.y);
164     LightGeometry localGeometry = lightGeometry;
165     localGeometry.center.x = lightCenter.fX;
166     localGeometry.center.y = lightCenter.fY;
167     LightingInfo::updateLighting(localGeometry, lightInfo);
168     renderFrame(*layerUpdateQueue, dirty, renderNodes, opaque, contentDrawBounds, surface,
169                 preTransform);
170 
171     // Draw visual debugging features
172     if (CC_UNLIKELY(Properties::showDirtyRegions ||
173                     ProfileType::None != Properties::getProfileType())) {
174         std::scoped_lock lock(profilerLock);
175         SkCanvas* profileCanvas = surface->getCanvas();
176         SkiaProfileRenderer profileRenderer(profileCanvas, frame.width(), frame.height());
177         profiler->draw(profileRenderer);
178     }
179 
180     {
181         ATRACE_NAME("flush commands");
182         skgpu::ganesh::FlushAndSubmit(surface);
183     }
184     layerUpdateQueue->clear();
185 
186     // Log memory statistics
187     if (CC_UNLIKELY(Properties::debugLevel != kDebugDisabled)) {
188         dumpResourceCacheUsage();
189     }
190 
191     return {true, IRenderPipeline::DrawResult::kUnknownTime, android::base::unique_fd{}};
192 }
193 
swapBuffers(const Frame & frame,IRenderPipeline::DrawResult & drawResult,const SkRect & screenDirty,FrameInfo * currentFrameInfo,bool * requireSwap)194 bool SkiaOpenGLPipeline::swapBuffers(const Frame& frame, IRenderPipeline::DrawResult& drawResult,
195                                      const SkRect& screenDirty, FrameInfo* currentFrameInfo,
196                                      bool* requireSwap) {
197     GL_CHECKPOINT(LOW);
198 
199     // Even if we decided to cancel the frame, from the perspective of jank
200     // metrics the frame was swapped at this point
201     currentFrameInfo->markSwapBuffers();
202 
203     if (mHardwareBuffer) {
204         return false;
205     }
206 
207     *requireSwap = drawResult.success || mEglManager.damageRequiresSwap();
208 
209     if (*requireSwap && (CC_UNLIKELY(!mEglManager.swapBuffers(frame, screenDirty)))) {
210         return false;
211     }
212 
213     return *requireSwap;
214 }
215 
createTextureLayer()216 DeferredLayerUpdater* SkiaOpenGLPipeline::createTextureLayer() {
217     mRenderThread.requireGlContext();
218     return new DeferredLayerUpdater(mRenderThread.renderState());
219 }
220 
onContextDestroyed()221 void SkiaOpenGLPipeline::onContextDestroyed() {
222     if (mEglSurface != EGL_NO_SURFACE) {
223         mEglManager.destroySurface(mEglSurface);
224         mEglSurface = EGL_NO_SURFACE;
225     }
226 }
227 
onStop()228 void SkiaOpenGLPipeline::onStop() {
229     if (mEglManager.isCurrent(mEglSurface)) {
230         mEglManager.makeCurrent(EGL_NO_SURFACE);
231     }
232 }
233 
setSurface(ANativeWindow * surface,SwapBehavior swapBehavior)234 bool SkiaOpenGLPipeline::setSurface(ANativeWindow* surface, SwapBehavior swapBehavior) {
235     mNativeWindow = surface;
236     mSwapBehavior = swapBehavior;
237 
238     if (mEglSurface != EGL_NO_SURFACE) {
239         mEglManager.destroySurface(mEglSurface);
240         mEglSurface = EGL_NO_SURFACE;
241     }
242 
243     if (surface) {
244         mRenderThread.requireGlContext();
245         auto newSurface = mEglManager.createSurface(surface, mColorMode, mSurfaceColorSpace);
246         if (!newSurface) {
247             return false;
248         }
249         mEglSurface = newSurface.unwrap();
250     }
251 
252     if (mEglSurface != EGL_NO_SURFACE) {
253         const bool preserveBuffer = (swapBehavior != SwapBehavior::kSwap_discardBuffer);
254         mEglManager.setPreserveBuffer(mEglSurface, preserveBuffer);
255         return true;
256     }
257 
258     return false;
259 }
260 
flush()261 [[nodiscard]] android::base::unique_fd SkiaOpenGLPipeline::flush() {
262     int fence = -1;
263     EGLSyncKHR sync = EGL_NO_SYNC_KHR;
264     mEglManager.createReleaseFence(true, &sync, &fence);
265     // If a sync object is returned here then the device does not support native
266     // fences, we block on the returned sync and return -1 as a file descriptor
267     if (sync != EGL_NO_SYNC_KHR) {
268         EGLDisplay display = mEglManager.eglDisplay();
269         EGLint result = eglClientWaitSyncKHR(display, sync, 0, 1000000000);
270         if (result == EGL_FALSE) {
271             ALOGE("EglManager::createReleaseFence: error waiting for previous fence: %#x",
272                   eglGetError());
273         } else if (result == EGL_TIMEOUT_EXPIRED_KHR) {
274             ALOGE("EglManager::createReleaseFence: timeout waiting for previous fence");
275         }
276         eglDestroySyncKHR(display, sync);
277     }
278     return android::base::unique_fd(fence);
279 }
280 
isSurfaceReady()281 bool SkiaOpenGLPipeline::isSurfaceReady() {
282     return CC_UNLIKELY(mEglSurface != EGL_NO_SURFACE);
283 }
284 
isContextReady()285 bool SkiaOpenGLPipeline::isContextReady() {
286     return CC_LIKELY(mEglManager.hasEglContext());
287 }
288 
invokeFunctor(const RenderThread & thread,Functor * functor)289 void SkiaOpenGLPipeline::invokeFunctor(const RenderThread& thread, Functor* functor) {
290     DrawGlInfo::Mode mode = DrawGlInfo::kModeProcessNoContext;
291     if (thread.eglManager().hasEglContext()) {
292         mode = DrawGlInfo::kModeProcess;
293     }
294 
295     (*functor)(mode, nullptr);
296 
297     // If there's no context we don't need to reset as there's no gl state to save/restore
298     if (mode != DrawGlInfo::kModeProcessNoContext) {
299         thread.getGrContext()->resetContext();
300     }
301 }
302 
303 } /* namespace skiapipeline */
304 } /* namespace uirenderer */
305 } /* namespace android */
306