OSDN Git Service

Merge remote-tracking branch 'cm/cm-13.0' into cm-13.0-x86
[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 #include <ui/mat4.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 "DispSync.h"
53 #include "FrameTracker.h"
54 #include "MessageQueue.h"
55
56 #include "DisplayHardware/HWComposer.h"
57 #include "Effects/Daltonizer.h"
58
59 #include "FrameRateHelper.h"
60
61 namespace android {
62
63 // ---------------------------------------------------------------------------
64
65 class Client;
66 class DisplayEventConnection;
67 class EventThread;
68 class IGraphicBufferAlloc;
69 class Layer;
70 class LayerDim;
71 class LayerBlur;
72 class Surface;
73 class RenderEngine;
74 class EventControlThread;
75
76 // ---------------------------------------------------------------------------
77
78 enum {
79     eTransactionNeeded        = 0x01,
80     eTraversalNeeded          = 0x02,
81     eDisplayTransactionNeeded = 0x04,
82     eTransactionMask          = 0x07
83 };
84
85 class SurfaceFlinger : public BnSurfaceComposer,
86                        private IBinder::DeathRecipient,
87                        private HWComposer::EventHandler
88 {
89 public:
90 #ifdef QTI_BSP
91     friend class ExSurfaceFlinger;
92 #endif
93
94     static char const* getServiceName() ANDROID_API {
95         return "SurfaceFlinger";
96     }
97
98     SurfaceFlinger() ANDROID_API;
99
100     // must be called before clients can connect
101     void init() ANDROID_API;
102
103     // starts SurfaceFlinger main loop in the current thread
104     void run() ANDROID_API;
105
106     enum {
107         EVENT_VSYNC = HWC_EVENT_VSYNC
108     };
109
110     // post an asynchronous message to the main thread
111     status_t postMessageAsync(const sp<MessageBase>& msg, nsecs_t reltime = 0, uint32_t flags = 0);
112
113     // post a synchronous message to the main thread
114     status_t postMessageSync(const sp<MessageBase>& msg, nsecs_t reltime = 0, uint32_t flags = 0);
115
116     // force full composition on all displays
117     void repaintEverything();
118
119     // returns the default Display
120     sp<const DisplayDevice> getDefaultDisplayDevice() const {
121         return getDisplayDevice(mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]);
122     }
123
124     // utility function to delete a texture on the main thread
125     void deleteTextureAsync(uint32_t texture);
126
127     // enable/disable h/w composer event
128     // TODO: this should be made accessible only to EventThread
129     void eventControl(int disp, int event, int enabled);
130
131     // called on the main thread by MessageQueue when an internal message
132     // is received
133     // TODO: this should be made accessible only to MessageQueue
134     void onMessageReceived(int32_t what);
135
136     // for debugging only
137     // TODO: this should be made accessible only to HWComposer
138     const Vector< sp<Layer> >& getLayerSortedByZForHwcDisplay(int id);
139
140     RenderEngine& getRenderEngine() const {
141         return *mRenderEngine;
142     }
143
144     void screenReleased(const sp<IBinder>& display);
145     void screenAcquired(const sp<IBinder>& display);
146
147 private:
148     friend class Client;
149     friend class DisplayEventConnection;
150     friend class Layer;
151     friend class LayerDim;
152 #ifdef QTI_BSP
153     friend class ExLayer;
154 #endif
155     friend class MonitoredProducer;
156     friend class LayerBlur;
157
158     // This value is specified in number of frames.  Log frame stats at most
159     // every half hour.
160     enum { LOG_FRAME_STATS_PERIOD =  30*60*60 };
161
162     static const size_t MAX_LAYERS = 4096;
163
164     // We're reference counted, never destroy SurfaceFlinger directly
165     virtual ~SurfaceFlinger();
166
167     /* ------------------------------------------------------------------------
168      * Internal data structures
169      */
170
171     class LayerVector : public SortedVector< sp<Layer> > {
172     public:
173         LayerVector();
174         LayerVector(const LayerVector& rhs);
175         virtual int do_compare(const void* lhs, const void* rhs) const;
176     };
177
178     struct DisplayDeviceState {
179         DisplayDeviceState();
180         DisplayDeviceState(DisplayDevice::DisplayType type);
181         bool isValid() const { return type >= 0; }
182         bool isMainDisplay() const { return type == DisplayDevice::DISPLAY_PRIMARY; }
183         bool isVirtualDisplay() const { return type >= DisplayDevice::DISPLAY_VIRTUAL; }
184         DisplayDevice::DisplayType type;
185         sp<IGraphicBufferProducer> surface;
186         uint32_t layerStack;
187         Rect viewport;
188         Rect frame;
189         uint8_t orientation;
190         uint32_t width, height;
191         String8 displayName;
192         bool isSecure;
193     };
194
195     struct State {
196         LayerVector layersSortedByZ;
197         DefaultKeyedVector< wp<IBinder>, DisplayDeviceState> displays;
198     };
199
200     /* ------------------------------------------------------------------------
201      * IBinder interface
202      */
203     virtual status_t onTransact(uint32_t code, const Parcel& data,
204         Parcel* reply, uint32_t flags);
205     virtual status_t dump(int fd, const Vector<String16>& args);
206
207     /* ------------------------------------------------------------------------
208      * ISurfaceComposer interface
209      */
210     virtual sp<ISurfaceComposerClient> createConnection();
211     virtual sp<IGraphicBufferAlloc> createGraphicBufferAlloc();
212     virtual sp<IBinder> createDisplay(const String8& displayName, bool secure);
213     virtual void destroyDisplay(const sp<IBinder>& display);
214     virtual sp<IBinder> getBuiltInDisplay(int32_t id);
215     virtual void setTransactionState(const Vector<ComposerState>& state,
216             const Vector<DisplayState>& displays, uint32_t flags);
217     virtual void bootFinished();
218     virtual bool authenticateSurfaceTexture(
219         const sp<IGraphicBufferProducer>& bufferProducer) const;
220     virtual sp<IDisplayEventConnection> createDisplayEventConnection();
221     virtual status_t captureScreen(const sp<IBinder>& display,
222             const sp<IGraphicBufferProducer>& producer,
223             Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
224             uint32_t minLayerZ, uint32_t maxLayerZ,
225             bool useIdentityTransform, ISurfaceComposer::Rotation rotation,
226             bool isCpuConsumer);
227     virtual status_t getDisplayStats(const sp<IBinder>& display,
228             DisplayStatInfo* stats);
229     virtual status_t getDisplayConfigs(const sp<IBinder>& display,
230             Vector<DisplayInfo>* configs);
231     virtual int getActiveConfig(const sp<IBinder>& display);
232     virtual void setPowerMode(const sp<IBinder>& display, int mode);
233     virtual status_t setActiveConfig(const sp<IBinder>& display, int id);
234     virtual status_t clearAnimationFrameStats();
235     virtual status_t getAnimationFrameStats(FrameStats* outStats) const;
236
237     /* ------------------------------------------------------------------------
238      * DeathRecipient interface
239      */
240     virtual void binderDied(const wp<IBinder>& who);
241
242     /* ------------------------------------------------------------------------
243      * RefBase interface
244      */
245     virtual void onFirstRef();
246
247     /* ------------------------------------------------------------------------
248      * HWComposer::EventHandler interface
249      */
250     virtual void onVSyncReceived(int type, nsecs_t timestamp);
251     virtual void onHotplugReceived(int disp, bool connected);
252
253     /* ------------------------------------------------------------------------
254      * Extensions
255      */
256     virtual void updateExtendedMode() { }
257
258     virtual void getIndexLOI(size_t /*dpy*/,
259                      const LayerVector& /*currentLayers*/,
260                      bool& /*bIgnoreLayers*/,
261                      int& /*indexLOI*/) { }
262
263     virtual bool updateLayerVisibleNonTransparentRegion(
264                      const int& dpy, const sp<Layer>& layer,
265                      bool& bIgnoreLayers, int& indexLOI,
266                      uint32_t layerStack, const int& i);
267
268     virtual void delayDPTransactionIfNeeded(
269                      const Vector<DisplayState>& /*displays*/) { }
270
271     virtual bool canDrawLayerinScreenShot(
272                      const sp<const DisplayDevice>& hw,
273                      const sp<Layer>& layer);
274
275     virtual void isfreezeSurfacePresent(
276                      bool& freezeSurfacePresent,
277                      const sp<const DisplayDevice>& /*hw*/,
278                      const int32_t& /*id*/) { freezeSurfacePresent = false; }
279
280     virtual void setOrientationEventControl(
281                      bool& /*freezeSurfacePresent*/,
282                      const int32_t& /*id*/) { }
283
284     virtual void updateVisibleRegionsDirty() { }
285
286     virtual void  drawWormHoleIfRequired(HWComposer::LayerListIterator &cur,
287         const HWComposer::LayerListIterator &end,
288         const sp<const DisplayDevice>& hw,
289         const Region& region);
290     /* ------------------------------------------------------------------------
291      * Message handling
292      */
293     void waitForEvent();
294     void signalTransaction();
295     void signalLayerUpdate();
296     void signalRefresh();
297
298     // called on the main thread in response to initializeDisplays()
299     void onInitializeDisplays();
300     // called on the main thread in response to setActiveConfig()
301     void setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode);
302     // called on the main thread in response to setPowerMode()
303     void setPowerModeInternal(const sp<DisplayDevice>& hw, int mode);
304
305     // Returns whether the transaction actually modified any state
306     bool handleMessageTransaction();
307
308     // Returns whether a new buffer has been latched (see handlePageFlip())
309     bool handleMessageInvalidate();
310
311     void handleMessageRefresh();
312
313     void handleTransaction(uint32_t transactionFlags);
314     void handleTransactionLocked(uint32_t transactionFlags);
315
316     void updateCursorAsync();
317
318     /* handlePageFlip - latch a new buffer if available and compute the dirty
319      * region. Returns whether a new buffer has been latched, i.e., whether it
320      * is necessary to perform a refresh during this vsync.
321      */
322     bool handlePageFlip();
323
324     /* ------------------------------------------------------------------------
325      * Transactions
326      */
327     uint32_t getTransactionFlags(uint32_t flags);
328     uint32_t peekTransactionFlags(uint32_t flags);
329     uint32_t setTransactionFlags(uint32_t flags);
330     void commitTransaction();
331     uint32_t setClientStateLocked(const sp<Client>& client, const layer_state_t& s);
332     uint32_t setDisplayStateLocked(const DisplayState& s);
333
334     /* ------------------------------------------------------------------------
335      * Layer management
336      */
337     status_t createLayer(const String8& name, const sp<Client>& client,
338             uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
339             sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp);
340
341     status_t createNormalLayer(const sp<Client>& client, const String8& name,
342             uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
343             sp<IBinder>* outHandle, sp<IGraphicBufferProducer>* outGbp,
344             sp<Layer>* outLayer);
345
346     status_t createDimLayer(const sp<Client>& client, const String8& name,
347             uint32_t w, uint32_t h, uint32_t flags, sp<IBinder>* outHandle,
348             sp<IGraphicBufferProducer>* outGbp, sp<Layer>* outLayer);
349
350     status_t createBlurLayer(const sp<Client>& client, const String8& name,
351             uint32_t w, uint32_t h, uint32_t flags, sp<IBinder>* outHandle,
352             sp<IGraphicBufferProducer>* outGbp, sp<Layer>* outLayer);
353
354     // called in response to the window-manager calling
355     // ISurfaceComposerClient::destroySurface()
356     status_t onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle);
357
358     // called when all clients have released all their references to
359     // this layer meaning it is entirely safe to destroy all
360     // resources associated to this layer.
361     status_t onLayerDestroyed(const wp<Layer>& layer);
362
363     // remove a layer from SurfaceFlinger immediately
364     status_t removeLayer(const sp<Layer>& layer);
365
366     // add a layer to SurfaceFlinger
367     status_t addClientLayer(const sp<Client>& client,
368             const sp<IBinder>& handle,
369             const sp<IGraphicBufferProducer>& gbc,
370             const sp<Layer>& lbc);
371
372     /* ------------------------------------------------------------------------
373      * Boot animation, on/off animations and screen capture
374      */
375
376     void startBootAnim();
377
378     void renderScreenImplLocked(
379             const sp<const DisplayDevice>& hw,
380             Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
381             uint32_t minLayerZ, uint32_t maxLayerZ,
382             bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation);
383
384     status_t captureScreenImplLocked(
385             const sp<const DisplayDevice>& hw,
386             const sp<IGraphicBufferProducer>& producer,
387             Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
388             uint32_t minLayerZ, uint32_t maxLayerZ,
389             bool useIdentityTransform, Transform::orientation_flags rotation,
390             bool useReadPixels);
391
392     /* ------------------------------------------------------------------------
393      * EGL
394      */
395     size_t getMaxTextureSize() const;
396     size_t getMaxViewportDims() const;
397
398     /* ------------------------------------------------------------------------
399      * Display and layer stack management
400      */
401     // called when starting, or restarting after system_server death
402     void initializeDisplays();
403
404     // Create an IBinder for a builtin display and add it to current state
405     void createBuiltinDisplayLocked(DisplayDevice::DisplayType type);
406
407     // NOTE: can only be called from the main thread or with mStateLock held
408     sp<const DisplayDevice> getDisplayDevice(const wp<IBinder>& dpy) const {
409         return mDisplays.valueFor(dpy);
410     }
411
412     // NOTE: can only be called from the main thread or with mStateLock held
413     sp<DisplayDevice> getDisplayDevice(const wp<IBinder>& dpy) {
414         return mDisplays.valueFor(dpy);
415     }
416
417     // mark a region of a layer stack dirty. this updates the dirty
418     // region of all screens presenting this layer stack.
419     void invalidateLayerStack(uint32_t layerStack, const Region& dirty);
420
421     // allocate a h/w composer display id
422     int32_t allocateHwcDisplayId(DisplayDevice::DisplayType type);
423
424     /* ------------------------------------------------------------------------
425      * H/W composer
426      */
427
428     HWComposer& getHwComposer() const { return *mHwc; }
429
430     /* ------------------------------------------------------------------------
431      * Compositing
432      */
433     void invalidateHwcGeometry();
434     void computeVisibleRegions(size_t dpy,
435             const LayerVector& currentLayers, uint32_t layerStack,
436             Region& dirtyRegion, Region& opaqueRegion);
437
438     void preComposition();
439     void postComposition();
440     void rebuildLayerStacks();
441     void setUpHWComposer();
442     void doComposition();
443     void doDebugFlashRegions();
444     void doDisplayComposition(const sp<const DisplayDevice>& hw, const Region& dirtyRegion);
445
446     // compose surfaces for display hw. this fails if using GL and the surface
447     // has been destroyed and is no longer valid.
448     bool doComposeSurfaces(const sp<const DisplayDevice>& hw, const Region& dirty);
449
450     void postFramebuffer();
451     void drawWormhole(const sp<const DisplayDevice>& hw, const Region& region) const;
452
453     /* ------------------------------------------------------------------------
454      * Display management
455      */
456
457     /* ------------------------------------------------------------------------
458      * VSync
459      */
460      void enableHardwareVsync();
461      void disableHardwareVsync(bool makeUnavailable);
462      void resyncToHardwareVsync(bool makeAvailable);
463
464     /* ------------------------------------------------------------------------
465      * Debugging & dumpsys
466      */
467     void listLayersLocked(const Vector<String16>& args, size_t& index, String8& result) const;
468     void dumpStatsLocked(const Vector<String16>& args, size_t& index, String8& result) const;
469     void clearStatsLocked(const Vector<String16>& args, size_t& index, String8& result);
470     void dumpAllLocked(const Vector<String16>& args, size_t& index, String8& result) const;
471     bool startDdmConnection();
472     static void appendSfConfigString(String8& result);
473     void checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
474             const sp<const DisplayDevice>& hw,
475             uint32_t minLayerZ, uint32_t maxLayerZ);
476
477     void logFrameStats();
478
479     void dumpStaticScreenStats(String8& result) const;
480     virtual void dumpDrawCycle(bool /* prePrepare */ ) { }
481
482     /* ------------------------------------------------------------------------
483      * Attributes
484      */
485
486     // access must be protected by mStateLock
487     mutable Mutex mStateLock;
488     State mCurrentState;
489     volatile int32_t mTransactionFlags;
490     Condition mTransactionCV;
491     bool mTransactionPending;
492     bool mAnimTransactionPending;
493     Vector< sp<Layer> > mLayersPendingRemoval;
494     SortedVector< wp<IBinder> > mGraphicBufferProducerList;
495
496     // protected by mStateLock (but we could use another lock)
497     bool mLayersRemoved;
498
499     // access must be protected by mInvalidateLock
500     volatile int32_t mRepaintEverything;
501
502     // constant members (no synchronization needed for access)
503     HWComposer* mHwc;
504     RenderEngine* mRenderEngine;
505     nsecs_t mBootTime;
506     bool mGpuToCpuSupported;
507     bool mDropMissedFrames;
508     sp<EventThread> mEventThread;
509     sp<EventThread> mSFEventThread;
510     sp<EventControlThread> mEventControlThread;
511     EGLContext mEGLContext;
512     EGLDisplay mEGLDisplay;
513     sp<IBinder> mBuiltinDisplays[DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES];
514
515     // Can only accessed from the main thread, these members
516     // don't need synchronization
517     State mDrawingState;
518     bool mVisibleRegionsDirty;
519     bool mHwWorkListDirty;
520     bool mAnimCompositionPending;
521
522     // this may only be written from the main thread with mStateLock held
523     // it may be read from other threads with mStateLock held
524     DefaultKeyedVector< wp<IBinder>, sp<DisplayDevice> > mDisplays;
525
526     // don't use a lock for these, we don't care
527     int mDebugRegion;
528     int mDebugDDMS;
529     int mDebugDisableHWC;
530     int mDebugDisableTransformHint;
531     volatile nsecs_t mDebugInSwapBuffers;
532     nsecs_t mLastSwapBufferTime;
533     volatile nsecs_t mDebugInTransaction;
534     nsecs_t mLastTransactionTime;
535     bool mBootFinished;
536     bool mForceFullDamage;
537
538     // these are thread safe
539     mutable MessageQueue mEventQueue;
540     FrameTracker mAnimFrameTracker;
541     DispSync mPrimaryDispSync;
542
543     // protected by mDestroyedLayerLock;
544     mutable Mutex mDestroyedLayerLock;
545     Vector<Layer const *> mDestroyedLayers;
546
547     // protected by mHWVsyncLock
548     Mutex mHWVsyncLock;
549     bool mPrimaryHWVsyncEnabled;
550     bool mHWVsyncAvailable;
551
552     /* ------------------------------------------------------------------------
553      * Feature prototyping
554      */
555
556     Daltonizer mDaltonizer;
557     bool mDaltonize;
558
559     mat4 mColorMatrix;
560     bool mHasColorMatrix;
561
562     mat4 mSecondaryColorMatrix;
563     bool mHasSecondaryColorMatrix;
564
565     // Static screen stats
566     bool mHasPoweredOff;
567     static const size_t NUM_BUCKETS = 8; // < 1-7, 7+
568     nsecs_t mFrameBuckets[NUM_BUCKETS];
569     nsecs_t mTotalTime;
570     nsecs_t mLastSwapTime;
571
572     FrameRateHelper mFrameRateHelper;
573
574     /*
575      * A number that increases on every new frame composition and screen capture.
576      * LayerBlur can speed up it's drawing by caching texture using this variable
577      * if multiple LayerBlur objects draw in one frame composition.
578      * In case of display mirroring, this variable should be increased on every display.
579      */
580     uint32_t mActiveFrameSequence;
581
582 };
583
584 }; // namespace android
585
586 #endif // ANDROID_SURFACE_FLINGER_H