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 "SkiaOpenGLPipeline.h"
18
19 #include "DeferredLayerUpdater.h"
20 #include "GlLayer.h"
21 #include "LayerDrawable.h"
22 #include "SkiaPipeline.h"
23 #include "SkiaProfileRenderer.h"
24 #include "hwui/Bitmap.h"
25 #include "renderstate/RenderState.h"
26 #include "renderthread/EglManager.h"
27 #include "renderthread/Frame.h"
28 #include "utils/TraceUtils.h"
29
30 #include <GrBackendSurface.h>
31 #include <SkImageInfo.h>
32 #include <SkBlendMode.h>
33
34 #include <cutils/properties.h>
35 #include <strings.h>
36
37 using namespace android::uirenderer::renderthread;
38
39 namespace android {
40 namespace uirenderer {
41 namespace skiapipeline {
42
SkiaOpenGLPipeline(RenderThread & thread)43 SkiaOpenGLPipeline::SkiaOpenGLPipeline(RenderThread& thread)
44 : SkiaPipeline(thread), mEglManager(thread.eglManager()) {}
45
makeCurrent()46 MakeCurrentResult SkiaOpenGLPipeline::makeCurrent() {
47 // TODO: Figure out why this workaround is needed, see b/13913604
48 // In the meantime this matches the behavior of GLRenderer, so it is not a regression
49 EGLint error = 0;
50 if (!mEglManager.makeCurrent(mEglSurface, &error)) {
51 return MakeCurrentResult::AlreadyCurrent;
52 }
53 return error ? MakeCurrentResult::Failed : MakeCurrentResult::Succeeded;
54 }
55
getFrame()56 Frame SkiaOpenGLPipeline::getFrame() {
57 LOG_ALWAYS_FATAL_IF(mEglSurface == EGL_NO_SURFACE,
58 "drawRenderNode called on a context with no surface!");
59 return mEglManager.beginFrame(mEglSurface);
60 }
61
draw(const Frame & frame,const SkRect & screenDirty,const SkRect & dirty,const FrameBuilder::LightGeometry & lightGeometry,LayerUpdateQueue * layerUpdateQueue,const Rect & contentDrawBounds,bool opaque,bool wideColorGamut,const BakedOpRenderer::LightInfo & lightInfo,const std::vector<sp<RenderNode>> & renderNodes,FrameInfoVisualizer * profiler)62 bool SkiaOpenGLPipeline::draw(const Frame& frame, const SkRect& screenDirty, const SkRect& dirty,
63 const FrameBuilder::LightGeometry& lightGeometry,
64 LayerUpdateQueue* layerUpdateQueue, const Rect& contentDrawBounds,
65 bool opaque, bool wideColorGamut,
66 const BakedOpRenderer::LightInfo& lightInfo,
67 const std::vector<sp<RenderNode>>& renderNodes,
68 FrameInfoVisualizer* profiler) {
69 mEglManager.damageFrame(frame, dirty);
70
71 // setup surface for fbo0
72 GrGLFramebufferInfo fboInfo;
73 fboInfo.fFBOID = 0;
74 GrPixelConfig pixelConfig =
75 wideColorGamut ? kRGBA_half_GrPixelConfig : kRGBA_8888_GrPixelConfig;
76
77 GrBackendRenderTarget backendRT(frame.width(), frame.height(), 0, STENCIL_BUFFER_SIZE,
78 pixelConfig, fboInfo);
79
80 SkSurfaceProps props(0, kUnknown_SkPixelGeometry);
81
82 SkASSERT(mRenderThread.getGrContext() != nullptr);
83 sk_sp<SkSurface> surface(SkSurface::MakeFromBackendRenderTarget(
84 mRenderThread.getGrContext(), backendRT, kBottomLeft_GrSurfaceOrigin, nullptr, &props));
85
86 SkiaPipeline::updateLighting(lightGeometry, lightInfo);
87 renderFrame(*layerUpdateQueue, dirty, renderNodes, opaque, wideColorGamut, contentDrawBounds,
88 surface);
89 layerUpdateQueue->clear();
90
91 // Draw visual debugging features
92 if (CC_UNLIKELY(Properties::showDirtyRegions ||
93 ProfileType::None != Properties::getProfileType())) {
94 SkCanvas* profileCanvas = surface->getCanvas();
95 SkiaProfileRenderer profileRenderer(profileCanvas);
96 profiler->draw(profileRenderer);
97 profileCanvas->flush();
98 }
99
100 // Log memory statistics
101 if (CC_UNLIKELY(Properties::debugLevel != kDebugDisabled)) {
102 dumpResourceCacheUsage();
103 }
104
105 return true;
106 }
107
swapBuffers(const Frame & frame,bool drew,const SkRect & screenDirty,FrameInfo * currentFrameInfo,bool * requireSwap)108 bool SkiaOpenGLPipeline::swapBuffers(const Frame& frame, bool drew, const SkRect& screenDirty,
109 FrameInfo* currentFrameInfo, bool* requireSwap) {
110 GL_CHECKPOINT(LOW);
111
112 // Even if we decided to cancel the frame, from the perspective of jank
113 // metrics the frame was swapped at this point
114 currentFrameInfo->markSwapBuffers();
115
116 *requireSwap = drew || mEglManager.damageRequiresSwap();
117
118 if (*requireSwap && (CC_UNLIKELY(!mEglManager.swapBuffers(frame, screenDirty)))) {
119 return false;
120 }
121
122 return *requireSwap;
123 }
124
copyLayerInto(DeferredLayerUpdater * deferredLayer,SkBitmap * bitmap)125 bool SkiaOpenGLPipeline::copyLayerInto(DeferredLayerUpdater* deferredLayer, SkBitmap* bitmap) {
126 if (!mRenderThread.getGrContext()) {
127 return false;
128 }
129
130 // acquire most recent buffer for drawing
131 deferredLayer->updateTexImage();
132 deferredLayer->apply();
133
134 // drop the colorSpace as we only support readback into sRGB or extended sRGB
135 SkImageInfo surfaceInfo = bitmap->info().makeColorSpace(nullptr);
136
137 /* This intermediate surface is present to work around a bug in SwiftShader that
138 * prevents us from reading the contents of the layer's texture directly. The
139 * workaround involves first rendering that texture into an intermediate buffer and
140 * then reading from the intermediate buffer into the bitmap.
141 */
142 sk_sp<SkSurface> tmpSurface = SkSurface::MakeRenderTarget(mRenderThread.getGrContext(),
143 SkBudgeted::kYes, surfaceInfo);
144
145 if (!tmpSurface.get()) {
146 surfaceInfo = surfaceInfo.makeColorType(SkColorType::kN32_SkColorType);
147 tmpSurface = SkSurface::MakeRenderTarget(mRenderThread.getGrContext(),
148 SkBudgeted::kYes, surfaceInfo);
149 if (!tmpSurface.get()) {
150 ALOGW("Unable to readback GPU contents into the provided bitmap");
151 return false;
152 }
153 }
154
155 Layer* layer = deferredLayer->backingLayer();
156 const SkRect dstRect = SkRect::MakeIWH(bitmap->width(), bitmap->height());
157 if (LayerDrawable::DrawLayer(mRenderThread.getGrContext(), tmpSurface->getCanvas(), layer,
158 &dstRect)) {
159 sk_sp<SkImage> tmpImage = tmpSurface->makeImageSnapshot();
160 if (tmpImage->readPixels(surfaceInfo, bitmap->getPixels(), bitmap->rowBytes(), 0, 0)) {
161 bitmap->notifyPixelsChanged();
162 return true;
163 }
164
165 // if we fail to readback from the GPU directly (e.g. 565) then we attempt to read into 8888
166 // and then draw that into the destination format before giving up.
167 SkBitmap tmpBitmap;
168 SkImageInfo bitmapInfo = SkImageInfo::MakeN32(bitmap->width(), bitmap->height(),
169 bitmap->alphaType());
170 if (tmpBitmap.tryAllocPixels(bitmapInfo) &&
171 tmpImage->readPixels(bitmapInfo, tmpBitmap.getPixels(),
172 tmpBitmap.rowBytes(), 0, 0)) {
173 SkCanvas canvas(*bitmap);
174 SkPaint paint;
175 paint.setBlendMode(SkBlendMode::kSrc);
176 canvas.drawBitmap(tmpBitmap, 0, 0, &paint);
177 bitmap->notifyPixelsChanged();
178 return true;
179 }
180 }
181
182 return false;
183 }
184
createLayer(RenderState & renderState,uint32_t layerWidth,uint32_t layerHeight,sk_sp<SkColorFilter> colorFilter,int alpha,SkBlendMode mode,bool blend)185 static Layer* createLayer(RenderState& renderState, uint32_t layerWidth, uint32_t layerHeight,
186 sk_sp<SkColorFilter> colorFilter, int alpha, SkBlendMode mode, bool blend) {
187 GlLayer* layer =
188 new GlLayer(renderState, layerWidth, layerHeight, colorFilter, alpha, mode, blend);
189 layer->generateTexture();
190 return layer;
191 }
192
createTextureLayer()193 DeferredLayerUpdater* SkiaOpenGLPipeline::createTextureLayer() {
194 mEglManager.initialize();
195 return new DeferredLayerUpdater(mRenderThread.renderState(), createLayer, Layer::Api::OpenGL);
196 }
197
onStop()198 void SkiaOpenGLPipeline::onStop() {
199 if (mEglManager.isCurrent(mEglSurface)) {
200 mEglManager.makeCurrent(EGL_NO_SURFACE);
201 }
202 }
203
setSurface(Surface * surface,SwapBehavior swapBehavior,ColorMode colorMode)204 bool SkiaOpenGLPipeline::setSurface(Surface* surface, SwapBehavior swapBehavior,
205 ColorMode colorMode) {
206 if (mEglSurface != EGL_NO_SURFACE) {
207 mEglManager.destroySurface(mEglSurface);
208 mEglSurface = EGL_NO_SURFACE;
209 }
210
211 if (surface) {
212 const bool wideColorGamut = colorMode == ColorMode::WideColorGamut;
213 mEglSurface = mEglManager.createSurface(surface, wideColorGamut);
214 }
215
216 if (mEglSurface != EGL_NO_SURFACE) {
217 const bool preserveBuffer = (swapBehavior != SwapBehavior::kSwap_discardBuffer);
218 mBufferPreserved = mEglManager.setPreserveBuffer(mEglSurface, preserveBuffer);
219 return true;
220 }
221
222 return false;
223 }
224
isSurfaceReady()225 bool SkiaOpenGLPipeline::isSurfaceReady() {
226 return CC_UNLIKELY(mEglSurface != EGL_NO_SURFACE);
227 }
228
isContextReady()229 bool SkiaOpenGLPipeline::isContextReady() {
230 return CC_LIKELY(mEglManager.hasEglContext());
231 }
232
invokeFunctor(const RenderThread & thread,Functor * functor)233 void SkiaOpenGLPipeline::invokeFunctor(const RenderThread& thread, Functor* functor) {
234 DrawGlInfo::Mode mode = DrawGlInfo::kModeProcessNoContext;
235 if (thread.eglManager().hasEglContext()) {
236 mode = DrawGlInfo::kModeProcess;
237 }
238
239 (*functor)(mode, nullptr);
240
241 // If there's no context we don't need to reset as there's no gl state to save/restore
242 if (mode != DrawGlInfo::kModeProcessNoContext) {
243 thread.getGrContext()->resetContext();
244 }
245 }
246
247 #define FENCE_TIMEOUT 2000000000
248
249 class AutoEglFence {
250 public:
AutoEglFence(EGLDisplay display)251 AutoEglFence(EGLDisplay display) : mDisplay(display) {
252 fence = eglCreateSyncKHR(mDisplay, EGL_SYNC_FENCE_KHR, NULL);
253 }
254
~AutoEglFence()255 ~AutoEglFence() {
256 if (fence != EGL_NO_SYNC_KHR) {
257 eglDestroySyncKHR(mDisplay, fence);
258 }
259 }
260
261 EGLSyncKHR fence = EGL_NO_SYNC_KHR;
262
263 private:
264 EGLDisplay mDisplay = EGL_NO_DISPLAY;
265 };
266
267 class AutoEglImage {
268 public:
AutoEglImage(EGLDisplay display,EGLClientBuffer clientBuffer)269 AutoEglImage(EGLDisplay display, EGLClientBuffer clientBuffer) : mDisplay(display) {
270 EGLint imageAttrs[] = {EGL_IMAGE_PRESERVED_KHR, EGL_TRUE, EGL_NONE};
271 image = eglCreateImageKHR(display, EGL_NO_CONTEXT, EGL_NATIVE_BUFFER_ANDROID, clientBuffer,
272 imageAttrs);
273 }
274
~AutoEglImage()275 ~AutoEglImage() {
276 if (image != EGL_NO_IMAGE_KHR) {
277 eglDestroyImageKHR(mDisplay, image);
278 }
279 }
280
281 EGLImageKHR image = EGL_NO_IMAGE_KHR;
282
283 private:
284 EGLDisplay mDisplay = EGL_NO_DISPLAY;
285 };
286
287 class AutoSkiaGlTexture {
288 public:
AutoSkiaGlTexture()289 AutoSkiaGlTexture() {
290 glGenTextures(1, &mTexture);
291 glBindTexture(GL_TEXTURE_2D, mTexture);
292 }
293
~AutoSkiaGlTexture()294 ~AutoSkiaGlTexture() { glDeleteTextures(1, &mTexture); }
295
296 private:
297 GLuint mTexture = 0;
298 };
299
isFP16Supported(const sk_sp<GrContext> & grContext)300 static bool isFP16Supported(const sk_sp<GrContext>& grContext) {
301 static std::once_flag sOnceFlag;
302 static bool supported = false;
303
304 std::call_once(sOnceFlag, [](const sk_sp<GrContext>& grContext) {
305 if (!grContext->caps()->isConfigTexturable(kRGBA_half_GrPixelConfig)) {
306 supported = false;
307 return;
308 }
309
310 sp<GraphicBuffer> buffer = new GraphicBuffer(1, 1, PIXEL_FORMAT_RGBA_FP16,
311 GraphicBuffer::USAGE_HW_TEXTURE | GraphicBuffer::USAGE_SW_WRITE_NEVER |
312 GraphicBuffer::USAGE_SW_READ_NEVER, "tempFp16Buffer");
313 status_t error = buffer->initCheck();
314 supported = !error;
315 }, grContext);
316
317 return supported;
318 }
319
allocateHardwareBitmap(renderthread::RenderThread & renderThread,SkBitmap & skBitmap)320 sk_sp<Bitmap> SkiaOpenGLPipeline::allocateHardwareBitmap(renderthread::RenderThread& renderThread,
321 SkBitmap& skBitmap) {
322 renderThread.eglManager().initialize();
323
324 sk_sp<GrContext> grContext = sk_ref_sp(renderThread.getGrContext());
325 const SkImageInfo& info = skBitmap.info();
326 PixelFormat pixelFormat;
327 GLint format, type;
328 bool isSupported = false;
329
330 // TODO: add support for linear blending (when ANDROID_ENABLE_LINEAR_BLENDING is defined)
331 switch (info.colorType()) {
332 case kRGBA_8888_SkColorType:
333 isSupported = true;
334 // ARGB_4444 is upconverted to RGBA_8888
335 case kARGB_4444_SkColorType:
336 pixelFormat = PIXEL_FORMAT_RGBA_8888;
337 format = GL_RGBA;
338 type = GL_UNSIGNED_BYTE;
339 break;
340 case kRGBA_F16_SkColorType:
341 isSupported = isFP16Supported(grContext);
342 if (isSupported) {
343 type = GL_HALF_FLOAT;
344 pixelFormat = PIXEL_FORMAT_RGBA_FP16;
345 } else {
346 type = GL_UNSIGNED_BYTE;
347 pixelFormat = PIXEL_FORMAT_RGBA_8888;
348 }
349 format = GL_RGBA;
350 break;
351 case kRGB_565_SkColorType:
352 isSupported = true;
353 pixelFormat = PIXEL_FORMAT_RGB_565;
354 format = GL_RGB;
355 type = GL_UNSIGNED_SHORT_5_6_5;
356 break;
357 case kGray_8_SkColorType:
358 isSupported = true;
359 pixelFormat = PIXEL_FORMAT_RGBA_8888;
360 format = GL_LUMINANCE;
361 type = GL_UNSIGNED_BYTE;
362 break;
363 default:
364 ALOGW("unable to create hardware bitmap of colortype: %d", info.colorType());
365 return nullptr;
366 }
367
368 SkBitmap bitmap;
369 if (isSupported) {
370 bitmap = skBitmap;
371 } else {
372 bitmap.allocPixels(
373 SkImageInfo::MakeN32(info.width(), info.height(), info.alphaType(), nullptr));
374 bitmap.eraseColor(0);
375 if (info.colorType() == kRGBA_F16_SkColorType) {
376 // Drawing RGBA_F16 onto ARGB_8888 is not supported
377 skBitmap.readPixels(bitmap.info().makeColorSpace(SkColorSpace::MakeSRGB()),
378 bitmap.getPixels(), bitmap.rowBytes(), 0, 0);
379 } else {
380 SkCanvas canvas(bitmap);
381 canvas.drawBitmap(skBitmap, 0.0f, 0.0f, nullptr);
382 }
383 }
384
385 sp<GraphicBuffer> buffer = new GraphicBuffer(
386 info.width(), info.height(), pixelFormat,
387 GraphicBuffer::USAGE_HW_TEXTURE | GraphicBuffer::USAGE_SW_WRITE_NEVER |
388 GraphicBuffer::USAGE_SW_READ_NEVER,
389 std::string("Bitmap::allocateSkiaHardwareBitmap pid [") + std::to_string(getpid()) +
390 "]");
391
392 status_t error = buffer->initCheck();
393 if (error < 0) {
394 ALOGW("createGraphicBuffer() failed in GraphicBuffer.create()");
395 return nullptr;
396 }
397
398 // upload the bitmap into a texture
399 EGLDisplay display = eglGetCurrentDisplay();
400 LOG_ALWAYS_FATAL_IF(display == EGL_NO_DISPLAY, "Failed to get EGL_DEFAULT_DISPLAY! err=%s",
401 uirenderer::renderthread::EglManager::eglErrorString());
402 // We use an EGLImage to access the content of the GraphicBuffer
403 // The EGL image is later bound to a 2D texture
404 EGLClientBuffer clientBuffer = (EGLClientBuffer)buffer->getNativeBuffer();
405 AutoEglImage autoImage(display, clientBuffer);
406 if (autoImage.image == EGL_NO_IMAGE_KHR) {
407 ALOGW("Could not create EGL image, err =%s",
408 uirenderer::renderthread::EglManager::eglErrorString());
409 return nullptr;
410 }
411 AutoSkiaGlTexture glTexture;
412 glEGLImageTargetTexture2DOES(GL_TEXTURE_2D, autoImage.image);
413 GL_CHECKPOINT(MODERATE);
414
415 // glTexSubImage2D is synchronous in sense that it memcpy() from pointer that we provide.
416 // But asynchronous in sense that driver may upload texture onto hardware buffer when we first
417 // use it in drawing
418 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, info.width(), info.height(), format, type,
419 bitmap.getPixels());
420 GL_CHECKPOINT(MODERATE);
421
422 // The fence is used to wait for the texture upload to finish
423 // properly. We cannot rely on glFlush() and glFinish() as
424 // some drivers completely ignore these API calls
425 AutoEglFence autoFence(display);
426 if (autoFence.fence == EGL_NO_SYNC_KHR) {
427 LOG_ALWAYS_FATAL("Could not create sync fence %#x", eglGetError());
428 return nullptr;
429 }
430 // The flag EGL_SYNC_FLUSH_COMMANDS_BIT_KHR will trigger a
431 // pipeline flush (similar to what a glFlush() would do.)
432 EGLint waitStatus = eglClientWaitSyncKHR(display, autoFence.fence,
433 EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, FENCE_TIMEOUT);
434 if (waitStatus != EGL_CONDITION_SATISFIED_KHR) {
435 LOG_ALWAYS_FATAL("Failed to wait for the fence %#x", eglGetError());
436 return nullptr;
437 }
438
439 grContext->resetContext(kTextureBinding_GrGLBackendState);
440
441 return sk_sp<Bitmap>(new Bitmap(buffer.get(), bitmap.info()));
442 }
443
444 } /* namespace skiapipeline */
445 } /* namespace uirenderer */
446 } /* namespace android */
447