CanvasContext.cpp revision 50210d912925aef14e4ce69be82e4949122a3cd9
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#include "CanvasContext.h" 18 19#include "AnimationContext.h" 20#include "Caches.h" 21#include "DeferredLayerUpdater.h" 22#include "EglManager.h" 23#include "LayerRenderer.h" 24#include "OpenGLRenderer.h" 25#include "Properties.h" 26#include "RenderThread.h" 27#include "renderstate/RenderState.h" 28#include "renderstate/Stencil.h" 29 30#include <algorithm> 31#include <strings.h> 32#include <cutils/properties.h> 33#include <private/hwui/DrawGlInfo.h> 34 35#define TRIM_MEMORY_COMPLETE 80 36#define TRIM_MEMORY_UI_HIDDEN 20 37 38namespace android { 39namespace uirenderer { 40namespace renderthread { 41 42CanvasContext::CanvasContext(RenderThread& thread, bool translucent, 43 RenderNode* rootRenderNode, IContextFactory* contextFactory) 44 : mRenderThread(thread) 45 , mEglManager(thread.eglManager()) 46 , mOpaque(!translucent) 47 , mAnimationContext(contextFactory->createAnimationContext(mRenderThread.timeLord())) 48 , mRootRenderNode(rootRenderNode) 49 , mJankTracker(thread.timeLord().frameIntervalNanos()) 50 , mProfiler(mFrames) { 51 mRenderThread.renderState().registerCanvasContext(this); 52 mProfiler.setDensity(mRenderThread.mainDisplayInfo().density); 53} 54 55CanvasContext::~CanvasContext() { 56 destroy(); 57 mRenderThread.renderState().unregisterCanvasContext(this); 58} 59 60void CanvasContext::destroy() { 61 stopDrawing(); 62 setSurface(nullptr); 63 freePrefetechedLayers(); 64 destroyHardwareResources(); 65 mAnimationContext->destroy(); 66 if (mCanvas) { 67 delete mCanvas; 68 mCanvas = nullptr; 69 } 70} 71 72void CanvasContext::setSurface(ANativeWindow* window) { 73 ATRACE_CALL(); 74 75 mNativeWindow = window; 76 77 if (mEglSurface != EGL_NO_SURFACE) { 78 mEglManager.destroySurface(mEglSurface); 79 mEglSurface = EGL_NO_SURFACE; 80 } 81 82 if (window) { 83 mEglSurface = mEglManager.createSurface(window); 84 } 85 86 if (mEglSurface != EGL_NO_SURFACE) { 87 const bool preserveBuffer = (mSwapBehavior != kSwap_discardBuffer); 88 mBufferPreserved = mEglManager.setPreserveBuffer(mEglSurface, preserveBuffer); 89 mHaveNewSurface = true; 90 makeCurrent(); 91 } else { 92 mRenderThread.removeFrameCallback(this); 93 } 94} 95 96void CanvasContext::swapBuffers(const SkRect& dirty, EGLint width, EGLint height) { 97 if (CC_UNLIKELY(!mEglManager.swapBuffers(mEglSurface, dirty, width, height))) { 98 setSurface(nullptr); 99 } 100 mHaveNewSurface = false; 101} 102 103void CanvasContext::requireSurface() { 104 LOG_ALWAYS_FATAL_IF(mEglSurface == EGL_NO_SURFACE, 105 "requireSurface() called but no surface set!"); 106 makeCurrent(); 107} 108 109void CanvasContext::setSwapBehavior(SwapBehavior swapBehavior) { 110 mSwapBehavior = swapBehavior; 111} 112 113bool CanvasContext::initialize(ANativeWindow* window) { 114 setSurface(window); 115 if (mCanvas) return false; 116 mCanvas = new OpenGLRenderer(mRenderThread.renderState()); 117 mCanvas->initProperties(); 118 return true; 119} 120 121void CanvasContext::updateSurface(ANativeWindow* window) { 122 setSurface(window); 123} 124 125bool CanvasContext::pauseSurface(ANativeWindow* window) { 126 return mRenderThread.removeFrameCallback(this); 127} 128 129// TODO: don't pass viewport size, it's automatic via EGL 130void CanvasContext::setup(int width, int height, float lightRadius, 131 uint8_t ambientShadowAlpha, uint8_t spotShadowAlpha) { 132 if (!mCanvas) return; 133 mCanvas->initLight(lightRadius, ambientShadowAlpha, spotShadowAlpha); 134} 135 136void CanvasContext::setLightCenter(const Vector3& lightCenter) { 137 if (!mCanvas) return; 138 mCanvas->setLightCenter(lightCenter); 139} 140 141void CanvasContext::setOpaque(bool opaque) { 142 mOpaque = opaque; 143} 144 145void CanvasContext::makeCurrent() { 146 // TODO: Figure out why this workaround is needed, see b/13913604 147 // In the meantime this matches the behavior of GLRenderer, so it is not a regression 148 mHaveNewSurface |= mEglManager.makeCurrent(mEglSurface); 149} 150 151void CanvasContext::processLayerUpdate(DeferredLayerUpdater* layerUpdater) { 152 bool success = layerUpdater->apply(); 153 LOG_ALWAYS_FATAL_IF(!success, "Failed to update layer!"); 154 if (layerUpdater->backingLayer()->deferredUpdateScheduled) { 155 mCanvas->pushLayerUpdate(layerUpdater->backingLayer()); 156 } 157} 158 159void CanvasContext::prepareTree(TreeInfo& info, int64_t* uiFrameInfo) { 160 mRenderThread.removeFrameCallback(this); 161 162 mCurrentFrameInfo = &mFrames.next(); 163 mCurrentFrameInfo->importUiThreadInfo(uiFrameInfo); 164 mCurrentFrameInfo->markSyncStart(); 165 166 info.damageAccumulator = &mDamageAccumulator; 167 info.renderer = mCanvas; 168 if (mPrefetechedLayers.size() && info.mode == TreeInfo::MODE_FULL) { 169 info.canvasContext = this; 170 } 171 mAnimationContext->startFrame(info.mode); 172 mRootRenderNode->prepareTree(info); 173 mAnimationContext->runRemainingAnimations(info); 174 175 if (info.canvasContext) { 176 freePrefetechedLayers(); 177 } 178 179 if (CC_UNLIKELY(!mNativeWindow.get())) { 180 mCurrentFrameInfo->addFlag(FrameInfoFlags::kSkippedFrame); 181 info.out.canDrawThisFrame = false; 182 return; 183 } 184 185 int runningBehind = 0; 186 // TODO: This query is moderately expensive, investigate adding some sort 187 // of fast-path based off when we last called eglSwapBuffers() as well as 188 // last vsync time. Or something. 189 mNativeWindow->query(mNativeWindow.get(), 190 NATIVE_WINDOW_CONSUMER_RUNNING_BEHIND, &runningBehind); 191 info.out.canDrawThisFrame = !runningBehind; 192 193 if (!info.out.canDrawThisFrame) { 194 mCurrentFrameInfo->addFlag(FrameInfoFlags::kSkippedFrame); 195 } 196 197 if (info.out.hasAnimations || !info.out.canDrawThisFrame) { 198 if (!info.out.requiresUiRedraw) { 199 // If animationsNeedsRedraw is set don't bother posting for an RT anim 200 // as we will just end up fighting the UI thread. 201 mRenderThread.postFrameCallback(this); 202 } 203 } 204} 205 206void CanvasContext::stopDrawing() { 207 mRenderThread.removeFrameCallback(this); 208} 209 210void CanvasContext::notifyFramePending() { 211 ATRACE_CALL(); 212 mRenderThread.pushBackFrameCallback(this); 213} 214 215void CanvasContext::draw() { 216 LOG_ALWAYS_FATAL_IF(!mCanvas || mEglSurface == EGL_NO_SURFACE, 217 "drawRenderNode called on a context with no canvas or surface!"); 218 219 SkRect dirty; 220 mDamageAccumulator.finish(&dirty); 221 222 if (dirty.isEmpty() && Properties::skipEmptyFrames) { 223 mCurrentFrameInfo->addFlag(FrameInfoFlags::kSkippedFrame); 224 return; 225 } 226 227 mCurrentFrameInfo->markIssueDrawCommandsStart(); 228 229 EGLint width, height; 230 mEglManager.beginFrame(mEglSurface, &width, &height); 231 if (width != mCanvas->getViewportWidth() || height != mCanvas->getViewportHeight()) { 232 mCanvas->setViewport(width, height); 233 dirty.setEmpty(); 234 } else if (!mBufferPreserved || mHaveNewSurface) { 235 dirty.setEmpty(); 236 } else { 237 if (!dirty.isEmpty() && !dirty.intersect(0, 0, width, height)) { 238 ALOGW("Dirty " RECT_STRING " doesn't intersect with 0 0 %d %d ?", 239 SK_RECT_ARGS(dirty), width, height); 240 dirty.setEmpty(); 241 } 242 profiler().unionDirty(&dirty); 243 } 244 245 if (!dirty.isEmpty()) { 246 mCanvas->prepareDirty(dirty.fLeft, dirty.fTop, 247 dirty.fRight, dirty.fBottom, mOpaque); 248 } else { 249 mCanvas->prepare(mOpaque); 250 } 251 252 Rect outBounds; 253 mCanvas->drawRenderNode(mRootRenderNode.get(), outBounds); 254 255 profiler().draw(mCanvas); 256 257 bool drew = mCanvas->finish(); 258 259 // Even if we decided to cancel the frame, from the perspective of jank 260 // metrics the frame was swapped at this point 261 mCurrentFrameInfo->markSwapBuffers(); 262 263 if (drew) { 264 swapBuffers(dirty, width, height); 265 } else { 266 mEglManager.cancelFrame(); 267 } 268 269 // TODO: Use a fence for real completion? 270 mCurrentFrameInfo->markFrameCompleted(); 271 mJankTracker.addFrame(*mCurrentFrameInfo); 272 mRenderThread.jankTracker().addFrame(*mCurrentFrameInfo); 273} 274 275// Called by choreographer to do an RT-driven animation 276void CanvasContext::doFrame() { 277 if (CC_UNLIKELY(!mCanvas || mEglSurface == EGL_NO_SURFACE)) { 278 return; 279 } 280 281 ATRACE_CALL(); 282 283 int64_t frameInfo[UI_THREAD_FRAME_INFO_SIZE]; 284 UiFrameInfoBuilder(frameInfo) 285 .addFlag(FrameInfoFlags::kRTAnimation) 286 .setVsync(mRenderThread.timeLord().computeFrameTimeNanos(), 287 mRenderThread.timeLord().latestVsync()); 288 289 TreeInfo info(TreeInfo::MODE_RT_ONLY, mRenderThread.renderState()); 290 prepareTree(info, frameInfo); 291 if (info.out.canDrawThisFrame) { 292 draw(); 293 } 294} 295 296void CanvasContext::invokeFunctor(RenderThread& thread, Functor* functor) { 297 ATRACE_CALL(); 298 DrawGlInfo::Mode mode = DrawGlInfo::kModeProcessNoContext; 299 if (thread.eglManager().hasEglContext()) { 300 thread.eglManager().requireGlContext(); 301 mode = DrawGlInfo::kModeProcess; 302 } 303 304 thread.renderState().invokeFunctor(functor, mode, nullptr); 305} 306 307void CanvasContext::markLayerInUse(RenderNode* node) { 308 if (mPrefetechedLayers.erase(node)) { 309 node->decStrong(nullptr); 310 } 311} 312 313static void destroyPrefetechedNode(RenderNode* node) { 314 ALOGW("Incorrectly called buildLayer on View: %s, destroying layer...", node->getName()); 315 node->destroyHardwareResources(); 316 node->decStrong(nullptr); 317} 318 319void CanvasContext::freePrefetechedLayers() { 320 if (mPrefetechedLayers.size()) { 321 requireGlContext(); 322 std::for_each(mPrefetechedLayers.begin(), mPrefetechedLayers.end(), destroyPrefetechedNode); 323 mPrefetechedLayers.clear(); 324 } 325} 326 327void CanvasContext::buildLayer(RenderNode* node) { 328 ATRACE_CALL(); 329 if (!mEglManager.hasEglContext() || !mCanvas) { 330 return; 331 } 332 requireGlContext(); 333 // buildLayer() will leave the tree in an unknown state, so we must stop drawing 334 stopDrawing(); 335 336 TreeInfo info(TreeInfo::MODE_FULL, mRenderThread.renderState()); 337 info.damageAccumulator = &mDamageAccumulator; 338 info.renderer = mCanvas; 339 info.runAnimations = false; 340 node->prepareTree(info); 341 SkRect ignore; 342 mDamageAccumulator.finish(&ignore); 343 // Tickle the GENERIC property on node to mark it as dirty for damaging 344 // purposes when the frame is actually drawn 345 node->setPropertyFieldsDirty(RenderNode::GENERIC); 346 347 mCanvas->markLayersAsBuildLayers(); 348 mCanvas->flushLayerUpdates(); 349 350 node->incStrong(nullptr); 351 mPrefetechedLayers.insert(node); 352} 353 354bool CanvasContext::copyLayerInto(DeferredLayerUpdater* layer, SkBitmap* bitmap) { 355 requireGlContext(); 356 layer->apply(); 357 return LayerRenderer::copyLayer(mRenderThread.renderState(), layer->backingLayer(), bitmap); 358} 359 360void CanvasContext::destroyHardwareResources() { 361 stopDrawing(); 362 if (mEglManager.hasEglContext()) { 363 requireGlContext(); 364 freePrefetechedLayers(); 365 mRootRenderNode->destroyHardwareResources(); 366 Caches::getInstance().flush(Caches::kFlushMode_Layers); 367 } 368} 369 370void CanvasContext::trimMemory(RenderThread& thread, int level) { 371 // No context means nothing to free 372 if (!thread.eglManager().hasEglContext()) return; 373 374 ATRACE_CALL(); 375 thread.eglManager().requireGlContext(); 376 if (level >= TRIM_MEMORY_COMPLETE) { 377 Caches::getInstance().flush(Caches::kFlushMode_Full); 378 thread.eglManager().destroy(); 379 } else if (level >= TRIM_MEMORY_UI_HIDDEN) { 380 Caches::getInstance().flush(Caches::kFlushMode_Moderate); 381 } 382} 383 384void CanvasContext::runWithGlContext(RenderTask* task) { 385 requireGlContext(); 386 task->run(); 387} 388 389Layer* CanvasContext::createTextureLayer() { 390 requireSurface(); 391 return LayerRenderer::createTextureLayer(mRenderThread.renderState()); 392} 393 394void CanvasContext::requireGlContext() { 395 mEglManager.requireGlContext(); 396} 397 398void CanvasContext::setTextureAtlas(RenderThread& thread, 399 const sp<GraphicBuffer>& buffer, int64_t* map, size_t mapSize) { 400 thread.eglManager().setTextureAtlas(buffer, map, mapSize); 401} 402 403void CanvasContext::dumpFrames(int fd) { 404 FILE* file = fdopen(fd, "a"); 405 fprintf(file, "\n\n---PROFILEDATA---"); 406 for (size_t i = 0; i < mFrames.size(); i++) { 407 FrameInfo& frame = mFrames[i]; 408 if (frame[FrameInfoIndex::kSyncStart] == 0) { 409 continue; 410 } 411 fprintf(file, "\n"); 412 for (int i = 0; i < static_cast<int>(FrameInfoIndex::kNumIndexes); i++) { 413 fprintf(file, "%" PRId64 ",", frame[i]); 414 } 415 } 416 fprintf(file, "\n---PROFILEDATA---\n\n"); 417 fflush(file); 418} 419 420void CanvasContext::resetFrameStats() { 421 mFrames.clear(); 422 mRenderThread.jankTracker().reset(); 423} 424 425} /* namespace renderthread */ 426} /* namespace uirenderer */ 427} /* namespace android */ 428