CanvasContext.cpp revision 4c9e59d03c2bca38001225b79d01740b8999adfb
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, const Vector3& lightCenter, float lightRadius, 131 uint8_t ambientShadowAlpha, uint8_t spotShadowAlpha) { 132 if (!mCanvas) return; 133 mCanvas->initLight(lightCenter, lightRadius, ambientShadowAlpha, spotShadowAlpha); 134} 135 136void CanvasContext::setOpaque(bool opaque) { 137 mOpaque = opaque; 138} 139 140void CanvasContext::makeCurrent() { 141 // TODO: Figure out why this workaround is needed, see b/13913604 142 // In the meantime this matches the behavior of GLRenderer, so it is not a regression 143 mHaveNewSurface |= mEglManager.makeCurrent(mEglSurface); 144} 145 146void CanvasContext::processLayerUpdate(DeferredLayerUpdater* layerUpdater) { 147 bool success = layerUpdater->apply(); 148 LOG_ALWAYS_FATAL_IF(!success, "Failed to update layer!"); 149 if (layerUpdater->backingLayer()->deferredUpdateScheduled) { 150 mCanvas->pushLayerUpdate(layerUpdater->backingLayer()); 151 } 152} 153 154void CanvasContext::prepareTree(TreeInfo& info, int64_t* uiFrameInfo) { 155 mRenderThread.removeFrameCallback(this); 156 157 mCurrentFrameInfo = &mFrames.next(); 158 mCurrentFrameInfo->importUiThreadInfo(uiFrameInfo); 159 mCurrentFrameInfo->markSyncStart(); 160 161 info.damageAccumulator = &mDamageAccumulator; 162 info.renderer = mCanvas; 163 if (mPrefetechedLayers.size() && info.mode == TreeInfo::MODE_FULL) { 164 info.canvasContext = this; 165 } 166 mAnimationContext->startFrame(info.mode); 167 mRootRenderNode->prepareTree(info); 168 mAnimationContext->runRemainingAnimations(info); 169 170 if (info.canvasContext) { 171 freePrefetechedLayers(); 172 } 173 174 if (CC_UNLIKELY(!mNativeWindow.get())) { 175 mCurrentFrameInfo->addFlag(FrameInfoFlags::kSkippedFrame); 176 info.out.canDrawThisFrame = false; 177 return; 178 } 179 180 int runningBehind = 0; 181 // TODO: This query is moderately expensive, investigate adding some sort 182 // of fast-path based off when we last called eglSwapBuffers() as well as 183 // last vsync time. Or something. 184 mNativeWindow->query(mNativeWindow.get(), 185 NATIVE_WINDOW_CONSUMER_RUNNING_BEHIND, &runningBehind); 186 info.out.canDrawThisFrame = !runningBehind; 187 188 if (!info.out.canDrawThisFrame) { 189 mCurrentFrameInfo->addFlag(FrameInfoFlags::kSkippedFrame); 190 } 191 192 if (info.out.hasAnimations || !info.out.canDrawThisFrame) { 193 if (!info.out.requiresUiRedraw) { 194 // If animationsNeedsRedraw is set don't bother posting for an RT anim 195 // as we will just end up fighting the UI thread. 196 mRenderThread.postFrameCallback(this); 197 } 198 } 199} 200 201void CanvasContext::stopDrawing() { 202 mRenderThread.removeFrameCallback(this); 203} 204 205void CanvasContext::notifyFramePending() { 206 ATRACE_CALL(); 207 mRenderThread.pushBackFrameCallback(this); 208} 209 210void CanvasContext::draw() { 211 LOG_ALWAYS_FATAL_IF(!mCanvas || mEglSurface == EGL_NO_SURFACE, 212 "drawRenderNode called on a context with no canvas or surface!"); 213 214 SkRect dirty; 215 mDamageAccumulator.finish(&dirty); 216 217 if (dirty.isEmpty() && Properties::skipEmptyFrames) { 218 mCurrentFrameInfo->addFlag(FrameInfoFlags::kSkippedFrame); 219 return; 220 } 221 222 mCurrentFrameInfo->markIssueDrawCommandsStart(); 223 224 EGLint width, height; 225 mEglManager.beginFrame(mEglSurface, &width, &height); 226 if (width != mCanvas->getViewportWidth() || height != mCanvas->getViewportHeight()) { 227 mCanvas->setViewport(width, height); 228 dirty.setEmpty(); 229 } else if (!mBufferPreserved || mHaveNewSurface) { 230 dirty.setEmpty(); 231 } else { 232 if (!dirty.isEmpty() && !dirty.intersect(0, 0, width, height)) { 233 ALOGW("Dirty " RECT_STRING " doesn't intersect with 0 0 %d %d ?", 234 SK_RECT_ARGS(dirty), width, height); 235 dirty.setEmpty(); 236 } 237 profiler().unionDirty(&dirty); 238 } 239 240 if (!dirty.isEmpty()) { 241 mCanvas->prepareDirty(dirty.fLeft, dirty.fTop, 242 dirty.fRight, dirty.fBottom, mOpaque); 243 } else { 244 mCanvas->prepare(mOpaque); 245 } 246 247 Rect outBounds; 248 mCanvas->drawRenderNode(mRootRenderNode.get(), outBounds); 249 250 profiler().draw(mCanvas); 251 252 bool drew = mCanvas->finish(); 253 254 // Even if we decided to cancel the frame, from the perspective of jank 255 // metrics the frame was swapped at this point 256 mCurrentFrameInfo->markSwapBuffers(); 257 258 if (drew) { 259 swapBuffers(dirty, width, height); 260 } else { 261 mEglManager.cancelFrame(); 262 } 263 264 // TODO: Use a fence for real completion? 265 mCurrentFrameInfo->markFrameCompleted(); 266 mJankTracker.addFrame(*mCurrentFrameInfo); 267 mRenderThread.jankTracker().addFrame(*mCurrentFrameInfo); 268} 269 270// Called by choreographer to do an RT-driven animation 271void CanvasContext::doFrame() { 272 if (CC_UNLIKELY(!mCanvas || mEglSurface == EGL_NO_SURFACE)) { 273 return; 274 } 275 276 ATRACE_CALL(); 277 278 int64_t frameInfo[UI_THREAD_FRAME_INFO_SIZE]; 279 UiFrameInfoBuilder(frameInfo) 280 .addFlag(FrameInfoFlags::kRTAnimation) 281 .setVsync(mRenderThread.timeLord().computeFrameTimeNanos(), 282 mRenderThread.timeLord().latestVsync()); 283 284 TreeInfo info(TreeInfo::MODE_RT_ONLY, mRenderThread.renderState()); 285 prepareTree(info, frameInfo); 286 if (info.out.canDrawThisFrame) { 287 draw(); 288 } 289} 290 291void CanvasContext::invokeFunctor(RenderThread& thread, Functor* functor) { 292 ATRACE_CALL(); 293 DrawGlInfo::Mode mode = DrawGlInfo::kModeProcessNoContext; 294 if (thread.eglManager().hasEglContext()) { 295 thread.eglManager().requireGlContext(); 296 mode = DrawGlInfo::kModeProcess; 297 } 298 299 thread.renderState().invokeFunctor(functor, mode, nullptr); 300} 301 302void CanvasContext::markLayerInUse(RenderNode* node) { 303 if (mPrefetechedLayers.erase(node)) { 304 node->decStrong(nullptr); 305 } 306} 307 308static void destroyPrefetechedNode(RenderNode* node) { 309 ALOGW("Incorrectly called buildLayer on View: %s, destroying layer...", node->getName()); 310 node->destroyHardwareResources(); 311 node->decStrong(nullptr); 312} 313 314void CanvasContext::freePrefetechedLayers() { 315 if (mPrefetechedLayers.size()) { 316 requireGlContext(); 317 std::for_each(mPrefetechedLayers.begin(), mPrefetechedLayers.end(), destroyPrefetechedNode); 318 mPrefetechedLayers.clear(); 319 } 320} 321 322void CanvasContext::buildLayer(RenderNode* node) { 323 ATRACE_CALL(); 324 if (!mEglManager.hasEglContext() || !mCanvas) { 325 return; 326 } 327 requireGlContext(); 328 // buildLayer() will leave the tree in an unknown state, so we must stop drawing 329 stopDrawing(); 330 331 TreeInfo info(TreeInfo::MODE_FULL, mRenderThread.renderState()); 332 info.damageAccumulator = &mDamageAccumulator; 333 info.renderer = mCanvas; 334 info.runAnimations = false; 335 node->prepareTree(info); 336 SkRect ignore; 337 mDamageAccumulator.finish(&ignore); 338 // Tickle the GENERIC property on node to mark it as dirty for damaging 339 // purposes when the frame is actually drawn 340 node->setPropertyFieldsDirty(RenderNode::GENERIC); 341 342 mCanvas->markLayersAsBuildLayers(); 343 mCanvas->flushLayerUpdates(); 344 345 node->incStrong(nullptr); 346 mPrefetechedLayers.insert(node); 347} 348 349bool CanvasContext::copyLayerInto(DeferredLayerUpdater* layer, SkBitmap* bitmap) { 350 requireGlContext(); 351 layer->apply(); 352 return LayerRenderer::copyLayer(mRenderThread.renderState(), layer->backingLayer(), bitmap); 353} 354 355void CanvasContext::destroyHardwareResources() { 356 stopDrawing(); 357 if (mEglManager.hasEglContext()) { 358 requireGlContext(); 359 freePrefetechedLayers(); 360 mRootRenderNode->destroyHardwareResources(); 361 Caches::getInstance().flush(Caches::kFlushMode_Layers); 362 } 363} 364 365void CanvasContext::trimMemory(RenderThread& thread, int level) { 366 // No context means nothing to free 367 if (!thread.eglManager().hasEglContext()) return; 368 369 ATRACE_CALL(); 370 thread.eglManager().requireGlContext(); 371 if (level >= TRIM_MEMORY_COMPLETE) { 372 Caches::getInstance().flush(Caches::kFlushMode_Full); 373 thread.eglManager().destroy(); 374 } else if (level >= TRIM_MEMORY_UI_HIDDEN) { 375 Caches::getInstance().flush(Caches::kFlushMode_Moderate); 376 } 377} 378 379void CanvasContext::runWithGlContext(RenderTask* task) { 380 requireGlContext(); 381 task->run(); 382} 383 384Layer* CanvasContext::createTextureLayer() { 385 requireSurface(); 386 return LayerRenderer::createTextureLayer(mRenderThread.renderState()); 387} 388 389void CanvasContext::requireGlContext() { 390 mEglManager.requireGlContext(); 391} 392 393void CanvasContext::setTextureAtlas(RenderThread& thread, 394 const sp<GraphicBuffer>& buffer, int64_t* map, size_t mapSize) { 395 thread.eglManager().setTextureAtlas(buffer, map, mapSize); 396} 397 398void CanvasContext::dumpFrames(int fd) { 399 FILE* file = fdopen(fd, "a"); 400 fprintf(file, "\n\n---PROFILEDATA---"); 401 for (size_t i = 0; i < mFrames.size(); i++) { 402 FrameInfo& frame = mFrames[i]; 403 if (frame[FrameInfoIndex::kSyncStart] == 0) { 404 continue; 405 } 406 fprintf(file, "\n"); 407 for (int i = 0; i < static_cast<int>(FrameInfoIndex::kNumIndexes); i++) { 408 fprintf(file, "%" PRId64 ",", frame[i]); 409 } 410 } 411 fprintf(file, "\n---PROFILEDATA---\n\n"); 412 fflush(file); 413} 414 415void CanvasContext::resetFrameStats() { 416 mFrames.clear(); 417 mRenderThread.jankTracker().reset(); 418} 419 420} /* namespace renderthread */ 421} /* namespace uirenderer */ 422} /* namespace android */ 423