OSDN Git Service

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