blob: bd16d645f183c106f925742f55115106e9a640d1 [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()),
David Sodman4a36e932017-11-07 14:29:47 -0800238 mFrameBuckets(),
239 mTotalTime(0),
240 mLastSwapTime(0),
David Sodmanbc815282017-11-05 18:57:52 -0800241 mComposerSequenceId(0) {
242}
243
Lloyd Pique90c115d2018-09-18 21:39:42 -0700244SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory,
245 SurfaceFlinger::SkipInitializationTag)
Lloyd Pique12eb4232018-01-17 11:54:43 -0800246 : BnSurfaceComposer(),
Lloyd Pique90c115d2018-09-18 21:39:42 -0700247 mFactory(factory),
Jamie Gennis2d5e2302012-10-15 18:24:43 -0700248 mTransactionPending(false),
249 mAnimTransactionPending(false),
Mathias Agopian076b1cc2009-04-10 14:24:30 -0700250 mLayersRemoved(false),
Robert Carr1f0a16a2016-10-24 16:27:39 -0700251 mLayersAdded(false),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800252 mBootTime(systemTime()),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800253 mVisibleRegionsDirty(false),
Dan Stoza9e56aa02015-11-02 13:00:03 -0800254 mGeometryInvalid(false),
Jamie Gennis4b0eba92013-02-05 13:30:24 -0800255 mAnimCompositionPending(false),
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800256 mBootStage(BootStage::BOOTLOADER),
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800257 mDebugRegion(0),
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700258 mDebugDDMS(0),
Mathias Agopian73d3ba92010-09-22 18:58:01 -0700259 mDebugDisableHWC(0),
Mathias Agopiana4583642011-08-23 18:03:18 -0700260 mDebugDisableTransformHint(0),
Mathias Agopian9795c422009-08-26 16:36:26 -0700261 mDebugInTransaction(0),
262 mLastTransactionTime(0),
Dan Stozaee44edd2015-03-23 15:50:23 -0700263 mForceFullDamage(false),
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800264 mTimeStats(factory.createTimeStats()),
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700265 mPrimaryHWVsyncEnabled(false),
Jesse Hall948fe0c2013-10-14 12:56:09 -0700266 mHWVsyncAvailable(false),
David Sodman2b406362017-12-15 13:33:47 -0800267 mRefreshStartTime(0),
Dan Stozab90cf072015-03-05 11:05:59 -0800268 mHasPoweredOff(false),
Steven Thomas050b2c82017-03-06 11:45:16 -0800269 mNumLayers(0),
Steven Thomasb02664d2017-07-26 18:48:28 -0700270 mVrFlingerRequestsDisplay(false),
Lloyd Pique70d91362018-10-18 16:02:55 -0700271 mMainThreadId(std::this_thread::get_id()),
272 mCompositionEngine{getFactory().createCompositionEngine()} {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800273
Lloyd Pique90c115d2018-09-18 21:39:42 -0700274SurfaceFlinger::SurfaceFlinger(surfaceflinger::Factory& factory)
275 : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800276 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800277
278 vsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
279 &ISurfaceFlingerConfigs::vsyncEventPhaseOffsetNs>(1000000);
280
281 sfVsyncPhaseOffsetNs = getInt64< ISurfaceFlingerConfigs,
282 &ISurfaceFlingerConfigs::vsyncSfEventPhaseOffsetNs>(1000000);
283
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800284 hasSyncFramework = getBool< ISurfaceFlingerConfigs,
285 &ISurfaceFlingerConfigs::hasSyncFramework>(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800286
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700287 dispSyncPresentTimeOffset = getInt64< ISurfaceFlingerConfigs,
288 &ISurfaceFlingerConfigs::presentTimeOffsetFromVSyncNs>(0);
289
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700290 useHwcForRgbToYuv = getBool< ISurfaceFlingerConfigs,
291 &ISurfaceFlingerConfigs::useHwcForRGBtoYUV>(false);
292
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800293 maxVirtualDisplaySize = getUInt64<ISurfaceFlingerConfigs,
294 &ISurfaceFlingerConfigs::maxVirtualDisplaySize>(0);
295
Steven Thomas050b2c82017-03-06 11:45:16 -0800296 // Vr flinger is only enabled on Daydream ready devices.
297 useVrFlinger = getBool< ISurfaceFlingerConfigs,
298 &ISurfaceFlingerConfigs::useVrFlinger>(false);
299
Fabien Sanglard1971b632017-03-10 14:50:03 -0800300 maxFrameBufferAcquiredBuffers = getInt64< ISurfaceFlingerConfigs,
301 &ISurfaceFlingerConfigs::maxFrameBufferAcquiredBuffers>(2);
302
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600303 hasWideColorDisplay =
304 getBool<ISurfaceFlingerConfigs, &ISurfaceFlingerConfigs::hasWideColorDisplay>(false);
Peiyong Lin13effd12018-07-24 17:01:47 -0700305 useColorManagement =
Peiyong Lin0256f722018-08-31 15:45:10 -0700306 getBool<V1_2::ISurfaceFlingerConfigs,
307 &V1_2::ISurfaceFlingerConfigs::useColorManagement>(false);
308
309 auto surfaceFlingerConfigsServiceV1_2 = V1_2::ISurfaceFlingerConfigs::getService();
310 if (surfaceFlingerConfigsServiceV1_2) {
311 surfaceFlingerConfigsServiceV1_2->getCompositionPreference(
Peiyong Linc6780972018-10-28 15:24:08 -0700312 [&](auto tmpDefaultDataspace, auto tmpDefaultPixelFormat,
313 auto tmpWideColorGamutDataspace, auto tmpWideColorGamutPixelFormat) {
314 defaultCompositionDataspace = tmpDefaultDataspace;
315 defaultCompositionPixelFormat = tmpDefaultPixelFormat;
316 wideColorGamutCompositionDataspace = tmpWideColorGamutDataspace;
317 wideColorGamutCompositionPixelFormat = tmpWideColorGamutPixelFormat;
318 });
Peiyong Lin0256f722018-08-31 15:45:10 -0700319 }
Peiyong Lin9d846a52018-11-05 13:18:20 -0800320 mDefaultCompositionDataspace = defaultCompositionDataspace;
321 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600322
Peiyong Linb3839ad2018-09-05 15:37:19 -0700323 useContextPriority = getBool<ISurfaceFlingerConfigs,
324 &ISurfaceFlingerConfigs::useContextPriority>(true);
325
Iris Chang7501ed62018-04-30 14:45:42 +0800326 V1_1::DisplayOrientation primaryDisplayOrientation =
Peiyong Lin0256f722018-08-31 15:45:10 -0700327 getDisplayOrientation<V1_1::ISurfaceFlingerConfigs,
328 &V1_1::ISurfaceFlingerConfigs::primaryDisplayOrientation>(
Iris Chang7501ed62018-04-30 14:45:42 +0800329 V1_1::DisplayOrientation::ORIENTATION_0);
330
331 switch (primaryDisplayOrientation) {
332 case V1_1::DisplayOrientation::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700333 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800334 break;
335 case V1_1::DisplayOrientation::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700336 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800337 break;
338 case V1_1::DisplayOrientation::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700339 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800340 break;
341 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700342 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800343 break;
344 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700345 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800346
Lloyd Pique90c115d2018-09-18 21:39:42 -0700347 mPrimaryDispSync =
348 getFactory().createDispSync("PrimaryDispSync", SurfaceFlinger::hasSyncFramework,
349 SurfaceFlinger::dispSyncPresentTimeOffset);
Saurabh Shahf4174532017-07-13 10:45:07 -0700350
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800351 // debugging stuff...
352 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700353
Mathias Agopianb4b17302013-03-20 18:36:41 -0700354 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700355 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700356
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800357 property_get("debug.sf.showupdates", value, "0");
358 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700359
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700360 property_get("debug.sf.ddms", value, "0");
361 mDebugDDMS = atoi(value);
362 if (mDebugDDMS) {
Keun young Park63f165f2012-08-31 10:53:36 -0700363 if (!startDdmConnection()) {
364 // start failed, and DDMS debugging not enabled
365 mDebugDDMS = 0;
366 }
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700367 }
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700368 ALOGI_IF(mDebugRegion, "showupdates enabled");
369 ALOGI_IF(mDebugDDMS, "DDMS debugging enabled");
Dan Stozac5da2712016-07-20 15:38:12 -0700370
371 property_get("debug.sf.disable_backpressure", value, "0");
372 mPropagateBackpressure = !atoi(value);
373 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700374
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800375 property_get("debug.sf.enable_hwc_vds", value, "0");
376 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800377 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800378
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800379 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800380 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800381 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700382
Yiwei Zhang243b3782018-05-15 17:40:04 -0700383 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700384 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
385 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
386
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200387 property_get("debug.sf.early_phase_offset_ns", value, "-1");
388 const int earlySfOffsetNs = atoi(value);
389
390 property_get("debug.sf.early_gl_phase_offset_ns", value, "-1");
391 const int earlyGlSfOffsetNs = atoi(value);
392
393 property_get("debug.sf.early_app_phase_offset_ns", value, "-1");
394 const int earlyAppOffsetNs = atoi(value);
395
396 property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
397 const int earlyGlAppOffsetNs = atoi(value);
398
Ana Krulec98b5b242018-08-10 15:03:23 -0700399 property_get("debug.sf.use_scheduler", value, "0");
400 mUseScheduler = atoi(value);
401
Jorim Jaggi22ec38b2018-06-19 15:57:08 +0200402 const VSyncModulator::Offsets earlyOffsets =
403 {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
404 earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
405 const VSyncModulator::Offsets earlyGlOffsets =
406 {earlyGlSfOffsetNs != -1 ? earlyGlSfOffsetNs : sfVsyncPhaseOffsetNs,
407 earlyGlAppOffsetNs != -1 ? earlyGlAppOffsetNs : vsyncPhaseOffsetNs};
408 mVsyncModulator.setPhaseOffsets(earlyOffsets, earlyGlOffsets,
409 {sfVsyncPhaseOffsetNs, vsyncPhaseOffsetNs});
Dan Stoza84d619e2018-03-28 17:07:36 -0700410
Romain Guy11d63f42017-07-20 12:47:14 -0700411 // We should be reading 'persist.sys.sf.color_saturation' here
412 // but since /data may be encrypted, we need to wait until after vold
413 // comes online to attempt to read the property. The property is
414 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800415
416 if (useTrebleTestingOverride()) {
417 // Without the override SurfaceFlinger cannot connect to HIDL
418 // services that are not listed in the manifests. Considered
419 // deriving the setting from the set service name, but it
420 // would be brittle if the name that's not 'default' is used
421 // for production purposes later on.
422 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
423 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800424}
425
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800426void SurfaceFlinger::onFirstRef()
427{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800428 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800429}
430
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800431SurfaceFlinger::~SurfaceFlinger()
432{
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800433}
434
Dan Stozac7014012014-02-14 15:03:43 -0800435void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800436{
437 // the window manager died on us. prepare its eulogy.
438
Andy McFadden13a082e2012-08-24 10:16:42 -0700439 // restore initial conditions (default device unblank, etc)
440 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800441
442 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700443 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800444}
445
Robert Carr1db73f62016-12-21 12:58:51 -0800446static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700447 status_t err = client->initCheck();
448 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800449 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800450 }
Robert Carr1db73f62016-12-21 12:58:51 -0800451 return nullptr;
452}
453
454sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
455 return initClient(new Client(this));
456}
457
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700458sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
459 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700460{
461 class DisplayToken : public BBinder {
462 sp<SurfaceFlinger> flinger;
463 virtual ~DisplayToken() {
464 // no more references, this display must be terminated
465 Mutex::Autolock _l(flinger->mStateLock);
466 flinger->mCurrentState.displays.removeItem(this);
467 flinger->setTransactionFlags(eDisplayTransactionNeeded);
468 }
469 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700470 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700471 : flinger(flinger) {
472 }
473 };
474
475 sp<BBinder> token = new DisplayToken(this);
476
477 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700478 // Display ID is assigned when virtual display is allocated by HWC.
479 DisplayDeviceState state;
480 state.isSecure = secure;
481 state.displayName = displayName;
482 mCurrentState.displays.add(token, state);
483 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700484 return token;
485}
486
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700487void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700488 Mutex::Autolock _l(mStateLock);
489
Dominik Laskowski075d3172018-05-24 15:50:06 -0700490 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
491 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700492 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700493 return;
494 }
495
Dominik Laskowski075d3172018-05-24 15:50:06 -0700496 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
497 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700498 ALOGE("destroyDisplay called for non-virtual display");
499 return;
500 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700501 mInterceptor->saveDisplayDeletion(state.sequenceId);
502 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700503 setTransactionFlags(eDisplayTransactionNeeded);
504}
505
Mathias Agopiane57f2922012-08-09 16:29:12 -0700506sp<IBinder> SurfaceFlinger::getBuiltInDisplay(int32_t id) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700507 std::optional<DisplayId> displayId;
508
509 if (id == HWC_DISPLAY_PRIMARY) {
510 displayId = getInternalDisplayId();
511 } else if (id == HWC_DISPLAY_EXTERNAL) {
512 displayId = getExternalDisplayId();
513 }
514
515 if (!displayId) {
516 ALOGE("%s: Invalid display %d", __FUNCTION__, id);
Peiyong Lin566a3b42018-01-09 18:22:43 -0800517 return nullptr;
Mathias Agopiane57f2922012-08-09 16:29:12 -0700518 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700519
520 return getPhysicalDisplayToken(*displayId);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700521}
522
Ady Abraham37965d42018-11-01 13:43:32 -0700523status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
524 if (!outGetColorManagement) {
525 return BAD_VALUE;
526 }
527 *outGetColorManagement = useColorManagement;
528 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700529}
530
Lloyd Pique441d5042018-10-18 16:49:51 -0700531HWComposer& SurfaceFlinger::getHwComposer() const {
532 return mCompositionEngine->getHwComposer();
533}
534
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700535renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
536 return mCompositionEngine->getRenderEngine();
537}
538
Lloyd Pique70d91362018-10-18 16:02:55 -0700539compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
540 return *mCompositionEngine.get();
541}
542
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800543void SurfaceFlinger::bootFinished()
544{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700545 if (mStartPropertySetThread->join() != NO_ERROR) {
546 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800547 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800548 const nsecs_t now = systemTime();
549 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000550 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700551
552 // wait patiently for the window manager death
553 const String16 name("window");
554 sp<IBinder> window(defaultServiceManager()->getService(name));
555 if (window != 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700556 window->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700557 }
Robert Carr720e5062018-07-30 17:45:14 -0700558 sp<IBinder> input(defaultServiceManager()->getService(
559 String16("inputflinger")));
560 if (input == nullptr) {
561 ALOGE("Failed to link to input service");
562 } else {
563 mInputFlinger = interface_cast<IInputFlinger>(input);
564 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700565
Steven Thomas050b2c82017-03-06 11:45:16 -0800566 if (mVrFlinger) {
567 mVrFlinger->OnBootFinished();
568 }
569
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700570 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700571 // formerly we would just kill the process, but we now ask it to exit so it
572 // can choose where to stop the animation.
573 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700574
575 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
576 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
577 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700578
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800579 postMessageAsync(new LambdaMessage([this] {
580 readPersistentProperties();
581 mBootStage = BootStage::FINISHED;
582 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800583}
584
Dan Stoza436ccf32018-06-21 12:10:12 -0700585uint32_t SurfaceFlinger::getNewTexture() {
586 {
587 std::lock_guard lock(mTexturePoolMutex);
588 if (!mTexturePool.empty()) {
589 uint32_t name = mTexturePool.back();
590 mTexturePool.pop_back();
591 ATRACE_INT("TexturePoolSize", mTexturePool.size());
592 return name;
593 }
594
595 // The pool was too small, so increase it for the future
596 ++mTexturePoolSize;
597 }
598
599 // The pool was empty, so we need to get a new texture name directly using a
600 // blocking call to the main thread
601 uint32_t name = 0;
602 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
603 return name;
604}
605
Mathias Agopian3f844832013-08-07 21:24:32 -0700606void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700607 postMessageAsync(new LambdaMessage([=] { getRenderEngine().deleteTextures(1, &texture); }));
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700608}
609
Wei Wangf9b05ee2017-07-19 20:59:39 -0700610// Do not call property_set on main thread which will be blocked by init
611// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700612void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700613 ALOGI( "SurfaceFlinger's main thread ready to run. "
614 "Initializing graphics H/W...");
615
Thierry Strudel2924d012017-08-14 15:19:37 -0700616 ALOGI("Phase offest NS: %" PRId64 "", vsyncPhaseOffsetNs);
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900617
Steven Thomasb02664d2017-07-26 18:48:28 -0700618 Mutex::Autolock _l(mStateLock);
Dan Stoza9e56aa02015-11-02 13:00:03 -0800619
Steven Thomasb02664d2017-07-26 18:48:28 -0700620 // start the EventThread
Ana Krulec98b5b242018-08-10 15:03:23 -0700621 if (mUseScheduler) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700622 mScheduler = getFactory().createScheduler([this](bool enabled) {
623 setVsyncEnabled(EventThread::DisplayType::Primary, enabled);
624 });
625
Ana Krulec98b5b242018-08-10 15:03:23 -0700626 mAppConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700627 mScheduler->createConnection("appConnection", SurfaceFlinger::vsyncPhaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700628 [this] { resyncWithRateLimit(); },
629 impl::EventThread::InterceptVSyncsCallback());
630 mSfConnectionHandle =
Ana Krulece588e312018-09-18 12:32:24 -0700631 mScheduler->createConnection("sfConnection", SurfaceFlinger::sfVsyncPhaseOffsetNs,
Ana Krulec98b5b242018-08-10 15:03:23 -0700632 [this] { resyncWithRateLimit(); },
633 [this](nsecs_t timestamp) {
634 mInterceptor->saveVSyncEvent(timestamp);
635 });
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800636
Ana Krulec98b5b242018-08-10 15:03:23 -0700637 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
Ana Krulec12096d02018-09-07 14:54:14 -0700638 mVsyncModulator.setSchedulerAndHandles(mScheduler.get(), mAppConnectionHandle.get(),
639 mSfConnectionHandle.get());
Ana Krulec98b5b242018-08-10 15:03:23 -0700640 } else {
641 mEventThreadSource =
642 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
643 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
644 mEventThread =
645 std::make_unique<impl::EventThread>(mEventThreadSource.get(),
646 [this] { resyncWithRateLimit(); },
647 impl::EventThread::InterceptVSyncsCallback(),
648 "appEventThread");
649 mSfEventThreadSource =
650 std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
651 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
652
653 mSFEventThread =
654 std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
655 [this] { resyncWithRateLimit(); },
656 [this](nsecs_t timestamp) {
657 mInterceptor->saveVSyncEvent(timestamp);
658 },
659 "sfEventThread");
660 mEventQueue->setEventThread(mSFEventThread.get());
661 mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
662 }
Dan Stoza9e56aa02015-11-02 13:00:03 -0800663
Steven Thomasb02664d2017-07-26 18:48:28 -0700664 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700665 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700666 renderEngineFeature |= (useColorManagement ?
667 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700668 renderEngineFeature |= (useContextPriority ?
669 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700670
671 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700672 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700673 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700674 renderEngineFeature));
Steven Thomasb02664d2017-07-26 18:48:28 -0700675
676 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
677 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700678 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
679 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800680 // Process any initial hotplug and resulting display changes.
681 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700682 const auto display = getDefaultDisplayDeviceLocked();
683 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700684 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700685 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800686
Steven Thomas050b2c82017-03-06 11:45:16 -0800687 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700688 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700689 // This callback is called from the vr flinger dispatch thread. We
690 // need to call signalTransaction(), which requires holding
691 // mStateLock when we're not on the main thread. Acquiring
692 // mStateLock from the vr flinger dispatch thread might trigger a
693 // deadlock in surface flinger (see b/66916578), so post a message
694 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700695 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700696 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
697 mVrFlingerRequestsDisplay = requestDisplay;
698 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700699 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800700 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700701 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
702 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700703 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700704 .value_or(0),
705 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800706 if (!mVrFlinger) {
707 ALOGE("Failed to start vrflinger");
708 }
709 }
710
Lloyd Pique90c115d2018-09-18 21:39:42 -0700711 mEventControlThread = getFactory().createEventControlThread(
Dominik Laskowski075d3172018-05-24 15:50:06 -0700712 [this](bool enabled) { setVsyncEnabled(EventThread::DisplayType::Primary, enabled); });
Jamie Gennisd1700752013-10-14 12:22:52 -0700713
Mathias Agopian92a979a2012-08-02 18:32:23 -0700714 // initialize our drawing state
715 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700716
Andy McFadden13a082e2012-08-24 10:16:42 -0700717 // set initial conditions (e.g. unblank default device)
718 initializeDisplays();
719
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700720 getRenderEngine().primeCache();
Dan Stoza4e637772016-07-28 13:31:51 -0700721
Wei Wangf9b05ee2017-07-19 20:59:39 -0700722 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700723
724 const bool presentFenceReliable =
725 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
726 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700727
728 if (mStartPropertySetThread->Start() != NO_ERROR) {
729 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800730 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800731
Ana Krulec7d1d6832018-12-27 11:10:09 -0800732 if (mUseScheduler) {
733 mScheduler->setExpiredIdleTimerCallback([this]() { setRefreshRateTo(60.f /* fps */); });
734 mScheduler->setResetIdleTimerCallback([this]() { setRefreshRateTo(90.f /* fps */); });
735 }
736
Dan Stoza9e56aa02015-11-02 13:00:03 -0800737 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700738}
739
Romain Guy11d63f42017-07-20 12:47:14 -0700740void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700741 Mutex::Autolock _l(mStateLock);
742
Romain Guy11d63f42017-07-20 12:47:14 -0700743 char value[PROPERTY_VALUE_MAX];
744
745 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800746 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700747 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800748 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100749
750 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700751 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700752}
753
Mathias Agopiana67e4182012-06-19 17:26:12 -0700754void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800755 // Start boot animation service by setting a property mailbox
756 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700757 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800758 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700759 if (mStartPropertySetThread->join() != NO_ERROR) {
760 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800761 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700762}
763
Mathias Agopian875d8e12013-06-07 15:35:48 -0700764size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700765 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700766}
767
Mathias Agopian875d8e12013-06-07 15:35:48 -0700768size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700769 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700770}
771
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800772// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800773
Jamie Gennis582270d2011-08-17 18:19:00 -0700774bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800775 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800776 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800777 return authenticateSurfaceTextureLocked(bufferProducer);
778}
779
780bool SurfaceFlinger::authenticateSurfaceTextureLocked(
781 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800782 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800783 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800784}
785
Brian Anderson6b376712017-04-04 10:51:39 -0700786status_t SurfaceFlinger::getSupportedFrameTimestamps(
787 std::vector<FrameEvent>* outSupported) const {
788 *outSupported = {
789 FrameEvent::REQUESTED_PRESENT,
790 FrameEvent::ACQUIRE,
791 FrameEvent::LATCH,
792 FrameEvent::FIRST_REFRESH_START,
793 FrameEvent::LAST_REFRESH_START,
794 FrameEvent::GPU_COMPOSITION_DONE,
795 FrameEvent::DEQUEUE_READY,
796 FrameEvent::RELEASE,
797 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700798 ConditionalLock _l(mStateLock,
799 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700800 if (!getHwComposer().hasCapability(
801 HWC2::Capability::PresentFenceIsNotReliable)) {
802 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
803 }
804 return NO_ERROR;
805}
806
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700807status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
808 Vector<DisplayInfo>* configs) {
809 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700810 return BAD_VALUE;
811 }
812
Dominik Laskowski075d3172018-05-24 15:50:06 -0700813 const auto displayId = getPhysicalDisplayId(displayToken);
814 if (!displayId) {
815 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700816 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700817
Mathias Agopian8b736f12012-08-13 17:54:26 -0700818 // TODO: Not sure if display density should handled by SF any longer
819 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700820 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700821 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700822 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800823 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700824 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700825 }
826 return density;
827 }
828 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700829 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700830 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700831 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700832 return getDensityFromProperty("ro.sf.lcd_density"); }
833 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700834
Dan Stoza7f7da322014-05-02 15:26:25 -0700835 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700836
Steven Thomas6d8110b2017-08-31 18:24:21 -0700837 ConditionalLock _l(mStateLock,
838 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700839 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700840 DisplayInfo info = DisplayInfo();
841
Dan Stoza9e56aa02015-11-02 13:00:03 -0800842 float xdpi = hwConfig->getDpiX();
843 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700844
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700845 info.w = hwConfig->getWidth();
846 info.h = hwConfig->getHeight();
847 // Default display viewport to display width and height
848 info.viewportW = info.w;
849 info.viewportH = info.h;
850
Dominik Laskowski075d3172018-05-24 15:50:06 -0700851 if (displayId == getInternalDisplayId()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700852 // The density of the device is provided by a build property
853 float density = Density::getBuildDensity() / 160.0f;
854 if (density == 0) {
855 // the build doesn't provide a density -- this is wrong!
856 // use xdpi instead
857 ALOGE("ro.sf.lcd_density must be defined as a build property");
858 density = xdpi / 160.0f;
859 }
860 if (Density::getEmuDensity()) {
861 // if "qemu.sf.lcd_density" is specified, it overrides everything
862 xdpi = ydpi = density = Density::getEmuDensity();
863 density /= 160.0f;
864 }
865 info.density = density;
866
867 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700868 const auto display = getDefaultDisplayDeviceLocked();
869 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700870
871 // This is for screenrecord
872 const Rect viewport = display->getViewport();
873 if (viewport.isValid()) {
874 info.viewportW = uint32_t(viewport.getWidth());
875 info.viewportH = uint32_t(viewport.getHeight());
876 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700877 } else {
878 // TODO: where should this value come from?
879 static const int TV_DENSITY = 213;
880 info.density = TV_DENSITY / 160.0f;
881 info.orientation = 0;
882 }
883
Dan Stoza7f7da322014-05-02 15:26:25 -0700884 info.xdpi = xdpi;
885 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800886 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900887 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800888
Andy McFadden91b2ca82014-06-13 14:04:23 -0700889 // This is how far in advance a buffer must be queued for
890 // presentation at a given time. If you want a buffer to appear
891 // on the screen at time N, you must submit the buffer before
892 // (N - presentationDeadline).
893 //
894 // Normally it's one full refresh period (to give SF a chance to
895 // latch the buffer), but this can be reduced by configuring a
896 // DispSync offset. Any additional delays introduced by the hardware
897 // composer or panel must be accounted for here.
898 //
899 // We add an additional 1ms to allow for processing time and
900 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800901 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800902 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700903
904 // All non-virtual displays are currently considered secure.
905 info.secure = true;
906
Dominik Laskowski075d3172018-05-24 15:50:06 -0700907 if (displayId == getInternalDisplayId() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700908 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800909 std::swap(info.w, info.h);
910 }
911
Michael Wright28f24d02016-07-12 13:30:53 -0700912 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700913 }
914
Dan Stoza7f7da322014-05-02 15:26:25 -0700915 return NO_ERROR;
916}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700917
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700918status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
919 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700920 return BAD_VALUE;
921 }
922
Ana Krulece588e312018-09-18 12:32:24 -0700923 if (mUseScheduler) {
924 mScheduler->getDisplayStatInfo(stats);
925 } else {
926 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
927 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
928 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700929 return NO_ERROR;
930}
931
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700932int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
933 const auto display = getDisplayDevice(displayToken);
934 if (!display) {
935 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800936 return BAD_VALUE;
937 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700938
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700939 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700940}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700941
Ana Krulec7d1d6832018-12-27 11:10:09 -0800942status_t SurfaceFlinger::setActiveConfigAsync(const sp<IBinder>& displayToken, int mode) {
943 ATRACE_NAME("setActiveConfigAsync");
944 postMessageAsync(new LambdaMessage([=] { setActiveConfigInternal(displayToken, mode); }));
945 return NO_ERROR;
946}
947
948status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
949 ATRACE_NAME("setActiveConfigSync");
950 postMessageSync(new LambdaMessage([&] { setActiveConfigInternal(displayToken, mode); }));
951 return NO_ERROR;
952}
953
954void SurfaceFlinger::setActiveConfigInternal(const sp<IBinder>& displayToken, int mode) {
955 Vector<DisplayInfo> configs;
956 getDisplayConfigs(displayToken, &configs);
957 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
958 ALOGE("Attempt to set active config %d for display with %zu configs", mode, configs.size());
959 return;
960 }
961
962 const auto display = getDisplayDevice(displayToken);
963 if (!display) {
964 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
965 displayToken.get());
966 return;
967 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700968 if (display->isVirtual()) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800969 ALOGW("Attempt to set active config %d for virtual display", mode);
970 return;
971 }
972 int currentDisplayPowerMode = display->getPowerMode();
973 if (currentDisplayPowerMode != HWC_POWER_MODE_NORMAL) {
974 // Don't change active config when in AoD.
Dominik Laskowski075d3172018-05-24 15:50:06 -0700975 return;
976 }
977
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700978 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700979 if (mode == currentMode) {
Ana Krulec7d1d6832018-12-27 11:10:09 -0800980 // Don't update config if we are already running in the desired mode.
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700981 return;
982 }
983
Dominik Laskowski075d3172018-05-24 15:50:06 -0700984 const auto displayId = display->getId();
985 LOG_ALWAYS_FATAL_IF(!displayId);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700986
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700987 display->setActiveConfig(mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700988 getHwComposer().setActiveConfig(*displayId, mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700989
Ana Krulec7d1d6832018-12-27 11:10:09 -0800990 ATRACE_INT("ActiveConfigMode", mode);
991 resyncToHardwareVsync(true);
Mathias Agopianc666cae2012-07-25 18:56:13 -0700992}
Dominik Laskowski075d3172018-05-24 15:50:06 -0700993
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700994status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
995 Vector<ColorMode>* outColorModes) {
996 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700997 return BAD_VALUE;
998 }
999
Dominik Laskowski075d3172018-05-24 15:50:06 -07001000 const auto displayId = getPhysicalDisplayId(displayToken);
1001 if (!displayId) {
1002 return NAME_NOT_FOUND;
Michael Wright28f24d02016-07-12 13:30:53 -07001003 }
1004
Peiyong Lina52f0292018-03-14 17:26:31 -07001005 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001006 {
1007 ConditionalLock _l(mStateLock,
1008 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001009 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -07001010 }
Michael Wright28f24d02016-07-12 13:30:53 -07001011 outColorModes->clear();
1012 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1013
1014 return NO_ERROR;
1015}
1016
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001017ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1018 if (const auto display = getDisplayDevice(displayToken)) {
1019 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001020 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001021 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001022}
1023
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001024void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1025 Dataspace dataSpace, RenderIntent renderIntent) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001026 if (display->isVirtual()) {
1027 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
1028 return;
1029 }
1030
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001031 ColorMode currentMode = display->getActiveColorMode();
1032 Dataspace currentDataSpace = display->getCompositionDataSpace();
1033 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001034
Peiyong Lin38e9a562018-04-10 16:24:20 -07001035 if (mode == currentMode && dataSpace == currentDataSpace &&
1036 renderIntent == currentRenderIntent) {
1037 return;
1038 }
1039
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001040 display->setActiveColorMode(mode);
1041 display->setCompositionDataSpace(dataSpace);
1042 display->setActiveRenderIntent(renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001043
Dominik Laskowski075d3172018-05-24 15:50:06 -07001044 const auto displayId = display->getId();
1045 LOG_ALWAYS_FATAL_IF(!displayId);
1046 getHwComposer().setActiveColorMode(*displayId, mode, renderIntent);
1047
Dominik Laskowski34157762018-10-31 13:07:19 -07001048 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), display=%s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001049 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
Dominik Laskowski34157762018-10-31 13:07:19 -07001050 renderIntent, to_string(*displayId).c_str());
Michael Wright28f24d02016-07-12 13:30:53 -07001051}
1052
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001053status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001054 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001055 Vector<ColorMode> modes;
1056 getDisplayColorModes(displayToken, &modes);
1057 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1058 if (mode < ColorMode::NATIVE || !exists) {
1059 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1060 decodeColorMode(mode).c_str(), mode, displayToken.get());
1061 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001062 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001063 const auto display = getDisplayDevice(displayToken);
1064 if (!display) {
1065 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1066 decodeColorMode(mode).c_str(), mode, displayToken.get());
1067 } else if (display->isVirtual()) {
1068 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1069 decodeColorMode(mode).c_str(), mode);
1070 } else {
1071 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1072 RenderIntent::COLORIMETRIC);
1073 }
1074 }));
1075
Michael Wright28f24d02016-07-12 13:30:53 -07001076 return NO_ERROR;
1077}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001078
Svetoslavd85084b2014-03-20 10:28:31 -07001079status_t SurfaceFlinger::clearAnimationFrameStats() {
1080 Mutex::Autolock _l(mStateLock);
1081 mAnimFrameTracker.clearStats();
1082 return NO_ERROR;
1083}
1084
1085status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1086 Mutex::Autolock _l(mStateLock);
1087 mAnimFrameTracker.getStats(outStats);
1088 return NO_ERROR;
1089}
1090
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001091status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1092 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001093 Mutex::Autolock _l(mStateLock);
1094
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001095 const auto display = getDisplayDeviceLocked(displayToken);
1096 if (!display) {
1097 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001098 return BAD_VALUE;
1099 }
1100
Peiyong Linfb069302018-04-25 14:34:31 -07001101 // At this point the DisplayDeivce should already be set up,
1102 // meaning the luminance information is already queried from
1103 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001104 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001105 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1106 capabilities.getDesiredMaxLuminance(),
1107 capabilities.getDesiredMaxAverageLuminance(),
1108 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001109
1110 return NO_ERROR;
1111}
1112
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001113status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1114 ui::PixelFormat* outFormat,
1115 ui::Dataspace* outDataspace,
1116 uint8_t* outComponentMask) const {
1117 if (!outFormat || !outDataspace || !outComponentMask) {
1118 return BAD_VALUE;
1119 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001120 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001121 if (!display || !display->getId()) {
1122 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1123 return BAD_VALUE;
1124 }
1125 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1126 outDataspace, outComponentMask);
1127}
1128
Kevin DuBois74e53772018-11-19 10:52:38 -08001129status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1130 bool enable, uint8_t componentMask,
1131 uint64_t maxFrames) const {
1132 const auto display = getDisplayDevice(displayToken);
1133 if (!display || !display->getId()) {
1134 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1135 return BAD_VALUE;
1136 }
1137
1138 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1139 componentMask, maxFrames);
1140}
1141
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001142status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1143 uint64_t maxFrames, uint64_t timestamp,
1144 DisplayedFrameStats* outStats) const {
1145 const auto display = getDisplayDevice(displayToken);
1146 if (!display || !display->getId()) {
1147 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1148 return BAD_VALUE;
1149 }
1150
1151 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1152 outStats);
1153}
1154
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001155status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001156 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001157 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001158
Chia-I Wu90f669f2017-10-05 14:24:41 -07001159 if (mInjectVSyncs == enable) {
1160 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001161 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001162
Ana Krulec98b5b242018-08-10 15:03:23 -07001163 // TODO(akrulec): Part of the Injector should be refactored, so that it
1164 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001165 if (enable) {
1166 ALOGV("VSync Injections enabled");
1167 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001168 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001169 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001170 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001171 impl::EventThread::InterceptVSyncsCallback(),
1172 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001173 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001174 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001175 } else {
1176 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001177 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001178 }
1179
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001180 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001181 }));
1182
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001183 return NO_ERROR;
1184}
1185
1186status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001187 Mutex::Autolock _l(mStateLock);
1188
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001189 if (!mInjectVSyncs) {
1190 ALOGE("VSync Injections not enabled");
1191 return BAD_VALUE;
1192 }
1193 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1194 ALOGV("Injecting VSync inside SurfaceFlinger");
1195 mVSyncInjector->onInjectSyncEvent(when);
1196 }
1197 return NO_ERROR;
1198}
1199
Lloyd Pique755e3192018-01-31 16:46:15 -08001200status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1201 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001202 // Try to acquire a lock for 1s, fail gracefully
1203 const status_t err = mStateLock.timedLock(s2ns(1));
1204 const bool locked = (err == NO_ERROR);
1205 if (!locked) {
1206 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1207 return TIMED_OUT;
1208 }
1209
1210 outLayers->clear();
1211 mCurrentState.traverseInZOrder([&](Layer* layer) {
1212 outLayers->push_back(layer->getLayerDebugInfo());
1213 });
1214
1215 mStateLock.unlock();
1216 return NO_ERROR;
1217}
1218
Peiyong Linc6780972018-10-28 15:24:08 -07001219status_t SurfaceFlinger::getCompositionPreference(
1220 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1221 Dataspace* outWideColorGamutDataspace,
1222 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001223 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001224 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001225 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001226 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001227 return NO_ERROR;
1228}
1229
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001230// ----------------------------------------------------------------------------
1231
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001232sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1233 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulec98b5b242018-08-10 15:03:23 -07001234 if (mUseScheduler) {
1235 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1236 return mScheduler->createDisplayEventConnection(mSfConnectionHandle);
1237 } else {
1238 return mScheduler->createDisplayEventConnection(mAppConnectionHandle);
1239 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001240 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001241 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1242 return mSFEventThread->createEventConnection();
1243 } else {
1244 return mEventThread->createEventConnection();
1245 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001246 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001247}
1248
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001249// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001250
1251void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001252 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001253}
1254
1255void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001256 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001257}
1258
1259void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001260 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001261}
1262
1263void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001264 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001265 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001266}
1267
1268status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001269 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001270 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001271}
1272
1273status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001274 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001275 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001276 if (res == NO_ERROR) {
1277 msg->wait();
1278 }
1279 return res;
1280}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001281
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001282void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001283 do {
1284 waitForEvent();
1285 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001286}
1287
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001288void SurfaceFlinger::enableHardwareVsync() {
1289 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001290 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001291 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001292 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001293 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001294 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001295}
1296
Jesse Hall948fe0c2013-10-14 12:56:09 -07001297void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001298 Mutex::Autolock _l(mHWVsyncLock);
1299
Jesse Hall948fe0c2013-10-14 12:56:09 -07001300 if (makeAvailable) {
1301 mHWVsyncAvailable = true;
Ana Krulec7ab56032018-11-02 20:51:06 +01001302 // TODO(b/113612090): This is silly, but necessary evil until we turn on the flag for good.
1303 if (mUseScheduler) {
1304 mScheduler->makeHWSyncAvailable(true);
1305 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001306 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001307 // Hardware vsync is not currently available, so abort the resync
1308 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001309 return;
1310 }
1311
Dominik Laskowski075d3172018-05-24 15:50:06 -07001312 const auto displayId = getInternalDisplayId();
1313 if (!displayId || !getHwComposer().isConnected(*displayId)) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001314 return;
1315 }
1316
Dominik Laskowski075d3172018-05-24 15:50:06 -07001317 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001318 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001319
Ana Krulece588e312018-09-18 12:32:24 -07001320 if (mUseScheduler) {
1321 mScheduler->setVsyncPeriod(period);
1322 } else {
1323 mPrimaryDispSync->reset();
1324 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001325
Ana Krulece588e312018-09-18 12:32:24 -07001326 if (!mPrimaryHWVsyncEnabled) {
1327 mPrimaryDispSync->beginResync();
1328 mEventControlThread->setVsyncEnabled(true);
1329 mPrimaryHWVsyncEnabled = true;
1330 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001331 }
1332}
1333
Jesse Hall948fe0c2013-10-14 12:56:09 -07001334void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001335 Mutex::Autolock _l(mHWVsyncLock);
1336 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001337 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001338 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001339 mPrimaryHWVsyncEnabled = false;
1340 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001341 if (makeUnavailable) {
1342 mHWVsyncAvailable = false;
1343 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001344}
1345
Tim Murray4a4e4a22016-04-19 16:29:23 +00001346void SurfaceFlinger::resyncWithRateLimit() {
1347 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001348
1349 // No explicit locking is needed here since EventThread holds a lock while calling this method
1350 static nsecs_t sLastResyncAttempted = 0;
1351 const nsecs_t now = systemTime();
1352 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001353 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001354 }
Dan Stoza57164302017-05-08 14:03:54 -07001355 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001356}
1357
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001358void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1359 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001360 ATRACE_NAME("SF onVsync");
1361
Steven Thomas3cfac282017-02-06 12:29:30 -08001362 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001363 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001364 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001365 return;
1366 }
1367
Dominik Laskowski075d3172018-05-24 15:50:06 -07001368 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001369 return;
1370 }
1371
Dominik Laskowski075d3172018-05-24 15:50:06 -07001372 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001373 // For now, we don't do anything with external display vsyncs.
1374 return;
1375 }
1376
Ana Krulece588e312018-09-18 12:32:24 -07001377 if (mUseScheduler) {
1378 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001379 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001380 bool needsHwVsync = false;
1381 { // Scope for the lock
1382 Mutex::Autolock _l(mHWVsyncLock);
1383 if (mPrimaryHWVsyncEnabled) {
1384 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1385 }
1386 }
1387
1388 if (needsHwVsync) {
1389 enableHardwareVsync();
1390 } else {
1391 disableHardwareVsync(false);
1392 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001393 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001394}
1395
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001396void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001397 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1398 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001399}
1400
Ana Krulec7d1d6832018-12-27 11:10:09 -08001401void SurfaceFlinger::setRefreshRateTo(float newFps) {
1402 const auto displayId = getInternalDisplayId();
1403 if (!displayId || mBootStage != BootStage::FINISHED) {
1404 return;
1405 }
1406 // TODO(b/113612090): There should be a message queue flush here. Because this esentially
1407 // runs on a mainthread, we cannot call postMessageSync. This can be resolved in a better
1408 // manner, once the setActiveConfig is synchronous, and is executed at a known time in a
1409 // refresh cycle.
1410
1411 // Don't do any updating if the current fps is the same as the new one.
1412 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
1413 const nsecs_t currentVsyncPeriod = activeConfig->getVsyncPeriod();
1414 if (currentVsyncPeriod == 0) {
1415 return;
1416 }
1417 // TODO(b/113612090): Consider having an enum value for correct refresh rates, rather than
1418 // floating numbers.
1419 const float currentFps = 1e9 / currentVsyncPeriod;
1420 if (std::abs(currentFps - newFps) <= 1) {
1421 return;
1422 }
1423
1424 auto configs = getHwComposer().getConfigs(*displayId);
1425 for (int i = 0; i < configs.size(); i++) {
1426 const nsecs_t vsyncPeriod = configs.at(i)->getVsyncPeriod();
1427 if (vsyncPeriod == 0) {
1428 continue;
1429 }
1430 const float fps = 1e9 / vsyncPeriod;
1431 // TODO(b/113612090): There should be a better way at determining which config
1432 // has the right refresh rate.
1433 if (std::abs(fps - newFps) <= 1) {
1434 const auto display = getBuiltInDisplay(HWC_DISPLAY_PRIMARY);
1435 if (!display) return;
1436 // This is posted in async function to avoid deadlock when getDisplayDevice
1437 // requires mStateLock.
1438 setActiveConfigAsync(display, i);
1439 ATRACE_INT("FPS", newFps);
1440 }
1441 }
1442}
1443
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001444void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001445 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001446 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001447 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001448
Lloyd Piqueba04e622017-12-14 17:11:26 -08001449 // Ignore events that do not have the right sequenceId.
1450 if (sequenceId != getBE().mComposerSequenceId) {
1451 return;
1452 }
1453
Steven Thomasb02664d2017-07-26 18:48:28 -07001454 // Only lock if we're not on the main thread. This function is normally
1455 // called on a hwbinder thread, but for the primary display it's called on
1456 // the main thread with the state lock already held, so don't attempt to
1457 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001458 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001459
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001460 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001461
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001462 if (std::this_thread::get_id() == mMainThreadId) {
1463 // Process all pending hot plug events immediately if we are on the main thread.
1464 processDisplayHotplugEventsLocked();
1465 }
1466
Lloyd Piqueba04e622017-12-14 17:11:26 -08001467 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001468}
1469
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001470void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001471 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001472 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001473 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001474 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001475 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001476}
1477
Dominik Laskowski075d3172018-05-24 15:50:06 -07001478void SurfaceFlinger::setVsyncEnabled(EventThread::DisplayType /*displayType*/, bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001479 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001480 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001481 if (const auto displayId = getInternalDisplayId()) {
1482 getHwComposer().setVsyncEnabled(*displayId,
1483 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1484 }
Mathias Agopian86303202012-07-24 22:46:10 -07001485}
1486
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001487// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001488void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001489 if (mUseScheduler) {
1490 mScheduler->disableHardwareVsync(true);
1491 } else {
1492 disableHardwareVsync(true);
1493 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001494 // Clear the drawing state so that the logic inside of
1495 // handleTransactionLocked will fire. It will determine the delta between
1496 // mCurrentState and mDrawingState and re-apply all changes when we make the
1497 // transition.
1498 mDrawingState.displays.clear();
1499 mDisplays.clear();
1500}
1501
Steven Thomas050b2c82017-03-06 11:45:16 -08001502void SurfaceFlinger::updateVrFlinger() {
1503 if (!mVrFlinger)
1504 return;
1505 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001506 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001507 return;
1508 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001509
Lloyd Pique441d5042018-10-18 16:49:51 -07001510 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001511 ALOGE("Vr flinger is only supported for remote hardware composer"
1512 " service connections. Ignoring request to transition to vr"
1513 " flinger.");
1514 mVrFlingerRequestsDisplay = false;
1515 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001516 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001517
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001518 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001519
Steven Thomas0123ac62018-07-12 11:32:34 -07001520 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001521 LOG_ALWAYS_FATAL_IF(!display);
1522 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001523 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1524 // called below. Clear the reference now so we don't accidentally use it
1525 // later.
1526 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001527
Steven Thomasb02664d2017-07-26 18:48:28 -07001528 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001529 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001530 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001531
Steven Thomasb02664d2017-07-26 18:48:28 -07001532 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001533 // Delete the current instance before creating the new one
1534 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1535 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1536 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1537 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001538
Lloyd Pique441d5042018-10-18 16:49:51 -07001539 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001540 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001541
1542 if (vrFlingerRequestsDisplay) {
1543 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001544 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001545
1546 mVisibleRegionsDirty = true;
1547 invalidateHwcGeometry();
1548
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001549 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001550 display = getDefaultDisplayDeviceLocked();
1551 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001552 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001553
Steven Thomasb02664d2017-07-26 18:48:28 -07001554 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski075d3172018-05-24 15:50:06 -07001555 const auto activeConfig = getHwComposer().getActiveConfig(*display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001556 const nsecs_t period = activeConfig->getVsyncPeriod();
1557 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001558
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001559 // The present fences returned from vr_hwc are not an accurate
1560 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001561 if (mUseScheduler) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001562 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
1563 !hasSyncFramework);
Ana Krulece588e312018-09-18 12:32:24 -07001564 } else {
Lloyd Pique441d5042018-10-18 16:49:51 -07001565 mPrimaryDispSync->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
Ana Krulece588e312018-09-18 12:32:24 -07001566 !hasSyncFramework);
1567 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001568
Steven Thomasb02664d2017-07-26 18:48:28 -07001569 // Use phase of 0 since phase is not known.
1570 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07001571 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
1572 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001573
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001574 resyncToHardwareVsync(false);
1575
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001576 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001577 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001578}
1579
Mathias Agopian4fec8732012-06-29 14:12:52 -07001580void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001581 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001582 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001583 case MessageQueue::INVALIDATE: {
Ana Krulec3084c052018-11-21 20:27:17 +01001584 if (mUseScheduler) {
1585 // This call is made each time SF wakes up and creates a new frame.
1586 mScheduler->incrementFrameCounter();
1587 }
Dan Stoza50182882016-07-08 12:02:20 -07001588 bool frameMissed = !mHadClientComposition &&
1589 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001590 (mPreviousPresentFence->getSignalTime() ==
1591 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001592 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001593 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001594 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001595 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001596 if (mPropagateBackpressure) {
1597 signalLayerUpdate();
1598 break;
1599 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001600 }
Dan Stoza50182882016-07-08 12:02:20 -07001601
Steven Thomas050b2c82017-03-06 11:45:16 -08001602 // Now that we're going to make it to the handleMessageTransaction()
1603 // call below it's safe to call updateVrFlinger(), which will
1604 // potentially trigger a display handoff.
1605 updateVrFlinger();
1606
Dan Stoza6b9454d2014-11-07 16:00:59 -08001607 bool refreshNeeded = handleMessageTransaction();
1608 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001609 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001610 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001611 // Signal a refresh if a transaction modified the window state,
1612 // a new buffer was latched, or if HWC has requested a full
1613 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001614 signalRefresh();
1615 }
1616 break;
1617 }
1618 case MessageQueue::REFRESH: {
1619 handleMessageRefresh();
1620 break;
1621 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001622 }
1623}
1624
Dan Stoza6b9454d2014-11-07 16:00:59 -08001625bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001626 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001627
1628 // Apply any ready transactions in the queues if there are still transactions that have not been
1629 // applied, wake up during the next vsync period and check again
1630 bool transactionNeeded = false;
1631 if (!flushTransactionQueues()) {
1632 transactionNeeded = true;
1633 }
1634
Mathias Agopian4fec8732012-06-29 14:12:52 -07001635 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001636 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001637 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001638
1639 if (transactionNeeded) {
1640 setTransactionFlags(eTransactionNeeded);
1641 }
1642
1643 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001644}
1645
Mathias Agopian4fec8732012-06-29 14:12:52 -07001646void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001647 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001648
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001649 mRefreshPending = false;
1650
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001651 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001652 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001653 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001654 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001655 for (const auto& [token, display] : mDisplays) {
1656 beginFrame(display);
1657 prepareFrame(display);
1658 doDebugFlashRegions(display, repaintEverything);
1659 doComposition(display, repaintEverything);
1660 }
1661
Adrian Roos1e1a1282017-11-01 19:05:31 +01001662 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001663 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001664
1665 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001666 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001667
Dan Stozabfbffeb2016-07-21 14:49:33 -07001668 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001669 for (const auto& [token, display] : mDisplays) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001670 mHadClientComposition =
1671 mHadClientComposition || getHwComposer().hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001672 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001673
Alec Mouri86770e52018-09-24 22:40:58 +00001674 // Setup RenderEngine sync fences if native sync is supported.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07001675 if (getRenderEngine().useNativeFenceSync()) {
Alec Mouri86770e52018-09-24 22:40:58 +00001676 if (mHadClientComposition) {
1677 base::unique_fd flushFence(getRenderEngine().flush());
1678 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1679 getBE().flushFence = new Fence(std::move(flushFence));
1680 } else {
1681 // Cleanup for hygiene.
1682 getBE().flushFence = Fence::NO_FENCE;
1683 }
1684 }
1685
Jorim Jaggi90535212018-05-23 23:44:06 +02001686 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001687
David Sodman7e4ae112018-02-09 15:02:28 -08001688 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001689 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001690 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[token]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001691 compositionInfo.hwc.hwcLayer = nullptr;
1692 }
David Sodmanba340492018-08-05 21:51:33 -07001693 }
David Sodman7e4ae112018-02-09 15:02:28 -08001694
1695 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001696}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001697
David Sodmanfa9b2af2017-12-24 13:28:59 -08001698
1699bool SurfaceFlinger::handleMessageInvalidate() {
1700 ATRACE_CALL();
1701 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001702}
1703
David Sodman79bba0e2018-08-05 18:07:49 -07001704void SurfaceFlinger::calculateWorkingSet() {
1705 ATRACE_CALL();
1706 ALOGV(__FUNCTION__);
1707
David Sodman79bba0e2018-08-05 18:07:49 -07001708 // build the h/w work list
1709 if (CC_UNLIKELY(mGeometryInvalid)) {
1710 mGeometryInvalid = false;
1711 for (const auto& [token, display] : mDisplays) {
1712 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001713 if (!displayId) {
1714 continue;
1715 }
David Sodman79bba0e2018-08-05 18:07:49 -07001716
Dominik Laskowski075d3172018-05-24 15:50:06 -07001717 const Vector<sp<Layer>>& currentLayers = display->getVisibleLayersSortedByZ();
1718 for (size_t i = 0; i < currentLayers.size(); i++) {
1719 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001720
Dominik Laskowski075d3172018-05-24 15:50:06 -07001721 if (!layer->hasHwcLayer(*displayId)) {
1722 if (!layer->createHwcLayer(&getHwComposer(), *displayId)) {
1723 layer->forceClientComposition(*displayId);
1724 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001725 }
1726 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001727
1728 layer->setGeometry(display, i);
1729 if (mDebugDisableHWC || mDebugRegion) {
1730 layer->forceClientComposition(*displayId);
1731 }
David Sodman79bba0e2018-08-05 18:07:49 -07001732 }
1733 }
1734 }
1735
1736 // Set the per-frame data
1737 for (const auto& [token, display] : mDisplays) {
1738 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001739 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001740 continue;
1741 }
1742
1743 if (mDrawingState.colorMatrixChanged) {
1744 display->setColorTransform(mDrawingState.colorMatrix);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001745 status_t result =
1746 getHwComposer().setColorTransform(*displayId, mDrawingState.colorMatrix);
Dominik Laskowski34157762018-10-31 13:07:19 -07001747 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on display %s: %d",
1748 to_string(*displayId).c_str(), result);
David Sodman79bba0e2018-08-05 18:07:49 -07001749 }
1750 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1751 if (layer->isHdrY410()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001752 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001753 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1754 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1755 !display->hasHDR10Support()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001756 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001757 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1758 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1759 !display->hasHLGSupport()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001760 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001761 }
1762
Peiyong Lind3788632018-09-18 16:01:31 -07001763 // TODO(b/111562338) remove when composer 2.3 is shipped.
1764 if (layer->hasColorTransform()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001765 layer->forceClientComposition(*displayId);
Peiyong Lind3788632018-09-18 16:01:31 -07001766 }
1767
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001768 if (layer->getRoundedCornerState().radius > 0.0f) {
1769 layer->forceClientComposition(*displayId);
1770 }
1771
Dominik Laskowski075d3172018-05-24 15:50:06 -07001772 if (layer->getForceClientComposition(*displayId)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001773 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski075d3172018-05-24 15:50:06 -07001774 layer->setCompositionType(*displayId, HWC2::Composition::Client);
David Sodman79bba0e2018-08-05 18:07:49 -07001775 continue;
1776 }
1777
Dominik Laskowski075d3172018-05-24 15:50:06 -07001778 layer->setPerFrameData(*displayId, display->getTransform(), display->getViewport(),
1779 display->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001780 }
1781
Peiyong Lin13effd12018-07-24 17:01:47 -07001782 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001783 ColorMode colorMode;
1784 Dataspace dataSpace;
1785 RenderIntent renderIntent;
1786 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1787 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1788 }
1789 }
1790
1791 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001792
1793 for (const auto& [token, display] : mDisplays) {
1794 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001795 const auto displayId = display->getId();
David Sodmanba340492018-08-05 21:51:33 -07001796 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001797
1798 if (displayId) {
1799 if (!layer->setHwcLayer(*displayId)) {
1800 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1801 }
1802 layer->getBE().compositionInfo.hwc.displayId = *displayId;
David Sodmanba340492018-08-05 21:51:33 -07001803 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001804
Dominik Laskowski05275f12018-11-01 15:03:24 -07001805 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001806 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1807 }
1808 }
David Sodman79bba0e2018-08-05 18:07:49 -07001809}
1810
David Sodmanfa9b2af2017-12-24 13:28:59 -08001811void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001812{
1813 // is debugging enabled
1814 if (CC_LIKELY(!mDebugRegion))
1815 return;
1816
David Sodmanfa9b2af2017-12-24 13:28:59 -08001817 if (display->isPoweredOn()) {
1818 // transform the dirty region into this screen's coordinate space
1819 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1820 if (!dirtyRegion.isEmpty()) {
1821 // redraw the whole screen
1822 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001823
David Sodmanfa9b2af2017-12-24 13:28:59 -08001824 // and draw the dirty region
David Sodmanfa9b2af2017-12-24 13:28:59 -08001825 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07001826 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001827
Alec Mouri0a9c7b82018-11-16 13:05:25 -08001828 display->queueBuffer(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001829 }
1830 }
1831
David Sodmanfa9b2af2017-12-24 13:28:59 -08001832 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001833
1834 if (mDebugRegion > 1) {
1835 usleep(mDebugRegion * 1000);
1836 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001837
Dominik Laskowski05275f12018-11-01 15:03:24 -07001838 prepareFrame(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001839}
1840
Adrian Roos1e1a1282017-11-01 19:05:31 +01001841void SurfaceFlinger::doTracing(const char* where) {
1842 ATRACE_CALL();
1843 ATRACE_NAME(where);
1844 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001845 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001846 }
1847}
1848
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001849void SurfaceFlinger::logLayerStats() {
1850 ATRACE_CALL();
1851 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001852 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001853 if (display->isPrimary()) {
1854 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001855 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001856 }
1857 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001858
1859 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001860 }
1861}
1862
David Sodman2b406362017-12-15 13:33:47 -08001863void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001864{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001865 ATRACE_CALL();
1866 ALOGV("preComposition");
1867
David Sodman2b406362017-12-15 13:33:47 -08001868 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1869
Mathias Agopiancd60f992012-08-16 16:28:27 -07001870 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001871 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001872 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001873 needExtraInvalidate = true;
1874 }
Robert Carr2047fae2016-11-28 14:09:09 -08001875 });
1876
Mathias Agopiancd60f992012-08-16 16:28:27 -07001877 if (needExtraInvalidate) {
1878 signalLayerUpdate();
1879 }
1880}
1881
Ana Krulece588e312018-09-18 12:32:24 -07001882void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1883 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001884 // Update queue of past composite+present times and determine the
1885 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001886 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001887 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001888 while (!getBE().mCompositePresentTimes.empty()) {
1889 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001890 // Cached values should have been updated before calling this method,
1891 // which helps avoid duplicate syscalls.
1892 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1893 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1894 break;
1895 }
1896 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001897 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001898 }
1899
1900 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001901 while (getBE().mCompositePresentTimes.size() > 16) {
1902 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001903 }
1904
Ana Krulece588e312018-09-18 12:32:24 -07001905 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001906}
1907
Ana Krulece588e312018-09-18 12:32:24 -07001908void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1909 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001910 // Integer division and modulo round toward 0 not -inf, so we need to
1911 // treat negative and positive offsets differently.
Ana Krulece588e312018-09-18 12:32:24 -07001912 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0)
1913 ? (stats.vsyncPeriod - (sfVsyncPhaseOffsetNs % stats.vsyncPeriod))
1914 : ((-sfVsyncPhaseOffsetNs) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001915
Brian Andersond0010582017-03-07 13:20:31 -08001916 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1917 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001918 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001919 }
1920
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001921 // Snap the latency to a value that removes scheduling jitter from the
1922 // composition and present times, which often have >1ms of jitter.
1923 // Reducing jitter is important if an app attempts to extrapolate
1924 // something (such as user input) to an accurate diasplay time.
1925 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1926 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001927 nsecs_t bias = stats.vsyncPeriod / 2;
1928 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1929 nsecs_t snappedCompositeToPresentLatency =
1930 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001931
David Sodman99974d22017-11-28 12:04:33 -08001932 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001933 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1934 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001935 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001936}
1937
David Sodman2b406362017-12-15 13:33:47 -08001938void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001939{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001940 ATRACE_CALL();
1941 ALOGV("postComposition");
1942
Brian Anderson3546a3f2016-07-14 11:51:14 -07001943 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001944 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001945 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001946 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001947 }
1948
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001949 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001950 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001951
David Sodman73beded2017-11-15 11:56:06 -08001952 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001953 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001954 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001955 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001956 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001957 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001958 } else {
1959 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1960 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001961
David Sodman73beded2017-11-15 11:56:06 -08001962 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001963 mPreviousPresentFence =
Dominik Laskowski075d3172018-05-24 15:50:06 -07001964 display ? getHwComposer().getPresentFence(*display->getId()) : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001965 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001966 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001967
Ana Krulece588e312018-09-18 12:32:24 -07001968 DisplayStatInfo stats;
1969 if (mUseScheduler) {
1970 mScheduler->getDisplayStatInfo(&stats);
1971 } else {
1972 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
1973 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
1974 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001975
David Sodman2b406362017-12-15 13:33:47 -08001976 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001977 // when we started doing work for this frame, but that should be okay
1978 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07001979 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001980 CompositorTiming compositorTiming;
1981 {
David Sodman99974d22017-11-28 12:04:33 -08001982 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1983 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001984 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001985
Robert Carr2047fae2016-11-28 14:09:09 -08001986 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001987 bool frameLatched = layer->onPostComposition(display->getId(), glCompositionDoneFenceTime,
1988 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001989 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001990 recordBufferingStats(layer->getName().string(),
1991 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001992 }
Robert Carr2047fae2016-11-28 14:09:09 -08001993 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001994
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001995 if (presentFenceTime->isValid()) {
Ana Krulece588e312018-09-18 12:32:24 -07001996 if (mUseScheduler) {
1997 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001998 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001999 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
2000 enableHardwareVsync();
2001 } else {
2002 disableHardwareVsync(false);
2003 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002004 }
2005 }
2006
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002007 if (!hasSyncFramework) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002008 if (display && getHwComposer().isConnected(*display->getId()) && display->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07002009 if (mUseScheduler) {
2010 mScheduler->enableHardwareVsync();
2011 } else {
2012 enableHardwareVsync();
2013 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002014 }
2015 }
2016
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002017 if (mAnimCompositionPending) {
2018 mAnimCompositionPending = false;
2019
Brian Anderson4e606e32017-03-16 15:34:57 -07002020 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002021 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002022 std::move(presentFenceTime));
Dominik Laskowski075d3172018-05-24 15:50:06 -07002023 } else if (display && getHwComposer().isConnected(*display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002024 // The HWC doesn't support present fences, so use the refresh
2025 // timestamp instead.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002026 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(*display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002027 mAnimFrameTracker.setActualPresentTime(presentTime);
2028 }
2029 mAnimFrameTracker.advanceFrame();
2030 }
Dan Stozab90cf072015-03-05 11:05:59 -08002031
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002032 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002033 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002034 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002035 }
2036
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002037 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002038
Dominik Laskowski075d3172018-05-24 15:50:06 -07002039 if (display && getHwComposer().isConnected(*display->getId()) && !display->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002040 return;
2041 }
2042
2043 nsecs_t currentTime = systemTime();
2044 if (mHasPoweredOff) {
2045 mHasPoweredOff = false;
2046 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002047 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002048 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002049 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2050 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002051 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002052 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002053 }
David Sodman4a36e932017-11-07 14:29:47 -08002054 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002055 }
David Sodman4a36e932017-11-07 14:29:47 -08002056 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002057
2058 {
2059 std::lock_guard lock(mTexturePoolMutex);
2060 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
2061 if (refillCount > 0) {
2062 const size_t offset = mTexturePool.size();
2063 mTexturePool.resize(mTexturePoolSize);
2064 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2065 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2066 }
2067 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002068
Marissa Wallfda30bb2018-10-12 11:34:28 -07002069 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002070 mTransactionCompletedThread.sendCallbacks();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002071}
2072
2073void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002074 ATRACE_CALL();
2075 ALOGV("rebuildLayerStacks");
2076
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002077 // We need to clear these out now as these may be holding on to a
2078 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2079 // also holds a reference. When the set of visible layers is recomputed,
2080 // some layers may be destroyed if the only thing keeping them alive was
2081 // that list of visible layers associated with each display. The layer
2082 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2083 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2084 for (const auto& [token, display] : mDisplays) {
2085 getBE().mCompositionInfo[token].clear();
2086 }
2087
Mathias Agopiancd60f992012-08-16 16:28:27 -07002088 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002089 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002090 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002091 mVisibleRegionsDirty = false;
2092 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002093
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002094 for (const auto& pair : mDisplays) {
2095 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07002096 Region opaqueRegion;
2097 Region dirtyRegion;
2098 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002099 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07002100 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002101 const Rect bounds = display->getBounds();
2102 if (display->isPoweredOn()) {
2103 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002104
Jeff Sharkey76488112017-02-27 14:15:18 -07002105 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08002106 bool hwcLayerDestroyed = false;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002107 const auto displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002108 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002109 Region drawRegion(tr.transform(
2110 layer->visibleNonTransparentRegion));
2111 drawRegion.andSelf(bounds);
2112 if (!drawRegion.isEmpty()) {
2113 layersSortedByZ.add(layer);
2114 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002115 // Clear out the HWC layer if this layer was
2116 // previously visible, but no longer is
Dominik Laskowski075d3172018-05-24 15:50:06 -07002117 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Jeff Sharkey76488112017-02-27 14:15:18 -07002118 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002119 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002120 // WM changes display->layerStack upon sleep/awake.
2121 // Here we make sure we delete the HWC layers even if
2122 // WM changed their layer stack.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002123 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Chia-I Wu83806892017-11-16 10:50:20 -08002124 }
2125
2126 // If a layer is not going to get a release fence because
2127 // it is invisible, but it is also going to release its
2128 // old buffer, add it to the list of layers needing
2129 // fences.
2130 if (hwcLayerDestroyed) {
2131 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2132 mLayersWithQueuedFrames.cend(), layer);
2133 if (found != mLayersWithQueuedFrames.cend()) {
2134 layersNeedingFences.add(layer);
2135 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002136 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002137 });
2138 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002139 display->setVisibleLayersSortedByZ(layersSortedByZ);
2140 display->setLayersNeedingFences(layersNeedingFences);
2141 display->undefinedRegion.set(bounds);
2142 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2143 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002144 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002145 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002146}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002147
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002148// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002149// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002150// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002151// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002152// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002153// The returned HDR data space is one of
2154// - Dataspace::UNKNOWN
2155// - Dataspace::BT2020_HLG
2156// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002157Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2158 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002159 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002160 *outHdrDataSpace = Dataspace::UNKNOWN;
2161
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002162 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002163 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002164 case Dataspace::V0_SCRGB:
2165 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002166 case Dataspace::BT2020:
2167 case Dataspace::BT2020_ITU:
2168 case Dataspace::BT2020_LINEAR:
2169 case Dataspace::DISPLAY_BT2020:
2170 bestDataSpace = Dataspace::DISPLAY_BT2020;
2171 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002172 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002173 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002174 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002175 case Dataspace::BT2020_PQ:
2176 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002177 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002178 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002179 case Dataspace::BT2020_HLG:
2180 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002181 // When there's mixed PQ content and HLG content, we set the HDR
2182 // data space to be BT2020_PQ and convert HLG to PQ.
2183 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2184 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002185 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002186 break;
2187 default:
2188 break;
2189 }
Romain Guy54f154a2017-10-24 21:40:32 +01002190 }
2191
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002192 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002193}
2194
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002195// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002196void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2197 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002198 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2199 *outMode = ColorMode::NATIVE;
2200 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002201 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002202 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002203 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002204
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002205 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002206 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002207
Peiyong Lindfde5112018-06-05 10:58:41 -07002208 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002209 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07002210 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002211 if (isHdr) {
2212 bestDataSpace = hdrDataSpace;
2213 }
2214
Chia-I Wu0d711262018-05-21 15:19:35 -07002215 RenderIntent intent;
2216 switch (mDisplayColorSetting) {
2217 case DisplayColorSetting::MANAGED:
2218 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002219 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002220 break;
2221 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002222 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002223 break;
2224 default: // vendor display color setting
2225 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2226 break;
2227 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002228
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002229 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002230}
2231
David Sodmanfa9b2af2017-12-24 13:28:59 -08002232void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002233{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002234 bool dirty = !display->getDirtyRegion(false).isEmpty();
2235 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2236 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002237
David Sodmanfa9b2af2017-12-24 13:28:59 -08002238 // If nothing has changed (!dirty), don't recompose.
2239 // If something changed, but we don't currently have any visible layers,
2240 // and didn't when we last did a composition, then skip it this time.
2241 // The second rule does two things:
2242 // - When all layers are removed from a display, we'll emit one black
2243 // frame, then nothing more until we get new layers.
2244 // - When a display is created with a private layer stack, we won't
2245 // emit any black frames until a layer is added to the layer stack.
2246 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002247
Dominik Laskowski075d3172018-05-24 15:50:06 -07002248 const char flagPrefix[] = {'-', '+'};
2249 static_cast<void>(flagPrefix);
2250 ALOGV_IF(display->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2251 __FUNCTION__, mustRecompose ? "doing" : "skipping", display->getDebugName().c_str(),
2252 flagPrefix[dirty], flagPrefix[empty], flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002253
David Sodmanfa9b2af2017-12-24 13:28:59 -08002254 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002255
David Sodmanfa9b2af2017-12-24 13:28:59 -08002256 if (mustRecompose) {
2257 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002258 }
2259}
2260
David Sodmanfa9b2af2017-12-24 13:28:59 -08002261void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002262{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002263 if (!display->isPoweredOn()) {
2264 return;
David Sodman2b406362017-12-15 13:33:47 -08002265 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002266
Dominik Laskowski05275f12018-11-01 15:03:24 -07002267 status_t result = display->prepareFrame(getHwComposer(),
2268 getBE().mCompositionInfo[display->getDisplayToken()]);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002269 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
2270 display->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002271}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002272
David Sodmanfa9b2af2017-12-24 13:28:59 -08002273void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002274 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002275 ALOGV("doComposition");
2276
David Sodmanfa9b2af2017-12-24 13:28:59 -08002277 if (display->isPoweredOn()) {
2278 // transform the dirty region into this screen's coordinate space
2279 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002280
David Sodmanfa9b2af2017-12-24 13:28:59 -08002281 // repaint the framebuffer (if needed)
2282 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002283
David Sodmanfa9b2af2017-12-24 13:28:59 -08002284 display->dirtyRegion.clear();
2285 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002286 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002287 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002288}
2289
David Sodmanfa9b2af2017-12-24 13:28:59 -08002290void SurfaceFlinger::postFrame()
2291{
2292 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002293 const auto display = getDefaultDisplayDeviceLocked();
2294 if (display && getHwComposer().isConnected(*display->getId())) {
2295 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002296 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2297 logFrameStats();
2298 }
2299 }
2300}
2301
2302void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002303{
Mathias Agopian841cde52012-03-01 15:44:37 -08002304 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002305 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002306
David Sodmanfa9b2af2017-12-24 13:28:59 -08002307 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002308
David Sodmanfa9b2af2017-12-24 13:28:59 -08002309 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002310 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002311 if (displayId) {
2312 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002313 }
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002314 display->onPresentDisplayCompleted();
David Sodman15094112018-10-11 09:39:37 -07002315 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002316 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002317
Chia-I Wu7b549592017-11-15 09:14:57 -08002318 // The layer buffer from the previous frame (if any) is released
2319 // by HWC only when the release fence from this frame (if any) is
2320 // signaled. Always get the release fence from HWC first.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002321 if (displayId && layer->hasHwcLayer(*displayId)) {
2322 releaseFence = getHwComposer().getLayerReleaseFence(*displayId,
2323 layer->getHwcLayer(*displayId));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002324 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002325
2326 // If the layer was client composited in the previous frame, we
2327 // need to merge with the previous client target acquire fence.
2328 // Since we do not track that, always merge with the current
2329 // client target acquire fence when it is available, even though
2330 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002331 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002332 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002333 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002334 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002335
David Sodman15094112018-10-11 09:39:37 -07002336 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002337 }
Chia-I Wu83806892017-11-16 10:50:20 -08002338
2339 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002340 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002341 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002342 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002343 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002344 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002345 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002346 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002347 }
2348 }
2349
Dominik Laskowski075d3172018-05-24 15:50:06 -07002350 if (displayId) {
2351 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002352 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002353 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002354}
2355
Mathias Agopian87baae12012-07-31 12:38:26 -07002356void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002357{
Mathias Agopian841cde52012-03-01 15:44:37 -08002358 ATRACE_CALL();
2359
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002360 // here we keep a copy of the drawing state (that is the state that's
2361 // going to be overwritten by handleTransactionLocked()) outside of
2362 // mStateLock so that the side-effects of the State assignment
2363 // don't happen with mStateLock held (which can cause deadlocks).
2364 State drawingState(mDrawingState);
2365
Mathias Agopianca4d3602011-05-19 15:38:14 -07002366 Mutex::Autolock _l(mStateLock);
2367 const nsecs_t now = systemTime();
2368 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002369
Mathias Agopianca4d3602011-05-19 15:38:14 -07002370 // Here we're guaranteed that some transaction flags are set
2371 // so we can call handleTransactionLocked() unconditionally.
2372 // We call getTransactionFlags(), which will also clear the flags,
2373 // with mStateLock held to guarantee that mCurrentState won't change
2374 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002375
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002376 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002377 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002378 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002379
Mathias Agopianca4d3602011-05-19 15:38:14 -07002380 mLastTransactionTime = systemTime() - now;
2381 mDebugInTransaction = 0;
2382 invalidateHwcGeometry();
2383 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002384}
2385
Lloyd Piqueba04e622017-12-14 17:11:26 -08002386void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2387 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002388 const std::optional<DisplayIdentificationInfo> info =
2389 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002390
Dominik Laskowski075d3172018-05-24 15:50:06 -07002391 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002392 continue;
2393 }
2394
Lloyd Piqueba04e622017-12-14 17:11:26 -08002395 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002396 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002397 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002398 mPhysicalDisplayTokens[info->id] = new BBinder();
2399 DisplayDeviceState state;
2400 state.displayId = info->id;
2401 state.isSecure = true; // All physical displays are currently considered secure.
2402 state.displayName = info->name;
2403 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2404 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002405 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002406 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002407 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002408
Dominik Laskowski075d3172018-05-24 15:50:06 -07002409 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2410 if (index >= 0) {
2411 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2412 mInterceptor->saveDisplayDeletion(state.sequenceId);
2413 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002414 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002415 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002416 }
2417
2418 processDisplayChangesLocked();
2419 }
2420
2421 mPendingHotplugEvents.clear();
2422}
2423
Lloyd Pique99d3da52018-01-22 17:48:03 -08002424sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002425 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
2426 const DisplayDeviceState& state, const sp<DisplaySurface>& dispSurface,
2427 const sp<IGraphicBufferProducer>& producer) {
2428 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002429 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002430 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002431 creationArgs.isSecure = state.isSecure;
2432 creationArgs.displaySurface = dispSurface;
2433 creationArgs.hasWideColorGamut = false;
2434 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002435
Dominik Laskowski075d3172018-05-24 15:50:06 -07002436 const bool isInternalDisplay = displayId && displayId == getInternalDisplayId();
2437 creationArgs.isPrimary = isInternalDisplay;
2438
2439 if (useColorManagement && displayId) {
2440 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002441 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002442 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002443 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002444 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002445
Dominik Laskowski7e045462018-05-30 13:02:02 -07002446 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002447 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002448 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002449 }
tangrobin6753a022018-08-10 10:58:54 +08002450 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002451
Dominik Laskowski075d3172018-05-24 15:50:06 -07002452 if (displayId) {
2453 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002454 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002455 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002456 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002457
Lloyd Pique90c115d2018-09-18 21:39:42 -07002458 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002459 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002460 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002461
Lloyd Pique99d3da52018-01-22 17:48:03 -08002462 // Make sure that composition can never be stalled by a virtual display
2463 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002464 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002465 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002466 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2467 }
2468
Dominik Laskowski075d3172018-05-24 15:50:06 -07002469 creationArgs.displayInstallOrientation =
2470 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002471
Lloyd Pique99d3da52018-01-22 17:48:03 -08002472 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002473 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002474
Lloyd Pique90c115d2018-09-18 21:39:42 -07002475 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002476
2477 if (maxFrameBufferAcquiredBuffers >= 3) {
2478 nativeWindowSurface->preallocateBuffers();
2479 }
2480
2481 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002482 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002483 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002484 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002485 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002486 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002487 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002488 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002489 if (!state.isVirtual()) {
2490 LOG_ALWAYS_FATAL_IF(!displayId);
2491 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002492 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002493
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002494 display->setLayerStack(state.layerStack);
2495 display->setProjection(state.orientation, state.viewport, state.frame);
2496 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002497
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002498 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002499}
2500
Lloyd Pique347200f2017-12-14 17:00:15 -08002501void SurfaceFlinger::processDisplayChangesLocked() {
2502 // here we take advantage of Vector's copy-on-write semantics to
2503 // improve performance by skipping the transaction entirely when
2504 // know that the lists are identical
2505 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2506 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2507 if (!curr.isIdenticalTo(draw)) {
2508 mVisibleRegionsDirty = true;
2509 const size_t cc = curr.size();
2510 size_t dc = draw.size();
2511
2512 // find the displays that were removed
2513 // (ie: in drawing state but not in current state)
2514 // also handle displays that changed
2515 // (ie: displays that are in both lists)
2516 for (size_t i = 0; i < dc;) {
2517 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2518 if (j < 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002519 // Save display IDs before disconnecting.
2520 const auto internalDisplayId = getInternalDisplayId();
2521 const auto externalDisplayId = getExternalDisplayId();
2522
Lloyd Pique347200f2017-12-14 17:00:15 -08002523 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002524 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2525 display->disconnect(getHwComposer());
2526 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002527 if (internalDisplayId && internalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002528 if (mUseScheduler) {
2529 mScheduler->hotplugReceived(mAppConnectionHandle,
2530 EventThread::DisplayType::Primary, false);
2531 } else {
2532 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2533 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002534 } else if (externalDisplayId && externalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002535 if (mUseScheduler) {
2536 mScheduler->hotplugReceived(mAppConnectionHandle,
2537 EventThread::DisplayType::External, false);
2538 } else {
2539 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2540 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002541 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002542 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002543 } else {
2544 // this display is in both lists. see if something changed.
2545 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002546 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002547 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2548 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2549 if (state_binder != draw_binder) {
2550 // changing the surface is like destroying and
2551 // recreating the DisplayDevice, so we just remove it
2552 // from the drawing state, so that it get re-added
2553 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002554 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2555 display->disconnect(getHwComposer());
2556 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002557 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002558 mDrawingState.displays.removeItemsAt(i);
2559 dc--;
2560 // at this point we must loop to the next item
2561 continue;
2562 }
2563
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002564 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002565 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002566 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002567 }
2568 if ((state.orientation != draw[i].orientation) ||
2569 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002570 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002571 }
2572 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002573 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002574 }
2575 }
2576 }
2577 ++i;
2578 }
2579
2580 // find displays that were added
2581 // (ie: in current state but not in drawing state)
2582 for (size_t i = 0; i < cc; i++) {
2583 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2584 const DisplayDeviceState& state(curr[i]);
2585
2586 sp<DisplaySurface> dispSurface;
2587 sp<IGraphicBufferProducer> producer;
2588 sp<IGraphicBufferProducer> bqProducer;
2589 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002590 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002591
Dominik Laskowski075d3172018-05-24 15:50:06 -07002592 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002593 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002594 // Virtual displays without a surface are dormant:
2595 // they have external state (layer stack, projection,
2596 // etc.) but no internal state (i.e. a DisplayDevice).
2597 if (state.surface != nullptr) {
2598 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002599 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002600 int width = 0;
2601 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2602 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2603 int height = 0;
2604 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2605 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2606 int intFormat = 0;
2607 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2608 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002609 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002610
Dominik Laskowski075d3172018-05-24 15:50:06 -07002611 displayId =
2612 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002613 }
2614
2615 // TODO: Plumb requested format back up to consumer
2616
2617 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002618 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002619 bqProducer, bqConsumer,
2620 state.displayName);
2621
2622 dispSurface = vds;
2623 producer = vds;
2624 }
2625 } else {
2626 ALOGE_IF(state.surface != nullptr,
2627 "adding a supported display, but rendering "
2628 "surface is provided (%p), ignoring it",
2629 state.surface.get());
2630
Dominik Laskowski075d3172018-05-24 15:50:06 -07002631 displayId = state.displayId;
2632 LOG_ALWAYS_FATAL_IF(!displayId);
2633 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002634 producer = bqProducer;
2635 }
2636
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002637 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002638 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002639 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002640 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002641 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002642 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002643 LOG_ALWAYS_FATAL_IF(!displayId);
2644
2645 if (displayId == getInternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002646 if (mUseScheduler) {
2647 mScheduler->hotplugReceived(mAppConnectionHandle,
2648 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002649 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002650 } else {
2651 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2652 true);
2653 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002654 } else if (displayId == getExternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002655 if (mUseScheduler) {
2656 mScheduler->hotplugReceived(mAppConnectionHandle,
2657 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002658 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002659 } else {
2660 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2661 true);
2662 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002663 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002664 }
2665 }
2666 }
2667 }
2668 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002669
2670 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002671}
2672
Mathias Agopian87baae12012-07-31 12:38:26 -07002673void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002674{
Dan Stoza7dde5992015-05-22 09:51:44 -07002675 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002676 mCurrentState.traverseInZOrder([](Layer* layer) {
2677 layer->notifyAvailableFrames();
2678 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002679
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002680 /*
2681 * Traversal of the children
2682 * (perform the transaction for each of them if needed)
2683 */
2684
Robert Carr720e5062018-07-30 17:45:14 -07002685 bool inputChanged = false;
Mathias Agopian3559b072012-08-15 13:46:03 -07002686 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002687 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002688 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002689 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002690
2691 const uint32_t flags = layer->doTransaction(0);
2692 if (flags & Layer::eVisibleRegion)
2693 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002694
2695 if (flags & Layer::eInputInfoChanged) {
2696 inputChanged = true;
2697 }
Robert Carr2047fae2016-11-28 14:09:09 -08002698 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002699 }
2700
2701 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002702 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002703 */
2704
Mathias Agopiane57f2922012-08-09 16:29:12 -07002705 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002706 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002707 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002708 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002709
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002710 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002711 // The transform hint might have changed for some layers
2712 // (either because a display has changed, or because a layer
2713 // as changed).
2714 //
2715 // Walk through all the layers in currentLayers,
2716 // and update their transform hint.
2717 //
2718 // If a layer is visible only on a single display, then that
2719 // display is used to calculate the hint, otherwise we use the
2720 // default display.
2721 //
2722 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2723 // the hint is set before we acquire a buffer from the surface texture.
2724 //
2725 // NOTE: layer transactions have taken place already, so we use their
2726 // drawing state. However, SurfaceFlinger's own transaction has not
2727 // happened yet, so we must use the current state layer list
2728 // (soon to become the drawing state list).
2729 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002730 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002731 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002732 bool first = true;
2733 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002734 // NOTE: we rely on the fact that layers are sorted by
2735 // layerStack first (so we don't have to traverse the list
2736 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002737 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002738 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002739 currentlayerStack = layerStack;
2740 // figure out if this layerstack is mirrored
2741 // (more than one display) if so, pick the default display,
2742 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002743 hintDisplay = nullptr;
2744 for (const auto& [token, display] : mDisplays) {
2745 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2746 if (hintDisplay) {
2747 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002748 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002749 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002750 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002751 }
2752 }
2753 }
2754 }
Chet Haase91d25932013-04-11 15:24:55 -07002755
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002756 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002757 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2758 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002759
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002760 // could be null when this layer is using a layerStack
2761 // that is not visible on any display. Also can occur at
2762 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002763 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002764 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002765
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002766 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002767 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002768 if (hintDisplay) {
2769 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002770 }
Robert Carr2047fae2016-11-28 14:09:09 -08002771
2772 first = false;
2773 });
Mathias Agopian84300952012-11-21 16:02:13 -08002774 }
2775
2776
Mathias Agopian3559b072012-08-15 13:46:03 -07002777 /*
2778 * Perform our own transaction if needed
2779 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002780
2781 if (mLayersAdded) {
2782 mLayersAdded = false;
2783 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002784 mVisibleRegionsDirty = true;
2785 }
2786
2787 // some layers might have been removed, so
2788 // we need to update the regions they're exposing.
2789 if (mLayersRemoved) {
2790 mLayersRemoved = false;
2791 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002792 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002793 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002794 // this layer is not visible anymore
2795 // TODO: we could traverse the tree from front to back and
2796 // compute the actual visible region
2797 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002798 Region visibleReg;
2799 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002800 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002801 }
Robert Carr2047fae2016-11-28 14:09:09 -08002802 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002803 }
2804
2805 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002806
Vishnu Nairde19f852018-12-18 16:11:53 -08002807 if (inputChanged || mVisibleRegionsDirty) {
Robert Carr720e5062018-07-30 17:45:14 -07002808 updateInputWindows();
2809 }
chaviwfbe5d9c2018-12-26 12:23:37 -08002810 executeInputWindowCommands();
Robert Carr720e5062018-07-30 17:45:14 -07002811
Riley Andrews03414a12014-07-01 14:22:59 -07002812 updateCursorAsync();
2813}
2814
Robert Carr720e5062018-07-30 17:45:14 -07002815void SurfaceFlinger::updateInputWindows() {
2816 ATRACE_CALL();
2817
Vishnu Nairde19f852018-12-18 16:11:53 -08002818 if (mInputFlinger == nullptr) {
2819 return;
2820 }
2821
Robert Carr720e5062018-07-30 17:45:14 -07002822 Vector<InputWindowInfo> inputHandles;
2823
2824 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2825 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002826 // When calculating the screen bounds we ignore the transparent region since it may
2827 // result in an unwanted offset.
2828 inputHandles.add(layer->fillInputInfo(
2829 layer->computeScreenBounds(false /* reduceTransparentRegion */)));
Robert Carr720e5062018-07-30 17:45:14 -07002830 }
2831 });
2832 mInputFlinger->setInputWindows(inputHandles);
2833}
2834
chaviwfbe5d9c2018-12-26 12:23:37 -08002835void SurfaceFlinger::executeInputWindowCommands() {
2836 if (!mInputFlinger) {
2837 return;
2838 }
2839
2840 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
2841 if (transferTouchFocusCommand.fromToken != nullptr &&
2842 transferTouchFocusCommand.toToken != nullptr &&
2843 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
2844 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
2845 transferTouchFocusCommand.toToken);
2846 }
2847 }
2848
2849 mInputWindowCommands.clear();
2850}
2851
Riley Andrews03414a12014-07-01 14:22:59 -07002852void SurfaceFlinger::updateCursorAsync()
2853{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002854 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002855 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002856 continue;
2857 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002858
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002859 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2860 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002861 }
2862 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002863}
2864
chaviw61626f22018-11-15 16:26:27 -08002865void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
2866 if (layer->hasReadyFrame()) {
2867 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
2868 if (layer->shouldPresentNow(expectedPresentTime)) {
2869 bool ignored = false;
2870 layer->latchBuffer(ignored, systemTime(), Fence::NO_FENCE);
2871 }
2872 }
2873 layer->releasePendingBuffer(systemTime());
2874}
2875
Mathias Agopian4fec8732012-06-29 14:12:52 -07002876void SurfaceFlinger::commitTransaction()
2877{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002878 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002879 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002880 for (const auto& l : mLayersPendingRemoval) {
2881 recordBufferingStats(l->getName().string(),
2882 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07002883
2884 // We need to release the HWC layers when the Layer is removed
2885 // from the current state otherwise the HWC layer just continues
2886 // showing at its last configured state until we eventually
2887 // abandon the buffer queue.
2888 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08002889 l->destroyHwcLayersForAllDisplays();
2890 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07002891 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002892 }
2893 mLayersPendingRemoval.clear();
2894 }
2895
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002896 // If this transaction is part of a window animation then the next frame
2897 // we composite should be considered an animation as well.
2898 mAnimCompositionPending = mAnimTransactionPending;
2899
Mathias Agopian4fec8732012-06-29 14:12:52 -07002900 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002901 // clear the "changed" flags in current state
2902 mCurrentState.colorMatrixChanged = false;
2903
Robert Carr1f0a16a2016-10-24 16:27:39 -07002904 mDrawingState.traverseInZOrder([](Layer* layer) {
2905 layer->commitChildList();
2906 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002907 mTransactionPending = false;
2908 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002909 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002910}
2911
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002912void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2913 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002914 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002915 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002916
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002917 Region aboveOpaqueLayers;
2918 Region aboveCoveredLayers;
2919 Region dirty;
2920
Mathias Agopian87baae12012-07-31 12:38:26 -07002921 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002922
Robert Carr2047fae2016-11-28 14:09:09 -08002923 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002924 // start with the whole surface at its current location
2925 const Layer::State& s(layer->getDrawingState());
2926
Jesse Hall01e29052013-02-19 16:13:35 -08002927 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002928 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002929 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002930 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002931
Mathias Agopianab028732010-03-16 16:41:46 -07002932 /*
2933 * opaqueRegion: area of a surface that is fully opaque.
2934 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002935 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002936
2937 /*
2938 * visibleRegion: area of a surface that is visible on screen
2939 * and not fully transparent. This is essentially the layer's
2940 * footprint minus the opaque regions above it.
2941 * Areas covered by a translucent surface are considered visible.
2942 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002943 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002944
2945 /*
2946 * coveredRegion: area of a surface that is covered by all
2947 * visible regions above it (which includes the translucent areas).
2948 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002949 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002950
Jesse Halla8026d22012-09-25 13:25:04 -07002951 /*
2952 * transparentRegion: area of a surface that is hinted to be completely
2953 * transparent. This is only used to tell when the layer has no visible
2954 * non-transparent regions and can be removed from the layer list. It
2955 * does not affect the visibleRegion of this layer or any layers
2956 * beneath it. The hint may not be correct if apps don't respect the
2957 * SurfaceView restrictions (which, sadly, some don't).
2958 */
2959 Region transparentRegion;
2960
Mathias Agopianab028732010-03-16 16:41:46 -07002961
2962 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002963 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002964 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002965 Rect bounds(layer->computeScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07002966
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002967 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002968 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002969 if (!visibleRegion.isEmpty()) {
2970 // Remove the transparent area from the visible region
2971 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002972 if (tr.preserveRects()) {
2973 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002974 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002975 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002976 // transformation too complex, can't do the
2977 // transparent region optimization.
2978 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002979 }
Mathias Agopianab028732010-03-16 16:41:46 -07002980 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002981
Mathias Agopianab028732010-03-16 16:41:46 -07002982 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002983 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002984 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002985 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002986 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002987 // the opaque region is the layer's footprint
2988 opaqueRegion = visibleRegion;
2989 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002990 }
2991 }
2992
Robert Carre5f4f692018-01-12 13:12:28 -08002993 if (visibleRegion.isEmpty()) {
2994 layer->clearVisibilityRegions();
2995 return;
2996 }
2997
Mathias Agopianab028732010-03-16 16:41:46 -07002998 // Clip the covered region to the visible region
2999 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
3000
3001 // Update aboveCoveredLayers for next (lower) layer
3002 aboveCoveredLayers.orSelf(visibleRegion);
3003
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003004 // subtract the opaque region covered by the layers above us
3005 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003006
3007 // compute this layer's dirty region
3008 if (layer->contentDirty) {
3009 // we need to invalidate the whole region
3010 dirty = visibleRegion;
3011 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07003012 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003013 layer->contentDirty = false;
3014 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003015 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07003016 * the exposed region consists of two components:
3017 * 1) what's VISIBLE now and was COVERED before
3018 * 2) what's EXPOSED now less what was EXPOSED before
3019 *
3020 * note that (1) is conservative, we start with the whole
3021 * visible region but only keep what used to be covered by
3022 * something -- which mean it may have been exposed.
3023 *
3024 * (2) handles areas that were not covered by anything but got
3025 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07003026 */
Mathias Agopianab028732010-03-16 16:41:46 -07003027 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07003028 const Region oldVisibleRegion = layer->visibleRegion;
3029 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07003030 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
3031 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003032 }
3033 dirty.subtractSelf(aboveOpaqueLayers);
3034
3035 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07003036 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003037
Mathias Agopianab028732010-03-16 16:41:46 -07003038 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003039 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003040
Jesse Halla8026d22012-09-25 13:25:04 -07003041 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003042 layer->setVisibleRegion(visibleRegion);
3043 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07003044 layer->setVisibleNonTransparentRegion(
3045 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08003046 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003047
Mathias Agopian87baae12012-07-31 12:38:26 -07003048 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003049}
3050
Chia-I Wuab0c3192017-08-01 11:29:00 -07003051void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07003052 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003053 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
3054 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003055 }
3056 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003057}
3058
Dan Stoza6b9454d2014-11-07 16:00:59 -08003059bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003060{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003061 ALOGV("handlePageFlip");
3062
Brian Andersond6927fb2016-07-23 23:37:30 -07003063 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003064
Mathias Agopian4fec8732012-06-29 14:12:52 -07003065 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003066 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003067 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003068
3069 // Store the set of layers that need updates. This set must not change as
3070 // buffers are being latched, as this could result in a deadlock.
3071 // Example: Two producers share the same command stream and:
3072 // 1.) Layer 0 is latched
3073 // 2.) Layer 0 gets a new frame
3074 // 2.) Layer 1 gets a new frame
3075 // 3.) Layer 1 is latched.
3076 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3077 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003078 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003079 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003080 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003081 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3082 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003083 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003084 } else {
3085 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003086 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003087 } else {
3088 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003089 }
Robert Carr2047fae2016-11-28 14:09:09 -08003090 });
3091
Lloyd Piquef2c79392018-12-20 16:23:33 -08003092 if (!mLayersWithQueuedFrames.empty()) {
3093 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3094 // writes to Layer current state. See also b/119481871
3095 Mutex::Autolock lock(mStateLock);
3096
3097 for (auto& layer : mLayersWithQueuedFrames) {
3098 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
3099 layer->useSurfaceDamage();
3100 invalidateLayerStack(layer, dirty);
3101 if (layer->isBufferLatched()) {
3102 newDataLatched = true;
3103 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003104 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003105 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003106
Alec Mouri86770e52018-09-24 22:40:58 +00003107 // Clear the renderengine fence here...
3108 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3109 // clear instead of sp::clear.
3110 getBE().flushFence = Fence::NO_FENCE;
3111
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003112 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003113
Vishnu Nairde19f852018-12-18 16:11:53 -08003114 if (visibleRegions) {
3115 // Update input window info if the layer receives its first buffer.
3116 updateInputWindows();
3117 }
3118
Dan Stoza6b9454d2014-11-07 16:00:59 -08003119 // If we will need to wake up at some time in the future to deal with a
3120 // queued frame that shouldn't be displayed during this vsync period, wake
3121 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003122 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003123 signalLayerUpdate();
3124 }
3125
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003126 // enter boot animation on first buffer latch
3127 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3128 ALOGI("Enter boot animation");
3129 mBootStage = BootStage::BOOTANIMATION;
3130 }
3131
Dan Stoza6b9454d2014-11-07 16:00:59 -08003132 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003133 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003134}
3135
Mathias Agopianad456f92011-01-13 17:53:01 -08003136void SurfaceFlinger::invalidateHwcGeometry()
3137{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003138 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003139}
3140
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003141void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& display,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003142 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08003143 // We only need to actually compose the display if:
3144 // 1) It is being handled by hardware composer, which may need this to
3145 // keep its virtual display state machine in sync, or
3146 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski34157762018-10-31 13:07:19 -07003147 if (!display->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003148 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003149 return;
3150 }
3151
Dan Stoza9e56aa02015-11-02 13:00:03 -08003152 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003153 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003154
3155 // swap buffers (presentation)
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003156 display->queueBuffer(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003157}
3158
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003159bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003160 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003161
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003162 const Region bounds(display->bounds());
3163 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07003164 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07003165 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003166 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003167
Peiyong Lind3788632018-09-18 16:01:31 -07003168 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003169 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003170
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003171 // Framebuffer will live in this scope for GPU composition.
3172 std::unique_ptr<renderengine::BindNativeBufferAsFramebuffer> fbo;
3173
Dan Stoza9e56aa02015-11-02 13:00:03 -08003174 if (hasClientComposition) {
3175 ALOGV("hasClientComposition");
3176
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003177 sp<GraphicBuffer> buf = display->dequeueBuffer();
3178
3179 if (buf == nullptr) {
3180 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3181 "client composition for this frame",
3182 display->getDisplayName().c_str());
3183 return false;
3184 }
3185
3186 // Bind the framebuffer in this scope.
3187 fbo = std::make_unique<renderengine::BindNativeBufferAsFramebuffer>(getRenderEngine(),
3188 buf->getNativeBuffer());
3189
3190 if (fbo->getStatus() != NO_ERROR) {
3191 ALOGW("Binding buffer for display [%s] failed with status: %d",
3192 display->getDisplayName().c_str(), fbo->getStatus());
3193 return false;
3194 }
3195
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003196 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003197 if (display->hasWideColorGamut()) {
3198 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003199 }
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003200 getRenderEngine().setOutputDataSpace(outputDataspace);
3201 getRenderEngine().setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003202 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003203
Lloyd Pique441d5042018-10-18 16:49:51 -07003204 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003205 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003206 getHwComposer()
3207 .hasDisplayCapability(displayId,
3208 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003209
Peiyong Lind3788632018-09-18 16:01:31 -07003210 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003211 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3212 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003213 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003214 }
3215
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003216 display->setViewportAndProjection();
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003217
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003218 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003219 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003220 // when using overlays, we assume a fully transparent framebuffer
3221 // NOTE: we could reduce how much we need to clear, for instance
3222 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003223 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003224 // We'll revisit later if needed.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003225 getRenderEngine().clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003226 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003227 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003228 // we're left with the letterbox region
3229 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003230 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003231
3232 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003233 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003234
Mathias Agopianb9494d52012-04-18 02:28:45 -07003235 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003236 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003237 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003238 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003239 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003240 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003241
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003242 const Rect& bounds = display->getBounds();
3243 const Rect& scissor = display->getScissor();
3244 if (scissor != bounds) {
3245 // scissor doesn't match the screen's dimensions, so we
3246 // need to clear everything outside of it and enable
3247 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003248
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003249 // enable scissor for this frame
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003250 getRenderEngine().setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003251 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003252 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003253
Mathias Agopian85d751c2012-08-29 16:59:24 -07003254 /*
3255 * and then, render the layers targeted at the framebuffer
3256 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003257
Dan Stoza9e56aa02015-11-02 13:00:03 -08003258 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07003259 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003260 bool firstLayer = true;
David Sodmanc1498e62018-09-12 14:36:26 -07003261 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003262 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003263 displayTransform.transform(layer->visibleRegion)));
3264 ALOGV("Layer: %s", layer->getName().string());
3265 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003266 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003267 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003268 case HWC2::Composition::Cursor:
3269 case HWC2::Composition::Device:
3270 case HWC2::Composition::Sideband:
3271 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003272 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003273 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003274 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003275 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003276 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003277 // never clear the very first layer since we're
3278 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003279 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003280 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003281 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003282 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003283 case HWC2::Composition::Client: {
Peiyong Lind3788632018-09-18 16:01:31 -07003284 if (layer->hasColorTransform()) {
3285 mat4 tmpMatrix;
3286 if (applyColorMatrix) {
3287 tmpMatrix = mDrawingState.colorMatrix;
3288 }
3289 tmpMatrix *= layer->getColorTransform();
Peiyong Lind3788632018-09-18 16:01:31 -07003290 getRenderEngine().setColorTransform(tmpMatrix);
3291 } else {
3292 getRenderEngine().setColorTransform(colorMatrix);
3293 }
David Sodmanc1498e62018-09-12 14:36:26 -07003294 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003295 break;
3296 }
3297 default:
3298 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003299 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003300 } else {
3301 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003302 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003303 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003304 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003305
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003306 // Perform some cleanup steps if we used client composition.
3307 if (hasClientComposition) {
3308 getRenderEngine().setColorTransform(mat4());
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003309 getRenderEngine().disableScissor();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003310 display->finishBuffer();
3311 // Clear out error flags here so that we don't wait until next
3312 // composition to log.
3313 getRenderEngine().checkErrors();
3314 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003315 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003316}
3317
Chia-I Wu28e3a252018-09-07 12:05:02 -07003318void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003319 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003320 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003321}
3322
Dan Stoza7d89d062015-04-30 13:29:25 -07003323status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003324 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003325 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003326 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003327 const sp<Layer>& parent,
3328 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003329{
Dan Stoza7d89d062015-04-30 13:29:25 -07003330 // add this layer to the current state list
3331 {
3332 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003333 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003334 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3335 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003336 return NO_MEMORY;
3337 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003338 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003339 mCurrentState.layersSortedByZ.add(lbc);
Robert Carrb89ea9d2018-12-10 13:01:14 -08003340 } else if (parent == nullptr || parent->isRemovedFromCurrentState()) {
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003341 ALOGE("addClientLayer called with a removed parent");
chaviw61626f22018-11-15 16:26:27 -08003342 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003343 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003344 parent->addChild(lbc);
3345 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003346
Yiwei Zhang243b3782018-05-15 17:40:04 -07003347 if (gbc != nullptr) {
3348 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3349 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3350 mMaxGraphicBufferProducerListSize,
3351 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3352 mGraphicBufferProducerList.size(),
3353 mMaxGraphicBufferProducerListSize, mNumLayers);
3354 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003355 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003356 }
3357
Mathias Agopian96f08192010-06-02 23:28:45 -07003358 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003359 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003360
Dan Stoza7d89d062015-04-30 13:29:25 -07003361 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003362}
3363
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003364uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003365 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003366}
3367
Mathias Agopian3f844832013-08-07 21:24:32 -07003368uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003369 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003370}
3371
Mathias Agopian3f844832013-08-07 21:24:32 -07003372uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003373 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003374}
3375
3376uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003377 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003378 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003379 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003380 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003381 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003382 }
3383 return old;
3384}
3385
Marissa Wall713b63f2018-10-17 15:42:43 -07003386bool SurfaceFlinger::flushTransactionQueues() {
3387 Mutex::Autolock _l(mStateLock);
3388 auto it = mTransactionQueues.begin();
3389 while (it != mTransactionQueues.end()) {
3390 auto& [applyToken, transactionQueue] = *it;
3391
3392 while (!transactionQueue.empty()) {
3393 const auto& [states, displays, flags] = transactionQueue.front();
3394 if (composerStateContainsUnsignaledFences(states)) {
3395 break;
3396 }
chaviw273171b2018-12-26 11:46:30 -08003397 applyTransactionState(states, displays, flags, mInputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003398 transactionQueue.pop();
3399 }
3400
3401 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3402 }
3403 return mTransactionQueues.empty();
3404}
3405
chaviwca27f252018-02-06 16:46:39 -08003406bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3407 for (const ComposerState& state : states) {
3408 // Here we need to check that the interface we're given is indeed
3409 // one of our own. A malicious client could give us a nullptr
3410 // IInterface, or one of its own or even one of our own but a
3411 // different type. All these situations would cause us to crash.
3412 if (state.client == nullptr) {
3413 return true;
3414 }
3415
3416 sp<IBinder> binder = IInterface::asBinder(state.client);
3417 if (binder == nullptr) {
3418 return true;
3419 }
3420
3421 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3422 return true;
3423 }
3424 }
3425 return false;
3426}
3427
Marissa Wall713b63f2018-10-17 15:42:43 -07003428bool SurfaceFlinger::composerStateContainsUnsignaledFences(const Vector<ComposerState>& states) {
3429 for (const ComposerState& state : states) {
3430 const layer_state_t& s = state.state;
3431 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3432 continue;
3433 }
3434 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
3435 return true;
3436 }
3437 }
3438 return false;
3439}
3440
3441void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3442 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003443 const sp<IBinder>& applyToken,
3444 const InputWindowCommands& inputWindowCommands) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003445 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003446 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003447
chaviwca27f252018-02-06 16:46:39 -08003448 if (containsAnyInvalidClientState(states)) {
3449 return;
3450 }
3451
Marissa Wall713b63f2018-10-17 15:42:43 -07003452 // If its TransactionQueue already has a pending TransactionState or if it is pending
3453 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
3454 composerStateContainsUnsignaledFences(states)) {
3455 mTransactionQueues[applyToken].emplace(states, displays, flags);
3456 setTransactionFlags(eTransactionNeeded);
3457 return;
3458 }
3459
chaviw273171b2018-12-26 11:46:30 -08003460 applyTransactionState(states, displays, flags, inputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003461}
3462
3463void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003464 const Vector<DisplayState>& displays, uint32_t flags,
3465 const InputWindowCommands& inputWindowCommands) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003466 uint32_t transactionFlags = 0;
3467
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003468 if (flags & eAnimation) {
3469 // For window updates that are part of an animation we must wait for
3470 // previous animation "frames" to be handled.
3471 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003472 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003473 if (CC_UNLIKELY(err != NO_ERROR)) {
3474 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003475 // caller after a few seconds.
3476 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3477 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003478 mAnimTransactionPending = false;
3479 break;
3480 }
3481 }
3482 }
3483
chaviwca27f252018-02-06 16:46:39 -08003484 for (const DisplayState& display : displays) {
3485 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003486 }
3487
Marissa Walle2ffb422018-10-12 11:33:52 -07003488 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003489 for (const ComposerState& state : states) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003490 clientStateFlags |= setClientStateLocked(state);
chaviwca27f252018-02-06 16:46:39 -08003491 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003492 // If the state doesn't require a traversal and there are callbacks, send them now
3493 if (!(clientStateFlags & eTraversalNeeded)) {
3494 mTransactionCompletedThread.sendCallbacks();
3495 }
3496 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003497
chaviw273171b2018-12-26 11:46:30 -08003498 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3499
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003500 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3501 // anyway. This can be used as a flush mechanism for previous async transactions.
3502 // Empty animation transaction can be used to simulate back-pressure, so also force a
3503 // transaction for empty animation transactions.
3504 if (transactionFlags == 0 &&
3505 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003506 transactionFlags = eTransactionNeeded;
3507 }
3508
Mathias Agopian386aa982011-11-07 21:58:03 -08003509 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003510 if (mInterceptor->isEnabled()) {
3511 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003512 }
Irvel468051e2016-06-13 16:44:44 -07003513
Mathias Agopian386aa982011-11-07 21:58:03 -08003514 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003515 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3516 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003517 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003518
3519 // if this is a synchronous transaction, wait for it to take effect
3520 // before returning.
3521 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003522 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003523 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003524 if (flags & eAnimation) {
3525 mAnimTransactionPending = true;
3526 }
3527 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003528 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3529 if (CC_UNLIKELY(err != NO_ERROR)) {
3530 // just in case something goes wrong in SF, return to the
3531 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003532 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3533 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003534 break;
3535 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003536 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003537 }
3538}
3539
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003540uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3541 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3542 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003543
Mathias Agopiane57f2922012-08-09 16:29:12 -07003544 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003545 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3546
3547 const uint32_t what = s.what;
3548 if (what & DisplayState::eSurfaceChanged) {
3549 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3550 state.surface = s.surface;
3551 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003552 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003553 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003554 if (what & DisplayState::eLayerStackChanged) {
3555 if (state.layerStack != s.layerStack) {
3556 state.layerStack = s.layerStack;
3557 flags |= eDisplayTransactionNeeded;
3558 }
3559 }
3560 if (what & DisplayState::eDisplayProjectionChanged) {
3561 if (state.orientation != s.orientation) {
3562 state.orientation = s.orientation;
3563 flags |= eDisplayTransactionNeeded;
3564 }
3565 if (state.frame != s.frame) {
3566 state.frame = s.frame;
3567 flags |= eDisplayTransactionNeeded;
3568 }
3569 if (state.viewport != s.viewport) {
3570 state.viewport = s.viewport;
3571 flags |= eDisplayTransactionNeeded;
3572 }
3573 }
3574 if (what & DisplayState::eDisplaySizeChanged) {
3575 if (state.width != s.width) {
3576 state.width = s.width;
3577 flags |= eDisplayTransactionNeeded;
3578 }
3579 if (state.height != s.height) {
3580 state.height = s.height;
3581 flags |= eDisplayTransactionNeeded;
3582 }
3583 }
3584
Mathias Agopiane57f2922012-08-09 16:29:12 -07003585 return flags;
3586}
3587
Robert Carrd4ae7f32018-06-07 16:10:57 -07003588bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3589 IPCThreadState* ipc = IPCThreadState::self();
3590 const int pid = ipc->getCallingPid();
3591 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003592 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003593 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003594 return false;
3595 }
3596 return true;
3597}
3598
chaviwca27f252018-02-06 16:46:39 -08003599uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3600 const layer_state_t& s = composerState.state;
3601 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3602
Mathias Agopian13127d82013-03-05 17:47:11 -08003603 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003604 if (layer == nullptr) {
3605 return 0;
3606 }
3607
chaviw8b3871a2017-11-01 17:41:01 -07003608 uint32_t flags = 0;
3609
Garfield Tan8a3083e2018-12-03 13:21:07 -08003610 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003611 bool geometryAppliesWithResize =
3612 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003613
3614 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3615 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003616 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003617 layer->pushPendingState();
3618 }
3619
chaviw8b3871a2017-11-01 17:41:01 -07003620 if (what & layer_state_t::ePositionChanged) {
3621 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3622 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003623 }
chaviw8b3871a2017-11-01 17:41:01 -07003624 }
3625 if (what & layer_state_t::eLayerChanged) {
3626 // NOTE: index needs to be calculated before we update the state
3627 const auto& p = layer->getParent();
3628 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003629 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003630 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003631 mCurrentState.layersSortedByZ.removeAt(idx);
3632 mCurrentState.layersSortedByZ.add(layer);
3633 // we need traversal (state changed)
3634 // AND transaction (list changed)
3635 flags |= eTransactionNeeded|eTraversalNeeded;
3636 }
chaviw8b3871a2017-11-01 17:41:01 -07003637 } else {
3638 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003639 flags |= eTransactionNeeded|eTraversalNeeded;
3640 }
3641 }
chaviw8b3871a2017-11-01 17:41:01 -07003642 }
3643 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003644 // NOTE: index needs to be calculated before we update the state
3645 const auto& p = layer->getParent();
3646 if (p == nullptr) {
3647 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3648 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3649 mCurrentState.layersSortedByZ.removeAt(idx);
3650 mCurrentState.layersSortedByZ.add(layer);
3651 // we need traversal (state changed)
3652 // AND transaction (list changed)
3653 flags |= eTransactionNeeded|eTraversalNeeded;
3654 }
3655 } else {
3656 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3657 flags |= eTransactionNeeded|eTraversalNeeded;
3658 }
chaviw8b3871a2017-11-01 17:41:01 -07003659 }
3660 }
3661 if (what & layer_state_t::eSizeChanged) {
3662 if (layer->setSize(s.w, s.h)) {
3663 flags |= eTraversalNeeded;
3664 }
3665 }
3666 if (what & layer_state_t::eAlphaChanged) {
3667 if (layer->setAlpha(s.alpha))
3668 flags |= eTraversalNeeded;
3669 }
3670 if (what & layer_state_t::eColorChanged) {
3671 if (layer->setColor(s.color))
3672 flags |= eTraversalNeeded;
3673 }
Peiyong Lind3788632018-09-18 16:01:31 -07003674 if (what & layer_state_t::eColorTransformChanged) {
3675 if (layer->setColorTransform(s.colorTransform)) {
3676 flags |= eTraversalNeeded;
3677 }
3678 }
chaviw8b3871a2017-11-01 17:41:01 -07003679 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003680 // TODO: b/109894387
3681 //
3682 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3683 // rotation. To see the problem observe that if we have a square parent, and a child
3684 // of the same size, then we rotate the child 45 degrees around it's center, the child
3685 // must now be cropped to a non rectangular 8 sided region.
3686 //
3687 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3688 // private API, and the WindowManager only uses rotation in one case, which is on a top
3689 // level layer in which cropping is not an issue.
3690 //
3691 // However given that abuse of rotation matrices could lead to surfaces extending outside
3692 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3693 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3694 // transformations.
3695 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003696 flags |= eTraversalNeeded;
3697 }
3698 if (what & layer_state_t::eTransparentRegionChanged) {
3699 if (layer->setTransparentRegionHint(s.transparentRegion))
3700 flags |= eTraversalNeeded;
3701 }
3702 if (what & layer_state_t::eFlagsChanged) {
3703 if (layer->setFlags(s.flags, s.mask))
3704 flags |= eTraversalNeeded;
3705 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003706 if (what & layer_state_t::eCropChanged_legacy) {
3707 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003708 flags |= eTraversalNeeded;
3709 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003710 if (what & layer_state_t::eCornerRadiusChanged) {
3711 if (layer->setCornerRadius(s.cornerRadius))
3712 flags |= eTraversalNeeded;
3713 }
chaviw8b3871a2017-11-01 17:41:01 -07003714 if (what & layer_state_t::eLayerStackChanged) {
3715 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3716 // We only allow setting layer stacks for top level layers,
3717 // everything else inherits layer stack from its parent.
3718 if (layer->hasParent()) {
3719 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3720 layer->getName().string());
3721 } else if (idx < 0) {
3722 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3723 "that also does not appear in the top level layer list. Something"
3724 " has gone wrong.", layer->getName().string());
3725 } else if (layer->setLayerStack(s.layerStack)) {
3726 mCurrentState.layersSortedByZ.removeAt(idx);
3727 mCurrentState.layersSortedByZ.add(layer);
3728 // we need traversal (state changed)
3729 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003730 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003731 }
3732 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003733 if (what & layer_state_t::eDeferTransaction_legacy) {
3734 if (s.barrierHandle_legacy != nullptr) {
3735 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3736 } else if (s.barrierGbp_legacy != nullptr) {
3737 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003738 if (authenticateSurfaceTextureLocked(gbp)) {
3739 const auto& otherLayer =
3740 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003741 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003742 } else {
3743 ALOGE("Attempt to defer transaction to to an"
3744 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003745 }
3746 }
chaviw8b3871a2017-11-01 17:41:01 -07003747 // We don't trigger a traversal here because if no other state is
3748 // changed, we don't want this to cause any more work
3749 }
3750 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003751 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003752 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003753 if (!hadParent) {
3754 mCurrentState.layersSortedByZ.remove(layer);
3755 }
chaviw8b3871a2017-11-01 17:41:01 -07003756 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003757 }
chaviw8b3871a2017-11-01 17:41:01 -07003758 }
3759 if (what & layer_state_t::eReparentChildren) {
3760 if (layer->reparentChildren(s.reparentHandle)) {
3761 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003762 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003763 }
chaviw8b3871a2017-11-01 17:41:01 -07003764 if (what & layer_state_t::eDetachChildren) {
3765 layer->detachChildren();
3766 }
3767 if (what & layer_state_t::eOverrideScalingModeChanged) {
3768 layer->setOverrideScalingMode(s.overrideScalingMode);
3769 // We don't trigger a traversal here because if no other state is
3770 // changed, we don't want this to cause any more work
3771 }
Marissa Wall61c58622018-07-18 10:12:20 -07003772 if (what & layer_state_t::eTransformChanged) {
3773 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3774 }
3775 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3776 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3777 flags |= eTraversalNeeded;
3778 }
3779 if (what & layer_state_t::eCropChanged) {
3780 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3781 }
Marissa Wall861616d2018-10-22 12:52:23 -07003782 if (what & layer_state_t::eFrameChanged) {
3783 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3784 }
Marissa Wall61c58622018-07-18 10:12:20 -07003785 if (what & layer_state_t::eBufferChanged) {
3786 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3787 }
3788 if (what & layer_state_t::eAcquireFenceChanged) {
3789 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3790 }
3791 if (what & layer_state_t::eDataspaceChanged) {
3792 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3793 }
3794 if (what & layer_state_t::eHdrMetadataChanged) {
3795 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3796 }
3797 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3798 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3799 }
3800 if (what & layer_state_t::eApiChanged) {
3801 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3802 }
3803 if (what & layer_state_t::eSidebandStreamChanged) {
3804 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3805 }
Robert Carr720e5062018-07-30 17:45:14 -07003806 if (what & layer_state_t::eInputInfoChanged) {
3807 layer->setInputInfo(s.inputInfo);
3808 flags |= eTraversalNeeded;
3809 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003810 std::vector<sp<CallbackHandle>> callbackHandles;
3811 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
3812 mTransactionCompletedThread.run();
3813 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
3814 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3815 }
3816 }
3817 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3818 // Do not put anything that updates layer state or modifies flags after
3819 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003820 return flags;
3821}
3822
chaviw273171b2018-12-26 11:46:30 -08003823uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3824 uint32_t flags = 0;
3825 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3826 flags |= eTraversalNeeded;
3827 }
3828
3829 mInputWindowCommands.merge(inputWindowCommands);
3830 return flags;
3831}
3832
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003833status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003834 const String8& name,
3835 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003836 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003837 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003838 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003839{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003840 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003841 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003842 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003843 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003844 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003845
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003846 status_t result = NO_ERROR;
3847
3848 sp<Layer> layer;
3849
Cody Northropbc755282017-03-31 12:00:08 -06003850 String8 uniqueName = getUniqueLayerName(name);
3851
Mathias Agopian3165cc22012-08-08 19:42:09 -07003852 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003853 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003854 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3855 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003856
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003857 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003858 case ISurfaceComposerClient::eFXSurfaceBufferState:
3859 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3860 break;
chaviw13fdc492017-06-27 12:40:18 -07003861 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003862 // check if buffer size is set for color layer.
3863 if (w > 0 || h > 0) {
3864 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3865 int(w), int(h));
3866 return BAD_VALUE;
3867 }
3868
chaviw13fdc492017-06-27 12:40:18 -07003869 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003870 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003871 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003872 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003873 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003874 // check if buffer size is set for container layer.
3875 if (w > 0 || h > 0) {
3876 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3877 int(w), int(h));
3878 return BAD_VALUE;
3879 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07003880 result = createContainerLayer(client,
3881 uniqueName, w, h, flags,
3882 handle, &layer);
3883 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003884 default:
3885 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003886 break;
3887 }
3888
Dan Stoza7d89d062015-04-30 13:29:25 -07003889 if (result != NO_ERROR) {
3890 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003891 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003892
Chia-I Wuab0c3192017-08-01 11:29:00 -07003893 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3894 // TODO b/64227542
3895 if (windowType == 441731) {
3896 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3897 layer->setPrimaryDisplayOnly();
3898 }
3899
Albert Chaulk479c60c2017-01-27 14:21:34 -05003900 layer->setInfo(windowType, ownerUid);
3901
Robert Carrb89ea9d2018-12-10 13:01:14 -08003902 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
3903 result = addClientLayer(client, *handle, *gbp, layer, *parent,
3904 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003905 if (result != NO_ERROR) {
3906 return result;
3907 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003908 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003909
3910 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003911 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003912}
3913
Cody Northropbc755282017-03-31 12:00:08 -06003914String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3915{
3916 bool matchFound = true;
3917 uint32_t dupeCounter = 0;
3918
3919 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3920 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3921
Dan Stoza436ccf32018-06-21 12:10:12 -07003922 // Grab the state lock since we're accessing mCurrentState
3923 Mutex::Autolock lock(mStateLock);
3924
Cody Northropbc755282017-03-31 12:00:08 -06003925 // Loop over layers until we're sure there is no matching name
3926 while (matchFound) {
3927 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003928 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003929 if (layer->getName() == uniqueName) {
3930 matchFound = true;
3931 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3932 }
3933 });
3934 }
3935
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003936 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3937 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003938
3939 return uniqueName;
3940}
3941
Marissa Wallfd668622018-05-10 10:21:13 -07003942status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3943 uint32_t w, uint32_t h, uint32_t flags,
3944 PixelFormat& format, sp<IBinder>* handle,
3945 sp<IGraphicBufferProducer>* gbp,
3946 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003947 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003948 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003949 case PIXEL_FORMAT_TRANSPARENT:
3950 case PIXEL_FORMAT_TRANSLUCENT:
3951 format = PIXEL_FORMAT_RGBA_8888;
3952 break;
3953 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003954 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003955 break;
3956 }
3957
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003958 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07003959 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07003960 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003961 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003962 *handle = layer->getHandle();
3963 *gbp = layer->getProducer();
3964 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003965 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003966
Marissa Wallfd668622018-05-10 10:21:13 -07003967 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003968 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003969}
3970
Marissa Wall61c58622018-07-18 10:12:20 -07003971status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3972 uint32_t w, uint32_t h, uint32_t flags,
3973 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003974 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07003975 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07003976 *handle = layer->getHandle();
3977 *outLayer = layer;
3978
3979 return NO_ERROR;
3980}
3981
chaviw13fdc492017-06-27 12:40:18 -07003982status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003983 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003984 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003985{
Lloyd Pique90c115d2018-09-18 21:39:42 -07003986 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003987 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003988 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003989}
3990
Robert Carr6b3f6c52018-08-13 13:05:17 -07003991status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
3992 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3993 sp<IBinder>* handle, sp<Layer>* outLayer)
3994{
Lloyd Pique90c115d2018-09-18 21:39:42 -07003995 *outLayer =
3996 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07003997 *handle = (*outLayer)->getHandle();
3998 return NO_ERROR;
3999}
4000
4001
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004002void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004003 mLayersPendingRemoval.add(layer);
4004 mLayersRemoved = true;
4005 setTransactionFlags(eTransactionNeeded);
4006}
4007
Robert Carr695d5282018-12-18 15:27:58 -08004008void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004009{
Robert Carr2e102c92018-10-23 12:11:15 -07004010 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004011 // If a layer has a parent, we allow it to out-live it's handle
4012 // with the idea that the parent holds a reference and will eventually
4013 // be cleaned up. However no one cleans up the top-level so we do so
4014 // here.
4015 if (layer->getParent() == nullptr) {
4016 mCurrentState.layersSortedByZ.remove(layer);
4017 }
4018 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08004019 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004020}
4021
Mathias Agopianb60314a2012-04-10 22:09:54 -07004022// ---------------------------------------------------------------------------
4023
Andy McFadden13a082e2012-08-24 10:16:42 -07004024void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004025 const auto displayToken = getInternalDisplayToken();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004026 if (!displayToken) return;
4027
Jesse Hall01e29052013-02-19 16:13:35 -08004028 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004029 Vector<ComposerState> state;
4030 Vector<DisplayState> displays;
4031 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004032 d.what = DisplayState::eDisplayProjectionChanged |
4033 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004034 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08004035 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004036 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004037 d.frame.makeInvalid();
4038 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004039 d.width = 0;
4040 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004041 displays.add(d);
chaviw273171b2018-12-26 11:46:30 -08004042 setTransactionState(state, displays, 0, nullptr, mInputWindowCommands);
Jamie Gennis6547ff42013-07-16 20:12:42 -07004043
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004044 const auto display = getDisplayDevice(displayToken);
4045 if (!display) return;
4046
Dominik Laskowskie9774092018-12-11 10:04:24 -08004047 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004048
Dominik Laskowski075d3172018-05-24 15:50:06 -07004049 const auto activeConfig = getHwComposer().getActiveConfig(*display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08004050 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07004051 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004052
Brian Andersond0010582017-03-07 13:20:31 -08004053 // Use phase of 0 since phase is not known.
4054 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07004055 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
4056 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004057}
4058
4059void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004060 // Async since we may be called from the main thread.
4061 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004062}
4063
Dominik Laskowskie9774092018-12-11 10:04:24 -08004064void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004065 if (display->isVirtual()) {
4066 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004067 return;
4068 }
4069
Dominik Laskowski075d3172018-05-24 15:50:06 -07004070 const auto displayId = display->getId();
4071 LOG_ALWAYS_FATAL_IF(!displayId);
4072
Dominik Laskowski34157762018-10-31 13:07:19 -07004073 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004074
4075 int currentMode = display->getPowerMode();
4076 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004077 return;
4078 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004079
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004080 display->setPowerMode(mode);
4081
Lloyd Pique4dccc412018-01-22 17:21:36 -08004082 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004083 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004084 }
4085
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004086 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004087 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004088 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004089 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004090 if (mUseScheduler) {
4091 mScheduler->onScreenAcquired(mAppConnectionHandle);
4092 } else {
4093 mEventThread->onScreenAcquired();
4094 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07004095 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004096 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004097
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004098 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004099 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004100 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004101
4102 struct sched_param param = {0};
4103 param.sched_priority = 1;
4104 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4105 ALOGW("Couldn't set SCHED_FIFO on display on");
4106 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004107 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004108 // Turn off the display
4109 struct sched_param param = {0};
4110 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4111 ALOGW("Couldn't set SCHED_OTHER on display off");
4112 }
4113
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004114 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07004115 if (mUseScheduler) {
4116 mScheduler->disableHardwareVsync(true);
4117 } else {
4118 disableHardwareVsync(true); // also cancels any in-progress resync
4119 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004120 if (mUseScheduler) {
4121 mScheduler->onScreenReleased(mAppConnectionHandle);
4122 } else {
4123 mEventThread->onScreenReleased();
4124 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004125 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004126
Dominik Laskowski075d3172018-05-24 15:50:06 -07004127 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004128 mVisibleRegionsDirty = true;
4129 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004130 } else if (mode == HWC_POWER_MODE_DOZE ||
4131 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004132 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004133 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004134 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004135 if (mUseScheduler) {
4136 mScheduler->onScreenAcquired(mAppConnectionHandle);
4137 } else {
4138 mEventThread->onScreenAcquired();
4139 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004140 resyncToHardwareVsync(true);
4141 }
4142 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4143 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004144 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07004145 if (mUseScheduler) {
4146 mScheduler->disableHardwareVsync(true);
4147 } else {
4148 disableHardwareVsync(true); // also cancels any in-progress resync
4149 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004150 if (mUseScheduler) {
4151 mScheduler->onScreenReleased(mAppConnectionHandle);
4152 } else {
4153 mEventThread->onScreenReleased();
4154 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004155 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004156 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004157 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004158 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004159 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004160 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004161
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004162 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004163 mTimeStats->setPowerMode(mode);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004164 }
4165
Dominik Laskowski34157762018-10-31 13:07:19 -07004166 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004167}
4168
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004169void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004170 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004171 const auto display = getDisplayDevice(displayToken);
4172 if (!display) {
4173 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4174 displayToken.get());
4175 } else if (display->isVirtual()) {
4176 ALOGW("Attempt to set power mode %d for virtual display", mode);
4177 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004178 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004179 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004180 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004181}
4182
4183// ---------------------------------------------------------------------------
4184
Lloyd Pique755e3192018-01-31 16:46:15 -08004185status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
4186 NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004187 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004188
Mathias Agopianbd115332013-04-18 16:41:04 -07004189 IPCThreadState* ipc = IPCThreadState::self();
4190 const int pid = ipc->getCallingPid();
4191 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004192
Mathias Agopianbd115332013-04-18 16:41:04 -07004193 if ((uid != AID_SHELL) &&
4194 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004195 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4196 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004197 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004198 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004199 // (this would indicate SF is stuck, but we want to be able to
4200 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004201 status_t err = mStateLock.timedLock(s2ns(1));
4202 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004203 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004204 StringAppendF(&result,
4205 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4206 "(no locks held)\n",
4207 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004208 }
4209
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004210 bool dumpAll = true;
4211 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004212 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004213
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004214 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004215 if ((index < numArgs) &&
4216 (args[index] == String16("--list"))) {
4217 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004218 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004219 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004220 }
4221
4222 if ((index < numArgs) &&
4223 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004224 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004225 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004226 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004227 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004228
4229 if ((index < numArgs) &&
4230 (args[index] == String16("--latency-clear"))) {
4231 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004232 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004233 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004234 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004235
4236 if ((index < numArgs) &&
4237 (args[index] == String16("--dispsync"))) {
4238 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004239 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004240 dumpAll = false;
4241 }
Dan Stozab90cf072015-03-05 11:05:59 -08004242
4243 if ((index < numArgs) &&
4244 (args[index] == String16("--static-screen"))) {
4245 index++;
4246 dumpStaticScreenStats(result);
4247 dumpAll = false;
4248 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004249
4250 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004251 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004252 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004253 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004254 dumpAll = false;
4255 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004256
4257 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4258 index++;
4259 dumpWideColorInfo(result);
4260 dumpAll = false;
4261 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004262
4263 if ((index < numArgs) &&
4264 (args[index] == String16("--enable-layer-stats"))) {
4265 index++;
4266 mLayerStats.enable();
4267 dumpAll = false;
4268 }
4269
4270 if ((index < numArgs) &&
4271 (args[index] == String16("--disable-layer-stats"))) {
4272 index++;
4273 mLayerStats.disable();
4274 dumpAll = false;
4275 }
4276
4277 if ((index < numArgs) &&
4278 (args[index] == String16("--clear-layer-stats"))) {
4279 index++;
4280 mLayerStats.clear();
4281 dumpAll = false;
4282 }
4283
4284 if ((index < numArgs) &&
4285 (args[index] == String16("--dump-layer-stats"))) {
4286 index++;
4287 mLayerStats.dump(result);
4288 dumpAll = false;
4289 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004290
4291 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004292 (args[index] == String16("--frame-composition"))) {
4293 index++;
4294 dumpFrameCompositionInfo(result);
4295 dumpAll = false;
4296 }
4297
4298 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004299 (args[index] == String16("--display-identification"))) {
4300 index++;
4301 dumpDisplayIdentificationData(result);
4302 dumpAll = false;
4303 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004304
4305 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4306 index++;
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004307 mTimeStats->parseArgs(asProto, args, index, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004308 dumpAll = false;
4309 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004310 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004311
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004312 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004313 if (asProto) {
4314 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4315 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4316 } else {
4317 dumpAllLocked(args, index, result);
4318 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004319 }
4320
Mathias Agopian9795c422009-08-26 16:36:26 -07004321 if (locked) {
4322 mStateLock.unlock();
4323 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004324 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004325 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004326 return NO_ERROR;
4327}
4328
Yiwei Zhang5434a782018-12-05 18:06:32 -08004329void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */, size_t& /* index */,
4330 std::string& result) const {
4331 mCurrentState.traverseInZOrder(
4332 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004333}
4334
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004335void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004336 std::string& result) const {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004337 String8 name;
4338 if (index < args.size()) {
4339 name = String8(args[index]);
4340 index++;
4341 }
4342
Dominik Laskowski075d3172018-05-24 15:50:06 -07004343 if (const auto displayId = getInternalDisplayId();
4344 displayId && getHwComposer().isConnected(*displayId)) {
4345 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004346 const nsecs_t period = activeConfig->getVsyncPeriod();
Yiwei Zhang5434a782018-12-05 18:06:32 -08004347 StringAppendF(&result, "%" PRId64 "\n", period);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004348 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004349
4350 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004351 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004352 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004353 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004354 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004355 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004356 }
Robert Carr2047fae2016-11-28 14:09:09 -08004357 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004358 }
4359}
4360
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004361void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004362 std::string& /* result */) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004363 String8 name;
4364 if (index < args.size()) {
4365 name = String8(args[index]);
4366 index++;
4367 }
4368
Robert Carr2047fae2016-11-28 14:09:09 -08004369 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004370 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004371 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004372 }
Robert Carr2047fae2016-11-28 14:09:09 -08004373 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004374
Svetoslavd85084b2014-03-20 10:28:31 -07004375 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004376}
4377
Jamie Gennis6547ff42013-07-16 20:12:42 -07004378// This should only be called from the main thread. Otherwise it would need
4379// the lock and should use mCurrentState rather than mDrawingState.
4380void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004381 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004382 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004383 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004384
4385 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4386}
4387
Yiwei Zhang5434a782018-12-05 18:06:32 -08004388void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004389 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004390
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004391 if (isLayerTripleBufferingDisabled())
4392 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004393
Yiwei Zhang5434a782018-12-05 18:06:32 -08004394 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4395 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4396 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4397 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4398 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4399 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004400 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004401}
4402
Yiwei Zhang5434a782018-12-05 18:06:32 -08004403void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4404 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004405 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4406 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004407 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004408 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004409 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004410 }
David Sodman4a36e932017-11-07 14:29:47 -08004411 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004412 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004413 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004414 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4415 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004416}
4417
Dan Stozae77c7662016-05-13 11:37:28 -07004418void SurfaceFlinger::recordBufferingStats(const char* layerName,
4419 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004420 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4421 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004422 for (const auto& segment : history) {
4423 if (!segment.usedThirdBuffer) {
4424 stats.twoBufferTime += segment.totalTime;
4425 }
4426 if (segment.occupancyAverage < 1.0f) {
4427 stats.doubleBufferedTime += segment.totalTime;
4428 } else if (segment.occupancyAverage < 2.0f) {
4429 stats.tripleBufferedTime += segment.totalTime;
4430 }
4431 ++stats.numSegments;
4432 stats.totalTime += segment.totalTime;
4433 }
4434}
4435
Yiwei Zhang5434a782018-12-05 18:06:32 -08004436void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4437 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004438
4439 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4440 const size_t count = currentLayers.size();
4441 for (size_t i=0 ; i<count ; i++) {
4442 currentLayers[i]->dumpFrameEvents(result);
4443 }
4444}
4445
Yiwei Zhang5434a782018-12-05 18:06:32 -08004446void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004447 result.append("Buffering stats:\n");
4448 result.append(" [Layer name] <Active time> <Two buffer> "
4449 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004450 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004451 typedef std::tuple<std::string, float, float, float> BufferTuple;
4452 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004453 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004454 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004455 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004456 if (stats.numSegments == 0) {
4457 continue;
4458 }
4459 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4460 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4461 stats.totalTime;
4462 float doubleBufferRatio = static_cast<float>(
4463 stats.doubleBufferedTime) / stats.totalTime;
4464 float tripleBufferRatio = static_cast<float>(
4465 stats.tripleBufferedTime) / stats.totalTime;
4466 sorted.insert({activeTime, {name, twoBufferRatio,
4467 doubleBufferRatio, tripleBufferRatio}});
4468 }
4469 for (const auto& sortedPair : sorted) {
4470 float activeTime = sortedPair.first;
4471 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004472 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4473 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004474 }
4475 result.append("\n");
4476}
4477
Yiwei Zhang5434a782018-12-05 18:06:32 -08004478void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004479 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004480 const auto displayId = display->getId();
4481 if (!displayId) {
4482 continue;
4483 }
4484 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004485 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004486 continue;
4487 }
4488
Yiwei Zhang5434a782018-12-05 18:06:32 -08004489 StringAppendF(&result,
4490 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4491 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004492 uint8_t port;
4493 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004494 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004495 result.append("no identification data\n");
4496 continue;
4497 }
4498
4499 if (!isEdid(data)) {
4500 result.append("unknown identification data: ");
4501 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004502 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004503 }
4504 result.append("\n");
4505 continue;
4506 }
4507
4508 const auto edid = parseEdid(data);
4509 if (!edid) {
4510 result.append("invalid EDID: ");
4511 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004512 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004513 }
4514 result.append("\n");
4515 continue;
4516 }
4517
Yiwei Zhang5434a782018-12-05 18:06:32 -08004518 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004519 result.append(edid->displayName.data(), edid->displayName.length());
4520 result.append("\"\n");
4521 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004522}
4523
Yiwei Zhang5434a782018-12-05 18:06:32 -08004524void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4525 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4526 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4527 StringAppendF(&result, "DisplayColorSetting: %s\n",
4528 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004529
4530 // TODO: print out if wide-color mode is active or not
4531
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004532 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004533 const auto displayId = display->getId();
4534 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004535 continue;
4536 }
4537
Yiwei Zhang5434a782018-12-05 18:06:32 -08004538 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004539 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004540 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004541 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004542 }
4543
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004544 ColorMode currentMode = display->getActiveColorMode();
Yiwei Zhang5434a782018-12-05 18:06:32 -08004545 StringAppendF(&result, " Current color mode: %s (%d)\n",
4546 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004547 }
4548 result.append("\n");
4549}
4550
Yiwei Zhang5434a782018-12-05 18:06:32 -08004551void SurfaceFlinger::dumpFrameCompositionInfo(std::string& result) const {
David Sodman7e4ae112018-02-09 15:02:28 -08004552 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004553 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4554 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004555 continue;
4556 }
4557
Dominik Laskowski05275f12018-11-01 15:03:24 -07004558 const auto& compositionInfoList = it->second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004559 StringAppendF(&result, "%s\n", display->getDebugName().c_str());
4560 StringAppendF(&result, "numComponents: %zu\n", compositionInfoList.size());
David Sodman7e4ae112018-02-09 15:02:28 -08004561 for (const auto& compositionInfo : compositionInfoList) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004562 compositionInfo.dump(result, nullptr);
4563 result.append("\n");
David Sodman7e4ae112018-02-09 15:02:28 -08004564 }
4565 }
David Sodman7e4ae112018-02-09 15:02:28 -08004566}
4567
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004568LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004569 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004570 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4571 const State& state = useDrawing ? mDrawingState : mCurrentState;
4572 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004573 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004574 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004575 });
4576
4577 return layersProto;
4578}
4579
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004580LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004581 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004582
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004583 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004584 resolution->set_w(display.getWidth());
4585 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004586
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004587 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4588 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4589 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004590
Dominik Laskowski075d3172018-05-24 15:50:06 -07004591 const auto displayId = display.getId();
4592 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004593 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004594 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004595 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004596 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004597 }
4598 });
4599
4600 return layersProto;
4601}
4602
Mathias Agopian74d211a2013-04-22 16:55:35 +02004603void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004604 std::string& result) const {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004605 bool colorize = false;
4606 if (index < args.size()
4607 && (args[index] == String16("--color"))) {
4608 colorize = true;
4609 index++;
4610 }
4611
4612 Colorizer colorizer(colorize);
4613
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004614 // figure out if we're stuck somewhere
4615 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004616 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004617 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4618
4619 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004620 * Dump library configuration.
4621 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004622
4623 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004624 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004625 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004626 appendSfConfigString(result);
4627 appendUiConfigString(result);
4628 appendGuiConfigString(result);
4629 result.append("\n");
4630
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004631 result.append("\nDisplay identification data:\n");
4632 dumpDisplayIdentificationData(result);
4633
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004634 result.append("\nWide-Color information:\n");
4635 dumpWideColorInfo(result);
4636
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004637 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004638 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004639 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004640 result.append(SyncFeatures::getInstance().toString());
4641 result.append("\n");
4642
Andy McFadden41d67d72014-04-25 16:58:34 -07004643 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004644 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004645 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004646
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004647 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4648 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004649 if (const auto displayId = getInternalDisplayId();
4650 displayId && getHwComposer().isConnected(*displayId)) {
4651 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004652 StringAppendF(&result,
4653 "Display %s: app phase %" PRId64 " ns, "
4654 "sf phase %" PRId64 " ns, "
4655 "early app phase %" PRId64 " ns, "
4656 "early sf phase %" PRId64 " ns, "
4657 "early app gl phase %" PRId64 " ns, "
4658 "early sf gl phase %" PRId64 " ns, "
4659 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4660 to_string(*displayId).c_str(), vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
4661 appEarlyOffset, sfEarlyOffset, appEarlyGlOffset, sfEarlyGlOffset,
4662 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004663 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004664 result.append("\n");
4665
Dan Stozab90cf072015-03-05 11:05:59 -08004666 // Dump static screen stats
4667 result.append("\n");
4668 dumpStaticScreenStats(result);
4669 result.append("\n");
4670
Yiwei Zhang5434a782018-12-05 18:06:32 -08004671 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004672
Dan Stozae77c7662016-05-13 11:37:28 -07004673 dumpBufferingStats(result);
4674
Andy McFadden4803b742012-09-24 19:07:20 -07004675 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004676 * Dump the visible layer list
4677 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004678 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004679 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4680 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4681 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004682 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004683
Chia-I Wu2f884132018-09-13 15:17:58 -07004684 {
4685 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4686 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004687 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004688 result.append("\n");
4689 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004690
David Sodman7e4ae112018-02-09 15:02:28 -08004691 result.append("\nFrame-Composition information:\n");
4692 dumpFrameCompositionInfo(result);
4693 result.append("\n");
4694
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004695 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004696 * Dump Display state
4697 */
4698
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004699 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004700 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004701 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004702 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004703 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004704 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004705 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004706
4707 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004708 * Dump SurfaceFlinger global state
4709 */
4710
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004711 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004712 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004713 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004714
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004715 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004716
Dominik Laskowski075d3172018-05-24 15:50:06 -07004717 if (const auto display = getDefaultDisplayDeviceLocked()) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004718 display->undefinedRegion.dump(result, "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004719 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4720 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004721 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004722 StringAppendF(&result,
4723 " transaction-flags : %08x\n"
4724 " gpu_to_cpu_unsupported : %d\n",
4725 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004726
Dominik Laskowski075d3172018-05-24 15:50:06 -07004727 if (const auto displayId = getInternalDisplayId();
4728 displayId && getHwComposer().isConnected(*displayId)) {
4729 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004730 StringAppendF(&result,
4731 " refresh-rate : %f fps\n"
4732 " x-dpi : %f\n"
4733 " y-dpi : %f\n",
4734 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4735 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004736 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004737
Yiwei Zhang5434a782018-12-05 18:06:32 -08004738 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004739
Yiwei Zhang5434a782018-12-05 18:06:32 -08004740 StringAppendF(&result, " use Scheduler: %s\n", mUseScheduler ? "true" : "false");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004741 /*
4742 * VSYNC state
4743 */
Ana Krulec98b5b242018-08-10 15:03:23 -07004744 if (mUseScheduler) {
4745 mScheduler->dump(mAppConnectionHandle, result);
4746 } else {
4747 mEventThread->dump(result);
4748 }
Dan Stozae22aec72016-08-01 13:20:59 -07004749 result.append("\n");
4750
4751 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004752 * Tracing state
4753 */
4754 mTracing.dump(result);
4755 result.append("\n");
4756
4757 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004758 * HWC layer minidump
4759 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004760 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004761 const auto displayId = display->getId();
4762 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004763 continue;
4764 }
4765
Yiwei Zhang5434a782018-12-05 18:06:32 -08004766 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004767 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004768 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004769 result.append("\n");
4770 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004771
4772 /*
4773 * Dump HWComposer state
4774 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004775 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004776 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004777 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004778 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004779 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004780 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004781
4782 /*
4783 * Dump gralloc state
4784 */
4785 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4786 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004787
4788 /*
4789 * Dump VrFlinger state if in use.
4790 */
4791 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4792 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004793 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004794 result.append("\n");
4795 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004796}
4797
Dominik Laskowski075d3172018-05-24 15:50:06 -07004798const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004799 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004800 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004801 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004802 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004803 }
4804 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004805
Dominik Laskowski34157762018-10-31 13:07:19 -07004806 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004807 static const Vector<sp<Layer>> empty;
4808 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004809}
4810
Keun young Park63f165f2012-08-31 10:53:36 -07004811bool SurfaceFlinger::startDdmConnection()
4812{
4813 void* libddmconnection_dso =
4814 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4815 if (!libddmconnection_dso) {
4816 return false;
4817 }
4818 void (*DdmConnection_start)(const char* name);
4819 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004820 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004821 if (!DdmConnection_start) {
4822 dlclose(libddmconnection_dso);
4823 return false;
4824 }
4825 (*DdmConnection_start)(getServiceName());
4826 return true;
4827}
4828
Chia-I Wu28f320b2018-05-03 11:02:56 -07004829void SurfaceFlinger::updateColorMatrixLocked() {
4830 mat4 colorMatrix;
4831 if (mGlobalSaturationFactor != 1.0f) {
4832 // Rec.709 luma coefficients
4833 float3 luminance{0.213f, 0.715f, 0.072f};
4834 luminance *= 1.0f - mGlobalSaturationFactor;
4835 mat4 saturationMatrix = mat4(
4836 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4837 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4838 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4839 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4840 );
4841 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4842 } else {
4843 colorMatrix = mClientColorMatrix * mDaltonizer();
4844 }
4845
4846 if (mCurrentState.colorMatrix != colorMatrix) {
4847 mCurrentState.colorMatrix = colorMatrix;
4848 mCurrentState.colorMatrixChanged = true;
4849 setTransactionFlags(eTransactionNeeded);
4850 }
4851}
4852
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004853status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004854#pragma clang diagnostic push
4855#pragma clang diagnostic error "-Wswitch-enum"
4856 switch (static_cast<ISurfaceComposerTag>(code)) {
4857 // These methods should at minimum make sure that the client requested
4858 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004859 case BOOT_FINISHED:
4860 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004861 case CREATE_DISPLAY:
4862 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004863 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004864 case GET_ACTIVE_COLOR_MODE:
4865 case GET_ANIMATION_FRAME_STATS:
4866 case GET_HDR_CAPABILITIES:
4867 case SET_ACTIVE_CONFIG:
4868 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004869 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004870 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004871 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004872 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4873 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004874 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4875 IPCThreadState* ipc = IPCThreadState::self();
4876 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4877 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004878 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004879 }
Robert Carr1db73f62016-12-21 12:58:51 -08004880 return OK;
4881 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004882 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004883 IPCThreadState* ipc = IPCThreadState::self();
4884 const int pid = ipc->getCallingPid();
4885 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004886 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4887 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004888 return PERMISSION_DENIED;
4889 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004890 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004891 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004892 // Used by apps to hook Choreographer to SurfaceFlinger.
4893 case CREATE_DISPLAY_EVENT_CONNECTION:
4894 // The following calls are currently used by clients that do not
4895 // request necessary permissions. However, they do not expose any secret
4896 // information, so it is OK to pass them.
4897 case AUTHENTICATE_SURFACE:
4898 case GET_ACTIVE_CONFIG:
4899 case GET_BUILT_IN_DISPLAY:
4900 case GET_DISPLAY_COLOR_MODES:
4901 case GET_DISPLAY_CONFIGS:
4902 case GET_DISPLAY_STATS:
4903 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4904 // Calling setTransactionState is safe, because you need to have been
4905 // granted a reference to Client* and Handle* to do anything with it.
4906 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004907 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004908 case GET_COLOR_MANAGEMENT:
Peiyong Lin0256f722018-08-31 15:45:10 -07004909 case GET_COMPOSITION_PREFERENCE: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004910 return OK;
4911 }
4912 case CAPTURE_LAYERS:
4913 case CAPTURE_SCREEN: {
4914 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004915 IPCThreadState* ipc = IPCThreadState::self();
4916 const int pid = ipc->getCallingPid();
4917 const int uid = ipc->getCallingUid();
4918 if ((uid != AID_GRAPHICS) &&
4919 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4920 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4921 return PERMISSION_DENIED;
4922 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004923 return OK;
4924 }
4925 // The following codes are deprecated and should never be allowed to access SF.
4926 case CONNECT_DISPLAY_UNUSED:
4927 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4928 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4929 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004930 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004931 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004932
4933 // These codes are used for the IBinder protocol to either interrogate the recipient
4934 // side of the transaction for its canonical interface descriptor or to dump its state.
4935 // We let them pass by default.
4936 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4937 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4938 code == IBinder::SYSPROPS_TRANSACTION) {
4939 return OK;
4940 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004941 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004942 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08004943 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004944 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4945 return OK;
4946 }
4947 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4948 return PERMISSION_DENIED;
4949#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004950}
4951
Ana Krulec13be8ad2018-08-21 02:43:56 +00004952status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4953 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004954 status_t credentialCheck = CheckTransactCodeCredentials(code);
4955 if (credentialCheck != OK) {
4956 return credentialCheck;
4957 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004958
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004959 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4960 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004961 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004962 IPCThreadState* ipc = IPCThreadState::self();
4963 const int uid = ipc->getCallingUid();
4964 if (CC_UNLIKELY(uid != AID_SYSTEM
4965 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004966 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004967 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004968 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004969 return PERMISSION_DENIED;
4970 }
4971 int n;
4972 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004973 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004974 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004975 return NO_ERROR;
4976 case 1002: // SHOW_UPDATES
4977 n = data.readInt32();
4978 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004979 invalidateHwcGeometry();
4980 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004981 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004982 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004983 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004984 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004985 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004986 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004987 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004988 setTransactionFlags(
4989 eTransactionNeeded|
4990 eDisplayTransactionNeeded|
4991 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004992 return NO_ERROR;
4993 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004994 case 1006:{ // send empty update
4995 signalRefresh();
4996 return NO_ERROR;
4997 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004998 case 1008: // toggle use of hw composer
4999 n = data.readInt32();
5000 mDebugDisableHWC = n ? 1 : 0;
5001 invalidateHwcGeometry();
5002 repaintEverything();
5003 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07005004 case 1009: // toggle use of transform hint
5005 n = data.readInt32();
5006 mDebugDisableTransformHint = n ? 1 : 0;
5007 invalidateHwcGeometry();
5008 repaintEverything();
5009 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005010 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005011 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005012 reply->writeInt32(0);
5013 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005014 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005015 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005016 return NO_ERROR;
5017 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005018 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005019 if (!display) {
5020 return NAME_NOT_FOUND;
5021 }
5022
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005023 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005024 return NO_ERROR;
5025 }
5026 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005027 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005028 // daltonize
5029 n = data.readInt32();
5030 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005031 case 1:
5032 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5033 break;
5034 case 2:
5035 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5036 break;
5037 case 3:
5038 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5039 break;
5040 default:
5041 mDaltonizer.setType(ColorBlindnessType::None);
5042 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005043 }
5044 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005045 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005046 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005047 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005048 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005049
5050 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005051 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005052 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005053 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005054 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005055 // apply a color matrix
5056 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005057 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005058 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005059 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005060 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005061 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005062 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005063 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005064 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005065 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005066 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005067
5068 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5069 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005070 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005071 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5072 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5073 }
5074
Chia-I Wu28f320b2018-05-03 11:02:56 -07005075 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005076 return NO_ERROR;
5077 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005078 // This is an experimental interface
5079 // Needs to be shifted to proper binder interface when we productize
5080 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005081 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005082 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07005083 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005084 return NO_ERROR;
5085 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005086 case 1017: {
5087 n = data.readInt32();
5088 mForceFullDamage = static_cast<bool>(n);
5089 return NO_ERROR;
5090 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005091 case 1018: { // Modify Choreographer's phase offset
5092 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005093 if (mUseScheduler) {
5094 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5095 } else {
5096 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5097 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005098 return NO_ERROR;
5099 }
5100 case 1019: { // Modify SurfaceFlinger's phase offset
5101 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005102 if (mUseScheduler) {
5103 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5104 } else {
5105 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5106 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005107 return NO_ERROR;
5108 }
Irvel468051e2016-06-13 16:44:44 -07005109 case 1020: { // Layer updates interceptor
5110 n = data.readInt32();
5111 if (n) {
5112 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005113 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005114 }
5115 else{
5116 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005117 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005118 }
5119 return NO_ERROR;
5120 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005121 case 1021: { // Disable HWC virtual displays
5122 n = data.readInt32();
5123 mUseHwcVirtualDisplays = !n;
5124 return NO_ERROR;
5125 }
Romain Guy0147a172017-06-01 13:53:56 -07005126 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005127 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005128 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005129
Chia-I Wu28f320b2018-05-03 11:02:56 -07005130 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005131 return NO_ERROR;
5132 }
Romain Guy54f154a2017-10-24 21:40:32 +01005133 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005134 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005135 invalidateHwcGeometry();
5136 repaintEverything();
5137 return NO_ERROR;
5138 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005139 // Deprecate, use 1030 to check whether the device is color managed.
5140 case 1024: {
5141 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005142 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005143 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005144 n = data.readInt32();
5145 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005146 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005147 mTracing.enable();
5148 doTracing("tracing.enable");
5149 reply->writeInt32(NO_ERROR);
5150 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005151 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005152 status_t err = mTracing.disable();
5153 reply->writeInt32(err);
5154 }
5155 return NO_ERROR;
5156 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005157 case 1026: { // Get layer tracing status
5158 reply->writeBool(mTracing.isEnabled());
5159 return NO_ERROR;
5160 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005161 // Is a DisplayColorSetting supported?
5162 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005163 const auto display = getDefaultDisplayDevice();
5164 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005165 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005166 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005167
5168 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5169 switch (setting) {
5170 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005171 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005172 break;
5173 case DisplayColorSetting::UNMANAGED:
5174 reply->writeBool(true);
5175 break;
5176 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005177 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005178 break;
5179 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005180 reply->writeBool(
5181 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005182 break;
5183 }
5184 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005185 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005186 // Is VrFlinger active?
5187 case 1028: {
5188 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005189 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005190 return NO_ERROR;
5191 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005192 // Is device color managed?
5193 case 1030: {
5194 reply->writeBool(useColorManagement);
5195 return NO_ERROR;
5196 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005197 // Override default composition data space
5198 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5199 // && adb shell stop zygote && adb shell start zygote
5200 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5201 // adb shell stop zygote && adb shell start zygote
5202 case 1031: {
5203 Mutex::Autolock _l(mStateLock);
5204 n = data.readInt32();
5205 if (n) {
5206 n = data.readInt32();
5207 if (n) {
5208 Dataspace dataspace = static_cast<Dataspace>(n);
5209 if (!validateCompositionDataspace(dataspace)) {
5210 return BAD_VALUE;
5211 }
5212 mDefaultCompositionDataspace = dataspace;
5213 }
5214 n = data.readInt32();
5215 if (n) {
5216 Dataspace dataspace = static_cast<Dataspace>(n);
5217 if (!validateCompositionDataspace(dataspace)) {
5218 return BAD_VALUE;
5219 }
5220 mWideColorGamutCompositionDataspace = dataspace;
5221 }
5222 } else {
5223 // restore composition data space.
5224 mDefaultCompositionDataspace = defaultCompositionDataspace;
5225 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5226 }
5227 return NO_ERROR;
5228 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005229 }
5230 }
5231 return err;
5232}
5233
Steven Thomas6d8110b2017-08-31 18:24:21 -07005234void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005235 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005236 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005237}
5238
Ana Krulec7d1d6832018-12-27 11:10:09 -08005239void SurfaceFlinger::repaintEverythingForHWC() {
5240 mRepaintEverything = true;
5241 mEventQueue->invalidateForHWC();
5242}
5243
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005244// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5245class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005246public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005247 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5248 ~WindowDisconnector() {
5249 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005250 }
5251
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005252private:
5253 ANativeWindow* mWindow;
5254 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005255};
5256
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005257status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005258 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5259 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005260 uint32_t reqWidth, uint32_t reqHeight,
5261 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005262 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005263 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005264
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005265 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005266
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005267 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5268
Chia-I Wu20261cb2018-08-23 12:55:44 -07005269 sp<DisplayDevice> display;
5270 {
5271 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005272
Chia-I Wu20261cb2018-08-23 12:55:44 -07005273 display = getDisplayDeviceLocked(displayToken);
5274 if (!display) return BAD_VALUE;
5275
Chia-I Wucb023152018-08-28 12:57:23 -07005276 // set the requested width/height to the logical display viewport size
5277 // by default
5278 if (reqWidth == 0 || reqHeight == 0) {
5279 reqWidth = uint32_t(display->getViewport().width());
5280 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005281 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005282 }
5283
Peiyong Lin0e003c92018-09-17 11:09:51 -07005284 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5285 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005286
5287 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005288 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005289 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5290 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005291}
5292
5293status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005294 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5295 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005296 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005297 ATRACE_CALL();
5298
5299 class LayerRenderArea : public RenderArea {
5300 public:
Robert Carr578038f2018-03-09 12:25:24 -08005301 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005302 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5303 bool childrenOnly)
5304 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005305 mLayer(layer),
5306 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005307 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005308 mFlinger(flinger),
5309 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005310 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005311 Rect getBounds() const override {
5312 const Layer::State& layerState(mLayer->getDrawingState());
5313 return mLayer->getBufferSize(layerState);
5314 }
Marissa Wall61c58622018-07-18 10:12:20 -07005315 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005316 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005317 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005318 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005319 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005320 }
chaviwa76b2712017-09-20 12:02:26 -07005321 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005322 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005323 Rect getSourceCrop() const override {
5324 if (mCrop.isEmpty()) {
5325 return getBounds();
5326 } else {
5327 return mCrop;
5328 }
5329 }
Robert Carr578038f2018-03-09 12:25:24 -08005330 class ReparentForDrawing {
5331 public:
5332 const sp<Layer>& oldParent;
5333 const sp<Layer>& newParent;
5334
5335 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5336 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005337 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005338 }
Robert Carr15eae092018-03-23 13:43:53 -07005339 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005340 };
5341
5342 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005343 const Rect sourceCrop = getSourceCrop();
5344 // no need to check rotation because there is none
5345 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5346 sourceCrop.height() != getReqHeight();
5347
Robert Carr578038f2018-03-09 12:25:24 -08005348 if (!mChildrenOnly) {
5349 mTransform = mLayer->getTransform().inverse();
5350 drawLayers();
5351 } else {
5352 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005353 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005354 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5355 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005356
5357 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5358 drawLayers();
5359 }
5360 }
chaviwa76b2712017-09-20 12:02:26 -07005361
chaviwa76b2712017-09-20 12:02:26 -07005362 private:
chaviw7206d492017-11-10 16:16:12 -08005363 const sp<Layer> mLayer;
5364 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005365
5366 // In the "childrenOnly" case we reparent the children to a screenshot
5367 // layer which has no properties set and which does not draw.
5368 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005369 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005370 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005371
5372 SurfaceFlinger* mFlinger;
5373 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005374 };
5375
5376 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5377 auto parent = layerHandle->owner.promote();
5378
Robert Carr2e102c92018-10-23 12:11:15 -07005379 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005380 ALOGE("captureLayers called with a removed parent");
5381 return NAME_NOT_FOUND;
5382 }
5383
Robert Carr578038f2018-03-09 12:25:24 -08005384 const int uid = IPCThreadState::self()->getCallingUid();
5385 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005386 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005387 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5388 return PERMISSION_DENIED;
5389 }
5390
chaviw7206d492017-11-10 16:16:12 -08005391 Rect crop(sourceCrop);
5392 if (sourceCrop.width() <= 0) {
5393 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005394 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005395 }
5396
5397 if (sourceCrop.height() <= 0) {
5398 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005399 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005400 }
5401
5402 int32_t reqWidth = crop.width() * frameScale;
5403 int32_t reqHeight = crop.height() * frameScale;
5404
Chia-I Wu20261cb2018-08-23 12:55:44 -07005405 // really small crop or frameScale
5406 if (reqWidth <= 0) {
5407 reqWidth = 1;
5408 }
5409 if (reqHeight <= 0) {
5410 reqHeight = 1;
5411 }
5412
Peiyong Lin0e003c92018-09-17 11:09:51 -07005413 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005414
Robert Carr578038f2018-03-09 12:25:24 -08005415 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005416 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5417 if (!layer->isVisible()) {
5418 return;
Robert Carr578038f2018-03-09 12:25:24 -08005419 } else if (childrenOnly && layer == parent.get()) {
5420 return;
chaviwa76b2712017-09-20 12:02:26 -07005421 }
5422 visitor(layer);
5423 });
5424 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005425 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005426}
5427
5428status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5429 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005430 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005431 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005432 bool useIdentityTransform) {
5433 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005434
Peiyong Lin0e003c92018-09-17 11:09:51 -07005435 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005436 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5437 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005438 *outBuffer =
5439 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5440 static_cast<android_pixel_format>(reqPixelFormat), 1,
5441 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005442
5443 // This mutex protects syncFd and captureResult for communication of the return values from the
5444 // main thread back to this Binder thread
5445 std::mutex captureMutex;
5446 std::condition_variable captureCondition;
5447 std::unique_lock<std::mutex> captureLock(captureMutex);
5448 int syncFd = -1;
5449 std::optional<status_t> captureResult;
5450
Robert Carr03480e22018-01-04 16:02:06 -08005451 const int uid = IPCThreadState::self()->getCallingUid();
5452 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5453
Dominik Laskowski8c001672018-05-30 16:52:06 -07005454 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005455 // If there is a refresh pending, bug out early and tell the binder thread to try again
5456 // after the refresh.
5457 if (mRefreshPending) {
5458 ATRACE_NAME("Skipping screenshot for now");
5459 std::unique_lock<std::mutex> captureLock(captureMutex);
5460 captureResult = std::make_optional<status_t>(EAGAIN);
5461 captureCondition.notify_one();
5462 return;
5463 }
5464
5465 status_t result = NO_ERROR;
5466 int fd = -1;
5467 {
5468 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005469 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005470 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5471 useIdentityTransform, forSystem, &fd);
5472 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005473 }
5474
5475 {
5476 std::unique_lock<std::mutex> captureLock(captureMutex);
5477 syncFd = fd;
5478 captureResult = std::make_optional<status_t>(result);
5479 captureCondition.notify_one();
5480 }
5481 });
5482
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005483 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005484 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005485 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005486 while (*captureResult == EAGAIN) {
5487 captureResult.reset();
5488 result = postMessageAsync(message);
5489 if (result != NO_ERROR) {
5490 return result;
5491 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005492 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005493 }
5494 result = *captureResult;
5495 }
5496
5497 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005498 sync_wait(syncFd, -1);
5499 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005500 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005501
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005502 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005503}
5504
chaviwa76b2712017-09-20 12:02:26 -07005505void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005506 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005507 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005508 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005509
Lloyd Pique144e1162017-12-20 16:44:52 -08005510 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005511
chaviwa76b2712017-09-20 12:02:26 -07005512 const auto reqWidth = renderArea.getReqWidth();
5513 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005514 const auto sourceCrop = renderArea.getSourceCrop();
5515 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005516
Peiyong Lin0e003c92018-09-17 11:09:51 -07005517 engine.setOutputDataSpace(renderArea.getReqDataSpace());
Chia-I Wu36574d92018-05-16 10:54:36 -07005518 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005519
Mathias Agopian180f10d2013-04-10 22:55:41 -07005520 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005521 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005522
5523 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005524 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005525 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005526
chaviw50da5042018-04-09 13:49:37 -07005527 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005528 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005529 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005530
chaviwa76b2712017-09-20 12:02:26 -07005531 traverseLayers([&](Layer* layer) {
Peiyong Lind3788632018-09-18 16:01:31 -07005532 engine.setColorTransform(layer->getColorTransform());
David Sodmanfb95bcc2017-12-22 15:45:30 -08005533 layer->draw(renderArea, useIdentityTransform);
Peiyong Lind3788632018-09-18 16:01:31 -07005534 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005535 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005536}
5537
chaviwa76b2712017-09-20 12:02:26 -07005538status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5539 TraverseLayersFunction traverseLayers,
5540 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005541 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005542 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005543 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005544 ATRACE_CALL();
5545
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005546 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005547
5548 traverseLayers([&](Layer* layer) {
5549 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5550 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005551
Robert Carr03480e22018-01-04 16:02:06 -08005552 // We allow the system server to take screenshots of secure layers for
5553 // use in situations like the Screen-rotation animation and place
5554 // the impetus on WindowManager to not persist them.
5555 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005556 ALOGW("FB is protected: PERMISSION_DENIED");
5557 return PERMISSION_DENIED;
5558 }
Peiyong Linfb530cf2018-12-15 05:07:38 +00005559 auto& engine(getRenderEngine());
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005560
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005561 // this binds the given EGLImage as a framebuffer for the
5562 // duration of this scope.
Peiyong Linfb530cf2018-12-15 05:07:38 +00005563 renderengine::BindNativeBufferAsFramebuffer bufferBond(engine, buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005564 if (bufferBond.getStatus() != NO_ERROR) {
5565 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005566 return INVALID_OPERATION;
5567 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005568
Dan Stozaabcda352017-06-01 14:37:39 -07005569 // this will in fact render into our dequeued buffer
5570 // via an FBO, which means we didn't have to create
5571 // an EGLSurface and therefore we're not
5572 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005573 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005574
Peiyong Linfb530cf2018-12-15 05:07:38 +00005575 base::unique_fd syncFd = engine.flush();
Alec Mouri492bc572018-09-11 21:40:04 +00005576 if (syncFd < 0) {
Peiyong Linfb530cf2018-12-15 05:07:38 +00005577 engine.finish();
Dan Stozaabcda352017-06-01 14:37:39 -07005578 }
Alec Mouri492bc572018-09-11 21:40:04 +00005579 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005580
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005581 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005582}
5583
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005584// ---------------------------------------------------------------------------
5585
Dan Stoza412903f2017-04-27 13:42:17 -07005586void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5587 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005588}
5589
Dan Stoza412903f2017-04-27 13:42:17 -07005590void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5591 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005592}
5593
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005594void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005595 const LayerVector::Visitor& visitor) {
5596 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005597 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005598 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005599 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005600 continue;
5601 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005602 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005603 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005604 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005605 return;
5606 }
chaviwa76b2712017-09-20 12:02:26 -07005607 if (!layer->isVisible()) {
5608 return;
5609 }
5610 visitor(layer);
5611 });
5612 }
5613}
5614
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005615}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005616
Lloyd Pique074e8122018-07-26 12:57:23 -07005617
Mathias Agopian3f844832013-08-07 21:24:32 -07005618#if defined(__gl_h_)
5619#error "don't include gl/gl.h in this file"
5620#endif
5621
5622#if defined(__gl2_h_)
5623#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005624#endif