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