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