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