SurfaceFlinger.h revision b79f61d41ef053bee1087ec612896c59f95f9686
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 <EGL/egl.h>
24#include <GLES/gl.h>
25
26#include <cutils/compiler.h>
27
28#include <utils/Atomic.h>
29#include <utils/Errors.h>
30#include <utils/KeyedVector.h>
31#include <utils/RefBase.h>
32#include <utils/SortedVector.h>
33#include <utils/threads.h>
34
35#include <binder/BinderService.h>
36#include <binder/IMemory.h>
37
38#include <ui/PixelFormat.h>
39
40#include <gui/ISurfaceComposer.h>
41#include <gui/ISurfaceComposerClient.h>
42
43#include <hardware/hwcomposer_defs.h>
44
45#include <private/gui/LayerState.h>
46
47#include "Barrier.h"
48#include "DisplayDevice.h"
49#include "FrameTracker.h"
50#include "MessageQueue.h"
51
52#include "DisplayHardware/HWComposer.h"
53
54namespace android {
55
56// ---------------------------------------------------------------------------
57
58class Client;
59class DisplayEventConnection;
60class EventThread;
61class IGraphicBufferAlloc;
62class Layer;
63class LayerBase;
64class LayerDim;
65class Surface;
66
67// ---------------------------------------------------------------------------
68
69enum {
70    eTransactionNeeded        = 0x01,
71    eTraversalNeeded          = 0x02,
72    eDisplayTransactionNeeded = 0x04,
73    eTransactionMask          = 0x07
74};
75
76class SurfaceFlinger : public BinderService<SurfaceFlinger>,
77                       public BnSurfaceComposer,
78                       private IBinder::DeathRecipient,
79                       private Thread,
80                       private HWComposer::EventHandler
81{
82public:
83    static char const* getServiceName() {
84        return "SurfaceFlinger";
85    }
86
87    SurfaceFlinger();
88
89    enum {
90        EVENT_VSYNC = HWC_EVENT_VSYNC
91    };
92
93    // post an asynchronous message to the main thread
94    status_t postMessageAsync(const sp<MessageBase>& msg, nsecs_t reltime = 0,
95        uint32_t flags = 0);
96
97    // post a synchronous message to the main thread
98    status_t postMessageSync(const sp<MessageBase>& msg, nsecs_t reltime = 0,
99        uint32_t flags = 0);
100
101    // force full composition on all displays
102    void repaintEverything();
103
104    // returns the default Display
105    sp<const DisplayDevice> getDefaultDisplayDevice() const {
106        return getDisplayDevice(mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]);
107    }
108
109    // utility function to delete a texture on the main thread
110    void deleteTextureAsync(GLuint texture);
111
112    // allocate a h/w composer display id
113    int32_t allocateHwcDisplayId(DisplayDevice::DisplayType type);
114
115    // enable/disable h/w composer event
116    // TODO: this should be made accessible only to EventThread
117    void eventControl(int disp, int event, int enabled);
118
119    // called on the main thread by MessageQueue when an internal message
120    // is received
121    // TODO: this should be made accessible only to MessageQueue
122    void onMessageReceived(int32_t what);
123
124    // for debugging only
125    // TODO: this should be made accessible only to HWComposer
126    const Vector< sp<LayerBase> >& getLayerSortedByZForHwcDisplay(int disp);
127
128private:
129    friend class Client;
130    friend class DisplayEventConnection;
131    friend class LayerBase;
132    friend class Layer;
133
134    // We're reference counted, never destroy SurfaceFlinger directly
135    virtual ~SurfaceFlinger();
136
137    /* ------------------------------------------------------------------------
138     * Internal data structures
139     */
140
141    class LayerVector : public SortedVector<sp<LayerBase> > {
142    public:
143        LayerVector();
144        LayerVector(const LayerVector& rhs);
145        virtual int do_compare(const void* lhs, const void* rhs) const;
146    };
147
148    struct DisplayDeviceState {
149        DisplayDeviceState();
150        DisplayDeviceState(DisplayDevice::DisplayType type);
151        bool isValid() const { return type >= 0; }
152        bool isMainDisplay() const { return type == DisplayDevice::DISPLAY_PRIMARY; }
153        bool isVirtualDisplay() const { return type >= DisplayDevice::DISPLAY_VIRTUAL; }
154        DisplayDevice::DisplayType type;
155        sp<IGraphicBufferProducer> surface;
156        uint32_t layerStack;
157        Rect viewport;
158        Rect frame;
159        uint8_t orientation;
160        String8 displayName;
161        bool isSecure;
162    };
163
164    struct State {
165        LayerVector layersSortedByZ;
166        DefaultKeyedVector< wp<IBinder>, DisplayDeviceState> displays;
167    };
168
169    /* ------------------------------------------------------------------------
170     * IBinder interface
171     */
172    virtual status_t onTransact(uint32_t code, const Parcel& data,
173        Parcel* reply, uint32_t flags);
174    virtual status_t dump(int fd, const Vector<String16>& args);
175
176    /* ------------------------------------------------------------------------
177     * ISurfaceComposer interface
178     */
179    virtual sp<ISurfaceComposerClient> createConnection();
180    virtual sp<IGraphicBufferAlloc> createGraphicBufferAlloc();
181    virtual sp<IBinder> createDisplay(const String8& displayName, bool secure);
182    virtual sp<IBinder> getBuiltInDisplay(int32_t id);
183    virtual void setTransactionState(const Vector<ComposerState>& state,
184            const Vector<DisplayState>& displays, uint32_t flags);
185    virtual void bootFinished();
186    virtual bool authenticateSurfaceTexture(
187        const sp<IGraphicBufferProducer>& bufferProducer) const;
188    virtual sp<IDisplayEventConnection> createDisplayEventConnection();
189    virtual status_t captureScreen(const sp<IBinder>& display, sp<IMemoryHeap>* heap,
190        uint32_t* width, uint32_t* height, PixelFormat* format,
191        uint32_t reqWidth, uint32_t reqHeight, uint32_t minLayerZ,
192        uint32_t maxLayerZ);
193    virtual status_t captureScreen(const sp<IBinder>& display,
194            const sp<IGraphicBufferProducer>& producer,
195            uint32_t reqWidth, uint32_t reqHeight,
196            uint32_t minLayerZ, uint32_t maxLayerZ);
197    // called when screen needs to turn off
198    virtual void blank(const sp<IBinder>& display);
199    // called when screen is turning back on
200    virtual void unblank(const sp<IBinder>& display);
201    virtual status_t getDisplayInfo(const sp<IBinder>& display, DisplayInfo* info);
202
203    /* ------------------------------------------------------------------------
204     * DeathRecipient interface
205     */
206    virtual void binderDied(const wp<IBinder>& who);
207
208    /* ------------------------------------------------------------------------
209     * Thread interface
210     */
211    virtual bool threadLoop();
212    virtual status_t readyToRun();
213    virtual void onFirstRef();
214
215    /* ------------------------------------------------------------------------
216     * HWComposer::EventHandler interface
217     */
218    virtual void onVSyncReceived(int type, nsecs_t timestamp);
219    virtual void onHotplugReceived(int disp, bool connected);
220
221    /* ------------------------------------------------------------------------
222     * Message handling
223     */
224    void waitForEvent();
225    void signalTransaction();
226    void signalLayerUpdate();
227    void signalRefresh();
228
229    // called on the main thread in response to initializeDisplays()
230    void onInitializeDisplays();
231    // called on the main thread in response to blank()
232    void onScreenReleased(const sp<const DisplayDevice>& hw);
233    // called on the main thread in response to unblank()
234    void onScreenAcquired(const sp<const DisplayDevice>& hw);
235
236    void handleMessageTransaction();
237    void handleMessageInvalidate();
238    void handleMessageRefresh();
239
240    void handleTransaction(uint32_t transactionFlags);
241    void handleTransactionLocked(uint32_t transactionFlags);
242
243    /* handlePageFilp: this is were we latch a new buffer
244     * if available and compute the dirty region.
245     */
246    void handlePageFlip();
247
248    /* ------------------------------------------------------------------------
249     * Transactions
250     */
251    uint32_t getTransactionFlags(uint32_t flags);
252    uint32_t peekTransactionFlags(uint32_t flags);
253    uint32_t setTransactionFlags(uint32_t flags);
254    void commitTransaction();
255    uint32_t setClientStateLocked(const sp<Client>& client,
256        const layer_state_t& s);
257    uint32_t setDisplayStateLocked(const DisplayState& s);
258
259    /* ------------------------------------------------------------------------
260     * Layer management
261     */
262    sp<ISurface> createLayer(const String8& name, const sp<Client>& client,
263            uint32_t w, uint32_t h, PixelFormat format, uint32_t flags);
264
265    sp<Layer> createNormalLayer(const sp<Client>& client,
266            uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format);
267
268    sp<LayerDim> createDimLayer(const sp<Client>& client,
269            uint32_t w, uint32_t h, uint32_t flags);
270
271    // called in response to the window-manager calling
272    // ISurfaceComposerClient::destroySurface()
273    // The specified layer is first placed in a purgatory list
274    // until all references from the client are released.
275    status_t onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle);
276
277    // called when all clients have released all their references to
278    // this layer meaning it is entirely safe to destroy all
279    // resources associated to this layer.
280    status_t onLayerDestroyed(const wp<LayerBase>& layer);
281
282    // remove a layer from SurfaceFlinger immediately
283    status_t removeLayer(const sp<LayerBase>& layer);
284
285    // add a layer to SurfaceFlinger
286    void addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
287        const sp<LayerBase>& lbc);
288
289    status_t removeLayer_l(const sp<LayerBase>& layer);
290    status_t purgatorizeLayer_l(const sp<LayerBase>& layer);
291
292    /* ------------------------------------------------------------------------
293     * Boot animation, on/off animations and screen capture
294     */
295
296    void startBootAnim();
297
298    status_t captureScreenImplLocked(
299            const sp<const DisplayDevice>& hw,
300            sp<IMemoryHeap>* heap,
301            uint32_t* width, uint32_t* height, PixelFormat* format,
302            uint32_t reqWidth, uint32_t reqHeight, uint32_t minLayerZ,
303            uint32_t maxLayerZ);
304
305    status_t captureScreenImplLocked(
306            const sp<const DisplayDevice>& hw,
307            const sp<IGraphicBufferProducer>& producer,
308            uint32_t reqWidth, uint32_t reqHeight,
309            uint32_t minLayerZ, uint32_t maxLayerZ);
310
311    /* ------------------------------------------------------------------------
312     * EGL
313     */
314    static status_t selectConfigForAttribute(EGLDisplay dpy,
315        EGLint const* attrs, EGLint attribute, EGLint value, EGLConfig* outConfig);
316    static EGLConfig selectEGLConfig(EGLDisplay disp, EGLint visualId);
317    static EGLContext createGLContext(EGLDisplay disp, EGLConfig config);
318    void initializeGL(EGLDisplay display);
319    uint32_t getMaxTextureSize() const;
320    uint32_t getMaxViewportDims() const;
321
322    /* ------------------------------------------------------------------------
323     * Display and layer stack management
324     */
325    // called when starting, or restarting after system_server death
326    void initializeDisplays();
327
328    // Create an IBinder for a builtin display and add it to current state
329    void createBuiltinDisplayLocked(DisplayDevice::DisplayType type);
330
331    // NOTE: can only be called from the main thread or with mStateLock held
332    sp<const DisplayDevice> getDisplayDevice(const wp<IBinder>& dpy) const {
333        return mDisplays.valueFor(dpy);
334    }
335
336    // NOTE: can only be called from the main thread or with mStateLock held
337    sp<DisplayDevice> getDisplayDevice(const wp<IBinder>& dpy) {
338        return mDisplays.valueFor(dpy);
339    }
340
341    // mark a region of a layer stack dirty. this updates the dirty
342    // region of all screens presenting this layer stack.
343    void invalidateLayerStack(uint32_t layerStack, const Region& dirty);
344
345    /* ------------------------------------------------------------------------
346     * H/W composer
347     */
348
349    HWComposer& getHwComposer() const { return *mHwc; }
350
351    /* ------------------------------------------------------------------------
352     * Compositing
353     */
354    void invalidateHwcGeometry();
355    static void computeVisibleRegions(
356            const LayerVector& currentLayers, uint32_t layerStack,
357            Region& dirtyRegion, Region& opaqueRegion);
358
359    void preComposition();
360    void postComposition();
361    void rebuildLayerStacks();
362    void setUpHWComposer();
363    void doComposition();
364    void doDebugFlashRegions();
365    void doDisplayComposition(const sp<const DisplayDevice>& hw,
366            const Region& dirtyRegion);
367    void doComposeSurfaces(const sp<const DisplayDevice>& hw,
368            const Region& dirty);
369
370    void postFramebuffer();
371    void drawWormhole(const sp<const DisplayDevice>& hw,
372            const Region& region) const;
373    GLuint getProtectedTexName() const {
374        return mProtectedTexName;
375    }
376
377    /* ------------------------------------------------------------------------
378     * Display management
379     */
380
381
382    /* ------------------------------------------------------------------------
383     * Debugging & dumpsys
384     */
385    void listLayersLocked(const Vector<String16>& args, size_t& index,
386        String8& result, char* buffer, size_t SIZE) const;
387    void dumpStatsLocked(const Vector<String16>& args, size_t& index,
388        String8& result, char* buffer, size_t SIZE) const;
389    void clearStatsLocked(const Vector<String16>& args, size_t& index,
390        String8& result, char* buffer, size_t SIZE);
391    void dumpAllLocked(String8& result, char* buffer, size_t SIZE) const;
392    bool startDdmConnection();
393    static void appendSfConfigString(String8& result);
394
395    /* ------------------------------------------------------------------------
396     * Attributes
397     */
398
399    // access must be protected by mStateLock
400    mutable Mutex mStateLock;
401    State mCurrentState;
402    volatile int32_t mTransactionFlags;
403    Condition mTransactionCV;
404    SortedVector<sp<LayerBase> > mLayerPurgatory;
405    bool mTransactionPending;
406    bool mAnimTransactionPending;
407    Vector<sp<LayerBase> > mLayersPendingRemoval;
408
409    // protected by mStateLock (but we could use another lock)
410    bool mLayersRemoved;
411
412    // access must be protected by mInvalidateLock
413    volatile int32_t mRepaintEverything;
414
415    // constant members (no synchronization needed for access)
416    HWComposer* mHwc;
417    GLuint mProtectedTexName;
418    nsecs_t mBootTime;
419    sp<EventThread> mEventThread;
420    GLint mMaxViewportDims[2];
421    GLint mMaxTextureSize;
422    EGLContext mEGLContext;
423    EGLConfig mEGLConfig;
424    EGLDisplay mEGLDisplay;
425    sp<IBinder> mBuiltinDisplays[DisplayDevice::NUM_DISPLAY_TYPES];
426
427    // Can only accessed from the main thread, these members
428    // don't need synchronization
429    State mDrawingState;
430    bool mVisibleRegionsDirty;
431    bool mHwWorkListDirty;
432    bool mAnimCompositionPending;
433
434    // this may only be written from the main thread with mStateLock held
435    // it may be read from other threads with mStateLock held
436    DefaultKeyedVector< wp<IBinder>, sp<DisplayDevice> > mDisplays;
437
438    // don't use a lock for these, we don't care
439    int mDebugRegion;
440    int mDebugDDMS;
441    int mDebugDisableHWC;
442    int mDebugDisableTransformHint;
443    volatile nsecs_t mDebugInSwapBuffers;
444    nsecs_t mLastSwapBufferTime;
445    volatile nsecs_t mDebugInTransaction;
446    nsecs_t mLastTransactionTime;
447    bool mBootFinished;
448
449    // these are thread safe
450    mutable MessageQueue mEventQueue;
451    mutable Barrier mReadyToRunBarrier;
452    FrameTracker mAnimFrameTracker;
453
454    // protected by mDestroyedLayerLock;
455    mutable Mutex mDestroyedLayerLock;
456    Vector<LayerBase const *> mDestroyedLayers;
457
458    /* ------------------------------------------------------------------------
459     * Feature prototyping
460     */
461
462    sp<IBinder> mExtDisplayToken;
463};
464
465// ---------------------------------------------------------------------------
466}; // namespace android
467
468#endif // ANDROID_SURFACE_FLINGER_H
469