OSDN Git Service

SurfaceFlinger: Set property in StartPropertySetThread during init
[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 <memory>
21 #include <stdint.h>
22 #include <sys/types.h>
23
24 #include <EGL/egl.h>
25
26 /*
27  * NOTE: Make sure this file doesn't include  anything from <gl/ > or <gl2/ >
28  */
29
30 #include <cutils/compiler.h>
31
32 #include <utils/Atomic.h>
33 #include <utils/Errors.h>
34 #include <utils/KeyedVector.h>
35 #include <utils/RefBase.h>
36 #include <utils/SortedVector.h>
37 #include <utils/threads.h>
38
39 #include <ui/FenceTime.h>
40 #include <ui/PixelFormat.h>
41 #include <math/mat4.h>
42
43 #include <gui/FrameTimestamps.h>
44 #include <gui/ISurfaceComposer.h>
45 #include <gui/ISurfaceComposerClient.h>
46 #include <gui/OccupancyTracker.h>
47
48 #include <hardware/hwcomposer_defs.h>
49
50 #include <system/graphics.h>
51
52 #include <private/gui/LayerState.h>
53
54 #include "Barrier.h"
55 #include "DisplayDevice.h"
56 #include "DispSync.h"
57 #include "FrameTracker.h"
58 #include "LayerVector.h"
59 #include "MessageQueue.h"
60 #include "SurfaceInterceptor.h"
61 #include "StartPropertySetThread.h"
62
63 #include "DisplayHardware/HWComposer.h"
64 #include "Effects/Daltonizer.h"
65
66 #include <map>
67 #include <mutex>
68 #include <queue>
69 #include <string>
70 #include <utility>
71
72 namespace android {
73
74 // ---------------------------------------------------------------------------
75
76 class Client;
77 class DisplayEventConnection;
78 class EventThread;
79 class Layer;
80 class LayerDim;
81 class Surface;
82 class RenderEngine;
83 class EventControlThread;
84 class VSyncSource;
85 class InjectVSyncSource;
86
87 namespace dvr {
88 class VrFlinger;
89 } // namespace dvr
90
91 // ---------------------------------------------------------------------------
92
93 enum {
94     eTransactionNeeded        = 0x01,
95     eTraversalNeeded          = 0x02,
96     eDisplayTransactionNeeded = 0x04,
97     eTransactionMask          = 0x07
98 };
99
100 class SurfaceFlinger : public BnSurfaceComposer,
101                        private IBinder::DeathRecipient,
102                        private HWComposer::EventHandler
103 {
104 public:
105
106     // This is the phase offset in nanoseconds of the software vsync event
107     // relative to the vsync event reported by HWComposer.  The software vsync
108     // event is when SurfaceFlinger and Choreographer-based applications run each
109     // frame.
110     //
111     // This phase offset allows adjustment of the minimum latency from application
112     // wake-up time (by Choreographer) to the time at which the resulting window
113     // image is displayed.  This value may be either positive (after the HW vsync)
114     // or negative (before the HW vsync). Setting it to 0 will result in a lower
115     // latency bound of two vsync periods because the app and SurfaceFlinger
116     // will run just after the HW vsync.  Setting it to a positive number will
117     // result in the minimum latency being:
118     //
119     //     (2 * VSYNC_PERIOD - (vsyncPhaseOffsetNs % VSYNC_PERIOD))
120     //
121     // Note that reducing this latency makes it more likely for the applications
122     // to not have their window content image ready in time.  When this happens
123     // the latency will end up being an additional vsync period, and animations
124     // will hiccup.  Therefore, this latency should be tuned somewhat
125     // conservatively (or at least with awareness of the trade-off being made).
126     static int64_t vsyncPhaseOffsetNs;
127     static int64_t sfVsyncPhaseOffsetNs;
128
129     // If fences from sync Framework are supported.
130     static bool hasSyncFramework;
131
132     // Instruct the Render Engine to use EGL_IMG_context_priority is available.
133     static bool useContextPriority;
134
135     // The offset in nanoseconds to use when DispSync timestamps present fence
136     // signaling time.
137     static int64_t dispSyncPresentTimeOffset;
138
139     // Some hardware can do RGB->YUV conversion more efficiently in hardware
140     // controlled by HWC than in hardware controlled by the video encoder.
141     // This instruct VirtualDisplaySurface to use HWC for such conversion on
142     // GL composition.
143     static bool useHwcForRgbToYuv;
144
145     // Maximum dimension supported by HWC for virtual display.
146     // Equal to min(max_height, max_width).
147     static uint64_t maxVirtualDisplaySize;
148
149     // Controls the number of buffers SurfaceFlinger will allocate for use in
150     // FramebufferSurface
151     static int64_t maxFrameBufferAcquiredBuffers;
152
153     // Indicate if platform supports color management on its
154     // wide-color display. This is typically found on devices
155     // with wide gamut (e.g. Display-P3) display.
156     // This also allows devices with wide-color displays that don't
157     // want to support color management to disable color management.
158     static bool hasWideColorDisplay;
159
160     static char const* getServiceName() ANDROID_API {
161         return "SurfaceFlinger";
162     }
163
164     SurfaceFlinger() ANDROID_API;
165
166     // must be called before clients can connect
167     void init() ANDROID_API;
168
169     // starts SurfaceFlinger main loop in the current thread
170     void run() ANDROID_API;
171
172     enum {
173         EVENT_VSYNC = HWC_EVENT_VSYNC
174     };
175
176     // post an asynchronous message to the main thread
177     status_t postMessageAsync(const sp<MessageBase>& msg, nsecs_t reltime = 0, uint32_t flags = 0);
178
179     // post a synchronous message to the main thread
180     status_t postMessageSync(const sp<MessageBase>& msg, nsecs_t reltime = 0, uint32_t flags = 0);
181
182     // force full composition on all displays
183     void repaintEverything();
184
185     // returns the default Display
186     sp<const DisplayDevice> getDefaultDisplayDevice() const {
187         Mutex::Autolock _l(mStateLock);
188         return getDefaultDisplayDeviceLocked();
189     }
190
191     // utility function to delete a texture on the main thread
192     void deleteTextureAsync(uint32_t texture);
193
194     // enable/disable h/w composer event
195     // TODO: this should be made accessible only to EventThread
196 #ifdef USE_HWC2
197     void setVsyncEnabled(int disp, int enabled);
198 #else
199     void eventControl(int disp, int event, int enabled);
200 #endif
201
202     // called on the main thread by MessageQueue when an internal message
203     // is received
204     // TODO: this should be made accessible only to MessageQueue
205     void onMessageReceived(int32_t what);
206
207     // for debugging only
208     // TODO: this should be made accessible only to HWComposer
209     const Vector< sp<Layer> >& getLayerSortedByZForHwcDisplay(int id);
210
211     RenderEngine& getRenderEngine() const {
212         return *mRenderEngine;
213     }
214
215     bool authenticateSurfaceTextureLocked(
216         const sp<IGraphicBufferProducer>& bufferProducer) const;
217
218 private:
219     friend class Client;
220     friend class DisplayEventConnection;
221     friend class EventThread;
222     friend class Layer;
223     friend class MonitoredProducer;
224
225     // This value is specified in number of frames.  Log frame stats at most
226     // every half hour.
227     enum { LOG_FRAME_STATS_PERIOD =  30*60*60 };
228
229     static const size_t MAX_LAYERS = 4096;
230
231     // We're reference counted, never destroy SurfaceFlinger directly
232     virtual ~SurfaceFlinger();
233
234     /* ------------------------------------------------------------------------
235      * Internal data structures
236      */
237
238     class State {
239     public:
240         explicit State(LayerVector::StateSet set) : stateSet(set) {}
241         State& operator=(const State& other) {
242             // We explicitly don't copy stateSet so that, e.g., mDrawingState
243             // always uses the Drawing StateSet.
244             layersSortedByZ = other.layersSortedByZ;
245             displays = other.displays;
246             return *this;
247         }
248
249         const LayerVector::StateSet stateSet = LayerVector::StateSet::Invalid;
250         LayerVector layersSortedByZ;
251         DefaultKeyedVector< wp<IBinder>, DisplayDeviceState> displays;
252
253         void traverseInZOrder(const LayerVector::Visitor& visitor) const;
254         void traverseInReverseZOrder(const LayerVector::Visitor& visitor) const;
255     };
256
257     /* ------------------------------------------------------------------------
258      * IBinder interface
259      */
260     virtual status_t onTransact(uint32_t code, const Parcel& data,
261         Parcel* reply, uint32_t flags);
262     virtual status_t dump(int fd, const Vector<String16>& args);
263
264     /* ------------------------------------------------------------------------
265      * ISurfaceComposer interface
266      */
267     virtual sp<ISurfaceComposerClient> createConnection();
268     virtual sp<ISurfaceComposerClient> createScopedConnection(const sp<IGraphicBufferProducer>& gbp);
269     virtual sp<IBinder> createDisplay(const String8& displayName, bool secure);
270     virtual void destroyDisplay(const sp<IBinder>& display);
271     virtual sp<IBinder> getBuiltInDisplay(int32_t id);
272     virtual void setTransactionState(const Vector<ComposerState>& state,
273             const Vector<DisplayState>& displays, uint32_t flags);
274     virtual void bootFinished();
275     virtual bool authenticateSurfaceTexture(
276         const sp<IGraphicBufferProducer>& bufferProducer) const;
277     virtual status_t getSupportedFrameTimestamps(
278             std::vector<FrameEvent>* outSupported) const;
279     virtual sp<IDisplayEventConnection> createDisplayEventConnection(
280             ISurfaceComposer::VsyncSource vsyncSource = eVsyncSourceApp);
281     virtual status_t captureScreen(const sp<IBinder>& display,
282             const sp<IGraphicBufferProducer>& producer,
283             Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
284             int32_t minLayerZ, int32_t maxLayerZ,
285             bool useIdentityTransform, ISurfaceComposer::Rotation rotation);
286     virtual status_t getDisplayStats(const sp<IBinder>& display,
287             DisplayStatInfo* stats);
288     virtual status_t getDisplayConfigs(const sp<IBinder>& display,
289             Vector<DisplayInfo>* configs);
290     virtual int getActiveConfig(const sp<IBinder>& display);
291     virtual status_t getDisplayColorModes(const sp<IBinder>& display,
292             Vector<android_color_mode_t>* configs);
293     virtual android_color_mode_t getActiveColorMode(const sp<IBinder>& display);
294     virtual status_t setActiveColorMode(const sp<IBinder>& display, android_color_mode_t colorMode);
295     virtual void setPowerMode(const sp<IBinder>& display, int mode);
296     virtual status_t setActiveConfig(const sp<IBinder>& display, int id);
297     virtual status_t clearAnimationFrameStats();
298     virtual status_t getAnimationFrameStats(FrameStats* outStats) const;
299     virtual status_t getHdrCapabilities(const sp<IBinder>& display,
300             HdrCapabilities* outCapabilities) const;
301     virtual status_t enableVSyncInjections(bool enable);
302     virtual status_t injectVSync(nsecs_t when);
303
304
305     /* ------------------------------------------------------------------------
306      * DeathRecipient interface
307      */
308     virtual void binderDied(const wp<IBinder>& who);
309
310     /* ------------------------------------------------------------------------
311      * RefBase interface
312      */
313     virtual void onFirstRef();
314
315     /* ------------------------------------------------------------------------
316      * HWComposer::EventHandler interface
317      */
318     virtual void onVSyncReceived(HWComposer* composer, int type, nsecs_t timestamp);
319     virtual void onHotplugReceived(HWComposer* composer, int disp, bool connected);
320     virtual void onInvalidateReceived(HWComposer* composer);
321
322     /* ------------------------------------------------------------------------
323      * Message handling
324      */
325     void waitForEvent();
326     void signalTransaction();
327     void signalLayerUpdate();
328     void signalRefresh();
329
330     // called on the main thread in response to initializeDisplays()
331     void onInitializeDisplays();
332     // called on the main thread in response to setActiveConfig()
333     void setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode);
334     // called on the main thread in response to setPowerMode()
335     void setPowerModeInternal(const sp<DisplayDevice>& hw, int mode);
336
337     // Called on the main thread in response to setActiveColorMode()
338     void setActiveColorModeInternal(const sp<DisplayDevice>& hw, android_color_mode_t colorMode);
339
340     // Returns whether the transaction actually modified any state
341     bool handleMessageTransaction();
342
343     // Returns whether a new buffer has been latched (see handlePageFlip())
344     bool handleMessageInvalidate();
345
346     void handleMessageRefresh();
347
348     void handleTransaction(uint32_t transactionFlags);
349     void handleTransactionLocked(uint32_t transactionFlags);
350
351     void updateCursorAsync();
352
353     /* handlePageFlip - latch a new buffer if available and compute the dirty
354      * region. Returns whether a new buffer has been latched, i.e., whether it
355      * is necessary to perform a refresh during this vsync.
356      */
357     bool handlePageFlip();
358
359     /* ------------------------------------------------------------------------
360      * Transactions
361      */
362     uint32_t getTransactionFlags(uint32_t flags);
363     uint32_t peekTransactionFlags();
364     uint32_t setTransactionFlags(uint32_t flags);
365     void commitTransaction();
366     uint32_t setClientStateLocked(const sp<Client>& client, const layer_state_t& s);
367     uint32_t setDisplayStateLocked(const DisplayState& s);
368
369     /* ------------------------------------------------------------------------
370      * Layer management
371      */
372     status_t createLayer(const String8& name, const sp<Client>& client,
373             uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
374             uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
375             sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent);
376
377     status_t createNormalLayer(const sp<Client>& client, const String8& name,
378             uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
379             sp<IBinder>* outHandle, sp<IGraphicBufferProducer>* outGbp,
380             sp<Layer>* outLayer);
381
382     status_t createDimLayer(const sp<Client>& client, const String8& name,
383             uint32_t w, uint32_t h, uint32_t flags, sp<IBinder>* outHandle,
384             sp<IGraphicBufferProducer>* outGbp, sp<Layer>* outLayer);
385
386     String8 getUniqueLayerName(const String8& name);
387
388     // called in response to the window-manager calling
389     // ISurfaceComposerClient::destroySurface()
390     status_t onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle);
391
392     // called when all clients have released all their references to
393     // this layer meaning it is entirely safe to destroy all
394     // resources associated to this layer.
395     status_t onLayerDestroyed(const wp<Layer>& layer);
396
397     // remove a layer from SurfaceFlinger immediately
398     status_t removeLayer(const sp<Layer>& layer, bool topLevelOnly = false);
399
400     // add a layer to SurfaceFlinger
401     status_t addClientLayer(const sp<Client>& client,
402             const sp<IBinder>& handle,
403             const sp<IGraphicBufferProducer>& gbc,
404             const sp<Layer>& lbc,
405             const sp<Layer>& parent);
406
407     /* ------------------------------------------------------------------------
408      * Boot animation, on/off animations and screen capture
409      */
410
411     void startBootAnim();
412
413     void renderScreenImplLocked(
414             const sp<const DisplayDevice>& hw,
415             Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
416             int32_t minLayerZ, int32_t maxLayerZ,
417             bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation);
418
419 #ifdef USE_HWC2
420     status_t captureScreenImplLocked(const sp<const DisplayDevice>& device,
421                                      ANativeWindowBuffer* buffer, Rect sourceCrop,
422                                      uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
423                                      int32_t maxLayerZ, bool useIdentityTransform,
424                                      Transform::orientation_flags rotation, bool isLocalScreenshot,
425                                      int* outSyncFd);
426 #else
427     status_t captureScreenImplLocked(
428             const sp<const DisplayDevice>& hw,
429             const sp<IGraphicBufferProducer>& producer,
430             Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
431             int32_t minLayerZ, int32_t maxLayerZ,
432             bool useIdentityTransform, Transform::orientation_flags rotation,
433             bool isLocalScreenshot);
434 #endif
435
436     sp<StartPropertySetThread> mStartPropertySetThread = nullptr;
437
438     /* ------------------------------------------------------------------------
439      * EGL
440      */
441     size_t getMaxTextureSize() const;
442     size_t getMaxViewportDims() const;
443
444     /* ------------------------------------------------------------------------
445      * Display and layer stack management
446      */
447     // called when starting, or restarting after system_server death
448     void initializeDisplays();
449
450     // Create an IBinder for a builtin display and add it to current state
451     void createBuiltinDisplayLocked(DisplayDevice::DisplayType type);
452
453
454     sp<const DisplayDevice> getDisplayDevice(const wp<IBinder>& dpy) const {
455       Mutex::Autolock _l(mStateLock);
456       return getDisplayDeviceLocked(dpy);
457     }
458
459     sp<DisplayDevice> getDisplayDevice(const wp<IBinder>& dpy) {
460       Mutex::Autolock _l(mStateLock);
461       return getDisplayDeviceLocked(dpy);
462     }
463
464     // NOTE: can only be called from the main thread or with mStateLock held
465     sp<const DisplayDevice> getDisplayDeviceLocked(const wp<IBinder>& dpy) const {
466         return mDisplays.valueFor(dpy);
467     }
468
469     // NOTE: can only be called from the main thread or with mStateLock held
470     sp<DisplayDevice> getDisplayDeviceLocked(const wp<IBinder>& dpy) {
471         return mDisplays.valueFor(dpy);
472     }
473
474     sp<const DisplayDevice> getDefaultDisplayDeviceLocked() const {
475         return getDisplayDeviceLocked(mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]);
476     }
477
478     void createDefaultDisplayDevice();
479
480     int32_t getDisplayType(const sp<IBinder>& display) {
481         if (!display.get()) return NAME_NOT_FOUND;
482         for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
483             if (display == mBuiltinDisplays[i]) {
484                 return i;
485             }
486         }
487         return NAME_NOT_FOUND;
488     }
489
490     // mark a region of a layer stack dirty. this updates the dirty
491     // region of all screens presenting this layer stack.
492     void invalidateLayerStack(uint32_t layerStack, const Region& dirty);
493
494 #ifndef USE_HWC2
495     int32_t allocateHwcDisplayId(DisplayDevice::DisplayType type);
496 #endif
497
498     /* ------------------------------------------------------------------------
499      * H/W composer
500      */
501
502     HWComposer& getHwComposer() const { return *mHwc; }
503
504     /* ------------------------------------------------------------------------
505      * Compositing
506      */
507     void invalidateHwcGeometry();
508     void computeVisibleRegions(uint32_t layerStack,
509             Region& dirtyRegion, Region& opaqueRegion);
510
511     void preComposition(nsecs_t refreshStartTime);
512     void postComposition(nsecs_t refreshStartTime);
513     void updateCompositorTiming(
514             nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
515             std::shared_ptr<FenceTime>& presentFenceTime);
516     void setCompositorTimingSnapped(
517             nsecs_t vsyncPhase, nsecs_t vsyncInterval,
518             nsecs_t compositeToPresentLatency);
519     void rebuildLayerStacks();
520
521     // Given a dataSpace, returns the appropriate color_mode to use
522     // to display that dataSpace.
523     android_color_mode pickColorMode(android_dataspace dataSpace) const;
524     android_dataspace bestTargetDataSpace(android_dataspace a, android_dataspace b) const;
525
526     mat4 computeSaturationMatrix() const;
527
528     void setUpHWComposer();
529     void doComposition();
530     void doDebugFlashRegions();
531     void doDisplayComposition(const sp<const DisplayDevice>& displayDevice, const Region& dirtyRegion);
532
533     // compose surfaces for display hw. this fails if using GL and the surface
534     // has been destroyed and is no longer valid.
535     bool doComposeSurfaces(const sp<const DisplayDevice>& displayDevice, const Region& dirty);
536
537     void postFramebuffer();
538     void drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const;
539
540     /* ------------------------------------------------------------------------
541      * Display management
542      */
543
544     /* ------------------------------------------------------------------------
545      * VSync
546      */
547     void enableHardwareVsync();
548     void resyncToHardwareVsync(bool makeAvailable);
549     void disableHardwareVsync(bool makeUnavailable);
550
551 public:
552     void resyncWithRateLimit();
553     void getCompositorTiming(CompositorTiming* compositorTiming);
554 private:
555
556     /* ------------------------------------------------------------------------
557      * Debugging & dumpsys
558      */
559     void listLayersLocked(const Vector<String16>& args, size_t& index, String8& result) const;
560     void dumpStatsLocked(const Vector<String16>& args, size_t& index, String8& result) const;
561     void clearStatsLocked(const Vector<String16>& args, size_t& index, String8& result);
562     void dumpAllLocked(const Vector<String16>& args, size_t& index, String8& result) const;
563     bool startDdmConnection();
564     void appendSfConfigString(String8& result) const;
565     void checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
566             const sp<const DisplayDevice>& hw,
567             int32_t minLayerZ, int32_t maxLayerZ);
568
569     void logFrameStats();
570
571     void dumpStaticScreenStats(String8& result) const;
572     // Not const because each Layer needs to query Fences and cache timestamps.
573     void dumpFrameEventsLocked(String8& result);
574
575     void recordBufferingStats(const char* layerName,
576             std::vector<OccupancyTracker::Segment>&& history);
577     void dumpBufferingStats(String8& result) const;
578     void dumpWideColorInfo(String8& result) const;
579
580     bool isLayerTripleBufferingDisabled() const {
581         return this->mLayerTripleBufferingDisabled;
582     }
583
584 #ifdef USE_HWC2
585     /* ------------------------------------------------------------------------
586      * VrFlinger
587      */
588     template<typename T>
589     void clearHwcLayers(const T& layers) {
590         for (size_t i = 0; i < layers.size(); ++i) {
591             layers[i]->clearHwcLayers();
592         }
593     }
594     void resetHwcLocked();
595
596     // Check to see if we should handoff to vr flinger.
597     void updateVrFlinger();
598 #endif
599
600     /* ------------------------------------------------------------------------
601      * Attributes
602      */
603
604     // access must be protected by mStateLock
605     mutable Mutex mStateLock;
606     State mCurrentState{LayerVector::StateSet::Current};
607     volatile int32_t mTransactionFlags;
608     Condition mTransactionCV;
609     bool mTransactionPending;
610     bool mAnimTransactionPending;
611     SortedVector< sp<Layer> > mLayersPendingRemoval;
612     SortedVector< wp<IBinder> > mGraphicBufferProducerList;
613
614     // protected by mStateLock (but we could use another lock)
615     bool mLayersRemoved;
616     bool mLayersAdded;
617
618     // access must be protected by mInvalidateLock
619     volatile int32_t mRepaintEverything;
620
621     // current, real and vr hardware composers.
622     HWComposer* mHwc;
623 #ifdef USE_HWC2
624     HWComposer* mRealHwc;
625     HWComposer* mVrHwc;
626 #endif
627     // constant members (no synchronization needed for access)
628     RenderEngine* mRenderEngine;
629     nsecs_t mBootTime;
630     bool mGpuToCpuSupported;
631     sp<EventThread> mEventThread;
632     sp<EventThread> mSFEventThread;
633     sp<EventThread> mInjectorEventThread;
634     sp<InjectVSyncSource> mVSyncInjector;
635     sp<EventControlThread> mEventControlThread;
636     EGLContext mEGLContext;
637     EGLDisplay mEGLDisplay;
638     sp<IBinder> mBuiltinDisplays[DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES];
639
640 #ifdef USE_HWC2
641     std::unique_ptr<dvr::VrFlinger> mVrFlinger;
642 #endif
643
644     // Can only accessed from the main thread, these members
645     // don't need synchronization
646     State mDrawingState{LayerVector::StateSet::Drawing};
647     bool mVisibleRegionsDirty;
648 #ifndef USE_HWC2
649     bool mHwWorkListDirty;
650 #else
651     bool mGeometryInvalid;
652 #endif
653     bool mAnimCompositionPending;
654 #ifdef USE_HWC2
655     std::vector<sp<Layer>> mLayersWithQueuedFrames;
656     sp<Fence> mPreviousPresentFence = Fence::NO_FENCE;
657     bool mHadClientComposition = false;
658 #endif
659     FenceTimeline mGlCompositionDoneTimeline;
660     FenceTimeline mDisplayTimeline;
661
662     // this may only be written from the main thread with mStateLock held
663     // it may be read from other threads with mStateLock held
664     DefaultKeyedVector< wp<IBinder>, sp<DisplayDevice> > mDisplays;
665
666     // don't use a lock for these, we don't care
667     int mDebugRegion;
668     int mDebugDDMS;
669     int mDebugDisableHWC;
670     int mDebugDisableTransformHint;
671     volatile nsecs_t mDebugInSwapBuffers;
672     nsecs_t mLastSwapBufferTime;
673     volatile nsecs_t mDebugInTransaction;
674     nsecs_t mLastTransactionTime;
675     bool mBootFinished;
676     bool mForceFullDamage;
677 #ifdef USE_HWC2
678     bool mPropagateBackpressure = true;
679 #endif
680     SurfaceInterceptor mInterceptor;
681     bool mUseHwcVirtualDisplays = false;
682
683     // Restrict layers to use two buffers in their bufferqueues.
684     bool mLayerTripleBufferingDisabled = false;
685
686     // these are thread safe
687     mutable MessageQueue mEventQueue;
688     FrameTracker mAnimFrameTracker;
689     DispSync mPrimaryDispSync;
690
691     // protected by mDestroyedLayerLock;
692     mutable Mutex mDestroyedLayerLock;
693     Vector<Layer const *> mDestroyedLayers;
694
695     // protected by mHWVsyncLock
696     Mutex mHWVsyncLock;
697     bool mPrimaryHWVsyncEnabled;
698     bool mHWVsyncAvailable;
699
700     // protected by mCompositorTimingLock;
701     mutable std::mutex mCompositorTimingLock;
702     CompositorTiming mCompositorTiming;
703
704     // Only accessed from the main thread.
705     struct CompositePresentTime {
706         nsecs_t composite { -1 };
707         std::shared_ptr<FenceTime> display { FenceTime::NO_FENCE };
708     };
709     std::queue<CompositePresentTime> mCompositePresentTimes;
710
711     std::atomic<bool> mRefreshPending{false};
712
713     /* ------------------------------------------------------------------------
714      * Feature prototyping
715      */
716
717     bool mInjectVSyncs;
718
719     Daltonizer mDaltonizer;
720 #ifndef USE_HWC2
721     bool mDaltonize;
722 #endif
723
724     mat4 mPreviousColorMatrix;
725     mat4 mColorMatrix;
726     bool mHasColorMatrix;
727
728     // Static screen stats
729     bool mHasPoweredOff;
730     static const size_t NUM_BUCKETS = 8; // < 1-7, 7+
731     nsecs_t mFrameBuckets[NUM_BUCKETS];
732     nsecs_t mTotalTime;
733     std::atomic<nsecs_t> mLastSwapTime;
734
735     size_t mNumLayers;
736
737     // Double- vs. triple-buffering stats
738     struct BufferingStats {
739         BufferingStats()
740           : numSegments(0),
741             totalTime(0),
742             twoBufferTime(0),
743             doubleBufferedTime(0),
744             tripleBufferedTime(0) {}
745
746         size_t numSegments;
747         nsecs_t totalTime;
748
749         // "Two buffer" means that a third buffer was never used, whereas
750         // "double-buffered" means that on average the segment only used two
751         // buffers (though it may have used a third for some part of the
752         // segment)
753         nsecs_t twoBufferTime;
754         nsecs_t doubleBufferedTime;
755         nsecs_t tripleBufferedTime;
756     };
757     mutable Mutex mBufferingStatsMutex;
758     std::unordered_map<std::string, BufferingStats> mBufferingStats;
759
760     // Verify that transaction is being called by an approved process:
761     // either AID_GRAPHICS or AID_SYSTEM.
762     status_t CheckTransactCodeCredentials(uint32_t code);
763
764 #ifdef USE_HWC2
765     std::atomic<bool> mVrFlingerRequestsDisplay;
766     static bool useVrFlinger;
767 #endif
768
769     float mSaturation = 1.0f;
770 };
771 }; // namespace android
772
773 #endif // ANDROID_SURFACE_FLINGER_H