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