CanvasContext.cpp revision fe5e7b7346a54537b980796ceeca66bfdbd05561
1/* 2 * Copyright (C) 2014 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#define LOG_TAG "CanvasContext" 18 19#include "CanvasContext.h" 20 21#include <cutils/properties.h> 22#include <private/hwui/DrawGlInfo.h> 23#include <strings.h> 24 25#include "RenderThread.h" 26#include "../Caches.h" 27#include "../DeferredLayerUpdater.h" 28#include "../LayerRenderer.h" 29#include "../OpenGLRenderer.h" 30#include "../Stencil.h" 31 32#define PROPERTY_RENDER_DIRTY_REGIONS "debug.hwui.render_dirty_regions" 33#define GLES_VERSION 2 34#define USE_TEXTURE_ATLAS false 35 36// Android-specific addition that is used to show when frames began in systrace 37EGLAPI void EGLAPIENTRY eglBeginFrame(EGLDisplay dpy, EGLSurface surface); 38 39namespace android { 40namespace uirenderer { 41namespace renderthread { 42 43#define ERROR_CASE(x) case x: return #x; 44static const char* egl_error_str(EGLint error) { 45 switch (error) { 46 ERROR_CASE(EGL_SUCCESS) 47 ERROR_CASE(EGL_NOT_INITIALIZED) 48 ERROR_CASE(EGL_BAD_ACCESS) 49 ERROR_CASE(EGL_BAD_ALLOC) 50 ERROR_CASE(EGL_BAD_ATTRIBUTE) 51 ERROR_CASE(EGL_BAD_CONFIG) 52 ERROR_CASE(EGL_BAD_CONTEXT) 53 ERROR_CASE(EGL_BAD_CURRENT_SURFACE) 54 ERROR_CASE(EGL_BAD_DISPLAY) 55 ERROR_CASE(EGL_BAD_MATCH) 56 ERROR_CASE(EGL_BAD_NATIVE_PIXMAP) 57 ERROR_CASE(EGL_BAD_NATIVE_WINDOW) 58 ERROR_CASE(EGL_BAD_PARAMETER) 59 ERROR_CASE(EGL_BAD_SURFACE) 60 ERROR_CASE(EGL_CONTEXT_LOST) 61 default: 62 return "Unknown error"; 63 } 64} 65static const char* egl_error_str() { 66 return egl_error_str(eglGetError()); 67} 68 69static bool load_dirty_regions_property() { 70 char buf[PROPERTY_VALUE_MAX]; 71 int len = property_get(PROPERTY_RENDER_DIRTY_REGIONS, buf, "true"); 72 return !strncasecmp("true", buf, len); 73} 74 75// This class contains the shared global EGL objects, such as EGLDisplay 76// and EGLConfig, which are re-used by CanvasContext 77class GlobalContext { 78public: 79 static GlobalContext* get(); 80 81 // Returns true on success, false on failure 82 void initialize(); 83 84 bool hasContext(); 85 86 void usePBufferSurface(); 87 EGLSurface createSurface(EGLNativeWindowType window); 88 void destroySurface(EGLSurface surface); 89 90 void destroy(); 91 92 bool isCurrent(EGLSurface surface) { return mCurrentSurface == surface; } 93 // Returns true if the current surface changed, false if it was already current 94 bool makeCurrent(EGLSurface surface); 95 void beginFrame(EGLSurface surface, EGLint* width, EGLint* height); 96 void swapBuffers(EGLSurface surface); 97 98 bool enableDirtyRegions(EGLSurface surface); 99 100 void setTextureAtlas(const sp<GraphicBuffer>& buffer, int64_t* map, size_t mapSize); 101 102private: 103 GlobalContext(); 104 // GlobalContext is never destroyed, method is purposely not implemented 105 ~GlobalContext(); 106 107 void loadConfig(); 108 void createContext(); 109 void initAtlas(); 110 111 static GlobalContext* sContext; 112 113 EGLDisplay mEglDisplay; 114 EGLConfig mEglConfig; 115 EGLContext mEglContext; 116 EGLSurface mPBufferSurface; 117 118 const bool mRequestDirtyRegions; 119 bool mCanSetDirtyRegions; 120 121 EGLSurface mCurrentSurface; 122 123 sp<GraphicBuffer> mAtlasBuffer; 124 int64_t* mAtlasMap; 125 size_t mAtlasMapSize; 126}; 127 128GlobalContext* GlobalContext::sContext = 0; 129 130GlobalContext* GlobalContext::get() { 131 if (!sContext) { 132 sContext = new GlobalContext(); 133 } 134 return sContext; 135} 136 137GlobalContext::GlobalContext() 138 : mEglDisplay(EGL_NO_DISPLAY) 139 , mEglConfig(0) 140 , mEglContext(EGL_NO_CONTEXT) 141 , mPBufferSurface(EGL_NO_SURFACE) 142 , mRequestDirtyRegions(load_dirty_regions_property()) 143 , mCurrentSurface(EGL_NO_SURFACE) 144 , mAtlasMap(NULL) 145 , mAtlasMapSize(0) { 146 mCanSetDirtyRegions = mRequestDirtyRegions; 147 ALOGD("Render dirty regions requested: %s", mRequestDirtyRegions ? "true" : "false"); 148} 149 150void GlobalContext::initialize() { 151 if (hasContext()) return; 152 153 mEglDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY); 154 LOG_ALWAYS_FATAL_IF(mEglDisplay == EGL_NO_DISPLAY, 155 "Failed to get EGL_DEFAULT_DISPLAY! err=%s", egl_error_str()); 156 157 EGLint major, minor; 158 LOG_ALWAYS_FATAL_IF(eglInitialize(mEglDisplay, &major, &minor) == EGL_FALSE, 159 "Failed to initialize display %p! err=%s", mEglDisplay, egl_error_str()); 160 161 ALOGI("Initialized EGL, version %d.%d", (int)major, (int)minor); 162 163 loadConfig(); 164 createContext(); 165 usePBufferSurface(); 166 Caches::getInstance().init(); 167 initAtlas(); 168} 169 170bool GlobalContext::hasContext() { 171 return mEglDisplay != EGL_NO_DISPLAY; 172} 173 174void GlobalContext::loadConfig() { 175 EGLint swapBehavior = mCanSetDirtyRegions ? EGL_SWAP_BEHAVIOR_PRESERVED_BIT : 0; 176 EGLint attribs[] = { 177 EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, 178 EGL_RED_SIZE, 8, 179 EGL_GREEN_SIZE, 8, 180 EGL_BLUE_SIZE, 8, 181 EGL_ALPHA_SIZE, 8, 182 EGL_DEPTH_SIZE, 0, 183 EGL_CONFIG_CAVEAT, EGL_NONE, 184 EGL_STENCIL_SIZE, Stencil::getStencilSize(), 185 EGL_SURFACE_TYPE, EGL_WINDOW_BIT | swapBehavior, 186 EGL_NONE 187 }; 188 189 EGLint num_configs = 1; 190 if (!eglChooseConfig(mEglDisplay, attribs, &mEglConfig, num_configs, &num_configs) 191 || num_configs != 1) { 192 // Failed to get a valid config 193 if (mCanSetDirtyRegions) { 194 ALOGW("Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without..."); 195 // Try again without dirty regions enabled 196 mCanSetDirtyRegions = false; 197 loadConfig(); 198 } else { 199 LOG_ALWAYS_FATAL("Failed to choose config, error = %s", egl_error_str()); 200 } 201 } 202} 203 204void GlobalContext::createContext() { 205 EGLint attribs[] = { EGL_CONTEXT_CLIENT_VERSION, GLES_VERSION, EGL_NONE }; 206 mEglContext = eglCreateContext(mEglDisplay, mEglConfig, EGL_NO_CONTEXT, attribs); 207 LOG_ALWAYS_FATAL_IF(mEglContext == EGL_NO_CONTEXT, 208 "Failed to create context, error = %s", egl_error_str()); 209} 210 211void GlobalContext::setTextureAtlas(const sp<GraphicBuffer>& buffer, 212 int64_t* map, size_t mapSize) { 213 214 // Already initialized 215 if (mAtlasBuffer.get()) { 216 ALOGW("Multiple calls to setTextureAtlas!"); 217 delete map; 218 return; 219 } 220 221 mAtlasBuffer = buffer; 222 mAtlasMap = map; 223 mAtlasMapSize = mapSize; 224 225 if (hasContext()) { 226 usePBufferSurface(); 227 initAtlas(); 228 } 229} 230 231void GlobalContext::initAtlas() { 232 if (USE_TEXTURE_ATLAS) { 233 Caches::getInstance().assetAtlas.init(mAtlasBuffer, mAtlasMap, mAtlasMapSize); 234 } 235} 236 237void GlobalContext::usePBufferSurface() { 238 LOG_ALWAYS_FATAL_IF(mEglDisplay == EGL_NO_DISPLAY, 239 "usePBufferSurface() called on uninitialized GlobalContext!"); 240 241 if (mPBufferSurface == EGL_NO_SURFACE) { 242 EGLint attribs[] = { EGL_WIDTH, 1, EGL_HEIGHT, 1, EGL_NONE }; 243 mPBufferSurface = eglCreatePbufferSurface(mEglDisplay, mEglConfig, attribs); 244 } 245 makeCurrent(mPBufferSurface); 246} 247 248EGLSurface GlobalContext::createSurface(EGLNativeWindowType window) { 249 initialize(); 250 return eglCreateWindowSurface(mEglDisplay, mEglConfig, window, NULL); 251} 252 253void GlobalContext::destroySurface(EGLSurface surface) { 254 if (isCurrent(surface)) { 255 makeCurrent(EGL_NO_SURFACE); 256 } 257 if (!eglDestroySurface(mEglDisplay, surface)) { 258 ALOGW("Failed to destroy surface %p, error=%s", (void*)surface, egl_error_str()); 259 } 260} 261 262void GlobalContext::destroy() { 263 if (mEglDisplay == EGL_NO_DISPLAY) return; 264 265 usePBufferSurface(); 266 if (Caches::hasInstance()) { 267 Caches::getInstance().terminate(); 268 } 269 270 eglDestroyContext(mEglDisplay, mEglContext); 271 eglDestroySurface(mEglDisplay, mPBufferSurface); 272 eglMakeCurrent(mEglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); 273 eglTerminate(mEglDisplay); 274 eglReleaseThread(); 275 276 mEglDisplay = EGL_NO_DISPLAY; 277 mEglContext = EGL_NO_CONTEXT; 278 mPBufferSurface = EGL_NO_SURFACE; 279 mCurrentSurface = EGL_NO_SURFACE; 280} 281 282bool GlobalContext::makeCurrent(EGLSurface surface) { 283 if (isCurrent(surface)) return false; 284 285 if (surface == EGL_NO_SURFACE) { 286 // If we are setting EGL_NO_SURFACE we don't care about any of the potential 287 // return errors, which would only happen if mEglDisplay had already been 288 // destroyed in which case the current context is already NO_CONTEXT 289 eglMakeCurrent(mEglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); 290 } else if (!eglMakeCurrent(mEglDisplay, surface, surface, mEglContext)) { 291 LOG_ALWAYS_FATAL("Failed to make current on surface %p, error=%s", 292 (void*)surface, egl_error_str()); 293 } 294 mCurrentSurface = surface; 295 return true; 296} 297 298void GlobalContext::beginFrame(EGLSurface surface, EGLint* width, EGLint* height) { 299 LOG_ALWAYS_FATAL_IF(surface == EGL_NO_SURFACE, 300 "Tried to beginFrame on EGL_NO_SURFACE!"); 301 makeCurrent(surface); 302 if (width) { 303 eglQuerySurface(mEglDisplay, surface, EGL_WIDTH, width); 304 } 305 if (height) { 306 eglQuerySurface(mEglDisplay, surface, EGL_HEIGHT, height); 307 } 308 eglBeginFrame(mEglDisplay, surface); 309} 310 311void GlobalContext::swapBuffers(EGLSurface surface) { 312 eglSwapBuffers(mEglDisplay, surface); 313 EGLint err = eglGetError(); 314 LOG_ALWAYS_FATAL_IF(err != EGL_SUCCESS, 315 "Encountered EGL error %d %s during rendering", err, egl_error_str(err)); 316} 317 318bool GlobalContext::enableDirtyRegions(EGLSurface surface) { 319 if (!mRequestDirtyRegions) return false; 320 321 if (mCanSetDirtyRegions) { 322 if (!eglSurfaceAttrib(mEglDisplay, surface, EGL_SWAP_BEHAVIOR, EGL_BUFFER_PRESERVED)) { 323 ALOGW("Failed to set EGL_SWAP_BEHAVIOR on surface %p, error=%s", 324 (void*) surface, egl_error_str()); 325 return false; 326 } 327 return true; 328 } 329 // Perhaps it is already enabled? 330 EGLint value; 331 if (!eglQuerySurface(mEglDisplay, surface, EGL_SWAP_BEHAVIOR, &value)) { 332 ALOGW("Failed to query EGL_SWAP_BEHAVIOR on surface %p, error=%p", 333 (void*) surface, egl_error_str()); 334 return false; 335 } 336 return value == EGL_BUFFER_PRESERVED; 337} 338 339CanvasContext::CanvasContext(bool translucent, RenderNode* rootRenderNode) 340 : mRenderThread(RenderThread::getInstance()) 341 , mEglSurface(EGL_NO_SURFACE) 342 , mDirtyRegionsEnabled(false) 343 , mOpaque(!translucent) 344 , mCanvas(0) 345 , mHaveNewSurface(false) 346 , mRootRenderNode(rootRenderNode) { 347 mGlobalContext = GlobalContext::get(); 348} 349 350CanvasContext::~CanvasContext() { 351 destroyCanvasAndSurface(); 352 mRenderThread.removeFrameCallback(this); 353} 354 355void CanvasContext::destroyCanvasAndSurface() { 356 if (mCanvas) { 357 delete mCanvas; 358 mCanvas = 0; 359 } 360 setSurface(NULL); 361} 362 363void CanvasContext::setSurface(ANativeWindow* window) { 364 mNativeWindow = window; 365 366 if (mEglSurface != EGL_NO_SURFACE) { 367 mGlobalContext->destroySurface(mEglSurface); 368 mEglSurface = EGL_NO_SURFACE; 369 } 370 371 if (window) { 372 mEglSurface = mGlobalContext->createSurface(window); 373 LOG_ALWAYS_FATAL_IF(mEglSurface == EGL_NO_SURFACE, 374 "Failed to create EGLSurface for window %p, eglErr = %s", 375 (void*) window, egl_error_str()); 376 } 377 378 if (mEglSurface != EGL_NO_SURFACE) { 379 mDirtyRegionsEnabled = mGlobalContext->enableDirtyRegions(mEglSurface); 380 mHaveNewSurface = true; 381 makeCurrent(); 382 } else { 383 mRenderThread.removeFrameCallback(this); 384 } 385} 386 387void CanvasContext::swapBuffers() { 388 mGlobalContext->swapBuffers(mEglSurface); 389 mHaveNewSurface = false; 390} 391 392void CanvasContext::requireSurface() { 393 LOG_ALWAYS_FATAL_IF(mEglSurface == EGL_NO_SURFACE, 394 "requireSurface() called but no surface set!"); 395 makeCurrent(); 396} 397 398bool CanvasContext::initialize(ANativeWindow* window) { 399 if (mCanvas) return false; 400 setSurface(window); 401 mCanvas = new OpenGLRenderer(); 402 mCanvas->initProperties(); 403 return true; 404} 405 406void CanvasContext::updateSurface(ANativeWindow* window) { 407 setSurface(window); 408} 409 410void CanvasContext::pauseSurface(ANativeWindow* window) { 411 // TODO: For now we just need a fence, in the future suspend any animations 412 // and such to prevent from trying to render into this surface 413} 414 415void CanvasContext::setup(int width, int height, const Vector3& lightCenter, float lightRadius) { 416 if (!mCanvas) return; 417 mCanvas->setViewport(width, height); 418 mCanvas->initializeLight(lightCenter, lightRadius); 419} 420 421void CanvasContext::setOpaque(bool opaque) { 422 mOpaque = opaque; 423} 424 425void CanvasContext::makeCurrent() { 426 // TODO: Figure out why this workaround is needed, see b/13913604 427 // In the meantime this matches the behavior of GLRenderer, so it is not a regression 428 mHaveNewSurface |= mGlobalContext->makeCurrent(mEglSurface); 429} 430 431void CanvasContext::prepareDraw(const Vector<DeferredLayerUpdater*>* layerUpdaters, 432 TreeInfo& info) { 433 LOG_ALWAYS_FATAL_IF(!mCanvas, "Cannot prepareDraw without a canvas!"); 434 makeCurrent(); 435 436 processLayerUpdates(layerUpdaters, info); 437 if (info.out.hasAnimations) { 438 // TODO: Uh... crap? 439 } 440 prepareTree(info); 441} 442 443void CanvasContext::processLayerUpdates(const Vector<DeferredLayerUpdater*>* layerUpdaters, 444 TreeInfo& info) { 445 for (size_t i = 0; i < layerUpdaters->size(); i++) { 446 DeferredLayerUpdater* update = layerUpdaters->itemAt(i); 447 bool success = update->apply(info); 448 LOG_ALWAYS_FATAL_IF(!success, "Failed to update layer!"); 449 if (update->backingLayer()->deferredUpdateScheduled) { 450 mCanvas->pushLayerUpdate(update->backingLayer()); 451 } 452 } 453} 454 455void CanvasContext::prepareTree(TreeInfo& info) { 456 mRenderThread.removeFrameCallback(this); 457 458 info.frameTimeMs = mRenderThread.timeLord().frameTimeMs(); 459 mRootRenderNode->prepareTree(info); 460 461 int runningBehind = 0; 462 // TODO: This query is moderately expensive, investigate adding some sort 463 // of fast-path based off when we last called eglSwapBuffers() as well as 464 // last vsync time. Or something. 465 mNativeWindow->query(mNativeWindow.get(), 466 NATIVE_WINDOW_CONSUMER_RUNNING_BEHIND, &runningBehind); 467 info.out.canDrawThisFrame = !runningBehind; 468 469 if (info.out.hasAnimations || !info.out.canDrawThisFrame) { 470 if (info.out.hasFunctors) { 471 info.out.requiresUiRedraw = true; 472 } else if (!info.out.requiresUiRedraw) { 473 // If animationsNeedsRedraw is set don't bother posting for an RT anim 474 // as we will just end up fighting the UI thread. 475 mRenderThread.postFrameCallback(this); 476 } 477 } 478} 479 480void CanvasContext::notifyFramePending() { 481 ATRACE_CALL(); 482 mRenderThread.pushBackFrameCallback(this); 483} 484 485void CanvasContext::draw(Rect* dirty) { 486 LOG_ALWAYS_FATAL_IF(!mCanvas || mEglSurface == EGL_NO_SURFACE, 487 "drawDisplayList called on a context with no canvas or surface!"); 488 489 profiler().markPlaybackStart(); 490 491 EGLint width, height; 492 mGlobalContext->beginFrame(mEglSurface, &width, &height); 493 if (width != mCanvas->getViewportWidth() || height != mCanvas->getViewportHeight()) { 494 mCanvas->setViewport(width, height); 495 dirty = NULL; 496 } else if (!mDirtyRegionsEnabled || mHaveNewSurface) { 497 dirty = NULL; 498 } else { 499 profiler().unionDirty(dirty); 500 } 501 502 status_t status; 503 if (dirty && !dirty->isEmpty()) { 504 status = mCanvas->prepareDirty(dirty->left, dirty->top, 505 dirty->right, dirty->bottom, mOpaque); 506 } else { 507 status = mCanvas->prepare(mOpaque); 508 } 509 510 Rect outBounds; 511 status |= mCanvas->drawDisplayList(mRootRenderNode.get(), outBounds); 512 513 profiler().draw(mCanvas); 514 515 mCanvas->finish(); 516 517 profiler().markPlaybackEnd(); 518 519 if (status & DrawGlInfo::kStatusDrew) { 520 swapBuffers(); 521 } 522 523 profiler().finishFrame(); 524} 525 526// Called by choreographer to do an RT-driven animation 527void CanvasContext::doFrame() { 528 if (CC_UNLIKELY(!mCanvas || mEglSurface == EGL_NO_SURFACE)) { 529 return; 530 } 531 532 ATRACE_CALL(); 533 534 profiler().startFrame(); 535 536 TreeInfo info; 537 info.evaluateAnimations = true; 538 info.performStagingPush = false; 539 info.prepareTextures = false; 540 541 prepareTree(info); 542 if (info.out.canDrawThisFrame) { 543 draw(NULL); 544 } 545} 546 547void CanvasContext::invokeFunctor(Functor* functor) { 548 ATRACE_CALL(); 549 DrawGlInfo::Mode mode = DrawGlInfo::kModeProcessNoContext; 550 if (mGlobalContext->hasContext()) { 551 requireGlContext(); 552 mode = DrawGlInfo::kModeProcess; 553 } 554 (*functor)(mode, NULL); 555 556 if (mCanvas) { 557 mCanvas->resume(); 558 } 559} 560 561bool CanvasContext::copyLayerInto(DeferredLayerUpdater* layer, SkBitmap* bitmap) { 562 requireGlContext(); 563 TreeInfo info; 564 layer->apply(info); 565 return LayerRenderer::copyLayer(layer->backingLayer(), bitmap); 566} 567 568void CanvasContext::flushCaches(Caches::FlushMode flushMode) { 569 if (mGlobalContext->hasContext()) { 570 requireGlContext(); 571 Caches::getInstance().flush(flushMode); 572 } 573} 574 575void CanvasContext::runWithGlContext(RenderTask* task) { 576 requireGlContext(); 577 task->run(); 578} 579 580Layer* CanvasContext::createRenderLayer(int width, int height) { 581 requireSurface(); 582 return LayerRenderer::createRenderLayer(width, height); 583} 584 585Layer* CanvasContext::createTextureLayer() { 586 requireSurface(); 587 return LayerRenderer::createTextureLayer(); 588} 589 590void CanvasContext::requireGlContext() { 591 if (mEglSurface != EGL_NO_SURFACE) { 592 makeCurrent(); 593 } else { 594 mGlobalContext->usePBufferSurface(); 595 } 596} 597 598void CanvasContext::setTextureAtlas(const sp<GraphicBuffer>& buffer, 599 int64_t* map, size_t mapSize) { 600 GlobalContext::get()->setTextureAtlas(buffer, map, mapSize); 601} 602 603} /* namespace renderthread */ 604} /* namespace uirenderer */ 605} /* namespace android */ 606