CanvasContext.cpp revision dcbc0e9e25bf99600d487f3c6f5e26487545cd9c
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 "Properties.h"
26#include "Readback.h"
27#include "RenderThread.h"
28#include "hwui/Canvas.h"
29#include "renderstate/RenderState.h"
30#include "renderstate/Stencil.h"
31#include "protos/hwui.pb.h"
32#include "OpenGLPipeline.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::create(RenderThread& thread,
65        bool translucent, RenderNode* rootRenderNode, IContextFactory* contextFactory) {
66
67    auto renderType = Properties::getRenderPipelineType();
68
69    switch (renderType) {
70        case RenderPipelineType::OpenGL:
71            return new CanvasContext(thread, translucent, rootRenderNode, contextFactory,
72                    std::make_unique<OpenGLPipeline>(thread));
73        case RenderPipelineType::SkiaGL:
74            //TODO: implement SKIA GL
75            LOG_ALWAYS_FATAL("skiaGL canvas type not implemented.");
76            break;
77        case RenderPipelineType::SkiaVulkan:
78            //TODO: implement Vulkan
79            LOG_ALWAYS_FATAL("Vulkan canvas type not implemented.");
80            break;
81        default:
82            LOG_ALWAYS_FATAL("canvas context type %d not supported", (int32_t) renderType);
83            break;
84    }
85    return nullptr;
86}
87
88CanvasContext::CanvasContext(RenderThread& thread, bool translucent,
89        RenderNode* rootRenderNode, IContextFactory* contextFactory,
90        std::unique_ptr<IRenderPipeline> renderPipeline)
91        : mRenderThread(thread)
92        , mOpaque(!translucent)
93        , mAnimationContext(contextFactory->createAnimationContext(mRenderThread.timeLord()))
94        , mJankTracker(thread.mainDisplayInfo())
95        , mProfiler(mFrames)
96        , mContentDrawBounds(0, 0, 0, 0)
97        , mRenderPipeline(std::move(renderPipeline)) {
98    mRenderNodes.emplace_back(rootRenderNode);
99    mRenderThread.renderState().registerCanvasContext(this);
100    mProfiler.setDensity(mRenderThread.mainDisplayInfo().density);
101}
102
103CanvasContext::~CanvasContext() {
104    destroy(nullptr);
105    mRenderThread.renderState().unregisterCanvasContext(this);
106}
107
108void CanvasContext::destroy(TreeObserver* observer) {
109    stopDrawing();
110    setSurface(nullptr);
111    freePrefetchedLayers(observer);
112    destroyHardwareResources(observer);
113    mAnimationContext->destroy();
114}
115
116void CanvasContext::setSurface(Surface* surface) {
117    ATRACE_CALL();
118
119    mNativeSurface = surface;
120
121    bool hasSurface = mRenderPipeline->setSurface(surface, mSwapBehavior);
122
123    mFrameNumber = -1;
124
125    if (hasSurface) {
126         mHaveNewSurface = true;
127         mSwapHistory.clear();
128    } else {
129         mRenderThread.removeFrameCallback(this);
130    }
131}
132
133void CanvasContext::setSwapBehavior(SwapBehavior swapBehavior) {
134    mSwapBehavior = swapBehavior;
135}
136
137void CanvasContext::initialize(Surface* surface) {
138    setSurface(surface);
139}
140
141void CanvasContext::updateSurface(Surface* surface) {
142    setSurface(surface);
143}
144
145bool CanvasContext::pauseSurface(Surface* surface) {
146    return mRenderThread.removeFrameCallback(this);
147}
148
149void CanvasContext::setStopped(bool stopped) {
150    if (mStopped != stopped) {
151        mStopped = stopped;
152        if (mStopped) {
153            mRenderThread.removeFrameCallback(this);
154            mRenderPipeline->onStop();
155        } else if (mIsDirty && hasSurface()) {
156            mRenderThread.postFrameCallback(this);
157        }
158    }
159}
160
161void CanvasContext::setup(float lightRadius,
162        uint8_t ambientShadowAlpha, uint8_t spotShadowAlpha) {
163    mLightGeometry.radius = lightRadius;
164    mLightInfo.ambientShadowAlpha = ambientShadowAlpha;
165    mLightInfo.spotShadowAlpha = spotShadowAlpha;
166}
167
168void CanvasContext::setLightCenter(const Vector3& lightCenter) {
169    mLightGeometry.center = lightCenter;
170}
171
172void CanvasContext::setOpaque(bool opaque) {
173    mOpaque = opaque;
174}
175
176bool CanvasContext::makeCurrent() {
177    if (mStopped) return false;
178
179    auto result = mRenderPipeline->makeCurrent();
180    switch (result) {
181        case MakeCurrentResult::AlreadyCurrent:
182            return true;
183        case MakeCurrentResult::Failed:
184            mHaveNewSurface = true;
185            setSurface(nullptr);
186            return false;
187        case MakeCurrentResult::Succeeded:
188            mHaveNewSurface = true;
189            return true;
190        default:
191            LOG_ALWAYS_FATAL("unexpected result %d from IRenderPipeline::makeCurrent",
192                    (int32_t) result);
193    }
194
195    return true;
196}
197
198static bool wasSkipped(FrameInfo* info) {
199    return info && ((*info)[FrameInfoIndex::Flags] & FrameInfoFlags::SkippedFrame);
200}
201
202bool CanvasContext::isSwapChainStuffed() {
203    static const auto SLOW_THRESHOLD = 6_ms;
204
205    if (mSwapHistory.size() != mSwapHistory.capacity()) {
206        // We want at least 3 frames of history before attempting to
207        // guess if the queue is stuffed
208        return false;
209    }
210    nsecs_t frameInterval = mRenderThread.timeLord().frameIntervalNanos();
211    auto& swapA = mSwapHistory[0];
212
213    // Was there a happy queue & dequeue time? If so, don't
214    // consider it stuffed
215    if (swapA.dequeueDuration < SLOW_THRESHOLD
216            && swapA.queueDuration < SLOW_THRESHOLD) {
217        return false;
218    }
219
220    for (size_t i = 1; i < mSwapHistory.size(); i++) {
221        auto& swapB = mSwapHistory[i];
222
223        // If there's a multi-frameInterval gap we effectively already dropped a frame,
224        // so consider the queue healthy.
225        if (swapA.swapCompletedTime - swapB.swapCompletedTime > frameInterval * 3) {
226            return false;
227        }
228
229        // Was there a happy queue & dequeue time? If so, don't
230        // consider it stuffed
231        if (swapB.dequeueDuration < SLOW_THRESHOLD
232                && swapB.queueDuration < SLOW_THRESHOLD) {
233            return false;
234        }
235
236        swapA = swapB;
237    }
238
239    // All signs point to a stuffed swap chain
240    ATRACE_NAME("swap chain stuffed");
241    return true;
242}
243
244void CanvasContext::prepareTree(TreeInfo& info, int64_t* uiFrameInfo,
245        int64_t syncQueued, RenderNode* target) {
246    mRenderThread.removeFrameCallback(this);
247
248    // If the previous frame was dropped we don't need to hold onto it, so
249    // just keep using the previous frame's structure instead
250    if (!wasSkipped(mCurrentFrameInfo)) {
251        mCurrentFrameInfo = &mFrames.next();
252    }
253    mCurrentFrameInfo->importUiThreadInfo(uiFrameInfo);
254    mCurrentFrameInfo->set(FrameInfoIndex::SyncQueued) = syncQueued;
255    mCurrentFrameInfo->markSyncStart();
256
257    info.damageAccumulator = &mDamageAccumulator;
258    info.layerUpdateQueue = &mLayerUpdateQueue;
259
260    mAnimationContext->startFrame(info.mode);
261    for (const sp<RenderNode>& node : mRenderNodes) {
262        // Only the primary target node will be drawn full - all other nodes would get drawn in
263        // real time mode. In case of a window, the primary node is the window content and the other
264        // node(s) are non client / filler nodes.
265        info.mode = (node.get() == target ? TreeInfo::MODE_FULL : TreeInfo::MODE_RT_ONLY);
266        node->prepareTree(info);
267        GL_CHECKPOINT(MODERATE);
268    }
269    mAnimationContext->runRemainingAnimations(info);
270    GL_CHECKPOINT(MODERATE);
271
272    freePrefetchedLayers(info.observer);
273    GL_CHECKPOINT(MODERATE);
274
275    mIsDirty = true;
276
277    if (CC_UNLIKELY(!mNativeSurface.get())) {
278        mCurrentFrameInfo->addFlag(FrameInfoFlags::SkippedFrame);
279        info.out.canDrawThisFrame = false;
280        return;
281    }
282
283    if (CC_LIKELY(mSwapHistory.size() && !Properties::forceDrawFrame)) {
284        nsecs_t latestVsync = mRenderThread.timeLord().latestVsync();
285        SwapHistory& lastSwap = mSwapHistory.back();
286        nsecs_t vsyncDelta = std::abs(lastSwap.vsyncTime - latestVsync);
287        // The slight fudge-factor is to deal with cases where
288        // the vsync was estimated due to being slow handling the signal.
289        // See the logic in TimeLord#computeFrameTimeNanos or in
290        // Choreographer.java for details on when this happens
291        if (vsyncDelta < 2_ms) {
292            // Already drew for this vsync pulse, UI draw request missed
293            // the deadline for RT animations
294            info.out.canDrawThisFrame = false;
295        } else if (vsyncDelta >= mRenderThread.timeLord().frameIntervalNanos() * 3
296                || (latestVsync - mLastDropVsync) < 500_ms) {
297            // It's been several frame intervals, assume the buffer queue is fine
298            // or the last drop was too recent
299            info.out.canDrawThisFrame = true;
300        } else {
301            info.out.canDrawThisFrame = !isSwapChainStuffed();
302            if (!info.out.canDrawThisFrame) {
303                // dropping frame
304                mLastDropVsync = mRenderThread.timeLord().latestVsync();
305            }
306        }
307    } else {
308        info.out.canDrawThisFrame = true;
309    }
310
311    if (!info.out.canDrawThisFrame) {
312        mCurrentFrameInfo->addFlag(FrameInfoFlags::SkippedFrame);
313    }
314
315    if (info.out.hasAnimations || !info.out.canDrawThisFrame) {
316        if (!info.out.requiresUiRedraw) {
317            // If animationsNeedsRedraw is set don't bother posting for an RT anim
318            // as we will just end up fighting the UI thread.
319            mRenderThread.postFrameCallback(this);
320        }
321    }
322}
323
324void CanvasContext::stopDrawing() {
325    mRenderThread.removeFrameCallback(this);
326    mAnimationContext->pauseAnimators();
327}
328
329void CanvasContext::notifyFramePending() {
330    ATRACE_CALL();
331    mRenderThread.pushBackFrameCallback(this);
332}
333
334void CanvasContext::draw() {
335    SkRect dirty;
336    mDamageAccumulator.finish(&dirty);
337
338    // TODO: Re-enable after figuring out cause of b/22592975
339//    if (dirty.isEmpty() && Properties::skipEmptyFrames) {
340//        mCurrentFrameInfo->addFlag(FrameInfoFlags::SkippedFrame);
341//        return;
342//    }
343
344    mCurrentFrameInfo->markIssueDrawCommandsStart();
345
346    Frame frame = mRenderPipeline->getFrame();
347
348    SkRect windowDirty = computeDirtyRect(frame, &dirty);
349
350    bool drew = mRenderPipeline->draw(frame, windowDirty, dirty, mLightGeometry, &mLayerUpdateQueue,
351            mContentDrawBounds, mOpaque, mLightInfo, mRenderNodes, &(profiler()));
352
353    waitOnFences();
354
355    bool requireSwap = false;
356    bool didSwap = mRenderPipeline->swapBuffers(frame, drew, windowDirty, mCurrentFrameInfo,
357            &requireSwap);
358
359    mIsDirty = false;
360
361    if (requireSwap) {
362        if (!didSwap) { //some error happened
363            setSurface(nullptr);
364        }
365        SwapHistory& swap = mSwapHistory.next();
366        swap.damage = windowDirty;
367        swap.swapCompletedTime = systemTime(CLOCK_MONOTONIC);
368        swap.vsyncTime = mRenderThread.timeLord().latestVsync();
369        if (mNativeSurface.get()) {
370            int durationUs;
371            mNativeSurface->query(NATIVE_WINDOW_LAST_DEQUEUE_DURATION, &durationUs);
372            swap.dequeueDuration = us2ns(durationUs);
373            mNativeSurface->query(NATIVE_WINDOW_LAST_QUEUE_DURATION, &durationUs);
374            swap.queueDuration = us2ns(durationUs);
375        } else {
376            swap.dequeueDuration = 0;
377            swap.queueDuration = 0;
378        }
379        mCurrentFrameInfo->set(FrameInfoIndex::DequeueBufferDuration)
380                = swap.dequeueDuration;
381        mCurrentFrameInfo->set(FrameInfoIndex::QueueBufferDuration)
382                = swap.queueDuration;
383        mHaveNewSurface = false;
384        mFrameNumber = -1;
385    } else {
386        mCurrentFrameInfo->set(FrameInfoIndex::DequeueBufferDuration) = 0;
387        mCurrentFrameInfo->set(FrameInfoIndex::QueueBufferDuration) = 0;
388    }
389
390    // TODO: Use a fence for real completion?
391    mCurrentFrameInfo->markFrameCompleted();
392
393#if LOG_FRAMETIME_MMA
394    float thisFrame = mCurrentFrameInfo->duration(
395            FrameInfoIndex::IssueDrawCommandsStart,
396            FrameInfoIndex::FrameCompleted) / NANOS_PER_MILLIS_F;
397    if (sFrameCount) {
398        sBenchMma = ((9 * sBenchMma) + thisFrame) / 10;
399    } else {
400        sBenchMma = thisFrame;
401    }
402    if (++sFrameCount == 10) {
403        sFrameCount = 1;
404        ALOGD("Average frame time: %.4f", sBenchMma);
405    }
406#endif
407
408    mJankTracker.addFrame(*mCurrentFrameInfo);
409    mRenderThread.jankTracker().addFrame(*mCurrentFrameInfo);
410    if (CC_UNLIKELY(mFrameMetricsReporter.get() != nullptr)) {
411        mFrameMetricsReporter->reportFrameMetrics(mCurrentFrameInfo->data());
412    }
413
414    GpuMemoryTracker::onFrameCompleted();
415#ifdef BUGREPORT_FONT_CACHE_USAGE
416    Caches& caches = Caches::getInstance();
417    caches.fontRenderer.getFontRenderer().historyTracker().frameCompleted();
418#endif
419
420}
421
422// Called by choreographer to do an RT-driven animation
423void CanvasContext::doFrame() {
424    if (!mRenderPipeline->isSurfaceReady()) return;
425    prepareAndDraw(nullptr);
426}
427
428void CanvasContext::prepareAndDraw(RenderNode* node) {
429    ATRACE_CALL();
430
431    nsecs_t vsync = mRenderThread.timeLord().computeFrameTimeNanos();
432    int64_t frameInfo[UI_THREAD_FRAME_INFO_SIZE];
433    UiFrameInfoBuilder(frameInfo)
434        .addFlag(FrameInfoFlags::RTAnimation)
435        .setVsync(vsync, vsync);
436
437    TreeInfo info(TreeInfo::MODE_RT_ONLY, *this);
438    prepareTree(info, frameInfo, systemTime(CLOCK_MONOTONIC), node);
439    if (info.out.canDrawThisFrame) {
440        draw();
441    } else {
442        // wait on fences so tasks don't overlap next frame
443        waitOnFences();
444    }
445}
446
447void CanvasContext::invokeFunctor(RenderThread& thread, Functor* functor) {
448    ATRACE_CALL();
449    DrawGlInfo::Mode mode = DrawGlInfo::kModeProcessNoContext;
450    if (thread.eglManager().hasEglContext()) {
451        mode = DrawGlInfo::kModeProcess;
452    }
453
454    thread.renderState().invokeFunctor(functor, mode, nullptr);
455}
456
457void CanvasContext::markLayerInUse(RenderNode* node) {
458    if (mPrefetchedLayers.erase(node)) {
459        node->decStrong(nullptr);
460    }
461}
462
463void CanvasContext::freePrefetchedLayers(TreeObserver* observer) {
464    if (mPrefetchedLayers.size()) {
465        for (auto& node : mPrefetchedLayers) {
466            ALOGW("Incorrectly called buildLayer on View: %s, destroying layer...",
467                    node->getName());
468            node->destroyHardwareResources(observer);
469            node->decStrong(observer);
470        }
471        mPrefetchedLayers.clear();
472    }
473}
474
475void CanvasContext::buildLayer(RenderNode* node, TreeObserver* observer) {
476    ATRACE_CALL();
477    if (!mRenderPipeline->isContextReady()) return;
478
479    // buildLayer() will leave the tree in an unknown state, so we must stop drawing
480    stopDrawing();
481
482    TreeInfo info(TreeInfo::MODE_FULL, *this);
483    info.damageAccumulator = &mDamageAccumulator;
484    info.observer = observer;
485    info.layerUpdateQueue = &mLayerUpdateQueue;
486    info.runAnimations = false;
487    node->prepareTree(info);
488    SkRect ignore;
489    mDamageAccumulator.finish(&ignore);
490    // Tickle the GENERIC property on node to mark it as dirty for damaging
491    // purposes when the frame is actually drawn
492    node->setPropertyFieldsDirty(RenderNode::GENERIC);
493
494    mRenderPipeline->renderLayers(mLightGeometry, &mLayerUpdateQueue, mOpaque, mLightInfo);
495
496    node->incStrong(nullptr);
497    mPrefetchedLayers.insert(node);
498}
499
500bool CanvasContext::copyLayerInto(DeferredLayerUpdater* layer, SkBitmap* bitmap) {
501    return mRenderPipeline->copyLayerInto(layer, bitmap);
502}
503
504void CanvasContext::destroyHardwareResources(TreeObserver* observer) {
505    stopDrawing();
506    if (mRenderPipeline->isContextReady()) {
507        freePrefetchedLayers(observer);
508        for (const sp<RenderNode>& node : mRenderNodes) {
509            node->destroyHardwareResources(observer);
510        }
511        Caches& caches = Caches::getInstance();
512        // Make sure to release all the textures we were owning as there won't
513        // be another draw
514        caches.textureCache.resetMarkInUse(this);
515        mRenderPipeline->onDestroyHardwareResources();
516    }
517}
518
519void CanvasContext::trimMemory(RenderThread& thread, int level) {
520    // No context means nothing to free
521    if (!thread.eglManager().hasEglContext()) return;
522
523    ATRACE_CALL();
524    if (level >= TRIM_MEMORY_COMPLETE) {
525        thread.renderState().flush(Caches::FlushMode::Full);
526        thread.eglManager().destroy();
527    } else if (level >= TRIM_MEMORY_UI_HIDDEN) {
528        thread.renderState().flush(Caches::FlushMode::Moderate);
529    }
530}
531
532DeferredLayerUpdater* CanvasContext::createTextureLayer() {
533    return mRenderPipeline->createTextureLayer();
534}
535
536void CanvasContext::setTextureAtlas(RenderThread& thread,
537        const sp<GraphicBuffer>& buffer, int64_t* map, size_t mapSize) {
538    thread.eglManager().setTextureAtlas(buffer, map, mapSize);
539}
540
541void CanvasContext::dumpFrames(int fd) {
542    FILE* file = fdopen(fd, "a");
543    fprintf(file, "\n\n---PROFILEDATA---\n");
544    for (size_t i = 0; i < static_cast<size_t>(FrameInfoIndex::NumIndexes); i++) {
545        fprintf(file, "%s", FrameInfoNames[i].c_str());
546        fprintf(file, ",");
547    }
548    for (size_t i = 0; i < mFrames.size(); i++) {
549        FrameInfo& frame = mFrames[i];
550        if (frame[FrameInfoIndex::SyncStart] == 0) {
551            continue;
552        }
553        fprintf(file, "\n");
554        for (int i = 0; i < static_cast<int>(FrameInfoIndex::NumIndexes); i++) {
555            fprintf(file, "%" PRId64 ",", frame[i]);
556        }
557    }
558    fprintf(file, "\n---PROFILEDATA---\n\n");
559    fflush(file);
560}
561
562void CanvasContext::resetFrameStats() {
563    mFrames.clear();
564    mRenderThread.jankTracker().reset();
565}
566
567void CanvasContext::serializeDisplayListTree() {
568#if ENABLE_RENDERNODE_SERIALIZATION
569    using namespace google::protobuf::io;
570    char package[128];
571    // Check whether tracing is enabled for this process.
572    FILE * file = fopen("/proc/self/cmdline", "r");
573    if (file) {
574        if (!fgets(package, 128, file)) {
575            ALOGE("Error reading cmdline: %s (%d)", strerror(errno), errno);
576            fclose(file);
577            return;
578        }
579        fclose(file);
580    } else {
581        ALOGE("Error opening /proc/self/cmdline: %s (%d)", strerror(errno),
582                errno);
583        return;
584    }
585    char path[1024];
586    snprintf(path, 1024, "/data/data/%s/cache/rendertree_dump", package);
587    int fd = open(path, O_CREAT | O_WRONLY, S_IRWXU | S_IRGRP | S_IROTH);
588    if (fd == -1) {
589        ALOGD("Failed to open '%s'", path);
590        return;
591    }
592    proto::RenderNode tree;
593    // TODO: Streaming writes?
594    mRootRenderNode->copyTo(&tree);
595    std::string data = tree.SerializeAsString();
596    write(fd, data.c_str(), data.length());
597    close(fd);
598#endif
599}
600
601void CanvasContext::waitOnFences() {
602    if (mFrameFences.size()) {
603        ATRACE_CALL();
604        for (auto& fence : mFrameFences) {
605            fence->getResult();
606        }
607        mFrameFences.clear();
608    }
609}
610
611class CanvasContext::FuncTaskProcessor : public TaskProcessor<bool> {
612public:
613    explicit FuncTaskProcessor(TaskManager* taskManager)
614            : TaskProcessor<bool>(taskManager) {}
615
616    virtual void onProcess(const sp<Task<bool> >& task) override {
617        FuncTask* t = static_cast<FuncTask*>(task.get());
618        t->func();
619        task->setResult(true);
620    }
621};
622
623void CanvasContext::enqueueFrameWork(std::function<void()>&& func) {
624    if (!mFrameWorkProcessor.get()) {
625        mFrameWorkProcessor = new FuncTaskProcessor(mRenderPipeline->getTaskManager());
626    }
627    sp<FuncTask> task(new FuncTask());
628    task->func = func;
629    mFrameFences.push_back(task);
630    mFrameWorkProcessor->add(task);
631}
632
633int64_t CanvasContext::getFrameNumber() {
634    // mFrameNumber is reset to -1 when the surface changes or we swap buffers
635    if (mFrameNumber == -1 && mNativeSurface.get()) {
636        mFrameNumber = static_cast<int64_t>(mNativeSurface->getNextFrameNumber());
637    }
638    return mFrameNumber;
639}
640
641SkRect CanvasContext::computeDirtyRect(const Frame& frame, SkRect* dirty) {
642    if (frame.width() != mLastFrameWidth || frame.height() != mLastFrameHeight) {
643        // can't rely on prior content of window if viewport size changes
644        dirty->setEmpty();
645        mLastFrameWidth = frame.width();
646        mLastFrameHeight = frame.height();
647    } else if (mHaveNewSurface || frame.bufferAge() == 0) {
648        // New surface needs a full draw
649        dirty->setEmpty();
650    } else {
651        if (!dirty->isEmpty() && !dirty->intersect(0, 0, frame.width(), frame.height())) {
652            ALOGW("Dirty " RECT_STRING " doesn't intersect with 0 0 %d %d ?",
653                    SK_RECT_ARGS(*dirty), frame.width(), frame.height());
654            dirty->setEmpty();
655        }
656        profiler().unionDirty(dirty);
657    }
658
659    if (dirty->isEmpty()) {
660        dirty->set(0, 0, frame.width(), frame.height());
661    }
662
663    // At this point dirty is the area of the window to update. However,
664    // the area of the frame we need to repaint is potentially different, so
665    // stash the screen area for later
666    SkRect windowDirty(*dirty);
667
668    // If the buffer age is 0 we do a full-screen repaint (handled above)
669    // If the buffer age is 1 the buffer contents are the same as they were
670    // last frame so there's nothing to union() against
671    // Therefore we only care about the > 1 case.
672    if (frame.bufferAge() > 1) {
673        if (frame.bufferAge() > (int) mSwapHistory.size()) {
674            // We don't have enough history to handle this old of a buffer
675            // Just do a full-draw
676            dirty->set(0, 0, frame.width(), frame.height());
677        } else {
678            // At this point we haven't yet added the latest frame
679            // to the damage history (happens below)
680            // So we need to damage
681            for (int i = mSwapHistory.size() - 1;
682                    i > ((int) mSwapHistory.size()) - frame.bufferAge(); i--) {
683                dirty->join(mSwapHistory[i].damage);
684            }
685        }
686    }
687
688    return windowDirty;
689}
690
691} /* namespace renderthread */
692} /* namespace uirenderer */
693} /* namespace android */
694