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