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 /*
25  * NOTE: Make sure this file doesn't include  anything from <gl/ > or <gl2/ >
26  */
27 
28 #include <cutils/compiler.h>
29 #include <cutils/atomic.h>
30 
31 #include <utils/Errors.h>
32 #include <utils/KeyedVector.h>
33 #include <utils/RefBase.h>
34 #include <utils/SortedVector.h>
35 #include <utils/threads.h>
36 #include <utils/Trace.h>
37 
38 #include <ui/FenceTime.h>
39 #include <ui/PixelFormat.h>
40 #include <math/mat4.h>
41 
42 #include <gui/FrameTimestamps.h>
43 #include <gui/ISurfaceComposer.h>
44 #include <gui/ISurfaceComposerClient.h>
45 #include <gui/LayerState.h>
46 
47 #include <gui/OccupancyTracker.h>
48 
49 #include <hardware/hwcomposer_defs.h>
50 
51 #include <serviceutils/PriorityDumper.h>
52 
53 #include <system/graphics.h>
54 
55 #include "Barrier.h"
56 #include "DisplayDevice.h"
57 #include "DispSync.h"
58 #include "EventThread.h"
59 #include "FrameTracker.h"
60 #include "LayerStats.h"
61 #include "LayerVector.h"
62 #include "MessageQueue.h"
63 #include "SurfaceInterceptor.h"
64 #include "SurfaceTracing.h"
65 #include "StartPropertySetThread.h"
66 #include "TimeStats/TimeStats.h"
67 #include "VSyncModulator.h"
68 
69 #include "DisplayHardware/HWC2.h"
70 #include "DisplayHardware/HWComposer.h"
71 
72 #include "Effects/Daltonizer.h"
73 
74 #include <map>
75 #include <mutex>
76 #include <queue>
77 #include <string>
78 #include <thread>
79 #include <utility>
80 #include "RenderArea.h"
81 
82 #include <layerproto/LayerProtoHeader.h>
83 
84 using namespace android::surfaceflinger;
85 
86 namespace android {
87 
88 // ---------------------------------------------------------------------------
89 
90 class Client;
91 class ColorLayer;
92 class DisplayEventConnection;
93 class EventControlThread;
94 class EventThread;
95 class IGraphicBufferConsumer;
96 class IGraphicBufferProducer;
97 class InjectVSyncSource;
98 class Layer;
99 class Surface;
100 class SurfaceFlingerBE;
101 class VSyncSource;
102 
103 namespace impl {
104 class EventThread;
105 } // namespace impl
106 
107 namespace RE {
108 class RenderEngine;
109 }
110 
111 typedef std::function<void(const LayerVector::Visitor&)> TraverseLayersFunction;
112 
113 namespace dvr {
114 class VrFlinger;
115 } // namespace dvr
116 
117 // ---------------------------------------------------------------------------
118 
119 enum {
120     eTransactionNeeded        = 0x01,
121     eTraversalNeeded          = 0x02,
122     eDisplayTransactionNeeded = 0x04,
123     eDisplayLayerStackChanged = 0x08,
124     eTransactionMask          = 0x0f,
125 };
126 
127 enum class DisplayColorSetting : int32_t {
128     MANAGED = 0,
129     UNMANAGED = 1,
130     ENHANCED = 2,
131 };
132 
133 // A thin interface to abstract creating instances of Surface (gui/Surface.h) to
134 // use as a NativeWindow.
135 class NativeWindowSurface {
136 public:
137     virtual ~NativeWindowSurface();
138 
139     // Gets the NativeWindow to use for the surface.
140     virtual sp<ANativeWindow> getNativeWindow() const = 0;
141 
142     // Indicates that the surface should allocate its buffers now.
143     virtual void preallocateBuffers() = 0;
144 };
145 
146 class SurfaceFlingerBE
147 {
148 public:
149     SurfaceFlingerBE();
150 
151     // The current hardware composer interface.
152     //
153     // The following thread safety rules apply when accessing mHwc, either
154     // directly or via getHwComposer():
155     //
156     // 1. When recreating mHwc, acquire mStateLock. We currently recreate mHwc
157     //    only when switching into and out of vr. Recreating mHwc must only be
158     //    done on the main thread.
159     //
160     // 2. When accessing mHwc on the main thread, it's not necessary to acquire
161     //    mStateLock.
162     //
163     // 3. When accessing mHwc on a thread other than the main thread, we always
164     //    need to acquire mStateLock. This is because the main thread could be
165     //    in the process of destroying the current mHwc instance.
166     //
167     // The above thread safety rules only apply to SurfaceFlinger.cpp. In
168     // SurfaceFlinger_hwc1.cpp we create mHwc at surface flinger init and never
169     // destroy it, so it's always safe to access mHwc from any thread without
170     // acquiring mStateLock.
171     std::unique_ptr<HWComposer> mHwc;
172 
173     const std::string mHwcServiceName; // "default" for real use, something else for testing.
174 
175     // constant members (no synchronization needed for access)
176     std::unique_ptr<RE::RenderEngine> mRenderEngine;
177     EGLContext mEGLContext;
178     EGLDisplay mEGLDisplay;
179 
180     FenceTimeline mGlCompositionDoneTimeline;
181     FenceTimeline mDisplayTimeline;
182 
183     // protected by mCompositorTimingLock;
184     mutable std::mutex mCompositorTimingLock;
185     CompositorTiming mCompositorTiming;
186 
187     // Only accessed from the main thread.
188     struct CompositePresentTime {
189         nsecs_t composite { -1 };
190         std::shared_ptr<FenceTime> display { FenceTime::NO_FENCE };
191     };
192     std::queue<CompositePresentTime> mCompositePresentTimes;
193 
194     static const size_t NUM_BUCKETS = 8; // < 1-7, 7+
195     nsecs_t mFrameBuckets[NUM_BUCKETS];
196     nsecs_t mTotalTime;
197     std::atomic<nsecs_t> mLastSwapTime;
198 
199     // Double- vs. triple-buffering stats
200     struct BufferingStats {
BufferingStatsBufferingStats201         BufferingStats()
202           : numSegments(0),
203             totalTime(0),
204             twoBufferTime(0),
205             doubleBufferedTime(0),
206             tripleBufferedTime(0) {}
207 
208         size_t numSegments;
209         nsecs_t totalTime;
210 
211         // "Two buffer" means that a third buffer was never used, whereas
212         // "double-buffered" means that on average the segment only used two
213         // buffers (though it may have used a third for some part of the
214         // segment)
215         nsecs_t twoBufferTime;
216         nsecs_t doubleBufferedTime;
217         nsecs_t tripleBufferedTime;
218     };
219     mutable Mutex mBufferingStatsMutex;
220     std::unordered_map<std::string, BufferingStats> mBufferingStats;
221 
222     // The composer sequence id is a monotonically increasing integer that we
223     // use to differentiate callbacks from different hardware composer
224     // instances. Each hardware composer instance gets a different sequence id.
225     int32_t mComposerSequenceId;
226 };
227 
228 
229 class SurfaceFlinger : public BnSurfaceComposer,
230                        public PriorityDumper,
231                        private IBinder::DeathRecipient,
232                        private HWC2::ComposerCallback
233 {
234 public:
getBE()235     SurfaceFlingerBE& getBE() { return mBE; }
getBE()236     const SurfaceFlingerBE& getBE() const { return mBE; }
237 
238     // This is the phase offset in nanoseconds of the software vsync event
239     // relative to the vsync event reported by HWComposer.  The software vsync
240     // event is when SurfaceFlinger and Choreographer-based applications run each
241     // frame.
242     //
243     // This phase offset allows adjustment of the minimum latency from application
244     // wake-up time (by Choreographer) to the time at which the resulting window
245     // image is displayed.  This value may be either positive (after the HW vsync)
246     // or negative (before the HW vsync). Setting it to 0 will result in a lower
247     // latency bound of two vsync periods because the app and SurfaceFlinger
248     // will run just after the HW vsync.  Setting it to a positive number will
249     // result in the minimum latency being:
250     //
251     //     (2 * VSYNC_PERIOD - (vsyncPhaseOffsetNs % VSYNC_PERIOD))
252     //
253     // Note that reducing this latency makes it more likely for the applications
254     // to not have their window content image ready in time.  When this happens
255     // the latency will end up being an additional vsync period, and animations
256     // will hiccup.  Therefore, this latency should be tuned somewhat
257     // conservatively (or at least with awareness of the trade-off being made).
258     static int64_t vsyncPhaseOffsetNs;
259     static int64_t sfVsyncPhaseOffsetNs;
260 
261     // If fences from sync Framework are supported.
262     static bool hasSyncFramework;
263 
264     // The offset in nanoseconds to use when DispSync timestamps present fence
265     // signaling time.
266     static int64_t dispSyncPresentTimeOffset;
267 
268     // Some hardware can do RGB->YUV conversion more efficiently in hardware
269     // controlled by HWC than in hardware controlled by the video encoder.
270     // This instruct VirtualDisplaySurface to use HWC for such conversion on
271     // GL composition.
272     static bool useHwcForRgbToYuv;
273 
274     // Maximum dimension supported by HWC for virtual display.
275     // Equal to min(max_height, max_width).
276     static uint64_t maxVirtualDisplaySize;
277 
278     // Controls the number of buffers SurfaceFlinger will allocate for use in
279     // FramebufferSurface
280     static int64_t maxFrameBufferAcquiredBuffers;
281 
282     // Indicate if platform supports color management on its
283     // wide-color display. This is typically found on devices
284     // with wide gamut (e.g. Display-P3) display.
285     // This also allows devices with wide-color displays that don't
286     // want to support color management to disable color management.
287     static bool hasWideColorDisplay;
288 
getServiceName()289     static char const* getServiceName() ANDROID_API {
290         return "SurfaceFlinger";
291     }
292 
293     struct SkipInitializationTag {};
294     static constexpr SkipInitializationTag SkipInitialization;
295     explicit SurfaceFlinger(SkipInitializationTag) ANDROID_API;
296     SurfaceFlinger() ANDROID_API;
297 
298     // must be called before clients can connect
299     void init() ANDROID_API;
300 
301     // starts SurfaceFlinger main loop in the current thread
302     void run() ANDROID_API;
303 
304     enum {
305         EVENT_VSYNC = HWC_EVENT_VSYNC
306     };
307 
308     // post an asynchronous message to the main thread
309     status_t postMessageAsync(const sp<MessageBase>& msg, nsecs_t reltime = 0, uint32_t flags = 0);
310 
311     // post a synchronous message to the main thread
312     status_t postMessageSync(const sp<MessageBase>& msg, nsecs_t reltime = 0, uint32_t flags = 0);
313 
314     // force full composition on all displays
315     void repaintEverything();
316 
317     // returns the default Display
getDefaultDisplayDevice()318     sp<const DisplayDevice> getDefaultDisplayDevice() const {
319         Mutex::Autolock _l(mStateLock);
320         return getDefaultDisplayDeviceLocked();
321     }
322 
323     // utility function to delete a texture on the main thread
324     void deleteTextureAsync(uint32_t texture);
325 
326     // enable/disable h/w composer event
327     // TODO: this should be made accessible only to EventThread
328     void setVsyncEnabled(int disp, int enabled);
329 
330     // called on the main thread by MessageQueue when an internal message
331     // is received
332     // TODO: this should be made accessible only to MessageQueue
333     void onMessageReceived(int32_t what);
334 
335     // for debugging only
336     // TODO: this should be made accessible only to HWComposer
337     const Vector< sp<Layer> >& getLayerSortedByZForHwcDisplay(int id);
338 
getRenderEngine()339     RE::RenderEngine& getRenderEngine() const { return *getBE().mRenderEngine; }
340 
341     bool authenticateSurfaceTextureLocked(
342         const sp<IGraphicBufferProducer>& bufferProducer) const;
343 
getPrimaryDisplayOrientation()344     int getPrimaryDisplayOrientation() const { return mPrimaryDisplayOrientation; }
345 
346 private:
347     friend class Client;
348     friend class DisplayEventConnection;
349     friend class impl::EventThread;
350     friend class Layer;
351     friend class BufferLayer;
352     friend class MonitoredProducer;
353 
354     // For unit tests
355     friend class TestableSurfaceFlinger;
356 
357     // This value is specified in number of frames.  Log frame stats at most
358     // every half hour.
359     enum { LOG_FRAME_STATS_PERIOD =  30*60*60 };
360 
361     static const size_t MAX_LAYERS = 4096;
362 
363     // We're reference counted, never destroy SurfaceFlinger directly
364     virtual ~SurfaceFlinger();
365 
366     /* ------------------------------------------------------------------------
367      * Internal data structures
368      */
369 
370     class State {
371     public:
State(LayerVector::StateSet set)372         explicit State(LayerVector::StateSet set) : stateSet(set), layersSortedByZ(set) {}
373         State& operator=(const State& other) {
374             // We explicitly don't copy stateSet so that, e.g., mDrawingState
375             // always uses the Drawing StateSet.
376             layersSortedByZ = other.layersSortedByZ;
377             displays = other.displays;
378             colorMatrixChanged = other.colorMatrixChanged;
379             if (colorMatrixChanged) {
380                 colorMatrix = other.colorMatrix;
381             }
382             return *this;
383         }
384 
385         const LayerVector::StateSet stateSet = LayerVector::StateSet::Invalid;
386         LayerVector layersSortedByZ;
387         DefaultKeyedVector< wp<IBinder>, DisplayDeviceState> displays;
388 
389         bool colorMatrixChanged = true;
390         mat4 colorMatrix;
391 
392         void traverseInZOrder(const LayerVector::Visitor& visitor) const;
393         void traverseInReverseZOrder(const LayerVector::Visitor& visitor) const;
394     };
395 
396     /* ------------------------------------------------------------------------
397      * IBinder interface
398      */
399     virtual status_t onTransact(uint32_t code, const Parcel& data,
400         Parcel* reply, uint32_t flags);
dump(int fd,const Vector<String16> & args)401     virtual status_t dump(int fd, const Vector<String16>& args) { return priorityDump(fd, args); }
402 
403     /* ------------------------------------------------------------------------
404      * ISurfaceComposer interface
405      */
406     virtual sp<ISurfaceComposerClient> createConnection();
407     virtual sp<ISurfaceComposerClient> createScopedConnection(const sp<IGraphicBufferProducer>& gbp);
408     virtual sp<IBinder> createDisplay(const String8& displayName, bool secure);
409     virtual void destroyDisplay(const sp<IBinder>& display);
410     virtual sp<IBinder> getBuiltInDisplay(int32_t id);
411     virtual void setTransactionState(const Vector<ComposerState>& state,
412             const Vector<DisplayState>& displays, uint32_t flags);
413     virtual void bootFinished();
414     virtual bool authenticateSurfaceTexture(
415         const sp<IGraphicBufferProducer>& bufferProducer) const;
416     virtual status_t getSupportedFrameTimestamps(
417             std::vector<FrameEvent>* outSupported) const;
418     virtual sp<IDisplayEventConnection> createDisplayEventConnection(
419             ISurfaceComposer::VsyncSource vsyncSource = eVsyncSourceApp);
420     virtual status_t captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
421                                    Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
422                                    int32_t minLayerZ, int32_t maxLayerZ, bool useIdentityTransform,
423                                    ISurfaceComposer::Rotation rotation);
424     virtual status_t captureLayers(const sp<IBinder>& parentHandle, sp<GraphicBuffer>* outBuffer,
425                                    const Rect& sourceCrop, float frameScale, bool childrenOnly);
426     virtual status_t getDisplayStats(const sp<IBinder>& display,
427             DisplayStatInfo* stats);
428     virtual status_t getDisplayConfigs(const sp<IBinder>& display,
429             Vector<DisplayInfo>* configs);
430     virtual int getActiveConfig(const sp<IBinder>& display);
431     virtual status_t getDisplayColorModes(const sp<IBinder>& display,
432             Vector<ui::ColorMode>* configs);
433     virtual ui::ColorMode getActiveColorMode(const sp<IBinder>& display);
434     virtual status_t setActiveColorMode(const sp<IBinder>& display, ui::ColorMode colorMode);
435     virtual void setPowerMode(const sp<IBinder>& display, int mode);
436     virtual status_t setActiveConfig(const sp<IBinder>& display, int id);
437     virtual status_t clearAnimationFrameStats();
438     virtual status_t getAnimationFrameStats(FrameStats* outStats) const;
439     virtual status_t getHdrCapabilities(const sp<IBinder>& display,
440             HdrCapabilities* outCapabilities) const;
441     virtual status_t enableVSyncInjections(bool enable);
442     virtual status_t injectVSync(nsecs_t when);
443     virtual status_t getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const;
444 
445 
446     /* ------------------------------------------------------------------------
447      * DeathRecipient interface
448      */
449     virtual void binderDied(const wp<IBinder>& who);
450 
451     /* ------------------------------------------------------------------------
452      * RefBase interface
453      */
454     virtual void onFirstRef();
455 
456     /* ------------------------------------------------------------------------
457      * HWC2::ComposerCallback / HWComposer::EventHandler interface
458      */
459     void onVsyncReceived(int32_t sequenceId, hwc2_display_t display,
460                          int64_t timestamp) override;
461     void onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
462                            HWC2::Connection connection) override;
463     void onRefreshReceived(int32_t sequenceId, hwc2_display_t display) override;
464 
465     /* ------------------------------------------------------------------------
466      * Message handling
467      */
468     void waitForEvent();
469     // Can only be called from the main thread or with mStateLock held
470     void signalTransaction();
471     // Can only be called from the main thread or with mStateLock held
472     void signalLayerUpdate();
473     void signalRefresh();
474 
475     // called on the main thread in response to initializeDisplays()
476     void onInitializeDisplays();
477     // called on the main thread in response to setActiveConfig()
478     void setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode);
479     // called on the main thread in response to setPowerMode()
480     void setPowerModeInternal(const sp<DisplayDevice>& hw, int mode,
481                               bool stateLockHeld);
482 
483     // Called on the main thread in response to setActiveColorMode()
484     void setActiveColorModeInternal(const sp<DisplayDevice>& hw,
485                                     ui::ColorMode colorMode,
486                                     ui::Dataspace dataSpace,
487                                     ui::RenderIntent renderIntent);
488 
489     // Returns whether the transaction actually modified any state
490     bool handleMessageTransaction();
491 
492     // Returns whether a new buffer has been latched (see handlePageFlip())
493     bool handleMessageInvalidate();
494 
495     void handleMessageRefresh();
496 
497     void handleTransaction(uint32_t transactionFlags);
498     void handleTransactionLocked(uint32_t transactionFlags);
499 
500     void updateCursorAsync();
501 
502     /* handlePageFlip - latch a new buffer if available and compute the dirty
503      * region. Returns whether a new buffer has been latched, i.e., whether it
504      * is necessary to perform a refresh during this vsync.
505      */
506     bool handlePageFlip();
507 
508     /* ------------------------------------------------------------------------
509      * Transactions
510      */
511     uint32_t getTransactionFlags(uint32_t flags);
512     uint32_t peekTransactionFlags();
513     // Can only be called from the main thread or with mStateLock held
514     uint32_t setTransactionFlags(uint32_t flags);
515     uint32_t setTransactionFlags(uint32_t flags, VSyncModulator::TransactionStart transactionStart);
516     void commitTransaction();
517     bool containsAnyInvalidClientState(const Vector<ComposerState>& states);
518     uint32_t setClientStateLocked(const ComposerState& composerState);
519     uint32_t setDisplayStateLocked(const DisplayState& s);
520     void setDestroyStateLocked(const ComposerState& composerState);
521 
522     /* ------------------------------------------------------------------------
523      * Layer management
524      */
525     status_t createLayer(const String8& name, const sp<Client>& client,
526             uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
527             int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
528             sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent);
529 
530     status_t createBufferLayer(const sp<Client>& client, const String8& name,
531             uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
532             sp<IBinder>* outHandle, sp<IGraphicBufferProducer>* outGbp,
533             sp<Layer>* outLayer);
534 
535     status_t createColorLayer(const sp<Client>& client, const String8& name,
536             uint32_t w, uint32_t h, uint32_t flags, sp<IBinder>* outHandle,
537             sp<Layer>* outLayer);
538 
539     String8 getUniqueLayerName(const String8& name);
540 
541     // called in response to the window-manager calling
542     // ISurfaceComposerClient::destroySurface()
543     status_t onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle);
544 
545     // called when all clients have released all their references to
546     // this layer meaning it is entirely safe to destroy all
547     // resources associated to this layer.
548     status_t onLayerDestroyed(const wp<Layer>& layer);
549 
550     // remove a layer from SurfaceFlinger immediately
551     status_t removeLayer(const sp<Layer>& layer, bool topLevelOnly = false);
552     status_t removeLayerLocked(const Mutex&, const sp<Layer>& layer, bool topLevelOnly = false);
553 
554     // add a layer to SurfaceFlinger
555     status_t addClientLayer(const sp<Client>& client,
556             const sp<IBinder>& handle,
557             const sp<IGraphicBufferProducer>& gbc,
558             const sp<Layer>& lbc,
559             const sp<Layer>& parent);
560 
561     /* ------------------------------------------------------------------------
562      * Boot animation, on/off animations and screen capture
563      */
564 
565     void startBootAnim();
566 
567     void renderScreenImplLocked(const RenderArea& renderArea, TraverseLayersFunction traverseLayers,
568                                 bool yswap, bool useIdentityTransform);
569     status_t captureScreenCommon(RenderArea& renderArea, TraverseLayersFunction traverseLayers,
570                                  sp<GraphicBuffer>* outBuffer,
571                                  bool useIdentityTransform);
572     status_t captureScreenImplLocked(const RenderArea& renderArea,
573                                      TraverseLayersFunction traverseLayers,
574                                      ANativeWindowBuffer* buffer, bool useIdentityTransform,
575                                      bool forSystem, int* outSyncFd);
576     void traverseLayersInDisplay(const sp<const DisplayDevice>& display, int32_t minLayerZ,
577                                  int32_t maxLayerZ, const LayerVector::Visitor& visitor);
578 
579     sp<StartPropertySetThread> mStartPropertySetThread = nullptr;
580 
581     /* ------------------------------------------------------------------------
582      * Properties
583      */
584     void readPersistentProperties();
585 
586     /* ------------------------------------------------------------------------
587      * EGL
588      */
589     size_t getMaxTextureSize() const;
590     size_t getMaxViewportDims() const;
591 
592     /* ------------------------------------------------------------------------
593      * Display and layer stack management
594      */
595     // called when starting, or restarting after system_server death
596     void initializeDisplays();
597 
getDisplayDevice(const wp<IBinder> & dpy)598     sp<const DisplayDevice> getDisplayDevice(const wp<IBinder>& dpy) const {
599       Mutex::Autolock _l(mStateLock);
600       return getDisplayDeviceLocked(dpy);
601     }
602 
getDisplayDevice(const wp<IBinder> & dpy)603     sp<DisplayDevice> getDisplayDevice(const wp<IBinder>& dpy) {
604       Mutex::Autolock _l(mStateLock);
605       return getDisplayDeviceLocked(dpy);
606     }
607 
608     // NOTE: can only be called from the main thread or with mStateLock held
getDisplayDeviceLocked(const wp<IBinder> & dpy)609     sp<const DisplayDevice> getDisplayDeviceLocked(const wp<IBinder>& dpy) const {
610         return mDisplays.valueFor(dpy);
611     }
612 
613     // NOTE: can only be called from the main thread or with mStateLock held
getDisplayDeviceLocked(const wp<IBinder> & dpy)614     sp<DisplayDevice> getDisplayDeviceLocked(const wp<IBinder>& dpy) {
615         return mDisplays.valueFor(dpy);
616     }
617 
getDefaultDisplayDeviceLocked()618     sp<const DisplayDevice> getDefaultDisplayDeviceLocked() const {
619         return getDisplayDeviceLocked(mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]);
620     }
621 
getDisplayType(const sp<IBinder> & display)622     int32_t getDisplayType(const sp<IBinder>& display) {
623         if (!display.get()) return NAME_NOT_FOUND;
624         for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
625             if (display == mBuiltinDisplays[i]) {
626                 return i;
627             }
628         }
629         return NAME_NOT_FOUND;
630     }
631 
632     // mark a region of a layer stack dirty. this updates the dirty
633     // region of all screens presenting this layer stack.
634     void invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty);
635 
636     /* ------------------------------------------------------------------------
637      * H/W composer
638      */
639 
getHwComposer()640     HWComposer& getHwComposer() const { return *getBE().mHwc; }
641 
642     /* ------------------------------------------------------------------------
643      * Compositing
644      */
645     void invalidateHwcGeometry();
646     void computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
647             Region& dirtyRegion, Region& opaqueRegion);
648 
649     void preComposition(nsecs_t refreshStartTime);
650     void postComposition(nsecs_t refreshStartTime);
651     void updateCompositorTiming(
652             nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
653             std::shared_ptr<FenceTime>& presentFenceTime);
654     void setCompositorTimingSnapped(
655             nsecs_t vsyncPhase, nsecs_t vsyncInterval,
656             nsecs_t compositeToPresentLatency);
657     void rebuildLayerStacks();
658 
659     ui::Dataspace getBestDataspace(const sp<const DisplayDevice>& displayDevice,
660                                    ui::Dataspace* outHdrDataSpace) const;
661 
662     // Returns the appropriate ColorMode, Dataspace and RenderIntent for the
663     // DisplayDevice. The function only returns the supported ColorMode,
664     // Dataspace and RenderIntent.
665     void pickColorMode(const sp<DisplayDevice>& displayDevice,
666                        ui::ColorMode* outMode,
667                        ui::Dataspace* outDataSpace,
668                        ui::RenderIntent* outRenderIntent) const;
669 
670     void setUpHWComposer();
671     void doComposition();
672     void doDebugFlashRegions();
673     void doTracing(const char* where);
674     void logLayerStats();
675     void doDisplayComposition(const sp<const DisplayDevice>& displayDevice, const Region& dirtyRegion);
676 
677     // compose surfaces for display hw. this fails if using GL and the surface
678     // has been destroyed and is no longer valid.
679     bool doComposeSurfaces(const sp<const DisplayDevice>& displayDevice);
680 
681     void postFramebuffer();
682     void drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const;
683 
684     /* ------------------------------------------------------------------------
685      * Display management
686      */
687     DisplayDevice::DisplayType determineDisplayType(hwc2_display_t display,
688             HWC2::Connection connection) const;
689     sp<DisplayDevice> setupNewDisplayDeviceInternal(const wp<IBinder>& display, int hwcId,
690                                                     const DisplayDeviceState& state,
691                                                     const sp<DisplaySurface>& dispSurface,
692                                                     const sp<IGraphicBufferProducer>& producer);
693     void processDisplayChangesLocked();
694     void processDisplayHotplugEventsLocked();
695 
696     /* ------------------------------------------------------------------------
697      * VSync
698      */
699     void enableHardwareVsync();
700     void resyncToHardwareVsync(bool makeAvailable);
701     void disableHardwareVsync(bool makeUnavailable);
702 
703 public:
704     void resyncWithRateLimit();
705     void getCompositorTiming(CompositorTiming* compositorTiming);
706 private:
707 
708     /* ------------------------------------------------------------------------
709      * Debugging & dumpsys
710      */
711 public:
dumpCritical(int fd,const Vector<String16> &,bool asProto)712     status_t dumpCritical(int fd, const Vector<String16>& /*args*/, bool asProto) {
713         return doDump(fd, Vector<String16>(), asProto);
714     }
715 
dumpAll(int fd,const Vector<String16> & args,bool asProto)716     status_t dumpAll(int fd, const Vector<String16>& args, bool asProto) {
717         return doDump(fd, args, asProto);
718     }
719 
720 private:
721     void listLayersLocked(const Vector<String16>& args, size_t& index, String8& result) const;
722     void dumpStatsLocked(const Vector<String16>& args, size_t& index, String8& result) const;
723     void clearStatsLocked(const Vector<String16>& args, size_t& index, String8& result);
724     void dumpAllLocked(const Vector<String16>& args, size_t& index, String8& result) const;
725     bool startDdmConnection();
726     void appendSfConfigString(String8& result) const;
727     void checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
728                          TraverseLayersFunction traverseLayers);
729 
730     void logFrameStats();
731 
732     void dumpStaticScreenStats(String8& result) const;
733     // Not const because each Layer needs to query Fences and cache timestamps.
734     void dumpFrameEventsLocked(String8& result);
735 
736     void recordBufferingStats(const char* layerName,
737             std::vector<OccupancyTracker::Segment>&& history);
738     void dumpBufferingStats(String8& result) const;
739     void dumpWideColorInfo(String8& result) const;
740     LayersProto dumpProtoInfo(LayerVector::StateSet stateSet) const;
741     LayersProto dumpVisibleLayersProtoInfo(int32_t hwcId) const;
742 
isLayerTripleBufferingDisabled()743     bool isLayerTripleBufferingDisabled() const {
744         return this->mLayerTripleBufferingDisabled;
745     }
746     status_t doDump(int fd, const Vector<String16>& args, bool asProto);
747 
748     /* ------------------------------------------------------------------------
749      * VrFlinger
750      */
751     void resetDisplayState();
752 
753     // Check to see if we should handoff to vr flinger.
754     void updateVrFlinger();
755 
756     void updateColorMatrixLocked();
757 
758     /* ------------------------------------------------------------------------
759      * Attributes
760      */
761 
762     // access must be protected by mStateLock
763     mutable Mutex mStateLock;
764     State mCurrentState{LayerVector::StateSet::Current};
765     volatile int32_t mTransactionFlags;
766     Condition mTransactionCV;
767     bool mTransactionPending;
768     bool mAnimTransactionPending;
769     SortedVector< sp<Layer> > mLayersPendingRemoval;
770 
771     // global color transform states
772     Daltonizer mDaltonizer;
773     float mGlobalSaturationFactor = 1.0f;
774     mat4 mClientColorMatrix;
775 
776     // Can't be unordered_set because wp<> isn't hashable
777     std::set<wp<IBinder>> mGraphicBufferProducerList;
778     size_t mMaxGraphicBufferProducerListSize = MAX_LAYERS;
779 
780     // protected by mStateLock (but we could use another lock)
781     bool mLayersRemoved;
782     bool mLayersAdded;
783 
784     // access must be protected by mInvalidateLock
785     volatile int32_t mRepaintEverything;
786 
787     // constant members (no synchronization needed for access)
788     nsecs_t mBootTime;
789     bool mGpuToCpuSupported;
790     std::unique_ptr<EventThread> mEventThread;
791     std::unique_ptr<EventThread> mSFEventThread;
792     std::unique_ptr<EventThread> mInjectorEventThread;
793     std::unique_ptr<VSyncSource> mEventThreadSource;
794     std::unique_ptr<VSyncSource> mSfEventThreadSource;
795     std::unique_ptr<InjectVSyncSource> mVSyncInjector;
796     std::unique_ptr<EventControlThread> mEventControlThread;
797     sp<IBinder> mBuiltinDisplays[DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES];
798 
799     VSyncModulator mVsyncModulator;
800 
801     // Can only accessed from the main thread, these members
802     // don't need synchronization
803     State mDrawingState{LayerVector::StateSet::Drawing};
804     bool mVisibleRegionsDirty;
805     bool mGeometryInvalid;
806     bool mAnimCompositionPending;
807     std::vector<sp<Layer>> mLayersWithQueuedFrames;
808     sp<Fence> mPreviousPresentFence = Fence::NO_FENCE;
809     bool mHadClientComposition = false;
810 
811     struct HotplugEvent {
812         hwc2_display_t display;
813         HWC2::Connection connection = HWC2::Connection::Invalid;
814     };
815     // protected by mStateLock
816     std::vector<HotplugEvent> mPendingHotplugEvents;
817 
818     // this may only be written from the main thread with mStateLock held
819     // it may be read from other threads with mStateLock held
820     DefaultKeyedVector< wp<IBinder>, sp<DisplayDevice> > mDisplays;
821 
822     // don't use a lock for these, we don't care
823     int mDebugRegion;
824     int mDebugDDMS;
825     int mDebugDisableHWC;
826     int mDebugDisableTransformHint;
827     volatile nsecs_t mDebugInSwapBuffers;
828     nsecs_t mLastSwapBufferTime;
829     volatile nsecs_t mDebugInTransaction;
830     nsecs_t mLastTransactionTime;
831     bool mBootFinished;
832     bool mForceFullDamage;
833     bool mPropagateBackpressure = true;
834     std::unique_ptr<SurfaceInterceptor> mInterceptor =
835             std::make_unique<impl::SurfaceInterceptor>(this);
836     SurfaceTracing mTracing;
837     LayerStats mLayerStats;
838     TimeStats& mTimeStats = TimeStats::getInstance();
839     bool mUseHwcVirtualDisplays = false;
840 
841     // Restrict layers to use two buffers in their bufferqueues.
842     bool mLayerTripleBufferingDisabled = false;
843 
844     // these are thread safe
845     mutable std::unique_ptr<MessageQueue> mEventQueue{std::make_unique<impl::MessageQueue>()};
846     FrameTracker mAnimFrameTracker;
847     DispSync mPrimaryDispSync;
848     int mPrimaryDisplayOrientation = DisplayState::eOrientationDefault;
849 
850     // protected by mDestroyedLayerLock;
851     mutable Mutex mDestroyedLayerLock;
852     Vector<Layer const *> mDestroyedLayers;
853 
854     // protected by mHWVsyncLock
855     Mutex mHWVsyncLock;
856     bool mPrimaryHWVsyncEnabled;
857     bool mHWVsyncAvailable;
858 
859     std::atomic<bool> mRefreshPending{false};
860 
861     /* ------------------------------------------------------------------------
862      * Feature prototyping
863      */
864 
865     bool mInjectVSyncs;
866 
867     // Static screen stats
868     bool mHasPoweredOff;
869 
870     size_t mNumLayers;
871 
872     // Verify that transaction is being called by an approved process:
873     // either AID_GRAPHICS or AID_SYSTEM.
874     status_t CheckTransactCodeCredentials(uint32_t code);
875 
876     std::unique_ptr<dvr::VrFlinger> mVrFlinger;
877     std::atomic<bool> mVrFlingerRequestsDisplay;
878     static bool useVrFlinger;
879     std::thread::id mMainThreadId;
880 
881     DisplayColorSetting mDisplayColorSetting = DisplayColorSetting::MANAGED;
882     // Applied on sRGB layers when the render intent is non-colorimetric.
883     mat4 mLegacySrgbSaturationMatrix;
884 
885     using CreateBufferQueueFunction =
886             std::function<void(sp<IGraphicBufferProducer>* /* outProducer */,
887                                sp<IGraphicBufferConsumer>* /* outConsumer */,
888                                bool /* consumerIsSurfaceFlinger */)>;
889     CreateBufferQueueFunction mCreateBufferQueue;
890 
891     using CreateNativeWindowSurfaceFunction =
892             std::function<std::unique_ptr<NativeWindowSurface>(const sp<IGraphicBufferProducer>&)>;
893     CreateNativeWindowSurfaceFunction mCreateNativeWindowSurface;
894 
895     SurfaceFlingerBE mBE;
896 };
897 }; // namespace android
898 
899 #endif // ANDROID_SURFACE_FLINGER_H
900