SurfaceFlinger.h revision 48bc05b56df9919fc39c5f2e3ea6535560eec98f
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 id);
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,
189            const sp<IGraphicBufferProducer>& producer,
190            uint32_t reqWidth, uint32_t reqHeight,
191            uint32_t minLayerZ, uint32_t maxLayerZ, bool isCpuConsumer);
192    // called when screen needs to turn off
193    virtual void blank(const sp<IBinder>& display);
194    // called when screen is turning back on
195    virtual void unblank(const sp<IBinder>& display);
196    virtual status_t getDisplayInfo(const sp<IBinder>& display, DisplayInfo* info);
197
198    /* ------------------------------------------------------------------------
199     * DeathRecipient interface
200     */
201    virtual void binderDied(const wp<IBinder>& who);
202
203    /* ------------------------------------------------------------------------
204     * Thread interface
205     */
206    virtual bool threadLoop();
207    virtual status_t readyToRun();
208    virtual void onFirstRef();
209
210    /* ------------------------------------------------------------------------
211     * HWComposer::EventHandler interface
212     */
213    virtual void onVSyncReceived(int type, nsecs_t timestamp);
214    virtual void onHotplugReceived(int disp, bool connected);
215
216    /* ------------------------------------------------------------------------
217     * Message handling
218     */
219    void waitForEvent();
220    void signalTransaction();
221    void signalLayerUpdate();
222    void signalRefresh();
223
224    // called on the main thread in response to initializeDisplays()
225    void onInitializeDisplays();
226    // called on the main thread in response to blank()
227    void onScreenReleased(const sp<const DisplayDevice>& hw);
228    // called on the main thread in response to unblank()
229    void onScreenAcquired(const sp<const DisplayDevice>& hw);
230
231    void handleMessageTransaction();
232    void handleMessageInvalidate();
233    void handleMessageRefresh();
234
235    void handleTransaction(uint32_t transactionFlags);
236    void handleTransactionLocked(uint32_t transactionFlags);
237
238    /* handlePageFilp: this is were we latch a new buffer
239     * if available and compute the dirty region.
240     */
241    void handlePageFlip();
242
243    /* ------------------------------------------------------------------------
244     * Transactions
245     */
246    uint32_t getTransactionFlags(uint32_t flags);
247    uint32_t peekTransactionFlags(uint32_t flags);
248    uint32_t setTransactionFlags(uint32_t flags);
249    void commitTransaction();
250    uint32_t setClientStateLocked(const sp<Client>& client,
251        const layer_state_t& s);
252    uint32_t setDisplayStateLocked(const DisplayState& s);
253
254    /* ------------------------------------------------------------------------
255     * Layer management
256     */
257    status_t createLayer(const String8& name, const sp<Client>& client,
258            uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
259            sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp);
260
261    status_t createNormalLayer(const sp<Client>& client, const String8& name,
262            uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
263            sp<IBinder>* outHandle, sp<IGraphicBufferProducer>* outGbp,
264            sp<Layer>* outLayer);
265
266    status_t createDimLayer(const sp<Client>& client, const String8& name,
267            uint32_t w, uint32_t h, uint32_t flags, sp<IBinder>* outHandle,
268            sp<IGraphicBufferProducer>* outGbp, sp<Layer>* outLayer);
269
270    // called in response to the window-manager calling
271    // ISurfaceComposerClient::destroySurface()
272    status_t onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle);
273
274    // called when all clients have released all their references to
275    // this layer meaning it is entirely safe to destroy all
276    // resources associated to this layer.
277    status_t onLayerDestroyed(const wp<Layer>& layer);
278
279    // remove a layer from SurfaceFlinger immediately
280    status_t removeLayer(const sp<Layer>& layer);
281
282    // add a layer to SurfaceFlinger
283    void addClientLayer(const sp<Client>& client,
284            const sp<IBinder>& handle,
285            const sp<IGraphicBufferProducer>& gbc,
286            const sp<Layer>& lbc);
287
288    /* ------------------------------------------------------------------------
289     * Boot animation, on/off animations and screen capture
290     */
291
292    void startBootAnim();
293
294    status_t captureScreenImplLocked(
295            const sp<const DisplayDevice>& hw,
296            const sp<IGraphicBufferProducer>& producer,
297            uint32_t reqWidth, uint32_t reqHeight,
298            uint32_t minLayerZ, uint32_t maxLayerZ);
299
300    status_t captureScreenImplCpuConsumerLocked(
301            const sp<const DisplayDevice>& hw,
302            const sp<IGraphicBufferProducer>& producer,
303            uint32_t reqWidth, uint32_t reqHeight,
304            uint32_t minLayerZ, uint32_t maxLayerZ);
305
306
307    /* ------------------------------------------------------------------------
308     * EGL
309     */
310    static status_t selectConfigForAttribute(EGLDisplay dpy,
311        EGLint const* attrs, EGLint attribute, EGLint value, EGLConfig* outConfig);
312    static EGLConfig selectEGLConfig(EGLDisplay disp, EGLint visualId);
313    static EGLContext createGLContext(EGLDisplay disp, EGLConfig config);
314    void initializeGL(EGLDisplay display);
315    uint32_t getMaxTextureSize() const;
316    uint32_t getMaxViewportDims() const;
317
318    /* ------------------------------------------------------------------------
319     * Display and layer stack management
320     */
321    // called when starting, or restarting after system_server death
322    void initializeDisplays();
323
324    // Create an IBinder for a builtin display and add it to current state
325    void createBuiltinDisplayLocked(DisplayDevice::DisplayType type);
326
327    // NOTE: can only be called from the main thread or with mStateLock held
328    sp<const DisplayDevice> getDisplayDevice(const wp<IBinder>& dpy) const {
329        return mDisplays.valueFor(dpy);
330    }
331
332    // NOTE: can only be called from the main thread or with mStateLock held
333    sp<DisplayDevice> getDisplayDevice(const wp<IBinder>& dpy) {
334        return mDisplays.valueFor(dpy);
335    }
336
337    // mark a region of a layer stack dirty. this updates the dirty
338    // region of all screens presenting this layer stack.
339    void invalidateLayerStack(uint32_t layerStack, const Region& dirty);
340
341    /* ------------------------------------------------------------------------
342     * H/W composer
343     */
344
345    HWComposer& getHwComposer() const { return *mHwc; }
346
347    /* ------------------------------------------------------------------------
348     * Compositing
349     */
350    void invalidateHwcGeometry();
351    static void computeVisibleRegions(
352            const LayerVector& currentLayers, uint32_t layerStack,
353            Region& dirtyRegion, Region& opaqueRegion);
354
355    void preComposition();
356    void postComposition();
357    void rebuildLayerStacks();
358    void setUpHWComposer();
359    void doComposition();
360    void doDebugFlashRegions();
361    void doDisplayComposition(const sp<const DisplayDevice>& hw,
362            const Region& dirtyRegion);
363    void doComposeSurfaces(const sp<const DisplayDevice>& hw,
364            const Region& dirty);
365
366    void postFramebuffer();
367    void drawWormhole(const sp<const DisplayDevice>& hw,
368            const Region& region) const;
369    GLuint getProtectedTexName() const {
370        return mProtectedTexName;
371    }
372
373    /* ------------------------------------------------------------------------
374     * Display management
375     */
376
377
378    /* ------------------------------------------------------------------------
379     * Debugging & dumpsys
380     */
381    void listLayersLocked(const Vector<String16>& args, size_t& index,
382        String8& result, char* buffer, size_t SIZE) const;
383    void dumpStatsLocked(const Vector<String16>& args, size_t& index,
384        String8& result, char* buffer, size_t SIZE) const;
385    void clearStatsLocked(const Vector<String16>& args, size_t& index,
386        String8& result, char* buffer, size_t SIZE);
387    void dumpAllLocked(String8& result, char* buffer, size_t SIZE) const;
388    bool startDdmConnection();
389    static void appendSfConfigString(String8& result);
390
391    /* ------------------------------------------------------------------------
392     * Attributes
393     */
394
395    // access must be protected by mStateLock
396    mutable Mutex mStateLock;
397    State mCurrentState;
398    volatile int32_t mTransactionFlags;
399    Condition mTransactionCV;
400    bool mTransactionPending;
401    bool mAnimTransactionPending;
402    Vector< sp<Layer> > mLayersPendingRemoval;
403    SortedVector< wp<IBinder> > mGraphicBufferProducerList;
404
405    // protected by mStateLock (but we could use another lock)
406    bool mLayersRemoved;
407
408    // access must be protected by mInvalidateLock
409    volatile int32_t mRepaintEverything;
410
411    // constant members (no synchronization needed for access)
412    HWComposer* mHwc;
413    GLuint mProtectedTexName;
414    nsecs_t mBootTime;
415    bool mGpuToCpuSupported;
416    sp<EventThread> mEventThread;
417    GLint mMaxViewportDims[2];
418    GLint mMaxTextureSize;
419    EGLContext mEGLContext;
420    EGLConfig mEGLConfig;
421    EGLDisplay mEGLDisplay;
422    EGLint mEGLNativeVisualId;
423    sp<IBinder> mBuiltinDisplays[DisplayDevice::NUM_DISPLAY_TYPES];
424
425    // Can only accessed from the main thread, these members
426    // don't need synchronization
427    State mDrawingState;
428    bool mVisibleRegionsDirty;
429    bool mHwWorkListDirty;
430    bool mAnimCompositionPending;
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    FrameTracker mAnimFrameTracker;
451
452    // protected by mDestroyedLayerLock;
453    mutable Mutex mDestroyedLayerLock;
454    Vector<Layer const *> mDestroyedLayers;
455
456    /* ------------------------------------------------------------------------
457     * Feature prototyping
458     */
459
460    sp<IBinder> mExtDisplayToken;
461};
462
463// ---------------------------------------------------------------------------
464}; // namespace android
465
466#endif // ANDROID_SURFACE_FLINGER_H
467