SurfaceFlinger.cpp revision cd65a2c51e2f0d7756274fad0ad2c2fe698d2229
1/*
2 * Copyright (C) 2007 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#define ATRACE_TAG ATRACE_TAG_GRAPHICS
18
19#include <stdint.h>
20#include <sys/types.h>
21#include <errno.h>
22#include <math.h>
23#include <dlfcn.h>
24
25#include <EGL/egl.h>
26
27#include <cutils/log.h>
28#include <cutils/properties.h>
29
30#include <binder/IPCThreadState.h>
31#include <binder/IServiceManager.h>
32#include <binder/MemoryHeapBase.h>
33#include <binder/PermissionCache.h>
34
35#include <ui/DisplayInfo.h>
36
37#include <gui/BitTube.h>
38#include <gui/BufferQueue.h>
39#include <gui/GuiConfig.h>
40#include <gui/IDisplayEventConnection.h>
41#include <gui/Surface.h>
42#include <gui/GraphicBufferAlloc.h>
43
44#include <ui/GraphicBufferAllocator.h>
45#include <ui/PixelFormat.h>
46#include <ui/UiConfig.h>
47
48#include <utils/misc.h>
49#include <utils/String8.h>
50#include <utils/String16.h>
51#include <utils/StopWatch.h>
52#include <utils/Trace.h>
53
54#include <private/android_filesystem_config.h>
55#include <private/gui/SyncFeatures.h>
56
57#include "Client.h"
58#include "clz.h"
59#include "Colorizer.h"
60#include "DdmConnection.h"
61#include "DisplayDevice.h"
62#include "DispSync.h"
63#include "EventControlThread.h"
64#include "EventThread.h"
65#include "Layer.h"
66#include "LayerDim.h"
67#include "SurfaceFlinger.h"
68
69#include "DisplayHardware/FramebufferSurface.h"
70#include "DisplayHardware/HWComposer.h"
71#include "DisplayHardware/VirtualDisplaySurface.h"
72
73#include "Effects/Daltonizer.h"
74
75#include "RenderEngine/RenderEngine.h"
76#include <cutils/compiler.h>
77
78#define DISPLAY_COUNT       1
79
80/*
81 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
82 * black pixels.
83 */
84#define DEBUG_SCREENSHOTS   false
85
86EGLAPI const char* eglQueryStringImplementationANDROID(EGLDisplay dpy, EGLint name);
87
88namespace android {
89
90// This works around the lack of support for the sync framework on some
91// devices.
92#ifdef RUNNING_WITHOUT_SYNC_FRAMEWORK
93static const bool runningWithoutSyncFramework = true;
94#else
95static const bool runningWithoutSyncFramework = false;
96#endif
97
98// This is the phase offset in nanoseconds of the software vsync event
99// relative to the vsync event reported by HWComposer.  The software vsync
100// event is when SurfaceFlinger and Choreographer-based applications run each
101// frame.
102//
103// This phase offset allows adjustment of the minimum latency from application
104// wake-up (by Choregographer) time to the time at which the resulting window
105// image is displayed.  This value may be either positive (after the HW vsync)
106// or negative (before the HW vsync).  Setting it to 0 will result in a
107// minimum latency of two vsync periods because the app and SurfaceFlinger
108// will run just after the HW vsync.  Setting it to a positive number will
109// result in the minimum latency being:
110//
111//     (2 * VSYNC_PERIOD - (vsyncPhaseOffsetNs % VSYNC_PERIOD))
112//
113// Note that reducing this latency makes it more likely for the applications
114// to not have their window content image ready in time.  When this happens
115// the latency will end up being an additional vsync period, and animations
116// will hiccup.  Therefore, this latency should be tuned somewhat
117// conservatively (or at least with awareness of the trade-off being made).
118static const int64_t vsyncPhaseOffsetNs = VSYNC_EVENT_PHASE_OFFSET_NS;
119
120// This is the phase offset at which SurfaceFlinger's composition runs.
121static const int64_t sfVsyncPhaseOffsetNs = SF_VSYNC_EVENT_PHASE_OFFSET_NS;
122
123// ---------------------------------------------------------------------------
124
125const String16 sHardwareTest("android.permission.HARDWARE_TEST");
126const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
127const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
128const String16 sDump("android.permission.DUMP");
129
130// ---------------------------------------------------------------------------
131
132SurfaceFlinger::SurfaceFlinger()
133    :   BnSurfaceComposer(),
134        mTransactionFlags(0),
135        mTransactionPending(false),
136        mAnimTransactionPending(false),
137        mLayersRemoved(false),
138        mRepaintEverything(0),
139        mRenderEngine(NULL),
140        mBootTime(systemTime()),
141        mVisibleRegionsDirty(false),
142        mHwWorkListDirty(false),
143        mAnimCompositionPending(false),
144        mDebugRegion(0),
145        mDebugDDMS(0),
146        mDebugDisableHWC(0),
147        mDebugDisableTransformHint(0),
148        mDebugInSwapBuffers(0),
149        mLastSwapBufferTime(0),
150        mDebugInTransaction(0),
151        mLastTransactionTime(0),
152        mBootFinished(false),
153        mPrimaryHWVsyncEnabled(false),
154        mHWVsyncAvailable(false),
155        mDaltonize(false),
156        mHasColorMatrix(false)
157{
158    ALOGI("SurfaceFlinger is starting");
159
160    // debugging stuff...
161    char value[PROPERTY_VALUE_MAX];
162
163    property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
164    mGpuToCpuSupported = !atoi(value);
165
166    property_get("debug.sf.showupdates", value, "0");
167    mDebugRegion = atoi(value);
168
169    property_get("debug.sf.ddms", value, "0");
170    mDebugDDMS = atoi(value);
171    if (mDebugDDMS) {
172        if (!startDdmConnection()) {
173            // start failed, and DDMS debugging not enabled
174            mDebugDDMS = 0;
175        }
176    }
177    ALOGI_IF(mDebugRegion, "showupdates enabled");
178    ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
179}
180
181void SurfaceFlinger::onFirstRef()
182{
183    mEventQueue.init(this);
184}
185
186SurfaceFlinger::~SurfaceFlinger()
187{
188    EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
189    eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
190    eglTerminate(display);
191}
192
193void SurfaceFlinger::binderDied(const wp<IBinder>& who)
194{
195    // the window manager died on us. prepare its eulogy.
196
197    // restore initial conditions (default device unblank, etc)
198    initializeDisplays();
199
200    // restart the boot-animation
201    startBootAnim();
202}
203
204sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
205{
206    sp<ISurfaceComposerClient> bclient;
207    sp<Client> client(new Client(this));
208    status_t err = client->initCheck();
209    if (err == NO_ERROR) {
210        bclient = client;
211    }
212    return bclient;
213}
214
215sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
216        bool secure)
217{
218    class DisplayToken : public BBinder {
219        sp<SurfaceFlinger> flinger;
220        virtual ~DisplayToken() {
221             // no more references, this display must be terminated
222             Mutex::Autolock _l(flinger->mStateLock);
223             flinger->mCurrentState.displays.removeItem(this);
224             flinger->setTransactionFlags(eDisplayTransactionNeeded);
225         }
226     public:
227        DisplayToken(const sp<SurfaceFlinger>& flinger)
228            : flinger(flinger) {
229        }
230    };
231
232    sp<BBinder> token = new DisplayToken(this);
233
234    Mutex::Autolock _l(mStateLock);
235    DisplayDeviceState info(DisplayDevice::DISPLAY_VIRTUAL);
236    info.displayName = displayName;
237    info.isSecure = secure;
238    mCurrentState.displays.add(token, info);
239
240    return token;
241}
242
243void SurfaceFlinger::destroyDisplay(const sp<IBinder>& display) {
244    Mutex::Autolock _l(mStateLock);
245
246    ssize_t idx = mCurrentState.displays.indexOfKey(display);
247    if (idx < 0) {
248        ALOGW("destroyDisplay: invalid display token");
249        return;
250    }
251
252    const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
253    if (!info.isVirtualDisplay()) {
254        ALOGE("destroyDisplay called for non-virtual display");
255        return;
256    }
257
258    mCurrentState.displays.removeItemsAt(idx);
259    setTransactionFlags(eDisplayTransactionNeeded);
260}
261
262void SurfaceFlinger::createBuiltinDisplayLocked(DisplayDevice::DisplayType type) {
263    ALOGW_IF(mBuiltinDisplays[type],
264            "Overwriting display token for display type %d", type);
265    mBuiltinDisplays[type] = new BBinder();
266    DisplayDeviceState info(type);
267    // All non-virtual displays are currently considered secure.
268    info.isSecure = true;
269    mCurrentState.displays.add(mBuiltinDisplays[type], info);
270}
271
272sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
273    if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
274        ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
275        return NULL;
276    }
277    return mBuiltinDisplays[id];
278}
279
280sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
281{
282    sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
283    return gba;
284}
285
286void SurfaceFlinger::bootFinished()
287{
288    const nsecs_t now = systemTime();
289    const nsecs_t duration = now - mBootTime;
290    ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
291    mBootFinished = true;
292
293    // wait patiently for the window manager death
294    const String16 name("window");
295    sp<IBinder> window(defaultServiceManager()->getService(name));
296    if (window != 0) {
297        window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
298    }
299
300    // stop boot animation
301    // formerly we would just kill the process, but we now ask it to exit so it
302    // can choose where to stop the animation.
303    property_set("service.bootanim.exit", "1");
304}
305
306void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
307    class MessageDestroyGLTexture : public MessageBase {
308        RenderEngine& engine;
309        uint32_t texture;
310    public:
311        MessageDestroyGLTexture(RenderEngine& engine, uint32_t texture)
312            : engine(engine), texture(texture) {
313        }
314        virtual bool handler() {
315            engine.deleteTextures(1, &texture);
316            return true;
317        }
318    };
319    postMessageAsync(new MessageDestroyGLTexture(getRenderEngine(), texture));
320}
321
322status_t SurfaceFlinger::selectConfigForAttribute(
323        EGLDisplay dpy,
324        EGLint const* attrs,
325        EGLint attribute, EGLint wanted,
326        EGLConfig* outConfig)
327{
328    EGLConfig config = NULL;
329    EGLint numConfigs = -1, n=0;
330    eglGetConfigs(dpy, NULL, 0, &numConfigs);
331    EGLConfig* const configs = new EGLConfig[numConfigs];
332    eglChooseConfig(dpy, attrs, configs, numConfigs, &n);
333
334    if (n) {
335        if (attribute != EGL_NONE) {
336            for (int i=0 ; i<n ; i++) {
337                EGLint value = 0;
338                eglGetConfigAttrib(dpy, configs[i], attribute, &value);
339                if (wanted == value) {
340                    *outConfig = configs[i];
341                    delete [] configs;
342                    return NO_ERROR;
343                }
344            }
345        } else {
346            // just pick the first one
347            *outConfig = configs[0];
348            delete [] configs;
349            return NO_ERROR;
350        }
351    }
352    delete [] configs;
353    return NAME_NOT_FOUND;
354}
355
356class EGLAttributeVector {
357    struct Attribute;
358    class Adder;
359    friend class Adder;
360    KeyedVector<Attribute, EGLint> mList;
361    struct Attribute {
362        Attribute() {};
363        Attribute(EGLint v) : v(v) { }
364        EGLint v;
365        bool operator < (const Attribute& other) const {
366            // this places EGL_NONE at the end
367            EGLint lhs(v);
368            EGLint rhs(other.v);
369            if (lhs == EGL_NONE) lhs = 0x7FFFFFFF;
370            if (rhs == EGL_NONE) rhs = 0x7FFFFFFF;
371            return lhs < rhs;
372        }
373    };
374    class Adder {
375        friend class EGLAttributeVector;
376        EGLAttributeVector& v;
377        EGLint attribute;
378        Adder(EGLAttributeVector& v, EGLint attribute)
379            : v(v), attribute(attribute) {
380        }
381    public:
382        void operator = (EGLint value) {
383            if (attribute != EGL_NONE) {
384                v.mList.add(attribute, value);
385            }
386        }
387        operator EGLint () const { return v.mList[attribute]; }
388    };
389public:
390    EGLAttributeVector() {
391        mList.add(EGL_NONE, EGL_NONE);
392    }
393    void remove(EGLint attribute) {
394        if (attribute != EGL_NONE) {
395            mList.removeItem(attribute);
396        }
397    }
398    Adder operator [] (EGLint attribute) {
399        return Adder(*this, attribute);
400    }
401    EGLint operator [] (EGLint attribute) const {
402       return mList[attribute];
403    }
404    // cast-operator to (EGLint const*)
405    operator EGLint const* () const { return &mList.keyAt(0).v; }
406};
407
408status_t SurfaceFlinger::selectEGLConfig(EGLDisplay display, EGLint nativeVisualId,
409    EGLint renderableType, EGLConfig* config) {
410    // select our EGLConfig. It must support EGL_RECORDABLE_ANDROID if
411    // it is to be used with WIFI displays
412    status_t err;
413    EGLint wantedAttribute;
414    EGLint wantedAttributeValue;
415
416    EGLAttributeVector attribs;
417    if (renderableType) {
418        attribs[EGL_RENDERABLE_TYPE]            = renderableType;
419        attribs[EGL_RECORDABLE_ANDROID]         = EGL_TRUE;
420        attribs[EGL_SURFACE_TYPE]               = EGL_WINDOW_BIT|EGL_PBUFFER_BIT;
421        attribs[EGL_FRAMEBUFFER_TARGET_ANDROID] = EGL_TRUE;
422        attribs[EGL_RED_SIZE]                   = 8;
423        attribs[EGL_GREEN_SIZE]                 = 8;
424        attribs[EGL_BLUE_SIZE]                  = 8;
425        wantedAttribute                         = EGL_NONE;
426        wantedAttributeValue                    = EGL_NONE;
427
428    } else {
429        // if no renderable type specified, fallback to a simplified query
430        wantedAttribute                         = EGL_NATIVE_VISUAL_ID;
431        wantedAttributeValue                    = nativeVisualId;
432    }
433
434    err = selectConfigForAttribute(display, attribs, wantedAttribute,
435        wantedAttributeValue, config);
436    if (err == NO_ERROR) {
437        EGLint caveat;
438        if (eglGetConfigAttrib(display, *config, EGL_CONFIG_CAVEAT, &caveat))
439            ALOGW_IF(caveat == EGL_SLOW_CONFIG, "EGL_SLOW_CONFIG selected!");
440    }
441    return err;
442}
443
444class DispSyncSource : public VSyncSource, private DispSync::Callback {
445public:
446    DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync) :
447            mValue(0),
448            mPhaseOffset(phaseOffset),
449            mTraceVsync(traceVsync),
450            mDispSync(dispSync) {}
451
452    virtual ~DispSyncSource() {}
453
454    virtual void setVSyncEnabled(bool enable) {
455        // Do NOT lock the mutex here so as to avoid any mutex ordering issues
456        // with locking it in the onDispSyncEvent callback.
457        if (enable) {
458            status_t err = mDispSync->addEventListener(mPhaseOffset,
459                    static_cast<DispSync::Callback*>(this));
460            if (err != NO_ERROR) {
461                ALOGE("error registering vsync callback: %s (%d)",
462                        strerror(-err), err);
463            }
464            ATRACE_INT("VsyncOn", 1);
465        } else {
466            status_t err = mDispSync->removeEventListener(
467                    static_cast<DispSync::Callback*>(this));
468            if (err != NO_ERROR) {
469                ALOGE("error unregistering vsync callback: %s (%d)",
470                        strerror(-err), err);
471            }
472            ATRACE_INT("VsyncOn", 0);
473        }
474    }
475
476    virtual void setCallback(const sp<VSyncSource::Callback>& callback) {
477        Mutex::Autolock lock(mMutex);
478        mCallback = callback;
479    }
480
481private:
482    virtual void onDispSyncEvent(nsecs_t when) {
483        sp<VSyncSource::Callback> callback;
484        {
485            Mutex::Autolock lock(mMutex);
486            callback = mCallback;
487
488            if (mTraceVsync) {
489                mValue = (mValue + 1) % 2;
490                ATRACE_INT("VSYNC", mValue);
491            }
492        }
493
494        if (callback != NULL) {
495            callback->onVSyncEvent(when);
496        }
497    }
498
499    int mValue;
500
501    const nsecs_t mPhaseOffset;
502    const bool mTraceVsync;
503
504    DispSync* mDispSync;
505    sp<VSyncSource::Callback> mCallback;
506    Mutex mMutex;
507};
508
509void SurfaceFlinger::init() {
510    ALOGI(  "SurfaceFlinger's main thread ready to run. "
511            "Initializing graphics H/W...");
512
513    status_t err;
514    Mutex::Autolock _l(mStateLock);
515
516    // initialize EGL for the default display
517    mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
518    eglInitialize(mEGLDisplay, NULL, NULL);
519
520    // Initialize the H/W composer object.  There may or may not be an
521    // actual hardware composer underneath.
522    mHwc = new HWComposer(this,
523            *static_cast<HWComposer::EventHandler *>(this));
524
525    // First try to get an ES2 config
526    err = selectEGLConfig(mEGLDisplay, mHwc->getVisualID(), EGL_OPENGL_ES2_BIT,
527            &mEGLConfig);
528
529    if (err != NO_ERROR) {
530        // If ES2 fails, try ES1
531        err = selectEGLConfig(mEGLDisplay, mHwc->getVisualID(),
532                EGL_OPENGL_ES_BIT, &mEGLConfig);
533    }
534
535    if (err != NO_ERROR) {
536        // still didn't work, probably because we're on the emulator...
537        // try a simplified query
538        ALOGW("no suitable EGLConfig found, trying a simpler query");
539        err = selectEGLConfig(mEGLDisplay, mHwc->getVisualID(), 0, &mEGLConfig);
540    }
541
542    if (err != NO_ERROR) {
543        // this EGL is too lame for android
544        LOG_ALWAYS_FATAL("no suitable EGLConfig found, giving up");
545    }
546
547    // print some debugging info
548    EGLint r,g,b,a;
549    eglGetConfigAttrib(mEGLDisplay, mEGLConfig, EGL_RED_SIZE,   &r);
550    eglGetConfigAttrib(mEGLDisplay, mEGLConfig, EGL_GREEN_SIZE, &g);
551    eglGetConfigAttrib(mEGLDisplay, mEGLConfig, EGL_BLUE_SIZE,  &b);
552    eglGetConfigAttrib(mEGLDisplay, mEGLConfig, EGL_ALPHA_SIZE, &a);
553    ALOGI("EGL informations:");
554    ALOGI("vendor    : %s", eglQueryString(mEGLDisplay, EGL_VENDOR));
555    ALOGI("version   : %s", eglQueryString(mEGLDisplay, EGL_VERSION));
556    ALOGI("extensions: %s", eglQueryString(mEGLDisplay, EGL_EXTENSIONS));
557    ALOGI("Client API: %s", eglQueryString(mEGLDisplay, EGL_CLIENT_APIS)?:"Not Supported");
558    ALOGI("EGLSurface: %d-%d-%d-%d, config=%p", r, g, b, a, mEGLConfig);
559
560    // get a RenderEngine for the given display / config (can't fail)
561    mRenderEngine = RenderEngine::create(mEGLDisplay, mEGLConfig);
562
563    // retrieve the EGL context that was selected/created
564    mEGLContext = mRenderEngine->getEGLContext();
565
566    // figure out which format we got
567    eglGetConfigAttrib(mEGLDisplay, mEGLConfig,
568            EGL_NATIVE_VISUAL_ID, &mEGLNativeVisualId);
569
570    LOG_ALWAYS_FATAL_IF(mEGLContext == EGL_NO_CONTEXT,
571            "couldn't create EGLContext");
572
573    // initialize our non-virtual displays
574    for (size_t i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
575        DisplayDevice::DisplayType type((DisplayDevice::DisplayType)i);
576        // set-up the displays that are already connected
577        if (mHwc->isConnected(i) || type==DisplayDevice::DISPLAY_PRIMARY) {
578            // All non-virtual displays are currently considered secure.
579            bool isSecure = true;
580            createBuiltinDisplayLocked(type);
581            wp<IBinder> token = mBuiltinDisplays[i];
582
583            sp<BufferQueue> bq = new BufferQueue(new GraphicBufferAlloc());
584            sp<FramebufferSurface> fbs = new FramebufferSurface(*mHwc, i, bq);
585            sp<DisplayDevice> hw = new DisplayDevice(this,
586                    type, allocateHwcDisplayId(type), isSecure, token,
587                    fbs, bq,
588                    mEGLConfig);
589            if (i > DisplayDevice::DISPLAY_PRIMARY) {
590                // FIXME: currently we don't get blank/unblank requests
591                // for displays other than the main display, so we always
592                // assume a connected display is unblanked.
593                ALOGD("marking display %d as acquired/unblanked", i);
594                hw->acquireScreen();
595            }
596            mDisplays.add(token, hw);
597        }
598    }
599
600    // make the GLContext current so that we can create textures when creating Layers
601    // (which may happens before we render something)
602    getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
603
604    // start the EventThread
605    sp<VSyncSource> vsyncSrc = new DispSyncSource(&mPrimaryDispSync,
606            vsyncPhaseOffsetNs, true);
607    mEventThread = new EventThread(vsyncSrc);
608    sp<VSyncSource> sfVsyncSrc = new DispSyncSource(&mPrimaryDispSync,
609            sfVsyncPhaseOffsetNs, false);
610    mSFEventThread = new EventThread(sfVsyncSrc);
611    mEventQueue.setEventThread(mSFEventThread);
612
613    mEventControlThread = new EventControlThread(this);
614    mEventControlThread->run("EventControl", PRIORITY_URGENT_DISPLAY);
615
616    // set a fake vsync period if there is no HWComposer
617    if (mHwc->initCheck() != NO_ERROR) {
618        mPrimaryDispSync.setPeriod(16666667);
619    }
620
621    // initialize our drawing state
622    mDrawingState = mCurrentState;
623
624    // set initial conditions (e.g. unblank default device)
625    initializeDisplays();
626
627    // start boot animation
628    startBootAnim();
629}
630
631int32_t SurfaceFlinger::allocateHwcDisplayId(DisplayDevice::DisplayType type) {
632    return (uint32_t(type) < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) ?
633            type : mHwc->allocateDisplayId();
634}
635
636void SurfaceFlinger::startBootAnim() {
637    // start boot animation
638    property_set("service.bootanim.exit", "0");
639    property_set("ctl.start", "bootanim");
640}
641
642size_t SurfaceFlinger::getMaxTextureSize() const {
643    return mRenderEngine->getMaxTextureSize();
644}
645
646size_t SurfaceFlinger::getMaxViewportDims() const {
647    return mRenderEngine->getMaxViewportDims();
648}
649
650// ----------------------------------------------------------------------------
651
652bool SurfaceFlinger::authenticateSurfaceTexture(
653        const sp<IGraphicBufferProducer>& bufferProducer) const {
654    Mutex::Autolock _l(mStateLock);
655    sp<IBinder> surfaceTextureBinder(bufferProducer->asBinder());
656    return mGraphicBufferProducerList.indexOf(surfaceTextureBinder) >= 0;
657}
658
659status_t SurfaceFlinger::getDisplayInfo(const sp<IBinder>& display, DisplayInfo* info) {
660    int32_t type = NAME_NOT_FOUND;
661    for (int i=0 ; i<DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES ; i++) {
662        if (display == mBuiltinDisplays[i]) {
663            type = i;
664            break;
665        }
666    }
667
668    if (type < 0) {
669        return type;
670    }
671
672    const HWComposer& hwc(getHwComposer());
673    float xdpi = hwc.getDpiX(type);
674    float ydpi = hwc.getDpiY(type);
675
676    // TODO: Not sure if display density should handled by SF any longer
677    class Density {
678        static int getDensityFromProperty(char const* propName) {
679            char property[PROPERTY_VALUE_MAX];
680            int density = 0;
681            if (property_get(propName, property, NULL) > 0) {
682                density = atoi(property);
683            }
684            return density;
685        }
686    public:
687        static int getEmuDensity() {
688            return getDensityFromProperty("qemu.sf.lcd_density"); }
689        static int getBuildDensity()  {
690            return getDensityFromProperty("ro.sf.lcd_density"); }
691    };
692
693    if (type == DisplayDevice::DISPLAY_PRIMARY) {
694        // The density of the device is provided by a build property
695        float density = Density::getBuildDensity() / 160.0f;
696        if (density == 0) {
697            // the build doesn't provide a density -- this is wrong!
698            // use xdpi instead
699            ALOGE("ro.sf.lcd_density must be defined as a build property");
700            density = xdpi / 160.0f;
701        }
702        if (Density::getEmuDensity()) {
703            // if "qemu.sf.lcd_density" is specified, it overrides everything
704            xdpi = ydpi = density = Density::getEmuDensity();
705            density /= 160.0f;
706        }
707        info->density = density;
708
709        // TODO: this needs to go away (currently needed only by webkit)
710        sp<const DisplayDevice> hw(getDefaultDisplayDevice());
711        info->orientation = hw->getOrientation();
712    } else {
713        // TODO: where should this value come from?
714        static const int TV_DENSITY = 213;
715        info->density = TV_DENSITY / 160.0f;
716        info->orientation = 0;
717    }
718
719    info->w = hwc.getWidth(type);
720    info->h = hwc.getHeight(type);
721    info->xdpi = xdpi;
722    info->ydpi = ydpi;
723    info->fps = float(1e9 / hwc.getRefreshPeriod(type));
724
725    // All non-virtual displays are currently considered secure.
726    info->secure = true;
727
728    return NO_ERROR;
729}
730
731// ----------------------------------------------------------------------------
732
733sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
734    return mEventThread->createEventConnection();
735}
736
737// ----------------------------------------------------------------------------
738
739void SurfaceFlinger::waitForEvent() {
740    mEventQueue.waitMessage();
741}
742
743void SurfaceFlinger::signalTransaction() {
744    mEventQueue.invalidate();
745}
746
747void SurfaceFlinger::signalLayerUpdate() {
748    mEventQueue.invalidate();
749}
750
751void SurfaceFlinger::signalRefresh() {
752    mEventQueue.refresh();
753}
754
755status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
756        nsecs_t reltime, uint32_t flags) {
757    return mEventQueue.postMessage(msg, reltime);
758}
759
760status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
761        nsecs_t reltime, uint32_t flags) {
762    status_t res = mEventQueue.postMessage(msg, reltime);
763    if (res == NO_ERROR) {
764        msg->wait();
765    }
766    return res;
767}
768
769void SurfaceFlinger::run() {
770    do {
771        waitForEvent();
772    } while (true);
773}
774
775void SurfaceFlinger::enableHardwareVsync() {
776    Mutex::Autolock _l(mHWVsyncLock);
777    if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
778        mPrimaryDispSync.beginResync();
779        //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
780        mEventControlThread->setVsyncEnabled(true);
781        mPrimaryHWVsyncEnabled = true;
782    }
783}
784
785void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
786    Mutex::Autolock _l(mHWVsyncLock);
787
788    if (makeAvailable) {
789        mHWVsyncAvailable = true;
790    } else if (!mHWVsyncAvailable) {
791        ALOGE("resyncToHardwareVsync called when HW vsync unavailable");
792        return;
793    }
794
795    const nsecs_t period =
796            getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
797
798    mPrimaryDispSync.reset();
799    mPrimaryDispSync.setPeriod(period);
800
801    if (!mPrimaryHWVsyncEnabled) {
802        mPrimaryDispSync.beginResync();
803        //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, true);
804        mEventControlThread->setVsyncEnabled(true);
805        mPrimaryHWVsyncEnabled = true;
806    }
807}
808
809void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
810    Mutex::Autolock _l(mHWVsyncLock);
811    if (mPrimaryHWVsyncEnabled) {
812        //eventControl(HWC_DISPLAY_PRIMARY, SurfaceFlinger::EVENT_VSYNC, false);
813        mEventControlThread->setVsyncEnabled(false);
814        mPrimaryDispSync.endResync();
815        mPrimaryHWVsyncEnabled = false;
816    }
817    if (makeUnavailable) {
818        mHWVsyncAvailable = false;
819    }
820}
821
822void SurfaceFlinger::onVSyncReceived(int type, nsecs_t timestamp) {
823    bool needsHwVsync = false;
824
825    { // Scope for the lock
826        Mutex::Autolock _l(mHWVsyncLock);
827        if (type == 0 && mPrimaryHWVsyncEnabled) {
828            needsHwVsync = mPrimaryDispSync.addResyncSample(timestamp);
829        }
830    }
831
832    if (needsHwVsync) {
833        enableHardwareVsync();
834    } else {
835        disableHardwareVsync(false);
836    }
837}
838
839void SurfaceFlinger::onHotplugReceived(int type, bool connected) {
840    if (mEventThread == NULL) {
841        // This is a temporary workaround for b/7145521.  A non-null pointer
842        // does not mean EventThread has finished initializing, so this
843        // is not a correct fix.
844        ALOGW("WARNING: EventThread not started, ignoring hotplug");
845        return;
846    }
847
848    if (uint32_t(type) < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
849        Mutex::Autolock _l(mStateLock);
850        if (connected) {
851            createBuiltinDisplayLocked((DisplayDevice::DisplayType)type);
852        } else {
853            mCurrentState.displays.removeItem(mBuiltinDisplays[type]);
854            mBuiltinDisplays[type].clear();
855        }
856        setTransactionFlags(eDisplayTransactionNeeded);
857
858        // Defer EventThread notification until SF has updated mDisplays.
859    }
860}
861
862void SurfaceFlinger::eventControl(int disp, int event, int enabled) {
863    ATRACE_CALL();
864    getHwComposer().eventControl(disp, event, enabled);
865}
866
867void SurfaceFlinger::onMessageReceived(int32_t what) {
868    ATRACE_CALL();
869    switch (what) {
870    case MessageQueue::TRANSACTION:
871        handleMessageTransaction();
872        break;
873    case MessageQueue::INVALIDATE:
874        handleMessageTransaction();
875        handleMessageInvalidate();
876        signalRefresh();
877        break;
878    case MessageQueue::REFRESH:
879        handleMessageRefresh();
880        break;
881    }
882}
883
884void SurfaceFlinger::handleMessageTransaction() {
885    uint32_t transactionFlags = peekTransactionFlags(eTransactionMask);
886    if (transactionFlags) {
887        handleTransaction(transactionFlags);
888    }
889}
890
891void SurfaceFlinger::handleMessageInvalidate() {
892    ATRACE_CALL();
893    handlePageFlip();
894}
895
896void SurfaceFlinger::handleMessageRefresh() {
897    ATRACE_CALL();
898    preComposition();
899    rebuildLayerStacks();
900    setUpHWComposer();
901    doDebugFlashRegions();
902    doComposition();
903    postComposition();
904}
905
906void SurfaceFlinger::doDebugFlashRegions()
907{
908    // is debugging enabled
909    if (CC_LIKELY(!mDebugRegion))
910        return;
911
912    const bool repaintEverything = mRepaintEverything;
913    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
914        const sp<DisplayDevice>& hw(mDisplays[dpy]);
915        if (hw->canDraw()) {
916            // transform the dirty region into this screen's coordinate space
917            const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
918            if (!dirtyRegion.isEmpty()) {
919                // redraw the whole screen
920                doComposeSurfaces(hw, Region(hw->bounds()));
921
922                // and draw the dirty region
923                const int32_t height = hw->getHeight();
924                RenderEngine& engine(getRenderEngine());
925                engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
926
927                hw->compositionComplete();
928                hw->swapBuffers(getHwComposer());
929            }
930        }
931    }
932
933    postFramebuffer();
934
935    if (mDebugRegion > 1) {
936        usleep(mDebugRegion * 1000);
937    }
938
939    HWComposer& hwc(getHwComposer());
940    if (hwc.initCheck() == NO_ERROR) {
941        status_t err = hwc.prepare();
942        ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
943    }
944}
945
946void SurfaceFlinger::preComposition()
947{
948    bool needExtraInvalidate = false;
949    const LayerVector& layers(mDrawingState.layersSortedByZ);
950    const size_t count = layers.size();
951    for (size_t i=0 ; i<count ; i++) {
952        if (layers[i]->onPreComposition()) {
953            needExtraInvalidate = true;
954        }
955    }
956    if (needExtraInvalidate) {
957        signalLayerUpdate();
958    }
959}
960
961void SurfaceFlinger::postComposition()
962{
963    const LayerVector& layers(mDrawingState.layersSortedByZ);
964    const size_t count = layers.size();
965    for (size_t i=0 ; i<count ; i++) {
966        layers[i]->onPostComposition();
967    }
968
969    const HWComposer& hwc = getHwComposer();
970    sp<Fence> presentFence = hwc.getDisplayFence(HWC_DISPLAY_PRIMARY);
971
972    if (presentFence->isValid()) {
973        if (mPrimaryDispSync.addPresentFence(presentFence)) {
974            enableHardwareVsync();
975        } else {
976            disableHardwareVsync(false);
977        }
978    }
979
980    if (runningWithoutSyncFramework) {
981        const sp<const DisplayDevice> hw(getDefaultDisplayDevice());
982        if (hw->isScreenAcquired()) {
983            enableHardwareVsync();
984        }
985    }
986
987    if (mAnimCompositionPending) {
988        mAnimCompositionPending = false;
989
990        if (presentFence->isValid()) {
991            mAnimFrameTracker.setActualPresentFence(presentFence);
992        } else {
993            // The HWC doesn't support present fences, so use the refresh
994            // timestamp instead.
995            nsecs_t presentTime = hwc.getRefreshTimestamp(HWC_DISPLAY_PRIMARY);
996            mAnimFrameTracker.setActualPresentTime(presentTime);
997        }
998        mAnimFrameTracker.advanceFrame();
999    }
1000}
1001
1002void SurfaceFlinger::rebuildLayerStacks() {
1003    // rebuild the visible layer list per screen
1004    if (CC_UNLIKELY(mVisibleRegionsDirty)) {
1005        ATRACE_CALL();
1006        mVisibleRegionsDirty = false;
1007        invalidateHwcGeometry();
1008
1009        const LayerVector& layers(mDrawingState.layersSortedByZ);
1010        for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1011            Region opaqueRegion;
1012            Region dirtyRegion;
1013            Vector< sp<Layer> > layersSortedByZ;
1014            const sp<DisplayDevice>& hw(mDisplays[dpy]);
1015            const Transform& tr(hw->getTransform());
1016            const Rect bounds(hw->getBounds());
1017            if (hw->canDraw()) {
1018                SurfaceFlinger::computeVisibleRegions(layers,
1019                        hw->getLayerStack(), dirtyRegion, opaqueRegion);
1020
1021                const size_t count = layers.size();
1022                for (size_t i=0 ; i<count ; i++) {
1023                    const sp<Layer>& layer(layers[i]);
1024                    const Layer::State& s(layer->getDrawingState());
1025                    if (s.layerStack == hw->getLayerStack()) {
1026                        Region drawRegion(tr.transform(
1027                                layer->visibleNonTransparentRegion));
1028                        drawRegion.andSelf(bounds);
1029                        if (!drawRegion.isEmpty()) {
1030                            layersSortedByZ.add(layer);
1031                        }
1032                    }
1033                }
1034            }
1035            hw->setVisibleLayersSortedByZ(layersSortedByZ);
1036            hw->undefinedRegion.set(bounds);
1037            hw->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1038            hw->dirtyRegion.orSelf(dirtyRegion);
1039        }
1040    }
1041}
1042
1043void SurfaceFlinger::setUpHWComposer() {
1044    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1045        mDisplays[dpy]->beginFrame();
1046    }
1047
1048    HWComposer& hwc(getHwComposer());
1049    if (hwc.initCheck() == NO_ERROR) {
1050        // build the h/w work list
1051        if (CC_UNLIKELY(mHwWorkListDirty)) {
1052            mHwWorkListDirty = false;
1053            for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1054                sp<const DisplayDevice> hw(mDisplays[dpy]);
1055                const int32_t id = hw->getHwcDisplayId();
1056                if (id >= 0) {
1057                    const Vector< sp<Layer> >& currentLayers(
1058                        hw->getVisibleLayersSortedByZ());
1059                    const size_t count = currentLayers.size();
1060                    if (hwc.createWorkList(id, count) == NO_ERROR) {
1061                        HWComposer::LayerListIterator cur = hwc.begin(id);
1062                        const HWComposer::LayerListIterator end = hwc.end(id);
1063                        for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1064                            const sp<Layer>& layer(currentLayers[i]);
1065                            layer->setGeometry(hw, *cur);
1066                            if (mDebugDisableHWC || mDebugRegion || mDaltonize || mHasColorMatrix) {
1067                                cur->setSkip(true);
1068                            }
1069                        }
1070                    }
1071                }
1072            }
1073        }
1074
1075        // set the per-frame data
1076        for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1077            sp<const DisplayDevice> hw(mDisplays[dpy]);
1078            const int32_t id = hw->getHwcDisplayId();
1079            if (id >= 0) {
1080                const Vector< sp<Layer> >& currentLayers(
1081                    hw->getVisibleLayersSortedByZ());
1082                const size_t count = currentLayers.size();
1083                HWComposer::LayerListIterator cur = hwc.begin(id);
1084                const HWComposer::LayerListIterator end = hwc.end(id);
1085                for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
1086                    /*
1087                     * update the per-frame h/w composer data for each layer
1088                     * and build the transparent region of the FB
1089                     */
1090                    const sp<Layer>& layer(currentLayers[i]);
1091                    layer->setPerFrameData(hw, *cur);
1092                }
1093            }
1094        }
1095
1096        status_t err = hwc.prepare();
1097        ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
1098
1099        for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1100            sp<const DisplayDevice> hw(mDisplays[dpy]);
1101            hw->prepareFrame(hwc);
1102        }
1103    }
1104}
1105
1106void SurfaceFlinger::doComposition() {
1107    ATRACE_CALL();
1108    const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
1109    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1110        const sp<DisplayDevice>& hw(mDisplays[dpy]);
1111        if (hw->canDraw()) {
1112            // transform the dirty region into this screen's coordinate space
1113            const Region dirtyRegion(hw->getDirtyRegion(repaintEverything));
1114
1115            // repaint the framebuffer (if needed)
1116            doDisplayComposition(hw, dirtyRegion);
1117
1118            hw->dirtyRegion.clear();
1119            hw->flip(hw->swapRegion);
1120            hw->swapRegion.clear();
1121        }
1122        // inform the h/w that we're done compositing
1123        hw->compositionComplete();
1124    }
1125    postFramebuffer();
1126}
1127
1128void SurfaceFlinger::postFramebuffer()
1129{
1130    ATRACE_CALL();
1131
1132    const nsecs_t now = systemTime();
1133    mDebugInSwapBuffers = now;
1134
1135    HWComposer& hwc(getHwComposer());
1136    if (hwc.initCheck() == NO_ERROR) {
1137        if (!hwc.supportsFramebufferTarget()) {
1138            // EGL spec says:
1139            //   "surface must be bound to the calling thread's current context,
1140            //    for the current rendering API."
1141            getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
1142        }
1143        hwc.commit();
1144    }
1145
1146    // make the default display current because the VirtualDisplayDevice code cannot
1147    // deal with dequeueBuffer() being called outside of the composition loop; however
1148    // the code below can call glFlush() which is allowed (and does in some case) call
1149    // dequeueBuffer().
1150    getDefaultDisplayDevice()->makeCurrent(mEGLDisplay, mEGLContext);
1151
1152    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1153        sp<const DisplayDevice> hw(mDisplays[dpy]);
1154        const Vector< sp<Layer> >& currentLayers(hw->getVisibleLayersSortedByZ());
1155        hw->onSwapBuffersCompleted(hwc);
1156        const size_t count = currentLayers.size();
1157        int32_t id = hw->getHwcDisplayId();
1158        if (id >=0 && hwc.initCheck() == NO_ERROR) {
1159            HWComposer::LayerListIterator cur = hwc.begin(id);
1160            const HWComposer::LayerListIterator end = hwc.end(id);
1161            for (size_t i = 0; cur != end && i < count; ++i, ++cur) {
1162                currentLayers[i]->onLayerDisplayed(hw, &*cur);
1163            }
1164        } else {
1165            for (size_t i = 0; i < count; i++) {
1166                currentLayers[i]->onLayerDisplayed(hw, NULL);
1167            }
1168        }
1169    }
1170
1171    mLastSwapBufferTime = systemTime() - now;
1172    mDebugInSwapBuffers = 0;
1173
1174    uint32_t flipCount = getDefaultDisplayDevice()->getPageFlipCount();
1175    if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
1176        logFrameStats();
1177    }
1178}
1179
1180void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
1181{
1182    ATRACE_CALL();
1183
1184    // here we keep a copy of the drawing state (that is the state that's
1185    // going to be overwritten by handleTransactionLocked()) outside of
1186    // mStateLock so that the side-effects of the State assignment
1187    // don't happen with mStateLock held (which can cause deadlocks).
1188    State drawingState(mDrawingState);
1189
1190    Mutex::Autolock _l(mStateLock);
1191    const nsecs_t now = systemTime();
1192    mDebugInTransaction = now;
1193
1194    // Here we're guaranteed that some transaction flags are set
1195    // so we can call handleTransactionLocked() unconditionally.
1196    // We call getTransactionFlags(), which will also clear the flags,
1197    // with mStateLock held to guarantee that mCurrentState won't change
1198    // until the transaction is committed.
1199
1200    transactionFlags = getTransactionFlags(eTransactionMask);
1201    handleTransactionLocked(transactionFlags);
1202
1203    mLastTransactionTime = systemTime() - now;
1204    mDebugInTransaction = 0;
1205    invalidateHwcGeometry();
1206    // here the transaction has been committed
1207}
1208
1209void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
1210{
1211    const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
1212    const size_t count = currentLayers.size();
1213
1214    /*
1215     * Traversal of the children
1216     * (perform the transaction for each of them if needed)
1217     */
1218
1219    if (transactionFlags & eTraversalNeeded) {
1220        for (size_t i=0 ; i<count ; i++) {
1221            const sp<Layer>& layer(currentLayers[i]);
1222            uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
1223            if (!trFlags) continue;
1224
1225            const uint32_t flags = layer->doTransaction(0);
1226            if (flags & Layer::eVisibleRegion)
1227                mVisibleRegionsDirty = true;
1228        }
1229    }
1230
1231    /*
1232     * Perform display own transactions if needed
1233     */
1234
1235    if (transactionFlags & eDisplayTransactionNeeded) {
1236        // here we take advantage of Vector's copy-on-write semantics to
1237        // improve performance by skipping the transaction entirely when
1238        // know that the lists are identical
1239        const KeyedVector<  wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
1240        const KeyedVector<  wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
1241        if (!curr.isIdenticalTo(draw)) {
1242            mVisibleRegionsDirty = true;
1243            const size_t cc = curr.size();
1244                  size_t dc = draw.size();
1245
1246            // find the displays that were removed
1247            // (ie: in drawing state but not in current state)
1248            // also handle displays that changed
1249            // (ie: displays that are in both lists)
1250            for (size_t i=0 ; i<dc ; i++) {
1251                const ssize_t j = curr.indexOfKey(draw.keyAt(i));
1252                if (j < 0) {
1253                    // in drawing state but not in current state
1254                    if (!draw[i].isMainDisplay()) {
1255                        // Call makeCurrent() on the primary display so we can
1256                        // be sure that nothing associated with this display
1257                        // is current.
1258                        const sp<const DisplayDevice> defaultDisplay(getDefaultDisplayDevice());
1259                        defaultDisplay->makeCurrent(mEGLDisplay, mEGLContext);
1260                        sp<DisplayDevice> hw(getDisplayDevice(draw.keyAt(i)));
1261                        if (hw != NULL)
1262                            hw->disconnect(getHwComposer());
1263                        if (draw[i].type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES)
1264                            mEventThread->onHotplugReceived(draw[i].type, false);
1265                        mDisplays.removeItem(draw.keyAt(i));
1266                    } else {
1267                        ALOGW("trying to remove the main display");
1268                    }
1269                } else {
1270                    // this display is in both lists. see if something changed.
1271                    const DisplayDeviceState& state(curr[j]);
1272                    const wp<IBinder>& display(curr.keyAt(j));
1273                    if (state.surface->asBinder() != draw[i].surface->asBinder()) {
1274                        // changing the surface is like destroying and
1275                        // recreating the DisplayDevice, so we just remove it
1276                        // from the drawing state, so that it get re-added
1277                        // below.
1278                        sp<DisplayDevice> hw(getDisplayDevice(display));
1279                        if (hw != NULL)
1280                            hw->disconnect(getHwComposer());
1281                        mDisplays.removeItem(display);
1282                        mDrawingState.displays.removeItemsAt(i);
1283                        dc--; i--;
1284                        // at this point we must loop to the next item
1285                        continue;
1286                    }
1287
1288                    const sp<DisplayDevice> disp(getDisplayDevice(display));
1289                    if (disp != NULL) {
1290                        if (state.layerStack != draw[i].layerStack) {
1291                            disp->setLayerStack(state.layerStack);
1292                        }
1293                        if ((state.orientation != draw[i].orientation)
1294                                || (state.viewport != draw[i].viewport)
1295                                || (state.frame != draw[i].frame))
1296                        {
1297                            disp->setProjection(state.orientation,
1298                                    state.viewport, state.frame);
1299                        }
1300                    }
1301                }
1302            }
1303
1304            // find displays that were added
1305            // (ie: in current state but not in drawing state)
1306            for (size_t i=0 ; i<cc ; i++) {
1307                if (draw.indexOfKey(curr.keyAt(i)) < 0) {
1308                    const DisplayDeviceState& state(curr[i]);
1309
1310                    sp<DisplaySurface> dispSurface;
1311                    sp<IGraphicBufferProducer> producer;
1312                    sp<BufferQueue> bq = new BufferQueue(new GraphicBufferAlloc());
1313
1314                    int32_t hwcDisplayId = -1;
1315                    if (state.isVirtualDisplay()) {
1316                        // Virtual displays without a surface are dormant:
1317                        // they have external state (layer stack, projection,
1318                        // etc.) but no internal state (i.e. a DisplayDevice).
1319                        if (state.surface != NULL) {
1320
1321                            hwcDisplayId = allocateHwcDisplayId(state.type);
1322                            sp<VirtualDisplaySurface> vds = new VirtualDisplaySurface(
1323                                    *mHwc, hwcDisplayId, state.surface, bq,
1324                                    state.displayName);
1325
1326                            dispSurface = vds;
1327                            if (hwcDisplayId >= 0) {
1328                                producer = vds;
1329                            } else {
1330                                // There won't be any interaction with HWC for this virtual display,
1331                                // so the GLES driver can pass buffers directly to the sink.
1332                                producer = state.surface;
1333                            }
1334                        }
1335                    } else {
1336                        ALOGE_IF(state.surface!=NULL,
1337                                "adding a supported display, but rendering "
1338                                "surface is provided (%p), ignoring it",
1339                                state.surface.get());
1340                        hwcDisplayId = allocateHwcDisplayId(state.type);
1341                        // for supported (by hwc) displays we provide our
1342                        // own rendering surface
1343                        dispSurface = new FramebufferSurface(*mHwc, state.type, bq);
1344                        producer = bq;
1345                    }
1346
1347                    const wp<IBinder>& display(curr.keyAt(i));
1348                    if (dispSurface != NULL) {
1349                        sp<DisplayDevice> hw = new DisplayDevice(this,
1350                                state.type, hwcDisplayId, state.isSecure,
1351                                display, dispSurface, producer, mEGLConfig);
1352                        hw->setLayerStack(state.layerStack);
1353                        hw->setProjection(state.orientation,
1354                                state.viewport, state.frame);
1355                        hw->setDisplayName(state.displayName);
1356                        mDisplays.add(display, hw);
1357                        if (state.isVirtualDisplay()) {
1358                            if (hwcDisplayId >= 0) {
1359                                mHwc->setVirtualDisplayProperties(hwcDisplayId,
1360                                        hw->getWidth(), hw->getHeight(),
1361                                        hw->getFormat());
1362                            }
1363                        } else {
1364                            mEventThread->onHotplugReceived(state.type, true);
1365                        }
1366                    }
1367                }
1368            }
1369        }
1370    }
1371
1372    if (transactionFlags & (eTraversalNeeded|eDisplayTransactionNeeded)) {
1373        // The transform hint might have changed for some layers
1374        // (either because a display has changed, or because a layer
1375        // as changed).
1376        //
1377        // Walk through all the layers in currentLayers,
1378        // and update their transform hint.
1379        //
1380        // If a layer is visible only on a single display, then that
1381        // display is used to calculate the hint, otherwise we use the
1382        // default display.
1383        //
1384        // NOTE: we do this here, rather than in rebuildLayerStacks() so that
1385        // the hint is set before we acquire a buffer from the surface texture.
1386        //
1387        // NOTE: layer transactions have taken place already, so we use their
1388        // drawing state. However, SurfaceFlinger's own transaction has not
1389        // happened yet, so we must use the current state layer list
1390        // (soon to become the drawing state list).
1391        //
1392        sp<const DisplayDevice> disp;
1393        uint32_t currentlayerStack = 0;
1394        for (size_t i=0; i<count; i++) {
1395            // NOTE: we rely on the fact that layers are sorted by
1396            // layerStack first (so we don't have to traverse the list
1397            // of displays for every layer).
1398            const sp<Layer>& layer(currentLayers[i]);
1399            uint32_t layerStack = layer->getDrawingState().layerStack;
1400            if (i==0 || currentlayerStack != layerStack) {
1401                currentlayerStack = layerStack;
1402                // figure out if this layerstack is mirrored
1403                // (more than one display) if so, pick the default display,
1404                // if not, pick the only display it's on.
1405                disp.clear();
1406                for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1407                    sp<const DisplayDevice> hw(mDisplays[dpy]);
1408                    if (hw->getLayerStack() == currentlayerStack) {
1409                        if (disp == NULL) {
1410                            disp = hw;
1411                        } else {
1412                            disp = NULL;
1413                            break;
1414                        }
1415                    }
1416                }
1417            }
1418            if (disp == NULL) {
1419                // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
1420                // redraw after transform hint changes. See bug 8508397.
1421
1422                // could be null when this layer is using a layerStack
1423                // that is not visible on any display. Also can occur at
1424                // screen off/on times.
1425                disp = getDefaultDisplayDevice();
1426            }
1427            layer->updateTransformHint(disp);
1428        }
1429    }
1430
1431
1432    /*
1433     * Perform our own transaction if needed
1434     */
1435
1436    const LayerVector& layers(mDrawingState.layersSortedByZ);
1437    if (currentLayers.size() > layers.size()) {
1438        // layers have been added
1439        mVisibleRegionsDirty = true;
1440    }
1441
1442    // some layers might have been removed, so
1443    // we need to update the regions they're exposing.
1444    if (mLayersRemoved) {
1445        mLayersRemoved = false;
1446        mVisibleRegionsDirty = true;
1447        const size_t count = layers.size();
1448        for (size_t i=0 ; i<count ; i++) {
1449            const sp<Layer>& layer(layers[i]);
1450            if (currentLayers.indexOf(layer) < 0) {
1451                // this layer is not visible anymore
1452                // TODO: we could traverse the tree from front to back and
1453                //       compute the actual visible region
1454                // TODO: we could cache the transformed region
1455                const Layer::State& s(layer->getDrawingState());
1456                Region visibleReg = s.transform.transform(
1457                        Region(Rect(s.active.w, s.active.h)));
1458                invalidateLayerStack(s.layerStack, visibleReg);
1459            }
1460        }
1461    }
1462
1463    commitTransaction();
1464}
1465
1466void SurfaceFlinger::commitTransaction()
1467{
1468    if (!mLayersPendingRemoval.isEmpty()) {
1469        // Notify removed layers now that they can't be drawn from
1470        for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
1471            mLayersPendingRemoval[i]->onRemoved();
1472        }
1473        mLayersPendingRemoval.clear();
1474    }
1475
1476    // If this transaction is part of a window animation then the next frame
1477    // we composite should be considered an animation as well.
1478    mAnimCompositionPending = mAnimTransactionPending;
1479
1480    mDrawingState = mCurrentState;
1481    mTransactionPending = false;
1482    mAnimTransactionPending = false;
1483    mTransactionCV.broadcast();
1484}
1485
1486void SurfaceFlinger::computeVisibleRegions(
1487        const LayerVector& currentLayers, uint32_t layerStack,
1488        Region& outDirtyRegion, Region& outOpaqueRegion)
1489{
1490    ATRACE_CALL();
1491
1492    Region aboveOpaqueLayers;
1493    Region aboveCoveredLayers;
1494    Region dirty;
1495
1496    outDirtyRegion.clear();
1497
1498    size_t i = currentLayers.size();
1499    while (i--) {
1500        const sp<Layer>& layer = currentLayers[i];
1501
1502        // start with the whole surface at its current location
1503        const Layer::State& s(layer->getDrawingState());
1504
1505        // only consider the layers on the given layer stack
1506        if (s.layerStack != layerStack)
1507            continue;
1508
1509        /*
1510         * opaqueRegion: area of a surface that is fully opaque.
1511         */
1512        Region opaqueRegion;
1513
1514        /*
1515         * visibleRegion: area of a surface that is visible on screen
1516         * and not fully transparent. This is essentially the layer's
1517         * footprint minus the opaque regions above it.
1518         * Areas covered by a translucent surface are considered visible.
1519         */
1520        Region visibleRegion;
1521
1522        /*
1523         * coveredRegion: area of a surface that is covered by all
1524         * visible regions above it (which includes the translucent areas).
1525         */
1526        Region coveredRegion;
1527
1528        /*
1529         * transparentRegion: area of a surface that is hinted to be completely
1530         * transparent. This is only used to tell when the layer has no visible
1531         * non-transparent regions and can be removed from the layer list. It
1532         * does not affect the visibleRegion of this layer or any layers
1533         * beneath it. The hint may not be correct if apps don't respect the
1534         * SurfaceView restrictions (which, sadly, some don't).
1535         */
1536        Region transparentRegion;
1537
1538
1539        // handle hidden surfaces by setting the visible region to empty
1540        if (CC_LIKELY(layer->isVisible())) {
1541            const bool translucent = !layer->isOpaque();
1542            Rect bounds(s.transform.transform(layer->computeBounds()));
1543            visibleRegion.set(bounds);
1544            if (!visibleRegion.isEmpty()) {
1545                // Remove the transparent area from the visible region
1546                if (translucent) {
1547                    const Transform tr(s.transform);
1548                    if (tr.transformed()) {
1549                        if (tr.preserveRects()) {
1550                            // transform the transparent region
1551                            transparentRegion = tr.transform(s.activeTransparentRegion);
1552                        } else {
1553                            // transformation too complex, can't do the
1554                            // transparent region optimization.
1555                            transparentRegion.clear();
1556                        }
1557                    } else {
1558                        transparentRegion = s.activeTransparentRegion;
1559                    }
1560                }
1561
1562                // compute the opaque region
1563                const int32_t layerOrientation = s.transform.getOrientation();
1564                if (s.alpha==255 && !translucent &&
1565                        ((layerOrientation & Transform::ROT_INVALID) == false)) {
1566                    // the opaque region is the layer's footprint
1567                    opaqueRegion = visibleRegion;
1568                }
1569            }
1570        }
1571
1572        // Clip the covered region to the visible region
1573        coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1574
1575        // Update aboveCoveredLayers for next (lower) layer
1576        aboveCoveredLayers.orSelf(visibleRegion);
1577
1578        // subtract the opaque region covered by the layers above us
1579        visibleRegion.subtractSelf(aboveOpaqueLayers);
1580
1581        // compute this layer's dirty region
1582        if (layer->contentDirty) {
1583            // we need to invalidate the whole region
1584            dirty = visibleRegion;
1585            // as well, as the old visible region
1586            dirty.orSelf(layer->visibleRegion);
1587            layer->contentDirty = false;
1588        } else {
1589            /* compute the exposed region:
1590             *   the exposed region consists of two components:
1591             *   1) what's VISIBLE now and was COVERED before
1592             *   2) what's EXPOSED now less what was EXPOSED before
1593             *
1594             * note that (1) is conservative, we start with the whole
1595             * visible region but only keep what used to be covered by
1596             * something -- which mean it may have been exposed.
1597             *
1598             * (2) handles areas that were not covered by anything but got
1599             * exposed because of a resize.
1600             */
1601            const Region newExposed = visibleRegion - coveredRegion;
1602            const Region oldVisibleRegion = layer->visibleRegion;
1603            const Region oldCoveredRegion = layer->coveredRegion;
1604            const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
1605            dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
1606        }
1607        dirty.subtractSelf(aboveOpaqueLayers);
1608
1609        // accumulate to the screen dirty region
1610        outDirtyRegion.orSelf(dirty);
1611
1612        // Update aboveOpaqueLayers for next (lower) layer
1613        aboveOpaqueLayers.orSelf(opaqueRegion);
1614
1615        // Store the visible region in screen space
1616        layer->setVisibleRegion(visibleRegion);
1617        layer->setCoveredRegion(coveredRegion);
1618        layer->setVisibleNonTransparentRegion(
1619                visibleRegion.subtract(transparentRegion));
1620    }
1621
1622    outOpaqueRegion = aboveOpaqueLayers;
1623}
1624
1625void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
1626        const Region& dirty) {
1627    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1628        const sp<DisplayDevice>& hw(mDisplays[dpy]);
1629        if (hw->getLayerStack() == layerStack) {
1630            hw->dirtyRegion.orSelf(dirty);
1631        }
1632    }
1633}
1634
1635void SurfaceFlinger::handlePageFlip()
1636{
1637    Region dirtyRegion;
1638
1639    bool visibleRegions = false;
1640    const LayerVector& layers(mDrawingState.layersSortedByZ);
1641    const size_t count = layers.size();
1642    for (size_t i=0 ; i<count ; i++) {
1643        const sp<Layer>& layer(layers[i]);
1644        const Region dirty(layer->latchBuffer(visibleRegions));
1645        const Layer::State& s(layer->getDrawingState());
1646        invalidateLayerStack(s.layerStack, dirty);
1647    }
1648
1649    mVisibleRegionsDirty |= visibleRegions;
1650}
1651
1652void SurfaceFlinger::invalidateHwcGeometry()
1653{
1654    mHwWorkListDirty = true;
1655}
1656
1657
1658void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& hw,
1659        const Region& inDirtyRegion)
1660{
1661    Region dirtyRegion(inDirtyRegion);
1662
1663    // compute the invalid region
1664    hw->swapRegion.orSelf(dirtyRegion);
1665
1666    uint32_t flags = hw->getFlags();
1667    if (flags & DisplayDevice::SWAP_RECTANGLE) {
1668        // we can redraw only what's dirty, but since SWAP_RECTANGLE only
1669        // takes a rectangle, we must make sure to update that whole
1670        // rectangle in that case
1671        dirtyRegion.set(hw->swapRegion.bounds());
1672    } else {
1673        if (flags & DisplayDevice::PARTIAL_UPDATES) {
1674            // We need to redraw the rectangle that will be updated
1675            // (pushed to the framebuffer).
1676            // This is needed because PARTIAL_UPDATES only takes one
1677            // rectangle instead of a region (see DisplayDevice::flip())
1678            dirtyRegion.set(hw->swapRegion.bounds());
1679        } else {
1680            // we need to redraw everything (the whole screen)
1681            dirtyRegion.set(hw->bounds());
1682            hw->swapRegion = dirtyRegion;
1683        }
1684    }
1685
1686    if (CC_LIKELY(!mDaltonize && !mHasColorMatrix)) {
1687        doComposeSurfaces(hw, dirtyRegion);
1688    } else {
1689        RenderEngine& engine(getRenderEngine());
1690        mat4 colorMatrix = mColorMatrix;
1691        if (mDaltonize) {
1692            colorMatrix = colorMatrix * mDaltonizer();
1693        }
1694        engine.beginGroup(colorMatrix);
1695        doComposeSurfaces(hw, dirtyRegion);
1696        engine.endGroup();
1697    }
1698
1699    // update the swap region and clear the dirty region
1700    hw->swapRegion.orSelf(dirtyRegion);
1701
1702    // swap buffers (presentation)
1703    hw->swapBuffers(getHwComposer());
1704}
1705
1706void SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty)
1707{
1708    RenderEngine& engine(getRenderEngine());
1709    const int32_t id = hw->getHwcDisplayId();
1710    HWComposer& hwc(getHwComposer());
1711    HWComposer::LayerListIterator cur = hwc.begin(id);
1712    const HWComposer::LayerListIterator end = hwc.end(id);
1713
1714    bool hasGlesComposition = hwc.hasGlesComposition(id);
1715    if (hasGlesComposition) {
1716        if (!hw->makeCurrent(mEGLDisplay, mEGLContext)) {
1717            ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
1718                  hw->getDisplayName().string());
1719            return;
1720        }
1721
1722        // Never touch the framebuffer if we don't have any framebuffer layers
1723        const bool hasHwcComposition = hwc.hasHwcComposition(id);
1724        if (hasHwcComposition) {
1725            // when using overlays, we assume a fully transparent framebuffer
1726            // NOTE: we could reduce how much we need to clear, for instance
1727            // remove where there are opaque FB layers. however, on some
1728            // GPUs doing a "clean slate" clear might be more efficient.
1729            // We'll revisit later if needed.
1730            engine.clearWithColor(0, 0, 0, 0);
1731        } else {
1732            // we start with the whole screen area
1733            const Region bounds(hw->getBounds());
1734
1735            // we remove the scissor part
1736            // we're left with the letterbox region
1737            // (common case is that letterbox ends-up being empty)
1738            const Region letterbox(bounds.subtract(hw->getScissor()));
1739
1740            // compute the area to clear
1741            Region region(hw->undefinedRegion.merge(letterbox));
1742
1743            // but limit it to the dirty region
1744            region.andSelf(dirty);
1745
1746            // screen is already cleared here
1747            if (!region.isEmpty()) {
1748                // can happen with SurfaceView
1749                drawWormhole(hw, region);
1750            }
1751        }
1752
1753        if (hw->getDisplayType() != DisplayDevice::DISPLAY_PRIMARY) {
1754            // just to be on the safe side, we don't set the
1755            // scissor on the main display. It should never be needed
1756            // anyways (though in theory it could since the API allows it).
1757            const Rect& bounds(hw->getBounds());
1758            const Rect& scissor(hw->getScissor());
1759            if (scissor != bounds) {
1760                // scissor doesn't match the screen's dimensions, so we
1761                // need to clear everything outside of it and enable
1762                // the GL scissor so we don't draw anything where we shouldn't
1763
1764                // enable scissor for this frame
1765                const uint32_t height = hw->getHeight();
1766                engine.setScissor(scissor.left, height - scissor.bottom,
1767                        scissor.getWidth(), scissor.getHeight());
1768            }
1769        }
1770    }
1771
1772    /*
1773     * and then, render the layers targeted at the framebuffer
1774     */
1775
1776    const Vector< sp<Layer> >& layers(hw->getVisibleLayersSortedByZ());
1777    const size_t count = layers.size();
1778    const Transform& tr = hw->getTransform();
1779    if (cur != end) {
1780        // we're using h/w composer
1781        for (size_t i=0 ; i<count && cur!=end ; ++i, ++cur) {
1782            const sp<Layer>& layer(layers[i]);
1783            const Region clip(dirty.intersect(tr.transform(layer->visibleRegion)));
1784            if (!clip.isEmpty()) {
1785                switch (cur->getCompositionType()) {
1786                    case HWC_OVERLAY: {
1787                        const Layer::State& state(layer->getDrawingState());
1788                        if ((cur->getHints() & HWC_HINT_CLEAR_FB)
1789                                && i
1790                                && layer->isOpaque() && (state.alpha == 0xFF)
1791                                && hasGlesComposition) {
1792                            // never clear the very first layer since we're
1793                            // guaranteed the FB is already cleared
1794                            layer->clearWithOpenGL(hw, clip);
1795                        }
1796                        break;
1797                    }
1798                    case HWC_FRAMEBUFFER: {
1799                        layer->draw(hw, clip);
1800                        break;
1801                    }
1802                    case HWC_FRAMEBUFFER_TARGET: {
1803                        // this should not happen as the iterator shouldn't
1804                        // let us get there.
1805                        ALOGW("HWC_FRAMEBUFFER_TARGET found in hwc list (index=%d)", i);
1806                        break;
1807                    }
1808                }
1809            }
1810            layer->setAcquireFence(hw, *cur);
1811        }
1812    } else {
1813        // we're not using h/w composer
1814        for (size_t i=0 ; i<count ; ++i) {
1815            const sp<Layer>& layer(layers[i]);
1816            const Region clip(dirty.intersect(
1817                    tr.transform(layer->visibleRegion)));
1818            if (!clip.isEmpty()) {
1819                layer->draw(hw, clip);
1820            }
1821        }
1822    }
1823
1824    // disable scissor at the end of the frame
1825    engine.disableScissor();
1826}
1827
1828void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const {
1829    const int32_t height = hw->getHeight();
1830    RenderEngine& engine(getRenderEngine());
1831    engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
1832}
1833
1834void SurfaceFlinger::addClientLayer(const sp<Client>& client,
1835        const sp<IBinder>& handle,
1836        const sp<IGraphicBufferProducer>& gbc,
1837        const sp<Layer>& lbc)
1838{
1839    // attach this layer to the client
1840    client->attachLayer(handle, lbc);
1841
1842    // add this layer to the current state list
1843    Mutex::Autolock _l(mStateLock);
1844    mCurrentState.layersSortedByZ.add(lbc);
1845    mGraphicBufferProducerList.add(gbc->asBinder());
1846}
1847
1848status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
1849    Mutex::Autolock _l(mStateLock);
1850    ssize_t index = mCurrentState.layersSortedByZ.remove(layer);
1851    if (index >= 0) {
1852        mLayersPendingRemoval.push(layer);
1853        mLayersRemoved = true;
1854        setTransactionFlags(eTransactionNeeded);
1855        return NO_ERROR;
1856    }
1857    return status_t(index);
1858}
1859
1860uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t flags) {
1861    return android_atomic_release_load(&mTransactionFlags);
1862}
1863
1864uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
1865    return android_atomic_and(~flags, &mTransactionFlags) & flags;
1866}
1867
1868uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
1869    uint32_t old = android_atomic_or(flags, &mTransactionFlags);
1870    if ((old & flags)==0) { // wake the server up
1871        signalTransaction();
1872    }
1873    return old;
1874}
1875
1876void SurfaceFlinger::setTransactionState(
1877        const Vector<ComposerState>& state,
1878        const Vector<DisplayState>& displays,
1879        uint32_t flags)
1880{
1881    ATRACE_CALL();
1882    Mutex::Autolock _l(mStateLock);
1883    uint32_t transactionFlags = 0;
1884
1885    if (flags & eAnimation) {
1886        // For window updates that are part of an animation we must wait for
1887        // previous animation "frames" to be handled.
1888        while (mAnimTransactionPending) {
1889            status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
1890            if (CC_UNLIKELY(err != NO_ERROR)) {
1891                // just in case something goes wrong in SF, return to the
1892                // caller after a few seconds.
1893                ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
1894                        "waiting for previous animation frame");
1895                mAnimTransactionPending = false;
1896                break;
1897            }
1898        }
1899    }
1900
1901    size_t count = displays.size();
1902    for (size_t i=0 ; i<count ; i++) {
1903        const DisplayState& s(displays[i]);
1904        transactionFlags |= setDisplayStateLocked(s);
1905    }
1906
1907    count = state.size();
1908    for (size_t i=0 ; i<count ; i++) {
1909        const ComposerState& s(state[i]);
1910        // Here we need to check that the interface we're given is indeed
1911        // one of our own. A malicious client could give us a NULL
1912        // IInterface, or one of its own or even one of our own but a
1913        // different type. All these situations would cause us to crash.
1914        //
1915        // NOTE: it would be better to use RTTI as we could directly check
1916        // that we have a Client*. however, RTTI is disabled in Android.
1917        if (s.client != NULL) {
1918            sp<IBinder> binder = s.client->asBinder();
1919            if (binder != NULL) {
1920                String16 desc(binder->getInterfaceDescriptor());
1921                if (desc == ISurfaceComposerClient::descriptor) {
1922                    sp<Client> client( static_cast<Client *>(s.client.get()) );
1923                    transactionFlags |= setClientStateLocked(client, s.state);
1924                }
1925            }
1926        }
1927    }
1928
1929    if (transactionFlags) {
1930        // this triggers the transaction
1931        setTransactionFlags(transactionFlags);
1932
1933        // if this is a synchronous transaction, wait for it to take effect
1934        // before returning.
1935        if (flags & eSynchronous) {
1936            mTransactionPending = true;
1937        }
1938        if (flags & eAnimation) {
1939            mAnimTransactionPending = true;
1940        }
1941        while (mTransactionPending) {
1942            status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
1943            if (CC_UNLIKELY(err != NO_ERROR)) {
1944                // just in case something goes wrong in SF, return to the
1945                // called after a few seconds.
1946                ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
1947                mTransactionPending = false;
1948                break;
1949            }
1950        }
1951    }
1952}
1953
1954uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s)
1955{
1956    ssize_t dpyIdx = mCurrentState.displays.indexOfKey(s.token);
1957    if (dpyIdx < 0)
1958        return 0;
1959
1960    uint32_t flags = 0;
1961    DisplayDeviceState& disp(mCurrentState.displays.editValueAt(dpyIdx));
1962    if (disp.isValid()) {
1963        const uint32_t what = s.what;
1964        if (what & DisplayState::eSurfaceChanged) {
1965            if (disp.surface->asBinder() != s.surface->asBinder()) {
1966                disp.surface = s.surface;
1967                flags |= eDisplayTransactionNeeded;
1968            }
1969        }
1970        if (what & DisplayState::eLayerStackChanged) {
1971            if (disp.layerStack != s.layerStack) {
1972                disp.layerStack = s.layerStack;
1973                flags |= eDisplayTransactionNeeded;
1974            }
1975        }
1976        if (what & DisplayState::eDisplayProjectionChanged) {
1977            if (disp.orientation != s.orientation) {
1978                disp.orientation = s.orientation;
1979                flags |= eDisplayTransactionNeeded;
1980            }
1981            if (disp.frame != s.frame) {
1982                disp.frame = s.frame;
1983                flags |= eDisplayTransactionNeeded;
1984            }
1985            if (disp.viewport != s.viewport) {
1986                disp.viewport = s.viewport;
1987                flags |= eDisplayTransactionNeeded;
1988            }
1989        }
1990    }
1991    return flags;
1992}
1993
1994uint32_t SurfaceFlinger::setClientStateLocked(
1995        const sp<Client>& client,
1996        const layer_state_t& s)
1997{
1998    uint32_t flags = 0;
1999    sp<Layer> layer(client->getLayerUser(s.surface));
2000    if (layer != 0) {
2001        const uint32_t what = s.what;
2002        if (what & layer_state_t::ePositionChanged) {
2003            if (layer->setPosition(s.x, s.y))
2004                flags |= eTraversalNeeded;
2005        }
2006        if (what & layer_state_t::eLayerChanged) {
2007            // NOTE: index needs to be calculated before we update the state
2008            ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2009            if (layer->setLayer(s.z)) {
2010                mCurrentState.layersSortedByZ.removeAt(idx);
2011                mCurrentState.layersSortedByZ.add(layer);
2012                // we need traversal (state changed)
2013                // AND transaction (list changed)
2014                flags |= eTransactionNeeded|eTraversalNeeded;
2015            }
2016        }
2017        if (what & layer_state_t::eSizeChanged) {
2018            if (layer->setSize(s.w, s.h)) {
2019                flags |= eTraversalNeeded;
2020            }
2021        }
2022        if (what & layer_state_t::eAlphaChanged) {
2023            if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
2024                flags |= eTraversalNeeded;
2025        }
2026        if (what & layer_state_t::eMatrixChanged) {
2027            if (layer->setMatrix(s.matrix))
2028                flags |= eTraversalNeeded;
2029        }
2030        if (what & layer_state_t::eTransparentRegionChanged) {
2031            if (layer->setTransparentRegionHint(s.transparentRegion))
2032                flags |= eTraversalNeeded;
2033        }
2034        if (what & layer_state_t::eVisibilityChanged) {
2035            if (layer->setFlags(s.flags, s.mask))
2036                flags |= eTraversalNeeded;
2037        }
2038        if (what & layer_state_t::eCropChanged) {
2039            if (layer->setCrop(s.crop))
2040                flags |= eTraversalNeeded;
2041        }
2042        if (what & layer_state_t::eLayerStackChanged) {
2043            // NOTE: index needs to be calculated before we update the state
2044            ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
2045            if (layer->setLayerStack(s.layerStack)) {
2046                mCurrentState.layersSortedByZ.removeAt(idx);
2047                mCurrentState.layersSortedByZ.add(layer);
2048                // we need traversal (state changed)
2049                // AND transaction (list changed)
2050                flags |= eTransactionNeeded|eTraversalNeeded;
2051            }
2052        }
2053    }
2054    return flags;
2055}
2056
2057status_t SurfaceFlinger::createLayer(
2058        const String8& name,
2059        const sp<Client>& client,
2060        uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
2061        sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp)
2062{
2063    //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string());
2064    if (int32_t(w|h) < 0) {
2065        ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
2066                int(w), int(h));
2067        return BAD_VALUE;
2068    }
2069
2070    status_t result = NO_ERROR;
2071
2072    sp<Layer> layer;
2073
2074    switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
2075        case ISurfaceComposerClient::eFXSurfaceNormal:
2076            result = createNormalLayer(client,
2077                    name, w, h, flags, format,
2078                    handle, gbp, &layer);
2079            break;
2080        case ISurfaceComposerClient::eFXSurfaceDim:
2081            result = createDimLayer(client,
2082                    name, w, h, flags,
2083                    handle, gbp, &layer);
2084            break;
2085        default:
2086            result = BAD_VALUE;
2087            break;
2088    }
2089
2090    if (result == NO_ERROR) {
2091        addClientLayer(client, *handle, *gbp, layer);
2092        setTransactionFlags(eTransactionNeeded);
2093    }
2094    return result;
2095}
2096
2097status_t SurfaceFlinger::createNormalLayer(const sp<Client>& client,
2098        const String8& name, uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
2099        sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2100{
2101    // initialize the surfaces
2102    switch (format) {
2103    case PIXEL_FORMAT_TRANSPARENT:
2104    case PIXEL_FORMAT_TRANSLUCENT:
2105        format = PIXEL_FORMAT_RGBA_8888;
2106        break;
2107    case PIXEL_FORMAT_OPAQUE:
2108#ifdef NO_RGBX_8888
2109        format = PIXEL_FORMAT_RGB_565;
2110#else
2111        format = PIXEL_FORMAT_RGBX_8888;
2112#endif
2113        break;
2114    }
2115
2116#ifdef NO_RGBX_8888
2117    if (format == PIXEL_FORMAT_RGBX_8888)
2118        format = PIXEL_FORMAT_RGBA_8888;
2119#endif
2120
2121    *outLayer = new Layer(this, client, name, w, h, flags);
2122    status_t err = (*outLayer)->setBuffers(w, h, format, flags);
2123    if (err == NO_ERROR) {
2124        *handle = (*outLayer)->getHandle();
2125        *gbp = (*outLayer)->getBufferQueue();
2126    }
2127
2128    ALOGE_IF(err, "createNormalLayer() failed (%s)", strerror(-err));
2129    return err;
2130}
2131
2132status_t SurfaceFlinger::createDimLayer(const sp<Client>& client,
2133        const String8& name, uint32_t w, uint32_t h, uint32_t flags,
2134        sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp, sp<Layer>* outLayer)
2135{
2136    *outLayer = new LayerDim(this, client, name, w, h, flags);
2137    *handle = (*outLayer)->getHandle();
2138    *gbp = (*outLayer)->getBufferQueue();
2139    return NO_ERROR;
2140}
2141
2142status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
2143{
2144    // called by the window manager when it wants to remove a Layer
2145    status_t err = NO_ERROR;
2146    sp<Layer> l(client->getLayerUser(handle));
2147    if (l != NULL) {
2148        err = removeLayer(l);
2149        ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2150                "error removing layer=%p (%s)", l.get(), strerror(-err));
2151    }
2152    return err;
2153}
2154
2155status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
2156{
2157    // called by ~LayerCleaner() when all references to the IBinder (handle)
2158    // are gone
2159    status_t err = NO_ERROR;
2160    sp<Layer> l(layer.promote());
2161    if (l != NULL) {
2162        err = removeLayer(l);
2163        ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
2164                "error removing layer=%p (%s)", l.get(), strerror(-err));
2165    }
2166    return err;
2167}
2168
2169// ---------------------------------------------------------------------------
2170
2171void SurfaceFlinger::onInitializeDisplays() {
2172    // reset screen orientation and use primary layer stack
2173    Vector<ComposerState> state;
2174    Vector<DisplayState> displays;
2175    DisplayState d;
2176    d.what = DisplayState::eDisplayProjectionChanged |
2177             DisplayState::eLayerStackChanged;
2178    d.token = mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY];
2179    d.layerStack = 0;
2180    d.orientation = DisplayState::eOrientationDefault;
2181    d.frame.makeInvalid();
2182    d.viewport.makeInvalid();
2183    displays.add(d);
2184    setTransactionState(state, displays, 0);
2185    onScreenAcquired(getDefaultDisplayDevice());
2186
2187    const nsecs_t period =
2188            getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
2189    mAnimFrameTracker.setDisplayRefreshPeriod(period);
2190}
2191
2192void SurfaceFlinger::initializeDisplays() {
2193    class MessageScreenInitialized : public MessageBase {
2194        SurfaceFlinger* flinger;
2195    public:
2196        MessageScreenInitialized(SurfaceFlinger* flinger) : flinger(flinger) { }
2197        virtual bool handler() {
2198            flinger->onInitializeDisplays();
2199            return true;
2200        }
2201    };
2202    sp<MessageBase> msg = new MessageScreenInitialized(this);
2203    postMessageAsync(msg);  // we may be called from main thread, use async message
2204}
2205
2206
2207void SurfaceFlinger::onScreenAcquired(const sp<const DisplayDevice>& hw) {
2208    ALOGD("Screen acquired, type=%d flinger=%p", hw->getDisplayType(), this);
2209    if (hw->isScreenAcquired()) {
2210        // this is expected, e.g. when power manager wakes up during boot
2211        ALOGD(" screen was previously acquired");
2212        return;
2213    }
2214
2215    hw->acquireScreen();
2216    int32_t type = hw->getDisplayType();
2217    if (type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2218        // built-in display, tell the HWC
2219        getHwComposer().acquire(type);
2220
2221        if (type == DisplayDevice::DISPLAY_PRIMARY) {
2222            // FIXME: eventthread only knows about the main display right now
2223            mEventThread->onScreenAcquired();
2224
2225            resyncToHardwareVsync(true);
2226        }
2227    }
2228    mVisibleRegionsDirty = true;
2229    repaintEverything();
2230}
2231
2232void SurfaceFlinger::onScreenReleased(const sp<const DisplayDevice>& hw) {
2233    ALOGD("Screen released, type=%d flinger=%p", hw->getDisplayType(), this);
2234    if (!hw->isScreenAcquired()) {
2235        ALOGD(" screen was previously released");
2236        return;
2237    }
2238
2239    hw->releaseScreen();
2240    int32_t type = hw->getDisplayType();
2241    if (type < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
2242        if (type == DisplayDevice::DISPLAY_PRIMARY) {
2243            disableHardwareVsync(true); // also cancels any in-progress resync
2244
2245            // FIXME: eventthread only knows about the main display right now
2246            mEventThread->onScreenReleased();
2247        }
2248
2249        // built-in display, tell the HWC
2250        getHwComposer().release(type);
2251    }
2252    mVisibleRegionsDirty = true;
2253    // from this point on, SF will stop drawing on this display
2254}
2255
2256void SurfaceFlinger::unblank(const sp<IBinder>& display) {
2257    class MessageScreenAcquired : public MessageBase {
2258        SurfaceFlinger& mFlinger;
2259        sp<IBinder> mDisplay;
2260    public:
2261        MessageScreenAcquired(SurfaceFlinger& flinger,
2262                const sp<IBinder>& disp) : mFlinger(flinger), mDisplay(disp) { }
2263        virtual bool handler() {
2264            const sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
2265            if (hw == NULL) {
2266                ALOGE("Attempt to unblank null display %p", mDisplay.get());
2267            } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
2268                ALOGW("Attempt to unblank virtual display");
2269            } else {
2270                mFlinger.onScreenAcquired(hw);
2271            }
2272            return true;
2273        }
2274    };
2275    sp<MessageBase> msg = new MessageScreenAcquired(*this, display);
2276    postMessageSync(msg);
2277}
2278
2279void SurfaceFlinger::blank(const sp<IBinder>& display) {
2280    class MessageScreenReleased : public MessageBase {
2281        SurfaceFlinger& mFlinger;
2282        sp<IBinder> mDisplay;
2283    public:
2284        MessageScreenReleased(SurfaceFlinger& flinger,
2285                const sp<IBinder>& disp) : mFlinger(flinger), mDisplay(disp) { }
2286        virtual bool handler() {
2287            const sp<DisplayDevice> hw(mFlinger.getDisplayDevice(mDisplay));
2288            if (hw == NULL) {
2289                ALOGE("Attempt to blank null display %p", mDisplay.get());
2290            } else if (hw->getDisplayType() >= DisplayDevice::DISPLAY_VIRTUAL) {
2291                ALOGW("Attempt to blank virtual display");
2292            } else {
2293                mFlinger.onScreenReleased(hw);
2294            }
2295            return true;
2296        }
2297    };
2298    sp<MessageBase> msg = new MessageScreenReleased(*this, display);
2299    postMessageSync(msg);
2300}
2301
2302// ---------------------------------------------------------------------------
2303
2304status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
2305{
2306    String8 result;
2307
2308    IPCThreadState* ipc = IPCThreadState::self();
2309    const int pid = ipc->getCallingPid();
2310    const int uid = ipc->getCallingUid();
2311    if ((uid != AID_SHELL) &&
2312            !PermissionCache::checkPermission(sDump, pid, uid)) {
2313        result.appendFormat("Permission Denial: "
2314                "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
2315    } else {
2316        // Try to get the main lock, but don't insist if we can't
2317        // (this would indicate SF is stuck, but we want to be able to
2318        // print something in dumpsys).
2319        int retry = 3;
2320        while (mStateLock.tryLock()<0 && --retry>=0) {
2321            usleep(1000000);
2322        }
2323        const bool locked(retry >= 0);
2324        if (!locked) {
2325            result.append(
2326                    "SurfaceFlinger appears to be unresponsive, "
2327                    "dumping anyways (no locks held)\n");
2328        }
2329
2330        bool dumpAll = true;
2331        size_t index = 0;
2332        size_t numArgs = args.size();
2333        if (numArgs) {
2334            if ((index < numArgs) &&
2335                    (args[index] == String16("--list"))) {
2336                index++;
2337                listLayersLocked(args, index, result);
2338                dumpAll = false;
2339            }
2340
2341            if ((index < numArgs) &&
2342                    (args[index] == String16("--latency"))) {
2343                index++;
2344                dumpStatsLocked(args, index, result);
2345                dumpAll = false;
2346            }
2347
2348            if ((index < numArgs) &&
2349                    (args[index] == String16("--latency-clear"))) {
2350                index++;
2351                clearStatsLocked(args, index, result);
2352                dumpAll = false;
2353            }
2354        }
2355
2356        if (dumpAll) {
2357            dumpAllLocked(args, index, result);
2358        }
2359
2360        if (locked) {
2361            mStateLock.unlock();
2362        }
2363    }
2364    write(fd, result.string(), result.size());
2365    return NO_ERROR;
2366}
2367
2368void SurfaceFlinger::listLayersLocked(const Vector<String16>& args, size_t& index,
2369        String8& result) const
2370{
2371    const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2372    const size_t count = currentLayers.size();
2373    for (size_t i=0 ; i<count ; i++) {
2374        const sp<Layer>& layer(currentLayers[i]);
2375        result.appendFormat("%s\n", layer->getName().string());
2376    }
2377}
2378
2379void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
2380        String8& result) const
2381{
2382    String8 name;
2383    if (index < args.size()) {
2384        name = String8(args[index]);
2385        index++;
2386    }
2387
2388    const nsecs_t period =
2389            getHwComposer().getRefreshPeriod(HWC_DISPLAY_PRIMARY);
2390    result.appendFormat("%lld\n", period);
2391
2392    if (name.isEmpty()) {
2393        mAnimFrameTracker.dump(result);
2394    } else {
2395        const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2396        const size_t count = currentLayers.size();
2397        for (size_t i=0 ; i<count ; i++) {
2398            const sp<Layer>& layer(currentLayers[i]);
2399            if (name == layer->getName()) {
2400                layer->dumpStats(result);
2401            }
2402        }
2403    }
2404}
2405
2406void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
2407        String8& result)
2408{
2409    String8 name;
2410    if (index < args.size()) {
2411        name = String8(args[index]);
2412        index++;
2413    }
2414
2415    const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2416    const size_t count = currentLayers.size();
2417    for (size_t i=0 ; i<count ; i++) {
2418        const sp<Layer>& layer(currentLayers[i]);
2419        if (name.isEmpty() || (name == layer->getName())) {
2420            layer->clearStats();
2421        }
2422    }
2423
2424    mAnimFrameTracker.clear();
2425}
2426
2427// This should only be called from the main thread.  Otherwise it would need
2428// the lock and should use mCurrentState rather than mDrawingState.
2429void SurfaceFlinger::logFrameStats() {
2430    const LayerVector& drawingLayers = mDrawingState.layersSortedByZ;
2431    const size_t count = drawingLayers.size();
2432    for (size_t i=0 ; i<count ; i++) {
2433        const sp<Layer>& layer(drawingLayers[i]);
2434        layer->logFrameStats();
2435    }
2436
2437    mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
2438}
2439
2440/*static*/ void SurfaceFlinger::appendSfConfigString(String8& result)
2441{
2442    static const char* config =
2443            " [sf"
2444#ifdef NO_RGBX_8888
2445            " NO_RGBX_8888"
2446#endif
2447#ifdef HAS_CONTEXT_PRIORITY
2448            " HAS_CONTEXT_PRIORITY"
2449#endif
2450#ifdef NEVER_DEFAULT_TO_ASYNC_MODE
2451            " NEVER_DEFAULT_TO_ASYNC_MODE"
2452#endif
2453#ifdef TARGET_DISABLE_TRIPLE_BUFFERING
2454            " TARGET_DISABLE_TRIPLE_BUFFERING"
2455#endif
2456            "]";
2457    result.append(config);
2458}
2459
2460void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
2461        String8& result) const
2462{
2463    bool colorize = false;
2464    if (index < args.size()
2465            && (args[index] == String16("--color"))) {
2466        colorize = true;
2467        index++;
2468    }
2469
2470    Colorizer colorizer(colorize);
2471
2472    // figure out if we're stuck somewhere
2473    const nsecs_t now = systemTime();
2474    const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
2475    const nsecs_t inTransaction(mDebugInTransaction);
2476    nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
2477    nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
2478
2479    /*
2480     * Dump library configuration.
2481     */
2482
2483    colorizer.bold(result);
2484    result.append("Build configuration:");
2485    colorizer.reset(result);
2486    appendSfConfigString(result);
2487    appendUiConfigString(result);
2488    appendGuiConfigString(result);
2489    result.append("\n");
2490
2491    colorizer.bold(result);
2492    result.append("Sync configuration: ");
2493    colorizer.reset(result);
2494    result.append(SyncFeatures::getInstance().toString());
2495    result.append("\n");
2496
2497    /*
2498     * Dump the visible layer list
2499     */
2500    const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
2501    const size_t count = currentLayers.size();
2502    colorizer.bold(result);
2503    result.appendFormat("Visible layers (count = %d)\n", count);
2504    colorizer.reset(result);
2505    for (size_t i=0 ; i<count ; i++) {
2506        const sp<Layer>& layer(currentLayers[i]);
2507        layer->dump(result, colorizer);
2508    }
2509
2510    /*
2511     * Dump Display state
2512     */
2513
2514    colorizer.bold(result);
2515    result.appendFormat("Displays (%d entries)\n", mDisplays.size());
2516    colorizer.reset(result);
2517    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
2518        const sp<const DisplayDevice>& hw(mDisplays[dpy]);
2519        hw->dump(result);
2520    }
2521
2522    /*
2523     * Dump SurfaceFlinger global state
2524     */
2525
2526    colorizer.bold(result);
2527    result.append("SurfaceFlinger global state:\n");
2528    colorizer.reset(result);
2529
2530    HWComposer& hwc(getHwComposer());
2531    sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2532
2533    colorizer.bold(result);
2534    result.appendFormat("EGL implementation : %s\n",
2535            eglQueryStringImplementationANDROID(mEGLDisplay, EGL_VERSION));
2536    colorizer.reset(result);
2537    result.appendFormat("%s\n",
2538            eglQueryStringImplementationANDROID(mEGLDisplay, EGL_EXTENSIONS));
2539
2540    mRenderEngine->dump(result);
2541
2542    hw->undefinedRegion.dump(result, "undefinedRegion");
2543    result.appendFormat("  orientation=%d, canDraw=%d\n",
2544            hw->getOrientation(), hw->canDraw());
2545    result.appendFormat(
2546            "  last eglSwapBuffers() time: %f us\n"
2547            "  last transaction time     : %f us\n"
2548            "  transaction-flags         : %08x\n"
2549            "  refresh-rate              : %f fps\n"
2550            "  x-dpi                     : %f\n"
2551            "  y-dpi                     : %f\n"
2552            "  EGL_NATIVE_VISUAL_ID      : %d\n"
2553            "  gpu_to_cpu_unsupported    : %d\n"
2554            ,
2555            mLastSwapBufferTime/1000.0,
2556            mLastTransactionTime/1000.0,
2557            mTransactionFlags,
2558            1e9 / hwc.getRefreshPeriod(HWC_DISPLAY_PRIMARY),
2559            hwc.getDpiX(HWC_DISPLAY_PRIMARY),
2560            hwc.getDpiY(HWC_DISPLAY_PRIMARY),
2561            mEGLNativeVisualId,
2562            !mGpuToCpuSupported);
2563
2564    result.appendFormat("  eglSwapBuffers time: %f us\n",
2565            inSwapBuffersDuration/1000.0);
2566
2567    result.appendFormat("  transaction time: %f us\n",
2568            inTransactionDuration/1000.0);
2569
2570    /*
2571     * VSYNC state
2572     */
2573    mEventThread->dump(result);
2574
2575    /*
2576     * Dump HWComposer state
2577     */
2578    colorizer.bold(result);
2579    result.append("h/w composer state:\n");
2580    colorizer.reset(result);
2581    result.appendFormat("  h/w composer %s and %s\n",
2582            hwc.initCheck()==NO_ERROR ? "present" : "not present",
2583                    (mDebugDisableHWC || mDebugRegion || mDaltonize
2584                            || mHasColorMatrix) ? "disabled" : "enabled");
2585    hwc.dump(result);
2586
2587    /*
2588     * Dump gralloc state
2589     */
2590    const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
2591    alloc.dump(result);
2592}
2593
2594const Vector< sp<Layer> >&
2595SurfaceFlinger::getLayerSortedByZForHwcDisplay(int id) {
2596    // Note: mStateLock is held here
2597    wp<IBinder> dpy;
2598    for (size_t i=0 ; i<mDisplays.size() ; i++) {
2599        if (mDisplays.valueAt(i)->getHwcDisplayId() == id) {
2600            dpy = mDisplays.keyAt(i);
2601            break;
2602        }
2603    }
2604    if (dpy == NULL) {
2605        ALOGE("getLayerSortedByZForHwcDisplay: invalid hwc display id %d", id);
2606        // Just use the primary display so we have something to return
2607        dpy = getBuiltInDisplay(DisplayDevice::DISPLAY_PRIMARY);
2608    }
2609    return getDisplayDevice(dpy)->getVisibleLayersSortedByZ();
2610}
2611
2612bool SurfaceFlinger::startDdmConnection()
2613{
2614    void* libddmconnection_dso =
2615            dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
2616    if (!libddmconnection_dso) {
2617        return false;
2618    }
2619    void (*DdmConnection_start)(const char* name);
2620    DdmConnection_start =
2621            (typeof DdmConnection_start)dlsym(libddmconnection_dso, "DdmConnection_start");
2622    if (!DdmConnection_start) {
2623        dlclose(libddmconnection_dso);
2624        return false;
2625    }
2626    (*DdmConnection_start)(getServiceName());
2627    return true;
2628}
2629
2630status_t SurfaceFlinger::onTransact(
2631    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
2632{
2633    switch (code) {
2634        case CREATE_CONNECTION:
2635        case CREATE_DISPLAY:
2636        case SET_TRANSACTION_STATE:
2637        case BOOT_FINISHED:
2638        case BLANK:
2639        case UNBLANK:
2640        {
2641            // codes that require permission check
2642            IPCThreadState* ipc = IPCThreadState::self();
2643            const int pid = ipc->getCallingPid();
2644            const int uid = ipc->getCallingUid();
2645            if ((uid != AID_GRAPHICS) &&
2646                    !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
2647                ALOGE("Permission Denial: "
2648                        "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2649                return PERMISSION_DENIED;
2650            }
2651            break;
2652        }
2653        case CAPTURE_SCREEN:
2654        {
2655            // codes that require permission check
2656            IPCThreadState* ipc = IPCThreadState::self();
2657            const int pid = ipc->getCallingPid();
2658            const int uid = ipc->getCallingUid();
2659            if ((uid != AID_GRAPHICS) &&
2660                    !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
2661                ALOGE("Permission Denial: "
2662                        "can't read framebuffer pid=%d, uid=%d", pid, uid);
2663                return PERMISSION_DENIED;
2664            }
2665            break;
2666        }
2667    }
2668
2669    status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
2670    if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
2671        CHECK_INTERFACE(ISurfaceComposer, data, reply);
2672        if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
2673            IPCThreadState* ipc = IPCThreadState::self();
2674            const int pid = ipc->getCallingPid();
2675            const int uid = ipc->getCallingUid();
2676            ALOGE("Permission Denial: "
2677                    "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
2678            return PERMISSION_DENIED;
2679        }
2680        int n;
2681        switch (code) {
2682            case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
2683            case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
2684                return NO_ERROR;
2685            case 1002:  // SHOW_UPDATES
2686                n = data.readInt32();
2687                mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
2688                invalidateHwcGeometry();
2689                repaintEverything();
2690                return NO_ERROR;
2691            case 1004:{ // repaint everything
2692                repaintEverything();
2693                return NO_ERROR;
2694            }
2695            case 1005:{ // force transaction
2696                setTransactionFlags(
2697                        eTransactionNeeded|
2698                        eDisplayTransactionNeeded|
2699                        eTraversalNeeded);
2700                return NO_ERROR;
2701            }
2702            case 1006:{ // send empty update
2703                signalRefresh();
2704                return NO_ERROR;
2705            }
2706            case 1008:  // toggle use of hw composer
2707                n = data.readInt32();
2708                mDebugDisableHWC = n ? 1 : 0;
2709                invalidateHwcGeometry();
2710                repaintEverything();
2711                return NO_ERROR;
2712            case 1009:  // toggle use of transform hint
2713                n = data.readInt32();
2714                mDebugDisableTransformHint = n ? 1 : 0;
2715                invalidateHwcGeometry();
2716                repaintEverything();
2717                return NO_ERROR;
2718            case 1010:  // interrogate.
2719                reply->writeInt32(0);
2720                reply->writeInt32(0);
2721                reply->writeInt32(mDebugRegion);
2722                reply->writeInt32(0);
2723                reply->writeInt32(mDebugDisableHWC);
2724                return NO_ERROR;
2725            case 1013: {
2726                Mutex::Autolock _l(mStateLock);
2727                sp<const DisplayDevice> hw(getDefaultDisplayDevice());
2728                reply->writeInt32(hw->getPageFlipCount());
2729                return NO_ERROR;
2730            }
2731            case 1014: {
2732                // daltonize
2733                n = data.readInt32();
2734                switch (n % 10) {
2735                    case 1: mDaltonizer.setType(Daltonizer::protanomaly);   break;
2736                    case 2: mDaltonizer.setType(Daltonizer::deuteranomaly); break;
2737                    case 3: mDaltonizer.setType(Daltonizer::tritanomaly);   break;
2738                }
2739                if (n >= 10) {
2740                    mDaltonizer.setMode(Daltonizer::correction);
2741                } else {
2742                    mDaltonizer.setMode(Daltonizer::simulation);
2743                }
2744                mDaltonize = n > 0;
2745                invalidateHwcGeometry();
2746                repaintEverything();
2747                return NO_ERROR;
2748            }
2749            case 1015: {
2750                // apply a color matrix
2751                n = data.readInt32();
2752                mHasColorMatrix = n ? 1 : 0;
2753                if (n) {
2754                    // color matrix is sent as mat3 matrix followed by vec3
2755                    // offset, then packed into a mat4 where the last row is
2756                    // the offset and extra values are 0
2757                    for (size_t i = 0 ; i < 4; i++) {
2758                      for (size_t j = 0; j < 4; j++) {
2759                          mColorMatrix[i][j] = data.readFloat();
2760                      }
2761                    }
2762                } else {
2763                    mColorMatrix = mat4();
2764                }
2765                invalidateHwcGeometry();
2766                repaintEverything();
2767                return NO_ERROR;
2768            }
2769        }
2770    }
2771    return err;
2772}
2773
2774void SurfaceFlinger::repaintEverything() {
2775    android_atomic_or(1, &mRepaintEverything);
2776    signalTransaction();
2777}
2778
2779// ---------------------------------------------------------------------------
2780// Capture screen into an IGraphiBufferProducer
2781// ---------------------------------------------------------------------------
2782
2783/* The code below is here to handle b/8734824
2784 *
2785 * We create a IGraphicBufferProducer wrapper that forwards all calls
2786 * to the calling binder thread, where they are executed. This allows
2787 * the calling thread to be reused (on the other side) and not
2788 * depend on having "enough" binder threads to handle the requests.
2789 *
2790 */
2791
2792class GraphicProducerWrapper : public BBinder, public MessageHandler {
2793    sp<IGraphicBufferProducer> impl;
2794    sp<Looper> looper;
2795    status_t result;
2796    bool exitPending;
2797    bool exitRequested;
2798    mutable Barrier barrier;
2799    volatile int32_t memoryBarrier;
2800    uint32_t code;
2801    Parcel const* data;
2802    Parcel* reply;
2803
2804    enum {
2805        MSG_API_CALL,
2806        MSG_EXIT
2807    };
2808
2809    /*
2810     * this is called by our "fake" BpGraphicBufferProducer. We package the
2811     * data and reply Parcel and forward them to the calling thread.
2812     */
2813    virtual status_t transact(uint32_t code,
2814            const Parcel& data, Parcel* reply, uint32_t flags) {
2815        this->code = code;
2816        this->data = &data;
2817        this->reply = reply;
2818        android_atomic_acquire_store(0, &memoryBarrier);
2819        if (exitPending) {
2820            // if we've exited, we run the message synchronously right here
2821            handleMessage(Message(MSG_API_CALL));
2822        } else {
2823            barrier.close();
2824            looper->sendMessage(this, Message(MSG_API_CALL));
2825            barrier.wait();
2826        }
2827        return NO_ERROR;
2828    }
2829
2830    /*
2831     * here we run on the binder calling thread. All we've got to do is
2832     * call the real BpGraphicBufferProducer.
2833     */
2834    virtual void handleMessage(const Message& message) {
2835        android_atomic_release_load(&memoryBarrier);
2836        if (message.what == MSG_API_CALL) {
2837            impl->asBinder()->transact(code, data[0], reply);
2838            barrier.open();
2839        } else if (message.what == MSG_EXIT) {
2840            exitRequested = true;
2841        }
2842    }
2843
2844public:
2845    GraphicProducerWrapper(const sp<IGraphicBufferProducer>& impl) :
2846        impl(impl), looper(new Looper(true)), result(NO_ERROR),
2847        exitPending(false), exitRequested(false) {
2848    }
2849
2850    status_t waitForResponse() {
2851        do {
2852            looper->pollOnce(-1);
2853        } while (!exitRequested);
2854        return result;
2855    }
2856
2857    void exit(status_t result) {
2858        this->result = result;
2859        exitPending = true;
2860        looper->sendMessage(this, Message(MSG_EXIT));
2861    }
2862};
2863
2864
2865status_t SurfaceFlinger::captureScreen(const sp<IBinder>& display,
2866        const sp<IGraphicBufferProducer>& producer,
2867        uint32_t reqWidth, uint32_t reqHeight,
2868        uint32_t minLayerZ, uint32_t maxLayerZ) {
2869
2870    if (CC_UNLIKELY(display == 0))
2871        return BAD_VALUE;
2872
2873    if (CC_UNLIKELY(producer == 0))
2874        return BAD_VALUE;
2875
2876    // if we have secure windows on this display, never allow the screen capture
2877    // unless the producer interface is local (i.e.: we can take a screenshot for
2878    // ourselves).
2879    if (!producer->asBinder()->localBinder()) {
2880        Mutex::Autolock _l(mStateLock);
2881        sp<const DisplayDevice> hw(getDisplayDevice(display));
2882        if (hw->getSecureLayerVisible()) {
2883            ALOGW("FB is protected: PERMISSION_DENIED");
2884            return PERMISSION_DENIED;
2885        }
2886    }
2887
2888    class MessageCaptureScreen : public MessageBase {
2889        SurfaceFlinger* flinger;
2890        sp<IBinder> display;
2891        sp<IGraphicBufferProducer> producer;
2892        uint32_t reqWidth, reqHeight;
2893        uint32_t minLayerZ,maxLayerZ;
2894        status_t result;
2895    public:
2896        MessageCaptureScreen(SurfaceFlinger* flinger,
2897                const sp<IBinder>& display,
2898                const sp<IGraphicBufferProducer>& producer,
2899                uint32_t reqWidth, uint32_t reqHeight,
2900                uint32_t minLayerZ, uint32_t maxLayerZ)
2901            : flinger(flinger), display(display), producer(producer),
2902              reqWidth(reqWidth), reqHeight(reqHeight),
2903              minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
2904              result(PERMISSION_DENIED)
2905        {
2906        }
2907        status_t getResult() const {
2908            return result;
2909        }
2910        virtual bool handler() {
2911            Mutex::Autolock _l(flinger->mStateLock);
2912            sp<const DisplayDevice> hw(flinger->getDisplayDevice(display));
2913            result = flinger->captureScreenImplLocked(hw,
2914                    producer, reqWidth, reqHeight, minLayerZ, maxLayerZ);
2915            static_cast<GraphicProducerWrapper*>(producer->asBinder().get())->exit(result);
2916            return true;
2917        }
2918    };
2919
2920    // make sure to process transactions before screenshots -- a transaction
2921    // might already be pending but scheduled for VSYNC; this guarantees we
2922    // will handle it before the screenshot. When VSYNC finally arrives
2923    // the scheduled transaction will be a no-op. If no transactions are
2924    // scheduled at this time, this will end-up being a no-op as well.
2925    mEventQueue.invalidateTransactionNow();
2926
2927    // this creates a "fake" BBinder which will serve as a "fake" remote
2928    // binder to receive the marshaled calls and forward them to the
2929    // real remote (a BpGraphicBufferProducer)
2930    sp<GraphicProducerWrapper> wrapper = new GraphicProducerWrapper(producer);
2931
2932    // the asInterface() call below creates our "fake" BpGraphicBufferProducer
2933    // which does the marshaling work forwards to our "fake remote" above.
2934    sp<MessageBase> msg = new MessageCaptureScreen(this,
2935            display, IGraphicBufferProducer::asInterface( wrapper ),
2936            reqWidth, reqHeight, minLayerZ, maxLayerZ);
2937
2938    status_t res = postMessageAsync(msg);
2939    if (res == NO_ERROR) {
2940        res = wrapper->waitForResponse();
2941    }
2942    return res;
2943}
2944
2945
2946void SurfaceFlinger::renderScreenImplLocked(
2947        const sp<const DisplayDevice>& hw,
2948        uint32_t reqWidth, uint32_t reqHeight,
2949        uint32_t minLayerZ, uint32_t maxLayerZ,
2950        bool yswap)
2951{
2952    ATRACE_CALL();
2953    RenderEngine& engine(getRenderEngine());
2954
2955    // get screen geometry
2956    const uint32_t hw_w = hw->getWidth();
2957    const uint32_t hw_h = hw->getHeight();
2958    const bool filtering = reqWidth != hw_w || reqWidth != hw_h;
2959
2960    // make sure to clear all GL error flags
2961    engine.checkErrors();
2962
2963    // set-up our viewport
2964    engine.setViewportAndProjection(reqWidth, reqHeight, hw_w, hw_h, yswap);
2965    engine.disableTexturing();
2966
2967    // redraw the screen entirely...
2968    engine.clearWithColor(0, 0, 0, 1);
2969
2970    const LayerVector& layers( mDrawingState.layersSortedByZ );
2971    const size_t count = layers.size();
2972    for (size_t i=0 ; i<count ; ++i) {
2973        const sp<Layer>& layer(layers[i]);
2974        const Layer::State& state(layer->getDrawingState());
2975        if (state.layerStack == hw->getLayerStack()) {
2976            if (state.z >= minLayerZ && state.z <= maxLayerZ) {
2977                if (layer->isVisible()) {
2978                    if (filtering) layer->setFiltering(true);
2979                    layer->draw(hw);
2980                    if (filtering) layer->setFiltering(false);
2981                }
2982            }
2983        }
2984    }
2985
2986    // compositionComplete is needed for older driver
2987    hw->compositionComplete();
2988    hw->setViewportAndProjection();
2989}
2990
2991
2992status_t SurfaceFlinger::captureScreenImplLocked(
2993        const sp<const DisplayDevice>& hw,
2994        const sp<IGraphicBufferProducer>& producer,
2995        uint32_t reqWidth, uint32_t reqHeight,
2996        uint32_t minLayerZ, uint32_t maxLayerZ)
2997{
2998    ATRACE_CALL();
2999
3000    // get screen geometry
3001    const uint32_t hw_w = hw->getWidth();
3002    const uint32_t hw_h = hw->getHeight();
3003
3004    if ((reqWidth > hw_w) || (reqHeight > hw_h)) {
3005        ALOGE("size mismatch (%d, %d) > (%d, %d)",
3006                reqWidth, reqHeight, hw_w, hw_h);
3007        return BAD_VALUE;
3008    }
3009
3010    reqWidth  = (!reqWidth)  ? hw_w : reqWidth;
3011    reqHeight = (!reqHeight) ? hw_h : reqHeight;
3012
3013    // create a surface (because we're a producer, and we need to
3014    // dequeue/queue a buffer)
3015    sp<Surface> sur = new Surface(producer, false);
3016    ANativeWindow* window = sur.get();
3017
3018    status_t result = NO_ERROR;
3019    if (native_window_api_connect(window, NATIVE_WINDOW_API_EGL) == NO_ERROR) {
3020        uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
3021                        GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
3022
3023        int err = 0;
3024        err = native_window_set_buffers_dimensions(window, reqWidth, reqHeight);
3025        err |= native_window_set_scaling_mode(window, NATIVE_WINDOW_SCALING_MODE_SCALE_TO_WINDOW);
3026        err |= native_window_set_buffers_format(window, HAL_PIXEL_FORMAT_RGBA_8888);
3027        err |= native_window_set_usage(window, usage);
3028
3029        if (err == NO_ERROR) {
3030            ANativeWindowBuffer* buffer;
3031            /* TODO: Once we have the sync framework everywhere this can use
3032             * server-side waits on the fence that dequeueBuffer returns.
3033             */
3034            result = native_window_dequeue_buffer_and_wait(window,  &buffer);
3035            if (result == NO_ERROR) {
3036                // create an EGLImage from the buffer so we can later
3037                // turn it into a texture
3038                EGLImageKHR image = eglCreateImageKHR(mEGLDisplay, EGL_NO_CONTEXT,
3039                        EGL_NATIVE_BUFFER_ANDROID, buffer, NULL);
3040                if (image != EGL_NO_IMAGE_KHR) {
3041                    // this binds the given EGLImage as a framebuffer for the
3042                    // duration of this scope.
3043                    RenderEngine::BindImageAsFramebuffer imageBond(getRenderEngine(), image);
3044                    if (imageBond.getStatus() == NO_ERROR) {
3045                        // this will in fact render into our dequeued buffer
3046                        // via an FBO, which means we didn't have to create
3047                        // an EGLSurface and therefore we're not
3048                        // dependent on the context's EGLConfig.
3049                        renderScreenImplLocked(hw, reqWidth, reqHeight,
3050                                minLayerZ, maxLayerZ, true);
3051
3052                        // Create a sync point and wait on it, so we know the buffer is
3053                        // ready before we pass it along.  We can't trivially call glFlush(),
3054                        // so we use a wait flag instead.
3055                        // TODO: pass a sync fd to queueBuffer() and let the consumer wait.
3056                        EGLSyncKHR sync = eglCreateSyncKHR(mEGLDisplay, EGL_SYNC_FENCE_KHR, NULL);
3057                        if (sync != EGL_NO_SYNC_KHR) {
3058                            EGLint result = eglClientWaitSyncKHR(mEGLDisplay, sync,
3059                                    EGL_SYNC_FLUSH_COMMANDS_BIT_KHR, 2000000000 /*2 sec*/);
3060                            EGLint eglErr = eglGetError();
3061                            eglDestroySyncKHR(mEGLDisplay, sync);
3062                            if (result == EGL_TIMEOUT_EXPIRED_KHR) {
3063                                ALOGW("captureScreen: fence wait timed out");
3064                            } else {
3065                                ALOGW_IF(eglErr != EGL_SUCCESS,
3066                                        "captureScreen: error waiting on EGL fence: %#x", eglErr);
3067                            }
3068                        } else {
3069                            ALOGW("captureScreen: error creating EGL fence: %#x", eglGetError());
3070                            // not fatal
3071                        }
3072
3073                        if (DEBUG_SCREENSHOTS) {
3074                            uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
3075                            getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
3076                            checkScreenshot(reqWidth, reqHeight, reqWidth, pixels,
3077                                    hw, minLayerZ, maxLayerZ);
3078                            delete [] pixels;
3079                        }
3080
3081                    } else {
3082                        ALOGE("got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot");
3083                        result = INVALID_OPERATION;
3084                    }
3085                    // destroy our image
3086                    eglDestroyImageKHR(mEGLDisplay, image);
3087                } else {
3088                    result = BAD_VALUE;
3089                }
3090                window->queueBuffer(window, buffer, -1);
3091            }
3092        } else {
3093            result = BAD_VALUE;
3094        }
3095        native_window_api_disconnect(window, NATIVE_WINDOW_API_EGL);
3096    }
3097
3098    return result;
3099}
3100
3101void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
3102        const sp<const DisplayDevice>& hw, uint32_t minLayerZ, uint32_t maxLayerZ) {
3103    if (DEBUG_SCREENSHOTS) {
3104        for (size_t y=0 ; y<h ; y++) {
3105            uint32_t const * p = (uint32_t const *)vaddr + y*s;
3106            for (size_t x=0 ; x<w ; x++) {
3107                if (p[x] != 0xFF000000) return;
3108            }
3109        }
3110        ALOGE("*** we just took a black screenshot ***\n"
3111                "requested minz=%d, maxz=%d, layerStack=%d",
3112                minLayerZ, maxLayerZ, hw->getLayerStack());
3113        const LayerVector& layers( mDrawingState.layersSortedByZ );
3114        const size_t count = layers.size();
3115        for (size_t i=0 ; i<count ; ++i) {
3116            const sp<Layer>& layer(layers[i]);
3117            const Layer::State& state(layer->getDrawingState());
3118            const bool visible = (state.layerStack == hw->getLayerStack())
3119                                && (state.z >= minLayerZ && state.z <= maxLayerZ)
3120                                && (layer->isVisible());
3121            ALOGE("%c index=%d, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%x",
3122                    visible ? '+' : '-',
3123                            i, layer->getName().string(), state.layerStack, state.z,
3124                            layer->isVisible(), state.flags, state.alpha);
3125        }
3126    }
3127}
3128
3129// ---------------------------------------------------------------------------
3130
3131SurfaceFlinger::LayerVector::LayerVector() {
3132}
3133
3134SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
3135    : SortedVector<sp<Layer> >(rhs) {
3136}
3137
3138int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
3139    const void* rhs) const
3140{
3141    // sort layers per layer-stack, then by z-order and finally by sequence
3142    const sp<Layer>& l(*reinterpret_cast<const sp<Layer>*>(lhs));
3143    const sp<Layer>& r(*reinterpret_cast<const sp<Layer>*>(rhs));
3144
3145    uint32_t ls = l->getCurrentState().layerStack;
3146    uint32_t rs = r->getCurrentState().layerStack;
3147    if (ls != rs)
3148        return ls - rs;
3149
3150    uint32_t lz = l->getCurrentState().z;
3151    uint32_t rz = r->getCurrentState().z;
3152    if (lz != rz)
3153        return lz - rz;
3154
3155    return l->sequence - r->sequence;
3156}
3157
3158// ---------------------------------------------------------------------------
3159
3160SurfaceFlinger::DisplayDeviceState::DisplayDeviceState()
3161    : type(DisplayDevice::DISPLAY_ID_INVALID) {
3162}
3163
3164SurfaceFlinger::DisplayDeviceState::DisplayDeviceState(DisplayDevice::DisplayType type)
3165    : type(type), layerStack(DisplayDevice::NO_LAYER_STACK), orientation(0) {
3166    viewport.makeInvalid();
3167    frame.makeInvalid();
3168}
3169
3170// ---------------------------------------------------------------------------
3171
3172}; // namespace android
3173
3174
3175#if defined(__gl_h_)
3176#error "don't include gl/gl.h in this file"
3177#endif
3178
3179#if defined(__gl2_h_)
3180#error "don't include gl2/gl2.h in this file"
3181#endif
3182