• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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     status_t clearLayerFrameStats(const sp<const Client>& client, const sp<IBinder>& handle);
347 
348     status_t getLayerFrameStats(const sp<const Client>& client, const sp<IBinder>& handle, FrameStats* outStats);
349 
350     sp<Layer> fromHandle(const sp<IBinder>& handle) REQUIRES(mStateLock);
351 
352 private:
353     friend class Client;
354     friend class DisplayEventConnection;
355     friend class impl::EventThread;
356     friend class Layer;
357     friend class BufferLayer;
358     friend class MonitoredProducer;
359 
360     // For unit tests
361     friend class TestableSurfaceFlinger;
362 
363     // This value is specified in number of frames.  Log frame stats at most
364     // every half hour.
365     enum { LOG_FRAME_STATS_PERIOD =  30*60*60 };
366 
367     static const size_t MAX_LAYERS = 4096;
368 
369     // We're reference counted, never destroy SurfaceFlinger directly
370     virtual ~SurfaceFlinger();
371 
372     /* ------------------------------------------------------------------------
373      * Internal data structures
374      */
375 
376     class State {
377     public:
State(LayerVector::StateSet set)378         explicit State(LayerVector::StateSet set) : stateSet(set), layersSortedByZ(set) {}
379         State& operator=(const State& other) {
380             // We explicitly don't copy stateSet so that, e.g., mDrawingState
381             // always uses the Drawing StateSet.
382             layersSortedByZ = other.layersSortedByZ;
383             displays = other.displays;
384             colorMatrixChanged = other.colorMatrixChanged;
385             if (colorMatrixChanged) {
386                 colorMatrix = other.colorMatrix;
387             }
388             return *this;
389         }
390 
391         const LayerVector::StateSet stateSet = LayerVector::StateSet::Invalid;
392         LayerVector layersSortedByZ;
393         DefaultKeyedVector< wp<IBinder>, DisplayDeviceState> displays;
394 
395         bool colorMatrixChanged = true;
396         mat4 colorMatrix;
397 
398         void traverseInZOrder(const LayerVector::Visitor& visitor) const;
399         void traverseInReverseZOrder(const LayerVector::Visitor& visitor) const;
400     };
401 
402     /* ------------------------------------------------------------------------
403      * IBinder interface
404      */
405     virtual status_t onTransact(uint32_t code, const Parcel& data,
406         Parcel* reply, uint32_t flags);
dump(int fd,const Vector<String16> & args)407     virtual status_t dump(int fd, const Vector<String16>& args) { return priorityDump(fd, args); }
408 
409     /* ------------------------------------------------------------------------
410      * ISurfaceComposer interface
411      */
412     virtual sp<ISurfaceComposerClient> createConnection();
413     virtual sp<ISurfaceComposerClient> createScopedConnection(const sp<IGraphicBufferProducer>& gbp);
414     virtual sp<IBinder> createDisplay(const String8& displayName, bool secure);
415     virtual void destroyDisplay(const sp<IBinder>& display);
416     virtual sp<IBinder> getBuiltInDisplay(int32_t id);
417     virtual void setTransactionState(const Vector<ComposerState>& state,
418             const Vector<DisplayState>& displays, uint32_t flags);
419     virtual void bootFinished();
420     virtual bool authenticateSurfaceTexture(
421         const sp<IGraphicBufferProducer>& bufferProducer) const;
422     virtual status_t getSupportedFrameTimestamps(
423             std::vector<FrameEvent>* outSupported) const;
424     virtual sp<IDisplayEventConnection> createDisplayEventConnection(
425             ISurfaceComposer::VsyncSource vsyncSource = eVsyncSourceApp);
426     virtual status_t captureScreen(const sp<IBinder>& display, sp<GraphicBuffer>* outBuffer,
427                                    bool& outCapturedSecureLayers,
428                                    Rect sourceCrop, uint32_t reqWidth, uint32_t reqHeight,
429                                    int32_t minLayerZ, int32_t maxLayerZ, bool useIdentityTransform,
430                                    ISurfaceComposer::Rotation rotation, bool captureSecureLayers);
431     virtual status_t captureLayers(const sp<IBinder>& parentHandle, sp<GraphicBuffer>* outBuffer,
432                                    const Rect& sourceCrop, float frameScale, bool childrenOnly);
433     virtual status_t getDisplayStats(const sp<IBinder>& display,
434             DisplayStatInfo* stats);
435     virtual status_t getDisplayConfigs(const sp<IBinder>& display,
436             Vector<DisplayInfo>* configs);
437     virtual int getActiveConfig(const sp<IBinder>& display);
438     virtual status_t getDisplayColorModes(const sp<IBinder>& display,
439             Vector<ui::ColorMode>* configs);
440     virtual ui::ColorMode getActiveColorMode(const sp<IBinder>& display);
441     virtual status_t setActiveColorMode(const sp<IBinder>& display, ui::ColorMode colorMode);
442     virtual void setPowerMode(const sp<IBinder>& display, int mode);
443     virtual status_t setActiveConfig(const sp<IBinder>& display, int id);
444     virtual status_t clearAnimationFrameStats();
445     virtual status_t getAnimationFrameStats(FrameStats* outStats) const;
446     virtual status_t getHdrCapabilities(const sp<IBinder>& display,
447             HdrCapabilities* outCapabilities) const;
448     virtual status_t enableVSyncInjections(bool enable);
449     virtual status_t injectVSync(nsecs_t when);
450     virtual status_t getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers);
451 
452 
453     /* ------------------------------------------------------------------------
454      * DeathRecipient interface
455      */
456     virtual void binderDied(const wp<IBinder>& who);
457 
458     /* ------------------------------------------------------------------------
459      * RefBase interface
460      */
461     virtual void onFirstRef();
462 
463     /* ------------------------------------------------------------------------
464      * HWC2::ComposerCallback / HWComposer::EventHandler interface
465      */
466     void onVsyncReceived(int32_t sequenceId, hwc2_display_t display,
467                          int64_t timestamp) override;
468     void onHotplugReceived(int32_t sequenceId, hwc2_display_t display,
469                            HWC2::Connection connection) override;
470     void onRefreshReceived(int32_t sequenceId, hwc2_display_t display) override;
471 
472     /* ------------------------------------------------------------------------
473      * Message handling
474      */
475     void waitForEvent();
476     // Can only be called from the main thread or with mStateLock held
477     void signalTransaction();
478     // Can only be called from the main thread or with mStateLock held
479     void signalLayerUpdate();
480     void signalRefresh();
481 
482     // called on the main thread in response to initializeDisplays()
483     void onInitializeDisplays();
484     // called on the main thread in response to setActiveConfig()
485     void setActiveConfigInternal(const sp<DisplayDevice>& hw, int mode);
486     // called on the main thread in response to setPowerMode()
487     void setPowerModeInternal(const sp<DisplayDevice>& hw, int mode,
488                               bool stateLockHeld);
489 
490     // Called on the main thread in response to setActiveColorMode()
491     void setActiveColorModeInternal(const sp<DisplayDevice>& hw,
492                                     ui::ColorMode colorMode,
493                                     ui::Dataspace dataSpace,
494                                     ui::RenderIntent renderIntent);
495 
496     // Returns whether the transaction actually modified any state
497     bool handleMessageTransaction();
498 
499     // Returns whether a new buffer has been latched (see handlePageFlip())
500     bool handleMessageInvalidate();
501 
502     void handleMessageRefresh();
503 
504     void handleTransaction(uint32_t transactionFlags);
505     void handleTransactionLocked(uint32_t transactionFlags);
506 
507     void updateCursorAsync();
508 
509     /* handlePageFlip - latch a new buffer if available and compute the dirty
510      * region. Returns whether a new buffer has been latched, i.e., whether it
511      * is necessary to perform a refresh during this vsync.
512      */
513     bool handlePageFlip();
514 
515     /* ------------------------------------------------------------------------
516      * Transactions
517      */
518     uint32_t getTransactionFlags(uint32_t flags);
519     uint32_t peekTransactionFlags();
520     // Can only be called from the main thread or with mStateLock held
521     uint32_t setTransactionFlags(uint32_t flags);
522     uint32_t setTransactionFlags(uint32_t flags, VSyncModulator::TransactionStart transactionStart);
523     void commitTransaction();
524     bool containsAnyInvalidClientState(const Vector<ComposerState>& states);
525     uint32_t setClientStateLocked(const ComposerState& composerState) REQUIRES(mStateLock);
526     uint32_t setDisplayStateLocked(const DisplayState& s);
527     void setDestroyStateLocked(const ComposerState& composerState) REQUIRES(mStateLock);
528 
529     /* ------------------------------------------------------------------------
530      * Layer management
531      */
532     status_t createLayer(const String8& name, const sp<Client>& client, uint32_t w, uint32_t h,
533                          PixelFormat format, uint32_t flags, int32_t windowType, int32_t ownerUid,
534                          sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp,
535                          const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer = nullptr);
536 
537     status_t createBufferLayer(const sp<Client>& client, const String8& name,
538             uint32_t w, uint32_t h, uint32_t flags, PixelFormat& format,
539             sp<IBinder>* outHandle, sp<IGraphicBufferProducer>* outGbp,
540             sp<Layer>* outLayer);
541 
542     status_t createColorLayer(const sp<Client>& client, const String8& name,
543             uint32_t w, uint32_t h, uint32_t flags, sp<IBinder>* outHandle,
544             sp<Layer>* outLayer);
545 
546     String8 getUniqueLayerName(const String8& name);
547 
548     // called in response to the window-manager calling
549     // ISurfaceComposerClient::destroySurface()
550     status_t onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle);
551 
552     // called when all clients have released all their references to
553     // this layer meaning it is entirely safe to destroy all
554     // resources associated to this layer.
555     status_t onLayerDestroyed(const wp<Layer>& layer);
556 
557     // remove a layer from SurfaceFlinger immediately
558     status_t removeLayer(const sp<Layer>& layer, bool topLevelOnly = false);
559     status_t removeLayerLocked(const Mutex&, const sp<Layer>& layer, bool topLevelOnly = false);
560 
561     // remove layer from mapping
562     status_t removeLayerFromMap(const wp<Layer>& layer);
563 
564     // add a layer to SurfaceFlinger
565     status_t addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
566                             const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
567                             const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer);
568 
569     /* ------------------------------------------------------------------------
570      * Boot animation, on/off animations and screen capture
571      */
572 
573     void startBootAnim();
574 
575     void renderScreenImplLocked(const RenderArea& renderArea, TraverseLayersFunction traverseLayers,
576                                 bool yswap, bool useIdentityTransform);
577     status_t captureScreenCommon(RenderArea& renderArea, TraverseLayersFunction traverseLayers,
578                                  sp<GraphicBuffer>* outBuffer,
579                                  bool useIdentityTransform, bool& outCapturedSecureLayers);
580     status_t captureScreenImplLocked(const RenderArea& renderArea,
581                                      TraverseLayersFunction traverseLayers,
582                                      ANativeWindowBuffer* buffer, bool useIdentityTransform,
583                                      bool forSystem, int* outSyncFd, bool& outCapturedSecureLayers);
584     void traverseLayersInDisplay(const sp<const DisplayDevice>& display, int32_t minLayerZ,
585                                  int32_t maxLayerZ, const LayerVector::Visitor& visitor);
586 
587     sp<StartPropertySetThread> mStartPropertySetThread = nullptr;
588 
589     /* ------------------------------------------------------------------------
590      * Properties
591      */
592     void readPersistentProperties();
593 
594     /* ------------------------------------------------------------------------
595      * EGL
596      */
597     size_t getMaxTextureSize() const;
598     size_t getMaxViewportDims() const;
599 
600     /* ------------------------------------------------------------------------
601      * Display and layer stack management
602      */
603     // called when starting, or restarting after system_server death
604     void initializeDisplays();
605 
getDisplayDevice(const wp<IBinder> & dpy)606     sp<const DisplayDevice> getDisplayDevice(const wp<IBinder>& dpy) const {
607       Mutex::Autolock _l(mStateLock);
608       return getDisplayDeviceLocked(dpy);
609     }
610 
getDisplayDevice(const wp<IBinder> & dpy)611     sp<DisplayDevice> getDisplayDevice(const wp<IBinder>& dpy) {
612       Mutex::Autolock _l(mStateLock);
613       return getDisplayDeviceLocked(dpy);
614     }
615 
616     // NOTE: can only be called from the main thread or with mStateLock held
getDisplayDeviceLocked(const wp<IBinder> & dpy)617     sp<const DisplayDevice> getDisplayDeviceLocked(const wp<IBinder>& dpy) const {
618         return mDisplays.valueFor(dpy);
619     }
620 
621     // NOTE: can only be called from the main thread or with mStateLock held
getDisplayDeviceLocked(const wp<IBinder> & dpy)622     sp<DisplayDevice> getDisplayDeviceLocked(const wp<IBinder>& dpy) {
623         return mDisplays.valueFor(dpy);
624     }
625 
getDefaultDisplayDeviceLocked()626     sp<const DisplayDevice> getDefaultDisplayDeviceLocked() const {
627         return getDisplayDeviceLocked(mBuiltinDisplays[DisplayDevice::DISPLAY_PRIMARY]);
628     }
629 
getDisplayType(const sp<IBinder> & display)630     int32_t getDisplayType(const sp<IBinder>& display) {
631         if (!display.get()) return NAME_NOT_FOUND;
632         for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
633             if (display == mBuiltinDisplays[i]) {
634                 return i;
635             }
636         }
637         return NAME_NOT_FOUND;
638     }
639 
640     // mark a region of a layer stack dirty. this updates the dirty
641     // region of all screens presenting this layer stack.
642     void invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty);
643 
644     /* ------------------------------------------------------------------------
645      * H/W composer
646      */
647 
getHwComposer()648     HWComposer& getHwComposer() const { return *getBE().mHwc; }
649 
650     /* ------------------------------------------------------------------------
651      * Compositing
652      */
653     void invalidateHwcGeometry();
654     void computeVisibleRegions(const sp<const DisplayDevice>& displayDevice,
655             Region& dirtyRegion, Region& opaqueRegion);
656 
657     void preComposition(nsecs_t refreshStartTime);
658     void postComposition(nsecs_t refreshStartTime);
659     void updateCompositorTiming(
660             nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
661             std::shared_ptr<FenceTime>& presentFenceTime);
662     void setCompositorTimingSnapped(
663             nsecs_t vsyncPhase, nsecs_t vsyncInterval,
664             nsecs_t compositeToPresentLatency);
665     void rebuildLayerStacks();
666 
667     ui::Dataspace getBestDataspace(const sp<const DisplayDevice>& displayDevice,
668                                    ui::Dataspace* outHdrDataSpace) const;
669 
670     // Returns the appropriate ColorMode, Dataspace and RenderIntent for the
671     // DisplayDevice. The function only returns the supported ColorMode,
672     // Dataspace and RenderIntent.
673     void pickColorMode(const sp<DisplayDevice>& displayDevice,
674                        ui::ColorMode* outMode,
675                        ui::Dataspace* outDataSpace,
676                        ui::RenderIntent* outRenderIntent) const;
677 
678     void setUpHWComposer();
679     void doComposition();
680     void doDebugFlashRegions();
681     void doTracing(const char* where);
682     void logLayerStats();
683     void doDisplayComposition(const sp<const DisplayDevice>& displayDevice, const Region& dirtyRegion);
684 
685     // compose surfaces for display hw. this fails if using GL and the surface
686     // has been destroyed and is no longer valid.
687     bool doComposeSurfaces(const sp<const DisplayDevice>& displayDevice);
688 
689     void postFramebuffer();
690     void drawWormhole(const sp<const DisplayDevice>& displayDevice, const Region& region) const;
691 
692     /* ------------------------------------------------------------------------
693      * Display management
694      */
695     DisplayDevice::DisplayType determineDisplayType(hwc2_display_t display,
696             HWC2::Connection connection) const;
697     sp<DisplayDevice> setupNewDisplayDeviceInternal(const wp<IBinder>& display, int hwcId,
698                                                     const DisplayDeviceState& state,
699                                                     const sp<DisplaySurface>& dispSurface,
700                                                     const sp<IGraphicBufferProducer>& producer);
701     void processDisplayChangesLocked();
702     void processDisplayHotplugEventsLocked();
703 
704     /* ------------------------------------------------------------------------
705      * VSync
706      */
707     void enableHardwareVsync();
708     void resyncToHardwareVsync(bool makeAvailable);
709     void disableHardwareVsync(bool makeUnavailable);
710 
711 public:
712     void resyncWithRateLimit();
713     void getCompositorTiming(CompositorTiming* compositorTiming);
714 private:
715 
716     /* ------------------------------------------------------------------------
717      * Debugging & dumpsys
718      */
719 public:
dumpCritical(int fd,const Vector<String16> &,bool asProto)720     status_t dumpCritical(int fd, const Vector<String16>& /*args*/, bool asProto) {
721         return doDump(fd, Vector<String16>(), asProto);
722     }
723 
dumpAll(int fd,const Vector<String16> & args,bool asProto)724     status_t dumpAll(int fd, const Vector<String16>& args, bool asProto) {
725         return doDump(fd, args, asProto);
726     }
727 
728 private:
729     void listLayersLocked(const Vector<String16>& args, size_t& index, String8& result) const;
730     void dumpStatsLocked(const Vector<String16>& args, size_t& index, String8& result) const;
731     void clearStatsLocked(const Vector<String16>& args, size_t& index, String8& result);
732     void dumpAllLocked(const Vector<String16>& args, size_t& index, String8& result) const;
733     bool startDdmConnection();
734     void appendSfConfigString(String8& result) const;
735     void checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
736                          TraverseLayersFunction traverseLayers);
737 
738     void logFrameStats();
739 
740     void dumpStaticScreenStats(String8& result) const;
741     // Not const because each Layer needs to query Fences and cache timestamps.
742     void dumpFrameEventsLocked(String8& result);
743 
744     void recordBufferingStats(const char* layerName,
745             std::vector<OccupancyTracker::Segment>&& history);
746     void dumpBufferingStats(String8& result) const;
747     void dumpWideColorInfo(String8& result) const;
748     LayersProto dumpProtoInfo(LayerVector::StateSet stateSet) const;
749     LayersProto dumpVisibleLayersProtoInfo(int32_t hwcId) const;
750 
isLayerTripleBufferingDisabled()751     bool isLayerTripleBufferingDisabled() const {
752         return this->mLayerTripleBufferingDisabled;
753     }
754     status_t doDump(int fd, const Vector<String16>& args, bool asProto);
755 
756     /* ------------------------------------------------------------------------
757      * VrFlinger
758      */
759     void resetDisplayState();
760 
761     // Check to see if we should handoff to vr flinger.
762     void updateVrFlinger();
763 
764     void updateColorMatrixLocked();
765 
766     /* ------------------------------------------------------------------------
767      * Attributes
768      */
769 
770     // access must be protected by mStateLock
771     mutable Mutex mStateLock;
772     State mCurrentState{LayerVector::StateSet::Current};
773     volatile int32_t mTransactionFlags;
774     Condition mTransactionCV;
775     bool mTransactionPending;
776     bool mAnimTransactionPending;
777     SortedVector< sp<Layer> > mLayersPendingRemoval;
778 
779     // global color transform states
780     Daltonizer mDaltonizer;
781     float mGlobalSaturationFactor = 1.0f;
782     mat4 mClientColorMatrix;
783 
784     // Can't be unordered_set because wp<> isn't hashable
785     std::set<wp<IBinder>> mGraphicBufferProducerList;
786     size_t mMaxGraphicBufferProducerListSize = MAX_LAYERS;
787 
788     // protected by mStateLock (but we could use another lock)
789     bool mLayersRemoved;
790     bool mLayersAdded;
791 
792     // access must be protected by mInvalidateLock
793     volatile int32_t mRepaintEverything;
794 
795     // constant members (no synchronization needed for access)
796     nsecs_t mBootTime;
797     bool mGpuToCpuSupported;
798     std::unique_ptr<EventThread> mEventThread;
799     std::unique_ptr<EventThread> mSFEventThread;
800     std::unique_ptr<EventThread> mInjectorEventThread;
801     std::unique_ptr<VSyncSource> mEventThreadSource;
802     std::unique_ptr<VSyncSource> mSfEventThreadSource;
803     std::unique_ptr<InjectVSyncSource> mVSyncInjector;
804     std::unique_ptr<EventControlThread> mEventControlThread;
805     sp<IBinder> mBuiltinDisplays[DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES];
806 
807     VSyncModulator mVsyncModulator;
808 
809     // Can only accessed from the main thread, these members
810     // don't need synchronization
811     State mDrawingState{LayerVector::StateSet::Drawing};
812     bool mVisibleRegionsDirty;
813     bool mGeometryInvalid;
814     bool mAnimCompositionPending;
815     std::vector<sp<Layer>> mLayersWithQueuedFrames;
816     sp<Fence> mPreviousPresentFence = Fence::NO_FENCE;
817     bool mHadClientComposition = false;
818 
819     struct HotplugEvent {
820         hwc2_display_t display;
821         HWC2::Connection connection = HWC2::Connection::Invalid;
822     };
823     // protected by mStateLock
824     std::vector<HotplugEvent> mPendingHotplugEvents;
825 
826     // this may only be written from the main thread with mStateLock held
827     // it may be read from other threads with mStateLock held
828     DefaultKeyedVector< wp<IBinder>, sp<DisplayDevice> > mDisplays;
829 
830     // protected by mStateLock
831     std::unordered_map<BBinder*, wp<Layer>> mLayersByLocalBinderToken;
832 
833     // don't use a lock for these, we don't care
834     int mDebugRegion;
835     int mDebugDDMS;
836     int mDebugDisableHWC;
837     int mDebugDisableTransformHint;
838     volatile nsecs_t mDebugInSwapBuffers;
839     nsecs_t mLastSwapBufferTime;
840     volatile nsecs_t mDebugInTransaction;
841     nsecs_t mLastTransactionTime;
842     bool mBootFinished;
843     bool mForceFullDamage;
844     bool mPropagateBackpressure = true;
845     std::unique_ptr<SurfaceInterceptor> mInterceptor =
846             std::make_unique<impl::SurfaceInterceptor>(this);
847     SurfaceTracing mTracing;
848     LayerStats mLayerStats;
849     TimeStats& mTimeStats = TimeStats::getInstance();
850     bool mUseHwcVirtualDisplays = false;
851 
852     // Restrict layers to use two buffers in their bufferqueues.
853     bool mLayerTripleBufferingDisabled = false;
854 
855     // these are thread safe
856     mutable std::unique_ptr<MessageQueue> mEventQueue{std::make_unique<impl::MessageQueue>()};
857     FrameTracker mAnimFrameTracker;
858     DispSync mPrimaryDispSync;
859     int mPrimaryDisplayOrientation = DisplayState::eOrientationDefault;
860 
861     // protected by mDestroyedLayerLock;
862     mutable Mutex mDestroyedLayerLock;
863     Vector<Layer const *> mDestroyedLayers;
864 
865     // protected by mHWVsyncLock
866     Mutex mHWVsyncLock;
867     bool mPrimaryHWVsyncEnabled;
868     bool mHWVsyncAvailable;
869 
870     std::atomic<bool> mRefreshPending{false};
871 
872     /* ------------------------------------------------------------------------
873      * Feature prototyping
874      */
875 
876     bool mInjectVSyncs;
877 
878     // Static screen stats
879     bool mHasPoweredOff;
880 
881     size_t mNumLayers;
882 
883     // Verify that transaction is being called by an approved process:
884     // either AID_GRAPHICS or AID_SYSTEM.
885     status_t CheckTransactCodeCredentials(uint32_t code);
886 
887     std::unique_ptr<dvr::VrFlinger> mVrFlinger;
888     std::atomic<bool> mVrFlingerRequestsDisplay;
889     static bool useVrFlinger;
890     std::thread::id mMainThreadId;
891 
892     DisplayColorSetting mDisplayColorSetting = DisplayColorSetting::MANAGED;
893     // Applied on sRGB layers when the render intent is non-colorimetric.
894     mat4 mLegacySrgbSaturationMatrix;
895 
896     using CreateBufferQueueFunction =
897             std::function<void(sp<IGraphicBufferProducer>* /* outProducer */,
898                                sp<IGraphicBufferConsumer>* /* outConsumer */,
899                                bool /* consumerIsSurfaceFlinger */)>;
900     CreateBufferQueueFunction mCreateBufferQueue;
901 
902     using CreateNativeWindowSurfaceFunction =
903             std::function<std::unique_ptr<NativeWindowSurface>(const sp<IGraphicBufferProducer>&)>;
904     CreateNativeWindowSurfaceFunction mCreateNativeWindowSurface;
905 
906     SurfaceFlingerBE mBE;
907 };
908 }; // namespace android
909 
910 #endif // ANDROID_SURFACE_FLINGER_H
911