CanvasContext.cpp revision e7f27fbf93ad0c26dfc6142ff1fde4a70b94aa23
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 <GpuMemoryTracker.h> 18#include "CanvasContext.h" 19 20#include "AnimationContext.h" 21#include "Caches.h" 22#include "DeferredLayerUpdater.h" 23#include "EglManager.h" 24#include "LayerUpdateQueue.h" 25#include "LayerRenderer.h" 26#include "OpenGLRenderer.h" 27#include "Properties.h" 28#include "RenderThread.h" 29#include "hwui/Canvas.h" 30#include "renderstate/RenderState.h" 31#include "renderstate/Stencil.h" 32#include "protos/hwui.pb.h" 33#include "utils/GLUtils.h" 34#include "utils/TimeUtils.h" 35 36#include <cutils/properties.h> 37#include <google/protobuf/io/zero_copy_stream_impl.h> 38#include <private/hwui/DrawGlInfo.h> 39#include <strings.h> 40 41#include <algorithm> 42#include <fcntl.h> 43#include <sys/stat.h> 44 45#include <cstdlib> 46 47#define TRIM_MEMORY_COMPLETE 80 48#define TRIM_MEMORY_UI_HIDDEN 20 49 50#define ENABLE_RENDERNODE_SERIALIZATION false 51 52#define LOG_FRAMETIME_MMA 0 53 54#if LOG_FRAMETIME_MMA 55static float sBenchMma = 0; 56static int sFrameCount = 0; 57static const float NANOS_PER_MILLIS_F = 1000000.0f; 58#endif 59 60namespace android { 61namespace uirenderer { 62namespace renderthread { 63 64CanvasContext::CanvasContext(RenderThread& thread, bool translucent, 65 RenderNode* rootRenderNode, IContextFactory* contextFactory) 66 : mRenderThread(thread) 67 , mEglManager(thread.eglManager()) 68 , mOpaque(!translucent) 69 , mAnimationContext(contextFactory->createAnimationContext(mRenderThread.timeLord())) 70 , mJankTracker(thread.timeLord().frameIntervalNanos()) 71 , mProfiler(mFrames) 72 , mContentDrawBounds(0, 0, 0, 0) { 73 mRenderNodes.emplace_back(rootRenderNode); 74 mRenderThread.renderState().registerCanvasContext(this); 75 mProfiler.setDensity(mRenderThread.mainDisplayInfo().density); 76} 77 78CanvasContext::~CanvasContext() { 79 destroy(nullptr); 80 mRenderThread.renderState().unregisterCanvasContext(this); 81} 82 83void CanvasContext::destroy(TreeObserver* observer) { 84 stopDrawing(); 85 setSurface(nullptr); 86 freePrefetchedLayers(observer); 87 destroyHardwareResources(observer); 88 mAnimationContext->destroy(); 89#if !HWUI_NEW_OPS 90 if (mCanvas) { 91 delete mCanvas; 92 mCanvas = nullptr; 93 } 94#endif 95} 96 97void CanvasContext::setSurface(Surface* surface) { 98 ATRACE_CALL(); 99 100 mNativeSurface = surface; 101 102 if (mEglSurface != EGL_NO_SURFACE) { 103 mEglManager.destroySurface(mEglSurface); 104 mEglSurface = EGL_NO_SURFACE; 105 } 106 107 if (surface) { 108 mEglSurface = mEglManager.createSurface(surface); 109 } 110 111 mFrameNumber = -1; 112 113 if (mEglSurface != EGL_NO_SURFACE) { 114 const bool preserveBuffer = (mSwapBehavior != kSwap_discardBuffer); 115 mBufferPreserved = mEglManager.setPreserveBuffer(mEglSurface, preserveBuffer); 116 mHaveNewSurface = true; 117 mSwapHistory.clear(); 118 } else { 119 mRenderThread.removeFrameCallback(this); 120 } 121} 122 123void CanvasContext::setSwapBehavior(SwapBehavior swapBehavior) { 124 mSwapBehavior = swapBehavior; 125} 126 127void CanvasContext::initialize(Surface* surface) { 128 setSurface(surface); 129#if !HWUI_NEW_OPS 130 if (mCanvas) return; 131 mCanvas = new OpenGLRenderer(mRenderThread.renderState()); 132 mCanvas->initProperties(); 133#endif 134} 135 136void CanvasContext::updateSurface(Surface* surface) { 137 setSurface(surface); 138} 139 140bool CanvasContext::pauseSurface(Surface* surface) { 141 return mRenderThread.removeFrameCallback(this); 142} 143 144void CanvasContext::setStopped(bool stopped) { 145 if (mStopped != stopped) { 146 mStopped = stopped; 147 if (mStopped) { 148 mRenderThread.removeFrameCallback(this); 149 if (mEglManager.isCurrent(mEglSurface)) { 150 mEglManager.makeCurrent(EGL_NO_SURFACE); 151 } 152 } else if (mIsDirty && hasSurface()) { 153 mRenderThread.postFrameCallback(this); 154 } 155 } 156} 157 158void CanvasContext::setup(float lightRadius, 159 uint8_t ambientShadowAlpha, uint8_t spotShadowAlpha) { 160#if HWUI_NEW_OPS 161 mLightGeometry.radius = lightRadius; 162 mLightInfo.ambientShadowAlpha = ambientShadowAlpha; 163 mLightInfo.spotShadowAlpha = spotShadowAlpha; 164#else 165 if (!mCanvas) return; 166 mCanvas->initLight(lightRadius, ambientShadowAlpha, spotShadowAlpha); 167#endif 168} 169 170void CanvasContext::setLightCenter(const Vector3& lightCenter) { 171#if HWUI_NEW_OPS 172 mLightGeometry.center = lightCenter; 173#else 174 if (!mCanvas) return; 175 mCanvas->setLightCenter(lightCenter); 176#endif 177} 178 179void CanvasContext::setOpaque(bool opaque) { 180 mOpaque = opaque; 181} 182 183bool CanvasContext::makeCurrent() { 184 if (mStopped) return false; 185 186 // TODO: Figure out why this workaround is needed, see b/13913604 187 // In the meantime this matches the behavior of GLRenderer, so it is not a regression 188 EGLint error = 0; 189 mHaveNewSurface |= mEglManager.makeCurrent(mEglSurface, &error); 190 if (error) { 191 setSurface(nullptr); 192 } 193 return !error; 194} 195 196static bool wasSkipped(FrameInfo* info) { 197 return info && ((*info)[FrameInfoIndex::Flags] & FrameInfoFlags::SkippedFrame); 198} 199 200bool CanvasContext::isSwapChainStuffed() { 201 if (mSwapHistory.size() != mSwapHistory.capacity()) { 202 // We want at least 3 frames of history before attempting to 203 // guess if the queue is stuffed 204 return false; 205 } 206 nsecs_t frameInterval = mRenderThread.timeLord().frameIntervalNanos(); 207 auto& swapA = mSwapHistory[0]; 208 209 // Was there a happy queue & dequeue time? If so, don't 210 // consider it stuffed 211 if (swapA.dequeueDuration < 3_ms 212 && swapA.queueDuration < 3_ms) { 213 return false; 214 } 215 216 for (size_t i = 1; i < mSwapHistory.size(); i++) { 217 auto& swapB = mSwapHistory[i]; 218 219 // If there's a frameInterval gap we effectively already dropped a frame, 220 // so consider the queue healthy. 221 if (swapA.swapCompletedTime - swapB.swapCompletedTime > frameInterval) { 222 return false; 223 } 224 225 // Was there a happy queue & dequeue time? If so, don't 226 // consider it stuffed 227 if (swapB.dequeueDuration < 3_ms 228 && swapB.queueDuration < 3_ms) { 229 return false; 230 } 231 232 swapA = swapB; 233 } 234 235 // All signs point to a stuffed swap chain 236 return true; 237} 238 239void CanvasContext::prepareTree(TreeInfo& info, int64_t* uiFrameInfo, 240 int64_t syncQueued, RenderNode* target) { 241 mRenderThread.removeFrameCallback(this); 242 243 // If the previous frame was dropped we don't need to hold onto it, so 244 // just keep using the previous frame's structure instead 245 if (!wasSkipped(mCurrentFrameInfo)) { 246 mCurrentFrameInfo = &mFrames.next(); 247 } 248 mCurrentFrameInfo->importUiThreadInfo(uiFrameInfo); 249 mCurrentFrameInfo->set(FrameInfoIndex::SyncQueued) = syncQueued; 250 mCurrentFrameInfo->markSyncStart(); 251 252 info.damageAccumulator = &mDamageAccumulator; 253#if HWUI_NEW_OPS 254 info.layerUpdateQueue = &mLayerUpdateQueue; 255#else 256 info.renderer = mCanvas; 257#endif 258 259 mAnimationContext->startFrame(info.mode); 260 for (const sp<RenderNode>& node : mRenderNodes) { 261 // Only the primary target node will be drawn full - all other nodes would get drawn in 262 // real time mode. In case of a window, the primary node is the window content and the other 263 // node(s) are non client / filler nodes. 264 info.mode = (node.get() == target ? TreeInfo::MODE_FULL : TreeInfo::MODE_RT_ONLY); 265 node->prepareTree(info); 266 GL_CHECKPOINT(MODERATE); 267 } 268 mAnimationContext->runRemainingAnimations(info); 269 GL_CHECKPOINT(MODERATE); 270 271 freePrefetchedLayers(info.observer); 272 GL_CHECKPOINT(MODERATE); 273 274 mIsDirty = true; 275 276 if (CC_UNLIKELY(!mNativeSurface.get())) { 277 mCurrentFrameInfo->addFlag(FrameInfoFlags::SkippedFrame); 278 info.out.canDrawThisFrame = false; 279 return; 280 } 281 282 if (CC_LIKELY(mSwapHistory.size() && !Properties::forceDrawFrame)) { 283 nsecs_t latestVsync = mRenderThread.timeLord().latestVsync(); 284 SwapHistory& lastSwap = mSwapHistory.back(); 285 int durationUs; 286 mNativeSurface->query(NATIVE_WINDOW_LAST_DEQUEUE_DURATION, &durationUs); 287 lastSwap.dequeueDuration = us2ns(durationUs); 288 mNativeSurface->query(NATIVE_WINDOW_LAST_QUEUE_DURATION, &durationUs); 289 lastSwap.queueDuration = us2ns(durationUs); 290 nsecs_t vsyncDelta = std::abs(lastSwap.vsyncTime - latestVsync); 291 // The slight fudge-factor is to deal with cases where 292 // the vsync was estimated due to being slow handling the signal. 293 // See the logic in TimeLord#computeFrameTimeNanos or in 294 // Choreographer.java for details on when this happens 295 if (vsyncDelta < 2_ms) { 296 // Already drew for this vsync pulse, UI draw request missed 297 // the deadline for RT animations 298 info.out.canDrawThisFrame = false; 299 } else if (vsyncDelta >= mRenderThread.timeLord().frameIntervalNanos()) { 300 // It's been at least an entire frame interval, assume 301 // the buffer queue is fine 302 info.out.canDrawThisFrame = true; 303 } else { 304 info.out.canDrawThisFrame = !isSwapChainStuffed(); 305 } 306 } else { 307 info.out.canDrawThisFrame = true; 308 } 309 310 if (!info.out.canDrawThisFrame) { 311 mCurrentFrameInfo->addFlag(FrameInfoFlags::SkippedFrame); 312 } 313 314 if (info.out.hasAnimations || !info.out.canDrawThisFrame) { 315 if (!info.out.requiresUiRedraw) { 316 // If animationsNeedsRedraw is set don't bother posting for an RT anim 317 // as we will just end up fighting the UI thread. 318 mRenderThread.postFrameCallback(this); 319 } 320 } 321} 322 323void CanvasContext::stopDrawing() { 324 mRenderThread.removeFrameCallback(this); 325 mAnimationContext->detachAnimators(); 326} 327 328void CanvasContext::notifyFramePending() { 329 ATRACE_CALL(); 330 mRenderThread.pushBackFrameCallback(this); 331} 332 333void CanvasContext::draw() { 334#if !HWUI_NEW_OPS 335 LOG_ALWAYS_FATAL_IF(!mCanvas || mEglSurface == EGL_NO_SURFACE, 336 "drawRenderNode called on a context with no canvas or surface!"); 337#endif 338 339 SkRect dirty; 340 mDamageAccumulator.finish(&dirty); 341 342 // TODO: Re-enable after figuring out cause of b/22592975 343// if (dirty.isEmpty() && Properties::skipEmptyFrames) { 344// mCurrentFrameInfo->addFlag(FrameInfoFlags::SkippedFrame); 345// return; 346// } 347 348 mCurrentFrameInfo->markIssueDrawCommandsStart(); 349 350 Frame frame = mEglManager.beginFrame(mEglSurface); 351 352 if (frame.width() != mLastFrameWidth || frame.height() != mLastFrameHeight) { 353 // can't rely on prior content of window if viewport size changes 354 dirty.setEmpty(); 355 mLastFrameWidth = frame.width(); 356 mLastFrameHeight = frame.height(); 357 } else if (mHaveNewSurface || frame.bufferAge() == 0) { 358 // New surface needs a full draw 359 dirty.setEmpty(); 360 } else { 361 if (!dirty.isEmpty() && !dirty.intersect(0, 0, frame.width(), frame.height())) { 362 ALOGW("Dirty " RECT_STRING " doesn't intersect with 0 0 %d %d ?", 363 SK_RECT_ARGS(dirty), frame.width(), frame.height()); 364 dirty.setEmpty(); 365 } 366 profiler().unionDirty(&dirty); 367 } 368 369 if (dirty.isEmpty()) { 370 dirty.set(0, 0, frame.width(), frame.height()); 371 } 372 373 // At this point dirty is the area of the screen to update. However, 374 // the area of the frame we need to repaint is potentially different, so 375 // stash the screen area for later 376 SkRect screenDirty(dirty); 377 378 // If the buffer age is 0 we do a full-screen repaint (handled above) 379 // If the buffer age is 1 the buffer contents are the same as they were 380 // last frame so there's nothing to union() against 381 // Therefore we only care about the > 1 case. 382 if (frame.bufferAge() > 1) { 383 if (frame.bufferAge() > (int) mSwapHistory.size()) { 384 // We don't have enough history to handle this old of a buffer 385 // Just do a full-draw 386 dirty.set(0, 0, frame.width(), frame.height()); 387 } else { 388 // At this point we haven't yet added the latest frame 389 // to the damage history (happens below) 390 // So we need to damage 391 for (int i = mSwapHistory.size() - 1; 392 i > ((int) mSwapHistory.size()) - frame.bufferAge(); i--) { 393 dirty.join(mSwapHistory[i].damage); 394 } 395 } 396 } 397 398 mEglManager.damageFrame(frame, dirty); 399 400#if HWUI_NEW_OPS 401 auto& caches = Caches::getInstance(); 402 FrameBuilder frameBuilder(dirty, frame.width(), frame.height(), mLightGeometry, caches); 403 404 frameBuilder.deferLayers(mLayerUpdateQueue); 405 mLayerUpdateQueue.clear(); 406 407 frameBuilder.deferRenderNodeScene(mRenderNodes, mContentDrawBounds); 408 409 BakedOpRenderer renderer(caches, mRenderThread.renderState(), 410 mOpaque, mLightInfo); 411 frameBuilder.replayBakedOps<BakedOpDispatcher>(renderer); 412 profiler().draw(&renderer); 413 bool drew = renderer.didDraw(); 414 415 // post frame cleanup 416 caches.clearGarbage(); 417 caches.pathCache.trim(); 418 caches.tessellationCache.trim(); 419 420#if DEBUG_MEMORY_USAGE 421 mCaches.dumpMemoryUsage(); 422#else 423 if (CC_UNLIKELY(Properties::debugLevel & kDebugMemory)) { 424 caches.dumpMemoryUsage(); 425 } 426#endif 427 428#else 429 mCanvas->prepareDirty(frame.width(), frame.height(), 430 dirty.fLeft, dirty.fTop, dirty.fRight, dirty.fBottom, mOpaque); 431 432 Rect outBounds; 433 // It there are multiple render nodes, they are laid out as follows: 434 // #0 - backdrop (content + caption) 435 // #1 - content (positioned at (0,0) and clipped to - its bounds mContentDrawBounds) 436 // #2 - additional overlay nodes 437 // Usually the backdrop cannot be seen since it will be entirely covered by the content. While 438 // resizing however it might become partially visible. The following render loop will crop the 439 // backdrop against the content and draw the remaining part of it. It will then draw the content 440 // cropped to the backdrop (since that indicates a shrinking of the window). 441 // 442 // Additional nodes will be drawn on top with no particular clipping semantics. 443 444 // The bounds of the backdrop against which the content should be clipped. 445 Rect backdropBounds = mContentDrawBounds; 446 // Usually the contents bounds should be mContentDrawBounds - however - we will 447 // move it towards the fixed edge to give it a more stable appearance (for the moment). 448 Rect contentBounds; 449 // If there is no content bounds we ignore the layering as stated above and start with 2. 450 int layer = (mContentDrawBounds.isEmpty() || mRenderNodes.size() == 1) ? 2 : 0; 451 // Draw all render nodes. Note that 452 for (const sp<RenderNode>& node : mRenderNodes) { 453 if (layer == 0) { // Backdrop. 454 // Draw the backdrop clipped to the inverse content bounds, but assume that the content 455 // was moved to the upper left corner. 456 const RenderProperties& properties = node->properties(); 457 Rect targetBounds(properties.getLeft(), properties.getTop(), 458 properties.getRight(), properties.getBottom()); 459 // Move the content bounds towards the fixed corner of the backdrop. 460 const int x = targetBounds.left; 461 const int y = targetBounds.top; 462 contentBounds.set(x, y, x + mContentDrawBounds.getWidth(), 463 y + mContentDrawBounds.getHeight()); 464 // Remember the intersection of the target bounds and the intersection bounds against 465 // which we have to crop the content. 466 backdropBounds.set(x, y, x + backdropBounds.getWidth(), y + backdropBounds.getHeight()); 467 backdropBounds.doIntersect(targetBounds); 468 // Check if we have to draw something on the left side ... 469 if (targetBounds.left < contentBounds.left) { 470 mCanvas->save(SaveFlags::Clip); 471 if (mCanvas->clipRect(targetBounds.left, targetBounds.top, 472 contentBounds.left, targetBounds.bottom, 473 SkRegion::kIntersect_Op)) { 474 mCanvas->drawRenderNode(node.get(), outBounds); 475 } 476 // Reduce the target area by the area we have just painted. 477 targetBounds.left = std::min(contentBounds.left, targetBounds.right); 478 mCanvas->restore(); 479 } 480 // ... or on the right side ... 481 if (targetBounds.right > contentBounds.right && 482 !targetBounds.isEmpty()) { 483 mCanvas->save(SaveFlags::Clip); 484 if (mCanvas->clipRect(contentBounds.right, targetBounds.top, 485 targetBounds.right, targetBounds.bottom, 486 SkRegion::kIntersect_Op)) { 487 mCanvas->drawRenderNode(node.get(), outBounds); 488 } 489 // Reduce the target area by the area we have just painted. 490 targetBounds.right = std::max(targetBounds.left, contentBounds.right); 491 mCanvas->restore(); 492 } 493 // ... or at the top ... 494 if (targetBounds.top < contentBounds.top && 495 !targetBounds.isEmpty()) { 496 mCanvas->save(SaveFlags::Clip); 497 if (mCanvas->clipRect(targetBounds.left, targetBounds.top, targetBounds.right, 498 contentBounds.top, 499 SkRegion::kIntersect_Op)) { 500 mCanvas->drawRenderNode(node.get(), outBounds); 501 } 502 // Reduce the target area by the area we have just painted. 503 targetBounds.top = std::min(contentBounds.top, targetBounds.bottom); 504 mCanvas->restore(); 505 } 506 // ... or at the bottom. 507 if (targetBounds.bottom > contentBounds.bottom && 508 !targetBounds.isEmpty()) { 509 mCanvas->save(SaveFlags::Clip); 510 if (mCanvas->clipRect(targetBounds.left, contentBounds.bottom, targetBounds.right, 511 targetBounds.bottom, SkRegion::kIntersect_Op)) { 512 mCanvas->drawRenderNode(node.get(), outBounds); 513 } 514 mCanvas->restore(); 515 } 516 } else if (layer == 1) { // Content 517 // It gets cropped against the bounds of the backdrop to stay inside. 518 mCanvas->save(SaveFlags::MatrixClip); 519 520 // We shift and clip the content to match its final location in the window. 521 const float left = mContentDrawBounds.left; 522 const float top = mContentDrawBounds.top; 523 const float dx = backdropBounds.left - left; 524 const float dy = backdropBounds.top - top; 525 const float width = backdropBounds.getWidth(); 526 const float height = backdropBounds.getHeight(); 527 528 mCanvas->translate(dx, dy); 529 if (mCanvas->clipRect(left, top, left + width, top + height, SkRegion::kIntersect_Op)) { 530 mCanvas->drawRenderNode(node.get(), outBounds); 531 } 532 mCanvas->restore(); 533 } else { // draw the rest on top at will! 534 mCanvas->drawRenderNode(node.get(), outBounds); 535 } 536 layer++; 537 } 538 539 profiler().draw(mCanvas); 540 541 bool drew = mCanvas->finish(); 542#endif 543 544 waitOnFences(); 545 546 GL_CHECKPOINT(LOW); 547 548 // Even if we decided to cancel the frame, from the perspective of jank 549 // metrics the frame was swapped at this point 550 mCurrentFrameInfo->markSwapBuffers(); 551 mIsDirty = false; 552 553 if (drew || mEglManager.damageRequiresSwap()) { 554 if (CC_UNLIKELY(!mEglManager.swapBuffers(frame, screenDirty))) { 555 setSurface(nullptr); 556 } 557 SwapHistory& swap = mSwapHistory.next(); 558 swap.damage = screenDirty; 559 swap.swapCompletedTime = systemTime(CLOCK_MONOTONIC); 560 swap.vsyncTime = mRenderThread.timeLord().latestVsync(); 561 mHaveNewSurface = false; 562 mFrameNumber = -1; 563 } 564 565 // TODO: Use a fence for real completion? 566 mCurrentFrameInfo->markFrameCompleted(); 567 568#if LOG_FRAMETIME_MMA 569 float thisFrame = mCurrentFrameInfo->duration( 570 FrameInfoIndex::IssueDrawCommandsStart, 571 FrameInfoIndex::FrameCompleted) / NANOS_PER_MILLIS_F; 572 if (sFrameCount) { 573 sBenchMma = ((9 * sBenchMma) + thisFrame) / 10; 574 } else { 575 sBenchMma = thisFrame; 576 } 577 if (++sFrameCount == 10) { 578 sFrameCount = 1; 579 ALOGD("Average frame time: %.4f", sBenchMma); 580 } 581#endif 582 583 mJankTracker.addFrame(*mCurrentFrameInfo); 584 mRenderThread.jankTracker().addFrame(*mCurrentFrameInfo); 585 if (CC_UNLIKELY(mFrameMetricsReporter.get() != nullptr)) { 586 mFrameMetricsReporter->reportFrameMetrics(mCurrentFrameInfo->data()); 587 } 588 589 GpuMemoryTracker::onFrameCompleted(); 590} 591 592// Called by choreographer to do an RT-driven animation 593void CanvasContext::doFrame() { 594#if HWUI_NEW_OPS 595 if (CC_UNLIKELY(mEglSurface == EGL_NO_SURFACE)) return; 596#else 597 if (CC_UNLIKELY(!mCanvas || mEglSurface == EGL_NO_SURFACE)) return; 598#endif 599 prepareAndDraw(nullptr); 600} 601 602void CanvasContext::prepareAndDraw(RenderNode* node) { 603 ATRACE_CALL(); 604 605 nsecs_t vsync = mRenderThread.timeLord().computeFrameTimeNanos(); 606 int64_t frameInfo[UI_THREAD_FRAME_INFO_SIZE]; 607 UiFrameInfoBuilder(frameInfo) 608 .addFlag(FrameInfoFlags::RTAnimation) 609 .setVsync(vsync, vsync); 610 611 TreeInfo info(TreeInfo::MODE_RT_ONLY, *this); 612 prepareTree(info, frameInfo, systemTime(CLOCK_MONOTONIC), node); 613 if (info.out.canDrawThisFrame) { 614 draw(); 615 } 616} 617 618void CanvasContext::invokeFunctor(RenderThread& thread, Functor* functor) { 619 ATRACE_CALL(); 620 DrawGlInfo::Mode mode = DrawGlInfo::kModeProcessNoContext; 621 if (thread.eglManager().hasEglContext()) { 622 mode = DrawGlInfo::kModeProcess; 623 } 624 625 thread.renderState().invokeFunctor(functor, mode, nullptr); 626} 627 628void CanvasContext::markLayerInUse(RenderNode* node) { 629 if (mPrefetchedLayers.erase(node)) { 630 node->decStrong(nullptr); 631 } 632} 633 634void CanvasContext::freePrefetchedLayers(TreeObserver* observer) { 635 if (mPrefetchedLayers.size()) { 636 for (auto& node : mPrefetchedLayers) { 637 ALOGW("Incorrectly called buildLayer on View: %s, destroying layer...", 638 node->getName()); 639 node->destroyHardwareResources(observer); 640 node->decStrong(observer); 641 } 642 mPrefetchedLayers.clear(); 643 } 644} 645 646void CanvasContext::buildLayer(RenderNode* node, TreeObserver* observer) { 647 ATRACE_CALL(); 648 if (!mEglManager.hasEglContext()) return; 649#if !HWUI_NEW_OPS 650 if (!mCanvas) return; 651#endif 652 653 // buildLayer() will leave the tree in an unknown state, so we must stop drawing 654 stopDrawing(); 655 656 TreeInfo info(TreeInfo::MODE_FULL, *this); 657 info.damageAccumulator = &mDamageAccumulator; 658 info.observer = observer; 659#if HWUI_NEW_OPS 660 info.layerUpdateQueue = &mLayerUpdateQueue; 661#else 662 info.renderer = mCanvas; 663#endif 664 info.runAnimations = false; 665 node->prepareTree(info); 666 SkRect ignore; 667 mDamageAccumulator.finish(&ignore); 668 // Tickle the GENERIC property on node to mark it as dirty for damaging 669 // purposes when the frame is actually drawn 670 node->setPropertyFieldsDirty(RenderNode::GENERIC); 671 672#if HWUI_NEW_OPS 673 static const std::vector< sp<RenderNode> > emptyNodeList; 674 auto& caches = Caches::getInstance(); 675 FrameBuilder frameBuilder(mLayerUpdateQueue, mLightGeometry, caches); 676 mLayerUpdateQueue.clear(); 677 BakedOpRenderer renderer(caches, mRenderThread.renderState(), 678 mOpaque, mLightInfo); 679 LOG_ALWAYS_FATAL_IF(renderer.didDraw(), "shouldn't draw in buildlayer case"); 680 frameBuilder.replayBakedOps<BakedOpDispatcher>(renderer); 681#else 682 mCanvas->markLayersAsBuildLayers(); 683 mCanvas->flushLayerUpdates(); 684#endif 685 686 node->incStrong(nullptr); 687 mPrefetchedLayers.insert(node); 688} 689 690bool CanvasContext::copyLayerInto(DeferredLayerUpdater* layer, SkBitmap* bitmap) { 691 layer->apply(); 692 return LayerRenderer::copyLayer(mRenderThread.renderState(), layer->backingLayer(), bitmap); 693} 694 695void CanvasContext::destroyHardwareResources(TreeObserver* observer) { 696 stopDrawing(); 697 if (mEglManager.hasEglContext()) { 698 freePrefetchedLayers(observer); 699 for (const sp<RenderNode>& node : mRenderNodes) { 700 node->destroyHardwareResources(observer); 701 } 702 Caches& caches = Caches::getInstance(); 703 // Make sure to release all the textures we were owning as there won't 704 // be another draw 705 caches.textureCache.resetMarkInUse(this); 706 mRenderThread.renderState().flush(Caches::FlushMode::Layers); 707 } 708} 709 710void CanvasContext::trimMemory(RenderThread& thread, int level) { 711 // No context means nothing to free 712 if (!thread.eglManager().hasEglContext()) return; 713 714 ATRACE_CALL(); 715 if (level >= TRIM_MEMORY_COMPLETE) { 716 thread.renderState().flush(Caches::FlushMode::Full); 717 thread.eglManager().destroy(); 718 } else if (level >= TRIM_MEMORY_UI_HIDDEN) { 719 thread.renderState().flush(Caches::FlushMode::Moderate); 720 } 721} 722 723Layer* CanvasContext::createTextureLayer() { 724 mEglManager.initialize(); 725 return LayerRenderer::createTextureLayer(mRenderThread.renderState()); 726} 727 728void CanvasContext::setTextureAtlas(RenderThread& thread, 729 const sp<GraphicBuffer>& buffer, int64_t* map, size_t mapSize) { 730 thread.eglManager().setTextureAtlas(buffer, map, mapSize); 731} 732 733void CanvasContext::dumpFrames(int fd) { 734 FILE* file = fdopen(fd, "a"); 735 fprintf(file, "\n\n---PROFILEDATA---\n"); 736 for (size_t i = 0; i < static_cast<size_t>(FrameInfoIndex::NumIndexes); i++) { 737 fprintf(file, "%s", FrameInfoNames[i].c_str()); 738 fprintf(file, ","); 739 } 740 for (size_t i = 0; i < mFrames.size(); i++) { 741 FrameInfo& frame = mFrames[i]; 742 if (frame[FrameInfoIndex::SyncStart] == 0) { 743 continue; 744 } 745 fprintf(file, "\n"); 746 for (int i = 0; i < static_cast<int>(FrameInfoIndex::NumIndexes); i++) { 747 fprintf(file, "%" PRId64 ",", frame[i]); 748 } 749 } 750 fprintf(file, "\n---PROFILEDATA---\n\n"); 751 fflush(file); 752} 753 754void CanvasContext::resetFrameStats() { 755 mFrames.clear(); 756 mRenderThread.jankTracker().reset(); 757} 758 759void CanvasContext::serializeDisplayListTree() { 760#if ENABLE_RENDERNODE_SERIALIZATION 761 using namespace google::protobuf::io; 762 char package[128]; 763 // Check whether tracing is enabled for this process. 764 FILE * file = fopen("/proc/self/cmdline", "r"); 765 if (file) { 766 if (!fgets(package, 128, file)) { 767 ALOGE("Error reading cmdline: %s (%d)", strerror(errno), errno); 768 fclose(file); 769 return; 770 } 771 fclose(file); 772 } else { 773 ALOGE("Error opening /proc/self/cmdline: %s (%d)", strerror(errno), 774 errno); 775 return; 776 } 777 char path[1024]; 778 snprintf(path, 1024, "/data/data/%s/cache/rendertree_dump", package); 779 int fd = open(path, O_CREAT | O_WRONLY, S_IRWXU | S_IRGRP | S_IROTH); 780 if (fd == -1) { 781 ALOGD("Failed to open '%s'", path); 782 return; 783 } 784 proto::RenderNode tree; 785 // TODO: Streaming writes? 786 mRootRenderNode->copyTo(&tree); 787 std::string data = tree.SerializeAsString(); 788 write(fd, data.c_str(), data.length()); 789 close(fd); 790#endif 791} 792 793void CanvasContext::waitOnFences() { 794 if (mFrameFences.size()) { 795 ATRACE_CALL(); 796 for (auto& fence : mFrameFences) { 797 fence->getResult(); 798 } 799 mFrameFences.clear(); 800 } 801} 802 803class CanvasContext::FuncTaskProcessor : public TaskProcessor<bool> { 804public: 805 explicit FuncTaskProcessor(Caches& caches) 806 : TaskProcessor<bool>(&caches.tasks) {} 807 808 virtual void onProcess(const sp<Task<bool> >& task) override { 809 FuncTask* t = static_cast<FuncTask*>(task.get()); 810 t->func(); 811 task->setResult(true); 812 } 813}; 814 815void CanvasContext::enqueueFrameWork(std::function<void()>&& func) { 816 if (!mFrameWorkProcessor.get()) { 817 mFrameWorkProcessor = new FuncTaskProcessor(Caches::getInstance()); 818 } 819 sp<FuncTask> task(new FuncTask()); 820 task->func = func; 821 mFrameFences.push_back(task); 822 mFrameWorkProcessor->add(task); 823} 824 825int64_t CanvasContext::getFrameNumber() { 826 // mFrameNumber is reset to -1 when the surface changes or we swap buffers 827 if (mFrameNumber == -1 && mNativeSurface.get()) { 828 mFrameNumber = static_cast<int64_t>(mNativeSurface->getNextFrameNumber()); 829 } 830 return mFrameNumber; 831} 832 833} /* namespace renderthread */ 834} /* namespace uirenderer */ 835} /* namespace android */ 836