OSDN Git Service

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