CanvasContext.cpp revision 882d515cd54627f320269aa2d744f1c9f1a75c71
13473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi/* 23473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi * Copyright (C) 2014 The Android Open Source Project 33473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi * 43473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi * Licensed under the Apache License, Version 2.0 (the "License"); 53473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi * you may not use this file except in compliance with the License. 63473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi * You may obtain a copy of the License at 73473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi * 83473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi * http://www.apache.org/licenses/LICENSE-2.0 93473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi * 103473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi * Unless required by applicable law or agreed to in writing, software 113473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi * distributed under the License is distributed on an "AS IS" BASIS, 123473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 133473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi * See the License for the specific language governing permissions and 143473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi * limitations under the License. 153473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi */ 163473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi 173473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi#include <GpuMemoryTracker.h> 183473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi#include "CanvasContext.h" 193473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi 203473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi#include "AnimationContext.h" 213473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi#include "Caches.h" 223473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi#include "DeferredLayerUpdater.h" 233473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi#include "EglManager.h" 243473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi#include "LayerUpdateQueue.h" 253473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi#include "LayerRenderer.h" 263473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi#include "OpenGLRenderer.h" 273473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi#include "Properties.h" 283473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi#include "RenderThread.h" 293473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi#include "hwui/Canvas.h" 303473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi#include "renderstate/RenderState.h" 313473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi#include "renderstate/Stencil.h" 323473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi#include "protos/hwui.pb.h" 333473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi#include "utils/GLUtils.h" 343473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi#include "utils/TimeUtils.h" 353473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi 363473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi#include <cutils/properties.h> 373473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi#include <google/protobuf/io/zero_copy_stream_impl.h> 383473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi#include <private/hwui/DrawGlInfo.h> 393473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi#include <strings.h> 403473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi 413473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi#include <algorithm> 423473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi#include <fcntl.h> 433473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi#include <sys/stat.h> 443473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi 453473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi#include <cstdlib> 463473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi 473473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi#define TRIM_MEMORY_COMPLETE 80 483473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi#define TRIM_MEMORY_UI_HIDDEN 20 493473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi 503473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi#define ENABLE_RENDERNODE_SERIALIZATION false 513473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi 523473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi#define LOG_FRAMETIME_MMA 0 533473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi 543473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi#if LOG_FRAMETIME_MMA 553473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimistatic float sBenchMma = 0; 563473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimistatic int sFrameCount = 0; 573473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimistatic const float NANOS_PER_MILLIS_F = 1000000.0f; 583473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi#endif 593473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi 603473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aiminamespace android { 613473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aiminamespace uirenderer { 623473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aiminamespace renderthread { 633473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi 643473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi AimiCanvasContext::CanvasContext(RenderThread& thread, bool translucent, 653473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi RenderNode* rootRenderNode, IContextFactory* contextFactory) 663473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi : mRenderThread(thread) 673473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi , mEglManager(thread.eglManager()) 683473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi , mOpaque(!translucent) 693473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi , mAnimationContext(contextFactory->createAnimationContext(mRenderThread.timeLord())) 703473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi , mJankTracker(thread.mainDisplayInfo()) 713473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi , mProfiler(mFrames) 723473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi , mContentDrawBounds(0, 0, 0, 0) { 733473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi mRenderNodes.emplace_back(rootRenderNode); 743473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi mRenderThread.renderState().registerCanvasContext(this); 753473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi mProfiler.setDensity(mRenderThread.mainDisplayInfo().density); 763473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi} 773473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi 783473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi AimiCanvasContext::~CanvasContext() { 793473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi destroy(nullptr); 803473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi mRenderThread.renderState().unregisterCanvasContext(this); 813856b090cd04ba5dd4a59a12430ed724d5995909Steve Block} 823473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi 833473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimivoid CanvasContext::destroy(TreeObserver* observer) { 843473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi stopDrawing(); 853856b090cd04ba5dd4a59a12430ed724d5995909Steve Block setSurface(nullptr); 863473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi freePrefetchedLayers(observer); 873473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi destroyHardwareResources(observer); 883473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi mAnimationContext->destroy(); 893473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi#if !HWUI_NEW_OPS 903473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi if (mCanvas) { 913473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi delete mCanvas; 923473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi mCanvas = nullptr; 933473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi } 943473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi#endif 953473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi} 963473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi 973473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimivoid CanvasContext::setSurface(Surface* surface) { 983473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi ATRACE_CALL(); 993856b090cd04ba5dd4a59a12430ed724d5995909Steve Block 1003473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi mNativeSurface = surface; 1013473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi 1023473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi if (mEglSurface != EGL_NO_SURFACE) { 1033856b090cd04ba5dd4a59a12430ed724d5995909Steve Block mEglManager.destroySurface(mEglSurface); 1043473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi mEglSurface = EGL_NO_SURFACE; 1053473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi } 1063473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi 1073473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi if (surface) { 1083473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi mEglSurface = mEglManager.createSurface(surface); 1093473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi } 1103473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi 1113473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi mFrameNumber = -1; 1123473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi 1133473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi if (mEglSurface != EGL_NO_SURFACE) { 1143473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi const bool preserveBuffer = (mSwapBehavior != kSwap_discardBuffer); 1153473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi mBufferPreserved = mEglManager.setPreserveBuffer(mEglSurface, preserveBuffer); 1163473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi mHaveNewSurface = true; 1173473846f64f5b28e1cbeb70ef5867073fc93159eTakeshi Aimi mSwapHistory.clear(); 118 } else { 119 mRenderThread.removeFrameCallback(this); 120 } 121} 122 123void CanvasContext::setSwapBehavior(SwapBehavior swapBehavior) { 124 mSwapBehavior = swapBehavior; 125} 126 127void CanvasContext::initialize(Surface* surface) { 128 setSurface(surface); 129#if !HWUI_NEW_OPS 130 if (mCanvas) return; 131 mCanvas = new OpenGLRenderer(mRenderThread.renderState()); 132 mCanvas->initProperties(); 133#endif 134} 135 136void CanvasContext::updateSurface(Surface* surface) { 137 setSurface(surface); 138} 139 140bool CanvasContext::pauseSurface(Surface* surface) { 141 return mRenderThread.removeFrameCallback(this); 142} 143 144void CanvasContext::setStopped(bool stopped) { 145 if (mStopped != stopped) { 146 mStopped = stopped; 147 if (mStopped) { 148 mRenderThread.removeFrameCallback(this); 149 if (mEglManager.isCurrent(mEglSurface)) { 150 mEglManager.makeCurrent(EGL_NO_SURFACE); 151 } 152 } else if (mIsDirty && hasSurface()) { 153 mRenderThread.postFrameCallback(this); 154 } 155 } 156} 157 158// TODO: don't pass viewport size, it's automatic via EGL 159void CanvasContext::setup(int width, int height, float lightRadius, 160 uint8_t ambientShadowAlpha, uint8_t spotShadowAlpha) { 161#if HWUI_NEW_OPS 162 mLightGeometry.radius = lightRadius; 163 mLightInfo.ambientShadowAlpha = ambientShadowAlpha; 164 mLightInfo.spotShadowAlpha = spotShadowAlpha; 165#else 166 if (!mCanvas) return; 167 mCanvas->initLight(lightRadius, ambientShadowAlpha, spotShadowAlpha); 168#endif 169} 170 171void CanvasContext::setLightCenter(const Vector3& lightCenter) { 172#if HWUI_NEW_OPS 173 mLightGeometry.center = lightCenter; 174#else 175 if (!mCanvas) return; 176 mCanvas->setLightCenter(lightCenter); 177#endif 178} 179 180void CanvasContext::setOpaque(bool opaque) { 181 mOpaque = opaque; 182} 183 184bool CanvasContext::makeCurrent() { 185 if (mStopped) return false; 186 187 // TODO: Figure out why this workaround is needed, see b/13913604 188 // In the meantime this matches the behavior of GLRenderer, so it is not a regression 189 EGLint error = 0; 190 mHaveNewSurface |= mEglManager.makeCurrent(mEglSurface, &error); 191 if (error) { 192 setSurface(nullptr); 193 } 194 return !error; 195} 196 197static bool wasSkipped(FrameInfo* info) { 198 return info && ((*info)[FrameInfoIndex::Flags] & FrameInfoFlags::SkippedFrame); 199} 200 201bool CanvasContext::isSwapChainStuffed() { 202 static const auto SLOW_THRESHOLD = 6_ms; 203 204 if (mSwapHistory.size() != mSwapHistory.capacity()) { 205 // We want at least 3 frames of history before attempting to 206 // guess if the queue is stuffed 207 return false; 208 } 209 nsecs_t frameInterval = mRenderThread.timeLord().frameIntervalNanos(); 210 auto& swapA = mSwapHistory[0]; 211 212 // Was there a happy queue & dequeue time? If so, don't 213 // consider it stuffed 214 if (swapA.dequeueDuration < SLOW_THRESHOLD 215 && swapA.queueDuration < SLOW_THRESHOLD) { 216 return false; 217 } 218 219 for (size_t i = 1; i < mSwapHistory.size(); i++) { 220 auto& swapB = mSwapHistory[i]; 221 222 // If there's a multi-frameInterval gap we effectively already dropped a frame, 223 // so consider the queue healthy. 224 if (swapA.swapCompletedTime - swapB.swapCompletedTime > frameInterval * 3) { 225 return false; 226 } 227 228 // Was there a happy queue & dequeue time? If so, don't 229 // consider it stuffed 230 if (swapB.dequeueDuration < SLOW_THRESHOLD 231 && swapB.queueDuration < SLOW_THRESHOLD) { 232 return false; 233 } 234 235 swapA = swapB; 236 } 237 238 // All signs point to a stuffed swap chain 239 ATRACE_NAME("swap chain stuffed"); 240 return true; 241} 242 243void CanvasContext::prepareTree(TreeInfo& info, int64_t* uiFrameInfo, 244 int64_t syncQueued, RenderNode* target) { 245 mRenderThread.removeFrameCallback(this); 246 247 // If the previous frame was dropped we don't need to hold onto it, so 248 // just keep using the previous frame's structure instead 249 if (!wasSkipped(mCurrentFrameInfo)) { 250 mCurrentFrameInfo = &mFrames.next(); 251 } 252 mCurrentFrameInfo->importUiThreadInfo(uiFrameInfo); 253 mCurrentFrameInfo->set(FrameInfoIndex::SyncQueued) = syncQueued; 254 mCurrentFrameInfo->markSyncStart(); 255 256 info.damageAccumulator = &mDamageAccumulator; 257#if HWUI_NEW_OPS 258 info.layerUpdateQueue = &mLayerUpdateQueue; 259#else 260 info.renderer = mCanvas; 261#endif 262 263 mAnimationContext->startFrame(info.mode); 264 for (const sp<RenderNode>& node : mRenderNodes) { 265 // Only the primary target node will be drawn full - all other nodes would get drawn in 266 // real time mode. In case of a window, the primary node is the window content and the other 267 // node(s) are non client / filler nodes. 268 info.mode = (node.get() == target ? TreeInfo::MODE_FULL : TreeInfo::MODE_RT_ONLY); 269 node->prepareTree(info); 270 GL_CHECKPOINT(MODERATE); 271 } 272 mAnimationContext->runRemainingAnimations(info); 273 GL_CHECKPOINT(MODERATE); 274 275 freePrefetchedLayers(info.observer); 276 GL_CHECKPOINT(MODERATE); 277 278 mIsDirty = true; 279 280 if (CC_UNLIKELY(!mNativeSurface.get())) { 281 mCurrentFrameInfo->addFlag(FrameInfoFlags::SkippedFrame); 282 info.out.canDrawThisFrame = false; 283 return; 284 } 285 286 if (CC_LIKELY(mSwapHistory.size())) { 287 nsecs_t latestVsync = mRenderThread.timeLord().latestVsync(); 288 SwapHistory& lastSwap = mSwapHistory.back(); 289 nsecs_t vsyncDelta = std::abs(lastSwap.vsyncTime - latestVsync); 290 // The slight fudge-factor is to deal with cases where 291 // the vsync was estimated due to being slow handling the signal. 292 // See the logic in TimeLord#computeFrameTimeNanos or in 293 // Choreographer.java for details on when this happens 294 if (vsyncDelta < 2_ms) { 295 // Already drew for this vsync pulse, UI draw request missed 296 // the deadline for RT animations 297 info.out.canDrawThisFrame = false; 298 } else if (vsyncDelta >= mRenderThread.timeLord().frameIntervalNanos() * 3 299 || (latestVsync - mLastDropVsync) < 500_ms) { 300 // It's been several frame intervals, assume the buffer queue is fine 301 // or the last drop was too recent 302 info.out.canDrawThisFrame = true; 303 } else { 304 info.out.canDrawThisFrame = !isSwapChainStuffed(); 305 if (!info.out.canDrawThisFrame) { 306 // dropping frame 307 mLastDropVsync = mRenderThread.timeLord().latestVsync(); 308 } 309 } 310 } else { 311 info.out.canDrawThisFrame = true; 312 } 313 314 if (!info.out.canDrawThisFrame) { 315 mCurrentFrameInfo->addFlag(FrameInfoFlags::SkippedFrame); 316 } 317 318 if (info.out.hasAnimations || !info.out.canDrawThisFrame) { 319 if (!info.out.requiresUiRedraw) { 320 // If animationsNeedsRedraw is set don't bother posting for an RT anim 321 // as we will just end up fighting the UI thread. 322 mRenderThread.postFrameCallback(this); 323 } 324 } 325} 326 327void CanvasContext::stopDrawing() { 328 mRenderThread.removeFrameCallback(this); 329 mAnimationContext->detachAnimators(); 330} 331 332void CanvasContext::notifyFramePending() { 333 ATRACE_CALL(); 334 mRenderThread.pushBackFrameCallback(this); 335} 336 337void CanvasContext::draw() { 338#if !HWUI_NEW_OPS 339 LOG_ALWAYS_FATAL_IF(!mCanvas || mEglSurface == EGL_NO_SURFACE, 340 "drawRenderNode called on a context with no canvas or surface!"); 341#endif 342 343 SkRect dirty; 344 mDamageAccumulator.finish(&dirty); 345 346 // TODO: Re-enable after figuring out cause of b/22592975 347// if (dirty.isEmpty() && Properties::skipEmptyFrames) { 348// mCurrentFrameInfo->addFlag(FrameInfoFlags::SkippedFrame); 349// return; 350// } 351 352 mCurrentFrameInfo->markIssueDrawCommandsStart(); 353 354 Frame frame = mEglManager.beginFrame(mEglSurface); 355 356 if (frame.width() != mLastFrameWidth || frame.height() != mLastFrameHeight) { 357 // can't rely on prior content of window if viewport size changes 358 dirty.setEmpty(); 359 mLastFrameWidth = frame.width(); 360 mLastFrameHeight = frame.height(); 361 } else if (mHaveNewSurface || frame.bufferAge() == 0) { 362 // New surface needs a full draw 363 dirty.setEmpty(); 364 } else { 365 if (!dirty.isEmpty() && !dirty.intersect(0, 0, frame.width(), frame.height())) { 366 ALOGW("Dirty " RECT_STRING " doesn't intersect with 0 0 %d %d ?", 367 SK_RECT_ARGS(dirty), frame.width(), frame.height()); 368 dirty.setEmpty(); 369 } 370 profiler().unionDirty(&dirty); 371 } 372 373 if (dirty.isEmpty()) { 374 dirty.set(0, 0, frame.width(), frame.height()); 375 } 376 377 // At this point dirty is the area of the screen to update. However, 378 // the area of the frame we need to repaint is potentially different, so 379 // stash the screen area for later 380 SkRect screenDirty(dirty); 381 382 // If the buffer age is 0 we do a full-screen repaint (handled above) 383 // If the buffer age is 1 the buffer contents are the same as they were 384 // last frame so there's nothing to union() against 385 // Therefore we only care about the > 1 case. 386 if (frame.bufferAge() > 1) { 387 if (frame.bufferAge() > (int) mSwapHistory.size()) { 388 // We don't have enough history to handle this old of a buffer 389 // Just do a full-draw 390 dirty.set(0, 0, frame.width(), frame.height()); 391 } else { 392 // At this point we haven't yet added the latest frame 393 // to the damage history (happens below) 394 // So we need to damage 395 for (int i = mSwapHistory.size() - 1; 396 i > ((int) mSwapHistory.size()) - frame.bufferAge(); i--) { 397 dirty.join(mSwapHistory[i].damage); 398 } 399 } 400 } 401 402 mEglManager.damageFrame(frame, dirty); 403 404#if HWUI_NEW_OPS 405 auto& caches = Caches::getInstance(); 406 FrameBuilder frameBuilder(dirty, frame.width(), frame.height(), mLightGeometry, caches); 407 408 frameBuilder.deferLayers(mLayerUpdateQueue); 409 mLayerUpdateQueue.clear(); 410 411 frameBuilder.deferRenderNodeScene(mRenderNodes, mContentDrawBounds); 412 413 BakedOpRenderer renderer(caches, mRenderThread.renderState(), 414 mOpaque, mLightInfo); 415 frameBuilder.replayBakedOps<BakedOpDispatcher>(renderer); 416 profiler().draw(&renderer); 417 bool drew = renderer.didDraw(); 418 419 // post frame cleanup 420 caches.clearGarbage(); 421 caches.pathCache.trim(); 422 caches.tessellationCache.trim(); 423 424#if DEBUG_MEMORY_USAGE 425 mCaches.dumpMemoryUsage(); 426#else 427 if (CC_UNLIKELY(Properties::debugLevel & kDebugMemory)) { 428 caches.dumpMemoryUsage(); 429 } 430#endif 431 432#else 433 mCanvas->prepareDirty(frame.width(), frame.height(), 434 dirty.fLeft, dirty.fTop, dirty.fRight, dirty.fBottom, mOpaque); 435 436 Rect outBounds; 437 // It there are multiple render nodes, they are laid out as follows: 438 // #0 - backdrop (content + caption) 439 // #1 - content (positioned at (0,0) and clipped to - its bounds mContentDrawBounds) 440 // #2 - additional overlay nodes 441 // Usually the backdrop cannot be seen since it will be entirely covered by the content. While 442 // resizing however it might become partially visible. The following render loop will crop the 443 // backdrop against the content and draw the remaining part of it. It will then draw the content 444 // cropped to the backdrop (since that indicates a shrinking of the window). 445 // 446 // Additional nodes will be drawn on top with no particular clipping semantics. 447 448 // The bounds of the backdrop against which the content should be clipped. 449 Rect backdropBounds = mContentDrawBounds; 450 // Usually the contents bounds should be mContentDrawBounds - however - we will 451 // move it towards the fixed edge to give it a more stable appearance (for the moment). 452 Rect contentBounds; 453 // If there is no content bounds we ignore the layering as stated above and start with 2. 454 int layer = (mContentDrawBounds.isEmpty() || mRenderNodes.size() == 1) ? 2 : 0; 455 // Draw all render nodes. Note that 456 for (const sp<RenderNode>& node : mRenderNodes) { 457 if (layer == 0) { // Backdrop. 458 // Draw the backdrop clipped to the inverse content bounds, but assume that the content 459 // was moved to the upper left corner. 460 const RenderProperties& properties = node->properties(); 461 Rect targetBounds(properties.getLeft(), properties.getTop(), 462 properties.getRight(), properties.getBottom()); 463 // Move the content bounds towards the fixed corner of the backdrop. 464 const int x = targetBounds.left; 465 const int y = targetBounds.top; 466 contentBounds.set(x, y, x + mContentDrawBounds.getWidth(), 467 y + mContentDrawBounds.getHeight()); 468 // Remember the intersection of the target bounds and the intersection bounds against 469 // which we have to crop the content. 470 backdropBounds.set(x, y, x + backdropBounds.getWidth(), y + backdropBounds.getHeight()); 471 backdropBounds.doIntersect(targetBounds); 472 // Check if we have to draw something on the left side ... 473 if (targetBounds.left < contentBounds.left) { 474 mCanvas->save(SaveFlags::Clip); 475 if (mCanvas->clipRect(targetBounds.left, targetBounds.top, 476 contentBounds.left, targetBounds.bottom, 477 SkRegion::kIntersect_Op)) { 478 mCanvas->drawRenderNode(node.get(), outBounds); 479 } 480 // Reduce the target area by the area we have just painted. 481 targetBounds.left = std::min(contentBounds.left, targetBounds.right); 482 mCanvas->restore(); 483 } 484 // ... or on the right side ... 485 if (targetBounds.right > contentBounds.right && 486 !targetBounds.isEmpty()) { 487 mCanvas->save(SaveFlags::Clip); 488 if (mCanvas->clipRect(contentBounds.right, targetBounds.top, 489 targetBounds.right, targetBounds.bottom, 490 SkRegion::kIntersect_Op)) { 491 mCanvas->drawRenderNode(node.get(), outBounds); 492 } 493 // Reduce the target area by the area we have just painted. 494 targetBounds.right = std::max(targetBounds.left, contentBounds.right); 495 mCanvas->restore(); 496 } 497 // ... or at the top ... 498 if (targetBounds.top < contentBounds.top && 499 !targetBounds.isEmpty()) { 500 mCanvas->save(SaveFlags::Clip); 501 if (mCanvas->clipRect(targetBounds.left, targetBounds.top, targetBounds.right, 502 contentBounds.top, 503 SkRegion::kIntersect_Op)) { 504 mCanvas->drawRenderNode(node.get(), outBounds); 505 } 506 // Reduce the target area by the area we have just painted. 507 targetBounds.top = std::min(contentBounds.top, targetBounds.bottom); 508 mCanvas->restore(); 509 } 510 // ... or at the bottom. 511 if (targetBounds.bottom > contentBounds.bottom && 512 !targetBounds.isEmpty()) { 513 mCanvas->save(SaveFlags::Clip); 514 if (mCanvas->clipRect(targetBounds.left, contentBounds.bottom, targetBounds.right, 515 targetBounds.bottom, SkRegion::kIntersect_Op)) { 516 mCanvas->drawRenderNode(node.get(), outBounds); 517 } 518 mCanvas->restore(); 519 } 520 } else if (layer == 1) { // Content 521 // It gets cropped against the bounds of the backdrop to stay inside. 522 mCanvas->save(SaveFlags::MatrixClip); 523 524 // We shift and clip the content to match its final location in the window. 525 const float left = mContentDrawBounds.left; 526 const float top = mContentDrawBounds.top; 527 const float dx = backdropBounds.left - left; 528 const float dy = backdropBounds.top - top; 529 const float width = backdropBounds.getWidth(); 530 const float height = backdropBounds.getHeight(); 531 532 mCanvas->translate(dx, dy); 533 if (mCanvas->clipRect(left, top, left + width, top + height, SkRegion::kIntersect_Op)) { 534 mCanvas->drawRenderNode(node.get(), outBounds); 535 } 536 mCanvas->restore(); 537 } else { // draw the rest on top at will! 538 mCanvas->drawRenderNode(node.get(), outBounds); 539 } 540 layer++; 541 } 542 543 profiler().draw(mCanvas); 544 545 bool drew = mCanvas->finish(); 546#endif 547 548 waitOnFences(); 549 550 GL_CHECKPOINT(LOW); 551 552 // Even if we decided to cancel the frame, from the perspective of jank 553 // metrics the frame was swapped at this point 554 mCurrentFrameInfo->markSwapBuffers(); 555 mIsDirty = false; 556 557 if (drew || mEglManager.damageRequiresSwap()) { 558 if (CC_UNLIKELY(!mEglManager.swapBuffers(frame, screenDirty))) { 559 setSurface(nullptr); 560 } 561 SwapHistory& swap = mSwapHistory.next(); 562 swap.damage = screenDirty; 563 swap.swapCompletedTime = systemTime(CLOCK_MONOTONIC); 564 swap.vsyncTime = mRenderThread.timeLord().latestVsync(); 565 if (mNativeSurface.get()) { 566 int durationUs; 567 mNativeSurface->query(NATIVE_WINDOW_LAST_DEQUEUE_DURATION, &durationUs); 568 swap.dequeueDuration = us2ns(durationUs); 569 mNativeSurface->query(NATIVE_WINDOW_LAST_QUEUE_DURATION, &durationUs); 570 swap.queueDuration = us2ns(durationUs); 571 } else { 572 swap.dequeueDuration = 0; 573 swap.queueDuration = 0; 574 } 575 mCurrentFrameInfo->set(FrameInfoIndex::DequeueBufferDuration) 576 = swap.dequeueDuration; 577 mCurrentFrameInfo->set(FrameInfoIndex::QueueBufferDuration) 578 = swap.queueDuration; 579 mHaveNewSurface = false; 580 mFrameNumber = -1; 581 } 582 583 // TODO: Use a fence for real completion? 584 mCurrentFrameInfo->markFrameCompleted(); 585 586#if LOG_FRAMETIME_MMA 587 float thisFrame = mCurrentFrameInfo->duration( 588 FrameInfoIndex::IssueDrawCommandsStart, 589 FrameInfoIndex::FrameCompleted) / NANOS_PER_MILLIS_F; 590 if (sFrameCount) { 591 sBenchMma = ((9 * sBenchMma) + thisFrame) / 10; 592 } else { 593 sBenchMma = thisFrame; 594 } 595 if (++sFrameCount == 10) { 596 sFrameCount = 1; 597 ALOGD("Average frame time: %.4f", sBenchMma); 598 } 599#endif 600 601 mJankTracker.addFrame(*mCurrentFrameInfo); 602 mRenderThread.jankTracker().addFrame(*mCurrentFrameInfo); 603 if (CC_UNLIKELY(mFrameMetricsReporter.get() != nullptr)) { 604 mFrameMetricsReporter->reportFrameMetrics(mCurrentFrameInfo->data()); 605 } 606 607 GpuMemoryTracker::onFrameCompleted(); 608} 609 610// Called by choreographer to do an RT-driven animation 611void CanvasContext::doFrame() { 612#if HWUI_NEW_OPS 613 if (CC_UNLIKELY(mEglSurface == EGL_NO_SURFACE)) return; 614#else 615 if (CC_UNLIKELY(!mCanvas || mEglSurface == EGL_NO_SURFACE)) return; 616#endif 617 prepareAndDraw(nullptr); 618} 619 620void CanvasContext::prepareAndDraw(RenderNode* node) { 621 ATRACE_CALL(); 622 623 nsecs_t vsync = mRenderThread.timeLord().computeFrameTimeNanos(); 624 int64_t frameInfo[UI_THREAD_FRAME_INFO_SIZE]; 625 UiFrameInfoBuilder(frameInfo) 626 .addFlag(FrameInfoFlags::RTAnimation) 627 .setVsync(vsync, vsync); 628 629 TreeInfo info(TreeInfo::MODE_RT_ONLY, *this); 630 prepareTree(info, frameInfo, systemTime(CLOCK_MONOTONIC), node); 631 if (info.out.canDrawThisFrame) { 632 draw(); 633 } 634} 635 636void CanvasContext::invokeFunctor(RenderThread& thread, Functor* functor) { 637 ATRACE_CALL(); 638 DrawGlInfo::Mode mode = DrawGlInfo::kModeProcessNoContext; 639 if (thread.eglManager().hasEglContext()) { 640 mode = DrawGlInfo::kModeProcess; 641 } 642 643 thread.renderState().invokeFunctor(functor, mode, nullptr); 644} 645 646void CanvasContext::markLayerInUse(RenderNode* node) { 647 if (mPrefetchedLayers.erase(node)) { 648 node->decStrong(nullptr); 649 } 650} 651 652void CanvasContext::freePrefetchedLayers(TreeObserver* observer) { 653 if (mPrefetchedLayers.size()) { 654 for (auto& node : mPrefetchedLayers) { 655 ALOGW("Incorrectly called buildLayer on View: %s, destroying layer...", 656 node->getName()); 657 node->destroyHardwareResources(observer); 658 node->decStrong(observer); 659 } 660 mPrefetchedLayers.clear(); 661 } 662} 663 664void CanvasContext::buildLayer(RenderNode* node, TreeObserver* observer) { 665 ATRACE_CALL(); 666 if (!mEglManager.hasEglContext()) return; 667#if !HWUI_NEW_OPS 668 if (!mCanvas) return; 669#endif 670 671 // buildLayer() will leave the tree in an unknown state, so we must stop drawing 672 stopDrawing(); 673 674 TreeInfo info(TreeInfo::MODE_FULL, *this); 675 info.damageAccumulator = &mDamageAccumulator; 676 info.observer = observer; 677#if HWUI_NEW_OPS 678 info.layerUpdateQueue = &mLayerUpdateQueue; 679#else 680 info.renderer = mCanvas; 681#endif 682 info.runAnimations = false; 683 node->prepareTree(info); 684 SkRect ignore; 685 mDamageAccumulator.finish(&ignore); 686 // Tickle the GENERIC property on node to mark it as dirty for damaging 687 // purposes when the frame is actually drawn 688 node->setPropertyFieldsDirty(RenderNode::GENERIC); 689 690#if HWUI_NEW_OPS 691 static const std::vector< sp<RenderNode> > emptyNodeList; 692 auto& caches = Caches::getInstance(); 693 FrameBuilder frameBuilder(mLayerUpdateQueue, mLightGeometry, caches); 694 mLayerUpdateQueue.clear(); 695 BakedOpRenderer renderer(caches, mRenderThread.renderState(), 696 mOpaque, mLightInfo); 697 LOG_ALWAYS_FATAL_IF(renderer.didDraw(), "shouldn't draw in buildlayer case"); 698 frameBuilder.replayBakedOps<BakedOpDispatcher>(renderer); 699#else 700 mCanvas->markLayersAsBuildLayers(); 701 mCanvas->flushLayerUpdates(); 702#endif 703 704 node->incStrong(nullptr); 705 mPrefetchedLayers.insert(node); 706} 707 708bool CanvasContext::copyLayerInto(DeferredLayerUpdater* layer, SkBitmap* bitmap) { 709 layer->apply(); 710 return LayerRenderer::copyLayer(mRenderThread.renderState(), layer->backingLayer(), bitmap); 711} 712 713void CanvasContext::destroyHardwareResources(TreeObserver* observer) { 714 stopDrawing(); 715 if (mEglManager.hasEglContext()) { 716 freePrefetchedLayers(observer); 717 for (const sp<RenderNode>& node : mRenderNodes) { 718 node->destroyHardwareResources(observer); 719 } 720 Caches& caches = Caches::getInstance(); 721 // Make sure to release all the textures we were owning as there won't 722 // be another draw 723 caches.textureCache.resetMarkInUse(this); 724 mRenderThread.renderState().flush(Caches::FlushMode::Layers); 725 } 726} 727 728void CanvasContext::trimMemory(RenderThread& thread, int level) { 729 // No context means nothing to free 730 if (!thread.eglManager().hasEglContext()) return; 731 732 ATRACE_CALL(); 733 if (level >= TRIM_MEMORY_COMPLETE) { 734 thread.renderState().flush(Caches::FlushMode::Full); 735 thread.eglManager().destroy(); 736 } else if (level >= TRIM_MEMORY_UI_HIDDEN) { 737 thread.renderState().flush(Caches::FlushMode::Moderate); 738 } 739} 740 741void CanvasContext::runWithGlContext(RenderTask* task) { 742 LOG_ALWAYS_FATAL_IF(!mEglManager.hasEglContext(), 743 "GL context not initialized!"); 744 task->run(); 745} 746 747Layer* CanvasContext::createTextureLayer() { 748 mEglManager.initialize(); 749 return LayerRenderer::createTextureLayer(mRenderThread.renderState()); 750} 751 752void CanvasContext::setTextureAtlas(RenderThread& thread, 753 const sp<GraphicBuffer>& buffer, int64_t* map, size_t mapSize) { 754 thread.eglManager().setTextureAtlas(buffer, map, mapSize); 755} 756 757void CanvasContext::dumpFrames(int fd) { 758 FILE* file = fdopen(fd, "a"); 759 fprintf(file, "\n\n---PROFILEDATA---\n"); 760 for (size_t i = 0; i < static_cast<size_t>(FrameInfoIndex::NumIndexes); i++) { 761 fprintf(file, "%s", FrameInfoNames[i].c_str()); 762 fprintf(file, ","); 763 } 764 for (size_t i = 0; i < mFrames.size(); i++) { 765 FrameInfo& frame = mFrames[i]; 766 if (frame[FrameInfoIndex::SyncStart] == 0) { 767 continue; 768 } 769 fprintf(file, "\n"); 770 for (int i = 0; i < static_cast<int>(FrameInfoIndex::NumIndexes); i++) { 771 fprintf(file, "%" PRId64 ",", frame[i]); 772 } 773 } 774 fprintf(file, "\n---PROFILEDATA---\n\n"); 775 fflush(file); 776} 777 778void CanvasContext::resetFrameStats() { 779 mFrames.clear(); 780 mRenderThread.jankTracker().reset(); 781} 782 783void CanvasContext::serializeDisplayListTree() { 784#if ENABLE_RENDERNODE_SERIALIZATION 785 using namespace google::protobuf::io; 786 char package[128]; 787 // Check whether tracing is enabled for this process. 788 FILE * file = fopen("/proc/self/cmdline", "r"); 789 if (file) { 790 if (!fgets(package, 128, file)) { 791 ALOGE("Error reading cmdline: %s (%d)", strerror(errno), errno); 792 fclose(file); 793 return; 794 } 795 fclose(file); 796 } else { 797 ALOGE("Error opening /proc/self/cmdline: %s (%d)", strerror(errno), 798 errno); 799 return; 800 } 801 char path[1024]; 802 snprintf(path, 1024, "/data/data/%s/cache/rendertree_dump", package); 803 int fd = open(path, O_CREAT | O_WRONLY, S_IRWXU | S_IRGRP | S_IROTH); 804 if (fd == -1) { 805 ALOGD("Failed to open '%s'", path); 806 return; 807 } 808 proto::RenderNode tree; 809 // TODO: Streaming writes? 810 mRootRenderNode->copyTo(&tree); 811 std::string data = tree.SerializeAsString(); 812 write(fd, data.c_str(), data.length()); 813 close(fd); 814#endif 815} 816 817void CanvasContext::waitOnFences() { 818 if (mFrameFences.size()) { 819 ATRACE_CALL(); 820 for (auto& fence : mFrameFences) { 821 fence->getResult(); 822 } 823 mFrameFences.clear(); 824 } 825} 826 827class CanvasContext::FuncTaskProcessor : public TaskProcessor<bool> { 828public: 829 FuncTaskProcessor(Caches& caches) 830 : TaskProcessor<bool>(&caches.tasks) {} 831 832 virtual void onProcess(const sp<Task<bool> >& task) override { 833 FuncTask* t = static_cast<FuncTask*>(task.get()); 834 t->func(); 835 task->setResult(true); 836 } 837}; 838 839void CanvasContext::enqueueFrameWork(std::function<void()>&& func) { 840 if (!mFrameWorkProcessor.get()) { 841 mFrameWorkProcessor = new FuncTaskProcessor(Caches::getInstance()); 842 } 843 sp<FuncTask> task(new FuncTask()); 844 task->func = func; 845 mFrameFences.push_back(task); 846 mFrameWorkProcessor->add(task); 847} 848 849int64_t CanvasContext::getFrameNumber() { 850 // mFrameNumber is reset to -1 when the surface changes or we swap buffers 851 if (mFrameNumber == -1 && mNativeSurface.get()) { 852 mFrameNumber = static_cast<int64_t>(mNativeSurface->getNextFrameNumber()); 853 } 854 return mFrameNumber; 855} 856 857} /* namespace renderthread */ 858} /* namespace uirenderer */ 859} /* namespace android */ 860