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