Home | History | Annotate | Download | only in surfaceflinger
      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 #ifndef ANDROID_SURFACE_FLINGER_H
     18 #define ANDROID_SURFACE_FLINGER_H
     19 
     20 #include <stdint.h>
     21 #include <sys/types.h>
     22 
     23 #include <EGL/egl.h>
     24 #include <GLES/gl.h>
     25 
     26 #include <cutils/compiler.h>
     27 
     28 #include <utils/Atomic.h>
     29 #include <utils/Errors.h>
     30 #include <utils/KeyedVector.h>
     31 #include <utils/RefBase.h>
     32 #include <utils/SortedVector.h>
     33 #include <utils/threads.h>
     34 
     35 #include <binder/BinderService.h>
     36 #include <binder/IMemory.h>
     37 
     38 #include <ui/PixelFormat.h>
     39 
     40 #include <gui/ISurfaceComposer.h>
     41 #include <gui/ISurfaceComposerClient.h>
     42 
     43 #include <hardware/hwcomposer_defs.h>
     44 
     45 #include <private/gui/LayerState.h>
     46 
     47 #include "Barrier.h"
     48 #include "MessageQueue.h"
     49 #include "DisplayDevice.h"
     50 
     51 #include "DisplayHardware/HWComposer.h"
     52 
     53 namespace android {
     54 
     55 // ---------------------------------------------------------------------------
     56 
     57 class Client;
     58 class DisplayEventConnection;
     59 class EventThread;
     60 class IGraphicBufferAlloc;
     61 class Layer;
     62 class LayerBase;
     63 class LayerBaseClient;
     64 class LayerDim;
     65 class LayerScreenshot;
     66 class SurfaceTextureClient;
     67 
     68 // ---------------------------------------------------------------------------
     69 
     70 enum {
     71     eTransactionNeeded        = 0x01,
     72     eTraversalNeeded          = 0x02,
     73     eDisplayTransactionNeeded = 0x04,
     74     eTransactionMask          = 0x07
     75 };
     76 
     77 class SurfaceFlinger : public BinderService<SurfaceFlinger>,
     78                        public BnSurfaceComposer,
     79                        private IBinder::DeathRecipient,
     80                        private Thread,
     81                        private HWComposer::EventHandler
     82 {
     83 public:
     84     static char const* getServiceName() {
     85         return "SurfaceFlinger";
     86     }
     87 
     88     SurfaceFlinger();
     89 
     90     enum {
     91         EVENT_VSYNC = HWC_EVENT_VSYNC
     92     };
     93 
     94     // post an asynchronous message to the main thread
     95     status_t postMessageAsync(const sp<MessageBase>& msg, nsecs_t reltime = 0,
     96         uint32_t flags = 0);
     97 
     98     // post a synchronous message to the main thread
     99     status_t postMessageSync(const sp<MessageBase>& msg, nsecs_t reltime = 0,
    100         uint32_t flags = 0);
    101 
    102     // force full composition on all displays
    103     void repaintEverything();
    104 
    105     // renders content on given display to a texture. thread-safe version.
    106     status_t renderScreenToTexture(uint32_t layerStack, GLuint* textureName,
    107         GLfloat* uOut, GLfloat* vOut);
    108 
    109     // renders content on given display to a texture, w/o acquiring main lock
    110     status_t renderScreenToTextureLocked(uint32_t layerStack, GLuint* textureName,
    111         GLfloat* uOut, GLfloat* vOut);
    112 
    113     // returns the default Display
    114     sp<const DisplayDevice> getDefaultDisplayDevice() const {
    115         return getDisplayDevice(mDefaultDisplays[DisplayDevice::DISPLAY_PRIMARY]);
    116     }
    117 
    118     // utility function to delete a texture on the main thread
    119     void deleteTextureAsync(GLuint texture);
    120 
    121     // allocate a h/w composer display id
    122     int32_t allocateHwcDisplayId(DisplayDevice::DisplayType type);
    123 
    124     // enable/disable h/w composer event
    125     // TODO: this should be made accessible only to EventThread
    126     void eventControl(int disp, int event, int enabled);
    127 
    128     // called on the main thread by MessageQueue when an internal message
    129     // is received
    130     // TODO: this should be made accessible only to MessageQueue
    131     void onMessageReceived(int32_t what);
    132 
    133     // for debugging only
    134     // TODO: this should be made accessible only to HWComposer
    135     const Vector< sp<LayerBase> >& getLayerSortedByZForHwcDisplay(int disp);
    136 
    137 private:
    138     friend class Client;
    139     friend class DisplayEventConnection;
    140     friend class LayerBase;
    141     friend class LayerBaseClient;
    142     friend class Layer;
    143     friend class LayerScreenshot;
    144 
    145     // We're reference counted, never destroy SurfaceFlinger directly
    146     virtual ~SurfaceFlinger();
    147 
    148     /* ------------------------------------------------------------------------
    149      * Internal data structures
    150      */
    151 
    152     class LayerVector : public SortedVector<sp<LayerBase> > {
    153     public:
    154         LayerVector();
    155         LayerVector(const LayerVector& rhs);
    156         virtual int do_compare(const void* lhs, const void* rhs) const;
    157     };
    158 
    159     struct DisplayDeviceState {
    160         DisplayDeviceState();
    161         DisplayDeviceState(DisplayDevice::DisplayType type);
    162         bool isValid() const { return type >= 0; }
    163         bool isMainDisplay() const { return type == DisplayDevice::DISPLAY_PRIMARY; }
    164         bool isVirtualDisplay() const { return type >= DisplayDevice::DISPLAY_VIRTUAL; }
    165         DisplayDevice::DisplayType type;
    166         sp<ISurfaceTexture> surface;
    167         uint32_t layerStack;
    168         Rect viewport;
    169         Rect frame;
    170         uint8_t orientation;
    171         String8 displayName;
    172         bool isSecure;
    173     };
    174 
    175     struct State {
    176         LayerVector layersSortedByZ;
    177         DefaultKeyedVector< wp<IBinder>, DisplayDeviceState> displays;
    178     };
    179 
    180     /* ------------------------------------------------------------------------
    181      * IBinder interface
    182      */
    183     virtual status_t onTransact(uint32_t code, const Parcel& data,
    184         Parcel* reply, uint32_t flags);
    185     virtual status_t dump(int fd, const Vector<String16>& args);
    186 
    187     /* ------------------------------------------------------------------------
    188      * ISurfaceComposer interface
    189      */
    190     virtual sp<ISurfaceComposerClient> createConnection();
    191     virtual sp<IGraphicBufferAlloc> createGraphicBufferAlloc();
    192     virtual sp<IBinder> createDisplay(const String8& displayName, bool secure);
    193     virtual sp<IBinder> getBuiltInDisplay(int32_t id);
    194     virtual void setTransactionState(const Vector<ComposerState>& state,
    195             const Vector<DisplayState>& displays, uint32_t flags);
    196     virtual void bootFinished();
    197     virtual bool authenticateSurfaceTexture(
    198         const sp<ISurfaceTexture>& surface) const;
    199     virtual sp<IDisplayEventConnection> createDisplayEventConnection();
    200     virtual status_t captureScreen(const sp<IBinder>& display, sp<IMemoryHeap>* heap,
    201         uint32_t* width, uint32_t* height, PixelFormat* format,
    202         uint32_t reqWidth, uint32_t reqHeight, uint32_t minLayerZ,
    203         uint32_t maxLayerZ);
    204     // called when screen needs to turn off
    205     virtual void blank(const sp<IBinder>& display);
    206     // called when screen is turning back on
    207     virtual void unblank(const sp<IBinder>& display);
    208     virtual status_t getDisplayInfo(const sp<IBinder>& display, DisplayInfo* info);
    209 
    210     /* ------------------------------------------------------------------------
    211      * DeathRecipient interface
    212      */
    213     virtual void binderDied(const wp<IBinder>& who);
    214 
    215     /* ------------------------------------------------------------------------
    216      * Thread interface
    217      */
    218     virtual bool threadLoop();
    219     virtual status_t readyToRun();
    220     virtual void onFirstRef();
    221 
    222     /* ------------------------------------------------------------------------
    223      * HWComposer::EventHandler interface
    224      */
    225     virtual void onVSyncReceived(int type, nsecs_t timestamp);
    226     virtual void onHotplugReceived(int disp, bool connected);
    227 
    228     /* ------------------------------------------------------------------------
    229      * Message handling
    230      */
    231     void waitForEvent();
    232     void signalTransaction();
    233     void signalLayerUpdate();
    234     void signalRefresh();
    235 
    236     // called on the main thread in response to initializeDisplays()
    237     void onInitializeDisplays();
    238     // called on the main thread in response to blank()
    239     void onScreenReleased(const sp<const DisplayDevice>& hw);
    240     // called on the main thread in response to unblank()
    241     void onScreenAcquired(const sp<const DisplayDevice>& hw);
    242 
    243     void handleMessageTransaction();
    244     void handleMessageInvalidate();
    245     void handleMessageRefresh();
    246 
    247     void handleTransaction(uint32_t transactionFlags);
    248     void handleTransactionLocked(uint32_t transactionFlags);
    249 
    250     /* handlePageFilp: this is were we latch a new buffer
    251      * if available and compute the dirty region.
    252      */
    253     void handlePageFlip();
    254 
    255     /* ------------------------------------------------------------------------
    256      * Transactions
    257      */
    258     uint32_t getTransactionFlags(uint32_t flags);
    259     uint32_t peekTransactionFlags(uint32_t flags);
    260     uint32_t setTransactionFlags(uint32_t flags);
    261     void commitTransaction();
    262     uint32_t setClientStateLocked(const sp<Client>& client,
    263         const layer_state_t& s);
    264     uint32_t setDisplayStateLocked(const DisplayState& s);
    265 
    266     /* ------------------------------------------------------------------------
    267      * Layer management
    268      */
    269     sp<ISurface> createLayer(ISurfaceComposerClient::surface_data_t* params,
    270             const String8& name, const sp<Client>& client,
    271             uint32_t w, uint32_t h, PixelFormat format, uint32_t flags);
    272 
    273     sp<Layer> createNormalLayer(const sp<Client>& client,
    274             uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format);
    275 
    276     sp<LayerDim> createDimLayer(const sp<Client>& client,
    277             uint32_t w, uint32_t h, uint32_t flags);
    278 
    279     sp<LayerScreenshot> createScreenshotLayer(const sp<Client>& client,
    280             uint32_t w, uint32_t h, uint32_t flags);
    281 
    282     // called in response to the window-manager calling
    283     // ISurfaceComposerClient::destroySurface()
    284     // The specified layer is first placed in a purgatory list
    285     // until all references from the client are released.
    286     status_t onLayerRemoved(const sp<Client>& client, SurfaceID sid);
    287 
    288     // called when all clients have released all their references to
    289     // this layer meaning it is entirely safe to destroy all
    290     // resources associated to this layer.
    291     status_t onLayerDestroyed(const wp<LayerBaseClient>& layer);
    292 
    293     // remove a layer from SurfaceFlinger immediately
    294     status_t removeLayer(const sp<LayerBase>& layer);
    295 
    296     // add a layer to SurfaceFlinger
    297     ssize_t addClientLayer(const sp<Client>& client,
    298         const sp<LayerBaseClient>& lbc);
    299 
    300     status_t removeLayer_l(const sp<LayerBase>& layer);
    301     status_t purgatorizeLayer_l(const sp<LayerBase>& layer);
    302 
    303     /* ------------------------------------------------------------------------
    304      * Boot animation, on/off animations and screen capture
    305      */
    306 
    307     void startBootAnim();
    308 
    309     status_t captureScreenImplLocked(const sp<IBinder>& display, sp<IMemoryHeap>* heap,
    310         uint32_t* width, uint32_t* height, PixelFormat* format,
    311         uint32_t reqWidth, uint32_t reqHeight, uint32_t minLayerZ,
    312         uint32_t maxLayerZ);
    313 
    314     /* ------------------------------------------------------------------------
    315      * EGL
    316      */
    317     static status_t selectConfigForAttribute(EGLDisplay dpy,
    318         EGLint const* attrs, EGLint attribute, EGLint value, EGLConfig* outConfig);
    319     static EGLConfig selectEGLConfig(EGLDisplay disp, EGLint visualId);
    320     static EGLContext createGLContext(EGLDisplay disp, EGLConfig config);
    321     void initializeGL(EGLDisplay display);
    322     uint32_t getMaxTextureSize() const;
    323     uint32_t getMaxViewportDims() const;
    324 
    325     /* ------------------------------------------------------------------------
    326      * Display and layer stack management
    327      */
    328     // called when starting, or restarting after system_server death
    329     void initializeDisplays();
    330 
    331     // NOTE: can only be called from the main thread or with mStateLock held
    332     sp<const DisplayDevice> getDisplayDevice(const wp<IBinder>& dpy) const {
    333         return mDisplays.valueFor(dpy);
    334     }
    335 
    336     // NOTE: can only be called from the main thread or with mStateLock held
    337     sp<DisplayDevice> getDisplayDevice(const wp<IBinder>& dpy) {
    338         return mDisplays.valueFor(dpy);
    339     }
    340 
    341     // mark a region of a layer stack dirty. this updates the dirty
    342     // region of all screens presenting this layer stack.
    343     void invalidateLayerStack(uint32_t layerStack, const Region& dirty);
    344 
    345     /* ------------------------------------------------------------------------
    346      * H/W composer
    347      */
    348 
    349     HWComposer& getHwComposer() const { return *mHwc; }
    350 
    351     /* ------------------------------------------------------------------------
    352      * Compositing
    353      */
    354     void invalidateHwcGeometry();
    355     static void computeVisibleRegions(
    356             const LayerVector& currentLayers, uint32_t layerStack,
    357             Region& dirtyRegion, Region& opaqueRegion);
    358 
    359     void preComposition();
    360     void postComposition();
    361     void rebuildLayerStacks();
    362     void setUpHWComposer();
    363     void doComposition();
    364     void doDebugFlashRegions();
    365     void doDisplayComposition(const sp<const DisplayDevice>& hw,
    366             const Region& dirtyRegion);
    367     void doComposeSurfaces(const sp<const DisplayDevice>& hw,
    368             const Region& dirty);
    369 
    370     void postFramebuffer();
    371     void drawWormhole(const sp<const DisplayDevice>& hw,
    372             const Region& region) const;
    373     GLuint getProtectedTexName() const {
    374         return mProtectedTexName;
    375     }
    376 
    377     /* ------------------------------------------------------------------------
    378      * Display management
    379      */
    380 
    381 
    382     /* ------------------------------------------------------------------------
    383      * Debugging & dumpsys
    384      */
    385     void listLayersLocked(const Vector<String16>& args, size_t& index,
    386         String8& result, char* buffer, size_t SIZE) const;
    387     void dumpStatsLocked(const Vector<String16>& args, size_t& index,
    388         String8& result, char* buffer, size_t SIZE) const;
    389     void clearStatsLocked(const Vector<String16>& args, size_t& index,
    390         String8& result, char* buffer, size_t SIZE) const;
    391     void dumpAllLocked(String8& result, char* buffer, size_t SIZE) const;
    392     bool startDdmConnection();
    393     static void appendSfConfigString(String8& result);
    394 
    395     /* ------------------------------------------------------------------------
    396      * Attributes
    397      */
    398 
    399     // access must be protected by mStateLock
    400     mutable Mutex mStateLock;
    401     State mCurrentState;
    402     volatile int32_t mTransactionFlags;
    403     Condition mTransactionCV;
    404     SortedVector<sp<LayerBase> > mLayerPurgatory;
    405     bool mTransactionPending;
    406     bool mAnimTransactionPending;
    407     Vector<sp<LayerBase> > mLayersPendingRemoval;
    408 
    409     // protected by mStateLock (but we could use another lock)
    410     bool mLayersRemoved;
    411 
    412     // access must be protected by mInvalidateLock
    413     volatile int32_t mRepaintEverything;
    414 
    415     // constant members (no synchronization needed for access)
    416     HWComposer* mHwc;
    417     GLuint mProtectedTexName;
    418     nsecs_t mBootTime;
    419     sp<EventThread> mEventThread;
    420     GLint mMaxViewportDims[2];
    421     GLint mMaxTextureSize;
    422     EGLContext mEGLContext;
    423     EGLConfig mEGLConfig;
    424     EGLDisplay mEGLDisplay;
    425     sp<IBinder> mDefaultDisplays[DisplayDevice::NUM_DISPLAY_TYPES];
    426 
    427     // Can only accessed from the main thread, these members
    428     // don't need synchronization
    429     State mDrawingState;
    430     bool mVisibleRegionsDirty;
    431     bool mHwWorkListDirty;
    432 
    433     // this may only be written from the main thread with mStateLock held
    434     // it may be read from other threads with mStateLock held
    435     DefaultKeyedVector< wp<IBinder>, sp<DisplayDevice> > mDisplays;
    436 
    437     // don't use a lock for these, we don't care
    438     int mDebugRegion;
    439     int mDebugDDMS;
    440     int mDebugDisableHWC;
    441     int mDebugDisableTransformHint;
    442     volatile nsecs_t mDebugInSwapBuffers;
    443     nsecs_t mLastSwapBufferTime;
    444     volatile nsecs_t mDebugInTransaction;
    445     nsecs_t mLastTransactionTime;
    446     bool mBootFinished;
    447 
    448     // these are thread safe
    449     mutable MessageQueue mEventQueue;
    450     mutable Barrier mReadyToRunBarrier;
    451 
    452     // protected by mDestroyedLayerLock;
    453     mutable Mutex mDestroyedLayerLock;
    454     Vector<LayerBase const *> mDestroyedLayers;
    455 
    456     /* ------------------------------------------------------------------------
    457      * Feature prototyping
    458      */
    459 
    460     sp<IBinder> mExtDisplayToken;
    461 };
    462 
    463 // ---------------------------------------------------------------------------
    464 }; // namespace android
    465 
    466 #endif // ANDROID_SURFACE_FLINGER_H
    467