SurfaceFlinger.h revision c90e469393493ff2dbb96a60abf1c828d9da2012
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    static constexpr const char* kTimestampProperty = "service.sf.present_timestamp";
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(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    int32_t getDisplayType(const sp<IBinder>& display) {
446        if (!display.get()) return NAME_NOT_FOUND;
447        for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
448            if (display == mBuiltinDisplays[i]) {
449                return i;
450            }
451        }
452        return NAME_NOT_FOUND;
453    }
454
455    // mark a region of a layer stack dirty. this updates the dirty
456    // region of all screens presenting this layer stack.
457    void invalidateLayerStack(uint32_t layerStack, const Region& dirty);
458
459#ifndef USE_HWC2
460    int32_t allocateHwcDisplayId(DisplayDevice::DisplayType type);
461#endif
462
463    /* ------------------------------------------------------------------------
464     * H/W composer
465     */
466
467    HWComposer& getHwComposer() const { return *mHwc; }
468
469    /* ------------------------------------------------------------------------
470     * Compositing
471     */
472    void invalidateHwcGeometry();
473    void computeVisibleRegions(uint32_t layerStack,
474            Region& dirtyRegion, Region& opaqueRegion);
475
476    void preComposition(nsecs_t refreshStartTime);
477    void postComposition(nsecs_t refreshStartTime);
478    void updateCompositorTiming(
479            nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
480            std::shared_ptr<FenceTime>& presentFenceTime);
481    void setCompositorTimingSnapped(
482            nsecs_t vsyncPhase, nsecs_t vsyncInterval,
483            nsecs_t compositeToPresentLatency);
484    void rebuildLayerStacks();
485
486    // Given a dataSpace, returns the appropriate color_mode to use
487    // to display that dataSpace.
488    android_color_mode pickColorMode(android_dataspace dataSpace);
489    android_dataspace bestTargetDataSpace(android_dataspace a, android_dataspace b);
490
491    void setUpHWComposer();
492    void doComposition();
493    void doDebugFlashRegions();
494    void doDisplayComposition(const sp<const DisplayDevice>& displayDevice, const Region& dirtyRegion);
495
496    // compose surfaces for display hw. this fails if using GL and the surface
497    // has been destroyed and is no longer valid.
498    bool doComposeSurfaces(const sp<const DisplayDevice>& displayDevice, const Region& dirty);
499
500    void postFramebuffer();
501    void drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const;
502
503    /* ------------------------------------------------------------------------
504     * Display management
505     */
506
507    /* ------------------------------------------------------------------------
508     * VSync
509     */
510    void enableHardwareVsync();
511    void resyncToHardwareVsync(bool makeAvailable);
512    void disableHardwareVsync(bool makeUnavailable);
513
514public:
515    void resyncWithRateLimit();
516    void getCompositorTiming(CompositorTiming* compositorTiming);
517private:
518
519    /* ------------------------------------------------------------------------
520     * Debugging & dumpsys
521     */
522    void listLayersLocked(const Vector<String16>& args, size_t& index, String8& result) const;
523    void dumpStatsLocked(const Vector<String16>& args, size_t& index, String8& result) const;
524    void clearStatsLocked(const Vector<String16>& args, size_t& index, String8& result);
525    void dumpAllLocked(const Vector<String16>& args, size_t& index, String8& result) const;
526    bool startDdmConnection();
527    void appendSfConfigString(String8& result) const;
528    void checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
529            const sp<const DisplayDevice>& hw,
530            int32_t minLayerZ, int32_t maxLayerZ);
531
532    void logFrameStats();
533
534    void dumpStaticScreenStats(String8& result) const;
535    // Not const because each Layer needs to query Fences and cache timestamps.
536    void dumpFrameEventsLocked(String8& result);
537
538    void recordBufferingStats(const char* layerName,
539            std::vector<OccupancyTracker::Segment>&& history);
540    void dumpBufferingStats(String8& result) const;
541    void dumpWideColorInfo(String8& result) const;
542
543    bool isLayerTripleBufferingDisabled() const {
544        return this->mLayerTripleBufferingDisabled;
545    }
546
547#ifdef USE_HWC2
548    /* ------------------------------------------------------------------------
549     * VrFlinger
550     */
551    void clearHwcLayers(const LayerVector& layers);
552    void resetHwc();
553
554    // Check to see if we should handoff to vr flinger.
555    void updateVrFlinger();
556#endif
557
558    /* ------------------------------------------------------------------------
559     * Attributes
560     */
561
562    // access must be protected by mStateLock
563    mutable Mutex mStateLock;
564    State mCurrentState;
565    volatile int32_t mTransactionFlags;
566    Condition mTransactionCV;
567    bool mTransactionPending;
568    bool mAnimTransactionPending;
569    SortedVector< sp<Layer> > mLayersPendingRemoval;
570    SortedVector< wp<IBinder> > mGraphicBufferProducerList;
571
572    // protected by mStateLock (but we could use another lock)
573    bool mLayersRemoved;
574    bool mLayersAdded;
575
576    // access must be protected by mInvalidateLock
577    volatile int32_t mRepaintEverything;
578
579    // current, real and vr hardware composers.
580    HWComposer* mHwc;
581#ifdef USE_HWC2
582    HWComposer* mRealHwc;
583    HWComposer* mVrHwc;
584#endif
585    // constant members (no synchronization needed for access)
586    RenderEngine* mRenderEngine;
587    nsecs_t mBootTime;
588    bool mGpuToCpuSupported;
589    sp<EventThread> mEventThread;
590    sp<EventThread> mSFEventThread;
591    sp<EventThread> mInjectorEventThread;
592    sp<InjectVSyncSource> mVSyncInjector;
593    sp<EventControlThread> mEventControlThread;
594    EGLContext mEGLContext;
595    EGLDisplay mEGLDisplay;
596    sp<IBinder> mBuiltinDisplays[DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES];
597
598#ifdef USE_HWC2
599    std::unique_ptr<dvr::VrFlinger> mVrFlinger;
600#endif
601
602    // Can only accessed from the main thread, these members
603    // don't need synchronization
604    State mDrawingState;
605    bool mVisibleRegionsDirty;
606#ifndef USE_HWC2
607    bool mHwWorkListDirty;
608#else
609    bool mGeometryInvalid;
610#endif
611    bool mAnimCompositionPending;
612#ifdef USE_HWC2
613    std::vector<sp<Layer>> mLayersWithQueuedFrames;
614    sp<Fence> mPreviousPresentFence = Fence::NO_FENCE;
615    bool mHadClientComposition = false;
616#endif
617    FenceTimeline mGlCompositionDoneTimeline;
618    FenceTimeline mDisplayTimeline;
619
620    // this may only be written from the main thread with mStateLock held
621    // it may be read from other threads with mStateLock held
622    DefaultKeyedVector< wp<IBinder>, sp<DisplayDevice> > mDisplays;
623
624    // don't use a lock for these, we don't care
625    int mDebugRegion;
626    int mDebugDDMS;
627    int mDebugDisableHWC;
628    int mDebugDisableTransformHint;
629    volatile nsecs_t mDebugInSwapBuffers;
630    nsecs_t mLastSwapBufferTime;
631    volatile nsecs_t mDebugInTransaction;
632    nsecs_t mLastTransactionTime;
633    bool mBootFinished;
634    bool mForceFullDamage;
635#ifdef USE_HWC2
636    bool mPropagateBackpressure = true;
637#endif
638    SurfaceInterceptor mInterceptor;
639    bool mUseHwcVirtualDisplays = false;
640
641    // Restrict layers to use two buffers in their bufferqueues.
642    bool mLayerTripleBufferingDisabled = false;
643
644    // these are thread safe
645    mutable MessageQueue mEventQueue;
646    FrameTracker mAnimFrameTracker;
647    DispSync mPrimaryDispSync;
648
649    // protected by mDestroyedLayerLock;
650    mutable Mutex mDestroyedLayerLock;
651    Vector<Layer const *> mDestroyedLayers;
652
653    // protected by mHWVsyncLock
654    Mutex mHWVsyncLock;
655    bool mPrimaryHWVsyncEnabled;
656    bool mHWVsyncAvailable;
657
658    // protected by mCompositorTimingLock;
659    mutable std::mutex mCompositorTimingLock;
660    CompositorTiming mCompositorTiming;
661
662    // Only accessed from the main thread.
663    struct CompositePresentTime {
664        nsecs_t composite { -1 };
665        std::shared_ptr<FenceTime> display { FenceTime::NO_FENCE };
666    };
667    std::queue<CompositePresentTime> mCompositePresentTimes;
668
669    /* ------------------------------------------------------------------------
670     * Feature prototyping
671     */
672
673    bool mInjectVSyncs;
674
675    Daltonizer mDaltonizer;
676#ifndef USE_HWC2
677    bool mDaltonize;
678#endif
679
680    mat4 mPreviousColorMatrix;
681    mat4 mColorMatrix;
682    bool mHasColorMatrix;
683
684    // Static screen stats
685    bool mHasPoweredOff;
686    static const size_t NUM_BUCKETS = 8; // < 1-7, 7+
687    nsecs_t mFrameBuckets[NUM_BUCKETS];
688    nsecs_t mTotalTime;
689    std::atomic<nsecs_t> mLastSwapTime;
690
691    size_t mNumLayers;
692
693    // Double- vs. triple-buffering stats
694    struct BufferingStats {
695        BufferingStats()
696          : numSegments(0),
697            totalTime(0),
698            twoBufferTime(0),
699            doubleBufferedTime(0),
700            tripleBufferedTime(0) {}
701
702        size_t numSegments;
703        nsecs_t totalTime;
704
705        // "Two buffer" means that a third buffer was never used, whereas
706        // "double-buffered" means that on average the segment only used two
707        // buffers (though it may have used a third for some part of the
708        // segment)
709        nsecs_t twoBufferTime;
710        nsecs_t doubleBufferedTime;
711        nsecs_t tripleBufferedTime;
712    };
713    mutable Mutex mBufferingStatsMutex;
714    std::unordered_map<std::string, BufferingStats> mBufferingStats;
715
716    // Verify that transaction is being called by an approved process:
717    // either AID_GRAPHICS or AID_SYSTEM.
718    status_t CheckTransactCodeCredentials(uint32_t code);
719
720#ifdef USE_HWC2
721    std::atomic<bool> mVrFlingerRequestsDisplay;
722    static bool useVrFlinger;
723#endif
724    };
725}; // namespace android
726
727#endif // ANDROID_SURFACE_FLINGER_H
728