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