blob: 4b950364be5b68ee3c8706a6110c92c4753d3677 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
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
Dan Stoza9e56aa02015-11-02 13:00:03 -080017// #define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080020#include <stdint.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070021#include <sys/types.h>
Romain Guy0147a172017-06-01 13:53:56 -070022#include <algorithm>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080023#include <errno.h>
24#include <math.h>
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -070025#include <mutex>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Greg Hackmann86efcc02014-03-07 12:44:02 -080027#include <inttypes.h>
Jesse Hallb154c422014-07-13 12:47:02 -070028#include <stdatomic.h>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070029#include <optional>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070030
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080031#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070032#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070034#include <binder/IPCThreadState.h>
35#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070036#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070037
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080038#include <dvr/vr_flinger.h>
39
Chia-I Wud49d6692018-06-27 07:17:41 +080040#include <ui/ColorSpace.h>
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -060041#include <ui/DebugUtils.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070042#include <ui/DisplayInfo.h>
Lajos Molnar67d8bd62014-09-11 14:58:45 -070043#include <ui/DisplayStatInfo.h>
Mathias Agopianc666cae2012-07-25 18:56:13 -070044
Jamie Gennis1a4d8832012-08-02 20:11:05 -070045#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070046#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070047#include <gui/IDisplayEventConnection.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080048#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080049#include <gui/Surface.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070050
51#include <ui/GraphicBufferAllocator.h>
52#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070053#include <ui/UiConfig.h>
Mathias Agopiand0566bc2011-11-17 17:49:17 -080054
Mathias Agopiancde87a32012-09-13 14:09:01 -070055#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080056#include <utils/String8.h>
57#include <utils/String16.h>
58#include <utils/StopWatch.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070059#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080060#include <utils/Trace.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080061
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070063#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080064
Robert Carr578038f2018-03-09 12:25:24 -080065#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070066#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070067#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020068#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080069#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020070#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080071#include "ContainerLayer.h"
Mathias Agopian90ac7992012-02-25 18:48:35 -080072#include "DdmConnection.h"
Jamie Gennisfaf77cc2013-07-30 15:10:32 -070073#include "DispSync.h"
Robert Carr578038f2018-03-09 12:25:24 -080074#include "DisplayDevice.h"
Jamie Gennisd1700752013-10-14 12:22:52 -070075#include "EventControlThread.h"
Mathias Agopiand0566bc2011-11-17 17:49:17 -080076#include "EventThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070078#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080079#include "MonitoredProducer.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080080#include "SurfaceFlinger.h"
Robert Carr578038f2018-03-09 12:25:24 -080081#include "clz.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080082
Steven Thomasb02664d2017-07-26 18:48:28 -070083#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070084#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070085#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070086#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070087#include "DisplayHardware/VirtualDisplaySurface.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080088
Mathias Agopianff2ed702013-09-01 21:36:12 -070089#include "Effects/Daltonizer.h"
90
Mathias Agopian875d8e12013-06-07 15:35:48 -070091#include "RenderEngine/RenderEngine.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070092#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070093
Jiyong Park4b20c2e2017-01-14 19:45:11 +090094#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +080095#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
96#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +090097#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +090098
chaviw1d044282017-09-27 12:19:28 -070099#include <layerproto/LayerProtoParser.h>
100
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800101#define DISPLAY_COUNT 1
102
Mathias Agopianfee2b462013-07-03 12:34:01 -0700103/*
104 * DEBUG_SCREENSHOTS: set to true to check that screenshots are not all
105 * black pixels.
106 */
107#define DEBUG_SCREENSHOTS false
108
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800109namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700110
Jaesoo Lee43518572017-01-23 19:03:16 +0900111using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900112using namespace android::hardware::configstore::V1_0;
Peiyong Lin9f034472018-03-28 15:29:00 -0700113using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700114using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700115using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700116using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900117
Steven Thomasb02664d2017-07-26 18:48:28 -0700118namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700119
120#pragma clang diagnostic push
121#pragma clang diagnostic error "-Wswitch-enum"
122
123bool isWideColorMode(const ColorMode colorMode) {
124 switch (colorMode) {
125 case ColorMode::DISPLAY_P3:
126 case ColorMode::ADOBE_RGB:
127 case ColorMode::DCI_P3:
128 case ColorMode::BT2020:
129 case ColorMode::BT2100_PQ:
130 case ColorMode::BT2100_HLG:
131 return true;
132 case ColorMode::NATIVE:
133 case ColorMode::STANDARD_BT601_625:
134 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
135 case ColorMode::STANDARD_BT601_525:
136 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
137 case ColorMode::STANDARD_BT709:
138 case ColorMode::SRGB:
139 return false;
140 }
141 return false;
142}
143
144#pragma clang diagnostic pop
145
Steven Thomasb02664d2017-07-26 18:48:28 -0700146class ConditionalLock {
147public:
148 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
149 if (lock) {
150 mMutex.lock();
151 }
152 }
153 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
154private:
155 Mutex& mMutex;
156 bool mLocked;
157};
Peiyong Linfca547f2018-07-09 13:03:33 -0700158
Steven Thomasb02664d2017-07-26 18:48:28 -0700159} // namespace anonymous
160
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800161// ---------------------------------------------------------------------------
162
Mathias Agopian99b49842011-06-27 16:05:52 -0700163const String16 sHardwareTest("android.permission.HARDWARE_TEST");
164const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
165const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
166const String16 sDump("android.permission.DUMP");
167
168// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800169int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
170int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700171int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700172bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800173uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800174bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800175bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800176int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Lloyd Piquec5208312018-01-08 17:59:02 -0800177// TODO(courtneygo): Rename hasWideColorDisplay to clarify its actual meaning.
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600178bool SurfaceFlinger::hasWideColorDisplay;
Mathias Agopian99b49842011-06-27 16:05:52 -0700179
Kalle Raitaa099a242017-01-11 11:17:29 -0800180
181std::string getHwcServiceName() {
182 char value[PROPERTY_VALUE_MAX] = {};
183 property_get("debug.sf.hwc_service_name", value, "default");
184 ALOGI("Using HWComposer service: '%s'", value);
185 return std::string(value);
186}
187
188bool useTrebleTestingOverride() {
189 char value[PROPERTY_VALUE_MAX] = {};
190 property_get("debug.sf.treble_testing_override", value, "false");
191 ALOGI("Treble testing override: '%s'", value);
192 return std::string(value) == "true";
193}
194
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800195std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
196 switch(displayColorSetting) {
197 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700198 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800199 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700200 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800201 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700202 return std::string("Enhanced");
203 default:
204 return std::string("Unknown ") +
205 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800206 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800207}
208
Lloyd Pique99d3da52018-01-22 17:48:03 -0800209NativeWindowSurface::~NativeWindowSurface() = default;
210
211namespace impl {
212
213class NativeWindowSurface final : public android::NativeWindowSurface {
214public:
215 static std::unique_ptr<android::NativeWindowSurface> create(
216 const sp<IGraphicBufferProducer>& producer) {
217 return std::make_unique<NativeWindowSurface>(producer);
218 }
219
220 explicit NativeWindowSurface(const sp<IGraphicBufferProducer>& producer)
221 : surface(new Surface(producer, false)) {}
222
223 ~NativeWindowSurface() override = default;
224
225private:
226 sp<ANativeWindow> getNativeWindow() const override { return surface; }
227
228 void preallocateBuffers() override { surface->allocateBuffers(); }
229
230 sp<Surface> surface;
231};
232
233} // namespace impl
234
David Sodmanbc815282017-11-05 18:57:52 -0800235SurfaceFlingerBE::SurfaceFlingerBE()
236 : mHwcServiceName(getHwcServiceName()),
237 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800238 mFrameBuckets(),
239 mTotalTime(0),
240 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800241 mComposerSequenceId(0) {
242}
243
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800244SurfaceFlinger::SurfaceFlinger(SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800245 : BnSurfaceComposer(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800246 mTransactionFlags(0),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700247 mTransactionPending(false),
248 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700249 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700250 mLayersAdded(false),
Mathias Agopian52bbb1a2012-07-31 19:01:53 -0700251 mRepaintEverything(0),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800252 mBootTime(systemTime()),
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700253 mDisplayTokens(),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800254 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800255 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800256 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800257 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800258 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700259 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700260 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700261 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700262 mDebugInSwapBuffers(0),
263 mLastSwapBufferTime(0),
264 mDebugInTransaction(0),
265 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700266 mForceFullDamage(false),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700267 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700268 mHWVsyncAvailable(false),
Dan Stozab90cf072015-03-05 11:05:59 -0800269 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800270 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700271 mVrFlingerRequestsDisplay(false),
Lloyd Pique12eb4232018-01-17 11:54:43 -0800272 mMainThreadId(std::this_thread::get_id()),
Lloyd Pique99d3da52018-01-22 17:48:03 -0800273 mCreateBufferQueue(&BufferQueue::createBufferQueue),
274 mCreateNativeWindowSurface(&impl::NativeWindowSurface::create) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800275
276SurfaceFlinger::SurfaceFlinger() : SurfaceFlinger(SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800277 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800278
279 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
280 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
281
282 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
283 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
284
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800285 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
286 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800287
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700288 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
289 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
290
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700291 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
292 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
293
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800294 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
295 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
296
Steven Thomas050b2c82017-03-06 11:45:16 -0800297 // Vr flinger is only enabled on Daydream ready devices.
298 useVrFlinger = getBool< ISurfaceFlingerConfigs,
299 &ISurfaceFlingerConfigs::useVrFlinger>(false);
300
Fabien Sanglard1971b632017-03-10 14:50:03 -0800301 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
302 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
303
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600304 hasWideColorDisplay =
305 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
306
Iris Chang7501ed62018-04-30 14:45:42 +0800307 V1_1::DisplayOrientation primaryDisplayOrientation =
308 getDisplayOrientation< V1_1::ISurfaceFlingerConfigs, &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
309 V1_1::DisplayOrientation::ORIENTATION_0);
310
311 switch (primaryDisplayOrientation) {
312 case V1_1::DisplayOrientation::ORIENTATION_90:
313 mPrimaryDisplayOrientation = DisplayState::eOrientation90;
314 break;
315 case V1_1::DisplayOrientation::ORIENTATION_180:
316 mPrimaryDisplayOrientation = DisplayState::eOrientation180;
317 break;
318 case V1_1::DisplayOrientation::ORIENTATION_270:
319 mPrimaryDisplayOrientation = DisplayState::eOrientation270;
320 break;
321 default:
322 mPrimaryDisplayOrientation = DisplayState::eOrientationDefault;
323 break;
324 }
325 ALOGV("Primary Display Orientation is set to %2d.", mPrimaryDisplayOrientation);
326
Lloyd Pique41be5d22018-06-21 13:11:48 -0700327 // Note: We create a local temporary with the real DispSync implementation
328 // type temporarily so we can initialize it with the configured values,
329 // before storing it for more generic use using the interface type.
330 auto primaryDispSync = std::make_unique<impl::DispSync>("PrimaryDispSync");
331 primaryDispSync->init(SurfaceFlinger::hasSyncFramework,
332 SurfaceFlinger::dispSyncPresentTimeOffset);
333 mPrimaryDispSync = std::move(primaryDispSync);
Saurabh Shahf4174532017-07-13 10:45:07 -0700334
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800335 // debugging stuff...
336 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700337
Mathias Agopianb4b17302013-03-20 18:36:41 -0700338 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700339 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700340
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800341 property_get("debug.sf.showupdates", value, "0");
342 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700343
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700344 property_get("debug.sf.ddms", value, "0");
345 mDebugDDMS = atoi(value);
346 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700347 if (!startDdmConnection()) {
348 // start failed, and DDMS debugging not enabled
349 mDebugDDMS = 0;
350 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700351 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700352 ALOGI_IF(mDebugRegion, "showupdates enabled");
353 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700354
355 property_get("debug.sf.disable_backpressure", value, "0");
356 mPropagateBackpressure = !atoi(value);
357 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700358
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800359 property_get("debug.sf.enable_hwc_vds", value, "0");
360 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800361 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800362
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800363 property_get("ro.sf.disable_triple_buffer", value, "1");
364 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800365 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700366
Yiwei Zhang243b3782018-05-15 17:40:04 -0700367 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700368 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
369 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
370
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200371 property_get("debug.sf.early_phase_offset_ns", value, "-1");
372 const int earlySfOffsetNs = atoi(value);
373
374 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
375 const int earlyGlSfOffsetNs = atoi(value);
376
377 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
378 const int earlyAppOffsetNs = atoi(value);
379
380 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
381 const int earlyGlAppOffsetNs = atoi(value);
382
383 const VSyncModulator::Offsets earlyOffsets =
384 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
385 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
386 const VSyncModulator::Offsets earlyGlOffsets =
387 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
388 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
389 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
390 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700391
Romain Guy11d63f42017-07-20 12:47:14 -0700392 // We should be reading 'persist.sys.sf.color_saturation' here
393 // but since /data may be encrypted, we need to wait until after vold
394 // comes online to attempt to read the property. The property is
395 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800396
397 if (useTrebleTestingOverride()) {
398 // Without the override SurfaceFlinger cannot connect to HIDL
399 // services that are not listed in the manifests. Considered
400 // deriving the setting from the set service name, but it
401 // would be brittle if the name that's not 'default' is used
402 // for production purposes later on.
403 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
404 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800405}
406
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800407void SurfaceFlinger::onFirstRef()
408{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800409 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800410}
411
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800412SurfaceFlinger::~SurfaceFlinger()
413{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800414}
415
Dan Stozac7014012014-02-14 15:03:43 -0800416void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800417{
418 // the window manager died on us. prepare its eulogy.
419
Andy McFadden13a082e2012-08-24 10:16:42 -0700420 // restore initial conditions (default device unblank, etc)
421 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800422
423 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700424 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800425}
426
Robert Carr1db73f62016-12-21 12:58:51 -0800427static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700428 status_t err = client->initCheck();
429 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800430 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800431 }
Robert Carr1db73f62016-12-21 12:58:51 -0800432 return nullptr;
433}
434
435sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
436 return initClient(new Client(this));
437}
438
439sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
440 const sp<IGraphicBufferProducer>& gbp) {
441 if (authenticateSurfaceTexture(gbp) == false) {
442 return nullptr;
443 }
444 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
445 if (layer == nullptr) {
446 return nullptr;
447 }
448
449 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800450}
451
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700452sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
453 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700454{
455 class DisplayToken : public BBinder {
456 sp<SurfaceFlinger> flinger;
457 virtual ~DisplayToken() {
458 // no more references, this display must be terminated
459 Mutex::Autolock _l(flinger->mStateLock);
460 flinger->mCurrentState.displays.removeItem(this);
461 flinger->setTransactionFlags(eDisplayTransactionNeeded);
462 }
463 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700464 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700465 : flinger(flinger) {
466 }
467 };
468
469 sp<BBinder> token = new DisplayToken(this);
470
471 Mutex::Autolock _l(mStateLock);
Dominik Laskowski663bd282018-04-19 15:26:54 -0700472 DisplayDeviceState info;
473 info.type = DisplayDevice::DISPLAY_VIRTUAL;
Andy McFadden8dfa92f2012-09-17 18:27:17 -0700474 info.displayName = displayName;
Dominik Laskowski663bd282018-04-19 15:26:54 -0700475 info.isSecure = secure;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700476 mCurrentState.displays.add(token, info);
Lloyd Pique4dccc412018-01-22 17:21:36 -0800477 mInterceptor->saveDisplayCreation(info);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700478 return token;
479}
480
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700481void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700482 Mutex::Autolock _l(mStateLock);
483
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700484 ssize_t idx = mCurrentState.displays.indexOfKey(displayToken);
Jesse Hall6c913be2013-08-08 12:15:49 -0700485 if (idx < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700486 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700487 return;
488 }
489
490 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -0700491 if (!info.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700492 ALOGE("destroyDisplay called for non-virtual display");
493 return;
494 }
Dominik Laskowski663bd282018-04-19 15:26:54 -0700495 mInterceptor->saveDisplayDeletion(info.sequenceId);
Jesse Hall6c913be2013-08-08 12:15:49 -0700496 mCurrentState.displays.removeItemsAt(idx);
497 setTransactionFlags(eDisplayTransactionNeeded);
498}
499
Mathias Agopiane57f2922012-08-09 16:29:12 -0700500sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Jesse Hall9e663de2013-08-16 14:28:37 -0700501 if (uint32_t(id) >= DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES) {
Mathias Agopiane57f2922012-08-09 16:29:12 -0700502 ALOGE("getDefaultDisplay: id=%d is not a valid default display id", id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800503 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700504 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700505 return mDisplayTokens[id];
Mathias Agopiane57f2922012-08-09 16:29:12 -0700506}
507
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800508void SurfaceFlinger::bootFinished()
509{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700510 if (mStartPropertySetThread->join() != NO_ERROR) {
511 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800512 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800513 const nsecs_t now = systemTime();
514 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000515 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700516
517 // wait patiently for the window manager death
518 const String16 name("window");
519 sp<IBinder> window(defaultServiceManager()->getService(name));
520 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700521 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700522 }
523
Steven Thomas050b2c82017-03-06 11:45:16 -0800524 if (mVrFlinger) {
525 mVrFlinger->OnBootFinished();
526 }
527
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700528 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700529 // formerly we would just kill the process, but we now ask it to exit so it
530 // can choose where to stop the animation.
531 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700532
533 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
534 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
535 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700536
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800537 postMessageAsync(new LambdaMessage([this] {
538 readPersistentProperties();
539 mBootStage = BootStage::FINISHED;
540 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800541}
542
Dan Stoza436ccf32018-06-21 12:10:12 -0700543uint32_t SurfaceFlinger::getNewTexture() {
544 {
545 std::lock_guard lock(mTexturePoolMutex);
546 if (!mTexturePool.empty()) {
547 uint32_t name = mTexturePool.back();
548 mTexturePool.pop_back();
549 ATRACE_INT("TexturePoolSize", mTexturePool.size());
550 return name;
551 }
552
553 // The pool was too small, so increase it for the future
554 ++mTexturePoolSize;
555 }
556
557 // The pool was empty, so we need to get a new texture name directly using a
558 // blocking call to the main thread
559 uint32_t name = 0;
560 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
561 return name;
562}
563
Mathias Agopian3f844832013-08-07 21:24:32 -0700564void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700565 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700566}
567
Lloyd Piquee83f9312018-02-01 12:53:17 -0800568class DispSyncSource final : public VSyncSource, private DispSync::Callback {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700569public:
Andy McFadden5167ec62014-05-22 13:08:43 -0700570 DispSyncSource(DispSync* dispSync, nsecs_t phaseOffset, bool traceVsync,
Tim Murray4a4e4a22016-04-19 16:29:23 +0000571 const char* name) :
572 mName(name),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700573 mValue(0),
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700574 mTraceVsync(traceVsync),
Tim Murray4a4e4a22016-04-19 16:29:23 +0000575 mVsyncOnLabel(String8::format("VsyncOn-%s", name)),
576 mVsyncEventLabel(String8::format("VSYNC-%s", name)),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700577 mDispSync(dispSync),
578 mCallbackMutex(),
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700579 mVsyncMutex(),
580 mPhaseOffset(phaseOffset),
581 mEnabled(false) {}
Mathias Agopiana4912602012-07-12 14:25:33 -0700582
Lloyd Piquee83f9312018-02-01 12:53:17 -0800583 ~DispSyncSource() override = default;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700584
Lloyd Piquee83f9312018-02-01 12:53:17 -0800585 void setVSyncEnabled(bool enable) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700586 Mutex::Autolock lock(mVsyncMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700587 if (enable) {
Tim Murray4a4e4a22016-04-19 16:29:23 +0000588 status_t err = mDispSync->addEventListener(mName, mPhaseOffset,
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700589 static_cast<DispSync::Callback*>(this));
590 if (err != NO_ERROR) {
591 ALOGE("error registering vsync callback: %s (%d)",
592 strerror(-err), err);
593 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700594 //ATRACE_INT(mVsyncOnLabel.string(), 1);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700595 } else {
596 status_t err = mDispSync->removeEventListener(
597 static_cast<DispSync::Callback*>(this));
598 if (err != NO_ERROR) {
599 ALOGE("error unregistering vsync callback: %s (%d)",
600 strerror(-err), err);
601 }
Andy McFadden5167ec62014-05-22 13:08:43 -0700602 //ATRACE_INT(mVsyncOnLabel.string(), 0);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700603 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700604 mEnabled = enable;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700605 }
606
Lloyd Piquee83f9312018-02-01 12:53:17 -0800607 void setCallback(VSyncSource::Callback* callback) override{
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700608 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700609 mCallback = callback;
610 }
611
Lloyd Piquee83f9312018-02-01 12:53:17 -0800612 void setPhaseOffset(nsecs_t phaseOffset) override {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700613 Mutex::Autolock lock(mVsyncMutex);
614
615 // Normalize phaseOffset to [0, period)
616 auto period = mDispSync->getPeriod();
617 phaseOffset %= period;
618 if (phaseOffset < 0) {
619 // If we're here, then phaseOffset is in (-period, 0). After this
620 // operation, it will be in (0, period)
621 phaseOffset += period;
622 }
623 mPhaseOffset = phaseOffset;
624
625 // If we're not enabled, we don't need to mess with the listeners
626 if (!mEnabled) {
627 return;
628 }
629
Dan Stoza84d619e2018-03-28 17:07:36 -0700630 status_t err = mDispSync->changePhaseOffset(static_cast<DispSync::Callback*>(this),
631 mPhaseOffset);
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700632 if (err != NO_ERROR) {
Dan Stoza84d619e2018-03-28 17:07:36 -0700633 ALOGE("error changing vsync offset: %s (%d)",
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700634 strerror(-err), err);
635 }
636 }
637
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700638private:
639 virtual void onDispSyncEvent(nsecs_t when) {
Lloyd Piquee83f9312018-02-01 12:53:17 -0800640 VSyncSource::Callback* callback;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700641 {
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700642 Mutex::Autolock lock(mCallbackMutex);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700643 callback = mCallback;
644
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700645 if (mTraceVsync) {
646 mValue = (mValue + 1) % 2;
Andy McFadden5167ec62014-05-22 13:08:43 -0700647 ATRACE_INT(mVsyncEventLabel.string(), mValue);
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700648 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700649 }
650
Peiyong Lin566a3b42018-01-09 18:22:43 -0800651 if (callback != nullptr) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700652 callback->onVSyncEvent(when);
653 }
654 }
655
Tim Murray4a4e4a22016-04-19 16:29:23 +0000656 const char* const mName;
657
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700658 int mValue;
659
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700660 const bool mTraceVsync;
Andy McFadden5167ec62014-05-22 13:08:43 -0700661 const String8 mVsyncOnLabel;
662 const String8 mVsyncEventLabel;
Jamie Gennis0a645cc2013-10-14 20:52:46 -0700663
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700664 DispSync* mDispSync;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700665
666 Mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800667 VSyncSource::Callback* mCallback = nullptr;
Dan Stozadb4ac3c2015-04-14 11:34:01 -0700668
669 Mutex mVsyncMutex; // Protects the following
670 nsecs_t mPhaseOffset;
671 bool mEnabled;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700672};
673
Lloyd Piquee83f9312018-02-01 12:53:17 -0800674class InjectVSyncSource final : public VSyncSource {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700675public:
Lloyd Piquee83f9312018-02-01 12:53:17 -0800676 InjectVSyncSource() = default;
677 ~InjectVSyncSource() override = default;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700678
Lloyd Piquee83f9312018-02-01 12:53:17 -0800679 void setCallback(VSyncSource::Callback* callback) override {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700680 std::lock_guard<std::mutex> lock(mCallbackMutex);
681 mCallback = callback;
682 }
683
Lloyd Piquee83f9312018-02-01 12:53:17 -0800684 void onInjectSyncEvent(nsecs_t when) {
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700685 std::lock_guard<std::mutex> lock(mCallbackMutex);
Chia-I Wu90f669f2017-10-05 14:24:41 -0700686 if (mCallback) {
687 mCallback->onVSyncEvent(when);
688 }
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700689 }
690
Lloyd Piquee83f9312018-02-01 12:53:17 -0800691 void setVSyncEnabled(bool) override {}
692 void setPhaseOffset(nsecs_t) override {}
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700693
694private:
695 std::mutex mCallbackMutex; // Protects the following
Lloyd Piquee83f9312018-02-01 12:53:17 -0800696 VSyncSource::Callback* mCallback = nullptr;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -0700697};
698
Wei Wangf9b05ee2017-07-19 20:59:39 -0700699// Do not call property_set on main thread which will be blocked by init
700// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700701void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700702 ALOGI( "SurfaceFlinger's main thread ready to run. "
703 "Initializing graphics H/W...");
704
Thierry Strudel2924d012017-08-14 15:19:37 -0700705 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900706
Steven Thomasb02664d2017-07-26 18:48:28 -0700707 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800708
Steven Thomasb02664d2017-07-26 18:48:28 -0700709 // start the EventThread
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800710 mEventThreadSource =
Lloyd Pique41be5d22018-06-21 13:11:48 -0700711 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
712 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
Lloyd Pique24b0a482018-03-09 18:52:26 -0800713 mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700714 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800715 impl::EventThread::InterceptVSyncsCallback(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800716 "appEventThread");
717 mSfEventThreadSource =
Lloyd Pique41be5d22018-06-21 13:11:48 -0700718 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
Lloyd Pique0fcde1b2017-12-20 16:50:21 -0800719 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800720
Lloyd Pique24b0a482018-03-09 18:52:26 -0800721 mSFEventThread =
722 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
Dominik Laskowski8c001672018-05-30 16:52:06 -0700723 [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -0800724 [this](nsecs_t timestamp) {
725 mInterceptor->saveVSyncEvent(timestamp);
726 },
727 "sfEventThread");
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800728 mEventQueue->setEventThread(mSFEventThread.get());
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200729 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
Dan Stoza9e56aa02015-11-02 13:00:03 -0800730
Steven Thomasb02664d2017-07-26 18:48:28 -0700731 // Get a RenderEngine for the given display / config (can't fail)
Lloyd Pique144e1162017-12-20 16:44:52 -0800732 getBE().mRenderEngine =
733 RE::impl::RenderEngine::create(HAL_PIXEL_FORMAT_RGBA_8888,
734 hasWideColorDisplay
735 ? RE::RenderEngine::WIDE_COLOR_SUPPORT
736 : 0);
David Sodmanbc815282017-11-05 18:57:52 -0800737 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700738
739 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
740 "Starting with vr flinger active is not currently supported.");
Lloyd Piquea822d522017-12-20 16:42:57 -0800741 getBE().mHwc.reset(
742 new HWComposer(std::make_unique<Hwc2::impl::Composer>(getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -0700743 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800744 // Process any initial hotplug and resulting display changes.
745 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700746 const auto display = getDefaultDisplayDeviceLocked();
747 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
748 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(display->getId()),
749 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800750
Lloyd Piquefcd86612017-12-14 17:15:36 -0800751 // make the default display GLContext current so that we can create textures
752 // when creating Layers (which may happens before we render something)
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700753 display->makeCurrent();
Lloyd Piquefcd86612017-12-14 17:15:36 -0800754
Steven Thomas050b2c82017-03-06 11:45:16 -0800755 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700756 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700757 // This callback is called from the vr flinger dispatch thread. We
758 // need to call signalTransaction(), which requires holding
759 // mStateLock when we're not on the main thread. Acquiring
760 // mStateLock from the vr flinger dispatch thread might trigger a
761 // deadlock in surface flinger (see b/66916578), so post a message
762 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700763 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700764 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
765 mVrFlingerRequestsDisplay = requestDisplay;
766 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700767 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800768 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700769 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
770 getHwComposer()
771 .getHwcDisplayId(display->getId())
772 .value_or(0),
773 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800774 if (!mVrFlinger) {
775 ALOGE("Failed to start vrflinger");
776 }
777 }
778
Lloyd Pique379adc12018-01-22 17:31:47 -0800779 mEventControlThread = std::make_unique<impl::EventControlThread>(
780 [this](bool enabled) { setVsyncEnabled(HWC_DISPLAY_PRIMARY, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700781
Mathias Agopian92a979a2012-08-02 18:32:23 -0700782 // initialize our drawing state
783 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700784
Andy McFadden13a082e2012-08-24 10:16:42 -0700785 // set initial conditions (e.g. unblank default device)
786 initializeDisplays();
787
David Sodmanbc815282017-11-05 18:57:52 -0800788 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700789
Wei Wangf9b05ee2017-07-19 20:59:39 -0700790 // Inform native graphics APIs whether the present timestamp is supported:
791 if (getHwComposer().hasCapability(
792 HWC2::Capability::PresentFenceIsNotReliable)) {
793 mStartPropertySetThread = new StartPropertySetThread(false);
794 } else {
795 mStartPropertySetThread = new StartPropertySetThread(true);
796 }
797
798 if (mStartPropertySetThread->Start() != NO_ERROR) {
799 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800800 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800801
Chia-I Wud49d6692018-06-27 07:17:41 +0800802 // This is a hack. Per definition of getDataspaceSaturationMatrix, the returned matrix
803 // is used to saturate legacy sRGB content. However, to make sure the same color under
804 // Display P3 will be saturated to the same color, we intentionally break the API spec
805 // and apply this saturation matrix on Display P3 content. Unless the risk of applying
806 // such saturation matrix on Display P3 is understood fully, the API should always return
807 // identify matrix.
808 mEnhancedSaturationMatrix = getBE().mHwc->getDataspaceSaturationMatrix(display->getId(),
809 Dataspace::SRGB_LINEAR);
810
811 // we will apply this on Display P3.
812 if (mEnhancedSaturationMatrix != mat4()) {
813 ColorSpace srgb(ColorSpace::sRGB());
814 ColorSpace displayP3(ColorSpace::DisplayP3());
815 mat4 srgbToP3 = mat4(ColorSpaceConnector(srgb, displayP3).getTransform());
816 mat4 p3ToSrgb = mat4(ColorSpaceConnector(displayP3, srgb).getTransform());
817 mEnhancedSaturationMatrix = srgbToP3 * mEnhancedSaturationMatrix * p3ToSrgb;
818 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800819
Dan Stoza9e56aa02015-11-02 13:00:03 -0800820 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700821}
822
Romain Guy11d63f42017-07-20 12:47:14 -0700823void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700824 Mutex::Autolock _l(mStateLock);
825
Romain Guy11d63f42017-07-20 12:47:14 -0700826 char value[PROPERTY_VALUE_MAX];
827
828 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800829 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700830 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800831 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100832
833 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700834 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700835}
836
Mathias Agopiana67e4182012-06-19 17:26:12 -0700837void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800838 // Start boot animation service by setting a property mailbox
839 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700840 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800841 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700842 if (mStartPropertySetThread->join() != NO_ERROR) {
843 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800844 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700845}
846
Mathias Agopian875d8e12013-06-07 15:35:48 -0700847size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800848 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700849}
850
Mathias Agopian875d8e12013-06-07 15:35:48 -0700851size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800852 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700853}
854
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800855// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800856
Jamie Gennis582270d2011-08-17 18:19:00 -0700857bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800858 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800859 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800860 return authenticateSurfaceTextureLocked(bufferProducer);
861}
862
863bool SurfaceFlinger::authenticateSurfaceTextureLocked(
864 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800865 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800866 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800867}
868
Brian Anderson6b376712017-04-04 10:51:39 -0700869status_t SurfaceFlinger::getSupportedFrameTimestamps(
870 std::vector<FrameEvent>* outSupported) const {
871 *outSupported = {
872 FrameEvent::REQUESTED_PRESENT,
873 FrameEvent::ACQUIRE,
874 FrameEvent::LATCH,
875 FrameEvent::FIRST_REFRESH_START,
876 FrameEvent::LAST_REFRESH_START,
877 FrameEvent::GPU_COMPOSITION_DONE,
878 FrameEvent::DEQUEUE_READY,
879 FrameEvent::RELEASE,
880 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700881 ConditionalLock _l(mStateLock,
882 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700883 if (!getHwComposer().hasCapability(
884 HWC2::Capability::PresentFenceIsNotReliable)) {
885 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
886 }
887 return NO_ERROR;
888}
889
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700890status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
891 Vector<DisplayInfo>* configs) {
892 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700893 return BAD_VALUE;
894 }
895
Jesse Hall692c7232012-11-08 15:41:56 -0800896 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700897 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
898 if (displayToken == mDisplayTokens[i]) {
Mathias Agopian1604f772012-09-18 21:54:42 -0700899 type = i;
900 break;
901 }
902 }
903
904 if (type < 0) {
905 return type;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700906 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700907
Mathias Agopian8b736f12012-08-13 17:54:26 -0700908 // TODO: Not sure if display density should handled by SF any longer
909 class Density {
910 static int getDensityFromProperty(char const* propName) {
911 char property[PROPERTY_VALUE_MAX];
912 int density = 0;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800913 if (property_get(propName, property, nullptr) > 0) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700914 density = atoi(property);
915 }
916 return density;
917 }
918 public:
919 static int getEmuDensity() {
920 return getDensityFromProperty("qemu.sf.lcd_density"); }
921 static int getBuildDensity() {
922 return getDensityFromProperty("ro.sf.lcd_density"); }
923 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700924
Dan Stoza7f7da322014-05-02 15:26:25 -0700925 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700926
Steven Thomas6d8110b2017-08-31 18:24:21 -0700927 ConditionalLock _l(mStateLock,
928 std::this_thread::get_id() != mMainThreadId);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800929 for (const auto& hwConfig : getHwComposer().getConfigs(type)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700930 DisplayInfo info = DisplayInfo();
931
Dan Stoza9e56aa02015-11-02 13:00:03 -0800932 float xdpi = hwConfig->getDpiX();
933 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700934
935 if (type == DisplayDevice::DISPLAY_PRIMARY) {
936 // The density of the device is provided by a build property
937 float density = Density::getBuildDensity() / 160.0f;
938 if (density == 0) {
939 // the build doesn't provide a density -- this is wrong!
940 // use xdpi instead
941 ALOGE("ro.sf.lcd_density must be defined as a build property");
942 density = xdpi / 160.0f;
943 }
944 if (Density::getEmuDensity()) {
945 // if "qemu.sf.lcd_density" is specified, it overrides everything
946 xdpi = ydpi = density = Density::getEmuDensity();
947 density /= 160.0f;
948 }
949 info.density = density;
950
951 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700952 const auto display = getDefaultDisplayDeviceLocked();
953 info.orientation = display ? display->getOrientation() : 0;
Dan Stoza7f7da322014-05-02 15:26:25 -0700954 } else {
955 // TODO: where should this value come from?
956 static const int TV_DENSITY = 213;
957 info.density = TV_DENSITY / 160.0f;
958 info.orientation = 0;
959 }
960
Dan Stoza9e56aa02015-11-02 13:00:03 -0800961 info.w = hwConfig->getWidth();
962 info.h = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700963 info.xdpi = xdpi;
964 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800965 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900966 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800967
Andy McFadden91b2ca82014-06-13 14:04:23 -0700968 // This is how far in advance a buffer must be queued for
969 // presentation at a given time. If you want a buffer to appear
970 // on the screen at time N, you must submit the buffer before
971 // (N - presentationDeadline).
972 //
973 // Normally it's one full refresh period (to give SF a chance to
974 // latch the buffer), but this can be reduced by configuring a
975 // DispSync offset. Any additional delays introduced by the hardware
976 // composer or panel must be accounted for here.
977 //
978 // We add an additional 1ms to allow for processing time and
979 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800980 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800981 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700982
983 // All non-virtual displays are currently considered secure.
984 info.secure = true;
985
Iris Chang7501ed62018-04-30 14:45:42 +0800986 if (type == DisplayDevice::DISPLAY_PRIMARY &&
987 mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
988 std::swap(info.w, info.h);
989 }
990
Michael Wright28f24d02016-07-12 13:30:53 -0700991 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700992 }
993
Dan Stoza7f7da322014-05-02 15:26:25 -0700994 return NO_ERROR;
995}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700996
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700997status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
998 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700999 return BAD_VALUE;
1000 }
1001
1002 // FIXME for now we always return stats for the primary display
1003 memset(stats, 0, sizeof(*stats));
Lloyd Pique41be5d22018-06-21 13:11:48 -07001004 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
1005 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
Lajos Molnar67d8bd62014-09-11 14:58:45 -07001006 return NO_ERROR;
1007}
1008
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001009int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
1010 const auto display = getDisplayDevice(displayToken);
1011 if (!display) {
1012 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +08001013 return BAD_VALUE;
1014 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001015
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001016 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -07001017}
Jamie Gennisdd3cb842012-10-19 18:19:11 -07001018
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001019void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
1020 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001021 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001022 return;
1023 }
1024
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001025 if (display->isVirtual()) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001026 ALOGW("Trying to set config for virtual display");
1027 return;
1028 }
1029
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001030 display->setActiveConfig(mode);
1031 getHwComposer().setActiveConfig(display->getDisplayType(), mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001032}
1033
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001034status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001035 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001036 Vector<DisplayInfo> configs;
1037 getDisplayConfigs(displayToken, &configs);
1038 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
1039 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
1040 configs.size());
1041 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -07001042 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001043 const auto display = getDisplayDevice(displayToken);
1044 if (!display) {
1045 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
1046 displayToken.get());
1047 } else if (display->isVirtual()) {
1048 ALOGW("Attempt to set active config %d for virtual display", mode);
1049 } else {
1050 setActiveConfigInternal(display, mode);
1051 }
1052 }));
1053
Mathias Agopian888c8222012-08-04 21:10:38 -07001054 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001055}
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001056status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1057 Vector<ColorMode>* outColorModes) {
1058 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001059 return BAD_VALUE;
1060 }
1061
Michael Wright28f24d02016-07-12 13:30:53 -07001062 int32_t type = NAME_NOT_FOUND;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001063 for (int i = 0; i < DisplayDevice::NUM_BUILTIN_DISPLAY_TYPES; ++i) {
1064 if (displayToken == mDisplayTokens[i]) {
Michael Wright28f24d02016-07-12 13:30:53 -07001065 type = i;
1066 break;
1067 }
1068 }
1069
1070 if (type < 0) {
1071 return type;
1072 }
1073
Peiyong Lina52f0292018-03-14 17:26:31 -07001074 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001075 {
1076 ConditionalLock _l(mStateLock,
1077 std::this_thread::get_id() != mMainThreadId);
1078 modes = getHwComposer().getColorModes(type);
1079 }
Michael Wright28f24d02016-07-12 13:30:53 -07001080 outColorModes->clear();
1081 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1082
1083 return NO_ERROR;
1084}
1085
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001086ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1087 if (const auto display = getDisplayDevice(displayToken)) {
1088 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001089 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001090 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001091}
1092
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001093void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1094 Dataspace dataSpace, RenderIntent renderIntent) {
1095 ColorMode currentMode = display->getActiveColorMode();
1096 Dataspace currentDataSpace = display->getCompositionDataSpace();
1097 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001098
Peiyong Lin38e9a562018-04-10 16:24:20 -07001099 if (mode == currentMode && dataSpace == currentDataSpace &&
1100 renderIntent == currentRenderIntent) {
1101 return;
1102 }
1103
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001104 if (display->isVirtual()) {
Peiyong Lin38e9a562018-04-10 16:24:20 -07001105 ALOGW("Trying to set config for virtual display");
1106 return;
1107 }
1108
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001109 display->setActiveColorMode(mode);
1110 display->setCompositionDataSpace(dataSpace);
1111 display->setActiveRenderIntent(renderIntent);
1112 getHwComposer().setActiveColorMode(display->getDisplayType(), mode, renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001113
1114 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), type=%d",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001115 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
1116 renderIntent, display->getDisplayType());
Michael Wright28f24d02016-07-12 13:30:53 -07001117}
1118
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001119status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001120 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001121 Vector<ColorMode> modes;
1122 getDisplayColorModes(displayToken, &modes);
1123 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1124 if (mode < ColorMode::NATIVE || !exists) {
1125 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1126 decodeColorMode(mode).c_str(), mode, displayToken.get());
1127 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001128 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001129 const auto display = getDisplayDevice(displayToken);
1130 if (!display) {
1131 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1132 decodeColorMode(mode).c_str(), mode, displayToken.get());
1133 } else if (display->isVirtual()) {
1134 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1135 decodeColorMode(mode).c_str(), mode);
1136 } else {
1137 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1138 RenderIntent::COLORIMETRIC);
1139 }
1140 }));
1141
Michael Wright28f24d02016-07-12 13:30:53 -07001142 return NO_ERROR;
1143}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001144
Svetoslavd85084b2014-03-20 10:28:31 -07001145status_t SurfaceFlinger::clearAnimationFrameStats() {
1146 Mutex::Autolock _l(mStateLock);
1147 mAnimFrameTracker.clearStats();
1148 return NO_ERROR;
1149}
1150
1151status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1152 Mutex::Autolock _l(mStateLock);
1153 mAnimFrameTracker.getStats(outStats);
1154 return NO_ERROR;
1155}
1156
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001157status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1158 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001159 Mutex::Autolock _l(mStateLock);
1160
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001161 const auto display = getDisplayDeviceLocked(displayToken);
1162 if (!display) {
1163 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001164 return BAD_VALUE;
1165 }
1166
Peiyong Linfb069302018-04-25 14:34:31 -07001167 // At this point the DisplayDeivce should already be set up,
1168 // meaning the luminance information is already queried from
1169 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001170 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001171 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1172 capabilities.getDesiredMaxLuminance(),
1173 capabilities.getDesiredMaxAverageLuminance(),
1174 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001175
1176 return NO_ERROR;
1177}
1178
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001179status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001180 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001181 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001182
Chia-I Wu90f669f2017-10-05 14:24:41 -07001183 if (mInjectVSyncs == enable) {
1184 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001185 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001186
1187 if (enable) {
1188 ALOGV("VSync Injections enabled");
1189 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001190 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001191 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001192 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001193 impl::EventThread::InterceptVSyncsCallback(),
1194 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001195 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001196 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001197 } else {
1198 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001199 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001200 }
1201
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001202 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001203 }));
1204
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001205 return NO_ERROR;
1206}
1207
1208status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001209 Mutex::Autolock _l(mStateLock);
1210
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001211 if (!mInjectVSyncs) {
1212 ALOGE("VSync Injections not enabled");
1213 return BAD_VALUE;
1214 }
1215 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1216 ALOGV("Injecting VSync inside SurfaceFlinger");
1217 mVSyncInjector->onInjectSyncEvent(when);
1218 }
1219 return NO_ERROR;
1220}
1221
Lloyd Pique755e3192018-01-31 16:46:15 -08001222status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1223 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001224 // Try to acquire a lock for 1s, fail gracefully
1225 const status_t err = mStateLock.timedLock(s2ns(1));
1226 const bool locked = (err == NO_ERROR);
1227 if (!locked) {
1228 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1229 return TIMED_OUT;
1230 }
1231
1232 outLayers->clear();
1233 mCurrentState.traverseInZOrder([&](Layer* layer) {
1234 outLayers->push_back(layer->getLayerDebugInfo());
1235 });
1236
1237 mStateLock.unlock();
1238 return NO_ERROR;
1239}
1240
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001241// ----------------------------------------------------------------------------
1242
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001243sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1244 ISurfaceComposer::VsyncSource vsyncSource) {
1245 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1246 return mSFEventThread->createEventConnection();
1247 } else {
1248 return mEventThread->createEventConnection();
1249 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001250}
1251
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001252// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001253
1254void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001255 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001256}
1257
1258void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001259 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001260}
1261
1262void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001263 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001264}
1265
1266void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001267 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001268 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001269}
1270
1271status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001272 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001273 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001274}
1275
1276status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001277 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001278 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001279 if (res == NO_ERROR) {
1280 msg->wait();
1281 }
1282 return res;
1283}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001284
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001285void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001286 do {
1287 waitForEvent();
1288 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001289}
1290
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001291void SurfaceFlinger::enableHardwareVsync() {
1292 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001293 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001294 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001295 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001296 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001297 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001298}
1299
Jesse Hall948fe0c2013-10-14 12:56:09 -07001300void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001301 Mutex::Autolock _l(mHWVsyncLock);
1302
Jesse Hall948fe0c2013-10-14 12:56:09 -07001303 if (makeAvailable) {
1304 mHWVsyncAvailable = true;
1305 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001306 // Hardware vsync is not currently available, so abort the resync
1307 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001308 return;
1309 }
1310
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001311 const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
1312 if (!getHwComposer().isConnected(displayId)) {
1313 return;
1314 }
1315
1316 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001317 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001318
Lloyd Pique41be5d22018-06-21 13:11:48 -07001319 mPrimaryDispSync->reset();
1320 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001321
1322 if (!mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001323 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001324 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001325 mPrimaryHWVsyncEnabled = true;
1326 }
1327}
1328
Jesse Hall948fe0c2013-10-14 12:56:09 -07001329void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001330 Mutex::Autolock _l(mHWVsyncLock);
1331 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001332 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001333 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001334 mPrimaryHWVsyncEnabled = false;
1335 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001336 if (makeUnavailable) {
1337 mHWVsyncAvailable = false;
1338 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001339}
1340
Tim Murray4a4e4a22016-04-19 16:29:23 +00001341void SurfaceFlinger::resyncWithRateLimit() {
1342 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001343
1344 // No explicit locking is needed here since EventThread holds a lock while calling this method
1345 static nsecs_t sLastResyncAttempted = 0;
1346 const nsecs_t now = systemTime();
1347 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001348 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001349 }
Dan Stoza57164302017-05-08 14:03:54 -07001350 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001351}
1352
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001353void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1354 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001355 ATRACE_NAME("SF onVsync");
1356
Steven Thomas3cfac282017-02-06 12:29:30 -08001357 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001358 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001359 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001360 return;
1361 }
1362
1363 int32_t type;
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001364 if (!getBE().mHwc->onVsync(hwcDisplayId, timestamp, &type)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001365 return;
1366 }
1367
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001368 if (type != DisplayDevice::DISPLAY_PRIMARY) {
1369 // For now, we don't do anything with external display vsyncs.
1370 return;
1371 }
1372
Jamie Gennisd1700752013-10-14 12:22:52 -07001373 bool needsHwVsync = false;
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001374
Jamie Gennisd1700752013-10-14 12:22:52 -07001375 { // Scope for the lock
1376 Mutex::Autolock _l(mHWVsyncLock);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001377 if (mPrimaryHWVsyncEnabled) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001378 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001379 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001380 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001381
1382 if (needsHwVsync) {
1383 enableHardwareVsync();
1384 } else {
1385 disableHardwareVsync(false);
1386 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001387}
1388
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001389void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001390 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1391 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001392}
1393
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001394void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001395 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001396 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001397 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001398
Lloyd Piqueba04e622017-12-14 17:11:26 -08001399 // Ignore events that do not have the right sequenceId.
1400 if (sequenceId != getBE().mComposerSequenceId) {
1401 return;
1402 }
1403
Steven Thomasb02664d2017-07-26 18:48:28 -07001404 // Only lock if we're not on the main thread. This function is normally
1405 // called on a hwbinder thread, but for the primary display it's called on
1406 // the main thread with the state lock already held, so don't attempt to
1407 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001408 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001409
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001410 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001411
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001412 if (std::this_thread::get_id() == mMainThreadId) {
1413 // Process all pending hot plug events immediately if we are on the main thread.
1414 processDisplayHotplugEventsLocked();
1415 }
1416
Lloyd Piqueba04e622017-12-14 17:11:26 -08001417 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001418}
1419
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001420void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001421 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001422 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001423 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001424 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001425 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001426}
1427
Dan Stoza9e56aa02015-11-02 13:00:03 -08001428void SurfaceFlinger::setVsyncEnabled(int disp, int enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001429 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001430 Mutex::Autolock lock(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001431 getHwComposer().setVsyncEnabled(disp,
1432 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
Mathias Agopian86303202012-07-24 22:46:10 -07001433}
1434
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001435// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001436void SurfaceFlinger::resetDisplayState() {
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001437 disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001438 // Clear the drawing state so that the logic inside of
1439 // handleTransactionLocked will fire. It will determine the delta between
1440 // mCurrentState and mDrawingState and re-apply all changes when we make the
1441 // transition.
1442 mDrawingState.displays.clear();
Chia-I Wu7f402902017-11-09 12:51:10 -08001443 getRenderEngine().resetCurrentSurface();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001444 mDisplays.clear();
1445}
1446
Steven Thomas050b2c82017-03-06 11:45:16 -08001447void SurfaceFlinger::updateVrFlinger() {
1448 if (!mVrFlinger)
1449 return;
1450 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001451 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001452 return;
1453 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001454
David Sodman105b7dc2017-11-04 20:28:14 -07001455 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001456 ALOGE("Vr flinger is only supported for remote hardware composer"
1457 " service connections. Ignoring request to transition to vr"
1458 " flinger.");
1459 mVrFlingerRequestsDisplay = false;
1460 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001461 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001462
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001463 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001464
Steven Thomas0123ac62018-07-12 11:32:34 -07001465 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001466 LOG_ALWAYS_FATAL_IF(!display);
1467 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001468 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1469 // called below. Clear the reference now so we don't accidentally use it
1470 // later.
1471 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001472
Steven Thomasb02664d2017-07-26 18:48:28 -07001473 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001474 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001475 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001476
Steven Thomasb02664d2017-07-26 18:48:28 -07001477 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001478 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Piquea822d522017-12-20 16:42:57 -08001479 getBE().mHwc.reset(new HWComposer(std::make_unique<Hwc2::impl::Composer>(
1480 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName)));
David Sodman105b7dc2017-11-04 20:28:14 -07001481 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001482
David Sodman105b7dc2017-11-04 20:28:14 -07001483 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1484 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001485
1486 if (vrFlingerRequestsDisplay) {
1487 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001488 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001489
1490 mVisibleRegionsDirty = true;
1491 invalidateHwcGeometry();
1492
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001493 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001494 display = getDefaultDisplayDeviceLocked();
1495 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001496 setPowerModeInternal(display, currentDisplayPowerMode, /*stateLockHeld*/ true);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001497
Steven Thomasb02664d2017-07-26 18:48:28 -07001498 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001499 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001500 const nsecs_t period = activeConfig->getVsyncPeriod();
1501 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001502
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001503 // The present fences returned from vr_hwc are not an accurate
1504 // representation of vsync times.
Lloyd Pique41be5d22018-06-21 13:11:48 -07001505 mPrimaryDispSync->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() ||
1506 !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001507
Steven Thomasb02664d2017-07-26 18:48:28 -07001508 // Use phase of 0 since phase is not known.
1509 // Use latency of 0, which will snap to the ideal latency.
1510 setCompositorTimingSnapped(0, period, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001511
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001512 resyncToHardwareVsync(false);
1513
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001514 android_atomic_or(1, &mRepaintEverything);
1515 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001516}
1517
Mathias Agopian4fec8732012-06-29 14:12:52 -07001518void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001519 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001520 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001521 case MessageQueue::INVALIDATE: {
Dan Stoza50182882016-07-08 12:02:20 -07001522 bool frameMissed = !mHadClientComposition &&
1523 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001524 (mPreviousPresentFence->getSignalTime() ==
1525 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001526 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001527 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001528 if (frameMissed) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001529 mTimeStats.incrementMissedFrames();
1530 if (mPropagateBackpressure) {
1531 signalLayerUpdate();
1532 break;
1533 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001534 }
Dan Stoza50182882016-07-08 12:02:20 -07001535
Steven Thomas050b2c82017-03-06 11:45:16 -08001536 // Now that we're going to make it to the handleMessageTransaction()
1537 // call below it's safe to call updateVrFlinger(), which will
1538 // potentially trigger a display handoff.
1539 updateVrFlinger();
1540
Dan Stoza6b9454d2014-11-07 16:00:59 -08001541 bool refreshNeeded = handleMessageTransaction();
1542 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001543 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001544 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001545 // Signal a refresh if a transaction modified the window state,
1546 // a new buffer was latched, or if HWC has requested a full
1547 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001548 signalRefresh();
1549 }
1550 break;
1551 }
1552 case MessageQueue::REFRESH: {
1553 handleMessageRefresh();
1554 break;
1555 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001556 }
1557}
1558
Dan Stoza6b9454d2014-11-07 16:00:59 -08001559bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001560 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001561 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001562 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001563 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001564 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001565 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001566}
1567
Dan Stoza6b9454d2014-11-07 16:00:59 -08001568bool SurfaceFlinger::handleMessageInvalidate() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001569 ATRACE_CALL();
Dan Stoza6b9454d2014-11-07 16:00:59 -08001570 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001571}
1572
1573void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001574 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001575
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001576 mRefreshPending = false;
1577
Lloyd Pique074e8122018-07-26 12:57:23 -07001578 nsecs_t refreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1579
1580 preComposition(refreshStartTime);
1581 rebuildLayerStacks();
1582 setUpHWComposer();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001583 doDebugFlashRegions();
Adrian Roos1e1a1282017-11-01 19:05:31 +01001584 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001585 logLayerStats();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001586 doComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001587 postComposition(refreshStartTime);
Dan Stoza05dacfb2016-07-01 13:33:38 -07001588
Dan Stozabfbffeb2016-07-21 14:49:33 -07001589 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001590 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001591 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001592 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001593 }
Jorim Jaggi90535212018-05-23 23:44:06 +02001594 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001595
Dan Stoza9e56aa02015-11-02 13:00:03 -08001596 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001597}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001598
Mathias Agopiancd60f992012-08-16 16:28:27 -07001599void SurfaceFlinger::doDebugFlashRegions()
1600{
1601 // is debugging enabled
1602 if (CC_LIKELY(!mDebugRegion))
1603 return;
1604
1605 const bool repaintEverything = mRepaintEverything;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001606 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001607 if (display->isPoweredOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001608 // transform the dirty region into this screen's coordinate space
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001609 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001610 if (!dirtyRegion.isEmpty()) {
1611 // redraw the whole screen
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001612 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001613
1614 // and draw the dirty region
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001615 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08001616 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07001617 engine.fillRegionWithColor(dirtyRegion, height, 1, 0, 1, 1);
1618
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001619 display->swapBuffers(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001620 }
1621 }
1622 }
1623
1624 postFramebuffer();
1625
1626 if (mDebugRegion > 1) {
1627 usleep(mDebugRegion * 1000);
1628 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001629
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001630 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001631 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07001632 continue;
1633 }
1634
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001635 status_t result = display->prepareFrame(*getBE().mHwc);
1636 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %d failed: %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07001637 display->getId(), result, strerror(-result));
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001638 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001639}
1640
Adrian Roos1e1a1282017-11-01 19:05:31 +01001641void SurfaceFlinger::doTracing(const char* where) {
1642 ATRACE_CALL();
1643 ATRACE_NAME(where);
1644 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001645 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001646 }
1647}
1648
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001649void SurfaceFlinger::logLayerStats() {
1650 ATRACE_CALL();
1651 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001652 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001653 if (display->isPrimary()) {
1654 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001655 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001656 }
1657 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001658
1659 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001660 }
1661}
1662
Lloyd Pique074e8122018-07-26 12:57:23 -07001663void SurfaceFlinger::preComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001664{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001665 ATRACE_CALL();
1666 ALOGV("preComposition");
1667
Mathias Agopiancd60f992012-08-16 16:28:27 -07001668 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001669 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique074e8122018-07-26 12:57:23 -07001670 if (layer->onPreComposition(refreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001671 needExtraInvalidate = true;
1672 }
Robert Carr2047fae2016-11-28 14:09:09 -08001673 });
1674
Mathias Agopiancd60f992012-08-16 16:28:27 -07001675 if (needExtraInvalidate) {
1676 signalLayerUpdate();
1677 }
1678}
1679
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001680void SurfaceFlinger::updateCompositorTiming(
1681 nsecs_t vsyncPhase, nsecs_t vsyncInterval, nsecs_t compositeTime,
1682 std::shared_ptr<FenceTime>& presentFenceTime) {
1683 // Update queue of past composite+present times and determine the
1684 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001685 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001686 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001687 while (!getBE().mCompositePresentTimes.empty()) {
1688 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001689 // Cached values should have been updated before calling this method,
1690 // which helps avoid duplicate syscalls.
1691 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1692 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1693 break;
1694 }
1695 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001696 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001697 }
1698
1699 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001700 while (getBE().mCompositePresentTimes.size() > 16) {
1701 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001702 }
1703
Brian Andersond0010582017-03-07 13:20:31 -08001704 setCompositorTimingSnapped(
1705 vsyncPhase, vsyncInterval, compositeToPresentLatency);
1706}
1707
1708void SurfaceFlinger::setCompositorTimingSnapped(nsecs_t vsyncPhase,
1709 nsecs_t vsyncInterval, nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001710 // Integer division and modulo round toward 0 not -inf, so we need to
1711 // treat negative and positive offsets differently.
Brian Andersond0010582017-03-07 13:20:31 -08001712 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0) ?
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001713 (vsyncInterval - (sfVsyncPhaseOffsetNs % vsyncInterval)) :
1714 ((-sfVsyncPhaseOffsetNs) % vsyncInterval);
1715
Brian Andersond0010582017-03-07 13:20:31 -08001716 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1717 if (idealLatency <= 0) {
1718 idealLatency = vsyncInterval;
1719 }
1720
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001721 // Snap the latency to a value that removes scheduling jitter from the
1722 // composition and present times, which often have >1ms of jitter.
1723 // Reducing jitter is important if an app attempts to extrapolate
1724 // something (such as user input) to an accurate diasplay time.
1725 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1726 // with (presentLatency % interval).
Brian Andersond0010582017-03-07 13:20:31 -08001727 nsecs_t bias = vsyncInterval / 2;
1728 int64_t extraVsyncs =
1729 (compositeToPresentLatency - idealLatency + bias) / vsyncInterval;
1730 nsecs_t snappedCompositeToPresentLatency = (extraVsyncs > 0) ?
1731 idealLatency + (extraVsyncs * vsyncInterval) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001732
David Sodman99974d22017-11-28 12:04:33 -08001733 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1734 getBE().mCompositorTiming.deadline = vsyncPhase - idealLatency;
1735 getBE().mCompositorTiming.interval = vsyncInterval;
1736 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001737}
1738
Lloyd Pique074e8122018-07-26 12:57:23 -07001739void SurfaceFlinger::postComposition(nsecs_t refreshStartTime)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001740{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001741 ATRACE_CALL();
1742 ALOGV("postComposition");
1743
Brian Anderson3546a3f2016-07-14 11:51:14 -07001744 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001745 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001746 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001747 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001748 }
1749
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001750 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001751 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001752
David Sodman73beded2017-11-15 11:56:06 -08001753 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001754 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001755 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001756 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001757 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001758 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001759 } else {
1760 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1761 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001762
David Sodman73beded2017-11-15 11:56:06 -08001763 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001764 mPreviousPresentFence =
1765 display ? getHwComposer().getPresentFence(display->getId()) : Fence::NO_FENCE;
1766 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001767 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001768
Lloyd Pique41be5d22018-06-21 13:11:48 -07001769 nsecs_t vsyncPhase = mPrimaryDispSync->computeNextRefresh(0);
1770 nsecs_t vsyncInterval = mPrimaryDispSync->getPeriod();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001771
Lloyd Pique074e8122018-07-26 12:57:23 -07001772 // We use the refreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001773 // when we started doing work for this frame, but that should be okay
1774 // since updateCompositorTiming has snapping logic.
1775 updateCompositorTiming(
Lloyd Pique074e8122018-07-26 12:57:23 -07001776 vsyncPhase, vsyncInterval, refreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001777 CompositorTiming compositorTiming;
1778 {
David Sodman99974d22017-11-28 12:04:33 -08001779 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1780 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001781 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001782
Robert Carr2047fae2016-11-28 14:09:09 -08001783 mDrawingState.traverseInZOrder([&](Layer* layer) {
1784 bool frameLatched = layer->onPostComposition(glCompositionDoneFenceTime,
Brian Anderson4e606e32017-03-16 15:34:57 -07001785 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001786 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001787 recordBufferingStats(layer->getName().string(),
1788 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001789 }
Robert Carr2047fae2016-11-28 14:09:09 -08001790 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001791
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001792 if (presentFenceTime->isValid()) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001793 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001794 enableHardwareVsync();
1795 } else {
Jesse Hall948fe0c2013-10-14 12:56:09 -07001796 disableHardwareVsync(false);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001797 }
1798 }
1799
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001800 if (!hasSyncFramework) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001801 if (display && getHwComposer().isConnected(display->getId()) && display->isPoweredOn()) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001802 enableHardwareVsync();
1803 }
1804 }
1805
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001806 if (mAnimCompositionPending) {
1807 mAnimCompositionPending = false;
1808
Brian Anderson4e606e32017-03-16 15:34:57 -07001809 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001810 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001811 std::move(presentFenceTime));
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001812 } else if (display && getHwComposer().isConnected(display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001813 // The HWC doesn't support present fences, so use the refresh
1814 // timestamp instead.
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001815 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001816 mAnimFrameTracker.setActualPresentTime(presentTime);
1817 }
1818 mAnimFrameTracker.advanceFrame();
1819 }
Dan Stozab90cf072015-03-05 11:05:59 -08001820
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001821 mTimeStats.incrementTotalFrames();
1822 if (mHadClientComposition) {
1823 mTimeStats.incrementClientCompositionFrames();
1824 }
1825
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001826 if (display && getHwComposer().isConnected(display->getId()) &&
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001827 display->getPowerMode() == HWC_POWER_MODE_OFF) {
Dan Stozab90cf072015-03-05 11:05:59 -08001828 return;
1829 }
1830
1831 nsecs_t currentTime = systemTime();
1832 if (mHasPoweredOff) {
1833 mHasPoweredOff = false;
1834 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001835 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001836 size_t numPeriods = static_cast<size_t>(elapsedTime / vsyncInterval);
David Sodman4a36e932017-11-07 14:29:47 -08001837 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1838 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001839 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001840 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001841 }
David Sodman4a36e932017-11-07 14:29:47 -08001842 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001843 }
David Sodman4a36e932017-11-07 14:29:47 -08001844 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001845
1846 {
1847 std::lock_guard lock(mTexturePoolMutex);
1848 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1849 if (refillCount > 0) {
1850 const size_t offset = mTexturePool.size();
1851 mTexturePool.resize(mTexturePoolSize);
1852 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1853 ATRACE_INT("TexturePoolSize", mTexturePool.size());
1854 }
1855 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001856}
1857
1858void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08001859 ATRACE_CALL();
1860 ALOGV("rebuildLayerStacks");
1861
Mathias Agopiancd60f992012-08-16 16:28:27 -07001862 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07001863 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07001864 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07001865 mVisibleRegionsDirty = false;
1866 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001867
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001868 for (const auto& pair : mDisplays) {
1869 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07001870 Region opaqueRegion;
1871 Region dirtyRegion;
1872 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08001873 Vector<sp<Layer>> layersNeedingFences;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001874 const Transform& tr = display->getTransform();
1875 const Rect bounds = display->getBounds();
1876 if (display->isPoweredOn()) {
1877 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001878
Jeff Sharkey76488112017-02-27 14:15:18 -07001879 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08001880 bool hwcLayerDestroyed = false;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001881 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07001882 Region drawRegion(tr.transform(
1883 layer->visibleNonTransparentRegion));
1884 drawRegion.andSelf(bounds);
1885 if (!drawRegion.isEmpty()) {
1886 layersSortedByZ.add(layer);
1887 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001888 // Clear out the HWC layer if this layer was
1889 // previously visible, but no longer is
1890 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Jeff Sharkey76488112017-02-27 14:15:18 -07001891 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07001892 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07001893 // WM changes display->layerStack upon sleep/awake.
1894 // Here we make sure we delete the HWC layers even if
1895 // WM changed their layer stack.
1896 hwcLayerDestroyed = layer->destroyHwcLayer(display->getId());
Chia-I Wu83806892017-11-16 10:50:20 -08001897 }
1898
1899 // If a layer is not going to get a release fence because
1900 // it is invisible, but it is also going to release its
1901 // old buffer, add it to the list of layers needing
1902 // fences.
1903 if (hwcLayerDestroyed) {
1904 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
1905 mLayersWithQueuedFrames.cend(), layer);
1906 if (found != mLayersWithQueuedFrames.cend()) {
1907 layersNeedingFences.add(layer);
1908 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001909 }
Jeff Sharkey76488112017-02-27 14:15:18 -07001910 });
1911 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001912 display->setVisibleLayersSortedByZ(layersSortedByZ);
1913 display->setLayersNeedingFences(layersNeedingFences);
1914 display->undefinedRegion.set(bounds);
1915 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
1916 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001917 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08001918 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001919}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07001920
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001921// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001922// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07001923// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001924// - Dataspace::DISPLAY_P3
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001925// The returned HDR data space is one of
1926// - Dataspace::UNKNOWN
1927// - Dataspace::BT2020_HLG
1928// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001929Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
1930 Dataspace* outHdrDataSpace) const {
Chia-I Wu7112a112018-05-07 15:27:06 -07001931 Dataspace bestDataSpace = Dataspace::SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001932 *outHdrDataSpace = Dataspace::UNKNOWN;
1933
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001934 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07001935 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001936 case Dataspace::V0_SCRGB:
1937 case Dataspace::V0_SCRGB_LINEAR:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001938 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07001939 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001940 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001941 case Dataspace::BT2020_PQ:
1942 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001943 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001944 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07001945 case Dataspace::BT2020_HLG:
1946 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001947 // When there's mixed PQ content and HLG content, we set the HDR
1948 // data space to be BT2020_PQ and convert HLG to PQ.
1949 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
1950 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07001951 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001952 break;
1953 default:
1954 break;
1955 }
Romain Guy54f154a2017-10-24 21:40:32 +01001956 }
1957
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001958 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001959}
1960
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001961// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001962void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
1963 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001964 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
1965 *outMode = ColorMode::NATIVE;
1966 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001967 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001968 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08001969 }
Romain Guy88d37dd2017-05-26 17:57:05 -07001970
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001971 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001972 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07001973
Peiyong Lindfde5112018-06-05 10:58:41 -07001974 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001975 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07001976 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001977 if (isHdr) {
1978 bestDataSpace = hdrDataSpace;
1979 }
1980
Chia-I Wu0d711262018-05-21 15:19:35 -07001981 RenderIntent intent;
1982 switch (mDisplayColorSetting) {
1983 case DisplayColorSetting::MANAGED:
1984 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001985 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07001986 break;
1987 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07001988 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07001989 break;
1990 default: // vendor display color setting
1991 intent = static_cast<RenderIntent>(mDisplayColorSetting);
1992 break;
1993 }
Chia-I Wube02ec02018-05-18 10:59:36 -07001994
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001995 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06001996}
1997
Lloyd Pique074e8122018-07-26 12:57:23 -07001998void SurfaceFlinger::setUpHWComposer() {
1999 ATRACE_CALL();
2000 ALOGV("setUpHWComposer");
Lloyd Piqueb7d12302018-07-26 12:56:47 -07002001
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002002 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002003 bool dirty = !display->getDirtyRegion(mRepaintEverything).isEmpty();
2004 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2005 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
Jesse Hallb7a05492014-08-14 15:45:06 -07002006
2007 // If nothing has changed (!dirty), don't recompose.
2008 // If something changed, but we don't currently have any visible layers,
2009 // and didn't when we last did a composition, then skip it this time.
2010 // The second rule does two things:
2011 // - When all layers are removed from a display, we'll emit one black
2012 // frame, then nothing more until we get new layers.
2013 // - When a display is created with a private layer stack, we won't
2014 // emit any black frames until a layer is added to the layer stack.
2015 bool mustRecompose = dirty && !(empty && wasEmpty);
2016
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002017 ALOGV_IF(display->isVirtual(), "Display %d: %s composition (%sdirty %sempty %swasEmpty)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07002018 display->getId(), mustRecompose ? "doing" : "skipping", dirty ? "+" : "-",
2019 empty ? "+" : "-", wasEmpty ? "+" : "-");
Jesse Hallb7a05492014-08-14 15:45:06 -07002020
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002021 display->beginFrame(mustRecompose);
Jesse Hallb7a05492014-08-14 15:45:06 -07002022
2023 if (mustRecompose) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002024 display->lastCompositionHadVisibleLayers = !empty;
Jesse Hallb7a05492014-08-14 15:45:06 -07002025 }
Jesse Hall028dc8f2013-08-20 16:35:32 -07002026 }
2027
Lloyd Pique074e8122018-07-26 12:57:23 -07002028 // build the h/w work list
2029 if (CC_UNLIKELY(mGeometryInvalid)) {
2030 mGeometryInvalid = false;
2031 for (const auto& [token, display] : mDisplays) {
2032 const auto displayId = display->getId();
2033 if (displayId >= 0) {
2034 const Vector<sp<Layer>>& currentLayers = display->getVisibleLayersSortedByZ();
2035 for (size_t i = 0; i < currentLayers.size(); i++) {
2036 const auto& layer = currentLayers[i];
2037 if (!layer->hasHwcLayer(displayId)) {
2038 if (!layer->createHwcLayer(getBE().mHwc.get(), displayId)) {
2039 layer->forceClientComposition(displayId);
2040 continue;
2041 }
2042 }
2043
2044 layer->setGeometry(display, i);
2045 if (mDebugDisableHWC || mDebugRegion) {
2046 layer->forceClientComposition(displayId);
2047 }
2048 }
2049 }
2050 }
2051 }
2052
2053 // Set the per-frame data
2054 for (const auto& [token, display] : mDisplays) {
2055 const auto displayId = display->getId();
2056 if (displayId < 0) {
2057 continue;
2058 }
2059
2060 if (mDrawingState.colorMatrixChanged) {
2061 display->setColorTransform(mDrawingState.colorMatrix);
2062 status_t result = getBE().mHwc->setColorTransform(displayId, mDrawingState.colorMatrix);
2063 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on display %d: %d",
2064 displayId, result);
2065 }
2066 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2067 if (layer->isHdrY410()) {
2068 layer->forceClientComposition(displayId);
2069 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
2070 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
2071 !display->hasHDR10Support()) {
2072 layer->forceClientComposition(displayId);
2073 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
2074 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
2075 !display->hasHLGSupport()) {
2076 layer->forceClientComposition(displayId);
2077 }
2078
2079 if (layer->getForceClientComposition(displayId)) {
2080 ALOGV("[%s] Requesting Client composition", layer->getName().string());
2081 layer->setCompositionType(displayId, HWC2::Composition::Client);
2082 continue;
2083 }
2084
2085 layer->setPerFrameData(display);
2086 }
2087
2088 if (hasWideColorDisplay) {
2089 ColorMode colorMode;
2090 Dataspace dataSpace;
2091 RenderIntent renderIntent;
2092 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
2093 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
2094 }
2095 }
2096
2097 mDrawingState.colorMatrixChanged = false;
2098
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002099 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002100 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002101 continue;
2102 }
2103
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002104 status_t result = display->prepareFrame(*getBE().mHwc);
2105 ALOGE_IF(result != NO_ERROR, "prepareFrame for display %d failed: %d (%s)",
Dominik Laskowski7e045462018-05-30 13:02:02 -07002106 display->getId(), result, strerror(-result));
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002107 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002108}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002109
Mathias Agopiancd60f992012-08-16 16:28:27 -07002110void SurfaceFlinger::doComposition() {
2111 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002112 ALOGV("doComposition");
2113
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002114 const bool repaintEverything = android_atomic_and(0, &mRepaintEverything);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002115 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002116 if (display->isPoweredOn()) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002117 // transform the dirty region into this screen's coordinate space
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002118 const Region dirtyRegion = display->getDirtyRegion(repaintEverything);
Mathias Agopian02b95102012-11-05 17:50:57 -08002119
2120 // repaint the framebuffer (if needed)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002121 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002122
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002123 display->dirtyRegion.clear();
2124 display->flip();
Mathias Agopian87baae12012-07-31 12:38:26 -07002125 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002126 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002127 postFramebuffer();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002128}
2129
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002130void SurfaceFlinger::postFramebuffer()
2131{
Mathias Agopian841cde52012-03-01 15:44:37 -08002132 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002133 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002134
Mathias Agopiana44b0412011-10-16 18:46:35 -07002135 const nsecs_t now = systemTime();
2136 mDebugInSwapBuffers = now;
Jesse Hallc5c5a142012-07-02 16:49:28 -07002137
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002138 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002139 if (!display->isPoweredOn()) {
Dan Stoza7bdf55a2016-06-17 11:29:01 -07002140 continue;
2141 }
Dominik Laskowski7e045462018-05-30 13:02:02 -07002142 const auto displayId = display->getId();
2143 if (displayId >= 0) {
2144 getBE().mHwc->presentAndGetReleaseFences(displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002145 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002146 display->onSwapBuffersCompleted();
2147 display->makeCurrent();
2148 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002149 sp<Fence> releaseFence = Fence::NO_FENCE;
2150
Chia-I Wu7b549592017-11-15 09:14:57 -08002151 // The layer buffer from the previous frame (if any) is released
2152 // by HWC only when the release fence from this frame (if any) is
2153 // signaled. Always get the release fence from HWC first.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002154 auto hwcLayer = layer->getHwcLayer(displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002155 if (displayId >= 0) {
2156 releaseFence = getBE().mHwc->getLayerReleaseFence(displayId, hwcLayer);
2157 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002158
2159 // If the layer was client composited in the previous frame, we
2160 // need to merge with the previous client target acquire fence.
2161 // Since we do not track that, always merge with the current
2162 // client target acquire fence when it is available, even though
2163 // this is suboptimal.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002164 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002165 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002166 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002167 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002168
David Sodmanb8af7922017-12-21 15:17:55 -08002169 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002170 }
Chia-I Wu83806892017-11-16 10:50:20 -08002171
2172 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002173 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002174 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002175 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002176 sp<Fence> presentFence = getBE().mHwc->getPresentFence(displayId);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002177 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002178 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002179 }
2180 }
2181
Dominik Laskowski7e045462018-05-30 13:02:02 -07002182 if (displayId >= 0) {
2183 getBE().mHwc->clearReleaseFences(displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002184 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002185 }
2186
Mathias Agopiana44b0412011-10-16 18:46:35 -07002187 mLastSwapBufferTime = systemTime() - now;
2188 mDebugInSwapBuffers = 0;
Jamie Gennis6547ff42013-07-16 20:12:42 -07002189
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002190 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002191 const auto display = getDefaultDisplayDeviceLocked();
2192 if (display && getHwComposer().isConnected(display->getId())) {
2193 const uint32_t flipCount = display->getPageFlipCount();
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002194 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2195 logFrameStats();
2196 }
Jamie Gennis6547ff42013-07-16 20:12:42 -07002197 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002198}
2199
Mathias Agopian87baae12012-07-31 12:38:26 -07002200void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002201{
Mathias Agopian841cde52012-03-01 15:44:37 -08002202 ATRACE_CALL();
2203
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002204 // here we keep a copy of the drawing state (that is the state that's
2205 // going to be overwritten by handleTransactionLocked()) outside of
2206 // mStateLock so that the side-effects of the State assignment
2207 // don't happen with mStateLock held (which can cause deadlocks).
2208 State drawingState(mDrawingState);
2209
Mathias Agopianca4d3602011-05-19 15:38:14 -07002210 Mutex::Autolock _l(mStateLock);
2211 const nsecs_t now = systemTime();
2212 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002213
Mathias Agopianca4d3602011-05-19 15:38:14 -07002214 // Here we're guaranteed that some transaction flags are set
2215 // so we can call handleTransactionLocked() unconditionally.
2216 // We call getTransactionFlags(), which will also clear the flags,
2217 // with mStateLock held to guarantee that mCurrentState won't change
2218 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002219
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002220 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002221 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002222 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002223
Mathias Agopianca4d3602011-05-19 15:38:14 -07002224 mLastTransactionTime = systemTime() - now;
2225 mDebugInTransaction = 0;
2226 invalidateHwcGeometry();
2227 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002228}
2229
Dominik Laskowski7e045462018-05-30 13:02:02 -07002230DisplayDevice::DisplayType SurfaceFlinger::determineDisplayType(hwc2_display_t hwcDisplayId,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002231 HWC2::Connection connection) const {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002232 // Figure out whether the event is for the primary display or an
2233 // external display by matching the Hwc display id against one for a
2234 // connected display. If we did not find a match, we then check what
2235 // displays are not already connected to determine the type. If we don't
2236 // have a connected primary display, we assume the new display is meant to
2237 // be the primary display, and then if we don't have an external display,
2238 // we assume it is that.
Dominik Laskowski7e045462018-05-30 13:02:02 -07002239 const auto primaryHwcDisplayId = getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_PRIMARY);
2240 const auto externalHwcDisplayId =
Lloyd Pique715a2c12017-12-14 17:18:08 -08002241 getBE().mHwc->getHwcDisplayId(DisplayDevice::DISPLAY_EXTERNAL);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002242 if (primaryHwcDisplayId && primaryHwcDisplayId == hwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002243 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002244 } else if (externalHwcDisplayId && externalHwcDisplayId == hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002245 return DisplayDevice::DISPLAY_EXTERNAL;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002246 } else if (connection == HWC2::Connection::Connected && !primaryHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002247 return DisplayDevice::DISPLAY_PRIMARY;
Dominik Laskowski7e045462018-05-30 13:02:02 -07002248 } else if (connection == HWC2::Connection::Connected && !externalHwcDisplayId) {
Lloyd Pique715a2c12017-12-14 17:18:08 -08002249 return DisplayDevice::DISPLAY_EXTERNAL;
2250 }
2251
2252 return DisplayDevice::DISPLAY_ID_INVALID;
2253}
2254
Lloyd Piqueba04e622017-12-14 17:11:26 -08002255void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2256 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002257 auto displayType = determineDisplayType(event.hwcDisplayId, event.connection);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002258 if (displayType == DisplayDevice::DISPLAY_ID_INVALID) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002259 ALOGW("Unable to determine the display type for display %" PRIu64, event.hwcDisplayId);
Lloyd Pique715a2c12017-12-14 17:18:08 -08002260 continue;
2261 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002262
2263 if (getBE().mHwc->isUsingVrComposer() && displayType == DisplayDevice::DISPLAY_EXTERNAL) {
2264 ALOGE("External displays are not supported by the vr hardware composer.");
2265 continue;
2266 }
2267
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002268 const auto displayId =
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002269 getBE().mHwc->onHotplug(event.hwcDisplayId, displayType, event.connection);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002270 if (displayId) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07002271 ALOGV("Display %" PRIu64 " has stable ID %" PRIu64, event.hwcDisplayId, *displayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07002272 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002273
2274 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002275 if (!mDisplayTokens[displayType].get()) {
Steven Thomaseb6d2052018-03-20 15:40:48 -07002276 ALOGV("Creating built in display %d", displayType);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002277 mDisplayTokens[displayType] = new BBinder();
Dominik Laskowski663bd282018-04-19 15:26:54 -07002278 DisplayDeviceState info;
2279 info.type = displayType;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002280 info.displayName = displayType == DisplayDevice::DISPLAY_PRIMARY ?
2281 "Built-in Screen" : "External Screen";
Dominik Laskowski663bd282018-04-19 15:26:54 -07002282 info.isSecure = true; // All physical displays are currently considered secure.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002283 mCurrentState.displays.add(mDisplayTokens[displayType], info);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002284 mInterceptor->saveDisplayCreation(info);
2285 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002286 } else {
Lloyd Piquefcd86612017-12-14 17:15:36 -08002287 ALOGV("Removing built in display %d", displayType);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002288
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002289 ssize_t idx = mCurrentState.displays.indexOfKey(mDisplayTokens[displayType]);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002290 if (idx >= 0) {
2291 const DisplayDeviceState& info(mCurrentState.displays.valueAt(idx));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002292 mInterceptor->saveDisplayDeletion(info.sequenceId);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002293 mCurrentState.displays.removeItemsAt(idx);
2294 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002295 mDisplayTokens[displayType].clear();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002296 }
2297
2298 processDisplayChangesLocked();
2299 }
2300
2301 mPendingHotplugEvents.clear();
2302}
2303
Lloyd Pique99d3da52018-01-22 17:48:03 -08002304sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski7e045462018-05-30 13:02:02 -07002305 const wp<IBinder>& displayToken, int32_t displayId, const DisplayDeviceState& state,
Lloyd Pique99d3da52018-01-22 17:48:03 -08002306 const sp<DisplaySurface>& dispSurface, const sp<IGraphicBufferProducer>& producer) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002307 bool hasWideColorGamut = false;
Chia-I Wube02ec02018-05-18 10:59:36 -07002308 std::unordered_map<ColorMode, std::vector<RenderIntent>> hwcColorModes;
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002309 HdrCapabilities hdrCapabilities;
2310 int32_t supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002311
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002312 if (hasWideColorDisplay && displayId >= 0) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002313 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002314 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002315 if (isWideColorMode(colorMode)) {
2316 hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002317 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002318
Dominik Laskowski7e045462018-05-30 13:02:02 -07002319 std::vector<RenderIntent> renderIntents =
2320 getHwComposer().getRenderIntents(displayId, colorMode);
Chia-I Wube02ec02018-05-18 10:59:36 -07002321 hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002322 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002323
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002324 getHwComposer().getHdrCapabilities(displayId, &hdrCapabilities);
2325 supportedPerFrameMetadata = getHwComposer().getSupportedPerFrameMetadata(displayId);
2326 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002327
2328 auto nativeWindowSurface = mCreateNativeWindowSurface(producer);
2329 auto nativeWindow = nativeWindowSurface->getNativeWindow();
2330
2331 /*
2332 * Create our display's surface
2333 */
2334 std::unique_ptr<RE::Surface> renderSurface = getRenderEngine().createSurface();
2335 renderSurface->setCritical(state.type == DisplayDevice::DISPLAY_PRIMARY);
Dominik Laskowski281644e2018-04-19 15:47:35 -07002336 renderSurface->setAsync(state.isVirtual());
Lloyd Pique99d3da52018-01-22 17:48:03 -08002337 renderSurface->setNativeWindow(nativeWindow.get());
2338 const int displayWidth = renderSurface->queryWidth();
2339 const int displayHeight = renderSurface->queryHeight();
2340
2341 // Make sure that composition can never be stalled by a virtual display
2342 // consumer that isn't processing buffers fast enough. We have to do this
2343 // in two places:
2344 // * Here, in case the display is composed entirely by HWC.
2345 // * In makeCurrent(), using eglSwapInterval. Some EGL drivers set the
2346 // window's swap interval in eglMakeCurrent, so they'll override the
2347 // interval we set here.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002348 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002349 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2350 }
2351
2352 // virtual displays are always considered enabled
Dominik Laskowski281644e2018-04-19 15:47:35 -07002353 auto initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002354
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002355 sp<DisplayDevice> display =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002356 new DisplayDevice(this, state.type, displayId, state.isSecure, displayToken,
2357 nativeWindow, dispSurface, std::move(renderSurface), displayWidth,
2358 displayHeight, hasWideColorGamut, hdrCapabilities,
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002359 supportedPerFrameMetadata, hwcColorModes, initialPowerMode);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002360
2361 if (maxFrameBufferAcquiredBuffers >= 3) {
2362 nativeWindowSurface->preallocateBuffers();
2363 }
2364
2365 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002366 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
2367 if (hasWideColorGamut) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002368 defaultColorMode = ColorMode::SRGB;
Chia-I Wube02ec02018-05-18 10:59:36 -07002369 defaultDataSpace = Dataspace::SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002370 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002371 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002372 RenderIntent::COLORIMETRIC);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002373 if (state.type < DisplayDevice::DISPLAY_VIRTUAL) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002374 display->setActiveConfig(getHwComposer().getActiveConfigIndex(state.type));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002375 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002376 display->setLayerStack(state.layerStack);
2377 display->setProjection(state.orientation, state.viewport, state.frame);
2378 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002379
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002380 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002381}
2382
Lloyd Pique347200f2017-12-14 17:00:15 -08002383void SurfaceFlinger::processDisplayChangesLocked() {
2384 // here we take advantage of Vector's copy-on-write semantics to
2385 // improve performance by skipping the transaction entirely when
2386 // know that the lists are identical
2387 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2388 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2389 if (!curr.isIdenticalTo(draw)) {
2390 mVisibleRegionsDirty = true;
2391 const size_t cc = curr.size();
2392 size_t dc = draw.size();
2393
2394 // find the displays that were removed
2395 // (ie: in drawing state but not in current state)
2396 // also handle displays that changed
2397 // (ie: displays that are in both lists)
2398 for (size_t i = 0; i < dc;) {
2399 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2400 if (j < 0) {
2401 // in drawing state but not in current state
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002402 // Call makeCurrent() on the primary display so we can
2403 // be sure that nothing associated with this display
2404 // is current.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002405 if (const auto defaultDisplay = getDefaultDisplayDeviceLocked()) {
2406 defaultDisplay->makeCurrent();
2407 }
2408 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2409 display->disconnect(getHwComposer());
2410 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002411 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
2412 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2413 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
2414 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2415 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002416 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002417 } else {
2418 // this display is in both lists. see if something changed.
2419 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002420 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002421 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2422 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2423 if (state_binder != draw_binder) {
2424 // changing the surface is like destroying and
2425 // recreating the DisplayDevice, so we just remove it
2426 // from the drawing state, so that it get re-added
2427 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002428 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2429 display->disconnect(getHwComposer());
2430 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002431 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002432 mDrawingState.displays.removeItemsAt(i);
2433 dc--;
2434 // at this point we must loop to the next item
2435 continue;
2436 }
2437
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002438 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002439 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002440 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002441 }
2442 if ((state.orientation != draw[i].orientation) ||
2443 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002444 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002445 }
2446 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002447 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002448 }
2449 }
2450 }
2451 ++i;
2452 }
2453
2454 // find displays that were added
2455 // (ie: in current state but not in drawing state)
2456 for (size_t i = 0; i < cc; i++) {
2457 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2458 const DisplayDeviceState& state(curr[i]);
2459
2460 sp<DisplaySurface> dispSurface;
2461 sp<IGraphicBufferProducer> producer;
2462 sp<IGraphicBufferProducer> bqProducer;
2463 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique12eb4232018-01-17 11:54:43 -08002464 mCreateBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002465
Dominik Laskowski7e045462018-05-30 13:02:02 -07002466 int32_t displayId = -1;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002467 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002468 // Virtual displays without a surface are dormant:
2469 // they have external state (layer stack, projection,
2470 // etc.) but no internal state (i.e. a DisplayDevice).
2471 if (state.surface != nullptr) {
2472 // Allow VR composer to use virtual displays.
2473 if (mUseHwcVirtualDisplays || getBE().mHwc->isUsingVrComposer()) {
2474 int width = 0;
2475 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2476 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2477 int height = 0;
2478 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2479 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2480 int intFormat = 0;
2481 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2482 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002483 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002484
Dominik Laskowski7e045462018-05-30 13:02:02 -07002485 getBE().mHwc->allocateVirtualDisplay(width, height, &format,
2486 &displayId);
Lloyd Pique347200f2017-12-14 17:00:15 -08002487 }
2488
2489 // TODO: Plumb requested format back up to consumer
2490
2491 sp<VirtualDisplaySurface> vds =
Dominik Laskowski7e045462018-05-30 13:02:02 -07002492 new VirtualDisplaySurface(*getBE().mHwc, displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002493 bqProducer, bqConsumer,
2494 state.displayName);
2495
2496 dispSurface = vds;
2497 producer = vds;
2498 }
2499 } else {
2500 ALOGE_IF(state.surface != nullptr,
2501 "adding a supported display, but rendering "
2502 "surface is provided (%p), ignoring it",
2503 state.surface.get());
2504
Dominik Laskowski7e045462018-05-30 13:02:02 -07002505 displayId = state.type;
2506 dispSurface = new FramebufferSurface(*getBE().mHwc, displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002507 producer = bqProducer;
2508 }
2509
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002510 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002511 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002512 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002513 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002514 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002515 if (!state.isVirtual()) {
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002516 if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
2517 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2518 true);
2519 } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
2520 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2521 true);
2522 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002523 }
2524 }
2525 }
2526 }
2527 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002528
2529 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002530}
2531
Mathias Agopian87baae12012-07-31 12:38:26 -07002532void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002533{
Dan Stoza7dde5992015-05-22 09:51:44 -07002534 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002535 mCurrentState.traverseInZOrder([](Layer* layer) {
2536 layer->notifyAvailableFrames();
2537 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002538
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002539 /*
2540 * Traversal of the children
2541 * (perform the transaction for each of them if needed)
2542 */
2543
Mathias Agopian3559b072012-08-15 13:46:03 -07002544 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002545 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002546 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002547 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002548
2549 const uint32_t flags = layer->doTransaction(0);
2550 if (flags & Layer::eVisibleRegion)
2551 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002552 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002553 }
2554
2555 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002556 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002557 */
2558
Mathias Agopiane57f2922012-08-09 16:29:12 -07002559 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002560 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002561 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002562 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002563
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002564 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002565 // The transform hint might have changed for some layers
2566 // (either because a display has changed, or because a layer
2567 // as changed).
2568 //
2569 // Walk through all the layers in currentLayers,
2570 // and update their transform hint.
2571 //
2572 // If a layer is visible only on a single display, then that
2573 // display is used to calculate the hint, otherwise we use the
2574 // default display.
2575 //
2576 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2577 // the hint is set before we acquire a buffer from the surface texture.
2578 //
2579 // NOTE: layer transactions have taken place already, so we use their
2580 // drawing state. However, SurfaceFlinger's own transaction has not
2581 // happened yet, so we must use the current state layer list
2582 // (soon to become the drawing state list).
2583 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002584 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002585 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002586 bool first = true;
2587 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002588 // NOTE: we rely on the fact that layers are sorted by
2589 // layerStack first (so we don't have to traverse the list
2590 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002591 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002592 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002593 currentlayerStack = layerStack;
2594 // figure out if this layerstack is mirrored
2595 // (more than one display) if so, pick the default display,
2596 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002597 hintDisplay = nullptr;
2598 for (const auto& [token, display] : mDisplays) {
2599 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2600 if (hintDisplay) {
2601 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002602 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002603 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002604 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002605 }
2606 }
2607 }
2608 }
Chet Haase91d25932013-04-11 15:24:55 -07002609
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002610 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002611 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2612 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002613
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002614 // could be null when this layer is using a layerStack
2615 // that is not visible on any display. Also can occur at
2616 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002617 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002618 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002619
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002620 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002621 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002622 if (hintDisplay) {
2623 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002624 }
Robert Carr2047fae2016-11-28 14:09:09 -08002625
2626 first = false;
2627 });
Mathias Agopian84300952012-11-21 16:02:13 -08002628 }
2629
2630
Mathias Agopian3559b072012-08-15 13:46:03 -07002631 /*
2632 * Perform our own transaction if needed
2633 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002634
2635 if (mLayersAdded) {
2636 mLayersAdded = false;
2637 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002638 mVisibleRegionsDirty = true;
2639 }
2640
2641 // some layers might have been removed, so
2642 // we need to update the regions they're exposing.
2643 if (mLayersRemoved) {
2644 mLayersRemoved = false;
2645 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002646 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002647 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002648 // this layer is not visible anymore
2649 // TODO: we could traverse the tree from front to back and
2650 // compute the actual visible region
2651 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002652 Region visibleReg;
2653 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002654 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002655 }
Robert Carr2047fae2016-11-28 14:09:09 -08002656 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002657 }
2658
2659 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002660
2661 updateCursorAsync();
2662}
2663
2664void SurfaceFlinger::updateCursorAsync()
2665{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002666 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002667 if (display->getId() < 0) {
Riley Andrews03414a12014-07-01 14:22:59 -07002668 continue;
2669 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002670
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002671 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2672 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002673 }
2674 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002675}
2676
2677void SurfaceFlinger::commitTransaction()
2678{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002679 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002680 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002681 for (const auto& l : mLayersPendingRemoval) {
2682 recordBufferingStats(l->getName().string(),
2683 l->getOccupancyHistory(true));
2684 l->onRemoved();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002685 }
2686 mLayersPendingRemoval.clear();
2687 }
2688
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002689 // If this transaction is part of a window animation then the next frame
2690 // we composite should be considered an animation as well.
2691 mAnimCompositionPending = mAnimTransactionPending;
2692
Mathias Agopian4fec8732012-06-29 14:12:52 -07002693 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002694 // clear the "changed" flags in current state
2695 mCurrentState.colorMatrixChanged = false;
2696
Robert Carr1f0a16a2016-10-24 16:27:39 -07002697 mDrawingState.traverseInZOrder([](Layer* layer) {
2698 layer->commitChildList();
2699 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002700 mTransactionPending = false;
2701 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002702 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002703}
2704
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002705void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2706 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002707 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002708 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002709
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002710 Region aboveOpaqueLayers;
2711 Region aboveCoveredLayers;
2712 Region dirty;
2713
Mathias Agopian87baae12012-07-31 12:38:26 -07002714 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002715
Robert Carr2047fae2016-11-28 14:09:09 -08002716 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002717 // start with the whole surface at its current location
Mathias Agopian1eae0ee2013-06-05 16:59:15 -07002718 const Layer::State& s(layer->getDrawingState());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002719
Jesse Hall01e29052013-02-19 16:13:35 -08002720 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002721 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002722 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002723 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002724
Mathias Agopianab028732010-03-16 16:41:46 -07002725 /*
2726 * opaqueRegion: area of a surface that is fully opaque.
2727 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002728 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002729
2730 /*
2731 * visibleRegion: area of a surface that is visible on screen
2732 * and not fully transparent. This is essentially the layer's
2733 * footprint minus the opaque regions above it.
2734 * Areas covered by a translucent surface are considered visible.
2735 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002736 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002737
2738 /*
2739 * coveredRegion: area of a surface that is covered by all
2740 * visible regions above it (which includes the translucent areas).
2741 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002742 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002743
Jesse Halla8026d22012-09-25 13:25:04 -07002744 /*
2745 * transparentRegion: area of a surface that is hinted to be completely
2746 * transparent. This is only used to tell when the layer has no visible
2747 * non-transparent regions and can be removed from the layer list. It
2748 * does not affect the visibleRegion of this layer or any layers
2749 * beneath it. The hint may not be correct if apps don't respect the
2750 * SurfaceView restrictions (which, sadly, some don't).
2751 */
2752 Region transparentRegion;
2753
Mathias Agopianab028732010-03-16 16:41:46 -07002754
2755 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002756 if (CC_LIKELY(layer->isVisible())) {
Andy McFadden4125a4f2014-01-29 17:17:11 -08002757 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002758 Rect bounds(layer->computeScreenBounds());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002759 visibleRegion.set(bounds);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002760 Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002761 if (!visibleRegion.isEmpty()) {
2762 // Remove the transparent area from the visible region
2763 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002764 if (tr.preserveRects()) {
2765 // transform the transparent region
Marissa Wall61c58622018-07-18 10:12:20 -07002766 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002767 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002768 // transformation too complex, can't do the
2769 // transparent region optimization.
2770 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002771 }
Mathias Agopianab028732010-03-16 16:41:46 -07002772 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002773
Mathias Agopianab028732010-03-16 16:41:46 -07002774 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002775 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002776 if (layer->getAlpha() == 1.0f && !translucent &&
Mathias Agopianab028732010-03-16 16:41:46 -07002777 ((layerOrientation & Transform::ROT_INVALID) == false)) {
2778 // the opaque region is the layer's footprint
2779 opaqueRegion = visibleRegion;
2780 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002781 }
2782 }
2783
Robert Carre5f4f692018-01-12 13:12:28 -08002784 if (visibleRegion.isEmpty()) {
2785 layer->clearVisibilityRegions();
2786 return;
2787 }
2788
Mathias Agopianab028732010-03-16 16:41:46 -07002789 // Clip the covered region to the visible region
2790 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2791
2792 // Update aboveCoveredLayers for next (lower) layer
2793 aboveCoveredLayers.orSelf(visibleRegion);
2794
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002795 // subtract the opaque region covered by the layers above us
2796 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002797
2798 // compute this layer's dirty region
2799 if (layer->contentDirty) {
2800 // we need to invalidate the whole region
2801 dirty = visibleRegion;
2802 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002803 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002804 layer->contentDirty = false;
2805 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002806 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002807 * the exposed region consists of two components:
2808 * 1) what's VISIBLE now and was COVERED before
2809 * 2) what's EXPOSED now less what was EXPOSED before
2810 *
2811 * note that (1) is conservative, we start with the whole
2812 * visible region but only keep what used to be covered by
2813 * something -- which mean it may have been exposed.
2814 *
2815 * (2) handles areas that were not covered by anything but got
2816 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002817 */
Mathias Agopianab028732010-03-16 16:41:46 -07002818 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002819 const Region oldVisibleRegion = layer->visibleRegion;
2820 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002821 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2822 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002823 }
2824 dirty.subtractSelf(aboveOpaqueLayers);
2825
2826 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002827 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002828
Mathias Agopianab028732010-03-16 16:41:46 -07002829 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002830 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002831
Jesse Halla8026d22012-09-25 13:25:04 -07002832 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002833 layer->setVisibleRegion(visibleRegion);
2834 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002835 layer->setVisibleNonTransparentRegion(
2836 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002837 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002838
Mathias Agopian87baae12012-07-31 12:38:26 -07002839 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002840}
2841
Chia-I Wuab0c3192017-08-01 11:29:00 -07002842void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002843 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002844 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2845 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002846 }
2847 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002848}
2849
Dan Stoza6b9454d2014-11-07 16:00:59 -08002850bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002851{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002852 ALOGV("handlePageFlip");
2853
Brian Andersond6927fb2016-07-23 23:37:30 -07002854 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002855
Mathias Agopian4fec8732012-06-29 14:12:52 -07002856 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002857 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002858 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002859
2860 // Store the set of layers that need updates. This set must not change as
2861 // buffers are being latched, as this could result in a deadlock.
2862 // Example: Two producers share the same command stream and:
2863 // 1.) Layer 0 is latched
2864 // 2.) Layer 0 gets a new frame
2865 // 2.) Layer 1 gets a new frame
2866 // 3.) Layer 1 is latched.
2867 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2868 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002869 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002870 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002871 frameQueued = true;
Lloyd Pique41be5d22018-06-21 13:11:48 -07002872 if (layer->shouldPresentNow(*mPrimaryDispSync)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002873 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002874 } else {
2875 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002876 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002877 } else {
2878 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002879 }
Robert Carr2047fae2016-11-28 14:09:09 -08002880 });
2881
Dan Stoza9e56aa02015-11-02 13:00:03 -08002882 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersond6927fb2016-07-23 23:37:30 -07002883 const Region dirty(layer->latchBuffer(visibleRegions, latchTime));
Dan Stozaee44edd2015-03-23 15:50:23 -07002884 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07002885 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07002886 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06002887 newDataLatched = true;
2888 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002889 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002890
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002891 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002892
2893 // If we will need to wake up at some time in the future to deal with a
2894 // queued frame that shouldn't be displayed during this vsync period, wake
2895 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002896 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002897 signalLayerUpdate();
2898 }
2899
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002900 // enter boot animation on first buffer latch
2901 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2902 ALOGI("Enter boot animation");
2903 mBootStage = BootStage::BOOTANIMATION;
2904 }
2905
Dan Stoza6b9454d2014-11-07 16:00:59 -08002906 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002907 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002908}
2909
Mathias Agopianad456f92011-01-13 17:53:01 -08002910void SurfaceFlinger::invalidateHwcGeometry()
2911{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002912 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002913}
2914
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002915void SurfaceFlinger::doDisplayComposition(const sp<const DisplayDevice>& display,
2916 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08002917 // We only need to actually compose the display if:
2918 // 1) It is being handled by hardware composer, which may need this to
2919 // keep its virtual display state machine in sync, or
2920 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski7e045462018-05-30 13:02:02 -07002921 bool isHwcDisplay = display->getId() >= 0;
Dan Stoza71433162014-02-04 16:22:36 -08002922 if (!isHwcDisplay && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002923 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08002924 return;
2925 }
2926
Dan Stoza9e56aa02015-11-02 13:00:03 -08002927 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002928 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07002929
2930 // swap buffers (presentation)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002931 display->swapBuffers(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002932}
2933
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002934bool SurfaceFlinger::doComposeSurfaces(const sp<const DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002935 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07002936
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002937 const Region bounds(display->bounds());
2938 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07002939 const auto displayId = display->getId();
2940 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002941 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002942
Chia-I Wu8e50e692018-05-04 10:12:37 -07002943 bool applyColorMatrix = false;
Chia-I Wud49d6692018-06-27 07:17:41 +08002944 bool needsEnhancedColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07002945
Dan Stoza9e56aa02015-11-02 13:00:03 -08002946 if (hasClientComposition) {
2947 ALOGV("hasClientComposition");
2948
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002949 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002950 if (display->hasWideColorGamut()) {
2951 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002952 }
2953 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07002954 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002955 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08002956
Dominik Laskowski7e045462018-05-30 13:02:02 -07002957 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002958 const bool skipClientColorTransform = getBE().mHwc->hasCapability(
2959 HWC2::Capability::SkipClientColorTransform);
2960
Chia-I Wud49d6692018-06-27 07:17:41 +08002961 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002962 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
2963 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08002964 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07002965 }
2966
Chia-I Wud49d6692018-06-27 07:17:41 +08002967 // The current enhanced saturation matrix is designed to enhance Display P3,
2968 // thus we only apply this matrix when the render intent is not colorimetric
2969 // and the output color space is Display P3.
2970 needsEnhancedColorMatrix =
2971 (display->getActiveRenderIntent() >= RenderIntent::ENHANCE &&
2972 outputDataspace == Dataspace::DISPLAY_P3);
2973 if (needsEnhancedColorMatrix) {
2974 colorMatrix *= mEnhancedSaturationMatrix;
2975 }
2976
2977 getRenderEngine().setupColorTransform(colorMatrix);
Chia-I Wu8e50e692018-05-04 10:12:37 -07002978
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002979 if (!display->makeCurrent()) {
Michael Chockc8c71092013-03-04 15:15:46 -08002980 ALOGW("DisplayDevice::makeCurrent failed. Aborting surface composition for display %s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002981 display->getDisplayName().c_str());
Chia-I Wu7f402902017-11-09 12:51:10 -08002982 getRenderEngine().resetCurrentSurface();
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002983
2984 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07002985 const auto defaultDisplay = getDefaultDisplayDeviceLocked();
2986 if (!defaultDisplay || !defaultDisplay->makeCurrent()) {
2987 ALOGE("DisplayDevice::makeCurrent on default display failed. Aborting.");
Michael Lentine3f121fc2014-10-01 11:17:28 -07002988 }
2989 return false;
Michael Chockc8c71092013-03-04 15:15:46 -08002990 }
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002991
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002992 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08002993 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07002994 // when using overlays, we assume a fully transparent framebuffer
2995 // NOTE: we could reduce how much we need to clear, for instance
2996 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07002997 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07002998 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08002999 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003000 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003001 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003002 // we're left with the letterbox region
3003 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003004 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003005
3006 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003007 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003008
Mathias Agopianb9494d52012-04-18 02:28:45 -07003009 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003010 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003011 // can happen with SurfaceView
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003012 drawWormhole(display, region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003013 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003014 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003015
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003016 if (!display->isPrimary()) {
Mathias Agopian766dc492012-10-30 18:08:06 -07003017 // just to be on the safe side, we don't set the
Mathias Agopianf45c5102012-10-24 16:29:17 -07003018 // scissor on the main display. It should never be needed
3019 // anyways (though in theory it could since the API allows it).
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003020 const Rect& bounds = display->getBounds();
3021 const Rect& scissor = display->getScissor();
Mathias Agopianf45c5102012-10-24 16:29:17 -07003022 if (scissor != bounds) {
3023 // scissor doesn't match the screen's dimensions, so we
3024 // need to clear everything outside of it and enable
3025 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003026
Mathias Agopianf45c5102012-10-24 16:29:17 -07003027 // enable scissor for this frame
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003028 const uint32_t height = display->getHeight();
David Sodmanbc815282017-11-05 18:57:52 -08003029 getBE().mRenderEngine->setScissor(scissor.left, height - scissor.bottom,
Mathias Agopian3f844832013-08-07 21:24:32 -07003030 scissor.getWidth(), scissor.getHeight());
Mathias Agopianf45c5102012-10-24 16:29:17 -07003031 }
3032 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003033 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003034
Mathias Agopian85d751c2012-08-29 16:59:24 -07003035 /*
3036 * and then, render the layers targeted at the framebuffer
3037 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003038
Dan Stoza9e56aa02015-11-02 13:00:03 -08003039 ALOGV("Rendering client layers");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003040 const Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003041 bool firstLayer = true;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003042 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003043 const Region clip(bounds.intersect(
3044 displayTransform.transform(layer->visibleRegion)));
3045 ALOGV("Layer: %s", layer->getName().string());
Dominik Laskowski7e045462018-05-30 13:02:02 -07003046 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003047 if (!clip.isEmpty()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003048 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003049 case HWC2::Composition::Cursor:
3050 case HWC2::Composition::Device:
3051 case HWC2::Composition::Sideband:
3052 case HWC2::Composition::SolidColor: {
3053 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski7e045462018-05-30 13:02:02 -07003054 if (layer->getClearClientTarget(displayId) && !firstLayer &&
Rajavenu Kyatham2eae6d32018-04-10 12:34:05 +05303055 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
3056 hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003057 // never clear the very first layer since we're
3058 // guaranteed the FB is already cleared
3059 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003060 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003061 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003062 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003063 case HWC2::Composition::Client: {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003064 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003065 break;
3066 }
3067 default:
3068 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003069 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003070 } else {
3071 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003072 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003073 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003074 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003075
Chia-I Wud49d6692018-06-27 07:17:41 +08003076 if (applyColorMatrix || needsEnhancedColorMatrix) {
Chia-I Wu8e50e692018-05-04 10:12:37 -07003077 getRenderEngine().setupColorTransform(mat4());
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003078 }
3079
Mathias Agopianf45c5102012-10-24 16:29:17 -07003080 // disable scissor at the end of the frame
David Sodmanbc815282017-11-05 18:57:52 -08003081 getBE().mRenderEngine->disableScissor();
Michael Lentine3f121fc2014-10-01 11:17:28 -07003082 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003083}
3084
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003085void SurfaceFlinger::drawWormhole(const sp<const DisplayDevice>& display,
3086 const Region& region) const {
3087 const int32_t height = display->getHeight();
Lloyd Pique144e1162017-12-20 16:44:52 -08003088 auto& engine(getRenderEngine());
Mathias Agopian3f844832013-08-07 21:24:32 -07003089 engine.fillRegionWithColor(region, height, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003090}
3091
Dan Stoza7d89d062015-04-30 13:29:25 -07003092status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003093 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003094 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003095 const sp<Layer>& lbc,
3096 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003097{
Dan Stoza7d89d062015-04-30 13:29:25 -07003098 // add this layer to the current state list
3099 {
3100 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003101 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003102 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3103 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003104 return NO_MEMORY;
3105 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003106 if (parent == nullptr) {
3107 mCurrentState.layersSortedByZ.add(lbc);
3108 } else {
Robert Carrebd62af2017-11-28 08:49:59 -08003109 if (parent->isPendingRemoval()) {
Chia-I Wu98f1c102017-05-30 14:54:08 -07003110 ALOGE("addClientLayer called with a removed parent");
3111 return NAME_NOT_FOUND;
3112 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003113 parent->addChild(lbc);
3114 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003115
Yiwei Zhang243b3782018-05-15 17:40:04 -07003116 if (gbc != nullptr) {
3117 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3118 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3119 mMaxGraphicBufferProducerListSize,
3120 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3121 mGraphicBufferProducerList.size(),
3122 mMaxGraphicBufferProducerListSize, mNumLayers);
3123 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003124 mLayersAdded = true;
3125 mNumLayers++;
Dan Stoza7d89d062015-04-30 13:29:25 -07003126 }
3127
Mathias Agopian96f08192010-06-02 23:28:45 -07003128 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003129 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003130
Dan Stoza7d89d062015-04-30 13:29:25 -07003131 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003132}
3133
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003134status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer, bool topLevelOnly) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003135 Mutex::Autolock _l(mStateLock);
chaviwca27f252018-02-06 16:46:39 -08003136 return removeLayerLocked(mStateLock, layer, topLevelOnly);
3137}
Robert Carr7f9b8992017-03-10 11:08:39 -08003138
chaviwca27f252018-02-06 16:46:39 -08003139status_t SurfaceFlinger::removeLayerLocked(const Mutex&, const sp<Layer>& layer,
3140 bool topLevelOnly) {
chaviw8b3871a2017-11-01 17:41:01 -07003141 if (layer->isPendingRemoval()) {
3142 return NO_ERROR;
3143 }
3144
Robert Carr1f0a16a2016-10-24 16:27:39 -07003145 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003146 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003147 if (p != nullptr) {
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003148 if (topLevelOnly) {
3149 return NO_ERROR;
3150 }
3151
Chia-I Wu98f1c102017-05-30 14:54:08 -07003152 sp<Layer> ancestor = p;
3153 while (ancestor->getParent() != nullptr) {
3154 ancestor = ancestor->getParent();
3155 }
3156 if (mCurrentState.layersSortedByZ.indexOf(ancestor) < 0) {
3157 ALOGE("removeLayer called with a layer whose parent has been removed");
3158 return NAME_NOT_FOUND;
3159 }
Chia-I Wufae51c42017-06-15 12:53:59 -07003160
3161 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003162 } else {
3163 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003164 }
3165
Robert Carr136e2f62017-02-08 17:54:29 -08003166 // As a matter of normal operation, the LayerCleaner will produce a second
3167 // attempt to remove the surface. The Layer will be kept alive in mDrawingState
3168 // so we will succeed in promoting it, but it's already been removed
3169 // from mCurrentState. As long as we can find it in mDrawingState we have no problem
3170 // otherwise something has gone wrong and we are leaking the layer.
3171 if (index < 0 && mDrawingState.layersSortedByZ.indexOf(layer) < 0) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003172 ALOGE("Failed to find layer (%s) in layer parent (%s).",
3173 layer->getName().string(),
3174 (p != nullptr) ? p->getName().string() : "no-parent");
3175 return BAD_VALUE;
Robert Carr136e2f62017-02-08 17:54:29 -08003176 } else if (index < 0) {
3177 return NO_ERROR;
Steve Pfetsch598f6d52016-10-25 21:47:58 +00003178 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003179
Chia-I Wuc6657022017-08-15 11:18:17 -07003180 layer->onRemovedFromCurrentState();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003181 mLayersPendingRemoval.add(layer);
3182 mLayersRemoved = true;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003183 mNumLayers -= 1 + layer->getChildrenCount();
Robert Carr1f0a16a2016-10-24 16:27:39 -07003184 setTransactionFlags(eTransactionNeeded);
3185 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003186}
3187
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003188uint32_t SurfaceFlinger::peekTransactionFlags() {
Mathias Agopiandea20b12011-05-03 17:04:02 -07003189 return android_atomic_release_load(&mTransactionFlags);
3190}
3191
Mathias Agopian3f844832013-08-07 21:24:32 -07003192uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003193 return android_atomic_and(~flags, &mTransactionFlags) & flags;
3194}
3195
Mathias Agopian3f844832013-08-07 21:24:32 -07003196uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Dan Stoza84d619e2018-03-28 17:07:36 -07003197 return setTransactionFlags(flags, VSyncModulator::TransactionStart::NORMAL);
3198}
3199
3200uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
3201 VSyncModulator::TransactionStart transactionStart) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003202 uint32_t old = android_atomic_or(flags, &mTransactionFlags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003203 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003204 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003205 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003206 }
3207 return old;
3208}
3209
chaviwca27f252018-02-06 16:46:39 -08003210bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3211 for (const ComposerState& state : states) {
3212 // Here we need to check that the interface we're given is indeed
3213 // one of our own. A malicious client could give us a nullptr
3214 // IInterface, or one of its own or even one of our own but a
3215 // different type. All these situations would cause us to crash.
3216 if (state.client == nullptr) {
3217 return true;
3218 }
3219
3220 sp<IBinder> binder = IInterface::asBinder(state.client);
3221 if (binder == nullptr) {
3222 return true;
3223 }
3224
3225 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3226 return true;
3227 }
3228 }
3229 return false;
3230}
3231
Mathias Agopian8b33f032012-07-24 20:43:54 -07003232void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003233 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003234 const Vector<DisplayState>& displays,
3235 uint32_t flags)
3236{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003237 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003238 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003239 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003240
chaviwca27f252018-02-06 16:46:39 -08003241 if (containsAnyInvalidClientState(states)) {
3242 return;
3243 }
3244
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003245 if (flags & eAnimation) {
3246 // For window updates that are part of an animation we must wait for
3247 // previous animation "frames" to be handled.
3248 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003249 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003250 if (CC_UNLIKELY(err != NO_ERROR)) {
3251 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003252 // caller after a few seconds.
3253 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3254 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003255 mAnimTransactionPending = false;
3256 break;
3257 }
3258 }
3259 }
3260
chaviwca27f252018-02-06 16:46:39 -08003261 for (const DisplayState& display : displays) {
3262 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003263 }
3264
chaviwca27f252018-02-06 16:46:39 -08003265 for (const ComposerState& state : states) {
3266 transactionFlags |= setClientStateLocked(state);
3267 }
3268
3269 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3270 // as destroyed should only occur after setting all other states. This is to allow for a
3271 // child re-parent to happen before marking its original parent as destroyed (which would
3272 // then mark the child as destroyed).
3273 for (const ComposerState& state : states) {
3274 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003275 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003276
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003277 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3278 // anyway. This can be used as a flush mechanism for previous async transactions.
3279 // Empty animation transaction can be used to simulate back-pressure, so also force a
3280 // transaction for empty animation transactions.
3281 if (transactionFlags == 0 &&
3282 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003283 transactionFlags = eTransactionNeeded;
3284 }
3285
Mathias Agopian386aa982011-11-07 21:58:03 -08003286 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003287 if (mInterceptor->isEnabled()) {
3288 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003289 }
Irvel468051e2016-06-13 16:44:44 -07003290
Mathias Agopian386aa982011-11-07 21:58:03 -08003291 // this triggers the transaction
Dan Stoza84d619e2018-03-28 17:07:36 -07003292 const auto start = (flags & eEarlyWakeup)
3293 ? VSyncModulator::TransactionStart::EARLY
3294 : VSyncModulator::TransactionStart::NORMAL;
3295 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003296
3297 // if this is a synchronous transaction, wait for it to take effect
3298 // before returning.
3299 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003300 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003301 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003302 if (flags & eAnimation) {
3303 mAnimTransactionPending = true;
3304 }
3305 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003306 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3307 if (CC_UNLIKELY(err != NO_ERROR)) {
3308 // just in case something goes wrong in SF, return to the
3309 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003310 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3311 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003312 break;
3313 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003314 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003315 }
3316}
3317
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003318uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3319 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3320 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003321
Mathias Agopiane57f2922012-08-09 16:29:12 -07003322 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003323 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3324
3325 const uint32_t what = s.what;
3326 if (what & DisplayState::eSurfaceChanged) {
3327 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3328 state.surface = s.surface;
3329 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003330 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003331 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003332 if (what & DisplayState::eLayerStackChanged) {
3333 if (state.layerStack != s.layerStack) {
3334 state.layerStack = s.layerStack;
3335 flags |= eDisplayTransactionNeeded;
3336 }
3337 }
3338 if (what & DisplayState::eDisplayProjectionChanged) {
3339 if (state.orientation != s.orientation) {
3340 state.orientation = s.orientation;
3341 flags |= eDisplayTransactionNeeded;
3342 }
3343 if (state.frame != s.frame) {
3344 state.frame = s.frame;
3345 flags |= eDisplayTransactionNeeded;
3346 }
3347 if (state.viewport != s.viewport) {
3348 state.viewport = s.viewport;
3349 flags |= eDisplayTransactionNeeded;
3350 }
3351 }
3352 if (what & DisplayState::eDisplaySizeChanged) {
3353 if (state.width != s.width) {
3354 state.width = s.width;
3355 flags |= eDisplayTransactionNeeded;
3356 }
3357 if (state.height != s.height) {
3358 state.height = s.height;
3359 flags |= eDisplayTransactionNeeded;
3360 }
3361 }
3362
Mathias Agopiane57f2922012-08-09 16:29:12 -07003363 return flags;
3364}
3365
Robert Carrd4ae7f32018-06-07 16:10:57 -07003366bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3367 IPCThreadState* ipc = IPCThreadState::self();
3368 const int pid = ipc->getCallingPid();
3369 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003370 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulece2437712018-07-19 17:01:45 -07003371 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003372 return false;
3373 }
3374 return true;
3375}
3376
chaviwca27f252018-02-06 16:46:39 -08003377uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3378 const layer_state_t& s = composerState.state;
3379 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3380
Mathias Agopian13127d82013-03-05 17:47:11 -08003381 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003382 if (layer == nullptr) {
3383 return 0;
3384 }
3385
3386 if (layer->isPendingRemoval()) {
3387 ALOGW("Attempting to set client state on removed layer: %s", layer->getName().string());
3388 return 0;
3389 }
3390
3391 uint32_t flags = 0;
3392
3393 const uint32_t what = s.what;
3394 bool geometryAppliesWithResize =
3395 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003396
3397 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3398 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003399 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003400 layer->pushPendingState();
3401 }
3402
chaviw8b3871a2017-11-01 17:41:01 -07003403 if (what & layer_state_t::ePositionChanged) {
3404 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3405 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003406 }
chaviw8b3871a2017-11-01 17:41:01 -07003407 }
3408 if (what & layer_state_t::eLayerChanged) {
3409 // NOTE: index needs to be calculated before we update the state
3410 const auto& p = layer->getParent();
3411 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003412 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003413 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003414 mCurrentState.layersSortedByZ.removeAt(idx);
3415 mCurrentState.layersSortedByZ.add(layer);
3416 // we need traversal (state changed)
3417 // AND transaction (list changed)
3418 flags |= eTransactionNeeded|eTraversalNeeded;
3419 }
chaviw8b3871a2017-11-01 17:41:01 -07003420 } else {
3421 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003422 flags |= eTransactionNeeded|eTraversalNeeded;
3423 }
3424 }
chaviw8b3871a2017-11-01 17:41:01 -07003425 }
3426 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003427 // NOTE: index needs to be calculated before we update the state
3428 const auto& p = layer->getParent();
3429 if (p == nullptr) {
3430 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3431 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3432 mCurrentState.layersSortedByZ.removeAt(idx);
3433 mCurrentState.layersSortedByZ.add(layer);
3434 // we need traversal (state changed)
3435 // AND transaction (list changed)
3436 flags |= eTransactionNeeded|eTraversalNeeded;
3437 }
3438 } else {
3439 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3440 flags |= eTransactionNeeded|eTraversalNeeded;
3441 }
chaviw8b3871a2017-11-01 17:41:01 -07003442 }
3443 }
3444 if (what & layer_state_t::eSizeChanged) {
3445 if (layer->setSize(s.w, s.h)) {
3446 flags |= eTraversalNeeded;
3447 }
3448 }
3449 if (what & layer_state_t::eAlphaChanged) {
3450 if (layer->setAlpha(s.alpha))
3451 flags |= eTraversalNeeded;
3452 }
3453 if (what & layer_state_t::eColorChanged) {
3454 if (layer->setColor(s.color))
3455 flags |= eTraversalNeeded;
3456 }
3457 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003458 // TODO: b/109894387
3459 //
3460 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3461 // rotation. To see the problem observe that if we have a square parent, and a child
3462 // of the same size, then we rotate the child 45 degrees around it's center, the child
3463 // must now be cropped to a non rectangular 8 sided region.
3464 //
3465 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3466 // private API, and the WindowManager only uses rotation in one case, which is on a top
3467 // level layer in which cropping is not an issue.
3468 //
3469 // However given that abuse of rotation matrices could lead to surfaces extending outside
3470 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3471 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3472 // transformations.
3473 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003474 flags |= eTraversalNeeded;
3475 }
3476 if (what & layer_state_t::eTransparentRegionChanged) {
3477 if (layer->setTransparentRegionHint(s.transparentRegion))
3478 flags |= eTraversalNeeded;
3479 }
3480 if (what & layer_state_t::eFlagsChanged) {
3481 if (layer->setFlags(s.flags, s.mask))
3482 flags |= eTraversalNeeded;
3483 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003484 if (what & layer_state_t::eCropChanged_legacy) {
3485 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003486 flags |= eTraversalNeeded;
3487 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003488 if (what & layer_state_t::eFinalCropChanged_legacy) {
3489 if (layer->setFinalCrop_legacy(s.finalCrop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003490 flags |= eTraversalNeeded;
3491 }
3492 if (what & layer_state_t::eLayerStackChanged) {
3493 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3494 // We only allow setting layer stacks for top level layers,
3495 // everything else inherits layer stack from its parent.
3496 if (layer->hasParent()) {
3497 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3498 layer->getName().string());
3499 } else if (idx < 0) {
3500 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3501 "that also does not appear in the top level layer list. Something"
3502 " has gone wrong.", layer->getName().string());
3503 } else if (layer->setLayerStack(s.layerStack)) {
3504 mCurrentState.layersSortedByZ.removeAt(idx);
3505 mCurrentState.layersSortedByZ.add(layer);
3506 // we need traversal (state changed)
3507 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003508 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003509 }
3510 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003511 if (what & layer_state_t::eDeferTransaction_legacy) {
3512 if (s.barrierHandle_legacy != nullptr) {
3513 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3514 } else if (s.barrierGbp_legacy != nullptr) {
3515 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003516 if (authenticateSurfaceTextureLocked(gbp)) {
3517 const auto& otherLayer =
3518 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003519 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003520 } else {
3521 ALOGE("Attempt to defer transaction to to an"
3522 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003523 }
3524 }
chaviw8b3871a2017-11-01 17:41:01 -07003525 // We don't trigger a traversal here because if no other state is
3526 // changed, we don't want this to cause any more work
3527 }
3528 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003529 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003530 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003531 if (!hadParent) {
3532 mCurrentState.layersSortedByZ.remove(layer);
3533 }
chaviw8b3871a2017-11-01 17:41:01 -07003534 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003535 }
chaviw8b3871a2017-11-01 17:41:01 -07003536 }
3537 if (what & layer_state_t::eReparentChildren) {
3538 if (layer->reparentChildren(s.reparentHandle)) {
3539 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003540 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003541 }
chaviw8b3871a2017-11-01 17:41:01 -07003542 if (what & layer_state_t::eDetachChildren) {
3543 layer->detachChildren();
3544 }
3545 if (what & layer_state_t::eOverrideScalingModeChanged) {
3546 layer->setOverrideScalingMode(s.overrideScalingMode);
3547 // We don't trigger a traversal here because if no other state is
3548 // changed, we don't want this to cause any more work
3549 }
Marissa Wall61c58622018-07-18 10:12:20 -07003550 if (what & layer_state_t::eTransformChanged) {
3551 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3552 }
3553 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3554 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3555 flags |= eTraversalNeeded;
3556 }
3557 if (what & layer_state_t::eCropChanged) {
3558 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3559 }
3560 if (what & layer_state_t::eBufferChanged) {
3561 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3562 }
3563 if (what & layer_state_t::eAcquireFenceChanged) {
3564 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3565 }
3566 if (what & layer_state_t::eDataspaceChanged) {
3567 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3568 }
3569 if (what & layer_state_t::eHdrMetadataChanged) {
3570 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3571 }
3572 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3573 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3574 }
3575 if (what & layer_state_t::eApiChanged) {
3576 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3577 }
3578 if (what & layer_state_t::eSidebandStreamChanged) {
3579 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3580 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003581 return flags;
3582}
3583
chaviwca27f252018-02-06 16:46:39 -08003584void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3585 const layer_state_t& state = composerState.state;
3586 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3587
3588 sp<Layer> layer(client->getLayerUser(state.surface));
3589 if (layer == nullptr) {
3590 return;
3591 }
3592
3593 if (layer->isPendingRemoval()) {
3594 ALOGW("Attempting to destroy on removed layer: %s", layer->getName().string());
3595 return;
3596 }
3597
3598 if (state.what & layer_state_t::eDestroySurface) {
3599 removeLayerLocked(mStateLock, layer);
3600 }
3601}
3602
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003603status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003604 const String8& name,
3605 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003606 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003607 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003608 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003609{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003610 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003611 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003612 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003613 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003614 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003615
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003616 status_t result = NO_ERROR;
3617
3618 sp<Layer> layer;
3619
Cody Northropbc755282017-03-31 12:00:08 -06003620 String8 uniqueName = getUniqueLayerName(name);
3621
Mathias Agopian3165cc22012-08-08 19:42:09 -07003622 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003623 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003624 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3625 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003626
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003627 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003628 case ISurfaceComposerClient::eFXSurfaceBufferState:
3629 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3630 break;
chaviw13fdc492017-06-27 12:40:18 -07003631 case ISurfaceComposerClient::eFXSurfaceColor:
3632 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003633 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003634 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003635 break;
3636 default:
3637 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003638 break;
3639 }
3640
Dan Stoza7d89d062015-04-30 13:29:25 -07003641 if (result != NO_ERROR) {
3642 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003643 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003644
Chia-I Wuab0c3192017-08-01 11:29:00 -07003645 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3646 // TODO b/64227542
3647 if (windowType == 441731) {
3648 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3649 layer->setPrimaryDisplayOnly();
3650 }
3651
Albert Chaulk479c60c2017-01-27 14:21:34 -05003652 layer->setInfo(windowType, ownerUid);
3653
Robert Carr1f0a16a2016-10-24 16:27:39 -07003654 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003655 if (result != NO_ERROR) {
3656 return result;
3657 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003658 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003659
3660 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003661 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003662}
3663
Cody Northropbc755282017-03-31 12:00:08 -06003664String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3665{
3666 bool matchFound = true;
3667 uint32_t dupeCounter = 0;
3668
3669 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3670 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3671
Dan Stoza436ccf32018-06-21 12:10:12 -07003672 // Grab the state lock since we're accessing mCurrentState
3673 Mutex::Autolock lock(mStateLock);
3674
Cody Northropbc755282017-03-31 12:00:08 -06003675 // Loop over layers until we're sure there is no matching name
3676 while (matchFound) {
3677 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003678 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003679 if (layer->getName() == uniqueName) {
3680 matchFound = true;
3681 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3682 }
3683 });
3684 }
3685
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003686 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3687 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003688
3689 return uniqueName;
3690}
3691
Marissa Wallfd668622018-05-10 10:21:13 -07003692status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3693 uint32_t w, uint32_t h, uint32_t flags,
3694 PixelFormat& format, sp<IBinder>* handle,
3695 sp<IGraphicBufferProducer>* gbp,
3696 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003697 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003698 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003699 case PIXEL_FORMAT_TRANSPARENT:
3700 case PIXEL_FORMAT_TRANSLUCENT:
3701 format = PIXEL_FORMAT_RGBA_8888;
3702 break;
3703 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003704 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003705 break;
3706 }
3707
Marissa Wallfd668622018-05-10 10:21:13 -07003708 sp<BufferQueueLayer> layer = new BufferQueueLayer(this, client, name, w, h, flags);
3709 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003710 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003711 *handle = layer->getHandle();
3712 *gbp = layer->getProducer();
3713 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003714 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003715
Marissa Wallfd668622018-05-10 10:21:13 -07003716 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003717 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003718}
3719
Marissa Wall61c58622018-07-18 10:12:20 -07003720status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3721 uint32_t w, uint32_t h, uint32_t flags,
3722 sp<IBinder>* handle, sp<Layer>* outLayer) {
3723 sp<BufferStateLayer> layer = new BufferStateLayer(this, client, name, w, h, flags);
3724 *handle = layer->getHandle();
3725 *outLayer = layer;
3726
3727 return NO_ERROR;
3728}
3729
chaviw13fdc492017-06-27 12:40:18 -07003730status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003731 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003732 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003733{
chaviw13fdc492017-06-27 12:40:18 -07003734 *outLayer = new ColorLayer(this, client, name, w, h, flags);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003735 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003736 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003737}
3738
Mathias Agopianac9fa422013-02-11 16:40:36 -08003739status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003740{
Robert Carr9524cb32017-02-13 11:32:32 -08003741 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003742 status_t err = NO_ERROR;
3743 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003744 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003745 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003746 err = removeLayer(l);
3747 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3748 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003749 }
3750 return err;
3751}
3752
Mathias Agopian13127d82013-03-05 17:47:11 -08003753status_t SurfaceFlinger::onLayerDestroyed(const wp<Layer>& layer)
Mathias Agopian9a112062009-04-17 19:36:26 -07003754{
Mathias Agopian67106042013-03-14 19:18:13 -07003755 // called by ~LayerCleaner() when all references to the IBinder (handle)
3756 // are gone
Robert Carr9524cb32017-02-13 11:32:32 -08003757 sp<Layer> l = layer.promote();
3758 if (l == nullptr) {
3759 // The layer has already been removed, carry on
3760 return NO_ERROR;
Robert Carr9524cb32017-02-13 11:32:32 -08003761 }
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003762 // If we have a parent, then we can continue to live as long as it does.
3763 return removeLayer(l, true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003764}
3765
Mathias Agopianb60314a2012-04-10 22:09:54 -07003766// ---------------------------------------------------------------------------
3767
Andy McFadden13a082e2012-08-24 10:16:42 -07003768void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003769 const auto displayToken = mDisplayTokens[DisplayDevice::DISPLAY_PRIMARY];
3770 if (!displayToken) return;
3771
Jesse Hall01e29052013-02-19 16:13:35 -08003772 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003773 Vector<ComposerState> state;
3774 Vector<DisplayState> displays;
3775 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003776 d.what = DisplayState::eDisplayProjectionChanged |
3777 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003778 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003779 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003780 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003781 d.frame.makeInvalid();
3782 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003783 d.width = 0;
3784 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003785 displays.add(d);
3786 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003787
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003788 const auto display = getDisplayDevice(displayToken);
3789 if (!display) return;
3790
3791 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL, /*stateLockHeld*/ false);
3792
3793 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003794 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003795 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003796
Brian Andersond0010582017-03-07 13:20:31 -08003797 // Use phase of 0 since phase is not known.
3798 // Use latency of 0, which will snap to the ideal latency.
3799 setCompositorTimingSnapped(0, period, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003800}
3801
3802void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003803 // Async since we may be called from the main thread.
3804 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003805}
3806
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003807void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode,
3808 bool stateLockHeld) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07003809 const int32_t displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003810 ALOGD("Setting power mode %d on display %d", mode, displayId);
Andy McFadden13a082e2012-08-24 10:16:42 -07003811
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003812 int currentMode = display->getPowerMode();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003813 if (mode == currentMode) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003814 return;
3815 }
3816
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003817 if (display->isVirtual()) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003818 ALOGW("Trying to set power mode for virtual display");
3819 return;
3820 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003821
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003822 display->setPowerMode(mode);
3823
Lloyd Pique4dccc412018-01-22 17:21:36 -08003824 if (mInterceptor->isEnabled()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07003825 ConditionalLock lock(mStateLock, !stateLockHeld);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003826 ssize_t idx = mCurrentState.displays.indexOfKey(display->getDisplayToken());
Irvelffc9efc2016-07-27 15:16:37 -07003827 if (idx < 0) {
3828 ALOGW("Surface Interceptor SavePowerMode: invalid display token");
3829 return;
3830 }
Dominik Laskowski663bd282018-04-19 15:26:54 -07003831 mInterceptor->savePowerModeUpdate(mCurrentState.displays.valueAt(idx).sequenceId, mode);
Irvelffc9efc2016-07-27 15:16:37 -07003832 }
3833
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003834 int32_t type = display->getDisplayType();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003835 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003836 // Turn on the display
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003837 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003838 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003839 // FIXME: eventthread only knows about the main display right now
3840 mEventThread->onScreenAcquired();
Jesse Hall948fe0c2013-10-14 12:56:09 -07003841 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003842 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003843
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003844 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003845 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003846 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003847
3848 struct sched_param param = {0};
3849 param.sched_priority = 1;
3850 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3851 ALOGW("Couldn't set SCHED_FIFO on display on");
3852 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003853 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003854 // Turn off the display
3855 struct sched_param param = {0};
3856 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3857 ALOGW("Couldn't set SCHED_OTHER on display off");
3858 }
3859
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003860 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Jesse Hall948fe0c2013-10-14 12:56:09 -07003861 disableHardwareVsync(true); // also cancels any in-progress resync
3862
Mathias Agopiancde87a32012-09-13 14:09:01 -07003863 // FIXME: eventthread only knows about the main display right now
3864 mEventThread->onScreenReleased();
3865 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003866
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003867 getHwComposer().setPowerMode(type, mode);
3868 mVisibleRegionsDirty = true;
3869 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003870 } else if (mode == HWC_POWER_MODE_DOZE ||
3871 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003872 // Update display while dozing
3873 getHwComposer().setPowerMode(type, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003874 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003875 // FIXME: eventthread only knows about the main display right now
3876 mEventThread->onScreenAcquired();
3877 resyncToHardwareVsync(true);
3878 }
3879 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3880 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003881 if (display->isPrimary()) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003882 disableHardwareVsync(true); // also cancels any in-progress resync
3883 // FIXME: eventthread only knows about the main display right now
3884 mEventThread->onScreenReleased();
3885 }
3886 getHwComposer().setPowerMode(type, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003887 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003888 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003889 getHwComposer().setPowerMode(type, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003890 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003891
3892 ALOGD("Finished setting power mode %d on display %d", mode, displayId);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003893}
3894
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003895void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003896 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003897 const auto display = getDisplayDevice(displayToken);
3898 if (!display) {
3899 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3900 displayToken.get());
3901 } else if (display->isVirtual()) {
3902 ALOGW("Attempt to set power mode %d for virtual display", mode);
3903 } else {
3904 setPowerModeInternal(display, mode, /*stateLockHeld*/ false);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003905 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003906 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003907}
3908
3909// ---------------------------------------------------------------------------
3910
Lloyd Pique755e3192018-01-31 16:46:15 -08003911status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
3912 NO_THREAD_SAFETY_ANALYSIS {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003913 String8 result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003914
Mathias Agopianbd115332013-04-18 16:41:04 -07003915 IPCThreadState* ipc = IPCThreadState::self();
3916 const int pid = ipc->getCallingPid();
3917 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003918
Mathias Agopianbd115332013-04-18 16:41:04 -07003919 if ((uid != AID_SHELL) &&
3920 !PermissionCache::checkPermission(sDump, pid, uid)) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02003921 result.appendFormat("Permission Denial: "
Mathias Agopianbd115332013-04-18 16:41:04 -07003922 "can't dump SurfaceFlinger from pid=%d, uid=%d\n", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003923 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003924 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003925 // (this would indicate SF is stuck, but we want to be able to
3926 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003927 status_t err = mStateLock.timedLock(s2ns(1));
3928 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003929 if (!locked) {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003930 result.appendFormat(
3931 "SurfaceFlinger appears to be unresponsive (%s [%d]), "
3932 "dumping anyways (no locks held)\n", strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003933 }
3934
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003935 bool dumpAll = true;
3936 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003937 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07003938
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003939 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003940 if ((index < numArgs) &&
3941 (args[index] == String16("--list"))) {
3942 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003943 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003944 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003945 }
3946
3947 if ((index < numArgs) &&
3948 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003949 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003950 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003951 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003952 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003953
3954 if ((index < numArgs) &&
3955 (args[index] == String16("--latency-clear"))) {
3956 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02003957 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08003958 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003959 }
Andy McFaddenc751e922014-05-08 14:53:26 -07003960
3961 if ((index < numArgs) &&
3962 (args[index] == String16("--dispsync"))) {
3963 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07003964 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07003965 dumpAll = false;
3966 }
Dan Stozab90cf072015-03-05 11:05:59 -08003967
3968 if ((index < numArgs) &&
3969 (args[index] == String16("--static-screen"))) {
3970 index++;
3971 dumpStaticScreenStats(result);
3972 dumpAll = false;
3973 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08003974
3975 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07003976 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08003977 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07003978 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08003979 dumpAll = false;
3980 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06003981
3982 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
3983 index++;
3984 dumpWideColorInfo(result);
3985 dumpAll = false;
3986 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08003987
3988 if ((index < numArgs) &&
3989 (args[index] == String16("--enable-layer-stats"))) {
3990 index++;
3991 mLayerStats.enable();
3992 dumpAll = false;
3993 }
3994
3995 if ((index < numArgs) &&
3996 (args[index] == String16("--disable-layer-stats"))) {
3997 index++;
3998 mLayerStats.disable();
3999 dumpAll = false;
4000 }
4001
4002 if ((index < numArgs) &&
4003 (args[index] == String16("--clear-layer-stats"))) {
4004 index++;
4005 mLayerStats.clear();
4006 dumpAll = false;
4007 }
4008
4009 if ((index < numArgs) &&
4010 (args[index] == String16("--dump-layer-stats"))) {
4011 index++;
4012 mLayerStats.dump(result);
4013 dumpAll = false;
4014 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004015
4016 if ((index < numArgs) &&
4017 (args[index] == String16("--display-identification"))) {
4018 index++;
4019 dumpDisplayIdentificationData(result);
4020 dumpAll = false;
4021 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004022
4023 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4024 index++;
4025 mTimeStats.parseArgs(asProto, args, index, result);
4026 dumpAll = false;
4027 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004028 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004029
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004030 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004031 if (asProto) {
4032 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4033 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4034 } else {
4035 dumpAllLocked(args, index, result);
4036 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004037 }
4038
Mathias Agopian9795c422009-08-26 16:36:26 -07004039 if (locked) {
4040 mStateLock.unlock();
4041 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004042 }
4043 write(fd, result.string(), result.size());
4044 return NO_ERROR;
4045}
4046
Dan Stozac7014012014-02-14 15:03:43 -08004047void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */,
4048 size_t& /* index */, String8& result) const
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004049{
Robert Carr2047fae2016-11-28 14:09:09 -08004050 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian74d211a2013-04-22 16:55:35 +02004051 result.appendFormat("%s\n", layer->getName().string());
Robert Carr2047fae2016-11-28 14:09:09 -08004052 });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004053}
4054
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004055void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Mathias Agopian74d211a2013-04-22 16:55:35 +02004056 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004057{
4058 String8 name;
4059 if (index < args.size()) {
4060 name = String8(args[index]);
4061 index++;
4062 }
4063
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004064 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4065 getHwComposer().isConnected(displayId)) {
4066 const auto activeConfig = getBE().mHwc->getActiveConfig(displayId);
4067 const nsecs_t period = activeConfig->getVsyncPeriod();
4068 result.appendFormat("%" PRId64 "\n", period);
4069 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004070
4071 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004072 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004073 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004074 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004075 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004076 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004077 }
Robert Carr2047fae2016-11-28 14:09:09 -08004078 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004079 }
4080}
4081
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004082void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Dan Stozac7014012014-02-14 15:03:43 -08004083 String8& /* result */)
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004084{
4085 String8 name;
4086 if (index < args.size()) {
4087 name = String8(args[index]);
4088 index++;
4089 }
4090
Robert Carr2047fae2016-11-28 14:09:09 -08004091 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004092 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004093 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004094 }
Robert Carr2047fae2016-11-28 14:09:09 -08004095 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004096
Svetoslavd85084b2014-03-20 10:28:31 -07004097 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004098}
4099
Jamie Gennis6547ff42013-07-16 20:12:42 -07004100// This should only be called from the main thread. Otherwise it would need
4101// the lock and should use mCurrentState rather than mDrawingState.
4102void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004103 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004104 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004105 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004106
4107 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4108}
4109
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004110void SurfaceFlinger::appendSfConfigString(String8& result) const
Andy McFadden4803b742012-09-24 19:07:20 -07004111{
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004112 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004113
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004114 if (isLayerTripleBufferingDisabled())
4115 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004116
4117 result.appendFormat(" PRESENT_TIME_OFFSET=%" PRId64 , dispSyncPresentTimeOffset);
Fabien Sanglarda34ed632017-03-14 11:43:52 -07004118 result.appendFormat(" FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -08004119 result.appendFormat(" MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08004120 result.appendFormat(" RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
Fabien Sanglard1971b632017-03-10 14:50:03 -08004121 result.appendFormat(" NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4122 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004123 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004124}
4125
Dan Stozab90cf072015-03-05 11:05:59 -08004126void SurfaceFlinger::dumpStaticScreenStats(String8& result) const
4127{
4128 result.appendFormat("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004129 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4130 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004131 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004132 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004133 result.appendFormat(" < %zd frames: %.3f s (%.1f%%)\n",
4134 b + 1, bucketTimeSec, percent);
4135 }
David Sodman4a36e932017-11-07 14:29:47 -08004136 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004137 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004138 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Dan Stozab90cf072015-03-05 11:05:59 -08004139 result.appendFormat(" %zd+ frames: %.3f s (%.1f%%)\n",
David Sodman4a36e932017-11-07 14:29:47 -08004140 SurfaceFlingerBE::NUM_BUCKETS - 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004141}
4142
Dan Stozae77c7662016-05-13 11:37:28 -07004143void SurfaceFlinger::recordBufferingStats(const char* layerName,
4144 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004145 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4146 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004147 for (const auto& segment : history) {
4148 if (!segment.usedThirdBuffer) {
4149 stats.twoBufferTime += segment.totalTime;
4150 }
4151 if (segment.occupancyAverage < 1.0f) {
4152 stats.doubleBufferedTime += segment.totalTime;
4153 } else if (segment.occupancyAverage < 2.0f) {
4154 stats.tripleBufferedTime += segment.totalTime;
4155 }
4156 ++stats.numSegments;
4157 stats.totalTime += segment.totalTime;
4158 }
4159}
4160
Brian Andersond6927fb2016-07-23 23:37:30 -07004161void SurfaceFlinger::dumpFrameEventsLocked(String8& result) {
4162 result.appendFormat("Layer frame timestamps:\n");
4163
4164 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4165 const size_t count = currentLayers.size();
4166 for (size_t i=0 ; i<count ; i++) {
4167 currentLayers[i]->dumpFrameEvents(result);
4168 }
4169}
4170
Dan Stozae77c7662016-05-13 11:37:28 -07004171void SurfaceFlinger::dumpBufferingStats(String8& result) const {
4172 result.append("Buffering stats:\n");
4173 result.append(" [Layer name] <Active time> <Two buffer> "
4174 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004175 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004176 typedef std::tuple<std::string, float, float, float> BufferTuple;
4177 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004178 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004179 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004180 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004181 if (stats.numSegments == 0) {
4182 continue;
4183 }
4184 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4185 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4186 stats.totalTime;
4187 float doubleBufferRatio = static_cast<float>(
4188 stats.doubleBufferedTime) / stats.totalTime;
4189 float tripleBufferRatio = static_cast<float>(
4190 stats.tripleBufferedTime) / stats.totalTime;
4191 sorted.insert({activeTime, {name, twoBufferRatio,
4192 doubleBufferRatio, tripleBufferRatio}});
4193 }
4194 for (const auto& sortedPair : sorted) {
4195 float activeTime = sortedPair.first;
4196 const BufferTuple& values = sortedPair.second;
4197 result.appendFormat(" [%s] %.2f %.3f %.3f %.3f\n",
4198 std::get<0>(values).c_str(), activeTime,
4199 std::get<1>(values), std::get<2>(values),
4200 std::get<3>(values));
4201 }
4202 result.append("\n");
4203}
4204
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004205void SurfaceFlinger::dumpDisplayIdentificationData(String8& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004206 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004207 const int32_t displayId = display->getId();
4208 const auto hwcDisplayId = getHwComposer().getHwcDisplayId(displayId);
4209 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004210 continue;
4211 }
4212
Dominik Laskowski7e045462018-05-30 13:02:02 -07004213 result.appendFormat("Display %d (HWC display %" PRIu64 "): ", displayId, *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004214 uint8_t port;
4215 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004216 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004217 result.append("no identification data\n");
4218 continue;
4219 }
4220
4221 if (!isEdid(data)) {
4222 result.append("unknown identification data: ");
4223 for (uint8_t byte : data) {
4224 result.appendFormat("%x ", byte);
4225 }
4226 result.append("\n");
4227 continue;
4228 }
4229
4230 const auto edid = parseEdid(data);
4231 if (!edid) {
4232 result.append("invalid EDID: ");
4233 for (uint8_t byte : data) {
4234 result.appendFormat("%x ", byte);
4235 }
4236 result.append("\n");
4237 continue;
4238 }
4239
4240 result.appendFormat("port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
4241 result.append(edid->displayName.data(), edid->displayName.length());
4242 result.append("\"\n");
4243 }
4244 result.append("\n");
4245}
4246
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004247void SurfaceFlinger::dumpWideColorInfo(String8& result) const {
4248 result.appendFormat("hasWideColorDisplay: %d\n", hasWideColorDisplay);
Chia-I Wu0d711262018-05-21 15:19:35 -07004249 result.appendFormat("DisplayColorSetting: %s\n",
4250 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004251
4252 // TODO: print out if wide-color mode is active or not
4253
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004254 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004255 const int32_t displayId = display->getId();
4256 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004257 continue;
4258 }
4259
Dominik Laskowski7e045462018-05-30 13:02:02 -07004260 result.appendFormat("Display %d color modes:\n", displayId);
4261 std::vector<ColorMode> modes = getHwComposer().getColorModes(displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004262 for (auto&& mode : modes) {
4263 result.appendFormat(" %s (%d)\n", decodeColorMode(mode).c_str(), mode);
4264 }
4265
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004266 ColorMode currentMode = display->getActiveColorMode();
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004267 result.appendFormat(" Current color mode: %s (%d)\n",
4268 decodeColorMode(currentMode).c_str(), currentMode);
4269 }
4270 result.append("\n");
4271}
4272
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004273LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004274 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004275 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4276 const State& state = useDrawing ? mDrawingState : mCurrentState;
4277 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004278 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004279 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004280 });
4281
4282 return layersProto;
4283}
4284
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004285LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004286 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004287
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004288 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004289 resolution->set_w(display.getWidth());
4290 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004291
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004292 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4293 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4294 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004295
Dominik Laskowski7e045462018-05-30 13:02:02 -07004296 const int32_t displayId = display.getId();
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004297 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004298 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004299 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski7e045462018-05-30 13:02:02 -07004300 layer->writeToProto(layerProto, displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004301 }
4302 });
4303
4304 return layersProto;
4305}
4306
Mathias Agopian74d211a2013-04-22 16:55:35 +02004307void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
4308 String8& result) const
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004309{
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004310 bool colorize = false;
4311 if (index < args.size()
4312 && (args[index] == String16("--color"))) {
4313 colorize = true;
4314 index++;
4315 }
4316
4317 Colorizer colorizer(colorize);
4318
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004319 // figure out if we're stuck somewhere
4320 const nsecs_t now = systemTime();
4321 const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
4322 const nsecs_t inTransaction(mDebugInTransaction);
4323 nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
4324 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4325
4326 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004327 * Dump library configuration.
4328 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004329
4330 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004331 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004332 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004333 appendSfConfigString(result);
4334 appendUiConfigString(result);
4335 appendGuiConfigString(result);
4336 result.append("\n");
4337
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004338 result.append("\nDisplay identification data:\n");
4339 dumpDisplayIdentificationData(result);
4340
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004341 result.append("\nWide-Color information:\n");
4342 dumpWideColorInfo(result);
4343
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004344 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004345 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004346 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004347 result.append(SyncFeatures::getInstance().toString());
4348 result.append("\n");
4349
Andy McFadden41d67d72014-04-25 16:58:34 -07004350 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004351 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004352 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004353
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004354 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4355 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004356 if (const auto displayId = DisplayDevice::DISPLAY_PRIMARY;
4357 getHwComposer().isConnected(displayId)) {
4358 const auto activeConfig = getHwComposer().getActiveConfig(displayId);
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004359 result.appendFormat("Display %d: "
4360 "app phase %" PRId64 " ns, "
4361 "sf phase %" PRId64 " ns, "
4362 "early app phase %" PRId64 " ns, "
4363 "early sf phase %" PRId64 " ns, "
4364 "early app gl phase %" PRId64 " ns, "
4365 "early sf gl phase %" PRId64 " ns, "
4366 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4367 displayId,
4368 vsyncPhaseOffsetNs,
4369 sfVsyncPhaseOffsetNs,
4370 appEarlyOffset,
4371 sfEarlyOffset,
4372 appEarlyGlOffset,
4373 sfEarlyOffset,
4374 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004375 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004376 result.append("\n");
4377
Dan Stozab90cf072015-03-05 11:05:59 -08004378 // Dump static screen stats
4379 result.append("\n");
4380 dumpStaticScreenStats(result);
4381 result.append("\n");
4382
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004383 result.appendFormat("Missed frame count: %u\n\n", mFrameMissedCount.load());
4384
Dan Stozae77c7662016-05-13 11:37:28 -07004385 dumpBufferingStats(result);
4386
Andy McFadden4803b742012-09-24 19:07:20 -07004387 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004388 * Dump the visible layer list
4389 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004390 colorizer.bold(result);
Robert Carr1f0a16a2016-10-24 16:27:39 -07004391 result.appendFormat("Visible layers (count = %zu)\n", mNumLayers);
Dan Stoza0a0158c2018-03-16 13:38:54 -07004392 result.appendFormat("GraphicBufferProducers: %zu, max %zu\n",
4393 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004394 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004395
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004396 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
chaviw1d044282017-09-27 12:19:28 -07004397 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
chaviw7ba019b2018-03-14 13:28:39 -07004398 result.append(LayerProtoParser::layersToString(std::move(layerTree)).c_str());
Chia-I Wu1e043612018-03-01 09:45:09 -08004399 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004400
4401 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004402 * Dump Display state
4403 */
4404
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004405 colorizer.bold(result);
Greg Hackmann86efcc02014-03-07 12:44:02 -08004406 result.appendFormat("Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004407 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004408 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004409 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004410 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004411 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004412
4413 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004414 * Dump SurfaceFlinger global state
4415 */
4416
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004417 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004418 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004419 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004420
Mathias Agopian888c8222012-08-04 21:10:38 -07004421 HWComposer& hwc(getHwComposer());
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004422 const auto display = getDefaultDisplayDeviceLocked();
Mathias Agopianca088332013-03-28 17:44:13 -07004423
David Sodmanbc815282017-11-05 18:57:52 -08004424 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004425
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004426 if (display) {
4427 display->undefinedRegion.dump(result, "undefinedRegion");
4428 result.appendFormat(" orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4429 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004430 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004431 result.appendFormat(" last eglSwapBuffers() time: %f us\n"
4432 " last transaction time : %f us\n"
4433 " transaction-flags : %08x\n"
4434 " gpu_to_cpu_unsupported : %d\n",
4435 mLastSwapBufferTime / 1000.0, mLastTransactionTime / 1000.0,
4436 mTransactionFlags, !mGpuToCpuSupported);
4437
4438 if (display) {
4439 const auto activeConfig = getHwComposer().getActiveConfig(display->getId());
4440 result.appendFormat(" refresh-rate : %f fps\n"
4441 " x-dpi : %f\n"
4442 " y-dpi : %f\n",
4443 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4444 activeConfig->getDpiY());
4445 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004446
Mathias Agopian74d211a2013-04-22 16:55:35 +02004447 result.appendFormat(" eglSwapBuffers time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004448 inSwapBuffersDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004449
Mathias Agopian74d211a2013-04-22 16:55:35 +02004450 result.appendFormat(" transaction time: %f us\n",
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004451 inTransactionDuration/1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004452
4453 /*
4454 * VSYNC state
4455 */
Mathias Agopian74d211a2013-04-22 16:55:35 +02004456 mEventThread->dump(result);
Dan Stozae22aec72016-08-01 13:20:59 -07004457 result.append("\n");
4458
4459 /*
4460 * HWC layer minidump
4461 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004462 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004463 const int32_t displayId = display->getId();
4464 if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
Dan Stozae22aec72016-08-01 13:20:59 -07004465 continue;
4466 }
4467
Dominik Laskowski7e045462018-05-30 13:02:02 -07004468 result.appendFormat("Display %d HWC layers:\n", displayId);
Dan Stozae22aec72016-08-01 13:20:59 -07004469 Layer::miniDumpHeader(result);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004470 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004471 result.append("\n");
4472 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004473
4474 /*
4475 * Dump HWComposer state
4476 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004477 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004478 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004479 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004480 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Dan Stoza9e56aa02015-11-02 13:00:03 -08004481 result.appendFormat(" h/w composer %s\n",
4482 hwcDisabled ? "disabled" : "enabled");
Mathias Agopian74d211a2013-04-22 16:55:35 +02004483 hwc.dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004484
4485 /*
4486 * Dump gralloc state
4487 */
4488 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4489 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004490
4491 /*
4492 * Dump VrFlinger state if in use.
4493 */
4494 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4495 result.append("VrFlinger state:\n");
4496 result.append(mVrFlinger->Dump().c_str());
4497 result.append("\n");
4498 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004499}
4500
Dominik Laskowski7e045462018-05-30 13:02:02 -07004501const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(int32_t displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004502 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004503 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004504 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004505 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004506 }
4507 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004508
4509 ALOGE("%s: Invalid display %d", __FUNCTION__, displayId);
4510 static const Vector<sp<Layer>> empty;
4511 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004512}
4513
Keun young Park63f165f2012-08-31 10:53:36 -07004514bool SurfaceFlinger::startDdmConnection()
4515{
4516 void* libddmconnection_dso =
4517 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4518 if (!libddmconnection_dso) {
4519 return false;
4520 }
4521 void (*DdmConnection_start)(const char* name);
4522 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004523 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004524 if (!DdmConnection_start) {
4525 dlclose(libddmconnection_dso);
4526 return false;
4527 }
4528 (*DdmConnection_start)(getServiceName());
4529 return true;
4530}
4531
Chia-I Wu28f320b2018-05-03 11:02:56 -07004532void SurfaceFlinger::updateColorMatrixLocked() {
4533 mat4 colorMatrix;
4534 if (mGlobalSaturationFactor != 1.0f) {
4535 // Rec.709 luma coefficients
4536 float3 luminance{0.213f, 0.715f, 0.072f};
4537 luminance *= 1.0f - mGlobalSaturationFactor;
4538 mat4 saturationMatrix = mat4(
4539 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4540 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4541 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4542 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4543 );
4544 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4545 } else {
4546 colorMatrix = mClientColorMatrix * mDaltonizer();
4547 }
4548
4549 if (mCurrentState.colorMatrix != colorMatrix) {
4550 mCurrentState.colorMatrix = colorMatrix;
4551 mCurrentState.colorMatrixChanged = true;
4552 setTransactionFlags(eTransactionNeeded);
4553 }
4554}
4555
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004556status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulece2437712018-07-19 17:01:45 -07004557#pragma clang diagnostic push
4558#pragma clang diagnostic error "-Wswitch-enum"
4559 switch (static_cast<ISurfaceComposerTag>(code)) {
4560 // These methods should at minimum make sure that the client requested
4561 // access to SF.
4562 case AUTHENTICATE_SURFACE:
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004563 case BOOT_FINISHED:
Svetoslavd85084b2014-03-20 10:28:31 -07004564 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulece2437712018-07-19 17:01:45 -07004565 case CREATE_CONNECTION:
4566 case CREATE_DISPLAY:
4567 case DESTROY_DISPLAY:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004568 case ENABLE_VSYNC_INJECTIONS:
Ana Krulece2437712018-07-19 17:01:45 -07004569 case GET_ACTIVE_COLOR_MODE:
4570 case GET_ANIMATION_FRAME_STATS:
4571 case GET_HDR_CAPABILITIES:
4572 case GET_DISPLAY_COLOR_MODES:
4573 case SET_ACTIVE_CONFIG:
4574 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004575 case INJECT_VSYNC:
Ana Krulece2437712018-07-19 17:01:45 -07004576 case SET_POWER_MODE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004577 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4578 IPCThreadState* ipc = IPCThreadState::self();
4579 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4580 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004581 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004582 }
Robert Carr1db73f62016-12-21 12:58:51 -08004583 return OK;
4584 }
Ana Krulece2437712018-07-19 17:01:45 -07004585 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004586 IPCThreadState* ipc = IPCThreadState::self();
4587 const int pid = ipc->getCallingPid();
4588 const int uid = ipc->getCallingUid();
Ana Krulece2437712018-07-19 17:01:45 -07004589 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4590 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004591 return PERMISSION_DENIED;
4592 }
Ana Krulece2437712018-07-19 17:01:45 -07004593 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004594 }
Ana Krulece2437712018-07-19 17:01:45 -07004595 // Used by apps to hook Choreographer to SurfaceFlinger.
4596 case CREATE_DISPLAY_EVENT_CONNECTION:
4597 // The following calls are currently used by clients that do not
4598 // request necessary permissions. However, they do not expose any secret
4599 // information, so it is OK to pass them.
4600 case GET_ACTIVE_CONFIG:
4601 case GET_BUILT_IN_DISPLAY:
4602 case GET_DISPLAY_CONFIGS:
4603 case GET_DISPLAY_STATS:
4604 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4605 // Calling setTransactionState is safe, because you need to have been
4606 // granted a reference to Client* and Handle* to do anything with it.
4607 case SET_TRANSACTION_STATE:
4608 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
4609 case CREATE_SCOPED_CONNECTION: {
4610 return OK;
4611 }
4612 case CAPTURE_LAYERS:
4613 case CAPTURE_SCREEN: {
4614 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004615 IPCThreadState* ipc = IPCThreadState::self();
4616 const int pid = ipc->getCallingPid();
4617 const int uid = ipc->getCallingUid();
4618 if ((uid != AID_GRAPHICS) &&
4619 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4620 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4621 return PERMISSION_DENIED;
4622 }
Ana Krulece2437712018-07-19 17:01:45 -07004623 return OK;
4624 }
4625 // The following codes are deprecated and should never be allowed to access SF.
4626 case CONNECT_DISPLAY_UNUSED:
4627 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4628 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4629 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004630 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004631 }
Ana Krulece2437712018-07-19 17:01:45 -07004632
4633 // This code is used for IBinder protocol to interrogate the recipient
4634 // side of the transaction for its canonical interface descriptor. We
4635 // can let it pass by default.
4636 if (code == IBinder::INTERFACE_TRANSACTION) {
4637 return OK;
4638 }
David Sodmandeed4e72018-08-08 12:44:26 -07004639 // Numbers from 1000 to 1029 are currently use for backdoors. The code
Ana Krulece2437712018-07-19 17:01:45 -07004640 // in onTransact verifies that the user is root, and has access to use SF.
David Sodmandeed4e72018-08-08 12:44:26 -07004641 if (code >= 1000 && code <= 1029) {
Ana Krulece2437712018-07-19 17:01:45 -07004642 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4643 return OK;
4644 }
4645 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4646 return PERMISSION_DENIED;
4647#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004648}
4649
Ana Krulece2437712018-07-19 17:01:45 -07004650status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4651 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004652 status_t credentialCheck = CheckTransactCodeCredentials(code);
4653 if (credentialCheck != OK) {
4654 return credentialCheck;
4655 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004656
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004657 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4658 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004659 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004660 IPCThreadState* ipc = IPCThreadState::self();
4661 const int uid = ipc->getCallingUid();
4662 if (CC_UNLIKELY(uid != AID_SYSTEM
4663 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004664 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004665 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004666 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004667 return PERMISSION_DENIED;
4668 }
4669 int n;
4670 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004671 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004672 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004673 return NO_ERROR;
4674 case 1002: // SHOW_UPDATES
4675 n = data.readInt32();
4676 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004677 invalidateHwcGeometry();
4678 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004679 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004680 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004681 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004682 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004683 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004684 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004685 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004686 setTransactionFlags(
4687 eTransactionNeeded|
4688 eDisplayTransactionNeeded|
4689 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004690 return NO_ERROR;
4691 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004692 case 1006:{ // send empty update
4693 signalRefresh();
4694 return NO_ERROR;
4695 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004696 case 1008: // toggle use of hw composer
4697 n = data.readInt32();
4698 mDebugDisableHWC = n ? 1 : 0;
4699 invalidateHwcGeometry();
4700 repaintEverything();
4701 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004702 case 1009: // toggle use of transform hint
4703 n = data.readInt32();
4704 mDebugDisableTransformHint = n ? 1 : 0;
4705 invalidateHwcGeometry();
4706 repaintEverything();
4707 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004708 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004709 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004710 reply->writeInt32(0);
4711 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004712 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004713 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004714 return NO_ERROR;
4715 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004716 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004717 if (!display) {
4718 return NAME_NOT_FOUND;
4719 }
4720
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004721 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004722 return NO_ERROR;
4723 }
4724 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004725 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004726 // daltonize
4727 n = data.readInt32();
4728 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004729 case 1:
4730 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4731 break;
4732 case 2:
4733 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4734 break;
4735 case 3:
4736 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4737 break;
4738 default:
4739 mDaltonizer.setType(ColorBlindnessType::None);
4740 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004741 }
4742 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004743 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004744 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004745 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004746 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004747
4748 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004749 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004750 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004751 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004752 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004753 // apply a color matrix
4754 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004755 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004756 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004757 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004758 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004759 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004760 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004761 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004762 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004763 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004764 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004765
4766 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4767 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004768 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004769 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4770 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4771 }
4772
Chia-I Wu28f320b2018-05-03 11:02:56 -07004773 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004774 return NO_ERROR;
4775 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004776 // This is an experimental interface
4777 // Needs to be shifted to proper binder interface when we productize
4778 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004779 n = data.readInt32();
Lloyd Pique41be5d22018-06-21 13:11:48 -07004780 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004781 return NO_ERROR;
4782 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004783 case 1017: {
4784 n = data.readInt32();
4785 mForceFullDamage = static_cast<bool>(n);
4786 return NO_ERROR;
4787 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004788 case 1018: { // Modify Choreographer's phase offset
4789 n = data.readInt32();
4790 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4791 return NO_ERROR;
4792 }
4793 case 1019: { // Modify SurfaceFlinger's phase offset
4794 n = data.readInt32();
4795 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
4796 return NO_ERROR;
4797 }
Irvel468051e2016-06-13 16:44:44 -07004798 case 1020: { // Layer updates interceptor
4799 n = data.readInt32();
4800 if (n) {
4801 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004802 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004803 }
4804 else{
4805 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004806 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004807 }
4808 return NO_ERROR;
4809 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004810 case 1021: { // Disable HWC virtual displays
4811 n = data.readInt32();
4812 mUseHwcVirtualDisplays = !n;
4813 return NO_ERROR;
4814 }
Romain Guy0147a172017-06-01 13:53:56 -07004815 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004816 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004817 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004818
Chia-I Wu28f320b2018-05-03 11:02:56 -07004819 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004820 return NO_ERROR;
4821 }
Romain Guy54f154a2017-10-24 21:40:32 +01004822 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07004823 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01004824 invalidateHwcGeometry();
4825 repaintEverything();
4826 return NO_ERROR;
4827 }
4828 case 1024: { // Is wide color gamut rendering/color management supported?
4829 reply->writeBool(hasWideColorDisplay);
4830 return NO_ERROR;
4831 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004832 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004833 n = data.readInt32();
4834 if (n) {
4835 ALOGV("LayerTracing enabled");
4836 mTracing.enable();
4837 doTracing("tracing.enable");
4838 reply->writeInt32(NO_ERROR);
4839 } else {
4840 ALOGV("LayerTracing disabled");
4841 status_t err = mTracing.disable();
4842 reply->writeInt32(err);
4843 }
4844 return NO_ERROR;
4845 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004846 case 1026: { // Get layer tracing status
4847 reply->writeBool(mTracing.isEnabled());
4848 return NO_ERROR;
4849 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004850 // Is a DisplayColorSetting supported?
4851 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004852 const auto display = getDefaultDisplayDevice();
4853 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004854 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004855 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004856
4857 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4858 switch (setting) {
4859 case DisplayColorSetting::MANAGED:
4860 reply->writeBool(hasWideColorDisplay);
4861 break;
4862 case DisplayColorSetting::UNMANAGED:
4863 reply->writeBool(true);
4864 break;
4865 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004866 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004867 break;
4868 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004869 reply->writeBool(
4870 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004871 break;
4872 }
4873 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004874 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004875 // Is VrFlinger active?
4876 case 1028: {
4877 Mutex::Autolock _l(mStateLock);
4878 reply->writeBool(getBE().mHwc->isUsingVrComposer());
4879 return NO_ERROR;
4880 }
David Sodman6d46c1e2018-07-13 12:59:48 -07004881 case 1029: {
4882 // Code 1029 is an experimental feature that allows applications to
4883 // simulate a high frequency panel by setting a multiplier and divisor
4884 // on the VSYNC-sf clock. If either the multiplier or divisor are
4885 // 0, then the code will set both to 1 to return the VSYNC-sf clock
4886 // to it's normal frequency.
4887 int multiplier = data.readInt32();
4888 int divisor = data.readInt32();
4889
4890 if ((multiplier == 0) || (divisor == 0)) {
4891 multiplier = 1;
4892 divisor = 1;
4893 }
4894
4895 if ((multiplier == 1) && (divisor == 1)) {
4896 enableHardwareVsync();
4897 } else {
4898 disableHardwareVsync(true);
4899 }
4900 getBE().mHwc->getActiveConfig(DisplayDevice::DISPLAY_PRIMARY)
4901 ->scalePanelFrequency(multiplier, divisor);
4902 mPrimaryDispSync->scalePeriod(multiplier, divisor);
4903
4904 ATRACE_INT("PeriodMultiplier", multiplier);
4905 ATRACE_INT("PeriodDivisor", divisor);
4906 return NO_ERROR;
4907 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004908 }
4909 }
4910 return err;
4911}
4912
Steven Thomas6d8110b2017-08-31 18:24:21 -07004913void SurfaceFlinger::repaintEverything() {
Dan Stozac7a25ad2018-04-12 11:45:09 -07004914 android_atomic_or(1, &mRepaintEverything);
4915 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004916}
4917
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004918// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4919class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004920public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004921 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4922 ~WindowDisconnector() {
4923 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004924 }
4925
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004926private:
4927 ANativeWindow* mWindow;
4928 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004929};
4930
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004931status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
4932 sp<GraphicBuffer>* outBuffer, Rect sourceCrop,
4933 uint32_t reqWidth, uint32_t reqHeight, int32_t minLayerZ,
4934 int32_t maxLayerZ, bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07004935 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004936 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004937
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004938 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07004939
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004940 const auto display = getDisplayDeviceLocked(displayToken);
4941 if (!display) return BAD_VALUE;
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004942
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004943 DisplayRenderArea renderArea(display, sourceCrop, reqHeight, reqWidth, rotation);
chaviwa76b2712017-09-20 12:02:26 -07004944
4945 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004946 display, minLayerZ, maxLayerZ, std::placeholders::_1);
Chavi Weingarten40482ff2017-11-30 01:51:40 +00004947 return captureScreenCommon(renderArea, traverseLayers, outBuffer, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07004948}
4949
4950status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Vishnu Nair87704c92018-01-08 15:32:57 -08004951 sp<GraphicBuffer>* outBuffer, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08004952 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004953 ATRACE_CALL();
4954
4955 class LayerRenderArea : public RenderArea {
4956 public:
Robert Carr578038f2018-03-09 12:25:24 -08004957 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
4958 int32_t reqWidth, int32_t reqHeight, bool childrenOnly)
chaviw50da5042018-04-09 13:49:37 -07004959 : RenderArea(reqHeight, reqWidth, CaptureFill::CLEAR),
Robert Carr578038f2018-03-09 12:25:24 -08004960 mLayer(layer),
4961 mCrop(crop),
4962 mFlinger(flinger),
4963 mChildrenOnly(childrenOnly) {}
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004964 const Transform& getTransform() const override { return mTransform; }
chaviwa76b2712017-09-20 12:02:26 -07004965 Rect getBounds() const override {
4966 const Layer::State& layerState(mLayer->getDrawingState());
Marissa Wall61c58622018-07-18 10:12:20 -07004967 return Rect(mLayer->getActiveWidth(layerState), mLayer->getActiveHeight(layerState));
chaviwa76b2712017-09-20 12:02:26 -07004968 }
Marissa Wall61c58622018-07-18 10:12:20 -07004969 int getHeight() const override {
4970 return mLayer->getActiveHeight(mLayer->getDrawingState());
4971 }
4972 int getWidth() const override { return mLayer->getActiveWidth(mLayer->getDrawingState()); }
chaviwa76b2712017-09-20 12:02:26 -07004973 bool isSecure() const override { return false; }
4974 bool needsFiltering() const override { return false; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004975 Rect getSourceCrop() const override {
4976 if (mCrop.isEmpty()) {
4977 return getBounds();
4978 } else {
4979 return mCrop;
4980 }
4981 }
Robert Carr578038f2018-03-09 12:25:24 -08004982 class ReparentForDrawing {
4983 public:
4984 const sp<Layer>& oldParent;
4985 const sp<Layer>& newParent;
4986
4987 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
4988 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07004989 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004990 }
Robert Carr15eae092018-03-23 13:43:53 -07004991 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004992 };
4993
4994 void render(std::function<void()> drawLayers) override {
4995 if (!mChildrenOnly) {
4996 mTransform = mLayer->getTransform().inverse();
4997 drawLayers();
4998 } else {
4999 Rect bounds = getBounds();
5000 screenshotParentLayer =
5001 new ContainerLayer(mFlinger, nullptr, String8("Screenshot Parent"),
5002 bounds.getWidth(), bounds.getHeight(), 0);
5003
5004 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5005 drawLayers();
5006 }
5007 }
chaviwa76b2712017-09-20 12:02:26 -07005008
chaviwa76b2712017-09-20 12:02:26 -07005009 private:
chaviw7206d492017-11-10 16:16:12 -08005010 const sp<Layer> mLayer;
5011 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005012
5013 // In the "childrenOnly" case we reparent the children to a screenshot
5014 // layer which has no properties set and which does not draw.
5015 sp<ContainerLayer> screenshotParentLayer;
5016 Transform mTransform;
5017
5018 SurfaceFlinger* mFlinger;
5019 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005020 };
5021
5022 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5023 auto parent = layerHandle->owner.promote();
5024
chaviw7206d492017-11-10 16:16:12 -08005025 if (parent == nullptr || parent->isPendingRemoval()) {
5026 ALOGE("captureLayers called with a removed parent");
5027 return NAME_NOT_FOUND;
5028 }
5029
Robert Carr578038f2018-03-09 12:25:24 -08005030 const int uid = IPCThreadState::self()->getCallingUid();
5031 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5032 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5033 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5034 return PERMISSION_DENIED;
5035 }
5036
chaviw7206d492017-11-10 16:16:12 -08005037 Rect crop(sourceCrop);
5038 if (sourceCrop.width() <= 0) {
5039 crop.left = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005040 crop.right = parent->getActiveWidth(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005041 }
5042
5043 if (sourceCrop.height() <= 0) {
5044 crop.top = 0;
Marissa Wall61c58622018-07-18 10:12:20 -07005045 crop.bottom = parent->getActiveHeight(parent->getCurrentState());
chaviw7206d492017-11-10 16:16:12 -08005046 }
5047
5048 int32_t reqWidth = crop.width() * frameScale;
5049 int32_t reqHeight = crop.height() * frameScale;
5050
Robert Carr578038f2018-03-09 12:25:24 -08005051 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005052
Robert Carr578038f2018-03-09 12:25:24 -08005053 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005054 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5055 if (!layer->isVisible()) {
5056 return;
Robert Carr578038f2018-03-09 12:25:24 -08005057 } else if (childrenOnly && layer == parent.get()) {
5058 return;
chaviwa76b2712017-09-20 12:02:26 -07005059 }
5060 visitor(layer);
5061 });
5062 };
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005063 return captureScreenCommon(renderArea, traverseLayers, outBuffer, false);
chaviwa76b2712017-09-20 12:02:26 -07005064}
5065
5066status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5067 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005068 sp<GraphicBuffer>* outBuffer,
chaviwa76b2712017-09-20 12:02:26 -07005069 bool useIdentityTransform) {
5070 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005071
Iris Chang7501ed62018-04-30 14:45:42 +08005072 renderArea.updateDimensions(mPrimaryDisplayOrientation);
chaviwa76b2712017-09-20 12:02:26 -07005073
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005074 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5075 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
5076 *outBuffer = new GraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5077 HAL_PIXEL_FORMAT_RGBA_8888, 1, usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005078
5079 // This mutex protects syncFd and captureResult for communication of the return values from the
5080 // main thread back to this Binder thread
5081 std::mutex captureMutex;
5082 std::condition_variable captureCondition;
5083 std::unique_lock<std::mutex> captureLock(captureMutex);
5084 int syncFd = -1;
5085 std::optional<status_t> captureResult;
5086
Robert Carr03480e22018-01-04 16:02:06 -08005087 const int uid = IPCThreadState::self()->getCallingUid();
5088 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5089
Dominik Laskowski8c001672018-05-30 16:52:06 -07005090 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005091 // If there is a refresh pending, bug out early and tell the binder thread to try again
5092 // after the refresh.
5093 if (mRefreshPending) {
5094 ATRACE_NAME("Skipping screenshot for now");
5095 std::unique_lock<std::mutex> captureLock(captureMutex);
5096 captureResult = std::make_optional<status_t>(EAGAIN);
5097 captureCondition.notify_one();
5098 return;
5099 }
5100
5101 status_t result = NO_ERROR;
5102 int fd = -1;
5103 {
5104 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005105 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005106 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5107 useIdentityTransform, forSystem, &fd);
5108 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005109 }
5110
5111 {
5112 std::unique_lock<std::mutex> captureLock(captureMutex);
5113 syncFd = fd;
5114 captureResult = std::make_optional<status_t>(result);
5115 captureCondition.notify_one();
5116 }
5117 });
5118
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005119 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005120 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005121 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005122 while (*captureResult == EAGAIN) {
5123 captureResult.reset();
5124 result = postMessageAsync(message);
5125 if (result != NO_ERROR) {
5126 return result;
5127 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005128 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005129 }
5130 result = *captureResult;
5131 }
5132
5133 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005134 sync_wait(syncFd, -1);
5135 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005136 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005137
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005138 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005139}
5140
chaviwa76b2712017-09-20 12:02:26 -07005141void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
5142 TraverseLayersFunction traverseLayers, bool yswap,
5143 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005144 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005145
Lloyd Pique144e1162017-12-20 16:44:52 -08005146 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005147
5148 // get screen geometry
chaviwa76b2712017-09-20 12:02:26 -07005149 const auto raWidth = renderArea.getWidth();
5150 const auto raHeight = renderArea.getHeight();
5151
5152 const auto reqWidth = renderArea.getReqWidth();
5153 const auto reqHeight = renderArea.getReqHeight();
5154 Rect sourceCrop = renderArea.getSourceCrop();
5155
Iris Chang7501ed62018-04-30 14:45:42 +08005156 bool filtering = false;
5157 if (mPrimaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
5158 filtering = static_cast<int32_t>(reqWidth) != raHeight ||
5159 static_cast<int32_t>(reqHeight) != raWidth;
5160 } else {
5161 filtering = static_cast<int32_t>(reqWidth) != raWidth ||
5162 static_cast<int32_t>(reqHeight) != raHeight;
5163 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005164
Dan Stozac1879002014-05-22 15:59:05 -07005165 // if a default or invalid sourceCrop is passed in, set reasonable values
chaviwa76b2712017-09-20 12:02:26 -07005166 if (sourceCrop.width() == 0 || sourceCrop.height() == 0 || !sourceCrop.isValid()) {
Dan Stozac1879002014-05-22 15:59:05 -07005167 sourceCrop.setLeftTop(Point(0, 0));
chaviwa76b2712017-09-20 12:02:26 -07005168 sourceCrop.setRightBottom(Point(raWidth, raHeight));
Iris Chang7501ed62018-04-30 14:45:42 +08005169 } else if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5170 Transform tr;
5171 uint32_t flags = 0x00;
5172 switch (mPrimaryDisplayOrientation) {
5173 case DisplayState::eOrientation90:
5174 flags = Transform::ROT_90;
5175 break;
5176 case DisplayState::eOrientation180:
5177 flags = Transform::ROT_180;
5178 break;
5179 case DisplayState::eOrientation270:
5180 flags = Transform::ROT_270;
5181 break;
5182 }
5183 tr.set(flags, raWidth, raHeight);
5184 sourceCrop = tr.transform(sourceCrop);
Dan Stozac1879002014-05-22 15:59:05 -07005185 }
5186
5187 // ensure that sourceCrop is inside screen
5188 if (sourceCrop.left < 0) {
5189 ALOGE("Invalid crop rect: l = %d (< 0)", sourceCrop.left);
5190 }
chaviwa76b2712017-09-20 12:02:26 -07005191 if (sourceCrop.right > raWidth) {
5192 ALOGE("Invalid crop rect: r = %d (> %d)", sourceCrop.right, raWidth);
Dan Stozac1879002014-05-22 15:59:05 -07005193 }
5194 if (sourceCrop.top < 0) {
5195 ALOGE("Invalid crop rect: t = %d (< 0)", sourceCrop.top);
5196 }
chaviwa76b2712017-09-20 12:02:26 -07005197 if (sourceCrop.bottom > raHeight) {
5198 ALOGE("Invalid crop rect: b = %d (> %d)", sourceCrop.bottom, raHeight);
Dan Stozac1879002014-05-22 15:59:05 -07005199 }
5200
Chia-I Wu36574d92018-05-16 10:54:36 -07005201 // assume ColorMode::SRGB / RenderIntent::COLORIMETRIC
5202 engine.setOutputDataSpace(Dataspace::SRGB);
5203 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005204
Mathias Agopian180f10d2013-04-10 22:55:41 -07005205 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005206 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005207
Iris Chang7501ed62018-04-30 14:45:42 +08005208 Transform::orientation_flags rotation = renderArea.getRotationFlags();
5209 if (mPrimaryDisplayOrientation != DisplayState::eOrientationDefault) {
5210 // convert hw orientation into flag presentation
5211 // here inverse transform needed
5212 uint8_t hw_rot_90 = 0x00;
5213 uint8_t hw_flip_hv = 0x00;
5214 switch (mPrimaryDisplayOrientation) {
5215 case DisplayState::eOrientation90:
5216 hw_rot_90 = Transform::ROT_90;
5217 hw_flip_hv = Transform::ROT_180;
5218 break;
5219 case DisplayState::eOrientation180:
5220 hw_flip_hv = Transform::ROT_180;
5221 break;
5222 case DisplayState::eOrientation270:
5223 hw_rot_90 = Transform::ROT_90;
5224 break;
5225 }
5226
5227 // transform flags operation
5228 // 1) flip H V if both have ROT_90 flag
5229 // 2) XOR these flags
5230 uint8_t rotation_rot_90 = rotation & Transform::ROT_90;
5231 uint8_t rotation_flip_hv = rotation & Transform::ROT_180;
5232 if (rotation_rot_90 & hw_rot_90) {
5233 rotation_flip_hv = (~rotation_flip_hv) & Transform::ROT_180;
5234 }
5235 rotation = static_cast<Transform::orientation_flags>
5236 ((rotation_rot_90 ^ hw_rot_90) | (rotation_flip_hv ^ hw_flip_hv));
5237 }
5238
Mathias Agopian180f10d2013-04-10 22:55:41 -07005239 // set-up our viewport
chaviwa76b2712017-09-20 12:02:26 -07005240 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, raHeight, yswap,
Iris Chang7501ed62018-04-30 14:45:42 +08005241 rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005242 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005243
chaviw50da5042018-04-09 13:49:37 -07005244 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005245 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005246 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005247
chaviwa76b2712017-09-20 12:02:26 -07005248 traverseLayers([&](Layer* layer) {
5249 if (filtering) layer->setFiltering(true);
David Sodmanca10ed22018-04-16 14:10:25 -07005250 layer->drawNow(renderArea, useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005251 if (filtering) layer->setFiltering(false);
5252 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005253}
5254
chaviwa76b2712017-09-20 12:02:26 -07005255status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5256 TraverseLayersFunction traverseLayers,
5257 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005258 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005259 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005260 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005261 ATRACE_CALL();
5262
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005263 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005264
5265 traverseLayers([&](Layer* layer) {
5266 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5267 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005268
Robert Carr03480e22018-01-04 16:02:06 -08005269 // We allow the system server to take screenshots of secure layers for
5270 // use in situations like the Screen-rotation animation and place
5271 // the impetus on WindowManager to not persist them.
5272 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005273 ALOGW("FB is protected: PERMISSION_DENIED");
5274 return PERMISSION_DENIED;
5275 }
5276
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005277 // this binds the given EGLImage as a framebuffer for the
5278 // duration of this scope.
Lloyd Pique144e1162017-12-20 16:44:52 -08005279 RE::BindNativeBufferAsFramebuffer bufferBond(getRenderEngine(), buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005280 if (bufferBond.getStatus() != NO_ERROR) {
5281 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005282 return INVALID_OPERATION;
5283 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005284
Dan Stozaabcda352017-06-01 14:37:39 -07005285 // this will in fact render into our dequeued buffer
5286 // via an FBO, which means we didn't have to create
5287 // an EGLSurface and therefore we're not
5288 // dependent on the context's EGLConfig.
chaviwa76b2712017-09-20 12:02:26 -07005289 renderScreenImplLocked(renderArea, traverseLayers, true, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005290
Dan Stozaabcda352017-06-01 14:37:39 -07005291 if (DEBUG_SCREENSHOTS) {
Chia-I Wu767fcf72017-11-30 22:07:38 -08005292 getRenderEngine().finish();
5293 *outSyncFd = -1;
5294
chaviwa76b2712017-09-20 12:02:26 -07005295 const auto reqWidth = renderArea.getReqWidth();
5296 const auto reqHeight = renderArea.getReqHeight();
5297
Dan Stozaabcda352017-06-01 14:37:39 -07005298 uint32_t* pixels = new uint32_t[reqWidth*reqHeight];
5299 getRenderEngine().readPixels(0, 0, reqWidth, reqHeight, pixels);
chaviwa76b2712017-09-20 12:02:26 -07005300 checkScreenshot(reqWidth, reqHeight, reqWidth, pixels, traverseLayers);
Dan Stozaabcda352017-06-01 14:37:39 -07005301 delete [] pixels;
Chia-I Wu767fcf72017-11-30 22:07:38 -08005302 } else {
5303 base::unique_fd syncFd = getRenderEngine().flush();
5304 if (syncFd < 0) {
5305 getRenderEngine().finish();
5306 }
5307 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005308 }
5309
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005310 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005311}
5312
Mathias Agopiand5556842013-09-19 17:08:37 -07005313void SurfaceFlinger::checkScreenshot(size_t w, size_t s, size_t h, void const* vaddr,
chaviwa76b2712017-09-20 12:02:26 -07005314 TraverseLayersFunction traverseLayers) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005315 if (DEBUG_SCREENSHOTS) {
chaviwa76b2712017-09-20 12:02:26 -07005316 for (size_t y = 0; y < h; y++) {
5317 uint32_t const* p = (uint32_t const*)vaddr + y * s;
5318 for (size_t x = 0; x < w; x++) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005319 if (p[x] != 0xFF000000) return;
5320 }
5321 }
chaviwa76b2712017-09-20 12:02:26 -07005322 ALOGE("*** we just took a black screenshot ***");
Robert Carr1f0a16a2016-10-24 16:27:39 -07005323
Robert Carr2047fae2016-11-28 14:09:09 -08005324 size_t i = 0;
chaviwa76b2712017-09-20 12:02:26 -07005325 traverseLayers([&](Layer* layer) {
Mathias Agopianfee2b462013-07-03 12:34:01 -07005326 const Layer::State& state(layer->getDrawingState());
chaviwa76b2712017-09-20 12:02:26 -07005327 ALOGE("%c index=%zu, name=%s, layerStack=%d, z=%d, visible=%d, flags=%x, alpha=%.3f",
5328 layer->isVisible() ? '+' : '-', i, layer->getName().string(),
5329 layer->getLayerStack(), state.z, layer->isVisible(), state.flags,
5330 static_cast<float>(state.color.a));
5331 i++;
5332 });
Mathias Agopianfee2b462013-07-03 12:34:01 -07005333 }
5334}
5335
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005336// ---------------------------------------------------------------------------
5337
Dan Stoza412903f2017-04-27 13:42:17 -07005338void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5339 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005340}
5341
Dan Stoza412903f2017-04-27 13:42:17 -07005342void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5343 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005344}
5345
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005346void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
5347 int32_t minLayerZ, int32_t maxLayerZ,
chaviwa76b2712017-09-20 12:02:26 -07005348 const LayerVector::Visitor& visitor) {
5349 // We loop through the first level of layers without traversing,
5350 // as we need to interpret min/max layer Z in the top level Z space.
5351 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005352 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005353 continue;
5354 }
5355 const Layer::State& state(layer->getDrawingState());
Chia-I Wuec2d9852017-11-21 09:21:01 -08005356 // relative layers are traversed in Layer::traverseInZOrder
5357 if (state.zOrderRelativeOf != nullptr || state.z < minLayerZ || state.z > maxLayerZ) {
chaviwa76b2712017-09-20 12:02:26 -07005358 continue;
5359 }
5360 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005361 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005362 return;
5363 }
chaviwa76b2712017-09-20 12:02:26 -07005364 if (!layer->isVisible()) {
5365 return;
5366 }
5367 visitor(layer);
5368 });
5369 }
5370}
5371
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005372}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005373
Lloyd Pique074e8122018-07-26 12:57:23 -07005374
Mathias Agopian3f844832013-08-07 21:24:32 -07005375#if defined(__gl_h_)
5376#error "don't include gl/gl.h in this file"
5377#endif
5378
5379#if defined(__gl2_h_)
5380#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005381#endif