SurfaceFlinger.cpp revision 1a4d883dcc1725892bfb5c28dec255a233186524
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
24#include <EGL/egl.h>
25#include <GLES/gl.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/IDisplayEventConnection.h>
40#include <gui/SurfaceTextureClient.h>
41
42#include <ui/GraphicBufferAllocator.h>
43#include <ui/PixelFormat.h>
44
45#include <utils/String8.h>
46#include <utils/String16.h>
47#include <utils/StopWatch.h>
48#include <utils/Trace.h>
49
50#include <private/android_filesystem_config.h>
51
52#include "clz.h"
53#include "DdmConnection.h"
54#include "DisplayDevice.h"
55#include "Client.h"
56#include "EventThread.h"
57#include "GLExtensions.h"
58#include "Layer.h"
59#include "LayerDim.h"
60#include "LayerScreenshot.h"
61#include "SurfaceFlinger.h"
62
63#include "DisplayHardware/FramebufferSurface.h"
64#include "DisplayHardware/HWComposer.h"
65
66
67#define EGL_VERSION_HW_ANDROID  0x3143
68
69#define DISPLAY_COUNT       1
70
71namespace android {
72// ---------------------------------------------------------------------------
73
74const String16 sHardwareTest("android.permission.HARDWARE_TEST");
75const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
76const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
77const String16 sDump("android.permission.DUMP");
78
79// ---------------------------------------------------------------------------
80
81SurfaceFlinger::SurfaceFlinger()
82    :   BnSurfaceComposer(), Thread(false),
83        mTransactionFlags(0),
84        mTransationPending(false),
85        mLayersRemoved(false),
86        mRepaintEverything(0),
87        mBootTime(systemTime()),
88        mVisibleRegionsDirty(false),
89        mHwWorkListDirty(false),
90        mDebugRegion(0),
91        mDebugDDMS(0),
92        mDebugDisableHWC(0),
93        mDebugDisableTransformHint(0),
94        mDebugInSwapBuffers(0),
95        mLastSwapBufferTime(0),
96        mDebugInTransaction(0),
97        mLastTransactionTime(0),
98        mBootFinished(false),
99        mExternalDisplaySurface(EGL_NO_SURFACE)
100{
101    ALOGI("SurfaceFlinger is starting");
102
103    // debugging stuff...
104    char value[PROPERTY_VALUE_MAX];
105
106    property_get("debug.sf.showupdates", value, "0");
107    mDebugRegion = atoi(value);
108
109    property_get("debug.sf.ddms", value, "0");
110    mDebugDDMS = atoi(value);
111    if (mDebugDDMS) {
112        DdmConnection::start(getServiceName());
113    }
114
115    ALOGI_IF(mDebugRegion, "showupdates enabled");
116    ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
117}
118
119void SurfaceFlinger::onFirstRef()
120{
121    mEventQueue.init(this);
122
123    run("SurfaceFlinger", PRIORITY_URGENT_DISPLAY);
124
125    // Wait for the main thread to be done with its initialization
126    mReadyToRunBarrier.wait();
127}
128
129
130SurfaceFlinger::~SurfaceFlinger()
131{
132    EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
133    eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
134    eglTerminate(display);
135}
136
137void SurfaceFlinger::binderDied(const wp<IBinder>& who)
138{
139    // the window manager died on us. prepare its eulogy.
140
141    // reset screen orientation
142    Vector<ComposerState> state;
143    Vector<DisplayState> displays;
144    DisplayState d;
145    d.orientation = eOrientationDefault;
146    displays.add(d);
147    setTransactionState(state, displays, 0);
148
149    // restart the boot-animation
150    startBootAnim();
151}
152
153sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
154{
155    sp<ISurfaceComposerClient> bclient;
156    sp<Client> client(new Client(this));
157    status_t err = client->initCheck();
158    if (err == NO_ERROR) {
159        bclient = client;
160    }
161    return bclient;
162}
163
164sp<IGraphicBufferAlloc> SurfaceFlinger::createGraphicBufferAlloc()
165{
166    sp<GraphicBufferAlloc> gba(new GraphicBufferAlloc());
167    return gba;
168}
169
170void SurfaceFlinger::bootFinished()
171{
172    const nsecs_t now = systemTime();
173    const nsecs_t duration = now - mBootTime;
174    ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
175    mBootFinished = true;
176
177    // wait patiently for the window manager death
178    const String16 name("window");
179    sp<IBinder> window(defaultServiceManager()->getService(name));
180    if (window != 0) {
181        window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
182    }
183
184    // stop boot animation
185    // formerly we would just kill the process, but we now ask it to exit so it
186    // can choose where to stop the animation.
187    property_set("service.bootanim.exit", "1");
188}
189
190void SurfaceFlinger::deleteTextureAsync(GLuint texture) {
191    class MessageDestroyGLTexture : public MessageBase {
192        GLuint texture;
193    public:
194        MessageDestroyGLTexture(GLuint texture)
195            : texture(texture) {
196        }
197        virtual bool handler() {
198            glDeleteTextures(1, &texture);
199            return true;
200        }
201    };
202    postMessageAsync(new MessageDestroyGLTexture(texture));
203}
204
205status_t SurfaceFlinger::selectConfigForPixelFormat(
206        EGLDisplay dpy,
207        EGLint const* attrs,
208        PixelFormat format,
209        EGLConfig* outConfig)
210{
211    EGLConfig config = NULL;
212    EGLint numConfigs = -1, n=0;
213    eglGetConfigs(dpy, NULL, 0, &numConfigs);
214    EGLConfig* const configs = new EGLConfig[numConfigs];
215    eglChooseConfig(dpy, attrs, configs, numConfigs, &n);
216    for (int i=0 ; i<n ; i++) {
217        EGLint nativeVisualId = 0;
218        eglGetConfigAttrib(dpy, configs[i], EGL_NATIVE_VISUAL_ID, &nativeVisualId);
219        if (nativeVisualId>0 && format == nativeVisualId) {
220            *outConfig = configs[i];
221            delete [] configs;
222            return NO_ERROR;
223        }
224    }
225    delete [] configs;
226    return NAME_NOT_FOUND;
227}
228
229EGLConfig SurfaceFlinger::selectEGLConfig(EGLDisplay display, EGLint nativeVisualId) {
230    // select our EGLConfig. It must support EGL_RECORDABLE_ANDROID if
231    // it is to be used with WIFI displays
232    EGLConfig config;
233    EGLint dummy;
234    status_t err;
235    EGLint attribs[] = {
236            EGL_SURFACE_TYPE,           EGL_WINDOW_BIT,
237            EGL_RECORDABLE_ANDROID,     EGL_TRUE,
238            EGL_NONE
239    };
240    err = selectConfigForPixelFormat(display, attribs, nativeVisualId, &config);
241    if (err) {
242        // maybe we failed because of EGL_RECORDABLE_ANDROID
243        ALOGW("couldn't find an EGLConfig with EGL_RECORDABLE_ANDROID");
244        attribs[2] = EGL_NONE;
245        err = selectConfigForPixelFormat(display, attribs, nativeVisualId, &config);
246    }
247    ALOGE_IF(err, "couldn't find an EGLConfig matching the screen format");
248    if (eglGetConfigAttrib(display, config, EGL_CONFIG_CAVEAT, &dummy) == EGL_TRUE) {
249        ALOGW_IF(dummy == EGL_SLOW_CONFIG, "EGL_SLOW_CONFIG selected!");
250    }
251    return config;
252}
253
254EGLContext SurfaceFlinger::createGLContext(EGLDisplay display, EGLConfig config) {
255    // Also create our EGLContext
256    EGLint contextAttributes[] = {
257#ifdef EGL_IMG_context_priority
258#ifdef HAS_CONTEXT_PRIORITY
259#warning "using EGL_IMG_context_priority"
260            EGL_CONTEXT_PRIORITY_LEVEL_IMG, EGL_CONTEXT_PRIORITY_HIGH_IMG,
261#endif
262#endif
263            EGL_NONE, EGL_NONE
264    };
265    EGLContext ctxt = eglCreateContext(display, config, NULL, contextAttributes);
266    ALOGE_IF(ctxt==EGL_NO_CONTEXT, "EGLContext creation failed");
267    return ctxt;
268}
269
270void SurfaceFlinger::initializeGL(EGLDisplay display, EGLSurface surface) {
271    EGLBoolean result = eglMakeCurrent(display, surface, surface, mEGLContext);
272    if (!result) {
273        ALOGE("Couldn't create a working GLES context. check logs. exiting...");
274        exit(0);
275    }
276
277    GLExtensions& extensions(GLExtensions::getInstance());
278    extensions.initWithGLStrings(
279            glGetString(GL_VENDOR),
280            glGetString(GL_RENDERER),
281            glGetString(GL_VERSION),
282            glGetString(GL_EXTENSIONS),
283            eglQueryString(display, EGL_VENDOR),
284            eglQueryString(display, EGL_VERSION),
285            eglQueryString(display, EGL_EXTENSIONS));
286
287    EGLint w, h;
288    eglQuerySurface(display, surface, EGL_WIDTH,  &w);
289    eglQuerySurface(display, surface, EGL_HEIGHT, &h);
290
291    glGetIntegerv(GL_MAX_TEXTURE_SIZE, &mMaxTextureSize);
292    glGetIntegerv(GL_MAX_VIEWPORT_DIMS, mMaxViewportDims);
293
294    glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
295    glPixelStorei(GL_PACK_ALIGNMENT, 4);
296    glEnableClientState(GL_VERTEX_ARRAY);
297    glShadeModel(GL_FLAT);
298    glDisable(GL_DITHER);
299    glDisable(GL_CULL_FACE);
300
301    struct pack565 {
302        inline uint16_t operator() (int r, int g, int b) const {
303            return (r<<11)|(g<<5)|b;
304        }
305    } pack565;
306
307    const uint16_t protTexData[] = { pack565(0x03, 0x03, 0x03) };
308    glGenTextures(1, &mProtectedTexName);
309    glBindTexture(GL_TEXTURE_2D, mProtectedTexName);
310    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
311    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
312    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
313    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
314    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 1, 1, 0,
315            GL_RGB, GL_UNSIGNED_SHORT_5_6_5, protTexData);
316
317    glViewport(0, 0, w, h);
318    glMatrixMode(GL_PROJECTION);
319    glLoadIdentity();
320    // put the origin in the left-bottom corner
321    glOrthof(0, w, 0, h, 0, 1); // l=0, r=w ; b=0, t=h
322
323    // print some debugging info
324    EGLint r,g,b,a;
325    eglGetConfigAttrib(display, mEGLConfig, EGL_RED_SIZE,   &r);
326    eglGetConfigAttrib(display, mEGLConfig, EGL_GREEN_SIZE, &g);
327    eglGetConfigAttrib(display, mEGLConfig, EGL_BLUE_SIZE,  &b);
328    eglGetConfigAttrib(display, mEGLConfig, EGL_ALPHA_SIZE, &a);
329    ALOGI("EGL informations:");
330    ALOGI("vendor    : %s", extensions.getEglVendor());
331    ALOGI("version   : %s", extensions.getEglVersion());
332    ALOGI("extensions: %s", extensions.getEglExtension());
333    ALOGI("Client API: %s", eglQueryString(display, EGL_CLIENT_APIS)?:"Not Supported");
334    ALOGI("EGLSurface: %d-%d-%d-%d, config=%p", r, g, b, a, mEGLConfig);
335    ALOGI("OpenGL ES informations:");
336    ALOGI("vendor    : %s", extensions.getVendor());
337    ALOGI("renderer  : %s", extensions.getRenderer());
338    ALOGI("version   : %s", extensions.getVersion());
339    ALOGI("extensions: %s", extensions.getExtension());
340    ALOGI("GL_MAX_TEXTURE_SIZE = %d", mMaxTextureSize);
341    ALOGI("GL_MAX_VIEWPORT_DIMS = %d x %d", mMaxViewportDims[0], mMaxViewportDims[1]);
342}
343
344status_t SurfaceFlinger::readyToRun()
345{
346    ALOGI(  "SurfaceFlinger's main thread ready to run. "
347            "Initializing graphics H/W...");
348
349    // initialize EGL
350    mEGLDisplay = eglGetDisplay(EGL_DEFAULT_DISPLAY);
351    eglInitialize(mEGLDisplay, NULL, NULL);
352
353    // Initialize the main display
354    // create native window to main display
355    sp<FramebufferSurface> fbs = FramebufferSurface::create();
356    if (fbs == NULL) {
357        ALOGE("Display subsystem failed to initialize. check logs. exiting...");
358        exit(0);
359    }
360
361    sp<SurfaceTextureClient> stc(new SurfaceTextureClient(static_cast<sp<ISurfaceTexture> >(fbs->getBufferQueue())));
362
363    // initialize the config and context
364    int format;
365    ANativeWindow* const anw = stc.get();
366    anw->query(anw, NATIVE_WINDOW_FORMAT, &format);
367    mEGLConfig  = selectEGLConfig(mEGLDisplay, format);
368    mEGLContext = createGLContext(mEGLDisplay, mEGLConfig);
369
370    // initialize our main display hardware
371    mCurrentState.displays.add(DisplayDevice::DISPLAY_ID_MAIN, DisplayDeviceState());
372    sp<DisplayDevice> hw = new DisplayDevice(this, DisplayDevice::DISPLAY_ID_MAIN, anw, fbs, mEGLConfig);
373    mDisplays.add(DisplayDevice::DISPLAY_ID_MAIN, hw);
374
375    //  initialize OpenGL ES
376    EGLSurface surface = hw->getEGLSurface();
377    initializeGL(mEGLDisplay, surface);
378
379    // start the EventThread
380    mEventThread = new EventThread(this);
381    mEventQueue.setEventThread(mEventThread);
382
383    // initialize the H/W composer
384    mHwc = new HWComposer(this, *static_cast<HWComposer::EventHandler *>(this));
385
386    // initialize our drawing state
387    mDrawingState = mCurrentState;
388
389    // We're now ready to accept clients...
390    mReadyToRunBarrier.open();
391
392    // start boot animation
393    startBootAnim();
394
395    return NO_ERROR;
396}
397
398void SurfaceFlinger::startBootAnim() {
399    // start boot animation
400    property_set("service.bootanim.exit", "0");
401    property_set("ctl.start", "bootanim");
402}
403
404uint32_t SurfaceFlinger::getMaxTextureSize() const {
405    return mMaxTextureSize;
406}
407
408uint32_t SurfaceFlinger::getMaxViewportDims() const {
409    return mMaxViewportDims[0] < mMaxViewportDims[1] ?
410            mMaxViewportDims[0] : mMaxViewportDims[1];
411}
412
413// ----------------------------------------------------------------------------
414
415bool SurfaceFlinger::authenticateSurfaceTexture(
416        const sp<ISurfaceTexture>& surfaceTexture) const {
417    Mutex::Autolock _l(mStateLock);
418    sp<IBinder> surfaceTextureBinder(surfaceTexture->asBinder());
419
420    // Check the visible layer list for the ISurface
421    const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
422    size_t count = currentLayers.size();
423    for (size_t i=0 ; i<count ; i++) {
424        const sp<LayerBase>& layer(currentLayers[i]);
425        sp<LayerBaseClient> lbc(layer->getLayerBaseClient());
426        if (lbc != NULL) {
427            wp<IBinder> lbcBinder = lbc->getSurfaceTextureBinder();
428            if (lbcBinder == surfaceTextureBinder) {
429                return true;
430            }
431        }
432    }
433
434    // Check the layers in the purgatory.  This check is here so that if a
435    // SurfaceTexture gets destroyed before all the clients are done using it,
436    // the error will not be reported as "surface XYZ is not authenticated", but
437    // will instead fail later on when the client tries to use the surface,
438    // which should be reported as "surface XYZ returned an -ENODEV".  The
439    // purgatorized layers are no less authentic than the visible ones, so this
440    // should not cause any harm.
441    size_t purgatorySize =  mLayerPurgatory.size();
442    for (size_t i=0 ; i<purgatorySize ; i++) {
443        const sp<LayerBase>& layer(mLayerPurgatory.itemAt(i));
444        sp<LayerBaseClient> lbc(layer->getLayerBaseClient());
445        if (lbc != NULL) {
446            wp<IBinder> lbcBinder = lbc->getSurfaceTextureBinder();
447            if (lbcBinder == surfaceTextureBinder) {
448                return true;
449            }
450        }
451    }
452
453    return false;
454}
455
456status_t SurfaceFlinger::getDisplayInfo(DisplayID dpy, DisplayInfo* info) {
457    // TODO: this is here only for compatibility -- show go away eventually.
458    if (uint32_t(dpy) >= 2) {
459        return BAD_INDEX;
460    }
461    sp<const DisplayDevice> hw(getDefaultDisplayDevice());
462    info->w = hw->getWidth();
463    info->h = hw->getHeight();
464    info->xdpi = hw->getDpiX();
465    info->ydpi = hw->getDpiY();
466    info->fps = float(1e9 / getHwComposer().getRefreshPeriod());
467    info->density = hw->getDensity();
468    info->orientation = hw->getOrientation();
469    // TODO: this needs to go away (currently needed only by webkit)
470    getPixelFormatInfo(hw->getFormat(), &info->pixelFormatInfo);
471    return NO_ERROR;
472}
473
474// ----------------------------------------------------------------------------
475
476sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection() {
477    return mEventThread->createEventConnection();
478}
479
480void SurfaceFlinger::connectDisplay(const sp<ISurfaceTexture> display) {
481    EGLSurface result = EGL_NO_SURFACE;
482    EGLSurface old_surface = EGL_NO_SURFACE;
483    sp<SurfaceTextureClient> stc;
484
485    if (display != NULL) {
486        stc = new SurfaceTextureClient(display);
487        result = eglCreateWindowSurface(mEGLDisplay,
488                mEGLConfig, (EGLNativeWindowType)stc.get(), NULL);
489        ALOGE_IF(result == EGL_NO_SURFACE,
490                "eglCreateWindowSurface failed (ISurfaceTexture=%p)",
491                display.get());
492    }
493
494    { // scope for the lock
495        Mutex::Autolock _l(mStateLock);
496        old_surface = mExternalDisplaySurface;
497        mExternalDisplayNativeWindow = stc;
498        mExternalDisplaySurface = result;
499        ALOGD("mExternalDisplaySurface = %p", result);
500    }
501
502    if (old_surface != EGL_NO_SURFACE) {
503        // Note: EGL allows to destroy an object while its current
504        // it will fail to become current next time though.
505        eglDestroySurface(mEGLDisplay, old_surface);
506    }
507}
508
509EGLSurface SurfaceFlinger::getExternalDisplaySurface() const {
510    Mutex::Autolock _l(mStateLock);
511    return mExternalDisplaySurface;
512}
513
514// ----------------------------------------------------------------------------
515
516void SurfaceFlinger::waitForEvent() {
517    mEventQueue.waitMessage();
518}
519
520void SurfaceFlinger::signalTransaction() {
521    mEventQueue.invalidate();
522}
523
524void SurfaceFlinger::signalLayerUpdate() {
525    mEventQueue.invalidate();
526}
527
528void SurfaceFlinger::signalRefresh() {
529    mEventQueue.refresh();
530}
531
532status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
533        nsecs_t reltime, uint32_t flags) {
534    return mEventQueue.postMessage(msg, reltime);
535}
536
537status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
538        nsecs_t reltime, uint32_t flags) {
539    status_t res = mEventQueue.postMessage(msg, reltime);
540    if (res == NO_ERROR) {
541        msg->wait();
542    }
543    return res;
544}
545
546bool SurfaceFlinger::threadLoop() {
547    waitForEvent();
548    return true;
549}
550
551void SurfaceFlinger::onVSyncReceived(int dpy, nsecs_t timestamp) {
552    mEventThread->onVSyncReceived(dpy, timestamp);
553}
554
555void SurfaceFlinger::eventControl(int event, int enabled) {
556    getHwComposer().eventControl(event, enabled);
557}
558
559void SurfaceFlinger::onMessageReceived(int32_t what) {
560    ATRACE_CALL();
561    switch (what) {
562    case MessageQueue::INVALIDATE:
563        handleMessageTransaction();
564        handleMessageInvalidate();
565        signalRefresh();
566        break;
567    case MessageQueue::REFRESH:
568        handleMessageRefresh();
569        break;
570    }
571}
572
573void SurfaceFlinger::handleMessageTransaction() {
574    const uint32_t mask = eTransactionNeeded | eTraversalNeeded;
575    uint32_t transactionFlags = peekTransactionFlags(mask);
576    if (transactionFlags) {
577        handleTransaction(transactionFlags);
578    }
579}
580
581void SurfaceFlinger::handleMessageInvalidate() {
582    handlePageFlip();
583}
584
585void SurfaceFlinger::handleMessageRefresh() {
586    handleRefresh();
587
588    if (CC_UNLIKELY(mVisibleRegionsDirty)) {
589        mVisibleRegionsDirty = false;
590        invalidateHwcGeometry();
591
592        /*
593         *  rebuild the visible layer list per screen
594         */
595
596        const LayerVector& currentLayers(mDrawingState.layersSortedByZ);
597        for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
598            const sp<DisplayDevice>& hw(mDisplays[dpy]);
599            Region opaqueRegion;
600            Region dirtyRegion;
601            computeVisibleRegions(currentLayers,
602                    hw->getLayerStack(), dirtyRegion, opaqueRegion);
603            hw->dirtyRegion.orSelf(dirtyRegion);
604
605            Vector< sp<LayerBase> > layersSortedByZ;
606            const size_t count = currentLayers.size();
607            for (size_t i=0 ; i<count ; i++) {
608                const Layer::State& s(currentLayers[i]->drawingState());
609                if (s.layerStack == hw->getLayerStack()) {
610                    if (!currentLayers[i]->visibleRegion.isEmpty()) {
611                        layersSortedByZ.add(currentLayers[i]);
612                    }
613                }
614            }
615            hw->setVisibleLayersSortedByZ(layersSortedByZ);
616            hw->undefinedRegion.set(hw->getBounds());
617            hw->undefinedRegion.subtractSelf(hw->getTransform().transform(opaqueRegion));
618        }
619    }
620
621    HWComposer& hwc(getHwComposer());
622    if (hwc.initCheck() == NO_ERROR) {
623        // build the h/w work list
624        const bool workListsDirty = mHwWorkListDirty;
625        mHwWorkListDirty = false;
626        for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
627            sp<const DisplayDevice> hw(mDisplays[dpy]);
628            const Vector< sp<LayerBase> >& currentLayers(hw->getVisibleLayersSortedByZ());
629            const size_t count = currentLayers.size();
630
631            hwc.createWorkList(count); // FIXME: the worklist should include enough space for all layer of all displays
632
633            HWComposer::LayerListIterator cur = hwc.begin();
634            const HWComposer::LayerListIterator end = hwc.end();
635            for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
636                const sp<LayerBase>& layer(currentLayers[i]);
637
638                if (CC_UNLIKELY(workListsDirty)) {
639                    layer->setGeometry(hw, *cur);
640                    if (mDebugDisableHWC || mDebugRegion) {
641                        cur->setSkip(true);
642                    }
643                }
644
645                /*
646                 * update the per-frame h/w composer data for each layer
647                 * and build the transparent region of the FB
648                 */
649                layer->setPerFrameData(hw, *cur);
650            }
651        }
652        status_t err = hwc.prepare();
653        ALOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err));
654    }
655
656    const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
657    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
658        const sp<DisplayDevice>& hw(mDisplays[dpy]);
659
660        // transform the dirty region into this screen's coordinate space
661        const Transform& planeTransform(hw->getTransform());
662        Region dirtyRegion;
663        if (repaintEverything) {
664            dirtyRegion.set(hw->bounds());
665        } else {
666            dirtyRegion = planeTransform.transform(hw->dirtyRegion);
667            dirtyRegion.andSelf(hw->bounds());
668        }
669        hw->dirtyRegion.clear();
670
671        if (!dirtyRegion.isEmpty()) {
672            if (hw->canDraw()) {
673                // repaint the framebuffer (if needed)
674                handleRepaint(hw, dirtyRegion);
675            }
676        }
677        // inform the h/w that we're done compositing
678        hw->compositionComplete();
679    }
680
681    postFramebuffer();
682
683
684#if 1
685    // render to the external display if we have one
686    EGLSurface externalDisplaySurface = getExternalDisplaySurface();
687    if (externalDisplaySurface != EGL_NO_SURFACE) {
688        EGLSurface cur = eglGetCurrentSurface(EGL_DRAW);
689        EGLBoolean success = eglMakeCurrent(eglGetCurrentDisplay(),
690                externalDisplaySurface, externalDisplaySurface,
691                eglGetCurrentContext());
692
693        ALOGE_IF(!success, "eglMakeCurrent -> external failed");
694
695        if (success) {
696            // redraw the screen entirely...
697            glDisable(GL_TEXTURE_EXTERNAL_OES);
698            glDisable(GL_TEXTURE_2D);
699            glClearColor(0,0,0,1);
700            glClear(GL_COLOR_BUFFER_BIT);
701            glMatrixMode(GL_MODELVIEW);
702            glLoadIdentity();
703
704            const sp<DisplayDevice>& hw(getDisplayDevice(0));
705            const Vector< sp<LayerBase> >& layers( hw->getVisibleLayersSortedByZ() );
706            const size_t count = layers.size();
707            for (size_t i=0 ; i<count ; ++i) {
708                const sp<LayerBase>& layer(layers[i]);
709                layer->draw(hw);
710            }
711
712            success = eglSwapBuffers(eglGetCurrentDisplay(), externalDisplaySurface);
713            ALOGE_IF(!success, "external display eglSwapBuffers failed");
714
715            hw->compositionComplete();
716        }
717
718        success = eglMakeCurrent(eglGetCurrentDisplay(),
719                cur, cur, eglGetCurrentContext());
720
721        ALOGE_IF(!success, "eglMakeCurrent -> internal failed");
722    }
723#endif
724
725}
726
727void SurfaceFlinger::postFramebuffer()
728{
729    ATRACE_CALL();
730
731    const nsecs_t now = systemTime();
732    mDebugInSwapBuffers = now;
733
734    HWComposer& hwc(getHwComposer());
735
736    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
737        const sp<DisplayDevice>& hw(mDisplays[dpy]);
738        if (hwc.initCheck() == NO_ERROR) {
739            const Vector< sp<LayerBase> >& currentLayers(hw->getVisibleLayersSortedByZ());
740            const size_t count = currentLayers.size();
741            HWComposer::LayerListIterator cur = hwc.begin();
742            const HWComposer::LayerListIterator end = hwc.end();
743            for (size_t i=0 ; cur!=end && i<count ; ++i, ++cur) {
744                const sp<LayerBase>& layer(currentLayers[i]);
745                layer->setAcquireFence(hw, *cur);
746            }
747        }
748        hw->flip(hw->swapRegion);
749        hw->swapRegion.clear();
750    }
751
752    if (hwc.initCheck() == NO_ERROR) {
753        // FIXME: eventually commit() won't take arguments
754        hwc.commit(mEGLDisplay, getDefaultDisplayDevice()->getEGLSurface());
755    }
756
757    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
758        sp<const DisplayDevice> hw(mDisplays[dpy]);
759        const Vector< sp<LayerBase> >& currentLayers(hw->getVisibleLayersSortedByZ());
760        const size_t count = currentLayers.size();
761        if (hwc.initCheck() == NO_ERROR) {
762            HWComposer::LayerListIterator cur = hwc.begin();
763            const HWComposer::LayerListIterator end = hwc.end();
764            for (size_t i = 0; cur != end && i < count; ++i, ++cur) {
765                currentLayers[i]->onLayerDisplayed(hw, &*cur);
766            }
767        } else {
768            eglSwapBuffers(mEGLDisplay, hw->getEGLSurface());
769            for (size_t i = 0; i < count; i++) {
770                currentLayers[i]->onLayerDisplayed(hw, NULL);
771            }
772        }
773
774        // FIXME: we need to call eglSwapBuffers() on displays that have GL composition
775    }
776
777    mLastSwapBufferTime = systemTime() - now;
778    mDebugInSwapBuffers = 0;
779}
780
781void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
782{
783    ATRACE_CALL();
784
785    Mutex::Autolock _l(mStateLock);
786    const nsecs_t now = systemTime();
787    mDebugInTransaction = now;
788
789    // Here we're guaranteed that some transaction flags are set
790    // so we can call handleTransactionLocked() unconditionally.
791    // We call getTransactionFlags(), which will also clear the flags,
792    // with mStateLock held to guarantee that mCurrentState won't change
793    // until the transaction is committed.
794
795    const uint32_t mask = eTransactionNeeded | eTraversalNeeded;
796    transactionFlags = getTransactionFlags(mask);
797    handleTransactionLocked(transactionFlags);
798
799    mLastTransactionTime = systemTime() - now;
800    mDebugInTransaction = 0;
801    invalidateHwcGeometry();
802    // here the transaction has been committed
803}
804
805void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
806{
807    const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
808    const size_t count = currentLayers.size();
809
810    /*
811     * Traversal of the children
812     * (perform the transaction for each of them if needed)
813     */
814
815    const bool layersNeedTransaction = transactionFlags & eTraversalNeeded;
816    if (layersNeedTransaction) {
817        for (size_t i=0 ; i<count ; i++) {
818            const sp<LayerBase>& layer = currentLayers[i];
819            uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
820            if (!trFlags) continue;
821
822            const uint32_t flags = layer->doTransaction(0);
823            if (flags & Layer::eVisibleRegion)
824                mVisibleRegionsDirty = true;
825        }
826    }
827
828    /*
829     * Perform our own transaction if needed
830     */
831
832    if (transactionFlags & eTransactionNeeded) {
833        // here we take advantage of Vector's copy-on-write semantics to
834        // improve performance by skipping the transaction entirely when
835        // know that the lists are identical
836        const KeyedVector<int32_t, DisplayDeviceState>& curr(mCurrentState.displays);
837        const KeyedVector<int32_t, DisplayDeviceState>& draw(mDrawingState.displays);
838        if (!curr.isIdenticalTo(draw)) {
839            mVisibleRegionsDirty = true;
840            const size_t cc = curr.size();
841            const size_t dc = draw.size();
842
843            // find the displays that were removed
844            // (ie: in drawing state but not in current state)
845            // also handle displays that changed
846            // (ie: displays that are in both lists)
847            for (size_t i=0 ; i<dc ; i++) {
848                if (curr.indexOfKey(draw[i].id) < 0) {
849                    // in drawing state but not in current state
850                    if (draw[i].id != DisplayDevice::DISPLAY_ID_MAIN) {
851                        mDisplays.removeItem(draw[i].id);
852                    } else {
853                        ALOGW("trying to remove the main display");
854                    }
855                } else {
856                    // this display is in both lists. see if something changed.
857                    const DisplayDeviceState& state(curr[i]);
858                    if (state.layerStack != draw[i].layerStack) {
859                        const sp<DisplayDevice>& disp(getDisplayDevice(state.id));
860                        //disp->setLayerStack(state.layerStack); // FIXME: set layer stack
861                    }
862                    if (curr[i].orientation != draw[i].orientation) {
863                        const sp<DisplayDevice>& disp(getDisplayDevice(state.id));
864                        disp->setOrientation(state.orientation);
865                    }
866                }
867            }
868
869            // find displays that were added
870            // (ie: in current state but not in drawing state)
871            for (size_t i=0 ; i<cc ; i++) {
872                if (mDrawingState.displays.indexOfKey(curr[i].id) < 0) {
873                    // FIXME: we need to pass the surface here
874                    sp<DisplayDevice> disp = new DisplayDevice(this, curr[i].id, 0, 0, mEGLConfig);
875                    mDisplays.add(curr[i].id, disp);
876                }
877            }
878        }
879
880        if (currentLayers.size() > mDrawingState.layersSortedByZ.size()) {
881            // layers have been added
882            mVisibleRegionsDirty = true;
883        }
884
885        // some layers might have been removed, so
886        // we need to update the regions they're exposing.
887        if (mLayersRemoved) {
888            mLayersRemoved = false;
889            mVisibleRegionsDirty = true;
890            const LayerVector& previousLayers(mDrawingState.layersSortedByZ);
891            const size_t count = previousLayers.size();
892            for (size_t i=0 ; i<count ; i++) {
893                const sp<LayerBase>& layer(previousLayers[i]);
894                if (currentLayers.indexOf(layer) < 0) {
895                    // this layer is not visible anymore
896                    // TODO: we could traverse the tree from front to back and
897                    //       compute the actual visible region
898                    // TODO: we could cache the transformed region
899                    Layer::State front(layer->drawingState());
900                    Region visibleReg = front.transform.transform(
901                            Region(Rect(front.active.w, front.active.h)));
902                    invalidateLayerStack(front.layerStack, visibleReg);
903                }
904            }
905        }
906    }
907
908    commitTransaction();
909}
910
911void SurfaceFlinger::commitTransaction()
912{
913    if (!mLayersPendingRemoval.isEmpty()) {
914        // Notify removed layers now that they can't be drawn from
915        for (size_t i = 0; i < mLayersPendingRemoval.size(); i++) {
916            mLayersPendingRemoval[i]->onRemoved();
917        }
918        mLayersPendingRemoval.clear();
919    }
920
921    mDrawingState = mCurrentState;
922    mTransationPending = false;
923    mTransactionCV.broadcast();
924}
925
926void SurfaceFlinger::computeVisibleRegions(
927        const LayerVector& currentLayers, uint32_t layerStack,
928        Region& outDirtyRegion, Region& outOpaqueRegion)
929{
930    ATRACE_CALL();
931
932    Region aboveOpaqueLayers;
933    Region aboveCoveredLayers;
934    Region dirty;
935
936    outDirtyRegion.clear();
937
938    size_t i = currentLayers.size();
939    while (i--) {
940        const sp<LayerBase>& layer = currentLayers[i];
941
942        // start with the whole surface at its current location
943        const Layer::State& s(layer->drawingState());
944
945        // only consider the layers on the given later stack
946        if (s.layerStack != layerStack)
947            continue;
948
949        /*
950         * opaqueRegion: area of a surface that is fully opaque.
951         */
952        Region opaqueRegion;
953
954        /*
955         * visibleRegion: area of a surface that is visible on screen
956         * and not fully transparent. This is essentially the layer's
957         * footprint minus the opaque regions above it.
958         * Areas covered by a translucent surface are considered visible.
959         */
960        Region visibleRegion;
961
962        /*
963         * coveredRegion: area of a surface that is covered by all
964         * visible regions above it (which includes the translucent areas).
965         */
966        Region coveredRegion;
967
968
969        // handle hidden surfaces by setting the visible region to empty
970        if (CC_LIKELY(!(s.flags & ISurfaceComposer::eLayerHidden) && s.alpha)) {
971            const bool translucent = !layer->isOpaque();
972            Rect bounds(layer->computeBounds());
973            visibleRegion.set(bounds);
974            if (!visibleRegion.isEmpty()) {
975                // Remove the transparent area from the visible region
976                if (translucent) {
977                    Region transparentRegionScreen;
978                    const Transform tr(s.transform);
979                    if (tr.transformed()) {
980                        if (tr.preserveRects()) {
981                            // transform the transparent region
982                            transparentRegionScreen = tr.transform(s.transparentRegion);
983                        } else {
984                            // transformation too complex, can't do the
985                            // transparent region optimization.
986                            transparentRegionScreen.clear();
987                        }
988                    } else {
989                        transparentRegionScreen = s.transparentRegion;
990                    }
991                    visibleRegion.subtractSelf(transparentRegionScreen);
992                }
993
994                // compute the opaque region
995                const int32_t layerOrientation = s.transform.getOrientation();
996                if (s.alpha==255 && !translucent &&
997                        ((layerOrientation & Transform::ROT_INVALID) == false)) {
998                    // the opaque region is the layer's footprint
999                    opaqueRegion = visibleRegion;
1000                }
1001            }
1002        }
1003
1004        // Clip the covered region to the visible region
1005        coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
1006
1007        // Update aboveCoveredLayers for next (lower) layer
1008        aboveCoveredLayers.orSelf(visibleRegion);
1009
1010        // subtract the opaque region covered by the layers above us
1011        visibleRegion.subtractSelf(aboveOpaqueLayers);
1012
1013        // compute this layer's dirty region
1014        if (layer->contentDirty) {
1015            // we need to invalidate the whole region
1016            dirty = visibleRegion;
1017            // as well, as the old visible region
1018            dirty.orSelf(layer->visibleRegion);
1019            layer->contentDirty = false;
1020        } else {
1021            /* compute the exposed region:
1022             *   the exposed region consists of two components:
1023             *   1) what's VISIBLE now and was COVERED before
1024             *   2) what's EXPOSED now less what was EXPOSED before
1025             *
1026             * note that (1) is conservative, we start with the whole
1027             * visible region but only keep what used to be covered by
1028             * something -- which mean it may have been exposed.
1029             *
1030             * (2) handles areas that were not covered by anything but got
1031             * exposed because of a resize.
1032             */
1033            const Region newExposed = visibleRegion - coveredRegion;
1034            const Region oldVisibleRegion = layer->visibleRegion;
1035            const Region oldCoveredRegion = layer->coveredRegion;
1036            const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
1037            dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
1038        }
1039        dirty.subtractSelf(aboveOpaqueLayers);
1040
1041        // accumulate to the screen dirty region
1042        outDirtyRegion.orSelf(dirty);
1043
1044        // Update aboveOpaqueLayers for next (lower) layer
1045        aboveOpaqueLayers.orSelf(opaqueRegion);
1046
1047        // Store the visible region is screen space
1048        layer->setVisibleRegion(visibleRegion);
1049        layer->setCoveredRegion(coveredRegion);
1050    }
1051
1052    outOpaqueRegion = aboveOpaqueLayers;
1053}
1054
1055void SurfaceFlinger::invalidateLayerStack(uint32_t layerStack,
1056        const Region& dirty) {
1057    for (size_t dpy=0 ; dpy<mDisplays.size() ; dpy++) {
1058        const sp<DisplayDevice>& hw(mDisplays[dpy]);
1059        if (hw->getLayerStack() == layerStack) {
1060            hw->dirtyRegion.orSelf(dirty);
1061        }
1062    }
1063}
1064
1065void SurfaceFlinger::handlePageFlip()
1066{
1067    ATRACE_CALL();
1068    Region dirtyRegion;
1069
1070    const LayerVector& currentLayers(mDrawingState.layersSortedByZ);
1071
1072    bool visibleRegions = false;
1073    const size_t count = currentLayers.size();
1074    sp<LayerBase> const* layers = currentLayers.array();
1075    for (size_t i=0 ; i<count ; i++) {
1076        const sp<LayerBase>& layer(layers[i]);
1077        const Region dirty(layer->latchBuffer(visibleRegions));
1078        Layer::State s(layer->drawingState());
1079        invalidateLayerStack(s.layerStack, dirty);
1080    }
1081
1082    mVisibleRegionsDirty |= visibleRegions;
1083}
1084
1085void SurfaceFlinger::invalidateHwcGeometry()
1086{
1087    mHwWorkListDirty = true;
1088}
1089
1090void SurfaceFlinger::handleRefresh()
1091{
1092    bool needInvalidate = false;
1093    const LayerVector& currentLayers(mDrawingState.layersSortedByZ);
1094    const size_t count = currentLayers.size();
1095    for (size_t i=0 ; i<count ; i++) {
1096        const sp<LayerBase>& layer(currentLayers[i]);
1097        if (layer->onPreComposition()) {
1098            needInvalidate = true;
1099        }
1100    }
1101    if (needInvalidate) {
1102        signalLayerUpdate();
1103    }
1104}
1105
1106void SurfaceFlinger::handleRepaint(const sp<const DisplayDevice>& hw,
1107        const Region& inDirtyRegion)
1108{
1109    ATRACE_CALL();
1110
1111    Region dirtyRegion(inDirtyRegion);
1112
1113    // compute the invalid region
1114    hw->swapRegion.orSelf(dirtyRegion);
1115
1116    if (CC_UNLIKELY(mDebugRegion)) {
1117        debugFlashRegions(hw, dirtyRegion);
1118    }
1119
1120    uint32_t flags = hw->getFlags();
1121    if (flags & DisplayDevice::SWAP_RECTANGLE) {
1122        // we can redraw only what's dirty, but since SWAP_RECTANGLE only
1123        // takes a rectangle, we must make sure to update that whole
1124        // rectangle in that case
1125        dirtyRegion.set(hw->swapRegion.bounds());
1126    } else {
1127        if (flags & DisplayDevice::PARTIAL_UPDATES) {
1128            // We need to redraw the rectangle that will be updated
1129            // (pushed to the framebuffer).
1130            // This is needed because PARTIAL_UPDATES only takes one
1131            // rectangle instead of a region (see DisplayDevice::flip())
1132            dirtyRegion.set(hw->swapRegion.bounds());
1133        } else {
1134            // we need to redraw everything (the whole screen)
1135            dirtyRegion.set(hw->bounds());
1136            hw->swapRegion = dirtyRegion;
1137        }
1138    }
1139
1140    composeSurfaces(hw, dirtyRegion);
1141
1142    const LayerVector& currentLayers(mDrawingState.layersSortedByZ);
1143    const size_t count = currentLayers.size();
1144    for (size_t i=0 ; i<count ; i++) {
1145        currentLayers[i]->onPostComposition();
1146    }
1147
1148    // update the swap region and clear the dirty region
1149    hw->swapRegion.orSelf(dirtyRegion);
1150}
1151
1152void SurfaceFlinger::composeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty)
1153{
1154    HWComposer& hwc(getHwComposer());
1155    HWComposer::LayerListIterator cur = hwc.begin();
1156    const HWComposer::LayerListIterator end = hwc.end();
1157
1158    const size_t fbLayerCount = hwc.getLayerCount(HWC_FRAMEBUFFER);  // FIXME: this should be per display
1159    if (cur==end || fbLayerCount) {
1160
1161        DisplayDevice::makeCurrent(hw, mEGLContext);
1162
1163        // set the frame buffer
1164        glMatrixMode(GL_MODELVIEW);
1165        glLoadIdentity();
1166
1167        // Never touch the framebuffer if we don't have any framebuffer layers
1168        if (hwc.getLayerCount(HWC_OVERLAY)) { // FIXME: this should be per display
1169            // when using overlays, we assume a fully transparent framebuffer
1170            // NOTE: we could reduce how much we need to clear, for instance
1171            // remove where there are opaque FB layers. however, on some
1172            // GPUs doing a "clean slate" glClear might be more efficient.
1173            // We'll revisit later if needed.
1174            glClearColor(0, 0, 0, 0);
1175            glClear(GL_COLOR_BUFFER_BIT);
1176        } else {
1177            const Region region(hw->undefinedRegion.intersect(dirty));
1178            // screen is already cleared here
1179            if (!region.isEmpty()) {
1180                // can happen with SurfaceView
1181                drawWormhole(region);
1182            }
1183        }
1184
1185        /*
1186         * and then, render the layers targeted at the framebuffer
1187         */
1188
1189        const Vector< sp<LayerBase> >& layers(hw->getVisibleLayersSortedByZ());
1190        const size_t count = layers.size();
1191        const Transform& tr = hw->getTransform();
1192        for (size_t i=0 ; i<count ; ++i) {
1193            const sp<LayerBase>& layer(layers[i]);
1194            const Region clip(dirty.intersect(tr.transform(layer->visibleRegion)));
1195            if (!clip.isEmpty()) {
1196                if (cur != end && cur->getCompositionType() == HWC_OVERLAY) {
1197                    if (i && (cur->getHints() & HWC_HINT_CLEAR_FB)
1198                            && layer->isOpaque()) {
1199                        // never clear the very first layer since we're
1200                        // guaranteed the FB is already cleared
1201                        layer->clearWithOpenGL(hw, clip);
1202                    }
1203                    ++cur;
1204                    continue;
1205                }
1206                // render the layer
1207                layer->draw(hw, clip);
1208            }
1209            if (cur != end) {
1210                ++cur;
1211            }
1212        }
1213    }
1214}
1215
1216void SurfaceFlinger::debugFlashRegions(const sp<const DisplayDevice>& hw,
1217        const Region& dirtyRegion)
1218{
1219    const uint32_t flags = hw->getFlags();
1220    const int32_t height = hw->getHeight();
1221    if (hw->swapRegion.isEmpty()) {
1222        return;
1223    }
1224
1225    if (!(flags & DisplayDevice::SWAP_RECTANGLE)) {
1226        const Region repaint((flags & DisplayDevice::PARTIAL_UPDATES) ?
1227                dirtyRegion.bounds() : hw->bounds());
1228        composeSurfaces(hw, repaint);
1229    }
1230
1231    glDisable(GL_TEXTURE_EXTERNAL_OES);
1232    glDisable(GL_TEXTURE_2D);
1233    glDisable(GL_BLEND);
1234
1235    static int toggle = 0;
1236    toggle = 1 - toggle;
1237    if (toggle) {
1238        glColor4f(1, 0, 1, 1);
1239    } else {
1240        glColor4f(1, 1, 0, 1);
1241    }
1242
1243    Region::const_iterator it = dirtyRegion.begin();
1244    Region::const_iterator const end = dirtyRegion.end();
1245    while (it != end) {
1246        const Rect& r = *it++;
1247        GLfloat vertices[][2] = {
1248                { r.left,  height - r.top },
1249                { r.left,  height - r.bottom },
1250                { r.right, height - r.bottom },
1251                { r.right, height - r.top }
1252        };
1253        glVertexPointer(2, GL_FLOAT, 0, vertices);
1254        glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1255    }
1256
1257    hw->flip(hw->swapRegion);
1258
1259    if (mDebugRegion > 1)
1260        usleep(mDebugRegion * 1000);
1261}
1262
1263void SurfaceFlinger::drawWormhole(const Region& region) const
1264{
1265    glDisable(GL_TEXTURE_EXTERNAL_OES);
1266    glDisable(GL_TEXTURE_2D);
1267    glDisable(GL_BLEND);
1268    glColor4f(0,0,0,0);
1269
1270    GLfloat vertices[4][2];
1271    glVertexPointer(2, GL_FLOAT, 0, vertices);
1272    Region::const_iterator it = region.begin();
1273    Region::const_iterator const end = region.end();
1274    while (it != end) {
1275        const Rect& r = *it++;
1276        vertices[0][0] = r.left;
1277        vertices[0][1] = r.top;
1278        vertices[1][0] = r.right;
1279        vertices[1][1] = r.top;
1280        vertices[2][0] = r.right;
1281        vertices[2][1] = r.bottom;
1282        vertices[3][0] = r.left;
1283        vertices[3][1] = r.bottom;
1284        glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1285    }
1286}
1287
1288ssize_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
1289        const sp<LayerBaseClient>& lbc)
1290{
1291    // attach this layer to the client
1292    size_t name = client->attachLayer(lbc);
1293
1294    // add this layer to the current state list
1295    Mutex::Autolock _l(mStateLock);
1296    mCurrentState.layersSortedByZ.add(lbc);
1297
1298    return ssize_t(name);
1299}
1300
1301status_t SurfaceFlinger::removeLayer(const sp<LayerBase>& layer)
1302{
1303    Mutex::Autolock _l(mStateLock);
1304    status_t err = purgatorizeLayer_l(layer);
1305    if (err == NO_ERROR)
1306        setTransactionFlags(eTransactionNeeded);
1307    return err;
1308}
1309
1310status_t SurfaceFlinger::removeLayer_l(const sp<LayerBase>& layerBase)
1311{
1312    ssize_t index = mCurrentState.layersSortedByZ.remove(layerBase);
1313    if (index >= 0) {
1314        mLayersRemoved = true;
1315        return NO_ERROR;
1316    }
1317    return status_t(index);
1318}
1319
1320status_t SurfaceFlinger::purgatorizeLayer_l(const sp<LayerBase>& layerBase)
1321{
1322    // First add the layer to the purgatory list, which makes sure it won't
1323    // go away, then remove it from the main list (through a transaction).
1324    ssize_t err = removeLayer_l(layerBase);
1325    if (err >= 0) {
1326        mLayerPurgatory.add(layerBase);
1327    }
1328
1329    mLayersPendingRemoval.push(layerBase);
1330
1331    // it's possible that we don't find a layer, because it might
1332    // have been destroyed already -- this is not technically an error
1333    // from the user because there is a race between Client::destroySurface(),
1334    // ~Client() and ~ISurface().
1335    return (err == NAME_NOT_FOUND) ? status_t(NO_ERROR) : err;
1336}
1337
1338uint32_t SurfaceFlinger::peekTransactionFlags(uint32_t flags)
1339{
1340    return android_atomic_release_load(&mTransactionFlags);
1341}
1342
1343uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags)
1344{
1345    return android_atomic_and(~flags, &mTransactionFlags) & flags;
1346}
1347
1348uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags)
1349{
1350    uint32_t old = android_atomic_or(flags, &mTransactionFlags);
1351    if ((old & flags)==0) { // wake the server up
1352        signalTransaction();
1353    }
1354    return old;
1355}
1356
1357
1358void SurfaceFlinger::setTransactionState(
1359        const Vector<ComposerState>& state,
1360        const Vector<DisplayState>& displays,
1361        uint32_t flags)
1362{
1363    Mutex::Autolock _l(mStateLock);
1364
1365    int orientation = eOrientationUnchanged;
1366    if (displays.size()) {
1367        // TODO: handle all displays
1368        orientation = displays[0].orientation;
1369    }
1370
1371    uint32_t transactionFlags = 0;
1372    // FIXME: don't hardcode display id here
1373    if (mCurrentState.displays.valueFor(0).orientation != orientation) {
1374        if (uint32_t(orientation)<=eOrientation270 || orientation==42) {
1375            mCurrentState.displays.editValueFor(0).orientation = orientation;
1376            transactionFlags |= eTransactionNeeded;
1377        } else if (orientation != eOrientationUnchanged) {
1378            ALOGW("setTransactionState: ignoring unrecognized orientation: %d",
1379                    orientation);
1380        }
1381    }
1382
1383    const size_t count = state.size();
1384    for (size_t i=0 ; i<count ; i++) {
1385        const ComposerState& s(state[i]);
1386        sp<Client> client( static_cast<Client *>(s.client.get()) );
1387        transactionFlags |= setClientStateLocked(client, s.state);
1388    }
1389
1390    if (transactionFlags) {
1391        // this triggers the transaction
1392        setTransactionFlags(transactionFlags);
1393
1394        // if this is a synchronous transaction, wait for it to take effect
1395        // before returning.
1396        if (flags & eSynchronous) {
1397            mTransationPending = true;
1398        }
1399        while (mTransationPending) {
1400            status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
1401            if (CC_UNLIKELY(err != NO_ERROR)) {
1402                // just in case something goes wrong in SF, return to the
1403                // called after a few seconds.
1404                ALOGW_IF(err == TIMED_OUT, "closeGlobalTransaction timed out!");
1405                mTransationPending = false;
1406                break;
1407            }
1408        }
1409    }
1410}
1411
1412sp<ISurface> SurfaceFlinger::createLayer(
1413        ISurfaceComposerClient::surface_data_t* params,
1414        const String8& name,
1415        const sp<Client>& client,
1416        DisplayID d, uint32_t w, uint32_t h, PixelFormat format,
1417        uint32_t flags)
1418{
1419    sp<LayerBaseClient> layer;
1420    sp<ISurface> surfaceHandle;
1421
1422    if (int32_t(w|h) < 0) {
1423        ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
1424                int(w), int(h));
1425        return surfaceHandle;
1426    }
1427
1428    //ALOGD("createLayer for (%d x %d), name=%s", w, h, name.string());
1429    switch (flags & eFXSurfaceMask) {
1430        case eFXSurfaceNormal:
1431            layer = createNormalLayer(client, d, w, h, flags, format);
1432            break;
1433        case eFXSurfaceBlur:
1434            // for now we treat Blur as Dim, until we can implement it
1435            // efficiently.
1436        case eFXSurfaceDim:
1437            layer = createDimLayer(client, d, w, h, flags);
1438            break;
1439        case eFXSurfaceScreenshot:
1440            layer = createScreenshotLayer(client, d, w, h, flags);
1441            break;
1442    }
1443
1444    if (layer != 0) {
1445        layer->initStates(w, h, flags);
1446        layer->setName(name);
1447        ssize_t token = addClientLayer(client, layer);
1448        surfaceHandle = layer->getSurface();
1449        if (surfaceHandle != 0) {
1450            params->token = token;
1451            params->identity = layer->getIdentity();
1452        }
1453        setTransactionFlags(eTransactionNeeded);
1454    }
1455
1456    return surfaceHandle;
1457}
1458
1459sp<Layer> SurfaceFlinger::createNormalLayer(
1460        const sp<Client>& client, DisplayID display,
1461        uint32_t w, uint32_t h, uint32_t flags,
1462        PixelFormat& format)
1463{
1464    // initialize the surfaces
1465    switch (format) {
1466    case PIXEL_FORMAT_TRANSPARENT:
1467    case PIXEL_FORMAT_TRANSLUCENT:
1468        format = PIXEL_FORMAT_RGBA_8888;
1469        break;
1470    case PIXEL_FORMAT_OPAQUE:
1471#ifdef NO_RGBX_8888
1472        format = PIXEL_FORMAT_RGB_565;
1473#else
1474        format = PIXEL_FORMAT_RGBX_8888;
1475#endif
1476        break;
1477    }
1478
1479#ifdef NO_RGBX_8888
1480    if (format == PIXEL_FORMAT_RGBX_8888)
1481        format = PIXEL_FORMAT_RGBA_8888;
1482#endif
1483
1484    sp<Layer> layer = new Layer(this, display, client);
1485    status_t err = layer->setBuffers(w, h, format, flags);
1486    if (CC_LIKELY(err != NO_ERROR)) {
1487        ALOGE("createNormalLayer() failed (%s)", strerror(-err));
1488        layer.clear();
1489    }
1490    return layer;
1491}
1492
1493sp<LayerDim> SurfaceFlinger::createDimLayer(
1494        const sp<Client>& client, DisplayID display,
1495        uint32_t w, uint32_t h, uint32_t flags)
1496{
1497    sp<LayerDim> layer = new LayerDim(this, display, client);
1498    return layer;
1499}
1500
1501sp<LayerScreenshot> SurfaceFlinger::createScreenshotLayer(
1502        const sp<Client>& client, DisplayID display,
1503        uint32_t w, uint32_t h, uint32_t flags)
1504{
1505    sp<LayerScreenshot> layer = new LayerScreenshot(this, display, client);
1506    return layer;
1507}
1508
1509status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, SurfaceID sid)
1510{
1511    /*
1512     * called by the window manager, when a surface should be marked for
1513     * destruction.
1514     *
1515     * The surface is removed from the current and drawing lists, but placed
1516     * in the purgatory queue, so it's not destroyed right-away (we need
1517     * to wait for all client's references to go away first).
1518     */
1519
1520    status_t err = NAME_NOT_FOUND;
1521    Mutex::Autolock _l(mStateLock);
1522    sp<LayerBaseClient> layer = client->getLayerUser(sid);
1523
1524    if (layer != 0) {
1525        err = purgatorizeLayer_l(layer);
1526        if (err == NO_ERROR) {
1527            setTransactionFlags(eTransactionNeeded);
1528        }
1529    }
1530    return err;
1531}
1532
1533status_t SurfaceFlinger::onLayerDestroyed(const wp<LayerBaseClient>& layer)
1534{
1535    // called by ~ISurface() when all references are gone
1536    status_t err = NO_ERROR;
1537    sp<LayerBaseClient> l(layer.promote());
1538    if (l != NULL) {
1539        Mutex::Autolock _l(mStateLock);
1540        err = removeLayer_l(l);
1541        if (err == NAME_NOT_FOUND) {
1542            // The surface wasn't in the current list, which means it was
1543            // removed already, which means it is in the purgatory,
1544            // and need to be removed from there.
1545            ssize_t idx = mLayerPurgatory.remove(l);
1546            ALOGE_IF(idx < 0,
1547                    "layer=%p is not in the purgatory list", l.get());
1548        }
1549        ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
1550                "error removing layer=%p (%s)", l.get(), strerror(-err));
1551    }
1552    return err;
1553}
1554
1555uint32_t SurfaceFlinger::setClientStateLocked(
1556        const sp<Client>& client,
1557        const layer_state_t& s)
1558{
1559    uint32_t flags = 0;
1560    sp<LayerBaseClient> layer(client->getLayerUser(s.surface));
1561    if (layer != 0) {
1562        const uint32_t what = s.what;
1563        if (what & ePositionChanged) {
1564            if (layer->setPosition(s.x, s.y))
1565                flags |= eTraversalNeeded;
1566        }
1567        if (what & eLayerChanged) {
1568            // NOTE: index needs to be calculated before we update the state
1569            ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
1570            if (layer->setLayer(s.z)) {
1571                mCurrentState.layersSortedByZ.removeAt(idx);
1572                mCurrentState.layersSortedByZ.add(layer);
1573                // we need traversal (state changed)
1574                // AND transaction (list changed)
1575                flags |= eTransactionNeeded|eTraversalNeeded;
1576            }
1577        }
1578        if (what & eSizeChanged) {
1579            if (layer->setSize(s.w, s.h)) {
1580                flags |= eTraversalNeeded;
1581            }
1582        }
1583        if (what & eAlphaChanged) {
1584            if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
1585                flags |= eTraversalNeeded;
1586        }
1587        if (what & eMatrixChanged) {
1588            if (layer->setMatrix(s.matrix))
1589                flags |= eTraversalNeeded;
1590        }
1591        if (what & eTransparentRegionChanged) {
1592            if (layer->setTransparentRegionHint(s.transparentRegion))
1593                flags |= eTraversalNeeded;
1594        }
1595        if (what & eVisibilityChanged) {
1596            if (layer->setFlags(s.flags, s.mask))
1597                flags |= eTraversalNeeded;
1598        }
1599        if (what & eCropChanged) {
1600            if (layer->setCrop(s.crop))
1601                flags |= eTraversalNeeded;
1602        }
1603        if (what & eLayerStackChanged) {
1604            // NOTE: index needs to be calculated before we update the state
1605            ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
1606            if (layer->setLayerStack(s.layerStack)) {
1607                mCurrentState.layersSortedByZ.removeAt(idx);
1608                mCurrentState.layersSortedByZ.add(layer);
1609                // we need traversal (state changed)
1610                // AND transaction (list changed)
1611                flags |= eTransactionNeeded|eTraversalNeeded;
1612            }
1613        }
1614    }
1615    return flags;
1616}
1617
1618// ---------------------------------------------------------------------------
1619
1620void SurfaceFlinger::onScreenAcquired() {
1621    ALOGD("Screen about to return, flinger = %p", this);
1622    sp<const DisplayDevice> hw(getDefaultDisplayDevice()); // XXX: this should be per DisplayDevice
1623    getHwComposer().acquire();
1624    hw->acquireScreen();
1625    mEventThread->onScreenAcquired();
1626}
1627
1628void SurfaceFlinger::onScreenReleased() {
1629    ALOGD("About to give-up screen, flinger = %p", this);
1630    sp<const DisplayDevice> hw(getDefaultDisplayDevice()); // XXX: this should be per DisplayDevice
1631    if (hw->isScreenAcquired()) {
1632        mEventThread->onScreenReleased();
1633        hw->releaseScreen();
1634        getHwComposer().release();
1635        // from this point on, SF will stop drawing
1636    }
1637}
1638
1639void SurfaceFlinger::unblank() {
1640    class MessageScreenAcquired : public MessageBase {
1641        SurfaceFlinger* flinger;
1642    public:
1643        MessageScreenAcquired(SurfaceFlinger* flinger) : flinger(flinger) { }
1644        virtual bool handler() {
1645            flinger->onScreenAcquired();
1646            return true;
1647        }
1648    };
1649    sp<MessageBase> msg = new MessageScreenAcquired(this);
1650    postMessageSync(msg);
1651}
1652
1653void SurfaceFlinger::blank() {
1654    class MessageScreenReleased : public MessageBase {
1655        SurfaceFlinger* flinger;
1656    public:
1657        MessageScreenReleased(SurfaceFlinger* flinger) : flinger(flinger) { }
1658        virtual bool handler() {
1659            flinger->onScreenReleased();
1660            return true;
1661        }
1662    };
1663    sp<MessageBase> msg = new MessageScreenReleased(this);
1664    postMessageSync(msg);
1665}
1666
1667// ---------------------------------------------------------------------------
1668
1669status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
1670{
1671    const size_t SIZE = 4096;
1672    char buffer[SIZE];
1673    String8 result;
1674
1675    if (!PermissionCache::checkCallingPermission(sDump)) {
1676        snprintf(buffer, SIZE, "Permission Denial: "
1677                "can't dump SurfaceFlinger from pid=%d, uid=%d\n",
1678                IPCThreadState::self()->getCallingPid(),
1679                IPCThreadState::self()->getCallingUid());
1680        result.append(buffer);
1681    } else {
1682        // Try to get the main lock, but don't insist if we can't
1683        // (this would indicate SF is stuck, but we want to be able to
1684        // print something in dumpsys).
1685        int retry = 3;
1686        while (mStateLock.tryLock()<0 && --retry>=0) {
1687            usleep(1000000);
1688        }
1689        const bool locked(retry >= 0);
1690        if (!locked) {
1691            snprintf(buffer, SIZE,
1692                    "SurfaceFlinger appears to be unresponsive, "
1693                    "dumping anyways (no locks held)\n");
1694            result.append(buffer);
1695        }
1696
1697        bool dumpAll = true;
1698        size_t index = 0;
1699        size_t numArgs = args.size();
1700        if (numArgs) {
1701            if ((index < numArgs) &&
1702                    (args[index] == String16("--list"))) {
1703                index++;
1704                listLayersLocked(args, index, result, buffer, SIZE);
1705                dumpAll = false;
1706            }
1707
1708            if ((index < numArgs) &&
1709                    (args[index] == String16("--latency"))) {
1710                index++;
1711                dumpStatsLocked(args, index, result, buffer, SIZE);
1712                dumpAll = false;
1713            }
1714
1715            if ((index < numArgs) &&
1716                    (args[index] == String16("--latency-clear"))) {
1717                index++;
1718                clearStatsLocked(args, index, result, buffer, SIZE);
1719                dumpAll = false;
1720            }
1721        }
1722
1723        if (dumpAll) {
1724            dumpAllLocked(result, buffer, SIZE);
1725        }
1726
1727        if (locked) {
1728            mStateLock.unlock();
1729        }
1730    }
1731    write(fd, result.string(), result.size());
1732    return NO_ERROR;
1733}
1734
1735void SurfaceFlinger::listLayersLocked(const Vector<String16>& args, size_t& index,
1736        String8& result, char* buffer, size_t SIZE) const
1737{
1738    const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
1739    const size_t count = currentLayers.size();
1740    for (size_t i=0 ; i<count ; i++) {
1741        const sp<LayerBase>& layer(currentLayers[i]);
1742        snprintf(buffer, SIZE, "%s\n", layer->getName().string());
1743        result.append(buffer);
1744    }
1745}
1746
1747void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
1748        String8& result, char* buffer, size_t SIZE) const
1749{
1750    String8 name;
1751    if (index < args.size()) {
1752        name = String8(args[index]);
1753        index++;
1754    }
1755
1756    const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
1757    const size_t count = currentLayers.size();
1758    for (size_t i=0 ; i<count ; i++) {
1759        const sp<LayerBase>& layer(currentLayers[i]);
1760        if (name.isEmpty()) {
1761            snprintf(buffer, SIZE, "%s\n", layer->getName().string());
1762            result.append(buffer);
1763        }
1764        if (name.isEmpty() || (name == layer->getName())) {
1765            layer->dumpStats(result, buffer, SIZE);
1766        }
1767    }
1768}
1769
1770void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
1771        String8& result, char* buffer, size_t SIZE) const
1772{
1773    String8 name;
1774    if (index < args.size()) {
1775        name = String8(args[index]);
1776        index++;
1777    }
1778
1779    const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
1780    const size_t count = currentLayers.size();
1781    for (size_t i=0 ; i<count ; i++) {
1782        const sp<LayerBase>& layer(currentLayers[i]);
1783        if (name.isEmpty() || (name == layer->getName())) {
1784            layer->clearStats();
1785        }
1786    }
1787}
1788
1789void SurfaceFlinger::dumpAllLocked(
1790        String8& result, char* buffer, size_t SIZE) const
1791{
1792    // figure out if we're stuck somewhere
1793    const nsecs_t now = systemTime();
1794    const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
1795    const nsecs_t inTransaction(mDebugInTransaction);
1796    nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
1797    nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
1798
1799    /*
1800     * Dump the visible layer list
1801     */
1802    const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
1803    const size_t count = currentLayers.size();
1804    snprintf(buffer, SIZE, "Visible layers (count = %d)\n", count);
1805    result.append(buffer);
1806    for (size_t i=0 ; i<count ; i++) {
1807        const sp<LayerBase>& layer(currentLayers[i]);
1808        layer->dump(result, buffer, SIZE);
1809    }
1810
1811    /*
1812     * Dump the layers in the purgatory
1813     */
1814
1815    const size_t purgatorySize = mLayerPurgatory.size();
1816    snprintf(buffer, SIZE, "Purgatory state (%d entries)\n", purgatorySize);
1817    result.append(buffer);
1818    for (size_t i=0 ; i<purgatorySize ; i++) {
1819        const sp<LayerBase>& layer(mLayerPurgatory.itemAt(i));
1820        layer->shortDump(result, buffer, SIZE);
1821    }
1822
1823    /*
1824     * Dump SurfaceFlinger global state
1825     */
1826
1827    snprintf(buffer, SIZE, "SurfaceFlinger global state:\n");
1828    result.append(buffer);
1829
1830    HWComposer& hwc(getHwComposer());
1831    sp<const DisplayDevice> hw(getDefaultDisplayDevice());
1832    const GLExtensions& extensions(GLExtensions::getInstance());
1833    snprintf(buffer, SIZE, "GLES: %s, %s, %s\n",
1834            extensions.getVendor(),
1835            extensions.getRenderer(),
1836            extensions.getVersion());
1837    result.append(buffer);
1838
1839    snprintf(buffer, SIZE, "EGL : %s\n",
1840            eglQueryString(mEGLDisplay, EGL_VERSION_HW_ANDROID));
1841    result.append(buffer);
1842
1843    snprintf(buffer, SIZE, "EXTS: %s\n", extensions.getExtension());
1844    result.append(buffer);
1845
1846    hw->undefinedRegion.dump(result, "undefinedRegion");
1847    snprintf(buffer, SIZE,
1848            "  orientation=%d, canDraw=%d\n",
1849            hw->getOrientation(), hw->canDraw());
1850    result.append(buffer);
1851    snprintf(buffer, SIZE,
1852            "  last eglSwapBuffers() time: %f us\n"
1853            "  last transaction time     : %f us\n"
1854            "  transaction-flags         : %08x\n"
1855            "  refresh-rate              : %f fps\n"
1856            "  x-dpi                     : %f\n"
1857            "  y-dpi                     : %f\n"
1858            "  density                   : %f\n",
1859            mLastSwapBufferTime/1000.0,
1860            mLastTransactionTime/1000.0,
1861            mTransactionFlags,
1862            1e9 / hwc.getRefreshPeriod(),
1863            hw->getDpiX(),
1864            hw->getDpiY(),
1865            hw->getDensity());
1866    result.append(buffer);
1867
1868    snprintf(buffer, SIZE, "  eglSwapBuffers time: %f us\n",
1869            inSwapBuffersDuration/1000.0);
1870    result.append(buffer);
1871
1872    snprintf(buffer, SIZE, "  transaction time: %f us\n",
1873            inTransactionDuration/1000.0);
1874    result.append(buffer);
1875
1876    /*
1877     * VSYNC state
1878     */
1879    mEventThread->dump(result, buffer, SIZE);
1880
1881    /*
1882     * Dump HWComposer state
1883     */
1884    snprintf(buffer, SIZE, "h/w composer state:\n");
1885    result.append(buffer);
1886    snprintf(buffer, SIZE, "  h/w composer %s and %s\n",
1887            hwc.initCheck()==NO_ERROR ? "present" : "not present",
1888                    (mDebugDisableHWC || mDebugRegion) ? "disabled" : "enabled");
1889    result.append(buffer);
1890    hwc.dump(result, buffer, SIZE, hw->getVisibleLayersSortedByZ());
1891
1892    /*
1893     * Dump gralloc state
1894     */
1895    const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
1896    alloc.dump(result);
1897    hw->dump(result);
1898}
1899
1900status_t SurfaceFlinger::onTransact(
1901    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1902{
1903    switch (code) {
1904        case CREATE_CONNECTION:
1905        case SET_TRANSACTION_STATE:
1906        case SET_ORIENTATION:
1907        case BOOT_FINISHED:
1908        case BLANK:
1909        case UNBLANK:
1910        {
1911            // codes that require permission check
1912            IPCThreadState* ipc = IPCThreadState::self();
1913            const int pid = ipc->getCallingPid();
1914            const int uid = ipc->getCallingUid();
1915            if ((uid != AID_GRAPHICS) &&
1916                    !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
1917                ALOGE("Permission Denial: "
1918                        "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
1919                return PERMISSION_DENIED;
1920            }
1921            break;
1922        }
1923        case CAPTURE_SCREEN:
1924        {
1925            // codes that require permission check
1926            IPCThreadState* ipc = IPCThreadState::self();
1927            const int pid = ipc->getCallingPid();
1928            const int uid = ipc->getCallingUid();
1929            if ((uid != AID_GRAPHICS) &&
1930                    !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
1931                ALOGE("Permission Denial: "
1932                        "can't read framebuffer pid=%d, uid=%d", pid, uid);
1933                return PERMISSION_DENIED;
1934            }
1935            break;
1936        }
1937    }
1938
1939    status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
1940    if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
1941        CHECK_INTERFACE(ISurfaceComposer, data, reply);
1942        if (CC_UNLIKELY(!PermissionCache::checkCallingPermission(sHardwareTest))) {
1943            IPCThreadState* ipc = IPCThreadState::self();
1944            const int pid = ipc->getCallingPid();
1945            const int uid = ipc->getCallingUid();
1946            ALOGE("Permission Denial: "
1947                    "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
1948            return PERMISSION_DENIED;
1949        }
1950        int n;
1951        switch (code) {
1952            case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
1953            case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
1954                return NO_ERROR;
1955            case 1002:  // SHOW_UPDATES
1956                n = data.readInt32();
1957                mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
1958                invalidateHwcGeometry();
1959                repaintEverything();
1960                return NO_ERROR;
1961            case 1004:{ // repaint everything
1962                repaintEverything();
1963                return NO_ERROR;
1964            }
1965            case 1005:{ // force transaction
1966                setTransactionFlags(eTransactionNeeded|eTraversalNeeded);
1967                return NO_ERROR;
1968            }
1969            case 1006:{ // send empty update
1970                signalRefresh();
1971                return NO_ERROR;
1972            }
1973            case 1008:  // toggle use of hw composer
1974                n = data.readInt32();
1975                mDebugDisableHWC = n ? 1 : 0;
1976                invalidateHwcGeometry();
1977                repaintEverything();
1978                return NO_ERROR;
1979            case 1009:  // toggle use of transform hint
1980                n = data.readInt32();
1981                mDebugDisableTransformHint = n ? 1 : 0;
1982                invalidateHwcGeometry();
1983                repaintEverything();
1984                return NO_ERROR;
1985            case 1010:  // interrogate.
1986                reply->writeInt32(0);
1987                reply->writeInt32(0);
1988                reply->writeInt32(mDebugRegion);
1989                reply->writeInt32(0);
1990                reply->writeInt32(mDebugDisableHWC);
1991                return NO_ERROR;
1992            case 1013: {
1993                Mutex::Autolock _l(mStateLock);
1994                sp<const DisplayDevice> hw(getDefaultDisplayDevice());
1995                reply->writeInt32(hw->getPageFlipCount());
1996            }
1997            return NO_ERROR;
1998        }
1999    }
2000    return err;
2001}
2002
2003void SurfaceFlinger::repaintEverything() {
2004    android_atomic_or(1, &mRepaintEverything);
2005    signalTransaction();
2006}
2007
2008// ---------------------------------------------------------------------------
2009
2010status_t SurfaceFlinger::renderScreenToTexture(DisplayID dpy,
2011        GLuint* textureName, GLfloat* uOut, GLfloat* vOut)
2012{
2013    Mutex::Autolock _l(mStateLock);
2014    return renderScreenToTextureLocked(dpy, textureName, uOut, vOut);
2015}
2016
2017status_t SurfaceFlinger::renderScreenToTextureLocked(DisplayID dpy,
2018        GLuint* textureName, GLfloat* uOut, GLfloat* vOut)
2019{
2020    ATRACE_CALL();
2021
2022    if (!GLExtensions::getInstance().haveFramebufferObject())
2023        return INVALID_OPERATION;
2024
2025    // get screen geometry
2026    sp<const DisplayDevice> hw(getDisplayDevice(dpy));
2027    const uint32_t hw_w = hw->getWidth();
2028    const uint32_t hw_h = hw->getHeight();
2029    GLfloat u = 1;
2030    GLfloat v = 1;
2031
2032    // make sure to clear all GL error flags
2033    while ( glGetError() != GL_NO_ERROR ) ;
2034
2035    // create a FBO
2036    GLuint name, tname;
2037    glGenTextures(1, &tname);
2038    glBindTexture(GL_TEXTURE_2D, tname);
2039    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
2040    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
2041    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB,
2042            hw_w, hw_h, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);
2043    if (glGetError() != GL_NO_ERROR) {
2044        while ( glGetError() != GL_NO_ERROR ) ;
2045        GLint tw = (2 << (31 - clz(hw_w)));
2046        GLint th = (2 << (31 - clz(hw_h)));
2047        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB,
2048                tw, th, 0, GL_RGB, GL_UNSIGNED_BYTE, 0);
2049        u = GLfloat(hw_w) / tw;
2050        v = GLfloat(hw_h) / th;
2051    }
2052    glGenFramebuffersOES(1, &name);
2053    glBindFramebufferOES(GL_FRAMEBUFFER_OES, name);
2054    glFramebufferTexture2DOES(GL_FRAMEBUFFER_OES,
2055            GL_COLOR_ATTACHMENT0_OES, GL_TEXTURE_2D, tname, 0);
2056
2057    // redraw the screen entirely...
2058    glDisable(GL_TEXTURE_EXTERNAL_OES);
2059    glDisable(GL_TEXTURE_2D);
2060    glClearColor(0,0,0,1);
2061    glClear(GL_COLOR_BUFFER_BIT);
2062    glMatrixMode(GL_MODELVIEW);
2063    glLoadIdentity();
2064    const Vector< sp<LayerBase> >& layers(hw->getVisibleLayersSortedByZ());
2065    const size_t count = layers.size();
2066    for (size_t i=0 ; i<count ; ++i) {
2067        const sp<LayerBase>& layer(layers[i]);
2068        layer->draw(hw);
2069    }
2070
2071    hw->compositionComplete();
2072
2073    // back to main framebuffer
2074    glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0);
2075    glDeleteFramebuffersOES(1, &name);
2076
2077    *textureName = tname;
2078    *uOut = u;
2079    *vOut = v;
2080    return NO_ERROR;
2081}
2082
2083// ---------------------------------------------------------------------------
2084
2085status_t SurfaceFlinger::captureScreenImplLocked(DisplayID dpy,
2086        sp<IMemoryHeap>* heap,
2087        uint32_t* w, uint32_t* h, PixelFormat* f,
2088        uint32_t sw, uint32_t sh,
2089        uint32_t minLayerZ, uint32_t maxLayerZ)
2090{
2091    ATRACE_CALL();
2092
2093    status_t result = PERMISSION_DENIED;
2094
2095    // only one display supported for now
2096    if (CC_UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT)) {
2097        return BAD_VALUE;
2098    }
2099
2100    if (!GLExtensions::getInstance().haveFramebufferObject()) {
2101        return INVALID_OPERATION;
2102    }
2103
2104    // get screen geometry
2105    sp<const DisplayDevice> hw(getDisplayDevice(dpy));
2106    const uint32_t hw_w = hw->getWidth();
2107    const uint32_t hw_h = hw->getHeight();
2108
2109    // if we have secure windows on this display, never allow the screen capture
2110    if (hw->getSecureLayerVisible()) {
2111        return PERMISSION_DENIED;
2112    }
2113
2114    if ((sw > hw_w) || (sh > hw_h)) {
2115        return BAD_VALUE;
2116    }
2117
2118    sw = (!sw) ? hw_w : sw;
2119    sh = (!sh) ? hw_h : sh;
2120    const size_t size = sw * sh * 4;
2121    const bool filtering = sw != hw_w || sh != hw_h;
2122
2123    //ALOGD("screenshot: sw=%d, sh=%d, minZ=%d, maxZ=%d",
2124    //        sw, sh, minLayerZ, maxLayerZ);
2125
2126    // make sure to clear all GL error flags
2127    while ( glGetError() != GL_NO_ERROR ) ;
2128
2129    // create a FBO
2130    GLuint name, tname;
2131    glGenRenderbuffersOES(1, &tname);
2132    glBindRenderbufferOES(GL_RENDERBUFFER_OES, tname);
2133    glRenderbufferStorageOES(GL_RENDERBUFFER_OES, GL_RGBA8_OES, sw, sh);
2134
2135    glGenFramebuffersOES(1, &name);
2136    glBindFramebufferOES(GL_FRAMEBUFFER_OES, name);
2137    glFramebufferRenderbufferOES(GL_FRAMEBUFFER_OES,
2138            GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, tname);
2139
2140    GLenum status = glCheckFramebufferStatusOES(GL_FRAMEBUFFER_OES);
2141
2142    if (status == GL_FRAMEBUFFER_COMPLETE_OES) {
2143
2144        // invert everything, b/c glReadPixel() below will invert the FB
2145        glViewport(0, 0, sw, sh);
2146        glMatrixMode(GL_PROJECTION);
2147        glPushMatrix();
2148        glLoadIdentity();
2149        glOrthof(0, hw_w, hw_h, 0, 0, 1);
2150        glMatrixMode(GL_MODELVIEW);
2151
2152        // redraw the screen entirely...
2153        glClearColor(0,0,0,1);
2154        glClear(GL_COLOR_BUFFER_BIT);
2155
2156        const LayerVector& layers(mDrawingState.layersSortedByZ);
2157        const size_t count = layers.size();
2158        for (size_t i=0 ; i<count ; ++i) {
2159            const sp<LayerBase>& layer(layers[i]);
2160            const uint32_t flags = layer->drawingState().flags;
2161            if (!(flags & ISurfaceComposer::eLayerHidden)) {
2162                const uint32_t z = layer->drawingState().z;
2163                if (z >= minLayerZ && z <= maxLayerZ) {
2164                    if (filtering) layer->setFiltering(true);
2165                    layer->draw(hw);
2166                    if (filtering) layer->setFiltering(false);
2167                }
2168            }
2169        }
2170
2171        // check for errors and return screen capture
2172        if (glGetError() != GL_NO_ERROR) {
2173            // error while rendering
2174            result = INVALID_OPERATION;
2175        } else {
2176            // allocate shared memory large enough to hold the
2177            // screen capture
2178            sp<MemoryHeapBase> base(
2179                    new MemoryHeapBase(size, 0, "screen-capture") );
2180            void* const ptr = base->getBase();
2181            if (ptr) {
2182                // capture the screen with glReadPixels()
2183                ScopedTrace _t(ATRACE_TAG, "glReadPixels");
2184                glReadPixels(0, 0, sw, sh, GL_RGBA, GL_UNSIGNED_BYTE, ptr);
2185                if (glGetError() == GL_NO_ERROR) {
2186                    *heap = base;
2187                    *w = sw;
2188                    *h = sh;
2189                    *f = PIXEL_FORMAT_RGBA_8888;
2190                    result = NO_ERROR;
2191                }
2192            } else {
2193                result = NO_MEMORY;
2194            }
2195        }
2196        glViewport(0, 0, hw_w, hw_h);
2197        glMatrixMode(GL_PROJECTION);
2198        glPopMatrix();
2199        glMatrixMode(GL_MODELVIEW);
2200    } else {
2201        result = BAD_VALUE;
2202    }
2203
2204    // release FBO resources
2205    glBindFramebufferOES(GL_FRAMEBUFFER_OES, 0);
2206    glDeleteRenderbuffersOES(1, &tname);
2207    glDeleteFramebuffersOES(1, &name);
2208
2209    hw->compositionComplete();
2210
2211    // ALOGD("screenshot: result = %s", result<0 ? strerror(result) : "OK");
2212
2213    return result;
2214}
2215
2216
2217status_t SurfaceFlinger::captureScreen(DisplayID dpy,
2218        sp<IMemoryHeap>* heap,
2219        uint32_t* width, uint32_t* height, PixelFormat* format,
2220        uint32_t sw, uint32_t sh,
2221        uint32_t minLayerZ, uint32_t maxLayerZ)
2222{
2223    // only one display supported for now
2224    if (CC_UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
2225        return BAD_VALUE;
2226
2227    if (!GLExtensions::getInstance().haveFramebufferObject())
2228        return INVALID_OPERATION;
2229
2230    class MessageCaptureScreen : public MessageBase {
2231        SurfaceFlinger* flinger;
2232        DisplayID dpy;
2233        sp<IMemoryHeap>* heap;
2234        uint32_t* w;
2235        uint32_t* h;
2236        PixelFormat* f;
2237        uint32_t sw;
2238        uint32_t sh;
2239        uint32_t minLayerZ;
2240        uint32_t maxLayerZ;
2241        status_t result;
2242    public:
2243        MessageCaptureScreen(SurfaceFlinger* flinger, DisplayID dpy,
2244                sp<IMemoryHeap>* heap, uint32_t* w, uint32_t* h, PixelFormat* f,
2245                uint32_t sw, uint32_t sh,
2246                uint32_t minLayerZ, uint32_t maxLayerZ)
2247            : flinger(flinger), dpy(dpy),
2248              heap(heap), w(w), h(h), f(f), sw(sw), sh(sh),
2249              minLayerZ(minLayerZ), maxLayerZ(maxLayerZ),
2250              result(PERMISSION_DENIED)
2251        {
2252        }
2253        status_t getResult() const {
2254            return result;
2255        }
2256        virtual bool handler() {
2257            Mutex::Autolock _l(flinger->mStateLock);
2258            result = flinger->captureScreenImplLocked(dpy,
2259                    heap, w, h, f, sw, sh, minLayerZ, maxLayerZ);
2260            return true;
2261        }
2262    };
2263
2264    sp<MessageBase> msg = new MessageCaptureScreen(this,
2265            dpy, heap, width, height, format, sw, sh, minLayerZ, maxLayerZ);
2266    status_t res = postMessageSync(msg);
2267    if (res == NO_ERROR) {
2268        res = static_cast<MessageCaptureScreen*>( msg.get() )->getResult();
2269    }
2270    return res;
2271}
2272
2273// ---------------------------------------------------------------------------
2274
2275SurfaceFlinger::LayerVector::LayerVector() {
2276}
2277
2278SurfaceFlinger::LayerVector::LayerVector(const LayerVector& rhs)
2279    : SortedVector<sp<LayerBase> >(rhs) {
2280}
2281
2282int SurfaceFlinger::LayerVector::do_compare(const void* lhs,
2283    const void* rhs) const
2284{
2285    // sort layers per layer-stack, then by z-order and finally by sequence
2286    const sp<LayerBase>& l(*reinterpret_cast<const sp<LayerBase>*>(lhs));
2287    const sp<LayerBase>& r(*reinterpret_cast<const sp<LayerBase>*>(rhs));
2288
2289    uint32_t ls = l->currentState().layerStack;
2290    uint32_t rs = r->currentState().layerStack;
2291    if (ls != rs)
2292        return ls - rs;
2293
2294    uint32_t lz = l->currentState().z;
2295    uint32_t rz = r->currentState().z;
2296    if (lz != rz)
2297        return lz - rz;
2298
2299    return l->sequence - r->sequence;
2300}
2301
2302// ---------------------------------------------------------------------------
2303
2304SurfaceFlinger::DisplayDeviceState::DisplayDeviceState()
2305    : id(DisplayDevice::DISPLAY_ID_MAIN), layerStack(0), orientation(0) {
2306}
2307
2308// ---------------------------------------------------------------------------
2309
2310GraphicBufferAlloc::GraphicBufferAlloc() {}
2311
2312GraphicBufferAlloc::~GraphicBufferAlloc() {}
2313
2314sp<GraphicBuffer> GraphicBufferAlloc::createGraphicBuffer(uint32_t w, uint32_t h,
2315        PixelFormat format, uint32_t usage, status_t* error) {
2316    sp<GraphicBuffer> graphicBuffer(new GraphicBuffer(w, h, format, usage));
2317    status_t err = graphicBuffer->initCheck();
2318    *error = err;
2319    if (err != 0 || graphicBuffer->handle == 0) {
2320        if (err == NO_MEMORY) {
2321            GraphicBuffer::dumpAllocationsToSystemLog();
2322        }
2323        ALOGE("GraphicBufferAlloc::createGraphicBuffer(w=%d, h=%d) "
2324             "failed (%s), handle=%p",
2325                w, h, strerror(-err), graphicBuffer->handle);
2326        return 0;
2327    }
2328    return graphicBuffer;
2329}
2330
2331// ---------------------------------------------------------------------------
2332
2333}; // namespace android
2334