SurfaceFlinger.h revision a67932fe6864ac346e7f78b86df11cf6c5344137
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#include <surfaceflinger/IGraphicBufferAlloc.h>
38
39#include "Barrier.h"
40#include "Layer.h"
41
42#include "MessageQueue.h"
43
44namespace android {
45
46// ---------------------------------------------------------------------------
47
48class Client;
49class DisplayHardware;
50class FreezeLock;
51class Layer;
52class LayerDim;
53struct surface_flinger_cblk_t;
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    size_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<ISurface> createSurface(
77            surface_data_t* params, const String8& name,
78            DisplayID display, uint32_t w, uint32_t h,PixelFormat format,
79            uint32_t flags);
80    virtual status_t destroySurface(SurfaceID surfaceId);
81    virtual status_t setState(int32_t count, const layer_state_t* states);
82    virtual status_t onTransact(
83        uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags);
84
85    // constant
86    sp<SurfaceFlinger> mFlinger;
87
88    // protected by mLock
89    DefaultKeyedVector< size_t, wp<LayerBaseClient> > mLayers;
90    size_t mNameGenerator;
91
92    // thread-safe
93    mutable Mutex mLock;
94};
95
96class GraphicBufferAlloc : public BnGraphicBufferAlloc
97{
98public:
99    GraphicBufferAlloc();
100    virtual ~GraphicBufferAlloc();
101    virtual sp<GraphicBuffer> createGraphicBuffer(uint32_t w, uint32_t h,
102        PixelFormat format, uint32_t usage);
103};
104
105// ---------------------------------------------------------------------------
106
107class GraphicPlane
108{
109public:
110    static status_t orientationToTransfrom(int orientation, int w, int h,
111            Transform* tr);
112
113                                GraphicPlane();
114                                ~GraphicPlane();
115
116        bool                    initialized() const;
117
118        void                    setDisplayHardware(DisplayHardware *);
119        status_t                setOrientation(int orientation);
120        int                     getOrientation() const { return mOrientation; }
121        int                     getWidth() const;
122        int                     getHeight() const;
123
124        const DisplayHardware&  displayHardware() const;
125        DisplayHardware&        editDisplayHardware();
126        const Transform&        transform() const;
127        EGLDisplay              getEGLDisplay() const;
128
129private:
130                                GraphicPlane(const GraphicPlane&);
131        GraphicPlane            operator = (const GraphicPlane&);
132
133        DisplayHardware*        mHw;
134        Transform               mGlobalTransform;
135        Transform               mDisplayTransform;
136        int                     mOrientation;
137        float                   mDisplayWidth;
138        float                   mDisplayHeight;
139        int                     mWidth;
140        int                     mHeight;
141};
142
143// ---------------------------------------------------------------------------
144
145enum {
146    eTransactionNeeded      = 0x01,
147    eTraversalNeeded        = 0x02
148};
149
150class SurfaceFlinger :
151        public BinderService<SurfaceFlinger>,
152        public BnSurfaceComposer,
153        protected Thread
154{
155public:
156    static char const* getServiceName() { return "SurfaceFlinger"; }
157
158                    SurfaceFlinger();
159    virtual         ~SurfaceFlinger();
160            void    init();
161
162    virtual status_t onTransact(
163        uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags);
164
165    virtual status_t dump(int fd, const Vector<String16>& args);
166
167    // ISurfaceComposer interface
168    virtual sp<ISurfaceComposerClient>  createConnection();
169    virtual sp<IGraphicBufferAlloc>     createGraphicBufferAlloc();
170    virtual sp<IMemoryHeap>             getCblk() const;
171    virtual void                        bootFinished();
172    virtual void                        openGlobalTransaction();
173    virtual void                        closeGlobalTransaction();
174    virtual status_t                    freezeDisplay(DisplayID dpy, uint32_t flags);
175    virtual status_t                    unfreezeDisplay(DisplayID dpy, uint32_t flags);
176    virtual int                         setOrientation(DisplayID dpy, int orientation, uint32_t flags);
177    virtual bool                        authenticateSurface(const sp<ISurface>& surface) const;
178
179    virtual status_t captureScreen(DisplayID dpy,
180            sp<IMemoryHeap>* heap,
181            uint32_t* width, uint32_t* height,
182            PixelFormat* format, uint32_t reqWidth, uint32_t reqHeight,
183            uint32_t minLayerZ, uint32_t maxLayerZ);
184
185    virtual status_t                    turnElectronBeamOff(int32_t mode);
186    virtual status_t                    turnElectronBeamOn(int32_t mode);
187
188            void                        screenReleased(DisplayID dpy);
189            void                        screenAcquired(DisplayID dpy);
190
191    status_t removeLayer(const sp<LayerBase>& layer);
192    status_t addLayer(const sp<LayerBase>& layer);
193    status_t invalidateLayerVisibility(const sp<LayerBase>& layer);
194    void invalidateHwcGeometry();
195    void destroyLayer(LayerBase const* layer);
196
197    sp<Layer> getLayer(const sp<ISurface>& sur) const;
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    status_t setClientState(const sp<Client>& client,
225            int32_t count, const layer_state_t* states);
226
227    class LayerVector : public SortedVector< sp<LayerBase> > {
228    public:
229        LayerVector() { }
230        LayerVector(const LayerVector& rhs) : SortedVector< sp<LayerBase> >(rhs) { }
231        virtual int do_compare(const void* lhs, const void* rhs) const {
232            const sp<LayerBase>& l(*reinterpret_cast<const sp<LayerBase>*>(lhs));
233            const sp<LayerBase>& r(*reinterpret_cast<const sp<LayerBase>*>(rhs));
234            // sort layers by Z order
235            uint32_t lz = l->currentState().z;
236            uint32_t rz = r->currentState().z;
237            // then by sequence, so we get a stable ordering
238            return (lz != rz) ? (lz - rz) : (l->sequence - r->sequence);
239        }
240    };
241
242    struct State {
243        State() {
244            orientation = ISurfaceComposer::eOrientationDefault;
245            freezeDisplay = 0;
246        }
247        LayerVector     layersSortedByZ;
248        uint8_t         orientation;
249        uint8_t         orientationType;
250        uint8_t         freezeDisplay;
251    };
252
253    virtual bool        threadLoop();
254    virtual status_t    readyToRun();
255    virtual void        onFirstRef();
256
257public:     // hack to work around gcc 4.0.3 bug
258    const GraphicPlane&     graphicPlane(int dpy) const;
259          GraphicPlane&     graphicPlane(int dpy);
260private:
261
262            void        waitForEvent();
263public:     // hack to work around gcc 4.0.3 bug
264            void        signalEvent();
265private:
266            void        handleConsoleEvents();
267            void        handleTransaction(uint32_t transactionFlags);
268            void        handleTransactionLocked(uint32_t transactionFlags);
269            void        handleDestroyLayers();
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        composeSurfaces(const Region& dirty);
283
284
285            ssize_t     addClientLayer(const sp<Client>& client,
286                    const sp<LayerBaseClient>& lbc);
287            status_t    addLayer_l(const sp<LayerBase>& layer);
288            status_t    removeLayer_l(const sp<LayerBase>& layer);
289            status_t    purgatorizeLayer_l(const sp<LayerBase>& layer);
290
291            uint32_t    getTransactionFlags(uint32_t flags);
292            uint32_t    peekTransactionFlags(uint32_t flags);
293            uint32_t    setTransactionFlags(uint32_t flags);
294            void        commitTransaction();
295
296
297            status_t captureScreenImplLocked(DisplayID dpy,
298                    sp<IMemoryHeap>* heap,
299                    uint32_t* width, uint32_t* height, PixelFormat* format,
300                    uint32_t reqWidth, uint32_t reqHeight,
301                    uint32_t minLayerZ, uint32_t maxLayerZ);
302
303            status_t turnElectronBeamOffImplLocked(int32_t mode);
304            status_t turnElectronBeamOnImplLocked(int32_t mode);
305            status_t electronBeamOffAnimationImplLocked();
306            status_t electronBeamOnAnimationImplLocked();
307            status_t renderScreenToTextureLocked(DisplayID dpy,
308                    GLuint* textureName, GLfloat* uOut, GLfloat* vOut);
309
310            friend class FreezeLock;
311            sp<FreezeLock> getFreezeLock() const;
312            inline void incFreezeCount() {
313                if (mFreezeCount == 0)
314                    mFreezeDisplayTime = 0;
315                mFreezeCount++;
316            }
317            inline void decFreezeCount() { if (mFreezeCount > 0) mFreezeCount--; }
318            inline bool hasFreezeRequest() const { return mFreezeDisplay; }
319            inline bool isFrozen() const {
320                return (mFreezeDisplay || mFreezeCount>0) && mBootFinished;
321            }
322
323
324            void        debugFlashRegions();
325            void        debugShowFPS() const;
326            void        drawWormhole() const;
327
328
329    mutable     MessageQueue    mEventQueue;
330
331    status_t postMessageAsync(const sp<MessageBase>& msg,
332            nsecs_t reltime=0, uint32_t flags = 0);
333
334    status_t postMessageSync(const sp<MessageBase>& msg,
335            nsecs_t reltime=0, uint32_t flags = 0);
336
337                // access must be protected by mStateLock
338    mutable     Mutex                   mStateLock;
339                State                   mCurrentState;
340    volatile    int32_t                 mTransactionFlags;
341    volatile    int32_t                 mTransactionCount;
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                nsecs_t                     mBootTime;
356                Permission                  mHardwareTest;
357                Permission                  mAccessSurfaceFlinger;
358                Permission                  mReadFramebuffer;
359                Permission                  mDump;
360
361                // Can only accessed from the main thread, these members
362                // don't need synchronization
363                State                       mDrawingState;
364                Region                      mDirtyRegion;
365                Region                      mDirtyRegionRemovedLayer;
366                Region                      mInvalidRegion;
367                Region                      mWormholeRegion;
368                bool                        mVisibleRegionsDirty;
369                bool                        mHwWorkListDirty;
370                bool                        mDeferReleaseConsole;
371                bool                        mFreezeDisplay;
372                int32_t                     mElectronBeamAnimationMode;
373                int32_t                     mFreezeCount;
374                nsecs_t                     mFreezeDisplayTime;
375                Vector< sp<LayerBase> >     mVisibleLayersSortedByZ;
376
377
378                // don't use a lock for these, we don't care
379                int                         mDebugRegion;
380                int                         mDebugBackground;
381                int                         mDebugDisableHWC;
382                volatile nsecs_t            mDebugInSwapBuffers;
383                nsecs_t                     mLastSwapBufferTime;
384                volatile nsecs_t            mDebugInTransaction;
385                nsecs_t                     mLastTransactionTime;
386                bool                        mBootFinished;
387
388                // these are thread safe
389    mutable     Barrier                     mReadyToRunBarrier;
390
391
392                // protected by mDestroyedLayerLock;
393    mutable     Mutex                       mDestroyedLayerLock;
394                Vector<LayerBase const *>   mDestroyedLayers;
395
396                // atomic variables
397                enum {
398                    eConsoleReleased = 1,
399                    eConsoleAcquired = 2
400                };
401   volatile     int32_t                     mConsoleSignals;
402
403   // only written in the main thread, only read in other threads
404   volatile     int32_t                     mSecureFrameBuffer;
405};
406
407// ---------------------------------------------------------------------------
408
409class FreezeLock : public LightRefBase<FreezeLock> {
410    SurfaceFlinger* mFlinger;
411public:
412    FreezeLock(SurfaceFlinger* flinger)
413        : mFlinger(flinger) {
414        mFlinger->incFreezeCount();
415    }
416    ~FreezeLock() {
417        mFlinger->decFreezeCount();
418    }
419};
420
421// ---------------------------------------------------------------------------
422}; // namespace android
423
424#endif // ANDROID_SURFACE_FLINGER_H
425