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