SurfaceFlinger.h revision 8630320433bd15aca239522e54e711ef6372ab07
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
51#include "DisplayHardware/HWComposer.h"
52
53namespace android {
54
55// ---------------------------------------------------------------------------
56
57class Client;
58class DisplayEventConnection;
59class DisplayHardware;
60class EventThread;
61class Layer;
62class LayerBase;
63class LayerBaseClient;
64class LayerDim;
65class LayerScreenshot;
66class SurfaceTextureClient;
67struct surface_flinger_cblk_t;
68
69// ---------------------------------------------------------------------------
70
71class GraphicBufferAlloc : public BnGraphicBufferAlloc {
72public:
73    GraphicBufferAlloc();
74    virtual ~GraphicBufferAlloc();
75    virtual sp<GraphicBuffer> createGraphicBuffer(uint32_t w, uint32_t h,
76        PixelFormat format, uint32_t usage, status_t* error);
77};
78
79// ---------------------------------------------------------------------------
80
81enum {
82    eTransactionNeeded = 0x01, eTraversalNeeded = 0x02
83};
84
85class SurfaceFlinger : public BinderService<SurfaceFlinger>,
86                       public BnSurfaceComposer,
87                       private IBinder::DeathRecipient,
88                       private Thread,
89                       private HWComposer::EventHandler
90{
91public:
92    static char const* getServiceName() {
93        return "SurfaceFlinger";
94    }
95
96    SurfaceFlinger();
97
98    enum {
99        EVENT_VSYNC = HWC_EVENT_VSYNC
100    };
101
102    // post an asynchronous message to the main thread
103    status_t postMessageAsync(const sp<MessageBase>& msg, nsecs_t reltime = 0,
104        uint32_t flags = 0);
105
106    // post a synchronous message to the main thread
107    status_t postMessageSync(const sp<MessageBase>& msg, nsecs_t reltime = 0,
108        uint32_t flags = 0);
109
110    // force full composition on all displays
111    void repaintEverything();
112
113    // renders content on given display to a texture. thread-safe version.
114    status_t renderScreenToTexture(DisplayID dpy, GLuint* textureName,
115        GLfloat* uOut, GLfloat* vOut);
116
117    // renders content on given display to a texture, w/o acquiring main lock
118    status_t renderScreenToTextureLocked(DisplayID dpy, GLuint* textureName,
119        GLfloat* uOut, GLfloat* vOut);
120
121    // returns the default Display
122    const DisplayHardware& getDefaultDisplayHardware() const {
123        return getDisplayHardware(0);
124    }
125
126    // utility function to delete a texture on the main thread
127    void deleteTextureAsync(GLuint texture);
128
129
130    // enable/disable h/w composer event
131    // TODO: this should be made accessible only to EventThread
132    void eventControl(int event, int enabled);
133
134    // called on the main thread by MessageQueue when an internal message
135    // is received
136    // TODO: this should be made accessible only to MessageQueue
137    void onMessageReceived(int32_t what);
138
139private:
140    friend class Client;
141    friend class DisplayEventConnection;
142    friend class LayerBase;
143    friend class LayerBaseClient;
144    friend class Layer;
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 State {
161        State();
162        LayerVector layersSortedByZ;
163        uint8_t orientation;
164        uint8_t orientationFlags;
165    };
166
167    /* ------------------------------------------------------------------------
168     * IBinder interface
169     */
170    virtual status_t onTransact(uint32_t code, const Parcel& data,
171        Parcel* reply, uint32_t flags);
172    virtual status_t dump(int fd, const Vector<String16>& args);
173
174    /* ------------------------------------------------------------------------
175     * ISurfaceComposer interface
176     */
177    virtual sp<ISurfaceComposerClient> createConnection();
178    virtual sp<IGraphicBufferAlloc> createGraphicBufferAlloc();
179    virtual sp<IMemoryHeap> getCblk() const;
180    virtual void bootFinished();
181    virtual void setTransactionState(const Vector<ComposerState>& state,
182            const Vector<DisplayState>& displays, uint32_t flags);
183    virtual bool authenticateSurfaceTexture(
184        const sp<ISurfaceTexture>& surface) const;
185    virtual sp<IDisplayEventConnection> createDisplayEventConnection();
186    virtual status_t captureScreen(DisplayID dpy, sp<IMemoryHeap>* heap,
187        uint32_t* width, uint32_t* height, PixelFormat* format,
188        uint32_t reqWidth, uint32_t reqHeight, uint32_t minLayerZ,
189        uint32_t maxLayerZ);
190    virtual status_t turnElectronBeamOff(int32_t mode);
191    virtual status_t turnElectronBeamOn(int32_t mode);
192    // called when screen needs to turn off
193    virtual void blank();
194    // called when screen is turning back on
195    virtual void unblank();
196    virtual void connectDisplay(const sp<ISurfaceTexture> display);
197
198    /* ------------------------------------------------------------------------
199     * DeathRecipient interface
200     */
201    virtual void binderDied(const wp<IBinder>& who);
202
203    /* ------------------------------------------------------------------------
204     * Thread interface
205     */
206    virtual bool threadLoop();
207    virtual status_t readyToRun();
208    virtual void onFirstRef();
209
210    /* ------------------------------------------------------------------------
211     * HWComposer::EventHandler interface
212     */
213    virtual void onVSyncReceived(int dpy, nsecs_t timestamp);
214
215    /* ------------------------------------------------------------------------
216     * Message handling
217     */
218    void waitForEvent();
219    void signalTransaction();
220    void signalLayerUpdate();
221    void signalRefresh();
222
223    // called on the main thread in response to screenReleased()
224    void onScreenReleased();
225    // called on the main thread in response to screenAcquired()
226    void onScreenAcquired();
227
228    void handleMessageTransaction();
229    void handleMessageInvalidate();
230    void handleMessageRefresh();
231
232    Region handleTransaction(uint32_t transactionFlags);
233    Region handleTransactionLocked(uint32_t transactionFlags);
234
235    /* handlePageFilp: this is were we latch a new buffer
236     * if available and compute the dirty region.
237     * The return value is the dirty region expressed in the
238     * window manager's coordinate space (or the layer's state
239     * space, which is the same thing), in particular the dirty
240     * region is independent from a specific display's orientation.
241     */
242    Region handlePageFlip();
243
244    void handleRefresh();
245    void handleWorkList(const DisplayHardware& hw);
246    void handleRepaint(const DisplayHardware& hw);
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
258    /* ------------------------------------------------------------------------
259     * Layer management
260     */
261    sp<ISurface> createLayer(ISurfaceComposerClient::surface_data_t* params,
262        const String8& name, const sp<Client>& client, DisplayID display,
263        uint32_t w, uint32_t h, PixelFormat format, uint32_t flags);
264
265    sp<Layer> createNormalLayer(const sp<Client>& client, DisplayID display,
266        uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format);
267
268    sp<LayerDim> createDimLayer(const sp<Client>& client, DisplayID display,
269        uint32_t w, uint32_t h, uint32_t flags);
270
271    sp<LayerScreenshot> createScreenshotLayer(const sp<Client>& client,
272        DisplayID display, uint32_t w, uint32_t h, uint32_t flags);
273
274    // called in response to the window-manager calling
275    // ISurfaceComposerClient::destroySurface()
276    // The specified layer is first placed in a purgatory list
277    // until all references from the client are released.
278    status_t onLayerRemoved(const sp<Client>& client, SurfaceID sid);
279
280    // called when all clients have released all their references to
281    // this layer meaning it is entirely safe to destroy all
282    // resources associated to this layer.
283    status_t onLayerDestroyed(const wp<LayerBaseClient>& layer);
284
285    // remove a layer from SurfaceFlinger immediately
286    status_t removeLayer(const sp<LayerBase>& layer);
287
288    // add a layer to SurfaceFlinger
289    ssize_t addClientLayer(const sp<Client>& client,
290        const sp<LayerBaseClient>& lbc);
291
292    status_t removeLayer_l(const sp<LayerBase>& layer);
293    status_t purgatorizeLayer_l(const sp<LayerBase>& layer);
294
295    /* ------------------------------------------------------------------------
296     * Boot animation, on/off animations and screen capture
297     */
298
299    void startBootAnim();
300
301    status_t captureScreenImplLocked(DisplayID dpy, sp<IMemoryHeap>* heap,
302        uint32_t* width, uint32_t* height, PixelFormat* format,
303        uint32_t reqWidth, uint32_t reqHeight, uint32_t minLayerZ,
304        uint32_t maxLayerZ);
305
306    status_t turnElectronBeamOffImplLocked(int32_t mode);
307    status_t turnElectronBeamOnImplLocked(int32_t mode);
308    status_t electronBeamOffAnimationImplLocked();
309    status_t electronBeamOnAnimationImplLocked();
310
311    /* ------------------------------------------------------------------------
312     * EGL
313     */
314    static status_t selectConfigForPixelFormat(EGLDisplay dpy,
315        EGLint const* attrs, PixelFormat format, EGLConfig* outConfig);
316    static EGLConfig selectEGLConfig(EGLDisplay disp, EGLint visualId);
317    static EGLContext createGLContext(EGLDisplay disp, EGLConfig config);
318    void initializeGL(EGLDisplay display, EGLSurface surface);
319    uint32_t getMaxTextureSize() const;
320    uint32_t getMaxViewportDims() const;
321
322    /* ------------------------------------------------------------------------
323     * Display management
324     */
325    const DisplayHardware& getDisplayHardware(DisplayID dpy) const {
326        return *mDisplayHardwares[dpy];
327    }
328
329    /* ------------------------------------------------------------------------
330     * H/W composer
331     */
332
333    HWComposer& getHwComposer() const { return *mHwc; }
334
335        /* ------------------------------------------------------------------------
336     * Compositing
337     */
338    void invalidateHwcGeometry();
339    void computeVisibleRegions(const LayerVector& currentLayers,
340        Region& dirtyRegion, Region& wormholeRegion);
341    void postFramebuffer();
342    void setupHardwareComposer(const DisplayHardware& hw);
343    void composeSurfaces(const DisplayHardware& hw, const Region& dirty);
344    void setInvalidateRegion(const Region& reg);
345    Region getAndClearInvalidateRegion();
346    void drawWormhole() const;
347    GLuint getProtectedTexName() const {
348        return mProtectedTexName;
349    }
350
351    /* ------------------------------------------------------------------------
352     * Debugging & dumpsys
353     */
354    void debugFlashRegions(const DisplayHardware& hw);
355    void listLayersLocked(const Vector<String16>& args, size_t& index,
356        String8& result, char* buffer, size_t SIZE) const;
357    void dumpStatsLocked(const Vector<String16>& args, size_t& index,
358        String8& result, char* buffer, size_t SIZE) const;
359    void clearStatsLocked(const Vector<String16>& args, size_t& index,
360        String8& result, char* buffer, size_t SIZE) const;
361    void dumpAllLocked(String8& result, char* buffer, size_t SIZE) const;
362
363    /* ------------------------------------------------------------------------
364     * Attributes
365     */
366
367    // access must be protected by mStateLock
368    mutable Mutex mStateLock;
369    State mCurrentState;
370    volatile int32_t mTransactionFlags;
371    Condition mTransactionCV;
372    SortedVector<sp<LayerBase> > mLayerPurgatory;
373    bool mTransationPending;
374    Vector<sp<LayerBase> > mLayersPendingRemoval;
375
376    // protected by mStateLock (but we could use another lock)
377    DisplayHardware* mDisplayHardwares[1];
378    bool mLayersRemoved;
379
380    // access must be protected by mInvalidateLock
381    mutable Mutex mInvalidateLock;
382    Region mInvalidateRegion;
383
384    // constant members (no synchronization needed for access)
385    sp<IMemoryHeap> mServerHeap;
386    surface_flinger_cblk_t* mServerCblk;
387    HWComposer* mHwc;
388    GLuint mWormholeTexName;
389    GLuint mProtectedTexName;
390    nsecs_t mBootTime;
391    sp<EventThread> mEventThread;
392    GLint mMaxViewportDims[2];
393    GLint mMaxTextureSize;
394    EGLContext mEGLContext;
395    EGLConfig mEGLConfig;
396
397    // Can only accessed from the main thread, these members
398    // don't need synchronization
399    State mDrawingState;
400    Region mDirtyRegion;
401    Region mDirtyRegionRemovedLayer;
402    Region mSwapRegion;
403    Region mWormholeRegion;
404    bool mVisibleRegionsDirty;
405    bool mHwWorkListDirty;
406    int32_t mElectronBeamAnimationMode;
407
408    // don't use a lock for these, we don't care
409    int mDebugRegion;
410    int mDebugDDMS;
411    int mDebugDisableHWC;
412    int mDebugDisableTransformHint;
413    volatile nsecs_t mDebugInSwapBuffers;
414    nsecs_t mLastSwapBufferTime;
415    volatile nsecs_t mDebugInTransaction;
416    nsecs_t mLastTransactionTime;
417    bool mBootFinished;
418
419    // these are thread safe
420    mutable MessageQueue mEventQueue;
421    mutable Barrier mReadyToRunBarrier;
422
423    // protected by mDestroyedLayerLock;
424    mutable Mutex mDestroyedLayerLock;
425    Vector<LayerBase const *> mDestroyedLayers;
426
427    /* ------------------------------------------------------------------------
428     * Feature prototyping
429     */
430
431    EGLSurface getExternalDisplaySurface() const;
432    sp<SurfaceTextureClient> mExternalDisplayNativeWindow;
433    EGLSurface mExternalDisplaySurface;
434public:
435    surface_flinger_cblk_t* getControlBlock() const;
436};
437
438// ---------------------------------------------------------------------------
439}; // namespace android
440
441#endif // ANDROID_SURFACE_FLINGER_H
442