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