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