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