SurfaceFlinger.h revision e9800c83114988b6f8cc25bb9d508ebb322f9903
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                                                            int orientation);
172    virtual status_t                    freezeDisplay(DisplayID dpy, uint32_t flags);
173    virtual status_t                    unfreezeDisplay(DisplayID dpy, uint32_t flags);
174    virtual int                         setOrientation(DisplayID dpy, int orientation, uint32_t flags);
175    virtual bool                        authenticateSurfaceTexture(const sp<ISurfaceTexture>& surface) const;
176
177    virtual status_t captureScreen(DisplayID dpy,
178            sp<IMemoryHeap>* heap,
179            uint32_t* width, uint32_t* height,
180            PixelFormat* format, uint32_t reqWidth, uint32_t reqHeight,
181            uint32_t minLayerZ, uint32_t maxLayerZ);
182
183    virtual status_t                    turnElectronBeamOff(int32_t mode);
184    virtual status_t                    turnElectronBeamOn(int32_t mode);
185
186            void                        screenReleased(DisplayID dpy);
187            void                        screenAcquired(DisplayID dpy);
188
189    status_t removeLayer(const sp<LayerBase>& layer);
190    status_t addLayer(const sp<LayerBase>& layer);
191    status_t invalidateLayerVisibility(const sp<LayerBase>& layer);
192    void invalidateHwcGeometry();
193
194    sp<Layer> getLayer(const sp<ISurface>& sur) const;
195
196    GLuint getProtectedTexName() const { return mProtectedTexName; }
197
198private:
199    // DeathRecipient interface
200    virtual void binderDied(const wp<IBinder>& who);
201
202private:
203    friend class Client;
204    friend class LayerBase;
205    friend class LayerBaseClient;
206    friend class Layer;
207    friend class LayerDim;
208
209    sp<ISurface> createSurface(
210            ISurfaceComposerClient::surface_data_t* params,
211            const String8& name,
212            const sp<Client>& client,
213            DisplayID display, uint32_t w, uint32_t h, PixelFormat format,
214            uint32_t flags);
215
216    sp<Layer> createNormalSurface(
217            const sp<Client>& client, DisplayID display,
218            uint32_t w, uint32_t h, uint32_t flags,
219            PixelFormat& format);
220
221    sp<LayerDim> createDimSurface(
222            const sp<Client>& client, DisplayID display,
223            uint32_t w, uint32_t h, uint32_t flags);
224
225    status_t removeSurface(const sp<Client>& client, SurfaceID sid);
226    status_t destroySurface(const wp<LayerBaseClient>& layer);
227    uint32_t setClientStateLocked(const sp<Client>& client, const layer_state_t& s);
228
229    class LayerVector : public SortedVector< sp<LayerBase> > {
230    public:
231        LayerVector() { }
232        LayerVector(const LayerVector& rhs) : SortedVector< sp<LayerBase> >(rhs) { }
233        virtual int do_compare(const void* lhs, const void* rhs) const {
234            const sp<LayerBase>& l(*reinterpret_cast<const sp<LayerBase>*>(lhs));
235            const sp<LayerBase>& r(*reinterpret_cast<const sp<LayerBase>*>(rhs));
236            // sort layers by Z order
237            uint32_t lz = l->currentState().z;
238            uint32_t rz = r->currentState().z;
239            // then by sequence, so we get a stable ordering
240            return (lz != rz) ? (lz - rz) : (l->sequence - r->sequence);
241        }
242    };
243
244    struct State {
245        State() {
246            orientation = ISurfaceComposer::eOrientationDefault;
247            freezeDisplay = 0;
248        }
249        LayerVector     layersSortedByZ;
250        uint8_t         orientation;
251        uint8_t         orientationFlags;
252        uint8_t         freezeDisplay;
253    };
254
255    virtual bool        threadLoop();
256    virtual status_t    readyToRun();
257    virtual void        onFirstRef();
258
259public:     // hack to work around gcc 4.0.3 bug
260    const GraphicPlane&     graphicPlane(int dpy) const;
261          GraphicPlane&     graphicPlane(int dpy);
262          void              signalEvent();
263          void              repaintEverything();
264
265private:
266            void        waitForEvent();
267            void        handleConsoleEvents();
268            void        handleTransaction(uint32_t transactionFlags);
269            void        handleTransactionLocked(uint32_t transactionFlags);
270
271            void        computeVisibleRegions(
272                            const LayerVector& currentLayers,
273                            Region& dirtyRegion,
274                            Region& wormholeRegion);
275
276            void        handlePageFlip();
277            bool        lockPageFlip(const LayerVector& currentLayers);
278            void        unlockPageFlip(const LayerVector& currentLayers);
279            void        handleWorkList();
280            void        handleRepaint();
281            void        postFramebuffer();
282            void        setupHardwareComposer(Region& dirtyInOut);
283            void        composeSurfaces(const Region& dirty);
284
285
286            ssize_t     addClientLayer(const sp<Client>& client,
287                    const sp<LayerBaseClient>& lbc);
288            status_t    addLayer_l(const sp<LayerBase>& layer);
289            status_t    removeLayer_l(const sp<LayerBase>& layer);
290            status_t    purgatorizeLayer_l(const sp<LayerBase>& layer);
291
292            uint32_t    getTransactionFlags(uint32_t flags);
293            uint32_t    peekTransactionFlags(uint32_t flags);
294            uint32_t    setTransactionFlags(uint32_t flags);
295            void        commitTransaction();
296
297
298            status_t captureScreenImplLocked(DisplayID dpy,
299                    sp<IMemoryHeap>* heap,
300                    uint32_t* width, uint32_t* height, PixelFormat* format,
301                    uint32_t reqWidth, uint32_t reqHeight,
302                    uint32_t minLayerZ, uint32_t maxLayerZ);
303
304            status_t turnElectronBeamOffImplLocked(int32_t mode);
305            status_t turnElectronBeamOnImplLocked(int32_t mode);
306            status_t electronBeamOffAnimationImplLocked();
307            status_t electronBeamOnAnimationImplLocked();
308            status_t renderScreenToTextureLocked(DisplayID dpy,
309                    GLuint* textureName, GLfloat* uOut, GLfloat* vOut);
310
311            friend class FreezeLock;
312            sp<FreezeLock> getFreezeLock() const;
313            inline void incFreezeCount() {
314                if (mFreezeCount == 0)
315                    mFreezeDisplayTime = 0;
316                mFreezeCount++;
317            }
318            inline void decFreezeCount() { if (mFreezeCount > 0) mFreezeCount--; }
319            inline bool hasFreezeRequest() const { return mFreezeDisplay; }
320            inline bool isFrozen() const {
321                return (mFreezeDisplay || mFreezeCount>0) && mBootFinished;
322            }
323
324
325            void        debugFlashRegions();
326            void        debugShowFPS() const;
327            void        drawWormhole() const;
328
329
330    mutable     MessageQueue    mEventQueue;
331
332    status_t postMessageAsync(const sp<MessageBase>& msg,
333            nsecs_t reltime=0, uint32_t flags = 0);
334
335    status_t postMessageSync(const sp<MessageBase>& msg,
336            nsecs_t reltime=0, uint32_t flags = 0);
337
338                // access must be protected by mStateLock
339    mutable     Mutex                   mStateLock;
340                State                   mCurrentState;
341    volatile    int32_t                 mTransactionFlags;
342                Condition               mTransactionCV;
343                SortedVector< sp<LayerBase> > mLayerPurgatory;
344                bool                    mResizeTransationPending;
345
346                // protected by mStateLock (but we could use another lock)
347                GraphicPlane                mGraphicPlanes[1];
348                bool                        mLayersRemoved;
349                DefaultKeyedVector< wp<IBinder>, wp<Layer> > mLayerMap;
350
351                // constant members (no synchronization needed for access)
352                sp<IMemoryHeap>             mServerHeap;
353                surface_flinger_cblk_t*     mServerCblk;
354                GLuint                      mWormholeTexName;
355                GLuint                      mProtectedTexName;
356                nsecs_t                     mBootTime;
357
358                // Can only accessed from the main thread, these members
359                // don't need synchronization
360                State                       mDrawingState;
361                Region                      mDirtyRegion;
362                Region                      mDirtyRegionRemovedLayer;
363                Region                      mSwapRegion;
364                Region                      mWormholeRegion;
365                bool                        mVisibleRegionsDirty;
366                bool                        mHwWorkListDirty;
367                bool                        mFreezeDisplay;
368                int32_t                     mElectronBeamAnimationMode;
369                int32_t                     mFreezeCount;
370                nsecs_t                     mFreezeDisplayTime;
371                Vector< sp<LayerBase> >     mVisibleLayersSortedByZ;
372
373
374                // don't use a lock for these, we don't care
375                int                         mDebugRegion;
376                int                         mDebugBackground;
377                int                         mDebugDDMS;
378                int                         mDebugDisableHWC;
379                int                         mDebugDisableTransformHint;
380                volatile nsecs_t            mDebugInSwapBuffers;
381                nsecs_t                     mLastSwapBufferTime;
382                volatile nsecs_t            mDebugInTransaction;
383                nsecs_t                     mLastTransactionTime;
384                bool                        mBootFinished;
385
386                // these are thread safe
387    mutable     Barrier                     mReadyToRunBarrier;
388
389
390                // protected by mDestroyedLayerLock;
391    mutable     Mutex                       mDestroyedLayerLock;
392                Vector<LayerBase const *>   mDestroyedLayers;
393
394                // atomic variables
395                enum {
396                    eConsoleReleased = 1,
397                    eConsoleAcquired = 2
398                };
399   volatile     int32_t                     mConsoleSignals;
400
401   // only written in the main thread, only read in other threads
402   volatile     int32_t                     mSecureFrameBuffer;
403};
404
405// ---------------------------------------------------------------------------
406
407class FreezeLock : public LightRefBase<FreezeLock> {
408    SurfaceFlinger* mFlinger;
409public:
410    FreezeLock(SurfaceFlinger* flinger)
411        : mFlinger(flinger) {
412        mFlinger->incFreezeCount();
413    }
414    ~FreezeLock() {
415        mFlinger->decFreezeCount();
416    }
417};
418
419// ---------------------------------------------------------------------------
420}; // namespace android
421
422#endif // ANDROID_SURFACE_FLINGER_H
423