SurfaceFlinger.h 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201
  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. #pragma once
  17. #include <sys/types.h>
  18. /*
  19. * NOTE: Make sure this file doesn't include anything from <gl/ > or <gl2/ >
  20. */
  21. #include <android-base/thread_annotations.h>
  22. #include <cutils/atomic.h>
  23. #include <cutils/compiler.h>
  24. #include <gui/BufferQueue.h>
  25. #include <gui/FrameTimestamps.h>
  26. #include <gui/ISurfaceComposer.h>
  27. #include <gui/ISurfaceComposerClient.h>
  28. #include <gui/LayerState.h>
  29. #include <gui/OccupancyTracker.h>
  30. #include <hardware/hwcomposer_defs.h>
  31. #include <input/ISetInputWindowsListener.h>
  32. #include <layerproto/LayerProtoHeader.h>
  33. #include <math/mat4.h>
  34. #include <serviceutils/PriorityDumper.h>
  35. #include <system/graphics.h>
  36. #include <ui/FenceTime.h>
  37. #include <ui/PixelFormat.h>
  38. #include <utils/Errors.h>
  39. #include <utils/KeyedVector.h>
  40. #include <utils/RefBase.h>
  41. #include <utils/SortedVector.h>
  42. #include <utils/Trace.h>
  43. #include <utils/threads.h>
  44. #include "ClientCache.h"
  45. #include "DisplayDevice.h"
  46. #include "DisplayHardware/HWC2.h"
  47. #include "DisplayHardware/PowerAdvisor.h"
  48. #include "Effects/Daltonizer.h"
  49. #include "FrameTracker.h"
  50. #include "LayerStats.h"
  51. #include "LayerVector.h"
  52. #include "Scheduler/RefreshRateConfigs.h"
  53. #include "Scheduler/RefreshRateStats.h"
  54. #include "Scheduler/Scheduler.h"
  55. #include "Scheduler/VSyncModulator.h"
  56. #include "SurfaceFlingerFactory.h"
  57. #include "SurfaceTracing.h"
  58. #include "TransactionCompletedThread.h"
  59. #include <atomic>
  60. #include <cstdint>
  61. #include <functional>
  62. #include <map>
  63. #include <memory>
  64. #include <mutex>
  65. #include <queue>
  66. #include <set>
  67. #include <string>
  68. #include <thread>
  69. #include <type_traits>
  70. #include <unordered_map>
  71. #include <unordered_set>
  72. #include <utility>
  73. using namespace android::surfaceflinger;
  74. namespace android {
  75. class Client;
  76. class EventThread;
  77. class HWComposer;
  78. class IGraphicBufferProducer;
  79. class IInputFlinger;
  80. class InjectVSyncSource;
  81. class Layer;
  82. class MessageBase;
  83. class RefreshRateOverlay;
  84. class RegionSamplingThread;
  85. class TimeStats;
  86. namespace compositionengine {
  87. class DisplaySurface;
  88. } // namespace compositionengine
  89. namespace renderengine {
  90. class RenderEngine;
  91. } // namespace renderengine
  92. namespace dvr {
  93. class VrFlinger;
  94. } // namespace dvr
  95. enum {
  96. eTransactionNeeded = 0x01,
  97. eTraversalNeeded = 0x02,
  98. eDisplayTransactionNeeded = 0x04,
  99. eDisplayLayerStackChanged = 0x08,
  100. eTransactionFlushNeeded = 0x10,
  101. eTransactionMask = 0x1f,
  102. };
  103. enum class DisplayColorSetting : int32_t {
  104. MANAGED = 0,
  105. UNMANAGED = 1,
  106. ENHANCED = 2,
  107. };
  108. class SurfaceFlingerBE
  109. {
  110. public:
  111. SurfaceFlingerBE();
  112. const std::string mHwcServiceName; // "default" for real use, something else for testing.
  113. FenceTimeline mGlCompositionDoneTimeline;
  114. FenceTimeline mDisplayTimeline;
  115. // protected by mCompositorTimingLock;
  116. mutable std::mutex mCompositorTimingLock;
  117. CompositorTiming mCompositorTiming;
  118. // Only accessed from the main thread.
  119. struct CompositePresentTime {
  120. nsecs_t composite = -1;
  121. std::shared_ptr<FenceTime> display = FenceTime::NO_FENCE;
  122. };
  123. std::queue<CompositePresentTime> mCompositePresentTimes;
  124. static const size_t NUM_BUCKETS = 8; // < 1-7, 7+
  125. nsecs_t mFrameBuckets[NUM_BUCKETS] = {};
  126. nsecs_t mTotalTime = 0;
  127. std::atomic<nsecs_t> mLastSwapTime = 0;
  128. // Double- vs. triple-buffering stats
  129. struct BufferingStats {
  130. size_t numSegments = 0;
  131. nsecs_t totalTime = 0;
  132. // "Two buffer" means that a third buffer was never used, whereas
  133. // "double-buffered" means that on average the segment only used two
  134. // buffers (though it may have used a third for some part of the
  135. // segment)
  136. nsecs_t twoBufferTime = 0;
  137. nsecs_t doubleBufferedTime = 0;
  138. nsecs_t tripleBufferedTime = 0;
  139. };
  140. mutable Mutex mBufferingStatsMutex;
  141. std::unordered_map<std::string, BufferingStats> mBufferingStats;
  142. // The composer sequence id is a monotonically increasing integer that we
  143. // use to differentiate callbacks from different hardware composer
  144. // instances. Each hardware composer instance gets a different sequence id.
  145. int32_t mComposerSequenceId = 0;
  146. };
  147. class SurfaceFlinger : public BnSurfaceComposer,
  148. public PriorityDumper,
  149. public ClientCache::ErasedRecipient,
  150. private IBinder::DeathRecipient,
  151. private HWC2::ComposerCallback {
  152. public:
  153. SurfaceFlingerBE& getBE() { return mBE; }
  154. const SurfaceFlingerBE& getBE() const { return mBE; }
  155. // This is the phase offset in nanoseconds of the software vsync event
  156. // relative to the vsync event reported by HWComposer. The software vsync
  157. // event is when SurfaceFlinger and Choreographer-based applications run each
  158. // frame.
  159. //
  160. // This phase offset allows adjustment of the minimum latency from application
  161. // wake-up time (by Choreographer) to the time at which the resulting window
  162. // image is displayed. This value may be either positive (after the HW vsync)
  163. // or negative (before the HW vsync). Setting it to 0 will result in a lower
  164. // latency bound of two vsync periods because the app and SurfaceFlinger
  165. // will run just after the HW vsync. Setting it to a positive number will
  166. // result in the minimum latency being:
  167. //
  168. // (2 * VSYNC_PERIOD - (vsyncPhaseOffsetNs % VSYNC_PERIOD))
  169. //
  170. // Note that reducing this latency makes it more likely for the applications
  171. // to not have their window content image ready in time. When this happens
  172. // the latency will end up being an additional vsync period, and animations
  173. // will hiccup. Therefore, this latency should be tuned somewhat
  174. // conservatively (or at least with awareness of the trade-off being made).
  175. static int64_t vsyncPhaseOffsetNs;
  176. static int64_t sfVsyncPhaseOffsetNs;
  177. // If fences from sync Framework are supported.
  178. static bool hasSyncFramework;
  179. // The offset in nanoseconds to use when DispSync timestamps present fence
  180. // signaling time.
  181. static int64_t dispSyncPresentTimeOffset;
  182. // Some hardware can do RGB->YUV conversion more efficiently in hardware
  183. // controlled by HWC than in hardware controlled by the video encoder.
  184. // This instruct VirtualDisplaySurface to use HWC for such conversion on
  185. // GL composition.
  186. static bool useHwcForRgbToYuv;
  187. // Maximum dimension supported by HWC for virtual display.
  188. // Equal to min(max_height, max_width).
  189. static uint64_t maxVirtualDisplaySize;
  190. // Controls the number of buffers SurfaceFlinger will allocate for use in
  191. // FramebufferSurface
  192. static int64_t maxFrameBufferAcquiredBuffers;
  193. // Indicate if a device has wide color gamut display. This is typically
  194. // found on devices with wide color gamut (e.g. Display-P3) display.
  195. static bool hasWideColorDisplay;
  196. static int primaryDisplayOrientation;
  197. // Indicate if device wants color management on its display.
  198. static bool useColorManagement;
  199. static bool useContextPriority;
  200. // The data space and pixel format that SurfaceFlinger expects hardware composer
  201. // to composite efficiently. Meaning under most scenarios, hardware composer
  202. // will accept layers with the data space and pixel format.
  203. static ui::Dataspace defaultCompositionDataspace;
  204. static ui::PixelFormat defaultCompositionPixelFormat;
  205. // The data space and pixel format that SurfaceFlinger expects hardware composer
  206. // to composite efficiently for wide color gamut surfaces. Meaning under most scenarios,
  207. // hardware composer will accept layers with the data space and pixel format.
  208. static ui::Dataspace wideColorGamutCompositionDataspace;
  209. static ui::PixelFormat wideColorGamutCompositionPixelFormat;
  210. static char const* getServiceName() ANDROID_API {
  211. return "SurfaceFlinger";
  212. }
  213. struct SkipInitializationTag {};
  214. static constexpr SkipInitializationTag SkipInitialization;
  215. SurfaceFlinger(surfaceflinger::Factory&, SkipInitializationTag) ANDROID_API;
  216. explicit SurfaceFlinger(surfaceflinger::Factory&) ANDROID_API;
  217. // must be called before clients can connect
  218. void init() ANDROID_API;
  219. // starts SurfaceFlinger main loop in the current thread
  220. void run() ANDROID_API;
  221. // post an asynchronous message to the main thread
  222. status_t postMessageAsync(const sp<MessageBase>& msg, nsecs_t reltime = 0, uint32_t flags = 0);
  223. // post a synchronous message to the main thread
  224. status_t postMessageSync(const sp<MessageBase>& msg, nsecs_t reltime = 0, uint32_t flags = 0);
  225. // force full composition on all displays
  226. void repaintEverything();
  227. // force full composition on all displays without resetting the scheduler idle timer.
  228. void repaintEverythingForHWC();
  229. surfaceflinger::Factory& getFactory() { return mFactory; }
  230. // The CompositionEngine encapsulates all composition related interfaces and actions.
  231. compositionengine::CompositionEngine& getCompositionEngine() const;
  232. // returns the default Display
  233. sp<const DisplayDevice> getDefaultDisplayDevice() {
  234. Mutex::Autolock _l(mStateLock);
  235. return getDefaultDisplayDeviceLocked();
  236. }
  237. // Obtains a name from the texture pool, or, if the pool is empty, posts a
  238. // synchronous message to the main thread to obtain one on the fly
  239. uint32_t getNewTexture();
  240. // utility function to delete a texture on the main thread
  241. void deleteTextureAsync(uint32_t texture);
  242. // enable/disable h/w composer event
  243. // TODO: this should be made accessible only to EventThread
  244. void setPrimaryVsyncEnabled(bool enabled);
  245. // main thread function to enable/disable h/w composer event
  246. void setPrimaryVsyncEnabledInternal(bool enabled);
  247. // called on the main thread by MessageQueue when an internal message
  248. // is received
  249. // TODO: this should be made accessible only to MessageQueue
  250. void onMessageReceived(int32_t what);
  251. // populates the expected present time for this frame.
  252. // When we are in negative offsets, we perform a correction so that the
  253. // predicted vsync for the *next* frame is used instead.
  254. void populateExpectedPresentTime();
  255. nsecs_t getExpectedPresentTime() const { return mExpectedPresentTime; }
  256. // for debugging only
  257. // TODO: this should be made accessible only to HWComposer
  258. const Vector<sp<Layer>>& getLayerSortedByZForHwcDisplay(DisplayId displayId);
  259. renderengine::RenderEngine& getRenderEngine() const;
  260. bool authenticateSurfaceTextureLocked(
  261. const sp<IGraphicBufferProducer>& bufferProducer) const;
  262. inline void onLayerCreated() { mNumLayers++; }
  263. inline void onLayerDestroyed(Layer* layer) {
  264. mNumLayers--;
  265. mOffscreenLayers.erase(layer);
  266. }
  267. TransactionCompletedThread& getTransactionCompletedThread() {
  268. return mTransactionCompletedThread;
  269. }
  270. sp<Layer> fromHandle(const sp<IBinder>& handle) REQUIRES(mStateLock);
  271. // Inherit from ClientCache::ErasedRecipient
  272. void bufferErased(const client_cache_t& clientCacheId) override;
  273. status_t enterSelf();
  274. status_t exitSelf();
  275. private:
  276. friend class BufferLayer;
  277. friend class BufferQueueLayer;
  278. friend class BufferStateLayer;
  279. friend class Client;
  280. friend class Layer;
  281. friend class MonitoredProducer;
  282. friend class RefreshRateOverlay;
  283. friend class RegionSamplingThread;
  284. friend class SurfaceTracing;
  285. // For unit tests
  286. friend class TestableSurfaceFlinger;
  287. // This value is specified in number of frames. Log frame stats at most
  288. // every half hour.
  289. enum { LOG_FRAME_STATS_PERIOD = 30*60*60 };
  290. static const size_t MAX_LAYERS = 4096;
  291. static const int MAX_TRACING_MEMORY = 100 * 1024 * 1024; // 100MB
  292. // We're reference counted, never destroy SurfaceFlinger directly
  293. virtual ~SurfaceFlinger();
  294. /* ------------------------------------------------------------------------
  295. * Internal data structures
  296. */
  297. class State {
  298. public:
  299. explicit State(LayerVector::StateSet set) : stateSet(set), layersSortedByZ(set) {}
  300. State& operator=(const State& other) {
  301. // We explicitly don't copy stateSet so that, e.g., mDrawingState
  302. // always uses the Drawing StateSet.
  303. layersSortedByZ = other.layersSortedByZ;
  304. displays = other.displays;
  305. colorMatrixChanged = other.colorMatrixChanged;
  306. if (colorMatrixChanged) {
  307. colorMatrix = other.colorMatrix;
  308. }
  309. return *this;
  310. }
  311. const LayerVector::StateSet stateSet = LayerVector::StateSet::Invalid;
  312. LayerVector layersSortedByZ;
  313. DefaultKeyedVector< wp<IBinder>, DisplayDeviceState> displays;
  314. bool colorMatrixChanged = true;
  315. mat4 colorMatrix;
  316. void traverseInZOrder(const LayerVector::Visitor& visitor) const;
  317. void traverseInReverseZOrder(const LayerVector::Visitor& visitor) const;
  318. };
  319. /* ------------------------------------------------------------------------
  320. * IBinder interface
  321. */
  322. status_t onTransact(uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags) override;
  323. status_t dump(int fd, const Vector<String16>& args) override { return priorityDump(fd, args); }
  324. bool callingThreadHasUnscopedSurfaceFlingerAccess() EXCLUDES(mStateLock);
  325. /* ------------------------------------------------------------------------
  326. * ISurfaceComposer interface
  327. */
  328. sp<ISurfaceComposerClient> createConnection() override;
  329. sp<IBinder> createDisplay(const String8& displayName, bool secure) override;
  330. void destroyDisplay(const sp<IBinder>& displayToken) override;
  331. std::vector<PhysicalDisplayId> getPhysicalDisplayIds() const override;
  332. sp<IBinder> getPhysicalDisplayToken(PhysicalDisplayId displayId) const override;
  333. void setTransactionState(const Vector<ComposerState>& state,
  334. const Vector<DisplayState>& displays, uint32_t flags,
  335. const sp<IBinder>& applyToken,
  336. const InputWindowCommands& inputWindowCommands,
  337. int64_t desiredPresentTime, const client_cache_t& uncacheBuffer,
  338. const std::vector<ListenerCallbacks>& listenerCallbacks) override;
  339. void bootFinished() override;
  340. bool authenticateSurfaceTexture(
  341. const sp<IGraphicBufferProducer>& bufferProducer) const override;
  342. status_t getSupportedFrameTimestamps(std::vector<FrameEvent>* outSupported) const override;
  343. sp<IDisplayEventConnection> createDisplayEventConnection(
  344. ISurfaceComposer::VsyncSource vsyncSource = eVsyncSourceApp,
  345. ISurfaceComposer::ConfigChanged configChanged =
  346. ISurfaceComposer::eConfigChangedSuppress) override;
  347. status_t captureScreen(const sp<IBinder>& displayToken, sp<GraphicBuffer>* outBuffer,
  348. bool& outCapturedSecureLayers, const ui::Dataspace reqDataspace,
  349. const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
  350. uint32_t reqWidth, uint32_t reqHeight,
  351. bool useIdentityTransform, ISurfaceComposer::Rotation rotation, bool captureSecureLayers) override;
  352. status_t captureScreen(uint64_t displayOrLayerStack, ui::Dataspace* outDataspace,
  353. sp<GraphicBuffer>* outBuffer) override;
  354. status_t captureLayers(
  355. const sp<IBinder>& parentHandle, sp<GraphicBuffer>* outBuffer,
  356. const ui::Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat,
  357. const Rect& sourceCrop,
  358. const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& exclude,
  359. float frameScale, bool childrenOnly) override;
  360. status_t getDisplayStats(const sp<IBinder>& displayToken, DisplayStatInfo* stats) override;
  361. status_t getDisplayConfigs(const sp<IBinder>& displayToken,
  362. Vector<DisplayInfo>* configs) override;
  363. int getActiveConfig(const sp<IBinder>& displayToken) override;
  364. status_t getDisplayColorModes(const sp<IBinder>& displayToken,
  365. Vector<ui::ColorMode>* configs) override;
  366. status_t getDisplayNativePrimaries(const sp<IBinder>& displayToken,
  367. ui::DisplayPrimaries &primaries);
  368. ui::ColorMode getActiveColorMode(const sp<IBinder>& displayToken) override;
  369. status_t setActiveColorMode(const sp<IBinder>& displayToken, ui::ColorMode colorMode) override;
  370. void setPowerMode(const sp<IBinder>& displayToken, int mode) override;
  371. status_t setActiveConfig(const sp<IBinder>& displayToken, int id) override;
  372. status_t clearAnimationFrameStats() override;
  373. status_t getAnimationFrameStats(FrameStats* outStats) const override;
  374. status_t getHdrCapabilities(const sp<IBinder>& displayToken,
  375. HdrCapabilities* outCapabilities) const override;
  376. status_t enableVSyncInjections(bool enable) override;
  377. status_t injectVSync(nsecs_t when) override;
  378. status_t getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const override;
  379. status_t getColorManagement(bool* outGetColorManagement) const override;
  380. status_t getCompositionPreference(ui::Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
  381. ui::Dataspace* outWideColorGamutDataspace,
  382. ui::PixelFormat* outWideColorGamutPixelFormat) const override;
  383. status_t getDisplayedContentSamplingAttributes(const sp<IBinder>& display,
  384. ui::PixelFormat* outFormat,
  385. ui::Dataspace* outDataspace,
  386. uint8_t* outComponentMask) const override;
  387. status_t setDisplayContentSamplingEnabled(const sp<IBinder>& display, bool enable,
  388. uint8_t componentMask,
  389. uint64_t maxFrames) const override;
  390. status_t getDisplayedContentSample(const sp<IBinder>& display, uint64_t maxFrames,
  391. uint64_t timestamp,
  392. DisplayedFrameStats* outStats) const override;
  393. status_t getProtectedContentSupport(bool* outSupported) const override;
  394. status_t isWideColorDisplay(const sp<IBinder>& displayToken,
  395. bool* outIsWideColorDisplay) const override;
  396. status_t addRegionSamplingListener(const Rect& samplingArea, const sp<IBinder>& stopLayerHandle,
  397. const sp<IRegionSamplingListener>& listener) override;
  398. status_t removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) override;
  399. status_t setAllowedDisplayConfigs(const sp<IBinder>& displayToken,
  400. const std::vector<int32_t>& allowedConfigs) override;
  401. status_t getAllowedDisplayConfigs(const sp<IBinder>& displayToken,
  402. std::vector<int32_t>* outAllowedConfigs) override;
  403. status_t getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
  404. bool* outSupport) const override;
  405. status_t setDisplayBrightness(const sp<IBinder>& displayToken, float brightness) const override;
  406. status_t notifyPowerHint(int32_t hintId) override;
  407. /* ------------------------------------------------------------------------
  408. * DeathRecipient interface
  409. */
  410. void binderDied(const wp<IBinder>& who) override;
  411. /* ------------------------------------------------------------------------
  412. * RefBase interface
  413. */
  414. void onFirstRef() override;
  415. /* ------------------------------------------------------------------------
  416. * HWC2::ComposerCallback / HWComposer::EventHandler interface
  417. */
  418. void onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
  419. int64_t timestamp) override;
  420. void onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
  421. HWC2::Connection connection) override;
  422. void onRefreshReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId) override;
  423. /* ------------------------------------------------------------------------
  424. * Message handling
  425. */
  426. void waitForEvent();
  427. // Can only be called from the main thread or with mStateLock held
  428. void signalTransaction();
  429. // Can only be called from the main thread or with mStateLock held
  430. void signalLayerUpdate();
  431. void signalRefresh();
  432. using RefreshRateType = scheduler::RefreshRateConfigs::RefreshRateType;
  433. struct ActiveConfigInfo {
  434. RefreshRateType type;
  435. int configId;
  436. Scheduler::ConfigEvent event;
  437. bool operator!=(const ActiveConfigInfo& other) const {
  438. return type != other.type || configId != other.configId || event != other.event;
  439. }
  440. };
  441. // called on the main thread in response to initializeDisplays()
  442. void onInitializeDisplays() REQUIRES(mStateLock);
  443. // Sets the desired active config bit. It obtains the lock, and sets mDesiredActiveConfig.
  444. void setDesiredActiveConfig(const ActiveConfigInfo& info) REQUIRES(mStateLock);
  445. // Once HWC has returned the present fence, this sets the active config and a new refresh
  446. // rate in SF.
  447. void setActiveConfigInternal() REQUIRES(mStateLock);
  448. // Active config is updated on INVALIDATE call in a state machine-like manner. When the
  449. // desired config was set, HWC needs to update the panel on the next refresh, and when
  450. // we receive the fence back, we know that the process was complete. It returns whether
  451. // we need to wait for the next invalidate
  452. bool performSetActiveConfig() REQUIRES(mStateLock);
  453. // Called when active config is no longer is progress
  454. void desiredActiveConfigChangeDone() REQUIRES(mStateLock);
  455. // called on the main thread in response to setPowerMode()
  456. void setPowerModeInternal(const sp<DisplayDevice>& display, int mode) REQUIRES(mStateLock);
  457. // Query the Scheduler or allowed display configs list for a matching config, and set it
  458. void setPreferredDisplayConfig() REQUIRES(mStateLock);
  459. // called on the main thread in response to setAllowedDisplayConfigs()
  460. void setAllowedDisplayConfigsInternal(const sp<DisplayDevice>& display,
  461. const std::vector<int32_t>& allowedConfigs)
  462. REQUIRES(mStateLock);
  463. // Returns whether the transaction actually modified any state
  464. bool handleMessageTransaction();
  465. // Returns whether a new buffer has been latched (see handlePageFlip())
  466. bool handleMessageInvalidate();
  467. void handleMessageRefresh();
  468. void handleTransaction(uint32_t transactionFlags);
  469. void handleTransactionLocked(uint32_t transactionFlags) REQUIRES(mStateLock);
  470. void updateInputFlinger();
  471. void updateInputWindowInfo();
  472. void commitInputWindowCommands() REQUIRES(mStateLock);
  473. void setInputWindowsFinished();
  474. void updateCursorAsync();
  475. /* handlePageFlip - latch a new buffer if available and compute the dirty
  476. * region. Returns whether a new buffer has been latched, i.e., whether it
  477. * is necessary to perform a refresh during this vsync.
  478. */
  479. bool handlePageFlip();
  480. /* ------------------------------------------------------------------------
  481. * Transactions
  482. */
  483. void applyTransactionState(const Vector<ComposerState>& state,
  484. const Vector<DisplayState>& displays, uint32_t flags,
  485. const InputWindowCommands& inputWindowCommands,
  486. const int64_t desiredPresentTime,
  487. const client_cache_t& uncacheBuffer,
  488. const std::vector<ListenerCallbacks>& listenerCallbacks,
  489. const int64_t postTime, bool privileged, bool isMainThread = false)
  490. REQUIRES(mStateLock);
  491. // Returns true if at least one transaction was flushed
  492. bool flushTransactionQueues();
  493. // Returns true if there is at least one transaction that needs to be flushed
  494. bool transactionFlushNeeded();
  495. uint32_t getTransactionFlags(uint32_t flags);
  496. uint32_t peekTransactionFlags();
  497. // Can only be called from the main thread or with mStateLock held
  498. uint32_t setTransactionFlags(uint32_t flags);
  499. uint32_t setTransactionFlags(uint32_t flags, Scheduler::TransactionStart transactionStart);
  500. void latchAndReleaseBuffer(const sp<Layer>& layer);
  501. void commitTransaction() REQUIRES(mStateLock);
  502. void commitOffscreenLayers();
  503. bool containsAnyInvalidClientState(const Vector<ComposerState>& states);
  504. bool transactionIsReadyToBeApplied(int64_t desiredPresentTime,
  505. const Vector<ComposerState>& states);
  506. uint32_t setClientStateLocked(const ComposerState& composerState, int64_t desiredPresentTime,
  507. const std::vector<ListenerCallbacks>& listenerCallbacks,
  508. int64_t postTime, bool privileged) REQUIRES(mStateLock);
  509. uint32_t setDisplayStateLocked(const DisplayState& s) REQUIRES(mStateLock);
  510. uint32_t addInputWindowCommands(const InputWindowCommands& inputWindowCommands)
  511. REQUIRES(mStateLock);
  512. /* ------------------------------------------------------------------------
  513. * Layer management
  514. */
  515. status_t createLayer(const String8& name, const String8& systemname, const sp<Client>& client, uint32_t w, uint32_t h,
  516. PixelFormat format, uint32_t flags, LayerMetadata metadata,
  517. sp<IBinder>* handle, sp<IGraphicBufferProducer>* gbp,
  518. const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer = nullptr);
  519. status_t createBufferQueueLayer(const sp<Client>& client, const String8& name, const String8& systemname, uint32_t w,
  520. uint32_t h, uint32_t flags, LayerMetadata metadata,
  521. PixelFormat& format, sp<IBinder>* outHandle,
  522. sp<IGraphicBufferProducer>* outGbp, sp<Layer>* outLayer);
  523. status_t createBufferStateLayer(const sp<Client>& client, const String8& name, const String8& systemname, uint32_t w,
  524. uint32_t h, uint32_t flags, LayerMetadata metadata,
  525. sp<IBinder>* outHandle, sp<Layer>* outLayer);
  526. status_t createColorLayer(const sp<Client>& client, const String8& name, const String8& systemname, uint32_t w, uint32_t h,
  527. uint32_t flags, LayerMetadata metadata, sp<IBinder>* outHandle,
  528. sp<Layer>* outLayer);
  529. status_t createContainerLayer(const sp<Client>& client, const String8& name, const String8& systemname, uint32_t w,
  530. uint32_t h, uint32_t flags, LayerMetadata metadata,
  531. sp<IBinder>* outHandle, sp<Layer>* outLayer);
  532. String8 getUniqueLayerName(const String8& name);
  533. // called when all clients have released all their references to
  534. // this layer meaning it is entirely safe to destroy all
  535. // resources associated to this layer.
  536. void onHandleDestroyed(sp<Layer>& layer);
  537. void markLayerPendingRemovalLocked(const sp<Layer>& layer);
  538. // add a layer to SurfaceFlinger
  539. status_t addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
  540. const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
  541. const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
  542. bool addToCurrentState);
  543. // Traverse through all the layers and compute and cache its bounds.
  544. void computeLayerBounds();
  545. /* ------------------------------------------------------------------------
  546. * Boot animation, on/off animations and screen capture
  547. */
  548. void startBootAnim();
  549. using TraverseLayersFunction = std::function<void(const LayerVector::Visitor&)>;
  550. void renderScreenImplLocked(const RenderArea& renderArea, TraverseLayersFunction traverseLayers,
  551. ANativeWindowBuffer* buffer, bool useIdentityTransform,
  552. int* outSyncFd);
  553. status_t captureScreenCommon(RenderArea& renderArea, TraverseLayersFunction traverseLayers,
  554. sp<GraphicBuffer>* outBuffer, const ui::PixelFormat reqPixelFormat,
  555. bool useIdentityTransform, bool& outCapturedSecureLayers);
  556. status_t captureScreenCommon(RenderArea& renderArea, TraverseLayersFunction traverseLayers,
  557. const sp<GraphicBuffer>& buffer, bool useIdentityTransform,
  558. bool& outCapturedSecureLayers);
  559. const sp<DisplayDevice> getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack);
  560. status_t captureScreenImplLocked(const RenderArea& renderArea,
  561. TraverseLayersFunction traverseLayers,
  562. ANativeWindowBuffer* buffer, bool useIdentityTransform,
  563. bool forSystem, int* outSyncFd, bool& outCapturedSecureLayers);
  564. void traverseLayersInDisplay(const sp<const DisplayDevice>& display,
  565. const LayerVector::Visitor& visitor);
  566. sp<StartPropertySetThread> mStartPropertySetThread;
  567. /* ------------------------------------------------------------------------
  568. * Properties
  569. */
  570. void readPersistentProperties();
  571. /* ------------------------------------------------------------------------
  572. * EGL
  573. */
  574. size_t getMaxTextureSize() const;
  575. size_t getMaxViewportDims() const;
  576. /* ------------------------------------------------------------------------
  577. * Display and layer stack management
  578. */
  579. // called when starting, or restarting after system_server death
  580. void initializeDisplays();
  581. sp<const DisplayDevice> getDisplayDevice(const wp<IBinder>& displayToken) const {
  582. Mutex::Autolock _l(mStateLock);
  583. return getDisplayDeviceLocked(displayToken);
  584. }
  585. sp<DisplayDevice> getDisplayDevice(const wp<IBinder>& displayToken) {
  586. Mutex::Autolock _l(mStateLock);
  587. return getDisplayDeviceLocked(displayToken);
  588. }
  589. // NOTE: can only be called from the main thread or with mStateLock held
  590. sp<const DisplayDevice> getDisplayDeviceLocked(const wp<IBinder>& displayToken) const {
  591. return const_cast<SurfaceFlinger*>(this)->getDisplayDeviceLocked(displayToken);
  592. }
  593. // NOTE: can only be called from the main thread or with mStateLock held
  594. sp<DisplayDevice> getDisplayDeviceLocked(const wp<IBinder>& displayToken) {
  595. const auto it = mDisplays.find(displayToken);
  596. return it == mDisplays.end() ? nullptr : it->second;
  597. }
  598. sp<const DisplayDevice> getDefaultDisplayDeviceLocked() const {
  599. return const_cast<SurfaceFlinger*>(this)->getDefaultDisplayDeviceLocked();
  600. }
  601. sp<DisplayDevice> getDefaultDisplayDeviceLocked() {
  602. if (const auto token = getInternalDisplayTokenLocked()) {
  603. return getDisplayDeviceLocked(token);
  604. }
  605. return nullptr;
  606. }
  607. // mark a region of a layer stack dirty. this updates the dirty
  608. // region of all screens presenting this layer stack.
  609. void invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty);
  610. /* ------------------------------------------------------------------------
  611. * H/W composer
  612. */
  613. // The current hardware composer interface.
  614. //
  615. // The following thread safety rules apply when accessing mHwc, either
  616. // directly or via getHwComposer():
  617. //
  618. // 1. When recreating mHwc, acquire mStateLock. We currently recreate mHwc
  619. // only when switching into and out of vr. Recreating mHwc must only be
  620. // done on the main thread.
  621. //
  622. // 2. When accessing mHwc on the main thread, it's not necessary to acquire
  623. // mStateLock.
  624. //
  625. // 3. When accessing mHwc on a thread other than the main thread, we always
  626. // need to acquire mStateLock. This is because the main thread could be
  627. // in the process of destroying the current mHwc instance.
  628. //
  629. // The above thread safety rules only apply to SurfaceFlinger.cpp. In
  630. // SurfaceFlinger_hwc1.cpp we create mHwc at surface flinger init and never
  631. // destroy it, so it's always safe to access mHwc from any thread without
  632. // acquiring mStateLock.
  633. HWComposer& getHwComposer() const;
  634. /* ------------------------------------------------------------------------
  635. * Compositing
  636. */
  637. void invalidateHwcGeometry();
  638. void computeVisibleRegions(const sp<const DisplayDevice>& display, Region& dirtyRegion,
  639. Region& opaqueRegion);
  640. void preComposition();
  641. void postComposition();
  642. void getCompositorTiming(CompositorTiming* compositorTiming);
  643. void updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
  644. std::shared_ptr<FenceTime>& presentFenceTime);
  645. void setCompositorTimingSnapped(const DisplayStatInfo& stats,
  646. nsecs_t compositeToPresentLatency);
  647. void rebuildLayerStacks();
  648. ui::Dataspace getBestDataspace(const sp<DisplayDevice>& display, ui::Dataspace* outHdrDataSpace,
  649. bool* outIsHdrClientComposition) const;
  650. // Returns the appropriate ColorMode, Dataspace and RenderIntent for the
  651. // DisplayDevice. The function only returns the supported ColorMode,
  652. // Dataspace and RenderIntent.
  653. void pickColorMode(const sp<DisplayDevice>& display, ui::ColorMode* outMode,
  654. ui::Dataspace* outDataSpace, ui::RenderIntent* outRenderIntent) const;
  655. void calculateWorkingSet();
  656. /*
  657. * beginFrame - This function handles any pre-frame processing that needs to be
  658. * prior to any CompositionInfo handling and is not dependent on data in
  659. * CompositionInfo
  660. */
  661. void beginFrame(const sp<DisplayDevice>& display);
  662. /* prepareFrame - This function will call into the DisplayDevice to prepare a
  663. * frame after CompositionInfo has been programmed. This provides a mechanism
  664. * to prepare the hardware composer
  665. */
  666. void prepareFrame(const sp<DisplayDevice>& display);
  667. void doComposition(const sp<DisplayDevice>& display, bool repainEverything);
  668. void doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything);
  669. void logLayerStats();
  670. void doDisplayComposition(const sp<DisplayDevice>& display, const Region& dirtyRegion);
  671. // This fails if using GL and the surface has been destroyed. readyFence
  672. // will be populated if using GL and native fence sync is supported, to
  673. // signal when drawing has completed.
  674. bool doComposeSurfaces(const sp<DisplayDevice>& display, const Region& debugRegionm,
  675. base::unique_fd* readyFence);
  676. void postFramebuffer(const sp<DisplayDevice>& display);
  677. void postFrame();
  678. void drawWormhole(const Region& region) const;
  679. /* ------------------------------------------------------------------------
  680. * Display management
  681. */
  682. sp<DisplayDevice> setupNewDisplayDeviceInternal(
  683. const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
  684. const DisplayDeviceState& state,
  685. const sp<compositionengine::DisplaySurface>& dispSurface,
  686. const sp<IGraphicBufferProducer>& producer);
  687. void processDisplayChangesLocked();
  688. void processDisplayHotplugEventsLocked();
  689. void dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected);
  690. /* ------------------------------------------------------------------------
  691. * VSync
  692. */
  693. nsecs_t getVsyncPeriod() const REQUIRES(mStateLock);
  694. // Sets the refresh rate by switching active configs, if they are available for
  695. // the desired refresh rate.
  696. void setRefreshRateTo(RefreshRateType, Scheduler::ConfigEvent event) REQUIRES(mStateLock);
  697. bool isDisplayConfigAllowed(int32_t configId) REQUIRES(mStateLock);
  698. /*
  699. * Display identification
  700. */
  701. sp<IBinder> getPhysicalDisplayTokenLocked(DisplayId displayId) const {
  702. const auto it = mPhysicalDisplayTokens.find(displayId);
  703. return it != mPhysicalDisplayTokens.end() ? it->second : nullptr;
  704. }
  705. std::optional<DisplayId> getPhysicalDisplayIdLocked(const sp<IBinder>& displayToken) const {
  706. for (const auto& [id, token] : mPhysicalDisplayTokens) {
  707. if (token == displayToken) {
  708. return id;
  709. }
  710. }
  711. return {};
  712. }
  713. // TODO(b/74619554): Remove special cases for primary display.
  714. sp<IBinder> getInternalDisplayTokenLocked() const {
  715. const auto displayId = getInternalDisplayIdLocked();
  716. return displayId ? getPhysicalDisplayTokenLocked(*displayId) : nullptr;
  717. }
  718. std::optional<DisplayId> getInternalDisplayIdLocked() const {
  719. const auto hwcDisplayId = getHwComposer().getInternalHwcDisplayId();
  720. return hwcDisplayId ? getHwComposer().toPhysicalDisplayId(*hwcDisplayId) : std::nullopt;
  721. }
  722. bool previousFrameMissed(int graceTimeMs = 0);
  723. void setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled);
  724. /*
  725. * Debugging & dumpsys
  726. */
  727. using DumpArgs = Vector<String16>;
  728. using Dumper = std::function<void(const DumpArgs&, bool asProto, std::string&)>;
  729. template <typename F, std::enable_if_t<!std::is_member_function_pointer_v<F>>* = nullptr>
  730. static Dumper dumper(F&& dump) {
  731. using namespace std::placeholders;
  732. return std::bind(std::forward<F>(dump), _3);
  733. }
  734. template <typename F, std::enable_if_t<std::is_member_function_pointer_v<F>>* = nullptr>
  735. Dumper dumper(F dump) {
  736. using namespace std::placeholders;
  737. return std::bind(dump, this, _3);
  738. }
  739. template <typename F>
  740. Dumper argsDumper(F dump) {
  741. using namespace std::placeholders;
  742. return std::bind(dump, this, _1, _3);
  743. }
  744. template <typename F>
  745. Dumper protoDumper(F dump) {
  746. using namespace std::placeholders;
  747. return std::bind(dump, this, _1, _2, _3);
  748. }
  749. void dumpAllLocked(const DumpArgs& args, std::string& result) const REQUIRES(mStateLock);
  750. void appendSfConfigString(std::string& result) const;
  751. void listLayersLocked(std::string& result) const;
  752. void dumpStatsLocked(const DumpArgs& args, std::string& result) const REQUIRES(mStateLock);
  753. void clearStatsLocked(const DumpArgs& args, std::string& result);
  754. void dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const;
  755. void logFrameStats();
  756. void dumpVSync(std::string& result) const REQUIRES(mStateLock);
  757. void dumpStaticScreenStats(std::string& result) const;
  758. // Not const because each Layer needs to query Fences and cache timestamps.
  759. void dumpFrameEventsLocked(std::string& result);
  760. void recordBufferingStats(const char* layerName,
  761. std::vector<OccupancyTracker::Segment>&& history);
  762. void dumpBufferingStats(std::string& result) const;
  763. void dumpDisplayIdentificationData(std::string& result) const;
  764. void dumpWideColorInfo(std::string& result) const;
  765. LayersProto dumpProtoInfo(LayerVector::StateSet stateSet,
  766. uint32_t traceFlags = SurfaceTracing::TRACE_ALL) const;
  767. void withTracingLock(std::function<void()> operation) REQUIRES(mStateLock);
  768. LayersProto dumpVisibleLayersProtoInfo(const sp<DisplayDevice>& display) const;
  769. bool isLayerTripleBufferingDisabled() const {
  770. return this->mLayerTripleBufferingDisabled;
  771. }
  772. status_t doDump(int fd, const DumpArgs& args, bool asProto);
  773. status_t dumpCritical(int fd, const DumpArgs&, bool asProto);
  774. status_t dumpAll(int fd, const DumpArgs& args, bool asProto) override {
  775. return doDump(fd, args, asProto);
  776. }
  777. /* ------------------------------------------------------------------------
  778. * VrFlinger
  779. */
  780. void resetDisplayState();
  781. // Check to see if we should handoff to vr flinger.
  782. void updateVrFlinger();
  783. void updateColorMatrixLocked();
  784. /* ------------------------------------------------------------------------
  785. * Attributes
  786. */
  787. surfaceflinger::Factory& mFactory;
  788. // access must be protected by mStateLock
  789. mutable Mutex mStateLock;
  790. State mCurrentState{LayerVector::StateSet::Current};
  791. std::atomic<int32_t> mTransactionFlags = 0;
  792. Condition mTransactionCV;
  793. bool mTransactionPending = false;
  794. bool mAnimTransactionPending = false;
  795. SortedVector<sp<Layer>> mLayersPendingRemoval;
  796. bool mTraversalNeededMainThread = false;
  797. // guards access to the mDrawing state if tracing is enabled.
  798. mutable std::mutex mDrawingStateLock;
  799. // global color transform states
  800. Daltonizer mDaltonizer;
  801. float mGlobalSaturationFactor = 1.0f;
  802. mat4 mClientColorMatrix;
  803. // Can't be unordered_set because wp<> isn't hashable
  804. std::set<wp<IBinder>> mGraphicBufferProducerList;
  805. size_t mMaxGraphicBufferProducerListSize = MAX_LAYERS;
  806. // protected by mStateLock (but we could use another lock)
  807. bool mLayersRemoved = false;
  808. bool mLayersAdded = false;
  809. std::atomic<bool> mRepaintEverything = false;
  810. // constant members (no synchronization needed for access)
  811. const nsecs_t mBootTime = systemTime();
  812. bool mGpuToCpuSupported = false;
  813. std::unique_ptr<EventThread> mInjectorEventThread;
  814. std::unique_ptr<InjectVSyncSource> mVSyncInjector;
  815. // Calculates correct offsets.
  816. VSyncModulator mVsyncModulator;
  817. // Keeps track of all available phase offsets for different refresh types.
  818. const std::unique_ptr<scheduler::PhaseOffsets> mPhaseOffsets;
  819. // Can only accessed from the main thread, these members
  820. // don't need synchronization
  821. State mDrawingState{LayerVector::StateSet::Drawing};
  822. bool mVisibleRegionsDirty = false;
  823. // Set during transaction commit stage to track if the input info for a layer has changed.
  824. bool mInputInfoChanged = false;
  825. bool mGeometryInvalid = false;
  826. bool mAnimCompositionPending = false;
  827. std::vector<sp<Layer>> mLayersWithQueuedFrames;
  828. // Tracks layers that need to update a display's dirty region.
  829. std::vector<sp<Layer>> mLayersPendingRefresh;
  830. std::array<sp<Fence>, 2> mPreviousPresentFences = {Fence::NO_FENCE, Fence::NO_FENCE};
  831. // True if in the previous frame at least one layer was composed via the GPU.
  832. bool mHadClientComposition = false;
  833. // True if in the previous frame at least one layer was composed via HW Composer.
  834. // Note that it is possible for a frame to be composed via both client and device
  835. // composition, for example in the case of overlays.
  836. bool mHadDeviceComposition = false;
  837. enum class BootStage {
  838. BOOTLOADER,
  839. BOOTANIMATION,
  840. FINISHED,
  841. };
  842. BootStage mBootStage = BootStage::BOOTLOADER;
  843. struct HotplugEvent {
  844. hwc2_display_t hwcDisplayId;
  845. HWC2::Connection connection = HWC2::Connection::Invalid;
  846. };
  847. // protected by mStateLock
  848. std::vector<HotplugEvent> mPendingHotplugEvents;
  849. // this may only be written from the main thread with mStateLock held
  850. // it may be read from other threads with mStateLock held
  851. std::map<wp<IBinder>, sp<DisplayDevice>> mDisplays;
  852. std::unordered_map<DisplayId, sp<IBinder>> mPhysicalDisplayTokens;
  853. // protected by mStateLock
  854. std::unordered_map<BBinder*, wp<Layer>> mLayersByLocalBinderToken;
  855. // don't use a lock for these, we don't care
  856. int mDebugRegion = 0;
  857. bool mDebugDisableHWC = false;
  858. bool mDebugDisableTransformHint = false;
  859. volatile nsecs_t mDebugInTransaction = 0;
  860. bool mForceFullDamage = false;
  861. bool mPropagateBackpressure = true;
  862. bool mPropagateBackpressureClientComposition = false;
  863. std::unique_ptr<SurfaceInterceptor> mInterceptor;
  864. SurfaceTracing mTracing{*this};
  865. bool mTracingEnabled = false;
  866. bool mTracingEnabledChanged GUARDED_BY(mStateLock) = false;
  867. LayerStats mLayerStats;
  868. const std::shared_ptr<TimeStats> mTimeStats;
  869. bool mUseHwcVirtualDisplays = false;
  870. std::atomic<uint32_t> mFrameMissedCount = 0;
  871. std::atomic<uint32_t> mHwcFrameMissedCount = 0;
  872. std::atomic<uint32_t> mGpuFrameMissedCount = 0;
  873. TransactionCompletedThread mTransactionCompletedThread;
  874. // Restrict layers to use two buffers in their bufferqueues.
  875. bool mLayerTripleBufferingDisabled = false;
  876. // these are thread safe
  877. std::unique_ptr<MessageQueue> mEventQueue;
  878. FrameTracker mAnimFrameTracker;
  879. // protected by mDestroyedLayerLock;
  880. mutable Mutex mDestroyedLayerLock;
  881. Vector<Layer const *> mDestroyedLayers;
  882. nsecs_t mRefreshStartTime = 0;
  883. std::atomic<bool> mRefreshPending = false;
  884. // We maintain a pool of pre-generated texture names to hand out to avoid
  885. // layer creation needing to run on the main thread (which it would
  886. // otherwise need to do to access RenderEngine).
  887. std::mutex mTexturePoolMutex;
  888. uint32_t mTexturePoolSize = 0;
  889. std::vector<uint32_t> mTexturePool;
  890. struct IBinderHash {
  891. std::size_t operator()(const sp<IBinder>& strongPointer) const {
  892. return std::hash<IBinder*>{}(strongPointer.get());
  893. }
  894. };
  895. struct TransactionState {
  896. TransactionState(const Vector<ComposerState>& composerStates,
  897. const Vector<DisplayState>& displayStates, uint32_t transactionFlags,
  898. int64_t desiredPresentTime, const client_cache_t& uncacheBuffer,
  899. const std::vector<ListenerCallbacks>& listenerCallbacks, int64_t postTime,
  900. bool privileged)
  901. : states(composerStates),
  902. displays(displayStates),
  903. flags(transactionFlags),
  904. desiredPresentTime(desiredPresentTime),
  905. buffer(uncacheBuffer),
  906. callback(listenerCallbacks),
  907. postTime(postTime),
  908. privileged(privileged) {}
  909. Vector<ComposerState> states;
  910. Vector<DisplayState> displays;
  911. uint32_t flags;
  912. const int64_t desiredPresentTime;
  913. client_cache_t buffer;
  914. std::vector<ListenerCallbacks> callback;
  915. const int64_t postTime;
  916. bool privileged;
  917. };
  918. std::unordered_map<sp<IBinder>, std::queue<TransactionState>, IBinderHash> mTransactionQueues;
  919. /* ------------------------------------------------------------------------
  920. * Feature prototyping
  921. */
  922. bool mInjectVSyncs = false;
  923. // Static screen stats
  924. bool mHasPoweredOff = false;
  925. size_t mNumLayers = 0;
  926. // Verify that transaction is being called by an approved process:
  927. // either AID_GRAPHICS or AID_SYSTEM.
  928. status_t CheckTransactCodeCredentials(uint32_t code);
  929. std::unique_ptr<dvr::VrFlinger> mVrFlinger;
  930. std::atomic<bool> mVrFlingerRequestsDisplay = false;
  931. static bool useVrFlinger;
  932. std::thread::id mMainThreadId = std::this_thread::get_id();
  933. DisplayColorSetting mDisplayColorSetting = DisplayColorSetting::ENHANCED;
  934. // Color mode forced by setting persist.sys.sf.color_mode, it must:
  935. // 1. not be NATIVE color mode, NATIVE color mode means no forced color mode;
  936. // 2. be one of the supported color modes returned by hardware composer, otherwise
  937. // it will not be respected.
  938. // persist.sys.sf.color_mode will only take effect when persist.sys.sf.native_mode
  939. // is not set to 1.
  940. // This property can be used to force SurfaceFlinger to always pick a certain color mode.
  941. ui::ColorMode mForceColorMode = ui::ColorMode::NATIVE;
  942. ui::Dataspace mDefaultCompositionDataspace;
  943. ui::Dataspace mWideColorGamutCompositionDataspace;
  944. ui::Dataspace mColorSpaceAgnosticDataspace;
  945. SurfaceFlingerBE mBE;
  946. std::unique_ptr<compositionengine::CompositionEngine> mCompositionEngine;
  947. /* ------------------------------------------------------------------------
  948. * Scheduler
  949. */
  950. bool mUseSmart90ForVideo = false;
  951. std::unique_ptr<Scheduler> mScheduler;
  952. sp<Scheduler::ConnectionHandle> mAppConnectionHandle;
  953. sp<Scheduler::ConnectionHandle> mSfConnectionHandle;
  954. scheduler::RefreshRateConfigs mRefreshRateConfigs;
  955. scheduler::RefreshRateStats mRefreshRateStats{mRefreshRateConfigs, *mTimeStats};
  956. // All configs are allowed if the set is empty.
  957. using DisplayConfigs = std::set<int32_t>;
  958. DisplayConfigs mAllowedDisplayConfigs GUARDED_BY(mStateLock);
  959. std::mutex mActiveConfigLock;
  960. // This bit is set once we start setting the config. We read from this bit during the
  961. // process. If at the end, this bit is different than mDesiredActiveConfig, we restart
  962. // the process.
  963. ActiveConfigInfo mUpcomingActiveConfig; // Always read and written on the main thread.
  964. // This bit can be set at any point in time when the system wants the new config.
  965. ActiveConfigInfo mDesiredActiveConfig GUARDED_BY(mActiveConfigLock);
  966. // below flags are set by main thread only
  967. bool mDesiredActiveConfigChanged GUARDED_BY(mActiveConfigLock) = false;
  968. bool mCheckPendingFence = false;
  969. bool mLumaSampling = true;
  970. sp<RegionSamplingThread> mRegionSamplingThread;
  971. ui::DisplayPrimaries mInternalDisplayPrimaries;
  972. sp<IInputFlinger> mInputFlinger;
  973. InputWindowCommands mPendingInputWindowCommands GUARDED_BY(mStateLock);
  974. // Should only be accessed by the main thread.
  975. InputWindowCommands mInputWindowCommands;
  976. struct SetInputWindowsListener : BnSetInputWindowsListener {
  977. explicit SetInputWindowsListener(sp<SurfaceFlinger> flinger)
  978. : mFlinger(std::move(flinger)) {}
  979. void onSetInputWindowsFinished() override;
  980. const sp<SurfaceFlinger> mFlinger;
  981. };
  982. const sp<SetInputWindowsListener> mSetInputWindowsListener = new SetInputWindowsListener(this);
  983. bool mPendingSyncInputWindows GUARDED_BY(mStateLock);
  984. Hwc2::impl::PowerAdvisor mPowerAdvisor;
  985. std::unique_ptr<RefreshRateOverlay> mRefreshRateOverlay;
  986. // Flag used to set override allowed display configs from backdoor
  987. bool mDebugDisplayConfigSetByBackdoor = false;
  988. // A set of layers that have no parent so they are not drawn on screen.
  989. // Should only be accessed by the main thread.
  990. // The Layer pointer is removed from the set when the destructor is called so there shouldn't
  991. // be any issues with a raw pointer referencing an invalid object.
  992. std::unordered_set<Layer*> mOffscreenLayers;
  993. // Flags to capture the state of Vsync in HWC
  994. HWC2::Vsync mHWCVsyncState = HWC2::Vsync::Disable;
  995. HWC2::Vsync mHWCVsyncPendingState = HWC2::Vsync::Disable;
  996. nsecs_t mExpectedPresentTime;
  997. };
  998. } // namespace android