CanvasContext.cpp revision dccca44ffda4836b56a21da95a046c9708ffd49c
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 "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 "hwui/Canvas.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 auto&& caches = Caches::getInstance(); 352 BakedOpRenderer renderer(caches, mRenderThread.renderState(), 353 mOpaque, mLightInfo); 354 frameBuilder.replayBakedOps<BakedOpDispatcher>(renderer); 355 profiler().draw(&renderer); 356 bool drew = renderer.didDraw(); 357 358 // post frame cleanup 359 caches.clearGarbage(); 360 caches.pathCache.trim(); 361 caches.tessellationCache.trim(); 362 363#if DEBUG_MEMORY_USAGE 364 mCaches.dumpMemoryUsage(); 365#else 366 if (CC_UNLIKELY(Properties::debugLevel & kDebugMemory)) { 367 caches.dumpMemoryUsage(); 368 } 369#endif 370 371#else 372 mCanvas->prepareDirty(frame.width(), frame.height(), 373 dirty.fLeft, dirty.fTop, dirty.fRight, dirty.fBottom, mOpaque); 374 375 Rect outBounds; 376 // It there are multiple render nodes, they are laid out as follows: 377 // #0 - backdrop (content + caption) 378 // #1 - content (positioned at (0,0) and clipped to - its bounds mContentDrawBounds) 379 // #2 - additional overlay nodes 380 // Usually the backdrop cannot be seen since it will be entirely covered by the content. While 381 // resizing however it might become partially visible. The following render loop will crop the 382 // backdrop against the content and draw the remaining part of it. It will then draw the content 383 // cropped to the backdrop (since that indicates a shrinking of the window). 384 // 385 // Additional nodes will be drawn on top with no particular clipping semantics. 386 387 // The bounds of the backdrop against which the content should be clipped. 388 Rect backdropBounds = mContentDrawBounds; 389 // Usually the contents bounds should be mContentDrawBounds - however - we will 390 // move it towards the fixed edge to give it a more stable appearance (for the moment). 391 Rect contentBounds; 392 // If there is no content bounds we ignore the layering as stated above and start with 2. 393 int layer = (mContentDrawBounds.isEmpty() || mRenderNodes.size() == 1) ? 2 : 0; 394 // Draw all render nodes. Note that 395 for (const sp<RenderNode>& node : mRenderNodes) { 396 if (layer == 0) { // Backdrop. 397 // Draw the backdrop clipped to the inverse content bounds, but assume that the content 398 // was moved to the upper left corner. 399 const RenderProperties& properties = node->properties(); 400 Rect targetBounds(properties.getLeft(), properties.getTop(), 401 properties.getRight(), properties.getBottom()); 402 // Move the content bounds towards the fixed corner of the backdrop. 403 const int x = targetBounds.left; 404 const int y = targetBounds.top; 405 contentBounds.set(x, y, x + mContentDrawBounds.getWidth(), 406 y + mContentDrawBounds.getHeight()); 407 // Remember the intersection of the target bounds and the intersection bounds against 408 // which we have to crop the content. 409 backdropBounds.set(x, y, x + backdropBounds.getWidth(), y + backdropBounds.getHeight()); 410 backdropBounds.doIntersect(targetBounds); 411 // Check if we have to draw something on the left side ... 412 if (targetBounds.left < contentBounds.left) { 413 mCanvas->save(SaveFlags::Clip); 414 if (mCanvas->clipRect(targetBounds.left, targetBounds.top, 415 contentBounds.left, targetBounds.bottom, 416 SkRegion::kIntersect_Op)) { 417 mCanvas->drawRenderNode(node.get(), outBounds); 418 } 419 // Reduce the target area by the area we have just painted. 420 targetBounds.left = std::min(contentBounds.left, targetBounds.right); 421 mCanvas->restore(); 422 } 423 // ... or on the right side ... 424 if (targetBounds.right > contentBounds.right && 425 !targetBounds.isEmpty()) { 426 mCanvas->save(SaveFlags::Clip); 427 if (mCanvas->clipRect(contentBounds.right, targetBounds.top, 428 targetBounds.right, targetBounds.bottom, 429 SkRegion::kIntersect_Op)) { 430 mCanvas->drawRenderNode(node.get(), outBounds); 431 } 432 // Reduce the target area by the area we have just painted. 433 targetBounds.right = std::max(targetBounds.left, contentBounds.right); 434 mCanvas->restore(); 435 } 436 // ... or at the top ... 437 if (targetBounds.top < contentBounds.top && 438 !targetBounds.isEmpty()) { 439 mCanvas->save(SaveFlags::Clip); 440 if (mCanvas->clipRect(targetBounds.left, targetBounds.top, targetBounds.right, 441 contentBounds.top, 442 SkRegion::kIntersect_Op)) { 443 mCanvas->drawRenderNode(node.get(), outBounds); 444 } 445 // Reduce the target area by the area we have just painted. 446 targetBounds.top = std::min(contentBounds.top, targetBounds.bottom); 447 mCanvas->restore(); 448 } 449 // ... or at the bottom. 450 if (targetBounds.bottom > contentBounds.bottom && 451 !targetBounds.isEmpty()) { 452 mCanvas->save(SaveFlags::Clip); 453 if (mCanvas->clipRect(targetBounds.left, contentBounds.bottom, targetBounds.right, 454 targetBounds.bottom, SkRegion::kIntersect_Op)) { 455 mCanvas->drawRenderNode(node.get(), outBounds); 456 } 457 mCanvas->restore(); 458 } 459 } else if (layer == 1) { // Content 460 // It gets cropped against the bounds of the backdrop to stay inside. 461 mCanvas->save(SaveFlags::MatrixClip); 462 463 // We shift and clip the content to match its final location in the window. 464 const float left = mContentDrawBounds.left; 465 const float top = mContentDrawBounds.top; 466 const float dx = backdropBounds.left - left; 467 const float dy = backdropBounds.top - top; 468 const float width = backdropBounds.getWidth(); 469 const float height = backdropBounds.getHeight(); 470 471 mCanvas->translate(dx, dy); 472 if (mCanvas->clipRect(left, top, left + width, top + height, SkRegion::kIntersect_Op)) { 473 mCanvas->drawRenderNode(node.get(), outBounds); 474 } 475 mCanvas->restore(); 476 } else { // draw the rest on top at will! 477 mCanvas->drawRenderNode(node.get(), outBounds); 478 } 479 layer++; 480 } 481 482 profiler().draw(mCanvas); 483 484 bool drew = mCanvas->finish(); 485#endif 486 487 waitOnFences(); 488 489 GL_CHECKPOINT(LOW); 490 491 // Even if we decided to cancel the frame, from the perspective of jank 492 // metrics the frame was swapped at this point 493 mCurrentFrameInfo->markSwapBuffers(); 494 495 if (drew || mEglManager.damageRequiresSwap()) { 496 if (CC_UNLIKELY(!mEglManager.swapBuffers(frame, screenDirty))) { 497 setSurface(nullptr); 498 } 499 SwapHistory& swap = mSwapHistory.next(); 500 swap.damage = screenDirty; 501 swap.swapTime = systemTime(CLOCK_MONOTONIC); 502 swap.vsyncTime = mRenderThread.timeLord().latestVsync(); 503 mHaveNewSurface = false; 504 } 505 506 // TODO: Use a fence for real completion? 507 mCurrentFrameInfo->markFrameCompleted(); 508 509#if LOG_FRAMETIME_MMA 510 float thisFrame = mCurrentFrameInfo->duration( 511 FrameInfoIndex::IssueDrawCommandsStart, 512 FrameInfoIndex::FrameCompleted) / NANOS_PER_MILLIS_F; 513 if (sFrameCount) { 514 sBenchMma = ((9 * sBenchMma) + thisFrame) / 10; 515 } else { 516 sBenchMma = thisFrame; 517 } 518 if (++sFrameCount == 10) { 519 sFrameCount = 1; 520 ALOGD("Average frame time: %.4f", sBenchMma); 521 } 522#endif 523 524 mJankTracker.addFrame(*mCurrentFrameInfo); 525 mRenderThread.jankTracker().addFrame(*mCurrentFrameInfo); 526 if (CC_UNLIKELY(mFrameMetricsReporter.get() != nullptr)) { 527 mFrameMetricsReporter->reportFrameMetrics(mCurrentFrameInfo->data()); 528 } 529 530 GpuMemoryTracker::onFrameCompleted(); 531} 532 533// Called by choreographer to do an RT-driven animation 534void CanvasContext::doFrame() { 535#if HWUI_NEW_OPS 536 if (CC_UNLIKELY(mEglSurface == EGL_NO_SURFACE)) return; 537#else 538 if (CC_UNLIKELY(!mCanvas || mEglSurface == EGL_NO_SURFACE)) return; 539#endif 540 prepareAndDraw(nullptr); 541} 542 543void CanvasContext::prepareAndDraw(RenderNode* node) { 544 ATRACE_CALL(); 545 546 nsecs_t vsync = mRenderThread.timeLord().computeFrameTimeNanos(); 547 int64_t frameInfo[UI_THREAD_FRAME_INFO_SIZE]; 548 UiFrameInfoBuilder(frameInfo) 549 .addFlag(FrameInfoFlags::RTAnimation) 550 .setVsync(vsync, vsync); 551 552 TreeInfo info(TreeInfo::MODE_RT_ONLY, *this); 553 prepareTree(info, frameInfo, systemTime(CLOCK_MONOTONIC), node); 554 if (info.out.canDrawThisFrame) { 555 draw(); 556 } 557} 558 559void CanvasContext::invokeFunctor(RenderThread& thread, Functor* functor) { 560 ATRACE_CALL(); 561 DrawGlInfo::Mode mode = DrawGlInfo::kModeProcessNoContext; 562 if (thread.eglManager().hasEglContext()) { 563 mode = DrawGlInfo::kModeProcess; 564 } 565 566 thread.renderState().invokeFunctor(functor, mode, nullptr); 567} 568 569void CanvasContext::markLayerInUse(RenderNode* node) { 570 if (mPrefetechedLayers.erase(node)) { 571 node->decStrong(nullptr); 572 } 573} 574 575static void destroyPrefetechedNode(RenderNode* node) { 576 ALOGW("Incorrectly called buildLayer on View: %s, destroying layer...", node->getName()); 577 node->destroyHardwareResources(); 578 node->decStrong(nullptr); 579} 580 581void CanvasContext::freePrefetechedLayers() { 582 if (mPrefetechedLayers.size()) { 583 std::for_each(mPrefetechedLayers.begin(), mPrefetechedLayers.end(), destroyPrefetechedNode); 584 mPrefetechedLayers.clear(); 585 } 586} 587 588void CanvasContext::buildLayer(RenderNode* node) { 589 ATRACE_CALL(); 590 if (!mEglManager.hasEglContext() || !mCanvas) { 591 return; 592 } 593 // buildLayer() will leave the tree in an unknown state, so we must stop drawing 594 stopDrawing(); 595 596 TreeInfo info(TreeInfo::MODE_FULL, *this); 597 info.damageAccumulator = &mDamageAccumulator; 598#if HWUI_NEW_OPS 599 info.layerUpdateQueue = &mLayerUpdateQueue; 600#else 601 info.renderer = mCanvas; 602#endif 603 info.runAnimations = false; 604 node->prepareTree(info); 605 SkRect ignore; 606 mDamageAccumulator.finish(&ignore); 607 // Tickle the GENERIC property on node to mark it as dirty for damaging 608 // purposes when the frame is actually drawn 609 node->setPropertyFieldsDirty(RenderNode::GENERIC); 610 611#if HWUI_NEW_OPS 612 // TODO: support buildLayer 613#else 614 mCanvas->markLayersAsBuildLayers(); 615 mCanvas->flushLayerUpdates(); 616#endif 617 618 node->incStrong(nullptr); 619 mPrefetechedLayers.insert(node); 620} 621 622bool CanvasContext::copyLayerInto(DeferredLayerUpdater* layer, SkBitmap* bitmap) { 623 layer->apply(); 624 return LayerRenderer::copyLayer(mRenderThread.renderState(), layer->backingLayer(), bitmap); 625} 626 627void CanvasContext::destroyHardwareResources() { 628 stopDrawing(); 629 if (mEglManager.hasEglContext()) { 630 freePrefetechedLayers(); 631 for (const sp<RenderNode>& node : mRenderNodes) { 632 node->destroyHardwareResources(); 633 } 634 Caches& caches = Caches::getInstance(); 635 // Make sure to release all the textures we were owning as there won't 636 // be another draw 637 caches.textureCache.resetMarkInUse(this); 638 mRenderThread.renderState().flush(Caches::FlushMode::Layers); 639 } 640} 641 642void CanvasContext::trimMemory(RenderThread& thread, int level) { 643 // No context means nothing to free 644 if (!thread.eglManager().hasEglContext()) return; 645 646 ATRACE_CALL(); 647 if (level >= TRIM_MEMORY_COMPLETE) { 648 thread.renderState().flush(Caches::FlushMode::Full); 649 thread.eglManager().destroy(); 650 } else if (level >= TRIM_MEMORY_UI_HIDDEN) { 651 thread.renderState().flush(Caches::FlushMode::Moderate); 652 } 653} 654 655void CanvasContext::runWithGlContext(RenderTask* task) { 656 LOG_ALWAYS_FATAL_IF(!mEglManager.hasEglContext(), 657 "GL context not initialized!"); 658 task->run(); 659} 660 661Layer* CanvasContext::createTextureLayer() { 662 requireSurface(); 663 return LayerRenderer::createTextureLayer(mRenderThread.renderState()); 664} 665 666void CanvasContext::setTextureAtlas(RenderThread& thread, 667 const sp<GraphicBuffer>& buffer, int64_t* map, size_t mapSize) { 668 thread.eglManager().setTextureAtlas(buffer, map, mapSize); 669} 670 671void CanvasContext::dumpFrames(int fd) { 672 FILE* file = fdopen(fd, "a"); 673 fprintf(file, "\n\n---PROFILEDATA---\n"); 674 for (size_t i = 0; i < static_cast<size_t>(FrameInfoIndex::NumIndexes); i++) { 675 fprintf(file, "%s", FrameInfoNames[i].c_str()); 676 fprintf(file, ","); 677 } 678 for (size_t i = 0; i < mFrames.size(); i++) { 679 FrameInfo& frame = mFrames[i]; 680 if (frame[FrameInfoIndex::SyncStart] == 0) { 681 continue; 682 } 683 fprintf(file, "\n"); 684 for (int i = 0; i < static_cast<int>(FrameInfoIndex::NumIndexes); i++) { 685 fprintf(file, "%" PRId64 ",", frame[i]); 686 } 687 } 688 fprintf(file, "\n---PROFILEDATA---\n\n"); 689 fflush(file); 690} 691 692void CanvasContext::resetFrameStats() { 693 mFrames.clear(); 694 mRenderThread.jankTracker().reset(); 695} 696 697void CanvasContext::serializeDisplayListTree() { 698#if ENABLE_RENDERNODE_SERIALIZATION 699 using namespace google::protobuf::io; 700 char package[128]; 701 // Check whether tracing is enabled for this process. 702 FILE * file = fopen("/proc/self/cmdline", "r"); 703 if (file) { 704 if (!fgets(package, 128, file)) { 705 ALOGE("Error reading cmdline: %s (%d)", strerror(errno), errno); 706 fclose(file); 707 return; 708 } 709 fclose(file); 710 } else { 711 ALOGE("Error opening /proc/self/cmdline: %s (%d)", strerror(errno), 712 errno); 713 return; 714 } 715 char path[1024]; 716 snprintf(path, 1024, "/data/data/%s/cache/rendertree_dump", package); 717 int fd = open(path, O_CREAT | O_WRONLY, S_IRWXU | S_IRGRP | S_IROTH); 718 if (fd == -1) { 719 ALOGD("Failed to open '%s'", path); 720 return; 721 } 722 proto::RenderNode tree; 723 // TODO: Streaming writes? 724 mRootRenderNode->copyTo(&tree); 725 std::string data = tree.SerializeAsString(); 726 write(fd, data.c_str(), data.length()); 727 close(fd); 728#endif 729} 730 731void CanvasContext::waitOnFences() { 732 if (mFrameFences.size()) { 733 ATRACE_CALL(); 734 for (auto& fence : mFrameFences) { 735 fence->getResult(); 736 } 737 mFrameFences.clear(); 738 } 739} 740 741class CanvasContext::FuncTaskProcessor : public TaskProcessor<bool> { 742public: 743 FuncTaskProcessor(Caches& caches) 744 : TaskProcessor<bool>(&caches.tasks) {} 745 746 virtual void onProcess(const sp<Task<bool> >& task) override { 747 FuncTask* t = static_cast<FuncTask*>(task.get()); 748 t->func(); 749 task->setResult(true); 750 } 751}; 752 753void CanvasContext::enqueueFrameWork(std::function<void()>&& func) { 754 if (!mFrameWorkProcessor.get()) { 755 mFrameWorkProcessor = new FuncTaskProcessor(Caches::getInstance()); 756 } 757 sp<FuncTask> task(new FuncTask()); 758 task->func = func; 759 mFrameWorkProcessor->add(task); 760} 761 762} /* namespace renderthread */ 763} /* namespace uirenderer */ 764} /* namespace android */ 765