blob: 7c05db7c8e6be3b8bc30a4fa0e6bae6f20114358 [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
Lloyd Pique70d91362018-10-18 16:02:55 -070038#include <compositionengine/CompositionEngine.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080039#include <dvr/vr_flinger.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070040#include <gui/BufferQueue.h>
Andy McFadden4803b742012-09-24 19:07:20 -070041#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070042#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080043#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080044#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080045#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070046#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070047#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070048#include <ui/ColorSpace.h>
49#include <ui/DebugUtils.h>
50#include <ui/DisplayInfo.h>
51#include <ui/DisplayStatInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070052#include <ui/GraphicBufferAllocator.h>
53#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070054#include <ui/UiConfig.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080055#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070056#include <utils/String16.h>
57#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070058#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080059#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070060#include <utils/misc.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"
Robert Carr578038f2018-03-09 12:25:24 -080073#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070075#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080076#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070077#include "NativeWindowSurface.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070078#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080079#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070080#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080081
Steven Thomasb02664d2017-07-26 18:48:28 -070082#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070083#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070084#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070085#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070086#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070087#include "Effects/Daltonizer.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070088#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -070089#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070090#include "Scheduler/EventControlThread.h"
91#include "Scheduler/EventThread.h"
Ana Krulec47454452018-08-14 11:04:14 -070092#include "Scheduler/InjectVSyncSource.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070093#include "Scheduler/MessageQueue.h"
Ana Krulec98b5b242018-08-10 15:03:23 -070094#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -080095#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -070096
Mathias Agopianff2ed702013-09-01 21:36:12 -070097#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -070098
David Sodman7e4ae112018-02-09 15:02:28 -080099#include "android-base/stringprintf.h"
100
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900101#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800102#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
Peiyong Lin13effd12018-07-24 17:01:47 -0700103#include <android/hardware/configstore/1.2/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800104#include <android/hardware/configstore/1.1/types.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900105#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900106
chaviw1d044282017-09-27 12:19:28 -0700107#include <layerproto/LayerProtoParser.h>
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;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800113using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700114using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700115using ui::Dataspace;
Peiyong Lin62665892018-04-16 11:07:44 -0700116using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700117using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900118
Steven Thomasb02664d2017-07-26 18:48:28 -0700119namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700120
121#pragma clang diagnostic push
122#pragma clang diagnostic error "-Wswitch-enum"
123
124bool isWideColorMode(const ColorMode colorMode) {
125 switch (colorMode) {
126 case ColorMode::DISPLAY_P3:
127 case ColorMode::ADOBE_RGB:
128 case ColorMode::DCI_P3:
129 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700130 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700131 case ColorMode::BT2100_PQ:
132 case ColorMode::BT2100_HLG:
133 return true;
134 case ColorMode::NATIVE:
135 case ColorMode::STANDARD_BT601_625:
136 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
137 case ColorMode::STANDARD_BT601_525:
138 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
139 case ColorMode::STANDARD_BT709:
140 case ColorMode::SRGB:
141 return false;
142 }
143 return false;
144}
145
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700146ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
147 switch (rotation) {
148 case ISurfaceComposer::eRotateNone:
149 return ui::Transform::ROT_0;
150 case ISurfaceComposer::eRotate90:
151 return ui::Transform::ROT_90;
152 case ISurfaceComposer::eRotate180:
153 return ui::Transform::ROT_180;
154 case ISurfaceComposer::eRotate270:
155 return ui::Transform::ROT_270;
156 }
157 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
158 return ui::Transform::ROT_0;
159}
160
Peiyong Linfca547f2018-07-09 13:03:33 -0700161#pragma clang diagnostic pop
162
Steven Thomasb02664d2017-07-26 18:48:28 -0700163class ConditionalLock {
164public:
165 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
166 if (lock) {
167 mMutex.lock();
168 }
169 }
170 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
171private:
172 Mutex& mMutex;
173 bool mLocked;
174};
Peiyong Linfca547f2018-07-09 13:03:33 -0700175
Peiyong Lin9d846a52018-11-05 13:18:20 -0800176// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
177bool validateCompositionDataspace(Dataspace dataspace) {
178 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
179}
180
Steven Thomasb02664d2017-07-26 18:48:28 -0700181} // namespace anonymous
182
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800183// ---------------------------------------------------------------------------
184
Mathias Agopian99b49842011-06-27 16:05:52 -0700185const String16 sHardwareTest("android.permission.HARDWARE_TEST");
186const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
187const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
188const String16 sDump("android.permission.DUMP");
189
190// ---------------------------------------------------------------------------
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800191int64_t SurfaceFlinger::vsyncPhaseOffsetNs;
192int64_t SurfaceFlinger::sfVsyncPhaseOffsetNs;
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700193int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700194bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800195uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800196bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800197bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800198int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600199bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700200int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700201bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700202bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700203Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
204ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
205Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
206ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700207
Kalle Raitaa099a242017-01-11 11:17:29 -0800208std::string getHwcServiceName() {
209 char value[PROPERTY_VALUE_MAX] = {};
210 property_get("debug.sf.hwc_service_name", value, "default");
211 ALOGI("Using HWComposer service: '%s'", value);
212 return std::string(value);
213}
214
215bool useTrebleTestingOverride() {
216 char value[PROPERTY_VALUE_MAX] = {};
217 property_get("debug.sf.treble_testing_override", value, "false");
218 ALOGI("Treble testing override: '%s'", value);
219 return std::string(value) == "true";
220}
221
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800222std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
223 switch(displayColorSetting) {
224 case DisplayColorSetting::MANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700225 return std::string("Managed");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800226 case DisplayColorSetting::UNMANAGED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700227 return std::string("Unmanaged");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800228 case DisplayColorSetting::ENHANCED:
Chia-I Wu0d711262018-05-21 15:19:35 -0700229 return std::string("Enhanced");
230 default:
231 return std::string("Unknown ") +
232 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800233 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800234}
235
David Sodmanbc815282017-11-05 18:57:52 -0800236SurfaceFlingerBE::SurfaceFlingerBE()
237 : mHwcServiceName(getHwcServiceName()),
238 mRenderEngine(nullptr),
David Sodman4a36e932017-11-07 14:29:47 -0800239 mFrameBuckets(),
240 mTotalTime(0),
241 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800242 mComposerSequenceId(0) {
243}
244
Lloyd Pique90c115d2018-09-18 21:39:42 -0700245SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory,
246 SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800247 : BnSurfaceComposer(),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700248 mFactory(factory),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700249 mTransactionPending(false),
250 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700251 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700252 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800253 mBootTime(systemTime()),
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 mDebugInTransaction(0),
263 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700264 mForceFullDamage(false),
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800265 mTimeStats(factory.createTimeStats()),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700266 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700267 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800268 mRefreshStartTime(0),
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 Pique70d91362018-10-18 16:02:55 -0700272 mMainThreadId(std::this_thread::get_id()),
273 mCompositionEngine{getFactory().createCompositionEngine()} {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800274
Lloyd Pique90c115d2018-09-18 21:39:42 -0700275SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory)
276 : SurfaceFlinger(factory, 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);
Peiyong Lin13effd12018-07-24 17:01:47 -0700306 useColorManagement =
Peiyong Lin0256f722018-08-31 15:45:10 -0700307 getBool<V1_2::ISurfaceFlingerConfigs,
308 &V1_2::ISurfaceFlingerConfigs::useColorManagement>(false);
309
310 auto surfaceFlingerConfigsServiceV1_2 = V1_2::ISurfaceFlingerConfigs::getService();
311 if (surfaceFlingerConfigsServiceV1_2) {
312 surfaceFlingerConfigsServiceV1_2->getCompositionPreference(
Peiyong Linc6780972018-10-28 15:24:08 -0700313 [&](auto tmpDefaultDataspace, auto tmpDefaultPixelFormat,
314 auto tmpWideColorGamutDataspace, auto tmpWideColorGamutPixelFormat) {
315 defaultCompositionDataspace = tmpDefaultDataspace;
316 defaultCompositionPixelFormat = tmpDefaultPixelFormat;
317 wideColorGamutCompositionDataspace = tmpWideColorGamutDataspace;
318 wideColorGamutCompositionPixelFormat = tmpWideColorGamutPixelFormat;
319 });
Peiyong Lin0256f722018-08-31 15:45:10 -0700320 }
Peiyong Lin9d846a52018-11-05 13:18:20 -0800321 mDefaultCompositionDataspace = defaultCompositionDataspace;
322 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600323
Peiyong Linb3839ad2018-09-05 15:37:19 -0700324 useContextPriority = getBool<ISurfaceFlingerConfigs,
325 &ISurfaceFlingerConfigs::useContextPriority>(true);
326
Iris Chang7501ed62018-04-30 14:45:42 +0800327 V1_1::DisplayOrientation primaryDisplayOrientation =
Peiyong Lin0256f722018-08-31 15:45:10 -0700328 getDisplayOrientation<V1_1::ISurfaceFlingerConfigs,
329 &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
Iris Chang7501ed62018-04-30 14:45:42 +0800330 V1_1::DisplayOrientation::ORIENTATION_0);
331
332 switch (primaryDisplayOrientation) {
333 case V1_1::DisplayOrientation::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700334 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800335 break;
336 case V1_1::DisplayOrientation::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700337 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800338 break;
339 case V1_1::DisplayOrientation::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700340 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800341 break;
342 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700343 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800344 break;
345 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700346 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800347
Lloyd Pique90c115d2018-09-18 21:39:42 -0700348 mPrimaryDispSync =
349 getFactory().createDispSync("PrimaryDispSync", SurfaceFlinger::hasSyncFramework,
350 SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700351
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800352 // debugging stuff...
353 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700354
Mathias Agopianb4b17302013-03-20 18:36:41 -0700355 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700356 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700357
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800358 property_get("debug.sf.showupdates", value, "0");
359 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700360
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700361 property_get("debug.sf.ddms", value, "0");
362 mDebugDDMS = atoi(value);
363 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700364 if (!startDdmConnection()) {
365 // start failed, and DDMS debugging not enabled
366 mDebugDDMS = 0;
367 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700368 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700369 ALOGI_IF(mDebugRegion, "showupdates enabled");
370 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700371
372 property_get("debug.sf.disable_backpressure", value, "0");
373 mPropagateBackpressure = !atoi(value);
374 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700375
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800376 property_get("debug.sf.enable_hwc_vds", value, "0");
377 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800378 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800379
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800380 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800381 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800382 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700383
Yiwei Zhang243b3782018-05-15 17:40:04 -0700384 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700385 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
386 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
387
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200388 property_get("debug.sf.early_phase_offset_ns", value, "-1");
389 const int earlySfOffsetNs = atoi(value);
390
391 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
392 const int earlyGlSfOffsetNs = atoi(value);
393
394 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
395 const int earlyAppOffsetNs = atoi(value);
396
397 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
398 const int earlyGlAppOffsetNs = atoi(value);
399
Ana Krulec98b5b242018-08-10 15:03:23 -0700400 property_get("debug.sf.use_scheduler", value, "0");
401 mUseScheduler = atoi(value);
402
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200403 const VSyncModulator::Offsets earlyOffsets =
404 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
405 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
406 const VSyncModulator::Offsets earlyGlOffsets =
407 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
408 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
409 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
410 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700411
Romain Guy11d63f42017-07-20 12:47:14 -0700412 // We should be reading 'persist.sys.sf.color_saturation' here
413 // but since /data may be encrypted, we need to wait until after vold
414 // comes online to attempt to read the property. The property is
415 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800416
417 if (useTrebleTestingOverride()) {
418 // Without the override SurfaceFlinger cannot connect to HIDL
419 // services that are not listed in the manifests. Considered
420 // deriving the setting from the set service name, but it
421 // would be brittle if the name that's not 'default' is used
422 // for production purposes later on.
423 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
424 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800425}
426
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800427void SurfaceFlinger::onFirstRef()
428{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800429 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800430}
431
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800432SurfaceFlinger::~SurfaceFlinger()
433{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800434}
435
Dan Stozac7014012014-02-14 15:03:43 -0800436void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800437{
438 // the window manager died on us. prepare its eulogy.
439
Andy McFadden13a082e2012-08-24 10:16:42 -0700440 // restore initial conditions (default device unblank, etc)
441 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800442
443 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700444 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800445}
446
Robert Carr1db73f62016-12-21 12:58:51 -0800447static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700448 status_t err = client->initCheck();
449 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800450 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800451 }
Robert Carr1db73f62016-12-21 12:58:51 -0800452 return nullptr;
453}
454
455sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
456 return initClient(new Client(this));
457}
458
459sp<ISurfaceComposerClient> SurfaceFlinger::createScopedConnection(
460 const sp<IGraphicBufferProducer>& gbp) {
461 if (authenticateSurfaceTexture(gbp) == false) {
462 return nullptr;
463 }
464 const auto& layer = (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
465 if (layer == nullptr) {
466 return nullptr;
467 }
468
469 return initClient(new Client(this, layer));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800470}
471
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700472sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
473 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700474{
475 class DisplayToken : public BBinder {
476 sp<SurfaceFlinger> flinger;
477 virtual ~DisplayToken() {
478 // no more references, this display must be terminated
479 Mutex::Autolock _l(flinger->mStateLock);
480 flinger->mCurrentState.displays.removeItem(this);
481 flinger->setTransactionFlags(eDisplayTransactionNeeded);
482 }
483 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700484 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700485 : flinger(flinger) {
486 }
487 };
488
489 sp<BBinder> token = new DisplayToken(this);
490
491 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700492 // Display ID is assigned when virtual display is allocated by HWC.
493 DisplayDeviceState state;
494 state.isSecure = secure;
495 state.displayName = displayName;
496 mCurrentState.displays.add(token, state);
497 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700498 return token;
499}
500
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700501void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700502 Mutex::Autolock _l(mStateLock);
503
Dominik Laskowski075d3172018-05-24 15:50:06 -0700504 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
505 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700506 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700507 return;
508 }
509
Dominik Laskowski075d3172018-05-24 15:50:06 -0700510 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
511 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700512 ALOGE("destroyDisplay called for non-virtual display");
513 return;
514 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700515 mInterceptor->saveDisplayDeletion(state.sequenceId);
516 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700517 setTransactionFlags(eDisplayTransactionNeeded);
518}
519
Mathias Agopiane57f2922012-08-09 16:29:12 -0700520sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700521 std::optional<DisplayId> displayId;
522
523 if (id == HWC_DISPLAY_PRIMARY) {
524 displayId = getInternalDisplayId();
525 } else if (id == HWC_DISPLAY_EXTERNAL) {
526 displayId = getExternalDisplayId();
527 }
528
529 if (!displayId) {
530 ALOGE("%s: Invalid display %d", __FUNCTION__, id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800531 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700532 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700533
534 return getPhysicalDisplayToken(*displayId);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700535}
536
Ady Abraham37965d42018-11-01 13:43:32 -0700537status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
538 if (!outGetColorManagement) {
539 return BAD_VALUE;
540 }
541 *outGetColorManagement = useColorManagement;
542 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700543}
544
Lloyd Pique441d5042018-10-18 16:49:51 -0700545HWComposer& SurfaceFlinger::getHwComposer() const {
546 return mCompositionEngine->getHwComposer();
547}
548
Lloyd Pique70d91362018-10-18 16:02:55 -0700549compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
550 return *mCompositionEngine.get();
551}
552
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800553void SurfaceFlinger::bootFinished()
554{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700555 if (mStartPropertySetThread->join() != NO_ERROR) {
556 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800557 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800558 const nsecs_t now = systemTime();
559 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000560 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700561
562 // wait patiently for the window manager death
563 const String16 name("window");
564 sp<IBinder> window(defaultServiceManager()->getService(name));
565 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700566 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700567 }
Robert Carr720e5062018-07-30 17:45:14 -0700568 sp<IBinder> input(defaultServiceManager()->getService(
569 String16("inputflinger")));
570 if (input == nullptr) {
571 ALOGE("Failed to link to input service");
572 } else {
573 mInputFlinger = interface_cast<IInputFlinger>(input);
574 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700575
Steven Thomas050b2c82017-03-06 11:45:16 -0800576 if (mVrFlinger) {
577 mVrFlinger->OnBootFinished();
578 }
579
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700580 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700581 // formerly we would just kill the process, but we now ask it to exit so it
582 // can choose where to stop the animation.
583 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700584
585 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
586 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
587 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700588
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800589 postMessageAsync(new LambdaMessage([this] {
590 readPersistentProperties();
591 mBootStage = BootStage::FINISHED;
592 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800593}
594
Dan Stoza436ccf32018-06-21 12:10:12 -0700595uint32_t SurfaceFlinger::getNewTexture() {
596 {
597 std::lock_guard lock(mTexturePoolMutex);
598 if (!mTexturePool.empty()) {
599 uint32_t name = mTexturePool.back();
600 mTexturePool.pop_back();
601 ATRACE_INT("TexturePoolSize", mTexturePool.size());
602 return name;
603 }
604
605 // The pool was too small, so increase it for the future
606 ++mTexturePoolSize;
607 }
608
609 // The pool was empty, so we need to get a new texture name directly using a
610 // blocking call to the main thread
611 uint32_t name = 0;
612 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
613 return name;
614}
615
Mathias Agopian3f844832013-08-07 21:24:32 -0700616void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700617 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700618}
619
Wei Wangf9b05ee2017-07-19 20:59:39 -0700620// Do not call property_set on main thread which will be blocked by init
621// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700622void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700623 ALOGI( "SurfaceFlinger's main thread ready to run. "
624 "Initializing graphics H/W...");
625
Thierry Strudel2924d012017-08-14 15:19:37 -0700626 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900627
Steven Thomasb02664d2017-07-26 18:48:28 -0700628 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800629
Steven Thomasb02664d2017-07-26 18:48:28 -0700630 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700631 if (mUseScheduler) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700632 mScheduler = getFactory().createScheduler([this](bool enabled) {
633 setVsyncEnabled(EventThread::DisplayType::Primary, enabled);
634 });
635
Ana Krulec98b5b242018-08-10 15:03:23 -0700636 mAppConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700637 mScheduler->createConnection("appConnection", SurfaceFlinger::vsyncPhaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700638 [this] { resyncWithRateLimit(); },
639 impl::EventThread::InterceptVSyncsCallback());
640 mSfConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700641 mScheduler->createConnection("sfConnection", SurfaceFlinger::sfVsyncPhaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700642 [this] { resyncWithRateLimit(); },
643 [this](nsecs_t timestamp) {
644 mInterceptor->saveVSyncEvent(timestamp);
645 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800646
Ana Krulec98b5b242018-08-10 15:03:23 -0700647 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700648 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
649 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700650 } else {
651 mEventThreadSource =
652 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
653 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
654 mEventThread =
655 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
656 [this] { resyncWithRateLimit(); },
657 impl::EventThread::InterceptVSyncsCallback(),
658 "appEventThread");
659 mSfEventThreadSource =
660 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
661 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
662
663 mSFEventThread =
664 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
665 [this] { resyncWithRateLimit(); },
666 [this](nsecs_t timestamp) {
667 mInterceptor->saveVSyncEvent(timestamp);
668 },
669 "sfEventThread");
670 mEventQueue->setEventThread(mSFEventThread.get());
671 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
672 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800673
Steven Thomasb02664d2017-07-26 18:48:28 -0700674 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700675 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700676 renderEngineFeature |= (useColorManagement ?
677 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700678 renderEngineFeature |= (useContextPriority ?
679 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700680
681 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
682 getBE().mRenderEngine =
Peiyong Linc6780972018-10-28 15:24:08 -0700683 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
684 renderEngineFeature);
David Sodmanbc815282017-11-05 18:57:52 -0800685 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700686
687 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
688 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700689 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
690 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800691 // Process any initial hotplug and resulting display changes.
692 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700693 const auto display = getDefaultDisplayDeviceLocked();
694 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700695 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700696 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800697
Steven Thomas050b2c82017-03-06 11:45:16 -0800698 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700699 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700700 // This callback is called from the vr flinger dispatch thread. We
701 // need to call signalTransaction(), which requires holding
702 // mStateLock when we're not on the main thread. Acquiring
703 // mStateLock from the vr flinger dispatch thread might trigger a
704 // deadlock in surface flinger (see b/66916578), so post a message
705 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700706 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700707 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
708 mVrFlingerRequestsDisplay = requestDisplay;
709 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700710 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800711 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700712 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
713 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700714 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700715 .value_or(0),
716 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800717 if (!mVrFlinger) {
718 ALOGE("Failed to start vrflinger");
719 }
720 }
721
Lloyd Pique90c115d2018-09-18 21:39:42 -0700722 mEventControlThread = getFactory().createEventControlThread(
Dominik Laskowski075d3172018-05-24 15:50:06 -0700723 [this](bool enabled) { setVsyncEnabled(EventThread::DisplayType::Primary, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700724
Mathias Agopian92a979a2012-08-02 18:32:23 -0700725 // initialize our drawing state
726 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700727
Andy McFadden13a082e2012-08-24 10:16:42 -0700728 // set initial conditions (e.g. unblank default device)
729 initializeDisplays();
730
David Sodmanbc815282017-11-05 18:57:52 -0800731 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700732
Wei Wangf9b05ee2017-07-19 20:59:39 -0700733 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700734
735 const bool presentFenceReliable =
736 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
737 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700738
739 if (mStartPropertySetThread->Start() != NO_ERROR) {
740 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800741 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800742
Dan Stoza9e56aa02015-11-02 13:00:03 -0800743 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700744}
745
Romain Guy11d63f42017-07-20 12:47:14 -0700746void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700747 Mutex::Autolock _l(mStateLock);
748
Romain Guy11d63f42017-07-20 12:47:14 -0700749 char value[PROPERTY_VALUE_MAX];
750
751 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800752 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700753 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800754 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100755
756 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700757 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700758}
759
Mathias Agopiana67e4182012-06-19 17:26:12 -0700760void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800761 // Start boot animation service by setting a property mailbox
762 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700763 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800764 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700765 if (mStartPropertySetThread->join() != NO_ERROR) {
766 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800767 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700768}
769
Mathias Agopian875d8e12013-06-07 15:35:48 -0700770size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800771 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700772}
773
Mathias Agopian875d8e12013-06-07 15:35:48 -0700774size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800775 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700776}
777
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800778// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800779
Jamie Gennis582270d2011-08-17 18:19:00 -0700780bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800781 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800782 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800783 return authenticateSurfaceTextureLocked(bufferProducer);
784}
785
786bool SurfaceFlinger::authenticateSurfaceTextureLocked(
787 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800788 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800789 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800790}
791
Brian Anderson6b376712017-04-04 10:51:39 -0700792status_t SurfaceFlinger::getSupportedFrameTimestamps(
793 std::vector<FrameEvent>* outSupported) const {
794 *outSupported = {
795 FrameEvent::REQUESTED_PRESENT,
796 FrameEvent::ACQUIRE,
797 FrameEvent::LATCH,
798 FrameEvent::FIRST_REFRESH_START,
799 FrameEvent::LAST_REFRESH_START,
800 FrameEvent::GPU_COMPOSITION_DONE,
801 FrameEvent::DEQUEUE_READY,
802 FrameEvent::RELEASE,
803 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700804 ConditionalLock _l(mStateLock,
805 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700806 if (!getHwComposer().hasCapability(
807 HWC2::Capability::PresentFenceIsNotReliable)) {
808 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
809 }
810 return NO_ERROR;
811}
812
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700813status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
814 Vector<DisplayInfo>* configs) {
815 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700816 return BAD_VALUE;
817 }
818
Dominik Laskowski075d3172018-05-24 15:50:06 -0700819 const auto displayId = getPhysicalDisplayId(displayToken);
820 if (!displayId) {
821 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700822 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700823
Mathias Agopian8b736f12012-08-13 17:54:26 -0700824 // TODO: Not sure if display density should handled by SF any longer
825 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700826 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700827 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700828 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800829 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700830 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700831 }
832 return density;
833 }
834 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700835 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700836 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700837 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700838 return getDensityFromProperty("ro.sf.lcd_density"); }
839 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700840
Dan Stoza7f7da322014-05-02 15:26:25 -0700841 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700842
Steven Thomas6d8110b2017-08-31 18:24:21 -0700843 ConditionalLock _l(mStateLock,
844 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700845 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700846 DisplayInfo info = DisplayInfo();
847
Dan Stoza9e56aa02015-11-02 13:00:03 -0800848 float xdpi = hwConfig->getDpiX();
849 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700850
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700851 info.w = hwConfig->getWidth();
852 info.h = hwConfig->getHeight();
853 // Default display viewport to display width and height
854 info.viewportW = info.w;
855 info.viewportH = info.h;
856
Dominik Laskowski075d3172018-05-24 15:50:06 -0700857 if (displayId == getInternalDisplayId()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700858 // The density of the device is provided by a build property
859 float density = Density::getBuildDensity() / 160.0f;
860 if (density == 0) {
861 // the build doesn't provide a density -- this is wrong!
862 // use xdpi instead
863 ALOGE("ro.sf.lcd_density must be defined as a build property");
864 density = xdpi / 160.0f;
865 }
866 if (Density::getEmuDensity()) {
867 // if "qemu.sf.lcd_density" is specified, it overrides everything
868 xdpi = ydpi = density = Density::getEmuDensity();
869 density /= 160.0f;
870 }
871 info.density = density;
872
873 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700874 const auto display = getDefaultDisplayDeviceLocked();
875 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700876
877 // This is for screenrecord
878 const Rect viewport = display->getViewport();
879 if (viewport.isValid()) {
880 info.viewportW = uint32_t(viewport.getWidth());
881 info.viewportH = uint32_t(viewport.getHeight());
882 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700883 } else {
884 // TODO: where should this value come from?
885 static const int TV_DENSITY = 213;
886 info.density = TV_DENSITY / 160.0f;
887 info.orientation = 0;
888 }
889
Dan Stoza7f7da322014-05-02 15:26:25 -0700890 info.xdpi = xdpi;
891 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800892 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900893 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800894
Andy McFadden91b2ca82014-06-13 14:04:23 -0700895 // This is how far in advance a buffer must be queued for
896 // presentation at a given time. If you want a buffer to appear
897 // on the screen at time N, you must submit the buffer before
898 // (N - presentationDeadline).
899 //
900 // Normally it's one full refresh period (to give SF a chance to
901 // latch the buffer), but this can be reduced by configuring a
902 // DispSync offset. Any additional delays introduced by the hardware
903 // composer or panel must be accounted for here.
904 //
905 // We add an additional 1ms to allow for processing time and
906 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800907 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800908 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700909
910 // All non-virtual displays are currently considered secure.
911 info.secure = true;
912
Dominik Laskowski075d3172018-05-24 15:50:06 -0700913 if (displayId == getInternalDisplayId() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700914 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800915 std::swap(info.w, info.h);
916 }
917
Michael Wright28f24d02016-07-12 13:30:53 -0700918 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700919 }
920
Dan Stoza7f7da322014-05-02 15:26:25 -0700921 return NO_ERROR;
922}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700923
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700924status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
925 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700926 return BAD_VALUE;
927 }
928
Ana Krulece588e312018-09-18 12:32:24 -0700929 if (mUseScheduler) {
930 mScheduler->getDisplayStatInfo(stats);
931 } else {
932 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
933 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
934 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700935 return NO_ERROR;
936}
937
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700938int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
939 const auto display = getDisplayDevice(displayToken);
940 if (!display) {
941 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800942 return BAD_VALUE;
943 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700944
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700945 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700946}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700947
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700948void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700949 if (display->isVirtual()) {
950 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
951 return;
952 }
953
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700954 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700955 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700956 return;
957 }
958
Dominik Laskowski075d3172018-05-24 15:50:06 -0700959 const auto displayId = display->getId();
960 LOG_ALWAYS_FATAL_IF(!displayId);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700961
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700962 display->setActiveConfig(mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700963 getHwComposer().setActiveConfig(*displayId, mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700964}
965
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700966status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700967 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700968 Vector<DisplayInfo> configs;
969 getDisplayConfigs(displayToken, &configs);
970 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
971 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
972 configs.size());
973 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700974 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700975 const auto display = getDisplayDevice(displayToken);
976 if (!display) {
977 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
978 displayToken.get());
979 } else if (display->isVirtual()) {
980 ALOGW("Attempt to set active config %d for virtual display", mode);
981 } else {
982 setActiveConfigInternal(display, mode);
983 }
984 }));
985
Mathias Agopian888c8222012-08-04 21:10:38 -0700986 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700987}
Dominik Laskowski075d3172018-05-24 15:50:06 -0700988
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700989status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
990 Vector<ColorMode>* outColorModes) {
991 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700992 return BAD_VALUE;
993 }
994
Dominik Laskowski075d3172018-05-24 15:50:06 -0700995 const auto displayId = getPhysicalDisplayId(displayToken);
996 if (!displayId) {
997 return NAME_NOT_FOUND;
Michael Wright28f24d02016-07-12 13:30:53 -0700998 }
999
Peiyong Lina52f0292018-03-14 17:26:31 -07001000 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001001 {
1002 ConditionalLock _l(mStateLock,
1003 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001004 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001005 }
Michael Wright28f24d02016-07-12 13:30:53 -07001006 outColorModes->clear();
1007 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1008
1009 return NO_ERROR;
1010}
1011
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001012ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1013 if (const auto display = getDisplayDevice(displayToken)) {
1014 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001015 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001016 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001017}
1018
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001019void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1020 Dataspace dataSpace, RenderIntent renderIntent) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001021 if (display->isVirtual()) {
1022 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
1023 return;
1024 }
1025
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001026 ColorMode currentMode = display->getActiveColorMode();
1027 Dataspace currentDataSpace = display->getCompositionDataSpace();
1028 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001029
Peiyong Lin38e9a562018-04-10 16:24:20 -07001030 if (mode == currentMode && dataSpace == currentDataSpace &&
1031 renderIntent == currentRenderIntent) {
1032 return;
1033 }
1034
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001035 display->setActiveColorMode(mode);
1036 display->setCompositionDataSpace(dataSpace);
1037 display->setActiveRenderIntent(renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001038
Dominik Laskowski075d3172018-05-24 15:50:06 -07001039 const auto displayId = display->getId();
1040 LOG_ALWAYS_FATAL_IF(!displayId);
1041 getHwComposer().setActiveColorMode(*displayId, mode, renderIntent);
1042
Dominik Laskowski34157762018-10-31 13:07:19 -07001043 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), display=%s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001044 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
Dominik Laskowski34157762018-10-31 13:07:19 -07001045 renderIntent, to_string(*displayId).c_str());
Michael Wright28f24d02016-07-12 13:30:53 -07001046}
1047
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001048status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001049 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001050 Vector<ColorMode> modes;
1051 getDisplayColorModes(displayToken, &modes);
1052 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1053 if (mode < ColorMode::NATIVE || !exists) {
1054 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1055 decodeColorMode(mode).c_str(), mode, displayToken.get());
1056 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001057 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001058 const auto display = getDisplayDevice(displayToken);
1059 if (!display) {
1060 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1061 decodeColorMode(mode).c_str(), mode, displayToken.get());
1062 } else if (display->isVirtual()) {
1063 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1064 decodeColorMode(mode).c_str(), mode);
1065 } else {
1066 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1067 RenderIntent::COLORIMETRIC);
1068 }
1069 }));
1070
Michael Wright28f24d02016-07-12 13:30:53 -07001071 return NO_ERROR;
1072}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001073
Svetoslavd85084b2014-03-20 10:28:31 -07001074status_t SurfaceFlinger::clearAnimationFrameStats() {
1075 Mutex::Autolock _l(mStateLock);
1076 mAnimFrameTracker.clearStats();
1077 return NO_ERROR;
1078}
1079
1080status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1081 Mutex::Autolock _l(mStateLock);
1082 mAnimFrameTracker.getStats(outStats);
1083 return NO_ERROR;
1084}
1085
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001086status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1087 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001088 Mutex::Autolock _l(mStateLock);
1089
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001090 const auto display = getDisplayDeviceLocked(displayToken);
1091 if (!display) {
1092 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001093 return BAD_VALUE;
1094 }
1095
Peiyong Linfb069302018-04-25 14:34:31 -07001096 // At this point the DisplayDeivce should already be set up,
1097 // meaning the luminance information is already queried from
1098 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001099 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001100 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1101 capabilities.getDesiredMaxLuminance(),
1102 capabilities.getDesiredMaxAverageLuminance(),
1103 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001104
1105 return NO_ERROR;
1106}
1107
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001108status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1109 ui::PixelFormat* outFormat,
1110 ui::Dataspace* outDataspace,
1111 uint8_t* outComponentMask) const {
1112 if (!outFormat || !outDataspace || !outComponentMask) {
1113 return BAD_VALUE;
1114 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001115 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001116 if (!display || !display->getId()) {
1117 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1118 return BAD_VALUE;
1119 }
1120 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1121 outDataspace, outComponentMask);
1122}
1123
Kevin DuBois74e53772018-11-19 10:52:38 -08001124status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1125 bool enable, uint8_t componentMask,
1126 uint64_t maxFrames) const {
1127 const auto display = getDisplayDevice(displayToken);
1128 if (!display || !display->getId()) {
1129 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1130 return BAD_VALUE;
1131 }
1132
1133 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1134 componentMask, maxFrames);
1135}
1136
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001137status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1138 uint64_t maxFrames, uint64_t timestamp,
1139 DisplayedFrameStats* outStats) const {
1140 const auto display = getDisplayDevice(displayToken);
1141 if (!display || !display->getId()) {
1142 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1143 return BAD_VALUE;
1144 }
1145
1146 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1147 outStats);
1148}
1149
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001150status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001151 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001152 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001153
Chia-I Wu90f669f2017-10-05 14:24:41 -07001154 if (mInjectVSyncs == enable) {
1155 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001156 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001157
Ana Krulec98b5b242018-08-10 15:03:23 -07001158 // TODO(akrulec): Part of the Injector should be refactored, so that it
1159 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001160 if (enable) {
1161 ALOGV("VSync Injections enabled");
1162 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001163 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001164 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001165 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001166 impl::EventThread::InterceptVSyncsCallback(),
1167 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001168 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001169 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001170 } else {
1171 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001172 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001173 }
1174
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001175 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001176 }));
1177
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001178 return NO_ERROR;
1179}
1180
1181status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001182 Mutex::Autolock _l(mStateLock);
1183
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001184 if (!mInjectVSyncs) {
1185 ALOGE("VSync Injections not enabled");
1186 return BAD_VALUE;
1187 }
1188 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1189 ALOGV("Injecting VSync inside SurfaceFlinger");
1190 mVSyncInjector->onInjectSyncEvent(when);
1191 }
1192 return NO_ERROR;
1193}
1194
Lloyd Pique755e3192018-01-31 16:46:15 -08001195status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1196 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001197 // Try to acquire a lock for 1s, fail gracefully
1198 const status_t err = mStateLock.timedLock(s2ns(1));
1199 const bool locked = (err == NO_ERROR);
1200 if (!locked) {
1201 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1202 return TIMED_OUT;
1203 }
1204
1205 outLayers->clear();
1206 mCurrentState.traverseInZOrder([&](Layer* layer) {
1207 outLayers->push_back(layer->getLayerDebugInfo());
1208 });
1209
1210 mStateLock.unlock();
1211 return NO_ERROR;
1212}
1213
Peiyong Linc6780972018-10-28 15:24:08 -07001214status_t SurfaceFlinger::getCompositionPreference(
1215 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1216 Dataspace* outWideColorGamutDataspace,
1217 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001218 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001219 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001220 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001221 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001222 return NO_ERROR;
1223}
1224
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001225// ----------------------------------------------------------------------------
1226
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001227sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1228 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulec98b5b242018-08-10 15:03:23 -07001229 if (mUseScheduler) {
1230 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1231 return mScheduler->createDisplayEventConnection(mSfConnectionHandle);
1232 } else {
1233 return mScheduler->createDisplayEventConnection(mAppConnectionHandle);
1234 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001235 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001236 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1237 return mSFEventThread->createEventConnection();
1238 } else {
1239 return mEventThread->createEventConnection();
1240 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001241 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001242}
1243
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001244// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001245
1246void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001247 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001248}
1249
1250void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001251 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001252}
1253
1254void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001255 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001256}
1257
1258void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001259 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001260 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001261}
1262
1263status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001264 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001265 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001266}
1267
1268status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001269 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001270 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001271 if (res == NO_ERROR) {
1272 msg->wait();
1273 }
1274 return res;
1275}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001276
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001277void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001278 do {
1279 waitForEvent();
1280 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001281}
1282
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001283void SurfaceFlinger::enableHardwareVsync() {
1284 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001285 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001286 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001287 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001288 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001289 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001290}
1291
Jesse Hall948fe0c2013-10-14 12:56:09 -07001292void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001293 Mutex::Autolock _l(mHWVsyncLock);
1294
Jesse Hall948fe0c2013-10-14 12:56:09 -07001295 if (makeAvailable) {
1296 mHWVsyncAvailable = true;
Ana Krulec7ab56032018-11-02 20:51:06 +01001297 // TODO(b/113612090): This is silly, but necessary evil until we turn on the flag for good.
1298 if (mUseScheduler) {
1299 mScheduler->makeHWSyncAvailable(true);
1300 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001301 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001302 // Hardware vsync is not currently available, so abort the resync
1303 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001304 return;
1305 }
1306
Dominik Laskowski075d3172018-05-24 15:50:06 -07001307 const auto displayId = getInternalDisplayId();
1308 if (!displayId || !getHwComposer().isConnected(*displayId)) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001309 return;
1310 }
1311
Dominik Laskowski075d3172018-05-24 15:50:06 -07001312 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001313 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001314
Ana Krulece588e312018-09-18 12:32:24 -07001315 if (mUseScheduler) {
1316 mScheduler->setVsyncPeriod(period);
1317 } else {
1318 mPrimaryDispSync->reset();
1319 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001320
Ana Krulece588e312018-09-18 12:32:24 -07001321 if (!mPrimaryHWVsyncEnabled) {
1322 mPrimaryDispSync->beginResync();
1323 mEventControlThread->setVsyncEnabled(true);
1324 mPrimaryHWVsyncEnabled = true;
1325 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001326 }
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
Dominik Laskowski075d3172018-05-24 15:50:06 -07001363 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001364 return;
1365 }
1366
Dominik Laskowski075d3172018-05-24 15:50:06 -07001367 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001368 // For now, we don't do anything with external display vsyncs.
1369 return;
1370 }
1371
Ana Krulece588e312018-09-18 12:32:24 -07001372 if (mUseScheduler) {
1373 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001374 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001375 bool needsHwVsync = false;
1376 { // Scope for the lock
1377 Mutex::Autolock _l(mHWVsyncLock);
1378 if (mPrimaryHWVsyncEnabled) {
1379 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1380 }
1381 }
1382
1383 if (needsHwVsync) {
1384 enableHardwareVsync();
1385 } else {
1386 disableHardwareVsync(false);
1387 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001388 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001389}
1390
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001391void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001392 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1393 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001394}
1395
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001396void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001397 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001398 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001399 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001400
Lloyd Piqueba04e622017-12-14 17:11:26 -08001401 // Ignore events that do not have the right sequenceId.
1402 if (sequenceId != getBE().mComposerSequenceId) {
1403 return;
1404 }
1405
Steven Thomasb02664d2017-07-26 18:48:28 -07001406 // Only lock if we're not on the main thread. This function is normally
1407 // called on a hwbinder thread, but for the primary display it's called on
1408 // the main thread with the state lock already held, so don't attempt to
1409 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001410 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001411
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001412 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001413
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001414 if (std::this_thread::get_id() == mMainThreadId) {
1415 // Process all pending hot plug events immediately if we are on the main thread.
1416 processDisplayHotplugEventsLocked();
1417 }
1418
Lloyd Piqueba04e622017-12-14 17:11:26 -08001419 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001420}
1421
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001422void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001423 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001424 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001425 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001426 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001427 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001428}
1429
Dominik Laskowski075d3172018-05-24 15:50:06 -07001430void SurfaceFlinger::setVsyncEnabled(EventThread::DisplayType /*displayType*/, bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001431 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001432 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001433 if (const auto displayId = getInternalDisplayId()) {
1434 getHwComposer().setVsyncEnabled(*displayId,
1435 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1436 }
Mathias Agopian86303202012-07-24 22:46:10 -07001437}
1438
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001439// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001440void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001441 if (mUseScheduler) {
1442 mScheduler->disableHardwareVsync(true);
1443 } else {
1444 disableHardwareVsync(true);
1445 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001446 // Clear the drawing state so that the logic inside of
1447 // handleTransactionLocked will fire. It will determine the delta between
1448 // mCurrentState and mDrawingState and re-apply all changes when we make the
1449 // transition.
1450 mDrawingState.displays.clear();
1451 mDisplays.clear();
1452}
1453
Steven Thomas050b2c82017-03-06 11:45:16 -08001454void SurfaceFlinger::updateVrFlinger() {
1455 if (!mVrFlinger)
1456 return;
1457 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001458 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001459 return;
1460 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001461
Lloyd Pique441d5042018-10-18 16:49:51 -07001462 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001463 ALOGE("Vr flinger is only supported for remote hardware composer"
1464 " service connections. Ignoring request to transition to vr"
1465 " flinger.");
1466 mVrFlingerRequestsDisplay = false;
1467 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001468 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001469
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001470 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001471
Steven Thomas0123ac62018-07-12 11:32:34 -07001472 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001473 LOG_ALWAYS_FATAL_IF(!display);
1474 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001475 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1476 // called below. Clear the reference now so we don't accidentally use it
1477 // later.
1478 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001479
Steven Thomasb02664d2017-07-26 18:48:28 -07001480 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001481 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001482 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001483
Steven Thomasb02664d2017-07-26 18:48:28 -07001484 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001485 // Delete the current instance before creating the new one
1486 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1487 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1488 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1489 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001490
Lloyd Pique441d5042018-10-18 16:49:51 -07001491 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001492 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001493
1494 if (vrFlingerRequestsDisplay) {
1495 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001496 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001497
1498 mVisibleRegionsDirty = true;
1499 invalidateHwcGeometry();
1500
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001501 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001502 display = getDefaultDisplayDeviceLocked();
1503 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001504 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001505
Steven Thomasb02664d2017-07-26 18:48:28 -07001506 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski075d3172018-05-24 15:50:06 -07001507 const auto activeConfig = getHwComposer().getActiveConfig(*display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001508 const nsecs_t period = activeConfig->getVsyncPeriod();
1509 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001510
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001511 // The present fences returned from vr_hwc are not an accurate
1512 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001513 if (mUseScheduler) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001514 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
1515 !hasSyncFramework);
Ana Krulece588e312018-09-18 12:32:24 -07001516 } else {
Lloyd Pique441d5042018-10-18 16:49:51 -07001517 mPrimaryDispSync->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
Ana Krulece588e312018-09-18 12:32:24 -07001518 !hasSyncFramework);
1519 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001520
Steven Thomasb02664d2017-07-26 18:48:28 -07001521 // Use phase of 0 since phase is not known.
1522 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07001523 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
1524 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001525
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001526 resyncToHardwareVsync(false);
1527
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001528 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001529 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001530}
1531
Mathias Agopian4fec8732012-06-29 14:12:52 -07001532void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001533 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001534 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001535 case MessageQueue::INVALIDATE: {
Ana Krulec3084c052018-11-21 20:27:17 +01001536 if (mUseScheduler) {
1537 // This call is made each time SF wakes up and creates a new frame.
1538 mScheduler->incrementFrameCounter();
1539 }
Dan Stoza50182882016-07-08 12:02:20 -07001540 bool frameMissed = !mHadClientComposition &&
1541 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001542 (mPreviousPresentFence->getSignalTime() ==
1543 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001544 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001545 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001546 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001547 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001548 if (mPropagateBackpressure) {
1549 signalLayerUpdate();
1550 break;
1551 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001552 }
Dan Stoza50182882016-07-08 12:02:20 -07001553
Steven Thomas050b2c82017-03-06 11:45:16 -08001554 // Now that we're going to make it to the handleMessageTransaction()
1555 // call below it's safe to call updateVrFlinger(), which will
1556 // potentially trigger a display handoff.
1557 updateVrFlinger();
1558
Dan Stoza6b9454d2014-11-07 16:00:59 -08001559 bool refreshNeeded = handleMessageTransaction();
1560 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001561 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001562 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001563 // Signal a refresh if a transaction modified the window state,
1564 // a new buffer was latched, or if HWC has requested a full
1565 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001566 signalRefresh();
1567 }
1568 break;
1569 }
1570 case MessageQueue::REFRESH: {
1571 handleMessageRefresh();
1572 break;
1573 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001574 }
1575}
1576
Dan Stoza6b9454d2014-11-07 16:00:59 -08001577bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001578 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001579 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001580 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001581 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001582 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001583 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001584}
1585
Mathias Agopian4fec8732012-06-29 14:12:52 -07001586void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001587 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001588
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001589 mRefreshPending = false;
1590
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001591 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001592 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001593 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001594 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001595 for (const auto& [token, display] : mDisplays) {
1596 beginFrame(display);
1597 prepareFrame(display);
1598 doDebugFlashRegions(display, repaintEverything);
1599 doComposition(display, repaintEverything);
1600 }
1601
Adrian Roos1e1a1282017-11-01 19:05:31 +01001602 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001603 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001604
1605 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001606 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001607
Dan Stozabfbffeb2016-07-21 14:49:33 -07001608 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001609 for (const auto& [token, display] : mDisplays) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001610 mHadClientComposition =
1611 mHadClientComposition || getHwComposer().hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001612 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001613
Alec Mouri86770e52018-09-24 22:40:58 +00001614 // Setup RenderEngine sync fences if native sync is supported.
1615 if (getBE().mRenderEngine->useNativeFenceSync()) {
1616 if (mHadClientComposition) {
1617 base::unique_fd flushFence(getRenderEngine().flush());
1618 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1619 getBE().flushFence = new Fence(std::move(flushFence));
1620 } else {
1621 // Cleanup for hygiene.
1622 getBE().flushFence = Fence::NO_FENCE;
1623 }
1624 }
1625
Jorim Jaggi90535212018-05-23 23:44:06 +02001626 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001627
David Sodman7e4ae112018-02-09 15:02:28 -08001628 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001629 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001630 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[token]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001631 compositionInfo.hwc.hwcLayer = nullptr;
1632 }
David Sodmanba340492018-08-05 21:51:33 -07001633 }
David Sodman7e4ae112018-02-09 15:02:28 -08001634
1635 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001636}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001637
David Sodmanfa9b2af2017-12-24 13:28:59 -08001638
1639bool SurfaceFlinger::handleMessageInvalidate() {
1640 ATRACE_CALL();
1641 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001642}
1643
David Sodman79bba0e2018-08-05 18:07:49 -07001644void SurfaceFlinger::calculateWorkingSet() {
1645 ATRACE_CALL();
1646 ALOGV(__FUNCTION__);
1647
David Sodman79bba0e2018-08-05 18:07:49 -07001648 // build the h/w work list
1649 if (CC_UNLIKELY(mGeometryInvalid)) {
1650 mGeometryInvalid = false;
1651 for (const auto& [token, display] : mDisplays) {
1652 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001653 if (!displayId) {
1654 continue;
1655 }
David Sodman79bba0e2018-08-05 18:07:49 -07001656
Dominik Laskowski075d3172018-05-24 15:50:06 -07001657 const Vector<sp<Layer>>& currentLayers = display->getVisibleLayersSortedByZ();
1658 for (size_t i = 0; i < currentLayers.size(); i++) {
1659 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001660
Dominik Laskowski075d3172018-05-24 15:50:06 -07001661 if (!layer->hasHwcLayer(*displayId)) {
1662 if (!layer->createHwcLayer(&getHwComposer(), *displayId)) {
1663 layer->forceClientComposition(*displayId);
1664 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001665 }
1666 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001667
1668 layer->setGeometry(display, i);
1669 if (mDebugDisableHWC || mDebugRegion) {
1670 layer->forceClientComposition(*displayId);
1671 }
David Sodman79bba0e2018-08-05 18:07:49 -07001672 }
1673 }
1674 }
1675
1676 // Set the per-frame data
1677 for (const auto& [token, display] : mDisplays) {
1678 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001679 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001680 continue;
1681 }
1682
1683 if (mDrawingState.colorMatrixChanged) {
1684 display->setColorTransform(mDrawingState.colorMatrix);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001685 status_t result =
1686 getHwComposer().setColorTransform(*displayId, mDrawingState.colorMatrix);
Dominik Laskowski34157762018-10-31 13:07:19 -07001687 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on display %s: %d",
1688 to_string(*displayId).c_str(), result);
David Sodman79bba0e2018-08-05 18:07:49 -07001689 }
1690 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1691 if (layer->isHdrY410()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001692 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001693 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1694 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1695 !display->hasHDR10Support()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001696 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001697 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1698 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1699 !display->hasHLGSupport()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001700 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001701 }
1702
Peiyong Lind3788632018-09-18 16:01:31 -07001703 // TODO(b/111562338) remove when composer 2.3 is shipped.
1704 if (layer->hasColorTransform()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001705 layer->forceClientComposition(*displayId);
Peiyong Lind3788632018-09-18 16:01:31 -07001706 }
1707
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001708 if (layer->getRoundedCornerState().radius > 0.0f) {
1709 layer->forceClientComposition(*displayId);
1710 }
1711
Dominik Laskowski075d3172018-05-24 15:50:06 -07001712 if (layer->getForceClientComposition(*displayId)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001713 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski075d3172018-05-24 15:50:06 -07001714 layer->setCompositionType(*displayId, HWC2::Composition::Client);
David Sodman79bba0e2018-08-05 18:07:49 -07001715 continue;
1716 }
1717
Dominik Laskowski075d3172018-05-24 15:50:06 -07001718 layer->setPerFrameData(*displayId, display->getTransform(), display->getViewport(),
1719 display->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001720 }
1721
Peiyong Lin13effd12018-07-24 17:01:47 -07001722 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001723 ColorMode colorMode;
1724 Dataspace dataSpace;
1725 RenderIntent renderIntent;
1726 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1727 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1728 }
1729 }
1730
1731 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001732
1733 for (const auto& [token, display] : mDisplays) {
1734 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001735 const auto displayId = display->getId();
David Sodmanba340492018-08-05 21:51:33 -07001736 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001737
1738 if (displayId) {
1739 if (!layer->setHwcLayer(*displayId)) {
1740 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1741 }
1742 layer->getBE().compositionInfo.hwc.displayId = *displayId;
David Sodmanba340492018-08-05 21:51:33 -07001743 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001744
Dominik Laskowski05275f12018-11-01 15:03:24 -07001745 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001746 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1747 }
1748 }
David Sodman79bba0e2018-08-05 18:07:49 -07001749}
1750
David Sodmanfa9b2af2017-12-24 13:28:59 -08001751void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001752{
1753 // is debugging enabled
1754 if (CC_LIKELY(!mDebugRegion))
1755 return;
1756
David Sodmanfa9b2af2017-12-24 13:28:59 -08001757 if (display->isPoweredOn()) {
1758 // transform the dirty region into this screen's coordinate space
1759 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1760 if (!dirtyRegion.isEmpty()) {
1761 // redraw the whole screen
1762 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001763
David Sodmanfa9b2af2017-12-24 13:28:59 -08001764 // and draw the dirty region
David Sodmanfa9b2af2017-12-24 13:28:59 -08001765 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07001766 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001767
Alec Mouri0a9c7b82018-11-16 13:05:25 -08001768 display->queueBuffer(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001769 }
1770 }
1771
David Sodmanfa9b2af2017-12-24 13:28:59 -08001772 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001773
1774 if (mDebugRegion > 1) {
1775 usleep(mDebugRegion * 1000);
1776 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001777
Dominik Laskowski05275f12018-11-01 15:03:24 -07001778 prepareFrame(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001779}
1780
Adrian Roos1e1a1282017-11-01 19:05:31 +01001781void SurfaceFlinger::doTracing(const char* where) {
1782 ATRACE_CALL();
1783 ATRACE_NAME(where);
1784 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001785 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001786 }
1787}
1788
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001789void SurfaceFlinger::logLayerStats() {
1790 ATRACE_CALL();
1791 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001792 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001793 if (display->isPrimary()) {
1794 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001795 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001796 }
1797 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001798
1799 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001800 }
1801}
1802
David Sodman2b406362017-12-15 13:33:47 -08001803void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001804{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001805 ATRACE_CALL();
1806 ALOGV("preComposition");
1807
David Sodman2b406362017-12-15 13:33:47 -08001808 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1809
Mathias Agopiancd60f992012-08-16 16:28:27 -07001810 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001811 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001812 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001813 needExtraInvalidate = true;
1814 }
Robert Carr2047fae2016-11-28 14:09:09 -08001815 });
1816
Mathias Agopiancd60f992012-08-16 16:28:27 -07001817 if (needExtraInvalidate) {
1818 signalLayerUpdate();
1819 }
1820}
1821
Ana Krulece588e312018-09-18 12:32:24 -07001822void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1823 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001824 // Update queue of past composite+present times and determine the
1825 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001826 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001827 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001828 while (!getBE().mCompositePresentTimes.empty()) {
1829 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001830 // Cached values should have been updated before calling this method,
1831 // which helps avoid duplicate syscalls.
1832 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1833 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1834 break;
1835 }
1836 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001837 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001838 }
1839
1840 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001841 while (getBE().mCompositePresentTimes.size() > 16) {
1842 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001843 }
1844
Ana Krulece588e312018-09-18 12:32:24 -07001845 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001846}
1847
Ana Krulece588e312018-09-18 12:32:24 -07001848void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1849 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001850 // Integer division and modulo round toward 0 not -inf, so we need to
1851 // treat negative and positive offsets differently.
Ana Krulece588e312018-09-18 12:32:24 -07001852 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0)
1853 ? (stats.vsyncPeriod - (sfVsyncPhaseOffsetNs % stats.vsyncPeriod))
1854 : ((-sfVsyncPhaseOffsetNs) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001855
Brian Andersond0010582017-03-07 13:20:31 -08001856 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1857 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001858 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001859 }
1860
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001861 // Snap the latency to a value that removes scheduling jitter from the
1862 // composition and present times, which often have >1ms of jitter.
1863 // Reducing jitter is important if an app attempts to extrapolate
1864 // something (such as user input) to an accurate diasplay time.
1865 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1866 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001867 nsecs_t bias = stats.vsyncPeriod / 2;
1868 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1869 nsecs_t snappedCompositeToPresentLatency =
1870 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001871
David Sodman99974d22017-11-28 12:04:33 -08001872 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001873 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1874 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001875 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001876}
1877
David Sodman2b406362017-12-15 13:33:47 -08001878void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001879{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001880 ATRACE_CALL();
1881 ALOGV("postComposition");
1882
Brian Anderson3546a3f2016-07-14 11:51:14 -07001883 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001884 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001885 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001886 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001887 }
1888
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001889 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001890 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001891
David Sodman73beded2017-11-15 11:56:06 -08001892 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001893 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001894 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001895 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001896 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001897 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001898 } else {
1899 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1900 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001901
David Sodman73beded2017-11-15 11:56:06 -08001902 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001903 mPreviousPresentFence =
Dominik Laskowski075d3172018-05-24 15:50:06 -07001904 display ? getHwComposer().getPresentFence(*display->getId()) : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001905 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001906 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001907
Ana Krulece588e312018-09-18 12:32:24 -07001908 DisplayStatInfo stats;
1909 if (mUseScheduler) {
1910 mScheduler->getDisplayStatInfo(&stats);
1911 } else {
1912 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
1913 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
1914 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001915
David Sodman2b406362017-12-15 13:33:47 -08001916 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001917 // when we started doing work for this frame, but that should be okay
1918 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07001919 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001920 CompositorTiming compositorTiming;
1921 {
David Sodman99974d22017-11-28 12:04:33 -08001922 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1923 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001924 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001925
Robert Carr2047fae2016-11-28 14:09:09 -08001926 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001927 bool frameLatched = layer->onPostComposition(display->getId(), glCompositionDoneFenceTime,
1928 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001929 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001930 recordBufferingStats(layer->getName().string(),
1931 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001932 }
Robert Carr2047fae2016-11-28 14:09:09 -08001933 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001934
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001935 if (presentFenceTime->isValid()) {
Ana Krulece588e312018-09-18 12:32:24 -07001936 if (mUseScheduler) {
1937 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001938 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001939 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
1940 enableHardwareVsync();
1941 } else {
1942 disableHardwareVsync(false);
1943 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001944 }
1945 }
1946
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001947 if (!hasSyncFramework) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001948 if (display && getHwComposer().isConnected(*display->getId()) && display->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07001949 if (mUseScheduler) {
1950 mScheduler->enableHardwareVsync();
1951 } else {
1952 enableHardwareVsync();
1953 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001954 }
1955 }
1956
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001957 if (mAnimCompositionPending) {
1958 mAnimCompositionPending = false;
1959
Brian Anderson4e606e32017-03-16 15:34:57 -07001960 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001961 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001962 std::move(presentFenceTime));
Dominik Laskowski075d3172018-05-24 15:50:06 -07001963 } else if (display && getHwComposer().isConnected(*display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001964 // The HWC doesn't support present fences, so use the refresh
1965 // timestamp instead.
Dominik Laskowski075d3172018-05-24 15:50:06 -07001966 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(*display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001967 mAnimFrameTracker.setActualPresentTime(presentTime);
1968 }
1969 mAnimFrameTracker.advanceFrame();
1970 }
Dan Stozab90cf072015-03-05 11:05:59 -08001971
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001972 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001973 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001974 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001975 }
1976
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001977 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07001978
Dominik Laskowski075d3172018-05-24 15:50:06 -07001979 if (display && getHwComposer().isConnected(*display->getId()) && !display->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08001980 return;
1981 }
1982
1983 nsecs_t currentTime = systemTime();
1984 if (mHasPoweredOff) {
1985 mHasPoweredOff = false;
1986 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001987 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07001988 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08001989 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1990 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001991 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001992 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001993 }
David Sodman4a36e932017-11-07 14:29:47 -08001994 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001995 }
David Sodman4a36e932017-11-07 14:29:47 -08001996 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001997
1998 {
1999 std::lock_guard lock(mTexturePoolMutex);
2000 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
2001 if (refillCount > 0) {
2002 const size_t offset = mTexturePool.size();
2003 mTexturePool.resize(mTexturePoolSize);
2004 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2005 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2006 }
2007 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002008
Marissa Wallfda30bb2018-10-12 11:34:28 -07002009 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002010 mTransactionCompletedThread.sendCallbacks();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002011}
2012
2013void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002014 ATRACE_CALL();
2015 ALOGV("rebuildLayerStacks");
2016
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002017 // We need to clear these out now as these may be holding on to a
2018 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2019 // also holds a reference. When the set of visible layers is recomputed,
2020 // some layers may be destroyed if the only thing keeping them alive was
2021 // that list of visible layers associated with each display. The layer
2022 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2023 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2024 for (const auto& [token, display] : mDisplays) {
2025 getBE().mCompositionInfo[token].clear();
2026 }
2027
Mathias Agopiancd60f992012-08-16 16:28:27 -07002028 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002029 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002030 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002031 mVisibleRegionsDirty = false;
2032 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002033
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002034 for (const auto& pair : mDisplays) {
2035 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07002036 Region opaqueRegion;
2037 Region dirtyRegion;
2038 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002039 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07002040 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002041 const Rect bounds = display->getBounds();
2042 if (display->isPoweredOn()) {
2043 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002044
Jeff Sharkey76488112017-02-27 14:15:18 -07002045 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08002046 bool hwcLayerDestroyed = false;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002047 const auto displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002048 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002049 Region drawRegion(tr.transform(
2050 layer->visibleNonTransparentRegion));
2051 drawRegion.andSelf(bounds);
2052 if (!drawRegion.isEmpty()) {
2053 layersSortedByZ.add(layer);
2054 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002055 // Clear out the HWC layer if this layer was
2056 // previously visible, but no longer is
Dominik Laskowski075d3172018-05-24 15:50:06 -07002057 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Jeff Sharkey76488112017-02-27 14:15:18 -07002058 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002059 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002060 // WM changes display->layerStack upon sleep/awake.
2061 // Here we make sure we delete the HWC layers even if
2062 // WM changed their layer stack.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002063 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Chia-I Wu83806892017-11-16 10:50:20 -08002064 }
2065
2066 // If a layer is not going to get a release fence because
2067 // it is invisible, but it is also going to release its
2068 // old buffer, add it to the list of layers needing
2069 // fences.
2070 if (hwcLayerDestroyed) {
2071 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2072 mLayersWithQueuedFrames.cend(), layer);
2073 if (found != mLayersWithQueuedFrames.cend()) {
2074 layersNeedingFences.add(layer);
2075 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002076 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002077 });
2078 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002079 display->setVisibleLayersSortedByZ(layersSortedByZ);
2080 display->setLayersNeedingFences(layersNeedingFences);
2081 display->undefinedRegion.set(bounds);
2082 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2083 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002084 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002085 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002086}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002087
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002088// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002089// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002090// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002091// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002092// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002093// The returned HDR data space is one of
2094// - Dataspace::UNKNOWN
2095// - Dataspace::BT2020_HLG
2096// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002097Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2098 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002099 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002100 *outHdrDataSpace = Dataspace::UNKNOWN;
2101
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002102 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002103 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002104 case Dataspace::V0_SCRGB:
2105 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002106 case Dataspace::BT2020:
2107 case Dataspace::BT2020_ITU:
2108 case Dataspace::BT2020_LINEAR:
2109 case Dataspace::DISPLAY_BT2020:
2110 bestDataSpace = Dataspace::DISPLAY_BT2020;
2111 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002112 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002113 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002114 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002115 case Dataspace::BT2020_PQ:
2116 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002117 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002118 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002119 case Dataspace::BT2020_HLG:
2120 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002121 // When there's mixed PQ content and HLG content, we set the HDR
2122 // data space to be BT2020_PQ and convert HLG to PQ.
2123 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2124 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002125 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002126 break;
2127 default:
2128 break;
2129 }
Romain Guy54f154a2017-10-24 21:40:32 +01002130 }
2131
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002132 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002133}
2134
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002135// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002136void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2137 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002138 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2139 *outMode = ColorMode::NATIVE;
2140 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002141 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002142 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002143 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002144
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002145 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002146 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002147
Peiyong Lindfde5112018-06-05 10:58:41 -07002148 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002149 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07002150 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002151 if (isHdr) {
2152 bestDataSpace = hdrDataSpace;
2153 }
2154
Chia-I Wu0d711262018-05-21 15:19:35 -07002155 RenderIntent intent;
2156 switch (mDisplayColorSetting) {
2157 case DisplayColorSetting::MANAGED:
2158 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002159 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002160 break;
2161 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002162 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002163 break;
2164 default: // vendor display color setting
2165 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2166 break;
2167 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002168
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002169 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002170}
2171
David Sodmanfa9b2af2017-12-24 13:28:59 -08002172void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002173{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002174 bool dirty = !display->getDirtyRegion(false).isEmpty();
2175 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2176 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002177
David Sodmanfa9b2af2017-12-24 13:28:59 -08002178 // If nothing has changed (!dirty), don't recompose.
2179 // If something changed, but we don't currently have any visible layers,
2180 // and didn't when we last did a composition, then skip it this time.
2181 // The second rule does two things:
2182 // - When all layers are removed from a display, we'll emit one black
2183 // frame, then nothing more until we get new layers.
2184 // - When a display is created with a private layer stack, we won't
2185 // emit any black frames until a layer is added to the layer stack.
2186 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002187
Dominik Laskowski075d3172018-05-24 15:50:06 -07002188 const char flagPrefix[] = {'-', '+'};
2189 static_cast<void>(flagPrefix);
2190 ALOGV_IF(display->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2191 __FUNCTION__, mustRecompose ? "doing" : "skipping", display->getDebugName().c_str(),
2192 flagPrefix[dirty], flagPrefix[empty], flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002193
David Sodmanfa9b2af2017-12-24 13:28:59 -08002194 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002195
David Sodmanfa9b2af2017-12-24 13:28:59 -08002196 if (mustRecompose) {
2197 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002198 }
2199}
2200
David Sodmanfa9b2af2017-12-24 13:28:59 -08002201void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002202{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002203 if (!display->isPoweredOn()) {
2204 return;
David Sodman2b406362017-12-15 13:33:47 -08002205 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002206
Dominik Laskowski05275f12018-11-01 15:03:24 -07002207 status_t result = display->prepareFrame(getHwComposer(),
2208 getBE().mCompositionInfo[display->getDisplayToken()]);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002209 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
2210 display->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002211}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002212
David Sodmanfa9b2af2017-12-24 13:28:59 -08002213void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002214 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002215 ALOGV("doComposition");
2216
David Sodmanfa9b2af2017-12-24 13:28:59 -08002217 if (display->isPoweredOn()) {
2218 // transform the dirty region into this screen's coordinate space
2219 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002220
David Sodmanfa9b2af2017-12-24 13:28:59 -08002221 // repaint the framebuffer (if needed)
2222 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002223
David Sodmanfa9b2af2017-12-24 13:28:59 -08002224 display->dirtyRegion.clear();
2225 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002226 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002227 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002228}
2229
David Sodmanfa9b2af2017-12-24 13:28:59 -08002230void SurfaceFlinger::postFrame()
2231{
2232 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002233 const auto display = getDefaultDisplayDeviceLocked();
2234 if (display && getHwComposer().isConnected(*display->getId())) {
2235 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002236 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2237 logFrameStats();
2238 }
2239 }
2240}
2241
2242void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002243{
Mathias Agopian841cde52012-03-01 15:44:37 -08002244 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002245 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002246
David Sodmanfa9b2af2017-12-24 13:28:59 -08002247 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002248
David Sodmanfa9b2af2017-12-24 13:28:59 -08002249 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002250 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002251 if (displayId) {
2252 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002253 }
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002254 display->onPresentDisplayCompleted();
David Sodman15094112018-10-11 09:39:37 -07002255 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002256 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002257
Chia-I Wu7b549592017-11-15 09:14:57 -08002258 // The layer buffer from the previous frame (if any) is released
2259 // by HWC only when the release fence from this frame (if any) is
2260 // signaled. Always get the release fence from HWC first.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002261 if (displayId && layer->hasHwcLayer(*displayId)) {
2262 releaseFence = getHwComposer().getLayerReleaseFence(*displayId,
2263 layer->getHwcLayer(*displayId));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002264 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002265
2266 // If the layer was client composited in the previous frame, we
2267 // need to merge with the previous client target acquire fence.
2268 // Since we do not track that, always merge with the current
2269 // client target acquire fence when it is available, even though
2270 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002271 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002272 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002273 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002274 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002275
David Sodman15094112018-10-11 09:39:37 -07002276 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002277 }
Chia-I Wu83806892017-11-16 10:50:20 -08002278
2279 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002280 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002281 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002282 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002283 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002284 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002285 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002286 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002287 }
2288 }
2289
Dominik Laskowski075d3172018-05-24 15:50:06 -07002290 if (displayId) {
2291 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002292 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002293 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002294}
2295
Mathias Agopian87baae12012-07-31 12:38:26 -07002296void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002297{
Mathias Agopian841cde52012-03-01 15:44:37 -08002298 ATRACE_CALL();
2299
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002300 // here we keep a copy of the drawing state (that is the state that's
2301 // going to be overwritten by handleTransactionLocked()) outside of
2302 // mStateLock so that the side-effects of the State assignment
2303 // don't happen with mStateLock held (which can cause deadlocks).
2304 State drawingState(mDrawingState);
2305
Mathias Agopianca4d3602011-05-19 15:38:14 -07002306 Mutex::Autolock _l(mStateLock);
2307 const nsecs_t now = systemTime();
2308 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002309
Mathias Agopianca4d3602011-05-19 15:38:14 -07002310 // Here we're guaranteed that some transaction flags are set
2311 // so we can call handleTransactionLocked() unconditionally.
2312 // We call getTransactionFlags(), which will also clear the flags,
2313 // with mStateLock held to guarantee that mCurrentState won't change
2314 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002315
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002316 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002317 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002318 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002319
Mathias Agopianca4d3602011-05-19 15:38:14 -07002320 mLastTransactionTime = systemTime() - now;
2321 mDebugInTransaction = 0;
2322 invalidateHwcGeometry();
2323 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002324}
2325
Lloyd Piqueba04e622017-12-14 17:11:26 -08002326void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2327 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002328 const std::optional<DisplayIdentificationInfo> info =
2329 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002330
Dominik Laskowski075d3172018-05-24 15:50:06 -07002331 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002332 continue;
2333 }
2334
Lloyd Piqueba04e622017-12-14 17:11:26 -08002335 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002336 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002337 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002338 mPhysicalDisplayTokens[info->id] = new BBinder();
2339 DisplayDeviceState state;
2340 state.displayId = info->id;
2341 state.isSecure = true; // All physical displays are currently considered secure.
2342 state.displayName = info->name;
2343 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2344 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002345 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002346 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002347 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002348
Dominik Laskowski075d3172018-05-24 15:50:06 -07002349 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2350 if (index >= 0) {
2351 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2352 mInterceptor->saveDisplayDeletion(state.sequenceId);
2353 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002354 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002355 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002356 }
2357
2358 processDisplayChangesLocked();
2359 }
2360
2361 mPendingHotplugEvents.clear();
2362}
2363
Lloyd Pique99d3da52018-01-22 17:48:03 -08002364sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002365 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
2366 const DisplayDeviceState& state, const sp<DisplaySurface>& dispSurface,
2367 const sp<IGraphicBufferProducer>& producer) {
2368 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002369 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002370 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002371 creationArgs.isSecure = state.isSecure;
2372 creationArgs.displaySurface = dispSurface;
2373 creationArgs.hasWideColorGamut = false;
2374 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002375
Dominik Laskowski075d3172018-05-24 15:50:06 -07002376 const bool isInternalDisplay = displayId && displayId == getInternalDisplayId();
2377 creationArgs.isPrimary = isInternalDisplay;
2378
2379 if (useColorManagement && displayId) {
2380 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002381 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002382 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002383 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002384 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002385
Dominik Laskowski7e045462018-05-30 13:02:02 -07002386 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002387 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002388 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002389 }
tangrobin6753a022018-08-10 10:58:54 +08002390 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002391
Dominik Laskowski075d3172018-05-24 15:50:06 -07002392 if (displayId) {
2393 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002394 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002395 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002396 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002397
Lloyd Pique90c115d2018-09-18 21:39:42 -07002398 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002399 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002400 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002401
Lloyd Pique99d3da52018-01-22 17:48:03 -08002402 // Make sure that composition can never be stalled by a virtual display
2403 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002404 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002405 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002406 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2407 }
2408
Dominik Laskowski075d3172018-05-24 15:50:06 -07002409 creationArgs.displayInstallOrientation =
2410 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002411
Lloyd Pique99d3da52018-01-22 17:48:03 -08002412 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002413 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002414
Lloyd Pique90c115d2018-09-18 21:39:42 -07002415 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002416
2417 if (maxFrameBufferAcquiredBuffers >= 3) {
2418 nativeWindowSurface->preallocateBuffers();
2419 }
2420
2421 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002422 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002423 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002424 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002425 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002426 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002427 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002428 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002429 if (!state.isVirtual()) {
2430 LOG_ALWAYS_FATAL_IF(!displayId);
2431 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002432 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002433
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002434 display->setLayerStack(state.layerStack);
2435 display->setProjection(state.orientation, state.viewport, state.frame);
2436 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002437
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002438 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002439}
2440
Lloyd Pique347200f2017-12-14 17:00:15 -08002441void SurfaceFlinger::processDisplayChangesLocked() {
2442 // here we take advantage of Vector's copy-on-write semantics to
2443 // improve performance by skipping the transaction entirely when
2444 // know that the lists are identical
2445 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2446 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2447 if (!curr.isIdenticalTo(draw)) {
2448 mVisibleRegionsDirty = true;
2449 const size_t cc = curr.size();
2450 size_t dc = draw.size();
2451
2452 // find the displays that were removed
2453 // (ie: in drawing state but not in current state)
2454 // also handle displays that changed
2455 // (ie: displays that are in both lists)
2456 for (size_t i = 0; i < dc;) {
2457 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2458 if (j < 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002459 // Save display IDs before disconnecting.
2460 const auto internalDisplayId = getInternalDisplayId();
2461 const auto externalDisplayId = getExternalDisplayId();
2462
Lloyd Pique347200f2017-12-14 17:00:15 -08002463 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002464 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2465 display->disconnect(getHwComposer());
2466 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002467 if (internalDisplayId && internalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002468 if (mUseScheduler) {
2469 mScheduler->hotplugReceived(mAppConnectionHandle,
2470 EventThread::DisplayType::Primary, false);
2471 } else {
2472 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2473 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002474 } else if (externalDisplayId && externalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002475 if (mUseScheduler) {
2476 mScheduler->hotplugReceived(mAppConnectionHandle,
2477 EventThread::DisplayType::External, false);
2478 } else {
2479 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2480 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002481 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002482 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002483 } else {
2484 // this display is in both lists. see if something changed.
2485 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002486 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002487 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2488 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2489 if (state_binder != draw_binder) {
2490 // changing the surface is like destroying and
2491 // recreating the DisplayDevice, so we just remove it
2492 // from the drawing state, so that it get re-added
2493 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002494 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2495 display->disconnect(getHwComposer());
2496 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002497 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002498 mDrawingState.displays.removeItemsAt(i);
2499 dc--;
2500 // at this point we must loop to the next item
2501 continue;
2502 }
2503
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002504 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002505 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002506 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002507 }
2508 if ((state.orientation != draw[i].orientation) ||
2509 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002510 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002511 }
2512 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002513 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002514 }
2515 }
2516 }
2517 ++i;
2518 }
2519
2520 // find displays that were added
2521 // (ie: in current state but not in drawing state)
2522 for (size_t i = 0; i < cc; i++) {
2523 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2524 const DisplayDeviceState& state(curr[i]);
2525
2526 sp<DisplaySurface> dispSurface;
2527 sp<IGraphicBufferProducer> producer;
2528 sp<IGraphicBufferProducer> bqProducer;
2529 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002530 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002531
Dominik Laskowski075d3172018-05-24 15:50:06 -07002532 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002533 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002534 // Virtual displays without a surface are dormant:
2535 // they have external state (layer stack, projection,
2536 // etc.) but no internal state (i.e. a DisplayDevice).
2537 if (state.surface != nullptr) {
2538 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002539 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002540 int width = 0;
2541 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2542 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2543 int height = 0;
2544 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2545 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2546 int intFormat = 0;
2547 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2548 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002549 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002550
Dominik Laskowski075d3172018-05-24 15:50:06 -07002551 displayId =
2552 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002553 }
2554
2555 // TODO: Plumb requested format back up to consumer
2556
2557 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002558 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002559 bqProducer, bqConsumer,
2560 state.displayName);
2561
2562 dispSurface = vds;
2563 producer = vds;
2564 }
2565 } else {
2566 ALOGE_IF(state.surface != nullptr,
2567 "adding a supported display, but rendering "
2568 "surface is provided (%p), ignoring it",
2569 state.surface.get());
2570
Dominik Laskowski075d3172018-05-24 15:50:06 -07002571 displayId = state.displayId;
2572 LOG_ALWAYS_FATAL_IF(!displayId);
2573 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002574 producer = bqProducer;
2575 }
2576
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002577 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002578 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002579 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002580 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002581 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002582 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002583 LOG_ALWAYS_FATAL_IF(!displayId);
2584
2585 if (displayId == getInternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002586 if (mUseScheduler) {
2587 mScheduler->hotplugReceived(mAppConnectionHandle,
2588 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002589 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002590 } else {
2591 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2592 true);
2593 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002594 } else if (displayId == getExternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002595 if (mUseScheduler) {
2596 mScheduler->hotplugReceived(mAppConnectionHandle,
2597 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002598 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002599 } else {
2600 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2601 true);
2602 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002603 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002604 }
2605 }
2606 }
2607 }
2608 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002609
2610 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002611}
2612
Mathias Agopian87baae12012-07-31 12:38:26 -07002613void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002614{
Dan Stoza7dde5992015-05-22 09:51:44 -07002615 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002616 mCurrentState.traverseInZOrder([](Layer* layer) {
2617 layer->notifyAvailableFrames();
2618 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002619
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002620 /*
2621 * Traversal of the children
2622 * (perform the transaction for each of them if needed)
2623 */
2624
Robert Carr720e5062018-07-30 17:45:14 -07002625 bool inputChanged = false;
Mathias Agopian3559b072012-08-15 13:46:03 -07002626 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002627 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002628 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002629 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002630
2631 const uint32_t flags = layer->doTransaction(0);
2632 if (flags & Layer::eVisibleRegion)
2633 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002634
2635 if (flags & Layer::eInputInfoChanged) {
2636 inputChanged = true;
2637 }
Robert Carr2047fae2016-11-28 14:09:09 -08002638 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002639 }
2640
2641 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002642 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002643 */
2644
Mathias Agopiane57f2922012-08-09 16:29:12 -07002645 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002646 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002647 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002648 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002649
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002650 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002651 // The transform hint might have changed for some layers
2652 // (either because a display has changed, or because a layer
2653 // as changed).
2654 //
2655 // Walk through all the layers in currentLayers,
2656 // and update their transform hint.
2657 //
2658 // If a layer is visible only on a single display, then that
2659 // display is used to calculate the hint, otherwise we use the
2660 // default display.
2661 //
2662 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2663 // the hint is set before we acquire a buffer from the surface texture.
2664 //
2665 // NOTE: layer transactions have taken place already, so we use their
2666 // drawing state. However, SurfaceFlinger's own transaction has not
2667 // happened yet, so we must use the current state layer list
2668 // (soon to become the drawing state list).
2669 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002670 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002671 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002672 bool first = true;
2673 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002674 // NOTE: we rely on the fact that layers are sorted by
2675 // layerStack first (so we don't have to traverse the list
2676 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002677 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002678 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002679 currentlayerStack = layerStack;
2680 // figure out if this layerstack is mirrored
2681 // (more than one display) if so, pick the default display,
2682 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002683 hintDisplay = nullptr;
2684 for (const auto& [token, display] : mDisplays) {
2685 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2686 if (hintDisplay) {
2687 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002688 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002689 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002690 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002691 }
2692 }
2693 }
2694 }
Chet Haase91d25932013-04-11 15:24:55 -07002695
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002696 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002697 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2698 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002699
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002700 // could be null when this layer is using a layerStack
2701 // that is not visible on any display. Also can occur at
2702 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002703 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002704 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002705
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002706 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002707 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002708 if (hintDisplay) {
2709 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002710 }
Robert Carr2047fae2016-11-28 14:09:09 -08002711
2712 first = false;
2713 });
Mathias Agopian84300952012-11-21 16:02:13 -08002714 }
2715
2716
Mathias Agopian3559b072012-08-15 13:46:03 -07002717 /*
2718 * Perform our own transaction if needed
2719 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002720
2721 if (mLayersAdded) {
2722 mLayersAdded = false;
2723 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002724 mVisibleRegionsDirty = true;
2725 }
2726
2727 // some layers might have been removed, so
2728 // we need to update the regions they're exposing.
2729 if (mLayersRemoved) {
2730 mLayersRemoved = false;
2731 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002732 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002733 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002734 // this layer is not visible anymore
2735 // TODO: we could traverse the tree from front to back and
2736 // compute the actual visible region
2737 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002738 Region visibleReg;
2739 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002740 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002741 }
Robert Carr2047fae2016-11-28 14:09:09 -08002742 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002743 }
2744
2745 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002746
Vishnu Nairde19f852018-12-18 16:11:53 -08002747 if (inputChanged || mVisibleRegionsDirty) {
Robert Carr720e5062018-07-30 17:45:14 -07002748 updateInputWindows();
2749 }
2750
Riley Andrews03414a12014-07-01 14:22:59 -07002751 updateCursorAsync();
2752}
2753
Robert Carr720e5062018-07-30 17:45:14 -07002754void SurfaceFlinger::updateInputWindows() {
2755 ATRACE_CALL();
2756
Vishnu Nairde19f852018-12-18 16:11:53 -08002757 if (mInputFlinger == nullptr) {
2758 return;
2759 }
2760
Robert Carr720e5062018-07-30 17:45:14 -07002761 Vector<InputWindowInfo> inputHandles;
2762
2763 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2764 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002765 // When calculating the screen bounds we ignore the transparent region since it may
2766 // result in an unwanted offset.
2767 inputHandles.add(layer->fillInputInfo(
2768 layer->computeScreenBounds(false /* reduceTransparentRegion */)));
Robert Carr720e5062018-07-30 17:45:14 -07002769 }
2770 });
2771 mInputFlinger->setInputWindows(inputHandles);
2772}
2773
Riley Andrews03414a12014-07-01 14:22:59 -07002774void SurfaceFlinger::updateCursorAsync()
2775{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002776 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002777 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002778 continue;
2779 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002780
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002781 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2782 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002783 }
2784 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002785}
2786
chaviw61626f22018-11-15 16:26:27 -08002787void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
2788 if (layer->hasReadyFrame()) {
2789 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
2790 if (layer->shouldPresentNow(expectedPresentTime)) {
2791 bool ignored = false;
2792 layer->latchBuffer(ignored, systemTime(), Fence::NO_FENCE);
2793 }
2794 }
2795 layer->releasePendingBuffer(systemTime());
2796}
2797
Mathias Agopian4fec8732012-06-29 14:12:52 -07002798void SurfaceFlinger::commitTransaction()
2799{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002800 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002801 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002802 for (const auto& l : mLayersPendingRemoval) {
2803 recordBufferingStats(l->getName().string(),
2804 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07002805
2806 // We need to release the HWC layers when the Layer is removed
2807 // from the current state otherwise the HWC layer just continues
2808 // showing at its last configured state until we eventually
2809 // abandon the buffer queue.
2810 if (l->isRemovedFromCurrentState()) {
Robert Carr3aee9892018-11-07 12:53:41 -08002811 l->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* child) {
chaviw61626f22018-11-15 16:26:27 -08002812 child->destroyHwcLayersForAllDisplays();
2813 latchAndReleaseBuffer(child);
Robert Carr3aee9892018-11-07 12:53:41 -08002814 });
Robert Carr2e102c92018-10-23 12:11:15 -07002815 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002816 }
2817 mLayersPendingRemoval.clear();
2818 }
2819
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002820 // If this transaction is part of a window animation then the next frame
2821 // we composite should be considered an animation as well.
2822 mAnimCompositionPending = mAnimTransactionPending;
2823
Mathias Agopian4fec8732012-06-29 14:12:52 -07002824 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002825 // clear the "changed" flags in current state
2826 mCurrentState.colorMatrixChanged = false;
2827
Robert Carr1f0a16a2016-10-24 16:27:39 -07002828 mDrawingState.traverseInZOrder([](Layer* layer) {
2829 layer->commitChildList();
2830 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002831 mTransactionPending = false;
2832 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002833 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002834}
2835
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002836void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2837 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002838 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002839 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002840
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002841 Region aboveOpaqueLayers;
2842 Region aboveCoveredLayers;
2843 Region dirty;
2844
Mathias Agopian87baae12012-07-31 12:38:26 -07002845 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002846
Robert Carr2047fae2016-11-28 14:09:09 -08002847 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Jesse Hall01e29052013-02-19 16:13:35 -08002848 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002849 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002850 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002851 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002852
Mathias Agopianab028732010-03-16 16:41:46 -07002853 /*
2854 * opaqueRegion: area of a surface that is fully opaque.
2855 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002856 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002857
2858 /*
2859 * visibleRegion: area of a surface that is visible on screen
2860 * and not fully transparent. This is essentially the layer's
2861 * footprint minus the opaque regions above it.
2862 * Areas covered by a translucent surface are considered visible.
2863 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002864 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002865
2866 /*
2867 * coveredRegion: area of a surface that is covered by all
2868 * visible regions above it (which includes the translucent areas).
2869 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002870 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002871
Jesse Halla8026d22012-09-25 13:25:04 -07002872 /*
2873 * transparentRegion: area of a surface that is hinted to be completely
2874 * transparent. This is only used to tell when the layer has no visible
2875 * non-transparent regions and can be removed from the layer list. It
2876 * does not affect the visibleRegion of this layer or any layers
2877 * beneath it. The hint may not be correct if apps don't respect the
2878 * SurfaceView restrictions (which, sadly, some don't).
2879 */
2880 Region transparentRegion;
2881
Mathias Agopianab028732010-03-16 16:41:46 -07002882
2883 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002884 if (CC_LIKELY(layer->isVisible())) {
Ady Abraham83729882018-12-07 12:26:48 -08002885 const bool translucent = !layer->isDrawingOpaque();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002886 Rect bounds(layer->computeScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07002887
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002888 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002889 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002890 if (!visibleRegion.isEmpty()) {
2891 // Remove the transparent area from the visible region
2892 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002893 if (tr.preserveRects()) {
2894 // transform the transparent region
Ady Abraham83729882018-12-07 12:26:48 -08002895 transparentRegion =
2896 tr.transform(layer->getDrawingActiveTransparentRegion());
Mathias Agopian4fec8732012-06-29 14:12:52 -07002897 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002898 // transformation too complex, can't do the
2899 // transparent region optimization.
2900 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002901 }
Mathias Agopianab028732010-03-16 16:41:46 -07002902 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002903
Mathias Agopianab028732010-03-16 16:41:46 -07002904 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002905 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002906 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002907 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002908 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002909 // the opaque region is the layer's footprint
2910 opaqueRegion = visibleRegion;
2911 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002912 }
2913 }
2914
Robert Carre5f4f692018-01-12 13:12:28 -08002915 if (visibleRegion.isEmpty()) {
2916 layer->clearVisibilityRegions();
2917 return;
2918 }
2919
Mathias Agopianab028732010-03-16 16:41:46 -07002920 // Clip the covered region to the visible region
2921 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2922
2923 // Update aboveCoveredLayers for next (lower) layer
2924 aboveCoveredLayers.orSelf(visibleRegion);
2925
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002926 // subtract the opaque region covered by the layers above us
2927 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002928
2929 // compute this layer's dirty region
2930 if (layer->contentDirty) {
2931 // we need to invalidate the whole region
2932 dirty = visibleRegion;
2933 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002934 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002935 layer->contentDirty = false;
2936 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002937 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002938 * the exposed region consists of two components:
2939 * 1) what's VISIBLE now and was COVERED before
2940 * 2) what's EXPOSED now less what was EXPOSED before
2941 *
2942 * note that (1) is conservative, we start with the whole
2943 * visible region but only keep what used to be covered by
2944 * something -- which mean it may have been exposed.
2945 *
2946 * (2) handles areas that were not covered by anything but got
2947 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002948 */
Mathias Agopianab028732010-03-16 16:41:46 -07002949 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002950 const Region oldVisibleRegion = layer->visibleRegion;
2951 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002952 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2953 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002954 }
2955 dirty.subtractSelf(aboveOpaqueLayers);
2956
2957 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002958 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002959
Mathias Agopianab028732010-03-16 16:41:46 -07002960 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002961 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002962
Jesse Halla8026d22012-09-25 13:25:04 -07002963 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002964 layer->setVisibleRegion(visibleRegion);
2965 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002966 layer->setVisibleNonTransparentRegion(
2967 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002968 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002969
Mathias Agopian87baae12012-07-31 12:38:26 -07002970 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002971}
2972
Chia-I Wuab0c3192017-08-01 11:29:00 -07002973void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002974 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002975 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2976 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002977 }
2978 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002979}
2980
Dan Stoza6b9454d2014-11-07 16:00:59 -08002981bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002982{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002983 ALOGV("handlePageFlip");
2984
Brian Andersond6927fb2016-07-23 23:37:30 -07002985 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002986
Mathias Agopian4fec8732012-06-29 14:12:52 -07002987 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002988 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002989 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002990
2991 // Store the set of layers that need updates. This set must not change as
2992 // buffers are being latched, as this could result in a deadlock.
2993 // Example: Two producers share the same command stream and:
2994 // 1.) Layer 0 is latched
2995 // 2.) Layer 0 gets a new frame
2996 // 2.) Layer 1 gets a new frame
2997 // 3.) Layer 1 is latched.
2998 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2999 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003000 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003001 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003002 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003003 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3004 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003005 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003006 } else {
3007 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003008 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003009 } else {
3010 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003011 }
Robert Carr2047fae2016-11-28 14:09:09 -08003012 });
3013
Dan Stoza9e56aa02015-11-02 13:00:03 -08003014 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri86770e52018-09-24 22:40:58 +00003015 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
Dan Stozaee44edd2015-03-23 15:50:23 -07003016 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003017 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07003018 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06003019 newDataLatched = true;
3020 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003021 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003022
Alec Mouri86770e52018-09-24 22:40:58 +00003023 // Clear the renderengine fence here...
3024 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3025 // clear instead of sp::clear.
3026 getBE().flushFence = Fence::NO_FENCE;
3027
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003028 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003029
Vishnu Nairde19f852018-12-18 16:11:53 -08003030 if (visibleRegions) {
3031 // Update input window info if the layer receives its first buffer.
3032 updateInputWindows();
3033 }
3034
Dan Stoza6b9454d2014-11-07 16:00:59 -08003035 // If we will need to wake up at some time in the future to deal with a
3036 // queued frame that shouldn't be displayed during this vsync period, wake
3037 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003038 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003039 signalLayerUpdate();
3040 }
3041
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003042 // enter boot animation on first buffer latch
3043 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3044 ALOGI("Enter boot animation");
3045 mBootStage = BootStage::BOOTANIMATION;
3046 }
3047
Dan Stoza6b9454d2014-11-07 16:00:59 -08003048 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003049 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003050}
3051
Mathias Agopianad456f92011-01-13 17:53:01 -08003052void SurfaceFlinger::invalidateHwcGeometry()
3053{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003054 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003055}
3056
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003057void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& display,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003058 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08003059 // We only need to actually compose the display if:
3060 // 1) It is being handled by hardware composer, which may need this to
3061 // keep its virtual display state machine in sync, or
3062 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski34157762018-10-31 13:07:19 -07003063 if (!display->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003064 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003065 return;
3066 }
3067
Dan Stoza9e56aa02015-11-02 13:00:03 -08003068 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003069 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003070
3071 // swap buffers (presentation)
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003072 display->queueBuffer(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003073}
3074
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003075bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003076 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003077
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003078 const Region bounds(display->bounds());
3079 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07003080 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07003081 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003082 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003083
Peiyong Lind3788632018-09-18 16:01:31 -07003084 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003085 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003086
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003087 // Framebuffer will live in this scope for GPU composition.
3088 std::unique_ptr<renderengine::BindNativeBufferAsFramebuffer> fbo;
3089
Dan Stoza9e56aa02015-11-02 13:00:03 -08003090 if (hasClientComposition) {
3091 ALOGV("hasClientComposition");
3092
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003093 sp<GraphicBuffer> buf = display->dequeueBuffer();
3094
3095 if (buf == nullptr) {
3096 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3097 "client composition for this frame",
3098 display->getDisplayName().c_str());
3099 return false;
3100 }
3101
3102 // Bind the framebuffer in this scope.
3103 fbo = std::make_unique<renderengine::BindNativeBufferAsFramebuffer>(getRenderEngine(),
3104 buf->getNativeBuffer());
3105
3106 if (fbo->getStatus() != NO_ERROR) {
3107 ALOGW("Binding buffer for display [%s] failed with status: %d",
3108 display->getDisplayName().c_str(), fbo->getStatus());
3109 return false;
3110 }
3111
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003112 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003113 if (display->hasWideColorGamut()) {
3114 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003115 }
3116 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07003117 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003118 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003119
Lloyd Pique441d5042018-10-18 16:49:51 -07003120 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003121 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003122 getHwComposer()
3123 .hasDisplayCapability(displayId,
3124 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003125
Peiyong Lind3788632018-09-18 16:01:31 -07003126 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003127 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3128 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003129 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003130 }
3131
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003132 display->setViewportAndProjection();
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003133
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003134 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003135 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003136 // when using overlays, we assume a fully transparent framebuffer
3137 // NOTE: we could reduce how much we need to clear, for instance
3138 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003139 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003140 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003141 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003142 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003143 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003144 // we're left with the letterbox region
3145 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003146 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003147
3148 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003149 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003150
Mathias Agopianb9494d52012-04-18 02:28:45 -07003151 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003152 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003153 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003154 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003155 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003156 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003157
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003158 const Rect& bounds = display->getBounds();
3159 const Rect& scissor = display->getScissor();
3160 if (scissor != bounds) {
3161 // scissor doesn't match the screen's dimensions, so we
3162 // need to clear everything outside of it and enable
3163 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003164
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003165 // enable scissor for this frame
Alec Mouri05483a02018-09-10 21:03:42 +00003166 getBE().mRenderEngine->setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003167 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003168 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003169
Mathias Agopian85d751c2012-08-29 16:59:24 -07003170 /*
3171 * and then, render the layers targeted at the framebuffer
3172 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003173
Dan Stoza9e56aa02015-11-02 13:00:03 -08003174 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07003175 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003176 bool firstLayer = true;
David Sodmanc1498e62018-09-12 14:36:26 -07003177 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003178 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003179 displayTransform.transform(layer->visibleRegion)));
3180 ALOGV("Layer: %s", layer->getName().string());
3181 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003182 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003183 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003184 case HWC2::Composition::Cursor:
3185 case HWC2::Composition::Device:
3186 case HWC2::Composition::Sideband:
3187 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003188 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07003189 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
Ady Abraham83729882018-12-07 12:26:48 -08003190 layer->isDrawingOpaque() && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003191 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003192 // never clear the very first layer since we're
3193 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003194 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003195 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003196 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003197 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003198 case HWC2::Composition::Client: {
Peiyong Lind3788632018-09-18 16:01:31 -07003199 if (layer->hasColorTransform()) {
3200 mat4 tmpMatrix;
3201 if (applyColorMatrix) {
3202 tmpMatrix = mDrawingState.colorMatrix;
3203 }
3204 tmpMatrix *= layer->getColorTransform();
Peiyong Lind3788632018-09-18 16:01:31 -07003205 getRenderEngine().setColorTransform(tmpMatrix);
3206 } else {
3207 getRenderEngine().setColorTransform(colorMatrix);
3208 }
David Sodmanc1498e62018-09-12 14:36:26 -07003209 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003210 break;
3211 }
3212 default:
3213 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003214 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003215 } else {
3216 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003217 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003218 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003219 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003220
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003221 // Perform some cleanup steps if we used client composition.
3222 if (hasClientComposition) {
3223 getRenderEngine().setColorTransform(mat4());
3224 getBE().mRenderEngine->disableScissor();
3225 display->finishBuffer();
3226 // Clear out error flags here so that we don't wait until next
3227 // composition to log.
3228 getRenderEngine().checkErrors();
3229 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003230 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003231}
3232
Chia-I Wu28e3a252018-09-07 12:05:02 -07003233void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003234 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003235 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003236}
3237
Dan Stoza7d89d062015-04-30 13:29:25 -07003238status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003239 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003240 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003241 const sp<Layer>& lbc,
3242 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003243{
Dan Stoza7d89d062015-04-30 13:29:25 -07003244 // add this layer to the current state list
3245 {
3246 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003247 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003248 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3249 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003250 return NO_MEMORY;
3251 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003252 if (parent == nullptr) {
3253 mCurrentState.layersSortedByZ.add(lbc);
3254 } else {
Robert Carr2e102c92018-10-23 12:11:15 -07003255 if (parent->isRemovedFromCurrentState()) {
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003256 ALOGE("addClientLayer called with a removed parent");
chaviw61626f22018-11-15 16:26:27 -08003257 lbc->onRemovedFromCurrentState();
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003258 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003259 parent->addChild(lbc);
3260 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003261
Yiwei Zhang243b3782018-05-15 17:40:04 -07003262 if (gbc != nullptr) {
3263 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3264 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3265 mMaxGraphicBufferProducerListSize,
3266 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3267 mGraphicBufferProducerList.size(),
3268 mMaxGraphicBufferProducerListSize, mNumLayers);
3269 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003270 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003271 }
3272
Mathias Agopian96f08192010-06-02 23:28:45 -07003273 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003274 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003275
Dan Stoza7d89d062015-04-30 13:29:25 -07003276 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003277}
3278
Robert Carr8d2711b2018-11-14 16:36:18 -08003279status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003280 Mutex::Autolock _l(mStateLock);
Robert Carr8d2711b2018-11-14 16:36:18 -08003281 return removeLayerLocked(mStateLock, layer);
chaviwca27f252018-02-06 16:46:39 -08003282}
Robert Carr7f9b8992017-03-10 11:08:39 -08003283
Robert Carr8d2711b2018-11-14 16:36:18 -08003284status_t SurfaceFlinger::removeLayerLocked(const Mutex& lock, const sp<Layer>& layer) {
chaviw5aedec92018-10-22 10:40:38 -07003285 if (layer->isLayerDetached()) {
3286 return NO_ERROR;
3287 }
3288
Robert Carr1f0a16a2016-10-24 16:27:39 -07003289 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003290 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003291 if (p != nullptr) {
Chia-I Wufae51c42017-06-15 12:53:59 -07003292 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003293 } else {
3294 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003295 }
3296
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003297 layer->onRemovedFromCurrentState();
Robert Carr2e102c92018-10-23 12:11:15 -07003298
3299 markLayerPendingRemovalLocked(lock, layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003300 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003301}
3302
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003303uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003304 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003305}
3306
Mathias Agopian3f844832013-08-07 21:24:32 -07003307uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003308 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003309}
3310
Mathias Agopian3f844832013-08-07 21:24:32 -07003311uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003312 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003313}
3314
3315uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003316 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003317 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003318 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003319 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003320 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003321 }
3322 return old;
3323}
3324
chaviwca27f252018-02-06 16:46:39 -08003325bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3326 for (const ComposerState& state : states) {
3327 // Here we need to check that the interface we're given is indeed
3328 // one of our own. A malicious client could give us a nullptr
3329 // IInterface, or one of its own or even one of our own but a
3330 // different type. All these situations would cause us to crash.
3331 if (state.client == nullptr) {
3332 return true;
3333 }
3334
3335 sp<IBinder> binder = IInterface::asBinder(state.client);
3336 if (binder == nullptr) {
3337 return true;
3338 }
3339
3340 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3341 return true;
3342 }
3343 }
3344 return false;
3345}
3346
Mathias Agopian8b33f032012-07-24 20:43:54 -07003347void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003348 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003349 const Vector<DisplayState>& displays,
3350 uint32_t flags)
3351{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003352 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003353 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003354 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003355
chaviwca27f252018-02-06 16:46:39 -08003356 if (containsAnyInvalidClientState(states)) {
3357 return;
3358 }
3359
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003360 if (flags & eAnimation) {
3361 // For window updates that are part of an animation we must wait for
3362 // previous animation "frames" to be handled.
3363 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003364 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003365 if (CC_UNLIKELY(err != NO_ERROR)) {
3366 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003367 // caller after a few seconds.
3368 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3369 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003370 mAnimTransactionPending = false;
3371 break;
3372 }
3373 }
3374 }
3375
chaviwca27f252018-02-06 16:46:39 -08003376 for (const DisplayState& display : displays) {
3377 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003378 }
3379
Marissa Walle2ffb422018-10-12 11:33:52 -07003380 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003381 for (const ComposerState& state : states) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003382 clientStateFlags |= setClientStateLocked(state);
chaviwca27f252018-02-06 16:46:39 -08003383 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003384 // If the state doesn't require a traversal and there are callbacks, send them now
3385 if (!(clientStateFlags & eTraversalNeeded)) {
3386 mTransactionCompletedThread.sendCallbacks();
3387 }
3388 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003389
3390 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3391 // as destroyed should only occur after setting all other states. This is to allow for a
3392 // child re-parent to happen before marking its original parent as destroyed (which would
3393 // then mark the child as destroyed).
3394 for (const ComposerState& state : states) {
3395 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003396 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003397
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003398 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3399 // anyway. This can be used as a flush mechanism for previous async transactions.
3400 // Empty animation transaction can be used to simulate back-pressure, so also force a
3401 // transaction for empty animation transactions.
3402 if (transactionFlags == 0 &&
3403 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003404 transactionFlags = eTransactionNeeded;
3405 }
3406
Mathias Agopian386aa982011-11-07 21:58:03 -08003407 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003408 if (mInterceptor->isEnabled()) {
3409 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003410 }
Irvel468051e2016-06-13 16:44:44 -07003411
Mathias Agopian386aa982011-11-07 21:58:03 -08003412 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003413 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3414 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003415 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003416
3417 // if this is a synchronous transaction, wait for it to take effect
3418 // before returning.
3419 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003420 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003421 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003422 if (flags & eAnimation) {
3423 mAnimTransactionPending = true;
3424 }
3425 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003426 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3427 if (CC_UNLIKELY(err != NO_ERROR)) {
3428 // just in case something goes wrong in SF, return to the
3429 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003430 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3431 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003432 break;
3433 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003434 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003435 }
3436}
3437
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003438uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3439 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3440 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003441
Mathias Agopiane57f2922012-08-09 16:29:12 -07003442 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003443 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3444
3445 const uint32_t what = s.what;
3446 if (what & DisplayState::eSurfaceChanged) {
3447 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3448 state.surface = s.surface;
3449 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003450 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003451 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003452 if (what & DisplayState::eLayerStackChanged) {
3453 if (state.layerStack != s.layerStack) {
3454 state.layerStack = s.layerStack;
3455 flags |= eDisplayTransactionNeeded;
3456 }
3457 }
3458 if (what & DisplayState::eDisplayProjectionChanged) {
3459 if (state.orientation != s.orientation) {
3460 state.orientation = s.orientation;
3461 flags |= eDisplayTransactionNeeded;
3462 }
3463 if (state.frame != s.frame) {
3464 state.frame = s.frame;
3465 flags |= eDisplayTransactionNeeded;
3466 }
3467 if (state.viewport != s.viewport) {
3468 state.viewport = s.viewport;
3469 flags |= eDisplayTransactionNeeded;
3470 }
3471 }
3472 if (what & DisplayState::eDisplaySizeChanged) {
3473 if (state.width != s.width) {
3474 state.width = s.width;
3475 flags |= eDisplayTransactionNeeded;
3476 }
3477 if (state.height != s.height) {
3478 state.height = s.height;
3479 flags |= eDisplayTransactionNeeded;
3480 }
3481 }
3482
Mathias Agopiane57f2922012-08-09 16:29:12 -07003483 return flags;
3484}
3485
Robert Carrd4ae7f32018-06-07 16:10:57 -07003486bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3487 IPCThreadState* ipc = IPCThreadState::self();
3488 const int pid = ipc->getCallingPid();
3489 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003490 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003491 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003492 return false;
3493 }
3494 return true;
3495}
3496
chaviwca27f252018-02-06 16:46:39 -08003497uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3498 const layer_state_t& s = composerState.state;
3499 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3500
Mathias Agopian13127d82013-03-05 17:47:11 -08003501 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003502 if (layer == nullptr) {
3503 return 0;
3504 }
3505
chaviw8b3871a2017-11-01 17:41:01 -07003506 uint32_t flags = 0;
3507
Garfield Tan8a3083e2018-12-03 13:21:07 -08003508 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003509 bool geometryAppliesWithResize =
3510 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003511
3512 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3513 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003514 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003515 layer->pushPendingState();
3516 }
3517
chaviw8b3871a2017-11-01 17:41:01 -07003518 if (what & layer_state_t::ePositionChanged) {
3519 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3520 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003521 }
chaviw8b3871a2017-11-01 17:41:01 -07003522 }
3523 if (what & layer_state_t::eLayerChanged) {
3524 // NOTE: index needs to be calculated before we update the state
3525 const auto& p = layer->getParent();
3526 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003527 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003528 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003529 mCurrentState.layersSortedByZ.removeAt(idx);
3530 mCurrentState.layersSortedByZ.add(layer);
3531 // we need traversal (state changed)
3532 // AND transaction (list changed)
3533 flags |= eTransactionNeeded|eTraversalNeeded;
3534 }
chaviw8b3871a2017-11-01 17:41:01 -07003535 } else {
3536 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003537 flags |= eTransactionNeeded|eTraversalNeeded;
3538 }
3539 }
chaviw8b3871a2017-11-01 17:41:01 -07003540 }
3541 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003542 // NOTE: index needs to be calculated before we update the state
3543 const auto& p = layer->getParent();
3544 if (p == nullptr) {
3545 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3546 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3547 mCurrentState.layersSortedByZ.removeAt(idx);
3548 mCurrentState.layersSortedByZ.add(layer);
3549 // we need traversal (state changed)
3550 // AND transaction (list changed)
3551 flags |= eTransactionNeeded|eTraversalNeeded;
3552 }
3553 } else {
3554 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3555 flags |= eTransactionNeeded|eTraversalNeeded;
3556 }
chaviw8b3871a2017-11-01 17:41:01 -07003557 }
3558 }
3559 if (what & layer_state_t::eSizeChanged) {
3560 if (layer->setSize(s.w, s.h)) {
3561 flags |= eTraversalNeeded;
3562 }
3563 }
3564 if (what & layer_state_t::eAlphaChanged) {
3565 if (layer->setAlpha(s.alpha))
3566 flags |= eTraversalNeeded;
3567 }
3568 if (what & layer_state_t::eColorChanged) {
3569 if (layer->setColor(s.color))
3570 flags |= eTraversalNeeded;
3571 }
Peiyong Lind3788632018-09-18 16:01:31 -07003572 if (what & layer_state_t::eColorTransformChanged) {
3573 if (layer->setColorTransform(s.colorTransform)) {
3574 flags |= eTraversalNeeded;
3575 }
3576 }
chaviw8b3871a2017-11-01 17:41:01 -07003577 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003578 // TODO: b/109894387
3579 //
3580 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3581 // rotation. To see the problem observe that if we have a square parent, and a child
3582 // of the same size, then we rotate the child 45 degrees around it's center, the child
3583 // must now be cropped to a non rectangular 8 sided region.
3584 //
3585 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3586 // private API, and the WindowManager only uses rotation in one case, which is on a top
3587 // level layer in which cropping is not an issue.
3588 //
3589 // However given that abuse of rotation matrices could lead to surfaces extending outside
3590 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3591 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3592 // transformations.
3593 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003594 flags |= eTraversalNeeded;
3595 }
3596 if (what & layer_state_t::eTransparentRegionChanged) {
3597 if (layer->setTransparentRegionHint(s.transparentRegion))
3598 flags |= eTraversalNeeded;
3599 }
3600 if (what & layer_state_t::eFlagsChanged) {
3601 if (layer->setFlags(s.flags, s.mask))
3602 flags |= eTraversalNeeded;
3603 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003604 if (what & layer_state_t::eCropChanged_legacy) {
3605 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003606 flags |= eTraversalNeeded;
3607 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003608 if (what & layer_state_t::eCornerRadiusChanged) {
3609 if (layer->setCornerRadius(s.cornerRadius))
3610 flags |= eTraversalNeeded;
3611 }
chaviw8b3871a2017-11-01 17:41:01 -07003612 if (what & layer_state_t::eLayerStackChanged) {
3613 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3614 // We only allow setting layer stacks for top level layers,
3615 // everything else inherits layer stack from its parent.
3616 if (layer->hasParent()) {
3617 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3618 layer->getName().string());
3619 } else if (idx < 0) {
3620 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3621 "that also does not appear in the top level layer list. Something"
3622 " has gone wrong.", layer->getName().string());
3623 } else if (layer->setLayerStack(s.layerStack)) {
3624 mCurrentState.layersSortedByZ.removeAt(idx);
3625 mCurrentState.layersSortedByZ.add(layer);
3626 // we need traversal (state changed)
3627 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003628 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003629 }
3630 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003631 if (what & layer_state_t::eDeferTransaction_legacy) {
3632 if (s.barrierHandle_legacy != nullptr) {
3633 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3634 } else if (s.barrierGbp_legacy != nullptr) {
3635 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003636 if (authenticateSurfaceTextureLocked(gbp)) {
3637 const auto& otherLayer =
3638 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003639 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003640 } else {
3641 ALOGE("Attempt to defer transaction to to an"
3642 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003643 }
3644 }
chaviw8b3871a2017-11-01 17:41:01 -07003645 // We don't trigger a traversal here because if no other state is
3646 // changed, we don't want this to cause any more work
3647 }
3648 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003649 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003650 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003651 if (!hadParent) {
3652 mCurrentState.layersSortedByZ.remove(layer);
3653 }
chaviw8b3871a2017-11-01 17:41:01 -07003654 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003655 }
chaviw8b3871a2017-11-01 17:41:01 -07003656 }
3657 if (what & layer_state_t::eReparentChildren) {
3658 if (layer->reparentChildren(s.reparentHandle)) {
3659 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003660 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003661 }
chaviw8b3871a2017-11-01 17:41:01 -07003662 if (what & layer_state_t::eDetachChildren) {
3663 layer->detachChildren();
3664 }
3665 if (what & layer_state_t::eOverrideScalingModeChanged) {
3666 layer->setOverrideScalingMode(s.overrideScalingMode);
3667 // We don't trigger a traversal here because if no other state is
3668 // changed, we don't want this to cause any more work
3669 }
Marissa Wall61c58622018-07-18 10:12:20 -07003670 if (what & layer_state_t::eTransformChanged) {
3671 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3672 }
3673 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3674 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3675 flags |= eTraversalNeeded;
3676 }
3677 if (what & layer_state_t::eCropChanged) {
3678 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3679 }
Marissa Wall861616d2018-10-22 12:52:23 -07003680 if (what & layer_state_t::eFrameChanged) {
3681 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3682 }
Marissa Wall61c58622018-07-18 10:12:20 -07003683 if (what & layer_state_t::eBufferChanged) {
3684 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3685 }
3686 if (what & layer_state_t::eAcquireFenceChanged) {
3687 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3688 }
3689 if (what & layer_state_t::eDataspaceChanged) {
3690 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3691 }
3692 if (what & layer_state_t::eHdrMetadataChanged) {
3693 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3694 }
3695 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3696 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3697 }
3698 if (what & layer_state_t::eApiChanged) {
3699 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3700 }
3701 if (what & layer_state_t::eSidebandStreamChanged) {
3702 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3703 }
Robert Carr720e5062018-07-30 17:45:14 -07003704 if (what & layer_state_t::eInputInfoChanged) {
3705 layer->setInputInfo(s.inputInfo);
3706 flags |= eTraversalNeeded;
3707 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003708 std::vector<sp<CallbackHandle>> callbackHandles;
3709 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
3710 mTransactionCompletedThread.run();
3711 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
3712 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3713 }
3714 }
3715 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3716 // Do not put anything that updates layer state or modifies flags after
3717 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003718 return flags;
3719}
3720
chaviwca27f252018-02-06 16:46:39 -08003721void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3722 const layer_state_t& state = composerState.state;
3723 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3724
3725 sp<Layer> layer(client->getLayerUser(state.surface));
3726 if (layer == nullptr) {
3727 return;
3728 }
3729
chaviwca27f252018-02-06 16:46:39 -08003730 if (state.what & layer_state_t::eDestroySurface) {
3731 removeLayerLocked(mStateLock, layer);
3732 }
3733}
3734
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003735status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003736 const String8& name,
3737 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003738 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003739 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003740 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003741{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003742 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003743 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003744 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003745 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003746 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003747
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003748 status_t result = NO_ERROR;
3749
3750 sp<Layer> layer;
3751
Cody Northropbc755282017-03-31 12:00:08 -06003752 String8 uniqueName = getUniqueLayerName(name);
3753
Mathias Agopian3165cc22012-08-08 19:42:09 -07003754 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003755 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003756 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3757 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003758
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003759 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003760 case ISurfaceComposerClient::eFXSurfaceBufferState:
3761 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3762 break;
chaviw13fdc492017-06-27 12:40:18 -07003763 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003764 // check if buffer size is set for color layer.
3765 if (w > 0 || h > 0) {
3766 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3767 int(w), int(h));
3768 return BAD_VALUE;
3769 }
3770
chaviw13fdc492017-06-27 12:40:18 -07003771 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003772 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003773 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003774 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003775 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003776 // check if buffer size is set for container layer.
3777 if (w > 0 || h > 0) {
3778 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3779 int(w), int(h));
3780 return BAD_VALUE;
3781 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07003782 result = createContainerLayer(client,
3783 uniqueName, w, h, flags,
3784 handle, &layer);
3785 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003786 default:
3787 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003788 break;
3789 }
3790
Dan Stoza7d89d062015-04-30 13:29:25 -07003791 if (result != NO_ERROR) {
3792 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003793 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003794
Chia-I Wuab0c3192017-08-01 11:29:00 -07003795 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3796 // TODO b/64227542
3797 if (windowType == 441731) {
3798 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3799 layer->setPrimaryDisplayOnly();
3800 }
3801
Albert Chaulk479c60c2017-01-27 14:21:34 -05003802 layer->setInfo(windowType, ownerUid);
3803
Robert Carr1f0a16a2016-10-24 16:27:39 -07003804 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003805 if (result != NO_ERROR) {
3806 return result;
3807 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003808 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003809
3810 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003811 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003812}
3813
Cody Northropbc755282017-03-31 12:00:08 -06003814String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3815{
3816 bool matchFound = true;
3817 uint32_t dupeCounter = 0;
3818
3819 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3820 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3821
Dan Stoza436ccf32018-06-21 12:10:12 -07003822 // Grab the state lock since we're accessing mCurrentState
3823 Mutex::Autolock lock(mStateLock);
3824
Cody Northropbc755282017-03-31 12:00:08 -06003825 // Loop over layers until we're sure there is no matching name
3826 while (matchFound) {
3827 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003828 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003829 if (layer->getName() == uniqueName) {
3830 matchFound = true;
3831 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3832 }
3833 });
3834 }
3835
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003836 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3837 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003838
3839 return uniqueName;
3840}
3841
Marissa Wallfd668622018-05-10 10:21:13 -07003842status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3843 uint32_t w, uint32_t h, uint32_t flags,
3844 PixelFormat& format, sp<IBinder>* handle,
3845 sp<IGraphicBufferProducer>* gbp,
3846 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003847 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003848 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003849 case PIXEL_FORMAT_TRANSPARENT:
3850 case PIXEL_FORMAT_TRANSLUCENT:
3851 format = PIXEL_FORMAT_RGBA_8888;
3852 break;
3853 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003854 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003855 break;
3856 }
3857
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003858 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07003859 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07003860 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003861 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003862 *handle = layer->getHandle();
3863 *gbp = layer->getProducer();
3864 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003865 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003866
Marissa Wallfd668622018-05-10 10:21:13 -07003867 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003868 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003869}
3870
Marissa Wall61c58622018-07-18 10:12:20 -07003871status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3872 uint32_t w, uint32_t h, uint32_t flags,
3873 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003874 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07003875 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07003876 *handle = layer->getHandle();
3877 *outLayer = layer;
3878
3879 return NO_ERROR;
3880}
3881
chaviw13fdc492017-06-27 12:40:18 -07003882status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003883 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003884 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003885{
Lloyd Pique90c115d2018-09-18 21:39:42 -07003886 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003887 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003888 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003889}
3890
Robert Carr6b3f6c52018-08-13 13:05:17 -07003891status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
3892 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3893 sp<IBinder>* handle, sp<Layer>* outLayer)
3894{
Lloyd Pique90c115d2018-09-18 21:39:42 -07003895 *outLayer =
3896 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07003897 *handle = (*outLayer)->getHandle();
3898 return NO_ERROR;
3899}
3900
3901
Mathias Agopianac9fa422013-02-11 16:40:36 -08003902status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003903{
Robert Carr9524cb32017-02-13 11:32:32 -08003904 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003905 status_t err = NO_ERROR;
3906 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003907 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003908 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003909 err = removeLayer(l);
3910 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3911 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003912 }
3913 return err;
3914}
3915
Robert Carr2e102c92018-10-23 12:11:15 -07003916void SurfaceFlinger::markLayerPendingRemovalLocked(const Mutex&, const sp<Layer>& layer) {
3917 mLayersPendingRemoval.add(layer);
3918 mLayersRemoved = true;
3919 setTransactionFlags(eTransactionNeeded);
3920}
3921
Robert Carr695d5282018-12-18 15:27:58 -08003922void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003923{
Robert Carr2e102c92018-10-23 12:11:15 -07003924 Mutex::Autolock lock(mStateLock);
3925 markLayerPendingRemovalLocked(mStateLock, layer);
Robert Carr695d5282018-12-18 15:27:58 -08003926 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00003927}
3928
Mathias Agopianb60314a2012-04-10 22:09:54 -07003929// ---------------------------------------------------------------------------
3930
Andy McFadden13a082e2012-08-24 10:16:42 -07003931void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003932 const auto displayToken = getInternalDisplayToken();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003933 if (!displayToken) return;
3934
Jesse Hall01e29052013-02-19 16:13:35 -08003935 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003936 Vector<ComposerState> state;
3937 Vector<DisplayState> displays;
3938 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003939 d.what = DisplayState::eDisplayProjectionChanged |
3940 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003941 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003942 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003943 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003944 d.frame.makeInvalid();
3945 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003946 d.width = 0;
3947 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003948 displays.add(d);
3949 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003950
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003951 const auto display = getDisplayDevice(displayToken);
3952 if (!display) return;
3953
Dominik Laskowskie9774092018-12-11 10:04:24 -08003954 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003955
Dominik Laskowski075d3172018-05-24 15:50:06 -07003956 const auto activeConfig = getHwComposer().getActiveConfig(*display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003957 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003958 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003959
Brian Andersond0010582017-03-07 13:20:31 -08003960 // Use phase of 0 since phase is not known.
3961 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07003962 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
3963 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003964}
3965
3966void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003967 // Async since we may be called from the main thread.
3968 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003969}
3970
Dominik Laskowskie9774092018-12-11 10:04:24 -08003971void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003972 if (display->isVirtual()) {
3973 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003974 return;
3975 }
3976
Dominik Laskowski075d3172018-05-24 15:50:06 -07003977 const auto displayId = display->getId();
3978 LOG_ALWAYS_FATAL_IF(!displayId);
3979
Dominik Laskowski34157762018-10-31 13:07:19 -07003980 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003981
3982 int currentMode = display->getPowerMode();
3983 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003984 return;
3985 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003986
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003987 display->setPowerMode(mode);
3988
Lloyd Pique4dccc412018-01-22 17:21:36 -08003989 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08003990 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07003991 }
3992
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003993 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003994 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07003995 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003996 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07003997 if (mUseScheduler) {
3998 mScheduler->onScreenAcquired(mAppConnectionHandle);
3999 } else {
4000 mEventThread->onScreenAcquired();
4001 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07004002 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004003 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004004
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004005 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004006 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004007 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004008
4009 struct sched_param param = {0};
4010 param.sched_priority = 1;
4011 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4012 ALOGW("Couldn't set SCHED_FIFO on display on");
4013 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004014 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004015 // Turn off the display
4016 struct sched_param param = {0};
4017 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4018 ALOGW("Couldn't set SCHED_OTHER on display off");
4019 }
4020
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004021 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07004022 if (mUseScheduler) {
4023 mScheduler->disableHardwareVsync(true);
4024 } else {
4025 disableHardwareVsync(true); // also cancels any in-progress resync
4026 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004027 if (mUseScheduler) {
4028 mScheduler->onScreenReleased(mAppConnectionHandle);
4029 } else {
4030 mEventThread->onScreenReleased();
4031 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004032 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004033
Dominik Laskowski075d3172018-05-24 15:50:06 -07004034 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004035 mVisibleRegionsDirty = true;
4036 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004037 } else if (mode == HWC_POWER_MODE_DOZE ||
4038 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004039 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004040 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004041 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004042 if (mUseScheduler) {
4043 mScheduler->onScreenAcquired(mAppConnectionHandle);
4044 } else {
4045 mEventThread->onScreenAcquired();
4046 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004047 resyncToHardwareVsync(true);
4048 }
4049 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4050 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004051 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07004052 if (mUseScheduler) {
4053 mScheduler->disableHardwareVsync(true);
4054 } else {
4055 disableHardwareVsync(true); // also cancels any in-progress resync
4056 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004057 if (mUseScheduler) {
4058 mScheduler->onScreenReleased(mAppConnectionHandle);
4059 } else {
4060 mEventThread->onScreenReleased();
4061 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004062 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004063 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004064 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004065 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004066 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004067 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004068
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004069 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004070 mTimeStats->setPowerMode(mode);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004071 }
4072
Dominik Laskowski34157762018-10-31 13:07:19 -07004073 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004074}
4075
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004076void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004077 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004078 const auto display = getDisplayDevice(displayToken);
4079 if (!display) {
4080 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4081 displayToken.get());
4082 } else if (display->isVirtual()) {
4083 ALOGW("Attempt to set power mode %d for virtual display", mode);
4084 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004085 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004086 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004087 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004088}
4089
4090// ---------------------------------------------------------------------------
4091
Lloyd Pique755e3192018-01-31 16:46:15 -08004092status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
4093 NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004094 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004095
Mathias Agopianbd115332013-04-18 16:41:04 -07004096 IPCThreadState* ipc = IPCThreadState::self();
4097 const int pid = ipc->getCallingPid();
4098 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004099
Mathias Agopianbd115332013-04-18 16:41:04 -07004100 if ((uid != AID_SHELL) &&
4101 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004102 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4103 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004104 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004105 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004106 // (this would indicate SF is stuck, but we want to be able to
4107 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004108 status_t err = mStateLock.timedLock(s2ns(1));
4109 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004110 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004111 StringAppendF(&result,
4112 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4113 "(no locks held)\n",
4114 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004115 }
4116
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004117 bool dumpAll = true;
4118 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004119 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004120
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004121 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004122 if ((index < numArgs) &&
4123 (args[index] == String16("--list"))) {
4124 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004125 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004126 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004127 }
4128
4129 if ((index < numArgs) &&
4130 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004131 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004132 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004133 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004134 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004135
4136 if ((index < numArgs) &&
4137 (args[index] == String16("--latency-clear"))) {
4138 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004139 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004140 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004141 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004142
4143 if ((index < numArgs) &&
4144 (args[index] == String16("--dispsync"))) {
4145 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004146 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004147 dumpAll = false;
4148 }
Dan Stozab90cf072015-03-05 11:05:59 -08004149
4150 if ((index < numArgs) &&
4151 (args[index] == String16("--static-screen"))) {
4152 index++;
4153 dumpStaticScreenStats(result);
4154 dumpAll = false;
4155 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004156
4157 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004158 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004159 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004160 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004161 dumpAll = false;
4162 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004163
4164 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4165 index++;
4166 dumpWideColorInfo(result);
4167 dumpAll = false;
4168 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004169
4170 if ((index < numArgs) &&
4171 (args[index] == String16("--enable-layer-stats"))) {
4172 index++;
4173 mLayerStats.enable();
4174 dumpAll = false;
4175 }
4176
4177 if ((index < numArgs) &&
4178 (args[index] == String16("--disable-layer-stats"))) {
4179 index++;
4180 mLayerStats.disable();
4181 dumpAll = false;
4182 }
4183
4184 if ((index < numArgs) &&
4185 (args[index] == String16("--clear-layer-stats"))) {
4186 index++;
4187 mLayerStats.clear();
4188 dumpAll = false;
4189 }
4190
4191 if ((index < numArgs) &&
4192 (args[index] == String16("--dump-layer-stats"))) {
4193 index++;
4194 mLayerStats.dump(result);
4195 dumpAll = false;
4196 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004197
4198 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004199 (args[index] == String16("--frame-composition"))) {
4200 index++;
4201 dumpFrameCompositionInfo(result);
4202 dumpAll = false;
4203 }
4204
4205 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004206 (args[index] == String16("--display-identification"))) {
4207 index++;
4208 dumpDisplayIdentificationData(result);
4209 dumpAll = false;
4210 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004211
4212 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4213 index++;
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004214 mTimeStats->parseArgs(asProto, args, index, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004215 dumpAll = false;
4216 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004217 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004218
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004219 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004220 if (asProto) {
4221 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4222 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4223 } else {
4224 dumpAllLocked(args, index, result);
4225 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004226 }
4227
Mathias Agopian9795c422009-08-26 16:36:26 -07004228 if (locked) {
4229 mStateLock.unlock();
4230 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004231 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004232 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004233 return NO_ERROR;
4234}
4235
Yiwei Zhang5434a782018-12-05 18:06:32 -08004236void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */, size_t& /* index */,
4237 std::string& result) const {
4238 mCurrentState.traverseInZOrder(
4239 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004240}
4241
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004242void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004243 std::string& result) const {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004244 String8 name;
4245 if (index < args.size()) {
4246 name = String8(args[index]);
4247 index++;
4248 }
4249
Dominik Laskowski075d3172018-05-24 15:50:06 -07004250 if (const auto displayId = getInternalDisplayId();
4251 displayId && getHwComposer().isConnected(*displayId)) {
4252 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004253 const nsecs_t period = activeConfig->getVsyncPeriod();
Yiwei Zhang5434a782018-12-05 18:06:32 -08004254 StringAppendF(&result, "%" PRId64 "\n", period);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004255 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004256
4257 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004258 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004259 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004260 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004261 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004262 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004263 }
Robert Carr2047fae2016-11-28 14:09:09 -08004264 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004265 }
4266}
4267
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004268void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004269 std::string& /* result */) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004270 String8 name;
4271 if (index < args.size()) {
4272 name = String8(args[index]);
4273 index++;
4274 }
4275
Robert Carr2047fae2016-11-28 14:09:09 -08004276 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004277 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004278 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004279 }
Robert Carr2047fae2016-11-28 14:09:09 -08004280 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004281
Svetoslavd85084b2014-03-20 10:28:31 -07004282 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004283}
4284
Jamie Gennis6547ff42013-07-16 20:12:42 -07004285// This should only be called from the main thread. Otherwise it would need
4286// the lock and should use mCurrentState rather than mDrawingState.
4287void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004288 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004289 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004290 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004291
4292 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4293}
4294
Yiwei Zhang5434a782018-12-05 18:06:32 -08004295void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004296 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004297
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004298 if (isLayerTripleBufferingDisabled())
4299 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004300
Yiwei Zhang5434a782018-12-05 18:06:32 -08004301 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4302 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4303 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4304 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4305 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4306 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004307 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004308}
4309
Yiwei Zhang5434a782018-12-05 18:06:32 -08004310void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4311 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004312 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4313 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004314 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004315 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004316 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004317 }
David Sodman4a36e932017-11-07 14:29:47 -08004318 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004319 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004320 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004321 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4322 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004323}
4324
Dan Stozae77c7662016-05-13 11:37:28 -07004325void SurfaceFlinger::recordBufferingStats(const char* layerName,
4326 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004327 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4328 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004329 for (const auto& segment : history) {
4330 if (!segment.usedThirdBuffer) {
4331 stats.twoBufferTime += segment.totalTime;
4332 }
4333 if (segment.occupancyAverage < 1.0f) {
4334 stats.doubleBufferedTime += segment.totalTime;
4335 } else if (segment.occupancyAverage < 2.0f) {
4336 stats.tripleBufferedTime += segment.totalTime;
4337 }
4338 ++stats.numSegments;
4339 stats.totalTime += segment.totalTime;
4340 }
4341}
4342
Yiwei Zhang5434a782018-12-05 18:06:32 -08004343void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4344 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004345
4346 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4347 const size_t count = currentLayers.size();
4348 for (size_t i=0 ; i<count ; i++) {
4349 currentLayers[i]->dumpFrameEvents(result);
4350 }
4351}
4352
Yiwei Zhang5434a782018-12-05 18:06:32 -08004353void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004354 result.append("Buffering stats:\n");
4355 result.append(" [Layer name] <Active time> <Two buffer> "
4356 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004357 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004358 typedef std::tuple<std::string, float, float, float> BufferTuple;
4359 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004360 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004361 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004362 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004363 if (stats.numSegments == 0) {
4364 continue;
4365 }
4366 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4367 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4368 stats.totalTime;
4369 float doubleBufferRatio = static_cast<float>(
4370 stats.doubleBufferedTime) / stats.totalTime;
4371 float tripleBufferRatio = static_cast<float>(
4372 stats.tripleBufferedTime) / stats.totalTime;
4373 sorted.insert({activeTime, {name, twoBufferRatio,
4374 doubleBufferRatio, tripleBufferRatio}});
4375 }
4376 for (const auto& sortedPair : sorted) {
4377 float activeTime = sortedPair.first;
4378 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004379 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4380 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004381 }
4382 result.append("\n");
4383}
4384
Yiwei Zhang5434a782018-12-05 18:06:32 -08004385void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004386 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004387 const auto displayId = display->getId();
4388 if (!displayId) {
4389 continue;
4390 }
4391 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004392 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004393 continue;
4394 }
4395
Yiwei Zhang5434a782018-12-05 18:06:32 -08004396 StringAppendF(&result,
4397 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4398 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004399 uint8_t port;
4400 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004401 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004402 result.append("no identification data\n");
4403 continue;
4404 }
4405
4406 if (!isEdid(data)) {
4407 result.append("unknown identification data: ");
4408 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004409 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004410 }
4411 result.append("\n");
4412 continue;
4413 }
4414
4415 const auto edid = parseEdid(data);
4416 if (!edid) {
4417 result.append("invalid EDID: ");
4418 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004419 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004420 }
4421 result.append("\n");
4422 continue;
4423 }
4424
Yiwei Zhang5434a782018-12-05 18:06:32 -08004425 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004426 result.append(edid->displayName.data(), edid->displayName.length());
4427 result.append("\"\n");
4428 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004429}
4430
Yiwei Zhang5434a782018-12-05 18:06:32 -08004431void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4432 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4433 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4434 StringAppendF(&result, "DisplayColorSetting: %s\n",
4435 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004436
4437 // TODO: print out if wide-color mode is active or not
4438
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004439 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004440 const auto displayId = display->getId();
4441 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004442 continue;
4443 }
4444
Yiwei Zhang5434a782018-12-05 18:06:32 -08004445 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004446 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004447 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004448 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004449 }
4450
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004451 ColorMode currentMode = display->getActiveColorMode();
Yiwei Zhang5434a782018-12-05 18:06:32 -08004452 StringAppendF(&result, " Current color mode: %s (%d)\n",
4453 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004454 }
4455 result.append("\n");
4456}
4457
Yiwei Zhang5434a782018-12-05 18:06:32 -08004458void SurfaceFlinger::dumpFrameCompositionInfo(std::string& result) const {
David Sodman7e4ae112018-02-09 15:02:28 -08004459 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004460 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4461 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004462 continue;
4463 }
4464
Dominik Laskowski05275f12018-11-01 15:03:24 -07004465 const auto& compositionInfoList = it->second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004466 StringAppendF(&result, "%s\n", display->getDebugName().c_str());
4467 StringAppendF(&result, "numComponents: %zu\n", compositionInfoList.size());
David Sodman7e4ae112018-02-09 15:02:28 -08004468 for (const auto& compositionInfo : compositionInfoList) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004469 compositionInfo.dump(result, nullptr);
4470 result.append("\n");
David Sodman7e4ae112018-02-09 15:02:28 -08004471 }
4472 }
David Sodman7e4ae112018-02-09 15:02:28 -08004473}
4474
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004475LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004476 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004477 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4478 const State& state = useDrawing ? mDrawingState : mCurrentState;
4479 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004480 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004481 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004482 });
4483
4484 return layersProto;
4485}
4486
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004487LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004488 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004489
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004490 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004491 resolution->set_w(display.getWidth());
4492 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004493
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004494 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4495 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4496 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004497
Dominik Laskowski075d3172018-05-24 15:50:06 -07004498 const auto displayId = display.getId();
4499 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004500 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004501 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004502 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004503 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004504 }
4505 });
4506
4507 return layersProto;
4508}
4509
Mathias Agopian74d211a2013-04-22 16:55:35 +02004510void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004511 std::string& result) const {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004512 bool colorize = false;
4513 if (index < args.size()
4514 && (args[index] == String16("--color"))) {
4515 colorize = true;
4516 index++;
4517 }
4518
4519 Colorizer colorizer(colorize);
4520
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004521 // figure out if we're stuck somewhere
4522 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004523 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004524 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4525
4526 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004527 * Dump library configuration.
4528 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004529
4530 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004531 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004532 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004533 appendSfConfigString(result);
4534 appendUiConfigString(result);
4535 appendGuiConfigString(result);
4536 result.append("\n");
4537
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004538 result.append("\nDisplay identification data:\n");
4539 dumpDisplayIdentificationData(result);
4540
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004541 result.append("\nWide-Color information:\n");
4542 dumpWideColorInfo(result);
4543
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004544 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004545 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004546 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004547 result.append(SyncFeatures::getInstance().toString());
4548 result.append("\n");
4549
Andy McFadden41d67d72014-04-25 16:58:34 -07004550 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004551 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004552 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004553
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004554 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4555 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004556 if (const auto displayId = getInternalDisplayId();
4557 displayId && getHwComposer().isConnected(*displayId)) {
4558 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004559 StringAppendF(&result,
4560 "Display %s: app phase %" PRId64 " ns, "
4561 "sf phase %" PRId64 " ns, "
4562 "early app phase %" PRId64 " ns, "
4563 "early sf phase %" PRId64 " ns, "
4564 "early app gl phase %" PRId64 " ns, "
4565 "early sf gl phase %" PRId64 " ns, "
4566 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4567 to_string(*displayId).c_str(), vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
4568 appEarlyOffset, sfEarlyOffset, appEarlyGlOffset, sfEarlyGlOffset,
4569 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004570 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004571 result.append("\n");
4572
Dan Stozab90cf072015-03-05 11:05:59 -08004573 // Dump static screen stats
4574 result.append("\n");
4575 dumpStaticScreenStats(result);
4576 result.append("\n");
4577
Yiwei Zhang5434a782018-12-05 18:06:32 -08004578 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004579
Dan Stozae77c7662016-05-13 11:37:28 -07004580 dumpBufferingStats(result);
4581
Andy McFadden4803b742012-09-24 19:07:20 -07004582 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004583 * Dump the visible layer list
4584 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004585 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004586 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4587 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4588 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004589 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004590
Chia-I Wu2f884132018-09-13 15:17:58 -07004591 {
4592 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4593 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004594 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004595 result.append("\n");
4596 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004597
David Sodman7e4ae112018-02-09 15:02:28 -08004598 result.append("\nFrame-Composition information:\n");
4599 dumpFrameCompositionInfo(result);
4600 result.append("\n");
4601
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004602 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004603 * Dump Display state
4604 */
4605
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004606 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004607 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004608 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004609 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004610 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004611 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004612 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004613
4614 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004615 * Dump SurfaceFlinger global state
4616 */
4617
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004618 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004619 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004620 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004621
David Sodmanbc815282017-11-05 18:57:52 -08004622 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004623
Dominik Laskowski075d3172018-05-24 15:50:06 -07004624 if (const auto display = getDefaultDisplayDeviceLocked()) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004625 display->undefinedRegion.dump(result, "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004626 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4627 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004628 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004629 StringAppendF(&result,
4630 " transaction-flags : %08x\n"
4631 " gpu_to_cpu_unsupported : %d\n",
4632 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004633
Dominik Laskowski075d3172018-05-24 15:50:06 -07004634 if (const auto displayId = getInternalDisplayId();
4635 displayId && getHwComposer().isConnected(*displayId)) {
4636 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004637 StringAppendF(&result,
4638 " refresh-rate : %f fps\n"
4639 " x-dpi : %f\n"
4640 " y-dpi : %f\n",
4641 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4642 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004643 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004644
Yiwei Zhang5434a782018-12-05 18:06:32 -08004645 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004646
Yiwei Zhang5434a782018-12-05 18:06:32 -08004647 StringAppendF(&result, " use Scheduler: %s\n", mUseScheduler ? "true" : "false");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004648 /*
4649 * VSYNC state
4650 */
Ana Krulec98b5b242018-08-10 15:03:23 -07004651 if (mUseScheduler) {
4652 mScheduler->dump(mAppConnectionHandle, result);
4653 } else {
4654 mEventThread->dump(result);
4655 }
Dan Stozae22aec72016-08-01 13:20:59 -07004656 result.append("\n");
4657
4658 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004659 * Tracing state
4660 */
4661 mTracing.dump(result);
4662 result.append("\n");
4663
4664 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004665 * HWC layer minidump
4666 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004667 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004668 const auto displayId = display->getId();
4669 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004670 continue;
4671 }
4672
Yiwei Zhang5434a782018-12-05 18:06:32 -08004673 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004674 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004675 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004676 result.append("\n");
4677 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004678
4679 /*
4680 * Dump HWComposer state
4681 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004682 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004683 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004684 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004685 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004686 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004687 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004688
4689 /*
4690 * Dump gralloc state
4691 */
4692 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4693 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004694
4695 /*
4696 * Dump VrFlinger state if in use.
4697 */
4698 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4699 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004700 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004701 result.append("\n");
4702 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004703}
4704
Dominik Laskowski075d3172018-05-24 15:50:06 -07004705const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004706 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004707 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004708 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004709 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004710 }
4711 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004712
Dominik Laskowski34157762018-10-31 13:07:19 -07004713 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004714 static const Vector<sp<Layer>> empty;
4715 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004716}
4717
Keun young Park63f165f2012-08-31 10:53:36 -07004718bool SurfaceFlinger::startDdmConnection()
4719{
4720 void* libddmconnection_dso =
4721 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4722 if (!libddmconnection_dso) {
4723 return false;
4724 }
4725 void (*DdmConnection_start)(const char* name);
4726 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004727 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004728 if (!DdmConnection_start) {
4729 dlclose(libddmconnection_dso);
4730 return false;
4731 }
4732 (*DdmConnection_start)(getServiceName());
4733 return true;
4734}
4735
Chia-I Wu28f320b2018-05-03 11:02:56 -07004736void SurfaceFlinger::updateColorMatrixLocked() {
4737 mat4 colorMatrix;
4738 if (mGlobalSaturationFactor != 1.0f) {
4739 // Rec.709 luma coefficients
4740 float3 luminance{0.213f, 0.715f, 0.072f};
4741 luminance *= 1.0f - mGlobalSaturationFactor;
4742 mat4 saturationMatrix = mat4(
4743 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4744 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4745 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4746 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4747 );
4748 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4749 } else {
4750 colorMatrix = mClientColorMatrix * mDaltonizer();
4751 }
4752
4753 if (mCurrentState.colorMatrix != colorMatrix) {
4754 mCurrentState.colorMatrix = colorMatrix;
4755 mCurrentState.colorMatrixChanged = true;
4756 setTransactionFlags(eTransactionNeeded);
4757 }
4758}
4759
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004760status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004761#pragma clang diagnostic push
4762#pragma clang diagnostic error "-Wswitch-enum"
4763 switch (static_cast<ISurfaceComposerTag>(code)) {
4764 // These methods should at minimum make sure that the client requested
4765 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004766 case BOOT_FINISHED:
4767 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004768 case CREATE_CONNECTION:
4769 case CREATE_DISPLAY:
4770 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004771 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004772 case GET_ACTIVE_COLOR_MODE:
4773 case GET_ANIMATION_FRAME_STATS:
4774 case GET_HDR_CAPABILITIES:
4775 case SET_ACTIVE_CONFIG:
4776 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004777 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004778 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004779 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004780 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4781 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004782 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4783 IPCThreadState* ipc = IPCThreadState::self();
4784 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4785 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004786 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004787 }
Robert Carr1db73f62016-12-21 12:58:51 -08004788 return OK;
4789 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004790 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004791 IPCThreadState* ipc = IPCThreadState::self();
4792 const int pid = ipc->getCallingPid();
4793 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004794 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4795 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004796 return PERMISSION_DENIED;
4797 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004798 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004799 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004800 // Used by apps to hook Choreographer to SurfaceFlinger.
4801 case CREATE_DISPLAY_EVENT_CONNECTION:
4802 // The following calls are currently used by clients that do not
4803 // request necessary permissions. However, they do not expose any secret
4804 // information, so it is OK to pass them.
4805 case AUTHENTICATE_SURFACE:
4806 case GET_ACTIVE_CONFIG:
4807 case GET_BUILT_IN_DISPLAY:
4808 case GET_DISPLAY_COLOR_MODES:
4809 case GET_DISPLAY_CONFIGS:
4810 case GET_DISPLAY_STATS:
4811 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4812 // Calling setTransactionState is safe, because you need to have been
4813 // granted a reference to Client* and Handle* to do anything with it.
4814 case SET_TRANSACTION_STATE:
4815 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
Peiyong Lin0256f722018-08-31 15:45:10 -07004816 case CREATE_SCOPED_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004817 case GET_COLOR_MANAGEMENT:
Peiyong Lin0256f722018-08-31 15:45:10 -07004818 case GET_COMPOSITION_PREFERENCE: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004819 return OK;
4820 }
4821 case CAPTURE_LAYERS:
4822 case CAPTURE_SCREEN: {
4823 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004824 IPCThreadState* ipc = IPCThreadState::self();
4825 const int pid = ipc->getCallingPid();
4826 const int uid = ipc->getCallingUid();
4827 if ((uid != AID_GRAPHICS) &&
4828 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4829 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4830 return PERMISSION_DENIED;
4831 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004832 return OK;
4833 }
4834 // The following codes are deprecated and should never be allowed to access SF.
4835 case CONNECT_DISPLAY_UNUSED:
4836 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4837 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4838 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004839 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004840 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004841
4842 // These codes are used for the IBinder protocol to either interrogate the recipient
4843 // side of the transaction for its canonical interface descriptor or to dump its state.
4844 // We let them pass by default.
4845 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4846 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4847 code == IBinder::SYSPROPS_TRANSACTION) {
4848 return OK;
4849 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004850 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004851 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08004852 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004853 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4854 return OK;
4855 }
4856 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4857 return PERMISSION_DENIED;
4858#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004859}
4860
Ana Krulec13be8ad2018-08-21 02:43:56 +00004861status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4862 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004863 status_t credentialCheck = CheckTransactCodeCredentials(code);
4864 if (credentialCheck != OK) {
4865 return credentialCheck;
4866 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004867
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004868 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4869 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004870 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004871 IPCThreadState* ipc = IPCThreadState::self();
4872 const int uid = ipc->getCallingUid();
4873 if (CC_UNLIKELY(uid != AID_SYSTEM
4874 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004875 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004876 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004877 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004878 return PERMISSION_DENIED;
4879 }
4880 int n;
4881 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004882 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004883 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004884 return NO_ERROR;
4885 case 1002: // SHOW_UPDATES
4886 n = data.readInt32();
4887 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004888 invalidateHwcGeometry();
4889 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004890 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004891 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004892 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004893 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004894 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004895 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004896 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004897 setTransactionFlags(
4898 eTransactionNeeded|
4899 eDisplayTransactionNeeded|
4900 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004901 return NO_ERROR;
4902 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004903 case 1006:{ // send empty update
4904 signalRefresh();
4905 return NO_ERROR;
4906 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004907 case 1008: // toggle use of hw composer
4908 n = data.readInt32();
4909 mDebugDisableHWC = n ? 1 : 0;
4910 invalidateHwcGeometry();
4911 repaintEverything();
4912 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004913 case 1009: // toggle use of transform hint
4914 n = data.readInt32();
4915 mDebugDisableTransformHint = n ? 1 : 0;
4916 invalidateHwcGeometry();
4917 repaintEverything();
4918 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004919 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004920 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004921 reply->writeInt32(0);
4922 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004923 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004924 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004925 return NO_ERROR;
4926 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004927 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004928 if (!display) {
4929 return NAME_NOT_FOUND;
4930 }
4931
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004932 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004933 return NO_ERROR;
4934 }
4935 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004936 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004937 // daltonize
4938 n = data.readInt32();
4939 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004940 case 1:
4941 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4942 break;
4943 case 2:
4944 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4945 break;
4946 case 3:
4947 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4948 break;
4949 default:
4950 mDaltonizer.setType(ColorBlindnessType::None);
4951 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004952 }
4953 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004954 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004955 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004956 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004957 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004958
4959 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004960 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004961 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004962 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004963 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004964 // apply a color matrix
4965 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004966 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004967 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004968 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004969 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004970 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004971 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004972 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004973 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004974 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004975 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004976
4977 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4978 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004979 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004980 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4981 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4982 }
4983
Chia-I Wu28f320b2018-05-03 11:02:56 -07004984 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004985 return NO_ERROR;
4986 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004987 // This is an experimental interface
4988 // Needs to be shifted to proper binder interface when we productize
4989 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004990 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07004991 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07004992 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004993 return NO_ERROR;
4994 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004995 case 1017: {
4996 n = data.readInt32();
4997 mForceFullDamage = static_cast<bool>(n);
4998 return NO_ERROR;
4999 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005000 case 1018: { // Modify Choreographer's phase offset
5001 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005002 if (mUseScheduler) {
5003 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5004 } else {
5005 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5006 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005007 return NO_ERROR;
5008 }
5009 case 1019: { // Modify SurfaceFlinger's phase offset
5010 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005011 if (mUseScheduler) {
5012 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5013 } else {
5014 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5015 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005016 return NO_ERROR;
5017 }
Irvel468051e2016-06-13 16:44:44 -07005018 case 1020: { // Layer updates interceptor
5019 n = data.readInt32();
5020 if (n) {
5021 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005022 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005023 }
5024 else{
5025 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005026 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005027 }
5028 return NO_ERROR;
5029 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005030 case 1021: { // Disable HWC virtual displays
5031 n = data.readInt32();
5032 mUseHwcVirtualDisplays = !n;
5033 return NO_ERROR;
5034 }
Romain Guy0147a172017-06-01 13:53:56 -07005035 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005036 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005037 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005038
Chia-I Wu28f320b2018-05-03 11:02:56 -07005039 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005040 return NO_ERROR;
5041 }
Romain Guy54f154a2017-10-24 21:40:32 +01005042 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005043 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005044 invalidateHwcGeometry();
5045 repaintEverything();
5046 return NO_ERROR;
5047 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005048 // Deprecate, use 1030 to check whether the device is color managed.
5049 case 1024: {
5050 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005051 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005052 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005053 n = data.readInt32();
5054 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005055 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005056 mTracing.enable();
5057 doTracing("tracing.enable");
5058 reply->writeInt32(NO_ERROR);
5059 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005060 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005061 status_t err = mTracing.disable();
5062 reply->writeInt32(err);
5063 }
5064 return NO_ERROR;
5065 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005066 case 1026: { // Get layer tracing status
5067 reply->writeBool(mTracing.isEnabled());
5068 return NO_ERROR;
5069 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005070 // Is a DisplayColorSetting supported?
5071 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005072 const auto display = getDefaultDisplayDevice();
5073 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005074 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005075 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005076
5077 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5078 switch (setting) {
5079 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005080 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005081 break;
5082 case DisplayColorSetting::UNMANAGED:
5083 reply->writeBool(true);
5084 break;
5085 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005086 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005087 break;
5088 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005089 reply->writeBool(
5090 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005091 break;
5092 }
5093 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005094 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005095 // Is VrFlinger active?
5096 case 1028: {
5097 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005098 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005099 return NO_ERROR;
5100 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005101 // Is device color managed?
5102 case 1030: {
5103 reply->writeBool(useColorManagement);
5104 return NO_ERROR;
5105 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005106 // Override default composition data space
5107 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5108 // && adb shell stop zygote && adb shell start zygote
5109 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5110 // adb shell stop zygote && adb shell start zygote
5111 case 1031: {
5112 Mutex::Autolock _l(mStateLock);
5113 n = data.readInt32();
5114 if (n) {
5115 n = data.readInt32();
5116 if (n) {
5117 Dataspace dataspace = static_cast<Dataspace>(n);
5118 if (!validateCompositionDataspace(dataspace)) {
5119 return BAD_VALUE;
5120 }
5121 mDefaultCompositionDataspace = dataspace;
5122 }
5123 n = data.readInt32();
5124 if (n) {
5125 Dataspace dataspace = static_cast<Dataspace>(n);
5126 if (!validateCompositionDataspace(dataspace)) {
5127 return BAD_VALUE;
5128 }
5129 mWideColorGamutCompositionDataspace = dataspace;
5130 }
5131 } else {
5132 // restore composition data space.
5133 mDefaultCompositionDataspace = defaultCompositionDataspace;
5134 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5135 }
5136 return NO_ERROR;
5137 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005138 }
5139 }
5140 return err;
5141}
5142
Steven Thomas6d8110b2017-08-31 18:24:21 -07005143void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005144 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005145 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005146}
5147
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005148// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5149class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005150public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005151 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5152 ~WindowDisconnector() {
5153 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005154 }
5155
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005156private:
5157 ANativeWindow* mWindow;
5158 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005159};
5160
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005161status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005162 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5163 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005164 uint32_t reqWidth, uint32_t reqHeight,
5165 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005166 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005167 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005168
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005169 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005170
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005171 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5172
Chia-I Wu20261cb2018-08-23 12:55:44 -07005173 sp<DisplayDevice> display;
5174 {
5175 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005176
Chia-I Wu20261cb2018-08-23 12:55:44 -07005177 display = getDisplayDeviceLocked(displayToken);
5178 if (!display) return BAD_VALUE;
5179
Chia-I Wucb023152018-08-28 12:57:23 -07005180 // set the requested width/height to the logical display viewport size
5181 // by default
5182 if (reqWidth == 0 || reqHeight == 0) {
5183 reqWidth = uint32_t(display->getViewport().width());
5184 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005185 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005186 }
5187
Peiyong Lin0e003c92018-09-17 11:09:51 -07005188 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5189 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005190
5191 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005192 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005193 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5194 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005195}
5196
5197status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005198 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5199 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005200 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005201 ATRACE_CALL();
5202
5203 class LayerRenderArea : public RenderArea {
5204 public:
Robert Carr578038f2018-03-09 12:25:24 -08005205 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005206 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5207 bool childrenOnly)
5208 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005209 mLayer(layer),
5210 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005211 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005212 mFlinger(flinger),
5213 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005214 const ui::Transform& getTransform() const override { return mTransform; }
Ady Abraham83729882018-12-07 12:26:48 -08005215 Rect getBounds() const override { return mLayer->getBufferSize(StateSet::Drawing); }
Marissa Wall61c58622018-07-18 10:12:20 -07005216 int getHeight() const override {
Ady Abraham83729882018-12-07 12:26:48 -08005217 return mLayer->getBufferSize(StateSet::Drawing).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005218 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005219 int getWidth() const override {
Ady Abraham83729882018-12-07 12:26:48 -08005220 return mLayer->getBufferSize(StateSet::Drawing).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005221 }
chaviwa76b2712017-09-20 12:02:26 -07005222 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005223 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005224 Rect getSourceCrop() const override {
5225 if (mCrop.isEmpty()) {
5226 return getBounds();
5227 } else {
5228 return mCrop;
5229 }
5230 }
Robert Carr578038f2018-03-09 12:25:24 -08005231 class ReparentForDrawing {
5232 public:
5233 const sp<Layer>& oldParent;
5234 const sp<Layer>& newParent;
5235
5236 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5237 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005238 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005239 }
Robert Carr15eae092018-03-23 13:43:53 -07005240 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005241 };
5242
5243 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005244 const Rect sourceCrop = getSourceCrop();
5245 // no need to check rotation because there is none
5246 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5247 sourceCrop.height() != getReqHeight();
5248
Robert Carr578038f2018-03-09 12:25:24 -08005249 if (!mChildrenOnly) {
5250 mTransform = mLayer->getTransform().inverse();
5251 drawLayers();
5252 } else {
5253 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005254 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005255 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5256 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005257
5258 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5259 drawLayers();
5260 }
5261 }
chaviwa76b2712017-09-20 12:02:26 -07005262
chaviwa76b2712017-09-20 12:02:26 -07005263 private:
chaviw7206d492017-11-10 16:16:12 -08005264 const sp<Layer> mLayer;
5265 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005266
5267 // In the "childrenOnly" case we reparent the children to a screenshot
5268 // layer which has no properties set and which does not draw.
5269 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005270 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005271 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005272
5273 SurfaceFlinger* mFlinger;
5274 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005275 };
5276
5277 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5278 auto parent = layerHandle->owner.promote();
5279
Robert Carr2e102c92018-10-23 12:11:15 -07005280 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005281 ALOGE("captureLayers called with a removed parent");
5282 return NAME_NOT_FOUND;
5283 }
5284
Robert Carr578038f2018-03-09 12:25:24 -08005285 const int uid = IPCThreadState::self()->getCallingUid();
5286 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Ady Abraham83729882018-12-07 12:26:48 -08005287 if (!forSystem && parent->getCurrentFlags() & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005288 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5289 return PERMISSION_DENIED;
5290 }
5291
chaviw7206d492017-11-10 16:16:12 -08005292 Rect crop(sourceCrop);
5293 if (sourceCrop.width() <= 0) {
5294 crop.left = 0;
Ady Abraham83729882018-12-07 12:26:48 -08005295 crop.right = parent->getBufferSize(StateSet::Current).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005296 }
5297
5298 if (sourceCrop.height() <= 0) {
5299 crop.top = 0;
Ady Abraham83729882018-12-07 12:26:48 -08005300 crop.bottom = parent->getBufferSize(StateSet::Current).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005301 }
5302
5303 int32_t reqWidth = crop.width() * frameScale;
5304 int32_t reqHeight = crop.height() * frameScale;
5305
Chia-I Wu20261cb2018-08-23 12:55:44 -07005306 // really small crop or frameScale
5307 if (reqWidth <= 0) {
5308 reqWidth = 1;
5309 }
5310 if (reqHeight <= 0) {
5311 reqHeight = 1;
5312 }
5313
Peiyong Lin0e003c92018-09-17 11:09:51 -07005314 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005315
Robert Carr578038f2018-03-09 12:25:24 -08005316 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005317 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5318 if (!layer->isVisible()) {
5319 return;
Robert Carr578038f2018-03-09 12:25:24 -08005320 } else if (childrenOnly && layer == parent.get()) {
5321 return;
chaviwa76b2712017-09-20 12:02:26 -07005322 }
5323 visitor(layer);
5324 });
5325 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005326 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005327}
5328
5329status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5330 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005331 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005332 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005333 bool useIdentityTransform) {
5334 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005335
Peiyong Lin0e003c92018-09-17 11:09:51 -07005336 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005337 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5338 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005339 *outBuffer =
5340 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5341 static_cast<android_pixel_format>(reqPixelFormat), 1,
5342 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005343
5344 // This mutex protects syncFd and captureResult for communication of the return values from the
5345 // main thread back to this Binder thread
5346 std::mutex captureMutex;
5347 std::condition_variable captureCondition;
5348 std::unique_lock<std::mutex> captureLock(captureMutex);
5349 int syncFd = -1;
5350 std::optional<status_t> captureResult;
5351
Robert Carr03480e22018-01-04 16:02:06 -08005352 const int uid = IPCThreadState::self()->getCallingUid();
5353 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5354
Dominik Laskowski8c001672018-05-30 16:52:06 -07005355 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005356 // If there is a refresh pending, bug out early and tell the binder thread to try again
5357 // after the refresh.
5358 if (mRefreshPending) {
5359 ATRACE_NAME("Skipping screenshot for now");
5360 std::unique_lock<std::mutex> captureLock(captureMutex);
5361 captureResult = std::make_optional<status_t>(EAGAIN);
5362 captureCondition.notify_one();
5363 return;
5364 }
5365
5366 status_t result = NO_ERROR;
5367 int fd = -1;
5368 {
5369 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005370 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005371 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5372 useIdentityTransform, forSystem, &fd);
5373 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005374 }
5375
5376 {
5377 std::unique_lock<std::mutex> captureLock(captureMutex);
5378 syncFd = fd;
5379 captureResult = std::make_optional<status_t>(result);
5380 captureCondition.notify_one();
5381 }
5382 });
5383
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005384 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005385 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005386 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005387 while (*captureResult == EAGAIN) {
5388 captureResult.reset();
5389 result = postMessageAsync(message);
5390 if (result != NO_ERROR) {
5391 return result;
5392 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005393 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005394 }
5395 result = *captureResult;
5396 }
5397
5398 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005399 sync_wait(syncFd, -1);
5400 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005401 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005402
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005403 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005404}
5405
chaviwa76b2712017-09-20 12:02:26 -07005406void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005407 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005408 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005409 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005410
Lloyd Pique144e1162017-12-20 16:44:52 -08005411 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005412
chaviwa76b2712017-09-20 12:02:26 -07005413 const auto reqWidth = renderArea.getReqWidth();
5414 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005415 const auto sourceCrop = renderArea.getSourceCrop();
5416 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005417
Peiyong Lin0e003c92018-09-17 11:09:51 -07005418 engine.setOutputDataSpace(renderArea.getReqDataSpace());
Chia-I Wu36574d92018-05-16 10:54:36 -07005419 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005420
Mathias Agopian180f10d2013-04-10 22:55:41 -07005421 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005422 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005423
5424 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005425 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005426 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005427
chaviw50da5042018-04-09 13:49:37 -07005428 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005429 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005430 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005431
chaviwa76b2712017-09-20 12:02:26 -07005432 traverseLayers([&](Layer* layer) {
Peiyong Lind3788632018-09-18 16:01:31 -07005433 engine.setColorTransform(layer->getColorTransform());
David Sodmanfb95bcc2017-12-22 15:45:30 -08005434 layer->draw(renderArea, useIdentityTransform);
Peiyong Lind3788632018-09-18 16:01:31 -07005435 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005436 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005437}
5438
chaviwa76b2712017-09-20 12:02:26 -07005439status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5440 TraverseLayersFunction traverseLayers,
5441 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005442 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005443 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005444 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005445 ATRACE_CALL();
5446
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005447 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005448
5449 traverseLayers([&](Layer* layer) {
5450 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5451 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005452
Robert Carr03480e22018-01-04 16:02:06 -08005453 // We allow the system server to take screenshots of secure layers for
5454 // use in situations like the Screen-rotation animation and place
5455 // the impetus on WindowManager to not persist them.
5456 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005457 ALOGW("FB is protected: PERMISSION_DENIED");
5458 return PERMISSION_DENIED;
5459 }
Peiyong Linfb530cf2018-12-15 05:07:38 +00005460 auto& engine(getRenderEngine());
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005461
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005462 // this binds the given EGLImage as a framebuffer for the
5463 // duration of this scope.
Peiyong Linfb530cf2018-12-15 05:07:38 +00005464 renderengine::BindNativeBufferAsFramebuffer bufferBond(engine, buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005465 if (bufferBond.getStatus() != NO_ERROR) {
5466 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005467 return INVALID_OPERATION;
5468 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005469
Dan Stozaabcda352017-06-01 14:37:39 -07005470 // this will in fact render into our dequeued buffer
5471 // via an FBO, which means we didn't have to create
5472 // an EGLSurface and therefore we're not
5473 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005474 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005475
Peiyong Linfb530cf2018-12-15 05:07:38 +00005476 base::unique_fd syncFd = engine.flush();
Alec Mouri492bc572018-09-11 21:40:04 +00005477 if (syncFd < 0) {
Peiyong Linfb530cf2018-12-15 05:07:38 +00005478 engine.finish();
Dan Stozaabcda352017-06-01 14:37:39 -07005479 }
Alec Mouri492bc572018-09-11 21:40:04 +00005480 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005481
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005482 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005483}
5484
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005485// ---------------------------------------------------------------------------
5486
Dan Stoza412903f2017-04-27 13:42:17 -07005487void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5488 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005489}
5490
Dan Stoza412903f2017-04-27 13:42:17 -07005491void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5492 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005493}
5494
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005495void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005496 const LayerVector::Visitor& visitor) {
5497 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005498 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005499 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005500 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005501 continue;
5502 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005503 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005504 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005505 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005506 return;
5507 }
chaviwa76b2712017-09-20 12:02:26 -07005508 if (!layer->isVisible()) {
5509 return;
5510 }
5511 visitor(layer);
5512 });
5513 }
5514}
5515
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005516}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005517
Lloyd Pique074e8122018-07-26 12:57:23 -07005518
Mathias Agopian3f844832013-08-07 21:24:32 -07005519#if defined(__gl_h_)
5520#error "don't include gl/gl.h in this file"
5521#endif
5522
5523#if defined(__gl2_h_)
5524#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005525#endif