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