blob: dc82b3267f8314ae2270180f0a7ffde25d873c4a [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
Dan Stoza9e56aa02015-11-02 13:00:03 -0800732 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700733}
734
Romain Guy11d63f42017-07-20 12:47:14 -0700735void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700736 Mutex::Autolock _l(mStateLock);
737
Romain Guy11d63f42017-07-20 12:47:14 -0700738 char value[PROPERTY_VALUE_MAX];
739
740 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800741 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700742 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800743 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100744
745 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700746 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700747}
748
Mathias Agopiana67e4182012-06-19 17:26:12 -0700749void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800750 // Start boot animation service by setting a property mailbox
751 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700752 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800753 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700754 if (mStartPropertySetThread->join() != NO_ERROR) {
755 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800756 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700757}
758
Mathias Agopian875d8e12013-06-07 15:35:48 -0700759size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700760 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700761}
762
Mathias Agopian875d8e12013-06-07 15:35:48 -0700763size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700764 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700765}
766
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800767// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800768
Jamie Gennis582270d2011-08-17 18:19:00 -0700769bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800770 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800771 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800772 return authenticateSurfaceTextureLocked(bufferProducer);
773}
774
775bool SurfaceFlinger::authenticateSurfaceTextureLocked(
776 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800777 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800778 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800779}
780
Brian Anderson6b376712017-04-04 10:51:39 -0700781status_t SurfaceFlinger::getSupportedFrameTimestamps(
782 std::vector<FrameEvent>* outSupported) const {
783 *outSupported = {
784 FrameEvent::REQUESTED_PRESENT,
785 FrameEvent::ACQUIRE,
786 FrameEvent::LATCH,
787 FrameEvent::FIRST_REFRESH_START,
788 FrameEvent::LAST_REFRESH_START,
789 FrameEvent::GPU_COMPOSITION_DONE,
790 FrameEvent::DEQUEUE_READY,
791 FrameEvent::RELEASE,
792 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700793 ConditionalLock _l(mStateLock,
794 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700795 if (!getHwComposer().hasCapability(
796 HWC2::Capability::PresentFenceIsNotReliable)) {
797 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
798 }
799 return NO_ERROR;
800}
801
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700802status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
803 Vector<DisplayInfo>* configs) {
804 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700805 return BAD_VALUE;
806 }
807
Dominik Laskowski075d3172018-05-24 15:50:06 -0700808 const auto displayId = getPhysicalDisplayId(displayToken);
809 if (!displayId) {
810 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700811 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700812
Mathias Agopian8b736f12012-08-13 17:54:26 -0700813 // TODO: Not sure if display density should handled by SF any longer
814 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700815 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700816 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700817 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800818 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700819 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700820 }
821 return density;
822 }
823 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700824 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700825 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700826 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700827 return getDensityFromProperty("ro.sf.lcd_density"); }
828 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700829
Dan Stoza7f7da322014-05-02 15:26:25 -0700830 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700831
Steven Thomas6d8110b2017-08-31 18:24:21 -0700832 ConditionalLock _l(mStateLock,
833 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700834 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700835 DisplayInfo info = DisplayInfo();
836
Dan Stoza9e56aa02015-11-02 13:00:03 -0800837 float xdpi = hwConfig->getDpiX();
838 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700839
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700840 info.w = hwConfig->getWidth();
841 info.h = hwConfig->getHeight();
842 // Default display viewport to display width and height
843 info.viewportW = info.w;
844 info.viewportH = info.h;
845
Dominik Laskowski075d3172018-05-24 15:50:06 -0700846 if (displayId == getInternalDisplayId()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700847 // The density of the device is provided by a build property
848 float density = Density::getBuildDensity() / 160.0f;
849 if (density == 0) {
850 // the build doesn't provide a density -- this is wrong!
851 // use xdpi instead
852 ALOGE("ro.sf.lcd_density must be defined as a build property");
853 density = xdpi / 160.0f;
854 }
855 if (Density::getEmuDensity()) {
856 // if "qemu.sf.lcd_density" is specified, it overrides everything
857 xdpi = ydpi = density = Density::getEmuDensity();
858 density /= 160.0f;
859 }
860 info.density = density;
861
862 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700863 const auto display = getDefaultDisplayDeviceLocked();
864 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700865
866 // This is for screenrecord
867 const Rect viewport = display->getViewport();
868 if (viewport.isValid()) {
869 info.viewportW = uint32_t(viewport.getWidth());
870 info.viewportH = uint32_t(viewport.getHeight());
871 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700872 } else {
873 // TODO: where should this value come from?
874 static const int TV_DENSITY = 213;
875 info.density = TV_DENSITY / 160.0f;
876 info.orientation = 0;
877 }
878
Dan Stoza7f7da322014-05-02 15:26:25 -0700879 info.xdpi = xdpi;
880 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800881 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900882 info.appVsyncOffset = vsyncPhaseOffsetNs;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800883
Andy McFadden91b2ca82014-06-13 14:04:23 -0700884 // This is how far in advance a buffer must be queued for
885 // presentation at a given time. If you want a buffer to appear
886 // on the screen at time N, you must submit the buffer before
887 // (N - presentationDeadline).
888 //
889 // Normally it's one full refresh period (to give SF a chance to
890 // latch the buffer), but this can be reduced by configuring a
891 // DispSync offset. Any additional delays introduced by the hardware
892 // composer or panel must be accounted for here.
893 //
894 // We add an additional 1ms to allow for processing time and
895 // differences between the ideal and actual refresh rate.
Dan Stoza9e56aa02015-11-02 13:00:03 -0800896 info.presentationDeadline = hwConfig->getVsyncPeriod() -
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800897 sfVsyncPhaseOffsetNs + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700898
899 // All non-virtual displays are currently considered secure.
900 info.secure = true;
901
Dominik Laskowski075d3172018-05-24 15:50:06 -0700902 if (displayId == getInternalDisplayId() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700903 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800904 std::swap(info.w, info.h);
905 }
906
Michael Wright28f24d02016-07-12 13:30:53 -0700907 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700908 }
909
Dan Stoza7f7da322014-05-02 15:26:25 -0700910 return NO_ERROR;
911}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700912
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700913status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
914 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700915 return BAD_VALUE;
916 }
917
Ana Krulece588e312018-09-18 12:32:24 -0700918 if (mUseScheduler) {
919 mScheduler->getDisplayStatInfo(stats);
920 } else {
921 stats->vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
922 stats->vsyncPeriod = mPrimaryDispSync->getPeriod();
923 }
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700924 return NO_ERROR;
925}
926
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700927int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
928 const auto display = getDisplayDevice(displayToken);
929 if (!display) {
930 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800931 return BAD_VALUE;
932 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700933
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700934 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700935}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700936
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700937void SurfaceFlinger::setActiveConfigInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -0700938 if (display->isVirtual()) {
939 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
940 return;
941 }
942
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700943 int currentMode = display->getActiveConfig();
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700944 if (mode == currentMode) {
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700945 return;
946 }
947
Dominik Laskowski075d3172018-05-24 15:50:06 -0700948 const auto displayId = display->getId();
949 LOG_ALWAYS_FATAL_IF(!displayId);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700950
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700951 display->setActiveConfig(mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700952 getHwComposer().setActiveConfig(*displayId, mode);
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700953}
954
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700955status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700956 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700957 Vector<DisplayInfo> configs;
958 getDisplayConfigs(displayToken, &configs);
959 if (mode < 0 || mode >= static_cast<int>(configs.size())) {
960 ALOGE("Attempt to set active config %d for display with %zu configs", mode,
961 configs.size());
962 return;
Michael Lentine6c9e34a2014-07-14 13:48:55 -0700963 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700964 const auto display = getDisplayDevice(displayToken);
965 if (!display) {
966 ALOGE("Attempt to set active config %d for invalid display token %p", mode,
967 displayToken.get());
968 } else if (display->isVirtual()) {
969 ALOGW("Attempt to set active config %d for virtual display", mode);
970 } else {
971 setActiveConfigInternal(display, mode);
972 }
973 }));
974
Mathias Agopian888c8222012-08-04 21:10:38 -0700975 return NO_ERROR;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700976}
Dominik Laskowski075d3172018-05-24 15:50:06 -0700977
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700978status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
979 Vector<ColorMode>* outColorModes) {
980 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -0700981 return BAD_VALUE;
982 }
983
Dominik Laskowski075d3172018-05-24 15:50:06 -0700984 const auto displayId = getPhysicalDisplayId(displayToken);
985 if (!displayId) {
986 return NAME_NOT_FOUND;
Michael Wright28f24d02016-07-12 13:30:53 -0700987 }
988
Peiyong Lina52f0292018-03-14 17:26:31 -0700989 std::vector<ColorMode> modes;
Steven Thomas6d8110b2017-08-31 18:24:21 -0700990 {
991 ConditionalLock _l(mStateLock,
992 std::this_thread::get_id() != mMainThreadId);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700993 modes = getHwComposer().getColorModes(*displayId);
Steven Thomas6d8110b2017-08-31 18:24:21 -0700994 }
Michael Wright28f24d02016-07-12 13:30:53 -0700995 outColorModes->clear();
996 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
997
998 return NO_ERROR;
999}
1000
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001001ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1002 if (const auto display = getDisplayDevice(displayToken)) {
1003 return display->getActiveColorMode();
Michael Wright28f24d02016-07-12 13:30:53 -07001004 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001005 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001006}
1007
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001008void SurfaceFlinger::setActiveColorModeInternal(const sp<DisplayDevice>& display, ColorMode mode,
1009 Dataspace dataSpace, RenderIntent renderIntent) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001010 if (display->isVirtual()) {
1011 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
1012 return;
1013 }
1014
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001015 ColorMode currentMode = display->getActiveColorMode();
1016 Dataspace currentDataSpace = display->getCompositionDataSpace();
1017 RenderIntent currentRenderIntent = display->getActiveRenderIntent();
Michael Wright28f24d02016-07-12 13:30:53 -07001018
Peiyong Lin38e9a562018-04-10 16:24:20 -07001019 if (mode == currentMode && dataSpace == currentDataSpace &&
1020 renderIntent == currentRenderIntent) {
1021 return;
1022 }
1023
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001024 display->setActiveColorMode(mode);
1025 display->setCompositionDataSpace(dataSpace);
1026 display->setActiveRenderIntent(renderIntent);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08001027
Dominik Laskowski075d3172018-05-24 15:50:06 -07001028 const auto displayId = display->getId();
1029 LOG_ALWAYS_FATAL_IF(!displayId);
1030 getHwComposer().setActiveColorMode(*displayId, mode, renderIntent);
1031
Dominik Laskowski34157762018-10-31 13:07:19 -07001032 ALOGV("Set active color mode: %s (%d), active render intent: %s (%d), display=%s",
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001033 decodeColorMode(mode).c_str(), mode, decodeRenderIntent(renderIntent).c_str(),
Dominik Laskowski34157762018-10-31 13:07:19 -07001034 renderIntent, to_string(*displayId).c_str());
Michael Wright28f24d02016-07-12 13:30:53 -07001035}
1036
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001037status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001038 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001039 Vector<ColorMode> modes;
1040 getDisplayColorModes(displayToken, &modes);
1041 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1042 if (mode < ColorMode::NATIVE || !exists) {
1043 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1044 decodeColorMode(mode).c_str(), mode, displayToken.get());
1045 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001046 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001047 const auto display = getDisplayDevice(displayToken);
1048 if (!display) {
1049 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1050 decodeColorMode(mode).c_str(), mode, displayToken.get());
1051 } else if (display->isVirtual()) {
1052 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1053 decodeColorMode(mode).c_str(), mode);
1054 } else {
1055 setActiveColorModeInternal(display, mode, Dataspace::UNKNOWN,
1056 RenderIntent::COLORIMETRIC);
1057 }
1058 }));
1059
Michael Wright28f24d02016-07-12 13:30:53 -07001060 return NO_ERROR;
1061}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001062
Svetoslavd85084b2014-03-20 10:28:31 -07001063status_t SurfaceFlinger::clearAnimationFrameStats() {
1064 Mutex::Autolock _l(mStateLock);
1065 mAnimFrameTracker.clearStats();
1066 return NO_ERROR;
1067}
1068
1069status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1070 Mutex::Autolock _l(mStateLock);
1071 mAnimFrameTracker.getStats(outStats);
1072 return NO_ERROR;
1073}
1074
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001075status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1076 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001077 Mutex::Autolock _l(mStateLock);
1078
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001079 const auto display = getDisplayDeviceLocked(displayToken);
1080 if (!display) {
1081 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001082 return BAD_VALUE;
1083 }
1084
Peiyong Linfb069302018-04-25 14:34:31 -07001085 // At this point the DisplayDeivce should already be set up,
1086 // meaning the luminance information is already queried from
1087 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001088 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001089 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1090 capabilities.getDesiredMaxLuminance(),
1091 capabilities.getDesiredMaxAverageLuminance(),
1092 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001093
1094 return NO_ERROR;
1095}
1096
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001097status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1098 ui::PixelFormat* outFormat,
1099 ui::Dataspace* outDataspace,
1100 uint8_t* outComponentMask) const {
1101 if (!outFormat || !outDataspace || !outComponentMask) {
1102 return BAD_VALUE;
1103 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001104 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001105 if (!display || !display->getId()) {
1106 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1107 return BAD_VALUE;
1108 }
1109 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1110 outDataspace, outComponentMask);
1111}
1112
Kevin DuBois74e53772018-11-19 10:52:38 -08001113status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1114 bool enable, uint8_t componentMask,
1115 uint64_t maxFrames) const {
1116 const auto display = getDisplayDevice(displayToken);
1117 if (!display || !display->getId()) {
1118 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1119 return BAD_VALUE;
1120 }
1121
1122 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1123 componentMask, maxFrames);
1124}
1125
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001126status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1127 uint64_t maxFrames, uint64_t timestamp,
1128 DisplayedFrameStats* outStats) const {
1129 const auto display = getDisplayDevice(displayToken);
1130 if (!display || !display->getId()) {
1131 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1132 return BAD_VALUE;
1133 }
1134
1135 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1136 outStats);
1137}
1138
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001139status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001140 postMessageSync(new LambdaMessage([&] {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001141 Mutex::Autolock _l(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001142
Chia-I Wu90f669f2017-10-05 14:24:41 -07001143 if (mInjectVSyncs == enable) {
1144 return;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001145 }
Chia-I Wu90f669f2017-10-05 14:24:41 -07001146
Ana Krulec98b5b242018-08-10 15:03:23 -07001147 // TODO(akrulec): Part of the Injector should be refactored, so that it
1148 // can be passed to Scheduler.
Chia-I Wu90f669f2017-10-05 14:24:41 -07001149 if (enable) {
1150 ALOGV("VSync Injections enabled");
1151 if (mVSyncInjector.get() == nullptr) {
Lloyd Piquee83f9312018-02-01 12:53:17 -08001152 mVSyncInjector = std::make_unique<InjectVSyncSource>();
Lloyd Pique24b0a482018-03-09 18:52:26 -08001153 mInjectorEventThread = std::make_unique<
Dominik Laskowski8c001672018-05-30 16:52:06 -07001154 impl::EventThread>(mVSyncInjector.get(), [this] { resyncWithRateLimit(); },
Lloyd Pique24b0a482018-03-09 18:52:26 -08001155 impl::EventThread::InterceptVSyncsCallback(),
1156 "injEventThread");
Chia-I Wu90f669f2017-10-05 14:24:41 -07001157 }
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001158 mEventQueue->setEventThread(mInjectorEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001159 } else {
1160 ALOGV("VSync Injections disabled");
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001161 mEventQueue->setEventThread(mSFEventThread.get());
Chia-I Wu90f669f2017-10-05 14:24:41 -07001162 }
1163
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001164 mInjectVSyncs = enable;
Dominik Laskowski8c001672018-05-30 16:52:06 -07001165 }));
1166
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001167 return NO_ERROR;
1168}
1169
1170status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Chia-I Wu90f669f2017-10-05 14:24:41 -07001171 Mutex::Autolock _l(mStateLock);
1172
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001173 if (!mInjectVSyncs) {
1174 ALOGE("VSync Injections not enabled");
1175 return BAD_VALUE;
1176 }
1177 if (mInjectVSyncs && mInjectorEventThread.get() != nullptr) {
1178 ALOGV("Injecting VSync inside SurfaceFlinger");
1179 mVSyncInjector->onInjectSyncEvent(when);
1180 }
1181 return NO_ERROR;
1182}
1183
Lloyd Pique755e3192018-01-31 16:46:15 -08001184status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1185 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001186 // Try to acquire a lock for 1s, fail gracefully
1187 const status_t err = mStateLock.timedLock(s2ns(1));
1188 const bool locked = (err == NO_ERROR);
1189 if (!locked) {
1190 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1191 return TIMED_OUT;
1192 }
1193
1194 outLayers->clear();
1195 mCurrentState.traverseInZOrder([&](Layer* layer) {
1196 outLayers->push_back(layer->getLayerDebugInfo());
1197 });
1198
1199 mStateLock.unlock();
1200 return NO_ERROR;
1201}
1202
Peiyong Linc6780972018-10-28 15:24:08 -07001203status_t SurfaceFlinger::getCompositionPreference(
1204 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1205 Dataspace* outWideColorGamutDataspace,
1206 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001207 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001208 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001209 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001210 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001211 return NO_ERROR;
1212}
1213
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001214// ----------------------------------------------------------------------------
1215
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001216sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
1217 ISurfaceComposer::VsyncSource vsyncSource) {
Ana Krulec98b5b242018-08-10 15:03:23 -07001218 if (mUseScheduler) {
1219 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1220 return mScheduler->createDisplayEventConnection(mSfConnectionHandle);
1221 } else {
1222 return mScheduler->createDisplayEventConnection(mAppConnectionHandle);
1223 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001224 } else {
Ana Krulec98b5b242018-08-10 15:03:23 -07001225 if (vsyncSource == eVsyncSourceSurfaceFlinger) {
1226 return mSFEventThread->createEventConnection();
1227 } else {
1228 return mEventThread->createEventConnection();
1229 }
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001230 }
Mathias Agopianbb641242010-05-18 17:06:55 -07001231}
1232
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001233// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001234
1235void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001236 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001237}
1238
1239void SurfaceFlinger::signalTransaction() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001240 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001241}
1242
1243void SurfaceFlinger::signalLayerUpdate() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001244 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001245}
1246
1247void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001248 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001249 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001250}
1251
1252status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001253 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001254 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001255}
1256
1257status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001258 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001259 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001260 if (res == NO_ERROR) {
1261 msg->wait();
1262 }
1263 return res;
1264}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001265
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001266void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001267 do {
1268 waitForEvent();
1269 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001270}
1271
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001272void SurfaceFlinger::enableHardwareVsync() {
1273 Mutex::Autolock _l(mHWVsyncLock);
Jesse Hall948fe0c2013-10-14 12:56:09 -07001274 if (!mPrimaryHWVsyncEnabled && mHWVsyncAvailable) {
Lloyd Pique41be5d22018-06-21 13:11:48 -07001275 mPrimaryDispSync->beginResync();
Jamie Gennisd1700752013-10-14 12:22:52 -07001276 mEventControlThread->setVsyncEnabled(true);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001277 mPrimaryHWVsyncEnabled = true;
Andy McFadden43601a22012-09-11 15:15:13 -07001278 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001279}
1280
Jesse Hall948fe0c2013-10-14 12:56:09 -07001281void SurfaceFlinger::resyncToHardwareVsync(bool makeAvailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001282 Mutex::Autolock _l(mHWVsyncLock);
1283
Jesse Hall948fe0c2013-10-14 12:56:09 -07001284 if (makeAvailable) {
1285 mHWVsyncAvailable = true;
Ana Krulec7ab56032018-11-02 20:51:06 +01001286 // TODO(b/113612090): This is silly, but necessary evil until we turn on the flag for good.
1287 if (mUseScheduler) {
1288 mScheduler->makeHWSyncAvailable(true);
1289 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001290 } else if (!mHWVsyncAvailable) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001291 // Hardware vsync is not currently available, so abort the resync
1292 // attempt for now
Jesse Hall948fe0c2013-10-14 12:56:09 -07001293 return;
1294 }
1295
Dominik Laskowski075d3172018-05-24 15:50:06 -07001296 const auto displayId = getInternalDisplayId();
1297 if (!displayId || !getHwComposer().isConnected(*displayId)) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001298 return;
1299 }
1300
Dominik Laskowski075d3172018-05-24 15:50:06 -07001301 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dan Stoza9e56aa02015-11-02 13:00:03 -08001302 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001303
Ana Krulece588e312018-09-18 12:32:24 -07001304 if (mUseScheduler) {
1305 mScheduler->setVsyncPeriod(period);
1306 } else {
1307 mPrimaryDispSync->reset();
1308 mPrimaryDispSync->setPeriod(period);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001309
Ana Krulece588e312018-09-18 12:32:24 -07001310 if (!mPrimaryHWVsyncEnabled) {
1311 mPrimaryDispSync->beginResync();
1312 mEventControlThread->setVsyncEnabled(true);
1313 mPrimaryHWVsyncEnabled = true;
1314 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001315 }
1316}
1317
Jesse Hall948fe0c2013-10-14 12:56:09 -07001318void SurfaceFlinger::disableHardwareVsync(bool makeUnavailable) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001319 Mutex::Autolock _l(mHWVsyncLock);
1320 if (mPrimaryHWVsyncEnabled) {
Jamie Gennisd1700752013-10-14 12:22:52 -07001321 mEventControlThread->setVsyncEnabled(false);
Lloyd Pique41be5d22018-06-21 13:11:48 -07001322 mPrimaryDispSync->endResync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001323 mPrimaryHWVsyncEnabled = false;
1324 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07001325 if (makeUnavailable) {
1326 mHWVsyncAvailable = false;
1327 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001328}
1329
Tim Murray4a4e4a22016-04-19 16:29:23 +00001330void SurfaceFlinger::resyncWithRateLimit() {
1331 static constexpr nsecs_t kIgnoreDelay = ms2ns(500);
Dan Stoza57164302017-05-08 14:03:54 -07001332
1333 // No explicit locking is needed here since EventThread holds a lock while calling this method
1334 static nsecs_t sLastResyncAttempted = 0;
1335 const nsecs_t now = systemTime();
1336 if (now - sLastResyncAttempted > kIgnoreDelay) {
Dan Stoza0a3c4d62016-04-19 11:56:20 -07001337 resyncToHardwareVsync(false);
Tim Murray4a4e4a22016-04-19 16:29:23 +00001338 }
Dan Stoza57164302017-05-08 14:03:54 -07001339 sLastResyncAttempted = now;
Tim Murray4a4e4a22016-04-19 16:29:23 +00001340}
1341
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001342void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1343 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001344 ATRACE_NAME("SF onVsync");
1345
Steven Thomas3cfac282017-02-06 12:29:30 -08001346 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001347 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001348 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001349 return;
1350 }
1351
Dominik Laskowski075d3172018-05-24 15:50:06 -07001352 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001353 return;
1354 }
1355
Dominik Laskowski075d3172018-05-24 15:50:06 -07001356 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001357 // For now, we don't do anything with external display vsyncs.
1358 return;
1359 }
1360
Ana Krulece588e312018-09-18 12:32:24 -07001361 if (mUseScheduler) {
1362 mScheduler->addResyncSample(timestamp);
Jamie Gennisd1700752013-10-14 12:22:52 -07001363 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001364 bool needsHwVsync = false;
1365 { // Scope for the lock
1366 Mutex::Autolock _l(mHWVsyncLock);
1367 if (mPrimaryHWVsyncEnabled) {
1368 needsHwVsync = mPrimaryDispSync->addResyncSample(timestamp);
1369 }
1370 }
1371
1372 if (needsHwVsync) {
1373 enableHardwareVsync();
1374 } else {
1375 disableHardwareVsync(false);
1376 }
Jamie Gennisd1700752013-10-14 12:22:52 -07001377 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001378}
1379
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001380void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001381 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1382 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001383}
1384
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001385void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001386 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001387 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001388 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001389
Lloyd Piqueba04e622017-12-14 17:11:26 -08001390 // Ignore events that do not have the right sequenceId.
1391 if (sequenceId != getBE().mComposerSequenceId) {
1392 return;
1393 }
1394
Steven Thomasb02664d2017-07-26 18:48:28 -07001395 // Only lock if we're not on the main thread. This function is normally
1396 // called on a hwbinder thread, but for the primary display it's called on
1397 // the main thread with the state lock already held, so don't attempt to
1398 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001399 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001400
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001401 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001402
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001403 if (std::this_thread::get_id() == mMainThreadId) {
1404 // Process all pending hot plug events immediately if we are on the main thread.
1405 processDisplayHotplugEventsLocked();
1406 }
1407
Lloyd Piqueba04e622017-12-14 17:11:26 -08001408 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001409}
1410
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001411void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001412 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001413 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001414 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001415 }
Dan Stozac7a25ad2018-04-12 11:45:09 -07001416 repaintEverything();
Steven Thomas3cfac282017-02-06 12:29:30 -08001417}
1418
Dominik Laskowski075d3172018-05-24 15:50:06 -07001419void SurfaceFlinger::setVsyncEnabled(EventThread::DisplayType /*displayType*/, bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001420 ATRACE_CALL();
Steven Thomasb02664d2017-07-26 18:48:28 -07001421 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001422 if (const auto displayId = getInternalDisplayId()) {
1423 getHwComposer().setVsyncEnabled(*displayId,
1424 enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable);
1425 }
Mathias Agopian86303202012-07-24 22:46:10 -07001426}
1427
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001428// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001429void SurfaceFlinger::resetDisplayState() {
Ana Krulece588e312018-09-18 12:32:24 -07001430 if (mUseScheduler) {
1431 mScheduler->disableHardwareVsync(true);
1432 } else {
1433 disableHardwareVsync(true);
1434 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001435 // Clear the drawing state so that the logic inside of
1436 // handleTransactionLocked will fire. It will determine the delta between
1437 // mCurrentState and mDrawingState and re-apply all changes when we make the
1438 // transition.
1439 mDrawingState.displays.clear();
1440 mDisplays.clear();
1441}
1442
Steven Thomas050b2c82017-03-06 11:45:16 -08001443void SurfaceFlinger::updateVrFlinger() {
1444 if (!mVrFlinger)
1445 return;
1446 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001447 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001448 return;
1449 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001450
Lloyd Pique441d5042018-10-18 16:49:51 -07001451 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001452 ALOGE("Vr flinger is only supported for remote hardware composer"
1453 " service connections. Ignoring request to transition to vr"
1454 " flinger.");
1455 mVrFlingerRequestsDisplay = false;
1456 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001457 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001458
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001459 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001460
Steven Thomas0123ac62018-07-12 11:32:34 -07001461 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001462 LOG_ALWAYS_FATAL_IF(!display);
1463 const int currentDisplayPowerMode = display->getPowerMode();
Steven Thomas0123ac62018-07-12 11:32:34 -07001464 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1465 // called below. Clear the reference now so we don't accidentally use it
1466 // later.
1467 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001468
Steven Thomasb02664d2017-07-26 18:48:28 -07001469 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001470 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001471 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001472
Steven Thomasb02664d2017-07-26 18:48:28 -07001473 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001474 // Delete the current instance before creating the new one
1475 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1476 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1477 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1478 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001479
Lloyd Pique441d5042018-10-18 16:49:51 -07001480 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001481 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001482
1483 if (vrFlingerRequestsDisplay) {
1484 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001485 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001486
1487 mVisibleRegionsDirty = true;
1488 invalidateHwcGeometry();
1489
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001490 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001491 display = getDefaultDisplayDeviceLocked();
1492 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001493 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001494
Steven Thomasb02664d2017-07-26 18:48:28 -07001495 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski075d3172018-05-24 15:50:06 -07001496 const auto activeConfig = getHwComposer().getActiveConfig(*display->getId());
Steven Thomasb02664d2017-07-26 18:48:28 -07001497 const nsecs_t period = activeConfig->getVsyncPeriod();
1498 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001499
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001500 // The present fences returned from vr_hwc are not an accurate
1501 // representation of vsync times.
Ana Krulece588e312018-09-18 12:32:24 -07001502 if (mUseScheduler) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001503 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
1504 !hasSyncFramework);
Ana Krulece588e312018-09-18 12:32:24 -07001505 } else {
Lloyd Pique441d5042018-10-18 16:49:51 -07001506 mPrimaryDispSync->setIgnorePresentFences(getHwComposer().isUsingVrComposer() ||
Ana Krulece588e312018-09-18 12:32:24 -07001507 !hasSyncFramework);
1508 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001509
Steven Thomasb02664d2017-07-26 18:48:28 -07001510 // Use phase of 0 since phase is not known.
1511 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07001512 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
1513 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001514
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001515 resyncToHardwareVsync(false);
1516
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001517 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001518 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001519}
1520
Mathias Agopian4fec8732012-06-29 14:12:52 -07001521void SurfaceFlinger::onMessageReceived(int32_t what) {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001522 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001523 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001524 case MessageQueue::INVALIDATE: {
Ana Krulec3084c052018-11-21 20:27:17 +01001525 if (mUseScheduler) {
1526 // This call is made each time SF wakes up and creates a new frame.
1527 mScheduler->incrementFrameCounter();
1528 }
Dan Stoza50182882016-07-08 12:02:20 -07001529 bool frameMissed = !mHadClientComposition &&
1530 mPreviousPresentFence != Fence::NO_FENCE &&
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001531 (mPreviousPresentFence->getSignalTime() ==
1532 Fence::SIGNAL_TIME_PENDING);
Marissa Wallcfcdaa52018-05-21 15:45:59 -07001533 mFrameMissedCount += frameMissed;
Dan Stoza50182882016-07-08 12:02:20 -07001534 ATRACE_INT("FrameMissed", static_cast<int>(frameMissed));
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001535 if (frameMissed) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001536 mTimeStats->incrementMissedFrames();
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001537 if (mPropagateBackpressure) {
1538 signalLayerUpdate();
1539 break;
1540 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001541 }
Dan Stoza50182882016-07-08 12:02:20 -07001542
Steven Thomas050b2c82017-03-06 11:45:16 -08001543 // Now that we're going to make it to the handleMessageTransaction()
1544 // call below it's safe to call updateVrFlinger(), which will
1545 // potentially trigger a display handoff.
1546 updateVrFlinger();
1547
Dan Stoza6b9454d2014-11-07 16:00:59 -08001548 bool refreshNeeded = handleMessageTransaction();
1549 refreshNeeded |= handleMessageInvalidate();
Dan Stoza58784442014-12-02 16:58:17 -08001550 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001551 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001552 // Signal a refresh if a transaction modified the window state,
1553 // a new buffer was latched, or if HWC has requested a full
1554 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001555 signalRefresh();
1556 }
1557 break;
1558 }
1559 case MessageQueue::REFRESH: {
1560 handleMessageRefresh();
1561 break;
1562 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001563 }
1564}
1565
Dan Stoza6b9454d2014-11-07 16:00:59 -08001566bool SurfaceFlinger::handleMessageTransaction() {
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001567 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001568
1569 // Apply any ready transactions in the queues if there are still transactions that have not been
1570 // applied, wake up during the next vsync period and check again
1571 bool transactionNeeded = false;
1572 if (!flushTransactionQueues()) {
1573 transactionNeeded = true;
1574 }
1575
Mathias Agopian4fec8732012-06-29 14:12:52 -07001576 if (transactionFlags) {
Mathias Agopian87baae12012-07-31 12:38:26 -07001577 handleTransaction(transactionFlags);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001578 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001579
1580 if (transactionNeeded) {
1581 setTransactionFlags(eTransactionNeeded);
1582 }
1583
1584 return transactionFlags;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001585}
1586
Mathias Agopian4fec8732012-06-29 14:12:52 -07001587void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001588 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001589
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001590 mRefreshPending = false;
1591
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001592 const bool repaintEverything = mRepaintEverything.exchange(false);
David Sodman2b406362017-12-15 13:33:47 -08001593 preComposition();
Lloyd Pique074e8122018-07-26 12:57:23 -07001594 rebuildLayerStacks();
David Sodman79bba0e2018-08-05 18:07:49 -07001595 calculateWorkingSet();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001596 for (const auto& [token, display] : mDisplays) {
1597 beginFrame(display);
1598 prepareFrame(display);
1599 doDebugFlashRegions(display, repaintEverything);
1600 doComposition(display, repaintEverything);
1601 }
1602
Adrian Roos1e1a1282017-11-01 19:05:31 +01001603 doTracing("handleRefresh");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001604 logLayerStats();
David Sodmanfa9b2af2017-12-24 13:28:59 -08001605
1606 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001607 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001608
Dan Stozabfbffeb2016-07-21 14:49:33 -07001609 mHadClientComposition = false;
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001610 for (const auto& [token, display] : mDisplays) {
Lloyd Pique441d5042018-10-18 16:49:51 -07001611 mHadClientComposition =
1612 mHadClientComposition || getHwComposer().hasClientComposition(display->getId());
Dan Stozabfbffeb2016-07-21 14:49:33 -07001613 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08001614
Alec Mouri86770e52018-09-24 22:40:58 +00001615 // Setup RenderEngine sync fences if native sync is supported.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07001616 if (getRenderEngine().useNativeFenceSync()) {
Alec Mouri86770e52018-09-24 22:40:58 +00001617 if (mHadClientComposition) {
1618 base::unique_fd flushFence(getRenderEngine().flush());
1619 ALOGE_IF(flushFence < 0, "Failed to flush RenderEngine!");
1620 getBE().flushFence = new Fence(std::move(flushFence));
1621 } else {
1622 // Cleanup for hygiene.
1623 getBE().flushFence = Fence::NO_FENCE;
1624 }
1625 }
1626
Jorim Jaggi90535212018-05-23 23:44:06 +02001627 mVsyncModulator.onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001628
David Sodman7e4ae112018-02-09 15:02:28 -08001629 getBE().mEndOfFrameCompositionInfo = std::move(getBE().mCompositionInfo);
David Sodman15fb96e2018-01-07 10:23:24 -08001630 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001631 for (auto& compositionInfo : getBE().mEndOfFrameCompositionInfo[token]) {
David Sodman15fb96e2018-01-07 10:23:24 -08001632 compositionInfo.hwc.hwcLayer = nullptr;
1633 }
David Sodmanba340492018-08-05 21:51:33 -07001634 }
David Sodman7e4ae112018-02-09 15:02:28 -08001635
1636 mLayersWithQueuedFrames.clear();
Mathias Agopiancd60f992012-08-16 16:28:27 -07001637}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001638
David Sodmanfa9b2af2017-12-24 13:28:59 -08001639
1640bool SurfaceFlinger::handleMessageInvalidate() {
1641 ATRACE_CALL();
1642 return handlePageFlip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07001643}
1644
David Sodman79bba0e2018-08-05 18:07:49 -07001645void SurfaceFlinger::calculateWorkingSet() {
1646 ATRACE_CALL();
1647 ALOGV(__FUNCTION__);
1648
David Sodman79bba0e2018-08-05 18:07:49 -07001649 // build the h/w work list
1650 if (CC_UNLIKELY(mGeometryInvalid)) {
1651 mGeometryInvalid = false;
1652 for (const auto& [token, display] : mDisplays) {
1653 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001654 if (!displayId) {
1655 continue;
1656 }
David Sodman79bba0e2018-08-05 18:07:49 -07001657
Dominik Laskowski075d3172018-05-24 15:50:06 -07001658 const Vector<sp<Layer>>& currentLayers = display->getVisibleLayersSortedByZ();
1659 for (size_t i = 0; i < currentLayers.size(); i++) {
1660 const auto& layer = currentLayers[i];
David Sodman79bba0e2018-08-05 18:07:49 -07001661
Dominik Laskowski075d3172018-05-24 15:50:06 -07001662 if (!layer->hasHwcLayer(*displayId)) {
1663 if (!layer->createHwcLayer(&getHwComposer(), *displayId)) {
1664 layer->forceClientComposition(*displayId);
1665 continue;
David Sodman79bba0e2018-08-05 18:07:49 -07001666 }
1667 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001668
1669 layer->setGeometry(display, i);
1670 if (mDebugDisableHWC || mDebugRegion) {
1671 layer->forceClientComposition(*displayId);
1672 }
David Sodman79bba0e2018-08-05 18:07:49 -07001673 }
1674 }
1675 }
1676
1677 // Set the per-frame data
1678 for (const auto& [token, display] : mDisplays) {
1679 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07001680 if (!displayId) {
David Sodman79bba0e2018-08-05 18:07:49 -07001681 continue;
1682 }
1683
1684 if (mDrawingState.colorMatrixChanged) {
1685 display->setColorTransform(mDrawingState.colorMatrix);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001686 status_t result =
1687 getHwComposer().setColorTransform(*displayId, mDrawingState.colorMatrix);
Dominik Laskowski34157762018-10-31 13:07:19 -07001688 ALOGE_IF(result != NO_ERROR, "Failed to set color transform on display %s: %d",
1689 to_string(*displayId).c_str(), result);
David Sodman79bba0e2018-08-05 18:07:49 -07001690 }
1691 for (auto& layer : display->getVisibleLayersSortedByZ()) {
1692 if (layer->isHdrY410()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001693 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001694 } else if ((layer->getDataSpace() == Dataspace::BT2020_PQ ||
1695 layer->getDataSpace() == Dataspace::BT2020_ITU_PQ) &&
1696 !display->hasHDR10Support()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001697 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001698 } else if ((layer->getDataSpace() == Dataspace::BT2020_HLG ||
1699 layer->getDataSpace() == Dataspace::BT2020_ITU_HLG) &&
1700 !display->hasHLGSupport()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001701 layer->forceClientComposition(*displayId);
David Sodman79bba0e2018-08-05 18:07:49 -07001702 }
1703
Peiyong Lind3788632018-09-18 16:01:31 -07001704 // TODO(b/111562338) remove when composer 2.3 is shipped.
1705 if (layer->hasColorTransform()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001706 layer->forceClientComposition(*displayId);
Peiyong Lind3788632018-09-18 16:01:31 -07001707 }
1708
Lucas Dupin1b6531c2018-07-05 17:18:21 -07001709 if (layer->getRoundedCornerState().radius > 0.0f) {
1710 layer->forceClientComposition(*displayId);
1711 }
1712
Dominik Laskowski075d3172018-05-24 15:50:06 -07001713 if (layer->getForceClientComposition(*displayId)) {
David Sodman79bba0e2018-08-05 18:07:49 -07001714 ALOGV("[%s] Requesting Client composition", layer->getName().string());
Dominik Laskowski075d3172018-05-24 15:50:06 -07001715 layer->setCompositionType(*displayId, HWC2::Composition::Client);
David Sodman79bba0e2018-08-05 18:07:49 -07001716 continue;
1717 }
1718
Dominik Laskowski075d3172018-05-24 15:50:06 -07001719 layer->setPerFrameData(*displayId, display->getTransform(), display->getViewport(),
1720 display->getSupportedPerFrameMetadata());
David Sodman79bba0e2018-08-05 18:07:49 -07001721 }
1722
Peiyong Lin13effd12018-07-24 17:01:47 -07001723 if (useColorManagement) {
David Sodman79bba0e2018-08-05 18:07:49 -07001724 ColorMode colorMode;
1725 Dataspace dataSpace;
1726 RenderIntent renderIntent;
1727 pickColorMode(display, &colorMode, &dataSpace, &renderIntent);
1728 setActiveColorModeInternal(display, colorMode, dataSpace, renderIntent);
1729 }
1730 }
1731
1732 mDrawingState.colorMatrixChanged = false;
David Sodmanba340492018-08-05 21:51:33 -07001733
1734 for (const auto& [token, display] : mDisplays) {
1735 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07001736 const auto displayId = display->getId();
David Sodmanba340492018-08-05 21:51:33 -07001737 layer->getBE().compositionInfo.compositionType = layer->getCompositionType(displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07001738
1739 if (displayId) {
1740 if (!layer->setHwcLayer(*displayId)) {
1741 ALOGV("Need to create HWCLayer for %s", layer->getName().string());
1742 }
1743 layer->getBE().compositionInfo.hwc.displayId = *displayId;
David Sodmanba340492018-08-05 21:51:33 -07001744 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001745
Dominik Laskowski05275f12018-11-01 15:03:24 -07001746 getBE().mCompositionInfo[token].push_back(layer->getBE().compositionInfo);
David Sodmanba340492018-08-05 21:51:33 -07001747 layer->getBE().compositionInfo.hwc.hwcLayer = nullptr;
1748 }
1749 }
David Sodman79bba0e2018-08-05 18:07:49 -07001750}
1751
David Sodmanfa9b2af2017-12-24 13:28:59 -08001752void SurfaceFlinger::doDebugFlashRegions(const sp<DisplayDevice>& display, bool repaintEverything)
Mathias Agopiancd60f992012-08-16 16:28:27 -07001753{
1754 // is debugging enabled
1755 if (CC_LIKELY(!mDebugRegion))
1756 return;
1757
David Sodmanfa9b2af2017-12-24 13:28:59 -08001758 if (display->isPoweredOn()) {
1759 // transform the dirty region into this screen's coordinate space
1760 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
1761 if (!dirtyRegion.isEmpty()) {
1762 // redraw the whole screen
1763 doComposeSurfaces(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001764
David Sodmanfa9b2af2017-12-24 13:28:59 -08001765 // and draw the dirty region
David Sodmanfa9b2af2017-12-24 13:28:59 -08001766 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07001767 engine.fillRegionWithColor(dirtyRegion, 1, 0, 1, 1);
Mathias Agopian3f844832013-08-07 21:24:32 -07001768
Alec Mouri0a9c7b82018-11-16 13:05:25 -08001769 display->queueBuffer(getHwComposer());
Mathias Agopiancd60f992012-08-16 16:28:27 -07001770 }
1771 }
1772
David Sodmanfa9b2af2017-12-24 13:28:59 -08001773 postFramebuffer(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001774
1775 if (mDebugRegion > 1) {
1776 usleep(mDebugRegion * 1000);
1777 }
Mathias Agopianbb53b0e2012-09-24 21:27:29 -07001778
Dominik Laskowski05275f12018-11-01 15:03:24 -07001779 prepareFrame(display);
Mathias Agopiancd60f992012-08-16 16:28:27 -07001780}
1781
Adrian Roos1e1a1282017-11-01 19:05:31 +01001782void SurfaceFlinger::doTracing(const char* where) {
1783 ATRACE_CALL();
1784 ATRACE_NAME(where);
1785 if (CC_UNLIKELY(mTracing.isEnabled())) {
Jorim Jaggi8e0af362017-11-14 16:28:28 +01001786 mTracing.traceLayers(where, dumpProtoInfo(LayerVector::StateSet::Drawing));
Adrian Roos1e1a1282017-11-01 19:05:31 +01001787 }
1788}
1789
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001790void SurfaceFlinger::logLayerStats() {
1791 ATRACE_CALL();
1792 if (CC_UNLIKELY(mLayerStats.isEnabled())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07001793 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001794 if (display->isPrimary()) {
1795 mLayerStats.logLayerStats(dumpVisibleLayersProtoInfo(*display));
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001796 return;
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001797 }
1798 }
Dominik Laskowski63165dc2018-05-25 18:36:52 -07001799
1800 ALOGE("logLayerStats: no primary display");
Yiwei Zhang7124ad32018-02-21 13:02:45 -08001801 }
1802}
1803
David Sodman2b406362017-12-15 13:33:47 -08001804void SurfaceFlinger::preComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001805{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001806 ATRACE_CALL();
1807 ALOGV("preComposition");
1808
David Sodman2b406362017-12-15 13:33:47 -08001809 mRefreshStartTime = systemTime(SYSTEM_TIME_MONOTONIC);
1810
Mathias Agopiancd60f992012-08-16 16:28:27 -07001811 bool needExtraInvalidate = false;
Robert Carr2047fae2016-11-28 14:09:09 -08001812 mDrawingState.traverseInZOrder([&](Layer* layer) {
David Sodman2b406362017-12-15 13:33:47 -08001813 if (layer->onPreComposition(mRefreshStartTime)) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001814 needExtraInvalidate = true;
1815 }
Robert Carr2047fae2016-11-28 14:09:09 -08001816 });
1817
Mathias Agopiancd60f992012-08-16 16:28:27 -07001818 if (needExtraInvalidate) {
1819 signalLayerUpdate();
1820 }
1821}
1822
Ana Krulece588e312018-09-18 12:32:24 -07001823void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1824 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001825 // Update queue of past composite+present times and determine the
1826 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001827 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001828 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001829 while (!getBE().mCompositePresentTimes.empty()) {
1830 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001831 // Cached values should have been updated before calling this method,
1832 // which helps avoid duplicate syscalls.
1833 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1834 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1835 break;
1836 }
1837 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001838 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001839 }
1840
1841 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001842 while (getBE().mCompositePresentTimes.size() > 16) {
1843 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001844 }
1845
Ana Krulece588e312018-09-18 12:32:24 -07001846 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001847}
1848
Ana Krulece588e312018-09-18 12:32:24 -07001849void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1850 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001851 // Integer division and modulo round toward 0 not -inf, so we need to
1852 // treat negative and positive offsets differently.
Ana Krulece588e312018-09-18 12:32:24 -07001853 nsecs_t idealLatency = (sfVsyncPhaseOffsetNs > 0)
1854 ? (stats.vsyncPeriod - (sfVsyncPhaseOffsetNs % stats.vsyncPeriod))
1855 : ((-sfVsyncPhaseOffsetNs) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001856
Brian Andersond0010582017-03-07 13:20:31 -08001857 // Just in case sfVsyncPhaseOffsetNs == -vsyncInterval.
1858 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001859 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001860 }
1861
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001862 // Snap the latency to a value that removes scheduling jitter from the
1863 // composition and present times, which often have >1ms of jitter.
1864 // Reducing jitter is important if an app attempts to extrapolate
1865 // something (such as user input) to an accurate diasplay time.
1866 // Snapping also allows an app to precisely calculate sfVsyncPhaseOffsetNs
1867 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001868 nsecs_t bias = stats.vsyncPeriod / 2;
1869 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1870 nsecs_t snappedCompositeToPresentLatency =
1871 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001872
David Sodman99974d22017-11-28 12:04:33 -08001873 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001874 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1875 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001876 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001877}
1878
David Sodman2b406362017-12-15 13:33:47 -08001879void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001880{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001881 ATRACE_CALL();
1882 ALOGV("postComposition");
1883
Brian Anderson3546a3f2016-07-14 11:51:14 -07001884 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001885 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001886 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001887 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001888 }
1889
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001890 // |mStateLock| not needed as we are on the main thread
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001891 const auto display = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001892
David Sodman73beded2017-11-15 11:56:06 -08001893 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001894 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001895 if (display && getHwComposer().hasClientComposition(display->getId())) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001896 glCompositionDoneFenceTime =
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001897 std::make_shared<FenceTime>(display->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001898 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001899 } else {
1900 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1901 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001902
David Sodman73beded2017-11-15 11:56:06 -08001903 getBE().mDisplayTimeline.updateSignalTimes();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001904 mPreviousPresentFence =
Dominik Laskowski075d3172018-05-24 15:50:06 -07001905 display ? getHwComposer().getPresentFence(*display->getId()) : Fence::NO_FENCE;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001906 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFence);
David Sodman73beded2017-11-15 11:56:06 -08001907 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001908
Ana Krulece588e312018-09-18 12:32:24 -07001909 DisplayStatInfo stats;
1910 if (mUseScheduler) {
1911 mScheduler->getDisplayStatInfo(&stats);
1912 } else {
1913 stats.vsyncTime = mPrimaryDispSync->computeNextRefresh(0);
1914 stats.vsyncPeriod = mPrimaryDispSync->getPeriod();
1915 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001916
David Sodman2b406362017-12-15 13:33:47 -08001917 // We use the mRefreshStartTime which might be sampled a little later than
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001918 // when we started doing work for this frame, but that should be okay
1919 // since updateCompositorTiming has snapping logic.
Ana Krulece588e312018-09-18 12:32:24 -07001920 updateCompositorTiming(stats, mRefreshStartTime, presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001921 CompositorTiming compositorTiming;
1922 {
David Sodman99974d22017-11-28 12:04:33 -08001923 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1924 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001925 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001926
Robert Carr2047fae2016-11-28 14:09:09 -08001927 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001928 bool frameLatched = layer->onPostComposition(display->getId(), glCompositionDoneFenceTime,
1929 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001930 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001931 recordBufferingStats(layer->getName().string(),
1932 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001933 }
Robert Carr2047fae2016-11-28 14:09:09 -08001934 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001935
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001936 if (presentFenceTime->isValid()) {
Ana Krulece588e312018-09-18 12:32:24 -07001937 if (mUseScheduler) {
1938 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001939 } else {
Ana Krulece588e312018-09-18 12:32:24 -07001940 if (mPrimaryDispSync->addPresentFence(presentFenceTime)) {
1941 enableHardwareVsync();
1942 } else {
1943 disableHardwareVsync(false);
1944 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001945 }
1946 }
1947
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001948 if (!hasSyncFramework) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07001949 if (display && getHwComposer().isConnected(*display->getId()) && display->isPoweredOn()) {
Ana Krulece588e312018-09-18 12:32:24 -07001950 if (mUseScheduler) {
1951 mScheduler->enableHardwareVsync();
1952 } else {
1953 enableHardwareVsync();
1954 }
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001955 }
1956 }
1957
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001958 if (mAnimCompositionPending) {
1959 mAnimCompositionPending = false;
1960
Brian Anderson4e606e32017-03-16 15:34:57 -07001961 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001962 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001963 std::move(presentFenceTime));
Dominik Laskowski075d3172018-05-24 15:50:06 -07001964 } else if (display && getHwComposer().isConnected(*display->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001965 // The HWC doesn't support present fences, so use the refresh
1966 // timestamp instead.
Dominik Laskowski075d3172018-05-24 15:50:06 -07001967 const nsecs_t presentTime = getHwComposer().getRefreshTimestamp(*display->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001968 mAnimFrameTracker.setActualPresentTime(presentTime);
1969 }
1970 mAnimFrameTracker.advanceFrame();
1971 }
Dan Stozab90cf072015-03-05 11:05:59 -08001972
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001973 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001974 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001975 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001976 }
1977
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001978 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07001979
Dominik Laskowski075d3172018-05-24 15:50:06 -07001980 if (display && getHwComposer().isConnected(*display->getId()) && !display->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08001981 return;
1982 }
1983
1984 nsecs_t currentTime = systemTime();
1985 if (mHasPoweredOff) {
1986 mHasPoweredOff = false;
1987 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001988 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07001989 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08001990 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1991 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001992 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001993 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001994 }
David Sodman4a36e932017-11-07 14:29:47 -08001995 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001996 }
David Sodman4a36e932017-11-07 14:29:47 -08001997 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001998
1999 {
2000 std::lock_guard lock(mTexturePoolMutex);
2001 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
2002 if (refillCount > 0) {
2003 const size_t offset = mTexturePool.size();
2004 mTexturePool.resize(mTexturePoolSize);
2005 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2006 ATRACE_INT("TexturePoolSize", mTexturePool.size());
2007 }
2008 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002009
Marissa Wallfda30bb2018-10-12 11:34:28 -07002010 mTransactionCompletedThread.addPresentFence(mPreviousPresentFence);
Marissa Walle2ffb422018-10-12 11:33:52 -07002011 mTransactionCompletedThread.sendCallbacks();
Mathias Agopiancd60f992012-08-16 16:28:27 -07002012}
2013
2014void SurfaceFlinger::rebuildLayerStacks() {
Dan Stoza9e56aa02015-11-02 13:00:03 -08002015 ATRACE_CALL();
2016 ALOGV("rebuildLayerStacks");
2017
Lloyd Piquedcec0bc2018-11-16 16:08:10 -08002018 // We need to clear these out now as these may be holding on to a
2019 // HWC2::Layer reference at the same time as the LayerBE::HWCInfo structure
2020 // also holds a reference. When the set of visible layers is recomputed,
2021 // some layers may be destroyed if the only thing keeping them alive was
2022 // that list of visible layers associated with each display. The layer
2023 // destruction code asserts that the HWC2::Layer is properly destroyed, but
2024 // that doesn't happen if SurfaceFlingerBE::mCompositionInfo keeps it alive.
2025 for (const auto& [token, display] : mDisplays) {
2026 getBE().mCompositionInfo[token].clear();
2027 }
2028
Mathias Agopiancd60f992012-08-16 16:28:27 -07002029 // rebuild the visible layer list per screen
Jeff Sharkey76488112017-02-27 14:15:18 -07002030 if (CC_UNLIKELY(mVisibleRegionsDirty)) {
Siarhei Vishniakoufc2589e2017-09-21 15:35:13 -07002031 ATRACE_NAME("rebuildLayerStacks VR Dirty");
Jeff Sharkey76488112017-02-27 14:15:18 -07002032 mVisibleRegionsDirty = false;
2033 invalidateHwcGeometry();
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002034
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002035 for (const auto& pair : mDisplays) {
2036 const auto& display = pair.second;
Jeff Sharkey76488112017-02-27 14:15:18 -07002037 Region opaqueRegion;
2038 Region dirtyRegion;
2039 Vector<sp<Layer>> layersSortedByZ;
Chia-I Wu83806892017-11-16 10:50:20 -08002040 Vector<sp<Layer>> layersNeedingFences;
Peiyong Linefefaac2018-08-17 12:27:51 -07002041 const ui::Transform& tr = display->getTransform();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002042 const Rect bounds = display->getBounds();
2043 if (display->isPoweredOn()) {
2044 computeVisibleRegions(display, dirtyRegion, opaqueRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002045
Jeff Sharkey76488112017-02-27 14:15:18 -07002046 mDrawingState.traverseInZOrder([&](Layer* layer) {
Chia-I Wu83806892017-11-16 10:50:20 -08002047 bool hwcLayerDestroyed = false;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002048 const auto displayId = display->getId();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002049 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Jeff Sharkey76488112017-02-27 14:15:18 -07002050 Region drawRegion(tr.transform(
2051 layer->visibleNonTransparentRegion));
2052 drawRegion.andSelf(bounds);
2053 if (!drawRegion.isEmpty()) {
2054 layersSortedByZ.add(layer);
2055 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002056 // Clear out the HWC layer if this layer was
2057 // previously visible, but no longer is
Dominik Laskowski075d3172018-05-24 15:50:06 -07002058 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Jeff Sharkey76488112017-02-27 14:15:18 -07002059 }
Chia-I Wu30505fb2018-03-26 16:20:31 -07002060 } else {
Lloyd Pique074e8122018-07-26 12:57:23 -07002061 // WM changes display->layerStack upon sleep/awake.
2062 // Here we make sure we delete the HWC layers even if
2063 // WM changed their layer stack.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002064 hwcLayerDestroyed = displayId && layer->destroyHwcLayer(*displayId);
Chia-I Wu83806892017-11-16 10:50:20 -08002065 }
2066
2067 // If a layer is not going to get a release fence because
2068 // it is invisible, but it is also going to release its
2069 // old buffer, add it to the list of layers needing
2070 // fences.
2071 if (hwcLayerDestroyed) {
2072 auto found = std::find(mLayersWithQueuedFrames.cbegin(),
2073 mLayersWithQueuedFrames.cend(), layer);
2074 if (found != mLayersWithQueuedFrames.cend()) {
2075 layersNeedingFences.add(layer);
2076 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002077 }
Jeff Sharkey76488112017-02-27 14:15:18 -07002078 });
2079 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002080 display->setVisibleLayersSortedByZ(layersSortedByZ);
2081 display->setLayersNeedingFences(layersNeedingFences);
2082 display->undefinedRegion.set(bounds);
2083 display->undefinedRegion.subtractSelf(tr.transform(opaqueRegion));
2084 display->dirtyRegion.orSelf(dirtyRegion);
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002085 }
Fabien Sanglard3beb7112017-02-24 17:33:52 -08002086 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002087}
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002088
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002089// Returns a data space that fits all visible layers. The returned data space
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002090// can only be one of
Chia-I Wu7a28ecb2018-05-04 10:38:39 -07002091// - Dataspace::SRGB (use legacy dataspace and let HWC saturate when colors are enhanced)
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002092// - Dataspace::DISPLAY_P3
Valerie Hau9758ae02018-10-09 16:05:09 -07002093// - Dataspace::DISPLAY_BT2020
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002094// The returned HDR data space is one of
2095// - Dataspace::UNKNOWN
2096// - Dataspace::BT2020_HLG
2097// - Dataspace::BT2020_PQ
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002098Dataspace SurfaceFlinger::getBestDataspace(const sp<const DisplayDevice>& display,
2099 Dataspace* outHdrDataSpace) const {
Peiyong Lin14724e62018-12-05 07:27:30 -08002100 Dataspace bestDataSpace = Dataspace::V0_SRGB;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002101 *outHdrDataSpace = Dataspace::UNKNOWN;
2102
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002103 for (const auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu01591c92018-05-22 12:03:00 -07002104 switch (layer->getDataSpace()) {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002105 case Dataspace::V0_SCRGB:
2106 case Dataspace::V0_SCRGB_LINEAR:
Valerie Hau9758ae02018-10-09 16:05:09 -07002107 case Dataspace::BT2020:
2108 case Dataspace::BT2020_ITU:
2109 case Dataspace::BT2020_LINEAR:
2110 case Dataspace::DISPLAY_BT2020:
2111 bestDataSpace = Dataspace::DISPLAY_BT2020;
2112 break;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002113 case Dataspace::DISPLAY_P3:
Chia-I Wube02ec02018-05-18 10:59:36 -07002114 bestDataSpace = Dataspace::DISPLAY_P3;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002115 break;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002116 case Dataspace::BT2020_PQ:
2117 case Dataspace::BT2020_ITU_PQ:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002118 *outHdrDataSpace = Dataspace::BT2020_PQ;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002119 break;
Peiyong Linf59a7192018-04-25 11:19:31 -07002120 case Dataspace::BT2020_HLG:
2121 case Dataspace::BT2020_ITU_HLG:
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002122 // When there's mixed PQ content and HLG content, we set the HDR
2123 // data space to be BT2020_PQ and convert HLG to PQ.
2124 if (*outHdrDataSpace == Dataspace::UNKNOWN) {
2125 *outHdrDataSpace = Dataspace::BT2020_HLG;
Peiyong Linf59a7192018-04-25 11:19:31 -07002126 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002127 break;
2128 default:
2129 break;
2130 }
Romain Guy54f154a2017-10-24 21:40:32 +01002131 }
2132
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002133 return bestDataSpace;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002134}
2135
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002136// Pick the ColorMode / Dataspace for the display device.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002137void SurfaceFlinger::pickColorMode(const sp<DisplayDevice>& display, ColorMode* outMode,
2138 Dataspace* outDataSpace, RenderIntent* outRenderIntent) const {
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002139 if (mDisplayColorSetting == DisplayColorSetting::UNMANAGED) {
2140 *outMode = ColorMode::NATIVE;
2141 *outDataSpace = Dataspace::UNKNOWN;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002142 *outRenderIntent = RenderIntent::COLORIMETRIC;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002143 return;
Chia-I Wu5c6e4632018-01-11 08:54:38 -08002144 }
Romain Guy88d37dd2017-05-26 17:57:05 -07002145
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002146 Dataspace hdrDataSpace;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002147 Dataspace bestDataSpace = getBestDataspace(display, &hdrDataSpace);
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002148
Peiyong Lindfde5112018-06-05 10:58:41 -07002149 // respect hdrDataSpace only when there is no legacy HDR support
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002150 const bool isHdr = hdrDataSpace != Dataspace::UNKNOWN &&
Peiyong Lindfde5112018-06-05 10:58:41 -07002151 !display->hasLegacyHdrSupport(hdrDataSpace);
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002152 if (isHdr) {
2153 bestDataSpace = hdrDataSpace;
2154 }
2155
Chia-I Wu0d711262018-05-21 15:19:35 -07002156 RenderIntent intent;
2157 switch (mDisplayColorSetting) {
2158 case DisplayColorSetting::MANAGED:
2159 case DisplayColorSetting::UNMANAGED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002160 intent = isHdr ? RenderIntent::TONE_MAP_COLORIMETRIC : RenderIntent::COLORIMETRIC;
Chia-I Wu0d711262018-05-21 15:19:35 -07002161 break;
2162 case DisplayColorSetting::ENHANCED:
Chia-I Wuc4b08bd2018-05-29 12:57:23 -07002163 intent = isHdr ? RenderIntent::TONE_MAP_ENHANCE : RenderIntent::ENHANCE;
Chia-I Wu0d711262018-05-21 15:19:35 -07002164 break;
2165 default: // vendor display color setting
2166 intent = static_cast<RenderIntent>(mDisplayColorSetting);
2167 break;
2168 }
Chia-I Wube02ec02018-05-18 10:59:36 -07002169
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002170 display->getBestColorMode(bestDataSpace, intent, outDataSpace, outMode, outRenderIntent);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -06002171}
2172
David Sodmanfa9b2af2017-12-24 13:28:59 -08002173void SurfaceFlinger::beginFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002174{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002175 bool dirty = !display->getDirtyRegion(false).isEmpty();
2176 bool empty = display->getVisibleLayersSortedByZ().size() == 0;
2177 bool wasEmpty = !display->lastCompositionHadVisibleLayers;
David Sodman2b406362017-12-15 13:33:47 -08002178
David Sodmanfa9b2af2017-12-24 13:28:59 -08002179 // If nothing has changed (!dirty), don't recompose.
2180 // If something changed, but we don't currently have any visible layers,
2181 // and didn't when we last did a composition, then skip it this time.
2182 // The second rule does two things:
2183 // - When all layers are removed from a display, we'll emit one black
2184 // frame, then nothing more until we get new layers.
2185 // - When a display is created with a private layer stack, we won't
2186 // emit any black frames until a layer is added to the layer stack.
2187 bool mustRecompose = dirty && !(empty && wasEmpty);
David Sodman2b406362017-12-15 13:33:47 -08002188
Dominik Laskowski075d3172018-05-24 15:50:06 -07002189 const char flagPrefix[] = {'-', '+'};
2190 static_cast<void>(flagPrefix);
2191 ALOGV_IF(display->isVirtual(), "%s: %s composition for %s (%cdirty %cempty %cwasEmpty)",
2192 __FUNCTION__, mustRecompose ? "doing" : "skipping", display->getDebugName().c_str(),
2193 flagPrefix[dirty], flagPrefix[empty], flagPrefix[wasEmpty]);
David Sodman2b406362017-12-15 13:33:47 -08002194
David Sodmanfa9b2af2017-12-24 13:28:59 -08002195 display->beginFrame(mustRecompose);
David Sodman2b406362017-12-15 13:33:47 -08002196
David Sodmanfa9b2af2017-12-24 13:28:59 -08002197 if (mustRecompose) {
2198 display->lastCompositionHadVisibleLayers = !empty;
David Sodman2b406362017-12-15 13:33:47 -08002199 }
2200}
2201
David Sodmanfa9b2af2017-12-24 13:28:59 -08002202void SurfaceFlinger::prepareFrame(const sp<DisplayDevice>& display)
David Sodman2b406362017-12-15 13:33:47 -08002203{
David Sodmanfa9b2af2017-12-24 13:28:59 -08002204 if (!display->isPoweredOn()) {
2205 return;
David Sodman2b406362017-12-15 13:33:47 -08002206 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002207
Dominik Laskowski05275f12018-11-01 15:03:24 -07002208 status_t result = display->prepareFrame(getHwComposer(),
2209 getBE().mCompositionInfo[display->getDisplayToken()]);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002210 ALOGE_IF(result != NO_ERROR, "prepareFrame failed for %s: %d (%s)",
2211 display->getDebugName().c_str(), result, strerror(-result));
David Sodman2b406362017-12-15 13:33:47 -08002212}
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002213
David Sodmanfa9b2af2017-12-24 13:28:59 -08002214void SurfaceFlinger::doComposition(const sp<DisplayDevice>& display, bool repaintEverything) {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002215 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002216 ALOGV("doComposition");
2217
David Sodmanfa9b2af2017-12-24 13:28:59 -08002218 if (display->isPoweredOn()) {
2219 // transform the dirty region into this screen's coordinate space
2220 const Region dirtyRegion(display->getDirtyRegion(repaintEverything));
Mathias Agopian02b95102012-11-05 17:50:57 -08002221
David Sodmanfa9b2af2017-12-24 13:28:59 -08002222 // repaint the framebuffer (if needed)
2223 doDisplayComposition(display, dirtyRegion);
Mathias Agopian02b95102012-11-05 17:50:57 -08002224
David Sodmanfa9b2af2017-12-24 13:28:59 -08002225 display->dirtyRegion.clear();
2226 display->flip();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002227 }
David Sodmanfa9b2af2017-12-24 13:28:59 -08002228 postFramebuffer(display);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002229}
2230
David Sodmanfa9b2af2017-12-24 13:28:59 -08002231void SurfaceFlinger::postFrame()
2232{
2233 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002234 const auto display = getDefaultDisplayDeviceLocked();
2235 if (display && getHwComposer().isConnected(*display->getId())) {
2236 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002237 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2238 logFrameStats();
2239 }
2240 }
2241}
2242
2243void SurfaceFlinger::postFramebuffer(const sp<DisplayDevice>& display)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002244{
Mathias Agopian841cde52012-03-01 15:44:37 -08002245 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002246 ALOGV("postFramebuffer");
Mathias Agopianb048cef2012-02-04 15:44:04 -08002247
David Sodmanfa9b2af2017-12-24 13:28:59 -08002248 mPostFramebufferTime = systemTime();
Jesse Hallc5c5a142012-07-02 16:49:28 -07002249
David Sodmanfa9b2af2017-12-24 13:28:59 -08002250 if (display->isPoweredOn()) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07002251 const auto displayId = display->getId();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002252 if (displayId) {
2253 getHwComposer().presentAndGetReleaseFences(*displayId);
Mathias Agopian2a231842012-09-24 18:12:35 -07002254 }
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002255 display->onPresentDisplayCompleted();
David Sodman15094112018-10-11 09:39:37 -07002256 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002257 sp<Fence> releaseFence = Fence::NO_FENCE;
David Sodman15094112018-10-11 09:39:37 -07002258
Chia-I Wu7b549592017-11-15 09:14:57 -08002259 // The layer buffer from the previous frame (if any) is released
2260 // by HWC only when the release fence from this frame (if any) is
2261 // signaled. Always get the release fence from HWC first.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002262 if (displayId && layer->hasHwcLayer(*displayId)) {
2263 releaseFence = getHwComposer().getLayerReleaseFence(*displayId,
2264 layer->getHwcLayer(*displayId));
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002265 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002266
2267 // If the layer was client composited in the previous frame, we
2268 // need to merge with the previous client target acquire fence.
2269 // Since we do not track that, always merge with the current
2270 // client target acquire fence when it is available, even though
2271 // this is suboptimal.
David Sodman15094112018-10-11 09:39:37 -07002272 if (layer->getCompositionType(displayId) == HWC2::Composition::Client) {
Chia-I Wu7b549592017-11-15 09:14:57 -08002273 releaseFence = Fence::merge("LayerRelease", releaseFence,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002274 display->getClientTargetAcquireFence());
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07002275 }
Chia-I Wu7b549592017-11-15 09:14:57 -08002276
David Sodman15094112018-10-11 09:39:37 -07002277 layer->getBE().onLayerDisplayed(releaseFence);
Dan Stoza9e56aa02015-11-02 13:00:03 -08002278 }
Chia-I Wu83806892017-11-16 10:50:20 -08002279
2280 // We've got a list of layers needing fences, that are disjoint with
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002281 // display->getVisibleLayersSortedByZ. The best we can do is to
Chia-I Wu83806892017-11-16 10:50:20 -08002282 // supply them with the present fence.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002283 if (!display->getLayersNeedingFences().isEmpty()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002284 sp<Fence> presentFence =
Lloyd Pique441d5042018-10-18 16:49:51 -07002285 displayId ? getHwComposer().getPresentFence(*displayId) : Fence::NO_FENCE;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002286 for (auto& layer : display->getLayersNeedingFences()) {
David Sodmanb8af7922017-12-21 15:17:55 -08002287 layer->getBE().onLayerDisplayed(presentFence);
Chia-I Wu83806892017-11-16 10:50:20 -08002288 }
2289 }
2290
Dominik Laskowski075d3172018-05-24 15:50:06 -07002291 if (displayId) {
2292 getHwComposer().clearReleaseFences(*displayId);
Jesse Hallef194142012-06-14 14:45:17 -07002293 }
Jamie Gennise8696a42012-01-15 18:54:57 -08002294 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002295}
2296
Mathias Agopian87baae12012-07-31 12:38:26 -07002297void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002298{
Mathias Agopian841cde52012-03-01 15:44:37 -08002299 ATRACE_CALL();
2300
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002301 // here we keep a copy of the drawing state (that is the state that's
2302 // going to be overwritten by handleTransactionLocked()) outside of
2303 // mStateLock so that the side-effects of the State assignment
2304 // don't happen with mStateLock held (which can cause deadlocks).
2305 State drawingState(mDrawingState);
2306
Mathias Agopianca4d3602011-05-19 15:38:14 -07002307 Mutex::Autolock _l(mStateLock);
2308 const nsecs_t now = systemTime();
2309 mDebugInTransaction = now;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002310
Mathias Agopianca4d3602011-05-19 15:38:14 -07002311 // Here we're guaranteed that some transaction flags are set
2312 // so we can call handleTransactionLocked() unconditionally.
2313 // We call getTransactionFlags(), which will also clear the flags,
2314 // with mStateLock held to guarantee that mCurrentState won't change
2315 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002316
Jorim Jaggif15c3be2018-04-12 12:56:58 +01002317 mVsyncModulator.onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002318 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002319 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002320
Mathias Agopianca4d3602011-05-19 15:38:14 -07002321 mLastTransactionTime = systemTime() - now;
2322 mDebugInTransaction = 0;
2323 invalidateHwcGeometry();
2324 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002325}
2326
Lloyd Piqueba04e622017-12-14 17:11:26 -08002327void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2328 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002329 const std::optional<DisplayIdentificationInfo> info =
2330 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002331
Dominik Laskowski075d3172018-05-24 15:50:06 -07002332 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002333 continue;
2334 }
2335
Lloyd Piqueba04e622017-12-14 17:11:26 -08002336 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002337 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002338 ALOGV("Creating display %s", to_string(info->id).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07002339 mPhysicalDisplayTokens[info->id] = new BBinder();
2340 DisplayDeviceState state;
2341 state.displayId = info->id;
2342 state.isSecure = true; // All physical displays are currently considered secure.
2343 state.displayName = info->name;
2344 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2345 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002346 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002347 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002348 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002349
Dominik Laskowski075d3172018-05-24 15:50:06 -07002350 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2351 if (index >= 0) {
2352 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2353 mInterceptor->saveDisplayDeletion(state.sequenceId);
2354 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002355 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002356 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002357 }
2358
2359 processDisplayChangesLocked();
2360 }
2361
2362 mPendingHotplugEvents.clear();
2363}
2364
Lloyd Pique99d3da52018-01-22 17:48:03 -08002365sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002366 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
2367 const DisplayDeviceState& state, const sp<DisplaySurface>& dispSurface,
2368 const sp<IGraphicBufferProducer>& producer) {
2369 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002370 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002371 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002372 creationArgs.isSecure = state.isSecure;
2373 creationArgs.displaySurface = dispSurface;
2374 creationArgs.hasWideColorGamut = false;
2375 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002376
Dominik Laskowski075d3172018-05-24 15:50:06 -07002377 const bool isInternalDisplay = displayId && displayId == getInternalDisplayId();
2378 creationArgs.isPrimary = isInternalDisplay;
2379
2380 if (useColorManagement && displayId) {
2381 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002382 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002383 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002384 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002385 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002386
Dominik Laskowski7e045462018-05-30 13:02:02 -07002387 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002388 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002389 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002390 }
tangrobin6753a022018-08-10 10:58:54 +08002391 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002392
Dominik Laskowski075d3172018-05-24 15:50:06 -07002393 if (displayId) {
2394 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002395 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002396 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002397 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002398
Lloyd Pique90c115d2018-09-18 21:39:42 -07002399 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002400 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002401 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002402
Lloyd Pique99d3da52018-01-22 17:48:03 -08002403 // Make sure that composition can never be stalled by a virtual display
2404 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002405 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002406 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002407 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2408 }
2409
Dominik Laskowski075d3172018-05-24 15:50:06 -07002410 creationArgs.displayInstallOrientation =
2411 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002412
Lloyd Pique99d3da52018-01-22 17:48:03 -08002413 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002414 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002415
Lloyd Pique90c115d2018-09-18 21:39:42 -07002416 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002417
2418 if (maxFrameBufferAcquiredBuffers >= 3) {
2419 nativeWindowSurface->preallocateBuffers();
2420 }
2421
2422 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002423 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002424 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002425 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002426 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002427 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002428 setActiveColorModeInternal(display, defaultColorMode, defaultDataSpace,
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002429 RenderIntent::COLORIMETRIC);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002430 if (!state.isVirtual()) {
2431 LOG_ALWAYS_FATAL_IF(!displayId);
2432 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002433 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002434
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002435 display->setLayerStack(state.layerStack);
2436 display->setProjection(state.orientation, state.viewport, state.frame);
2437 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002438
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002439 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002440}
2441
Lloyd Pique347200f2017-12-14 17:00:15 -08002442void SurfaceFlinger::processDisplayChangesLocked() {
2443 // here we take advantage of Vector's copy-on-write semantics to
2444 // improve performance by skipping the transaction entirely when
2445 // know that the lists are identical
2446 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2447 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2448 if (!curr.isIdenticalTo(draw)) {
2449 mVisibleRegionsDirty = true;
2450 const size_t cc = curr.size();
2451 size_t dc = draw.size();
2452
2453 // find the displays that were removed
2454 // (ie: in drawing state but not in current state)
2455 // also handle displays that changed
2456 // (ie: displays that are in both lists)
2457 for (size_t i = 0; i < dc;) {
2458 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2459 if (j < 0) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002460 // Save display IDs before disconnecting.
2461 const auto internalDisplayId = getInternalDisplayId();
2462 const auto externalDisplayId = getExternalDisplayId();
2463
Lloyd Pique347200f2017-12-14 17:00:15 -08002464 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002465 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
2466 display->disconnect(getHwComposer());
2467 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002468 if (internalDisplayId && internalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002469 if (mUseScheduler) {
2470 mScheduler->hotplugReceived(mAppConnectionHandle,
2471 EventThread::DisplayType::Primary, false);
2472 } else {
2473 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
2474 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002475 } else if (externalDisplayId && externalDisplayId == draw[i].displayId) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002476 if (mUseScheduler) {
2477 mScheduler->hotplugReceived(mAppConnectionHandle,
2478 EventThread::DisplayType::External, false);
2479 } else {
2480 mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
2481 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002482 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002483 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002484 } else {
2485 // this display is in both lists. see if something changed.
2486 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002487 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002488 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2489 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2490 if (state_binder != draw_binder) {
2491 // changing the surface is like destroying and
2492 // recreating the DisplayDevice, so we just remove it
2493 // from the drawing state, so that it get re-added
2494 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002495 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2496 display->disconnect(getHwComposer());
2497 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002498 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002499 mDrawingState.displays.removeItemsAt(i);
2500 dc--;
2501 // at this point we must loop to the next item
2502 continue;
2503 }
2504
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002505 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002506 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002507 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002508 }
2509 if ((state.orientation != draw[i].orientation) ||
2510 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002511 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002512 }
2513 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002514 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002515 }
2516 }
2517 }
2518 ++i;
2519 }
2520
2521 // find displays that were added
2522 // (ie: in current state but not in drawing state)
2523 for (size_t i = 0; i < cc; i++) {
2524 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2525 const DisplayDeviceState& state(curr[i]);
2526
2527 sp<DisplaySurface> dispSurface;
2528 sp<IGraphicBufferProducer> producer;
2529 sp<IGraphicBufferProducer> bqProducer;
2530 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002531 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002532
Dominik Laskowski075d3172018-05-24 15:50:06 -07002533 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002534 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002535 // Virtual displays without a surface are dormant:
2536 // they have external state (layer stack, projection,
2537 // etc.) but no internal state (i.e. a DisplayDevice).
2538 if (state.surface != nullptr) {
2539 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002540 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002541 int width = 0;
2542 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2543 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2544 int height = 0;
2545 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2546 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2547 int intFormat = 0;
2548 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2549 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002550 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002551
Dominik Laskowski075d3172018-05-24 15:50:06 -07002552 displayId =
2553 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002554 }
2555
2556 // TODO: Plumb requested format back up to consumer
2557
2558 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002559 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002560 bqProducer, bqConsumer,
2561 state.displayName);
2562
2563 dispSurface = vds;
2564 producer = vds;
2565 }
2566 } else {
2567 ALOGE_IF(state.surface != nullptr,
2568 "adding a supported display, but rendering "
2569 "surface is provided (%p), ignoring it",
2570 state.surface.get());
2571
Dominik Laskowski075d3172018-05-24 15:50:06 -07002572 displayId = state.displayId;
2573 LOG_ALWAYS_FATAL_IF(!displayId);
2574 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002575 producer = bqProducer;
2576 }
2577
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002578 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002579 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002580 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002581 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002582 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002583 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002584 LOG_ALWAYS_FATAL_IF(!displayId);
2585
2586 if (displayId == getInternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002587 if (mUseScheduler) {
2588 mScheduler->hotplugReceived(mAppConnectionHandle,
2589 EventThread::DisplayType::Primary,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002590 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002591 } else {
2592 mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
2593 true);
2594 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002595 } else if (displayId == getExternalDisplayId()) {
Ana Krulec98b5b242018-08-10 15:03:23 -07002596 if (mUseScheduler) {
2597 mScheduler->hotplugReceived(mAppConnectionHandle,
2598 EventThread::DisplayType::External,
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002599 true);
Ana Krulec98b5b242018-08-10 15:03:23 -07002600 } else {
2601 mEventThread->onHotplugReceived(EventThread::DisplayType::External,
2602 true);
2603 }
Dominik Laskowski00a6fa22018-06-06 16:42:02 -07002604 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002605 }
2606 }
2607 }
2608 }
2609 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002610
2611 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002612}
2613
Mathias Agopian87baae12012-07-31 12:38:26 -07002614void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002615{
Dan Stoza7dde5992015-05-22 09:51:44 -07002616 // Notify all layers of available frames
Robert Carr2047fae2016-11-28 14:09:09 -08002617 mCurrentState.traverseInZOrder([](Layer* layer) {
2618 layer->notifyAvailableFrames();
2619 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002620
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002621 /*
2622 * Traversal of the children
2623 * (perform the transaction for each of them if needed)
2624 */
2625
Robert Carr720e5062018-07-30 17:45:14 -07002626 bool inputChanged = false;
Mathias Agopian3559b072012-08-15 13:46:03 -07002627 if (transactionFlags & eTraversalNeeded) {
Robert Carr2047fae2016-11-28 14:09:09 -08002628 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002629 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002630 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002631
2632 const uint32_t flags = layer->doTransaction(0);
2633 if (flags & Layer::eVisibleRegion)
2634 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002635
2636 if (flags & Layer::eInputInfoChanged) {
2637 inputChanged = true;
2638 }
Robert Carr2047fae2016-11-28 14:09:09 -08002639 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002640 }
2641
2642 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002643 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002644 */
2645
Mathias Agopiane57f2922012-08-09 16:29:12 -07002646 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002647 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002648 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002649 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002650
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002651 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002652 // The transform hint might have changed for some layers
2653 // (either because a display has changed, or because a layer
2654 // as changed).
2655 //
2656 // Walk through all the layers in currentLayers,
2657 // and update their transform hint.
2658 //
2659 // If a layer is visible only on a single display, then that
2660 // display is used to calculate the hint, otherwise we use the
2661 // default display.
2662 //
2663 // NOTE: we do this here, rather than in rebuildLayerStacks() so that
2664 // the hint is set before we acquire a buffer from the surface texture.
2665 //
2666 // NOTE: layer transactions have taken place already, so we use their
2667 // drawing state. However, SurfaceFlinger's own transaction has not
2668 // happened yet, so we must use the current state layer list
2669 // (soon to become the drawing state list).
2670 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002671 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002672 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002673 bool first = true;
2674 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002675 // NOTE: we rely on the fact that layers are sorted by
2676 // layerStack first (so we don't have to traverse the list
2677 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002678 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002679 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002680 currentlayerStack = layerStack;
2681 // figure out if this layerstack is mirrored
2682 // (more than one display) if so, pick the default display,
2683 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002684 hintDisplay = nullptr;
2685 for (const auto& [token, display] : mDisplays) {
2686 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2687 if (hintDisplay) {
2688 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002689 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002690 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002691 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002692 }
2693 }
2694 }
2695 }
Chet Haase91d25932013-04-11 15:24:55 -07002696
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002697 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002698 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2699 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002700
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002701 // could be null when this layer is using a layerStack
2702 // that is not visible on any display. Also can occur at
2703 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002704 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002705 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002706
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002707 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002708 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002709 if (hintDisplay) {
2710 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002711 }
Robert Carr2047fae2016-11-28 14:09:09 -08002712
2713 first = false;
2714 });
Mathias Agopian84300952012-11-21 16:02:13 -08002715 }
2716
2717
Mathias Agopian3559b072012-08-15 13:46:03 -07002718 /*
2719 * Perform our own transaction if needed
2720 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002721
2722 if (mLayersAdded) {
2723 mLayersAdded = false;
2724 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002725 mVisibleRegionsDirty = true;
2726 }
2727
2728 // some layers might have been removed, so
2729 // we need to update the regions they're exposing.
2730 if (mLayersRemoved) {
2731 mLayersRemoved = false;
2732 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002733 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002734 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002735 // this layer is not visible anymore
2736 // TODO: we could traverse the tree from front to back and
2737 // compute the actual visible region
2738 // TODO: we could cache the transformed region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002739 Region visibleReg;
2740 visibleReg.set(layer->computeScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002741 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002742 }
Robert Carr2047fae2016-11-28 14:09:09 -08002743 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002744 }
2745
2746 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002747
Vishnu Nairde19f852018-12-18 16:11:53 -08002748 if (inputChanged || mVisibleRegionsDirty) {
Robert Carr720e5062018-07-30 17:45:14 -07002749 updateInputWindows();
2750 }
chaviwfbe5d9c2018-12-26 12:23:37 -08002751 executeInputWindowCommands();
Robert Carr720e5062018-07-30 17:45:14 -07002752
Riley Andrews03414a12014-07-01 14:22:59 -07002753 updateCursorAsync();
2754}
2755
Robert Carr720e5062018-07-30 17:45:14 -07002756void SurfaceFlinger::updateInputWindows() {
2757 ATRACE_CALL();
2758
Vishnu Nairde19f852018-12-18 16:11:53 -08002759 if (mInputFlinger == nullptr) {
2760 return;
2761 }
2762
Robert Carr720e5062018-07-30 17:45:14 -07002763 Vector<InputWindowInfo> inputHandles;
2764
2765 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2766 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002767 // When calculating the screen bounds we ignore the transparent region since it may
2768 // result in an unwanted offset.
2769 inputHandles.add(layer->fillInputInfo(
2770 layer->computeScreenBounds(false /* reduceTransparentRegion */)));
Robert Carr720e5062018-07-30 17:45:14 -07002771 }
2772 });
2773 mInputFlinger->setInputWindows(inputHandles);
2774}
2775
chaviwfbe5d9c2018-12-26 12:23:37 -08002776void SurfaceFlinger::executeInputWindowCommands() {
2777 if (!mInputFlinger) {
2778 return;
2779 }
2780
2781 for (const auto& transferTouchFocusCommand : mInputWindowCommands.transferTouchFocusCommands) {
2782 if (transferTouchFocusCommand.fromToken != nullptr &&
2783 transferTouchFocusCommand.toToken != nullptr &&
2784 transferTouchFocusCommand.fromToken != transferTouchFocusCommand.toToken) {
2785 mInputFlinger->transferTouchFocus(transferTouchFocusCommand.fromToken,
2786 transferTouchFocusCommand.toToken);
2787 }
2788 }
2789
2790 mInputWindowCommands.clear();
2791}
2792
Riley Andrews03414a12014-07-01 14:22:59 -07002793void SurfaceFlinger::updateCursorAsync()
2794{
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002795 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002796 if (!display->getId()) {
Riley Andrews03414a12014-07-01 14:22:59 -07002797 continue;
2798 }
Dan Stoza9e56aa02015-11-02 13:00:03 -08002799
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002800 for (auto& layer : display->getVisibleLayersSortedByZ()) {
2801 layer->updateCursorPosition(display);
Riley Andrews03414a12014-07-01 14:22:59 -07002802 }
2803 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002804}
2805
chaviw61626f22018-11-15 16:26:27 -08002806void SurfaceFlinger::latchAndReleaseBuffer(const sp<Layer>& layer) {
2807 if (layer->hasReadyFrame()) {
2808 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
2809 if (layer->shouldPresentNow(expectedPresentTime)) {
2810 bool ignored = false;
2811 layer->latchBuffer(ignored, systemTime(), Fence::NO_FENCE);
2812 }
2813 }
2814 layer->releasePendingBuffer(systemTime());
2815}
2816
Mathias Agopian4fec8732012-06-29 14:12:52 -07002817void SurfaceFlinger::commitTransaction()
2818{
Steve Pfetsch598f6d52016-10-25 21:47:58 +00002819 if (!mLayersPendingRemoval.isEmpty()) {
Mathias Agopian4fec8732012-06-29 14:12:52 -07002820 // Notify removed layers now that they can't be drawn from
Robert Carr1f0a16a2016-10-24 16:27:39 -07002821 for (const auto& l : mLayersPendingRemoval) {
2822 recordBufferingStats(l->getName().string(),
2823 l->getOccupancyHistory(true));
Robert Carr2e102c92018-10-23 12:11:15 -07002824
2825 // We need to release the HWC layers when the Layer is removed
2826 // from the current state otherwise the HWC layer just continues
2827 // showing at its last configured state until we eventually
2828 // abandon the buffer queue.
2829 if (l->isRemovedFromCurrentState()) {
Robert Carr6fb1a7e2018-12-11 12:07:25 -08002830 l->destroyHwcLayersForAllDisplays();
2831 latchAndReleaseBuffer(l);
Robert Carr2e102c92018-10-23 12:11:15 -07002832 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002833 }
2834 mLayersPendingRemoval.clear();
2835 }
2836
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002837 // If this transaction is part of a window animation then the next frame
2838 // we composite should be considered an animation as well.
2839 mAnimCompositionPending = mAnimTransactionPending;
2840
Mathias Agopian4fec8732012-06-29 14:12:52 -07002841 mDrawingState = mCurrentState;
Chia-I Wu28f320b2018-05-03 11:02:56 -07002842 // clear the "changed" flags in current state
2843 mCurrentState.colorMatrixChanged = false;
2844
Robert Carr1f0a16a2016-10-24 16:27:39 -07002845 mDrawingState.traverseInZOrder([](Layer* layer) {
2846 layer->commitChildList();
2847 });
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002848 mTransactionPending = false;
2849 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002850 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002851}
2852
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002853void SurfaceFlinger::computeVisibleRegions(const sp<const DisplayDevice>& display,
2854 Region& outDirtyRegion, Region& outOpaqueRegion) {
Mathias Agopian841cde52012-03-01 15:44:37 -08002855 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002856 ALOGV("computeVisibleRegions");
Mathias Agopian841cde52012-03-01 15:44:37 -08002857
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002858 Region aboveOpaqueLayers;
2859 Region aboveCoveredLayers;
2860 Region dirty;
2861
Mathias Agopian87baae12012-07-31 12:38:26 -07002862 outDirtyRegion.clear();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002863
Robert Carr2047fae2016-11-28 14:09:09 -08002864 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002865 // start with the whole surface at its current location
2866 const Layer::State& s(layer->getDrawingState());
2867
Jesse Hall01e29052013-02-19 16:13:35 -08002868 // only consider the layers on the given layer stack
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002869 if (!layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
Robert Carr2047fae2016-11-28 14:09:09 -08002870 return;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002871 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002872
Mathias Agopianab028732010-03-16 16:41:46 -07002873 /*
2874 * opaqueRegion: area of a surface that is fully opaque.
2875 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002876 Region opaqueRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002877
2878 /*
2879 * visibleRegion: area of a surface that is visible on screen
2880 * and not fully transparent. This is essentially the layer's
2881 * footprint minus the opaque regions above it.
2882 * Areas covered by a translucent surface are considered visible.
2883 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002884 Region visibleRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002885
2886 /*
2887 * coveredRegion: area of a surface that is covered by all
2888 * visible regions above it (which includes the translucent areas).
2889 */
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002890 Region coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002891
Jesse Halla8026d22012-09-25 13:25:04 -07002892 /*
2893 * transparentRegion: area of a surface that is hinted to be completely
2894 * transparent. This is only used to tell when the layer has no visible
2895 * non-transparent regions and can be removed from the layer list. It
2896 * does not affect the visibleRegion of this layer or any layers
2897 * beneath it. The hint may not be correct if apps don't respect the
2898 * SurfaceView restrictions (which, sadly, some don't).
2899 */
2900 Region transparentRegion;
2901
Mathias Agopianab028732010-03-16 16:41:46 -07002902
2903 // handle hidden surfaces by setting the visible region to empty
Mathias Agopianda27af92012-09-13 18:17:13 -07002904 if (CC_LIKELY(layer->isVisible())) {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002905 const bool translucent = !layer->isOpaque(s);
Robert Carr1f0a16a2016-10-24 16:27:39 -07002906 Rect bounds(layer->computeScreenBounds());
Robert Carr720e5062018-07-30 17:45:14 -07002907
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002908 visibleRegion.set(bounds);
Peiyong Linefefaac2018-08-17 12:27:51 -07002909 ui::Transform tr = layer->getTransform();
Mathias Agopianab028732010-03-16 16:41:46 -07002910 if (!visibleRegion.isEmpty()) {
2911 // Remove the transparent area from the visible region
2912 if (translucent) {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002913 if (tr.preserveRects()) {
2914 // transform the transparent region
Lloyd Pique0449b0f2018-12-20 16:23:45 -08002915 transparentRegion = tr.transform(layer->getActiveTransparentRegion(s));
Mathias Agopian4fec8732012-06-29 14:12:52 -07002916 } else {
Dan Stoza22f7fc42016-05-10 16:19:53 -07002917 // transformation too complex, can't do the
2918 // transparent region optimization.
2919 transparentRegion.clear();
Mathias Agopian4fec8732012-06-29 14:12:52 -07002920 }
Mathias Agopianab028732010-03-16 16:41:46 -07002921 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002922
Mathias Agopianab028732010-03-16 16:41:46 -07002923 // compute the opaque region
Robert Carr1f0a16a2016-10-24 16:27:39 -07002924 const int32_t layerOrientation = tr.getOrientation();
Jorim Jaggi039bbb82017-09-06 18:12:05 +02002925 if (layer->getAlpha() == 1.0f && !translucent &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07002926 layer->getRoundedCornerState().radius == 0.0f &&
Peiyong Linefefaac2018-08-17 12:27:51 -07002927 ((layerOrientation & ui::Transform::ROT_INVALID) == false)) {
Mathias Agopianab028732010-03-16 16:41:46 -07002928 // the opaque region is the layer's footprint
2929 opaqueRegion = visibleRegion;
2930 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002931 }
2932 }
2933
Robert Carre5f4f692018-01-12 13:12:28 -08002934 if (visibleRegion.isEmpty()) {
2935 layer->clearVisibilityRegions();
2936 return;
2937 }
2938
Mathias Agopianab028732010-03-16 16:41:46 -07002939 // Clip the covered region to the visible region
2940 coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
2941
2942 // Update aboveCoveredLayers for next (lower) layer
2943 aboveCoveredLayers.orSelf(visibleRegion);
2944
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002945 // subtract the opaque region covered by the layers above us
2946 visibleRegion.subtractSelf(aboveOpaqueLayers);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002947
2948 // compute this layer's dirty region
2949 if (layer->contentDirty) {
2950 // we need to invalidate the whole region
2951 dirty = visibleRegion;
2952 // as well, as the old visible region
Mathias Agopian4fec8732012-06-29 14:12:52 -07002953 dirty.orSelf(layer->visibleRegion);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002954 layer->contentDirty = false;
2955 } else {
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002956 /* compute the exposed region:
Mathias Agopianab028732010-03-16 16:41:46 -07002957 * the exposed region consists of two components:
2958 * 1) what's VISIBLE now and was COVERED before
2959 * 2) what's EXPOSED now less what was EXPOSED before
2960 *
2961 * note that (1) is conservative, we start with the whole
2962 * visible region but only keep what used to be covered by
2963 * something -- which mean it may have been exposed.
2964 *
2965 * (2) handles areas that were not covered by anything but got
2966 * exposed because of a resize.
Mathias Agopiana8d44f72009-06-28 02:54:16 -07002967 */
Mathias Agopianab028732010-03-16 16:41:46 -07002968 const Region newExposed = visibleRegion - coveredRegion;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002969 const Region oldVisibleRegion = layer->visibleRegion;
2970 const Region oldCoveredRegion = layer->coveredRegion;
Mathias Agopianab028732010-03-16 16:41:46 -07002971 const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
2972 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002973 }
2974 dirty.subtractSelf(aboveOpaqueLayers);
2975
2976 // accumulate to the screen dirty region
Mathias Agopian87baae12012-07-31 12:38:26 -07002977 outDirtyRegion.orSelf(dirty);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002978
Mathias Agopianab028732010-03-16 16:41:46 -07002979 // Update aboveOpaqueLayers for next (lower) layer
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002980 aboveOpaqueLayers.orSelf(opaqueRegion);
Andreas Huber8b42e8a2010-08-16 08:49:37 -07002981
Jesse Halla8026d22012-09-25 13:25:04 -07002982 // Store the visible region in screen space
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002983 layer->setVisibleRegion(visibleRegion);
2984 layer->setCoveredRegion(coveredRegion);
Jesse Halla8026d22012-09-25 13:25:04 -07002985 layer->setVisibleNonTransparentRegion(
2986 visibleRegion.subtract(transparentRegion));
Robert Carr2047fae2016-11-28 14:09:09 -08002987 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002988
Mathias Agopian87baae12012-07-31 12:38:26 -07002989 outOpaqueRegion = aboveOpaqueLayers;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002990}
2991
Chia-I Wuab0c3192017-08-01 11:29:00 -07002992void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002993 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002994 if (layer->belongsToDisplay(display->getLayerStack(), display->isPrimary())) {
2995 display->dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002996 }
2997 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002998}
2999
Dan Stoza6b9454d2014-11-07 16:00:59 -08003000bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003001{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003002 ALOGV("handlePageFlip");
3003
Brian Andersond6927fb2016-07-23 23:37:30 -07003004 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003005
Mathias Agopian4fec8732012-06-29 14:12:52 -07003006 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003007 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003008 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003009
3010 // Store the set of layers that need updates. This set must not change as
3011 // buffers are being latched, as this could result in a deadlock.
3012 // Example: Two producers share the same command stream and:
3013 // 1.) Layer 0 is latched
3014 // 2.) Layer 0 gets a new frame
3015 // 2.) Layer 1 gets a new frame
3016 // 3.) Layer 1 is latched.
3017 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3018 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08003019 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003020 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003021 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003022 const nsecs_t expectedPresentTime = mPrimaryDispSync->expectedPresentTime();
3023 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003024 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003025 } else {
3026 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003027 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003028 } else {
3029 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003030 }
Robert Carr2047fae2016-11-28 14:09:09 -08003031 });
3032
Lloyd Piquef2c79392018-12-20 16:23:33 -08003033 if (!mLayersWithQueuedFrames.empty()) {
3034 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3035 // writes to Layer current state. See also b/119481871
3036 Mutex::Autolock lock(mStateLock);
3037
3038 for (auto& layer : mLayersWithQueuedFrames) {
3039 const Region dirty(layer->latchBuffer(visibleRegions, latchTime, getBE().flushFence));
3040 layer->useSurfaceDamage();
3041 invalidateLayerStack(layer, dirty);
3042 if (layer->isBufferLatched()) {
3043 newDataLatched = true;
3044 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003045 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003046 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003047
Alec Mouri86770e52018-09-24 22:40:58 +00003048 // Clear the renderengine fence here...
3049 // downstream code assumes that a cleared fence == NO_FENCE, so reassign to
3050 // clear instead of sp::clear.
3051 getBE().flushFence = Fence::NO_FENCE;
3052
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003053 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003054
Vishnu Nairde19f852018-12-18 16:11:53 -08003055 if (visibleRegions) {
3056 // Update input window info if the layer receives its first buffer.
3057 updateInputWindows();
3058 }
3059
Dan Stoza6b9454d2014-11-07 16:00:59 -08003060 // If we will need to wake up at some time in the future to deal with a
3061 // queued frame that shouldn't be displayed during this vsync period, wake
3062 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003063 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003064 signalLayerUpdate();
3065 }
3066
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003067 // enter boot animation on first buffer latch
3068 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3069 ALOGI("Enter boot animation");
3070 mBootStage = BootStage::BOOTANIMATION;
3071 }
3072
Dan Stoza6b9454d2014-11-07 16:00:59 -08003073 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003074 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003075}
3076
Mathias Agopianad456f92011-01-13 17:53:01 -08003077void SurfaceFlinger::invalidateHwcGeometry()
3078{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003079 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003080}
3081
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003082void SurfaceFlinger::doDisplayComposition(const sp<DisplayDevice>& display,
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003083 const Region& inDirtyRegion) {
Dan Stoza71433162014-02-04 16:22:36 -08003084 // We only need to actually compose the display if:
3085 // 1) It is being handled by hardware composer, which may need this to
3086 // keep its virtual display state machine in sync, or
3087 // 2) There is work to be done (the dirty region isn't empty)
Dominik Laskowski34157762018-10-31 13:07:19 -07003088 if (!display->getId() && inDirtyRegion.isEmpty()) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003089 ALOGV("Skipping display composition");
Dan Stoza71433162014-02-04 16:22:36 -08003090 return;
3091 }
3092
Dan Stoza9e56aa02015-11-02 13:00:03 -08003093 ALOGV("doDisplayComposition");
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003094 if (!doComposeSurfaces(display)) return;
Mathias Agopianda27af92012-09-13 18:17:13 -07003095
3096 // swap buffers (presentation)
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003097 display->queueBuffer(getHwComposer());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003098}
3099
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003100bool SurfaceFlinger::doComposeSurfaces(const sp<DisplayDevice>& display) {
Dan Stoza9e56aa02015-11-02 13:00:03 -08003101 ALOGV("doComposeSurfaces");
Mathias Agopiancd20eb02011-09-22 20:57:04 -07003102
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003103 const Region bounds(display->bounds());
3104 const DisplayRenderArea renderArea(display);
Dominik Laskowski7e045462018-05-30 13:02:02 -07003105 const auto displayId = display->getId();
Lloyd Pique441d5042018-10-18 16:49:51 -07003106 const bool hasClientComposition = getHwComposer().hasClientComposition(displayId);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08003107 ATRACE_INT("hasClientComposition", hasClientComposition);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003108
Peiyong Lind3788632018-09-18 16:01:31 -07003109 mat4 colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003110 bool applyColorMatrix = false;
Dan Stoza9f26a9c2016-06-22 14:51:09 -07003111
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003112 // Framebuffer will live in this scope for GPU composition.
3113 std::unique_ptr<renderengine::BindNativeBufferAsFramebuffer> fbo;
3114
Dan Stoza9e56aa02015-11-02 13:00:03 -08003115 if (hasClientComposition) {
3116 ALOGV("hasClientComposition");
3117
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003118 sp<GraphicBuffer> buf = display->dequeueBuffer();
3119
3120 if (buf == nullptr) {
3121 ALOGW("Dequeuing buffer for display [%s] failed, bailing out of "
3122 "client composition for this frame",
3123 display->getDisplayName().c_str());
3124 return false;
3125 }
3126
3127 // Bind the framebuffer in this scope.
3128 fbo = std::make_unique<renderengine::BindNativeBufferAsFramebuffer>(getRenderEngine(),
3129 buf->getNativeBuffer());
3130
3131 if (fbo->getStatus() != NO_ERROR) {
3132 ALOGW("Binding buffer for display [%s] failed with status: %d",
3133 display->getDisplayName().c_str(), fbo->getStatus());
3134 return false;
3135 }
3136
Peiyong Lin34beb7a2018-03-28 11:57:12 -07003137 Dataspace outputDataspace = Dataspace::UNKNOWN;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003138 if (display->hasWideColorGamut()) {
3139 outputDataspace = display->getCompositionDataSpace();
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003140 }
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003141 getRenderEngine().setOutputDataSpace(outputDataspace);
3142 getRenderEngine().setDisplayMaxLuminance(
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003143 display->getHdrCapabilities().getDesiredMaxLuminance());
Chia-I Wu69bf10f2018-02-20 13:04:50 -08003144
Lloyd Pique441d5042018-10-18 16:49:51 -07003145 const bool hasDeviceComposition = getHwComposer().hasDeviceComposition(displayId);
Peiyong Lined531a32018-10-26 18:27:56 -07003146 const bool skipClientColorTransform =
Lloyd Pique441d5042018-10-18 16:49:51 -07003147 getHwComposer()
3148 .hasDisplayCapability(displayId,
3149 HWC2::DisplayCapability::SkipClientColorTransform);
Chia-I Wu8e50e692018-05-04 10:12:37 -07003150
Peiyong Lind3788632018-09-18 16:01:31 -07003151 // Compute the global color transform matrix.
Chia-I Wu8e50e692018-05-04 10:12:37 -07003152 applyColorMatrix = !hasDeviceComposition && !skipClientColorTransform;
3153 if (applyColorMatrix) {
Chia-I Wud49d6692018-06-27 07:17:41 +08003154 colorMatrix = mDrawingState.colorMatrix;
Chia-I Wu8e50e692018-05-04 10:12:37 -07003155 }
3156
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003157 display->setViewportAndProjection();
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003158
Mathias Agopian52bbb1a2012-07-31 19:01:53 -07003159 // Never touch the framebuffer if we don't have any framebuffer layers
Dan Stoza9e56aa02015-11-02 13:00:03 -08003160 if (hasDeviceComposition) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003161 // when using overlays, we assume a fully transparent framebuffer
3162 // NOTE: we could reduce how much we need to clear, for instance
3163 // remove where there are opaque FB layers. however, on some
Mathias Agopian3f844832013-08-07 21:24:32 -07003164 // GPUs doing a "clean slate" clear might be more efficient.
Mathias Agopianb9494d52012-04-18 02:28:45 -07003165 // We'll revisit later if needed.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003166 getRenderEngine().clearWithColor(0, 0, 0, 0);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003167 } else {
Chia-I Wub02087d2017-11-09 10:19:54 -08003168 // we start with the whole screen area and remove the scissor part
Mathias Agopian766dc492012-10-30 18:08:06 -07003169 // we're left with the letterbox region
3170 // (common case is that letterbox ends-up being empty)
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003171 const Region letterbox = bounds.subtract(display->getScissor());
Mathias Agopian766dc492012-10-30 18:08:06 -07003172
3173 // compute the area to clear
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003174 const Region region = display->undefinedRegion.merge(letterbox);
Mathias Agopian766dc492012-10-30 18:08:06 -07003175
Mathias Agopianb9494d52012-04-18 02:28:45 -07003176 // screen is already cleared here
Mathias Agopian87baae12012-07-31 12:38:26 -07003177 if (!region.isEmpty()) {
Mathias Agopianb9494d52012-04-18 02:28:45 -07003178 // can happen with SurfaceView
Chia-I Wu28e3a252018-09-07 12:05:02 -07003179 drawWormhole(region);
Mathias Agopianb9494d52012-04-18 02:28:45 -07003180 }
Mathias Agopiana2f4e562012-04-15 23:34:59 -07003181 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003182
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003183 const Rect& bounds = display->getBounds();
3184 const Rect& scissor = display->getScissor();
3185 if (scissor != bounds) {
3186 // scissor doesn't match the screen's dimensions, so we
3187 // need to clear everything outside of it and enable
3188 // the GL scissor so we don't draw anything where we shouldn't
Mathias Agopian3f844832013-08-07 21:24:32 -07003189
Yiwei Zhange4e26c02018-08-22 13:59:12 -07003190 // enable scissor for this frame
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003191 getRenderEngine().setScissor(scissor);
Mathias Agopianf45c5102012-10-24 16:29:17 -07003192 }
Mathias Agopian85d751c2012-08-29 16:59:24 -07003193 }
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003194
Mathias Agopian85d751c2012-08-29 16:59:24 -07003195 /*
3196 * and then, render the layers targeted at the framebuffer
3197 */
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003198
Dan Stoza9e56aa02015-11-02 13:00:03 -08003199 ALOGV("Rendering client layers");
Peiyong Linefefaac2018-08-17 12:27:51 -07003200 const ui::Transform& displayTransform = display->getTransform();
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003201 bool firstLayer = true;
David Sodmanc1498e62018-09-12 14:36:26 -07003202 for (auto& layer : display->getVisibleLayersSortedByZ()) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003203 const Region clip(bounds.intersect(
David Sodmanc1498e62018-09-12 14:36:26 -07003204 displayTransform.transform(layer->visibleRegion)));
3205 ALOGV("Layer: %s", layer->getName().string());
3206 ALOGV(" Composition type: %s", to_string(layer->getCompositionType(displayId)).c_str());
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003207 if (!clip.isEmpty()) {
David Sodmanc1498e62018-09-12 14:36:26 -07003208 switch (layer->getCompositionType(displayId)) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003209 case HWC2::Composition::Cursor:
3210 case HWC2::Composition::Device:
3211 case HWC2::Composition::Sideband:
3212 case HWC2::Composition::SolidColor: {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003213 LOG_ALWAYS_FATAL_IF(!displayId);
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003214 const Layer::State& state(layer->getDrawingState());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003215 if (layer->getClearClientTarget(*displayId) && !firstLayer &&
Lloyd Pique0449b0f2018-12-20 16:23:45 -08003216 layer->isOpaque(state) && (layer->getAlpha() == 1.0f) &&
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003217 layer->getRoundedCornerState().radius == 0.0f && hasClientComposition) {
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003218 // never clear the very first layer since we're
3219 // guaranteed the FB is already cleared
David Sodmanc1498e62018-09-12 14:36:26 -07003220 layer->clearWithOpenGL(renderArea);
Mathias Agopiancd60f992012-08-16 16:28:27 -07003221 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003222 break;
Mathias Agopiancd60f992012-08-16 16:28:27 -07003223 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003224 case HWC2::Composition::Client: {
Peiyong Lind3788632018-09-18 16:01:31 -07003225 if (layer->hasColorTransform()) {
3226 mat4 tmpMatrix;
3227 if (applyColorMatrix) {
3228 tmpMatrix = mDrawingState.colorMatrix;
3229 }
3230 tmpMatrix *= layer->getColorTransform();
Peiyong Lind3788632018-09-18 16:01:31 -07003231 getRenderEngine().setColorTransform(tmpMatrix);
3232 } else {
3233 getRenderEngine().setColorTransform(colorMatrix);
3234 }
David Sodmanc1498e62018-09-12 14:36:26 -07003235 layer->draw(renderArea, clip);
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003236 break;
3237 }
3238 default:
3239 break;
Mathias Agopian85d751c2012-08-29 16:59:24 -07003240 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003241 } else {
3242 ALOGV(" Skipping for empty clip");
Mathias Agopian85d751c2012-08-29 16:59:24 -07003243 }
Chia-I Wu5e9a43e2018-05-03 14:27:39 -07003244 firstLayer = false;
Mathias Agopian4b2ba532012-03-29 12:23:51 -07003245 }
Mathias Agopianf45c5102012-10-24 16:29:17 -07003246
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003247 // Perform some cleanup steps if we used client composition.
3248 if (hasClientComposition) {
3249 getRenderEngine().setColorTransform(mat4());
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07003250 getRenderEngine().disableScissor();
Alec Mouri0a9c7b82018-11-16 13:05:25 -08003251 display->finishBuffer();
3252 // Clear out error flags here so that we don't wait until next
3253 // composition to log.
3254 getRenderEngine().checkErrors();
3255 }
Michael Lentine3f121fc2014-10-01 11:17:28 -07003256 return true;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003257}
3258
Chia-I Wu28e3a252018-09-07 12:05:02 -07003259void SurfaceFlinger::drawWormhole(const Region& region) const {
Lloyd Pique144e1162017-12-20 16:44:52 -08003260 auto& engine(getRenderEngine());
Chia-I Wu28e3a252018-09-07 12:05:02 -07003261 engine.fillRegionWithColor(region, 0, 0, 0, 0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003262}
3263
Dan Stoza7d89d062015-04-30 13:29:25 -07003264status_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
Mathias Agopianac9fa422013-02-11 16:40:36 -08003265 const sp<IBinder>& handle,
Mathias Agopian67106042013-03-14 19:18:13 -07003266 const sp<IGraphicBufferProducer>& gbc,
Robert Carr1f0a16a2016-10-24 16:27:39 -07003267 const sp<Layer>& lbc,
Robert Carrb89ea9d2018-12-10 13:01:14 -08003268 const sp<Layer>& parent,
3269 bool addToCurrentState)
Mathias Agopian96f08192010-06-02 23:28:45 -07003270{
Dan Stoza7d89d062015-04-30 13:29:25 -07003271 // add this layer to the current state list
3272 {
3273 Mutex::Autolock _l(mStateLock);
Robert Carr1f0a16a2016-10-24 16:27:39 -07003274 if (mNumLayers >= MAX_LAYERS) {
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06003275 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers,
3276 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003277 return NO_MEMORY;
3278 }
Robert Carrb89ea9d2018-12-10 13:01:14 -08003279 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003280 mCurrentState.layersSortedByZ.add(lbc);
Robert Carrb89ea9d2018-12-10 13:01:14 -08003281 } else if (parent == nullptr || parent->isRemovedFromCurrentState()) {
Jorim Jaggi10c985e2018-10-23 11:17:45 +00003282 ALOGE("addClientLayer called with a removed parent");
chaviw61626f22018-11-15 16:26:27 -08003283 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003284 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003285 parent->addChild(lbc);
3286 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003287
Yiwei Zhang243b3782018-05-15 17:40:04 -07003288 if (gbc != nullptr) {
3289 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3290 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3291 mMaxGraphicBufferProducerListSize,
3292 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3293 mGraphicBufferProducerList.size(),
3294 mMaxGraphicBufferProducerListSize, mNumLayers);
3295 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003296 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003297 }
3298
Mathias Agopian96f08192010-06-02 23:28:45 -07003299 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003300 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003301
Dan Stoza7d89d062015-04-30 13:29:25 -07003302 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003303}
3304
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003305uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003306 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003307}
3308
Mathias Agopian3f844832013-08-07 21:24:32 -07003309uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003310 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003311}
3312
Mathias Agopian3f844832013-08-07 21:24:32 -07003313uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003314 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003315}
3316
3317uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003318 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003319 uint32_t old = mTransactionFlags.fetch_or(flags);
Dan Stoza84d619e2018-03-28 17:07:36 -07003320 mVsyncModulator.setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003321 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003322 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003323 }
3324 return old;
3325}
3326
Marissa Wall713b63f2018-10-17 15:42:43 -07003327bool SurfaceFlinger::flushTransactionQueues() {
3328 Mutex::Autolock _l(mStateLock);
3329 auto it = mTransactionQueues.begin();
3330 while (it != mTransactionQueues.end()) {
3331 auto& [applyToken, transactionQueue] = *it;
3332
3333 while (!transactionQueue.empty()) {
3334 const auto& [states, displays, flags] = transactionQueue.front();
3335 if (composerStateContainsUnsignaledFences(states)) {
3336 break;
3337 }
chaviw273171b2018-12-26 11:46:30 -08003338 applyTransactionState(states, displays, flags, mInputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003339 transactionQueue.pop();
3340 }
3341
3342 it = (transactionQueue.empty()) ? mTransactionQueues.erase(it) : std::next(it, 1);
3343 }
3344 return mTransactionQueues.empty();
3345}
3346
chaviwca27f252018-02-06 16:46:39 -08003347bool SurfaceFlinger::containsAnyInvalidClientState(const Vector<ComposerState>& states) {
3348 for (const ComposerState& state : states) {
3349 // Here we need to check that the interface we're given is indeed
3350 // one of our own. A malicious client could give us a nullptr
3351 // IInterface, or one of its own or even one of our own but a
3352 // different type. All these situations would cause us to crash.
3353 if (state.client == nullptr) {
3354 return true;
3355 }
3356
3357 sp<IBinder> binder = IInterface::asBinder(state.client);
3358 if (binder == nullptr) {
3359 return true;
3360 }
3361
3362 if (binder->queryLocalInterface(ISurfaceComposerClient::descriptor) == nullptr) {
3363 return true;
3364 }
3365 }
3366 return false;
3367}
3368
Marissa Wall713b63f2018-10-17 15:42:43 -07003369bool SurfaceFlinger::composerStateContainsUnsignaledFences(const Vector<ComposerState>& states) {
3370 for (const ComposerState& state : states) {
3371 const layer_state_t& s = state.state;
3372 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3373 continue;
3374 }
3375 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
3376 return true;
3377 }
3378 }
3379 return false;
3380}
3381
3382void SurfaceFlinger::setTransactionState(const Vector<ComposerState>& states,
3383 const Vector<DisplayState>& displays, uint32_t flags,
chaviw273171b2018-12-26 11:46:30 -08003384 const sp<IBinder>& applyToken,
3385 const InputWindowCommands& inputWindowCommands) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003386 ATRACE_CALL();
Mathias Agopian698c0872011-06-28 19:09:31 -07003387 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003388
chaviwca27f252018-02-06 16:46:39 -08003389 if (containsAnyInvalidClientState(states)) {
3390 return;
3391 }
3392
Marissa Wall713b63f2018-10-17 15:42:43 -07003393 // If its TransactionQueue already has a pending TransactionState or if it is pending
3394 if (mTransactionQueues.find(applyToken) != mTransactionQueues.end() ||
3395 composerStateContainsUnsignaledFences(states)) {
3396 mTransactionQueues[applyToken].emplace(states, displays, flags);
3397 setTransactionFlags(eTransactionNeeded);
3398 return;
3399 }
3400
chaviw273171b2018-12-26 11:46:30 -08003401 applyTransactionState(states, displays, flags, inputWindowCommands);
Marissa Wall713b63f2018-10-17 15:42:43 -07003402}
3403
3404void SurfaceFlinger::applyTransactionState(const Vector<ComposerState>& states,
chaviw273171b2018-12-26 11:46:30 -08003405 const Vector<DisplayState>& displays, uint32_t flags,
3406 const InputWindowCommands& inputWindowCommands) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003407 uint32_t transactionFlags = 0;
3408
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003409 if (flags & eAnimation) {
3410 // For window updates that are part of an animation we must wait for
3411 // previous animation "frames" to be handled.
3412 while (mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003413 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003414 if (CC_UNLIKELY(err != NO_ERROR)) {
3415 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003416 // caller after a few seconds.
3417 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3418 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003419 mAnimTransactionPending = false;
3420 break;
3421 }
3422 }
3423 }
3424
chaviwca27f252018-02-06 16:46:39 -08003425 for (const DisplayState& display : displays) {
3426 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003427 }
3428
Marissa Walle2ffb422018-10-12 11:33:52 -07003429 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003430 for (const ComposerState& state : states) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003431 clientStateFlags |= setClientStateLocked(state);
chaviwca27f252018-02-06 16:46:39 -08003432 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003433 // If the state doesn't require a traversal and there are callbacks, send them now
3434 if (!(clientStateFlags & eTraversalNeeded)) {
3435 mTransactionCompletedThread.sendCallbacks();
3436 }
3437 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003438
chaviw273171b2018-12-26 11:46:30 -08003439 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3440
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003441 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3442 // anyway. This can be used as a flush mechanism for previous async transactions.
3443 // Empty animation transaction can be used to simulate back-pressure, so also force a
3444 // transaction for empty animation transactions.
3445 if (transactionFlags == 0 &&
3446 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003447 transactionFlags = eTransactionNeeded;
3448 }
3449
Mathias Agopian386aa982011-11-07 21:58:03 -08003450 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003451 if (mInterceptor->isEnabled()) {
3452 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003453 }
Irvel468051e2016-06-13 16:44:44 -07003454
Mathias Agopian386aa982011-11-07 21:58:03 -08003455 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003456 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3457 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003458 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003459
3460 // if this is a synchronous transaction, wait for it to take effect
3461 // before returning.
3462 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003463 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003464 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003465 if (flags & eAnimation) {
3466 mAnimTransactionPending = true;
3467 }
3468 while (mTransactionPending) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003469 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3470 if (CC_UNLIKELY(err != NO_ERROR)) {
3471 // just in case something goes wrong in SF, return to the
3472 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003473 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3474 mTransactionPending = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003475 break;
3476 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003477 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003478 }
3479}
3480
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003481uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3482 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3483 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003484
Mathias Agopiane57f2922012-08-09 16:29:12 -07003485 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003486 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3487
3488 const uint32_t what = s.what;
3489 if (what & DisplayState::eSurfaceChanged) {
3490 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3491 state.surface = s.surface;
3492 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003493 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003494 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003495 if (what & DisplayState::eLayerStackChanged) {
3496 if (state.layerStack != s.layerStack) {
3497 state.layerStack = s.layerStack;
3498 flags |= eDisplayTransactionNeeded;
3499 }
3500 }
3501 if (what & DisplayState::eDisplayProjectionChanged) {
3502 if (state.orientation != s.orientation) {
3503 state.orientation = s.orientation;
3504 flags |= eDisplayTransactionNeeded;
3505 }
3506 if (state.frame != s.frame) {
3507 state.frame = s.frame;
3508 flags |= eDisplayTransactionNeeded;
3509 }
3510 if (state.viewport != s.viewport) {
3511 state.viewport = s.viewport;
3512 flags |= eDisplayTransactionNeeded;
3513 }
3514 }
3515 if (what & DisplayState::eDisplaySizeChanged) {
3516 if (state.width != s.width) {
3517 state.width = s.width;
3518 flags |= eDisplayTransactionNeeded;
3519 }
3520 if (state.height != s.height) {
3521 state.height = s.height;
3522 flags |= eDisplayTransactionNeeded;
3523 }
3524 }
3525
Mathias Agopiane57f2922012-08-09 16:29:12 -07003526 return flags;
3527}
3528
Robert Carrd4ae7f32018-06-07 16:10:57 -07003529bool callingThreadHasUnscopedSurfaceFlingerAccess() {
3530 IPCThreadState* ipc = IPCThreadState::self();
3531 const int pid = ipc->getCallingPid();
3532 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003533 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003534 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003535 return false;
3536 }
3537 return true;
3538}
3539
chaviwca27f252018-02-06 16:46:39 -08003540uint32_t SurfaceFlinger::setClientStateLocked(const ComposerState& composerState) {
3541 const layer_state_t& s = composerState.state;
3542 sp<Client> client(static_cast<Client*>(composerState.client.get()));
3543
Mathias Agopian13127d82013-03-05 17:47:11 -08003544 sp<Layer> layer(client->getLayerUser(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003545 if (layer == nullptr) {
3546 return 0;
3547 }
3548
chaviw8b3871a2017-11-01 17:41:01 -07003549 uint32_t flags = 0;
3550
Garfield Tan8a3083e2018-12-03 13:21:07 -08003551 const uint64_t what = s.what;
chaviw8b3871a2017-11-01 17:41:01 -07003552 bool geometryAppliesWithResize =
3553 what & layer_state_t::eGeometryAppliesWithResize;
Jorim Jaggidba32732018-05-28 17:43:52 +02003554
3555 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3556 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003557 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003558 layer->pushPendingState();
3559 }
3560
chaviw8b3871a2017-11-01 17:41:01 -07003561 if (what & layer_state_t::ePositionChanged) {
3562 if (layer->setPosition(s.x, s.y, !geometryAppliesWithResize)) {
3563 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003564 }
chaviw8b3871a2017-11-01 17:41:01 -07003565 }
3566 if (what & layer_state_t::eLayerChanged) {
3567 // NOTE: index needs to be calculated before we update the state
3568 const auto& p = layer->getParent();
3569 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003570 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003571 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003572 mCurrentState.layersSortedByZ.removeAt(idx);
3573 mCurrentState.layersSortedByZ.add(layer);
3574 // we need traversal (state changed)
3575 // AND transaction (list changed)
3576 flags |= eTransactionNeeded|eTraversalNeeded;
3577 }
chaviw8b3871a2017-11-01 17:41:01 -07003578 } else {
3579 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003580 flags |= eTransactionNeeded|eTraversalNeeded;
3581 }
3582 }
chaviw8b3871a2017-11-01 17:41:01 -07003583 }
3584 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003585 // NOTE: index needs to be calculated before we update the state
3586 const auto& p = layer->getParent();
3587 if (p == nullptr) {
3588 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3589 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3590 mCurrentState.layersSortedByZ.removeAt(idx);
3591 mCurrentState.layersSortedByZ.add(layer);
3592 // we need traversal (state changed)
3593 // AND transaction (list changed)
3594 flags |= eTransactionNeeded|eTraversalNeeded;
3595 }
3596 } else {
3597 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3598 flags |= eTransactionNeeded|eTraversalNeeded;
3599 }
chaviw8b3871a2017-11-01 17:41:01 -07003600 }
3601 }
3602 if (what & layer_state_t::eSizeChanged) {
3603 if (layer->setSize(s.w, s.h)) {
3604 flags |= eTraversalNeeded;
3605 }
3606 }
3607 if (what & layer_state_t::eAlphaChanged) {
3608 if (layer->setAlpha(s.alpha))
3609 flags |= eTraversalNeeded;
3610 }
3611 if (what & layer_state_t::eColorChanged) {
3612 if (layer->setColor(s.color))
3613 flags |= eTraversalNeeded;
3614 }
Peiyong Lind3788632018-09-18 16:01:31 -07003615 if (what & layer_state_t::eColorTransformChanged) {
3616 if (layer->setColorTransform(s.colorTransform)) {
3617 flags |= eTraversalNeeded;
3618 }
3619 }
chaviw8b3871a2017-11-01 17:41:01 -07003620 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003621 // TODO: b/109894387
3622 //
3623 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3624 // rotation. To see the problem observe that if we have a square parent, and a child
3625 // of the same size, then we rotate the child 45 degrees around it's center, the child
3626 // must now be cropped to a non rectangular 8 sided region.
3627 //
3628 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3629 // private API, and the WindowManager only uses rotation in one case, which is on a top
3630 // level layer in which cropping is not an issue.
3631 //
3632 // However given that abuse of rotation matrices could lead to surfaces extending outside
3633 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3634 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3635 // transformations.
3636 if (layer->setMatrix(s.matrix, callingThreadHasUnscopedSurfaceFlingerAccess()))
chaviw8b3871a2017-11-01 17:41:01 -07003637 flags |= eTraversalNeeded;
3638 }
3639 if (what & layer_state_t::eTransparentRegionChanged) {
3640 if (layer->setTransparentRegionHint(s.transparentRegion))
3641 flags |= eTraversalNeeded;
3642 }
3643 if (what & layer_state_t::eFlagsChanged) {
3644 if (layer->setFlags(s.flags, s.mask))
3645 flags |= eTraversalNeeded;
3646 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003647 if (what & layer_state_t::eCropChanged_legacy) {
3648 if (layer->setCrop_legacy(s.crop_legacy, !geometryAppliesWithResize))
chaviw8b3871a2017-11-01 17:41:01 -07003649 flags |= eTraversalNeeded;
3650 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003651 if (what & layer_state_t::eCornerRadiusChanged) {
3652 if (layer->setCornerRadius(s.cornerRadius))
3653 flags |= eTraversalNeeded;
3654 }
chaviw8b3871a2017-11-01 17:41:01 -07003655 if (what & layer_state_t::eLayerStackChanged) {
3656 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3657 // We only allow setting layer stacks for top level layers,
3658 // everything else inherits layer stack from its parent.
3659 if (layer->hasParent()) {
3660 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3661 layer->getName().string());
3662 } else if (idx < 0) {
3663 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3664 "that also does not appear in the top level layer list. Something"
3665 " has gone wrong.", layer->getName().string());
3666 } else if (layer->setLayerStack(s.layerStack)) {
3667 mCurrentState.layersSortedByZ.removeAt(idx);
3668 mCurrentState.layersSortedByZ.add(layer);
3669 // we need traversal (state changed)
3670 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003671 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003672 }
3673 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003674 if (what & layer_state_t::eDeferTransaction_legacy) {
3675 if (s.barrierHandle_legacy != nullptr) {
3676 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3677 } else if (s.barrierGbp_legacy != nullptr) {
3678 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003679 if (authenticateSurfaceTextureLocked(gbp)) {
3680 const auto& otherLayer =
3681 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003682 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003683 } else {
3684 ALOGE("Attempt to defer transaction to to an"
3685 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003686 }
3687 }
chaviw8b3871a2017-11-01 17:41:01 -07003688 // We don't trigger a traversal here because if no other state is
3689 // changed, we don't want this to cause any more work
3690 }
3691 if (what & layer_state_t::eReparent) {
chaviw8ea97bb2017-11-29 10:05:15 -08003692 bool hadParent = layer->hasParent();
chaviw8b3871a2017-11-01 17:41:01 -07003693 if (layer->reparent(s.parentHandleForChild)) {
chaviw8ea97bb2017-11-29 10:05:15 -08003694 if (!hadParent) {
3695 mCurrentState.layersSortedByZ.remove(layer);
3696 }
chaviw8b3871a2017-11-01 17:41:01 -07003697 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carr9524cb32017-02-13 11:32:32 -08003698 }
chaviw8b3871a2017-11-01 17:41:01 -07003699 }
3700 if (what & layer_state_t::eReparentChildren) {
3701 if (layer->reparentChildren(s.reparentHandle)) {
3702 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003703 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003704 }
chaviw8b3871a2017-11-01 17:41:01 -07003705 if (what & layer_state_t::eDetachChildren) {
3706 layer->detachChildren();
3707 }
3708 if (what & layer_state_t::eOverrideScalingModeChanged) {
3709 layer->setOverrideScalingMode(s.overrideScalingMode);
3710 // We don't trigger a traversal here because if no other state is
3711 // changed, we don't want this to cause any more work
3712 }
Marissa Wall61c58622018-07-18 10:12:20 -07003713 if (what & layer_state_t::eTransformChanged) {
3714 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3715 }
3716 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3717 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3718 flags |= eTraversalNeeded;
3719 }
3720 if (what & layer_state_t::eCropChanged) {
3721 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3722 }
Marissa Wall861616d2018-10-22 12:52:23 -07003723 if (what & layer_state_t::eFrameChanged) {
3724 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3725 }
Marissa Wall61c58622018-07-18 10:12:20 -07003726 if (what & layer_state_t::eBufferChanged) {
3727 if (layer->setBuffer(s.buffer)) flags |= eTraversalNeeded;
3728 }
3729 if (what & layer_state_t::eAcquireFenceChanged) {
3730 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3731 }
3732 if (what & layer_state_t::eDataspaceChanged) {
3733 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3734 }
3735 if (what & layer_state_t::eHdrMetadataChanged) {
3736 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3737 }
3738 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3739 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3740 }
3741 if (what & layer_state_t::eApiChanged) {
3742 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3743 }
3744 if (what & layer_state_t::eSidebandStreamChanged) {
3745 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3746 }
Robert Carr720e5062018-07-30 17:45:14 -07003747 if (what & layer_state_t::eInputInfoChanged) {
3748 layer->setInputInfo(s.inputInfo);
3749 flags |= eTraversalNeeded;
3750 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003751 std::vector<sp<CallbackHandle>> callbackHandles;
3752 if ((what & layer_state_t::eListenerCallbacksChanged) && (!s.listenerCallbacks.empty())) {
3753 mTransactionCompletedThread.run();
3754 for (const auto& [listener, callbackIds] : s.listenerCallbacks) {
3755 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3756 }
3757 }
3758 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3759 // Do not put anything that updates layer state or modifies flags after
3760 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003761 return flags;
3762}
3763
chaviw273171b2018-12-26 11:46:30 -08003764uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3765 uint32_t flags = 0;
3766 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3767 flags |= eTraversalNeeded;
3768 }
3769
3770 mInputWindowCommands.merge(inputWindowCommands);
3771 return flags;
3772}
3773
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003774status_t SurfaceFlinger::createLayer(
Mathias Agopian0ef4e152011-04-20 14:19:32 -07003775 const String8& name,
3776 const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003777 uint32_t w, uint32_t h, PixelFormat format, uint32_t flags,
rongliucfb187b2018-03-14 12:26:23 -07003778 int32_t windowType, int32_t ownerUid, sp<IBinder>* handle,
Albert Chaulk479c60c2017-01-27 14:21:34 -05003779 sp<IGraphicBufferProducer>* gbp, sp<Layer>* parent)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003780{
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003781 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003782 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003783 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003784 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003785 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003786
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003787 status_t result = NO_ERROR;
3788
3789 sp<Layer> layer;
3790
Cody Northropbc755282017-03-31 12:00:08 -06003791 String8 uniqueName = getUniqueLayerName(name);
3792
Mathias Agopian3165cc22012-08-08 19:42:09 -07003793 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003794 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Marissa Wallfd668622018-05-10 10:21:13 -07003795 result = createBufferQueueLayer(client, uniqueName, w, h, flags, format, handle, gbp,
3796 &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003797
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003798 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003799 case ISurfaceComposerClient::eFXSurfaceBufferState:
3800 result = createBufferStateLayer(client, uniqueName, w, h, flags, handle, &layer);
3801 break;
chaviw13fdc492017-06-27 12:40:18 -07003802 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003803 // check if buffer size is set for color layer.
3804 if (w > 0 || h > 0) {
3805 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3806 int(w), int(h));
3807 return BAD_VALUE;
3808 }
3809
chaviw13fdc492017-06-27 12:40:18 -07003810 result = createColorLayer(client,
Cody Northropbc755282017-03-31 12:00:08 -06003811 uniqueName, w, h, flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003812 handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003813 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003814 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003815 // check if buffer size is set for container layer.
3816 if (w > 0 || h > 0) {
3817 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3818 int(w), int(h));
3819 return BAD_VALUE;
3820 }
Robert Carr6b3f6c52018-08-13 13:05:17 -07003821 result = createContainerLayer(client,
3822 uniqueName, w, h, flags,
3823 handle, &layer);
3824 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003825 default:
3826 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003827 break;
3828 }
3829
Dan Stoza7d89d062015-04-30 13:29:25 -07003830 if (result != NO_ERROR) {
3831 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003832 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003833
Chia-I Wuab0c3192017-08-01 11:29:00 -07003834 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3835 // TODO b/64227542
3836 if (windowType == 441731) {
3837 windowType = 2024; // TYPE_NAVIGATION_BAR_PANEL
3838 layer->setPrimaryDisplayOnly();
3839 }
3840
Albert Chaulk479c60c2017-01-27 14:21:34 -05003841 layer->setInfo(windowType, ownerUid);
3842
Robert Carrb89ea9d2018-12-10 13:01:14 -08003843 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
3844 result = addClientLayer(client, *handle, *gbp, layer, *parent,
3845 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003846 if (result != NO_ERROR) {
3847 return result;
3848 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003849 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003850
3851 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003852 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003853}
3854
Cody Northropbc755282017-03-31 12:00:08 -06003855String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3856{
3857 bool matchFound = true;
3858 uint32_t dupeCounter = 0;
3859
3860 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3861 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3862
Dan Stoza436ccf32018-06-21 12:10:12 -07003863 // Grab the state lock since we're accessing mCurrentState
3864 Mutex::Autolock lock(mStateLock);
3865
Cody Northropbc755282017-03-31 12:00:08 -06003866 // Loop over layers until we're sure there is no matching name
3867 while (matchFound) {
3868 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003869 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003870 if (layer->getName() == uniqueName) {
3871 matchFound = true;
3872 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3873 }
3874 });
3875 }
3876
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003877 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3878 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003879
3880 return uniqueName;
3881}
3882
Marissa Wallfd668622018-05-10 10:21:13 -07003883status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3884 uint32_t w, uint32_t h, uint32_t flags,
3885 PixelFormat& format, sp<IBinder>* handle,
3886 sp<IGraphicBufferProducer>* gbp,
3887 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003888 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003889 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003890 case PIXEL_FORMAT_TRANSPARENT:
3891 case PIXEL_FORMAT_TRANSLUCENT:
3892 format = PIXEL_FORMAT_RGBA_8888;
3893 break;
3894 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003895 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003896 break;
3897 }
3898
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003899 sp<BufferQueueLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07003900 getFactory().createBufferQueueLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wallfd668622018-05-10 10:21:13 -07003901 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003902 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003903 *handle = layer->getHandle();
3904 *gbp = layer->getProducer();
3905 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003906 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003907
Marissa Wallfd668622018-05-10 10:21:13 -07003908 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003909 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003910}
3911
Marissa Wall61c58622018-07-18 10:12:20 -07003912status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3913 uint32_t w, uint32_t h, uint32_t flags,
3914 sp<IBinder>* handle, sp<Layer>* outLayer) {
Lloyd Pique42ab75e2018-09-12 20:46:03 -07003915 sp<BufferStateLayer> layer =
Lloyd Pique90c115d2018-09-18 21:39:42 -07003916 getFactory().createBufferStateLayer(LayerCreationArgs(this, client, name, w, h, flags));
Marissa Wall61c58622018-07-18 10:12:20 -07003917 *handle = layer->getHandle();
3918 *outLayer = layer;
3919
3920 return NO_ERROR;
3921}
3922
chaviw13fdc492017-06-27 12:40:18 -07003923status_t SurfaceFlinger::createColorLayer(const sp<Client>& client,
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003924 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
David Sodman0c69cad2017-08-21 12:12:51 -07003925 sp<IBinder>* handle, sp<Layer>* outLayer)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003926{
Lloyd Pique90c115d2018-09-18 21:39:42 -07003927 *outLayer = getFactory().createColorLayer(LayerCreationArgs(this, client, name, w, h, flags));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003928 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003929 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003930}
3931
Robert Carr6b3f6c52018-08-13 13:05:17 -07003932status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client,
3933 const String8& name, uint32_t w, uint32_t h, uint32_t flags,
3934 sp<IBinder>* handle, sp<Layer>* outLayer)
3935{
Lloyd Pique90c115d2018-09-18 21:39:42 -07003936 *outLayer =
3937 getFactory().createContainerLayer(LayerCreationArgs(this, client, name, w, h, flags));
Robert Carr6b3f6c52018-08-13 13:05:17 -07003938 *handle = (*outLayer)->getHandle();
3939 return NO_ERROR;
3940}
3941
3942
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003943void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07003944 mLayersPendingRemoval.add(layer);
3945 mLayersRemoved = true;
3946 setTransactionFlags(eTransactionNeeded);
3947}
3948
Robert Carr695d5282018-12-18 15:27:58 -08003949void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003950{
Robert Carr2e102c92018-10-23 12:11:15 -07003951 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003952 // If a layer has a parent, we allow it to out-live it's handle
3953 // with the idea that the parent holds a reference and will eventually
3954 // be cleaned up. However no one cleans up the top-level so we do so
3955 // here.
3956 if (layer->getParent() == nullptr) {
3957 mCurrentState.layersSortedByZ.remove(layer);
3958 }
3959 markLayerPendingRemovalLocked(layer);
Robert Carr695d5282018-12-18 15:27:58 -08003960 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00003961}
3962
Mathias Agopianb60314a2012-04-10 22:09:54 -07003963// ---------------------------------------------------------------------------
3964
Andy McFadden13a082e2012-08-24 10:16:42 -07003965void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003966 const auto displayToken = getInternalDisplayToken();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003967 if (!displayToken) return;
3968
Jesse Hall01e29052013-02-19 16:13:35 -08003969 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003970 Vector<ComposerState> state;
3971 Vector<DisplayState> displays;
3972 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003973 d.what = DisplayState::eDisplayProjectionChanged |
3974 DisplayState::eLayerStackChanged;
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003975 d.token = displayToken;
Jesse Hall01e29052013-02-19 16:13:35 -08003976 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003977 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003978 d.frame.makeInvalid();
3979 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003980 d.width = 0;
3981 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003982 displays.add(d);
chaviw273171b2018-12-26 11:46:30 -08003983 setTransactionState(state, displays, 0, nullptr, mInputWindowCommands);
Jamie Gennis6547ff42013-07-16 20:12:42 -07003984
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003985 const auto display = getDisplayDevice(displayToken);
3986 if (!display) return;
3987
Dominik Laskowskie9774092018-12-11 10:04:24 -08003988 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003989
Dominik Laskowski075d3172018-05-24 15:50:06 -07003990 const auto activeConfig = getHwComposer().getActiveConfig(*display->getId());
Dan Stoza9e56aa02015-11-02 13:00:03 -08003991 const nsecs_t period = activeConfig->getVsyncPeriod();
Jamie Gennis6547ff42013-07-16 20:12:42 -07003992 mAnimFrameTracker.setDisplayRefreshPeriod(period);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003993
Brian Andersond0010582017-03-07 13:20:31 -08003994 // Use phase of 0 since phase is not known.
3995 // Use latency of 0, which will snap to the ideal latency.
Ana Krulece588e312018-09-18 12:32:24 -07003996 DisplayStatInfo stats{0 /* vsyncTime */, period /* vsyncPeriod */};
3997 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003998}
3999
4000void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004001 // Async since we may be called from the main thread.
4002 postMessageAsync(new LambdaMessage([this] { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004003}
4004
Dominik Laskowskie9774092018-12-11 10:04:24 -08004005void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004006 if (display->isVirtual()) {
4007 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004008 return;
4009 }
4010
Dominik Laskowski075d3172018-05-24 15:50:06 -07004011 const auto displayId = display->getId();
4012 LOG_ALWAYS_FATAL_IF(!displayId);
4013
Dominik Laskowski34157762018-10-31 13:07:19 -07004014 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004015
4016 int currentMode = display->getPowerMode();
4017 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004018 return;
4019 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004020
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004021 display->setPowerMode(mode);
4022
Lloyd Pique4dccc412018-01-22 17:21:36 -08004023 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004024 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004025 }
4026
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004027 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004028 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07004029 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004030 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004031 if (mUseScheduler) {
4032 mScheduler->onScreenAcquired(mAppConnectionHandle);
4033 } else {
4034 mEventThread->onScreenAcquired();
4035 }
Jesse Hall948fe0c2013-10-14 12:56:09 -07004036 resyncToHardwareVsync(true);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004037 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004038
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004039 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004040 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004041 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004042
4043 struct sched_param param = {0};
4044 param.sched_priority = 1;
4045 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4046 ALOGW("Couldn't set SCHED_FIFO on display on");
4047 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004048 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004049 // Turn off the display
4050 struct sched_param param = {0};
4051 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4052 ALOGW("Couldn't set SCHED_OTHER on display off");
4053 }
4054
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004055 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulece588e312018-09-18 12:32:24 -07004056 if (mUseScheduler) {
4057 mScheduler->disableHardwareVsync(true);
4058 } else {
4059 disableHardwareVsync(true); // also cancels any in-progress resync
4060 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004061 if (mUseScheduler) {
4062 mScheduler->onScreenReleased(mAppConnectionHandle);
4063 } else {
4064 mEventThread->onScreenReleased();
4065 }
Mathias Agopiancde87a32012-09-13 14:09:01 -07004066 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004067
Dominik Laskowski075d3172018-05-24 15:50:06 -07004068 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004069 mVisibleRegionsDirty = true;
4070 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004071 } else if (mode == HWC_POWER_MODE_DOZE ||
4072 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004073 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004074 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004075 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulec98b5b242018-08-10 15:03:23 -07004076 if (mUseScheduler) {
4077 mScheduler->onScreenAcquired(mAppConnectionHandle);
4078 } else {
4079 mEventThread->onScreenAcquired();
4080 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004081 resyncToHardwareVsync(true);
4082 }
4083 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4084 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004085 if (display->isPrimary()) {
Ana Krulece588e312018-09-18 12:32:24 -07004086 if (mUseScheduler) {
4087 mScheduler->disableHardwareVsync(true);
4088 } else {
4089 disableHardwareVsync(true); // also cancels any in-progress resync
4090 }
Ana Krulec98b5b242018-08-10 15:03:23 -07004091 if (mUseScheduler) {
4092 mScheduler->onScreenReleased(mAppConnectionHandle);
4093 } else {
4094 mEventThread->onScreenReleased();
4095 }
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004096 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004097 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004098 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004099 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004100 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004101 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004102
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004103 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004104 mTimeStats->setPowerMode(mode);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004105 }
4106
Dominik Laskowski34157762018-10-31 13:07:19 -07004107 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004108}
4109
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004110void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004111 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004112 const auto display = getDisplayDevice(displayToken);
4113 if (!display) {
4114 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4115 displayToken.get());
4116 } else if (display->isVirtual()) {
4117 ALOGW("Attempt to set power mode %d for virtual display", mode);
4118 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004119 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004120 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004121 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004122}
4123
4124// ---------------------------------------------------------------------------
4125
Lloyd Pique755e3192018-01-31 16:46:15 -08004126status_t SurfaceFlinger::doDump(int fd, const Vector<String16>& args, bool asProto)
4127 NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004128 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004129
Mathias Agopianbd115332013-04-18 16:41:04 -07004130 IPCThreadState* ipc = IPCThreadState::self();
4131 const int pid = ipc->getCallingPid();
4132 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004133
Mathias Agopianbd115332013-04-18 16:41:04 -07004134 if ((uid != AID_SHELL) &&
4135 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004136 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4137 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004138 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004139 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004140 // (this would indicate SF is stuck, but we want to be able to
4141 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004142 status_t err = mStateLock.timedLock(s2ns(1));
4143 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004144 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004145 StringAppendF(&result,
4146 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4147 "(no locks held)\n",
4148 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004149 }
4150
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004151 bool dumpAll = true;
4152 size_t index = 0;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004153 size_t numArgs = args.size();
chaviwa3d7bd32017-11-03 09:41:53 -07004154
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004155 if (numArgs) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004156 if ((index < numArgs) &&
4157 (args[index] == String16("--list"))) {
4158 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004159 listLayersLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004160 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004161 }
4162
4163 if ((index < numArgs) &&
4164 (args[index] == String16("--latency"))) {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004165 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004166 dumpStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004167 dumpAll = false;
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004168 }
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004169
4170 if ((index < numArgs) &&
4171 (args[index] == String16("--latency-clear"))) {
4172 index++;
Mathias Agopian74d211a2013-04-22 16:55:35 +02004173 clearStatsLocked(args, index, result);
Mathias Agopian35aadd62012-03-08 22:01:51 -08004174 dumpAll = false;
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004175 }
Andy McFaddenc751e922014-05-08 14:53:26 -07004176
4177 if ((index < numArgs) &&
4178 (args[index] == String16("--dispsync"))) {
4179 index++;
Lloyd Pique41be5d22018-06-21 13:11:48 -07004180 mPrimaryDispSync->dump(result);
Andy McFaddenc751e922014-05-08 14:53:26 -07004181 dumpAll = false;
4182 }
Dan Stozab90cf072015-03-05 11:05:59 -08004183
4184 if ((index < numArgs) &&
4185 (args[index] == String16("--static-screen"))) {
4186 index++;
4187 dumpStaticScreenStats(result);
4188 dumpAll = false;
4189 }
Pablo Ceballos40845df2016-01-25 17:41:15 -08004190
4191 if ((index < numArgs) &&
Brian Andersond6927fb2016-07-23 23:37:30 -07004192 (args[index] == String16("--frame-events"))) {
Pablo Ceballos40845df2016-01-25 17:41:15 -08004193 index++;
Brian Andersond6927fb2016-07-23 23:37:30 -07004194 dumpFrameEventsLocked(result);
Pablo Ceballos40845df2016-01-25 17:41:15 -08004195 dumpAll = false;
4196 }
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004197
4198 if ((index < numArgs) && (args[index] == String16("--wide-color"))) {
4199 index++;
4200 dumpWideColorInfo(result);
4201 dumpAll = false;
4202 }
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004203
4204 if ((index < numArgs) &&
4205 (args[index] == String16("--enable-layer-stats"))) {
4206 index++;
4207 mLayerStats.enable();
4208 dumpAll = false;
4209 }
4210
4211 if ((index < numArgs) &&
4212 (args[index] == String16("--disable-layer-stats"))) {
4213 index++;
4214 mLayerStats.disable();
4215 dumpAll = false;
4216 }
4217
4218 if ((index < numArgs) &&
4219 (args[index] == String16("--clear-layer-stats"))) {
4220 index++;
4221 mLayerStats.clear();
4222 dumpAll = false;
4223 }
4224
4225 if ((index < numArgs) &&
4226 (args[index] == String16("--dump-layer-stats"))) {
4227 index++;
4228 mLayerStats.dump(result);
4229 dumpAll = false;
4230 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004231
4232 if ((index < numArgs) &&
David Sodman7e4ae112018-02-09 15:02:28 -08004233 (args[index] == String16("--frame-composition"))) {
4234 index++;
4235 dumpFrameCompositionInfo(result);
4236 dumpAll = false;
4237 }
4238
4239 if ((index < numArgs) &&
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004240 (args[index] == String16("--display-identification"))) {
4241 index++;
4242 dumpDisplayIdentificationData(result);
4243 dumpAll = false;
4244 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004245
4246 if ((index < numArgs) && (args[index] == String16("--timestats"))) {
4247 index++;
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004248 mTimeStats->parseArgs(asProto, args, index, result);
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004249 dumpAll = false;
4250 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004251 }
Mathias Agopian1b5e1022010-04-20 17:55:49 -07004252
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004253 if (dumpAll) {
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07004254 if (asProto) {
4255 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4256 result.append(layersProto.SerializeAsString().c_str(), layersProto.ByteSize());
4257 } else {
4258 dumpAllLocked(args, index, result);
4259 }
Mathias Agopian48b888a2011-01-19 16:15:53 -08004260 }
4261
Mathias Agopian9795c422009-08-26 16:36:26 -07004262 if (locked) {
4263 mStateLock.unlock();
4264 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004265 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004266 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004267 return NO_ERROR;
4268}
4269
Yiwei Zhang5434a782018-12-05 18:06:32 -08004270void SurfaceFlinger::listLayersLocked(const Vector<String16>& /* args */, size_t& /* index */,
4271 std::string& result) const {
4272 mCurrentState.traverseInZOrder(
4273 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004274}
4275
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004276void SurfaceFlinger::dumpStatsLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004277 std::string& result) const {
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004278 String8 name;
4279 if (index < args.size()) {
4280 name = String8(args[index]);
4281 index++;
4282 }
4283
Dominik Laskowski075d3172018-05-24 15:50:06 -07004284 if (const auto displayId = getInternalDisplayId();
4285 displayId && getHwComposer().isConnected(*displayId)) {
4286 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004287 const nsecs_t period = activeConfig->getVsyncPeriod();
Yiwei Zhang5434a782018-12-05 18:06:32 -08004288 StringAppendF(&result, "%" PRId64 "\n", period);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004289 }
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004290
4291 if (name.isEmpty()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004292 mAnimFrameTracker.dumpStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004293 } else {
Robert Carr2047fae2016-11-28 14:09:09 -08004294 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004295 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004296 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004297 }
Robert Carr2047fae2016-11-28 14:09:09 -08004298 });
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004299 }
4300}
4301
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004302void SurfaceFlinger::clearStatsLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004303 std::string& /* result */) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004304 String8 name;
4305 if (index < args.size()) {
4306 name = String8(args[index]);
4307 index++;
4308 }
4309
Robert Carr2047fae2016-11-28 14:09:09 -08004310 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004311 if (name.isEmpty() || (name == layer->getName())) {
Svetoslavd85084b2014-03-20 10:28:31 -07004312 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004313 }
Robert Carr2047fae2016-11-28 14:09:09 -08004314 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004315
Svetoslavd85084b2014-03-20 10:28:31 -07004316 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004317}
4318
Jamie Gennis6547ff42013-07-16 20:12:42 -07004319// This should only be called from the main thread. Otherwise it would need
4320// the lock and should use mCurrentState rather than mDrawingState.
4321void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004322 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004323 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004324 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004325
4326 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
4327}
4328
Yiwei Zhang5434a782018-12-05 18:06:32 -08004329void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004330 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004331
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004332 if (isLayerTripleBufferingDisabled())
4333 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004334
Yiwei Zhang5434a782018-12-05 18:06:32 -08004335 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4336 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4337 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4338 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4339 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4340 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004341 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004342}
4343
Yiwei Zhang5434a782018-12-05 18:06:32 -08004344void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4345 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004346 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4347 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004348 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004349 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004350 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004351 }
David Sodman4a36e932017-11-07 14:29:47 -08004352 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004353 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004354 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004355 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4356 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004357}
4358
Dan Stozae77c7662016-05-13 11:37:28 -07004359void SurfaceFlinger::recordBufferingStats(const char* layerName,
4360 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004361 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4362 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004363 for (const auto& segment : history) {
4364 if (!segment.usedThirdBuffer) {
4365 stats.twoBufferTime += segment.totalTime;
4366 }
4367 if (segment.occupancyAverage < 1.0f) {
4368 stats.doubleBufferedTime += segment.totalTime;
4369 } else if (segment.occupancyAverage < 2.0f) {
4370 stats.tripleBufferedTime += segment.totalTime;
4371 }
4372 ++stats.numSegments;
4373 stats.totalTime += segment.totalTime;
4374 }
4375}
4376
Yiwei Zhang5434a782018-12-05 18:06:32 -08004377void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4378 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004379
4380 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4381 const size_t count = currentLayers.size();
4382 for (size_t i=0 ; i<count ; i++) {
4383 currentLayers[i]->dumpFrameEvents(result);
4384 }
4385}
4386
Yiwei Zhang5434a782018-12-05 18:06:32 -08004387void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004388 result.append("Buffering stats:\n");
4389 result.append(" [Layer name] <Active time> <Two buffer> "
4390 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004391 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004392 typedef std::tuple<std::string, float, float, float> BufferTuple;
4393 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004394 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004395 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004396 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004397 if (stats.numSegments == 0) {
4398 continue;
4399 }
4400 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4401 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4402 stats.totalTime;
4403 float doubleBufferRatio = static_cast<float>(
4404 stats.doubleBufferedTime) / stats.totalTime;
4405 float tripleBufferRatio = static_cast<float>(
4406 stats.tripleBufferedTime) / stats.totalTime;
4407 sorted.insert({activeTime, {name, twoBufferRatio,
4408 doubleBufferRatio, tripleBufferRatio}});
4409 }
4410 for (const auto& sortedPair : sorted) {
4411 float activeTime = sortedPair.first;
4412 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004413 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4414 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004415 }
4416 result.append("\n");
4417}
4418
Yiwei Zhang5434a782018-12-05 18:06:32 -08004419void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004420 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004421 const auto displayId = display->getId();
4422 if (!displayId) {
4423 continue;
4424 }
4425 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004426 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004427 continue;
4428 }
4429
Yiwei Zhang5434a782018-12-05 18:06:32 -08004430 StringAppendF(&result,
4431 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4432 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004433 uint8_t port;
4434 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004435 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004436 result.append("no identification data\n");
4437 continue;
4438 }
4439
4440 if (!isEdid(data)) {
4441 result.append("unknown identification data: ");
4442 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004443 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004444 }
4445 result.append("\n");
4446 continue;
4447 }
4448
4449 const auto edid = parseEdid(data);
4450 if (!edid) {
4451 result.append("invalid EDID: ");
4452 for (uint8_t byte : data) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004453 StringAppendF(&result, "%x ", byte);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004454 }
4455 result.append("\n");
4456 continue;
4457 }
4458
Yiwei Zhang5434a782018-12-05 18:06:32 -08004459 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004460 result.append(edid->displayName.data(), edid->displayName.length());
4461 result.append("\"\n");
4462 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004463}
4464
Yiwei Zhang5434a782018-12-05 18:06:32 -08004465void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
4466 StringAppendF(&result, "Device has wide color display: %d\n", hasWideColorDisplay);
4467 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4468 StringAppendF(&result, "DisplayColorSetting: %s\n",
4469 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004470
4471 // TODO: print out if wide-color mode is active or not
4472
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004473 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004474 const auto displayId = display->getId();
4475 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004476 continue;
4477 }
4478
Yiwei Zhang5434a782018-12-05 18:06:32 -08004479 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004480 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004481 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004482 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004483 }
4484
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004485 ColorMode currentMode = display->getActiveColorMode();
Yiwei Zhang5434a782018-12-05 18:06:32 -08004486 StringAppendF(&result, " Current color mode: %s (%d)\n",
4487 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004488 }
4489 result.append("\n");
4490}
4491
Yiwei Zhang5434a782018-12-05 18:06:32 -08004492void SurfaceFlinger::dumpFrameCompositionInfo(std::string& result) const {
David Sodman7e4ae112018-02-09 15:02:28 -08004493 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski05275f12018-11-01 15:03:24 -07004494 const auto it = getBE().mEndOfFrameCompositionInfo.find(token);
4495 if (it == getBE().mEndOfFrameCompositionInfo.end()) {
David Sodman7e4ae112018-02-09 15:02:28 -08004496 continue;
4497 }
4498
Dominik Laskowski05275f12018-11-01 15:03:24 -07004499 const auto& compositionInfoList = it->second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004500 StringAppendF(&result, "%s\n", display->getDebugName().c_str());
4501 StringAppendF(&result, "numComponents: %zu\n", compositionInfoList.size());
David Sodman7e4ae112018-02-09 15:02:28 -08004502 for (const auto& compositionInfo : compositionInfoList) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004503 compositionInfo.dump(result, nullptr);
4504 result.append("\n");
David Sodman7e4ae112018-02-09 15:02:28 -08004505 }
4506 }
David Sodman7e4ae112018-02-09 15:02:28 -08004507}
4508
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004509LayersProto SurfaceFlinger::dumpProtoInfo(LayerVector::StateSet stateSet) const {
chaviw1d044282017-09-27 12:19:28 -07004510 LayersProto layersProto;
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004511 const bool useDrawing = stateSet == LayerVector::StateSet::Drawing;
4512 const State& state = useDrawing ? mDrawingState : mCurrentState;
4513 state.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004514 LayerProto* layerProto = layersProto.add_layers();
Jorim Jaggi8e0af362017-11-14 16:28:28 +01004515 layer->writeToProto(layerProto, stateSet);
chaviw1d044282017-09-27 12:19:28 -07004516 });
4517
4518 return layersProto;
4519}
4520
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004521LayersProto SurfaceFlinger::dumpVisibleLayersProtoInfo(const DisplayDevice& display) const {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004522 LayersProto layersProto;
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004523
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004524 SizeProto* resolution = layersProto.mutable_resolution();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004525 resolution->set_w(display.getWidth());
4526 resolution->set_h(display.getHeight());
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004527
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004528 layersProto.set_color_mode(decodeColorMode(display.getActiveColorMode()));
4529 layersProto.set_color_transform(decodeColorTransform(display.getColorTransform()));
4530 layersProto.set_global_transform(static_cast<int32_t>(display.getOrientationTransform()));
Yiwei Zhang60d1a192018-03-07 14:52:28 -08004531
Dominik Laskowski075d3172018-05-24 15:50:06 -07004532 const auto displayId = display.getId();
4533 LOG_ALWAYS_FATAL_IF(!displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004534 mDrawingState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004535 if (!layer->visibleRegion.isEmpty() && layer->getBE().mHwcLayers.count(*displayId)) {
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004536 LayerProto* layerProto = layersProto.add_layers();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004537 layer->writeToProto(layerProto, *displayId);
Yiwei Zhang7124ad32018-02-21 13:02:45 -08004538 }
4539 });
4540
4541 return layersProto;
4542}
4543
Mathias Agopian74d211a2013-04-22 16:55:35 +02004544void SurfaceFlinger::dumpAllLocked(const Vector<String16>& args, size_t& index,
Yiwei Zhang5434a782018-12-05 18:06:32 -08004545 std::string& result) const {
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004546 bool colorize = false;
4547 if (index < args.size()
4548 && (args[index] == String16("--color"))) {
4549 colorize = true;
4550 index++;
4551 }
4552
4553 Colorizer colorizer(colorize);
4554
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004555 // figure out if we're stuck somewhere
4556 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004557 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004558 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4559
4560 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004561 * Dump library configuration.
4562 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004563
4564 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004565 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004566 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004567 appendSfConfigString(result);
4568 appendUiConfigString(result);
4569 appendGuiConfigString(result);
4570 result.append("\n");
4571
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004572 result.append("\nDisplay identification data:\n");
4573 dumpDisplayIdentificationData(result);
4574
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004575 result.append("\nWide-Color information:\n");
4576 dumpWideColorInfo(result);
4577
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004578 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004579 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004580 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004581 result.append(SyncFeatures::getInstance().toString());
4582 result.append("\n");
4583
Andy McFadden41d67d72014-04-25 16:58:34 -07004584 colorizer.bold(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004585 result.append("DispSync configuration:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004586 colorizer.reset(result);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004587
Jorim Jaggi22ec38b2018-06-19 15:57:08 +02004588 const auto [sfEarlyOffset, appEarlyOffset] = mVsyncModulator.getEarlyOffsets();
4589 const auto [sfEarlyGlOffset, appEarlyGlOffset] = mVsyncModulator.getEarlyGlOffsets();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004590 if (const auto displayId = getInternalDisplayId();
4591 displayId && getHwComposer().isConnected(*displayId)) {
4592 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004593 StringAppendF(&result,
4594 "Display %s: app phase %" PRId64 " ns, "
4595 "sf phase %" PRId64 " ns, "
4596 "early app phase %" PRId64 " ns, "
4597 "early sf phase %" PRId64 " ns, "
4598 "early app gl phase %" PRId64 " ns, "
4599 "early sf gl phase %" PRId64 " ns, "
4600 "present offset %" PRId64 " ns (refresh %" PRId64 " ns)",
4601 to_string(*displayId).c_str(), vsyncPhaseOffsetNs, sfVsyncPhaseOffsetNs,
4602 appEarlyOffset, sfEarlyOffset, appEarlyGlOffset, sfEarlyGlOffset,
4603 dispSyncPresentTimeOffset, activeConfig->getVsyncPeriod());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004604 }
Andy McFadden41d67d72014-04-25 16:58:34 -07004605 result.append("\n");
4606
Dan Stozab90cf072015-03-05 11:05:59 -08004607 // Dump static screen stats
4608 result.append("\n");
4609 dumpStaticScreenStats(result);
4610 result.append("\n");
4611
Yiwei Zhang5434a782018-12-05 18:06:32 -08004612 StringAppendF(&result, "Missed frame count: %u\n\n", mFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004613
Dan Stozae77c7662016-05-13 11:37:28 -07004614 dumpBufferingStats(result);
4615
Andy McFadden4803b742012-09-24 19:07:20 -07004616 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004617 * Dump the visible layer list
4618 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004619 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004620 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers);
4621 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4622 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004623 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004624
Chia-I Wu2f884132018-09-13 15:17:58 -07004625 {
4626 LayersProto layersProto = dumpProtoInfo(LayerVector::StateSet::Current);
4627 auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004628 result.append(LayerProtoParser::layerTreeToString(layerTree));
Chia-I Wu2f884132018-09-13 15:17:58 -07004629 result.append("\n");
4630 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004631
David Sodman7e4ae112018-02-09 15:02:28 -08004632 result.append("\nFrame-Composition information:\n");
4633 dumpFrameCompositionInfo(result);
4634 result.append("\n");
4635
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004636 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004637 * Dump Display state
4638 */
4639
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004640 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004641 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004642 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004643 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004644 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004645 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004646 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004647
4648 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004649 * Dump SurfaceFlinger global state
4650 */
4651
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004652 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004653 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004654 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004655
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004656 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004657
Dominik Laskowski075d3172018-05-24 15:50:06 -07004658 if (const auto display = getDefaultDisplayDeviceLocked()) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004659 display->undefinedRegion.dump(result, "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004660 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4661 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004662 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004663 StringAppendF(&result,
4664 " transaction-flags : %08x\n"
4665 " gpu_to_cpu_unsupported : %d\n",
4666 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004667
Dominik Laskowski075d3172018-05-24 15:50:06 -07004668 if (const auto displayId = getInternalDisplayId();
4669 displayId && getHwComposer().isConnected(*displayId)) {
4670 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004671 StringAppendF(&result,
4672 " refresh-rate : %f fps\n"
4673 " x-dpi : %f\n"
4674 " y-dpi : %f\n",
4675 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4676 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004677 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004678
Yiwei Zhang5434a782018-12-05 18:06:32 -08004679 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004680
Yiwei Zhang5434a782018-12-05 18:06:32 -08004681 StringAppendF(&result, " use Scheduler: %s\n", mUseScheduler ? "true" : "false");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004682 /*
4683 * VSYNC state
4684 */
Ana Krulec98b5b242018-08-10 15:03:23 -07004685 if (mUseScheduler) {
4686 mScheduler->dump(mAppConnectionHandle, result);
4687 } else {
4688 mEventThread->dump(result);
4689 }
Dan Stozae22aec72016-08-01 13:20:59 -07004690 result.append("\n");
4691
4692 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004693 * Tracing state
4694 */
4695 mTracing.dump(result);
4696 result.append("\n");
4697
4698 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004699 * HWC layer minidump
4700 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004701 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004702 const auto displayId = display->getId();
4703 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004704 continue;
4705 }
4706
Yiwei Zhang5434a782018-12-05 18:06:32 -08004707 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004708 Layer::miniDumpHeader(result);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004709 mCurrentState.traverseInZOrder([&](Layer* layer) { layer->miniDump(result, *displayId); });
Dan Stozae22aec72016-08-01 13:20:59 -07004710 result.append("\n");
4711 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004712
4713 /*
4714 * Dump HWComposer state
4715 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004716 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004717 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004718 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004719 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004720 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004721 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004722
4723 /*
4724 * Dump gralloc state
4725 */
4726 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4727 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004728
4729 /*
4730 * Dump VrFlinger state if in use.
4731 */
4732 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4733 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004734 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004735 result.append("\n");
4736 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004737}
4738
Dominik Laskowski075d3172018-05-24 15:50:06 -07004739const Vector<sp<Layer>>& SurfaceFlinger::getLayerSortedByZForHwcDisplay(DisplayId displayId) {
Mathias Agopiandb9b41f2012-10-15 16:51:41 -07004740 // Note: mStateLock is held here
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004741 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski7e045462018-05-30 13:02:02 -07004742 if (display->getId() == displayId) {
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004743 return getDisplayDeviceLocked(token)->getVisibleLayersSortedByZ();
Jesse Hall48bc05b2013-03-21 14:06:52 -07004744 }
4745 }
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004746
Dominik Laskowski34157762018-10-31 13:07:19 -07004747 ALOGE("%s: Invalid display %s", __FUNCTION__, to_string(displayId).c_str());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004748 static const Vector<sp<Layer>> empty;
4749 return empty;
Mathias Agopiancb558572012-10-04 15:58:54 -07004750}
4751
Keun young Park63f165f2012-08-31 10:53:36 -07004752bool SurfaceFlinger::startDdmConnection()
4753{
4754 void* libddmconnection_dso =
4755 dlopen("libsurfaceflinger_ddmconnection.so", RTLD_NOW);
4756 if (!libddmconnection_dso) {
4757 return false;
4758 }
4759 void (*DdmConnection_start)(const char* name);
4760 DdmConnection_start =
Jesse Hall24cd98e2014-07-13 14:37:16 -07004761 (decltype(DdmConnection_start))dlsym(libddmconnection_dso, "DdmConnection_start");
Keun young Park63f165f2012-08-31 10:53:36 -07004762 if (!DdmConnection_start) {
4763 dlclose(libddmconnection_dso);
4764 return false;
4765 }
4766 (*DdmConnection_start)(getServiceName());
4767 return true;
4768}
4769
Chia-I Wu28f320b2018-05-03 11:02:56 -07004770void SurfaceFlinger::updateColorMatrixLocked() {
4771 mat4 colorMatrix;
4772 if (mGlobalSaturationFactor != 1.0f) {
4773 // Rec.709 luma coefficients
4774 float3 luminance{0.213f, 0.715f, 0.072f};
4775 luminance *= 1.0f - mGlobalSaturationFactor;
4776 mat4 saturationMatrix = mat4(
4777 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4778 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4779 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4780 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4781 );
4782 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4783 } else {
4784 colorMatrix = mClientColorMatrix * mDaltonizer();
4785 }
4786
4787 if (mCurrentState.colorMatrix != colorMatrix) {
4788 mCurrentState.colorMatrix = colorMatrix;
4789 mCurrentState.colorMatrixChanged = true;
4790 setTransactionFlags(eTransactionNeeded);
4791 }
4792}
4793
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004794status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004795#pragma clang diagnostic push
4796#pragma clang diagnostic error "-Wswitch-enum"
4797 switch (static_cast<ISurfaceComposerTag>(code)) {
4798 // These methods should at minimum make sure that the client requested
4799 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004800 case BOOT_FINISHED:
4801 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004802 case CREATE_DISPLAY:
4803 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004804 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004805 case GET_ACTIVE_COLOR_MODE:
4806 case GET_ANIMATION_FRAME_STATS:
4807 case GET_HDR_CAPABILITIES:
4808 case SET_ACTIVE_CONFIG:
4809 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004810 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004811 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004812 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004813 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
4814 case GET_DISPLAYED_CONTENT_SAMPLE: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004815 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4816 IPCThreadState* ipc = IPCThreadState::self();
4817 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4818 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004819 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004820 }
Robert Carr1db73f62016-12-21 12:58:51 -08004821 return OK;
4822 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004823 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004824 IPCThreadState* ipc = IPCThreadState::self();
4825 const int pid = ipc->getCallingPid();
4826 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004827 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4828 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004829 return PERMISSION_DENIED;
4830 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004831 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004832 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004833 // Used by apps to hook Choreographer to SurfaceFlinger.
4834 case CREATE_DISPLAY_EVENT_CONNECTION:
4835 // The following calls are currently used by clients that do not
4836 // request necessary permissions. However, they do not expose any secret
4837 // information, so it is OK to pass them.
4838 case AUTHENTICATE_SURFACE:
4839 case GET_ACTIVE_CONFIG:
4840 case GET_BUILT_IN_DISPLAY:
4841 case GET_DISPLAY_COLOR_MODES:
4842 case GET_DISPLAY_CONFIGS:
4843 case GET_DISPLAY_STATS:
4844 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4845 // Calling setTransactionState is safe, because you need to have been
4846 // granted a reference to Client* and Handle* to do anything with it.
4847 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004848 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004849 case GET_COLOR_MANAGEMENT:
Peiyong Lin0256f722018-08-31 15:45:10 -07004850 case GET_COMPOSITION_PREFERENCE: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004851 return OK;
4852 }
4853 case CAPTURE_LAYERS:
4854 case CAPTURE_SCREEN: {
4855 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004856 IPCThreadState* ipc = IPCThreadState::self();
4857 const int pid = ipc->getCallingPid();
4858 const int uid = ipc->getCallingUid();
4859 if ((uid != AID_GRAPHICS) &&
4860 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4861 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4862 return PERMISSION_DENIED;
4863 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004864 return OK;
4865 }
4866 // The following codes are deprecated and should never be allowed to access SF.
4867 case CONNECT_DISPLAY_UNUSED:
4868 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4869 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4870 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004871 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004872 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004873
4874 // These codes are used for the IBinder protocol to either interrogate the recipient
4875 // side of the transaction for its canonical interface descriptor or to dump its state.
4876 // We let them pass by default.
4877 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4878 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4879 code == IBinder::SYSPROPS_TRANSACTION) {
4880 return OK;
4881 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004882 // Numbers from 1000 to 1031 are currently use for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004883 // in onTransact verifies that the user is root, and has access to use SF.
Peiyong Lin9d846a52018-11-05 13:18:20 -08004884 if (code >= 1000 && code <= 1031) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004885 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4886 return OK;
4887 }
4888 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4889 return PERMISSION_DENIED;
4890#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004891}
4892
Ana Krulec13be8ad2018-08-21 02:43:56 +00004893status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4894 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004895 status_t credentialCheck = CheckTransactCodeCredentials(code);
4896 if (credentialCheck != OK) {
4897 return credentialCheck;
4898 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004899
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004900 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4901 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004902 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004903 IPCThreadState* ipc = IPCThreadState::self();
4904 const int uid = ipc->getCallingUid();
4905 if (CC_UNLIKELY(uid != AID_SYSTEM
4906 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004907 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004908 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004909 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004910 return PERMISSION_DENIED;
4911 }
4912 int n;
4913 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004914 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004915 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004916 return NO_ERROR;
4917 case 1002: // SHOW_UPDATES
4918 n = data.readInt32();
4919 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004920 invalidateHwcGeometry();
4921 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004922 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004923 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004924 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004925 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004926 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004927 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004928 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004929 setTransactionFlags(
4930 eTransactionNeeded|
4931 eDisplayTransactionNeeded|
4932 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004933 return NO_ERROR;
4934 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004935 case 1006:{ // send empty update
4936 signalRefresh();
4937 return NO_ERROR;
4938 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004939 case 1008: // toggle use of hw composer
4940 n = data.readInt32();
4941 mDebugDisableHWC = n ? 1 : 0;
4942 invalidateHwcGeometry();
4943 repaintEverything();
4944 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004945 case 1009: // toggle use of transform hint
4946 n = data.readInt32();
4947 mDebugDisableTransformHint = n ? 1 : 0;
4948 invalidateHwcGeometry();
4949 repaintEverything();
4950 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004951 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004952 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004953 reply->writeInt32(0);
4954 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004955 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004956 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004957 return NO_ERROR;
4958 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004959 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004960 if (!display) {
4961 return NAME_NOT_FOUND;
4962 }
4963
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004964 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004965 return NO_ERROR;
4966 }
4967 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004968 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004969 // daltonize
4970 n = data.readInt32();
4971 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004972 case 1:
4973 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4974 break;
4975 case 2:
4976 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4977 break;
4978 case 3:
4979 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4980 break;
4981 default:
4982 mDaltonizer.setType(ColorBlindnessType::None);
4983 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004984 }
4985 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004986 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004987 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004988 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004989 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004990
4991 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004992 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004993 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004994 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004995 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004996 // apply a color matrix
4997 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004998 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004999 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005000 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005001 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005002 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005003 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005004 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005005 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005006 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005007 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005008
5009 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5010 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005011 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005012 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5013 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5014 }
5015
Chia-I Wu28f320b2018-05-03 11:02:56 -07005016 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005017 return NO_ERROR;
5018 }
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005019 // This is an experimental interface
5020 // Needs to be shifted to proper binder interface when we productize
5021 case 1016: {
Andy McFadden645b1f72014-06-10 14:43:32 -07005022 n = data.readInt32();
Ana Krulece588e312018-09-18 12:32:24 -07005023 // TODO(b/113612090): Evaluate if this can be removed.
Lloyd Pique41be5d22018-06-21 13:11:48 -07005024 mPrimaryDispSync->setRefreshSkipCount(n);
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005025 return NO_ERROR;
5026 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005027 case 1017: {
5028 n = data.readInt32();
5029 mForceFullDamage = static_cast<bool>(n);
5030 return NO_ERROR;
5031 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005032 case 1018: { // Modify Choreographer's phase offset
5033 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005034 if (mUseScheduler) {
5035 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
5036 } else {
5037 mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5038 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005039 return NO_ERROR;
5040 }
5041 case 1019: { // Modify SurfaceFlinger's phase offset
5042 n = data.readInt32();
Ana Krulec98b5b242018-08-10 15:03:23 -07005043 if (mUseScheduler) {
5044 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
5045 } else {
5046 mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
5047 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005048 return NO_ERROR;
5049 }
Irvel468051e2016-06-13 16:44:44 -07005050 case 1020: { // Layer updates interceptor
5051 n = data.readInt32();
5052 if (n) {
5053 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005054 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005055 }
5056 else{
5057 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005058 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005059 }
5060 return NO_ERROR;
5061 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005062 case 1021: { // Disable HWC virtual displays
5063 n = data.readInt32();
5064 mUseHwcVirtualDisplays = !n;
5065 return NO_ERROR;
5066 }
Romain Guy0147a172017-06-01 13:53:56 -07005067 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005068 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005069 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005070
Chia-I Wu28f320b2018-05-03 11:02:56 -07005071 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005072 return NO_ERROR;
5073 }
Romain Guy54f154a2017-10-24 21:40:32 +01005074 case 1023: { // Set native mode
Chia-I Wu0d711262018-05-21 15:19:35 -07005075 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Romain Guy54f154a2017-10-24 21:40:32 +01005076 invalidateHwcGeometry();
5077 repaintEverything();
5078 return NO_ERROR;
5079 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005080 // Deprecate, use 1030 to check whether the device is color managed.
5081 case 1024: {
5082 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005083 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005084 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005085 n = data.readInt32();
5086 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005087 ALOGD("LayerTracing enabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005088 mTracing.enable();
5089 doTracing("tracing.enable");
5090 reply->writeInt32(NO_ERROR);
5091 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005092 ALOGD("LayerTracing disabled");
Adrian Roos1e1a1282017-11-01 19:05:31 +01005093 status_t err = mTracing.disable();
5094 reply->writeInt32(err);
5095 }
5096 return NO_ERROR;
5097 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005098 case 1026: { // Get layer tracing status
5099 reply->writeBool(mTracing.isEnabled());
5100 return NO_ERROR;
5101 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005102 // Is a DisplayColorSetting supported?
5103 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005104 const auto display = getDefaultDisplayDevice();
5105 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005106 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005107 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005108
5109 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5110 switch (setting) {
5111 case DisplayColorSetting::MANAGED:
Peiyong Lin13effd12018-07-24 17:01:47 -07005112 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005113 break;
5114 case DisplayColorSetting::UNMANAGED:
5115 reply->writeBool(true);
5116 break;
5117 case DisplayColorSetting::ENHANCED:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005118 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005119 break;
5120 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005121 reply->writeBool(
5122 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005123 break;
5124 }
5125 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005126 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005127 // Is VrFlinger active?
5128 case 1028: {
5129 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005130 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005131 return NO_ERROR;
5132 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005133 // Is device color managed?
5134 case 1030: {
5135 reply->writeBool(useColorManagement);
5136 return NO_ERROR;
5137 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005138 // Override default composition data space
5139 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5140 // && adb shell stop zygote && adb shell start zygote
5141 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5142 // adb shell stop zygote && adb shell start zygote
5143 case 1031: {
5144 Mutex::Autolock _l(mStateLock);
5145 n = data.readInt32();
5146 if (n) {
5147 n = data.readInt32();
5148 if (n) {
5149 Dataspace dataspace = static_cast<Dataspace>(n);
5150 if (!validateCompositionDataspace(dataspace)) {
5151 return BAD_VALUE;
5152 }
5153 mDefaultCompositionDataspace = dataspace;
5154 }
5155 n = data.readInt32();
5156 if (n) {
5157 Dataspace dataspace = static_cast<Dataspace>(n);
5158 if (!validateCompositionDataspace(dataspace)) {
5159 return BAD_VALUE;
5160 }
5161 mWideColorGamutCompositionDataspace = dataspace;
5162 }
5163 } else {
5164 // restore composition data space.
5165 mDefaultCompositionDataspace = defaultCompositionDataspace;
5166 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5167 }
5168 return NO_ERROR;
5169 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005170 }
5171 }
5172 return err;
5173}
5174
Steven Thomas6d8110b2017-08-31 18:24:21 -07005175void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005176 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005177 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005178}
5179
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005180// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5181class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005182public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005183 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5184 ~WindowDisconnector() {
5185 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005186 }
5187
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005188private:
5189 ANativeWindow* mWindow;
5190 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005191};
5192
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005193status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005194 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5195 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005196 uint32_t reqWidth, uint32_t reqHeight,
5197 bool useIdentityTransform,
chaviwa76b2712017-09-20 12:02:26 -07005198 ISurfaceComposer::Rotation rotation) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005199 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005200
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005201 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005202
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005203 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5204
Chia-I Wu20261cb2018-08-23 12:55:44 -07005205 sp<DisplayDevice> display;
5206 {
5207 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005208
Chia-I Wu20261cb2018-08-23 12:55:44 -07005209 display = getDisplayDeviceLocked(displayToken);
5210 if (!display) return BAD_VALUE;
5211
Chia-I Wucb023152018-08-28 12:57:23 -07005212 // set the requested width/height to the logical display viewport size
5213 // by default
5214 if (reqWidth == 0 || reqHeight == 0) {
5215 reqWidth = uint32_t(display->getViewport().width());
5216 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005217 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005218 }
5219
Peiyong Lin0e003c92018-09-17 11:09:51 -07005220 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
5221 renderAreaRotation);
chaviwa76b2712017-09-20 12:02:26 -07005222
5223 auto traverseLayers = std::bind(std::mem_fn(&SurfaceFlinger::traverseLayersInDisplay), this,
chaviw0e3479f2018-09-10 16:49:30 -07005224 display, std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005225 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
5226 useIdentityTransform);
chaviwa76b2712017-09-20 12:02:26 -07005227}
5228
5229status_t SurfaceFlinger::captureLayers(const sp<IBinder>& layerHandleBinder,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005230 sp<GraphicBuffer>* outBuffer, const Dataspace reqDataspace,
5231 const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
Robert Carr578038f2018-03-09 12:25:24 -08005232 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005233 ATRACE_CALL();
5234
5235 class LayerRenderArea : public RenderArea {
5236 public:
Robert Carr578038f2018-03-09 12:25:24 -08005237 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005238 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
5239 bool childrenOnly)
5240 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08005241 mLayer(layer),
5242 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005243 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005244 mFlinger(flinger),
5245 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005246 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005247 Rect getBounds() const override {
5248 const Layer::State& layerState(mLayer->getDrawingState());
5249 return mLayer->getBufferSize(layerState);
5250 }
Marissa Wall61c58622018-07-18 10:12:20 -07005251 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005252 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005253 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005254 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005255 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005256 }
chaviwa76b2712017-09-20 12:02:26 -07005257 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005258 bool needsFiltering() const override { return mNeedsFiltering; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005259 Rect getSourceCrop() const override {
5260 if (mCrop.isEmpty()) {
5261 return getBounds();
5262 } else {
5263 return mCrop;
5264 }
5265 }
Robert Carr578038f2018-03-09 12:25:24 -08005266 class ReparentForDrawing {
5267 public:
5268 const sp<Layer>& oldParent;
5269 const sp<Layer>& newParent;
5270
5271 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent)
5272 : oldParent(oldParent), newParent(newParent) {
Robert Carr15eae092018-03-23 13:43:53 -07005273 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005274 }
Robert Carr15eae092018-03-23 13:43:53 -07005275 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005276 };
5277
5278 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005279 const Rect sourceCrop = getSourceCrop();
5280 // no need to check rotation because there is none
5281 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5282 sourceCrop.height() != getReqHeight();
5283
Robert Carr578038f2018-03-09 12:25:24 -08005284 if (!mChildrenOnly) {
5285 mTransform = mLayer->getTransform().inverse();
5286 drawLayers();
5287 } else {
5288 Rect bounds = getBounds();
Lloyd Pique90c115d2018-09-18 21:39:42 -07005289 screenshotParentLayer = mFlinger->getFactory().createContainerLayer(
Lloyd Pique42ab75e2018-09-12 20:46:03 -07005290 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5291 bounds.getWidth(), bounds.getHeight(), 0));
Robert Carr578038f2018-03-09 12:25:24 -08005292
5293 ReparentForDrawing reparent(mLayer, screenshotParentLayer);
5294 drawLayers();
5295 }
5296 }
chaviwa76b2712017-09-20 12:02:26 -07005297
chaviwa76b2712017-09-20 12:02:26 -07005298 private:
chaviw7206d492017-11-10 16:16:12 -08005299 const sp<Layer> mLayer;
5300 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005301
5302 // In the "childrenOnly" case we reparent the children to a screenshot
5303 // layer which has no properties set and which does not draw.
5304 sp<ContainerLayer> screenshotParentLayer;
Peiyong Linefefaac2018-08-17 12:27:51 -07005305 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005306 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005307
5308 SurfaceFlinger* mFlinger;
5309 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005310 };
5311
5312 auto layerHandle = reinterpret_cast<Layer::Handle*>(layerHandleBinder.get());
5313 auto parent = layerHandle->owner.promote();
5314
Robert Carr2e102c92018-10-23 12:11:15 -07005315 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
chaviw7206d492017-11-10 16:16:12 -08005316 ALOGE("captureLayers called with a removed parent");
5317 return NAME_NOT_FOUND;
5318 }
5319
Robert Carr578038f2018-03-09 12:25:24 -08005320 const int uid = IPCThreadState::self()->getCallingUid();
5321 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005322 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
Robert Carr578038f2018-03-09 12:25:24 -08005323 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5324 return PERMISSION_DENIED;
5325 }
5326
chaviw7206d492017-11-10 16:16:12 -08005327 Rect crop(sourceCrop);
5328 if (sourceCrop.width() <= 0) {
5329 crop.left = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005330 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
chaviw7206d492017-11-10 16:16:12 -08005331 }
5332
5333 if (sourceCrop.height() <= 0) {
5334 crop.top = 0;
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005335 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
chaviw7206d492017-11-10 16:16:12 -08005336 }
5337
5338 int32_t reqWidth = crop.width() * frameScale;
5339 int32_t reqHeight = crop.height() * frameScale;
5340
Chia-I Wu20261cb2018-08-23 12:55:44 -07005341 // really small crop or frameScale
5342 if (reqWidth <= 0) {
5343 reqWidth = 1;
5344 }
5345 if (reqHeight <= 0) {
5346 reqHeight = 1;
5347 }
5348
Peiyong Lin0e003c92018-09-17 11:09:51 -07005349 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
chaviw7206d492017-11-10 16:16:12 -08005350
Robert Carr578038f2018-03-09 12:25:24 -08005351 auto traverseLayers = [parent, childrenOnly](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005352 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5353 if (!layer->isVisible()) {
5354 return;
Robert Carr578038f2018-03-09 12:25:24 -08005355 } else if (childrenOnly && layer == parent.get()) {
5356 return;
chaviwa76b2712017-09-20 12:02:26 -07005357 }
5358 visitor(layer);
5359 });
5360 };
Peiyong Lin0e003c92018-09-17 11:09:51 -07005361 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false);
chaviwa76b2712017-09-20 12:02:26 -07005362}
5363
5364status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5365 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005366 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005367 const ui::PixelFormat reqPixelFormat,
chaviwa76b2712017-09-20 12:02:26 -07005368 bool useIdentityTransform) {
5369 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005370
Peiyong Lin0e003c92018-09-17 11:09:51 -07005371 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005372 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5373 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005374 *outBuffer =
5375 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5376 static_cast<android_pixel_format>(reqPixelFormat), 1,
5377 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005378
5379 // This mutex protects syncFd and captureResult for communication of the return values from the
5380 // main thread back to this Binder thread
5381 std::mutex captureMutex;
5382 std::condition_variable captureCondition;
5383 std::unique_lock<std::mutex> captureLock(captureMutex);
5384 int syncFd = -1;
5385 std::optional<status_t> captureResult;
5386
Robert Carr03480e22018-01-04 16:02:06 -08005387 const int uid = IPCThreadState::self()->getCallingUid();
5388 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5389
Dominik Laskowski8c001672018-05-30 16:52:06 -07005390 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005391 // If there is a refresh pending, bug out early and tell the binder thread to try again
5392 // after the refresh.
5393 if (mRefreshPending) {
5394 ATRACE_NAME("Skipping screenshot for now");
5395 std::unique_lock<std::mutex> captureLock(captureMutex);
5396 captureResult = std::make_optional<status_t>(EAGAIN);
5397 captureCondition.notify_one();
5398 return;
5399 }
5400
5401 status_t result = NO_ERROR;
5402 int fd = -1;
5403 {
5404 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005405 renderArea.render([&] {
Robert Carr578038f2018-03-09 12:25:24 -08005406 result = captureScreenImplLocked(renderArea, traverseLayers, (*outBuffer).get(),
5407 useIdentityTransform, forSystem, &fd);
5408 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005409 }
5410
5411 {
5412 std::unique_lock<std::mutex> captureLock(captureMutex);
5413 syncFd = fd;
5414 captureResult = std::make_optional<status_t>(result);
5415 captureCondition.notify_one();
5416 }
5417 });
5418
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005419 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005420 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005421 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005422 while (*captureResult == EAGAIN) {
5423 captureResult.reset();
5424 result = postMessageAsync(message);
5425 if (result != NO_ERROR) {
5426 return result;
5427 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005428 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005429 }
5430 result = *captureResult;
5431 }
5432
5433 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005434 sync_wait(syncFd, -1);
5435 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005436 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005437
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005438 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005439}
5440
chaviwa76b2712017-09-20 12:02:26 -07005441void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005442 TraverseLayersFunction traverseLayers,
chaviwa76b2712017-09-20 12:02:26 -07005443 bool useIdentityTransform) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005444 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005445
Lloyd Pique144e1162017-12-20 16:44:52 -08005446 auto& engine(getRenderEngine());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005447
chaviwa76b2712017-09-20 12:02:26 -07005448 const auto reqWidth = renderArea.getReqWidth();
5449 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005450 const auto sourceCrop = renderArea.getSourceCrop();
5451 const auto rotation = renderArea.getRotationFlags();
Dan Stozac1879002014-05-22 15:59:05 -07005452
Peiyong Lin0e003c92018-09-17 11:09:51 -07005453 engine.setOutputDataSpace(renderArea.getReqDataSpace());
Chia-I Wu36574d92018-05-16 10:54:36 -07005454 engine.setDisplayMaxLuminance(DisplayDevice::sDefaultMaxLumiance);
Romain Guy88d37dd2017-05-26 17:57:05 -07005455
Mathias Agopian180f10d2013-04-10 22:55:41 -07005456 // make sure to clear all GL error flags
Mathias Agopian3f844832013-08-07 21:24:32 -07005457 engine.checkErrors();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005458
5459 // set-up our viewport
Chia-I Wu1be50b52018-08-29 10:44:48 -07005460 engine.setViewportAndProjection(reqWidth, reqHeight, sourceCrop, rotation);
Mathias Agopian3f844832013-08-07 21:24:32 -07005461 engine.disableTexturing();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005462
chaviw50da5042018-04-09 13:49:37 -07005463 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005464 // redraw the screen entirely...
chaviw50da5042018-04-09 13:49:37 -07005465 engine.clearWithColor(0, 0, 0, alpha);
Mathias Agopian180f10d2013-04-10 22:55:41 -07005466
chaviwa76b2712017-09-20 12:02:26 -07005467 traverseLayers([&](Layer* layer) {
Peiyong Lind3788632018-09-18 16:01:31 -07005468 engine.setColorTransform(layer->getColorTransform());
David Sodmanfb95bcc2017-12-22 15:45:30 -08005469 layer->draw(renderArea, useIdentityTransform);
Peiyong Lind3788632018-09-18 16:01:31 -07005470 engine.setColorTransform(mat4());
chaviwa76b2712017-09-20 12:02:26 -07005471 });
Mathias Agopian180f10d2013-04-10 22:55:41 -07005472}
5473
chaviwa76b2712017-09-20 12:02:26 -07005474status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5475 TraverseLayersFunction traverseLayers,
5476 ANativeWindowBuffer* buffer,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005477 bool useIdentityTransform,
Robert Carr03480e22018-01-04 16:02:06 -08005478 bool forSystem,
chaviwa76b2712017-09-20 12:02:26 -07005479 int* outSyncFd) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005480 ATRACE_CALL();
5481
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005482 bool secureLayerIsVisible = false;
chaviwa76b2712017-09-20 12:02:26 -07005483
5484 traverseLayers([&](Layer* layer) {
5485 secureLayerIsVisible = secureLayerIsVisible || (layer->isVisible() && layer->isSecure());
5486 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005487
Robert Carr03480e22018-01-04 16:02:06 -08005488 // We allow the system server to take screenshots of secure layers for
5489 // use in situations like the Screen-rotation animation and place
5490 // the impetus on WindowManager to not persist them.
5491 if (secureLayerIsVisible && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005492 ALOGW("FB is protected: PERMISSION_DENIED");
5493 return PERMISSION_DENIED;
5494 }
Peiyong Linfb530cf2018-12-15 05:07:38 +00005495 auto& engine(getRenderEngine());
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005496
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005497 // this binds the given EGLImage as a framebuffer for the
5498 // duration of this scope.
Peiyong Linfb530cf2018-12-15 05:07:38 +00005499 renderengine::BindNativeBufferAsFramebuffer bufferBond(engine, buffer);
Chia-I Wueadbaa62017-11-09 11:26:15 -08005500 if (bufferBond.getStatus() != NO_ERROR) {
5501 ALOGE("got ANWB binding error while taking screenshot");
Dan Stozaabcda352017-06-01 14:37:39 -07005502 return INVALID_OPERATION;
5503 }
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005504
Dan Stozaabcda352017-06-01 14:37:39 -07005505 // this will in fact render into our dequeued buffer
5506 // via an FBO, which means we didn't have to create
5507 // an EGLSurface and therefore we're not
5508 // dependent on the context's EGLConfig.
Chia-I Wu1be50b52018-08-29 10:44:48 -07005509 renderScreenImplLocked(renderArea, traverseLayers, useIdentityTransform);
Dan Stozaa9b1aa02017-06-01 14:16:23 -07005510
Peiyong Linfb530cf2018-12-15 05:07:38 +00005511 base::unique_fd syncFd = engine.flush();
Alec Mouri492bc572018-09-11 21:40:04 +00005512 if (syncFd < 0) {
Peiyong Linfb530cf2018-12-15 05:07:38 +00005513 engine.finish();
Dan Stozaabcda352017-06-01 14:37:39 -07005514 }
Alec Mouri492bc572018-09-11 21:40:04 +00005515 *outSyncFd = syncFd.release();
Dan Stozaabcda352017-06-01 14:37:39 -07005516
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005517 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005518}
5519
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005520// ---------------------------------------------------------------------------
5521
Dan Stoza412903f2017-04-27 13:42:17 -07005522void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5523 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005524}
5525
Dan Stoza412903f2017-04-27 13:42:17 -07005526void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5527 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005528}
5529
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005530void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005531 const LayerVector::Visitor& visitor) {
5532 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005533 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005534 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005535 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005536 continue;
5537 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005538 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005539 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005540 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005541 return;
5542 }
chaviwa76b2712017-09-20 12:02:26 -07005543 if (!layer->isVisible()) {
5544 return;
5545 }
5546 visitor(layer);
5547 });
5548 }
5549}
5550
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005551}; // namespace android
Mathias Agopian3f844832013-08-07 21:24:32 -07005552
Lloyd Pique074e8122018-07-26 12:57:23 -07005553
Mathias Agopian3f844832013-08-07 21:24:32 -07005554#if defined(__gl_h_)
5555#error "don't include gl/gl.h in this file"
5556#endif
5557
5558#if defined(__gl2_h_)
5559#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005560#endif