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