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