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