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