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