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