OSDN Git Service

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