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