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