SurfaceFlinger.h revision 59119e658a12279e8fff508f8773843de2d90917
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 <utils/SortedVector.h>
24#include <utils/KeyedVector.h>
25#include <utils/threads.h>
26#include <utils/Atomic.h>
27#include <utils/Errors.h>
28#include <utils/RefBase.h>
29
30#include <binder/IMemory.h>
31#include <binder/Permission.h>
32#include <binder/BinderService.h>
33
34#include <ui/PixelFormat.h>
35#include <surfaceflinger/ISurfaceComposer.h>
36#include <surfaceflinger/ISurfaceComposerClient.h>
37
38#include "Barrier.h"
39#include "Layer.h"
40
41#include "MessageQueue.h"
42
43namespace android {
44
45// ---------------------------------------------------------------------------
46
47class Client;
48class DisplayHardware;
49class FreezeLock;
50class Layer;
51class LayerBlur;
52class LayerDim;
53class LayerBuffer;
54
55#define LIKELY( exp )       (__builtin_expect( (exp) != 0, true  ))
56#define UNLIKELY( exp )     (__builtin_expect( (exp) != 0, false ))
57
58// ---------------------------------------------------------------------------
59
60class Client : public BnSurfaceComposerClient
61{
62public:
63        Client(const sp<SurfaceFlinger>& flinger);
64        ~Client();
65
66    status_t initCheck() const;
67
68    // protected by SurfaceFlinger::mStateLock
69    ssize_t attachLayer(const sp<LayerBaseClient>& layer);
70    void detachLayer(const LayerBaseClient* layer);
71    sp<LayerBaseClient> getLayerUser(int32_t i) const;
72
73private:
74
75    // ISurfaceComposerClient interface
76    virtual sp<IMemoryHeap> getControlBlock() const;
77    virtual ssize_t getTokenForSurface(const sp<ISurface>& sur) const;
78    virtual sp<ISurface> createSurface(
79            surface_data_t* params, int pid, const String8& name,
80            DisplayID display, uint32_t w, uint32_t h,PixelFormat format,
81            uint32_t flags);
82    virtual status_t destroySurface(SurfaceID surfaceId);
83    virtual status_t setState(int32_t count, const layer_state_t* states);
84
85    DefaultKeyedVector< size_t, wp<LayerBaseClient> > mLayers;
86    sp<SurfaceFlinger> mFlinger;
87    int32_t mNameGenerator;
88};
89
90class UserClient : public BnSurfaceComposerClient
91{
92public:
93    // pointer to this client's control block
94    SharedClient* ctrlblk;
95
96public:
97        UserClient(const sp<SurfaceFlinger>& flinger);
98        ~UserClient();
99
100    status_t initCheck() const;
101
102    // protected by SurfaceFlinger::mStateLock
103    void detachLayer(const Layer* layer);
104
105private:
106
107    // ISurfaceComposerClient interface
108    virtual sp<IMemoryHeap> getControlBlock() const;
109    virtual ssize_t getTokenForSurface(const sp<ISurface>& sur) const;
110    virtual sp<ISurface> createSurface(
111            surface_data_t* params, int pid, const String8& name,
112            DisplayID display, uint32_t w, uint32_t h,PixelFormat format,
113            uint32_t flags);
114    virtual status_t destroySurface(SurfaceID surfaceId);
115    virtual status_t setState(int32_t count, const layer_state_t* states);
116
117    // atomic-ops
118    mutable volatile int32_t mBitmap;
119
120    sp<IMemoryHeap> mCblkHeap;
121    sp<SurfaceFlinger> mFlinger;
122};
123
124// ---------------------------------------------------------------------------
125
126class GraphicPlane
127{
128public:
129    static status_t orientationToTransfrom(int orientation, int w, int h,
130            Transform* tr);
131
132                                GraphicPlane();
133                                ~GraphicPlane();
134
135        bool                    initialized() const;
136
137        void                    setDisplayHardware(DisplayHardware *);
138        status_t                setOrientation(int orientation);
139        int                     getOrientation() const { return mOrientation; }
140        int                     getWidth() const;
141        int                     getHeight() const;
142
143        const DisplayHardware&  displayHardware() const;
144        DisplayHardware&        editDisplayHardware();
145        const Transform&        transform() const;
146        EGLDisplay              getEGLDisplay() const;
147
148private:
149                                GraphicPlane(const GraphicPlane&);
150        GraphicPlane            operator = (const GraphicPlane&);
151
152        DisplayHardware*        mHw;
153        Transform               mGlobalTransform;
154        Transform               mDisplayTransform;
155        int                     mOrientation;
156        float                   mDisplayWidth;
157        float                   mDisplayHeight;
158        int                     mWidth;
159        int                     mHeight;
160};
161
162// ---------------------------------------------------------------------------
163
164enum {
165    eTransactionNeeded      = 0x01,
166    eTraversalNeeded        = 0x02
167};
168
169class SurfaceFlinger :
170        public BinderService<SurfaceFlinger>,
171        public BnSurfaceComposer,
172        protected Thread
173{
174public:
175    static char const* getServiceName() { return "SurfaceFlinger"; }
176
177                    SurfaceFlinger();
178    virtual         ~SurfaceFlinger();
179            void    init();
180
181    virtual status_t onTransact(
182        uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags);
183
184    virtual status_t dump(int fd, const Vector<String16>& args);
185
186    // ISurfaceComposer interface
187    virtual sp<ISurfaceComposerClient>  createConnection();
188    virtual sp<ISurfaceComposerClient>  createClientConnection();
189    virtual sp<IMemoryHeap>             getCblk() const;
190    virtual void                        bootFinished();
191    virtual void                        openGlobalTransaction();
192    virtual void                        closeGlobalTransaction();
193    virtual status_t                    freezeDisplay(DisplayID dpy, uint32_t flags);
194    virtual status_t                    unfreezeDisplay(DisplayID dpy, uint32_t flags);
195    virtual int                         setOrientation(DisplayID dpy, int orientation, uint32_t flags);
196    virtual void                        signal() const;
197    virtual status_t                    captureScreen(DisplayID dpy,
198                                                      sp<IMemoryHeap>* heap,
199                                                      uint32_t* width,
200                                                      uint32_t* height,
201                                                      PixelFormat* format,
202                                                      uint32_t reqWidth,
203                                                      uint32_t reqHeight);
204    virtual status_t                    turnElectronBeamOff(int32_t mode);
205
206            void                        screenReleased(DisplayID dpy);
207            void                        screenAcquired(DisplayID dpy);
208
209            overlay_control_device_t* getOverlayEngine() const;
210
211    status_t removeLayer(const sp<LayerBase>& layer);
212    status_t addLayer(const sp<LayerBase>& layer);
213    status_t invalidateLayerVisibility(const sp<LayerBase>& layer);
214
215    sp<Layer> getLayer(const sp<ISurface>& sur) const;
216
217private:
218    friend class Client;
219    friend class LayerBase;
220    friend class LayerBuffer;
221    friend class LayerBaseClient;
222    friend class LayerBaseClient::Surface;
223    friend class Layer;
224    friend class LayerBlur;
225    friend class LayerDim;
226
227    sp<ISurface> createSurface(const sp<Client>& client,
228            int pid, const String8& name,
229            ISurfaceComposerClient::surface_data_t* params,
230            DisplayID display, uint32_t w, uint32_t h, PixelFormat format,
231            uint32_t flags);
232
233    sp<Layer> createNormalSurface(
234            const sp<Client>& client, DisplayID display,
235            uint32_t w, uint32_t h, uint32_t flags,
236            PixelFormat& format);
237
238    sp<LayerBlur> createBlurSurface(
239            const sp<Client>& client, DisplayID display,
240            uint32_t w, uint32_t h, uint32_t flags);
241
242    sp<LayerDim> createDimSurface(
243            const sp<Client>& client, DisplayID display,
244            uint32_t w, uint32_t h, uint32_t flags);
245
246    sp<LayerBuffer> createPushBuffersSurface(
247            const sp<Client>& client, DisplayID display,
248            uint32_t w, uint32_t h, uint32_t flags);
249
250    status_t removeSurface(const sp<Client>& client, SurfaceID sid);
251    status_t destroySurface(const sp<LayerBaseClient>& layer);
252    status_t setClientState(const sp<Client>& client,
253            int32_t count, const layer_state_t* states);
254
255    class LayerVector : public SortedVector< sp<LayerBase> > {
256    public:
257        LayerVector() { }
258        LayerVector(const LayerVector& rhs) : SortedVector< sp<LayerBase> >(rhs) { }
259        virtual int do_compare(const void* lhs, const void* rhs) const {
260            const sp<LayerBase>& l(*reinterpret_cast<const sp<LayerBase>*>(lhs));
261            const sp<LayerBase>& r(*reinterpret_cast<const sp<LayerBase>*>(rhs));
262            // sort layers by Z order
263            uint32_t lz = l->currentState().z;
264            uint32_t rz = r->currentState().z;
265            // then by sequence, so we get a stable ordering
266            return (lz != rz) ? (lz - rz) : (l->sequence - r->sequence);
267        }
268    };
269
270    struct State {
271        State() {
272            orientation = ISurfaceComposer::eOrientationDefault;
273            freezeDisplay = 0;
274        }
275        LayerVector     layersSortedByZ;
276        uint8_t         orientation;
277        uint8_t         orientationType;
278        uint8_t         freezeDisplay;
279    };
280
281    virtual bool        threadLoop();
282    virtual status_t    readyToRun();
283    virtual void        onFirstRef();
284
285public:     // hack to work around gcc 4.0.3 bug
286    const GraphicPlane&     graphicPlane(int dpy) const;
287          GraphicPlane&     graphicPlane(int dpy);
288private:
289
290            void        waitForEvent();
291public:     // hack to work around gcc 4.0.3 bug
292            void        signalEvent();
293private:
294            void        handleConsoleEvents();
295            void        handleTransaction(uint32_t transactionFlags);
296            void        handleTransactionLocked(
297                            uint32_t transactionFlags,
298                            Vector< sp<LayerBase> >& ditchedLayers);
299
300            void        computeVisibleRegions(
301                            LayerVector& currentLayers,
302                            Region& dirtyRegion,
303                            Region& wormholeRegion);
304
305            void        handlePageFlip();
306            bool        lockPageFlip(const LayerVector& currentLayers);
307            void        unlockPageFlip(const LayerVector& currentLayers);
308            void        handleRepaint();
309            void        postFramebuffer();
310            void        composeSurfaces(const Region& dirty);
311            void        unlockClients();
312
313
314            ssize_t     addClientLayer(const sp<Client>& client,
315                    const sp<LayerBaseClient>& lbc);
316            status_t    addLayer_l(const sp<LayerBase>& layer);
317            status_t    removeLayer_l(const sp<LayerBase>& layer);
318            status_t    purgatorizeLayer_l(const sp<LayerBase>& layer);
319
320            uint32_t    getTransactionFlags(uint32_t flags);
321            uint32_t    setTransactionFlags(uint32_t flags);
322            void        commitTransaction();
323
324
325            status_t captureScreenImplLocked(DisplayID dpy,
326                    sp<IMemoryHeap>* heap,
327                    uint32_t* width, uint32_t* height, PixelFormat* format,
328                    uint32_t reqWidth = 0, uint32_t reqHeight = 0);
329
330            status_t turnElectronBeamOffImplLocked();
331
332            friend class FreezeLock;
333            sp<FreezeLock> getFreezeLock() const;
334            inline void incFreezeCount() {
335                if (mFreezeCount == 0)
336                    mFreezeDisplayTime = 0;
337                mFreezeCount++;
338            }
339            inline void decFreezeCount() { if (mFreezeCount > 0) mFreezeCount--; }
340            inline bool hasFreezeRequest() const { return mFreezeDisplay; }
341            inline bool isFrozen() const {
342                return (mFreezeDisplay || mFreezeCount>0) && mBootFinished;
343            }
344
345
346            void        debugFlashRegions();
347            void        debugShowFPS() const;
348            void        drawWormhole() const;
349
350
351    mutable     MessageQueue    mEventQueue;
352
353    status_t postMessageAsync(const sp<MessageBase>& msg,
354            nsecs_t reltime=0, uint32_t flags = 0);
355
356    status_t postMessageSync(const sp<MessageBase>& msg,
357            nsecs_t reltime=0, uint32_t flags = 0);
358
359                // access must be protected by mStateLock
360    mutable     Mutex                   mStateLock;
361                State                   mCurrentState;
362                State                   mDrawingState;
363    volatile    int32_t                 mTransactionFlags;
364    volatile    int32_t                 mTransactionCount;
365                Condition               mTransactionCV;
366                bool                    mResizeTransationPending;
367
368                // protected by mStateLock (but we could use another lock)
369                GraphicPlane                mGraphicPlanes[1];
370                bool                        mLayersRemoved;
371                DefaultKeyedVector< wp<IBinder>, wp<Layer> > mLayerMap;
372
373                // constant members (no synchronization needed for access)
374                sp<IMemoryHeap>             mServerHeap;
375                surface_flinger_cblk_t*     mServerCblk;
376                GLuint                      mWormholeTexName;
377                nsecs_t                     mBootTime;
378                Permission                  mHardwareTest;
379                Permission                  mAccessSurfaceFlinger;
380                Permission                  mReadFramebuffer;
381                Permission                  mDump;
382
383                // Can only accessed from the main thread, these members
384                // don't need synchronization
385                Region                      mDirtyRegion;
386                Region                      mDirtyRegionRemovedLayer;
387                Region                      mInvalidRegion;
388                Region                      mWormholeRegion;
389                bool                        mVisibleRegionsDirty;
390                bool                        mDeferReleaseConsole;
391                bool                        mFreezeDisplay;
392                int32_t                     mFreezeCount;
393                nsecs_t                     mFreezeDisplayTime;
394                Vector< sp<LayerBase> >     mVisibleLayersSortedByZ;
395
396
397                // don't use a lock for these, we don't care
398                int                         mDebugRegion;
399                int                         mDebugBackground;
400                volatile nsecs_t            mDebugInSwapBuffers;
401                nsecs_t                     mLastSwapBufferTime;
402                volatile nsecs_t            mDebugInTransaction;
403                nsecs_t                     mLastTransactionTime;
404                bool                        mBootFinished;
405
406                // these are thread safe
407    mutable     Barrier                     mReadyToRunBarrier;
408
409                // atomic variables
410                enum {
411                    eConsoleReleased = 1,
412                    eConsoleAcquired = 2
413                };
414   volatile     int32_t                     mConsoleSignals;
415
416   // only written in the main thread, only read in other threads
417   volatile     int32_t                     mSecureFrameBuffer;
418};
419
420// ---------------------------------------------------------------------------
421
422class FreezeLock : public LightRefBase<FreezeLock> {
423    SurfaceFlinger* mFlinger;
424public:
425    FreezeLock(SurfaceFlinger* flinger)
426        : mFlinger(flinger) {
427        mFlinger->incFreezeCount();
428    }
429    ~FreezeLock() {
430        mFlinger->decFreezeCount();
431    }
432};
433
434// ---------------------------------------------------------------------------
435}; // namespace android
436
437#endif // ANDROID_SURFACE_FLINGER_H
438