OSDN Git Service

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