SurfaceFlinger.h revision 3f84483382be2d528918cc1a6fbc6a7d68e0b181
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
25/*
26 * NOTE: Make sure this file doesn't include  anything from <gl/ > or <gl2/ >
27 */
28
29#include <cutils/compiler.h>
30
31#include <utils/Atomic.h>
32#include <utils/Errors.h>
33#include <utils/KeyedVector.h>
34#include <utils/RefBase.h>
35#include <utils/SortedVector.h>
36#include <utils/threads.h>
37
38#include <binder/BinderService.h>
39#include <binder/IMemory.h>
40
41#include <ui/PixelFormat.h>
42
43#include <gui/ISurfaceComposer.h>
44#include <gui/ISurfaceComposerClient.h>
45
46#include <hardware/hwcomposer_defs.h>
47
48#include <private/gui/LayerState.h>
49
50#include "Barrier.h"
51#include "DisplayDevice.h"
52#include "FrameTracker.h"
53#include "MessageQueue.h"
54
55#include "DisplayHardware/HWComposer.h"
56
57namespace android {
58
59// ---------------------------------------------------------------------------
60
61class Client;
62class DisplayEventConnection;
63class EventThread;
64class IGraphicBufferAlloc;
65class Layer;
66class LayerDim;
67class Surface;
68class RenderEngine;
69
70// ---------------------------------------------------------------------------
71
72enum {
73    eTransactionNeeded        = 0x01,
74    eTraversalNeeded          = 0x02,
75    eDisplayTransactionNeeded = 0x04,
76    eTransactionMask          = 0x07
77};
78
79class SurfaceFlinger : public BinderService<SurfaceFlinger>,
80                       public BnSurfaceComposer,
81                       private IBinder::DeathRecipient,
82                       private Thread,
83                       private HWComposer::EventHandler
84{
85public:
86    static char const* getServiceName() ANDROID_API {
87        return "SurfaceFlinger";
88    }
89
90    SurfaceFlinger() ANDROID_API;
91
92    enum {
93        EVENT_VSYNC = HWC_EVENT_VSYNC
94    };
95
96    // post an asynchronous message to the main thread
97    status_t postMessageAsync(const sp<MessageBase>& msg, nsecs_t reltime = 0, 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, uint32_t flags = 0);
101
102    // force full composition on all displays
103    void repaintEverything();
104
105    // returns the default Display
106    sp<const DisplayDevice> getDefaultDisplayDevice() const {
107        return getDisplayDevice(mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]);
108    }
109
110    // utility function to delete a texture on the main thread
111    void deleteTextureAsync(uint32_t texture);
112
113    // enable/disable h/w composer event
114    // TODO: this should be made accessible only to EventThread
115    void eventControl(int disp, int event, int enabled);
116
117    // called on the main thread by MessageQueue when an internal message
118    // is received
119    // TODO: this should be made accessible only to MessageQueue
120    void onMessageReceived(int32_t what);
121
122    // for debugging only
123    // TODO: this should be made accessible only to HWComposer
124    const Vector< sp<Layer> >& getLayerSortedByZForHwcDisplay(int id);
125
126    RenderEngine& getRenderEngine() const {
127        return *mRenderEngine;
128    }
129
130private:
131    friend class Client;
132    friend class DisplayEventConnection;
133    friend class Layer;
134    friend class SurfaceTextureLayer;
135
136    // This value is specified in number of frames.  Log frame stats at most
137    // every half hour.
138    enum { LOG_FRAME_STATS_PERIOD =  30*60*60 };
139
140    // We're reference counted, never destroy SurfaceFlinger directly
141    virtual ~SurfaceFlinger();
142
143    /* ------------------------------------------------------------------------
144     * Internal data structures
145     */
146
147    class LayerVector : public SortedVector< sp<Layer> > {
148    public:
149        LayerVector();
150        LayerVector(const LayerVector& rhs);
151        virtual int do_compare(const void* lhs, const void* rhs) const;
152    };
153
154    struct DisplayDeviceState {
155        DisplayDeviceState();
156        DisplayDeviceState(DisplayDevice::DisplayType type);
157        bool isValid() const { return type >= 0; }
158        bool isMainDisplay() const { return type == DisplayDevice::DISPLAY_PRIMARY; }
159        bool isVirtualDisplay() const { return type >= DisplayDevice::DISPLAY_VIRTUAL; }
160        DisplayDevice::DisplayType type;
161        sp<IGraphicBufferProducer> surface;
162        uint32_t layerStack;
163        Rect viewport;
164        Rect frame;
165        uint8_t orientation;
166        String8 displayName;
167        bool isSecure;
168    };
169
170    struct State {
171        LayerVector layersSortedByZ;
172        DefaultKeyedVector< wp<IBinder>, DisplayDeviceState> displays;
173    };
174
175    /* ------------------------------------------------------------------------
176     * IBinder interface
177     */
178    virtual status_t onTransact(uint32_t code, const Parcel& data,
179        Parcel* reply, uint32_t flags);
180    virtual status_t dump(int fd, const Vector<String16>& args);
181
182    /* ------------------------------------------------------------------------
183     * ISurfaceComposer interface
184     */
185    virtual sp<ISurfaceComposerClient> createConnection();
186    virtual sp<IGraphicBufferAlloc> createGraphicBufferAlloc();
187    virtual sp<IBinder> createDisplay(const String8& displayName, bool secure);
188    virtual void destroyDisplay(const sp<IBinder>& display);
189    virtual sp<IBinder> getBuiltInDisplay(int32_t id);
190    virtual void setTransactionState(const Vector<ComposerState>& state,
191            const Vector<DisplayState>& displays, uint32_t flags);
192    virtual void bootFinished();
193    virtual bool authenticateSurfaceTexture(
194        const sp<IGraphicBufferProducer>& bufferProducer) const;
195    virtual sp<IDisplayEventConnection> createDisplayEventConnection();
196    virtual status_t captureScreen(const sp<IBinder>& display,
197            const sp<IGraphicBufferProducer>& producer,
198            uint32_t reqWidth, uint32_t reqHeight,
199            uint32_t minLayerZ, uint32_t maxLayerZ);
200    // called when screen needs to turn off
201    virtual void blank(const sp<IBinder>& display);
202    // called when screen is turning back on
203    virtual void unblank(const sp<IBinder>& display);
204    virtual status_t getDisplayInfo(const sp<IBinder>& display, DisplayInfo* info);
205
206    /* ------------------------------------------------------------------------
207     * DeathRecipient interface
208     */
209    virtual void binderDied(const wp<IBinder>& who);
210
211    /* ------------------------------------------------------------------------
212     * Thread interface
213     */
214    virtual bool threadLoop();
215    virtual status_t readyToRun();
216    virtual void onFirstRef();
217
218    /* ------------------------------------------------------------------------
219     * HWComposer::EventHandler interface
220     */
221    virtual void onVSyncReceived(int type, nsecs_t timestamp);
222    virtual void onHotplugReceived(int disp, bool connected);
223
224    /* ------------------------------------------------------------------------
225     * Message handling
226     */
227    void waitForEvent();
228    void signalTransaction();
229    void signalLayerUpdate();
230    void signalRefresh();
231
232    // called on the main thread in response to initializeDisplays()
233    void onInitializeDisplays();
234    // called on the main thread in response to blank()
235    void onScreenReleased(const sp<const DisplayDevice>& hw);
236    // called on the main thread in response to unblank()
237    void onScreenAcquired(const sp<const DisplayDevice>& hw);
238
239    void handleMessageTransaction();
240    void handleMessageInvalidate();
241    void handleMessageRefresh();
242
243    void handleTransaction(uint32_t transactionFlags);
244    void handleTransactionLocked(uint32_t transactionFlags);
245
246    /* handlePageFilp: this is were we latch a new buffer
247     * if available and compute the dirty region.
248     */
249    void handlePageFlip();
250
251    /* ------------------------------------------------------------------------
252     * Transactions
253     */
254    uint32_t getTransactionFlags(uint32_t flags);
255    uint32_t peekTransactionFlags(uint32_t flags);
256    uint32_t setTransactionFlags(uint32_t flags);
257    void commitTransaction();
258    uint32_t setClientStateLocked(const sp<Client>& client, const layer_state_t& s);
259    uint32_t setDisplayStateLocked(const DisplayState& s);
260
261    /* ------------------------------------------------------------------------
262     * Layer management
263     */
264    status_t createLayer(const String8& name, const sp<Client>& client,
265            uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
266            sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp);
267
268    status_t createNormalLayer(const sp<Client>& client, const String8& name,
269            uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
270            sp<IBinder>* outHandle, sp<IGraphicBufferProducer>* outGbp,
271            sp<Layer>* outLayer);
272
273    status_t createDimLayer(const sp<Client>& client, const String8& name,
274            uint32_t w, uint32_t h, uint32_t flags, sp<IBinder>* outHandle,
275            sp<IGraphicBufferProducer>* outGbp, sp<Layer>* outLayer);
276
277    // called in response to the window-manager calling
278    // ISurfaceComposerClient::destroySurface()
279    status_t onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle);
280
281    // called when all clients have released all their references to
282    // this layer meaning it is entirely safe to destroy all
283    // resources associated to this layer.
284    status_t onLayerDestroyed(const wp<Layer>& layer);
285
286    // remove a layer from SurfaceFlinger immediately
287    status_t removeLayer(const sp<Layer>& layer);
288
289    // add a layer to SurfaceFlinger
290    void addClientLayer(const sp<Client>& client,
291            const sp<IBinder>& handle,
292            const sp<IGraphicBufferProducer>& gbc,
293            const sp<Layer>& lbc);
294
295    /* ------------------------------------------------------------------------
296     * Boot animation, on/off animations and screen capture
297     */
298
299    void startBootAnim();
300
301    void renderScreenImplLocked(
302            const sp<const DisplayDevice>& hw,
303            uint32_t reqWidth, uint32_t reqHeight,
304            uint32_t minLayerZ, uint32_t maxLayerZ,
305            bool yswap);
306
307    status_t captureScreenImplLocked(
308            const sp<const DisplayDevice>& hw,
309            const sp<IGraphicBufferProducer>& producer,
310            uint32_t reqWidth, uint32_t reqHeight,
311            uint32_t minLayerZ, 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    size_t getMaxTextureSize() const;
320    size_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    // allocate a h/w composer display id
346    int32_t allocateHwcDisplayId(DisplayDevice::DisplayType type);
347
348    /* ------------------------------------------------------------------------
349     * H/W composer
350     */
351
352    HWComposer& getHwComposer() const { return *mHwc; }
353
354    /* ------------------------------------------------------------------------
355     * Compositing
356     */
357    void invalidateHwcGeometry();
358    static void computeVisibleRegions(
359            const LayerVector& currentLayers, uint32_t layerStack,
360            Region& dirtyRegion, Region& opaqueRegion);
361
362    void preComposition();
363    void postComposition();
364    void rebuildLayerStacks();
365    void setUpHWComposer();
366    void doComposition();
367    void doDebugFlashRegions();
368    void doDisplayComposition(const sp<const DisplayDevice>& hw, const Region& dirtyRegion);
369    void doComposeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty);
370
371    void postFramebuffer();
372    void drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const;
373
374    /* ------------------------------------------------------------------------
375     * Display management
376     */
377
378
379    /* ------------------------------------------------------------------------
380     * Debugging & dumpsys
381     */
382    void listLayersLocked(const Vector<String16>& args, size_t& index, String8& result) const;
383    void dumpStatsLocked(const Vector<String16>& args, size_t& index, String8& result) const;
384    void clearStatsLocked(const Vector<String16>& args, size_t& index, String8& result);
385    void dumpAllLocked(const Vector<String16>& args, size_t& index, String8& result) const;
386    bool startDdmConnection();
387    static void appendSfConfigString(String8& result);
388    void checkScreenshot(const sp<GraphicBuffer>& buf, void const* vaddr,
389            const sp<const DisplayDevice>& hw,
390            uint32_t minLayerZ, uint32_t maxLayerZ);
391
392    void logFrameStats();
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    bool mTransactionPending;
404    bool mAnimTransactionPending;
405    Vector< sp<Layer> > mLayersPendingRemoval;
406    SortedVector< wp<IBinder> > mGraphicBufferProducerList;
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    RenderEngine* mRenderEngine;
417    nsecs_t mBootTime;
418    bool mGpuToCpuSupported;
419    sp<EventThread> mEventThread;
420    EGLContext mEGLContext;
421    EGLConfig mEGLConfig;
422    EGLDisplay mEGLDisplay;
423    EGLint mEGLNativeVisualId;
424    sp<IBinder> mBuiltinDisplays[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    bool mAnimCompositionPending;
432
433    // this may only be written from the main thread with mStateLock held
434    // it may be read from other threads with mStateLock held
435    DefaultKeyedVector< wp<IBinder>, sp<DisplayDevice> > mDisplays;
436
437    // don't use a lock for these, we don't care
438    int mDebugRegion;
439    int mDebugDDMS;
440    int mDebugDisableHWC;
441    int mDebugDisableTransformHint;
442    volatile nsecs_t mDebugInSwapBuffers;
443    nsecs_t mLastSwapBufferTime;
444    volatile nsecs_t mDebugInTransaction;
445    nsecs_t mLastTransactionTime;
446    bool mBootFinished;
447
448    // these are thread safe
449    mutable MessageQueue mEventQueue;
450    mutable Barrier mReadyToRunBarrier;
451    FrameTracker mAnimFrameTracker;
452
453    // protected by mDestroyedLayerLock;
454    mutable Mutex mDestroyedLayerLock;
455    Vector<Layer const *> mDestroyedLayers;
456
457    /* ------------------------------------------------------------------------
458     * Feature prototyping
459     */
460
461    sp<IBinder> mExtDisplayToken;
462};
463
464// ---------------------------------------------------------------------------
465}; // namespace android
466
467#endif // ANDROID_SURFACE_FLINGER_H
468