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