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