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