OSDN Git Service

Merge "Clean up handling of VR surface updates." 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     // Can only be called from the main thread or with mStateLock held
196     void repaintEverythingLocked();
197
198     // returns the default Display
199     sp<const DisplayDevice> getDefaultDisplayDevice() const {
200         Mutex::Autolock _l(mStateLock);
201         return getDefaultDisplayDeviceLocked();
202     }
203
204     // utility function to delete a texture on the main thread
205     void deleteTextureAsync(uint32_t texture);
206
207     // enable/disable h/w composer event
208     // TODO: this should be made accessible only to EventThread
209 #ifdef USE_HWC2
210     void setVsyncEnabled(int disp, int enabled);
211 #else
212     void eventControl(int disp, int event, int enabled);
213 #endif
214
215     // called on the main thread by MessageQueue when an internal message
216     // is received
217     // TODO: this should be made accessible only to MessageQueue
218     void onMessageReceived(int32_t what);
219
220     // for debugging only
221     // TODO: this should be made accessible only to HWComposer
222     const Vector< sp<Layer> >& getLayerSortedByZForHwcDisplay(int id);
223
224     RenderEngine& getRenderEngine() const {
225         return *mRenderEngine;
226     }
227
228     bool authenticateSurfaceTextureLocked(
229         const sp<IGraphicBufferProducer>& bufferProducer) const;
230
231 private:
232     friend class Client;
233     friend class DisplayEventConnection;
234     friend class EventThread;
235     friend class Layer;
236     friend class MonitoredProducer;
237
238     // This value is specified in number of frames.  Log frame stats at most
239     // every half hour.
240     enum { LOG_FRAME_STATS_PERIOD =  30*60*60 };
241
242     static const size_t MAX_LAYERS = 4096;
243
244     // We're reference counted, never destroy SurfaceFlinger directly
245     virtual ~SurfaceFlinger();
246
247     /* ------------------------------------------------------------------------
248      * Internal data structures
249      */
250
251     class State {
252     public:
253         explicit State(LayerVector::StateSet set) : stateSet(set) {}
254         State& operator=(const State& other) {
255             // We explicitly don't copy stateSet so that, e.g., mDrawingState
256             // always uses the Drawing StateSet.
257             layersSortedByZ = other.layersSortedByZ;
258             displays = other.displays;
259             return *this;
260         }
261
262         const LayerVector::StateSet stateSet = LayerVector::StateSet::Invalid;
263         LayerVector layersSortedByZ;
264         DefaultKeyedVector< wp<IBinder>, DisplayDeviceState> displays;
265
266         void traverseInZOrder(const LayerVector::Visitor& visitor) const;
267         void traverseInReverseZOrder(const LayerVector::Visitor& visitor) const;
268     };
269
270     /* ------------------------------------------------------------------------
271      * IBinder interface
272      */
273     virtual status_t onTransact(uint32_t code, const Parcel& data,
274         Parcel* reply, uint32_t flags);
275     virtual status_t dump(int fd, const Vector<String16>& args);
276
277     /* ------------------------------------------------------------------------
278      * ISurfaceComposer interface
279      */
280     virtual sp<ISurfaceComposerClient> createConnection();
281     virtual sp<ISurfaceComposerClient> createScopedConnection(const sp<IGraphicBufferProducer>& gbp);
282     virtual sp<IBinder> createDisplay(const String8& displayName, bool secure);
283     virtual void destroyDisplay(const sp<IBinder>& display);
284     virtual sp<IBinder> getBuiltInDisplay(int32_t id);
285     virtual void setTransactionState(const Vector<ComposerState>& state,
286             const Vector<DisplayState>& displays, uint32_t flags);
287     virtual void bootFinished();
288     virtual bool authenticateSurfaceTexture(
289         const sp<IGraphicBufferProducer>& bufferProducer) const;
290     virtual status_t getSupportedFrameTimestamps(
291             std::vector<FrameEvent>* outSupported) const;
292     virtual sp<IDisplayEventConnection> createDisplayEventConnection(
293             ISurfaceComposer::VsyncSource vsyncSource = eVsyncSourceApp);
294     virtual status_t captureScreen(const sp<IBinder>& display,
295             const sp<IGraphicBufferProducer>& producer,
296             Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
297             int32_t minLayerZ, int32_t maxLayerZ,
298             bool useIdentityTransform, ISurfaceComposer::Rotation rotation);
299     virtual status_t getDisplayStats(const sp<IBinder>& display,
300             DisplayStatInfo* stats);
301     virtual status_t getDisplayConfigs(const sp<IBinder>& display,
302             Vector<DisplayInfo>* configs);
303     virtual int getActiveConfig(const sp<IBinder>& display);
304     virtual status_t getDisplayColorModes(const sp<IBinder>& display,
305             Vector<android_color_mode_t>* configs);
306     virtual android_color_mode_t getActiveColorMode(const sp<IBinder>& display);
307     virtual status_t setActiveColorMode(const sp<IBinder>& display, android_color_mode_t colorMode);
308     virtual void setPowerMode(const sp<IBinder>& display, int mode);
309     virtual status_t setActiveConfig(const sp<IBinder>& display, int id);
310     virtual status_t clearAnimationFrameStats();
311     virtual status_t getAnimationFrameStats(FrameStats* outStats) const;
312     virtual status_t getHdrCapabilities(const sp<IBinder>& display,
313             HdrCapabilities* outCapabilities) const;
314     virtual status_t enableVSyncInjections(bool enable);
315     virtual status_t injectVSync(nsecs_t when);
316
317
318     /* ------------------------------------------------------------------------
319      * DeathRecipient interface
320      */
321     virtual void binderDied(const wp<IBinder>& who);
322
323     /* ------------------------------------------------------------------------
324      * RefBase interface
325      */
326     virtual void onFirstRef();
327
328     /* ------------------------------------------------------------------------
329      * HWC2::ComposerCallback / HWComposer::EventHandler interface
330      */
331 #ifdef USE_HWC2
332     void onVsyncReceived(int32_t sequenceId, hwc2_display_t display,
333                          int64_t timestamp) override;
334     void onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
335                            HWC2::Connection connection,
336                            bool primaryDisplay) override;
337     void onRefreshReceived(int32_t sequenceId, hwc2_display_t display) override;
338 #else
339     void onVSyncReceived(HWComposer* composer, int type, nsecs_t timestamp) override;
340     void onHotplugReceived(HWComposer* composer, int disp, bool connected) override;
341     void onInvalidateReceived(HWComposer* composer) override;
342 #endif
343
344     /* ------------------------------------------------------------------------
345      * Message handling
346      */
347     void waitForEvent();
348     // Can only be called from the main thread or with mStateLock held
349     void signalTransaction();
350     // Can only be called from the main thread or with mStateLock held
351     void signalLayerUpdate();
352     void signalRefresh();
353
354     // called on the main thread in response to initializeDisplays()
355     void onInitializeDisplays();
356     // called on the main thread in response to setActiveConfig()
357     void setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode);
358     // called on the main thread in response to setPowerMode()
359 #ifdef USE_HWC2
360     void setPowerModeInternal(const sp<DisplayDevice>& hw, int mode,
361                               bool stateLockHeld);
362 #else
363     void setPowerModeInternal(const sp<DisplayDevice>& hw, int mode);
364 #endif
365
366     // Called on the main thread in response to setActiveColorMode()
367     void setActiveColorModeInternal(const sp<DisplayDevice>& hw, android_color_mode_t colorMode);
368
369     // Returns whether the transaction actually modified any state
370     bool handleMessageTransaction();
371
372     // Returns whether a new buffer has been latched (see handlePageFlip())
373     bool handleMessageInvalidate();
374
375     void handleMessageRefresh();
376
377     void handleTransaction(uint32_t transactionFlags);
378     void handleTransactionLocked(uint32_t transactionFlags);
379
380     void updateCursorAsync();
381
382     /* handlePageFlip - latch a new buffer if available and compute the dirty
383      * region. Returns whether a new buffer has been latched, i.e., whether it
384      * is necessary to perform a refresh during this vsync.
385      */
386     bool handlePageFlip();
387
388     /* ------------------------------------------------------------------------
389      * Transactions
390      */
391     uint32_t getTransactionFlags(uint32_t flags);
392     uint32_t peekTransactionFlags();
393     // Can only be called from the main thread or with mStateLock held
394     uint32_t setTransactionFlags(uint32_t flags);
395     void commitTransaction();
396     uint32_t setClientStateLocked(const sp<Client>& client, const layer_state_t& s);
397     uint32_t setDisplayStateLocked(const DisplayState& s);
398
399     /* ------------------------------------------------------------------------
400      * Layer management
401      */
402     status_t createLayer(const String8& name, const sp<Client>& client,
403             uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
404             uint32_t windowType, uint32_t ownerUid, sp<IBinder>* handle,
405             sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent);
406
407     status_t createNormalLayer(const sp<Client>& client, const String8& name,
408             uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
409             sp<IBinder>* outHandle, sp<IGraphicBufferProducer>* outGbp,
410             sp<Layer>* outLayer);
411
412     status_t createDimLayer(const sp<Client>& client, const String8& name,
413             uint32_t w, uint32_t h, uint32_t flags, sp<IBinder>* outHandle,
414             sp<IGraphicBufferProducer>* outGbp, sp<Layer>* outLayer);
415
416     String8 getUniqueLayerName(const String8& name);
417
418     // called in response to the window-manager calling
419     // ISurfaceComposerClient::destroySurface()
420     status_t onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle);
421
422     // called when all clients have released all their references to
423     // this layer meaning it is entirely safe to destroy all
424     // resources associated to this layer.
425     status_t onLayerDestroyed(const wp<Layer>& layer);
426
427     // remove a layer from SurfaceFlinger immediately
428     status_t removeLayer(const sp<Layer>& layer, bool topLevelOnly = false);
429
430     // add a layer to SurfaceFlinger
431     status_t addClientLayer(const sp<Client>& client,
432             const sp<IBinder>& handle,
433             const sp<IGraphicBufferProducer>& gbc,
434             const sp<Layer>& lbc,
435             const sp<Layer>& parent);
436
437     /* ------------------------------------------------------------------------
438      * Boot animation, on/off animations and screen capture
439      */
440
441     void startBootAnim();
442
443     void renderScreenImplLocked(
444             const sp<const DisplayDevice>& hw,
445             Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
446             int32_t minLayerZ, int32_t maxLayerZ,
447             bool yswap, bool useIdentityTransform, Transform::orientation_flags rotation);
448
449 #ifdef USE_HWC2
450     status_t captureScreenImplLocked(const sp<const DisplayDevice>& device,
451                                      ANativeWindowBuffer* buffer, Rect sourceCrop,
452                                      uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
453                                      int32_t maxLayerZ, bool useIdentityTransform,
454                                      Transform::orientation_flags rotation, bool isLocalScreenshot,
455                                      int* outSyncFd);
456 #else
457     status_t captureScreenImplLocked(
458             const sp<const DisplayDevice>& hw,
459             const sp<IGraphicBufferProducer>& producer,
460             Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
461             int32_t minLayerZ, int32_t maxLayerZ,
462             bool useIdentityTransform, Transform::orientation_flags rotation,
463             bool isLocalScreenshot);
464 #endif
465
466     sp<StartPropertySetThread> mStartPropertySetThread = nullptr;
467
468     /* ------------------------------------------------------------------------
469      * Properties
470      */
471     void readPersistentProperties();
472
473     /* ------------------------------------------------------------------------
474      * EGL
475      */
476     size_t getMaxTextureSize() const;
477     size_t getMaxViewportDims() const;
478
479     /* ------------------------------------------------------------------------
480      * Display and layer stack management
481      */
482     // called when starting, or restarting after system_server death
483     void initializeDisplays();
484
485     // Create an IBinder for a builtin display and add it to current state
486     void createBuiltinDisplayLocked(DisplayDevice::DisplayType type);
487
488
489     sp<const DisplayDevice> getDisplayDevice(const wp<IBinder>& dpy) const {
490       Mutex::Autolock _l(mStateLock);
491       return getDisplayDeviceLocked(dpy);
492     }
493
494     sp<DisplayDevice> getDisplayDevice(const wp<IBinder>& dpy) {
495       Mutex::Autolock _l(mStateLock);
496       return getDisplayDeviceLocked(dpy);
497     }
498
499     // NOTE: can only be called from the main thread or with mStateLock held
500     sp<const DisplayDevice> getDisplayDeviceLocked(const wp<IBinder>& dpy) const {
501         return mDisplays.valueFor(dpy);
502     }
503
504     // NOTE: can only be called from the main thread or with mStateLock held
505     sp<DisplayDevice> getDisplayDeviceLocked(const wp<IBinder>& dpy) {
506         return mDisplays.valueFor(dpy);
507     }
508
509     sp<const DisplayDevice> getDefaultDisplayDeviceLocked() const {
510         return getDisplayDeviceLocked(mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]);
511     }
512
513     void createDefaultDisplayDevice();
514
515     int32_t getDisplayType(const sp<IBinder>& display) {
516         if (!display.get()) return NAME_NOT_FOUND;
517         for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
518             if (display == mBuiltinDisplays[i]) {
519                 return i;
520             }
521         }
522         return NAME_NOT_FOUND;
523     }
524
525     // mark a region of a layer stack dirty. this updates the dirty
526     // region of all screens presenting this layer stack.
527     void invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty);
528
529 #ifndef USE_HWC2
530     int32_t allocateHwcDisplayId(DisplayDevice::DisplayType type);
531 #endif
532
533     /* ------------------------------------------------------------------------
534      * H/W composer
535      */
536
537     HWComposer& getHwComposer() const { return *mHwc; }
538
539     /* ------------------------------------------------------------------------
540      * Compositing
541      */
542     void invalidateHwcGeometry();
543     void computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
544             Region& dirtyRegion, Region& opaqueRegion);
545
546     void preComposition(nsecs_t refreshStartTime);
547     void postComposition(nsecs_t refreshStartTime);
548     void updateCompositorTiming(
549             nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
550             std::shared_ptr<FenceTime>& presentFenceTime);
551     void setCompositorTimingSnapped(
552             nsecs_t vsyncPhase, nsecs_t vsyncInterval,
553             nsecs_t compositeToPresentLatency);
554     void rebuildLayerStacks();
555
556     // Given a dataSpace, returns the appropriate color_mode to use
557     // to display that dataSpace.
558     android_color_mode pickColorMode(android_dataspace dataSpace) const;
559     android_dataspace bestTargetDataSpace(android_dataspace a, android_dataspace b) const;
560
561     mat4 computeSaturationMatrix() const;
562
563     void setUpHWComposer();
564     void doComposition();
565     void doDebugFlashRegions();
566     void doDisplayComposition(const sp<const DisplayDevice>& displayDevice, const Region& dirtyRegion);
567
568     // compose surfaces for display hw. this fails if using GL and the surface
569     // has been destroyed and is no longer valid.
570     bool doComposeSurfaces(const sp<const DisplayDevice>& displayDevice, const Region& dirty);
571
572     void postFramebuffer();
573     void drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const;
574
575     /* ------------------------------------------------------------------------
576      * Display management
577      */
578
579     /* ------------------------------------------------------------------------
580      * VSync
581      */
582     void enableHardwareVsync();
583     void resyncToHardwareVsync(bool makeAvailable);
584     void disableHardwareVsync(bool makeUnavailable);
585
586 public:
587     void resyncWithRateLimit();
588     void getCompositorTiming(CompositorTiming* compositorTiming);
589 private:
590
591     /* ------------------------------------------------------------------------
592      * Debugging & dumpsys
593      */
594     void listLayersLocked(const Vector<String16>& args, size_t& index, String8& result) const;
595     void dumpStatsLocked(const Vector<String16>& args, size_t& index, String8& result) const;
596     void clearStatsLocked(const Vector<String16>& args, size_t& index, String8& result);
597     void dumpAllLocked(const Vector<String16>& args, size_t& index, String8& result) const;
598     bool startDdmConnection();
599     void appendSfConfigString(String8& result) const;
600     void checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
601             const sp<const DisplayDevice>& hw,
602             int32_t minLayerZ, int32_t maxLayerZ);
603
604     void logFrameStats();
605
606     void dumpStaticScreenStats(String8& result) const;
607     // Not const because each Layer needs to query Fences and cache timestamps.
608     void dumpFrameEventsLocked(String8& result);
609
610     void recordBufferingStats(const char* layerName,
611             std::vector<OccupancyTracker::Segment>&& history);
612     void dumpBufferingStats(String8& result) const;
613     void dumpWideColorInfo(String8& result) const;
614
615     bool isLayerTripleBufferingDisabled() const {
616         return this->mLayerTripleBufferingDisabled;
617     }
618
619 #ifdef USE_HWC2
620     /* ------------------------------------------------------------------------
621      * VrFlinger
622      */
623     void resetDisplayState();
624
625     // Check to see if we should handoff to vr flinger.
626     void updateVrFlinger();
627 #endif
628
629     /* ------------------------------------------------------------------------
630      * Attributes
631      */
632
633     // access must be protected by mStateLock
634     mutable Mutex mStateLock;
635     State mCurrentState{LayerVector::StateSet::Current};
636     volatile int32_t mTransactionFlags;
637     Condition mTransactionCV;
638     bool mTransactionPending;
639     bool mAnimTransactionPending;
640     SortedVector< sp<Layer> > mLayersPendingRemoval;
641     SortedVector< wp<IBinder> > mGraphicBufferProducerList;
642
643     // protected by mStateLock (but we could use another lock)
644     bool mLayersRemoved;
645     bool mLayersAdded;
646
647     // access must be protected by mInvalidateLock
648     volatile int32_t mRepaintEverything;
649
650     // The current hardware composer interface.
651     //
652     // The following thread safety rules apply when accessing mHwc, either
653     // directly or via getHwComposer():
654     //
655     // 1. When recreating mHwc, acquire mStateLock. We currently recreate mHwc
656     //    only when switching into and out of vr. Recreating mHwc must only be
657     //    done on the main thread.
658     //
659     // 2. When accessing mHwc on the main thread, it's not necessary to acquire
660     //    mStateLock.
661     //
662     // 3. When accessing mHwc on a thread other than the main thread, we always
663     //    need to acquire mStateLock. This is because the main thread could be
664     //    in the process of destroying the current mHwc instance.
665     //
666     // The above thread safety rules only apply to SurfaceFlinger.cpp. In
667     // SurfaceFlinger_hwc1.cpp we create mHwc at surface flinger init and never
668     // destroy it, so it's always safe to access mHwc from any thread without
669     // acquiring mStateLock.
670     std::unique_ptr<HWComposer> mHwc;
671
672     // constant members (no synchronization needed for access)
673     RenderEngine* mRenderEngine;
674     nsecs_t mBootTime;
675     bool mGpuToCpuSupported;
676     sp<EventThread> mEventThread;
677     sp<EventThread> mSFEventThread;
678     sp<EventThread> mInjectorEventThread;
679     sp<InjectVSyncSource> mVSyncInjector;
680     sp<EventControlThread> mEventControlThread;
681     EGLContext mEGLContext;
682     EGLDisplay mEGLDisplay;
683     sp<IBinder> mBuiltinDisplays[DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES];
684
685     // Can only accessed from the main thread, these members
686     // don't need synchronization
687     State mDrawingState{LayerVector::StateSet::Drawing};
688     bool mVisibleRegionsDirty;
689 #ifndef USE_HWC2
690     bool mHwWorkListDirty;
691 #else
692     bool mGeometryInvalid;
693 #endif
694     bool mAnimCompositionPending;
695 #ifdef USE_HWC2
696     std::vector<sp<Layer>> mLayersWithQueuedFrames;
697     sp<Fence> mPreviousPresentFence = Fence::NO_FENCE;
698     bool mHadClientComposition = false;
699 #endif
700     FenceTimeline mGlCompositionDoneTimeline;
701     FenceTimeline mDisplayTimeline;
702
703     // this may only be written from the main thread with mStateLock held
704     // it may be read from other threads with mStateLock held
705     DefaultKeyedVector< wp<IBinder>, sp<DisplayDevice> > mDisplays;
706
707     // don't use a lock for these, we don't care
708     int mDebugRegion;
709     int mDebugDDMS;
710     int mDebugDisableHWC;
711     int mDebugDisableTransformHint;
712     volatile nsecs_t mDebugInSwapBuffers;
713     nsecs_t mLastSwapBufferTime;
714     volatile nsecs_t mDebugInTransaction;
715     nsecs_t mLastTransactionTime;
716     bool mBootFinished;
717     bool mForceFullDamage;
718 #ifdef USE_HWC2
719     bool mPropagateBackpressure = true;
720 #endif
721     SurfaceInterceptor mInterceptor;
722     bool mUseHwcVirtualDisplays = false;
723
724     // Restrict layers to use two buffers in their bufferqueues.
725     bool mLayerTripleBufferingDisabled = false;
726
727     // these are thread safe
728     mutable MessageQueue mEventQueue;
729     FrameTracker mAnimFrameTracker;
730     DispSync mPrimaryDispSync;
731
732     // protected by mDestroyedLayerLock;
733     mutable Mutex mDestroyedLayerLock;
734     Vector<Layer const *> mDestroyedLayers;
735
736     // protected by mHWVsyncLock
737     Mutex mHWVsyncLock;
738     bool mPrimaryHWVsyncEnabled;
739     bool mHWVsyncAvailable;
740
741     // protected by mCompositorTimingLock;
742     mutable std::mutex mCompositorTimingLock;
743     CompositorTiming mCompositorTiming;
744
745     // Only accessed from the main thread.
746     struct CompositePresentTime {
747         nsecs_t composite { -1 };
748         std::shared_ptr<FenceTime> display { FenceTime::NO_FENCE };
749     };
750     std::queue<CompositePresentTime> mCompositePresentTimes;
751
752     std::atomic<bool> mRefreshPending{false};
753
754     /* ------------------------------------------------------------------------
755      * Feature prototyping
756      */
757
758     bool mInjectVSyncs;
759
760     Daltonizer mDaltonizer;
761 #ifndef USE_HWC2
762     bool mDaltonize;
763 #endif
764
765     mat4 mPreviousColorMatrix;
766     mat4 mColorMatrix;
767     bool mHasColorMatrix;
768
769     // Static screen stats
770     bool mHasPoweredOff;
771     static const size_t NUM_BUCKETS = 8; // < 1-7, 7+
772     nsecs_t mFrameBuckets[NUM_BUCKETS];
773     nsecs_t mTotalTime;
774     std::atomic<nsecs_t> mLastSwapTime;
775
776     size_t mNumLayers;
777
778     // Double- vs. triple-buffering stats
779     struct BufferingStats {
780         BufferingStats()
781           : numSegments(0),
782             totalTime(0),
783             twoBufferTime(0),
784             doubleBufferedTime(0),
785             tripleBufferedTime(0) {}
786
787         size_t numSegments;
788         nsecs_t totalTime;
789
790         // "Two buffer" means that a third buffer was never used, whereas
791         // "double-buffered" means that on average the segment only used two
792         // buffers (though it may have used a third for some part of the
793         // segment)
794         nsecs_t twoBufferTime;
795         nsecs_t doubleBufferedTime;
796         nsecs_t tripleBufferedTime;
797     };
798     mutable Mutex mBufferingStatsMutex;
799     std::unordered_map<std::string, BufferingStats> mBufferingStats;
800
801     // Verify that transaction is being called by an approved process:
802     // either AID_GRAPHICS or AID_SYSTEM.
803     status_t CheckTransactCodeCredentials(uint32_t code);
804
805 #ifdef USE_HWC2
806     std::unique_ptr<dvr::VrFlinger> mVrFlinger;
807     std::atomic<bool> mVrFlingerRequestsDisplay;
808     static bool useVrFlinger;
809     std::thread::id mMainThreadId;
810     // The composer sequence id is a monotonically increasing integer that we
811     // use to differentiate callbacks from different hardware composer
812     // instances. Each hardware composer instance gets a different sequence id.
813     int32_t mComposerSequenceId;
814 #endif
815
816     float mSaturation = 1.0f;
817 };
818 }; // namespace android
819
820 #endif // ANDROID_SURFACE_FLINGER_H