CanvasContext.cpp revision 975591a7af883d866d86ab819e164c6004694744
116f03928743b01638419874e2b6300b52da6eb4cJesse Hall/* 216f03928743b01638419874e2b6300b52da6eb4cJesse Hall * Copyright (C) 2014 The Android Open Source Project 316f03928743b01638419874e2b6300b52da6eb4cJesse Hall * 416f03928743b01638419874e2b6300b52da6eb4cJesse Hall * 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 "renderstate/RenderState.h" 30#include "renderstate/Stencil.h" 31#include "protos/hwui.pb.h" 32#include "utils/GLUtils.h" 33#include "utils/TimeUtils.h" 34 35#if HWUI_NEW_OPS 36#include "FrameBuilder.h" 37#endif 38 39#include <cutils/properties.h> 40#include <google/protobuf/io/zero_copy_stream_impl.h> 41#include <private/hwui/DrawGlInfo.h> 42#include <strings.h> 43 44#include <algorithm> 45#include <fcntl.h> 46#include <sys/stat.h> 47 48#include <cstdlib> 49 50#define TRIM_MEMORY_COMPLETE 80 51#define TRIM_MEMORY_UI_HIDDEN 20 52 53#define ENABLE_RENDERNODE_SERIALIZATION false 54 55#define LOG_FRAMETIME_MMA 0 56 57#if LOG_FRAMETIME_MMA 58static float sBenchMma = 0; 59static int sFrameCount = 0; 60static const float NANOS_PER_MILLIS_F = 1000000.0f; 61#endif 62 63namespace android { 64namespace uirenderer { 65namespace renderthread { 66 67CanvasContext::CanvasContext(RenderThread& thread, bool translucent, 68 RenderNode* rootRenderNode, IContextFactory* contextFactory) 69 : mRenderThread(thread) 70 , mEglManager(thread.eglManager()) 71 , mOpaque(!translucent) 72 , mAnimationContext(contextFactory->createAnimationContext(mRenderThread.timeLord())) 73 , mJankTracker(thread.timeLord().frameIntervalNanos()) 74 , mProfiler(mFrames) 75 , mContentDrawBounds(0, 0, 0, 0) { 76 mRenderNodes.emplace_back(rootRenderNode); 77 mRenderThread.renderState().registerCanvasContext(this); 78 mProfiler.setDensity(mRenderThread.mainDisplayInfo().density); 79} 80 81CanvasContext::~CanvasContext() { 82 destroy(); 83 mRenderThread.renderState().unregisterCanvasContext(this); 84} 85 86void CanvasContext::destroy() { 87 stopDrawing(); 88 setSurface(nullptr); 89 freePrefetechedLayers(); 90 destroyHardwareResources(); 91 mAnimationContext->destroy(); 92 if (mCanvas) { 93 delete mCanvas; 94 mCanvas = nullptr; 95 } 96} 97 98void CanvasContext::setSurface(ANativeWindow* window) { 99 ATRACE_CALL(); 100 101 mNativeWindow = window; 102 103 if (mEglSurface != EGL_NO_SURFACE) { 104 mEglManager.destroySurface(mEglSurface); 105 mEglSurface = EGL_NO_SURFACE; 106 } 107 108 if (window) { 109 mEglSurface = mEglManager.createSurface(window); 110 } 111 112 if (mEglSurface != EGL_NO_SURFACE) { 113 const bool preserveBuffer = (mSwapBehavior != kSwap_discardBuffer); 114 mBufferPreserved = mEglManager.setPreserveBuffer(mEglSurface, preserveBuffer); 115 mHaveNewSurface = true; 116 mSwapHistory.clear(); 117 makeCurrent(); 118 } else { 119 mRenderThread.removeFrameCallback(this); 120 } 121} 122 123void CanvasContext::requireSurface() { 124 LOG_ALWAYS_FATAL_IF(mEglSurface == EGL_NO_SURFACE, 125 "requireSurface() called but no surface set!"); 126 makeCurrent(); 127} 128 129void CanvasContext::setSwapBehavior(SwapBehavior swapBehavior) { 130 mSwapBehavior = swapBehavior; 131} 132 133void CanvasContext::initialize(ANativeWindow* window) { 134 setSurface(window); 135#if !HWUI_NEW_OPS 136 if (mCanvas) return; 137 mCanvas = new OpenGLRenderer(mRenderThread.renderState()); 138 mCanvas->initProperties(); 139#endif 140} 141 142void CanvasContext::updateSurface(ANativeWindow* window) { 143 setSurface(window); 144} 145 146bool CanvasContext::pauseSurface(ANativeWindow* window) { 147 return mRenderThread.removeFrameCallback(this); 148} 149 150// TODO: don't pass viewport size, it's automatic via EGL 151void CanvasContext::setup(int width, int height, float lightRadius, 152 uint8_t ambientShadowAlpha, uint8_t spotShadowAlpha) { 153#if HWUI_NEW_OPS 154 mLightInfo.lightRadius = lightRadius; 155 mLightInfo.ambientShadowAlpha = ambientShadowAlpha; 156 mLightInfo.spotShadowAlpha = spotShadowAlpha; 157#else 158 if (!mCanvas) return; 159 mCanvas->initLight(lightRadius, ambientShadowAlpha, spotShadowAlpha); 160#endif 161} 162 163void CanvasContext::setLightCenter(const Vector3& lightCenter) { 164#if HWUI_NEW_OPS 165 mLightCenter = lightCenter; 166#else 167 if (!mCanvas) return; 168 mCanvas->setLightCenter(lightCenter); 169#endif 170} 171 172void CanvasContext::setOpaque(bool opaque) { 173 mOpaque = opaque; 174} 175 176void CanvasContext::makeCurrent() { 177 // TODO: Figure out why this workaround is needed, see b/13913604 178 // In the meantime this matches the behavior of GLRenderer, so it is not a regression 179 EGLint error = 0; 180 mHaveNewSurface |= mEglManager.makeCurrent(mEglSurface, &error); 181 if (error) { 182 setSurface(nullptr); 183 } 184} 185 186static bool wasSkipped(FrameInfo* info) { 187 return info && ((*info)[FrameInfoIndex::Flags] & FrameInfoFlags::SkippedFrame); 188} 189 190void CanvasContext::prepareTree(TreeInfo& info, int64_t* uiFrameInfo, 191 int64_t syncQueued, RenderNode* target) { 192 mRenderThread.removeFrameCallback(this); 193 194 // If the previous frame was dropped we don't need to hold onto it, so 195 // just keep using the previous frame's structure instead 196 if (!wasSkipped(mCurrentFrameInfo)) { 197 mCurrentFrameInfo = &mFrames.next(); 198 } 199 mCurrentFrameInfo->importUiThreadInfo(uiFrameInfo); 200 mCurrentFrameInfo->set(FrameInfoIndex::SyncQueued) = syncQueued; 201 mCurrentFrameInfo->markSyncStart(); 202 203 info.damageAccumulator = &mDamageAccumulator; 204#if HWUI_NEW_OPS 205 info.layerUpdateQueue = &mLayerUpdateQueue; 206#else 207 info.renderer = mCanvas; 208#endif 209 210 mAnimationContext->startFrame(info.mode); 211 for (const sp<RenderNode>& node : mRenderNodes) { 212 // Only the primary target node will be drawn full - all other nodes would get drawn in 213 // real time mode. In case of a window, the primary node is the window content and the other 214 // node(s) are non client / filler nodes. 215 info.mode = (node.get() == target ? TreeInfo::MODE_FULL : TreeInfo::MODE_RT_ONLY); 216 node->prepareTree(info); 217 GL_CHECKPOINT(MODERATE); 218 } 219 mAnimationContext->runRemainingAnimations(info); 220 GL_CHECKPOINT(MODERATE); 221 222 freePrefetechedLayers(); 223 GL_CHECKPOINT(MODERATE); 224 225 if (CC_UNLIKELY(!mNativeWindow.get())) { 226 mCurrentFrameInfo->addFlag(FrameInfoFlags::SkippedFrame); 227 info.out.canDrawThisFrame = false; 228 return; 229 } 230 231 if (CC_LIKELY(mSwapHistory.size())) { 232 nsecs_t latestVsync = mRenderThread.timeLord().latestVsync(); 233 const SwapHistory& lastSwap = mSwapHistory.back(); 234 nsecs_t vsyncDelta = std::abs(lastSwap.vsyncTime - latestVsync); 235 // The slight fudge-factor is to deal with cases where 236 // the vsync was estimated due to being slow handling the signal. 237 // See the logic in TimeLord#computeFrameTimeNanos or in 238 // Choreographer.java for details on when this happens 239 if (vsyncDelta < 2_ms) { 240 // Already drew for this vsync pulse, UI draw request missed 241 // the deadline for RT animations 242 info.out.canDrawThisFrame = false; 243 } else if (lastSwap.swapTime < latestVsync) { 244 info.out.canDrawThisFrame = true; 245 } else { 246 // We're maybe behind? Find out for sure 247 int runningBehind = 0; 248 mNativeWindow->query(mNativeWindow.get(), 249 NATIVE_WINDOW_CONSUMER_RUNNING_BEHIND, &runningBehind); 250 info.out.canDrawThisFrame = !runningBehind; 251 } 252 } else { 253 info.out.canDrawThisFrame = true; 254 } 255 256 if (!info.out.canDrawThisFrame) { 257 mCurrentFrameInfo->addFlag(FrameInfoFlags::SkippedFrame); 258 } 259 260 if (info.out.hasAnimations || !info.out.canDrawThisFrame) { 261 if (!info.out.requiresUiRedraw) { 262 // If animationsNeedsRedraw is set don't bother posting for an RT anim 263 // as we will just end up fighting the UI thread. 264 mRenderThread.postFrameCallback(this); 265 } 266 } 267} 268 269void CanvasContext::stopDrawing() { 270 mRenderThread.removeFrameCallback(this); 271} 272 273void CanvasContext::notifyFramePending() { 274 ATRACE_CALL(); 275 mRenderThread.pushBackFrameCallback(this); 276} 277 278void CanvasContext::draw() { 279#if !HWUI_NEW_OPS 280 LOG_ALWAYS_FATAL_IF(!mCanvas || mEglSurface == EGL_NO_SURFACE, 281 "drawRenderNode called on a context with no canvas or surface!"); 282#endif 283 284 SkRect dirty; 285 mDamageAccumulator.finish(&dirty); 286 287 // TODO: Re-enable after figuring out cause of b/22592975 288// if (dirty.isEmpty() && Properties::skipEmptyFrames) { 289// mCurrentFrameInfo->addFlag(FrameInfoFlags::SkippedFrame); 290// return; 291// } 292 293 mCurrentFrameInfo->markIssueDrawCommandsStart(); 294 295 Frame frame = mEglManager.beginFrame(mEglSurface); 296 297 if (frame.width() != mLastFrameWidth || frame.height() != mLastFrameHeight) { 298 // can't rely on prior content of window if viewport size changes 299 dirty.setEmpty(); 300 mLastFrameWidth = frame.width(); 301 mLastFrameHeight = frame.height(); 302 } else if (mHaveNewSurface || frame.bufferAge() == 0) { 303 // New surface needs a full draw 304 dirty.setEmpty(); 305 } else { 306 if (!dirty.isEmpty() && !dirty.intersect(0, 0, frame.width(), frame.height())) { 307 ALOGW("Dirty " RECT_STRING " doesn't intersect with 0 0 %d %d ?", 308 SK_RECT_ARGS(dirty), frame.width(), frame.height()); 309 dirty.setEmpty(); 310 } 311 profiler().unionDirty(&dirty); 312 } 313 314 if (dirty.isEmpty()) { 315 dirty.set(0, 0, frame.width(), frame.height()); 316 } 317 318 // At this point dirty is the area of the screen to update. However, 319 // the area of the frame we need to repaint is potentially different, so 320 // stash the screen area for later 321 SkRect screenDirty(dirty); 322 323 // If the buffer age is 0 we do a full-screen repaint (handled above) 324 // If the buffer age is 1 the buffer contents are the same as they were 325 // last frame so there's nothing to union() against 326 // Therefore we only care about the > 1 case. 327 if (frame.bufferAge() > 1) { 328 if (frame.bufferAge() > (int) mSwapHistory.size()) { 329 // We don't have enough history to handle this old of a buffer 330 // Just do a full-draw 331 dirty.set(0, 0, frame.width(), frame.height()); 332 } else { 333 // At this point we haven't yet added the latest frame 334 // to the damage history (happens below) 335 // So we need to damage 336 for (int i = mSwapHistory.size() - 1; 337 i > ((int) mSwapHistory.size()) - frame.bufferAge(); i--) { 338 dirty.join(mSwapHistory[i].damage); 339 } 340 } 341 } 342 343 mEglManager.damageFrame(frame, dirty); 344 345#if HWUI_NEW_OPS 346 FrameBuilder frameBuilder(mLayerUpdateQueue, dirty, frame.width(), frame.height(), 347 mRenderNodes, mLightCenter); 348 mLayerUpdateQueue.clear(); 349 BakedOpRenderer renderer(Caches::getInstance(), mRenderThread.renderState(), 350 mOpaque, mLightInfo); 351 // TODO: profiler().draw(mCanvas); 352 frameBuilder.replayBakedOps<BakedOpDispatcher>(renderer); 353 bool drew = renderer.didDraw(); 354 355#else 356 mCanvas->prepareDirty(frame.width(), frame.height(), 357 dirty.fLeft, dirty.fTop, dirty.fRight, dirty.fBottom, mOpaque); 358 359 Rect outBounds; 360 // It there are multiple render nodes, they are laid out as follows: 361 // #0 - backdrop (content + caption) 362 // #1 - content (positioned at (0,0) and clipped to - its bounds mContentDrawBounds) 363 // #2 - additional overlay nodes 364 // Usually the backdrop cannot be seen since it will be entirely covered by the content. While 365 // resizing however it might become partially visible. The following render loop will crop the 366 // backdrop against the content and draw the remaining part of it. It will then draw the content 367 // cropped to the backdrop (since that indicates a shrinking of the window). 368 // 369 // Additional nodes will be drawn on top with no particular clipping semantics. 370 371 // The bounds of the backdrop against which the content should be clipped. 372 Rect backdropBounds = mContentDrawBounds; 373 // Usually the contents bounds should be mContentDrawBounds - however - we will 374 // move it towards the fixed edge to give it a more stable appearance (for the moment). 375 Rect contentBounds; 376 // If there is no content bounds we ignore the layering as stated above and start with 2. 377 int layer = (mContentDrawBounds.isEmpty() || mRenderNodes.size() == 1) ? 2 : 0; 378 // Draw all render nodes. Note that 379 for (const sp<RenderNode>& node : mRenderNodes) { 380 if (layer == 0) { // Backdrop. 381 // Draw the backdrop clipped to the inverse content bounds, but assume that the content 382 // was moved to the upper left corner. 383 const RenderProperties& properties = node->properties(); 384 Rect targetBounds(properties.getLeft(), properties.getTop(), 385 properties.getRight(), properties.getBottom()); 386 // Move the content bounds towards the fixed corner of the backdrop. 387 const int x = targetBounds.left; 388 const int y = targetBounds.top; 389 contentBounds.set(x, y, x + mContentDrawBounds.getWidth(), 390 y + mContentDrawBounds.getHeight()); 391 // Remember the intersection of the target bounds and the intersection bounds against 392 // which we have to crop the content. 393 backdropBounds.set(x, y, x + backdropBounds.getWidth(), y + backdropBounds.getHeight()); 394 backdropBounds.doIntersect(targetBounds); 395 // Check if we have to draw something on the left side ... 396 if (targetBounds.left < contentBounds.left) { 397 mCanvas->save(SkCanvas::kClip_SaveFlag); 398 if (mCanvas->clipRect(targetBounds.left, targetBounds.top, 399 contentBounds.left, targetBounds.bottom, 400 SkRegion::kIntersect_Op)) { 401 mCanvas->drawRenderNode(node.get(), outBounds); 402 } 403 // Reduce the target area by the area we have just painted. 404 targetBounds.left = std::min(contentBounds.left, targetBounds.right); 405 mCanvas->restore(); 406 } 407 // ... or on the right side ... 408 if (targetBounds.right > contentBounds.right && 409 !targetBounds.isEmpty()) { 410 mCanvas->save(SkCanvas::kClip_SaveFlag); 411 if (mCanvas->clipRect(contentBounds.right, targetBounds.top, 412 targetBounds.right, targetBounds.bottom, 413 SkRegion::kIntersect_Op)) { 414 mCanvas->drawRenderNode(node.get(), outBounds); 415 } 416 // Reduce the target area by the area we have just painted. 417 targetBounds.right = std::max(targetBounds.left, contentBounds.right); 418 mCanvas->restore(); 419 } 420 // ... or at the top ... 421 if (targetBounds.top < contentBounds.top && 422 !targetBounds.isEmpty()) { 423 mCanvas->save(SkCanvas::kClip_SaveFlag); 424 if (mCanvas->clipRect(targetBounds.left, targetBounds.top, targetBounds.right, 425 contentBounds.top, 426 SkRegion::kIntersect_Op)) { 427 mCanvas->drawRenderNode(node.get(), outBounds); 428 } 429 // Reduce the target area by the area we have just painted. 430 targetBounds.top = std::min(contentBounds.top, targetBounds.bottom); 431 mCanvas->restore(); 432 } 433 // ... or at the bottom. 434 if (targetBounds.bottom > contentBounds.bottom && 435 !targetBounds.isEmpty()) { 436 mCanvas->save(SkCanvas::kClip_SaveFlag); 437 if (mCanvas->clipRect(targetBounds.left, contentBounds.bottom, targetBounds.right, 438 targetBounds.bottom, SkRegion::kIntersect_Op)) { 439 mCanvas->drawRenderNode(node.get(), outBounds); 440 } 441 mCanvas->restore(); 442 } 443 } else if (layer == 1) { // Content 444 // It gets cropped against the bounds of the backdrop to stay inside. 445 mCanvas->save(SkCanvas::kClip_SaveFlag | SkCanvas::kMatrix_SaveFlag); 446 447 // We shift and clip the content to match its final location in the window. 448 const float left = mContentDrawBounds.left; 449 const float top = mContentDrawBounds.top; 450 const float dx = backdropBounds.left - left; 451 const float dy = backdropBounds.top - top; 452 const float width = backdropBounds.getWidth(); 453 const float height = backdropBounds.getHeight(); 454 455 mCanvas->translate(dx, dy); 456 if (mCanvas->clipRect(left, top, left + width, top + height, SkRegion::kIntersect_Op)) { 457 mCanvas->drawRenderNode(node.get(), outBounds); 458 } 459 mCanvas->restore(); 460 } else { // draw the rest on top at will! 461 mCanvas->drawRenderNode(node.get(), outBounds); 462 } 463 layer++; 464 } 465 466 profiler().draw(mCanvas); 467 468 bool drew = mCanvas->finish(); 469#endif 470 471 GL_CHECKPOINT(LOW); 472 473 // Even if we decided to cancel the frame, from the perspective of jank 474 // metrics the frame was swapped at this point 475 mCurrentFrameInfo->markSwapBuffers(); 476 477 if (drew) { 478 if (CC_UNLIKELY(!mEglManager.swapBuffers(frame, screenDirty))) { 479 setSurface(nullptr); 480 } 481 SwapHistory& swap = mSwapHistory.next(); 482 swap.damage = screenDirty; 483 swap.swapTime = systemTime(CLOCK_MONOTONIC); 484 swap.vsyncTime = mRenderThread.timeLord().latestVsync(); 485 mHaveNewSurface = false; 486 } 487 488 // TODO: Use a fence for real completion? 489 mCurrentFrameInfo->markFrameCompleted(); 490 491#if LOG_FRAMETIME_MMA 492 float thisFrame = mCurrentFrameInfo->duration( 493 FrameInfoIndex::IssueDrawCommandsStart, 494 FrameInfoIndex::FrameCompleted) / NANOS_PER_MILLIS_F; 495 if (sFrameCount) { 496 sBenchMma = ((9 * sBenchMma) + thisFrame) / 10; 497 } else { 498 sBenchMma = thisFrame; 499 } 500 if (++sFrameCount == 10) { 501 sFrameCount = 1; 502 ALOGD("Average frame time: %.4f", sBenchMma); 503 } 504#endif 505 506 mJankTracker.addFrame(*mCurrentFrameInfo); 507 mRenderThread.jankTracker().addFrame(*mCurrentFrameInfo); 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