blob: 8345ce22efb3efcdfff95f830555a50dbf679d7a [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 Pique70d91362018-10-18 16:02:55 -0700545compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
546 return *mCompositionEngine.get();
547}
548
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800549void SurfaceFlinger::bootFinished()
550{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700551 if (mStartPropertySetThread->join() != NO_ERROR) {
552 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800553 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800554 const nsecs_t now = systemTime();
555 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000556 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700557
558 // wait patiently for the window manager death
559 const String16 name("window");
560 sp<IBinder> window(defaultServiceManager()->getService(name));
561 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700562 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700563 }
Robert Carr720e5062018-07-30 17:45:14 -0700564 sp<IBinder> input(defaultServiceManager()->getService(
565 String16("inputflinger")));
566 if (input == nullptr) {
567 ALOGE("Failed to link to input service");
568 } else {
569 mInputFlinger = interface_cast<IInputFlinger>(input);
570 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700571
Steven Thomas050b2c82017-03-06 11:45:16 -0800572 if (mVrFlinger) {
573 mVrFlinger->OnBootFinished();
574 }
575
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700576 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700577 // formerly we would just kill the process, but we now ask it to exit so it
578 // can choose where to stop the animation.
579 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700580
581 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
582 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
583 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700584
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800585 postMessageAsync(new LambdaMessage([this] {
586 readPersistentProperties();
587 mBootStage = BootStage::FINISHED;
588 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800589}
590
Dan Stoza436ccf32018-06-21 12:10:12 -0700591uint32_t SurfaceFlinger::getNewTexture() {
592 {
593 std::lock_guard lock(mTexturePoolMutex);
594 if (!mTexturePool.empty()) {
595 uint32_t name = mTexturePool.back();
596 mTexturePool.pop_back();
597 ATRACE_INT("TexturePoolSize", mTexturePool.size());
598 return name;
599 }
600
601 // The pool was too small, so increase it for the future
602 ++mTexturePoolSize;
603 }
604
605 // The pool was empty, so we need to get a new texture name directly using a
606 // blocking call to the main thread
607 uint32_t name = 0;
608 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
609 return name;
610}
611
Mathias Agopian3f844832013-08-07 21:24:32 -0700612void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700613 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700614}
615
Wei Wangf9b05ee2017-07-19 20:59:39 -0700616// Do not call property_set on main thread which will be blocked by init
617// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700618void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700619 ALOGI( "SurfaceFlinger's main thread ready to run. "
620 "Initializing graphics H/W...");
621
Thierry Strudel2924d012017-08-14 15:19:37 -0700622 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900623
Steven Thomasb02664d2017-07-26 18:48:28 -0700624 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800625
Steven Thomasb02664d2017-07-26 18:48:28 -0700626 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700627 if (mUseScheduler) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700628 mScheduler = getFactory().createScheduler([this](bool enabled) {
629 setVsyncEnabled(EventThread::DisplayType::Primary, enabled);
630 });
631
Ana Krulec98b5b242018-08-10 15:03:23 -0700632 mAppConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700633 mScheduler->createConnection("appConnection", SurfaceFlinger::vsyncPhaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700634 [this] { resyncWithRateLimit(); },
635 impl::EventThread::InterceptVSyncsCallback());
636 mSfConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700637 mScheduler->createConnection("sfConnection", SurfaceFlinger::sfVsyncPhaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700638 [this] { resyncWithRateLimit(); },
639 [this](nsecs_t timestamp) {
640 mInterceptor->saveVSyncEvent(timestamp);
641 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800642
Ana Krulec98b5b242018-08-10 15:03:23 -0700643 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700644 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
645 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700646 } else {
647 mEventThreadSource =
648 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
649 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
650 mEventThread =
651 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
652 [this] { resyncWithRateLimit(); },
653 impl::EventThread::InterceptVSyncsCallback(),
654 "appEventThread");
655 mSfEventThreadSource =
656 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
657 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
658
659 mSFEventThread =
660 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
661 [this] { resyncWithRateLimit(); },
662 [this](nsecs_t timestamp) {
663 mInterceptor->saveVSyncEvent(timestamp);
664 },
665 "sfEventThread");
666 mEventQueue->setEventThread(mSFEventThread.get());
667 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
668 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800669
Steven Thomasb02664d2017-07-26 18:48:28 -0700670 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700671 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700672 renderEngineFeature |= (useColorManagement ?
673 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700674 renderEngineFeature |= (useContextPriority ?
675 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700676
677 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
678 getBE().mRenderEngine =
Peiyong Linc6780972018-10-28 15:24:08 -0700679 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
680 renderEngineFeature);
David Sodmanbc815282017-11-05 18:57:52 -0800681 LOG_ALWAYS_FATAL_IF(getBE().mRenderEngine == nullptr, "couldn't create RenderEngine");
Steven Thomasb02664d2017-07-26 18:48:28 -0700682
683 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
684 "Starting with vr flinger active is not currently supported.");
Lloyd Pique90c115d2018-09-18 21:39:42 -0700685 getBE().mHwc = getFactory().createHWComposer(getBE().mHwcServiceName);
David Sodman105b7dc2017-11-04 20:28:14 -0700686 getBE().mHwc->registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800687 // Process any initial hotplug and resulting display changes.
688 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700689 const auto display = getDefaultDisplayDeviceLocked();
690 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700691 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700692 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800693
Steven Thomas050b2c82017-03-06 11:45:16 -0800694 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700695 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700696 // This callback is called from the vr flinger dispatch thread. We
697 // need to call signalTransaction(), which requires holding
698 // mStateLock when we're not on the main thread. Acquiring
699 // mStateLock from the vr flinger dispatch thread might trigger a
700 // deadlock in surface flinger (see b/66916578), so post a message
701 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700702 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700703 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
704 mVrFlingerRequestsDisplay = requestDisplay;
705 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700706 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800707 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700708 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
709 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700710 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700711 .value_or(0),
712 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800713 if (!mVrFlinger) {
714 ALOGE("Failed to start vrflinger");
715 }
716 }
717
Lloyd Pique90c115d2018-09-18 21:39:42 -0700718 mEventControlThread = getFactory().createEventControlThread(
Dominik Laskowski075d3172018-05-24 15:50:06 -0700719 [this](bool enabled) { setVsyncEnabled(EventThread::DisplayType::Primary, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700720
Mathias Agopian92a979a2012-08-02 18:32:23 -0700721 // initialize our drawing state
722 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700723
Andy McFadden13a082e2012-08-24 10:16:42 -0700724 // set initial conditions (e.g. unblank default device)
725 initializeDisplays();
726
David Sodmanbc815282017-11-05 18:57:52 -0800727 getBE().mRenderEngine->primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700728
Wei Wangf9b05ee2017-07-19 20:59:39 -0700729 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700730
731 const bool presentFenceReliable =
732 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
733 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700734
735 if (mStartPropertySetThread->Start() != NO_ERROR) {
736 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800737 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800738
Dan Stoza9e56aa02015-11-02 13:00:03 -0800739 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700740}
741
Romain Guy11d63f42017-07-20 12:47:14 -0700742void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700743 Mutex::Autolock _l(mStateLock);
744
Romain Guy11d63f42017-07-20 12:47:14 -0700745 char value[PROPERTY_VALUE_MAX];
746
747 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800748 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700749 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800750 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100751
752 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700753 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700754}
755
Mathias Agopiana67e4182012-06-19 17:26:12 -0700756void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800757 // Start boot animation service by setting a property mailbox
758 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700759 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800760 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700761 if (mStartPropertySetThread->join() != NO_ERROR) {
762 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800763 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700764}
765
Mathias Agopian875d8e12013-06-07 15:35:48 -0700766size_t SurfaceFlinger::getMaxTextureSize() const {
David Sodmanbc815282017-11-05 18:57:52 -0800767 return getBE().mRenderEngine->getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700768}
769
Mathias Agopian875d8e12013-06-07 15:35:48 -0700770size_t SurfaceFlinger::getMaxViewportDims() const {
David Sodmanbc815282017-11-05 18:57:52 -0800771 return getBE().mRenderEngine->getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700772}
773
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800774// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800775
Jamie Gennis582270d2011-08-17 18:19:00 -0700776bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800777 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800778 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800779 return authenticateSurfaceTextureLocked(bufferProducer);
780}
781
782bool SurfaceFlinger::authenticateSurfaceTextureLocked(
783 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800784 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800785 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800786}
787
Brian Anderson6b376712017-04-04 10:51:39 -0700788status_t SurfaceFlinger::getSupportedFrameTimestamps(
789 std::vector<FrameEvent>* outSupported) const {
790 *outSupported = {
791 FrameEvent::REQUESTED_PRESENT,
792 FrameEvent::ACQUIRE,
793 FrameEvent::LATCH,
794 FrameEvent::FIRST_REFRESH_START,
795 FrameEvent::LAST_REFRESH_START,
796 FrameEvent::GPU_COMPOSITION_DONE,
797 FrameEvent::DEQUEUE_READY,
798 FrameEvent::RELEASE,
799 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700800 ConditionalLock _l(mStateLock,
801 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700802 if (!getHwComposer().hasCapability(
803 HWC2::Capability::PresentFenceIsNotReliable)) {
804 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
805 }
806 return NO_ERROR;
807}
808
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700809status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
810 Vector<DisplayInfo>* configs) {
811 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700812 return BAD_VALUE;
813 }
814
Dominik Laskowski075d3172018-05-24 15:50:06 -0700815 const auto displayId = getPhysicalDisplayId(displayToken);
816 if (!displayId) {
817 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700818 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700819
Mathias Agopian8b736f12012-08-13 17:54:26 -0700820 // TODO: Not sure if display density should handled by SF any longer
821 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700822 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700823 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700824 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800825 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700826 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700827 }
828 return density;
829 }
830 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700831 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700832 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700833 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700834 return getDensityFromProperty("ro.sf.lcd_density"); }
835 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700836
Dan Stoza7f7da322014-05-02 15:26:25 -0700837 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700838
Steven Thomas6d8110b2017-08-31 18:24:21 -0700839 ConditionalLock _l(mStateLock,
840 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700841 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700842 DisplayInfo info = DisplayInfo();
843
Dan Stoza9e56aa02015-11-02 13:00:03 -0800844 float xdpi = hwConfig->getDpiX();
845 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700846
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700847 info.w = hwConfig->getWidth();
848 info.h = hwConfig->getHeight();
849 // Default display viewport to display width and height
850 info.viewportW = info.w;
851 info.viewportH = info.h;
852
Dominik Laskowski075d3172018-05-24 15:50:06 -0700853 if (displayId == getInternalDisplayId()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700854 // The density of the device is provided by a build property
855 float density = Density::getBuildDensity() / 160.0f;
856 if (density == 0) {
857 // the build doesn't provide a density -- this is wrong!
858 // use xdpi instead
859 ALOGE("ro.sf.lcd_density must be defined as a build property");
860 density = xdpi / 160.0f;
861 }
862 if (Density::getEmuDensity()) {
863 // if "qemu.sf.lcd_density" is specified, it overrides everything
864 xdpi = ydpi = density = Density::getEmuDensity();
865 density /= 160.0f;
866 }
867 info.density = density;
868
869 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700870 const auto display = getDefaultDisplayDeviceLocked();
871 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700872
873 // This is for screenrecord
874 const Rect viewport = display->getViewport();
875 if (viewport.isValid()) {
876 info.viewportW = uint32_t(viewport.getWidth());
877 info.viewportH = uint32_t(viewport.getHeight());
878 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700879 } else {
880 // TODO: where should this value come from?
881 static const int TV_DENSITY = 213;
882 info.density = TV_DENSITY / 160.0f;
883 info.orientation = 0;
884 }
885
Dan Stoza7f7da322014-05-02 15:26:25 -0700886 info.xdpi = xdpi;
887 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800888 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900889 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800890
Andy McFadden91b2ca82014-06-13 14:04:23 -0700891 // This is how far in advance a buffer must be queued for
892 // presentation at a given time. If you want a buffer to appear
893 // on the screen at time N, you must submit the buffer before
894 // (N - presentationDeadline).
895 //
896 // Normally it's one full refresh period (to give SF a chance to
897 // latch the buffer), but this can be reduced by configuring a
898 // DispSync offset. Any additional delays introduced by the hardware
899 // composer or panel must be accounted for here.
900 //
901 // We add an additional 1ms to allow for processing time and
902 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800903 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800904 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700905
906 // All non-virtual displays are currently considered secure.
907 info.secure = true;
908
Dominik Laskowski075d3172018-05-24 15:50:06 -0700909 if (displayId == getInternalDisplayId() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700910 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800911 std::swap(info.w, info.h);
912 }
913
Michael Wright28f24d02016-07-12 13:30:53 -0700914 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700915 }
916
Dan Stoza7f7da322014-05-02 15:26:25 -0700917 return NO_ERROR;
918}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700919
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700920status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
921 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700922 return BAD_VALUE;
923 }
924
Ana Krulece588e312018-09-18 12:32:24 -0700925 if (mUseScheduler) {
926 mScheduler->getDisplayStatInfo(stats);
927 } else {
928 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
929 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
930 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700931 return NO_ERROR;
932}
933
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700934int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
935 const auto display = getDisplayDevice(displayToken);
936 if (!display) {
937 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800938 return BAD_VALUE;
939 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700940
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700941 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700942}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700943
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700944void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700945 if (display->isVirtual()) {
946 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
947 return;
948 }
949
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700950 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700951 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700952 return;
953 }
954
Dominik Laskowski075d3172018-05-24 15:50:06 -0700955 const auto displayId = display->getId();
956 LOG_ALWAYS_FATAL_IF(!displayId);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700957
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700958 display->setActiveConfig(mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700959 getHwComposer().setActiveConfig(*displayId, mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700960}
961
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700962status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700963 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700964 Vector<DisplayInfo> configs;
965 getDisplayConfigs(displayToken, &configs);
966 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
967 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
968 configs.size());
969 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700970 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700971 const auto display = getDisplayDevice(displayToken);
972 if (!display) {
973 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
974 displayToken.get());
975 } else if (display->isVirtual()) {
976 ALOGW("Attempt to set active config %d for virtual display", mode);
977 } else {
978 setActiveConfigInternal(display, mode);
979 }
980 }));
981
Mathias Agopian888c8222012-08-04 21:10:38 -0700982 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700983}
Dominik Laskowski075d3172018-05-24 15:50:06 -0700984
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700985status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
986 Vector<ColorMode>* outColorModes) {
987 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700988 return BAD_VALUE;
989 }
990
Dominik Laskowski075d3172018-05-24 15:50:06 -0700991 const auto displayId = getPhysicalDisplayId(displayToken);
992 if (!displayId) {
993 return NAME_NOT_FOUND;
Michael Wright28f24d02016-07-12 13:30:53 -0700994 }
995
Peiyong Lina52f0292018-03-14 17:26:31 -0700996 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700997 {
998 ConditionalLock _l(mStateLock,
999 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001000 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001001 }
Michael Wright28f24d02016-07-12 13:30:53 -07001002 outColorModes->clear();
1003 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1004
1005 return NO_ERROR;
1006}
1007
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001008ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1009 if (const auto display = getDisplayDevice(displayToken)) {
1010 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001011 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001012 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001013}
1014
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001015void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1016 Dataspace dataSpace, RenderIntent renderIntent) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001017 if (display->isVirtual()) {
1018 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
1019 return;
1020 }
1021
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001022 ColorMode currentMode = display->getActiveColorMode();
1023 Dataspace currentDataSpace = display->getCompositionDataSpace();
1024 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001025
Peiyong Lin38e9a562018-04-10 16:24:20 -07001026 if (mode == currentMode && dataSpace == currentDataSpace &&
1027 renderIntent == currentRenderIntent) {
1028 return;
1029 }
1030
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001031 display->setActiveColorMode(mode);
1032 display->setCompositionDataSpace(dataSpace);
1033 display->setActiveRenderIntent(renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001034
Dominik Laskowski075d3172018-05-24 15:50:06 -07001035 const auto displayId = display->getId();
1036 LOG_ALWAYS_FATAL_IF(!displayId);
1037 getHwComposer().setActiveColorMode(*displayId, mode, renderIntent);
1038
Dominik Laskowski34157762018-10-31 13:07:19 -07001039 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), display=%s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001040 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
Dominik Laskowski34157762018-10-31 13:07:19 -07001041 renderIntent, to_string(*displayId).c_str());
Michael Wright28f24d02016-07-12 13:30:53 -07001042}
1043
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001044status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001045 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001046 Vector<ColorMode> modes;
1047 getDisplayColorModes(displayToken, &modes);
1048 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1049 if (mode < ColorMode::NATIVE || !exists) {
1050 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1051 decodeColorMode(mode).c_str(), mode, displayToken.get());
1052 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001053 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001054 const auto display = getDisplayDevice(displayToken);
1055 if (!display) {
1056 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1057 decodeColorMode(mode).c_str(), mode, displayToken.get());
1058 } else if (display->isVirtual()) {
1059 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1060 decodeColorMode(mode).c_str(), mode);
1061 } else {
1062 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1063 RenderIntent::COLORIMETRIC);
1064 }
1065 }));
1066
Michael Wright28f24d02016-07-12 13:30:53 -07001067 return NO_ERROR;
1068}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001069
Svetoslavd85084b2014-03-20 10:28:31 -07001070status_t SurfaceFlinger::clearAnimationFrameStats() {
1071 Mutex::Autolock _l(mStateLock);
1072 mAnimFrameTracker.clearStats();
1073 return NO_ERROR;
1074}
1075
1076status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1077 Mutex::Autolock _l(mStateLock);
1078 mAnimFrameTracker.getStats(outStats);
1079 return NO_ERROR;
1080}
1081
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001082status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1083 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001084 Mutex::Autolock _l(mStateLock);
1085
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001086 const auto display = getDisplayDeviceLocked(displayToken);
1087 if (!display) {
1088 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001089 return BAD_VALUE;
1090 }
1091
Peiyong Linfb069302018-04-25 14:34:31 -07001092 // At this point the DisplayDeivce should already be set up,
1093 // meaning the luminance information is already queried from
1094 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001095 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001096 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1097 capabilities.getDesiredMaxLuminance(),
1098 capabilities.getDesiredMaxAverageLuminance(),
1099 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001100
1101 return NO_ERROR;
1102}
1103
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001104status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1105 ui::PixelFormat* outFormat,
1106 ui::Dataspace* outDataspace,
1107 uint8_t* outComponentMask) const {
1108 if (!outFormat || !outDataspace || !outComponentMask) {
1109 return BAD_VALUE;
1110 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001111 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001112 if (!display || !display->getId()) {
1113 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1114 return BAD_VALUE;
1115 }
1116 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1117 outDataspace, outComponentMask);
1118}
1119
Kevin DuBois74e53772018-11-19 10:52:38 -08001120status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1121 bool enable, uint8_t componentMask,
1122 uint64_t maxFrames) const {
1123 const auto display = getDisplayDevice(displayToken);
1124 if (!display || !display->getId()) {
1125 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1126 return BAD_VALUE;
1127 }
1128
1129 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1130 componentMask, maxFrames);
1131}
1132
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001133status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1134 uint64_t maxFrames, uint64_t timestamp,
1135 DisplayedFrameStats* outStats) const {
1136 const auto display = getDisplayDevice(displayToken);
1137 if (!display || !display->getId()) {
1138 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1139 return BAD_VALUE;
1140 }
1141
1142 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1143 outStats);
1144}
1145
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001146status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001147 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001148 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001149
Chia-I Wu90f669f2017-10-05 14:24:41 -07001150 if (mInjectVSyncs == enable) {
1151 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001152 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001153
Ana Krulec98b5b242018-08-10 15:03:23 -07001154 // TODO(akrulec): Part of the Injector should be refactored, so that it
1155 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001156 if (enable) {
1157 ALOGV("VSync Injections enabled");
1158 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001159 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001160 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001161 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001162 impl::EventThread::InterceptVSyncsCallback(),
1163 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001164 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001165 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001166 } else {
1167 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001168 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001169 }
1170
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001171 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001172 }));
1173
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001174 return NO_ERROR;
1175}
1176
1177status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001178 Mutex::Autolock _l(mStateLock);
1179
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001180 if (!mInjectVSyncs) {
1181 ALOGE("VSync Injections not enabled");
1182 return BAD_VALUE;
1183 }
1184 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1185 ALOGV("Injecting VSync inside SurfaceFlinger");
1186 mVSyncInjector->onInjectSyncEvent(when);
1187 }
1188 return NO_ERROR;
1189}
1190
Lloyd Pique755e3192018-01-31 16:46:15 -08001191status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1192 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001193 // Try to acquire a lock for 1s, fail gracefully
1194 const status_t err = mStateLock.timedLock(s2ns(1));
1195 const bool locked = (err == NO_ERROR);
1196 if (!locked) {
1197 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1198 return TIMED_OUT;
1199 }
1200
1201 outLayers->clear();
1202 mCurrentState.traverseInZOrder([&](Layer* layer) {
1203 outLayers->push_back(layer->getLayerDebugInfo());
1204 });
1205
1206 mStateLock.unlock();
1207 return NO_ERROR;
1208}
1209
Peiyong Linc6780972018-10-28 15:24:08 -07001210status_t SurfaceFlinger::getCompositionPreference(
1211 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1212 Dataspace* outWideColorGamutDataspace,
1213 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001214 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001215 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001216 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001217 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001218 return NO_ERROR;
1219}
1220
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001221// ----------------------------------------------------------------------------
1222
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001223sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1224 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulec98b5b242018-08-10 15:03:23 -07001225 if (mUseScheduler) {
1226 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1227 return mScheduler->createDisplayEventConnection(mSfConnectionHandle);
1228 } else {
1229 return mScheduler->createDisplayEventConnection(mAppConnectionHandle);
1230 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001231 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001232 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1233 return mSFEventThread->createEventConnection();
1234 } else {
1235 return mEventThread->createEventConnection();
1236 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001237 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001238}
1239
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001240// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001241
1242void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001243 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001244}
1245
1246void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001247 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001248}
1249
1250void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001251 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001252}
1253
1254void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001255 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001256 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001257}
1258
1259status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001260 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001261 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001262}
1263
1264status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001265 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001266 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001267 if (res == NO_ERROR) {
1268 msg->wait();
1269 }
1270 return res;
1271}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001272
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001273void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001274 do {
1275 waitForEvent();
1276 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001277}
1278
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001279void SurfaceFlinger::enableHardwareVsync() {
1280 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001281 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001282 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001283 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001284 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001285 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001286}
1287
Jesse Hall948fe0c2013-10-14 12:56:09 -07001288void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001289 Mutex::Autolock _l(mHWVsyncLock);
1290
Jesse Hall948fe0c2013-10-14 12:56:09 -07001291 if (makeAvailable) {
1292 mHWVsyncAvailable = true;
Ana Krulec7ab56032018-11-02 20:51:06 +01001293 // TODO(b/113612090): This is silly, but necessary evil until we turn on the flag for good.
1294 if (mUseScheduler) {
1295 mScheduler->makeHWSyncAvailable(true);
1296 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001297 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001298 // Hardware vsync is not currently available, so abort the resync
1299 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001300 return;
1301 }
1302
Dominik Laskowski075d3172018-05-24 15:50:06 -07001303 const auto displayId = getInternalDisplayId();
1304 if (!displayId || !getHwComposer().isConnected(*displayId)) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001305 return;
1306 }
1307
Dominik Laskowski075d3172018-05-24 15:50:06 -07001308 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001309 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001310
Ana Krulece588e312018-09-18 12:32:24 -07001311 if (mUseScheduler) {
1312 mScheduler->setVsyncPeriod(period);
1313 } else {
1314 mPrimaryDispSync->reset();
1315 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001316
Ana Krulece588e312018-09-18 12:32:24 -07001317 if (!mPrimaryHWVsyncEnabled) {
1318 mPrimaryDispSync->beginResync();
1319 mEventControlThread->setVsyncEnabled(true);
1320 mPrimaryHWVsyncEnabled = true;
1321 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001322 }
1323}
1324
Jesse Hall948fe0c2013-10-14 12:56:09 -07001325void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001326 Mutex::Autolock _l(mHWVsyncLock);
1327 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001328 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001329 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001330 mPrimaryHWVsyncEnabled = false;
1331 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001332 if (makeUnavailable) {
1333 mHWVsyncAvailable = false;
1334 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001335}
1336
Tim Murray4a4e4a22016-04-19 16:29:23 +00001337void SurfaceFlinger::resyncWithRateLimit() {
1338 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001339
1340 // No explicit locking is needed here since EventThread holds a lock while calling this method
1341 static nsecs_t sLastResyncAttempted = 0;
1342 const nsecs_t now = systemTime();
1343 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001344 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001345 }
Dan Stoza57164302017-05-08 14:03:54 -07001346 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001347}
1348
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001349void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1350 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001351 ATRACE_NAME("SF onVsync");
1352
Steven Thomas3cfac282017-02-06 12:29:30 -08001353 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001354 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001355 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001356 return;
1357 }
1358
Dominik Laskowski075d3172018-05-24 15:50:06 -07001359 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001360 return;
1361 }
1362
Dominik Laskowski075d3172018-05-24 15:50:06 -07001363 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001364 // For now, we don't do anything with external display vsyncs.
1365 return;
1366 }
1367
Ana Krulece588e312018-09-18 12:32:24 -07001368 if (mUseScheduler) {
1369 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001370 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001371 bool needsHwVsync = false;
1372 { // Scope for the lock
1373 Mutex::Autolock _l(mHWVsyncLock);
1374 if (mPrimaryHWVsyncEnabled) {
1375 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1376 }
1377 }
1378
1379 if (needsHwVsync) {
1380 enableHardwareVsync();
1381 } else {
1382 disableHardwareVsync(false);
1383 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001384 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001385}
1386
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001387void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001388 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1389 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001390}
1391
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001392void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001393 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001394 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001395 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001396
Lloyd Piqueba04e622017-12-14 17:11:26 -08001397 // Ignore events that do not have the right sequenceId.
1398 if (sequenceId != getBE().mComposerSequenceId) {
1399 return;
1400 }
1401
Steven Thomasb02664d2017-07-26 18:48:28 -07001402 // Only lock if we're not on the main thread. This function is normally
1403 // called on a hwbinder thread, but for the primary display it's called on
1404 // the main thread with the state lock already held, so don't attempt to
1405 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001406 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001407
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001408 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001409
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001410 if (std::this_thread::get_id() == mMainThreadId) {
1411 // Process all pending hot plug events immediately if we are on the main thread.
1412 processDisplayHotplugEventsLocked();
1413 }
1414
Lloyd Piqueba04e622017-12-14 17:11:26 -08001415 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001416}
1417
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001418void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001419 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001420 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001421 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001422 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001423 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001424}
1425
Dominik Laskowski075d3172018-05-24 15:50:06 -07001426void SurfaceFlinger::setVsyncEnabled(EventThread::DisplayType /*displayType*/, bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001427 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001428 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001429 if (const auto displayId = getInternalDisplayId()) {
1430 getHwComposer().setVsyncEnabled(*displayId,
1431 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1432 }
Mathias Agopian86303202012-07-24 22:46:10 -07001433}
1434
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001435// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001436void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001437 if (mUseScheduler) {
1438 mScheduler->disableHardwareVsync(true);
1439 } else {
1440 disableHardwareVsync(true);
1441 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001442 // Clear the drawing state so that the logic inside of
1443 // handleTransactionLocked will fire. It will determine the delta between
1444 // mCurrentState and mDrawingState and re-apply all changes when we make the
1445 // transition.
1446 mDrawingState.displays.clear();
1447 mDisplays.clear();
1448}
1449
Steven Thomas050b2c82017-03-06 11:45:16 -08001450void SurfaceFlinger::updateVrFlinger() {
1451 if (!mVrFlinger)
1452 return;
1453 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
David Sodman105b7dc2017-11-04 20:28:14 -07001454 if (vrFlingerRequestsDisplay == getBE().mHwc->isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001455 return;
1456 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001457
David Sodman105b7dc2017-11-04 20:28:14 -07001458 if (vrFlingerRequestsDisplay && !getBE().mHwc->getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001459 ALOGE("Vr flinger is only supported for remote hardware composer"
1460 " service connections. Ignoring request to transition to vr"
1461 " flinger.");
1462 mVrFlingerRequestsDisplay = false;
1463 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001464 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001465
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001466 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001467
Steven Thomas0123ac62018-07-12 11:32:34 -07001468 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001469 LOG_ALWAYS_FATAL_IF(!display);
1470 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001471 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1472 // called below. Clear the reference now so we don't accidentally use it
1473 // later.
1474 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001475
Steven Thomasb02664d2017-07-26 18:48:28 -07001476 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001477 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001478 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001479
Steven Thomasb02664d2017-07-26 18:48:28 -07001480 resetDisplayState();
David Sodman105b7dc2017-11-04 20:28:14 -07001481 getBE().mHwc.reset(); // Delete the current instance before creating the new one
Lloyd Pique90c115d2018-09-18 21:39:42 -07001482 getBE().mHwc = getFactory().createHWComposer(
1483 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName);
David Sodman105b7dc2017-11-04 20:28:14 -07001484 getBE().mHwc->registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001485
David Sodman105b7dc2017-11-04 20:28:14 -07001486 LOG_ALWAYS_FATAL_IF(!getBE().mHwc->getComposer()->isRemote(),
1487 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001488
1489 if (vrFlingerRequestsDisplay) {
1490 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001491 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001492
1493 mVisibleRegionsDirty = true;
1494 invalidateHwcGeometry();
1495
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001496 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001497 display = getDefaultDisplayDeviceLocked();
1498 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001499 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001500
Steven Thomasb02664d2017-07-26 18:48:28 -07001501 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski075d3172018-05-24 15:50:06 -07001502 const auto activeConfig = getHwComposer().getActiveConfig(*display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001503 const nsecs_t period = activeConfig->getVsyncPeriod();
1504 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001505
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001506 // The present fences returned from vr_hwc are not an accurate
1507 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001508 if (mUseScheduler) {
1509 mScheduler->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() || !hasSyncFramework);
1510 } else {
1511 mPrimaryDispSync->setIgnorePresentFences(getBE().mHwc->isUsingVrComposer() ||
1512 !hasSyncFramework);
1513 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001514
Steven Thomasb02664d2017-07-26 18:48:28 -07001515 // Use phase of 0 since phase is not known.
1516 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07001517 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
1518 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001519
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001520 resyncToHardwareVsync(false);
1521
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001522 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001523 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001524}
1525
Mathias Agopian4fec8732012-06-29 14:12:52 -07001526void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001527 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001528 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001529 case MessageQueue::INVALIDATE: {
Ana Krulec3084c052018-11-21 20:27:17 +01001530 if (mUseScheduler) {
1531 // This call is made each time SF wakes up and creates a new frame.
1532 mScheduler->incrementFrameCounter();
1533 }
Dan Stoza50182882016-07-08 12:02:20 -07001534 bool frameMissed = !mHadClientComposition &&
1535 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001536 (mPreviousPresentFence->getSignalTime() ==
1537 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001538 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001539 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001540 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001541 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001542 if (mPropagateBackpressure) {
1543 signalLayerUpdate();
1544 break;
1545 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001546 }
Dan Stoza50182882016-07-08 12:02:20 -07001547
Steven Thomas050b2c82017-03-06 11:45:16 -08001548 // Now that we're going to make it to the handleMessageTransaction()
1549 // call below it's safe to call updateVrFlinger(), which will
1550 // potentially trigger a display handoff.
1551 updateVrFlinger();
1552
Dan Stoza6b9454d2014-11-07 16:00:59 -08001553 bool refreshNeeded = handleMessageTransaction();
1554 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001555 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001556 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001557 // Signal a refresh if a transaction modified the window state,
1558 // a new buffer was latched, or if HWC has requested a full
1559 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001560 signalRefresh();
1561 }
1562 break;
1563 }
1564 case MessageQueue::REFRESH: {
1565 handleMessageRefresh();
1566 break;
1567 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001568 }
1569}
1570
Dan Stoza6b9454d2014-11-07 16:00:59 -08001571bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001572 uint32_t transactionFlags = peekTransactionFlags();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001573 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001574 handleTransaction(transactionFlags);
Dan Stoza6b9454d2014-11-07 16:00:59 -08001575 return true;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001576 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001577 return false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001578}
1579
Mathias Agopian4fec8732012-06-29 14:12:52 -07001580void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001581 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001582
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001583 mRefreshPending = false;
1584
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001585 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001586 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001587 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001588 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001589 for (const auto& [token, display] : mDisplays) {
1590 beginFrame(display);
1591 prepareFrame(display);
1592 doDebugFlashRegions(display, repaintEverything);
1593 doComposition(display, repaintEverything);
1594 }
1595
Adrian Roos1e1a1282017-11-01 19:05:31 +01001596 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001597 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001598
1599 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001600 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001601
Dan Stozabfbffeb2016-07-21 14:49:33 -07001602 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001603 for (const auto& [token, display] : mDisplays) {
Dan Stozabfbffeb2016-07-21 14:49:33 -07001604 mHadClientComposition = mHadClientComposition ||
Dominik Laskowski7e045462018-05-30 13:02:02 -07001605 getBE().mHwc->hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001606 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001607
Alec Mouri86770e52018-09-24 22:40:58 +00001608 // Setup RenderEngine sync fences if native sync is supported.
1609 if (getBE().mRenderEngine->useNativeFenceSync()) {
1610 if (mHadClientComposition) {
1611 base::unique_fd flushFence(getRenderEngine().flush());
1612 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1613 getBE().flushFence = new Fence(std::move(flushFence));
1614 } else {
1615 // Cleanup for hygiene.
1616 getBE().flushFence = Fence::NO_FENCE;
1617 }
1618 }
1619
Jorim Jaggi90535212018-05-23 23:44:06 +02001620 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001621
David Sodman7e4ae112018-02-09 15:02:28 -08001622 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001623 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001624 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[token]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001625 compositionInfo.hwc.hwcLayer = nullptr;
1626 }
David Sodmanba340492018-08-05 21:51:33 -07001627 }
David Sodman7e4ae112018-02-09 15:02:28 -08001628
1629 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001630}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001631
David Sodmanfa9b2af2017-12-24 13:28:59 -08001632
1633bool SurfaceFlinger::handleMessageInvalidate() {
1634 ATRACE_CALL();
1635 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001636}
1637
David Sodman79bba0e2018-08-05 18:07:49 -07001638void SurfaceFlinger::calculateWorkingSet() {
1639 ATRACE_CALL();
1640 ALOGV(__FUNCTION__);
1641
David Sodman79bba0e2018-08-05 18:07:49 -07001642 // build the h/w work list
1643 if (CC_UNLIKELY(mGeometryInvalid)) {
1644 mGeometryInvalid = false;
1645 for (const auto& [token, display] : mDisplays) {
1646 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001647 if (!displayId) {
1648 continue;
1649 }
David Sodman79bba0e2018-08-05 18:07:49 -07001650
Dominik Laskowski075d3172018-05-24 15:50:06 -07001651 const Vector<sp<Layer>>& currentLayers = display->getVisibleLayersSortedByZ();
1652 for (size_t i = 0; i < currentLayers.size(); i++) {
1653 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001654
Dominik Laskowski075d3172018-05-24 15:50:06 -07001655 if (!layer->hasHwcLayer(*displayId)) {
1656 if (!layer->createHwcLayer(&getHwComposer(), *displayId)) {
1657 layer->forceClientComposition(*displayId);
1658 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001659 }
1660 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001661
1662 layer->setGeometry(display, i);
1663 if (mDebugDisableHWC || mDebugRegion) {
1664 layer->forceClientComposition(*displayId);
1665 }
David Sodman79bba0e2018-08-05 18:07:49 -07001666 }
1667 }
1668 }
1669
1670 // Set the per-frame data
1671 for (const auto& [token, display] : mDisplays) {
1672 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001673 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001674 continue;
1675 }
1676
1677 if (mDrawingState.colorMatrixChanged) {
1678 display->setColorTransform(mDrawingState.colorMatrix);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001679 status_t result =
1680 getHwComposer().setColorTransform(*displayId, mDrawingState.colorMatrix);
Dominik Laskowski34157762018-10-31 13:07:19 -07001681 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on display %s: %d",
1682 to_string(*displayId).c_str(), result);
David Sodman79bba0e2018-08-05 18:07:49 -07001683 }
1684 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1685 if (layer->isHdrY410()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001686 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001687 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1688 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1689 !display->hasHDR10Support()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001690 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001691 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1692 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1693 !display->hasHLGSupport()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001694 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001695 }
1696
Peiyong Lind3788632018-09-18 16:01:31 -07001697 // TODO(b/111562338) remove when composer 2.3 is shipped.
1698 if (layer->hasColorTransform()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001699 layer->forceClientComposition(*displayId);
Peiyong Lind3788632018-09-18 16:01:31 -07001700 }
1701
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001702 if (layer->getRoundedCornerState().radius > 0.0f) {
1703 layer->forceClientComposition(*displayId);
1704 }
1705
Dominik Laskowski075d3172018-05-24 15:50:06 -07001706 if (layer->getForceClientComposition(*displayId)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001707 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski075d3172018-05-24 15:50:06 -07001708 layer->setCompositionType(*displayId, HWC2::Composition::Client);
David Sodman79bba0e2018-08-05 18:07:49 -07001709 continue;
1710 }
1711
Dominik Laskowski075d3172018-05-24 15:50:06 -07001712 layer->setPerFrameData(*displayId, display->getTransform(), display->getViewport(),
1713 display->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001714 }
1715
Peiyong Lin13effd12018-07-24 17:01:47 -07001716 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001717 ColorMode colorMode;
1718 Dataspace dataSpace;
1719 RenderIntent renderIntent;
1720 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1721 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1722 }
1723 }
1724
1725 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001726
1727 for (const auto& [token, display] : mDisplays) {
1728 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001729 const auto displayId = display->getId();
David Sodmanba340492018-08-05 21:51:33 -07001730 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001731
1732 if (displayId) {
1733 if (!layer->setHwcLayer(*displayId)) {
1734 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1735 }
1736 layer->getBE().compositionInfo.hwc.displayId = *displayId;
David Sodmanba340492018-08-05 21:51:33 -07001737 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001738
Dominik Laskowski05275f12018-11-01 15:03:24 -07001739 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001740 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1741 }
1742 }
David Sodman79bba0e2018-08-05 18:07:49 -07001743}
1744
David Sodmanfa9b2af2017-12-24 13:28:59 -08001745void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001746{
1747 // is debugging enabled
1748 if (CC_LIKELY(!mDebugRegion))
1749 return;
1750
David Sodmanfa9b2af2017-12-24 13:28:59 -08001751 if (display->isPoweredOn()) {
1752 // transform the dirty region into this screen's coordinate space
1753 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1754 if (!dirtyRegion.isEmpty()) {
1755 // redraw the whole screen
1756 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001757
David Sodmanfa9b2af2017-12-24 13:28:59 -08001758 // and draw the dirty region
David Sodmanfa9b2af2017-12-24 13:28:59 -08001759 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07001760 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001761
Alec Mouri0a9c7b82018-11-16 13:05:25 -08001762 display->queueBuffer(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001763 }
1764 }
1765
David Sodmanfa9b2af2017-12-24 13:28:59 -08001766 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001767
1768 if (mDebugRegion > 1) {
1769 usleep(mDebugRegion * 1000);
1770 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001771
Dominik Laskowski05275f12018-11-01 15:03:24 -07001772 prepareFrame(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001773}
1774
Adrian Roos1e1a1282017-11-01 19:05:31 +01001775void SurfaceFlinger::doTracing(const char* where) {
1776 ATRACE_CALL();
1777 ATRACE_NAME(where);
1778 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001779 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001780 }
1781}
1782
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001783void SurfaceFlinger::logLayerStats() {
1784 ATRACE_CALL();
1785 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001786 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001787 if (display->isPrimary()) {
1788 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001789 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001790 }
1791 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001792
1793 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001794 }
1795}
1796
David Sodman2b406362017-12-15 13:33:47 -08001797void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001798{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001799 ATRACE_CALL();
1800 ALOGV("preComposition");
1801
David Sodman2b406362017-12-15 13:33:47 -08001802 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1803
Mathias Agopiancd60f992012-08-16 16:28:27 -07001804 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001805 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001806 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001807 needExtraInvalidate = true;
1808 }
Robert Carr2047fae2016-11-28 14:09:09 -08001809 });
1810
Mathias Agopiancd60f992012-08-16 16:28:27 -07001811 if (needExtraInvalidate) {
1812 signalLayerUpdate();
1813 }
1814}
1815
Ana Krulece588e312018-09-18 12:32:24 -07001816void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1817 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001818 // Update queue of past composite+present times and determine the
1819 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001820 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001821 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001822 while (!getBE().mCompositePresentTimes.empty()) {
1823 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001824 // Cached values should have been updated before calling this method,
1825 // which helps avoid duplicate syscalls.
1826 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1827 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1828 break;
1829 }
1830 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001831 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001832 }
1833
1834 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001835 while (getBE().mCompositePresentTimes.size() > 16) {
1836 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001837 }
1838
Ana Krulece588e312018-09-18 12:32:24 -07001839 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001840}
1841
Ana Krulece588e312018-09-18 12:32:24 -07001842void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1843 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001844 // Integer division and modulo round toward 0 not -inf, so we need to
1845 // treat negative and positive offsets differently.
Ana Krulece588e312018-09-18 12:32:24 -07001846 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0)
1847 ? (stats.vsyncPeriod - (sfVsyncPhaseOffsetNs % stats.vsyncPeriod))
1848 : ((-sfVsyncPhaseOffsetNs) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001849
Brian Andersond0010582017-03-07 13:20:31 -08001850 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1851 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001852 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001853 }
1854
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001855 // Snap the latency to a value that removes scheduling jitter from the
1856 // composition and present times, which often have >1ms of jitter.
1857 // Reducing jitter is important if an app attempts to extrapolate
1858 // something (such as user input) to an accurate diasplay time.
1859 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1860 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001861 nsecs_t bias = stats.vsyncPeriod / 2;
1862 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1863 nsecs_t snappedCompositeToPresentLatency =
1864 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001865
David Sodman99974d22017-11-28 12:04:33 -08001866 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001867 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1868 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001869 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001870}
1871
David Sodman2b406362017-12-15 13:33:47 -08001872void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001873{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001874 ATRACE_CALL();
1875 ALOGV("postComposition");
1876
Brian Anderson3546a3f2016-07-14 11:51:14 -07001877 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001878 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001879 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001880 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001881 }
1882
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001883 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001884 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001885
David Sodman73beded2017-11-15 11:56:06 -08001886 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001887 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001888 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001889 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001890 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001891 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001892 } else {
1893 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1894 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001895
David Sodman73beded2017-11-15 11:56:06 -08001896 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001897 mPreviousPresentFence =
Dominik Laskowski075d3172018-05-24 15:50:06 -07001898 display ? getHwComposer().getPresentFence(*display->getId()) : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001899 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001900 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001901
Ana Krulece588e312018-09-18 12:32:24 -07001902 DisplayStatInfo stats;
1903 if (mUseScheduler) {
1904 mScheduler->getDisplayStatInfo(&stats);
1905 } else {
1906 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
1907 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
1908 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001909
David Sodman2b406362017-12-15 13:33:47 -08001910 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001911 // when we started doing work for this frame, but that should be okay
1912 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07001913 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001914 CompositorTiming compositorTiming;
1915 {
David Sodman99974d22017-11-28 12:04:33 -08001916 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1917 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001918 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001919
Robert Carr2047fae2016-11-28 14:09:09 -08001920 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001921 bool frameLatched = layer->onPostComposition(display->getId(), glCompositionDoneFenceTime,
1922 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001923 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001924 recordBufferingStats(layer->getName().string(),
1925 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001926 }
Robert Carr2047fae2016-11-28 14:09:09 -08001927 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001928
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001929 if (presentFenceTime->isValid()) {
Ana Krulece588e312018-09-18 12:32:24 -07001930 if (mUseScheduler) {
1931 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001932 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001933 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
1934 enableHardwareVsync();
1935 } else {
1936 disableHardwareVsync(false);
1937 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001938 }
1939 }
1940
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001941 if (!hasSyncFramework) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001942 if (display && getHwComposer().isConnected(*display->getId()) && display->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07001943 if (mUseScheduler) {
1944 mScheduler->enableHardwareVsync();
1945 } else {
1946 enableHardwareVsync();
1947 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001948 }
1949 }
1950
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001951 if (mAnimCompositionPending) {
1952 mAnimCompositionPending = false;
1953
Brian Anderson4e606e32017-03-16 15:34:57 -07001954 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001955 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001956 std::move(presentFenceTime));
Dominik Laskowski075d3172018-05-24 15:50:06 -07001957 } else if (display && getHwComposer().isConnected(*display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001958 // The HWC doesn't support present fences, so use the refresh
1959 // timestamp instead.
Dominik Laskowski075d3172018-05-24 15:50:06 -07001960 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(*display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001961 mAnimFrameTracker.setActualPresentTime(presentTime);
1962 }
1963 mAnimFrameTracker.advanceFrame();
1964 }
Dan Stozab90cf072015-03-05 11:05:59 -08001965
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001966 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001967 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001968 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001969 }
1970
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001971 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07001972
Dominik Laskowski075d3172018-05-24 15:50:06 -07001973 if (display && getHwComposer().isConnected(*display->getId()) && !display->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08001974 return;
1975 }
1976
1977 nsecs_t currentTime = systemTime();
1978 if (mHasPoweredOff) {
1979 mHasPoweredOff = false;
1980 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001981 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07001982 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08001983 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1984 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001985 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001986 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001987 }
David Sodman4a36e932017-11-07 14:29:47 -08001988 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001989 }
David Sodman4a36e932017-11-07 14:29:47 -08001990 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001991
1992 {
1993 std::lock_guard lock(mTexturePoolMutex);
1994 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
1995 if (refillCount > 0) {
1996 const size_t offset = mTexturePool.size();
1997 mTexturePool.resize(mTexturePoolSize);
1998 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1999 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2000 }
2001 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002002
Marissa Wallfda30bb2018-10-12 11:34:28 -07002003 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002004 mTransactionCompletedThread.sendCallbacks();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002005}
2006
2007void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002008 ATRACE_CALL();
2009 ALOGV("rebuildLayerStacks");
2010
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002011 // We need to clear these out now as these may be holding on to a
2012 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2013 // also holds a reference. When the set of visible layers is recomputed,
2014 // some layers may be destroyed if the only thing keeping them alive was
2015 // that list of visible layers associated with each display. The layer
2016 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2017 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2018 for (const auto& [token, display] : mDisplays) {
2019 getBE().mCompositionInfo[token].clear();
2020 }
2021
Mathias Agopiancd60f992012-08-16 16:28:27 -07002022 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002023 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002024 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002025 mVisibleRegionsDirty = false;
2026 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002027
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002028 for (const auto& pair : mDisplays) {
2029 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07002030 Region opaqueRegion;
2031 Region dirtyRegion;
2032 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002033 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07002034 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002035 const Rect bounds = display->getBounds();
2036 if (display->isPoweredOn()) {
2037 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002038
Jeff Sharkey76488112017-02-27 14:15:18 -07002039 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08002040 bool hwcLayerDestroyed = false;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002041 const auto displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002042 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002043 Region drawRegion(tr.transform(
2044 layer->visibleNonTransparentRegion));
2045 drawRegion.andSelf(bounds);
2046 if (!drawRegion.isEmpty()) {
2047 layersSortedByZ.add(layer);
2048 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002049 // Clear out the HWC layer if this layer was
2050 // previously visible, but no longer is
Dominik Laskowski075d3172018-05-24 15:50:06 -07002051 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Jeff Sharkey76488112017-02-27 14:15:18 -07002052 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002053 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002054 // WM changes display->layerStack upon sleep/awake.
2055 // Here we make sure we delete the HWC layers even if
2056 // WM changed their layer stack.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002057 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Chia-I Wu83806892017-11-16 10:50:20 -08002058 }
2059
2060 // If a layer is not going to get a release fence because
2061 // it is invisible, but it is also going to release its
2062 // old buffer, add it to the list of layers needing
2063 // fences.
2064 if (hwcLayerDestroyed) {
2065 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2066 mLayersWithQueuedFrames.cend(), layer);
2067 if (found != mLayersWithQueuedFrames.cend()) {
2068 layersNeedingFences.add(layer);
2069 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002070 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002071 });
2072 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002073 display->setVisibleLayersSortedByZ(layersSortedByZ);
2074 display->setLayersNeedingFences(layersNeedingFences);
2075 display->undefinedRegion.set(bounds);
2076 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2077 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002078 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002079 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002080}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002081
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002082// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002083// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002084// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002085// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002086// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002087// The returned HDR data space is one of
2088// - Dataspace::UNKNOWN
2089// - Dataspace::BT2020_HLG
2090// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002091Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2092 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002093 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002094 *outHdrDataSpace = Dataspace::UNKNOWN;
2095
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002096 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002097 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002098 case Dataspace::V0_SCRGB:
2099 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002100 case Dataspace::BT2020:
2101 case Dataspace::BT2020_ITU:
2102 case Dataspace::BT2020_LINEAR:
2103 case Dataspace::DISPLAY_BT2020:
2104 bestDataSpace = Dataspace::DISPLAY_BT2020;
2105 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002106 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002107 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002108 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002109 case Dataspace::BT2020_PQ:
2110 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002111 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002112 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002113 case Dataspace::BT2020_HLG:
2114 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002115 // When there's mixed PQ content and HLG content, we set the HDR
2116 // data space to be BT2020_PQ and convert HLG to PQ.
2117 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2118 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002119 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002120 break;
2121 default:
2122 break;
2123 }
Romain Guy54f154a2017-10-24 21:40:32 +01002124 }
2125
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002126 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002127}
2128
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002129// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002130void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2131 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002132 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2133 *outMode = ColorMode::NATIVE;
2134 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002135 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002136 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002137 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002138
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002139 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002140 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002141
Peiyong Lindfde5112018-06-05 10:58:41 -07002142 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002143 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07002144 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002145 if (isHdr) {
2146 bestDataSpace = hdrDataSpace;
2147 }
2148
Chia-I Wu0d711262018-05-21 15:19:35 -07002149 RenderIntent intent;
2150 switch (mDisplayColorSetting) {
2151 case DisplayColorSetting::MANAGED:
2152 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002153 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002154 break;
2155 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002156 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002157 break;
2158 default: // vendor display color setting
2159 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2160 break;
2161 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002162
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002163 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002164}
2165
David Sodmanfa9b2af2017-12-24 13:28:59 -08002166void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002167{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002168 bool dirty = !display->getDirtyRegion(false).isEmpty();
2169 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2170 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002171
David Sodmanfa9b2af2017-12-24 13:28:59 -08002172 // If nothing has changed (!dirty), don't recompose.
2173 // If something changed, but we don't currently have any visible layers,
2174 // and didn't when we last did a composition, then skip it this time.
2175 // The second rule does two things:
2176 // - When all layers are removed from a display, we'll emit one black
2177 // frame, then nothing more until we get new layers.
2178 // - When a display is created with a private layer stack, we won't
2179 // emit any black frames until a layer is added to the layer stack.
2180 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002181
Dominik Laskowski075d3172018-05-24 15:50:06 -07002182 const char flagPrefix[] = {'-', '+'};
2183 static_cast<void>(flagPrefix);
2184 ALOGV_IF(display->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2185 __FUNCTION__, mustRecompose ? "doing" : "skipping", display->getDebugName().c_str(),
2186 flagPrefix[dirty], flagPrefix[empty], flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002187
David Sodmanfa9b2af2017-12-24 13:28:59 -08002188 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002189
David Sodmanfa9b2af2017-12-24 13:28:59 -08002190 if (mustRecompose) {
2191 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002192 }
2193}
2194
David Sodmanfa9b2af2017-12-24 13:28:59 -08002195void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002196{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002197 if (!display->isPoweredOn()) {
2198 return;
David Sodman2b406362017-12-15 13:33:47 -08002199 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002200
Dominik Laskowski05275f12018-11-01 15:03:24 -07002201 status_t result = display->prepareFrame(getHwComposer(),
2202 getBE().mCompositionInfo[display->getDisplayToken()]);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002203 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
2204 display->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002205}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002206
David Sodmanfa9b2af2017-12-24 13:28:59 -08002207void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002208 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002209 ALOGV("doComposition");
2210
David Sodmanfa9b2af2017-12-24 13:28:59 -08002211 if (display->isPoweredOn()) {
2212 // transform the dirty region into this screen's coordinate space
2213 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002214
David Sodmanfa9b2af2017-12-24 13:28:59 -08002215 // repaint the framebuffer (if needed)
2216 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002217
David Sodmanfa9b2af2017-12-24 13:28:59 -08002218 display->dirtyRegion.clear();
2219 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002220 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002221 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002222}
2223
David Sodmanfa9b2af2017-12-24 13:28:59 -08002224void SurfaceFlinger::postFrame()
2225{
2226 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002227 const auto display = getDefaultDisplayDeviceLocked();
2228 if (display && getHwComposer().isConnected(*display->getId())) {
2229 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002230 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2231 logFrameStats();
2232 }
2233 }
2234}
2235
2236void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002237{
Mathias Agopian841cde52012-03-01 15:44:37 -08002238 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002239 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002240
David Sodmanfa9b2af2017-12-24 13:28:59 -08002241 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002242
David Sodmanfa9b2af2017-12-24 13:28:59 -08002243 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002244 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002245 if (displayId) {
2246 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002247 }
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002248 display->onPresentDisplayCompleted();
David Sodman15094112018-10-11 09:39:37 -07002249 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002250 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002251
Chia-I Wu7b549592017-11-15 09:14:57 -08002252 // The layer buffer from the previous frame (if any) is released
2253 // by HWC only when the release fence from this frame (if any) is
2254 // signaled. Always get the release fence from HWC first.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002255 if (displayId && layer->hasHwcLayer(*displayId)) {
2256 releaseFence = getHwComposer().getLayerReleaseFence(*displayId,
2257 layer->getHwcLayer(*displayId));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002258 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002259
2260 // If the layer was client composited in the previous frame, we
2261 // need to merge with the previous client target acquire fence.
2262 // Since we do not track that, always merge with the current
2263 // client target acquire fence when it is available, even though
2264 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002265 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002266 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002267 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002268 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002269
David Sodman15094112018-10-11 09:39:37 -07002270 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002271 }
Chia-I Wu83806892017-11-16 10:50:20 -08002272
2273 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002274 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002275 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002276 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002277 sp<Fence> presentFence =
2278 displayId ? getBE().mHwc->getPresentFence(*displayId) : Fence::NO_FENCE;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002279 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002280 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002281 }
2282 }
2283
Dominik Laskowski075d3172018-05-24 15:50:06 -07002284 if (displayId) {
2285 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002286 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002287 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002288}
2289
Mathias Agopian87baae12012-07-31 12:38:26 -07002290void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002291{
Mathias Agopian841cde52012-03-01 15:44:37 -08002292 ATRACE_CALL();
2293
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002294 // here we keep a copy of the drawing state (that is the state that's
2295 // going to be overwritten by handleTransactionLocked()) outside of
2296 // mStateLock so that the side-effects of the State assignment
2297 // don't happen with mStateLock held (which can cause deadlocks).
2298 State drawingState(mDrawingState);
2299
Mathias Agopianca4d3602011-05-19 15:38:14 -07002300 Mutex::Autolock _l(mStateLock);
2301 const nsecs_t now = systemTime();
2302 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002303
Mathias Agopianca4d3602011-05-19 15:38:14 -07002304 // Here we're guaranteed that some transaction flags are set
2305 // so we can call handleTransactionLocked() unconditionally.
2306 // We call getTransactionFlags(), which will also clear the flags,
2307 // with mStateLock held to guarantee that mCurrentState won't change
2308 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002309
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002310 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002311 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002312 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002313
Mathias Agopianca4d3602011-05-19 15:38:14 -07002314 mLastTransactionTime = systemTime() - now;
2315 mDebugInTransaction = 0;
2316 invalidateHwcGeometry();
2317 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002318}
2319
Lloyd Piqueba04e622017-12-14 17:11:26 -08002320void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2321 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002322 const std::optional<DisplayIdentificationInfo> info =
2323 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002324
Dominik Laskowski075d3172018-05-24 15:50:06 -07002325 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002326 continue;
2327 }
2328
Lloyd Piqueba04e622017-12-14 17:11:26 -08002329 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002330 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002331 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002332 mPhysicalDisplayTokens[info->id] = new BBinder();
2333 DisplayDeviceState state;
2334 state.displayId = info->id;
2335 state.isSecure = true; // All physical displays are currently considered secure.
2336 state.displayName = info->name;
2337 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2338 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002339 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002340 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002341 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002342
Dominik Laskowski075d3172018-05-24 15:50:06 -07002343 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2344 if (index >= 0) {
2345 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2346 mInterceptor->saveDisplayDeletion(state.sequenceId);
2347 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002348 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002349 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002350 }
2351
2352 processDisplayChangesLocked();
2353 }
2354
2355 mPendingHotplugEvents.clear();
2356}
2357
Lloyd Pique99d3da52018-01-22 17:48:03 -08002358sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002359 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
2360 const DisplayDeviceState& state, const sp<DisplaySurface>& dispSurface,
2361 const sp<IGraphicBufferProducer>& producer) {
2362 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002363 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002364 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002365 creationArgs.isSecure = state.isSecure;
2366 creationArgs.displaySurface = dispSurface;
2367 creationArgs.hasWideColorGamut = false;
2368 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002369
Dominik Laskowski075d3172018-05-24 15:50:06 -07002370 const bool isInternalDisplay = displayId && displayId == getInternalDisplayId();
2371 creationArgs.isPrimary = isInternalDisplay;
2372
2373 if (useColorManagement && displayId) {
2374 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002375 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002376 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002377 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002378 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002379
Dominik Laskowski7e045462018-05-30 13:02:02 -07002380 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002381 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002382 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002383 }
tangrobin6753a022018-08-10 10:58:54 +08002384 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002385
Dominik Laskowski075d3172018-05-24 15:50:06 -07002386 if (displayId) {
2387 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002388 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002389 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002390 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002391
Lloyd Pique90c115d2018-09-18 21:39:42 -07002392 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002393 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002394 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002395
Lloyd Pique99d3da52018-01-22 17:48:03 -08002396 // Make sure that composition can never be stalled by a virtual display
2397 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002398 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002399 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002400 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2401 }
2402
Dominik Laskowski075d3172018-05-24 15:50:06 -07002403 creationArgs.displayInstallOrientation =
2404 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002405
Lloyd Pique99d3da52018-01-22 17:48:03 -08002406 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002407 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002408
Lloyd Pique90c115d2018-09-18 21:39:42 -07002409 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002410
2411 if (maxFrameBufferAcquiredBuffers >= 3) {
2412 nativeWindowSurface->preallocateBuffers();
2413 }
2414
2415 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002416 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002417 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002418 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002419 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002420 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002421 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002422 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002423 if (!state.isVirtual()) {
2424 LOG_ALWAYS_FATAL_IF(!displayId);
2425 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002426 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002427
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002428 display->setLayerStack(state.layerStack);
2429 display->setProjection(state.orientation, state.viewport, state.frame);
2430 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002431
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002432 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002433}
2434
Lloyd Pique347200f2017-12-14 17:00:15 -08002435void SurfaceFlinger::processDisplayChangesLocked() {
2436 // here we take advantage of Vector's copy-on-write semantics to
2437 // improve performance by skipping the transaction entirely when
2438 // know that the lists are identical
2439 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2440 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2441 if (!curr.isIdenticalTo(draw)) {
2442 mVisibleRegionsDirty = true;
2443 const size_t cc = curr.size();
2444 size_t dc = draw.size();
2445
2446 // find the displays that were removed
2447 // (ie: in drawing state but not in current state)
2448 // also handle displays that changed
2449 // (ie: displays that are in both lists)
2450 for (size_t i = 0; i < dc;) {
2451 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2452 if (j < 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002453 // Save display IDs before disconnecting.
2454 const auto internalDisplayId = getInternalDisplayId();
2455 const auto externalDisplayId = getExternalDisplayId();
2456
Lloyd Pique347200f2017-12-14 17:00:15 -08002457 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002458 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2459 display->disconnect(getHwComposer());
2460 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002461 if (internalDisplayId && internalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002462 if (mUseScheduler) {
2463 mScheduler->hotplugReceived(mAppConnectionHandle,
2464 EventThread::DisplayType::Primary, false);
2465 } else {
2466 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2467 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002468 } else if (externalDisplayId && externalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002469 if (mUseScheduler) {
2470 mScheduler->hotplugReceived(mAppConnectionHandle,
2471 EventThread::DisplayType::External, false);
2472 } else {
2473 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2474 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002475 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002476 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002477 } else {
2478 // this display is in both lists. see if something changed.
2479 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002480 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002481 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2482 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2483 if (state_binder != draw_binder) {
2484 // changing the surface is like destroying and
2485 // recreating the DisplayDevice, so we just remove it
2486 // from the drawing state, so that it get re-added
2487 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002488 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2489 display->disconnect(getHwComposer());
2490 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002491 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002492 mDrawingState.displays.removeItemsAt(i);
2493 dc--;
2494 // at this point we must loop to the next item
2495 continue;
2496 }
2497
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002498 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002499 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002500 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002501 }
2502 if ((state.orientation != draw[i].orientation) ||
2503 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002504 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002505 }
2506 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002507 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002508 }
2509 }
2510 }
2511 ++i;
2512 }
2513
2514 // find displays that were added
2515 // (ie: in current state but not in drawing state)
2516 for (size_t i = 0; i < cc; i++) {
2517 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2518 const DisplayDeviceState& state(curr[i]);
2519
2520 sp<DisplaySurface> dispSurface;
2521 sp<IGraphicBufferProducer> producer;
2522 sp<IGraphicBufferProducer> bqProducer;
2523 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002524 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002525
Dominik Laskowski075d3172018-05-24 15:50:06 -07002526 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002527 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002528 // Virtual displays without a surface are dormant:
2529 // they have external state (layer stack, projection,
2530 // etc.) but no internal state (i.e. a DisplayDevice).
2531 if (state.surface != nullptr) {
2532 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002533 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002534 int width = 0;
2535 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2536 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2537 int height = 0;
2538 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2539 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2540 int intFormat = 0;
2541 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2542 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002543 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002544
Dominik Laskowski075d3172018-05-24 15:50:06 -07002545 displayId =
2546 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002547 }
2548
2549 // TODO: Plumb requested format back up to consumer
2550
2551 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002552 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002553 bqProducer, bqConsumer,
2554 state.displayName);
2555
2556 dispSurface = vds;
2557 producer = vds;
2558 }
2559 } else {
2560 ALOGE_IF(state.surface != nullptr,
2561 "adding a supported display, but rendering "
2562 "surface is provided (%p), ignoring it",
2563 state.surface.get());
2564
Dominik Laskowski075d3172018-05-24 15:50:06 -07002565 displayId = state.displayId;
2566 LOG_ALWAYS_FATAL_IF(!displayId);
2567 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002568 producer = bqProducer;
2569 }
2570
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002571 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002572 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002573 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002574 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002575 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002576 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002577 LOG_ALWAYS_FATAL_IF(!displayId);
2578
2579 if (displayId == getInternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002580 if (mUseScheduler) {
2581 mScheduler->hotplugReceived(mAppConnectionHandle,
2582 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002583 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002584 } else {
2585 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2586 true);
2587 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002588 } else if (displayId == getExternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002589 if (mUseScheduler) {
2590 mScheduler->hotplugReceived(mAppConnectionHandle,
2591 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002592 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002593 } else {
2594 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2595 true);
2596 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002597 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002598 }
2599 }
2600 }
2601 }
2602 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002603
2604 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002605}
2606
Mathias Agopian87baae12012-07-31 12:38:26 -07002607void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002608{
Dan Stoza7dde5992015-05-22 09:51:44 -07002609 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002610 mCurrentState.traverseInZOrder([](Layer* layer) {
2611 layer->notifyAvailableFrames();
2612 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002613
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002614 /*
2615 * Traversal of the children
2616 * (perform the transaction for each of them if needed)
2617 */
2618
Robert Carr720e5062018-07-30 17:45:14 -07002619 bool inputChanged = false;
Mathias Agopian3559b072012-08-15 13:46:03 -07002620 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002621 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002622 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002623 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002624
2625 const uint32_t flags = layer->doTransaction(0);
2626 if (flags & Layer::eVisibleRegion)
2627 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002628
2629 if (flags & Layer::eInputInfoChanged) {
2630 inputChanged = true;
2631 }
Robert Carr2047fae2016-11-28 14:09:09 -08002632 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002633 }
2634
2635 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002636 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002637 */
2638
Mathias Agopiane57f2922012-08-09 16:29:12 -07002639 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002640 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002641 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002642 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002643
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002644 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002645 // The transform hint might have changed for some layers
2646 // (either because a display has changed, or because a layer
2647 // as changed).
2648 //
2649 // Walk through all the layers in currentLayers,
2650 // and update their transform hint.
2651 //
2652 // If a layer is visible only on a single display, then that
2653 // display is used to calculate the hint, otherwise we use the
2654 // default display.
2655 //
2656 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2657 // the hint is set before we acquire a buffer from the surface texture.
2658 //
2659 // NOTE: layer transactions have taken place already, so we use their
2660 // drawing state. However, SurfaceFlinger's own transaction has not
2661 // happened yet, so we must use the current state layer list
2662 // (soon to become the drawing state list).
2663 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002664 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002665 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002666 bool first = true;
2667 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002668 // NOTE: we rely on the fact that layers are sorted by
2669 // layerStack first (so we don't have to traverse the list
2670 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002671 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002672 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002673 currentlayerStack = layerStack;
2674 // figure out if this layerstack is mirrored
2675 // (more than one display) if so, pick the default display,
2676 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002677 hintDisplay = nullptr;
2678 for (const auto& [token, display] : mDisplays) {
2679 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2680 if (hintDisplay) {
2681 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002682 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002683 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002684 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002685 }
2686 }
2687 }
2688 }
Chet Haase91d25932013-04-11 15:24:55 -07002689
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002690 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002691 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2692 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002693
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002694 // could be null when this layer is using a layerStack
2695 // that is not visible on any display. Also can occur at
2696 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002697 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002698 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002699
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002700 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002701 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002702 if (hintDisplay) {
2703 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002704 }
Robert Carr2047fae2016-11-28 14:09:09 -08002705
2706 first = false;
2707 });
Mathias Agopian84300952012-11-21 16:02:13 -08002708 }
2709
2710
Mathias Agopian3559b072012-08-15 13:46:03 -07002711 /*
2712 * Perform our own transaction if needed
2713 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002714
2715 if (mLayersAdded) {
2716 mLayersAdded = false;
2717 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002718 mVisibleRegionsDirty = true;
2719 }
2720
2721 // some layers might have been removed, so
2722 // we need to update the regions they're exposing.
2723 if (mLayersRemoved) {
2724 mLayersRemoved = false;
2725 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002726 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002727 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002728 // this layer is not visible anymore
2729 // TODO: we could traverse the tree from front to back and
2730 // compute the actual visible region
2731 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002732 Region visibleReg;
2733 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002734 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002735 }
Robert Carr2047fae2016-11-28 14:09:09 -08002736 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002737 }
2738
2739 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002740
Vishnu Nairde19f852018-12-18 16:11:53 -08002741 if (inputChanged || mVisibleRegionsDirty) {
Robert Carr720e5062018-07-30 17:45:14 -07002742 updateInputWindows();
2743 }
2744
Riley Andrews03414a12014-07-01 14:22:59 -07002745 updateCursorAsync();
2746}
2747
Robert Carr720e5062018-07-30 17:45:14 -07002748void SurfaceFlinger::updateInputWindows() {
2749 ATRACE_CALL();
2750
Vishnu Nairde19f852018-12-18 16:11:53 -08002751 if (mInputFlinger == nullptr) {
2752 return;
2753 }
2754
Robert Carr720e5062018-07-30 17:45:14 -07002755 Vector<InputWindowInfo> inputHandles;
2756
2757 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2758 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002759 // When calculating the screen bounds we ignore the transparent region since it may
2760 // result in an unwanted offset.
2761 inputHandles.add(layer->fillInputInfo(
2762 layer->computeScreenBounds(false /* reduceTransparentRegion */)));
Robert Carr720e5062018-07-30 17:45:14 -07002763 }
2764 });
2765 mInputFlinger->setInputWindows(inputHandles);
2766}
2767
Riley Andrews03414a12014-07-01 14:22:59 -07002768void SurfaceFlinger::updateCursorAsync()
2769{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002770 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002771 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002772 continue;
2773 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002774
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002775 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2776 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002777 }
2778 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002779}
2780
chaviw61626f22018-11-15 16:26:27 -08002781void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
2782 if (layer->hasReadyFrame()) {
2783 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
2784 if (layer->shouldPresentNow(expectedPresentTime)) {
2785 bool ignored = false;
2786 layer->latchBuffer(ignored, systemTime(), Fence::NO_FENCE);
2787 }
2788 }
2789 layer->releasePendingBuffer(systemTime());
2790}
2791
Mathias Agopian4fec8732012-06-29 14:12:52 -07002792void SurfaceFlinger::commitTransaction()
2793{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002794 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002795 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002796 for (const auto& l : mLayersPendingRemoval) {
2797 recordBufferingStats(l->getName().string(),
2798 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07002799
2800 // We need to release the HWC layers when the Layer is removed
2801 // from the current state otherwise the HWC layer just continues
2802 // showing at its last configured state until we eventually
2803 // abandon the buffer queue.
2804 if (l->isRemovedFromCurrentState()) {
Robert Carr3aee9892018-11-07 12:53:41 -08002805 l->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* child) {
chaviw61626f22018-11-15 16:26:27 -08002806 child->destroyHwcLayersForAllDisplays();
2807 latchAndReleaseBuffer(child);
Robert Carr3aee9892018-11-07 12:53:41 -08002808 });
Robert Carr2e102c92018-10-23 12:11:15 -07002809 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002810 }
2811 mLayersPendingRemoval.clear();
2812 }
2813
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002814 // If this transaction is part of a window animation then the next frame
2815 // we composite should be considered an animation as well.
2816 mAnimCompositionPending = mAnimTransactionPending;
2817
Mathias Agopian4fec8732012-06-29 14:12:52 -07002818 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002819 // clear the "changed" flags in current state
2820 mCurrentState.colorMatrixChanged = false;
2821
Robert Carr1f0a16a2016-10-24 16:27:39 -07002822 mDrawingState.traverseInZOrder([](Layer* layer) {
2823 layer->commitChildList();
2824 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002825 mTransactionPending = false;
2826 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002827 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002828}
2829
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002830void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2831 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002832 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002833 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002834
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002835 Region aboveOpaqueLayers;
2836 Region aboveCoveredLayers;
2837 Region dirty;
2838
Mathias Agopian87baae12012-07-31 12:38:26 -07002839 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002840
Robert Carr2047fae2016-11-28 14:09:09 -08002841 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Jesse Hall01e29052013-02-19 16:13:35 -08002842 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002843 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002844 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002845 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002846
Mathias Agopianab028732010-03-16 16:41:46 -07002847 /*
2848 * opaqueRegion: area of a surface that is fully opaque.
2849 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002850 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002851
2852 /*
2853 * visibleRegion: area of a surface that is visible on screen
2854 * and not fully transparent. This is essentially the layer's
2855 * footprint minus the opaque regions above it.
2856 * Areas covered by a translucent surface are considered visible.
2857 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002858 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002859
2860 /*
2861 * coveredRegion: area of a surface that is covered by all
2862 * visible regions above it (which includes the translucent areas).
2863 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002864 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002865
Jesse Halla8026d22012-09-25 13:25:04 -07002866 /*
2867 * transparentRegion: area of a surface that is hinted to be completely
2868 * transparent. This is only used to tell when the layer has no visible
2869 * non-transparent regions and can be removed from the layer list. It
2870 * does not affect the visibleRegion of this layer or any layers
2871 * beneath it. The hint may not be correct if apps don't respect the
2872 * SurfaceView restrictions (which, sadly, some don't).
2873 */
2874 Region transparentRegion;
2875
Mathias Agopianab028732010-03-16 16:41:46 -07002876
2877 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002878 if (CC_LIKELY(layer->isVisible())) {
Ady Abraham83729882018-12-07 12:26:48 -08002879 const bool translucent = !layer->isDrawingOpaque();
Robert Carr1f0a16a2016-10-24 16:27:39 -07002880 Rect bounds(layer->computeScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07002881
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002882 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002883 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002884 if (!visibleRegion.isEmpty()) {
2885 // Remove the transparent area from the visible region
2886 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002887 if (tr.preserveRects()) {
2888 // transform the transparent region
Ady Abraham83729882018-12-07 12:26:48 -08002889 transparentRegion =
2890 tr.transform(layer->getDrawingActiveTransparentRegion());
Mathias Agopian4fec8732012-06-29 14:12:52 -07002891 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002892 // transformation too complex, can't do the
2893 // transparent region optimization.
2894 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002895 }
Mathias Agopianab028732010-03-16 16:41:46 -07002896 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002897
Mathias Agopianab028732010-03-16 16:41:46 -07002898 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002899 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002900 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002901 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002902 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002903 // the opaque region is the layer's footprint
2904 opaqueRegion = visibleRegion;
2905 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002906 }
2907 }
2908
Robert Carre5f4f692018-01-12 13:12:28 -08002909 if (visibleRegion.isEmpty()) {
2910 layer->clearVisibilityRegions();
2911 return;
2912 }
2913
Mathias Agopianab028732010-03-16 16:41:46 -07002914 // Clip the covered region to the visible region
2915 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2916
2917 // Update aboveCoveredLayers for next (lower) layer
2918 aboveCoveredLayers.orSelf(visibleRegion);
2919
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002920 // subtract the opaque region covered by the layers above us
2921 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002922
2923 // compute this layer's dirty region
2924 if (layer->contentDirty) {
2925 // we need to invalidate the whole region
2926 dirty = visibleRegion;
2927 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002928 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002929 layer->contentDirty = false;
2930 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002931 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002932 * the exposed region consists of two components:
2933 * 1) what's VISIBLE now and was COVERED before
2934 * 2) what's EXPOSED now less what was EXPOSED before
2935 *
2936 * note that (1) is conservative, we start with the whole
2937 * visible region but only keep what used to be covered by
2938 * something -- which mean it may have been exposed.
2939 *
2940 * (2) handles areas that were not covered by anything but got
2941 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002942 */
Mathias Agopianab028732010-03-16 16:41:46 -07002943 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002944 const Region oldVisibleRegion = layer->visibleRegion;
2945 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002946 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2947 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002948 }
2949 dirty.subtractSelf(aboveOpaqueLayers);
2950
2951 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002952 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002953
Mathias Agopianab028732010-03-16 16:41:46 -07002954 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002955 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002956
Jesse Halla8026d22012-09-25 13:25:04 -07002957 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002958 layer->setVisibleRegion(visibleRegion);
2959 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002960 layer->setVisibleNonTransparentRegion(
2961 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002962 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002963
Mathias Agopian87baae12012-07-31 12:38:26 -07002964 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002965}
2966
Chia-I Wuab0c3192017-08-01 11:29:00 -07002967void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002968 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002969 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2970 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002971 }
2972 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002973}
2974
Dan Stoza6b9454d2014-11-07 16:00:59 -08002975bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002976{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002977 ALOGV("handlePageFlip");
2978
Brian Andersond6927fb2016-07-23 23:37:30 -07002979 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002980
Mathias Agopian4fec8732012-06-29 14:12:52 -07002981 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002982 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002983 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002984
2985 // Store the set of layers that need updates. This set must not change as
2986 // buffers are being latched, as this could result in a deadlock.
2987 // Example: Two producers share the same command stream and:
2988 // 1.) Layer 0 is latched
2989 // 2.) Layer 0 gets a new frame
2990 // 2.) Layer 1 gets a new frame
2991 // 3.) Layer 1 is latched.
2992 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2993 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002994 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002995 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002996 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002997 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
2998 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002999 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003000 } else {
3001 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003002 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003003 } else {
3004 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003005 }
Robert Carr2047fae2016-11-28 14:09:09 -08003006 });
3007
Dan Stoza9e56aa02015-11-02 13:00:03 -08003008 for (auto& layer : mLayersWithQueuedFrames) {
Alec Mouri86770e52018-09-24 22:40:58 +00003009 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
Dan Stozaee44edd2015-03-23 15:50:23 -07003010 layer->useSurfaceDamage();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003011 invalidateLayerStack(layer, dirty);
Chia-I Wua36bf922017-06-30 12:51:05 -07003012 if (layer->isBufferLatched()) {
Mike Stroyan0cd76192017-04-20 12:10:48 -06003013 newDataLatched = true;
3014 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003015 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003016
Alec Mouri86770e52018-09-24 22:40:58 +00003017 // Clear the renderengine fence here...
3018 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3019 // clear instead of sp::clear.
3020 getBE().flushFence = Fence::NO_FENCE;
3021
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003022 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003023
Vishnu Nairde19f852018-12-18 16:11:53 -08003024 if (visibleRegions) {
3025 // Update input window info if the layer receives its first buffer.
3026 updateInputWindows();
3027 }
3028
Dan Stoza6b9454d2014-11-07 16:00:59 -08003029 // If we will need to wake up at some time in the future to deal with a
3030 // queued frame that shouldn't be displayed during this vsync period, wake
3031 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003032 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003033 signalLayerUpdate();
3034 }
3035
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003036 // enter boot animation on first buffer latch
3037 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3038 ALOGI("Enter boot animation");
3039 mBootStage = BootStage::BOOTANIMATION;
3040 }
3041
Dan Stoza6b9454d2014-11-07 16:00:59 -08003042 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003043 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003044}
3045
Mathias Agopianad456f92011-01-13 17:53:01 -08003046void SurfaceFlinger::invalidateHwcGeometry()
3047{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003048 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003049}
3050
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003051void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& display,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003052 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08003053 // We only need to actually compose the display if:
3054 // 1) It is being handled by hardware composer, which may need this to
3055 // keep its virtual display state machine in sync, or
3056 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski34157762018-10-31 13:07:19 -07003057 if (!display->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003058 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003059 return;
3060 }
3061
Dan Stoza9e56aa02015-11-02 13:00:03 -08003062 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003063 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003064
3065 // swap buffers (presentation)
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003066 display->queueBuffer(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003067}
3068
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003069bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003070 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003071
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003072 const Region bounds(display->bounds());
3073 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07003074 const auto displayId = display->getId();
3075 const bool hasClientComposition = getBE().mHwc->hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003076 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003077
Peiyong Lind3788632018-09-18 16:01:31 -07003078 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003079 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003080
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003081 // Framebuffer will live in this scope for GPU composition.
3082 std::unique_ptr<renderengine::BindNativeBufferAsFramebuffer> fbo;
3083
Dan Stoza9e56aa02015-11-02 13:00:03 -08003084 if (hasClientComposition) {
3085 ALOGV("hasClientComposition");
3086
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003087 sp<GraphicBuffer> buf = display->dequeueBuffer();
3088
3089 if (buf == nullptr) {
3090 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3091 "client composition for this frame",
3092 display->getDisplayName().c_str());
3093 return false;
3094 }
3095
3096 // Bind the framebuffer in this scope.
3097 fbo = std::make_unique<renderengine::BindNativeBufferAsFramebuffer>(getRenderEngine(),
3098 buf->getNativeBuffer());
3099
3100 if (fbo->getStatus() != NO_ERROR) {
3101 ALOGW("Binding buffer for display [%s] failed with status: %d",
3102 display->getDisplayName().c_str(), fbo->getStatus());
3103 return false;
3104 }
3105
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003106 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003107 if (display->hasWideColorGamut()) {
3108 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003109 }
3110 getBE().mRenderEngine->setOutputDataSpace(outputDataspace);
Peiyong Linfb069302018-04-25 14:34:31 -07003111 getBE().mRenderEngine->setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003112 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003113
Dominik Laskowski7e045462018-05-30 13:02:02 -07003114 const bool hasDeviceComposition = getBE().mHwc->hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003115 const bool skipClientColorTransform =
3116 getBE().mHwc
3117 ->hasDisplayCapability(displayId,
3118 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003119
Peiyong Lind3788632018-09-18 16:01:31 -07003120 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003121 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3122 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003123 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003124 }
3125
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003126 display->setViewportAndProjection();
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003127
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003128 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003129 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003130 // when using overlays, we assume a fully transparent framebuffer
3131 // NOTE: we could reduce how much we need to clear, for instance
3132 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003133 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003134 // We'll revisit later if needed.
David Sodmanbc815282017-11-05 18:57:52 -08003135 getBE().mRenderEngine->clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003136 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003137 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003138 // we're left with the letterbox region
3139 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003140 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003141
3142 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003143 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003144
Mathias Agopianb9494d52012-04-18 02:28:45 -07003145 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003146 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003147 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003148 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003149 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003150 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003151
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003152 const Rect& bounds = display->getBounds();
3153 const Rect& scissor = display->getScissor();
3154 if (scissor != bounds) {
3155 // scissor doesn't match the screen's dimensions, so we
3156 // need to clear everything outside of it and enable
3157 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003158
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003159 // enable scissor for this frame
Alec Mouri05483a02018-09-10 21:03:42 +00003160 getBE().mRenderEngine->setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003161 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003162 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003163
Mathias Agopian85d751c2012-08-29 16:59:24 -07003164 /*
3165 * and then, render the layers targeted at the framebuffer
3166 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003167
Dan Stoza9e56aa02015-11-02 13:00:03 -08003168 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07003169 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003170 bool firstLayer = true;
David Sodmanc1498e62018-09-12 14:36:26 -07003171 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003172 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003173 displayTransform.transform(layer->visibleRegion)));
3174 ALOGV("Layer: %s", layer->getName().string());
3175 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003176 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003177 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003178 case HWC2::Composition::Cursor:
3179 case HWC2::Composition::Device:
3180 case HWC2::Composition::Sideband:
3181 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003182 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07003183 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
Ady Abraham83729882018-12-07 12:26:48 -08003184 layer->isDrawingOpaque() && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003185 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003186 // never clear the very first layer since we're
3187 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003188 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003189 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003190 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003191 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003192 case HWC2::Composition::Client: {
Peiyong Lind3788632018-09-18 16:01:31 -07003193 if (layer->hasColorTransform()) {
3194 mat4 tmpMatrix;
3195 if (applyColorMatrix) {
3196 tmpMatrix = mDrawingState.colorMatrix;
3197 }
3198 tmpMatrix *= layer->getColorTransform();
Peiyong Lind3788632018-09-18 16:01:31 -07003199 getRenderEngine().setColorTransform(tmpMatrix);
3200 } else {
3201 getRenderEngine().setColorTransform(colorMatrix);
3202 }
David Sodmanc1498e62018-09-12 14:36:26 -07003203 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003204 break;
3205 }
3206 default:
3207 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003208 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003209 } else {
3210 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003211 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003212 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003213 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003214
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003215 // Perform some cleanup steps if we used client composition.
3216 if (hasClientComposition) {
3217 getRenderEngine().setColorTransform(mat4());
3218 getBE().mRenderEngine->disableScissor();
3219 display->finishBuffer();
3220 // Clear out error flags here so that we don't wait until next
3221 // composition to log.
3222 getRenderEngine().checkErrors();
3223 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003224 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003225}
3226
Chia-I Wu28e3a252018-09-07 12:05:02 -07003227void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003228 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003229 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003230}
3231
Dan Stoza7d89d062015-04-30 13:29:25 -07003232status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003233 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003234 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003235 const sp<Layer>& lbc,
3236 const sp<Layer>& parent)
Mathias Agopian96f08192010-06-02 23:28:45 -07003237{
Dan Stoza7d89d062015-04-30 13:29:25 -07003238 // add this layer to the current state list
3239 {
3240 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003241 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003242 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3243 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003244 return NO_MEMORY;
3245 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003246 if (parent == nullptr) {
3247 mCurrentState.layersSortedByZ.add(lbc);
3248 } else {
Robert Carr2e102c92018-10-23 12:11:15 -07003249 if (parent->isRemovedFromCurrentState()) {
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003250 ALOGE("addClientLayer called with a removed parent");
chaviw61626f22018-11-15 16:26:27 -08003251 lbc->onRemovedFromCurrentState();
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003252 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003253 parent->addChild(lbc);
3254 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003255
Yiwei Zhang243b3782018-05-15 17:40:04 -07003256 if (gbc != nullptr) {
3257 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3258 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3259 mMaxGraphicBufferProducerListSize,
3260 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3261 mGraphicBufferProducerList.size(),
3262 mMaxGraphicBufferProducerListSize, mNumLayers);
3263 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003264 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003265 }
3266
Mathias Agopian96f08192010-06-02 23:28:45 -07003267 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003268 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003269
Dan Stoza7d89d062015-04-30 13:29:25 -07003270 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003271}
3272
Robert Carr8d2711b2018-11-14 16:36:18 -08003273status_t SurfaceFlinger::removeLayer(const sp<Layer>& layer) {
Robert Carr7f9b8992017-03-10 11:08:39 -08003274 Mutex::Autolock _l(mStateLock);
Robert Carr8d2711b2018-11-14 16:36:18 -08003275 return removeLayerLocked(mStateLock, layer);
chaviwca27f252018-02-06 16:46:39 -08003276}
Robert Carr7f9b8992017-03-10 11:08:39 -08003277
Robert Carr8d2711b2018-11-14 16:36:18 -08003278status_t SurfaceFlinger::removeLayerLocked(const Mutex& lock, const sp<Layer>& layer) {
chaviw5aedec92018-10-22 10:40:38 -07003279 if (layer->isLayerDetached()) {
3280 return NO_ERROR;
3281 }
3282
Robert Carr1f0a16a2016-10-24 16:27:39 -07003283 const auto& p = layer->getParent();
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003284 ssize_t index;
Chia-I Wu98f1c102017-05-30 14:54:08 -07003285 if (p != nullptr) {
Chia-I Wufae51c42017-06-15 12:53:59 -07003286 index = p->removeChild(layer);
Chia-I Wu515dc9c2017-06-15 12:53:59 -07003287 } else {
3288 index = mCurrentState.layersSortedByZ.remove(layer);
Chia-I Wu98f1c102017-05-30 14:54:08 -07003289 }
3290
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003291 layer->onRemovedFromCurrentState();
Robert Carr2e102c92018-10-23 12:11:15 -07003292
3293 markLayerPendingRemovalLocked(lock, layer);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003294 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003295}
3296
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003297uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003298 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003299}
3300
Mathias Agopian3f844832013-08-07 21:24:32 -07003301uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003302 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003303}
3304
Mathias Agopian3f844832013-08-07 21:24:32 -07003305uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003306 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003307}
3308
3309uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003310 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003311 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003312 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003313 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003314 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003315 }
3316 return old;
3317}
3318
chaviwca27f252018-02-06 16:46:39 -08003319bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3320 for (const ComposerState& state : states) {
3321 // Here we need to check that the interface we're given is indeed
3322 // one of our own. A malicious client could give us a nullptr
3323 // IInterface, or one of its own or even one of our own but a
3324 // different type. All these situations would cause us to crash.
3325 if (state.client == nullptr) {
3326 return true;
3327 }
3328
3329 sp<IBinder> binder = IInterface::asBinder(state.client);
3330 if (binder == nullptr) {
3331 return true;
3332 }
3333
3334 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3335 return true;
3336 }
3337 }
3338 return false;
3339}
3340
Mathias Agopian8b33f032012-07-24 20:43:54 -07003341void SurfaceFlinger::setTransactionState(
chaviwca27f252018-02-06 16:46:39 -08003342 const Vector<ComposerState>& states,
Mathias Agopian8b33f032012-07-24 20:43:54 -07003343 const Vector<DisplayState>& displays,
3344 uint32_t flags)
3345{
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003346 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003347 Mutex::Autolock _l(mStateLock);
Jamie Gennis28378392011-10-12 17:39:00 -07003348 uint32_t transactionFlags = 0;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003349
chaviwca27f252018-02-06 16:46:39 -08003350 if (containsAnyInvalidClientState(states)) {
3351 return;
3352 }
3353
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003354 if (flags & eAnimation) {
3355 // For window updates that are part of an animation we must wait for
3356 // previous animation "frames" to be handled.
3357 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003358 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003359 if (CC_UNLIKELY(err != NO_ERROR)) {
3360 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003361 // caller after a few seconds.
3362 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3363 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003364 mAnimTransactionPending = false;
3365 break;
3366 }
3367 }
3368 }
3369
chaviwca27f252018-02-06 16:46:39 -08003370 for (const DisplayState& display : displays) {
3371 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003372 }
3373
Marissa Walle2ffb422018-10-12 11:33:52 -07003374 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003375 for (const ComposerState& state : states) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003376 clientStateFlags |= setClientStateLocked(state);
chaviwca27f252018-02-06 16:46:39 -08003377 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003378 // If the state doesn't require a traversal and there are callbacks, send them now
3379 if (!(clientStateFlags & eTraversalNeeded)) {
3380 mTransactionCompletedThread.sendCallbacks();
3381 }
3382 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003383
3384 // Iterate through all layers again to determine if any need to be destroyed. Marking layers
3385 // as destroyed should only occur after setting all other states. This is to allow for a
3386 // child re-parent to happen before marking its original parent as destroyed (which would
3387 // then mark the child as destroyed).
3388 for (const ComposerState& state : states) {
3389 setDestroyStateLocked(state);
Mathias Agopian698c0872011-06-28 19:09:31 -07003390 }
Mathias Agopian698c0872011-06-28 19:09:31 -07003391
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003392 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3393 // anyway. This can be used as a flush mechanism for previous async transactions.
3394 // Empty animation transaction can be used to simulate back-pressure, so also force a
3395 // transaction for empty animation transactions.
3396 if (transactionFlags == 0 &&
3397 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003398 transactionFlags = eTransactionNeeded;
3399 }
3400
Mathias Agopian386aa982011-11-07 21:58:03 -08003401 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003402 if (mInterceptor->isEnabled()) {
3403 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003404 }
Irvel468051e2016-06-13 16:44:44 -07003405
Mathias Agopian386aa982011-11-07 21:58:03 -08003406 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003407 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3408 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003409 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003410
3411 // if this is a synchronous transaction, wait for it to take effect
3412 // before returning.
3413 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003414 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003415 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003416 if (flags & eAnimation) {
3417 mAnimTransactionPending = true;
3418 }
3419 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003420 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3421 if (CC_UNLIKELY(err != NO_ERROR)) {
3422 // just in case something goes wrong in SF, return to the
3423 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003424 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3425 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003426 break;
3427 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003428 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003429 }
3430}
3431
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003432uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3433 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3434 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003435
Mathias Agopiane57f2922012-08-09 16:29:12 -07003436 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003437 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3438
3439 const uint32_t what = s.what;
3440 if (what & DisplayState::eSurfaceChanged) {
3441 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3442 state.surface = s.surface;
3443 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003444 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003445 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003446 if (what & DisplayState::eLayerStackChanged) {
3447 if (state.layerStack != s.layerStack) {
3448 state.layerStack = s.layerStack;
3449 flags |= eDisplayTransactionNeeded;
3450 }
3451 }
3452 if (what & DisplayState::eDisplayProjectionChanged) {
3453 if (state.orientation != s.orientation) {
3454 state.orientation = s.orientation;
3455 flags |= eDisplayTransactionNeeded;
3456 }
3457 if (state.frame != s.frame) {
3458 state.frame = s.frame;
3459 flags |= eDisplayTransactionNeeded;
3460 }
3461 if (state.viewport != s.viewport) {
3462 state.viewport = s.viewport;
3463 flags |= eDisplayTransactionNeeded;
3464 }
3465 }
3466 if (what & DisplayState::eDisplaySizeChanged) {
3467 if (state.width != s.width) {
3468 state.width = s.width;
3469 flags |= eDisplayTransactionNeeded;
3470 }
3471 if (state.height != s.height) {
3472 state.height = s.height;
3473 flags |= eDisplayTransactionNeeded;
3474 }
3475 }
3476
Mathias Agopiane57f2922012-08-09 16:29:12 -07003477 return flags;
3478}
3479
Robert Carrd4ae7f32018-06-07 16:10:57 -07003480bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3481 IPCThreadState* ipc = IPCThreadState::self();
3482 const int pid = ipc->getCallingPid();
3483 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003484 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003485 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003486 return false;
3487 }
3488 return true;
3489}
3490
chaviwca27f252018-02-06 16:46:39 -08003491uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3492 const layer_state_t& s = composerState.state;
3493 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3494
Mathias Agopian13127d82013-03-05 17:47:11 -08003495 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003496 if (layer == nullptr) {
3497 return 0;
3498 }
3499
chaviw8b3871a2017-11-01 17:41:01 -07003500 uint32_t flags = 0;
3501
Garfield Tan8a3083e2018-12-03 13:21:07 -08003502 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003503 bool geometryAppliesWithResize =
3504 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003505
3506 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3507 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003508 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003509 layer->pushPendingState();
3510 }
3511
chaviw8b3871a2017-11-01 17:41:01 -07003512 if (what & layer_state_t::ePositionChanged) {
3513 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3514 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003515 }
chaviw8b3871a2017-11-01 17:41:01 -07003516 }
3517 if (what & layer_state_t::eLayerChanged) {
3518 // NOTE: index needs to be calculated before we update the state
3519 const auto& p = layer->getParent();
3520 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003521 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003522 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003523 mCurrentState.layersSortedByZ.removeAt(idx);
3524 mCurrentState.layersSortedByZ.add(layer);
3525 // we need traversal (state changed)
3526 // AND transaction (list changed)
3527 flags |= eTransactionNeeded|eTraversalNeeded;
3528 }
chaviw8b3871a2017-11-01 17:41:01 -07003529 } else {
3530 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003531 flags |= eTransactionNeeded|eTraversalNeeded;
3532 }
3533 }
chaviw8b3871a2017-11-01 17:41:01 -07003534 }
3535 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003536 // NOTE: index needs to be calculated before we update the state
3537 const auto& p = layer->getParent();
3538 if (p == nullptr) {
3539 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3540 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3541 mCurrentState.layersSortedByZ.removeAt(idx);
3542 mCurrentState.layersSortedByZ.add(layer);
3543 // we need traversal (state changed)
3544 // AND transaction (list changed)
3545 flags |= eTransactionNeeded|eTraversalNeeded;
3546 }
3547 } else {
3548 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3549 flags |= eTransactionNeeded|eTraversalNeeded;
3550 }
chaviw8b3871a2017-11-01 17:41:01 -07003551 }
3552 }
3553 if (what & layer_state_t::eSizeChanged) {
3554 if (layer->setSize(s.w, s.h)) {
3555 flags |= eTraversalNeeded;
3556 }
3557 }
3558 if (what & layer_state_t::eAlphaChanged) {
3559 if (layer->setAlpha(s.alpha))
3560 flags |= eTraversalNeeded;
3561 }
3562 if (what & layer_state_t::eColorChanged) {
3563 if (layer->setColor(s.color))
3564 flags |= eTraversalNeeded;
3565 }
Peiyong Lind3788632018-09-18 16:01:31 -07003566 if (what & layer_state_t::eColorTransformChanged) {
3567 if (layer->setColorTransform(s.colorTransform)) {
3568 flags |= eTraversalNeeded;
3569 }
3570 }
chaviw8b3871a2017-11-01 17:41:01 -07003571 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003572 // TODO: b/109894387
3573 //
3574 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3575 // rotation. To see the problem observe that if we have a square parent, and a child
3576 // of the same size, then we rotate the child 45 degrees around it's center, the child
3577 // must now be cropped to a non rectangular 8 sided region.
3578 //
3579 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3580 // private API, and the WindowManager only uses rotation in one case, which is on a top
3581 // level layer in which cropping is not an issue.
3582 //
3583 // However given that abuse of rotation matrices could lead to surfaces extending outside
3584 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3585 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3586 // transformations.
3587 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003588 flags |= eTraversalNeeded;
3589 }
3590 if (what & layer_state_t::eTransparentRegionChanged) {
3591 if (layer->setTransparentRegionHint(s.transparentRegion))
3592 flags |= eTraversalNeeded;
3593 }
3594 if (what & layer_state_t::eFlagsChanged) {
3595 if (layer->setFlags(s.flags, s.mask))
3596 flags |= eTraversalNeeded;
3597 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003598 if (what & layer_state_t::eCropChanged_legacy) {
3599 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003600 flags |= eTraversalNeeded;
3601 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003602 if (what & layer_state_t::eCornerRadiusChanged) {
3603 if (layer->setCornerRadius(s.cornerRadius))
3604 flags |= eTraversalNeeded;
3605 }
chaviw8b3871a2017-11-01 17:41:01 -07003606 if (what & layer_state_t::eLayerStackChanged) {
3607 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3608 // We only allow setting layer stacks for top level layers,
3609 // everything else inherits layer stack from its parent.
3610 if (layer->hasParent()) {
3611 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3612 layer->getName().string());
3613 } else if (idx < 0) {
3614 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3615 "that also does not appear in the top level layer list. Something"
3616 " has gone wrong.", layer->getName().string());
3617 } else if (layer->setLayerStack(s.layerStack)) {
3618 mCurrentState.layersSortedByZ.removeAt(idx);
3619 mCurrentState.layersSortedByZ.add(layer);
3620 // we need traversal (state changed)
3621 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003622 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003623 }
3624 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003625 if (what & layer_state_t::eDeferTransaction_legacy) {
3626 if (s.barrierHandle_legacy != nullptr) {
3627 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3628 } else if (s.barrierGbp_legacy != nullptr) {
3629 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003630 if (authenticateSurfaceTextureLocked(gbp)) {
3631 const auto& otherLayer =
3632 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003633 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003634 } else {
3635 ALOGE("Attempt to defer transaction to to an"
3636 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003637 }
3638 }
chaviw8b3871a2017-11-01 17:41:01 -07003639 // We don't trigger a traversal here because if no other state is
3640 // changed, we don't want this to cause any more work
3641 }
3642 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003643 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003644 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003645 if (!hadParent) {
3646 mCurrentState.layersSortedByZ.remove(layer);
3647 }
chaviw8b3871a2017-11-01 17:41:01 -07003648 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003649 }
chaviw8b3871a2017-11-01 17:41:01 -07003650 }
3651 if (what & layer_state_t::eReparentChildren) {
3652 if (layer->reparentChildren(s.reparentHandle)) {
3653 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003654 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003655 }
chaviw8b3871a2017-11-01 17:41:01 -07003656 if (what & layer_state_t::eDetachChildren) {
3657 layer->detachChildren();
3658 }
3659 if (what & layer_state_t::eOverrideScalingModeChanged) {
3660 layer->setOverrideScalingMode(s.overrideScalingMode);
3661 // We don't trigger a traversal here because if no other state is
3662 // changed, we don't want this to cause any more work
3663 }
Marissa Wall61c58622018-07-18 10:12:20 -07003664 if (what & layer_state_t::eTransformChanged) {
3665 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3666 }
3667 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3668 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3669 flags |= eTraversalNeeded;
3670 }
3671 if (what & layer_state_t::eCropChanged) {
3672 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3673 }
Marissa Wall861616d2018-10-22 12:52:23 -07003674 if (what & layer_state_t::eFrameChanged) {
3675 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3676 }
Marissa Wall61c58622018-07-18 10:12:20 -07003677 if (what & layer_state_t::eBufferChanged) {
3678 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3679 }
3680 if (what & layer_state_t::eAcquireFenceChanged) {
3681 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3682 }
3683 if (what & layer_state_t::eDataspaceChanged) {
3684 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3685 }
3686 if (what & layer_state_t::eHdrMetadataChanged) {
3687 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3688 }
3689 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3690 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3691 }
3692 if (what & layer_state_t::eApiChanged) {
3693 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3694 }
3695 if (what & layer_state_t::eSidebandStreamChanged) {
3696 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3697 }
Robert Carr720e5062018-07-30 17:45:14 -07003698 if (what & layer_state_t::eInputInfoChanged) {
3699 layer->setInputInfo(s.inputInfo);
3700 flags |= eTraversalNeeded;
3701 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003702 std::vector<sp<CallbackHandle>> callbackHandles;
3703 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
3704 mTransactionCompletedThread.run();
3705 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
3706 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3707 }
3708 }
3709 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3710 // Do not put anything that updates layer state or modifies flags after
3711 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003712 return flags;
3713}
3714
chaviwca27f252018-02-06 16:46:39 -08003715void SurfaceFlinger::setDestroyStateLocked(const ComposerState& composerState) {
3716 const layer_state_t& state = composerState.state;
3717 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3718
3719 sp<Layer> layer(client->getLayerUser(state.surface));
3720 if (layer == nullptr) {
3721 return;
3722 }
3723
chaviwca27f252018-02-06 16:46:39 -08003724 if (state.what & layer_state_t::eDestroySurface) {
3725 removeLayerLocked(mStateLock, layer);
3726 }
3727}
3728
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003729status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003730 const String8& name,
3731 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003732 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003733 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003734 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003735{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003736 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003737 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003738 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003739 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003740 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003741
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003742 status_t result = NO_ERROR;
3743
3744 sp<Layer> layer;
3745
Cody Northropbc755282017-03-31 12:00:08 -06003746 String8 uniqueName = getUniqueLayerName(name);
3747
Mathias Agopian3165cc22012-08-08 19:42:09 -07003748 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003749 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003750 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3751 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003752
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003753 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003754 case ISurfaceComposerClient::eFXSurfaceBufferState:
3755 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3756 break;
chaviw13fdc492017-06-27 12:40:18 -07003757 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003758 // check if buffer size is set for color layer.
3759 if (w > 0 || h > 0) {
3760 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3761 int(w), int(h));
3762 return BAD_VALUE;
3763 }
3764
chaviw13fdc492017-06-27 12:40:18 -07003765 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003766 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003767 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003768 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003769 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003770 // check if buffer size is set for container layer.
3771 if (w > 0 || h > 0) {
3772 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3773 int(w), int(h));
3774 return BAD_VALUE;
3775 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07003776 result = createContainerLayer(client,
3777 uniqueName, w, h, flags,
3778 handle, &layer);
3779 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003780 default:
3781 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003782 break;
3783 }
3784
Dan Stoza7d89d062015-04-30 13:29:25 -07003785 if (result != NO_ERROR) {
3786 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003787 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003788
Chia-I Wuab0c3192017-08-01 11:29:00 -07003789 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3790 // TODO b/64227542
3791 if (windowType == 441731) {
3792 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3793 layer->setPrimaryDisplayOnly();
3794 }
3795
Albert Chaulk479c60c2017-01-27 14:21:34 -05003796 layer->setInfo(windowType, ownerUid);
3797
Robert Carr1f0a16a2016-10-24 16:27:39 -07003798 result = addClientLayer(client, *handle, *gbp, layer, *parent);
Dan Stoza7d89d062015-04-30 13:29:25 -07003799 if (result != NO_ERROR) {
3800 return result;
3801 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003802 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003803
3804 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003805 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003806}
3807
Cody Northropbc755282017-03-31 12:00:08 -06003808String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3809{
3810 bool matchFound = true;
3811 uint32_t dupeCounter = 0;
3812
3813 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3814 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3815
Dan Stoza436ccf32018-06-21 12:10:12 -07003816 // Grab the state lock since we're accessing mCurrentState
3817 Mutex::Autolock lock(mStateLock);
3818
Cody Northropbc755282017-03-31 12:00:08 -06003819 // Loop over layers until we're sure there is no matching name
3820 while (matchFound) {
3821 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003822 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003823 if (layer->getName() == uniqueName) {
3824 matchFound = true;
3825 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3826 }
3827 });
3828 }
3829
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003830 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3831 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003832
3833 return uniqueName;
3834}
3835
Marissa Wallfd668622018-05-10 10:21:13 -07003836status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3837 uint32_t w, uint32_t h, uint32_t flags,
3838 PixelFormat& format, sp<IBinder>* handle,
3839 sp<IGraphicBufferProducer>* gbp,
3840 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003841 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003842 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003843 case PIXEL_FORMAT_TRANSPARENT:
3844 case PIXEL_FORMAT_TRANSLUCENT:
3845 format = PIXEL_FORMAT_RGBA_8888;
3846 break;
3847 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003848 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003849 break;
3850 }
3851
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003852 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07003853 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07003854 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003855 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003856 *handle = layer->getHandle();
3857 *gbp = layer->getProducer();
3858 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003859 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003860
Marissa Wallfd668622018-05-10 10:21:13 -07003861 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003862 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003863}
3864
Marissa Wall61c58622018-07-18 10:12:20 -07003865status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3866 uint32_t w, uint32_t h, uint32_t flags,
3867 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003868 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07003869 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07003870 *handle = layer->getHandle();
3871 *outLayer = layer;
3872
3873 return NO_ERROR;
3874}
3875
chaviw13fdc492017-06-27 12:40:18 -07003876status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003877 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003878 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003879{
Lloyd Pique90c115d2018-09-18 21:39:42 -07003880 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003881 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003882 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003883}
3884
Robert Carr6b3f6c52018-08-13 13:05:17 -07003885status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
3886 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3887 sp<IBinder>* handle, sp<Layer>* outLayer)
3888{
Lloyd Pique90c115d2018-09-18 21:39:42 -07003889 *outLayer =
3890 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07003891 *handle = (*outLayer)->getHandle();
3892 return NO_ERROR;
3893}
3894
3895
Mathias Agopianac9fa422013-02-11 16:40:36 -08003896status_t SurfaceFlinger::onLayerRemoved(const sp<Client>& client, const sp<IBinder>& handle)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003897{
Robert Carr9524cb32017-02-13 11:32:32 -08003898 // called by a client when it wants to remove a Layer
Mathias Agopian67106042013-03-14 19:18:13 -07003899 status_t err = NO_ERROR;
3900 sp<Layer> l(client->getLayerUser(handle));
Peiyong Lin566a3b42018-01-09 18:22:43 -08003901 if (l != nullptr) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003902 mInterceptor->saveSurfaceDeletion(l);
Mathias Agopian67106042013-03-14 19:18:13 -07003903 err = removeLayer(l);
3904 ALOGE_IF(err<0 && err != NAME_NOT_FOUND,
3905 "error removing layer=%p (%s)", l.get(), strerror(-err));
Mathias Agopian9a112062009-04-17 19:36:26 -07003906 }
3907 return err;
3908}
3909
Robert Carr2e102c92018-10-23 12:11:15 -07003910void SurfaceFlinger::markLayerPendingRemovalLocked(const Mutex&, const sp<Layer>& layer) {
3911 mLayersPendingRemoval.add(layer);
3912 mLayersRemoved = true;
3913 setTransactionFlags(eTransactionNeeded);
3914}
3915
Robert Carr695d5282018-12-18 15:27:58 -08003916void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003917{
Robert Carr2e102c92018-10-23 12:11:15 -07003918 Mutex::Autolock lock(mStateLock);
3919 markLayerPendingRemovalLocked(mStateLock, layer);
Robert Carr695d5282018-12-18 15:27:58 -08003920 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00003921}
3922
Mathias Agopianb60314a2012-04-10 22:09:54 -07003923// ---------------------------------------------------------------------------
3924
Andy McFadden13a082e2012-08-24 10:16:42 -07003925void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003926 const auto displayToken = getInternalDisplayToken();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003927 if (!displayToken) return;
3928
Jesse Hall01e29052013-02-19 16:13:35 -08003929 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003930 Vector<ComposerState> state;
3931 Vector<DisplayState> displays;
3932 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003933 d.what = DisplayState::eDisplayProjectionChanged |
3934 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003935 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003936 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003937 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003938 d.frame.makeInvalid();
3939 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003940 d.width = 0;
3941 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003942 displays.add(d);
3943 setTransactionState(state, displays, 0);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003944
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003945 const auto display = getDisplayDevice(displayToken);
3946 if (!display) return;
3947
Dominik Laskowskie9774092018-12-11 10:04:24 -08003948 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003949
Dominik Laskowski075d3172018-05-24 15:50:06 -07003950 const auto activeConfig = getHwComposer().getActiveConfig(*display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003951 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003952 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003953
Brian Andersond0010582017-03-07 13:20:31 -08003954 // Use phase of 0 since phase is not known.
3955 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07003956 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
3957 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003958}
3959
3960void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003961 // Async since we may be called from the main thread.
3962 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003963}
3964
Dominik Laskowskie9774092018-12-11 10:04:24 -08003965void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003966 if (display->isVirtual()) {
3967 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003968 return;
3969 }
3970
Dominik Laskowski075d3172018-05-24 15:50:06 -07003971 const auto displayId = display->getId();
3972 LOG_ALWAYS_FATAL_IF(!displayId);
3973
Dominik Laskowski34157762018-10-31 13:07:19 -07003974 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003975
3976 int currentMode = display->getPowerMode();
3977 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003978 return;
3979 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003980
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003981 display->setPowerMode(mode);
3982
Lloyd Pique4dccc412018-01-22 17:21:36 -08003983 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08003984 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07003985 }
3986
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003987 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003988 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07003989 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003990 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07003991 if (mUseScheduler) {
3992 mScheduler->onScreenAcquired(mAppConnectionHandle);
3993 } else {
3994 mEventThread->onScreenAcquired();
3995 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07003996 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003997 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003998
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003999 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004000 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004001 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004002
4003 struct sched_param param = {0};
4004 param.sched_priority = 1;
4005 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4006 ALOGW("Couldn't set SCHED_FIFO on display on");
4007 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004008 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004009 // Turn off the display
4010 struct sched_param param = {0};
4011 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4012 ALOGW("Couldn't set SCHED_OTHER on display off");
4013 }
4014
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004015 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07004016 if (mUseScheduler) {
4017 mScheduler->disableHardwareVsync(true);
4018 } else {
4019 disableHardwareVsync(true); // also cancels any in-progress resync
4020 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004021 if (mUseScheduler) {
4022 mScheduler->onScreenReleased(mAppConnectionHandle);
4023 } else {
4024 mEventThread->onScreenReleased();
4025 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004026 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004027
Dominik Laskowski075d3172018-05-24 15:50:06 -07004028 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004029 mVisibleRegionsDirty = true;
4030 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004031 } else if (mode == HWC_POWER_MODE_DOZE ||
4032 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004033 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004034 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004035 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004036 if (mUseScheduler) {
4037 mScheduler->onScreenAcquired(mAppConnectionHandle);
4038 } else {
4039 mEventThread->onScreenAcquired();
4040 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004041 resyncToHardwareVsync(true);
4042 }
4043 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4044 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004045 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07004046 if (mUseScheduler) {
4047 mScheduler->disableHardwareVsync(true);
4048 } else {
4049 disableHardwareVsync(true); // also cancels any in-progress resync
4050 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004051 if (mUseScheduler) {
4052 mScheduler->onScreenReleased(mAppConnectionHandle);
4053 } else {
4054 mEventThread->onScreenReleased();
4055 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004056 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004057 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004058 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004059 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004060 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004061 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004062
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004063 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004064 mTimeStats->setPowerMode(mode);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004065 }
4066
Dominik Laskowski34157762018-10-31 13:07:19 -07004067 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004068}
4069
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004070void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004071 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004072 const auto display = getDisplayDevice(displayToken);
4073 if (!display) {
4074 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4075 displayToken.get());
4076 } else if (display->isVirtual()) {
4077 ALOGW("Attempt to set power mode %d for virtual display", mode);
4078 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004079 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004080 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004081 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004082}
4083
4084// ---------------------------------------------------------------------------
4085
Lloyd Pique755e3192018-01-31 16:46:15 -08004086status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
4087 NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004088 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004089
Mathias Agopianbd115332013-04-18 16:41:04 -07004090 IPCThreadState* ipc = IPCThreadState::self();
4091 const int pid = ipc->getCallingPid();
4092 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004093
Mathias Agopianbd115332013-04-18 16:41:04 -07004094 if ((uid != AID_SHELL) &&
4095 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004096 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4097 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004098 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004099 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004100 // (this would indicate SF is stuck, but we want to be able to
4101 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004102 status_t err = mStateLock.timedLock(s2ns(1));
4103 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004104 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004105 StringAppendF(&result,
4106 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4107 "(no locks held)\n",
4108 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004109 }
4110
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004111 bool dumpAll = true;
4112 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004113 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004114
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004115 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004116 if ((index < numArgs) &&
4117 (args[index] == String16("--list"))) {
4118 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004119 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004120 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004121 }
4122
4123 if ((index < numArgs) &&
4124 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004125 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004126 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004127 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004128 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004129
4130 if ((index < numArgs) &&
4131 (args[index] == String16("--latency-clear"))) {
4132 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004133 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004134 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004135 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004136
4137 if ((index < numArgs) &&
4138 (args[index] == String16("--dispsync"))) {
4139 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004140 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004141 dumpAll = false;
4142 }
Dan Stozab90cf072015-03-05 11:05:59 -08004143
4144 if ((index < numArgs) &&
4145 (args[index] == String16("--static-screen"))) {
4146 index++;
4147 dumpStaticScreenStats(result);
4148 dumpAll = false;
4149 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004150
4151 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004152 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004153 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004154 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004155 dumpAll = false;
4156 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004157
4158 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4159 index++;
4160 dumpWideColorInfo(result);
4161 dumpAll = false;
4162 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004163
4164 if ((index < numArgs) &&
4165 (args[index] == String16("--enable-layer-stats"))) {
4166 index++;
4167 mLayerStats.enable();
4168 dumpAll = false;
4169 }
4170
4171 if ((index < numArgs) &&
4172 (args[index] == String16("--disable-layer-stats"))) {
4173 index++;
4174 mLayerStats.disable();
4175 dumpAll = false;
4176 }
4177
4178 if ((index < numArgs) &&
4179 (args[index] == String16("--clear-layer-stats"))) {
4180 index++;
4181 mLayerStats.clear();
4182 dumpAll = false;
4183 }
4184
4185 if ((index < numArgs) &&
4186 (args[index] == String16("--dump-layer-stats"))) {
4187 index++;
4188 mLayerStats.dump(result);
4189 dumpAll = false;
4190 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004191
4192 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004193 (args[index] == String16("--frame-composition"))) {
4194 index++;
4195 dumpFrameCompositionInfo(result);
4196 dumpAll = false;
4197 }
4198
4199 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004200 (args[index] == String16("--display-identification"))) {
4201 index++;
4202 dumpDisplayIdentificationData(result);
4203 dumpAll = false;
4204 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004205
4206 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4207 index++;
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004208 mTimeStats->parseArgs(asProto, args, index, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004209 dumpAll = false;
4210 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004211 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004212
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004213 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004214 if (asProto) {
4215 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4216 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4217 } else {
4218 dumpAllLocked(args, index, result);
4219 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004220 }
4221
Mathias Agopian9795c422009-08-26 16:36:26 -07004222 if (locked) {
4223 mStateLock.unlock();
4224 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004225 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004226 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004227 return NO_ERROR;
4228}
4229
Yiwei Zhang5434a782018-12-05 18:06:32 -08004230void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */, size_t& /* index */,
4231 std::string& result) const {
4232 mCurrentState.traverseInZOrder(
4233 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004234}
4235
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004236void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004237 std::string& result) const {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004238 String8 name;
4239 if (index < args.size()) {
4240 name = String8(args[index]);
4241 index++;
4242 }
4243
Dominik Laskowski075d3172018-05-24 15:50:06 -07004244 if (const auto displayId = getInternalDisplayId();
4245 displayId && getHwComposer().isConnected(*displayId)) {
4246 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004247 const nsecs_t period = activeConfig->getVsyncPeriod();
Yiwei Zhang5434a782018-12-05 18:06:32 -08004248 StringAppendF(&result, "%" PRId64 "\n", period);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004249 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004250
4251 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004252 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004253 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004254 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004255 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004256 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004257 }
Robert Carr2047fae2016-11-28 14:09:09 -08004258 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004259 }
4260}
4261
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004262void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004263 std::string& /* result */) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004264 String8 name;
4265 if (index < args.size()) {
4266 name = String8(args[index]);
4267 index++;
4268 }
4269
Robert Carr2047fae2016-11-28 14:09:09 -08004270 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004271 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004272 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004273 }
Robert Carr2047fae2016-11-28 14:09:09 -08004274 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004275
Svetoslavd85084b2014-03-20 10:28:31 -07004276 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004277}
4278
Jamie Gennis6547ff42013-07-16 20:12:42 -07004279// This should only be called from the main thread. Otherwise it would need
4280// the lock and should use mCurrentState rather than mDrawingState.
4281void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004282 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004283 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004284 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004285
4286 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4287}
4288
Yiwei Zhang5434a782018-12-05 18:06:32 -08004289void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004290 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004291
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004292 if (isLayerTripleBufferingDisabled())
4293 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004294
Yiwei Zhang5434a782018-12-05 18:06:32 -08004295 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4296 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4297 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4298 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4299 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4300 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004301 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004302}
4303
Yiwei Zhang5434a782018-12-05 18:06:32 -08004304void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4305 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004306 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4307 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004308 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004309 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004310 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004311 }
David Sodman4a36e932017-11-07 14:29:47 -08004312 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004313 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004314 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004315 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4316 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004317}
4318
Dan Stozae77c7662016-05-13 11:37:28 -07004319void SurfaceFlinger::recordBufferingStats(const char* layerName,
4320 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004321 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4322 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004323 for (const auto& segment : history) {
4324 if (!segment.usedThirdBuffer) {
4325 stats.twoBufferTime += segment.totalTime;
4326 }
4327 if (segment.occupancyAverage < 1.0f) {
4328 stats.doubleBufferedTime += segment.totalTime;
4329 } else if (segment.occupancyAverage < 2.0f) {
4330 stats.tripleBufferedTime += segment.totalTime;
4331 }
4332 ++stats.numSegments;
4333 stats.totalTime += segment.totalTime;
4334 }
4335}
4336
Yiwei Zhang5434a782018-12-05 18:06:32 -08004337void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4338 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004339
4340 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4341 const size_t count = currentLayers.size();
4342 for (size_t i=0 ; i<count ; i++) {
4343 currentLayers[i]->dumpFrameEvents(result);
4344 }
4345}
4346
Yiwei Zhang5434a782018-12-05 18:06:32 -08004347void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004348 result.append("Buffering stats:\n");
4349 result.append(" [Layer name] <Active time> <Two buffer> "
4350 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004351 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004352 typedef std::tuple<std::string, float, float, float> BufferTuple;
4353 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004354 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004355 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004356 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004357 if (stats.numSegments == 0) {
4358 continue;
4359 }
4360 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4361 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4362 stats.totalTime;
4363 float doubleBufferRatio = static_cast<float>(
4364 stats.doubleBufferedTime) / stats.totalTime;
4365 float tripleBufferRatio = static_cast<float>(
4366 stats.tripleBufferedTime) / stats.totalTime;
4367 sorted.insert({activeTime, {name, twoBufferRatio,
4368 doubleBufferRatio, tripleBufferRatio}});
4369 }
4370 for (const auto& sortedPair : sorted) {
4371 float activeTime = sortedPair.first;
4372 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004373 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4374 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004375 }
4376 result.append("\n");
4377}
4378
Yiwei Zhang5434a782018-12-05 18:06:32 -08004379void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004380 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004381 const auto displayId = display->getId();
4382 if (!displayId) {
4383 continue;
4384 }
4385 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004386 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004387 continue;
4388 }
4389
Yiwei Zhang5434a782018-12-05 18:06:32 -08004390 StringAppendF(&result,
4391 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4392 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004393 uint8_t port;
4394 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004395 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004396 result.append("no identification data\n");
4397 continue;
4398 }
4399
4400 if (!isEdid(data)) {
4401 result.append("unknown identification data: ");
4402 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004403 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004404 }
4405 result.append("\n");
4406 continue;
4407 }
4408
4409 const auto edid = parseEdid(data);
4410 if (!edid) {
4411 result.append("invalid EDID: ");
4412 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004413 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004414 }
4415 result.append("\n");
4416 continue;
4417 }
4418
Yiwei Zhang5434a782018-12-05 18:06:32 -08004419 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004420 result.append(edid->displayName.data(), edid->displayName.length());
4421 result.append("\"\n");
4422 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004423}
4424
Yiwei Zhang5434a782018-12-05 18:06:32 -08004425void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4426 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4427 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4428 StringAppendF(&result, "DisplayColorSetting: %s\n",
4429 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004430
4431 // TODO: print out if wide-color mode is active or not
4432
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004433 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004434 const auto displayId = display->getId();
4435 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004436 continue;
4437 }
4438
Yiwei Zhang5434a782018-12-05 18:06:32 -08004439 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004440 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004441 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004442 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004443 }
4444
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004445 ColorMode currentMode = display->getActiveColorMode();
Yiwei Zhang5434a782018-12-05 18:06:32 -08004446 StringAppendF(&result, " Current color mode: %s (%d)\n",
4447 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004448 }
4449 result.append("\n");
4450}
4451
Yiwei Zhang5434a782018-12-05 18:06:32 -08004452void SurfaceFlinger::dumpFrameCompositionInfo(std::string& result) const {
David Sodman7e4ae112018-02-09 15:02:28 -08004453 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004454 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4455 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004456 continue;
4457 }
4458
Dominik Laskowski05275f12018-11-01 15:03:24 -07004459 const auto& compositionInfoList = it->second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004460 StringAppendF(&result, "%s\n", display->getDebugName().c_str());
4461 StringAppendF(&result, "numComponents: %zu\n", compositionInfoList.size());
David Sodman7e4ae112018-02-09 15:02:28 -08004462 for (const auto& compositionInfo : compositionInfoList) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004463 compositionInfo.dump(result, nullptr);
4464 result.append("\n");
David Sodman7e4ae112018-02-09 15:02:28 -08004465 }
4466 }
David Sodman7e4ae112018-02-09 15:02:28 -08004467}
4468
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004469LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004470 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004471 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4472 const State& state = useDrawing ? mDrawingState : mCurrentState;
4473 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004474 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004475 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004476 });
4477
4478 return layersProto;
4479}
4480
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004481LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004482 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004483
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004484 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004485 resolution->set_w(display.getWidth());
4486 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004487
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004488 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4489 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4490 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004491
Dominik Laskowski075d3172018-05-24 15:50:06 -07004492 const auto displayId = display.getId();
4493 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004494 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004495 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004496 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004497 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004498 }
4499 });
4500
4501 return layersProto;
4502}
4503
Mathias Agopian74d211a2013-04-22 16:55:35 +02004504void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004505 std::string& result) const {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004506 bool colorize = false;
4507 if (index < args.size()
4508 && (args[index] == String16("--color"))) {
4509 colorize = true;
4510 index++;
4511 }
4512
4513 Colorizer colorizer(colorize);
4514
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004515 // figure out if we're stuck somewhere
4516 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004517 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004518 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4519
4520 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004521 * Dump library configuration.
4522 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004523
4524 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004525 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004526 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004527 appendSfConfigString(result);
4528 appendUiConfigString(result);
4529 appendGuiConfigString(result);
4530 result.append("\n");
4531
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004532 result.append("\nDisplay identification data:\n");
4533 dumpDisplayIdentificationData(result);
4534
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004535 result.append("\nWide-Color information:\n");
4536 dumpWideColorInfo(result);
4537
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004538 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004539 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004540 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004541 result.append(SyncFeatures::getInstance().toString());
4542 result.append("\n");
4543
Andy McFadden41d67d72014-04-25 16:58:34 -07004544 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004545 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004546 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004547
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004548 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4549 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004550 if (const auto displayId = getInternalDisplayId();
4551 displayId && getHwComposer().isConnected(*displayId)) {
4552 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004553 StringAppendF(&result,
4554 "Display %s: app phase %" PRId64 " ns, "
4555 "sf phase %" PRId64 " ns, "
4556 "early app phase %" PRId64 " ns, "
4557 "early sf phase %" PRId64 " ns, "
4558 "early app gl phase %" PRId64 " ns, "
4559 "early sf gl phase %" PRId64 " ns, "
4560 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4561 to_string(*displayId).c_str(), vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
4562 appEarlyOffset, sfEarlyOffset, appEarlyGlOffset, sfEarlyGlOffset,
4563 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004564 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004565 result.append("\n");
4566
Dan Stozab90cf072015-03-05 11:05:59 -08004567 // Dump static screen stats
4568 result.append("\n");
4569 dumpStaticScreenStats(result);
4570 result.append("\n");
4571
Yiwei Zhang5434a782018-12-05 18:06:32 -08004572 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004573
Dan Stozae77c7662016-05-13 11:37:28 -07004574 dumpBufferingStats(result);
4575
Andy McFadden4803b742012-09-24 19:07:20 -07004576 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004577 * Dump the visible layer list
4578 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004579 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004580 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4581 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4582 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004583 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004584
Chia-I Wu2f884132018-09-13 15:17:58 -07004585 {
4586 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4587 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004588 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004589 result.append("\n");
4590 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004591
David Sodman7e4ae112018-02-09 15:02:28 -08004592 result.append("\nFrame-Composition information:\n");
4593 dumpFrameCompositionInfo(result);
4594 result.append("\n");
4595
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004596 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004597 * Dump Display state
4598 */
4599
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004600 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004601 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004602 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004603 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004604 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004605 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004606 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004607
4608 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004609 * Dump SurfaceFlinger global state
4610 */
4611
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004612 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004613 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004614 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004615
David Sodmanbc815282017-11-05 18:57:52 -08004616 getBE().mRenderEngine->dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004617
Dominik Laskowski075d3172018-05-24 15:50:06 -07004618 if (const auto display = getDefaultDisplayDeviceLocked()) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004619 display->undefinedRegion.dump(result, "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004620 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4621 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004622 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004623 StringAppendF(&result,
4624 " transaction-flags : %08x\n"
4625 " gpu_to_cpu_unsupported : %d\n",
4626 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004627
Dominik Laskowski075d3172018-05-24 15:50:06 -07004628 if (const auto displayId = getInternalDisplayId();
4629 displayId && getHwComposer().isConnected(*displayId)) {
4630 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004631 StringAppendF(&result,
4632 " refresh-rate : %f fps\n"
4633 " x-dpi : %f\n"
4634 " y-dpi : %f\n",
4635 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4636 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004637 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004638
Yiwei Zhang5434a782018-12-05 18:06:32 -08004639 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004640
Yiwei Zhang5434a782018-12-05 18:06:32 -08004641 StringAppendF(&result, " use Scheduler: %s\n", mUseScheduler ? "true" : "false");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004642 /*
4643 * VSYNC state
4644 */
Ana Krulec98b5b242018-08-10 15:03:23 -07004645 if (mUseScheduler) {
4646 mScheduler->dump(mAppConnectionHandle, result);
4647 } else {
4648 mEventThread->dump(result);
4649 }
Dan Stozae22aec72016-08-01 13:20:59 -07004650 result.append("\n");
4651
4652 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004653 * Tracing state
4654 */
4655 mTracing.dump(result);
4656 result.append("\n");
4657
4658 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004659 * HWC layer minidump
4660 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004661 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004662 const auto displayId = display->getId();
4663 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004664 continue;
4665 }
4666
Yiwei Zhang5434a782018-12-05 18:06:32 -08004667 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004668 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004669 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004670 result.append("\n");
4671 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004672
4673 /*
4674 * Dump HWComposer state
4675 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004676 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004677 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004678 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004679 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004680 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004681 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004682
4683 /*
4684 * Dump gralloc state
4685 */
4686 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4687 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004688
4689 /*
4690 * Dump VrFlinger state if in use.
4691 */
4692 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4693 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004694 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004695 result.append("\n");
4696 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004697}
4698
Dominik Laskowski075d3172018-05-24 15:50:06 -07004699const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004700 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004701 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004702 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004703 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004704 }
4705 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004706
Dominik Laskowski34157762018-10-31 13:07:19 -07004707 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004708 static const Vector<sp<Layer>> empty;
4709 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004710}
4711
Keun young Park63f165f2012-08-31 10:53:36 -07004712bool SurfaceFlinger::startDdmConnection()
4713{
4714 void* libddmconnection_dso =
4715 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4716 if (!libddmconnection_dso) {
4717 return false;
4718 }
4719 void (*DdmConnection_start)(const char* name);
4720 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004721 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004722 if (!DdmConnection_start) {
4723 dlclose(libddmconnection_dso);
4724 return false;
4725 }
4726 (*DdmConnection_start)(getServiceName());
4727 return true;
4728}
4729
Chia-I Wu28f320b2018-05-03 11:02:56 -07004730void SurfaceFlinger::updateColorMatrixLocked() {
4731 mat4 colorMatrix;
4732 if (mGlobalSaturationFactor != 1.0f) {
4733 // Rec.709 luma coefficients
4734 float3 luminance{0.213f, 0.715f, 0.072f};
4735 luminance *= 1.0f - mGlobalSaturationFactor;
4736 mat4 saturationMatrix = mat4(
4737 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4738 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4739 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4740 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4741 );
4742 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4743 } else {
4744 colorMatrix = mClientColorMatrix * mDaltonizer();
4745 }
4746
4747 if (mCurrentState.colorMatrix != colorMatrix) {
4748 mCurrentState.colorMatrix = colorMatrix;
4749 mCurrentState.colorMatrixChanged = true;
4750 setTransactionFlags(eTransactionNeeded);
4751 }
4752}
4753
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004754status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004755#pragma clang diagnostic push
4756#pragma clang diagnostic error "-Wswitch-enum"
4757 switch (static_cast<ISurfaceComposerTag>(code)) {
4758 // These methods should at minimum make sure that the client requested
4759 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004760 case BOOT_FINISHED:
4761 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004762 case CREATE_CONNECTION:
4763 case CREATE_DISPLAY:
4764 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004765 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004766 case GET_ACTIVE_COLOR_MODE:
4767 case GET_ANIMATION_FRAME_STATS:
4768 case GET_HDR_CAPABILITIES:
4769 case SET_ACTIVE_CONFIG:
4770 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004771 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004772 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004773 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004774 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4775 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004776 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4777 IPCThreadState* ipc = IPCThreadState::self();
4778 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4779 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004780 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004781 }
Robert Carr1db73f62016-12-21 12:58:51 -08004782 return OK;
4783 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004784 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004785 IPCThreadState* ipc = IPCThreadState::self();
4786 const int pid = ipc->getCallingPid();
4787 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004788 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4789 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004790 return PERMISSION_DENIED;
4791 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004792 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004793 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004794 // Used by apps to hook Choreographer to SurfaceFlinger.
4795 case CREATE_DISPLAY_EVENT_CONNECTION:
4796 // The following calls are currently used by clients that do not
4797 // request necessary permissions. However, they do not expose any secret
4798 // information, so it is OK to pass them.
4799 case AUTHENTICATE_SURFACE:
4800 case GET_ACTIVE_CONFIG:
4801 case GET_BUILT_IN_DISPLAY:
4802 case GET_DISPLAY_COLOR_MODES:
4803 case GET_DISPLAY_CONFIGS:
4804 case GET_DISPLAY_STATS:
4805 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4806 // Calling setTransactionState is safe, because you need to have been
4807 // granted a reference to Client* and Handle* to do anything with it.
4808 case SET_TRANSACTION_STATE:
4809 // Creating a scoped connection is safe, as per discussion in ISurfaceComposer.h
Peiyong Lin0256f722018-08-31 15:45:10 -07004810 case CREATE_SCOPED_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004811 case GET_COLOR_MANAGEMENT:
Peiyong Lin0256f722018-08-31 15:45:10 -07004812 case GET_COMPOSITION_PREFERENCE: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004813 return OK;
4814 }
4815 case CAPTURE_LAYERS:
4816 case CAPTURE_SCREEN: {
4817 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004818 IPCThreadState* ipc = IPCThreadState::self();
4819 const int pid = ipc->getCallingPid();
4820 const int uid = ipc->getCallingUid();
4821 if ((uid != AID_GRAPHICS) &&
4822 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4823 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4824 return PERMISSION_DENIED;
4825 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004826 return OK;
4827 }
4828 // The following codes are deprecated and should never be allowed to access SF.
4829 case CONNECT_DISPLAY_UNUSED:
4830 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4831 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4832 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004833 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004834 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004835
4836 // These codes are used for the IBinder protocol to either interrogate the recipient
4837 // side of the transaction for its canonical interface descriptor or to dump its state.
4838 // We let them pass by default.
4839 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4840 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4841 code == IBinder::SYSPROPS_TRANSACTION) {
4842 return OK;
4843 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004844 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004845 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08004846 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004847 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4848 return OK;
4849 }
4850 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4851 return PERMISSION_DENIED;
4852#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004853}
4854
Ana Krulec13be8ad2018-08-21 02:43:56 +00004855status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4856 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004857 status_t credentialCheck = CheckTransactCodeCredentials(code);
4858 if (credentialCheck != OK) {
4859 return credentialCheck;
4860 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004861
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004862 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4863 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004864 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004865 IPCThreadState* ipc = IPCThreadState::self();
4866 const int uid = ipc->getCallingUid();
4867 if (CC_UNLIKELY(uid != AID_SYSTEM
4868 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004869 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004870 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004871 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004872 return PERMISSION_DENIED;
4873 }
4874 int n;
4875 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004876 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004877 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004878 return NO_ERROR;
4879 case 1002: // SHOW_UPDATES
4880 n = data.readInt32();
4881 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004882 invalidateHwcGeometry();
4883 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004884 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004885 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004886 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004887 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004888 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004889 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004890 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004891 setTransactionFlags(
4892 eTransactionNeeded|
4893 eDisplayTransactionNeeded|
4894 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004895 return NO_ERROR;
4896 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004897 case 1006:{ // send empty update
4898 signalRefresh();
4899 return NO_ERROR;
4900 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004901 case 1008: // toggle use of hw composer
4902 n = data.readInt32();
4903 mDebugDisableHWC = n ? 1 : 0;
4904 invalidateHwcGeometry();
4905 repaintEverything();
4906 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004907 case 1009: // toggle use of transform hint
4908 n = data.readInt32();
4909 mDebugDisableTransformHint = n ? 1 : 0;
4910 invalidateHwcGeometry();
4911 repaintEverything();
4912 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004913 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004914 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004915 reply->writeInt32(0);
4916 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004917 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004918 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004919 return NO_ERROR;
4920 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004921 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004922 if (!display) {
4923 return NAME_NOT_FOUND;
4924 }
4925
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004926 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004927 return NO_ERROR;
4928 }
4929 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004930 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004931 // daltonize
4932 n = data.readInt32();
4933 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004934 case 1:
4935 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4936 break;
4937 case 2:
4938 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4939 break;
4940 case 3:
4941 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4942 break;
4943 default:
4944 mDaltonizer.setType(ColorBlindnessType::None);
4945 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004946 }
4947 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004948 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004949 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004950 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004951 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004952
4953 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004954 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004955 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004956 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004957 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004958 // apply a color matrix
4959 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004960 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004961 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004962 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004963 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004964 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004965 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004966 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004967 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004968 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004969 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004970
4971 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4972 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004973 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004974 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4975 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4976 }
4977
Chia-I Wu28f320b2018-05-03 11:02:56 -07004978 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004979 return NO_ERROR;
4980 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004981 // This is an experimental interface
4982 // Needs to be shifted to proper binder interface when we productize
4983 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07004984 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07004985 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07004986 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004987 return NO_ERROR;
4988 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004989 case 1017: {
4990 n = data.readInt32();
4991 mForceFullDamage = static_cast<bool>(n);
4992 return NO_ERROR;
4993 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004994 case 1018: { // Modify Choreographer's phase offset
4995 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07004996 if (mUseScheduler) {
4997 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
4998 } else {
4999 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5000 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005001 return NO_ERROR;
5002 }
5003 case 1019: { // Modify SurfaceFlinger's phase offset
5004 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005005 if (mUseScheduler) {
5006 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5007 } else {
5008 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5009 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005010 return NO_ERROR;
5011 }
Irvel468051e2016-06-13 16:44:44 -07005012 case 1020: { // Layer updates interceptor
5013 n = data.readInt32();
5014 if (n) {
5015 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005016 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005017 }
5018 else{
5019 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005020 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005021 }
5022 return NO_ERROR;
5023 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005024 case 1021: { // Disable HWC virtual displays
5025 n = data.readInt32();
5026 mUseHwcVirtualDisplays = !n;
5027 return NO_ERROR;
5028 }
Romain Guy0147a172017-06-01 13:53:56 -07005029 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005030 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005031 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005032
Chia-I Wu28f320b2018-05-03 11:02:56 -07005033 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005034 return NO_ERROR;
5035 }
Romain Guy54f154a2017-10-24 21:40:32 +01005036 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005037 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005038 invalidateHwcGeometry();
5039 repaintEverything();
5040 return NO_ERROR;
5041 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005042 // Deprecate, use 1030 to check whether the device is color managed.
5043 case 1024: {
5044 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005045 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005046 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005047 n = data.readInt32();
5048 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005049 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005050 mTracing.enable();
5051 doTracing("tracing.enable");
5052 reply->writeInt32(NO_ERROR);
5053 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005054 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005055 status_t err = mTracing.disable();
5056 reply->writeInt32(err);
5057 }
5058 return NO_ERROR;
5059 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005060 case 1026: { // Get layer tracing status
5061 reply->writeBool(mTracing.isEnabled());
5062 return NO_ERROR;
5063 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005064 // Is a DisplayColorSetting supported?
5065 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005066 const auto display = getDefaultDisplayDevice();
5067 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005068 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005069 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005070
5071 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5072 switch (setting) {
5073 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005074 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005075 break;
5076 case DisplayColorSetting::UNMANAGED:
5077 reply->writeBool(true);
5078 break;
5079 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005080 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005081 break;
5082 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005083 reply->writeBool(
5084 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005085 break;
5086 }
5087 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005088 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005089 // Is VrFlinger active?
5090 case 1028: {
5091 Mutex::Autolock _l(mStateLock);
5092 reply->writeBool(getBE().mHwc->isUsingVrComposer());
5093 return NO_ERROR;
5094 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005095 // Is device color managed?
5096 case 1030: {
5097 reply->writeBool(useColorManagement);
5098 return NO_ERROR;
5099 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005100 // Override default composition data space
5101 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5102 // && adb shell stop zygote && adb shell start zygote
5103 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5104 // adb shell stop zygote && adb shell start zygote
5105 case 1031: {
5106 Mutex::Autolock _l(mStateLock);
5107 n = data.readInt32();
5108 if (n) {
5109 n = data.readInt32();
5110 if (n) {
5111 Dataspace dataspace = static_cast<Dataspace>(n);
5112 if (!validateCompositionDataspace(dataspace)) {
5113 return BAD_VALUE;
5114 }
5115 mDefaultCompositionDataspace = dataspace;
5116 }
5117 n = data.readInt32();
5118 if (n) {
5119 Dataspace dataspace = static_cast<Dataspace>(n);
5120 if (!validateCompositionDataspace(dataspace)) {
5121 return BAD_VALUE;
5122 }
5123 mWideColorGamutCompositionDataspace = dataspace;
5124 }
5125 } else {
5126 // restore composition data space.
5127 mDefaultCompositionDataspace = defaultCompositionDataspace;
5128 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5129 }
5130 return NO_ERROR;
5131 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005132 }
5133 }
5134 return err;
5135}
5136
Steven Thomas6d8110b2017-08-31 18:24:21 -07005137void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005138 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005139 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005140}
5141
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005142// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5143class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005144public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005145 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5146 ~WindowDisconnector() {
5147 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005148 }
5149
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005150private:
5151 ANativeWindow* mWindow;
5152 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005153};
5154
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005155status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005156 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5157 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005158 uint32_t reqWidth, uint32_t reqHeight,
5159 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005160 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005161 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005162
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005163 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005164
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005165 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5166
Chia-I Wu20261cb2018-08-23 12:55:44 -07005167 sp<DisplayDevice> display;
5168 {
5169 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005170
Chia-I Wu20261cb2018-08-23 12:55:44 -07005171 display = getDisplayDeviceLocked(displayToken);
5172 if (!display) return BAD_VALUE;
5173
Chia-I Wucb023152018-08-28 12:57:23 -07005174 // set the requested width/height to the logical display viewport size
5175 // by default
5176 if (reqWidth == 0 || reqHeight == 0) {
5177 reqWidth = uint32_t(display->getViewport().width());
5178 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005179 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005180 }
5181
Peiyong Lin0e003c92018-09-17 11:09:51 -07005182 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5183 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005184
5185 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005186 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005187 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5188 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005189}
5190
5191status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005192 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5193 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005194 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005195 ATRACE_CALL();
5196
5197 class LayerRenderArea : public RenderArea {
5198 public:
Robert Carr578038f2018-03-09 12:25:24 -08005199 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005200 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5201 bool childrenOnly)
5202 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005203 mLayer(layer),
5204 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005205 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005206 mFlinger(flinger),
5207 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005208 const ui::Transform& getTransform() const override { return mTransform; }
Ady Abraham83729882018-12-07 12:26:48 -08005209 Rect getBounds() const override { return mLayer->getBufferSize(StateSet::Drawing); }
Marissa Wall61c58622018-07-18 10:12:20 -07005210 int getHeight() const override {
Ady Abraham83729882018-12-07 12:26:48 -08005211 return mLayer->getBufferSize(StateSet::Drawing).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005212 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005213 int getWidth() const override {
Ady Abraham83729882018-12-07 12:26:48 -08005214 return mLayer->getBufferSize(StateSet::Drawing).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005215 }
chaviwa76b2712017-09-20 12:02:26 -07005216 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005217 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005218 Rect getSourceCrop() const override {
5219 if (mCrop.isEmpty()) {
5220 return getBounds();
5221 } else {
5222 return mCrop;
5223 }
5224 }
Robert Carr578038f2018-03-09 12:25:24 -08005225 class ReparentForDrawing {
5226 public:
5227 const sp<Layer>& oldParent;
5228 const sp<Layer>& newParent;
5229
5230 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5231 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005232 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005233 }
Robert Carr15eae092018-03-23 13:43:53 -07005234 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005235 };
5236
5237 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005238 const Rect sourceCrop = getSourceCrop();
5239 // no need to check rotation because there is none
5240 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5241 sourceCrop.height() != getReqHeight();
5242
Robert Carr578038f2018-03-09 12:25:24 -08005243 if (!mChildrenOnly) {
5244 mTransform = mLayer->getTransform().inverse();
5245 drawLayers();
5246 } else {
5247 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005248 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005249 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5250 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005251
5252 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5253 drawLayers();
5254 }
5255 }
chaviwa76b2712017-09-20 12:02:26 -07005256
chaviwa76b2712017-09-20 12:02:26 -07005257 private:
chaviw7206d492017-11-10 16:16:12 -08005258 const sp<Layer> mLayer;
5259 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005260
5261 // In the "childrenOnly" case we reparent the children to a screenshot
5262 // layer which has no properties set and which does not draw.
5263 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005264 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005265 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005266
5267 SurfaceFlinger* mFlinger;
5268 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005269 };
5270
5271 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5272 auto parent = layerHandle->owner.promote();
5273
Robert Carr2e102c92018-10-23 12:11:15 -07005274 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005275 ALOGE("captureLayers called with a removed parent");
5276 return NAME_NOT_FOUND;
5277 }
5278
Robert Carr578038f2018-03-09 12:25:24 -08005279 const int uid = IPCThreadState::self()->getCallingUid();
5280 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Ady Abraham83729882018-12-07 12:26:48 -08005281 if (!forSystem && parent->getCurrentFlags() & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005282 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5283 return PERMISSION_DENIED;
5284 }
5285
chaviw7206d492017-11-10 16:16:12 -08005286 Rect crop(sourceCrop);
5287 if (sourceCrop.width() <= 0) {
5288 crop.left = 0;
Ady Abraham83729882018-12-07 12:26:48 -08005289 crop.right = parent->getBufferSize(StateSet::Current).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005290 }
5291
5292 if (sourceCrop.height() <= 0) {
5293 crop.top = 0;
Ady Abraham83729882018-12-07 12:26:48 -08005294 crop.bottom = parent->getBufferSize(StateSet::Current).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005295 }
5296
5297 int32_t reqWidth = crop.width() * frameScale;
5298 int32_t reqHeight = crop.height() * frameScale;
5299
Chia-I Wu20261cb2018-08-23 12:55:44 -07005300 // really small crop or frameScale
5301 if (reqWidth <= 0) {
5302 reqWidth = 1;
5303 }
5304 if (reqHeight <= 0) {
5305 reqHeight = 1;
5306 }
5307
Peiyong Lin0e003c92018-09-17 11:09:51 -07005308 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005309
Robert Carr578038f2018-03-09 12:25:24 -08005310 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005311 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5312 if (!layer->isVisible()) {
5313 return;
Robert Carr578038f2018-03-09 12:25:24 -08005314 } else if (childrenOnly && layer == parent.get()) {
5315 return;
chaviwa76b2712017-09-20 12:02:26 -07005316 }
5317 visitor(layer);
5318 });
5319 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005320 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005321}
5322
5323status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5324 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005325 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005326 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005327 bool useIdentityTransform) {
5328 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005329
Peiyong Lin0e003c92018-09-17 11:09:51 -07005330 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005331 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5332 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005333 *outBuffer =
5334 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5335 static_cast<android_pixel_format>(reqPixelFormat), 1,
5336 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005337
5338 // This mutex protects syncFd and captureResult for communication of the return values from the
5339 // main thread back to this Binder thread
5340 std::mutex captureMutex;
5341 std::condition_variable captureCondition;
5342 std::unique_lock<std::mutex> captureLock(captureMutex);
5343 int syncFd = -1;
5344 std::optional<status_t> captureResult;
5345
Robert Carr03480e22018-01-04 16:02:06 -08005346 const int uid = IPCThreadState::self()->getCallingUid();
5347 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5348
Dominik Laskowski8c001672018-05-30 16:52:06 -07005349 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005350 // If there is a refresh pending, bug out early and tell the binder thread to try again
5351 // after the refresh.
5352 if (mRefreshPending) {
5353 ATRACE_NAME("Skipping screenshot for now");
5354 std::unique_lock<std::mutex> captureLock(captureMutex);
5355 captureResult = std::make_optional<status_t>(EAGAIN);
5356 captureCondition.notify_one();
5357 return;
5358 }
5359
5360 status_t result = NO_ERROR;
5361 int fd = -1;
5362 {
5363 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005364 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005365 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5366 useIdentityTransform, forSystem, &fd);
5367 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005368 }
5369
5370 {
5371 std::unique_lock<std::mutex> captureLock(captureMutex);
5372 syncFd = fd;
5373 captureResult = std::make_optional<status_t>(result);
5374 captureCondition.notify_one();
5375 }
5376 });
5377
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005378 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005379 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005380 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005381 while (*captureResult == EAGAIN) {
5382 captureResult.reset();
5383 result = postMessageAsync(message);
5384 if (result != NO_ERROR) {
5385 return result;
5386 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005387 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005388 }
5389 result = *captureResult;
5390 }
5391
5392 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005393 sync_wait(syncFd, -1);
5394 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005395 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005396
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005397 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005398}
5399
chaviwa76b2712017-09-20 12:02:26 -07005400void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005401 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005402 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005403 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005404
Lloyd Pique144e1162017-12-20 16:44:52 -08005405 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005406
chaviwa76b2712017-09-20 12:02:26 -07005407 const auto reqWidth = renderArea.getReqWidth();
5408 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005409 const auto sourceCrop = renderArea.getSourceCrop();
5410 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005411
Peiyong Lin0e003c92018-09-17 11:09:51 -07005412 engine.setOutputDataSpace(renderArea.getReqDataSpace());
Chia-I Wu36574d92018-05-16 10:54:36 -07005413 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005414
Mathias Agopian180f10d2013-04-10 22:55:41 -07005415 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005416 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005417
5418 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005419 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005420 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005421
chaviw50da5042018-04-09 13:49:37 -07005422 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005423 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005424 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005425
chaviwa76b2712017-09-20 12:02:26 -07005426 traverseLayers([&](Layer* layer) {
Peiyong Lind3788632018-09-18 16:01:31 -07005427 engine.setColorTransform(layer->getColorTransform());
David Sodmanfb95bcc2017-12-22 15:45:30 -08005428 layer->draw(renderArea, useIdentityTransform);
Peiyong Lind3788632018-09-18 16:01:31 -07005429 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005430 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005431}
5432
chaviwa76b2712017-09-20 12:02:26 -07005433status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5434 TraverseLayersFunction traverseLayers,
5435 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005436 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005437 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005438 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005439 ATRACE_CALL();
5440
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005441 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005442
5443 traverseLayers([&](Layer* layer) {
5444 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5445 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005446
Robert Carr03480e22018-01-04 16:02:06 -08005447 // We allow the system server to take screenshots of secure layers for
5448 // use in situations like the Screen-rotation animation and place
5449 // the impetus on WindowManager to not persist them.
5450 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005451 ALOGW("FB is protected: PERMISSION_DENIED");
5452 return PERMISSION_DENIED;
5453 }
Peiyong Linfb530cf2018-12-15 05:07:38 +00005454 auto& engine(getRenderEngine());
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005455
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005456 // this binds the given EGLImage as a framebuffer for the
5457 // duration of this scope.
Peiyong Linfb530cf2018-12-15 05:07:38 +00005458 renderengine::BindNativeBufferAsFramebuffer bufferBond(engine, buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005459 if (bufferBond.getStatus() != NO_ERROR) {
5460 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005461 return INVALID_OPERATION;
5462 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005463
Dan Stozaabcda352017-06-01 14:37:39 -07005464 // this will in fact render into our dequeued buffer
5465 // via an FBO, which means we didn't have to create
5466 // an EGLSurface and therefore we're not
5467 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005468 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005469
Peiyong Linfb530cf2018-12-15 05:07:38 +00005470 base::unique_fd syncFd = engine.flush();
Alec Mouri492bc572018-09-11 21:40:04 +00005471 if (syncFd < 0) {
Peiyong Linfb530cf2018-12-15 05:07:38 +00005472 engine.finish();
Dan Stozaabcda352017-06-01 14:37:39 -07005473 }
Alec Mouri492bc572018-09-11 21:40:04 +00005474 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005475
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005476 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005477}
5478
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005479// ---------------------------------------------------------------------------
5480
Dan Stoza412903f2017-04-27 13:42:17 -07005481void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5482 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005483}
5484
Dan Stoza412903f2017-04-27 13:42:17 -07005485void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5486 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005487}
5488
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005489void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005490 const LayerVector::Visitor& visitor) {
5491 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005492 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005493 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005494 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005495 continue;
5496 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005497 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005498 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005499 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005500 return;
5501 }
chaviwa76b2712017-09-20 12:02:26 -07005502 if (!layer->isVisible()) {
5503 return;
5504 }
5505 visitor(layer);
5506 });
5507 }
5508}
5509
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005510}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005511
Lloyd Pique074e8122018-07-26 12:57:23 -07005512
Mathias Agopian3f844832013-08-07 21:24:32 -07005513#if defined(__gl_h_)
5514#error "don't include gl/gl.h in this file"
5515#endif
5516
5517#if defined(__gl2_h_)
5518#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005519#endif